body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I've recently started work on a hobby project that's basically a sandbox file system written in Java, slightly inspired by <a href="https://icculus.org/physfs/" rel="noreferrer">PhysicsFS</a>. The point of the project is to separate what files a user can read/write to by restricting read/write to predefined locations on the disk. A "location" can be either a directory (folder) or an archive (*.zip file). </p> <p>An example use-case of this would be when creating an application that can load user plugins, for example a 3D-modelling program that can load scripts, and only allowing read/writes to the "Plugins" folder. By using the sandbox file system for loaded plugins you ensure that those untrusted plugins cannot mess with any user's files outside of the "Plugins" folder. </p> <p>I would like potential reviewers to mostly focus on readability and code style since I plan to make this a public project, and also some focus on good/bad practices when it comes to file systems and I/O (either something bad I'm doing or something good I should be doing). If there are some edge cases that would crash the program or allow a user to navigate outside the sandbox that would be nice to know too!</p> <p>Note that there are a few files I have not included in the review, mostly because they are either very simple wrappers around Strings or java <code>File</code> objects, or they are an <code>Enum</code> (but they can be included if needed).</p> <p>Here's an implementation of the file system using Java NIO I/O:</p> <pre><code>public class NIOFileSystem implements FileSystem&lt;NIOFSFile&gt; { private static final Logger LOGGER = LoggerFactory.getLogger(NIOFileSystem.class); private final List&lt;NIOFSRegistration&gt; registrations; private FilePath writePath; public NIOFileSystem() { this.registrations = new ArrayList&lt;&gt;(); this.writePath = null; } @Override public boolean addToSearchPath(final FilePath path, final FileLocation location) { requireNonNull(path, "path must not be null"); requireNonNull(location, "location must not be null"); final FilePath minimized = path.minimize(); if (!verifyFilePathAndLog(minimized)) return false; try { LOGGER.debug("Attempting to add '{}' ({}) to the search path.", path, location); final NIOFSRegistration reg = new NIOFSRegistration(minimized, location); if (registrations.contains(reg)) return false; registrations.add(reg); LOGGER.info("'{}' ({}) added to search path", path, location); return true; } catch (final URISyntaxException e) { LOGGER.error("Could not add '{}' ({}) to the search path: {}", path.toString(), location, e.toString()); return false; } } @Override public boolean isOnSearchPath(final FilePath path) { requireNonNull(path, "path must not be null"); final FilePath minimized = path.minimize(); if (!verifyFilePathAndLog(minimized)) return false; return registrations.stream().anyMatch(reg -&gt; reg.getFilePath().equals(minimized)); } @Override public boolean addAllArchivesToSearchPath(final FilePath path, final FileLocation location) { requireNonNull(path, "path must not be null"); requireNonNull(location, "location must not be null"); final FilePath minimized = path.minimize(); if (!verifyFilePathAndLog(minimized)) return false; try { LOGGER.debug("Adding all archives in path '{}' ({})", path, location); final Path filePath = FSUtils.constructNIOPath(path, location); final Iterator&lt;Path&gt; it = Files.walk(filePath, 1).iterator(); // If iterator is somehow empty something went wrong. if (!it.hasNext()) { LOGGER.warn("Iterator over path {} is empty", filePath); return false; } // The first element in the iterator is the input path // and we don't want to add that. it.next(); boolean success = true; while (it.hasNext()) { final Path p = it.next(); final FilePath fp = FilePath.from(p.toString()); final FileType fileType = FSUtils.getFileType(p); if (fileType != FileType.ARCHIVE) { LOGGER.trace("Not adding child '{}' because it is a {}", fp, fileType); continue; } // If we couldn't add the archive to the search path we have // to return false according to the spec. if (!addToSearchPath(fp, location)) success = false; } return success; } catch (final URISyntaxException e) { LOGGER.error("Could not create java.nio.file.Path path to '{}': {}", path, e); return false; } catch (final IOException e) { LOGGER.error("Could not walk file '{}': {}", path, e); return false; } } @Override public boolean setWriteDirectory(final FilePath path) { requireNonNull(path, "path must not be null"); this.writePath = path; return true; } @Override public Optional&lt;FilePath&gt; getWriteDirectory() { return Optional.ofNullable(writePath); } @Override public Optional&lt;NIOFSFile&gt; open(final FilePath path, final FileAccessType accessType) { requireNonNull(path, "path must not be null"); requireNonNull(accessType, "accessType must not be null"); final FilePath minimized = path.minimize(); if (!verifyFilePathAndLog(minimized)) return Optional.empty(); try { LOGGER.debug("Attempting to open file '{}' ({})", path, accessType); switch (accessType) { case READ: LOGGER.trace("Number of registered input directories: {}", registrations.size()); for (final NIOFSRegistration reg : registrations) { LOGGER.trace("Looking for file '{}' in '{}'", path, reg.getFilePath()); if (reg.getType() == FileType.ARCHIVE) { final Path zipFile = reg.getPath(); if (!Files.exists(zipFile)) continue; try (java.nio.file.FileSystem fs = FileSystems.newFileSystem(zipFile, null)) { final Path filePath = fs.getPath(path.toString()); if (!Files.exists(filePath)) continue; LOGGER.trace("Found file '{}' in '{}'", path, reg.getFilePath()); return Optional.of(new PreReadNIOFSFile(Files.readAllBytes(filePath))); } catch (final IOException e) { LOGGER.error("Could not fetch file '{}' from archive '{}': {}", path, zipFile, e); return Optional.empty(); } } final Path nioPath = reg.getPath(minimized); if (!Files.exists(nioPath)) continue; LOGGER.trace("Found file '{}' in '{}'", path, nioPath); return Optional.of(new NIOFSFile(nioPath, false)); } LOGGER.debug("Could not find file '{}'", path); return Optional.empty(); case WRITE: final FilePath fqPath = writePath.append(minimized); final Path nioPath = FSUtils.constructNIOPath(fqPath, FileLocation.EXTERNAL); LOGGER.trace("Looking for file '{}' in '{}' ({})", path, writePath, nioPath.toAbsolutePath()); return Optional.of(new NIOFSFile(nioPath, false)); default: throw new IllegalArgumentException("Cannot handle accessType " + accessType); } } catch (final URISyntaxException e) { LOGGER.error("Could not create directory '{}': {}", path, e); return Optional.empty(); } } @Override public boolean createDirectory(final FilePath path) { requireNonNull(path, "path must not be null"); final FilePath minimized = path.minimize(); if (!verifyFilePathAndLog(minimized)) return false; if (isNull(writePath)) { LOGGER.debug("Trying to create directory {} but no write path is set.", minimized); return false; } try { final FilePath fqPath = writePath.append(minimized); final Path nioPath = FSUtils.constructNIOPath(fqPath, FileLocation.EXTERNAL); final Path createdPath = Files.createDirectories(nioPath); LOGGER.debug("Created directory at '{}'", createdPath.toString()); return true; } catch (final IOException | URISyntaxException e) { LOGGER.error("Could not create directory '{}': {}", path, e); return false; } } @Override public Optional&lt;NIOFSFile&gt; createFile(final FilePath path) { requireNonNull(path, "path must not be null"); final FilePath minimized = path.minimize(); if (!verifyFilePathAndLog(minimized)) return Optional.empty(); if (isNull(writePath)) { LOGGER.debug("Trying to create file {} but no write path is set.", minimized); return Optional.empty(); } try { final FilePath fqPath = writePath.append(minimized); final Path nioPath = FSUtils.constructNIOPath(fqPath, FileLocation.EXTERNAL); LOGGER.debug("Trying to create file at '{}'", nioPath.toAbsolutePath()); final Path createdFilePath = Files.createFile(nioPath); LOGGER.debug("Created file at '{}'", createdFilePath); return Optional.of(new NIOFSFile(createdFilePath, true)); } catch (final FileAlreadyExistsException e) { LOGGER.warn("Could not create file '{}' because it already exists", path); return open(minimized, FileAccessType.WRITE); } catch (URISyntaxException | IOException e) { LOGGER.error("Could not create file '{}': {}", path, e); return Optional.empty(); } } @Override public boolean delete(final FilePath path) { return deleteInternal(path, false); } @Override public boolean forceDelete(final FilePath path) { return deleteInternal(path, true); } private boolean deleteInternal(final FilePath path, final boolean force) { requireNonNull(path, "path must not be null"); final FilePath minimized = path.minimize(); if (!verifyFilePathAndLog(minimized)) return false; if (isNull(writePath)) { LOGGER.debug("Trying to remove {} but no write path is set.", minimized); return false; } final FilePath fqPath = writePath.append(minimized); try { final Path nioPath = FSUtils.constructNIOPath(fqPath, FileLocation.EXTERNAL); LOGGER.debug("Trying to delete '{}'", nioPath.toAbsolutePath()); if (force) { return forceDelInternal(nioPath); } else { return delInternal(nioPath); } } catch (final DirectoryNotEmptyException e) { if (!force) LOGGER.warn( "Could not delete {} because it is a non-empty directory. Use FileSystem#forceDelete instead.", path); else LOGGER.error( "Fatal error trying to delete {}, directory not empty error even though delete was forced!", path); return false; } catch (final URISyntaxException | IOException | SecurityException e) { LOGGER.error("Could not delete '{}': {}", path, e); return false; } } private boolean forceDelInternal(final Path nioPath) throws IOException { requireNonNull(nioPath, "nioPath must not be null"); // Delete all files (not folders). We have to do this first // because we can't delete non-empty folders. final boolean allFilesDeleted = Files.walk(nioPath).filter(Files::isRegularFile) .map(Path::toFile).map(File::delete).allMatch(wasDeleted -&gt; wasDeleted); if (!allFilesDeleted) { LOGGER.warn("Could not empty all files from sub-directories of {}", nioPath.toAbsolutePath()); return false; } // Delete all folders too final boolean allDirsDeleted = Files.walk(nioPath).map(Path::toFile).map(File::delete) .allMatch(wasDeleted -&gt; wasDeleted); if (!allDirsDeleted) { LOGGER.warn("Could not delete empty directories at {}", nioPath.toAbsolutePath()); return false; } LOGGER.info("Deleted {}", nioPath.toAbsolutePath()); return true; } private boolean delInternal(final Path nioPath) throws IOException { requireNonNull(nioPath, "nioPath must not be null"); final boolean success = Files.deleteIfExists(nioPath); if (success) LOGGER.info("Deleted '{}'", nioPath.toAbsolutePath()); else LOGGER.warn("Failed to delete file '{}'", nioPath.toAbsolutePath()); return success; } private static boolean verifyFilePathAndLog(final FilePath path) { requireNonNull(path, "path must not be null"); return FSUtils.isSafePath(path, LOGGER); } } </code></pre> <p>Interface with documentation and specifications, if you would like to read that too:</p> <pre><code>/** Interface that represents an abstract file system that restricts reading / writing to only * specified directories. A file system can handle both directories (e.g. "documents/savegames/") or * archives (e.g. "mods/coolmod.zip"). * * @author {real name redacted} */ public interface FileSystem&lt;T extends FSFile&gt; { /** * &lt;p&gt; * Adds the given {@link FilePath} to the search path so that files in that path can be found * with {@link FileSystem#open(FilePath, FileAccessType)}. * &lt;/p&gt; * * &lt;p&gt; * The path can either point to a directory (e.g. &lt;code&gt;"savegames/"&lt;/code&gt;) or an archive (e.g. * &lt;code&gt;"graphics.zip"&lt;/code&gt;). * &lt;/p&gt; * * @param path * the path to add * @param location * where the file resides * @return &lt;code&gt;true&lt;/code&gt; if path was added to the search path, &lt;code&gt;false&lt;/code&gt; otherwise. * @see FileLocation * @see FilePath */ boolean addToSearchPath(FilePath path, FileLocation location); /** Returns true if and only if the {@link FilePath} is on the search path. False otherwise. * * @param path * the path * @return true if and only if the {@link FilePath} is on the search path. False otherwise */ boolean isOnSearchPath(FilePath path); /** Adds all immediate child archives of &lt;code&gt;path&lt;/code&gt; to the search path, but not the path * itself. Useful for adding things like a "mods" directory. E.g: * * &lt;code&gt; * &lt;pre&gt; * // mods/ * // coolmod.zip * // soundmod.zip * // 4kgraphics.zip * // logs/ * // 2019-03-31.txt * // someotherfolder/ * // somezip.zip * FilePath path = FilePath.from("mods/"); * * // coolmod.zip, soundmod.zip, 4kgraphics.zip are now all added to the search path, * // but &lt;b&gt;NOT&lt;/b&gt; either logs/, logs/2019-03-31.txt, or somezip.zip. * // mods/ itself is also &lt;b&gt;NOT&lt;/b&gt; added to the search path. * fs.addAllArchivesToSearchPath(path); * &lt;/pre&gt; * &lt;/code&gt; * * @param path * where to look for archives. * @param location * where the archives reside. * @return true if and only if ALL archives were added to the file path, false otherwise. * @see FileSystem#addToSearchPath(FilePath, FileLocation) * @see FileLocation * @see FilePath */ boolean addAllArchivesToSearchPath(FilePath path, FileLocation location); /** Sets the write directory. The write directory must not be an archive or a file. The write * directory is always {@link FileLocation#EXTERNAL}. There can only ever exist one write * directory for safety reasons. * * @param path * the directory * @return true if the directory was set, false otherwise * @see FileLocation * @see FilePath */ boolean setWriteDirectory(FilePath path); /** Returns an {@link Optional} containing the current write directory, or an empty Optional if * no write directory has been set. * * @return an {@link Optional} containing the current write directory. */ Optional&lt;FilePath&gt; getWriteDirectory(); /** Opens a file for reading or writing. * * @param path * the path to the file * @param accessType * how the file should be opened. * @return an optional containing the {@link FSFile}, or an empty optional if the file does not * exist. * @see FilePath * @see FileAccessType */ Optional&lt;T&gt; open(FilePath path, FileAccessType accessType); /** Creates a new directory in the write directory. If the path contains several directories all * intermediate directories will be created, e.g. "documents/logs/crashes/" will create * "documents/" and "documents/logs/" if they don't already exist. * * @param path * where to create the directory. * @return true if and only if the &lt;i&gt;final&lt;/i&gt; directory in the path was created (so "crashes/" * in "documents/logs/crashes/"). */ boolean createDirectory(FilePath path); /** Creates a new file in the write directory. If the directory the file is located in does not * exist this method returns an empty {@link Optional}, otherwise it returns an optional with * the created file. * * @param path * where to create the file * @return an optional containing the created file, or an empty optional if file could not be * created. */ Optional&lt;T&gt; createFile(FilePath path); /** Removes a file or directory present in the write directory. Cannot remove a directory if it * contains files or non-empty child directories. * * @param path * the path * @return true if the file/directory was removed, false otherwise * @see FileSystem#forceDelete(FilePath) */ boolean delete(FilePath path); /** Removes a file or directory present in the write directory, including all files in that * directory and all child directories. * * @param path * the path to the directory * @return true if the file/directory was removed, false otherwise * @see FileSystem#delete(FilePath) */ boolean forceDelete(FilePath path); /** Convenience function that converts a string to a {@link FilePath} then calls * {@link FileSystem#delete(FilePath)}. * * @param path * @return true if the file was removed, false otherwise */ default boolean delete(final String path) { return delete(FilePath.from(path)); } /** Convenience function that converts a string to a {@link FilePath} then calls * {@link FileSystem#forceDelete(FilePath)}. * * @param path * the path * @return true if the directory was removed, false otherwise */ default boolean forceDelete(final String path) { return forceDelete(FilePath.from(path)); } /** Convenience function that converts a string to a {@link FilePath} then calls * {@link FileSystem#addToSearchPath(FilePath, FileLocation)}. * * @see FileSystem#addToSearchPath(FilePath, FileLocation) * @param path * the string path * @return &lt;code&gt;true&lt;/code&gt; if path was added to the search path, &lt;code&gt;false&lt;/code&gt; otherwise. * @see FileLocation * @see FilePath */ default boolean addToSearchPath(final String path, final FileLocation location) { return addToSearchPath(FilePath.from(path), location); } /** Convenience function that converts a string to a {@link FilePath} then calls * {@link FileSystem#addAllArchivesToSearchPath(FilePath, FileLocation)}. * * @param path * the string path. * @param location * where the archives reside. * @return true if and only if ALL archives were added to the file path, false otherwise. * @see FileSystem#addToSearchPath(FilePath, FileLocation) * @see FileLocation * @see FilePath */ default boolean addAllArchivesToSearchPath(final String path, final FileLocation location) { return addAllArchivesToSearchPath(FilePath.from(path), location); } /** Convenience function that converts a string to a {@link FilePath} then calls * {@link FileSystem#setWriteDirectory(FilePath)}. * * @see FileSystem#setWriteDirectory(FilePath) * @param path * the string path * @return &lt;code&gt;true&lt;/code&gt; if path was set at the write directory, &lt;code&gt;false&lt;/code&gt; * otherwise. * @see FileLocation * @see FilePath */ default boolean setWriteDirectory(final String path) { return setWriteDirectory(FilePath.from(path)); } /** Convenience function that converts a string to a {@link FilePath} then calls * {@link FileSystem#open(FilePath, FileAccessType)}. * * @see FileSystem#open(FilePath, FileAccessType) * @param path * the string path * @param accessType * which directory we should open the file from * @return an optional containing the {@link FSFile}, or an empty optional if the file does not * exist. * @see FilePath * @see FileAccessType */ default Optional&lt;T&gt; open(final String path, final FileAccessType accessType) { return open(FilePath.from(path), accessType); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T17:38:24.100", "Id": "430180", "Score": "2", "body": "Your code reads really well. I would prefix most methods with `try*` though. I would expect `open` to throw an exception when the file does not exist, and `tryOpen` to return `optional.empty`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T21:38:19.067", "Id": "430320", "Score": "1", "body": "What prevents this user plugin from calling `FileSystems.getDefault()` and reading and writing from anywhere? Seem to me you want to install a [`SecurityManager`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/SecurityManager.html)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T23:57:22.917", "Id": "430334", "Score": "0", "body": "@AJNeufeld The point is that you probably would not use Java for your plugins, but preferably a scripting language like Javascript, Lua, Python, etc. and then you would route all I/O operations through my code. It is not supposed to be a magical solution that prevents any sort of tampering with the file system - it simply an interface that guarantees that all I/O operations that flows through it can only access predefined locations. Making sure that everything *actually* flows through it is the end-developer's problem :P" } ]
[ { "body": "<p>A few things I would change are:</p>\n\n<ul>\n<li>Some private methods tend to check for null on their arguments, even if you control, what they are being called with. Unless I plan to call with NULL, I'd remove those checks.</li>\n<li>The exception methods might either provide no message, as they do not help the caller more than the standard message of the exception or provide helpful details, like the value that caused the exception. </li>\n<li>The <code>registrations List</code> is used like a <code>Set</code>. As a Set behaves the way you use your List, I'd recommend using a Set. You should also be aware that <code>Set::add</code> already tells you if a new element was added or already contained. </li>\n<li><code>forceDelInternal</code> can be static</li>\n</ul>\n\n<p>I'd be happy to check more of the code after you have provided the rest of it, as it is harder than necessary with all the red underlines. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T16:23:14.143", "Id": "235238", "ParentId": "222313", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T17:32:51.450", "Id": "222313", "Score": "5", "Tags": [ "java", "file-system", "sandbox" ], "Title": "Sandbox file system for Java" }
222313
<p>I'm writing my own version of a Mandelbrot set generator, with pan and zoom functionality. (There's not yet a color overlay of sets generated with various beta values; the beta value is changed manually with a spinner.)</p> <ul> <li>Pan: drag left-click</li> <li>Zoom: roll mouse wheel</li> </ul> <p>The main problem with this code is that after zooming in ~500 times, the generated shape will jump around on the canvas, rather than staying centered on the mouse cursor. I've tried debugging and the best idea I have is that this error is due to the limits of floating-point precision.</p> <p>(As a self-taught Java programmer) I'm looking for suggestions regarding:</p> <ul> <li>How to zoom in indefinitely without losing precision</li> <li>Improving performance</li> <li>Class structure and overall code style</li> <li>Any other improvements</li> </ul> <hr> <p>Mandelbrot.java:</p> <pre class="lang-java prettyprint-override"><code>import java.awt.geom.Point2D; public class Mandelbrot { private int beta = 50; private volatile boolean abort = false; private volatile boolean generating = false; private volatile int genCount = 0; private Mandelbrot() { new GUI(this); } /** * @return Whether the given complex number diverges from the origin-centered * circle of radius 2 after {@code beta} number of tries. */ private boolean diverges(double real, double complex) { ComplexNumber cn = new ComplexNumber(real, complex); ComplexNumber z = new ComplexNumber(0); for(int i = 0; i &lt; beta; i++) { z.add(z.square(), cn); if(z.real*z.real + z.complex*z.complex &gt; 4) return true; } return false; } private void generatePoints(Point2D.Double tl, Point2D.Double br, int[] pixels, int threadID) { // final long startTime = System.nanoTime(); Point2D.Double start = GUI.wtc(tl); Point2D.Double end = GUI.wtc(br); double increment = (end.x - start.x)/(double)(GUI.SIZE - 1); for(double y = start.y, cy = 0; cy &lt; GUI.SIZE; y += increment, cy++) { // Stop computing if a new zoom/pan is commanded if(abort) { abort = false; System.out.printf("(%d) Aborting at cy %d\n", genCount, (int)cy); break; } for(double cx = 0, x = start.x; cx &lt; GUI.SIZE; x += increment, cx++) { if(x*x + y*y &gt; 4) continue; if(!diverges(x, y)) pixels[(int) (cy*GUI.SIZE + cx)] = 0xFF000000; } } // long elapsedTime = System.nanoTime() - startTime; // System.out.printf("thread %d time: %.3fs\n", threadID, elapsedTime / 1000000000.0); } int[] generatePoints(Point2D.Double tl, Point2D.Double br) { System.out.printf("(%d) Generating on thread: %s\n", genCount, Thread.currentThread().getName()); long startTime = System.nanoTime(); int[] pixels = new int[GUI.SIZE*GUI.SIZE]; generating = true; //TODO multithreaded Mandelbrot calculation generatePoints(tl, br, pixels, 0); generating = false; long elapsedTime = System.nanoTime() - startTime; System.out.printf("(" + genCount++ + ") Done. Took %.3fs\n\n", elapsedTime / 1000000000.0); return pixels; } void abortProcessing() { if(generating) { abort = true; } } void setBeta(int beta) { this.beta = beta; } int getBeta() { return beta; } public static void main(String[] args) { new Mandelbrot(); } } </code></pre> <p>GUI.java:</p> <pre class="lang-java prettyprint-override"><code>import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.geom.AffineTransform; import java.awt.geom.Ellipse2D; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerModel; import javax.swing.SpinnerNumberModel; import javax.swing.WindowConstants; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; @SuppressWarnings("serial") final class GUI { public static final int SIZE = 992; // Must be divisible by 4 public static final double ZOOM_FACTOR = 1.1; private BufferedImage image = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_ARGB); private Canvas canvas; GUI(Mandelbrot man) { canvas = new Canvas(man); refresh(man); JFrame frame = new JFrame("MandelBrot Set Viewer"); frame.setContentPane(setupPanel(man)); frame.pack(); // frame.setLocation(5456, 5); // frame.setLocation(4200, 975); // frame.setLocation(4200, 5); frame.setVisible(true); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } /** * Converts from window coordinates to Cartesian coordinates. */ public static Point2D.Double wtc(Point2D.Double window) { return new Point2D.Double((window.x * 4 / (double)GUI.SIZE) - 2, (window.y * 4 / (double)GUI.SIZE) - 2 ); } private JPanel setupPanel(final Mandelbrot man) { SpinnerModel betaModel = new SpinnerNumberModel(man.getBeta(), 1, Integer.MAX_VALUE, 1); JSpinner betaSpinner = new JSpinner(betaModel); betaSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { man.setBeta((int)((JSpinner) e.getSource()).getValue()); refresh(man); } }); JLabel betaLabel = new JLabel("Beta value:"); JPanel betaPanel = new JPanel(); betaPanel.add(betaLabel); betaPanel.add(betaSpinner); JButton resetButton = new JButton("Reset"); resetButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { canvas.reset(); } }); JPanel resetPanel = new JPanel(); resetPanel.add(resetButton); JPanel sidePanel = new JPanel(new BorderLayout(10, 10)); sidePanel.add(betaPanel, BorderLayout.NORTH); sidePanel.add(resetPanel, BorderLayout.SOUTH); JPanel mainPanel = new JPanel(); mainPanel.add(sidePanel); mainPanel.add(canvas); return mainPanel; } void refresh(Mandelbrot man) { //TODO use a Thread pool rather than creating a new Thread for each pan/zoom new Thread(new Runnable() { @Override public void run() { // Calculate Mandelbrot shape in the current viewing area image.getRaster().setDataElements(0, 0, image.getWidth(), image.getHeight(), man.generatePoints(canvas.tlClip, canvas.brClip)); canvas.repaint(); } }).start(); } private final class Canvas extends JPanel { final Point2D.Double tl = new Point2D.Double(0, 0); final Point2D.Double br = new Point2D.Double(SIZE, SIZE); // Point in Cartesian space at the top left of the viewing window volatile Point2D.Double tlClip = new Point2D.Double(0, 0); // Point in Cartesian space at the bottom right of the viewing window volatile Point2D.Double brClip = new Point2D.Double(SIZE, SIZE); AffineTransform transform = new AffineTransform(); Ellipse2D.Double backgroundCircle = new Ellipse2D.Double(0, 0, SIZE, SIZE); int prevX, prevY; double scale = 1; Canvas(Mandelbrot man) { setPreferredSize(new Dimension(SIZE, SIZE)); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { // For debugging System.out.println("tlClip: " + tlClip); System.out.println("brClip: " + brClip); } }); addMouseMotionListener(new MouseAdapter() { @Override public void mouseMoved(MouseEvent e) { prevX = e.getX(); prevY = e.getY(); } @Override public void mouseDragged(MouseEvent e) { pan(man, e); } }); addMouseWheelListener(new MouseAdapter() { @Override public void mouseWheelMoved(MouseWheelEvent e) { zoom(man, e); } }); } private void pan(Mandelbrot man, MouseEvent e) { man.abortProcessing(); // Stop processing the previous request--we have a new one int x = e.getX(); int y = e.getY(); double translateX = (x - prevX)/scale; double translateY = (y - prevY)/scale; transform.translate(translateX, translateY); updateClip(); refresh(man); prevX = x; prevY = y; } private void zoom(Mandelbrot man, MouseWheelEvent e) { man.abortProcessing(); // Stop processing the previous request--we have a new one int rotation = e.getWheelRotation(); Point2D p1 = e.getPoint(); Point2D p2 = null; try { p2 = transform.inverseTransform(p1, null); } catch(NoninvertibleTransformException ex) { // Should not happen ex.printStackTrace(); return; } transform.setToIdentity(); scale = (rotation &lt; 0) ? scale * ZOOM_FACTOR : scale / ZOOM_FACTOR; transform.translate(p1.getX(), p1.getY()); transform.scale(scale, scale); transform.translate(-p2.getX(), -p2.getY()); updateClip(); refresh(man); } private void updateClip() { try { AffineTransform inv = transform.createInverse(); inv.transform(tl, tlClip); inv.transform(br, brClip); } catch(NoninvertibleTransformException nte) { nte.printStackTrace(); } } private void reset() { transform.setToIdentity(); scale = 1; repaint(); } @Override public void paint(Graphics g) { // final long startTime = System.nanoTime(); super.paint(g); Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED); g2d.setColor(Color.GRAY); g2d.fill(transform.createTransformedShape(backgroundCircle)); g2d.drawImage(image, 0, 0, null); // long elapsedTime = System.nanoTime() - startTime; // System.out.printf("painting time: %.3fs\n\n", elapsedTime / 1000000000.0); } } } </code></pre> <p>ComplexNumber.java:</p> <pre class="lang-java prettyprint-override"><code>package mandelbrot; public class ComplexNumber { public double real, complex; public ComplexNumber(double real, double complex) { this.real = real; this.complex = complex; } public ComplexNumber(double real) { this.real = real; complex = 0; } public void add(ComplexNumber cn1, ComplexNumber cn2) { real = cn1.real + cn2.real; complex = cn1.complex + cn2.complex; } public ComplexNumber square() { // double f = real * real; // double o = real * complex; // double i = real * complex; // double l = -(complex * complex); double realTemp = real; real = real * real - complex * complex; complex = realTemp * complex * 2; return this; } @Override public String toString() { return real + " + " + complex + "i"; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T20:11:38.833", "Id": "430200", "Score": "1", "body": "In the `void generatePoints` method, you are repeatedly calculating `y*y` inside the inner loop. Try precalculating it before the loop." } ]
[ { "body": "<p>This is a great project to do. <a href=\"https://github.com/carcigenicate/mandelbrot/tree/master/src/mandelbrot\" rel=\"nofollow noreferrer\">I did a similar project in Swing</a>; except using Clojure's Seesaw wrapper library. You can add many interesting add-on panels to it. My favorite panels that I came up with were a panel that lets the user decide how they want things colored, and one that allowed multiple images to be saved to disk in parallel. It was a great lesson in handling complex async processes. They're worth considering trying.</p>\n\n<p>Anyways, onto some suggestions:</p>\n\n<p><code>diverges</code> can be made <em>much</em> more interesting if you allow it to return the <code>i</code> value that it fails at. This allows you to color your pixels based on the returned value of <code>i</code>, which adds a whole new dimension to what you can produce. <a href=\"https://drive.google.com/open?id=1asITJjqs-L7Iw7EeKFn6JiLYgbokGxlM\" rel=\"nofollow noreferrer\">This</a> is my favorite image that I've ever produced (linking externally because it's 80 MB large; it's just my Google Drive. It's safe I swear!). Here's a <em>tiny</em> sample of it:</p>\n\n<p><a href=\"https://i.stack.imgur.com/ymKTu.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ymKTu.jpg\" alt=\"Colored Mandelbrot Sample\"></a></p>\n\n<p>I'd change it to something like:</p>\n\n<pre><code>private int divergesAt(double real, double complex)\n{\n ComplexNumber cn = new ComplexNumber(real, complex);\n ComplexNumber z = new ComplexNumber(0);\n\n for(int i = 0; i &lt; beta; i++)\n {\n z.add(z.square(), cn);\n\n if(z.real*z.real + z.complex*z.complex &gt; 4) { // Don't neglect braces!\n return i;\n }\n }\n\n return beta;\n}\n</code></pre>\n\n<p>Then when you want to decide what color to make that pixel, do something like:</p>\n\n<pre><code>int iters = divergesAt(x, y);\n\n// java.awt.Color\nColor pixelColor = new Color(wrap(x * iters), wrap(y * iters), wrap((x + y) * iters);\n</code></pre>\n\n<p>Where <code>wrap</code> is some function that wraps the value to ensure that it's always between 0 and 255.</p>\n\n<p>You can create much more complicated \"equations\" as well though. <a href=\"https://github.com/carcigenicate/mandelbrot/blob/master/src/mandelbrot/coloring.clj\" rel=\"nofollow noreferrer\">Here</a> are some example equations that I used (in Clojure; although you should be able to figure out what's going on). <code>wr</code> is a <code>wrap</code> shortcut, <code>co</code> is a <code>Color</code> constructor shortcut, <code>x</code> and <code>y</code> are the pixel coordinates, and <code>n</code> is the number of iterations that pixel failed at. Play around with it. I spent days just trying out different coloring methods.</p>\n\n<hr>\n\n<p>On top of that, I have a couple comments regarding your <code>diverages</code> function:</p>\n\n<ul>\n<li><p>I would use far more whitespace, like how I showed in my example. Cramming everything together doesn't lend itself to readability.</p></li>\n<li><p>It's very confusing to have <code>ComplexNumber</code> as a mutable class. It's a number. Numbers are immutable. Ideally, the class methods should all return new <code>ComplexNumbers</code> instead of mutating themselves. This has the potential to be expensive; especially in a language like Java that doesn't lend itself to dealing with immutability. It will make your code make more sense though, and prevent bugs from popping up caused by background mutation.</p></li>\n<li><p>Don't be tempted to neglect braces just because they aren't necessary! Many odd bugs have occurred because we told ourselves \"I'll definitely remember to add braces if I refactor this later\". Limit your ability to cause future problems for yourself.</p></li>\n</ul>\n\n<hr>\n\n<p>On your question about precision, the only way I found around that was to use <code>BigDecimal</code>; but this creates <em>massive</em> performance problems. I found using doubles actually lets you zoom in pretty far before stuff starts getting weird. I actually found my iteration limits (like your <code>beta</code> here) to be larger deciding factors in how the final image looks. Anything less than 200 for the limit causes noticeable missed details to start popping up. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T20:44:31.663", "Id": "430205", "Score": "0", "body": "Great feedback; thank you. I'll have a look at the links you provided. Will upvote as soon as I have >=15 rep!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T20:46:42.563", "Id": "430207", "Score": "0", "body": "I'm still hoping for a satisfying solution to the precision problem... I wonder how the _deep_ fractal zooms on Youtube were generated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T20:48:45.080", "Id": "430209", "Score": "2", "body": "@PullNointer Likely using an arbitrary precision class like `BigDecimal` like I mentioned. They likely pre-computed everything before recording the zoom, so performance wasn't an issue. Or at least I always assumed that's how it was done." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T20:32:24.173", "Id": "222323", "ParentId": "222314", "Score": "2" } } ]
{ "AcceptedAnswerId": "222323", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T18:11:28.973", "Id": "222314", "Score": "4", "Tags": [ "java", "performance", "swing", "floating-point", "fractals" ], "Title": "Java Mandelbrot Set Viewer" }
222314
<p>I have a simple program that "minimizes" a file path. Minimizing simply means replacing unnecessary file entries with entries that mean the same thing:</p> <ul> <li><code>path1/path2/../path3</code> is replaced with <code>path1/path3</code></li> <li><code>path1/./path2</code> is replaced with <code>path1/path2</code></li> </ul> <p>I've achieved this using regex and it seems to cover all cases, but it also feels very slow and I have a hunch it might be prone to infinite loops:</p> <pre><code>private static final Pattern ONE_DOT = Pattern.compile("/\\./"); private static final Pattern TWO_DOTS = Pattern.compile("[^/]+/\\.\\./?"); public static String minimize(final String in) { String tmp = in; while (!stringIsMinimized(tmp)) { tmp = ONE_DOT.matcher(tmp).replaceAll("/"); tmp = TWO_DOTS.matcher(tmp).replaceAll(""); } return tmp; } public static boolean stringIsMinimized(final String str) { return !(ONE_DOT.matcher(str).find() || TWO_DOTS.matcher(str).find()); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T20:15:30.547", "Id": "430201", "Score": "0", "body": "`\"path1/..../path2/\"` yields `\"../path2/\"`" } ]
[ { "body": "<p>Your code actually doesn't work, because you use <code>replaceAll</code>. This means that your pattern will allow you to match <code>../../</code> and replace it with <code></code>, resulting in a lost double-back. You can fix this two ways:</p>\n\n<ol>\n<li>You could change the <code>replaceAll</code> to <code>replaceFirst</code></li>\n<li>You could change the pattern to exclude <code>../../</code> (<code>[^/.]+/\\\\.\\\\./?</code> works)</li>\n</ol>\n\n<p>You can then simplify your loop since the <code>ONE_DOT</code> case will be matched properly so you don't need to split out a check for minimization.</p>\n\n<p>Thus I would suggest:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static final Pattern ONE_DOT = Pattern.compile(\"/\\\\./\");\nprivate static final Pattern TWO_DOTS = Pattern.compile(\"([^/.]+/\\\\.\\\\.)+/?\");\n\npublic static String minimize(final String in) {\n String tmp = in;\n\n tmp = ONE_DOT.matcher(tmp).replaceAll(\"/\");\n\n while (TWO_DOTS.matcher(tmp).matches())\n tmp = TWO_DOTS.matcher(tmp).replaceAll(\"\");\n\n return tmp;\n}\n</code></pre>\n\n<p>At least as a first-pass improvement. There may be a way to do it without the loop using some kind of counting regular expression, but off the top of my head I'm not sure.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T20:17:10.883", "Id": "430202", "Score": "0", "body": "The fastest solution would probably be an iterator, a stack and some look-around." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T20:21:25.360", "Id": "430203", "Score": "0", "body": "Yeah, fastest would probably be something like `Arrays.stream(in.split(\"/\")).filter(x -> !x.equals(\".\")).reduce(\"\", {some lambda here})`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T20:01:12.633", "Id": "222321", "ParentId": "222317", "Score": "1" } }, { "body": "<blockquote>\n <p>Your code looks great!</p>\n</blockquote>\n\n<p>Here, maybe another option that we might exercise would be to possibly do the entire task with an expression, maybe something similar to these:</p>\n\n<pre><code>^(.+?\\/).+\\/(.+)$\n(.+?\\/).+\\/(.+)\n</code></pre>\n\n<p>Our first capturing group is non-greedy, collects our desired <code>path1</code> for both inputs, followed by a greedy <code>.+</code> that'd continue upto the last slash, and our <code>path2</code> and <code>path3</code> are in this group: <code>(.+)</code>, and our desired output can be called using <code>\\1\\2</code>.</p>\n\n<em>Escaping might be unnecessary, just following based on the <a href=\"https://regex101.com/r/yZfVoB/1/\" rel=\"nofollow noreferrer\">demo</a></em>.\n\n<hr>\n\n<h3>Test</h3>\n\n<pre><code>import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nfinal String regex = \"^(.+?\\\\/).+\\\\/(.+)$\";\nfinal String string = \"path1/path2/../path3\\n\"\n + \"path1/./path2\";\nfinal String subst = \"$1$2\";\n\nfinal Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);\nfinal Matcher matcher = pattern.matcher(string);\n\nfinal String result = matcher.replaceAll(subst);\n\nSystem.out.println(result);\n</code></pre>\n\n<h3>Demo</h3>\n\n<pre><code>console.log(`path1/path2/../path3\npath1/./path2`.replace(/^(.+?\\/).+\\/(.+)$/gm, `$1$2`));\n</code></pre>\n\n<h3>Performance</h3>\n\n<pre><code>const repeat = 1000000;\nconst start = Date.now();\n\nfor (var i = repeat; i &gt;= 0; i--) {\n const regex = '/^(.+?/).+/(.+)$/gm';\n const str = `path1/path2/../path3`;\n const subst = `$1$2`;\n\n var match = str.replace(regex, subst);\n}\n\nconst end = Date.now() - start;\nconsole.log(\"YAAAY! \\\"\" + match + \"\\\" is a match \");\nconsole.log(end / 1000 + \" is the runtime of \" + repeat + \" times benchmark test. \");\n</code></pre>\n\n\n\n<h3>RegEx Circuit</h3>\n\n<p><a href=\"https://jex.im/regulex/#!flags=&amp;re=%5E(a%7Cb)*%3F%24\" rel=\"nofollow noreferrer\">jex.im</a> visualizes regular expressions:</p>\n\n<p><a href=\"https://i.stack.imgur.com/FB7Xx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FB7Xx.png\" alt=\"enter image description here\"></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T01:28:53.467", "Id": "222335", "ParentId": "222317", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T18:32:46.560", "Id": "222317", "Score": "3", "Tags": [ "java", "regex" ], "Title": "Minimizing a file path" }
222317
<h2>Backstory</h2> <p>This is a buffer I wrote for use in multiple personal projects. It is designed to handle pretty much any data in pretty much any way. In particular I intend to use it in such instances as recursive-descent parsers, where it will be important to be able to 'undo' operations.</p> <h2>Undo</h2> <p>This 'undo' functionality is implemented alongside thread safety by maintaining references to a 'reference' object. Thus a buffer can be copied in a (mostly) shallow manner while maintaining the same underlying data. Removing from a copy of a buffer doesn't actually remove its 'head' node unless it is the last copy of a buffer to reference it.</p> <h2>Memory safety</h2> <p>The memory safety is achieved by re-using old nodes instead of freeing them if possible and not allowing data to be inserted unless there is an already allocated node available. This effectively implements a custom memory store.</p> <h2>Memory and Thread Safety</h2> <p>I had quite a bit of headache trying to get this to be both threadsafe and devoid of memory leaks. I believe I have finally achieved that. There were a lot of off-by-one errors that had to be corrected with respect to references and null pointers to ensure that everything gets cleaned up when appropriate <em>and</em> nothing gets cleaned up prematurely.</p> <h2>Your Task</h2> <p>The reason I am posting this here is because I intend to re-use this implementation a lot. As such I want to make sure it doesn't have any bugs later. While I don't expect subtle memory or thread-safety bugs to be easily detected, any stylistic changes that may be allowing such bugs to hide would be nice to detect early.</p> <p>Therefore if there are any areas where a slight change of methodology could get more inherent safety, I would greatly appreciate it. I was surprised by how finicky this was, considering that Ada typically makes it harder to actually make surface-level mistakes.</p> <p>If I had to point to one thing I'm not happy about it would be that each node is its own protected object. I would have thought it would be doable with only the reference list being protected and using its mutual exclusion to reference count the nodes. I just couldn't find a way to make that work.</p> <h2>Specification</h2> <pre><code>with Ada.Finalization; generic type Element is private; -- 0 capacity means use entire accessible memory pool Max_Capacity : Natural := 0; -- Total number of nodes to cache for re-use Max_Cache : Positive := 1; package Shared_Buffers is type Shared_Buffer is new Ada.Finalization.Controlled with private; procedure Insert (Into : in out Shared_Buffer; Value : Element); procedure Remove (From : in out Shared_Buffer; Value : out Element); function Has_Data (What : Shared_Buffer) return Boolean; procedure Initialize (Object : in out Shared_Buffer); procedure Adjust (Object : in out Shared_Buffer); procedure Finalize (Object : in out Shared_Buffer); private type Element_Node; type Element_Node_Access is access Element_Node; type Node_List is array (Positive range &lt;&gt;) of Element_Node_Access; protected type Element_Node is -- Reference counting features procedure Reference (Times : Positive := 1); procedure Ignore; procedure Clear; function Has_References return Boolean; function Get_References return Natural; -- Node features procedure Set (Value : Element); procedure Follow_With (Node : Element_Node_Access); function Get return Element; function Next return Element_Node_Access; entry Wait; private Data : Element; Following : Element_Node_Access := null; References : Natural := 1; end Element_Node; protected type Protected_Shared_Buffer is -- Reference counting features procedure Reference (From : Element_Node_Access); procedure Ignore; function Has_References return Boolean; -- Buffer features entry Insert (Value : Element); entry Get_Head (Node : out Element_Node_Access); procedure Remove (Node : in out Element_Node_Access); function Has_Head return Boolean; private Tail : Element_Node_Access := null; Head : Element_Node_Access := null; Cache : Node_List (1 .. Max_Cache) := (1 =&gt; new Element_Node, others =&gt; null); Cached : Natural := 1; Count : Natural := 1; References : Natural := 1; Newborns : Natural := 1; end Protected_Shared_Buffer; type Protected_Shared_Buffer_Access is access Protected_Shared_Buffer; type Shared_Buffer is new Ada.Finalization.Controlled with record Reference : Protected_Shared_Buffer_Access; Self : Element_Node_Access; Tailed : Boolean; end record; end Shared_Buffers; </code></pre> <h2>Body</h2> <pre><code>with Ada.Unchecked_Deallocation; package body Shared_Buffers is procedure Free_Node is new Ada.Unchecked_Deallocation (Element_Node, Element_Node_Access); procedure Free_Protected_Shared_Buffer is new Ada.Unchecked_Deallocation (Protected_Shared_Buffer, Protected_Shared_Buffer_Access); protected body Element_Node is procedure Reference (Times : Positive := 1) is begin References := References + Times; end Reference; procedure Ignore is begin if References &gt; 0 then References := References - 1; end if; end Ignore; procedure Clear is begin References := 0; end Clear; function Has_References return Boolean is (References &gt; 0); function Get_References return Natural is (References); procedure Set (Value : Element) is begin Data := Value; end Set; procedure Follow_With (Node : Element_Node_Access) is begin Following := Node; end Follow_With; function Get return Element is (Data); function Next return Element_Node_Access is (Following); entry Wait when Following /= null is begin null; end Wait; end Element_Node; protected body Protected_Shared_Buffer is procedure Reference (From : Element_Node_Access) is Node : Element_Node_Access := From; begin References := References + 1; if From = null then Newborns := Newborns + 1; end if; while Node /= null loop Node.Reference; Node := Node.Next; end loop; end Reference; procedure Ignore is begin if References &gt; 1 then References := References - 1; else References := 0; for I in Positive range 1 .. Cached loop Free_Node (Cache (I)); Count := Count - 1; end loop; end if; end Ignore; function Has_References return Boolean is (References &gt; 0); entry Insert (Value : Element) when Cached &gt; 0 is Node : Element_Node_Access := Cache (Cached); begin Node.Clear; Node.Set (Value); if Tail = null then Node.Reference (Newborns); Head := Node; else Node.Reference (Tail.Get_References); Tail.Follow_With (Node); end if; Tail := Node; if Max_Capacity = 0 or Count &lt; Max_Capacity then Cache (Cached) := new Element_Node; Count := Count + 1; else Cached := Cached - 1; end if; exception when Storage_Error =&gt; Cached := Cached - 1; end Insert; entry Get_Head (Node : out Element_Node_Access) when Head /= null is begin Node := Head; Newborns := Newborns - 1; end Get_Head; procedure Remove (Node : in out Element_Node_Access) is begin Node.Ignore; if not Node.Has_References then if Cached = Max_Cache then Free_Node (Node); Count := Count - 1; else Cached := Cached + 1; Cache (Cached) := Node; end if; end if; end Remove; function Has_Head return Boolean is (Head /= null); end Protected_Shared_Buffer; procedure Insert (Into : in out Shared_Buffer; Value : Element) is begin Into.Reference.Insert (Value); end Insert; procedure Remove (From : in out Shared_Buffer; Value : out Element) is Next : Element_Node_Access; begin if From.Tailed then if From.Self /= null then From.Self.Wait; Next := From.Self.Next; From.Reference.Remove (From.Self); From.Self := Next; else From.Reference.Get_Head (From.Self); end if; end if; Value := From.Self.Get; Next := From.Self.Next; if Next /= null then From.Reference.Remove (From.Self); From.Self := Next; From.Tailed := False; else From.Tailed := True; end if; end Remove; function Has_Data (What : Shared_Buffer) return Boolean is (if What.Tailed then ( if What.Self /= null then What.Self.Next /= null else What.Reference.Has_Head)); procedure Initialize (Object : in out Shared_Buffer) is begin Object.Reference := new Protected_Shared_Buffer; Object.Self := null; Object.Tailed := True; end Initialize; procedure Adjust (Object : in out Shared_Buffer) is begin Object.Reference.Reference (Object.Self); end Adjust; procedure Finalize (Object : in out Shared_Buffer) is Removed : Element_Node_Access; begin if not Object.Tailed then while Object.Self /= null loop Removed := Object.Self; Object.Self := Object.Self.Next; Object.Reference.Remove (Removed); end loop; end if; Object.Reference.Ignore; if not Object.Reference.Has_References then Free_Protected_Shared_Buffer (Object.Reference); end if; end Finalize; end Shared_Buffers; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T19:40:44.550", "Id": "222318", "Score": "2", "Tags": [ "multithreading", "linked-list", "error-handling", "memory-management", "ada" ], "Title": "Thread safe Shareable and Splittable Buffer with Safe Memory (Project)" }
222318
<p>Obviously, <code>'select *'</code> is never a good idea.</p> <p>HOWEVER, I have taken a job with an org that allowed this cancer to spread.</p> <p>They have huge queries, using <code>select *</code> as SUB-QUERIES, when the coder only needed 3 or 4 columns.</p> <pre><code> select t.field1, t.field2, t.field3, x.field4 ... from table t left join (select * from table where .... ) x on x.field5 = t.field5 left join (select * from table where .... ) y on y.field6 = t.field6 left join (select * from table where .... ) z on z.field7 = t.field7 </code></pre> <p>Performance on this beast is a dog.</p> <p>The databases we pull from we don't own, so I don't have rights to get an estimated or actual execution plan.</p> <p>Before I start rewriting these queries, is the query optimizer on the M$ SQL Server smart enough to translate the splat into just the needed columns? Or do I start targeting one query a day at lunch?</p> <p>Thank you for your time and consideration.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T20:31:16.160", "Id": "430204", "Score": "2", "body": "Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Perhaps https://dba.stackexchange.com is more suited for your question. Unless you can provide us with the required context." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T20:58:47.290", "Id": "430212", "Score": "0", "body": "Harsh dude. Harsh." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T20:59:50.217", "Id": "430213", "Score": "0", "body": "Well, I did spare you a bit. I didn't downvote :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T21:13:47.773", "Id": "430217", "Score": "0", "body": "Hmmm...DBAs I know don't write code. Not sure what they do.... Probably nothing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T21:15:19.773", "Id": "430219", "Score": "0", "body": "Harsh dude. Harsh." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T18:10:33.543", "Id": "430811", "Score": "0", "body": "Yes. the optimizer is smart enough to only gather the columns needed for the result set, as well as skipping left joins that are not needed for the result set. More than likely, your performance problem is in the Where clause." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T20:27:37.233", "Id": "222322", "Score": "1", "Tags": [ "sql", "t-sql" ], "Title": "Select splat in a subquery" }
222322
<p>Please review the code below and provide constructive feedback to improve.</p> <p>Multiple threads call the <code>SendMessageToMSMQ</code> method to send messages to a msmq queue.</p> <p>Occassionally <code>messageQueue.Send(sendMsg);</code> throws insufficent resources exception. Dont know why it's happening. Storage is not an issue, since I have checked the disk and the queue properties. There is no limit on queue storage. I doubt on the number of msmq connections being opened and closed...</p> <p>Any help appreciated. Thank you.</p> <pre><code> using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Messaging; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp1 { /// &lt;summary&gt; /// program assumes the msmq private queue with name "queueName" exists /// &lt;/summary&gt; static class Program { /// &lt;summary&gt; /// The main entry point for the application. /// &lt;/summary&gt; static void Main() { Parallel.For(0, 10000, index =&gt; { MSMQSender.SendMessageToMSMQ&lt;msmqMessageObject&gt;(new msmqMessageObject { Name = index.ToString(), Value = index.ToString(), count = index }); } ); } } public class MSMQSender { private static object lockObject = new object(); private static ConcurrentQueue&lt;msmqMessageObject&gt; concurrentQueue = new ConcurrentQueue&lt;msmqMessageObject&gt;(); public static void SendMessageToMSMQ&lt;T&gt;(T msmqMessageObject1) { if (Monitor.TryEnter(lockObject)) { try { using (var messageQueue = new MessageQueue()) { messageQueue.Path = string.Format(@"Formatname:DIRECT=OS:.\Private$\{0}", "queueName"); using (var sendMsg = new Message()) { sendMsg.Recoverable = false; sendMsg.Body = msmqMessageObject1; messageQueue.Send(sendMsg); } messageQueue.Close(); } if (concurrentQueue.Count &gt; 0) { msmqMessageObject msmqMessageObject2; while (concurrentQueue.TryDequeue(out msmqMessageObject2)) { try { using (var messageQueue = new MessageQueue()) { messageQueue.Path = string.Format(@"Formatname:DIRECT=OS:.\Private$\{0}", "queueName"); using (var sendMsg = new Message()) { sendMsg.Recoverable = false; sendMsg.Body = msmqMessageObject2; messageQueue.Send(sendMsg); } messageQueue.Close(); } } catch (Exception ex) { concurrentQueue.Enqueue(msmqMessageObject1 as msmqMessageObject); if (concurrentQueue.Count &gt; 10) { //todo: log error } break; } } } } catch (Exception ex) { concurrentQueue.Enqueue(msmqMessageObject1 as msmqMessageObject); if (concurrentQueue.Count &gt; 10) { //todo: log error } } finally { Monitor.Exit(lockObject); } } else { concurrentQueue.Enqueue(msmqMessageObject1 as msmqMessageObject); } } } public class msmqMessageObject { public string Name; public string Value; public int count; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T21:39:53.333", "Id": "430222", "Score": "1", "body": "Code Review is a community where programmers peer-review your working code. We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review. -> Do you have an idea why you get the exception occasionaly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T21:41:31.377", "Id": "430223", "Score": "0", "body": "The code works correctly. Issue is with MSMQ System.Messaging.MessageQueueException Source: System.Messaging Message: Insufficient resources to perform operation. Stack Trace: at System.Messaging.MessageQueue.SendInternal(Object obj, MessageQueueTransaction internalTransaction, MessageQueueTransactionType transactionType)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T21:48:04.603", "Id": "430225", "Score": "1", "body": "I am sorry, but I don't see how 'correctly working' and 'issue' can be symbiotes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T05:08:54.570", "Id": "430248", "Score": "0", "body": "Created a complete example." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T21:32:35.757", "Id": "222327", "Score": "3", "Tags": [ "c#", "performance", ".net", "error-handling", "queue" ], "Title": "msmq bulk send in c#" }
222327
<p>A coding challenge in which we are to write a function that compares two strings and returns the one that is smaller. The comparison is both lexicographical and numerical, depending on the content of the strings as explained below and in the comments of the code.</p> <p>Both strings may contain any characters. Consecutive numbers in the string are considered a single number. If during the search the character of only one string is a number, then that string is returned as numbers are lexicographically smaller than letters. </p> <p>If during the search the characters of both strings are numbers, then <code>parseInt(strX.slice(i))</code> checks if there are more consecutive digits in each string and returns the string whose number is numerically smaller.</p> <p>Examples:</p> <p>input: <code>"a"</code>, <code>"b"</code> expected output: <code>"a"</code> since <code>"a"</code> comes before <code>"b"</code> alphabetically </p> <p>input: <code>"a1"</code>, <code>"a2"</code> expected output: <code>"a1"</code> since 1 comes before 2</p> <p>input: <code>"a10"</code>, <code>"a2"</code> expected output: <code>"a2"</code> since 2 comes before 10 </p> <p>Here is the code: </p> <pre><code>const smallestString = (str1, str2) =&gt; { // we only need to iterate through the shortest string const len = str1.length &lt; str2.length ? str1.length : str2.length; for (let i = 0; i &lt; len; i++) { // check if both letters are strings if (str1[i].toUpperCase() !== str1[i].toLowerCase() &amp;&amp; str2[i].toUpperCase() !== str2[i].toLowerCase()) { if (str1[i] === str2[i]) { // if both letters are the same, continue continue; } else { return str1[i] &lt; str2[i] ? str1 : str2; // otherwise return the string with the 'smaller' char at that index } } else if (!isNaN(str1[i] || !isNaN(str2[i]))) { // check if either char is a number if (!isNaN(str1[i]) &amp;&amp; !isNaN(str2[i])) { // if both chars are numbers, return str with numerically smaller number return parseInt(str1.slice(i)) &lt; parseInt(str2.slice(i)) ? str1 : str2; } } else { return str1[i] &lt; str2[i] ? str1 : str1; } } return str1; // if we get here then both strings are equal and either can be returned } console.log(smallestString('a10', 'a2')); // returns 'a2' </code></pre> <p>I am seeking any and all feedback about cleaning up the code and possibly improving the algorithm's current time complexity of O(n).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T21:52:29.097", "Id": "430226", "Score": "1", "body": "Can we assume ANSI encoding of the strings, or can they include extended Unicode characters?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T21:53:23.493", "Id": "430227", "Score": "0", "body": "At this point I would only assume ANSI." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T21:53:37.660", "Id": "430228", "Score": "2", "body": "Since you may have to compare every character, you can't get below $O(n)\\$." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T21:55:10.980", "Id": "430229", "Score": "0", "body": "I was pretty sure that the time complexity of this problem cannot be less than O(n), however, I would still like feedback for refactoring." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T22:19:04.213", "Id": "430231", "Score": "1", "body": "What is the expected output of `('a10', 'ab')`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T22:38:09.123", "Id": "430235", "Score": "0", "body": "@vnp 'a10', since in such a case since a string with a number in it will be lexicographically smaller than a string with no numbers in it. If the current index of both strings is a number, then `parseInt(strX.slice(i))` checks if there are more consecutive digits in the string and returns the string whose number is numerically smaller." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T22:59:41.883", "Id": "430236", "Score": "0", "body": "You have to specify it in the problem statement. Otherwise it is unclear if the code works _correctly_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T23:06:02.310", "Id": "430237", "Score": "0", "body": "@vnp Please see edits above. The problem should now be clarified." } ]
[ { "body": "<pre><code> if (!isNaN(str1[i]) &amp;&amp; !isNaN(str2[i])) { // if both chars are numbers, return str with numerically smaller number\n return parseInt(str1.slice(i)) &lt; parseInt(str2.slice(i)) ? str1 : str2;\n }\n</code></pre>\n\n<p>seems like a bug. In case the numbers compare equal the code blindly returns the first string. Consider <code>(a10c, a10b)</code>.</p>\n\n<hr>\n\n<pre><code>return str1; // if we get here then both strings are equal and either can be returned\n</code></pre>\n\n<p>seems like another bug. At this point we only know that the strings are equal <em>up to the length of the shortest one</em>, and the shortest one should be returned. Which one is shortest is not tested here.</p>\n\n<hr>\n\n<p>The overall logic looks overcomplicated. Consider testing for numbers first; that would eliminate the need for a confusing <code>toUpper/toLower</code> mess, and the special case of special characters.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T23:37:06.767", "Id": "430238", "Score": "0", "body": "Well I didn't see the bug, but I fixed it now. Your feedback is greatly appreciated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T23:42:51.067", "Id": "430239", "Score": "0", "body": "Should I edit the post since this is Code Review?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T23:51:44.973", "Id": "430240", "Score": "0", "body": "@SeanValdivia No. Post a follow-up question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T01:12:39.790", "Id": "430242", "Score": "0", "body": "Can you elaborate? Will the content of this follow-up question have the same code as above, but fixed?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T23:20:50.520", "Id": "222332", "ParentId": "222329", "Score": "2" } } ]
{ "AcceptedAnswerId": "222332", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T21:50:37.230", "Id": "222329", "Score": "2", "Tags": [ "javascript", "programming-challenge", "strings", "complexity" ], "Title": "Coding Challenge: Return The Smaller String" }
222329
<p>I need to fetch data from an server that isn't always reliable and unfortunately fixing that is out of my hands. My team determined we would attempt the request up to 3 times.</p> <p>So I thought of using a try-catch inside the while loop but didn't like the extra indentation for no good reason and thought to remove the braces from the while loop.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>async function doAjax() { const data = { /* stuff */ } const retryLimit = 2; let retryCount = 0; let found = false; while (!found &amp;&amp; retryCount &lt;= retryLimit) try { let serverResponse = await $.get("url", data); // Do stuff } catch (err) { retryCount++; } // Do more stuff }</code></pre> </div> </div> </p> <p>I know my team won't be against this, but I still got curious if there's a consensus or some reason in favor/against writing code this way. Thoughts?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T22:21:20.620", "Id": "430232", "Score": "3", "body": "Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise." } ]
[ { "body": "<p>I would not do this. It breaks too far from any typical convention for very little gain. </p>\n\n<p>I'm personally against omitting braces at all; except in very narrow circumstances. I've seen many questions on stack overflow that stem from people omitting braces and not being able to figure out why \"only certain lines are running\".</p>\n\n<p>This also appears to look like a new language construct and feels a little jolting at first. It takes an extra second to realize what's going on.</p>\n\n<p>Considering how short the lines are, indentation shouldn't be a problem; and even if it is, there are other ways of addressing that problem. I would write this in the standard way</p>\n\n<pre><code>async function doAjax() {\n const data = { /* stuff */ }\n const retryLimit = 2;\n let retryCount = 0;\n let found = false;\n\n while (!found &amp;&amp; retryCount &lt;= retryLimit) {\n try {\n let serverResponse = await $.get(\"url\", data);\n // Do stuff\n\n } catch (err) {\n retryCount++;\n }\n }\n\n // Do more stuff\n}\n</code></pre>\n\n<p>If you like playing around with making code read interestingly and creating language constructs, I recommend playing around with a language with Clojure (or another lisp). Doing experimental things with the syntax is a little more expected in a language like that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T22:31:13.640", "Id": "430234", "Score": "0", "body": "Thank you for your honesty! I understand it was an opinion based question, and I would have asked on the javascript chat to get opinions but I don't have enough reputation " } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T22:26:20.693", "Id": "222331", "ParentId": "222330", "Score": "3" } } ]
{ "AcceptedAnswerId": "222331", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T22:18:46.743", "Id": "222330", "Score": "1", "Tags": [ "javascript", "jquery", "ajax" ], "Title": "Thoughts on using curly-brackets-less while loop with a try/catch?" }
222330
<p>I started to work on this CUDA C matrix class to learn both the object oriented programming in C++ and to learn CUDA. The initial goal of this project was to make a matrix class that can have almost similar syntax as MATLAB has. However, on the way I faced one big issue which was number the of host to device and the device to host data transfer calls. I was able to improve the situation by separating <code>lvalue</code> and <code>rvalue</code> references and move semantics. Currently I am at the stage where I have a working code which needs to be optimized.</p> <p>I am looking for the answers of following questions:</p> <ul> <li><p>Not being a developer or a computer science major I need to know how well written is this code?</p></li> <li><p>Is my approach of error and exception handling correct or not? Is there a better way? (Look at <code>imp_includes.hcu</code>, <code>cu_error_list.cu</code> and <code>error_check.cu</code>)</p></li> <li><p>I know that the way i am calculating the dimensions of the thread block in <code>block_dim.cu</code> is very naive. I would like to know if there is a better way to identify the dimensions of the thread block automatically.</p></li> <li><p>The solution I came up with to reduce the number of copy constructor calls now require me to have multiple overloads to separate <code>lavlue</code> and <code>rvalue</code> references. Is there a more simpler way to tackle this problem?</p></li> <li><p>To further improve the data transfer performance, I am thinking of using CUDA streams. I would like to have some comments on how useful it can be in this specific scenario.</p></li> <li><p>I am not expecting anyone to review the complete library. However, if there is any bit of code that can be improved, please let me know.</p></li> </ul> <p>Following are the minimal versions of the files that I think will be enough to answer my questions. The complete code can be found <a href="https://github.com/vxj9800/cuda-matrix-lib" rel="noreferrer">here</a>.</p> <h2>cu_mat.hcu ## - Class header</h2> <pre><code>#ifndef CU_MAT_HCU_ #define CU_MAT_HCU_ #include "imp_includes.hcu" class cu_mat { protected: size_t n_rows=0, n_cols=0; double *p=NULL; cu_mat(){} // Default constructor cu_mat(const size_t &amp;r, const size_t &amp;c, const double &amp;n); // Two argument constructor with initialization void init(const size_t &amp;r, const size_t &amp;c); // Two argument memory allocation with initialization public: /***** Constructors *****/ cu_mat(const cu_mat &amp;to_b_copied); // Copy constructor cu_mat(const std::initializer_list&lt;std::initializer_list&lt;double&gt;&gt; &amp;mat); // Single argument constructor with 'double' values cu_mat(const std::initializer_list&lt;std::initializer_list&lt;cu_mat&gt;&gt; &amp;mat); // Single argument constructor with 'cu_mat' values cu_mat(const double &amp;n); // Single value constructor cu_mat(cu_mat&amp;&amp; to_be_moved); // Move constructor /***** Operators *****/ // Add an ultimate '()' operator. // cu_mat operator()(const cu_mat rows, const cu_mat cols); // Sub-matrix access with 'cu_mat' cu_mat operator()(const size_t &amp;idx) const; // Matrix element access based on index cu_mat operator()(const size_t &amp;r, const size_t &amp;c) const; // Matrix element access cu_mat operator()(const size_t &amp;r_begin, const size_t &amp;r_end, const size_t &amp;c_begin, const size_t &amp;c_end) const; // Sub-matrix access cu_mat&amp; operator=(const cu_mat &amp;b); // Assignment operator to copy 'cu_mat' cu_mat&amp; operator=(cu_mat &amp;&amp;b); // Assignment operator to move 'cu_mat' // Assignment operator for 'double' to avoid implicit type casting cu_mat operator*(const cu_mat &amp;b) const &amp;; // Matrix multiplication operator cu_mat operator*(cu_mat &amp;&amp;b) const &amp;; // Matrix multiplication operator cu_mat operator*(const cu_mat &amp;b) &amp;&amp;; // Matrix multiplication operator cu_mat operator*(cu_mat &amp;&amp;b) &amp;&amp;; // Matrix multiplication operator cu_mat operator&gt;(const cu_mat &amp;b) const &amp;; // Greater than operator cu_mat operator&gt;(cu_mat &amp;&amp;b) const &amp;; // Greater than operator cu_mat operator&gt;(const cu_mat &amp;b) &amp;&amp;; // Greater than operator cu_mat operator&gt;(cu_mat &amp;&amp;b) &amp;&amp;; // Greater than operator explicit operator double(); // Type conversion from cu_mat to double /***** Member functions *****/ // Add an ultimate replace function cu_mat div(const cu_mat &amp;b) const &amp;; // Element wise division cu_mat div(cu_mat &amp;&amp;b) const &amp;; // Element wise division cu_mat div(const cu_mat &amp;b) &amp;&amp;; // Element wise division cu_mat div(cu_mat &amp;&amp;b) &amp;&amp;; // Element wise division cu_mat mult(const cu_mat &amp;b) const &amp;; // Element wise multiplication cu_mat mult(cu_mat &amp;&amp;b) const &amp;; // Element wise multiplication cu_mat mult(const cu_mat &amp;b) &amp;&amp;; // Element wise multiplication cu_mat mult(cu_mat &amp;&amp;b) &amp;&amp;; // Element wise multiplication cu_mat pow(const double &amp;n) const &amp;; // Element wise power cu_mat pow(const double &amp;n) &amp;&amp;; // Element wise power void replace(const size_t &amp;r, const size_t &amp;c, const cu_mat &amp;n); // Replace an element with a 'cu_mat' value void replace(const size_t &amp;r_begin, const size_t &amp;r_end, const size_t &amp;c_begin, const size_t &amp;c_end, const cu_mat &amp;n); // Replace submatrix with a 'cu_mat' matrix void get(); // Print matrix data void print(std::ofstream &amp;print); // Print matrix to a file size_t rows(); // Get number of rows size_t rows() const; // Get number of rows size_t cols(); // Get number of columns size_t cols() const ; // Get number of columns double* pointer(); // Get GPU memory pointer double* pointer() const; // Get GPU memory pointer /***** Supported external (friend) functions *****/ friend cu_mat randn(const size_t &amp;r, const size_t &amp;c); // Generate a matrix with normalized random numbers friend cu_mat randn(const size_t &amp;n); friend cu_mat mld(const cu_mat &amp;a, const cu_mat &amp;b); // Matrix left divide operator friend cu_mat mld(const cu_mat &amp;a, cu_mat &amp;&amp;b); // Matrix left divide operator friend cu_mat mld(cu_mat &amp;&amp;a, const cu_mat &amp;b); // Matrix left divide operator friend cu_mat mld(cu_mat &amp;&amp;a, cu_mat &amp;&amp;b); // Matrix left divide operator friend cu_mat eye(const size_t &amp;r, const size_t &amp;c); // Generate a non-square identity matrix friend cu_mat eye(const size_t &amp;n); friend cu_mat ones(const size_t &amp;r, const size_t &amp;c); // Matrix with all values 1 friend cu_mat ones(const size_t &amp;n); friend cu_mat zeros(const size_t &amp;r, const size_t &amp;c); // Matrix with all values 0 friend cu_mat zeros(const size_t &amp;n); friend cu_mat trans(cu_mat &amp;a); // Transpose of the matrix friend cu_mat horzcat(cu_mat &amp;a, cu_mat &amp;b); // Horizontal concatenation of two matrices friend cu_mat vertcat(cu_mat &amp;a, cu_mat &amp;b); // Vertical concatenation of two matrices friend cu_mat stepspace(const double &amp;i, const double &amp;step, const double &amp;f); // MATLAB colon operator friend bool isscalar(const cu_mat &amp;a); // Check if 'cu_mat' object is scalar /***** Destructor *****/ virtual ~cu_mat(); }; /***** Supported external (friend) functions *****/ cu_mat randn(const size_t &amp;r, const size_t &amp;c); // Generate a matrix with normalized random numbers cu_mat randn(const size_t &amp;n); cu_mat mld(const cu_mat &amp;a, const cu_mat &amp;b); // Matrix left divide operator cu_mat mld(const cu_mat &amp;a, cu_mat &amp;&amp;b); // Matrix left divide operator cu_mat mld(cu_mat &amp;&amp;a, const cu_mat &amp;b); // Matrix left divide operator cu_mat mld(cu_mat &amp;&amp;a, cu_mat &amp;&amp;b); // Matrix left divide operator cu_mat eye(const size_t &amp;r, const size_t &amp;c); // Generate a non-square identity matrix cu_mat eye(const size_t &amp;n); cu_mat ones(const size_t &amp;r, const size_t &amp;c); // Matrix with all values 1 cu_mat ones(const size_t &amp;n); cu_mat zeros(const size_t &amp;r, const size_t &amp;c); // Matrix with all values 0 cu_mat zeros(const size_t &amp;n); cu_mat trans(cu_mat &amp;a); // Transpose of the matrix cu_mat horzcat(cu_mat &amp;a, cu_mat &amp;b); // Horizontal concatenation of two matrices cu_mat vertcat(cu_mat &amp;a, cu_mat &amp;b); // Vertical concatenation of two matrices cu_mat stepspace(const double &amp;i, const double &amp;step, const double &amp;f); // MATLAB colon operator bool isscalar(const cu_mat &amp;a); // Check if 'cu_mat' object is scalar #endif /* CU_MAT_HCU_ */ </code></pre> <h2>cu_mat.cu ## - Member functions, constructors, destructors, operators and friend functions</h2> <pre><code>#include "cu_mat.hcu" // Constructors /************************************** Single argument constructor with 'double' values *******************************************/ cu_mat::cu_mat(const std::initializer_list&lt;std::initializer_list&lt;double&gt;&gt; &amp;mat) : n_rows(mat.size()), n_cols(mat.begin()-&gt;size()) { // ' -&gt; ' Means: pointer to an object -&gt; member function. Essentially accessing a member function with the help of a pointer to that object. // Define number of rows from the array input. Define number of columns from first row of array input // Check if the number of elements in each row are same. for(int i = 0; i&lt;n_rows; ++i) { confirm((mat.begin()+i)-&gt;size()==n_cols,"Error: Object initialization failed. Number of elements in each row must be same."); } // Copy input initializer-list to a new 2D array while making it column major. double *m = new double[n_rows*n_cols](); // Allocate space on CPU memory. confirm(m,"Error: Memory allocation failed while initializing the object."); // Check proper allocation. for(int i = 0; i&lt;n_rows; ++i) { for(int j = 0; j&lt;n_cols; ++j) { m[j*n_rows+i] = *((mat.begin()+i)-&gt;begin()+j); } } HANDLE_ERROR( cudaMalloc((void**)&amp;p, n_rows*n_cols*sizeof(double)) ); // Allocate memory on GPU. HANDLE_ERROR( cudaMemcpy(p,m,n_rows*n_cols*sizeof(double),cudaMemcpyHostToDevice) ); // Copy array from CPU to GPU delete[] m; } /***********************************************************************************************************************/ /************************************** Single argument constructor with 'cu_mat' values *******************************************/ __global__ void copymat(double* dest, double* src, size_t bias, size_t src_rows, size_t main_rows_bias, size_t n_ele) { unsigned int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx&lt;n_ele) dest[bias+idx+idx/src_rows*main_rows_bias] = src[idx]; } cu_mat::cu_mat(const std::initializer_list&lt;std::initializer_list&lt;cu_mat&gt;&gt; &amp;mat) { // Calculate total number of columns for(int i = 0; i&lt;mat.begin()-&gt;size(); ++i) n_cols += ((mat.begin())-&gt;begin()+i)-&gt;n_cols; // Check equal number of rows for horizontal concatenation and calculate total number of rows. for(int i = 0; i&lt;mat.size(); ++i) { size_t cols = ((mat.begin()+i)-&gt;begin())-&gt;n_cols; for(int j = 0; j&lt;(mat.begin()+i)-&gt;size()-1; ++j) { confirm(((mat.begin()+i)-&gt;begin()+j)-&gt;n_rows==((mat.begin()+i)-&gt;begin()+j+1)-&gt;n_rows,"Error: Dimensions of arrays being horizontally concatenated are not consistent."); cols += ((mat.begin()+i)-&gt;begin()+j+1)-&gt;n_cols; } confirm(cols == n_cols,"Error: Dimensions of arrays being vertically concatenated are not consistent.") n_rows += ((mat.begin()+i)-&gt;begin())-&gt;n_rows; } // Allocate memory and copy data if ((n_rows&gt;0)&amp;&amp;(n_cols&gt;0)) { HANDLE_ERROR( cudaMalloc((void**)&amp;p, n_rows*n_cols*sizeof(double)) ); // Allocate memory on GPU. size_t bias, src_rows, src_cols; size_t main_rows_bias, n_ele, n_threads; size_t r_sum = 0, c_sum = 0; for(int i = 0; i&lt;mat.size(); ++i){ for(int j = 0; j&lt;(mat.begin()+i)-&gt;size(); ++j){ bias = c_sum*n_rows+r_sum; src_rows = ((mat.begin()+i)-&gt;begin()+j)-&gt;n_rows; src_cols = ((mat.begin()+i)-&gt;begin()+j)-&gt;n_cols; main_rows_bias = n_rows-src_rows; n_ele = src_rows*src_cols; n_threads = block_dim(n_ele); c_sum += src_cols; copymat&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(p,((mat.begin()+i)-&gt;begin()+j)-&gt;p,bias,src_rows,main_rows_bias,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); } r_sum += src_rows; c_sum = 0; } } } /***********************************************************************************************************************/ /************************************ Single value constructor ***********************************************/ cu_mat::cu_mat(const double &amp;n) : n_rows(1), n_cols(1) { HANDLE_ERROR( cudaMalloc((void**)&amp;p, n_rows*n_cols*sizeof(double)) ); // Allocate memory on GPU. // std::cout &lt;&lt; p &lt;&lt; std::endl; HANDLE_ERROR( cudaMemcpy(p,&amp;n,n_rows*n_cols*sizeof(double),cudaMemcpyHostToDevice) ); // Copy array from CPU to GPU } /***********************************************************************************************************************/ /************************************ Copy constructor ***********************************************/ cu_mat::cu_mat(const cu_mat &amp;to_b_copied) : n_rows(to_b_copied.n_rows), n_cols(to_b_copied.n_cols) { // std::cout &lt;&lt; "Copy constructor called." &lt;&lt; std::endl; if ((n_rows&gt;0)&amp;&amp;(n_cols&gt;0)) { HANDLE_ERROR( cudaFree(p) ); HANDLE_ERROR( cudaMalloc((void**)&amp;p,n_rows*n_cols*sizeof(double)) ); // Allocate memory on GPU. HANDLE_ERROR( cudaMemcpy(p,to_b_copied.p,n_rows*n_cols*sizeof(double),cudaMemcpyDeviceToDevice) ); // Copy array from CPU to GPU } } /***********************************************************************************************************************/ /************************************ Two argument constructor with initialization ***********************************************/ __global__ void set_data(double* p, const double n, const double n_ele) { unsigned int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx&lt;n_ele) p[idx] = n; } cu_mat::cu_mat(const size_t &amp;r, const size_t &amp;c, const double &amp;n=0) : n_rows(r), n_cols(c) { if ((n_rows&gt;0)&amp;&amp;(n_cols&gt;0)) { HANDLE_ERROR( cudaMalloc((void**)&amp;p, n_rows*n_cols*sizeof(double)) ); if (n!=0) { size_t n_ele = n_rows*n_cols; size_t n_threads = block_dim(n_ele); set_data&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(p,n,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); } else { HANDLE_ERROR( cudaMemset(p,0,n_rows*n_cols*sizeof(double)) ); } } } /***********************************************************************************************************************/ /************************************ Move constructor ***********************************************/ cu_mat::cu_mat(cu_mat&amp;&amp; to_b_moved) { // std::cout &lt;&lt; "Move constructor called." &lt;&lt; std::endl; size_t nrows = to_b_moved.n_rows, ncols = to_b_moved.n_cols; double *ptr = to_b_moved.p; to_b_moved.n_rows = 0; to_b_moved.n_cols = 0; to_b_moved.p = NULL; n_rows = nrows; n_cols = ncols; p = ptr; } /***********************************************************************************************************************/ // Operators /************************************** Sub-matrix access with 'cu_mat' *******************************************/ // __global__ void check_integer() // cu_mat cu_mat::operator()(const cu_mat rows, const cu_mat cols) // { // confirm((rows.n_rows==1) || (rows.n_cols==1), "Error: 'rows' has to be a vector."); // confirm((cols.n_rows==1) || (cols.n_cols==1), "Error: 'rows' has to be a vector."); // confirm(idx &gt; 0, "Indexing starts from 1 for this library.") // confirm(idx &lt;= n_rows*n_cols,"Error: Index exceeds matrix bounds. Matrix has " &lt;&lt; n_rows*n_cols &lt;&lt; "elements in it."); // cu_mat temp(1,1); // HANDLE_ERROR( cudaMemcpy(temp.p,p+(idx-1),sizeof(double),cudaMemcpyDeviceToDevice) ); // Copy value from GPU to GPU // return temp; // } /***********************************************************************************************************************/ /************************************** Matrix element access based on index *******************************************/ cu_mat cu_mat::operator()(const size_t &amp;idx) const { confirm(idx &gt; 0, "Indexing starts from 1 for this library.") confirm(idx &lt;= n_rows*n_cols,"Error: Index exceeds matrix bounds. Matrix has " &lt;&lt; n_rows*n_cols &lt;&lt; " elements in it."); cu_mat temp(1,1); HANDLE_ERROR( cudaMemcpy(temp.p,p+(idx-1),sizeof(double),cudaMemcpyDeviceToDevice) ); // Copy value from GPU to GPU return std::move(temp); } /***********************************************************************************************************************/ /************************************** Access single element of the matrix *******************************************/ cu_mat cu_mat::operator()(const size_t &amp;r, const size_t &amp;c) const { confirm((r&gt;0)&amp;&amp;(c&gt;0), "Indexing starts from 1 for this library.") confirm((r&lt;=n_rows)&amp;&amp;(c&lt;=n_cols),"Error: Index exceeds matrix bounds. The size of the matrix is " &lt;&lt; n_rows &lt;&lt; "x" &lt;&lt; n_cols &lt;&lt; "."); cu_mat temp(1,1); HANDLE_ERROR( cudaMemcpy(temp.p,p+(c-1)*n_rows+r-1,sizeof(double),cudaMemcpyDeviceToDevice) ); // Copy value from GPU to GPU HANDLE_ERROR( cudaPeekAtLastError() ); return std::move(temp); } /***********************************************************************************************************************/ /************************************** Access sub-matrix *******************************************/ __global__ void submat(double* dest, double* src, size_t bias, size_t dest_rows, size_t main_rows_bias, size_t n_ele) { unsigned int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx&lt;n_ele) dest[idx] = src[bias+idx+idx/dest_rows*main_rows_bias]; } cu_mat cu_mat::operator()(const size_t &amp;r_begin, const size_t &amp;r_end, const size_t &amp;c_begin, const size_t &amp;c_end) const { confirm((r_begin&gt;0)&amp;&amp;(c_begin&gt;0), "Indexing starts from 1 for this library.") confirm((r_end&lt;=n_rows)&amp;&amp;(c_end&lt;=n_cols),"Error: Index exceeds matrix bounds. The size of the matrix is " &lt;&lt; n_rows &lt;&lt; "x" &lt;&lt; n_cols &lt;&lt; ".") cu_mat temp(r_end-r_begin+1,c_end-c_begin+1); size_t bias = (c_begin-1)*n_rows+r_begin-1; size_t main_rows_bias = n_rows-temp.n_rows; size_t n_ele = temp.n_rows*temp.n_cols; size_t n_threads = block_dim(n_ele); submat&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(temp.p,p,bias,temp.n_rows,main_rows_bias,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); return std::move(temp); } /***********************************************************************************************************************/ /*************************************** Assignment operator to copy 'cu_mat' **************************************/ cu_mat&amp; cu_mat::operator=(const cu_mat &amp;b) { // std::cout &lt;&lt; "Copy assignment operator called." &lt;&lt; std::endl; if ((n_rows*n_cols)!=(b.n_rows*b.n_cols)) { HANDLE_ERROR( cudaFree(p) ); HANDLE_ERROR( cudaMalloc((void**)&amp;p, b.n_rows*b.n_cols*sizeof(double)) ); // Allocate memory on GPU. } n_rows = b.n_rows; n_cols = b.n_cols; HANDLE_ERROR( cudaMemcpy(p,b.p,n_rows*n_cols*sizeof(double),cudaMemcpyDeviceToDevice) ); // Copy array from GPU to GPU return *this; } /***********************************************************************************************************************/ /*************************************** Assignment operator to move 'cu_mat' **************************************/ cu_mat&amp; cu_mat::operator=(cu_mat &amp;&amp;b) { // std::cout &lt;&lt; "Move assignment operator called." &lt;&lt; std::endl; n_rows = b.n_rows; b.n_rows = 0; n_cols = b.n_cols; b.n_cols = 0; HANDLE_ERROR( cudaFree(p) ); p = b.p; b.p = NULL; return *this; } /***********************************************************************************************************************/ /*************************************** Matrix multiplication **************************************/ __global__ void const_mat_mult(double *dest, double *src, double *n, size_t n_ele) { unsigned int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx&lt;n_ele) dest[idx] = (*n)*src[idx]; } cu_mat cu_mat::operator*(const cu_mat &amp;b) const &amp; { if (isscalar(*this)) { cu_mat c(b.n_rows,b.n_cols); size_t n_ele = c.n_rows*c.n_cols, n_threads = block_dim(n_ele); const_mat_mult&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(c.p,b.p,p,n_ele); return std::move(c); } else if (isscalar(b)) { cu_mat c(n_rows,n_cols); size_t n_ele = c.n_rows*c.n_cols, n_threads = block_dim(n_ele); const_mat_mult&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(c.p,p,b.p,n_ele); return std::move(c); } else { confirm(n_cols == b.n_rows,"Error : Matrix multiplication is not possible. Inner matrix dimensions must agree."); cu_mat c(n_rows,b.n_cols); HANDLE_ERROR( cudaMalloc((void**)&amp;c.p,c.n_rows*c.n_cols*sizeof(double)) ); // Allocate memory on GPU. double alf = 1.0, bet = 0; cublasHandle_t handle; HANDLE_ERROR( cublasCreate(&amp;handle) ); HANDLE_ERROR( cublasDgemm(handle,CUBLAS_OP_N,CUBLAS_OP_N,n_rows,b.n_cols,n_cols,&amp;alf,p,n_rows,b.p,n_cols,&amp;bet,c.p,n_rows) ); HANDLE_ERROR( cublasDestroy(handle) ); return std::move(c); } } cu_mat cu_mat::operator*(cu_mat &amp;&amp;b) const &amp; { if (isscalar(*this)) { cu_mat c = std::move(b); size_t n_ele = c.n_rows*c.n_cols, n_threads = block_dim(n_ele); const_mat_mult&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(c.p,c.p,p,n_ele); return std::move(c); } else if (isscalar(b)) { cu_mat c(n_rows,n_cols); size_t n_ele = c.n_rows*c.n_cols, n_threads = block_dim(n_ele); const_mat_mult&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(c.p,p,b.p,n_ele); return std::move(c); } else { confirm(n_cols == b.n_rows,"Error : Matrix multiplication is not possible. Inner matrix dimensions must agree."); cu_mat c(n_rows,b.n_cols); HANDLE_ERROR( cudaMalloc((void**)&amp;c.p,c.n_rows*c.n_cols*sizeof(double)) ); // Allocate memory on GPU. double alf = 1.0, bet = 0; cublasHandle_t handle; HANDLE_ERROR( cublasCreate(&amp;handle) ); HANDLE_ERROR( cublasDgemm(handle,CUBLAS_OP_N,CUBLAS_OP_N,n_rows,b.n_cols,n_cols,&amp;alf,p,n_rows,b.p,n_cols,&amp;bet,c.p,n_rows) ); HANDLE_ERROR( cublasDestroy(handle) ); return std::move(c); } } cu_mat cu_mat::operator*(const cu_mat &amp;b)&amp;&amp; { if (isscalar(*this)) { cu_mat c(b.n_rows,b.n_cols); size_t n_ele = c.n_rows*c.n_cols, n_threads = block_dim(n_ele); const_mat_mult&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(c.p,b.p,p,n_ele); return std::move(c); } else if (isscalar(b)) { cu_mat c = std::move(*this); size_t n_ele = c.n_rows*c.n_cols, n_threads = block_dim(n_ele); const_mat_mult&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(c.p,c.p,b.p,n_ele); return std::move(c); } else { confirm(n_cols == b.n_rows,"Error : Matrix multiplication is not possible. Inner matrix dimensions must agree."); cu_mat c(n_rows,b.n_cols); HANDLE_ERROR( cudaMalloc((void**)&amp;c.p,c.n_rows*c.n_cols*sizeof(double)) ); // Allocate memory on GPU. double alf = 1.0, bet = 0; cublasHandle_t handle; HANDLE_ERROR( cublasCreate(&amp;handle) ); HANDLE_ERROR( cublasDgemm(handle,CUBLAS_OP_N,CUBLAS_OP_N,n_rows,b.n_cols,n_cols,&amp;alf,p,n_rows,b.p,n_cols,&amp;bet,c.p,n_rows) ); HANDLE_ERROR( cublasDestroy(handle) ); return std::move(c); } } cu_mat cu_mat::operator*(cu_mat &amp;&amp;b)&amp;&amp; { if (isscalar(*this)) { cu_mat c = std::move(b); size_t n_ele = c.n_rows*c.n_cols, n_threads = block_dim(n_ele); const_mat_mult&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(c.p,c.p,p,n_ele); return std::move(c); } else if (isscalar(b)) { cu_mat c = std::move(*this); size_t n_ele = c.n_rows*c.n_cols, n_threads = block_dim(n_ele); const_mat_mult&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(c.p,c.p,b.p,n_ele); return std::move(c); } else { confirm(n_cols == b.n_rows,"Error : Matrix multiplication is not possible. Inner matrix dimensions must agree."); cu_mat c(n_rows,b.n_cols); HANDLE_ERROR( cudaMalloc((void**)&amp;c.p,c.n_rows*c.n_cols*sizeof(double)) ); // Allocate memory on GPU. double alf = 1.0, bet = 0; cublasHandle_t handle; HANDLE_ERROR( cublasCreate(&amp;handle) ); HANDLE_ERROR( cublasDgemm(handle,CUBLAS_OP_N,CUBLAS_OP_N,n_rows,b.n_cols,n_cols,&amp;alf,p,n_rows,b.p,n_cols,&amp;bet,c.p,n_rows) ); HANDLE_ERROR( cublasDestroy(handle) ); return std::move(c); } } /***********************************************************************************************************************/ /************************************ Greater than operator ***********************************************/ __global__ void elem_greater(double* a, double* b, double* c, size_t n_ele) { unsigned int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx&lt;n_ele) c[idx] = (a[idx] &gt; b[idx]); } cu_mat cu_mat::operator&gt;(const cu_mat &amp;b) const &amp; { confirm((n_rows == b.n_rows) &amp;&amp; (n_cols == b.n_cols),"Error : Boolean check is not possible. Matrices must have same dimensions."); cu_mat c(n_rows,n_cols); size_t n_ele = c.n_rows*c.n_cols; size_t n_threads = block_dim(n_ele); elem_greater&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(p,b.p,c.p,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); return std::move(c); } cu_mat cu_mat::operator&gt;(cu_mat &amp;&amp;b) const &amp; { confirm((n_rows == b.n_rows) &amp;&amp; (n_cols == b.n_cols),"Error : Boolean check is not possible. Matrices must have same dimensions."); cu_mat c = std::move(b); size_t n_ele = c.n_rows*c.n_cols; size_t n_threads = block_dim(n_ele); elem_greater&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(p,c.p,c.p,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); return std::move(c); } cu_mat cu_mat::operator&gt;(const cu_mat &amp;b) &amp;&amp; { confirm((n_rows == b.n_rows) &amp;&amp; (n_cols == b.n_cols),"Error : Boolean check is not possible. Matrices must have same dimensions."); cu_mat c = std::move(*this); size_t n_ele = c.n_rows*c.n_cols; size_t n_threads = block_dim(n_ele); elem_greater&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(c.p,b.p,c.p,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); return std::move(c); } cu_mat cu_mat::operator&gt;(cu_mat &amp;&amp;b) &amp;&amp; { confirm((n_rows == b.n_rows) &amp;&amp; (n_cols == b.n_cols),"Error : Boolean check is not possible. Matrices must have same dimensions."); cu_mat c = std::move(*this); size_t n_ele = c.n_rows*c.n_cols; size_t n_threads = block_dim(n_ele); elem_greater&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(c.p,b.p,c.p,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); return std::move(c); } /***********************************************************************************************************************/ /*************************************** Type conversion from cu_mat to double **************************************/ cu_mat::operator double() { confirm((n_rows==1) &amp;&amp; (n_cols==1), "Error: Type conversion is only possible in the case of 1x1 matrix."); double val; // Copy data from GPU to CPU. HANDLE_ERROR( cudaMemcpy(&amp;val,p,sizeof(double),cudaMemcpyDeviceToHost) ); return std::move(val); } /***********************************************************************************************************************/ // Member Functions /************************************ Two argument memory allocation with initialization ***********************************************/ void cu_mat::init(const size_t &amp;r, const size_t &amp;c) { n_rows = r; n_cols = c; if ((n_rows&gt;0)&amp;&amp;(n_cols&gt;0)) { HANDLE_ERROR( cudaMalloc((void**)&amp;p, n_rows*n_cols*sizeof(double)) ); HANDLE_ERROR( cudaMemset(p,0,n_rows*n_cols*sizeof(double)) ); } } /***********************************************************************************************************************/ /************************************ Element wise division ***********************************************/ __global__ void elem_div(double* a, double* b, double* c, size_t n_ele) { unsigned int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx&lt;n_ele) c[idx] = a[idx] / b[idx]; } cu_mat cu_mat::div(const cu_mat &amp;b) const &amp; { confirm((n_rows == b.n_rows) &amp;&amp; (n_cols == b.n_cols),"Error : Matrix multiplication is not possible. Matrices must have same dimensions."); cu_mat c(n_rows,n_cols); size_t n_ele = c.n_rows*c.n_cols; size_t n_threads = block_dim(n_ele); elem_div&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(p,b.p,c.p,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); return std::move(c); } cu_mat cu_mat::div(cu_mat &amp;&amp;b) const &amp; { confirm((n_rows == b.n_rows) &amp;&amp; (n_cols == b.n_cols),"Error : Matrix multiplication is not possible. Matrices must have same dimensions."); cu_mat c = std::move(b); size_t n_ele = c.n_rows*c.n_cols; size_t n_threads = block_dim(n_ele); elem_div&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(p,c.p,c.p,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); return std::move(c); } cu_mat cu_mat::div(const cu_mat &amp;b) &amp;&amp; { confirm((n_rows == b.n_rows) &amp;&amp; (n_cols == b.n_cols),"Error : Matrix multiplication is not possible. Matrices must have same dimensions."); cu_mat c = std::move(*this); size_t n_ele = c.n_rows*c.n_cols; size_t n_threads = block_dim(n_ele); elem_div&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(c.p,b.p,c.p,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); return std::move(c); } cu_mat cu_mat::div(cu_mat &amp;&amp;b) &amp;&amp; { confirm((n_rows == b.n_rows) &amp;&amp; (n_cols == b.n_cols),"Error : Matrix multiplication is not possible. Matrices must have same dimensions."); cu_mat c = std::move(*this); size_t n_ele = c.n_rows*c.n_cols; size_t n_threads = block_dim(n_ele); elem_div&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(c.p,b.p,c.p,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); return std::move(c); } /***********************************************************************************************************************/ /************************************ Element wise multiplication ***********************************************/ __global__ void elem_mult(double* a, double* b, double* c, size_t n_ele) { unsigned int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx&lt;n_ele) c[idx] = a[idx] * b[idx]; } cu_mat cu_mat::mult(const cu_mat &amp;b) const &amp; { confirm((n_rows == b.n_rows) &amp;&amp; (n_cols == b.n_cols),"Error : Matrix multiplication is not possible. Matrices must have same dimensions."); cu_mat c(n_rows,n_cols); size_t n_ele = c.n_rows*c.n_cols; size_t n_threads = block_dim(n_ele); elem_mult&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(p,b.p,c.p,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); return std::move(c); } cu_mat cu_mat::mult(cu_mat &amp;&amp;b) const &amp; { confirm((n_rows == b.n_rows) &amp;&amp; (n_cols == b.n_cols),"Error : Matrix multiplication is not possible. Matrices must have same dimensions."); cu_mat c = std::move(b); size_t n_ele = c.n_rows*c.n_cols; size_t n_threads = block_dim(n_ele); elem_mult&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(p,c.p,c.p,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); return std::move(c); } cu_mat cu_mat::mult(const cu_mat &amp;b) &amp;&amp; { confirm((n_rows == b.n_rows) &amp;&amp; (n_cols == b.n_cols),"Error : Matrix multiplication is not possible. Matrices must have same dimensions."); cu_mat c = std::move(*this); size_t n_ele = c.n_rows*c.n_cols; size_t n_threads = block_dim(n_ele); elem_mult&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(c.p,b.p,c.p,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); return std::move(c); } cu_mat cu_mat::mult(cu_mat &amp;&amp;b) &amp;&amp; { confirm((n_rows == b.n_rows) &amp;&amp; (n_cols == b.n_cols),"Error : Matrix multiplication is not possible. Matrices must have same dimensions."); cu_mat c = std::move(*this); size_t n_ele = c.n_rows*c.n_cols; size_t n_threads = block_dim(n_ele); elem_mult&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(c.p,b.p,c.p,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); return std::move(c); } /***********************************************************************************************************************/ /************************************ Element wise power ***********************************************/ __global__ void elem_power(double* dest, double* src, double n, size_t n_ele) { unsigned int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx&lt;n_ele) dest[idx] = pow(src[idx],n); } cu_mat cu_mat::pow(const double &amp;n) const &amp; { cu_mat c(n_rows,n_cols); size_t n_ele = c.n_rows*c.n_cols; size_t n_threads = block_dim(n_ele); elem_power&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(c.p,p,n,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); return std::move(c); } cu_mat cu_mat::pow(const double &amp;n) &amp;&amp; { cu_mat c = std::move(*this); size_t n_ele = c.n_rows*c.n_cols; size_t n_threads = block_dim(n_ele); elem_power&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(c.p,c.p,n,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); return std::move(c); } /***********************************************************************************************************************/ /************************************ Replace an element with a 'cu_mat' value ***********************************************/ void cu_mat::replace(const size_t &amp;r, const size_t &amp;c, const cu_mat &amp;n) { confirm((n.n_rows==1) &amp;&amp; (n.n_cols==1),"Error: Value being replaced with has to be scalar."); size_t bias = c*n_rows+r, src_rows = 1, src_cols = 1; size_t main_rows_bias = n_rows-src_rows, n_ele = src_rows*src_cols, n_threads = block_dim(n_ele); copymat&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(p,n.p,bias,src_rows,main_rows_bias,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); } /***********************************************************************************************************************/ /************************************ Replace submatrix with a 'cu_mat' matrix ***********************************************/ void cu_mat::replace(const size_t &amp;r_begin, const size_t &amp;r_end, const size_t &amp;c_begin, const size_t &amp;c_end, const cu_mat &amp;n) { confirm((r_end&lt;=n_rows) &amp;&amp; (c_end&lt;=n_cols),"Error: Index exceeds matrix bounds. The size of the matrix is " &lt;&lt; n_rows &lt;&lt; "x" &lt;&lt; n_cols &lt;&lt; "."); confirm((n.n_rows==r_end-r_begin+1) &amp;&amp; (n.n_cols==c_end-c_begin+1),"Error: Unable to replace the data due to size mismatch."); size_t bias = (c_begin-1)*n_rows+r_begin-1, src_rows = n.n_rows, src_cols = n.n_cols; size_t main_rows_bias = n_rows-src_rows, n_ele = src_rows*src_cols, n_threads = block_dim(n_ele); copymat&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(p,n.p,bias,src_rows,main_rows_bias,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); } /***********************************************************************************************************************/ /************************************ Print matrix data ***********************************************/ void cu_mat::get() { double *m = new double[n_rows*n_cols](); // Allocate space on CPU memory. confirm(m,"Error: Memory allocation failed in 'get()'.") // Check proper allocation. // Copy data from GPU to CPU. HANDLE_ERROR( cudaMemcpy(m,p,n_rows*n_cols*sizeof(double),cudaMemcpyDeviceToHost) ); std::cout &lt;&lt; std::scientific &lt;&lt; std::setprecision(4); for(int i = 0; i&lt;n_rows; ++i) { for(int j = 0; j&lt;n_cols; ++j) { std::cout&lt;&lt;m[j*n_rows+i]&lt;&lt;" "; } std::cout&lt;&lt;std::endl; } delete[] m; } /***********************************************************************************************************************/ /************************************ Print matrix to a file ***********************************************/ void cu_mat::print(std::ofstream &amp;print) { double *m = new double[n_rows*n_cols](); // Allocate space on CPU memory. confirm(m,"Error: Memory allocation failed in 'print()'.") // Check proper allocation. // Copy data from GPU to CPU. HANDLE_ERROR( cudaMemcpy(m,p,n_rows*n_cols*sizeof(double),cudaMemcpyDeviceToHost) ); // Print the matrix print &lt;&lt; std::scientific &lt;&lt; std::setprecision(8); for(int i = 0; i&lt;n_rows; ++i) { print &lt;&lt; " "; for(int j = 0; j&lt;n_cols; ++j) { print &lt;&lt; " " &lt;&lt; m[j*n_rows+i] &lt;&lt; " "; } print &lt;&lt; std::endl; } delete[] m; } /***********************************************************************************************************************/ /*************************************** Get number of rows *****************************************/ size_t cu_mat::rows(){return n_rows;} /***********************************************************************************************************************/ /*************************************** Get number of columns *****************************************/ size_t cu_mat::cols(){return n_cols;} /***********************************************************************************************************************/ /*************************************** Get GPU memory pointer *****************************************/ double* cu_mat::pointer(){return p;} /***********************************************************************************************************************/ /*************************************** Get number of rows *****************************************/ size_t cu_mat::rows() const {return n_rows;} /***********************************************************************************************************************/ /*************************************** Get number of columns *****************************************/ size_t cu_mat::cols() const {return n_cols;} /***********************************************************************************************************************/ /*************************************** Get GPU memory pointer *****************************************/ double* cu_mat::pointer() const {return p;} /***********************************************************************************************************************/ // Friend Functions /************************************** Matrix with random numbers ***********************************************/ cu_mat randn(const size_t &amp;r, const size_t &amp;c) { size_t r_new = r, c_new = c; if ((r%2!=0)&amp;&amp;(c%2!=0)) { r_new = r+1; c_new = c+1; } cu_mat a(r_new,c_new); curandGenerator_t prng; HANDLE_ERROR( curandCreateGenerator(&amp;prng, CURAND_RNG_PSEUDO_XORWOW) ); HANDLE_ERROR( curandSetPseudoRandomGeneratorSeed(prng,(unsigned long long) clock()) ); HANDLE_ERROR( curandGenerateNormalDouble(prng,a.p,a.n_rows*a.n_cols,0.0,1.0) ); //The number of values requested has to be multiple of 2. HANDLE_ERROR( curandDestroyGenerator(prng) ); return std::move(a(1,r,1,c)); } cu_mat randn(const size_t &amp;n=1){return std::move(randn(n,n));} /***************************************************************************************************************************/ /**************************************** Identity matrix *******************************************/ __global__ void eye_mat(double* p, const int r, const int n_ele) { unsigned int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx&lt;n_ele) { p[idx*r+idx] = 1.0; } } cu_mat eye(const size_t &amp;r, const size_t &amp;c) { cu_mat temp(r,c); size_t n_ele = min(r,c); size_t n_threads = block_dim(n_ele); eye_mat&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(temp.p,r,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); return std::move(temp); } cu_mat eye(const size_t &amp;n){return std::move(eye(n,n));} /***************************************************************************************************************************/ /***************************************** Matrix left divide *****************************************/ cu_mat mld(const cu_mat &amp;a, const cu_mat &amp;b) { return std::move(mld(cu_mat(a),cu_mat(b))); } cu_mat mld(const cu_mat &amp;a, cu_mat &amp;&amp;b) { return std::move(mld(cu_mat(a),std::move(b))); } cu_mat mld(cu_mat &amp;&amp;a, const cu_mat &amp;b) { return std::move(mld(std::move(a),cu_mat(b))); } cu_mat mld(cu_mat &amp;&amp;a, cu_mat &amp;&amp;b) // Adapted from CUSOLVER_Library.pdf QR examples { confirm(a.n_rows == b.n_rows,"Error: 'mld()' operation cannot be performed. Matrix dimensions must agree.") cu_mat A = std::move(a), B = std::move(b); // Copy current matrix to a new matrix for calculations. double *d_tau = NULL; double *d_work = NULL, alf = 1.0; int *devInfo = NULL, lwork = 0, info_gpu = 0; cusolverDnHandle_t cusolver_handle = NULL; cublasHandle_t cublas_handle = NULL; // step 1: create cusolver/cublas handle HANDLE_ERROR( cusolverDnCreate(&amp;cusolver_handle) ); HANDLE_ERROR( cublasCreate(&amp;cublas_handle) ); // step 2: allocate required extra memory on GPU. HANDLE_ERROR( cudaMalloc((void**)&amp;d_tau,sizeof(double)*A.n_cols) ); HANDLE_ERROR( cudaMalloc((void**)&amp;devInfo,sizeof(int)) ); // step 3: query working space of geqrf and ormqr HANDLE_ERROR( cusolverDnDgeqrf_bufferSize(cusolver_handle,A.n_rows,A.n_cols,A.p,A.n_rows,&amp;lwork) ); HANDLE_ERROR( cudaMalloc((void**)&amp;d_work, sizeof(double)*lwork) ); // step 4: compute QR factorization HANDLE_ERROR( cusolverDnDgeqrf(cusolver_handle,A.n_rows,A.n_cols,A.p,A.n_rows,d_tau,d_work,lwork,devInfo) ); HANDLE_ERROR( cudaDeviceSynchronize() ); // check if QR is good or not HANDLE_ERROR( cudaMemcpy(&amp;info_gpu, devInfo, sizeof(int),cudaMemcpyDeviceToHost) ); confirm(info_gpu == 0,"Error: 'mld()' operation cannot be performed. QR decomposition failed."); // step 5: compute Q^T*B (CUSOLVER documentation has typos. Follow LAPACK documentation.) HANDLE_ERROR( cusolverDnDormqr(cusolver_handle,CUBLAS_SIDE_LEFT,CUBLAS_OP_T,B.n_rows,B.n_cols,A.n_cols,A.p,A.n_rows,d_tau,B.p,B.n_rows,d_work,lwork,devInfo) ); HANDLE_ERROR( cudaDeviceSynchronize() ); // check if QR is good or not HANDLE_ERROR( cudaMemcpy(&amp;info_gpu, devInfo, sizeof(int),cudaMemcpyDeviceToHost) ); confirm(info_gpu == 0,"Error: 'mld()' operation cannot be performed. QR decomposition failed."); // step 6: compute x = R \ (Q^T*B) HANDLE_ERROR( cublasDtrsm(cublas_handle,CUBLAS_SIDE_LEFT,CUBLAS_FILL_MODE_UPPER,CUBLAS_OP_N,CUBLAS_DIAG_NON_UNIT,A.n_cols,B.n_cols,&amp;alf,A.p,A.n_rows,B.p,A.n_cols) ); HANDLE_ERROR( cudaDeviceSynchronize() ); // Free resources HANDLE_ERROR( cudaFree(d_tau) ); HANDLE_ERROR( cudaFree(devInfo) ); HANDLE_ERROR( cudaFree(d_work) ); HANDLE_ERROR( cublasDestroy(cublas_handle) ); HANDLE_ERROR( cusolverDnDestroy(cusolver_handle) ); return std::move(B); } /***************************************************************************************************************************/ /***************************************** Matrix with all values 1 *****************************************/ cu_mat ones(const size_t &amp;r, const size_t &amp;c) { cu_mat tmp(r,c,1); //tmp.del = 0; return std::move(tmp); } cu_mat ones(const size_t &amp;n){return std::move(ones(n,n));} /***************************************************************************************************************************/ /***************************************** Matrix with all values 0 *****************************************/ cu_mat zeros(const size_t &amp;r, const size_t &amp;c) { cu_mat tmp(r,c); //tmp.del = 0; return std::move(tmp); } cu_mat zeros(const size_t &amp;n){return std::move(zeros(n,n));} /***************************************************************************************************************************/ /*************************************** Transpose current matrix *****************************************/ __global__ void mat_trans(double* a, double* b, size_t rows, size_t cols, size_t n_ele) { unsigned int idx = threadIdx.x + blockIdx.x * blockDim.x; size_t r = idx%rows, c = idx/rows; if (idx&lt;n_ele) a[c+r*cols] = b[idx]; } cu_mat trans(cu_mat &amp;a) { cu_mat tmp(a.n_cols,a.n_rows); size_t n_ele = tmp.n_rows*tmp.n_cols; size_t n_threads = block_dim(n_ele); mat_trans&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(tmp.p,a.p,a.n_rows,a.n_cols,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); return std::move(tmp); } /***********************************************************************************************************************/ /*************************************** Horizontal concatenation of two matrices *****************************************/ cu_mat horzcat(cu_mat &amp;a, cu_mat &amp;b) { confirm(a.n_rows==b.n_rows,"Error: Dimensions of arrays being horizontally concatenated are not consistent."); cu_mat tmp(a.n_rows,a.n_cols+b.n_cols); HANDLE_ERROR( cudaMemcpy(tmp.p,a.p,a.n_rows*a.n_cols*sizeof(double),cudaMemcpyDeviceToDevice) ); size_t n_ele = b.n_rows*b.n_cols, n_threads = block_dim(n_ele); copymat&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(tmp.p,b.p,a.n_cols*tmp.n_rows,tmp.n_rows,0,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); return std::move(tmp); } /***************************************************************************************************************************/ /*************************************** Vertical concatenation of two matrices *****************************************/ cu_mat vertcat(cu_mat &amp;a, cu_mat &amp;b) { confirm(a.n_cols==b.n_cols,"Error: Dimensions of arrays being vertically concatenated are not consistent."); cu_mat tmp(a.n_rows+b.n_rows,a.n_cols); size_t n_ele = a.n_rows*a.n_cols, n_threads = block_dim(n_ele); copymat&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(tmp.p,a.p,0,a.n_rows,tmp.n_rows-a.n_rows,n_ele); n_ele = b.n_rows*b.n_cols; n_threads = block_dim(n_ele); copymat&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(tmp.p,b.p,a.n_rows,b.n_rows,tmp.n_rows-b.n_rows,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); return std::move(tmp); } /***************************************************************************************************************************/ /*************************************** MATLAB colon operator *****************************************/ __global__ void ss_mat_fill(double* dest, double i, double step, size_t n_ele) { unsigned int idx = threadIdx.x + blockIdx.x * blockDim.x; if(idx&lt;n_ele) { dest[idx] = i+step*idx; } } cu_mat stepspace(const double &amp;i, const double &amp;f, const double &amp;step=1) { size_t n; if (((f-i)/step)&gt;=0) n = (f-i)/step+1; else n = 0; cu_mat tmp(n,1); size_t n_ele = tmp.n_rows*tmp.n_cols, n_threads = block_dim(n_ele); ss_mat_fill&lt;&lt;&lt;n_ele/n_threads,n_threads&gt;&gt;&gt;(tmp.p,i,step,n_ele); HANDLE_ERROR( cudaPeekAtLastError() ); return std::move(tmp); } /***************************************************************************************************************************/ /************************************ Check if 'cu_mat' object is scalar ***********************************************/ bool isscalar(const cu_mat &amp;a) { return ((a.n_rows*a.n_cols)==1); } /***********************************************************************************************************************/ // Destructor cu_mat::~cu_mat() { HANDLE_ERROR( cudaFree(p) ); p = NULL; } </code></pre> <h2>block_dim.cu ## - Function to compute the block dimension for kernel calls</h2> <pre><code>#include "imp_includes.hcu" size_t block_dim(size_t n_ele) { size_t tc; if (n_ele&lt;=1024) return(n_ele); else if (n_ele%2==0){ for (tc=1024;tc&gt;1;tc=tc-2){ if (n_ele%tc==0) return(tc);}} else{ for (tc=1023;tc&gt;1;tc=tc-2){ if (n_ele%tc==0) return(tc);}} std::cout &lt;&lt; "Warning: Calculations cannot be divided equally. Be careful when making the CUDA kernel." &lt;&lt; std::endl; return(256); } </code></pre> <h2>cu_error_list.cu ## - List of possible cuBLAS, cuRAND and cuSOLVER api errors.</h2> <pre><code>#include "imp_includes.hcu" // cuBLAS API errors const char *cublasGetErrorString(cublasStatus_t err) { switch (err) { case CUBLAS_STATUS_NOT_INITIALIZED: return "CUBLAS_STATUS_NOT_INITIALIZED"; case CUBLAS_STATUS_ALLOC_FAILED: return "CUBLAS_STATUS_ALLOC_FAILED"; case CUBLAS_STATUS_INVALID_VALUE: return "CUBLAS_STATUS_INVALID_VALUE"; case CUBLAS_STATUS_ARCH_MISMATCH: return "CUBLAS_STATUS_ARCH_MISMATCH"; // case CUBLAS_STATUS_MAPPING_err: // return "CUBLAS_STATUS_MAPPING_err"; case CUBLAS_STATUS_EXECUTION_FAILED: return "CUBLAS_STATUS_EXECUTION_FAILED"; // case CUBLAS_STATUS_INTERNAL_err: // return "CUBLAS_STATUS_INTERNAL_err"; case CUBLAS_STATUS_NOT_SUPPORTED: return "CUBLAS_STATUS_NOT_SUPPORTED"; // case CUBLAS_STATUS_LICENSE_err: // return "CUBLAS_STATUS_LICENSE_err"; } return "&lt;unknown&gt;"; } // cuSOLVER API errors const char *cusolverGetErrorString(cusolverStatus_t err) { switch (err) { case CUSOLVER_STATUS_NOT_INITIALIZED: return "CUSOLVER_STATUS_NOT_INITIALIZED"; case CUSOLVER_STATUS_ALLOC_FAILED: return "CUSOLVER_STATUS_ALLOC_FAILED"; case CUSOLVER_STATUS_INVALID_VALUE: return "CUSOLVER_STATUS_INVALID_VALUE"; case CUSOLVER_STATUS_ARCH_MISMATCH: return "CUSOLVER_STATUS_ARCH_MISMATCH"; // case CUSOLVER_STATUS_MAPPING_err: // return "CUSOLVER_STATUS_MAPPING_err"; case CUSOLVER_STATUS_EXECUTION_FAILED: return "CUSOLVER_STATUS_EXECUTION_FAILED"; // case CUSOLVER_STATUS_INTERNAL_err: // return "CUSOLVER_STATUS_INTERNAL_err"; case CUSOLVER_STATUS_MATRIX_TYPE_NOT_SUPPORTED: return "CUSOLVER_STATUS_MATRIX_TYPE_NOT_SUPPORTED"; case CUSOLVER_STATUS_NOT_SUPPORTED: return "CUSOLVER_STATUS_NOT_SUPPORTED "; case CUSOLVER_STATUS_ZERO_PIVOT: return "CUSOLVER_STATUS_ZERO_PIVOT"; case CUSOLVER_STATUS_INVALID_LICENSE: return "CUSOLVER_STATUS_INVALID_LICENSE"; } return "&lt;unknown&gt;"; } // cuRAND API errors const char *curandGetErrorString(curandStatus_t err) { switch (err) { case CURAND_STATUS_VERSION_MISMATCH: return "CURAND_STATUS_VERSION_MISMATCH"; case CURAND_STATUS_NOT_INITIALIZED: return "CURAND_STATUS_NOT_INITIALIZED"; case CURAND_STATUS_ALLOCATION_FAILED: return "CURAND_STATUS_ALLOCATION_FAILED"; // case CURAND_STATUS_TYPE_err: // return "CURAND_STATUS_TYPE_err"; case CURAND_STATUS_OUT_OF_RANGE: return "CURAND_STATUS_OUT_OF_RANGE"; case CURAND_STATUS_LENGTH_NOT_MULTIPLE: return "CURAND_STATUS_LENGTH_NOT_MULTIPLE"; case CURAND_STATUS_DOUBLE_PRECISION_REQUIRED: return "CURAND_STATUS_DOUBLE_PRECISION_REQUIRED"; case CURAND_STATUS_LAUNCH_FAILURE: return "CURAND_STATUS_LAUNCH_FAILURE"; case CURAND_STATUS_PREEXISTING_FAILURE: return "CURAND_STATUS_PREEXISTING_FAILURE"; case CURAND_STATUS_INITIALIZATION_FAILED: return "CURAND_STATUS_INITIALIZATION_FAILED"; case CURAND_STATUS_ARCH_MISMATCH: return "CURAND_STATUS_ARCH_MISMATCH"; // case CURAND_STATUS_INTERNAL_err: // return "CURAND_STATUS_INTERNAL_err"; } return "&lt;unknown&gt;"; } </code></pre> <h2>error_check.cu ## - Overloaded functions to convert errors into strings</h2> <pre><code>#include "imp_includes.hcu" //#define HANDLE_ERROR( err ) (HandleError( err, __FILE__, __LINE__ )) void HandleError( cudaError_t err,const char *file,int line ) { confirm(err == cudaSuccess,cudaGetErrorString( err )&lt;&lt;" in "&lt;&lt;file&lt;&lt;" at "&lt;&lt;line&lt;&lt;"."); } void HandleError( cublasStatus_t err,const char *file,int line ) { confirm(err == CUBLAS_STATUS_SUCCESS,cublasGetErrorString( err )&lt;&lt;" in "&lt;&lt;file&lt;&lt;" at "&lt;&lt;line&lt;&lt;"."); } void HandleError( cusolverStatus_t err,const char *file,int line ) { confirm(err == CUSOLVER_STATUS_SUCCESS,cusolverGetErrorString( err )&lt;&lt;" in "&lt;&lt;file&lt;&lt;" at "&lt;&lt;line&lt;&lt;"."); } void HandleError( curandStatus_t err,const char *file,int line ) { confirm(err == CURAND_STATUS_SUCCESS,curandGetErrorString( err )&lt;&lt;" in "&lt;&lt;file&lt;&lt;" at "&lt;&lt;line&lt;&lt;"."); } </code></pre> <h2>cu_mat_test.cu ## - Main function to test the class</h2> <pre><code>#include "cu_mat.hcu" #include &lt;ctime&gt; int main() { clock_t begin = clock(); look_for_errors; cu_mat A = randn(5), b = randn(5,1); cu_mat c = mld(A,b); A.get(); b.get(); c.get(); report_errors; clock_t end = clock(); double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; std::cout &lt;&lt; elapsed_secs &lt;&lt; std::endl; return 0; } </code></pre> <h2>imp_includes.hcu ## - Macro definition for exception handling and included other required libraries</h2> <pre><code>#ifndef IMP_INCLUDES_H_ #define IMP_INCLUDES_H_ #include &lt;iostream&gt; #include &lt;cuda_runtime.h&gt; #include &lt;curand.h&gt; #include &lt;curand_kernel.h&gt; #include &lt;cublas_v2.h&gt; #include &lt;cusolverDn.h&gt; #include &lt;fstream&gt; #include &lt;iomanip&gt; #include &lt;functional&gt; // Macro definitions #define look_for_errors try{ #define report_errors }catch(int n){} #define confirm(cond,err) \ if(!(cond)) \ { \ std::cout &lt;&lt; "\a" &lt;&lt; err &lt;&lt; std::endl; \ throw 1; \ } #define HANDLE_ERROR( err ) (HandleError( err, __FILE__, __LINE__ )) // Extra functions size_t block_dim(size_t n_ele); const char *cublasGetErrorString(cublasStatus_t err); // cuBLAS API errors const char *cusolverGetErrorString(cusolverStatus_t err); // cuSOLVER API errors const char *curandGetErrorString(curandStatus_t err); // cuRAND API errors void HandleError( cudaError_t err,const char *file,int line ); void HandleError( cublasStatus_t err,const char *file,int line ); void HandleError( cusolverStatus_t err,const char *file,int line ); void HandleError( curandStatus_t err,const char *file,int line ); __global__ void copymat(double* dest, double* src, size_t bias, size_t src_rows, size_t main_rows_bias, size_t n_ele); #endif /* IMP_INCLUDES_HCU_ */ </code></pre>
[]
[ { "body": "<p>A few short comments:</p>\n\n<ol>\n<li>Initializing a matrix with a compile-time list of values (initializer list) does not seem to be very useful - as CUDA is used to process huge amounts of data, not a tiny number of elements you provide at compile time.</li>\n<li>Mixing code for mathematical / data structure abstractions with error handling utility code into the same class is not a good idea.</li>\n<li>Your function and method names are often unnecessary shortened (like <code>mld</code>), ambiguous (<code>confirm</code>), or involve redundancy (like <code>cu_mat</code> instead of <code>matrix</code> in an appropriate namespace).</li>\n<li>It looks like these are supposed to be matrices that are located in host memory, but copied back and forth to device memory for every single operation. Why is that a useful think to have?</li>\n</ol>\n\n<p>PS - If you want to use more C++-ish error handling, you could consider my <a href=\"https://github.com/eyalroz/cuda-api-wrappers\" rel=\"nofollow noreferrer\">CUDA API wrappers</a> which do just that (and is obviously separated from any application-specific logic).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T07:44:24.477", "Id": "222386", "ParentId": "222337", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T03:34:33.183", "Id": "222337", "Score": "6", "Tags": [ "c++", "object-oriented", "matrix", "cuda" ], "Title": "CUDA matrix class" }
222337
<p>I solved a problem with JavaScript which has the following requirements:</p> <ol> <li>Two non-empty linked lists representing two non-negative integers.</li> <li>Digits stored in reverse order</li> <li>Each node contains a single digit</li> <li>Add the two numbers and return it as a linked list</li> </ol> <p>Sample I/O:</p> <pre><code>Input: (2 -&gt; 4 -&gt; 3) + (5 -&gt; 6 -&gt; 4) Output: 7 -&gt; 0 -&gt; 8 Explanation: 342 + 465 = 807 </code></pre> <p>My code:</p> <pre><code> /** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ var addTwoNumbers = function(l1, l2) { let l1Str = ""; let l2Str = ""; while (l1 !== null) { l1Str += l1.val.toString(); l1 = l1.next; } while (l2 !== null) { l2Str += l2.val.toString(); l2 = l2.next; } let sum = (BigInt(l1Str.split("").reverse().join("")) + BigInt(l2Str.split("").reverse().join(""))).toString(); let resultNodeList = new ListNode(sum[sum.length - 1]); let resultHead = resultNodeList; for (let i = sum.length - 2;i &gt;= 0;i--) { resultNodeList.next = new ListNode(sum[i]); resultNodeList = resultNodeList.next; } return resultHead; }; </code></pre> <p>Note: I had to use <code>BigInt</code> cause <code>parseInt</code> won't work on big integers as expected.</p> <p>Although it passed all test cases, what are some ways to improve this code in terms of both time and space complexity?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T07:09:23.720", "Id": "430256", "Score": "0", "body": "In my opinion, using `BigInt` to perform the addition is considered cheating." } ]
[ { "body": "<h2>Here are a list of improvements:</h2>\n\n<ol>\n<li>Use ECMAScript features and syntax</li>\n<li>Create own implementation of BigInt</li>\n<li>Don't use strings !</li>\n<li>Create functions to regroup similar code and reduce code duplication</li>\n</ol>\n\n<h2>Detailed Explanation:</h2>\n\n<p>Generates a ListNode from a given array (array should already be reversed).</p>\n\n<pre><code>generateListNode = (list) =&gt; {\n const [ele] = list;\n //create the sentinel (starting point of the node list)\n const sentinel = new ListNode(ele);\n let current = sentinel;\n for(let i = 1; i &lt; list.length; i++){\n //update the next with the new list node\n //set the current to the new next\n current = current.next = new ListNode(list[i]);\n }\n return sentinel;\n}\n</code></pre>\n\n<hr>\n\n<p>Convert a ListNode to an Array</p>\n\n<pre><code>const convertToValueList = (list) =&gt; {\n const res = [];\n //as long as the value \"list\" is not null it'll continue the loop\n //push the list.val to the result array\n do { res.push(list.val); } while(list = list.next);\n return res;\n}\n</code></pre>\n\n<hr>\n\n<p>addTwoNumbers has it's own implementation of BigInt</p>\n\n<pre><code>const addTwoNumbers = function(l1, l2) {\n\n //Convert the ListNode to arrays\n const l1Values = convertToValueList(l1);\n const l2Values = convertToValueList(l2);\n\n //find the longest of either list\n const len = Math.max(l1Values.length, l2Values.length);\n\n //when adding a column, value should not exceed 9, otherwise it'll be set to the remainder\n //i.e.: 10 -&gt; 1, 23 -&gt; 2, 30 -&gt; 3\n let remainder = 0;\n //final result in reverse\n const sum = [];\n for (let i = 0; i &lt; len; i++) {\n //add the sum of each value of the list at the \"i\" position\n //if the value does not exist (i.e.: undefined) use default 0\n //add the remainder if it exists\n const tempSum = (l1Values[i] || 0) + (l2Values[i] || 0) + remainder;\n //update the remainder (any value under 10 is set to 0 because of Math.floor)\n remainder = Math.max(Math.floor(tempSum/10), 0);\n //add the value (modulo 10 so only numbers 0 - 9 are added)\n sum.push(tempSum % 10);\n }\n\n console.log(sum);\n //generate the list node and return final result\n return generateListNode(sum);\n};\n</code></pre>\n\n<h2>Working Example:</h2>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class ListNode {\n constructor(val){\n this.val = val;\n this.next = null;\n } \n}\n\ngenerateListNode = (list) =&gt; {\n const [ele] = list;\n const sentinel = new ListNode(ele);\n let current = sentinel;\n for(let i = 1; i &lt; list.length; i++){\n current = current.next = new ListNode(list[i]);\n }\n return sentinel;\n}\n\nconst list1 = generateListNode([2, 4, 3]);\nconst list2 = generateListNode([5, 6, 4]);\n\nconst convertToValueList = (list) =&gt; {\n const res = [];\n do { res.push(list.val); } while(list = list.next);\n return res;\n}\n\nconst addTwoNumbers = function(l1, l2) {\n\n const l1Values = convertToValueList(l1);\n const l2Values = convertToValueList(l2);\n \n const len = Math.max(l1Values.length, l2Values.length);\n \n let remainder = 0;\n const sum = [];\n for(let i = 0; i &lt; len; i++){\n const tempSum = (l1Values[i] || 0) + (l2Values[i] || 0) + remainder;\nremainder = Math.floor(tempSum/10);\n sum.push(tempSum % 10);\n }\n\n console.log(sum);\n return generateListNode(sum);\n};\n\nconst res = addTwoNumbers(list1, list2);\nconsole.log(res);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h2>Additional:</h2>\n\n<p>The best case scenario is if you have the option to add methods to <code>ListNode</code>.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class BodyNode {\n constructor(val){\n this.val = val;\n this.next = null;\n }\n}\n\nclass ListNode extends BodyNode {\n \n static FromArray(list){\n if(list.length === 0) throw new Error(\"Array cannot be of length 0\");\n const clone = list.slice();\n const instance = new ListNode(clone.shift());\n while(clone.length &gt; 0){\n instance.add(clone.shift());\n }\n return instance;\n }\n\n constructor(val){\n super(val);\n this.last = this;\n }\n \n add(val){\n this.last = this.last.next = new BodyNode(val);\n }\n \n toArray(){\n const res = [];\n let current = this;\n do { res.push(current.val); } while(current = current.next);\n return res;\n }\n \n}\n\nconst list1 = ListNode.FromArray([2, 4, 3]);\nconst list2 = ListNode.FromArray([5, 6, 4]);\n\nconst addTwoNumbers = function(l1, l2) {\n\n const l1Arr = l1.toArray();\n const l2Arr = l2.toArray();\n \n const len = Math.max(l1Arr.length, l2Arr.length);\n \n let remainder = 0;\n const sum = [];\n for(let i = 0; i &lt; len; i++){\n const tempSum = (l1Arr[i] || 0) + (l2Arr[i] || 0) + remainder;\n remainder = Math.floor(tempSum/10);\n sum.push(tempSum % 10);\n }\n\n console.log(sum);\n return ListNode.FromArray(sum);\n};\n\nconst res = addTwoNumbers(list1, list2);\nconsole.log(res);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T12:27:03.443", "Id": "222350", "ParentId": "222338", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T03:36:47.870", "Id": "222338", "Score": "2", "Tags": [ "javascript", "linked-list" ], "Title": "Adding elements of 2 linked list in reverse order" }
222338
<p>To stay in practice with my Python I've decided to write an explicit song checker. It checks each word in the song against an array of 14 explicit words contained in the text file. I've decided not to include the words that are to be checked against, for I am <a href="https://codereview.meta.stackexchange.com/q/9209">not sure about the rule of having explicit words in a program's code</a>. Feedback on efficiency and structure is what I'm going for mostly. Style and other critiques are invited as well.</p> <p><strong>explicit_song_checker.py</strong></p> <pre><code>explicit_words = [ #explicit words not shown ] def isClean(song_path): with open(song_path) as song: for line in song: words = line.split(" ") for word in words: for explicit_word in explicit_words: if word == explicit_word: return False return True def main(): song = raw_input("Enter path to song: \n") if isClean(song): print("CLEAN") else: print("EXPLICIT") if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T19:31:05.520", "Id": "430306", "Score": "6", "body": "The only tiny thing (not big enough for an answer, IMHO) I want to add to all the great answers already given, is about naming variables. It should be clear from the name what a variable contains. What does another programmer expect that a variable named `song` contains? It cannot be a song, because that is something that you hear. So probably the lyrics then? Or the file? Ah, the *path* to the *file* that contains the *lyrics* of the song. I would try to make variable names as \"explicit\" as possible ;-) So `song_path` (as used in the function) is already much better :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T00:32:20.517", "Id": "430336", "Score": "9", "body": "As a counterexample, check out the [Scunthorpe problem](https://en.wikipedia.org/wiki/Scunthorpe_problem) for what can happen if your check is overzealous…" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T08:19:56.610", "Id": "430500", "Score": "0", "body": "Not sure if scope creeping the review, but would be nice if your script could take a path to a folder and print all songs inside it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T07:23:44.233", "Id": "430673", "Score": "0", "body": "why not use a dictionary and some sort of hash. a linear search would be horrible" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T22:46:55.343", "Id": "430978", "Score": "1", "body": "There is a [meta CR post that involves this post](https://codereview.meta.stackexchange.com/q/9209/120114)" } ]
[ { "body": "<p>Splitting <code>line</code> into <code>words</code> using <code>words = line.split(\" \")</code> will only split the line on space characters. If two words are separated by a tab character, or other white space character other than a space, the split will not happen at that point, which may confuse your explicit checker.</p>\n\n<p>Using <code>words = line.split()</code> would split on spaces, tab characters, and any other white space characters.</p>\n\n<p>You might also want to investigate splitting using the word break regular expression <code>\\b</code>, which would treat non-word characters as break points, so that a line containing an explicit word immediately followed by a comma (such as <code>\"explicit,\"</code>) or period, or semicolon, etc. won't sneak through the filter.</p>\n\n<hr>\n\n<pre><code> for explicit_word in explicit_words:\n if word == explicit_word:\n return False\n</code></pre>\n\n<p>Python has great searching built into it. Instead of explicitly writing a loop over all explicit words, you could just ask Python to tell you if a word is in the list of explicit words:</p>\n\n<pre><code> if word in explicit_words:\n return False\n</code></pre>\n\n<p>Or better, use a <code>set()</code> of explicit words, and the <code>in</code> operation drops from <span class=\"math-container\">\\$O(n)\\$</span> to <span class=\"math-container\">\\$O(1)\\$</span> time complexity:</p>\n\n<pre><code>explicit_words = {\n \"explicit\", \"bad\", \"ugly\", \"offensive\", \"words\" \n}\n\n# ...\n\n if word in explicit_words:\n return False\n</code></pre>\n\n<hr>\n\n<p>We've improved things a little, but we still have an explicit (pun intended) loop over the list of words in a line. We can use the <code>any()</code> method, and a list comprehension, to get Python to do the looping for us, which should be faster.</p>\n\n<pre><code> for line in song:\n words = line.split()\n if any(word in explicit_words for word in words):\n return False\n</code></pre>\n\n<p>If <code>word in explicits</code> returns <code>True</code> for any of the <code>word</code> in the list <code>words</code>, the <code>any()</code> method will \"short-circuit\" and immediately return <code>True</code> without examining the remaining items in <code>words</code>.</p>\n\n<hr>\n\n<p>If <code>\"explicit\"</code> is a bad word, and the song lyrics contains <code>\"Explicit\"</code> or <code>\"EXPLICIT\"</code>, you wouldn't want to mark the song as \"CLEAN\", right? Perhaps you want <code>word.lower() in explicit_words</code>? As @wizzwizz4 pointed out, <code>.casefold()</code> is better than <code>.lower()</code>.</p>\n\n<hr>\n\n<p>Resulting method:</p>\n\n<pre><code>explicit_words = set(explicit_word.casefold()\n for explicit_word in (\"explicit\", \"bad\", \"ugly\", \"offensive\", \"words\"))\n\ndef isClean(song_path):\n with open(song_path) as song:\n for line in song:\n words = line.split()\n if any(word.casefold() in explicit_words for word in words):\n return False \n return True\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T12:22:01.590", "Id": "430271", "Score": "1", "body": "Why does it need to iterate over the song lines? `song.split()` would also split on `\\n` (and `\\r`, of course). Call me unpythonic, but I would directly `return any(word.lower() in explicit_words for word in song.split())`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T12:37:41.810", "Id": "430273", "Score": "0", "body": "@Helio I expect you would need `song.read().split()`, not `song.split()`. As for why I didn’t? I considered making it one-statement, and decided against doing so because the `split()` doesn’t consider punctuation as word separators. That area still needed replacement with a regex `\\b` style word splitting, so embedding it inside of the `any(...)` hides the work that still needed to be done." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T12:56:35.177", "Id": "430276", "Score": "0", "body": "yes, my bad; I've posted the comment thoughtlessly. A naïve alternative to regular expressions would be replacing punctuation symbols by spaces and then running `split`. However, that would be too clumsy. If this code is not an exercise, maybe the OP should use some specialized framework like NLTK." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T16:17:06.343", "Id": "430295", "Score": "3", "body": "Why not `str.casefold` instead of `str.lower`? They're the same for (most of) Latin, but different for stuff like Greek." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T16:26:45.690", "Id": "430296", "Score": "0", "body": "@wizzwizz4 Fair point; well made. All the words in `explicit_words` would need to be run through `casefold()` as well." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T04:35:28.337", "Id": "222342", "ParentId": "222339", "Score": "21" } }, { "body": "<p>I recommend practicing Python 3 rather than Python 2 these days.</p>\n\n<p>According to <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"noreferrer\">PEP 8</a>, <code>isClean()</code> should be <code>is_clean()</code>.</p>\n\n<p>One or more of your loops could be replaced by some use of the <a href=\"https://docs.python.org/2/library/functions.html#any\" rel=\"noreferrer\"><code>any()</code></a> function. Note that this suggests that an <code>is_explicit()</code> function would be a more natural concept than an <code>is_clean()</code> function.</p>\n\n<p>I would expect song lyrics to contain a mixture of uppercase and lowercase. Words may be delimited by punctuation as well as spaces. Therefore, <code>words = line.split(\" \")</code> is probably too naïve. Furthermore, I would expect each song to be short enough to fit entirely in memory very comfortably, so processing each file line by line is an unnecessary complication.</p>\n\n<p>I would rewrite the program to use a <a href=\"https://docs.python.org/2/library/re.html\" rel=\"noreferrer\">regular expression</a> instead.</p>\n\n<pre><code>import re\n\nexplicit_words = [\n …\n]\n\nis_explicit = re.compile(\n r'\\b(?:' +\n '|'.join(re.escape(w) for w in explicit_words) +\n r')\\b',\n re.IGNORECASE).search\n\ndef main():\n with open(raw_input(\"Enter path to song: \")) as song:\n print(\"EXPLICIT\" if is_explicit(song.read()) else \"CLEAN\")\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>The way I chose to write the <code>is_explicit()</code> function above might show too much Haskell influence for some Python programmers' taste. Here's a more conventional way of writing it:</p>\n\n<pre><code>def is_explicit(text):\n return re.search(\n r'\\b(?:' +\n '|'.join(re.escape(w) for w in explicit_words) +\n r')\\b',\n text,\n re.IGNORECASE\n )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T23:50:52.933", "Id": "430652", "Score": "0", "body": "The regex answer has a variety of things I don't like. Firstly, this compiles the regex every time. 2nd, regex has no guarantees of O(1) like a set would." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T00:00:02.713", "Id": "430653", "Score": "0", "body": "@OscarSmith The program calls the helper function once from `main()`, and the word list contains just 14 entries, so neither objection was a significant concern in this solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T00:21:47.733", "Id": "430654", "Score": "0", "body": "Oh, I was mainly commenting on the bottom block, where it's in the function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T07:32:13.343", "Id": "430675", "Score": "2", "body": "I don't think using the regular expression makes this code any easier to understand. https://www.xkcd.com/1171/" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T04:40:42.920", "Id": "222343", "ParentId": "222339", "Score": "25" } }, { "body": "<p>Some suggestions:</p>\n\n<ul>\n<li>Using <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"noreferrer\"><code>argparse</code></a> to parse arguments is preferable to any kind of interactive input, because it means that\n\n<ul>\n<li>it's much easier to automate and integrate in other scripts,</li>\n<li>you could trivially support passing <em>multiple</em> songs in one command,</li>\n<li>it's what any experienced shell user would expect, and</li>\n<li>if the user adds <code>--help</code> or doesn't pass any arguments they will get a synopsis for the command.</li>\n</ul></li>\n<li>The list of explicit words should <em>not</em> be part of the code, because it is configuration and is very likely to change often. You'll want to put words in a separate file and read them in during initialization. You could very easily make this an optional argument (with <code>argparse</code>) so that you could do fancy stuff like <code>./explicit_song_checker.py --words=./words.txt --words=./other.txt ./kill-the-queen.txt ./bulls-on-parade.txt</code></li>\n<li><a href=\"https://github.com/ambv/black\" rel=\"noreferrer\"><code>black</code></a> will automatically format your code to be pretty idiomatic, such as using <em>two</em> empty lines between top-level functions.</li>\n<li><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"noreferrer\"><code>flake8</code></a> will check for style issues. I believe it will assume that you're writing Python 3, and so will complain about the use of <code>raw_input</code> (called <code>input</code> in Python 3).</li>\n<li><a href=\"https://github.com/python/mypy/\" rel=\"noreferrer\"><code>mypy</code></a> can be used to enforce type hints, which is a super helpful way to make your code clearer without resorting to comments.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T06:27:07.740", "Id": "222344", "ParentId": "222339", "Score": "16" } }, { "body": "<ul>\n<li><p>To simplify your input you could change <code>word == explicit_word</code> to <code>explicit_word in word</code>.</p>\n\n<p>This can lead to the <a href=\"https://en.wikipedia.org/wiki/Scunthorpe_problem\" rel=\"nofollow noreferrer\">Scunthorpe problem</a>, and so from here you can check if the word only contains prefixes and suffixes.</p>\n\n<p>Given <a href=\"https://dictionary.cambridge.org/grammar/british-grammar/word-formation/prefixes\" rel=\"nofollow noreferrer\">the amount of common prefixes alone</a>, it's unlikely you'd catch all variations using a blacklist alone. It would also catch gibberish/semigibberish that you may not have thought of - \"Antioverfucked\" / \"Overantifucked\".</p></li>\n<li><p>Your code misses words without spaces \"I don't give afuck\" and so you may want to perform a 'similarity check'.</p>\n\n<p>This could also match thinks like \"sexx\".</p></li>\n<li><p>Your code doesn't reasonably handle ZWSP and other forms of Unicode abuse.</p>\n\n<pre><code>&gt;&gt;&gt; print('exp\\u200blitive')\nexp​litive\n&gt;&gt;&gt; 'exp\\u200blitive' == 'explitive'\nFalse\n&gt;&gt;&gt; print('exp\\u1DD3litive')\nexpᷓlitive\n</code></pre></li>\n<li><p>Your code doesn't reasonably detect leet speak.</p></li>\n<li><p>Your code doesn't reasonably detect creative Unicode character selections.</p>\n\n<pre><code>&gt;&gt;&gt; print('\\u2131\\u01DA\\u0255\\u212A')\nℱǚɕK\n</code></pre></li>\n<li><p>Your code doesn't reasonably handle phonetic abuse.</p>\n\n<p>\"Phuck\" is pronounced \"Fuck\".</p>\n\n<p>\"Bend Dover\" sounds like \"bend over\".</p>\n\n<p>\"I CUP\" spelt out is \"I see you pee\".</p>\n\n<p>\"See you next Tuesday\" each starting phonetic spells \"CU...\".</p></li>\n</ul>\n\n<hr>\n\n<p>When I say doesn't reasonably, I mean if someone combined the above to get something ridiculous like \"4n7ipᷓhǚ​ɕK\" your word list would have to be ridiculous in size to match it.</p>\n\n<p>It should also be fairly obvious that someone probably will find a way to bypass your check no matter what you do.</p>\n\n<h1>Practicality vs Perfection</h1>\n\n<p>Given how widespread leet speak is you should handle that at a bare minimum. This is fairly easy, you just 'translate' from this alphabet. And perform the checks you're already doing.</p>\n\n<p>You should then probably use a 'similar check' to match \"sexx\" or \"afuck\". This is as duplicating a letter or missing a space is readable and easy.<br>\nThis check may result in problems as \"Scunthorpe\" could be understood as \"s cunt thorp e\" so would be split into two two known words and two extra letters, and then the similarity check my come back low enough to say it's a swearword.</p>\n\n<p>From here ZWSP and other unicode abuse probably are the next most common. And with things like <a href=\"https://pypi.org/project/deasciiify/\" rel=\"nofollow noreferrer\"><code>deasciiify</code></a> it's only getting easier.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T02:37:46.280", "Id": "430464", "Score": "1", "body": "Yeah, if catching explicit language was easy, you wouldn't have things like controversies over video game language filters getting over-aggressive and filtering out legitimate speech." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T16:43:18.703", "Id": "430614", "Score": "1", "body": "If you only check for prefixes and suffixes, you still have the Penistone and Cockfosters problems." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T00:07:26.967", "Id": "222428", "ParentId": "222339", "Score": "4" } }, { "body": "<blockquote>\n<pre><code>explicit_words = [\n #explicit words not shown \n]\n</code></pre>\n</blockquote>\n\n<p>Instead of embedding the word list within the program, you might want to treat it as <em>configuration</em>, and load it from a data file. The advantage of this is that it can allow the use of alternative configurations by command-line option (e.g. use a list of French obscenities for French-language lyrics).</p>\n\n<hr>\n\n<p>On efficiency: we're only interested in the <em>set</em> of words in the lyrics. Given that many songs have repeated lyrics, then it's probably worth reducing the lyrics to a set of words before comparing that set with the banned words (use <a href=\"https://docs.python.org/3/library/stdtypes.html#frozenset.intersection\" rel=\"nofollow noreferrer\"><code>&amp;</code></a> for set intersection), or <a href=\"https://docs.python.org/3/library/stdtypes.html#frozenset.isdisjoint\" rel=\"nofollow noreferrer\"><code>set.isdisjoint()</code></a> for a potentially faster test.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T13:59:58.513", "Id": "222461", "ParentId": "222339", "Score": "2" } }, { "body": "<p>The code feedback is already done wonderfully. I'd like to write about some pointers that might be important, apart from the leet speak:</p>\n\n<ul>\n<li>The word Phoque , is French for seal. There are numerous examples of words which are perfectly meaningful in some language but if pronounced in English, might be considered offensive. You might need to do a <a href=\"https://stackabuse.com/phonetic-similarity-of-words-a-vectorized-approach-in-python/\" rel=\"nofollow noreferrer\">phonetic similarity check</a></li>\n<li>The context can be taken into account. For example, the word 'blow' or 'mom' need not be offensive. It becomes offensive only when it is surrounded by contextual words that make it offensive, ('job', etc). In these cases, you might need to come up with an <a href=\"https://machinelearningmastery.com/how-to-score-probability-predictions-in-python/\" rel=\"nofollow noreferrer\">algorithm that outputs a probability score</a> and filter songs based on that. </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T06:14:59.690", "Id": "430667", "Score": "0", "body": "I'd like to take this up as a project. This has tremendous scope. For example, you can integrate this into the smartphones of kids . If youre interested, drop me a message" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T06:13:36.660", "Id": "222501", "ParentId": "222339", "Score": "1" } } ]
{ "AcceptedAnswerId": "222343", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T03:44:46.167", "Id": "222339", "Score": "18", "Tags": [ "python", "python-3.x", "strings", "file" ], "Title": "Explicit song lyrics checker" }
222339
<p>I am a newbie when it comes to Object Oriented Programming and I have read a lot of online articles and lessons so I want to try it out on my own. I've written a console app in C# and tried implementing Object Oriented Design and SOLID Principles. </p> <p>The console app checks if a person has an access to a certain floor. Also, The app is in its initial stage so right now the Elevator accomodates a single person.</p> <p>Although the app works. any feedback,comments, and suggestions will be greatly appreciated especially in terms of SOLID principles or OOP Design.</p> <p>here is the code below</p> <pre><code>class Program { static void Main(string[] args) { Person maintenanceEmployee = new MaintenanceEmployee(); Elevator elev = new Elevator(maintenanceEmployee); elev.GoToFloor(Floors.FourthFloor); Person guest = new Guest(); Elevator elev2 = new Elevator(guest); elev2.GoToFloor(Floors.SecondFloor); Person empfromthirdfloor = new EmployeeFromThirdFloor(); Elevator elev3 = new Elevator(empfromthirdfloor); elev2.GoToFloor(Floors.ThirdFloor); Console.ReadLine(); } } public enum Floors { FirstFloor = 1, SecondFloor = 2, ThirdFloor = 3, FourthFloor = 4, FifthFloor = 5 } public class Elevator { Person person; public Elevator(Person _person) { this.person = _person; } public void GoToFloor(Floors _floor) { if (person.HasAccess(_floor)) { Console.WriteLine("Elevating to " + _floor.ToString()); } else { Console.WriteLine("No Access to " + _floor.ToString()); } } } public abstract class Person { public Floors[] accessibleFloors; public bool HasAccess(Floors _floor) { foreach (Floors i in accessibleFloors) { if (_floor == i) { return true; } } return false; } } public class MaintenanceEmployee : Person { public Floors[] _accessibleFloors = { Floors.FirstFloor, Floors.SecondFloor, Floors.ThirdFloor, Floors.FourthFloor, Floors.FifthFloor }; public MaintenanceEmployee() { //Not sure if this is the best practice //Reason why I did it like this is because //I need to change the arrays of accessibleFloors //in the abstract class "Person" in order to run successfully base.accessibleFloors = _accessibleFloors; } } public class EmployeeFromThirdFloor : Person { public Floors[] _accessibleFloors = { Floors.ThirdFloor }; public EmployeeFromThirdFloor() { //Not sure if this is the best practice //Reason why I did it like this is because //I need to change the arrays of accessibleFloors //of the abstract class "Person" in order to run successfully base.accessibleFloors = _accessibleFloors; } } public class Guest : Person { public Floors[] _accessibleFloors = { Floors.SecondFloor }; public Guest() { //Not sure if this is the best practice //Reason why I did it like this is because //I need to change the arrays of accessibleFloors //of the abstract class "Person" in order to run successfully base.accessibleFloors = _accessibleFloors; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T09:43:59.817", "Id": "430263", "Score": "1", "body": "Is it safe to assume an elevator can at most contain 1 person?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T09:56:54.707", "Id": "430265", "Score": "1", "body": "Please add a description about what you application does. _Elevator Sample_ is too general." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T10:04:05.060", "Id": "430266", "Score": "0", "body": "@dfwze well for now this is just its initial design, at this stage I just like to know if the coding is on track in terms of OOP or SOLID." } ]
[ { "body": "<h3>Person + Derived Classes</h3>\n<ul>\n<li><code>accessibleFloors</code> is a breach of <em>Open–closed principle</em>. Anyone is able to modiy this collection.</li>\n<li><code>accessibleFloors</code> could be considered a breach of <em>Single responsibility principle</em>. Consider having a <code>Role</code> class and <code>Person</code> storing his <code>Roles</code> set. This way, you can also mitigate redundant code and remove the need of derived classes as <code>EmployeeFromThirdFloor</code>, <code>Guest</code> and <code>MaintenanceEmployee</code> (in this trivial example these classes are not required).</li>\n<li><code>accessibleFloors</code> can be <code>null</code>. The code is not able to handle this situation.</li>\n<li><code>HasAccess</code> is way to convoluted: <code>accessibleFloors.Contains(_floor);</code> would do it.</li>\n</ul>\n<blockquote>\n<pre><code>public abstract class Person\n{\n public Floors[] accessibleFloors;\n\n public bool HasAccess(Floors _floor)\n {\n foreach (Floors i in accessibleFloors)\n {\n if (_floor == i)\n {\n return true;\n }\n }\n return false;\n }\n}\n</code></pre>\n</blockquote>\n<p>We can create a class <code>Role</code>.</p>\n<pre><code>public class Role \n{\n public HashSet&lt;Floors&gt; AccessibleFloors { get; }\n\n public Role (HashSet&lt;Floors&gt; accessibleFloors) \n {\n AccessibleFloors = accessibleFloors \n ?? throw new ArgumentNullException(nameof(accessibleFloors));\n }\n\n public bool HasAccess(Floor floor)\n { \n return AccessibleFloors.Contains(floor);\n }\n\n // override equals and gethashcode ..\n}\n</code></pre>\n<p>We can refactor <code>Person</code>.</p>\n<pre><code>public class Person\n{\n public HashSet&lt;Role&gt; Roles { get; }\n\n public Person(HashSet roles) {\n Roles = roles ?? throw new ArgumentNullException(nameof(roles));\n }\n\n public bool HasAccess(Floors floor)\n {\n return Roles.Any(r =&gt; r.HasAccess(floor));\n }\n}\n</code></pre>\n<p>Because of <em>Inheritance</em>, the derived classes do not require to create their own instance variable <code>_accessibleFloors</code>.</p>\n<blockquote>\n<p><code>base.accessibleFloors = _accessibleFloors;</code></p>\n</blockquote>\n<hr />\n<h3>Elevator</h3>\n<ul>\n<li>There is tight-coupling between an <code>Elevator</code> and a <code>Person</code>. You force the elevator to exist only with a person. What about an empty elevator.</li>\n<li><code>GoToFloor</code> is not usable code. Consider returning a <code>Boolean</code> and putting the <code>Console.WriteLine</code> in the calling code.</li>\n<li>The code cannot handle when <code>Person</code> is <code>null</code>.</li>\n</ul>\n<blockquote>\n<pre><code>public class Elevator\n{\n Person person;\n public Elevator(Person _person)\n {\n this.person = _person;\n }\n\n public void GoToFloor(Floors _floor)\n {\n if (person.HasAccess(_floor))\n {\n Console.WriteLine(&quot;Elevating to &quot; + _floor.ToString());\n }\n else\n {\n Console.WriteLine(&quot;No Access to &quot; + _floor.ToString());\n }\n }\n}\n</code></pre>\n</blockquote>\n<p><code>Elevator</code> could be refactored as follows.</p>\n<pre><code>public class Elevator\n{\n public Person Person { get; private set; }\n\n public bool IsFull =&gt; Person != null;\n public bool IsEmpty =&gt; Person == null;\n\n public bool Enter(Person person)\n {\n if (person == null) throw new ArgumentNullException(nameof(person));\n if (IsFull) return false;\n Person = person;\n return true;\n }\n\n public bool Exit(Floors floor)\n {\n if (IsEmpty) return false;\n if (!Person.HasAccess(floor)) return false;\n Person = null;\n return true;\n }\n}\n</code></pre>\n<hr />\n<h3>Program</h3>\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n var guestRoles = new HashSet&lt;Role&gt; { \n new Role(new HashSet&lt;Floors&gt; { Floors.FirstFloor }) \n };\n var guest = new Person(guestRoles);\n var elevator = new Elevator();\n \n if (elevator.Enter(guest)) \n {\n Console.WriteLine(&quot;guest has entered elevator&quot;);\n }\n else \n {\n Console.WriteLine(&quot;guest cannot enter elevator: elevator is full&quot;);\n }\n\n if (elevator.Exit(Floors.FirstFloor)) \n {\n Console.WriteLine(&quot;guest has exited elevator at FirstFloor&quot;);\n }\n else \n {\n Console.WriteLine(&quot;guest cannot exit elevator at FirstFloor: access is denied&quot;);\n }\n\n Console.ReadLine();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T11:33:43.060", "Id": "430270", "Score": "1", "body": "wow, I appreciate the remodelling and refactoring of the code. Thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T10:43:11.640", "Id": "222347", "ParentId": "222345", "Score": "3" } }, { "body": "<p>If I may add a single consideration to dfhwze's thorough answer:</p>\n\n<p>Having an enum defining floors is OK for a building with 5 floors, but would be overwhelming if we are talking <a href=\"https://en.wikipedia.org/wiki/Burj_Khalifa\" rel=\"nofollow noreferrer\">Burj Khalifa</a> with its 163 floors. Besides that it is a rather rigid concept having a predefined number of floors - supposed you want to reuse your object model for other buildings.</p>\n\n<p>Therefore I would create a <code>Floor</code> class too:</p>\n\n<pre><code>public class Floor\n{\n private Floor(string name, int index)\n {\n Name = name;\n Index = index;\n }\n\n public string Name { get; }\n public int Index { get; }\n\n public static IEnumerable&lt;Floor&gt; CreateFloors(params string[] names)\n {\n return names.Select((n, i) =&gt; new Floor(n, i));\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T12:37:38.913", "Id": "222351", "ParentId": "222345", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T09:11:17.273", "Id": "222345", "Score": "4", "Tags": [ "c#", "beginner", "object-oriented" ], "Title": "Object-oriented design implementation of an Elevator" }
222345
<p>I have a "back to top"-button on the page, It should be visible after the user has scrolled a certain amount<sup>*</sup>.</p> <p>This means I have to add or remove a class <code>active</code> every now and then.</p> <p>I have two solutions:</p> <ol> <li>Update the class on every scroll.</li> <li>Test whether the class is set/ not et and then test, whether it is necessary to interact.</li> </ol> <p>The setup:</p> <pre><code>this.button = document.querySelector('.some-class'); window.addEventListener('scroll', event =&gt; { this.onScroll(event); }); </code></pre> <p>The long version, which does add or remove the class only if needed:</p> <pre><code>onScroll(event) { if ( !this.button.classList.contains('active') &amp;&amp; (document.body.scrollTop &gt; 100 || document.documentElement.scrollTop &gt; 100) ) { this.button.classList.add('active'); } if ( this.button.classList.contains('active') &amp;&amp; (document.body.scrollTop &lt;= 100 || document.documentElement.scrollTop &lt;= 100) ) { this.button.classList.remove('is-active'); } } </code></pre> <p>The alternativ short version, that adds or removes the class everytime:</p> <pre><code>onScroll(event) { if (document.body.scrollTop &gt; 100 || document.documentElement.scrollTop &gt; 100) { this.button.classList.add('active'); } else { this.button.classList.remove('active'); } } </code></pre> <p>My questions are:</p> <ul> <li>Does the longer version have a better performance?</li> <li>Does the browser optimize it itself – i.e. in the short version if the class is already present, it doesn't repaint?</li> </ul> <p><sub><sup>*</sup> For simplicity this value is hard-coded here. It's a variable in the implemented version.</sub></p>
[]
[ { "body": "<blockquote>\n <p>Does the longer version have a better performance?</p>\n</blockquote>\n\n<p>No, the longer version has two different <code>if</code> conditions and you're recalculating the scroll area twice (i.e.: <code>document.body.scrollTop &gt; 100 || document.documentElement.scrollTop &gt; 100</code> and <code>document.body.scrollTop &lt;= 100 || document.documentElement.scrollTop &lt;= 100</code>)</p>\n\n<hr>\n\n<blockquote>\n <p>Does the browser optimize it itself – i.e. in the short version if the class is already present, it doesn't repaint?</p>\n</blockquote>\n\n<p>Yes, if the class name already exists it'll simply be ignored.</p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Methods\" rel=\"nofollow noreferrer\">classList MDN Documentation</a>:</p>\n\n<blockquote>\n <p>add( String [, String [, ...]] )</p>\n \n <p>Adds the specified class values. If these classes already exist in the element's class attribute they are <strong>ignored</strong>.</p>\n</blockquote>\n\n<hr>\n\n<p>Handling the scroll event <em>can</em> be performant heavy if you have a complex handler as the scroll event will be <em>continuously</em> fired during a scroll.</p>\n\n<p>If you wish to optimize your scroll event handler, I would <em>highly</em> recommend using <code>setTimeout</code>. This allows your script to <strong>ONLY</strong> be called once the scroll has ended and skips doing your \"heavy\" condition checking for every scroll tick.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let setTimeoutId = null;\nwindow.addEventListener('scroll', event =&gt; {\n //clear a previously pending timeout\n clearTimeout(setTimeoutId);\n //create a new timeout that will be launched in 400ms\n setTimeoutId = setTimeout(()=&gt;onScroll(event), 100);\n});\n\nfunction onScroll(event){\n console.log(\"On scroll called\");\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n height: 2000px;\n background-color: lightblue;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-22T09:50:59.747", "Id": "431292", "Score": "1", "body": "Thank you for pointing me into the right direction. For the last part: We already use a `pipe|throttler|debouncer` in our production code (depending on the project's framework). I just didn't wanted to bloat the question." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T11:18:26.087", "Id": "222348", "ParentId": "222346", "Score": "2" } } ]
{ "AcceptedAnswerId": "222348", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T10:25:42.763", "Id": "222346", "Score": "4", "Tags": [ "javascript", "html", "css", "comparative-review" ], "Title": "Showing a \"back-to-top\"-button after scrolling a certain amount" }
222346
<p>I am relatively new to C programming and I am currently working through the CS50 EDX course. The problem I have solved below is for week 1 (credit).</p> <p>Any suggestions on how to improve this code to further my learning would be most appreciated. I feel like my solution is very clunky although it does the job!</p> <pre><code>#include &lt;cs50.h&gt; #include &lt;stdio.h&gt; #include &lt;math.h&gt; int main(void) { long number = get_long("Number: "); // get the individual intergers of number // *2 odd digits int i1 = ((number / 1000000000000000) % 10); int t1 = i1 * 2; int i2 = ((number / 100000000000000) % 10); int i3 = ((number / 10000000000000) % 10); int t3 = i3 * 2; int i4 = ((number / 1000000000000) % 10); int i5 = ((number / 100000000000) % 10); int t5 = i5 * 2; int i6 = ((number / 10000000000) % 10); int i7 = ((number / 1000000000) % 10); int t7 = i7 * 2; int i8 = ((number / 100000000) % 10); int i9 = ((number / 10000000) % 10); int t9 = i9 * 2; int i10 = ((number / 1000000) % 10); int i11 = ((number / 100000) % 10); int t11 = i11 * 2; int i12 = ((number / 10000) % 10); int i13 = ((number / 1000) % 10); int t13 = i13 * 2; int i14 = ((number / 100) % 10); int i15 = ((number / 10) % 10); int t15 = i15 * 2; int i16 = (number % 10); // Luhns Alg // calculate sum of variable digits if &gt; 9 if (t1&gt;9) {t1 = t1 - 9;} if (t3&gt;9) {t3 = t3 - 9;} if (t5&gt;9) {t5 = t5 - 9;} if (t7&gt;9) {t7 = t7 - 9;} if (t9&gt;9) {t9 = t9 - 9;} if (t11&gt;9) {t11 = t11 - 9;} if (t13&gt;9) {t13 = t13 - 9;} if (t15&gt;9) {t15 = t15 - 9;} // check lunghs algo = true (0) // print card type int sum = (t1+t3+t5+t7+t9+t11+t13+t15+i2+i4+i6+i8+i10+i12+i14+i16); int check = (sum % 10); if (check != 0) printf("INVALID\n"); else { // check type of card if(i1 == 0 &amp;&amp; i2 == 3 &amp;&amp; i3 == 4) { printf("AMEX\n"); } else if(i1 == 0 &amp;&amp; i2 == 3 &amp;&amp; i3 == 7) { printf("AMEX\n"); } else if (i1 == 5 &amp;&amp; (i2 == 1 || i2 == 2 || i2 == 3 || i2 == 4 || i2 == 5)) { printf("MASTERCARD\n"); } else if (i1 == 4) { printf("VISA\n"); } else printf("INVALID\n"); } } </code></pre> <p>The code currently outputs the correct results below.</p> <p>378282246310005 = AMEX<br> 5555555555554444 = MASTERCARD<br> 5105105105105100 = MASTERCARD<br> 4111111111111111 = VISA<br> 5673598276138003 = INVALID<br> 4062901840 = INVALID</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T13:10:46.317", "Id": "430277", "Score": "5", "body": "Have loops or functions been introduced yet?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T13:13:29.320", "Id": "430278", "Score": "0", "body": "Loops have and some basic functions like checking for a positive integer. I did think about looping through variables which I saw required vectors or arrays but haven't got to that yet so don't really understand." } ]
[ { "body": "<p>It might be better to treat the credit card number as a string. In the C programming language a string is a null terminated array of type <code>char</code> or character. This would remove all the division in the program to get each character. It would also allow the program to detect if any non-numeric characters were entered. </p>\n\n<p>To get the actual numeric value of a character you would subtract <code>'0'</code> from the numeric character. For a single character this would always give you a value between zero and nine.</p>\n\n<p><strong>Variable Names</strong><br>\nHaving variables <code>i1</code> through <code>i16</code> is a very good indication that <code>i</code> should be an array, this is also true of <code>t</code>.</p>\n\n<p>Having single character variable names is generally frowned upon except for loop control values. A single character really doesn't tell anyone reading or modifying the code what the variable really is or does. It isn't really clear in the program what <code>i</code> or <code>t</code> represents. While <code>number</code> is longer, it might be better if it was <code>credit_card_number</code>.</p>\n\n<p><strong>Basic Principles When Writing Code</strong><br>\nOne of the earliest principles all programmers learn is <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself</a>, usually shortened to DRY code. Basically anytime you have code that repeats it would be better to put it into a loop or a function where the code is reused.</p>\n\n<p>One example of repeating code from the question is :</p>\n\n<pre><code> if (tN &gt; 9)\n {\n tN = tN - 9;\n }\n</code></pre>\n\n<p>This code can be made into a function:</p>\n\n<pre><code>int adjust_t_value(int tN)\n{\n if (tN &gt; 9)\n {\n return tN - 9;\n }\n else\n {\n return tN;\n }\n}\n</code></pre>\n\n<p>If the variable <code>t</code> was an array, then code in the program could be reduced to </p>\n\n<pre><code> for (int t_count = 0; t_count &lt; N; t_count++)\n {\n t[t_count] = adjust_t_value(t[t_count]);\n }\n</code></pre>\n\n<p>There is a second form of the if statement that could also make the code shorter, it is generally covered in the later part of any C programming course</p>\n\n<pre><code> tN = (tN &gt; 9)? tN - 9 : tN;\n</code></pre>\n\n<p>This single statement is equivalent to the function above.</p>\n\n<p>A second example of repeating code is the division to reduce each digit in the credit card number to a single number, this could also be put into a loop. The divisor could be reduced in each iteration of the loop if the algorithm sticks with using numbers.</p>\n\n<p>A second principle that should be taught early but is part of more complex programming is the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> which states that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated within the function, module or class. This reduces the size of functions which allows functions to be more readable, maintainable and easier to debug. This would mean breaking the <code>main()</code> function into two or three sub functions to reduce the complexity of main.</p>\n\n<p><strong>Use Vertical Spacing to Make the Code More Readable</strong><br>\nThe code in the question has the <code>if (tN &gt; 9)</code> on only two lines, it might be more readable if it was 4 lines as shown above.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T19:44:26.343", "Id": "430309", "Score": "0", "body": "Please can you review my update answer below?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T22:27:27.037", "Id": "430321", "Score": "0", "body": "There are (or at least there was, not sure if it's still the case nowadays) cards with 19-digit PANs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T22:35:00.010", "Id": "430322", "Score": "1", "body": "@jcaron Are/were they in Europe or Asia?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T15:35:01.907", "Id": "430415", "Score": "1", "body": "@pacmaninbw According to [Wikipedia](https://en.wikipedia.org/wiki/Payment_card_number) payment card numbers can range from 10 (formerly 8) to 19 digits, though in practice they actually range from 12 to 19. Examples include Maestro, China UnionPay, Diners Club, Discover, and JCB." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T15:39:20.913", "Id": "430416", "Score": "0", "body": "@jcaron Thank you, I have removed the suggest to check for 15 or 16 digits." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T15:12:17.587", "Id": "430583", "Score": "2", "body": "A string is absolutely the correct approach - after all, `long` (or even `unsigned long`) isn't necessarily large enough to represent decimals of the size required (9 digits are okay, but more than that is platform-dependent)." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T16:20:50.057", "Id": "222361", "ParentId": "222349", "Score": "11" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T12:06:07.703", "Id": "222349", "Score": "11", "Tags": [ "beginner", "c", "parsing", "checksum" ], "Title": "Credit card validation in C" }
222349
<p>I want to hash an array of strings into one hash as shown on scheme on the image below. But I do not want to implement some class based Merkle tree. It's just a simple function. Is this a good implementation or are there any possible improvements?</p> <p><a href="https://i.stack.imgur.com/OW5LL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OW5LL.png" alt="enter image description here"></a></p> <pre><code>public static String hashStrings(@NotNull String [] strs) { if (strs.length == 1) return hashString(strs[0]); List&lt;String&gt; hashes = new ArrayList&lt;&gt;(); for (int i = 0; i &lt; strs.length; i++) { hashes.add(hashString(strs[i])); } while(hashes.size() &gt; 1) { int currentSize = hashes.size(); int nextSize = currentSize % 2 == 0 ? currentSize / 2 : (currentSize + 1) / 2; for (int i = 0; i &lt; currentSize - 1; i += 2) { hashes.set(i / 2, hashString(hashes.get(i) + hashes.get(i + 1))); } if (currentSize % 2 == 1) { hashes.set(nextSize - 1, hashString(hashes.get(currentSize - 1))); } hashes = hashes.subList(0, nextSize); } return hashes.get(0); } </code></pre>
[]
[ { "body": "<p>In my opinion this statement is quite complicated to read, compared to what you want achieve:</p>\n\n<pre><code>int nextSize = currentSize % 2 == 0 ? currentSize / 2 : (currentSize + 1) / 2;\n</code></pre>\n\n<p>You could consider using some brackets:</p>\n\n<pre><code>int nextSize = (currentSize % 2 == 0) ? (currentSize / 2) : ((currentSize + 1) / 2);\n</code></pre>\n\n<p>Or just use <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#ceil(double)\" rel=\"nofollow noreferrer\">Math.ceil()</a>:</p>\n\n<pre><code>int nextSize = (int) Math.ceil(currentSize / 2.0))\n</code></pre>\n\n<p>Furthermore you are computing <code>hashes.size()</code> twice per loop:</p>\n\n<pre><code>while(hashes.size() &gt; 1)\n{\n int currentSize = hashes.size();\n // ...\n</code></pre>\n\n<p>you could write:</p>\n\n<pre><code>int currentSize = hashes.size();\nwhile(currentSize &gt; 1)\n{\n currentSize = hashes.size();\n // ....\n</code></pre>\n\n<p>instead.</p>\n\n<p>Other than that your code looks fine to me, besides <code>strs</code> is not the best name for a parameter. You could rename it to improve readability and usability.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T12:13:26.830", "Id": "222399", "ParentId": "222353", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T13:46:16.707", "Id": "222353", "Score": "3", "Tags": [ "java", "hash-map", "hashcode" ], "Title": "Hashing array of strings as Merkle tree in one function" }
222353
<p>Here is a practice exercise — <a href="https://automatetheboringstuff.com/chapter5/" rel="noreferrer"><em>Fantasy Game Inventory</em></a> <span class="math-container">\$-\$</span></p> <blockquote> <p><em>You are creating a fantasy video game. The data structure to model the player’s inventory will be a dictionary where the keys are string values describing the item in the inventory and the value is an integer value detailing how many of that item the player has. For example, the dictionary value <code>{'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}</code> means the player has 1 rope, 6 torches, 42 gold coins, and so on.</em></p> <p><em>Write a function named <code>display_inventory()</code> that would take any possible “inventory” and display it like the following -</em></p> <pre class="lang-none prettyprint-override"><code>Inventory: 12 arrows 42 gold coins 1 rope 6 torches 1 dagger Total number of items: 62 </code></pre> <p><em>Hint - You can use a for loop to loop through all the keys in a dictionary.</em></p> </blockquote> <p>I have written the following code. Any feedback is highly appreciated.</p> <pre><code>stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} def display_inventory(inventory): total_items = 0 print ("Inventory:") for item in inventory: print(str(inventory[item]) + ' ' + item) total_items += inventory[item] print("Total number of items: " + str(total_items)) if __name__ == '__main__': display_inventory(stuff) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T14:38:24.007", "Id": "430289", "Score": "9", "body": "The interesting part of this task is to generate the correct plural forms from the singulars. You completely missed this one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T04:13:00.713", "Id": "430349", "Score": "0", "body": "@RolandIllig - Please check my answer below which covers your suggestion. Thank you for pointing this out." } ]
[ { "body": "<p>I am suggesting to use <a href=\"https://realpython.com/python-f-strings/\" rel=\"noreferrer\">fstrings</a> and the dictionary <code>items()</code> method.</p>\n\n<p>The</p>\n\n<pre><code>print(f'{value} {key}')\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>print(str(inventory[item]) + ' ' + item)\n</code></pre>\n\n<p>is more neatly:</p>\n\n<pre><code>def display_inventory(inventory):\n total_items = 0 \n print (\"Inventory:\")\n\n for key, value in inventory.items():\n print(f'{value} {key}')\n total_items += value\n\n print(f'Total number of items: {total_items}')\n</code></pre>\n\n<p>Also, you can just calculate the total number in the needed place by the <code>sum()</code> function and the dictionary <code>values()</code> method. Then, you are not needing the <code>total_items</code> variable.</p>\n\n<pre><code>def display_inventory(inventory):\n print (\"Inventory:\")\n\n for key, value in inventory.items():\n print(f'{value} {key}')\n\n print(f'Total number of items: {sum(inventory.values())}')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T15:48:56.643", "Id": "222360", "ParentId": "222354", "Score": "12" } }, { "body": "<p>As mentioned in a comment by <a href=\"https://codereview.stackexchange.com/questions/222354/fantasy-game-inventory-ch-5-automate-the-boring-stuff#comment430289_222354\">Roland Illig</a>, I missed the interesting part of generating the correct plural forms from the singulars.</p>\n\n<p>Here's a module which supports Python 3 - <a href=\"https://pypi.python.org/pypi/inflect\" rel=\"noreferrer\">Inflect</a>.</p>\n\n<pre><code># Initialization\nimport inflect\np = inflect.engine()\n</code></pre>\n\n<p><strong>Examples -</strong></p>\n\n<pre><code>word = \"torch\"\nprint(f\"The plural of '{word}' is '{p.plural(word)}'.\")\n</code></pre>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; The plural of 'torch' is 'torches'.\n</code></pre>\n\n<hr>\n\n<pre><code>word = \"torches\"\nprint(f\"The singular of '{word}' is '{p.singular_noun(word)}'.\")\n</code></pre>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; The singular of 'torches' is 'torch'.\n</code></pre>\n\n<hr>\n\n<p>My updated code, expanding on <a href=\"https://codereview.stackexchange.com/questions/222354/fantasy-game-inventory-ch-5-automate-the-boring-stuff/222360#222360\">MiniMax's</a> answer, is:</p>\n\n<pre><code>import inflect\np = inflect.engine()\n\nstuff = {'rope': 0, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}\n\ndef display_inventory(inventory):\n\n print (\"Inventory:\")\n for key, value in inventory.items():\n\n if value != 1:\n key = p.plural(key)\n\n print(f'{value} {key}')\n print(f'Total number of items: {sum(inventory.values())}')\n\nif __name__ == '__main__':\n display_inventory(stuff)\n</code></pre>\n\n<p>This will give the following output -</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Inventory:\n0 ropes\n6 torches\n42 gold coins\n1 dagger\n12 arrows\nTotal number of items: 61\n</code></pre>\n\n<p><strong>OR</strong></p>\n\n<p>In cases like this -</p>\n\n<pre><code>stuff = {'ropes': 1, 'torches': 1, 'gold coin': 42, 'daggers': 1, 'arrow': 0}\n</code></pre>\n\n<p>where -</p>\n\n<pre><code>{'ropes': 1, 'torches': 1, 'daggers': 1}\n</code></pre>\n\n<p>you will need to generate the correct singular forms from the plurals.</p>\n\n<p>Therefore, expanding more on the previous code, I get -</p>\n\n<pre><code>import inflect\np = inflect.engine()\n\nstuff = stuff = {'ropes': 1, 'torches': 1, 'gold coin': 42, 'daggers': 1, 'arrow': 0}\n\ndef display_inventory(inventory):\n print (\"Inventory:\")\n for key, value in inventory.items():\n\n if value != 1:\n key = p.plural(key)\n else:\n key = p.singular_noun(key)\n\n print(f'{value} {key}')\n print(f'Total number of items: {sum(inventory.values())}')\n\nif __name__ == '__main__':\n display_inventory(stuff)\n</code></pre>\n\n<p>This will give the following output:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Inventory:\n1 rope\n1 torch\n42 gold coins\n1 dagger\n0 arrows\nTotal number of items: 45\n</code></pre>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T09:42:32.857", "Id": "430365", "Score": "0", "body": "Yes, that works. An easier way would probably be using a ternary: `key = p.plural(key) if value > 1 else p.singular_noun(key)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T11:07:02.667", "Id": "430371", "Score": "1", "body": "@Graipher The documentation of the inflict package suggests `p.plural(key, value)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T11:16:11.693", "Id": "430372", "Score": "0", "body": "@RolandIllig Might be, I don't know the packet. I just used the commands as they are in the post." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T18:03:18.063", "Id": "222365", "ParentId": "222354", "Score": "8" } }, { "body": "<p>I got stuck in this asnwer and decided to convert the dictionary into a list, resulting in the following code:</p>\n\n<pre><code>stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}\n\nkeys = list(stuff.keys())\nvalues = list(stuff.values())\n\ndef displayInventory(q):\n print(\"Inventory:\")\n item_total = 0\n for a in range(len(keys)):\n item_total = int(item_total) + int(values[a])\n print (str(values[a]) +' '+ str(keys[a]))\n a = a + 1\n print(\"Total number of items: \" + str(item_total))\n\ndisplayInventory(stuff)\n</code></pre>\n\n<p>After reviewing comments this is the new code i got:</p>\n\n<pre><code>stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}\n\ndef displayInventory(inventory):\n print(\"Inventory:\") \n for key, value in inventory.items():\n print(value, key)\n print('Total number of items: ' + str((sum(inventory.values()))))\n\ndisplayInventory(stuff)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-10T20:12:01.353", "Id": "449130", "Score": "2", "body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read [Why are alternative solutions not welcome?](https://codereview.meta.stackexchange.com/a/8404/120114)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-10T19:44:51.323", "Id": "230503", "ParentId": "222354", "Score": "1" } } ]
{ "AcceptedAnswerId": "222360", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T14:01:30.587", "Id": "222354", "Score": "8", "Tags": [ "python", "performance", "python-3.x", "formatting", "role-playing-game" ], "Title": "Fantasy game inventory — Ch. 5 Automate the Boring Stuff" }
222354
<p>I have a <a href="https://github.com/boostorg/math/pull/107" rel="noreferrer">PR</a> implementing Ooura and Mori's method for continuous Fourier integrals. I used it <a href="https://scicomp.stackexchange.com/a/32799/4392">here</a> to compute an oscillatory integral that Mathematica got completely wrong, and then I thought "well maybe this method is pretty good!" and figured I'd finish it after letting it languish for over a year.</p> <p>Here are a few concerns:</p> <ul> <li><p>I <em>agonized</em> over computing the nodes and weights accurately. But in the end, I had to precompute the nodes and weights in higher accuracy and cast them back down. Is there any way to avoid this that I'm missing? (If I don't do this, then the error goes down after a few levels, then starts <em>increasing</em>. Use <code>-DBOOST_MATH_INSTRUMENT_OOURA</code> to see it if you're interested.)</p></li> <li><p>There is also some code duplication that I can't really figure out how to get rid of. For example, for the sine integral, <code>f(0) = inf</code> is allowed, but for the cosine integral, <code>f(0)</code> must be finite. So you have this very small difference that disallows extracting the generic code into a single location. But maybe I'm just not being creative enough here.</p></li> <li><p>I'm also interested in whether the comments are well-written and informative. I couldn't understand my comments from when I stopped working on this last year, and now I'm worried I won't be able to understand my current comments next year!</p></li> </ul> <p>So here's the code:</p> <pre class="lang-cpp prettyprint-override"><code>// Copyright Nick Thompson, 2019 // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) /* * References: * Ooura, Takuya, and Masatake Mori. "A robust double exponential formula for Fourier-type integrals." Journal of computational and applied mathematics 112.1-2 (1999): 229-241. * http://www.kurims.kyoto-u.ac.jp/~ooura/intde.html */ #ifndef BOOST_MATH_QUADRATURE_OOURA_FOURIER_INTEGRALS_HPP #define BOOST_MATH_QUADRATURE_OOURA_FOURIER_INTEGRALS_HPP #include &lt;memory&gt; #include &lt;boost/math/quadrature/detail/ooura_fourier_integrals_detail.hpp&gt; namespace boost { namespace math { namespace quadrature { template&lt;class Real&gt; class ooura_fourier_sin { public: ooura_fourier_sin(const Real relative_error_tolerance = tools::root_epsilon&lt;Real&gt;(), size_t levels = sizeof(Real)) : impl_(std::make_shared&lt;detail::ooura_fourier_sin_detail&lt;Real&gt;&gt;(relative_error_tolerance, levels)) {} template&lt;class F&gt; std::pair&lt;Real, Real&gt; integrate(F const &amp; f, Real omega) { return impl_-&gt;integrate(f, omega); } std::vector&lt;std::vector&lt;Real&gt;&gt; const &amp; big_nodes() const { return impl_-&gt;big_nodes(); } std::vector&lt;std::vector&lt;Real&gt;&gt; const &amp; weights_for_big_nodes() const { return impl_-&gt;weights_for_big_nodes(); } std::vector&lt;std::vector&lt;Real&gt;&gt; const &amp; little_nodes() const { return impl_-&gt;little_nodes(); } std::vector&lt;std::vector&lt;Real&gt;&gt; const &amp; weights_for_little_nodes() const { return impl_-&gt;weights_for_little_nodes(); } private: std::shared_ptr&lt;detail::ooura_fourier_sin_detail&lt;Real&gt;&gt; impl_; }; template&lt;class Real&gt; class ooura_fourier_cos { public: ooura_fourier_cos(const Real relative_error_tolerance = tools::root_epsilon&lt;Real&gt;(), size_t levels = sizeof(Real)) : impl_(std::make_shared&lt;detail::ooura_fourier_cos_detail&lt;Real&gt;&gt;(relative_error_tolerance, levels)) {} template&lt;class F&gt; std::pair&lt;Real, Real&gt; integrate(F const &amp; f, Real omega) { return impl_-&gt;integrate(f, omega); } private: std::shared_ptr&lt;detail::ooura_fourier_cos_detail&lt;Real&gt;&gt; impl_; }; }}} #endif </code></pre> <p>And the detail (which contains the real meat):</p> <pre class="lang-cpp prettyprint-override"><code>// Copyright Nick Thompson, 2019 // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_MATH_QUADRATURE_DETAIL_OOURA_FOURIER_INTEGRALS_DETAIL_HPP #define BOOST_MATH_QUADRATURE_DETAIL_OOURA_FOURIER_INTEGRALS_DETAIL_HPP #include &lt;utility&gt; // for std::pair. #include &lt;mutex&gt; #include &lt;atomic&gt; #include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;boost/math/special_functions/expm1.hpp&gt; #include &lt;boost/math/special_functions/sin_pi.hpp&gt; #include &lt;boost/math/special_functions/cos_pi.hpp&gt; #include &lt;boost/math/constants/constants.hpp&gt; namespace boost { namespace math { namespace quadrature { namespace detail { // Ooura and Mori, A robust double exponential formula for Fourier-type integrals, // eta is the argument to the exponential in equation 3.3: template&lt;class Real&gt; std::pair&lt;Real, Real&gt; ooura_eta(Real x, Real alpha) { using std::expm1; using std::exp; using std::abs; Real expx = exp(x); Real eta_prime = 2 + alpha/expx + expx/4; Real eta; // This is the fast branch: if (abs(x) &gt; 0.125) { eta = 2*x - alpha*(1/expx - 1) + (expx - 1)/4; } else {// this is the slow branch using expm1 for small x: eta = 2*x - alpha*expm1(-x) + expm1(x)/4; } return {eta, eta_prime}; } // Ooura and Mori, A robust double exponential formula for Fourier-type integrals, // equation 3.6: template&lt;class Real&gt; Real calculate_ooura_alpha(Real h) { using boost::math::constants::pi; using std::log1p; using std::sqrt; Real x = sqrt(16 + 4*log1p(pi&lt;Real&gt;()/h)/h); return 1/x; } template&lt;class Real&gt; std::pair&lt;Real, Real&gt; ooura_sin_node_and_weight(long n, Real h, Real alpha) { using std::expm1; using std::exp; using std::abs; using boost::math::constants::pi; using std::isnan; if (n == 0) { // Equation 44 of https://arxiv.org/pdf/0911.4796.pdf Real eta_prime_0 = Real(2) + alpha + Real(1)/Real(4); Real node = pi&lt;Real&gt;()/(eta_prime_0*h); Real weight = pi&lt;Real&gt;()*boost::math::sin_pi(1/(eta_prime_0*h)); Real eta_dbl_prime = -alpha + Real(1)/Real(4); Real phi_prime_0 = (1 - eta_dbl_prime/(eta_prime_0*eta_prime_0))/2; weight *= phi_prime_0; return {node, weight}; } Real x = n*h; auto p = ooura_eta(x, alpha); auto eta = p.first; auto eta_prime = p.second; Real expm1_meta = expm1(-eta); Real exp_meta = exp(-eta); Real node = -n*pi&lt;Real&gt;()/expm1_meta; // I have verified that this is not a significant source of inaccuracy in the weight computation: Real phi_prime = -(expm1_meta + x*exp_meta*eta_prime)/(expm1_meta*expm1_meta); // The main source of inaccuracy is in computation of sin_pi. // But I've agonized over this, and I think it's as good as it can get: Real s = pi&lt;Real&gt;(); Real arg; if(eta &gt; 1) { arg = n/( 1/exp_meta - 1 ); s *= boost::math::sin_pi(arg); if (n&amp;1) { s *= -1; } } else if (eta &lt; -1) { arg = n/(1-exp_meta); s *= boost::math::sin_pi(arg); } else { arg = -n*exp_meta/expm1_meta; s *= boost::math::sin_pi(arg); if (n&amp;1) { s *= -1; } } Real weight = s*phi_prime; return {node, weight}; } #ifdef BOOST_MATH_INSTRUMENT_OOURA template&lt;class Real&gt; void print_ooura_estimate(size_t i, Real I0, Real I1, Real omega) { using std::abs; std::cout &lt;&lt; std::defaultfloat &lt;&lt; std::setprecision(std::numeric_limits&lt;Real&gt;::digits10) &lt;&lt; std::fixed; std::cout &lt;&lt; "h = " &lt;&lt; Real(1)/Real(1&lt;&lt;i) &lt;&lt; ", I_h = " &lt;&lt; I0/omega &lt;&lt; " = " &lt;&lt; std::hexfloat &lt;&lt; I0/omega &lt;&lt; ", absolute error est = " &lt;&lt; std::defaultfloat &lt;&lt; std::scientific &lt;&lt; abs(I0-I1) &lt;&lt; "\n"; } #endif template&lt;class Real&gt; std::pair&lt;Real, Real&gt; ooura_cos_node_and_weight(long n, Real h, Real alpha) { using std::expm1; using std::exp; using std::abs; using boost::math::constants::pi; Real x = h*(n-Real(1)/Real(2)); auto p = ooura_eta(x, alpha); auto eta = p.first; auto eta_prime = p.second; Real expm1_meta = expm1(-eta); Real exp_meta = exp(-eta); Real node = pi&lt;Real&gt;()*(Real(1)/Real(2)-n)/expm1_meta; Real phi_prime = -(expm1_meta + x*exp_meta*eta_prime)/(expm1_meta*expm1_meta); // Equation 4.6 of A robust double exponential formula for Fourier-type integrals Real s = pi&lt;Real&gt;(); Real arg; if (eta &lt; -1) { arg = -(n-Real(1)/Real(2))/expm1_meta; s *= boost::math::cos_pi(arg); } else { arg = -(n-Real(1)/Real(2))*exp_meta/expm1_meta; s *= boost::math::sin_pi(arg); if (n&amp;1) { s *= -1; } } Real weight = s*phi_prime; return {node, weight}; } template&lt;class Real&gt; class ooura_fourier_sin_detail { public: ooura_fourier_sin_detail(const Real relative_error_goal, size_t levels) { if (relative_error_goal &lt;= std::numeric_limits&lt;Real&gt;::epsilon()/2) { throw std::domain_error("The relative error goal cannot be smaller than the unit roundoff."); } using std::abs; requested_levels_ = levels; starting_level_ = 0; rel_err_goal_ = relative_error_goal; big_nodes_.reserve(levels); bweights_.reserve(levels); little_nodes_.reserve(levels); lweights_.reserve(levels); for (size_t i = 0; i &lt; levels; ++i) { if (std::is_same&lt;Real, float&gt;::value) { add_level&lt;double&gt;(i); } else if (std::is_same&lt;Real, double&gt;::value) { add_level&lt;long double&gt;(i); } else { add_level&lt;Real&gt;(i); } } } std::vector&lt;std::vector&lt;Real&gt;&gt; const &amp; big_nodes() const { return big_nodes_; } std::vector&lt;std::vector&lt;Real&gt;&gt; const &amp; weights_for_big_nodes() const { return bweights_; } std::vector&lt;std::vector&lt;Real&gt;&gt; const &amp; little_nodes() const { return little_nodes_; } std::vector&lt;std::vector&lt;Real&gt;&gt; const &amp; weights_for_little_nodes() const { return lweights_; } template&lt;class F&gt; std::pair&lt;Real,Real&gt; integrate(F const &amp; f, Real omega) { using std::abs; using std::max; using boost::math::constants::pi; if (omega == 0) { return {Real(0), Real(0)}; } if (omega &lt; 0) { auto p = this-&gt;integrate(f, -omega); return {-p.first, p.second}; } Real I1 = std::numeric_limits&lt;Real&gt;::quiet_NaN(); Real relative_error_estimate = std::numeric_limits&lt;Real&gt;::quiet_NaN(); // As we compute integrals, we learn about their structure. // Assuming we compute f(t)sin(wt) for many different omega, this gives some // a posteriori ability to choose a refinement level that is roughly appropriate. size_t i = starting_level_; do { Real I0 = estimate_integral(f, omega, i); #ifdef BOOST_MATH_INSTRUMENT_OOURA print_ooura_estimate(i, I0, I1, omega); #endif Real absolute_error_estimate = abs(I0-I1); Real scale = max(abs(I0), abs(I1)); if (!isnan(I1) &amp;&amp; absolute_error_estimate &lt;= rel_err_goal_*scale) { starting_level_ = std::max(long(i) - 1, long(0)); return {I0/omega, absolute_error_estimate/scale}; } I1 = I0; } while(++i &lt; big_nodes_.size()); // We've used up all our precomputed levels. // Now we need to add more. // It might seems reasonable to just keep adding levels indefinitely, if that's what the user wants. // But in fact the nodes and weights just merge into each other and the error gets worse after a certain number. // This value for max_additional_levels was chosen by observation of a slowly converging oscillatory integral: // f(x) := cos(7cos(x))sin(x)/x size_t max_additional_levels = 4; while (big_nodes_.size() &lt; requested_levels_ + max_additional_levels) { size_t i = big_nodes_.size(); if (std::is_same&lt;Real, float&gt;::value) { add_level&lt;double&gt;(i); } else if (std::is_same&lt;Real, double&gt;::value) { add_level&lt;long double&gt;(i); } else { add_level&lt;Real&gt;(i); } Real I0 = estimate_integral(f, omega, i); Real absolute_error_estimate = abs(I0-I1); Real scale = max(abs(I0), abs(I1)); #ifdef BOOST_MATH_INSTRUMENT_OOURA print_ooura_estimate(i, I0, I1, omega); #endif if (absolute_error_estimate &lt;= rel_err_goal_*scale) { starting_level_ = std::max(long(i) - 1, long(0)); return {I0/omega, absolute_error_estimate/scale}; } I1 = I0; ++i; } starting_level_ = big_nodes_.size() - 2; return {I1/omega, relative_error_estimate}; } private: template&lt;class PreciseReal&gt; void add_level(size_t i) { size_t current_num_levels = big_nodes_.size(); Real unit_roundoff = std::numeric_limits&lt;Real&gt;::epsilon()/2; // h0 = 1. Then all further levels have h_i = 1/2^i. // Since the nodes don't nest, we could conceivably divide h by (say) 1.5, or 3. // It's not clear how much benefit (or loss) would be obtained from this. PreciseReal h = PreciseReal(1)/PreciseReal(1&lt;&lt;i); std::vector&lt;Real&gt; bnode_row; std::vector&lt;Real&gt; bweight_row; // Definitely could use a more sophisticated heuristic for how many elements // will be placed in the vector. This is a pretty huge overestimate: bnode_row.reserve((1&lt;&lt;i)*sizeof(Real)); bweight_row.reserve((1&lt;&lt;i)*sizeof(Real)); std::vector&lt;Real&gt; lnode_row; std::vector&lt;Real&gt; lweight_row; lnode_row.reserve((1&lt;&lt;i)*sizeof(Real)); lweight_row.reserve((1&lt;&lt;i)*sizeof(Real)); Real max_weight = 1; auto alpha = calculate_ooura_alpha(h); long n = 0; Real w; do { auto precise_nw = ooura_sin_node_and_weight(n, h, alpha); Real node = static_cast&lt;Real&gt;(precise_nw.first); Real weight = static_cast&lt;Real&gt;(precise_nw.second); w = weight; bnode_row.push_back(node); bweight_row.push_back(weight); if (abs(weight) &gt; max_weight) { max_weight = abs(weight); } ++n; // f(t)-&gt;0 as t-&gt;infty, which is why the weights are computed up to the unit roundoff. } while(abs(w) &gt; unit_roundoff*max_weight); // This class tends to consume a lot of memory; shrink the vectors back down to size: bnode_row.shrink_to_fit(); bweight_row.shrink_to_fit(); // Why we are splitting the nodes into regimes where t_n &gt;&gt; 1 and t_n &lt;&lt; 1? // It will create the opportunity to sensibly truncate the quadrature sum to significant terms. n = -1; do { auto precise_nw = ooura_sin_node_and_weight(n, h, alpha); Real node = static_cast&lt;Real&gt;(precise_nw.first); if (node &lt;= 0) { break; } Real weight = static_cast&lt;Real&gt;(precise_nw.second); w = weight; using std::isnan; if (isnan(node)) { // This occurs at n = -11 in quad precision: break; } if (lnode_row.size() &gt; 0) { if (lnode_row[lnode_row.size()-1] == node) { // The nodes have fused into each other: break; } } lnode_row.push_back(node); lweight_row.push_back(weight); if (abs(weight) &gt; max_weight) { max_weight = abs(weight); } --n; // f(t)-&gt;infty is possible as t-&gt;0, hence compute up to the min. } while(abs(w) &gt; std::numeric_limits&lt;Real&gt;::min()*max_weight); lnode_row.shrink_to_fit(); lweight_row.shrink_to_fit(); // std::scoped_lock once C++17 is more common? std::lock_guard&lt;std::mutex&gt; lock(node_weight_mutex_); // Another thread might have already finished this calculation and appended it to the nodes/weights: if (current_num_levels == big_nodes_.size()) { big_nodes_.push_back(bnode_row); bweights_.push_back(bweight_row); little_nodes_.push_back(lnode_row); lweights_.push_back(lweight_row); } } template&lt;class F&gt; Real estimate_integral(F const &amp; f, Real omega, size_t i) { // Because so few function evaluations are required to get high accuracy on the integrals in the tests, // Kahan summation doesn't really help. //auto cond = boost::math::tools::summation_condition_number&lt;Real, true&gt;(0); Real I0 = 0; auto const &amp; b_nodes = big_nodes_[i]; auto const &amp; b_weights = bweights_[i]; // Will benchmark if this is helpful: Real inv_omega = 1/omega; for(size_t j = 0 ; j &lt; b_nodes.size(); ++j) { I0 += f(b_nodes[j]*inv_omega)*b_weights[j]; } auto const &amp; l_nodes = little_nodes_[i]; auto const &amp; l_weights = lweights_[i]; // If f decays rapidly as |t|-&gt;infty, not all of these calls are necessary. for (size_t j = 0; j &lt; l_nodes.size(); ++j) { I0 += f(l_nodes[j]*inv_omega)*l_weights[j]; } return I0; } std::mutex node_weight_mutex_; // Nodes for n &gt;= 0, giving t_n = pi*phi(nh)/h. Generally t_n &gt;&gt; 1. std::vector&lt;std::vector&lt;Real&gt;&gt; big_nodes_; // The term bweights_ will indicate that these are weights corresponding // to the big nodes: std::vector&lt;std::vector&lt;Real&gt;&gt; bweights_; // Nodes for n &lt; 0: Generally t_n &lt;&lt; 1, and an invariant is that t_n &gt; 0. std::vector&lt;std::vector&lt;Real&gt;&gt; little_nodes_; std::vector&lt;std::vector&lt;Real&gt;&gt; lweights_; Real rel_err_goal_; std::atomic&lt;long&gt; starting_level_; size_t requested_levels_; }; template&lt;class Real&gt; class ooura_fourier_cos_detail { public: ooura_fourier_cos_detail(const Real relative_error_goal, size_t levels) { if (relative_error_goal &lt;= std::numeric_limits&lt;Real&gt;::epsilon()/2) { throw std::domain_error("The relative error goal cannot be smaller than the unit roundoff."); } using std::abs; requested_levels_ = levels; starting_level_ = 0; rel_err_goal_ = relative_error_goal; big_nodes_.reserve(levels); bweights_.reserve(levels); little_nodes_.reserve(levels); lweights_.reserve(levels); for (size_t i = 0; i &lt; levels; ++i) { if (std::is_same&lt;Real, float&gt;::value) { add_level&lt;double&gt;(i); } else if (std::is_same&lt;Real, double&gt;::value) { add_level&lt;long double&gt;(i); } else { add_level&lt;Real&gt;(i); } } } template&lt;class F&gt; std::pair&lt;Real,Real&gt; integrate(F const &amp; f, Real omega) { using std::abs; using std::max; using boost::math::constants::pi; if (omega == 0) { throw std::domain_error("At omega = 0, the integral is not oscillatory. The user must choose an appropriate method for this case.\n"); } if (omega &lt; 0) { return this-&gt;integrate(f, -omega); } Real I1 = std::numeric_limits&lt;Real&gt;::quiet_NaN(); Real absolute_error_estimate = std::numeric_limits&lt;Real&gt;::quiet_NaN(); Real scale = std::numeric_limits&lt;Real&gt;::quiet_NaN(); size_t i = starting_level_; do { Real I0 = estimate_integral(f, omega, i); #ifdef BOOST_MATH_INSTRUMENT_OOURA print_ooura_estimate(i, I0, I1, omega); #endif absolute_error_estimate = abs(I0-I1); scale = max(abs(I0), abs(I1)); if (!isnan(I1) &amp;&amp; absolute_error_estimate &lt;= rel_err_goal_*scale) { starting_level_ = std::max(long(i) - 1, long(0)); return {I0/omega, absolute_error_estimate/scale}; } I1 = I0; } while(++i &lt; big_nodes_.size()); size_t max_additional_levels = 4; while (big_nodes_.size() &lt; requested_levels_ + max_additional_levels) { size_t i = big_nodes_.size(); if (std::is_same&lt;Real, float&gt;::value) { add_level&lt;double&gt;(i); } else if (std::is_same&lt;Real, double&gt;::value) { add_level&lt;long double&gt;(i); } else { add_level&lt;Real&gt;(i); } Real I0 = estimate_integral(f, omega, i); #ifdef BOOST_MATH_INSTRUMENT_OOURA print_ooura_estimate(i, I0, I1, omega); #endif absolute_error_estimate = abs(I0-I1); scale = max(abs(I0), abs(I1)); if (absolute_error_estimate &lt;= rel_err_goal_*scale) { starting_level_ = std::max(long(i) - 1, long(0)); return {I0/omega, absolute_error_estimate/scale}; } I1 = I0; ++i; } starting_level_ = big_nodes_.size() - 2; return {I1/omega, absolute_error_estimate/scale}; } private: template&lt;class PreciseReal&gt; void add_level(size_t i) { size_t current_num_levels = big_nodes_.size(); Real unit_roundoff = std::numeric_limits&lt;Real&gt;::epsilon()/2; PreciseReal h = PreciseReal(1)/PreciseReal(1&lt;&lt;i); std::vector&lt;Real&gt; bnode_row; std::vector&lt;Real&gt; bweight_row; bnode_row.reserve((1&lt;&lt;i)*sizeof(Real)); bweight_row.reserve((1&lt;&lt;i)*sizeof(Real)); std::vector&lt;Real&gt; lnode_row; std::vector&lt;Real&gt; lweight_row; lnode_row.reserve((1&lt;&lt;i)*sizeof(Real)); lweight_row.reserve((1&lt;&lt;i)*sizeof(Real)); Real max_weight = 1; auto alpha = calculate_ooura_alpha(h); long n = 0; Real w; do { auto precise_nw = ooura_cos_node_and_weight(n, h, alpha); Real node = static_cast&lt;Real&gt;(precise_nw.first); Real weight = static_cast&lt;Real&gt;(precise_nw.second); w = weight; bnode_row.push_back(node); bweight_row.push_back(weight); if (abs(weight) &gt; max_weight) { max_weight = abs(weight); } ++n; // f(t)-&gt;0 as t-&gt;infty, which is why the weights are computed up to the unit roundoff. } while(abs(w) &gt; unit_roundoff*max_weight); bnode_row.shrink_to_fit(); bweight_row.shrink_to_fit(); n = -1; do { auto precise_nw = ooura_cos_node_and_weight(n, h, alpha); Real node = static_cast&lt;Real&gt;(precise_nw.first); // The function cannot be singular at zero, // so zero is not a unreasonable node, // unlike in the case of the Fourier Sine. // Hence only break if the node is negative. if (node &lt; 0) { break; } Real weight = static_cast&lt;Real&gt;(precise_nw.second); w = weight; if (lnode_row.size() &gt; 0) { if (lnode_row.back() == node) { // The nodes have fused into each other: break; } } lnode_row.push_back(node); lweight_row.push_back(weight); if (abs(weight) &gt; max_weight) { max_weight = abs(weight); } --n; } while(abs(w) &gt; std::numeric_limits&lt;Real&gt;::min()*max_weight); lnode_row.shrink_to_fit(); lweight_row.shrink_to_fit(); std::lock_guard&lt;std::mutex&gt; lock(node_weight_mutex_); // Another thread might have already finished this calculation and appended it to the nodes/weights: if (current_num_levels == big_nodes_.size()) { big_nodes_.push_back(bnode_row); bweights_.push_back(bweight_row); little_nodes_.push_back(lnode_row); lweights_.push_back(lweight_row); } } template&lt;class F&gt; Real estimate_integral(F const &amp; f, Real omega, size_t i) { Real I0 = 0; auto const &amp; b_nodes = big_nodes_[i]; auto const &amp; b_weights = bweights_[i]; Real inv_omega = 1/omega; for(size_t j = 0 ; j &lt; b_nodes.size(); ++j) { I0 += f(b_nodes[j]*inv_omega)*b_weights[j]; } auto const &amp; l_nodes = little_nodes_[i]; auto const &amp; l_weights = lweights_[i]; for (size_t j = 0; j &lt; l_nodes.size(); ++j) { I0 += f(l_nodes[j]*inv_omega)*l_weights[j]; } return I0; } std::mutex node_weight_mutex_; std::vector&lt;std::vector&lt;Real&gt;&gt; big_nodes_; std::vector&lt;std::vector&lt;Real&gt;&gt; bweights_; std::vector&lt;std::vector&lt;Real&gt;&gt; little_nodes_; std::vector&lt;std::vector&lt;Real&gt;&gt; lweights_; Real rel_err_goal_; std::atomic&lt;long&gt; starting_level_; size_t requested_levels_; }; }}}} #endif <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<h1>Accuracy of floating point calculations</h1>\n\n<p>Indeed, when doing a large number of mathematical operations, you have to be careful to ensure proper accuracy of the results. Luckily, a lot of operations are mostly fine. The main thing that causes loss of precision is when adding together numbers that differ greatly in size. For example, adding <code>1</code> and <code>1e-100</code> will just result in <code>1</code>. However, multiplying them is perfectly fine, and will result in the expected <code>1e-100</code>.</p>\n\n<p>The most accurate way to do repeated summing (which is what numerical integration is all about) is to calculate the values of all the individual points, put them into an array, sort that array, and then sum adjacent pairs of array elements into another array that is half the size, and repeat that until you have one value left. The only issue with this of course is that it can use a lot of memory. However, since you already have arrays for nodes and weights, I think it could be an option here.</p>\n\n<p>Using a higher precision and converting it back may work in some cases. However, if the difference in magnitude between the smallest and the largest value that you are summing together is still bigger than what the higher precision variables can represent, you are out of luck.</p>\n\n<p>I would try to implement the sorting + repeated summing approach, and check the results you get with that against naive integration, and against integration with higher precision variables, and see whether any of this matters. It also wouldn't hurt to do some performance benchmarks to see the cost of each of these approaches.</p>\n\n<h1>Avoiding code duplication</h1>\n\n<p>Indeed there is a lot of code duplication between <code>oora_fourier_sin_detail</code> and <code>oora_fourier_cos_detail</code>. You could try to create a generic class that takes a (template) parameter that chooses between the sine and cosine variant, and then check that parameter to specialize some parts of the code, similar to how you used <code>if (std::is_same&lt;Real, ...&gt;::value)</code>.</p>\n\n<h1>Comments</h1>\n\n<p>The references to papers and equations are very good to have. However, most of the other comments are unfortunately bad in my opinion.</p>\n\n<p>First of all, it would help to understand what the code is doing without having to find the equations myself. Especially for someone not having a university level maths education, it can be hard to track down references when they are not used to how math papers are published. So instead of just saying \"Ooura and Mori, equation 3.3\", describe what it actually is that <code>oora_eta()</code> is calculating.</p>\n\n<p>In <code>oora_sin_node_and_weight()</code>, why is <code>n == 0</code> a special case?</p>\n\n<p>A comment like \"I have verified that this is not a signifant source of inaccuracy\" is a bit weird to see in code. Who is \"I\"? And how insignificant is it? And why would this line of code not be significant to begin with? It just adds more questions. If the way you calculate <code>rhi_prime</code> is an approximation instead of a more exact formula, then mention that this is an approximation and why it is valid to use here. If it is the exact formula, then I would not add any comment at all here. The fact that floating point operations are not perfect should be understood by all programmers, and the formula in that line doesn't look like there is any reason to worry about its accuracy.</p>\n\n<p>The comments in <code>oora_sin_node_and_weight()</code> and <code>oora_cos_node_and_weight()</code> are quite different, even though the functions are almost the same.</p>\n\n<p>A lot of comments say things like \"we could\", \"it's not clear\", \"this is a huge overestimate\". That doesn't inspire a lot of confidence in this code. Why are these comments there? If it's to remind you of something you have to fix later, mark it with \"TODO\", so it's clear that this is something for the future. It also makes it easy to grep for. An example:</p>\n\n<pre><code>// TODO: the size of the vectors is bigger than necessary, use a better heuristic\n</code></pre>\n\n<p>It's hard to write comments, especially for code you've just written. I would wait a week or two and then reread the code. Try to imagine a colleague or a student having to read your code.</p>\n\n<h1>Use <code>unique_ptr&lt;&gt;</code> instead of <code>shared_ptr&lt;&gt;</code></h1>\n\n<p>Your <code>impl_</code> variable is never shared with anything else, so there is no reason for it to be a shared pointer. Declare it as <code>std::unique&lt;...&gt; impl_</code> instead, and use <code>std::make_unique&lt;&gt;()</code> in the constructor.</p>\n\n<h1>Use a proper two-dimensional array class</h1>\n\n<p>Nesting vectors is not an efficient way of storing multi-dimensional arrays. Why not use <code>boost::multi_array</code> instead?</p>\n\n<h1>Why use mutexes and atomics if there are no threads?</h1>\n\n<p>You have a mutex to guard node weight vectors, and an atomic variable for the starting level. However, I see no mention of threads or asynchronous execution in your code, unless I am missing something. So it seems to me these things are useless, and should be removed from the code.</p>\n\n<h1>Avoid useless <code>using</code> statements</h1>\n\n<p>I see a lot of <code>using</code> statements in the code in functions that don't even use the functions or constants mentioned in these statement. For example, <code>using std::abs</code> in <code>oora_sin_node_and_weight()</code> is not used at all.</p>\n\n<p>In many cases, you only use these things once anyway, so it just increases the number of lines of code, for little gain in readability. I recommend that you just avoid using <code>using</code> altogether, and just write out all namespaces explicitly.</p>\n\n<h1>Use consistent whitespace</h1>\n\n<p>Sometimes you use spaces around operators, sometimes not. Be consistent in how you format your code. I suggest you use spaces around all binary operator. Conversely, don't use a space after a '(' and before a ')'.</p>\n\n<p>You don't have to fix all this by hand, I recommend you use a code formatting tool to do this for you. Check the Boost style guide for the recommended coding style.</p>\n\n<h1>Use <code>std::function&lt;&gt;</code> to pass function pointers</h1>\n\n<p>I see you are using <code>template&lt;class F&gt;</code> to allow passing function pointers as arguments. The problem is that <code>F</code> is allowed to be anything, even things that are not functions, and this will cause hard to read compiler errors. Instead, you can use <code>std::function&lt;&gt;</code> to specify that a function takes another function as an argument. For example:</p>\n\n<pre><code>Real estimate_integral(std::function&lt;Real(Real)&gt; f, Real omega, size_t i) {\n ...\n I0 += f(b_nodes[j] * inv_omega) * b_weights[j];\n ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-21T01:43:57.710", "Id": "458434", "Score": "0", "body": "The integrator does a lot of precompute which occupies a lot of memory and is independent of the function. Hence the documentation say to share this object between threads if you need the performance while (for example) assembling a stiffness matrix. Hence the `std::shared_ptr`, and hence the atomics." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-21T01:45:49.443", "Id": "458435", "Score": "0", "body": "The using statements are required for ADL, since `std::cos` is only defined on `float`, `double`, and `long double`, but this quadrature works in arbitrary precision provided definitions of `cos`, `sin`, so on are available. I'll double check that all of them are in fact necessary." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-21T00:07:59.570", "Id": "234413", "ParentId": "222355", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T14:25:38.583", "Id": "222355", "Score": "13", "Tags": [ "c++", "numerical-methods" ], "Title": "Continuous Fourier integrals by Ooura's method" }
222355
<p>I have a loop in a php file to HTTP_Request Server Via CURL->POST.</p> <p>But I don't know if I'm missing any security considerations. Also, is there a better way to perform this http request?</p> <pre><code>&lt;?php $j = 0; while ($j &lt;= 1) { $url = 'http://127.0.0.1/index.php'; $fields = array( 'input1' =&gt; 'variable1', 'input2' =&gt; 'variable2', ); $postvars = http_build_query($fields); $COOKIE_FILE_PATH = "/tmp/cookiescron.txt"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, count($fields)); curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars); curl_setopt($ch, CURLOPT_TIMEOUT, 2); curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); curl_setopt($ch, CURLOPT_FORBID_REUSE, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 10); curl_setopt($ch, CURLOPT_FRESH_CONNECT, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: close')); // execute post curl_exec($ch); // close connection curl_close($ch); $j++; sleep(25); } ?&gt; </code></pre> <p>This executes 2 requests in around 25~30 seconds.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T00:37:10.573", "Id": "430337", "Score": "0", "body": "Is it possible to repackage your array data so that you don't _need_ to perform iterated curl calls? The variability of your project data is not evident in your posted snippet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T00:39:05.073", "Id": "430339", "Score": "0", "body": "is mandatory, becouse i need sleep 25 second every bucle...i think" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T00:40:35.720", "Id": "430340", "Score": "0", "body": "So, whatever url you are sending your data to will only accept single doses of data? Can't send a deeper data structure? If you have written the receiving script, I recommend writing it to receive multiple rows of data so that only one curl call is necessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T00:44:36.800", "Id": "430341", "Score": "0", "body": "the url is the one mentioned in the script; and yes, the php is ready to receive other types of data passed by post, json, etc ... but I do not understand the question around the data structure ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T00:47:12.090", "Id": "430343", "Score": "0", "body": "Can you pass a deep input array: `$fields = array(array(\n 'input1' => 'variable1',\n 'input2' => 'variable2',\n ),array(\n 'input1' => 'variable3',\n 'input2' => 'variable4',\n ));` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T01:36:32.390", "Id": "430347", "Score": "0", "body": "https://imgur.com/a/Z2cOj3J" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T07:01:52.973", "Id": "430354", "Score": "0", "body": "Do you need to authenticate the users who are post data to your url? It looks like any bot that knows your url can POST whatever they want. Is logging-in / token generation necessary for your application? Everything _should be_ `htps`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T07:51:51.857", "Id": "430357", "Score": "0", "body": "not, not , not... system structure have a custom filter to get out all security ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T07:53:33.820", "Id": "430358", "Score": "1", "body": "...well, if you want a review regarding security, you should probably show the security part." } ]
[ { "body": "<p>Well, I didn't take the time to test my snippets, but here are two suggestions...</p>\n\n<p>#1 (preferred) - Bundle all of your input data into a single array, then pass it to your receiving url with a single curl call. It is best practice to minimize total calls (avoid iterated calls) so long as the operation works for your project, of course. This avoids sleepy time too.</p>\n\n<pre><code>$ch = curl_init();\n$fields = [\n ['input1' =&gt; 'variable1', 'input2' =&gt; 'variable2'],\n ['input1' =&gt; 'variable3', 'input2' =&gt; 'variable4']\n];\n$COOKIE_FILE_PATH = \"/tmp/cookiescron.txt\"; // this doesn't appear to be used\n$options = [\n CURLOPT_URL =&gt; 'http://127.0.0.1/index.php',\n CURLOPT_POST =&gt; true, // https://www.php.net/manual/en/function.curl-setopt.php says boolean is expected\n CURLOPT_POSTFIELDS =&gt; http_build_query($fields),\n CURLOPT_TIMEOUT =&gt; 2,\n CURLOPT_RETURNTRANSFER =&gt; false,\n CURLOPT_FORBID_REUSE =&gt; true,\n CURLOPT_CONNECTTIMEOUT =&gt; 2,\n CURLOPT_DNS_CACHE_TIMEOUT =&gt; 10,\n CURLOPT_FRESH_CONNECT =&gt; true,\n CURLOPT_HTTPHEADER =&gt; ['Connection: close']\n];\ncurl_setopt_array($ch, $options);\ncurl_exec($ch);\ncurl_close($ch);\n</code></pre>\n\n<hr>\n\n<p>#2 - If your requirements obligate the use of iterated curl calls, I'd recommend only updating the <code>CURLOPT_POSTFIELDS</code> value within the loop. (Again, not tested)</p>\n\n<pre><code>$ch = curl_init();\n$fields = [\n ['input1' =&gt; 'variable1', 'input2' =&gt; 'variable2'],\n ['input1' =&gt; 'variable3', 'input2' =&gt; 'variable4']\n];\n$COOKIE_FILE_PATH = \"/tmp/cookiescron.txt\"; // this doesn't appear to be used\n$options = [\n CURLOPT_URL =&gt; 'http://127.0.0.1/index.php',\n CURLOPT_POST =&gt; true, // https://www.php.net/manual/en/function.curl-setopt.php says boolean is expected\n CURLOPT_TIMEOUT =&gt; 2,\n CURLOPT_RETURNTRANSFER =&gt; false,\n CURLOPT_CONNECTTIMEOUT =&gt; 2,\n CURLOPT_DNS_CACHE_TIMEOUT =&gt; 10,\n];\nforeach ($fields as $data) {\n $options[CURLOPT_POSTFIELDS =&gt; http_build_query($data)]; // overwrites previous data\n curl_setopt_array($ch, $options);\n curl_exec($ch);\n sleep(25);\n}\ncurl_close($ch);\n</code></pre>\n\n<p>The takeaway here is to always try to leave as many processes as possible OUTSIDE of the loop to reduce calls/workload.</p>\n\n<p>Relevant documentation:</p>\n\n<ul>\n<li><a href=\"https://www.php.net/manual/en/function.curl-setopt.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/function.curl-setopt.php</a></li>\n<li><a href=\"https://www.php.net/manual/en/function.curl-setopt-array.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/function.curl-setopt-array.php</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T20:04:15.417", "Id": "430444", "Score": "0", "body": "if CURLOPT_FORBID_REUSE is true , this will get a warning???" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T21:02:53.913", "Id": "430452", "Score": "0", "body": "That makes sense. If I want to keep the connection / reuse the curl handle, I'd better allow its reuse. Updated." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T13:02:04.887", "Id": "222404", "ParentId": "222358", "Score": "2" } } ]
{ "AcceptedAnswerId": "222404", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T15:21:11.593", "Id": "222358", "Score": "2", "Tags": [ "php", "security", "http" ], "Title": "Using Curl/Post to execute a HTTP request" }
222358
<p>I've created a CV eager for corrections. Once it is properly written it'd be converted into a template, in order to share it with the community.</p> <p>Can you suggest some starting corrections or ideas? (I'm willing to implement them by my own, if I can) A brief, compilable version is pasted below:</p> <pre><code> \documentclass{article} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage[margin=2.3cm,top=1.6cm, textheight=1050pt]{geometry} %sets margin of text for the whole document \usepackage{titlesec} \usepackage{url} \usepackage{hyperref} \usepackage{bold-extra} \usepackage[dvipsnames]{xcolor} \pagenumbering{gobble} \usepackage{microtype} \usepackage{blindtext} \titleformat{\section}[block] % Customise the \section command {\normalfont\LARGE\bfseries\filcenter} % Make the \section headers large (\Large), % small capitals (\scshape) and left aligned (\raggedright) {}{0em} % A label like 'Section ...'. Here we omit labels {} % Can be used to insert code before the heading \titlespacing*{\section}{1em}{1em}{1em}[0em] \titleformat{\subsection}{\color{Mahogany}\Large\raggedright\scshape\bfseries}{}{0em}{} [\vspace{0.3ex}\titlerule] \titlespacing*{\subsection}{0pt}{0.75em}{0.75em} %load icons package for mail, phone and address. \title{\textbf{Mr. Nobody\\[1em] \footnotesize DoB January 23, 1995 \hspace{1.3em} NBL City, NBL. \hspace{1.3em} 666666 \hspace{1.3em} \url{mrnobody@gmail.com}\vspace{-1cm}}} \date{ } \author{} \begin{document} \maketitle \subsection*{Education} \paragraph{National University of X, Y.} MSc. in X Y (2012--2017). Thesis: \textit{Thermodynamics of chicken in Aqueous Phase Using Computational Tools, 2017.} \paragraph{High School, Dr XYZW.} Graduation in Natural Sciences (2011). \subsection*{Work Experience} \paragraph{Institute for XY Z (2018--2019).} Introduction to chicken Teacher, NBL, NBL. \subsection*{Projects} \paragraph{Hazards and Safety in the corridor (2018--2019), Coordinator.} Oriented to students of the Institute of NBL. The purpose was to do Xperiments, reflect upon hazard and safety in the corridor (H \&amp; S rules) and discuss results. \paragraph{webdeveloper (2018--On Going), x.} equis and the general equisequis site is Directed by equisen. The aim is producing an Orange External Resource. \paragraph{StackExchange Member (2017--On Going).} Q \&amp; A sites. {\href{https://stackexchange.com/users/6538373/santimirandarp}{Link to profile-overview}} \subsection{Language} <span class="math-container">\begin{tabular}{lr} \textbullet\textbullet\textbullet\textbullet &amp; \hspace{1em} A, B.\\ \textbullet\textbullet &amp; \hspace{1em} C, D. \end{tabular}</span> \subsection{Few Skills} <span class="math-container">\begin{tabular}{lr} \textbullet\textbullet\textbullet &amp; A: with B, C, and D, and pandas.\\ \textbullet\textbullet &amp; Linux Shell\slash . \\ %\item[\textbullet\textbullet\textbullet] \hspace{1em} Chemistry Laboratory Tasks. %\paragraph{\textbullet\textbullet\textbullet} \hspace{1em} Excel, OfficeCalc. \textbullet\textbullet\textbullet &amp; HTML, CSS. \end{tabular}</span> \subsection{Hobbies} %\raggedright Literature and Philosophy favorite authors: B. Russell, A. Huxley, W. Whitman, J.L. Borges. Poetry Channel at \href{emptylink}{YouTube}. Music Post-Rock. Play little violin and guitar.\\[1em] I've written a gutenmorgen with a short biography of Marvin Schr\"{o}dinger available \href{emptylink2}{here}. \subsection{Summary} \blindtext{3} \end{document} </code></pre> <hr> <p><strong>The output so far looks like this:</strong></p> <p><a href="https://i.stack.imgur.com/FMhS7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FMhS7.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T06:05:07.877", "Id": "430350", "Score": "1", "body": "Did you look at the [moderncv](https://ctan.org/tex-archive/macros/latex/contrib/moderncv/) package? It's what I used, and I got some nice comments on it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T09:11:10.047", "Id": "430362", "Score": "0", "body": "i haven't, there are so many packages that i've preferred just to invest my time in creating something simple. But maybe I should...thanks! @MaartenFabré" } ]
[ { "body": "<p>Some minor comments:</p>\n\n<ul>\n<li><p>hyperref should be loaded after the other packages (there are only few exceptions, see <a href=\"https://tex.stackexchange.com/q/1863/36296\">https://tex.stackexchange.com/q/1863/36296</a>)</p></li>\n<li><p>loading <code>url</code> is not really necessary because you already load <code>hyperref</code></p></li>\n<li><p>you specify too many values of the geometry package. The paperheight is implicitly given by the default value of your tex distribution, the bottom margin is set to 2.3cm, the top margin to 1.6cm and the textheight to 1050pt, this is one value too much because there no free length left to adjust. I would suggest to either remove the explicit declaration of the textheight or change margin=2.3cm to hmargin=2.3cm to make sure that there is at least one free length</p></li>\n<li><p><code>\\begin{tabular}{@{}lr@{}}</code> will ensure that the bullets are nicely aligned with the left boarder of the surrounding text</p></li>\n<li><p>using formatting instructions like <code>\\hspace{}</code> in the argument of <code>\\title{}</code> is hacky and can cause problems with the pdf meta data. As a quick fix you can provide an alternative string to be used in the pdf meta data with <code>\\texorpdfstring{tex code here}{pdf meta data here}</code>. The clean way would be to redefine <code>\\maketitle</code> and include all the formatting instructions there</p></li>\n<li><p>If you make your work available to the community, please consider adding version information and a suitable license. For example the LPPL (Latex Project Public License) encourages the users to rename a source file before editing it. Not having multiple different versions with the same name floating around the internet will make it much easier to help users on platforms like tex.se.</p></li>\n</ul>\n\n<hr>\n\n<pre><code>\\documentclass{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\\usepackage[margin=2.3cm,top=1.6cm]{geometry} \n%sets margin of text for the whole document\n\\usepackage{titlesec}\n% \\usepackage{url}\n\n\\usepackage{bold-extra}\n\\usepackage[dvipsnames]{xcolor}\n\\pagenumbering{gobble}\n\\usepackage{microtype}\n\\usepackage{blindtext}\n\\usepackage{hyperref}\n\n\\titleformat{\\section}[block] % Customise the \\section command \n {\\normalfont\\LARGE\\bfseries\\filcenter} % Make the \\section headers large (\\Large),\n % small capitals (\\scshape) and left aligned (\\raggedright)\n {}{0em} % A label like 'Section ...'. Here we omit labels\n {} % Can be used to insert code before the heading\n\\titlespacing*{\\section}{1em}{1em}{1em}[0em]\n\n\\titleformat{\\subsection}{\\color{Mahogany}\\Large\\raggedright\\scshape\\bfseries}{}{0em}{}\n[\\vspace{0.3ex}\\titlerule]\n\n\\titlespacing*{\\subsection}{0pt}{0.75em}{0.75em}\n%load icons package for mail, phone and address.\n\n\\title{\\texorpdfstring{\\textbf{Mr. Nobody\\\\[1em] \\footnotesize DoB January 23, 1995 \\hspace{1.3em} NBL City, NBL. \\hspace{1.3em} 666666 \\hspace{1.3em} \n\\url{mrnobody@gmail.com}\\vspace{-1cm}}}{Mr. Nobody}}\n\\date{ }\n\\author{}\n\n\\begin{document}\n\\maketitle\n\n\\subsection*{Education}\n\n\\paragraph{National University of X, Y.} MSc. in X Y (2012--2017). Thesis: \\textit{Thermodynamics of \nchicken in Aqueous Phase Using Computational Tools, 2017.}\n\n\\paragraph{High School, Dr XYZW.} Graduation in Natural Sciences (2011). \n\n\n\\subsection*{Work Experience}\n\n\\paragraph{Institute for XY Z (2018--2019).} \nIntroduction to chicken Teacher, NBL, NBL. \n\n\\subsection*{Projects}\n\n\\paragraph{Hazards and Safety in the corridor (2018--2019), Coordinator.} \nOriented to students of the Institute of NBL. The purpose was to \ndo Xperiments, reflect upon hazard and safety in the corridor (H \\&amp; S rules) and discuss results. \n\\paragraph{webdeveloper (2018--On Going), x.}\nequis and the general equisequis site is Directed by equisen.\nThe aim is producing an Orange External Resource.\n\\paragraph{StackExchange Member (2017--On Going).}\nQ \\&amp; A sites. {\\href{https://stackexchange.com/users/6538373/santimirandarp}{Link to profile-overview}} \n\n\\subsection{Language}\n\n<span class=\"math-container\">\\begin{tabular}{@{}lr@{}}\n\\textbullet\\textbullet\\textbullet\\textbullet &amp; \\hspace{1em} A, B.\\\\\n\\textbullet\\textbullet &amp; \\hspace{1em} C, D.\n\\end{tabular}</span>\n\n\\subsection{Few Skills}\n\n<span class=\"math-container\">\\begin{tabular}{@{}lr@{}}\n\\textbullet\\textbullet\\textbullet &amp; A: with B, C, and D, and pandas.\\\\ \n\\textbullet\\textbullet &amp; Linux Shell\\slash . \\\\\n%\\item[\\textbullet\\textbullet\\textbullet] \\hspace{1em} Chemistry Laboratory Tasks.\n%\\paragraph{\\textbullet\\textbullet\\textbullet} \\hspace{1em} Excel, OfficeCalc. \n\\textbullet\\textbullet\\textbullet &amp; HTML, CSS.\n\\end{tabular}</span>\n\\subsection{Hobbies}\n%\\raggedright\nLiterature and Philosophy favorite authors: B. Russell, A. Huxley, W. Whitman, J.L. Borges. \nPoetry Channel at \\href{emptylink}{YouTube}.\nMusic Post-Rock. Play little violin and guitar.\\\\[1em]\nI've written a gutenmorgen with a short biography of Marvin Schr\\\"{o}dinger available \n\\href{emptylink2}{here}. \n\n\n\\subsection{Summary}\n\n\\blindtext{3}\n\n\\end{document}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-18T12:24:44.443", "Id": "445764", "Score": "0", "body": "you may like this one: http://mrnobody.epizy.com/mrnobody/nobody.html?i=1 :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-18T12:42:52.707", "Id": "445770", "Score": "1", "body": "@santimirandarp :) Nice to see that Mr. Nobody is inclusive to robots, there is so much robot discrimination on the internet - all the mean robots.txt that exclude them from reading interesting websites!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T09:25:16.783", "Id": "222447", "ParentId": "222359", "Score": "3" } } ]
{ "AcceptedAnswerId": "222447", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T15:23:27.087", "Id": "222359", "Score": "4", "Tags": [ "data-visualization", "tex" ], "Title": "CV written in LaTeX" }
222359
<p>Write a function that takes 2 inputs:</p> <ul> <li>a matrix, for example 2-dimensional array, and </li> <li>indices, for example [row, col] </li> </ul> <p>This function should return the sum of all the second input's neighbors (up, down, left, right, diagonals).</p> <p>Below is my solution. Just wanted to know if there is a better way to solve this problem. And also wanted to know if I am covering all the edge cases.</p> <pre><code>function findingNeibors(myArray, i,j) { let rowLimit = myArray.length-1; let columnLimit= myArray[0].length-1; let sum = 0; if(i&lt;0 || j&lt; 0) { console.log("invalid Index") return }; if(i&gt;rowLimit || j&gt; columnLimit){ console.log("You are Out Of Bound"); return; } for(let x = Math.max(0,i-1); x&lt;=Math.min(i+1,rowLimit); x++){ for(let y = Math.max(0,j-1); y&lt;=Math.min(j+1,columnLimit); y++){ if(x!==i || y!==j){ console.log(myArray[x][y]); sum+=myArray[x][y]; } } } return sum; } let input = [ [0,1,2,3,4], [1,2,3,4,5], [2,3,4,5,6] ] findingNeibors(input,0,0); findingNeibors(input,2,2,0); findingNeibors(input,-1,3); findingNeibors(input,3,4); <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T16:43:08.077", "Id": "430299", "Score": "0", "body": "This is my first post. Any comments is appreciated. Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T16:57:53.313", "Id": "430300", "Score": "4", "body": "Since you ask about edge cases, I would expect that you have thought about them and have prepared some unit tests. Could you add the code of your unit tests?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T17:37:37.473", "Id": "430301", "Score": "0", "body": "What happens if the input is not a number? Is that as intended?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T17:38:39.177", "Id": "430302", "Score": "0", "body": "For edge cases i am taking care of -ve cordinates like if row/col is a -ve integer . Wanted to know if there are any other edge cases. And also if there are better ways to solve this problem as I am using nested for loops.\n@Mast i think the above will work for all inputs till the row/col are given as intergers." } ]
[ { "body": "<h2>Don't <code>return</code> if there is an error, throw the error.</h2>\n\n<pre><code>if(i&lt;0 || j&lt; 0) {\n throw new Error(\"Invalid Index\");\n}\n\nif(i&gt;rowLimit || j&gt; columnLimit){\n throw new Error(\"Index out of bounds\");\n}\n</code></pre>\n\n<hr>\n\n<h2>Don't assume an array has elements</h2>\n\n<p>(i.e.: <code>let columnLimit= myArray[0].length-1;</code> will throw a <code>TypeError</code> if there are no elements in the list)</p>\n\n<p>Play it safe.</p>\n\n<pre><code>//get first element in list, \n//if it doesn't exist set it to a default empty array\nconst [column = []] = myArray;\nconst columnLimit = column.length;\n</code></pre>\n\n<hr>\n\n<h2><code>const</code> before <code>let</code> and <code>let</code> before <code>var</code></h2>\n\n<p>When declaring variables, always define them with <code>const</code> by default. You only use <code>let</code> when you expect that variable in question is likely to mutate. And never use <code>var</code> unless you have a good reason to.</p>\n\n<p><em>Note: <code>const arr = []; arr.push(1)</code> mutates the array but not the variable</em></p>\n\n<hr>\n\n<blockquote>\n <p>am I covering all the edge cases ?</p>\n</blockquote>\n\n<p>Yes, you are.</p>\n\n<p><em>Assuming that the two dimensional array has columns of equal length</em></p>\n\n<hr>\n\n<blockquote>\n <p>Just wanted to know if there is a better way to solve this problem</p>\n</blockquote>\n\n<p>There are only 8 elements max possible around a single element, and yet for every element you check to see if <code>(i,j) != (x,y)</code>.</p>\n\n<p>To solve this \"problem\", simply add all values (even with (i,j))</p>\n\n<p>Then before returning subtract the element at (i,j)</p>\n\n<pre><code>for(let x = Math.max(0,i-1); x&lt;=Math.min(i+1,rowLimit); x++){\n for(let y = Math.max(0,j-1); y&lt;=Math.min(j+1,columnLimit); y++){\n sum+=myArray[x][y];\n }\n }\n\nreturn sum - myArray[i][j]\n</code></pre>\n\n<p><em>Is this better? Well, it's 9 additional conditions VS an extra addition and subtraction.</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T15:21:22.237", "Id": "430413", "Score": "0", "body": "```for(let x = Math.max(0,i-1); x<=Math.min(i+1,rowLimit); x++){\n for(let y = Math.max(0,j-1); y<=Math.min(j+1,columnLimit); y++){\n sum+=myArray[x][y];\n }\n }\nreturn sum - myArray[x][y]\n```\nThank you for all the comments. I have a question, wouldn't x and y will be undefined , as you are trying to use it outside its scope?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T16:39:59.057", "Id": "430425", "Score": "0", "body": "@mravenash that's a mistake on my part. I meant to put i,j. Usually x,y and i,j are switched around" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T11:16:16.787", "Id": "222393", "ParentId": "222362", "Score": "4" } }, { "body": "<p>First of all I would recommend more care formatting your code and choosing good names for your variables and functions. <code>findingNeibors</code> function misspells neighbors and doesn't find them, it gives a sum of all the neighbors in a matrix, so I renamed it <code>sumMatrixNeighbors</code>. You can see the other changes on the code below. The <code>i</code> and <code>j</code> are conventionally used for the looping iterator, so <code>x</code>, <code>y</code> seem better names for the coordinates (I am pretty sure <code>m</code>, <code>n</code> are usually used with matrix coordinates too).</p>\n\n<p>The missing corner cases to check were just to validate the matrix itself and check that the coordinates were actually integers. Also the nested for loops are fine.</p>\n\n<p>You should use a linter, follow a style guide and create unit tests. Some of the most important things to make good code.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function validateMatrixCoordinates(arrayMatrix, x, y) {\n if (!Array.isArray(arrayMatrix) || !Array.isArray(arrayMatrix[0])) {\n console.log(\"arrayMatrix is not a matrix of arrays\");\n return false;\n }\n if (!Number.isInteger(x) || !Number.isInteger(y)) {\n console.log(\"Index is not an Integer\");\n return false;\n }\n if (x &lt; 0 || y &lt; 0 || x &gt; arrayMatrix.length - 1 || y &gt; arrayMatrix[0].length - 1) {\n console.log(\"Index is Out Of Bounds\");\n return false;\n }\n return true;\n}\n\nfunction sumMatrixNeighbors(arrayMatrix, x, y) {\n let rowLimit = arrayMatrix.length - 1;\n let columnLimit = arrayMatrix[0].length - 1;\n let sum = 0;\n\n if (!validateMatrixCoordinates(arrayMatrix, x, y)) {\n return;\n }\n for (let i = Math.max(0, x - 1); i &lt;= Math.min(y + 1, rowLimit); i++) {\n for (let j = Math.max(0, y - 1); j &lt;= Math.min(y + 1, columnLimit); j++) {\n if ((x !== i || y !== j) &amp;&amp; Number.isInteger(arrayMatrix[i][j])) {\n sum += arrayMatrix[i][j];\n }\n }\n }\n\n return sum;\n}\n\nlet input = [\n [0, 1, 2, 3, 4],\n [1, 2, 3, 4, 5],\n [2, 3, 4, 5, 6]\n];\n\nconsole.log('Result for [2, 1]: ' + sumMatrixNeighbors(input, 2, 1));\nconsole.log('Result for [0, 0]: ' + sumMatrixNeighbors(input, 0, 0));\nconsole.log('Result for [\"a\", 0]: ' + sumMatrixNeighbors(input, \"a\", 0));\nconsole.log('Result for [1, -1]: ' + sumMatrixNeighbors(input, 1, -1));\nconsole.log('Result for [1, 4]: ' + sumMatrixNeighbors(input, 1, 4));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T13:10:31.163", "Id": "430379", "Score": "1", "body": "The first part of your answer is good, observations about the code. Writing code to demonstrate may not be necessary," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T12:33:41.963", "Id": "430734", "Score": "0", "body": "What will be the time and space complexity this?I think for time it will be O(row*cols) & space complexity - O(1). Kindly provide your thoughts." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T12:05:14.887", "Id": "222397", "ParentId": "222362", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T16:38:32.817", "Id": "222362", "Score": "3", "Tags": [ "javascript", "array" ], "Title": "Find sum of neighbors in a 2D array" }
222362
<p>There is a simple form which takes two numbers <code>num1</code>, <code>num2</code> and an operation <code>op</code>. After submission, a new object is created. I'm new to OOJS and any correction and improvements are appreciated. Is this the best way to code this small calculator in Javascript using Object Oriented approach?</p> <pre><code>window.onload = function() { let form = document.forms['cal-form']; form.addEventListener('submit', calculate); function calculate(e) { //prevent default form submission e.preventDefault(); //get form values let num1 = parseInt(document.getElementsByTagName('input')[0].value); let num2 = parseInt(document.getElementsByTagName('input')[1].value); let op = document.getElementsByTagName('select')[0].value; //create object constructor function function Calculate(num1, num2, op){ this.num1 = num1; this.num2 = num2; this.op = op; } Calculate.prototype.result = function() { let res; switch (op) { case 'add': res = this.num1 + this.num2; break; case 'sub': res = this.num1 - this.num2; break; case 'mul': res = this.num1 * this.num2; break; case 'div': res = this.num1 / this.num2; break; default: res= 'Error! No operation selected.'; } return res; }; //create an object let cal = new Calculate(num1, num2, op); //display result document.getElementById('result').innerHTML = cal.result(); } }; </code></pre>
[]
[ { "body": "<p>I don't really see any purpose to forcibly using a class setup here. All that's doing is allowing you to provide the data before <code>result</code> is called. That's not necessary here though, and there are other ways of achieving that. If you needed to create multiple <code>Calculate</code> objects, and retain them, and call <code>result</code> on them multiple times, there may be a purpose. I can't see any gain here though. </p>\n\n<p>I would just collapse everything down to a function that accepts the three bits of data (<code>op</code>, <code>num1</code> and <code>num2</code>) and just call the function directly when needed.</p>\n\n<hr>\n\n<p>There's cleaner ways of handling the \"dispatching\" than a <code>switch</code>. I'd just use a regular JavaScript object here:</p>\n\n<pre><code>// Associate the operator strings\n// with functions\nvar strToOp = {\"+\": (x, y) =&gt; x + y, \n \"-\": (x, y) =&gt; x - y, \n \"*\": (x, y) =&gt; x * y,\n \"/\": (x, y) =&gt; x / y};\n\nvar num1 = 2;\nvar num2 = 5;\nvar op = \"*\";\n\n// Get a function from the map\nvar func = strToOp[op];\n\n// func will be undefined if they supply a bad operator string\n// This is roughly equivalent to your \"default\" case\nif(func) {\n // And give the numbers to it\n var result = func(num1, num2);\n\n // Prints 10\n console.log(result);\n\n} else {\n // Handle bad operator\n} \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T18:15:17.890", "Id": "222366", "ParentId": "222364", "Score": "1" } }, { "body": "<p>If you want to use object-oriented javascript for this calculator, I would prefer the <a href=\"https://www.digitalocean.com/community/tutorials/understanding-classes-in-javascript\" rel=\"nofollow noreferrer\"><em>class syntax</em></a> over the <em>prototype syntax</em>.</p>\n\n<p>This prototype approach ..</p>\n\n<blockquote>\n<pre><code>function Calculate(num1, num2, op) {\n this.num1 = num1;\n this.num2 = num2;\n this.op = op;\n } \n\n Calculate.prototype.result = function() {\n // ..\n }\n</code></pre>\n</blockquote>\n\n<p>.. can be replaced by (<a href=\"https://jsfiddle.net/079axbj8/\" rel=\"nofollow noreferrer\">Fiddle</a>):</p>\n\n<pre><code>class BinaryExpression {\n constructor(a, b, op) {\n this.a = a;\n this.b = b;\n this.op = op;\n }\n evaluate() {\n switch (this.op) {\n case 'add':\n return this.a + this.b;\n case 'sub':\n return this.a - this.b;\n case 'mul':\n return this.a * this.b;\n case 'div':\n return this.a / this.b;\n default:\n return 'Error! No operation selected.';\n }\n }\n}\n</code></pre>\n\n<h3>Misc</h3>\n\n<ul>\n<li>Most math expression compilers would implement a switch for the specific binary operators, but you could take it a step further and sub-class each binary operation.</li>\n<li>Rather than returning a default message when the operator is not known, you could throw an exception and let the consumer handle it. </li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T18:21:57.067", "Id": "222367", "ParentId": "222364", "Score": "1" } } ]
{ "AcceptedAnswerId": "222367", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T17:52:28.997", "Id": "222364", "Score": "2", "Tags": [ "javascript", "beginner", "object-oriented", "math-expression-eval" ], "Title": "Simple calculator in Object-oriented JavaScript" }
222364
<p>Could use some help with my presentation in Software Development. I'm presenting how I reworked a game's parser (<a href="https://www.youtube.com/watch?v=cEcxgPvmQqU" rel="nofollow noreferrer">SpaceTaxi</a>). Basically we take in a .txt file with ASCII characters and convert them into entities that can be rendered in our game.</p> <p><a href="https://i.stack.imgur.com/0qNUX.png" rel="nofollow noreferrer">Input</a>, <a href="https://i.stack.imgur.com/lKk5w.jpg" rel="nofollow noreferrer">Output</a> </p> <p>In between the input and output I've written a parser. I've tried to follow the <em>Facade Design Pattern</em> with the <em>SOLID principles</em> in mind. </p> <p>I'm not sure how much code I should show here as I don't want to flood you, so I am going to upload some of it but tell me if it's sufficient.</p> <p><strong>What my code is intended to do</strong></p> <p>The parser should be a single instance and when called (<code>Parser.StartParse(string txtFile)</code>) the parser should go through a txt file comparing ascii characters with image files.<br> The image files are given to our project. </p> <p><strong>IParse.cs</strong></p> <pre><code>public interface IParse { void Parse(string[] txtFile); void Add(List&lt;char&gt; map); } public class ParseObstacles : IParse { public Dictionary&lt;char, string&gt; Dict; public List&lt;Entity&gt; Entities; public ParseObstacles() { Dict = new Dictionary&lt;char, string&gt;(); Entities = new List&lt;Entity&gt;(); } /// &lt;summary&gt; /// Extracts the txt information about what each character represents. /// Example from the-beach.txt: "A) aspargus-edge-left.png" /// Here we split ')' to first get the character, A, and it's /// correspondent filename, 'aspargus-edge-left.png'. /// &lt;/summary&gt; public void Parse(string[] txtFile) { foreach (var i in txtFile) { if (i.Contains(")")) { var tile = i.Split(')')[0].ToCharArray()[0]; var name = i.Split(')')[1].Trim(); Dict.Add(tile, name); } } } public void Add(List&lt;char&gt; map) { ParseHelper.AddEntities(map, Dict, Entities); } } </code></pre> <p>I intended for the parser to follow the facade pattern.<br> Does this code in fact implement the facade pattern?</p>
[]
[ { "body": "<p>First, we encounter interface <code>IParse</code>.</p>\n\n<blockquote>\n<pre><code>public interface IParse {\n void Parse(string[] txtFile);\n void Add(List&lt;char&gt; map);\n}\n</code></pre>\n</blockquote>\n\n<p>You should use C# conventions.</p>\n\n<ul>\n<li>interface name should be a noun or noun phrase <code>IParse</code> -> <code>IParser</code></li>\n<li>use a plural name for a variable that represents a sequence of items <code>txtFile</code> -> <code>segments??</code> </li>\n<li>use a meaningful name to describe structures <code>map</code> -> <code>??</code> -> doesn't say anything</li>\n<li>use the correct types, preferrably interfaces, when dealing with sequences; For instance, <code>IEnumerable</code> to iterate, <code>IList</code> to manipulate.</li>\n<li>Note that your interface does not have any state or return values. We are never able to interact with it bi-directionally. Too much encapsulation perhaps?</li>\n</ul>\n\n<p>Refactored:</p>\n\n<pre><code>public interface IParser {\n void Parse(IEnumerable&lt;string&gt; segments); // or whatever we are talking about ?\n void Add(IList&lt;char&gt; map); // what is map ?\n}\n</code></pre>\n\n<p>Let's move on to <code>ParseObstacles</code>.</p>\n\n<p>Your state is public, is this as designed or a code smell? Again, use conventions.</p>\n\n<blockquote>\n<pre><code>public Dictionary&lt;char, string&gt; Dict;\npublic List&lt;Entity&gt; Entities;\n</code></pre>\n</blockquote>\n\n<pre><code>private IDictionary&lt;char, string&gt; values; // they are values I suppose\nprivate IList&lt;Entity&gt; entities;\n</code></pre>\n\n<p>Next, we find method <em>Parse</em>. </p>\n\n<ul>\n<li>the signature is already changed by interface implementation</li>\n<li>Only use <code>i</code> as an index in an iterator</li>\n<li>perform <code>i.Split(')')</code> once</li>\n<li><code>Dict</code> is already renamed previously</li>\n</ul>\n\n<blockquote>\n<pre><code>public void Parse(string[] txtFile) {\n foreach (var i in txtFile) {\n if (i.Contains(\")\")) {\n var tile = i.Split(')')[0].ToCharArray()[0];\n var name = i.Split(')')[1].Trim();\n Dict.Add(tile, name);\n }\n }\n}\n</code></pre>\n</blockquote>\n\n<p>After changing the method:</p>\n\n<pre><code> public void Parse(IEnumerable&lt;string&gt; segments) {\n foreach (var segment in segments) {\n if (segment.Contains(\")\")) {\n var tokens = segment.Split(')');\n var tile = tokens[0].ToCharArray()[0];\n var name = tokens[1].Trim();\n values.Add(tile, name);\n }\n }\n }\n</code></pre>\n\n<p>Next up, method <code>Add</code>. This is a black-box for us. Consider the fact <code>ParseHelper</code> adds cyclomatic complexity to your API. Perhaps its code should be divided into the other classes.</p>\n\n<blockquote>\n<pre><code>public void Add(List&lt;char&gt; map) {\n ParseHelper.AddEntities(map, Dict, Entities);\n}\n</code></pre>\n</blockquote>\n\n<pre><code>public void Add(IList&lt;char&gt; map) {\n // not convinced about ParseHelper ..\n ParseHelper.AddEntities(map, values, entities);\n}\n</code></pre>\n\n<p>And finally, <code>ParserFacade</code>.</p>\n\n<p>Let's have a look at the singleton. </p>\n\n<ul>\n<li>A private constructor, well done. </li>\n<li>A nested static class holding the singleton, <a href=\"https://csharpindepth.com/articles/singleton\" rel=\"nofollow noreferrer\">good design</a>. </li>\n<li>all caps -> take it easy: <code>INSTANCE</code> -> <code>Instance</code> </li>\n<li>a getter method is best substituted with a property getter: <code>getInstance()</code> -> <code>Instance</code></li>\n</ul>\n\n<blockquote>\n<pre><code>private ParserFacade() { }\n\nprivate static class ParserFacadeHolder {\n public static readonly ParserFacade INSTANCE = new ParserFacade();\n}\n\npublic static ParserFacade getInstance() {\n return ParserFacadeHolder.INSTANCE;\n}\n</code></pre>\n</blockquote>\n\n<p>After changes:</p>\n\n<pre><code>private static class ParserFacadeHolder {\n public static readonly ParserFacade Instance = new ParserFacade();\n}\n\npublic static ParserFacade Instance =&gt; ParserFacadeHolder.Instance;\n</code></pre>\n\n<p>I don't like this helper class, but I did expect it to be static. Here you used an instance.</p>\n\n<blockquote>\n <p><code>private ParseHelper parseHelper;</code></p>\n</blockquote>\n\n<p>Public state detected. Code smell?</p>\n\n<blockquote>\n<pre><code> public ParseExits exits;\n public ParseObstacles obstacles;\n public ParsePlatforms platforms;\n public ParseCustomers customers;\n</code></pre>\n</blockquote>\n\n<p>Method <code>StartParse</code>:</p>\n\n<p>What bothers me here is the inconsistent and convoluted design of parsing behavior. <code>ParseExits</code> (and sibling classes) can parse the file. But then the facade calls the infamous helper to parse additional data, to then forward this data to <code>ParseExits</code>. This design is too complex in behavioral complexity.</p>\n\n<blockquote>\n<pre><code> exits = new ParseExits();\n exits.Parse(file);\n exits.Add(ParseHelper.GetAllTiles(file));\n</code></pre>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T21:11:09.257", "Id": "430317", "Score": "0", "body": "The thing is about ParseHelper.cs I have some code which all the sibling classes uses. So was not sure if it was a good idea to add some sort of class which could hold these methods they all use. Wanted to avoid copy+pasting" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T21:12:40.967", "Id": "430318", "Score": "0", "body": "@user10829235 There is a bit of everything in that class :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T21:30:10.923", "Id": "430319", "Score": "1", "body": "Code smell I guess. Damn.\n\nI thought a lot about the public/private scenario. I wanted my GameLoop in another file to be able to call Parser.exit.Entities or Parser.exit.Dict so I left it public purposely. But thank you for being aware of the small details. This is what really helps me" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T20:29:42.193", "Id": "222374", "ParentId": "222369", "Score": "3" } } ]
{ "AcceptedAnswerId": "222374", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T19:04:16.360", "Id": "222369", "Score": "3", "Tags": [ "c#", "design-patterns", "parsing" ], "Title": "Parsing Game Entities" }
222369
<p>As part of small MIDI library i've implemented the conversion of a VLQ (<a href="https://en.wikipedia.org/wiki/Variable-length_quantity" rel="nofollow noreferrer">variable length quantity</a>) for <code>byte[] -&gt; bigint</code> and <code>bigint -&gt; byte[]</code>. Even though the maximum value for a MIDI VLQ is defined as <code>0x0FFF_FFFF</code> i've decided to allow larger values for the moment.</p> <p>If there are any improvements for the code, coding style, ..., please let me know.</p> <p>Implementation:</p> <pre><code>module VariableLengthQuantity /// &lt;summary&gt; /// Reads a variable length quantity from the given byte array and returns a tuple /// of the value of the quantity and the remaining bytes of the array. /// &lt;/summary&gt; /// &lt;param name="bytes"&gt;A byte array that contains the variable length quantity.&lt;/param&gt; /// &lt;returns&gt;A tuple of the quantity as &lt;see cref="BigInteger"/&gt; and the remaining bytes of th array.&lt;/returns&gt; /// &lt;exception cref="System.ArgumentException"&gt; /// &lt;paramref name="bytes"/&gt; has a length of 0 or /// &lt;paramref name="bytes"/&gt; is missing the end byte of the quentity. /// &lt;/exception&gt; let toBigInt (bytes: byte[]) = if bytes.Length = 0 then invalidArg "bytes" "The byte array from which to build the variable length quantity has to have at least one element." let quantityBytes = // Modified version of Array.takeWhile. // Take all bytes from the array until a byte is found that // has the 7th bit not set (byte &amp;&amp;&amp; 0x80 = 0). let mutable count = 0 while count &lt; bytes.Length &amp;&amp; (bytes.[count] &amp;&amp;&amp; 0x80uy) &gt; 0uy do count &lt;- count + 1 if count = bytes.Length then invalidArg "bytes" ("Cannot fetch the bytes for a variable length quantity from the given " + "byte array because the end byte of the quantity is missing.") count &lt;- count + 1 Array.sub bytes 0 count let mutable quantity = 0I let mutable currentBit = 0 for i = quantityBytes.Length - 1 downto 0 do let quantityByte = quantityBytes.[i] // Bit 7 is a status bit. for bit = 0 to 6 do quantity &lt;- quantity ||| (bigint (int ((quantityByte &gt;&gt;&gt; bit) &amp;&amp;&amp; 1uy)) &lt;&lt;&lt; currentBit) currentBit &lt;- currentBit + 1 quantity, bytes.[quantityBytes.Length..] /// &lt;summary&gt; /// Creates a variable length quantity byte array from the given &lt;see cref="BigInteger" /&gt; /// &lt;/summary&gt; /// &lt;param name="value"&gt;The value for which to create the variable length quantity byte array.&lt;/param&gt; /// &lt;returns&gt;The created byte array.&lt;/returns&gt; /// &lt;exception cref="System.ArgumentException"&gt; /// &lt;paramref name="value"/&gt; is negative. /// &lt;/exception&gt; let toByteArray (value: bigint) = if value.Sign = -1 then invalidArg "value" "The given value must be greater or equal to zero." match value with | x when x &lt;= 127I -&gt; [| byte value |] | _ -&gt; let valueBytes = value.ToByteArray() let mutable resultBitIndex = 0 let mutable resultHelper = 0I for i = 0 to valueBytes.Length - 1 do let byte = valueBytes.[i] for bit = 0 to 7 do match resultBitIndex % 8 with | 7 -&gt; // Last bit of a byte is reserved for the more bytes indicator. // Therefore the last bit of of each byte is skipped and the the last bit of the // following byte is set to 1. Because the last bit is skipped the first byte // always has 0 as value for the 7th bit. resultBitIndex &lt;- resultBitIndex + 1 resultHelper &lt;- resultHelper ||| bigint (1 &lt;&lt;&lt; (resultBitIndex + 7)) | _ -&gt; () resultHelper &lt;- resultHelper ||| (bigint (int ((byte &gt;&gt;&gt; bit) &amp;&amp;&amp; 1uy)) &lt;&lt;&lt; resultBitIndex) resultBitIndex &lt;- resultBitIndex + 1 // Result array has to be MSB first. resultHelper.ToByteArray() |&gt; Array.rev |&gt; Array.skipWhile (fun x -&gt; x = 0x80uy) </code></pre> <p>Test cases:</p> <pre><code>open Microsoft.VisualStudio.TestTools.UnitTesting open System [&lt;TestClass&gt;] type TestVariableLengthQuantity () = [&lt;TestMethod&gt;] [&lt;ExpectedException(typeof&lt;ArgumentException&gt;)&gt;] member this.ToBigInt_ArrayLengthZero () = VariableLengthQuantity.toBigInt [||] |&gt; ignore [&lt;TestMethod&gt;] [&lt;ExpectedException(typeof&lt;ArgumentException&gt;)&gt;] member this.ToBigInt_ArrayMissingEndByte () = VariableLengthQuantity.toBigInt [| 0x82uy; 0x84uy; 0x80uy; 0x8Auy |] |&gt; ignore [&lt;TestMethod&gt;] member this.ToBigInt_SingleByte () = let result1, rem1 = VariableLengthQuantity.toBigInt [| 0x00uy |] let result2, rem2 = VariableLengthQuantity.toBigInt [| 0x71uy |] let result3, rem3 = VariableLengthQuantity.toBigInt [| 0x52uy |] let result4, rem4 = VariableLengthQuantity.toBigInt [| 0x44uy |] Assert.AreEqual(0I, result1) Assert.AreEqual(0, rem1.Length) Assert.AreEqual(113I, result2) Assert.AreEqual(0, rem2.Length) Assert.AreEqual(82I, result3) Assert.AreEqual(0, rem3.Length) Assert.AreEqual(68I, result4) Assert.AreEqual(0, rem4.Length) [&lt;TestMethod&gt;] member this.ToBigInt_MultipleBytes () = let result1, rem1 = VariableLengthQuantity.toBigInt [| 0x94uy; 0xE4uy; 0x6Buy |] let result2, rem2 = VariableLengthQuantity.toBigInt [| 0xDBuy; 0xB6uy; 0x01uy |] let result3, rem3 = VariableLengthQuantity.toBigInt [| 0x83uy; 0xFEuy; 0x7Fuy |] Assert.AreEqual(340_587I, result1) Assert.AreEqual(0, rem1.Length) Assert.AreEqual(1_497_857I, result2) Assert.AreEqual(0, rem2.Length) Assert.AreEqual(65_407I, result3) Assert.AreEqual(0, rem3.Length) [&lt;TestMethod&gt;] member this.ToBigInt_TrailingBytes () = let result1, rem1 = VariableLengthQuantity.toBigInt [| 0x94uy; 0xE4uy; 0x6Buy; 0xFFuy; 0x59uy |] let result2, rem2 = VariableLengthQuantity.toBigInt [| 0xDBuy; 0xB6uy; 0x01uy; 0x12uy |] Assert.AreEqual(340_587I, result1) Assert.AreEqual(2, rem1.Length) Assert.AreEqual(1_497_857I, result2) Assert.AreEqual(1, rem2.Length) [&lt;TestMethod&gt;] [&lt;ExpectedException(typeof&lt;ArgumentException&gt;)&gt;] member this.ToByteArray_NegativeNumber () = VariableLengthQuantity.toByteArray -1I |&gt; ignore [&lt;TestMethod&gt;] member this.ToByteArray () = let bytes1 = VariableLengthQuantity.toByteArray 0I let bytes2 = VariableLengthQuantity.toByteArray 113I let bytes3 = VariableLengthQuantity.toByteArray 65_407I let bytes4 = VariableLengthQuantity.toByteArray 340_587I let bytes5 = VariableLengthQuantity.toByteArray 1_497_857I let expected1 = [| 0x00uy |] let expected2 = [| 0x71uy |] let expected3 = [| 0x83uy; 0xFEuy; 0x7Fuy |] let expected4 = [| 0x94uy; 0xE4uy; 0x6Buy |] let expected5 = [| 0xDBuy; 0xB6uy; 0x01uy |] CollectionAssert.AreEqual(expected1, bytes1) CollectionAssert.AreEqual(expected2, bytes2) CollectionAssert.AreEqual(expected3, bytes3) CollectionAssert.AreEqual(expected4, bytes4) CollectionAssert.AreEqual(expected5, bytes5) </code></pre>
[]
[ { "body": "<p>It seems to work well with the provided test cases. The obvious objection when talking about functional programming in F# is to the use of <code>mutable</code> variables and loops. Instead it is common to use higher order functions and recursion.</p>\n\n<p>For inspiration, below is <code>toBigInt</code> in a more functional style:</p>\n\n<pre><code>let toBigInt (bytes: byte[]) =\n if bytes.Length = 0 then\n invalidArg \"bytes\" \"The byte array from which to build the variable length quantity has to have at least one element.\"\n\n let numUsableBytes = \n let indexOpt = bytes |&gt; Array.tryFindIndex (fun b -&gt; b &amp;&amp;&amp; 0x80uy = 0uy)\n match indexOpt with \n | Some(index) -&gt; index + 1\n | None -&gt; invalidArg \"bytes\" (\"Cannot fetch the bytes for a variable length quantity from the given \" +\n \"byte array because the end byte of the quantity is missing.\")\n\n let rec composeNum num bit resultBit byte =\n if bit = 7 then num, resultBit\n else\n composeNum (num ||| (bigint (int ((byte &gt;&gt;&gt; bit) &amp;&amp;&amp; 1uy)) &lt;&lt;&lt; resultBit)) (bit + 1) (resultBit + 1) byte\n\n let result, _ = \n Array.foldBack \n (fun byte (num, resultBit) -&gt; (composeNum num 0 resultBit byte)) \n (bytes |&gt; Array.take numUsableBytes)\n (0I, 0)\n result, bytes.[numUsableBytes..]\n</code></pre>\n\n<p>In the same way it is relatively easy to change <code>toByteArray</code> too.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T14:15:29.880", "Id": "430390", "Score": "1", "body": "While writing the functions i already thought that the `mutable` stuff would'nt be the optimal way, but since i'm not that familiar with all higher order functions yet, i really appreciate the feedback." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T18:51:16.877", "Id": "430430", "Score": "2", "body": "@Streamline: If you come from with a OO background as I do, it can be tempting to jump to the well known - but we then miss the best part of F# and FP. It took me some time to get familiar with the \"awkward\" concept of immutability, but the effort has paid off - also in respect to my understanding of OOP." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T08:24:03.067", "Id": "222388", "ParentId": "222370", "Score": "1" } } ]
{ "AcceptedAnswerId": "222388", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T19:16:51.153", "Id": "222370", "Score": "4", "Tags": [ "algorithm", "f#", "audio" ], "Title": "Convert to and from variable length quantities" }
222370
<p>In <a href="https://github.com/pc-magas/tcp_command" rel="nofollow noreferrer">https://github.com/pc-magas/tcp_command</a> as an attempt to learn C++ I made a simplistic TCP server in GNU/Linux that will receives simple "commands" in ASCII form. Each command ends with '\n' and a user can send multiple commands at once.</p> <p>My background is a web developer in php using symfony mostly and sometimes PSR-4 autoloading and heavily on Depedency Injection. Also I use Node.js as well and because in the future I plan to use C++ as Node.js/electron bindings I try to learn C++.</p> <p>The application is in this github <a href="https://github.com/pc-magas/tcp_command" rel="nofollow noreferrer"><code>repo</code></a>:</p> <p>My <code>main.cpp</code> file is simple like as hell:</p> <pre><code>#include&lt;iostream&gt; #include&lt;string&gt; #include "socket/network.h" #include "socket/simple_command.h" #include "tools/command_parser.h" int main(){ try{ CommandParser p; SimpleCommandHandler c(10,&amp;p); TCPServer server(7070, "127.0.0.1", &amp;c); server.listen(); }catch(Exception e){ std::cout&lt;&lt; e.getMessage(); return -1; } return 0; } </code></pre> <p>And I use the following implementations for the TCP server:</p> <ul> <li><code>network.h</code></li> </ul> <pre><code>#ifndef HTTP_NETWORK #define HTTP_NETWORK #include &lt;string&gt; #include &lt;arpa/inet.h&gt; //Dummy Value to be changed #define MAXPENDING 5 class Exception { public: Exception(std::string message):message(message){} std::string getMessage(); private: std::string message; }; class NetworkException:public Exception { public: NetworkException(std::string message) : Exception(message) {} }; //A generic way to handle Network Connections class ConnectionHandler { public: /** * @return 0 Close Connection 1 do not close */ virtual int handle(int socketid) = 0; }; class TCPServer { public: TCPServer(int port, std::string address, ConnectionHandler *c); ~TCPServer(); void listen(); private: int port; //Socket file Descriptor int servSock; struct sockaddr_in ServAddr; ConnectionHandler *c = NULL; }; #endif </code></pre> <ul> <li><code>network.cpp</code></li> </ul> <pre><code>#include"network.h" #include &lt;sys/socket.h&gt; #include &lt;arpa/inet.h&gt; #include &lt;unistd.h&gt; #include&lt;iostream&gt; #include&lt;cstring&gt; #include&lt;string&gt; #include &lt;thread&gt; std::string Exception::getMessage(){ return this-&gt;message; } TCPServer::TCPServer(int port,std::string address, ConnectionHandler *c) :port(port){ if ((this-&gt;servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) &lt; 0) { throw NetworkException(std::string("SOCKET Error: could not create basic socket")); } memset(&amp;this-&gt;ServAddr,0,sizeof(this-&gt;ServAddr)); ServAddr.sin_family = AF_INET; ServAddr.sin_addr.s_addr = inet_addr(address.c_str()); ServAddr.sin_port = htons(port); if (bind(this-&gt;servSock, (struct sockaddr *) &amp;this-&gt;ServAddr, sizeof(this-&gt;ServAddr)) &lt; 0) { throw NetworkException(std::string("SOCKET Error: Failed to bind a socket")); } if (::listen(this-&gt;servSock, MAXPENDING) &lt; 0) { throw NetworkException(std::string("SOCKET Error: Failed to Listen")); } if(c==NULL){ throw Exception("You should provice a connection Handler"); } this-&gt;c=c; } void TCPServer::listen(){ struct sockaddr_in ClntAddr; /* Client address */ socklen_t clntLen= (socklen_t)sizeof(ClntAddr); int clntSock; /* Socket descriptor for client */ //@todo Dummy Logic Depedency Inject Socket Handler for (;;) { if ((clntSock = accept(servSock, (struct sockaddr *) &amp;ClntAddr, &amp;clntLen)) &lt; 0) { std::cout&lt;&lt;"Failed to fetch"&lt;&lt;std::endl; } std::cout &lt;&lt; "Handling client: " &lt;&lt; inet_ntoa(ClntAddr.sin_addr) &lt;&lt; std::endl; send(clntSock, "WELCOME\n", 6, 0); this-&gt;c-&gt;handle(clntSock); close(clntSock); } } TCPServer::~TCPServer(){ close(this-&gt;servSock); } </code></pre> <p>Also, I have the <code>SimpleCommandHandler</code> to handle my network traffic:</p> <ul> <li><code>simple_command.h</code>: (I use the flag <code>NETWORK_TELNET</code> as a leftover from initial plan to use the telnet protocol.)</li> </ul> <pre><code>#ifndef NETWORK_TELNET #define NETWORK_TELNET #include"network.h" #include"../tools/command_parser.h" #include&lt;string&gt; class SimpleCommandHandler:public ConnectionHandler{ public: SimpleCommandHandler(int readBufferSize, CommandParser *commandParser):buffLen(readBufferSize),parser(commandParser){}; ~SimpleCommandHandler(){}; int handle(int socketid); private: std::string readLine(int socketid); void sendResult(int socketid, std::string result); const int buffLen; CommandParser* parser; }; #endif </code></pre> <ul> <li><code>simple_command.cpp</code>:</li> </ul> <pre><code>#include "simple_command.h" #include&lt;string&gt; #include&lt;cstring&gt; #include&lt;iostream&gt; std::string SimpleCommandHandler::readLine(int socketid){ int recvSize=0; char buffer[this-&gt;buffLen]; memset(&amp;buffer,'\0',this-&gt;buffLen*sizeof(char)); //reCeive a Byte less in order each received data to be a string (Initialized as an empty String with \0 encding char) while ((recvSize = recv(socketid, buffer, this-&gt;buffLen-1, 0)) &gt; 0) { this-&gt;parser-&gt;addData(socketid,(const char*) buffer,strlen(buffer)); memset(buffer,'\0',this-&gt;buffLen*sizeof(char)); //Reset Data in order to avoid Garbage } return this-&gt;parser-&gt;getCommand(socketid); } void SimpleCommandHandler::sendResult(int socketid, std::string result){ send(socketid, result.c_str(), result.length() + 1, 0); } int SimpleCommandHandler::handle(int socketid){ std::string command = this-&gt;readLine(socketid); std::cout &lt;&lt; "Command Sent: " &lt;&lt; command &lt;&lt; std::endl; if(command.compare("exit") == 0){ this-&gt;sendResult(socketid,"Thank You Very Much\nExiting\n"); return 0; } else { this-&gt;sendResult(socketid,"Wrong Command\n"); } return 1; } </code></pre> <p>And in the end the utility for parsing the commands:</p> <ul> <li><code>command_parser.h</code>:</li> </ul> <pre><code>#ifndef COMMANDPARSER #define COMMANDPARSER #include&lt;string&gt; #include&lt;map&gt; class CommandParser{ private: std::map&lt;int,std::string&gt; commandBuff; public: std::string getCommand(int socketid); void addData(int socketid, const char* data, int length); }; #endif </code></pre> <p>*<code>command_parser.cpp</code>:</p> <pre><code>#include "command_parser.h" #include&lt;string&gt; #include&lt;iostream&gt; void CommandParser::addData(int socketid, const char* data, int length){ this-&gt;commandBuff[socketid].append(data,length); } std::string CommandParser::getCommand(int socketid){ std::size_t pos = this-&gt;commandBuff[socketid].find('\n'); if (pos==std::string::npos){ return ""; } std::string fetchedCommand = this-&gt;commandBuff[socketid].substr(0,pos); this-&gt;commandBuff[socketid] = this-&gt;commandBuff[socketid].substr(pos+1); return fetchedCommand; } </code></pre> <p>I would like to hear the comments towards my code, mabe by me, the c++ virgin ;).</p>
[]
[ { "body": "<p>I'll start the serious bug, then work inwards from <code>main()</code>.</p>\n<hr />\n<h1>Biggest bug</h1>\n<p>The biggest problem with the code is that it only reads one command from each connection, leaving any subsequent commands for the next client to execute. Even if we read more commands, by looping until <code>handle()</code> returns false before closing the client socket, this still won't help if the client has commands after <code>exit</code>:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>netcat -4 localhost 7070 &lt;&lt;&lt;$'exit\\nstop\\n'\n</code></pre>\n<hr />\n<h1><code>main()</code></h1>\n<blockquote>\n<pre><code>}catch(Exception e){\n std::cout&lt;&lt; e.getMessage();\n return -1;\n}\n</code></pre>\n</blockquote>\n<p>-1 is a strange exit code - we normally use small <em>positive</em> numbers.</p>\n<p>Error messages should go to <code>std::cerr</code>, not to standard output.</p>\n<p>Most C++ runtime environments already do something similar - there's probably no need to catch all exceptions at this level.</p>\n<blockquote>\n<pre><code> TCPServer server(7070, &quot;127.0.0.1&quot;, &amp;c);\n</code></pre>\n</blockquote>\n<p>Port and bind address should be configurable - ideally from command arguments, but a short-term start would be to define file-scope constants.</p>\n<blockquote>\n<pre><code>return 0;\n</code></pre>\n</blockquote>\n<p>Although not wrong, there's little benefit to explicitly returning zero from <code>main()</code>.</p>\n<p>For a real Internet server, you'll normally want to daemonize the process (but retain user option to run in foreground, for debugging).</p>\n<hr />\n<h1><code>TCPServer::TCPServer()</code></h1>\n<blockquote>\n<pre><code>TCPServer::TCPServer(int port,std::string address, ConnectionHandler *c)\n:port(port){\n</code></pre>\n</blockquote>\n<p>We initialize <code>port</code>, but not the other members of the object.</p>\n<p>That said, <code>port</code> and <code>ServAddr</code> don't need to be members - they are used only to create <code>servSock</code> and then never used again. Member <code>c</code> needs a better name - remember, variable name verbosity should be proportional to the scope of the variable; members need more descriptive names than two-line locals. Here's how I'd write the initializer list:</p>\n<pre><code>TCPServer::TCPServer(int port, const std::string&amp;, ConnectionHandler *connection)\n : servSock(socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)),\n connection(connection)\n{\n</code></pre>\n<p>Perhaps consider passing a <em>reference</em> to the connection handler. This will have the side effect of making <code>TCPServer</code> non-assignable - but you probably want it to be non-copyable anyway.</p>\n<p>It's idiomatic to use the truthiness of a pointer to test for null pointers:</p>\n<pre><code>if (!connection) {\n throw Exception(&quot;You should provide a connection Handler&quot;); \n}\n</code></pre>\n<p>There's a lot of unnecessary qualification of members with <code>this-&gt;</code> - you should almost never need to use <code>this</code> with <code>-&gt;</code> like that.</p>\n<p><code>memset</code> should be <code>std::memset</code>.</p>\n<blockquote>\n<pre><code> throw NetworkException(std::string(&quot;SOCKET Error: could not create basic socket&quot;));\n</code></pre>\n</blockquote>\n<p>No need to explicitly construct <code>std::string</code> there - there's an implicit constructor that will be used. It might be nice to incorporate the error message from <code>errno</code> (use <code>errstr()</code> to create a human-friendly version). That applies to the checks after <code>bind()</code> and <code>listen()</code>, too.</p>\n<hr />\n<h1><code>TCPServer::listen</code></h1>\n<blockquote>\n<pre><code> std::cout &lt;&lt; &quot;Handling client: &quot; &lt;&lt; inet_ntoa(address.sin_addr) &lt;&lt; std::endl;\n</code></pre>\n</blockquote>\n<p>Status messages should go to <code>std::clog</code>, not standard output. And for this error, we don't want to use the bad client socket descriptor, so return immediately.</p>\n<blockquote>\n<pre><code> send(client, &quot;WELCOME\\n&quot;, 6, 0);\n</code></pre>\n</blockquote>\n<p>Why write only <code>WELCOM</code> here? We probably want to send all 8 characters:</p>\n<pre><code> static auto constexpr message = &quot;WELCOME\\n&quot;;\n send(client, message, std::strlen(message), 0);\n</code></pre>\n<hr />\n<h1><code>SimpleCommandHandler::readLine()</code></h1>\n<blockquote>\n<pre><code>char buffer[buffLen];\n</code></pre>\n</blockquote>\n<p>That's not valid C++, as <code>buffLen</code> isn't a compile-time constant expression. We could perhaps use a vector for this:</p>\n<pre><code>std::vector&lt;char&gt; storage(buffLen);\nchar *const buffer = storage.data();\n</code></pre>\n<p>Again, <code>std::memset()</code> needs its namespace qualification.</p>\n<p>Remember that <code>sizeof</code> reports in units of <code>char</code>, so <code>sizeof (char)</code> must be 1 by definition. Adding <code>* sizeof (char)</code> just serves to make the code harder to read.</p>\n<p>There's no need to null out the whole of the buffer every time we read a line. All that's required is to pass the correct length to the <code>addData()</code>:</p>\n<pre><code>std::string SimpleCommandHandler::readLine(int socketid){\n int recvSize=0;\n char buffer[buffLen];\n\n while ((recvSize = recv(socketid, buffer, buffLen-1, 0)) &gt; 0) {\n parser-&gt;addData(socketid, buffer, recvSize);\n }\n\n return parser-&gt;getCommand(socketid);\n}\n</code></pre>\n<p>I'm not sure why we need a map of client socket to command string, since we have a <em>blocking server</em>, that services only one client at a time. And since we don't clear the command buffer after a client disconnects, we end up executing old commands of previous sessions when a new client connects. (Part of the cause is that <code>readLine()</code> actually reads entire transmissions, not necessarily a single line).</p>\n<hr />\n<h1><code>CommandParser::getCommand()</code></h1>\n<p>Instead of repeatedly looking up in the map, it's better to make a local reference to the command buffer:</p>\n<pre><code>std::string CommandParser::getCommand(int socketid)\n{\n std::string&amp; buffer = commandBuff[socketid];\n\n std::size_t pos = buffer.find('\\n');\n if (pos == std::string::npos) {\n return &quot;&quot;;\n }\n\n std::string fetchedCommand = buffer.substr(0, pos);\n buffer = buffer.substr(pos+1);\n return fetchedCommand;\n}\n</code></pre>\n<hr />\n<h1>Other bits and pieces</h1>\n<p><code>ConnectionHandler</code> has virtual methods; that's normally a sign that you want a <code>virtual</code> destructor. Conversely, <code>SimpleCommandHandler</code> doesn't need to specify that its destructor is virtual. It should declare its override with <code>override</code>, though.</p>\n<p><code>Exception</code> would be simpler if it just inherits <code>std::exception</code> - or better, <code>std::runtime_error</code>.</p>\n<hr />\n<h1>Modified code</h1>\n<p>Incorporating some of the improvements suggested above (and all as one source file, because that's how I built it):</p>\n<pre><code>#include &lt;string&gt;\n#include &lt;map&gt;\n\nclass CommandParser\n{\nprivate:\n std::map&lt;int,std::string&gt; commandBuff = {};\n\npublic:\n std::string getCommand(int socketid);\n void addData(int socketid, const char* data, int length);\n void clear(int socketid);\n};\n\n//A generic way to handle Network Connections\nclass ConnectionHandler\n{\npublic:\n virtual ~ConnectionHandler() = default;\n\n /**\n * @return true if we should read more commands, else false\n */\n virtual bool handle(int socketid) = 0;\n\n bool finished = false;\n};\n\nclass SimpleCommandHandler: public ConnectionHandler\n{\npublic:\n SimpleCommandHandler(std::size_t readBufferSize, CommandParser&amp; commandParser)\n : buffLen(readBufferSize),\n parser(commandParser)\n {}\n SimpleCommandHandler(const SimpleCommandHandler&amp;) = delete;\n bool handle(int socketid) override;\n\nprivate:\n std::string readLine(int socketid);\n void sendResult(int socketid, std::string result);\n const std::size_t buffLen;\n CommandParser&amp; parser;\n};\n\n#include &lt;string&gt;\n\n//Dummy Value to be changed\n#define MAXPENDING 5\n\nclass Exception\n{\npublic:\n Exception(std::string message)\n : message(message)\n {}\n std::string getMessage();\nprivate:\n std::string message;\n};\n\n#include &lt;cstring&gt;\n#include &lt;exception&gt;\n\nclass NetworkException: public std::runtime_error {\npublic:\n NetworkException(std::string message)\n : std::runtime_error(message + &quot;: &quot; + std::strerror(errno))\n {}\n};\n\nclass TCPServer\n{\npublic:\n TCPServer(int port, const std::string&amp;, ConnectionHandler&amp; connection);\n ~TCPServer();\n void listen();\nprivate:\n //Socket file Descriptor\n int socket;\n ConnectionHandler&amp; connection;\n};\n\n\nint main()\n{\n CommandParser p;\n SimpleCommandHandler connection(10, p);\n TCPServer server(7070, &quot;127.0.0.1&quot;, connection);\n server.listen();\n}\n\n\n#include &lt;sys/socket.h&gt;\n#include &lt;arpa/inet.h&gt;\n#include &lt;unistd.h&gt;\n\n#include &lt;cstring&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n\nstd::string Exception::getMessage() {\n return message;\n}\n\nTCPServer::TCPServer(int port, const std::string&amp; address, ConnectionHandler&amp; connection)\n : socket(::socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)),\n connection(connection)\n{\n if (socket &lt; 0) {\n throw NetworkException(&quot;SOCKET Error: could not create basic socket&quot;);\n }\n\n struct sockaddr_in s_address; // server address\n std::memset(&amp;s_address, 0, sizeof s_address);\n s_address.sin_family = AF_INET;\n s_address.sin_addr.s_addr = ::inet_addr(address.c_str());\n s_address.sin_port = ::htons(port);\n\n if (::bind(socket, (struct sockaddr*)&amp;s_address, sizeof s_address) &lt; 0) {\n throw NetworkException(&quot;SOCKET Error: Failed to bind a socket&quot;);\n }\n\n if (::listen(socket, MAXPENDING) &lt; 0) {\n throw NetworkException(&quot;SOCKET Error: Failed to listen&quot;);\n }\n\n}\n\nvoid TCPServer::listen()\n{\n while (!connection.finished) {\n struct sockaddr_in address; /* Client address */\n socklen_t length = sizeof address;\n int client; /* Socket descriptor for client */\n if ((client = ::accept(socket, (struct sockaddr*)&amp;address, &amp;length)) &lt; 0) {\n std::cerr &lt;&lt; &quot;Failed to accept: &quot; &lt;&lt; std::strerror(errno) &lt;&lt; std::endl;\n return;\n }\n std::clog &lt;&lt; &quot;Handling client: &quot; &lt;&lt; ::inet_ntoa(address.sin_addr) &lt;&lt; std::endl;\n\n static auto constexpr message = &quot;WELCOME\\n&quot;;\n send(client, message, std::strlen(message), 0);\n\n while (connection.handle(client))\n ;\n close(client);\n\n // discard remaining received commands\n\n }\n}\n\nTCPServer::~TCPServer()\n{\n ::close(socket);\n}\n\n\n#include &lt;cstring&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n\nstd::string SimpleCommandHandler::readLine(int socketid)\n{\n std::vector&lt;char&gt; storage(buffLen);\n char *const buffer = storage.data();\n\n int recvSize = 0;\n while ((recvSize = ::recv(socketid, buffer, buffLen-1, 0)) &gt; 0) {\n parser.addData(socketid, buffer, recvSize);\n }\n\n return parser.getCommand(socketid);\n}\n\nvoid SimpleCommandHandler::sendResult(int socketid, std::string result) {\n send(socketid, result.c_str(), result.length() + 1, 0);\n}\n\nbool SimpleCommandHandler::handle(int socketid)\n{\n std::string command = readLine(socketid);\n std::clog &lt;&lt; &quot;Command received: &quot; &lt;&lt; command &lt;&lt; std::endl;\n\n if (command == &quot;exit&quot;) {\n sendResult(socketid, &quot;Thank You Very Much.\\nBye.\\n&quot;);\n parser.clear(socketid);\n return false;\n } else if (command == &quot;stop&quot;) {\n sendResult(socketid, &quot;Server exiting.\\n&quot;);\n parser.clear(socketid);\n finished = true;\n return false;\n } else {\n sendResult(socketid, &quot;Ignoring command '&quot; + command + &quot;'.\\n&quot;);\n return true;\n }\n}\n\n#include &lt;string&gt;\n\nvoid CommandParser::addData(int socketid, const char* data, int length) {\n commandBuff[socketid].append(data,length);\n}\n\nstd::string CommandParser::getCommand(int socketid)\n{\n std::string&amp; buffer = commandBuff[socketid];\n\n std::size_t pos = buffer.find('\\n');\n if (pos == std::string::npos) {\n return &quot;&quot;;\n }\n\n std::string fetchedCommand = buffer.substr(0, pos);\n buffer = buffer.substr(pos+1);\n return fetchedCommand;\n}\n\nvoid CommandParser::clear(int socketid)\n{\n commandBuff[socketid].clear();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T19:27:07.587", "Id": "430831", "Score": "0", "body": "For `ConnectionHandler` I thought to use a `shared_ptr`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T19:36:14.470", "Id": "430832", "Score": "0", "body": "Also, why are you using the nekudayim papadayim symbol before POSIX methods calls such as `bind` one?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T19:46:54.033", "Id": "430836", "Score": "0", "body": "Also before you asked I attempted to handle each connection via some threads should I place the while loop in `connection.handle(client)` inside the thread?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T17:24:38.790", "Id": "222478", "ParentId": "222371", "Score": "3" } } ]
{ "AcceptedAnswerId": "222478", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T19:23:21.800", "Id": "222371", "Score": "3", "Tags": [ "c++", "beginner", "parsing", "tcp" ], "Title": "A simple TCP command executer" }
222371
<p>Here is a practice exercise — <a href="https://automatetheboringstuff.com/chapter7/" rel="noreferrer"><em>Regex version of <code>strip()</code></em></a> <span class="math-container">\$-\$</span></p> <blockquote> <p><em>Write a function that takes a string and does the same thing as the <code>strip()</code> string method. If no other arguments are passed other than the string to strip, then whitespace characters will be removed from the beginning and end of the string. Otherwise, the characters specified in the second argument to the function will be removed from the string.</em></p> </blockquote> <p>I have written the following code. Is there any better way to write it? Any feedback is highly appreciated.</p> <pre><code>import re def regex_strip(s, chars = None): if chars == None: strip_left = re.compile(r'^\s*') strip_right = re.compile(r'\s*$') s = re.sub(strip_left, "", s) s = re.sub(strip_right, "", s) else: strip_left = re.compile(r'^[' + re.escape(chars) + r']*') strip_right = re.compile(r'[' + re.escape(chars) + r']*$') s = re.sub(strip_left, "", s) s = re.sub(strip_right, "", s) return s </code></pre> <p>Here is an example output -</p> <pre><code>s = '.* alphabetatheta *4453 +-' print(regex_strip(s, '.+-*')) &gt;&gt;&gt; alphabetatheta *4453 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T19:44:11.587", "Id": "430308", "Score": "3", "body": "It all depends whether \\s includes all the white space characters. There are tons of them: https://en.wikipedia.org/wiki/Whitespace_character" } ]
[ { "body": "<p>If you call <code>regex_strip(s, \"\")</code>, you will get:</p>\n\n<blockquote>\n <p>re.error: unterminated character set at position 0</p>\n</blockquote>\n\n<p>because neither <code>^[]</code> nor <code>[]$</code> is a valid regular expression. You could avoid this by using <code>if not chars:</code> instead of <code>if chars == None:</code>.</p>\n\n<hr>\n\n<p>There is no need to <code>re.compile()</code> your regular expressions; you aren't saving the compiled patterns anywhere for re-use.</p>\n\n<hr>\n\n<p>You can simplify your logic by using the reg-ex to capture the middle, non-stripped portion of the string, instead of doing two replacements for the start and end trim operations:</p>\n\n<pre><code>import re\n\ndef regex_strip(s, chars = None):\n\n if chars:\n trim = '[' + re.escape(chars) + ']*'\n else:\n trim = r'\\s*'\n\n return re.fullmatch(f\"{trim}(.*?){trim}\", s).group(1)\n</code></pre>\n\n<hr>\n\n<p>I'm not sure the point of asking you to write your own <code>strip()</code> function is to delegate the task to the reg-ex engine. It seems like going out and buying a sledge hammer when the problem is to build a nut cracker.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T14:53:44.460", "Id": "430770", "Score": "0", "body": "Maybe something of value to some on the subject of regex: https://www.regular-expressions.info ; also the man page *`regex(7)`* (which is less detailed but still maybe of value; there is of course also *`regex(3)`* but that's for C)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T20:40:27.853", "Id": "222375", "ParentId": "222372", "Score": "9" } }, { "body": "<p>DRY. Both branches do identical <code>re.sub</code>s. Take them out:</p>\n\n<pre><code>if chars is None:\n strip_left = re.compile(r'^\\s*')\n strip_right = re.compile(r'\\s*$')\nelse:\n strip_left = re.compile(r'^[' + re.escape(chars) + r']*')\n strip_right = re.compile(r'[' + re.escape(chars) + r']*$')\ns = re.sub(strip_left, \"\", s) \ns = re.sub(strip_right, \"\", s)\nreturn s\n</code></pre>\n\n<p>I recommend to go one step further, and unify the computation of <code>strip_*</code>:</p>\n\n<pre><code>if chars is None:\n chars = string.whitespace\n\nstrip_left = re.compile(r'^[' + re.escape(chars) + r']*')\nstrip_right = re.compile(r'[' + re.escape(chars) + r']*$')\ns = re.sub(strip_left, \"\", s) \ns = re.sub(strip_right, \"\", s)\nreturn s\n</code></pre>\n\n<hr>\n\n<p>It is <a href=\"https://stackoverflow.com/questions/3257919/what-is-the-difference-between-is-none-and-none\">recommended</a> to compare against <code>None</code> as <code>chars is None</code> rather than using <code>==</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T20:43:06.593", "Id": "222376", "ParentId": "222372", "Score": "8" } } ]
{ "AcceptedAnswerId": "222375", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T19:39:17.947", "Id": "222372", "Score": "5", "Tags": [ "python", "performance", "python-3.x", "regex", "reinventing-the-wheel" ], "Title": "Regex version of strip() - Ch. 7 Automate the Boring Stuff" }
222372
<p>The goal of this problem is to determine if a string with brackets is valid. Below is a summary of the question from careercup.</p> <p>Check if string s is valid based on brackets</p> <pre><code>"(({{}}))" is a valid s "{[]}" is a valid s "[{[}]]" is not valid </code></pre> <p>I know this is a rather basic exercise. I am looking for feedback on whether my solution is sound and efficient. I would also like to know if my code is clean. Also is there too much for a 45 minute interview? The solution is shown below.</p> <pre><code>public class Question_ValidStringWithBrackets { public bool IsValidBracketString(String s, BracketValidator validator = null) { if (s == null) throw new ArgumentNullException("A string is required"); if (validator == null) validator = BracketValidator.CreateDefaultValidator(); Stack&lt;char&gt; openStack = new Stack&lt;char&gt;(); foreach (var curBracket in s) { if (validator.IsOpen(curBracket)) { openStack.Push(curBracket); } else if (openStack.Count == 0 || validator.IsMatchingPair(openStack.Pop(), curBracket)) { return false; } } return openStack.Count == 0; } public class BracketValidator { private HashSet&lt;char&gt; openBrackets = new HashSet&lt;char&gt;(); private Dictionary&lt;char, char&gt; closedOpenedPair = new Dictionary&lt;char, char&gt;(); public void AddPair(char open, char close) { if (char.IsWhiteSpace(open) || char.IsWhiteSpace(close)) throw new ArgumentException("A bracket must be specified. An empty character is not allowed."); if (openBrackets.Contains(open) || openBrackets.Contains(close)) throw new ArgumentException("Brackets exist already."); if (closedOpenedPair.ContainsKey(open) || closedOpenedPair.ContainsKey(close)) throw new ArgumentException("Brackets exist already."); openBrackets.Add(open); closedOpenedPair.Add(close, open); } public Boolean IsOpen(char open) { return openBrackets.Contains(open); } public bool IsMatchingPair(char open, char close) { return closedOpenedPair.TryGetValue(open, out char actualClose) &amp;&amp; actualClose == close; } public static BracketValidator CreateDefaultValidator() { var validator = new BracketValidator(); validator.AddPair('{', '}'); validator.AddPair('[', ']'); validator.AddPair('(', ')'); return validator; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T09:16:04.527", "Id": "430363", "Score": "1", "body": "Trying to follow on my phone and think you have a bug. Should the else-if branch's condition be negated? Ie `! validator.IsMatchingPair(...) `" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T10:08:55.967", "Id": "430713", "Score": "0", "body": "@pinkfloydx33 Good catch! I was looking at my phone thinking this looks like a bug, but my test work. Yes, there should be a negation. I also had to do closedOpenedPair.Add(open, close) instead of (close, open)" } ]
[ { "body": "<h3>Guard conditions</h3>\n\n<p><code>ArgumentNullException</code> is typically thrown on incorrect usage of the API. It is not an end-user exception, so I would not bother with an exception message.</p>\n\n<blockquote>\n <p><code>throw new ArgumentNullException(\"A string is required\");</code></p>\n</blockquote>\n\n<pre><code>throw new ArgumentNullException(nameof(s)); // perhaps rename 's' to 'input' or 'value'\n</code></pre>\n\n<p>For the <code>ArgumentException</code> instances you throw, I would also add the <code>nameof(parameterName)</code> to the constructor. A decent error message is relevant here, so keep the message.</p>\n\n<p>You have a guard on whitespace. I don't see this in the spec. Is this a requirement? If not, allow white space as either an open or close bracket.</p>\n\n<blockquote>\n <p><code>if (char.IsWhiteSpace(open) || char.IsWhiteSpace(close))</code></p>\n</blockquote>\n\n<p>The next guard checks on duplicate registrations. An alternative policy is to ignore a registration if already registered. This depends on whether you want your API to be error-prone or act as a sandbox for consumers.</p>\n\n<blockquote>\n <p><code>if (openBrackets.Contains(open) || openBrackets.Contains(close))</code></p>\n</blockquote>\n\n<p>I'm missing a guard condition. I doubt <code>open</code> and <code>close</code> can be the same.</p>\n\n<pre><code>if (open == close) // throw ..\n</code></pre>\n\n<h3>Readability</h3>\n\n<p>You could substitute some <code>if</code> statements with a ternary operator.</p>\n\n<pre><code>s = s ?? throw new ArgumentNullException(nameof(s));\nvalidator = validator ?? BracketValidator.CreateDefaultValidator();\n</code></pre>\n\n<p>Redundant type declarations can be replaced by <code>var</code>. Unlike javascript, <code>var</code> is ok in C#.</p>\n\n<blockquote>\n <p><code>Stack&lt;char&gt; openStack = new Stack&lt;char&gt;();</code></p>\n</blockquote>\n\n<pre><code>var openStack = new Stack&lt;char&gt;();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T23:50:36.520", "Id": "430332", "Score": "1", "body": "Good stuff. I do have to get used to using var more often. What are your thoughts on using the actual type for function returns? For example, List<string> ids = GetStudentIds(). Depending on the implementation this could be guid, int, string, and etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T23:52:56.740", "Id": "430333", "Score": "2", "body": "@RockLeeroy That's an interesting question! I don't mind using a declarative type in such case. However, I'm usually greedy in the usage of `var`, and would still use it here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T23:58:31.153", "Id": "430335", "Score": "1", "body": "I would only use the declarative type when I specifically want my variable to have another scope than the return type of the function. For instance, `IList<string> ids = GetStudentIds();` (when this methods returns `List<string>`)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T07:39:12.097", "Id": "430356", "Score": "2", "body": "...I'm from the _`var`-everywhere-party_ :-P so I prefer `var ids = (IList<string>)GetStudentIds();` (mainly for consistency reasons with other `var`s so the code is alligned) I even do `var car = default(Car)` when I need an uninitialized variable. Because of this, I have _many_ _fans_ here ;-P" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T22:44:00.243", "Id": "222383", "ParentId": "222378", "Score": "3" } } ]
{ "AcceptedAnswerId": "222383", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T21:38:47.597", "Id": "222378", "Score": "3", "Tags": [ "c#", "programming-challenge", "strings", "interview-questions", "balanced-delimiters" ], "Title": "CareerCup (Bloomberg): Check if string is valid based on brackets" }
222378
<p>This is a translatable password validator for <code>django</code>, based on <code>zxcvbn-python</code> and available with <code>pip</code>. zxcvbn is a password strength estimator inspired by password crackers. It permits to prevent users to have to choose a password with one upper case, one special character and a number, but still check the password strengh and provide input to help the user choose a password.</p> <p>The project is available <a href="https://github.com/Pierre-Sassoulas/django-zxcvbn-password-validator" rel="nofollow noreferrer">here</a> on Github, and the package is on Pypi <a href="https://pypi.org/project/django-zxcvbn-password-validator/" rel="nofollow noreferrer">here</a>.</p> <p>I check the code with the <code>pre-commit</code> framework, using <code>black</code>, <code>isort</code>, <code>flake8</code> and <code>pylint</code> as git hooks. I'm testing it with <code>tox</code> and <code>coverage</code> locally, and I set up <code>travis</code> and <code>codacy</code> online. The translation is done with <code>django-rosetta</code>. I tried to make a clear readme with examples to explain what the package does in detail, there are also tests covering the code base entirely.</p> <p>I would be really interested in remarks about the whole project, code, tests, documentation, tooling, set up, design, complexity to onboard, and basically everything around the project that could make it better.</p> <p>But this makes a lot of things to review so the main part of the code is the following :</p> <pre><code>from django.conf import settings from django.core.exceptions import ImproperlyConfigured, ValidationError from django.utils.translation import ugettext_lazy as _ from zxcvbn import zxcvbn from django_zxcvbn_password_validator.settings import DEFAULT_MINIMAL_STRENGTH from django_zxcvbn_password_validator.translate_zxcvbn_text import ( translate_zxcvbn_text, translate_zxcvbn_time_estimate, ) class ZxcvbnPasswordValidator: def __init__(self, min_length=1, zxcvbn_implementation=zxcvbn): self.min_length = min_length self.zxcvbn_implementation = zxcvbn_implementation password_minimal_strength = getattr(settings, "PASSWORD_MINIMAL_STRENGTH", None) if password_minimal_strength is None: # Compatibility with a typo in previous version. password_minimal_strength = getattr( settings, "PASSWORD_MINIMAL_STRENTH", None ) if password_minimal_strength is None: password_minimal_strength = DEFAULT_MINIMAL_STRENGTH self.password_minimal_strength = password_minimal_strength self.__check_password_minimal_strength() def __check_password_minimal_strength(self): error_msg = "ZxcvbnPasswordValidator need an integer between 0 and 4 " error_msg += "for PASSWORD_MINIMAL_STRENGTH in the settings." try: not_an_int = ( int(self.password_minimal_strength) != self.password_minimal_strength ) except ValueError: not_an_int = True if not_an_int: error_msg += f" (not '{self.password_minimal_strength}', " error_msg += f"a {self.password_minimal_strength.__class__.__name__})" raise ImproperlyConfigured(error_msg) if self.password_minimal_strength &lt; 0 or self.password_minimal_strength &gt; 4: error_msg += f" ({self.password_minimal_strength} is not in [0,4])" raise ImproperlyConfigured(error_msg) def validate(self, password, user=None): def append_translated_feedback(old_feedbacks, feedback_type, new_feedbacks): if new_feedbacks: if isinstance(new_feedbacks, str): new_feedbacks = [new_feedbacks] for new_feedback in new_feedbacks: old_feedbacks.append( f"{feedback_type} : {translate_zxcvbn_text(new_feedback)}" ) user_inputs = [] if user: for value in user.__dict__.values(): user_inputs.append(value) results = self.zxcvbn_implementation(password, user_inputs=user_inputs) password_strength = results["score"] if password_strength &lt; self.password_minimal_strength: crack_time = results["crack_times_display"] offline_time = crack_time["offline_slow_hashing_1e4_per_second"] feedbacks = [ "{} {}".format( _("Your password is too guessable :"), _("It would take an offline attacker %(time)s to guess it.") % {"time": translate_zxcvbn_time_estimate(offline_time)}, ) ] append_translated_feedback( feedbacks, _("Warning"), results["feedback"]["warning"] ) append_translated_feedback( feedbacks, _("Advice"), results["feedback"]["suggestions"] ) raise ValidationError(feedbacks) def get_help_text(self): expectations = _("We expect") if self.password_minimal_strength == 0: expectations += " {}".format( _("nothing: you can use any password you want.") ) return expectations expectations += " {}".format(_("a password that cannot be guessed")) hardness = { 1: _("by your familly or friends."), 2: _("by attackers online."), 3: _("without access to our database."), 4: _("without a dedicated team and an access to our database."), } expectations += " {}".format(hardness.get(self.password_minimal_strength)) return "{} {} {} {}".format( _("There is no specific rule for a great password,"), _("however if your password is too easy to guess,"), _("we will tell you how to make a better one."), expectations, ) </code></pre> <p>Translation is done here :</p> <pre><code>import logging from django.utils.translation import ugettext_lazy as _ LOGGER = logging.getLogger(__file__) def translate_zxcvbn_text(text): """ This PR would make it cleaner, but it will also be very slow to be integrated in python-zxcvbn and we want this to work now : https://github.com/dropbox/zxcvbn/pull/124 """ i18n = { "Use a few words, avoid common phrases": _( "Use a few words, avoid common phrases" ), "No need for symbols, digits, or uppercase letters": _( "No need for symbols, digits, or uppercase letters" ), "Add another word or two. Uncommon words are better.": _( "Add another word or two. Uncommon words are better." ), "Straight rows of keys are easy to guess": _( "Straight rows of keys are easy to guess" ), "Short keyboard patterns are easy to guess": _( "Short keyboard patterns are easy to guess" ), "Use a longer keyboard pattern with more turns": _( "Use a longer keyboard pattern with more turns" ), 'Repeats like "aaa" are easy to guess': _( 'Repeats like "aaa" are easy to guess' ), 'Repeats like "abcabcabc" are only slightly harder to guess than "abc"': _( 'Repeats like "abcabcabc" are only slightly harder to guess than "abc"' ), "Avoid repeated words and characters": _("Avoid repeated words and characters"), 'Sequences like "abc" or "6543" are easy to guess': _( 'Sequences like "abc" or "6543" are easy to guess' ), "Avoid sequences": _("Avoid sequences"), "Recent years are easy to guess": _("Recent years are easy to guess"), "Avoid recent years": _("Avoid recent years"), "Avoid years that are associated with you": _( "Avoid years that are associated with you" ), "Dates are often easy to guess": _("Dates are often easy to guess"), "Avoid dates and years that are associated with you": _( "Avoid dates and years that are associated with you" ), "This is a top-10 common password": _("This is a top-10 common password"), "This is a top-100 common password": _("This is a top-100 common password"), "This is a very common password": _("This is a very common password"), "This is similar to a commonly used password": _( "This is similar to a commonly used password" ), "A word by itself is easy to guess": _("A word by itself is easy to guess"), "Names and surnames by themselves are easy to guess": _( "Names and surnames by themselves are easy to guess" ), "Common names and surnames are easy to guess": _( "Common names and surnames are easy to guess" ), "Capitalization doesn't help very much": _( "Capitalization doesn't help very much" ), "All-uppercase is almost as easy to guess as all-lowercase": _( "All-uppercase is almost as easy to guess as all-lowercase" ), "Reversed words aren't much harder to guess": _( "Reversed words aren't much harder to guess" ), "Predictable substitutions like '@' instead of 'a' don't help very much": _( "Predictable substitutions like '@' instead of 'a' don't help very much" ), } translated_text = i18n.get(text) if translated_text is None: # zxcvbn is inconsistent, sometime there is a dot, sometime not translated_text = i18n.get(text[:-1]) if translated_text is None: LOGGER.warning( "No translation for '%s' or '%s', update the generatei18ndict command.", text, text[:-1], ) return text return translated_text def translate_zxcvbn_time_estimate(text): def replace_dict(text, times): for original, translated in times.items(): text = text.replace(original, str(translated)) return text if text == "less than a second": return _("less than a second") text = text.replace("centuries", str(_("centuries"))) plural_times = { "seconds": _("seconds"), "minutes": _("minutes"), "hours": _("hours"), "days": _("days"), "months": _("months"), "years": _("years"), } times = { "second": _("second"), "minute": _("minute"), "hour": _("hour"), "day": _("day"), "month": _("month"), "year": _("year"), } # Plural first to avoid replacing "hours" by _("hour") + s # Adding an 's' does not mean plural in every language text = replace_dict(text, plural_times) text = replace_dict(text, times) return text </code></pre> <p>This part of the code is mostly generated by the following management command (done in case <code>zxcvbn</code> add string or remove string so it's easier to make new a new translation) :</p> <pre><code># -*- coding: utf-8 -*- from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Will generate what the i18n dict for the translate_zxcvbn_text function" def handle(self, *args, **options): existings_messages = [ "Use a few words, avoid common phrases", "No need for symbols, digits, or uppercase letters", "Add another word or two. Uncommon words are better.", "Straight rows of keys are easy to guess", "Short keyboard patterns are easy to guess", "Use a longer keyboard pattern with more turns", 'Repeats like "aaa" are easy to guess', 'Repeats like "abcabcabc" are only slightly harder to guess than "abc"', "Avoid repeated words and characters", 'Sequences like "abc" or "6543" are easy to guess', "Avoid sequences", "Recent years are easy to guess", "Avoid recent years", "Avoid years that are associated with you", "Dates are often easy to guess", "Avoid dates and years that are associated with you", "This is a top-10 common password", "This is a top-100 common password", "This is a very common password", "This is similar to a commonly used password", "A word by itself is easy to guess", "Names and surnames by themselves are easy to guess", "Common names and surnames are easy to guess", "Capitalization doesn't help very much", "All-uppercase is almost as easy to guess as all-lowercase", "Reversed words aren't much harder to guess", "Predictable substitutions like '@' instead of 'a' don't help very much", ] msg = " i18n = {" for message in existings_messages: message = message.replace("'", "\\'") msg += f" '{message}': _('{message}')," msg += " }" msg += "Please copy paste the following in the translate_zxcvbn_text function," msg += " then use 'python manage.py makemessages'." print(msg) </code></pre> <p>This is the whole code, everything else is either tests, documentation or packaging.</p> <p>Thank you in advance for any remarks or advices !</p>
[]
[ { "body": "<p>Some suggestions:</p>\n\n<ul>\n<li>The translations strings are duplicated, and are present in code rather than as a separate text file. I've not done i18n yet, but that seems strange. I would expect a .po file containing text and translations.</li>\n<li><code>user_imputs</code> should be <code>user_inputs</code></li>\n<li>You mix four types of string formatting: <code>+</code>/<code>+=</code>, <code>%</code>, <code>.format()</code> and f-strings. The first two I believe are generally discouraged in favour of the last two.</li>\n<li><code>add_list_of_advices</code> is confusing. The two calls to it each use a different branch of the method, and there is <em>no</em> common code between the branches. it looks like inlining it would actually make the code more readable.</li>\n<li>This is just personal style, but on the last major project my colleagues and I have found that 80 character width is too limiting - you end up having to artificially abbreviate names (which reduces readability) or use some very clunky line splitting (also reducing readability) far too often. We found that we can fit two files side by side with 120 character line widths on a modern screen; your experience may vary.</li>\n</ul>\n\n<p>In any case, this is some of the best code I've seen on this site!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T13:31:16.967", "Id": "430386", "Score": "1", "body": "Thank you very much! As you found a typo, it prompted me to check other typos as well. Well, it looks like I'll have to handle compatibility with old typos, because there is a typo in \"strength\" everywhere, including the variable defined by users in the setting file \"PASSWORD_MINIMAL_STREN**G**TH\" :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T14:52:08.017", "Id": "430397", "Score": "0", "body": "@Pierre.Sassoulas Also \"__check_password_minimal_streng**t**h\", in case you haven't caught it yet." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T10:20:00.717", "Id": "222389", "ParentId": "222379", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T22:00:25.500", "Id": "222379", "Score": "6", "Tags": [ "python", "security" ], "Title": "Password validator making zxcvbn easy to use with Django" }
222379
<p>I have two code snippets, doing exactly the same thing and both get the job done: </p> <ol> <li>use defaults</li> <li>use from config</li> </ol> <p>Which is cleaner to use in golang and why?</p> <p>first option:</p> <pre><code> package main import ( "fmt" "strings" ) func main() { fmt.Println(getShCfg(Cfg{}), "\n================") fmt.Println(getShCfg(Cfg{"8MB", "4MB"}), "\n================") fmt.Println(getShCfg(Cfg{"8MB", ""}), "\n================") fmt.Println(getShCfg(Cfg{"", "4MB"}), "\n================") } type Cfg struct { A, B string } func getShCfg(c Cfg) string { var out []string la := "l_sh_dit conf_data 7MB" lb := "l_sh_dit cert_data 3MB" if len(c.A) &gt; 0 { out = append(out, "l_sh_dit conf_data " + c.A) } else { out = append(out, la) } if len(c.B) &gt; 0 { out = append(out, "l_sh_dit cert_data "+c.B) } else { out = append(out, lb) } return strings.Join(out, ";\n\r") + ";" } </code></pre> <p>second option: </p> <pre><code> package main import ( "fmt" "strings" ) func main() { fmt.Println(getShCfg(Cfg{}), "\n================") fmt.Println(getShCfg(Cfg{"8MB", "4MB"}), "\n================") fmt.Println(getShCfg(Cfg{"8MB", ""}), "\n================") fmt.Println(getShCfg(Cfg{"", "4MB"}), "\n================") } type Cfg struct { A, B string } func getShCfg(c Cfg) string { out := []string{ getCfgProp("l_sh_dit conf_data", c.A, "7MB"), getCfgProp("l_sh_dit cert_data", c.B, "3MB"), } return strings.Join(out, ";\n\r") + ";" } func getCfgProp(key, val, def string) string { if len(val) &gt; 0 { return key + " " + val } return key + " " + def } </code></pre> <p>I would prefer the second option as it is more scalable i.e. if there are more than 2 parameters (two if else) so in this case I'm skipping on another <code>if-else</code> in the code …</p> <p>But in case there are only 2 parameters, is it worth to create a helper function? </p> <p>Also if there is a better/cleaner approach to achieve it with Golang please let me know</p>
[]
[ { "body": "<p>None of the above. Rewrite the first option in readable form. For example,</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\ntype Cfg struct{ A, B string }\n\nfunc getShCfg(c Cfg) string {\n var out []string\n\n msg := \"l_sh_dit conf_data \"\n if len(c.A) &gt; 0 {\n msg += c.A\n } else {\n msg += \"7MB\"\n }\n out = append(out, msg)\n\n msg = \"l_sh_dit cert_data \"\n if len(c.B) &gt; 0 {\n msg += c.B\n } else {\n msg += \"3MB\"\n }\n out = append(out, msg)\n\n return strings.Join(out, \";\\n\\r\") + \";\"\n}\n\nfunc main() {\n sep := \"\\n================\"\n for _, cfg := range []Cfg{\n {},\n {\"8MB\", \"4MB\"},\n {\"8MB\", \"\"},\n {\"\", \"4MB\"},\n } {\n fmt.Println(getShCfg(cfg), sep)\n }\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>l_sh_dit conf_data 7MB;\nl_sh_dit cert_data 3MB; \n================\nl_sh_dit conf_data 8MB;\nl_sh_dit cert_data 4MB; \n================\nl_sh_dit conf_data 8MB;\nl_sh_dit cert_data 3MB; \n================\nl_sh_dit conf_data 7MB;\nl_sh_dit cert_data 4MB; \n================\n</code></pre>\n\n<p>Factoring out common code and data simplifies and highlights the structure of the problem.</p>\n\n<p>To generalize we typically need three to seven cases. We have two. Configuration parameters usually contain a wide range of information and data types and structures. Idle speculation is not useful.</p>\n\n<p>We have safely encapsulated the problem. As we learn more, we can easily revise the code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T16:30:09.960", "Id": "222415", "ParentId": "222390", "Score": "2" } } ]
{ "AcceptedAnswerId": "222415", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T10:32:07.457", "Id": "222390", "Score": "2", "Tags": [ "beginner", "comparative-review", "go", "configuration" ], "Title": "Fetching configuration or default value" }
222390
<p>What I want is getting all names (first, middle, last) of the users along with each of their total hours of work which will be calculated by the SQL statement: <code>CAST(SUM(timediff(dateTimeOut,dateTimeIn) as time)</code>.</p> <p>I was able to achieve this with two queries, but somehow, I feel that this is inefficient (?):</p> <pre><code>$sql = "SELECT id, firstName, middleName, lastName FROM users_info"; $result = $pdo-&gt;query($sql); $rows = array(); while($row = $result-&gt;fetch()){ $time = $pdo-&gt;query( "SELECT CAST(SUM(timediff(dateTimeOut, dateTimeIn)) as time) as totalHoursWorked FROM users_time WHERE user_id = {$row['id']}" )-&gt;fetch(); $row['totalHoursWorked'] = $time['totalHoursWorked']; $rows[] = $row; } echo json_encode($rows); </code></pre> <p>I'll use the json data for a DataTable.</p> <pre><code>users_info table +----+-----------+------------+----------+ | id | firstName | middleName | lastName | +----+-----------+------------+----------+ | 1 | Isabelle | Luna | Ibarra | | 2 | George | Boston | Everett | | 3 | Skyler | Land | Cohen | +----+-----------+------------+----------+ users_time table: +---------+---------+---------------------+--------------------+ | time_id | user_id | dateTimeIn | dateTimeOut | +---------+---------+---------------------+--------------------+ | 1 | 1 | 2019-06-14 00:00:00 | 2019-06-16 09:00:0 | | 2 | 1 | 2019-06-15 00:00:00 | 2019-06-16 08:00:0 | | 3 | 2 | 2019-06-14 00:00:00 | 2019-06-16 09:30:0 | | 4 | 2 | 2019-06-15 00:00:00 | 2019-06-16 08:30:0 | | 5 | 3 | 2019-06-16 00:00:00 | 2019-06-16 09:00:0 | +---------+---------+---------------------+--------------------+ </code></pre> <p>db-fiddle link : <a href="https://www.db-fiddle.com/f/vpozKbVoXxPoGzcsBkLL36/0" rel="nofollow noreferrer">https://www.db-fiddle.com/f/vpozKbVoXxPoGzcsBkLL36/0</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T11:35:55.057", "Id": "430375", "Score": "1", "body": "Could you provide us the DDL and insert statements?" } ]
[ { "body": "<blockquote>\n <p><code>$sql = \"SELECT id, firstName, middleName, lastName FROM users_info\";</code></p>\n</blockquote>\n\n<p>and </p>\n\n<blockquote>\n<pre><code>\"SELECT CAST(SUM(timediff(dateTimeOut, dateTimeIn)) \n as time) as totalHoursWorked\n FROM users_time WHERE user_id = {$row['id']}\"\n</code></pre>\n</blockquote>\n\n<p>can be merged into a single query:</p>\n\n<pre><code> SELECT r.id, r.totalHoursWorked, t.firstName, t.middleName, t.lastName \n FROM (\n SELECT q.id, SUM(q.hoursWorked) as totalHoursWorked \n FROM (\n SELECT \n id\n , timestampdiff(second, dateTimeIn, dateTimeOut) / 3600.0 as hoursWorked\n FROM users_info\n INNER JOIN users_time ON user_id = id\n ) q\n GROUP BY id\n ) r\n INNER JOIN users_info t on t.id = r.id;\n</code></pre>\n\n<p>Yielding:</p>\n\n<pre><code>id totalHoursWorked firstName middleName lastName\n1 0.3 Isabelle Luna Ibarra\n2 0.3 George Boston Everett\n3 0.15 Skyler Land Cohen\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T11:30:44.060", "Id": "430373", "Score": "0", "body": "It's only returning a single row\n`[{\"id\":40,\"firstName\":\"Employee 406\",\"middleName\":\"Generated\",\"lastName\":\"Auto\",\"totalHoursWorked\":\"225:00:00\"}]`\n\ninstead of this:\n\n\n`[{\"id\":40,\"firstName\":\"Employee 406\",\"middleName\":\"Generated\",\"lastName\":\"Auto\",\"totalHoursWorked\":\"09:00:00\"},{\"id\":41,\"firstName\":\"Employee 692\",\"middleName\":\"Generated\",\"lastName\":\"Auto\",\"totalHoursWorked\":\"152:00:00\"},{\"id\":42,\"firstName\":\"Employee 399\",\"middleName\":\"Generated\",\"lastName\":\"Auto\",\"totalHoursWorked\":\"64:00:00\"}]` Basically, it was adding all the rows in the table." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T14:57:52.920", "Id": "430398", "Score": "0", "body": "@Gene Adrian San Luis Your timediff was not outputted in hours." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T11:19:12.097", "Id": "222394", "ParentId": "222392", "Score": "1" } }, { "body": "<p>Assuming that the id's in <code>users_info</code> exist in <code>users_time</code>, INNER JOIN (or just JOIN) is the way to merge the tables. If id's in <code>user_info</code> might not exist in <code>users_time</code> then use LEFT JOIN to allow <code>null</code> values in <code>totalHoursWorked</code>.</p>\n\n<p>Assuming you want all four columns' data to be included in your echo'ed json string (your posted code isn't do that), you can just <code>fetchAll()</code> directly into your <code>json_encode()</code> and echo it -- all at once.</p>\n\n<p>SQL: (<a href=\"https://www.db-fiddle.com/f/uqWbJAgpHc3hVTPt6Xqomf/0\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>$sql = \"SELECT i.id,\n MAX(i.firstName),\n MAX(i.middleName),\n MAX(i.lastName),\n CAST(SUM(TIMEDIFF(t.dateTimeOut, t.dateTimeIn)) AS TIME) AS totalHoursWorked\n FROM users_info i\n INNER JOIN users_time t ON i.id = t.user_id\n GROUP BY i.id\";\n$query = $pdo-&gt;query($sql);\necho json_encode($query-&gt;fetchAll(PDO::FETCH_ASSOC));\n</code></pre>\n\n<p>If you are truly only returning a single column (<code>totalHoursWorked</code>) without any of the other data, then I don't see the need to involve the <code>user_info</code> table at all.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T14:30:41.017", "Id": "430393", "Score": "0", "body": "I added the db-fiddle link: https://www.db-fiddle.com/f/vpozKbVoXxPoGzcsBkLL36/0" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T14:34:05.080", "Id": "430395", "Score": "0", "body": "Updated my answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T12:23:33.993", "Id": "222401", "ParentId": "222392", "Score": "2" } } ]
{ "AcceptedAnswerId": "222401", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T11:11:47.920", "Id": "222392", "Score": "1", "Tags": [ "php", "sql", "t-sql" ], "Title": "Combining two queries in one" }
222392
<p>This code is a mix of the same question one time rotating to the right and one time to the left. I tried to simplify the code since I'm struggling with all of the indexing here.</p> <p><a href="https://leetcode.com/problems/rotate-image/" rel="nofollow noreferrer">https://leetcode.com/problems/rotate-image/</a></p> <p><a href="https://www.geeksforgeeks.org/rotate-matrix-90-degree-without-using-extra-space-set-2/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/rotate-matrix-90-degree-without-using-extra-space-set-2/</a></p> <blockquote> <p>Rotate the image by 90 degrees (clockwise).</p> <p>Note:</p> <p>You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.</p> <p>Example 1:</p> <p>Given input matrix = [ [1,2,3], [4,5,6], [7,8,9] ],</p> <p>rotate the input matrix in-place such that it becomes: [ [7,4,1],<br> [8,5,2], [9,6,3] ] Example 2:</p> <p>Given input matrix = [ [ 5, 1, 9,11], [ 2, 4, 8,10], [13, 3, 6, 7], [15,14,12,16] ], </p> <p>rotate the input matrix in-place such that it becomes: [ [15,13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7,10,11] ]</p> </blockquote> <p>Please review this code as I am trying to simplify it in order to be able to have a good short solution for a coding interview. I can't memorize this logic of course I just want to have a solid simple solution in mind.</p> <pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ArrayQuestions { /// &lt;summary&gt; /// https://www.geeksforgeeks.org/inplace-rotate-square-matrix-by-90-degrees/ /// &lt;/summary&gt; [TestClass] public class RotateMatrix90 { [TestMethod] public void RotateClockWise2x2Test() { int[][] mat = { new[]{0,1}, new[]{2,3}, }; int[][] expected = { new[]{2,0}, new[]{3,1} }; RotateClockWise(mat); int size = mat.GetLength(0); for (int r = 0; r &lt; size; r++) { for (int c = 0; c &lt; size; c++) { Assert.AreEqual(expected[r][c], mat[r][c]); } } } [TestMethod] public void RotateClockWise3x3Test() { int[][] mat = { new[]{1, 2, 3}, new[]{4, 5, 6}, new[]{7, 8, 9} }; //tranpose then flip horizotally //1,4,7 //2,5,8 //3,6,9 int[][] expected = { new[]{7, 4, 1}, new[]{8, 5, 2}, new[]{9, 6, 3} }; RotateClockWise(mat); int size = mat.Length; for (int r = 0; r &lt; size; r++) { for (int c = 0; c &lt; size; c++) { Assert.AreEqual(expected[r][c], mat[r][c]); } } } [TestMethod] public void RotateCounterClockWise2x2Test() { int[][] mat = { new[]{0,1}, new[]{2,3}, }; //0,2 //1 3 int[][] expected = { new[]{1,3}, new[]{0,2} }; RotateCounterClockWise(mat); int size = mat.GetLength(0); for (int r = 0; r &lt; size; r++) { for (int c = 0; c &lt; size; c++) { Assert.AreEqual(expected[r][c], mat[r][c]); } } } [TestMethod] public void RotateCounterClockWise3x3Test() { int[][] mat = { new[]{1, 2, 3}, new[]{4, 5, 6}, new[]{7, 8, 9} }; //tranpose then flip horizotally //1,4,7 //2,5,8 //3,6,9 int[][] expected = { new[]{3, 6, 9}, new[]{2, 5, 8}, new[]{1, 4, 7} }; RotateCounterClockWise(mat); int size = mat.Length; for (int r = 0; r &lt; size; r++) { for (int c = 0; c &lt; size; c++) { Assert.AreEqual(expected[r][c], mat[r][c]); } } } //moving elements clockwise (90 degrees to the right) public void RotateClockWise(int[][] matrix) { Transpose(matrix); ReverseRows(matrix); } //moving elements counter clockwise public void RotateCounterClockWise(int[][] matrix) { Transpose(matrix); ReverseCols(matrix); } private void Transpose(int[][] matrix) { int size = matrix.Length; for (int i = 0; i &lt; size; i++) { for (int j = i; j &lt; size; j++) { Swap(ref matrix[i][j], ref matrix[j][i]); } } } private void ReverseRows(int[][] matrix) { for (int i = 0; i &lt; matrix.Length; i++) { for (int j = 0, k = matrix.Length - 1; j &lt; k; j++, k--) { Swap(ref matrix[i][j], ref matrix[i][k]); } } } private void ReverseCols(int[][] matrix) { for (int i = 0; i &lt; matrix.Length; i++) { for (int j = 0, k = matrix.Length - 1; j &lt; k; j++, k--) { Swap(ref matrix[k][i], ref matrix[j][i]); } } } void Swap(ref int i, ref int j) { int temp = i; i = j; j = temp; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T11:45:13.443", "Id": "430376", "Score": "1", "body": "You are mixing your code in with the unit tests. I suggest to make seperate classes for tests and code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T12:19:06.270", "Id": "430378", "Score": "1", "body": "I had to visit the link to find the spec of `n`x`n`. You could make our task helping you easier if you include crucial information in the question :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T13:30:39.307", "Id": "430385", "Score": "1", "body": "You have solved this one time before, just for a [normal array](https://codereview.stackexchange.com/questions/220769/geeksforgeeks-rotate-matrix-by-90-degrees/220796#220796) - with a O(n^2) complexity. You can easily change that solution for a jagged array and to handle clock wise rotation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T18:52:23.340", "Id": "430431", "Score": "1", "body": "@henrik I hate this solution. The indexing there is too complex." } ]
[ { "body": "<h3>Performance</h3>\n\n<p>Time complexity for your algorithm is <span class=\"math-container\">\\$O(N²+N²/2)\\$</span>. If you find a way to combine <code>Transpose</code> <span class=\"math-container\">\\$O(N²)\\$</span> and <code>ReverseCols</code> <span class=\"math-container\">\\$O(N²/2)\\$</span> in a single run, you could get <span class=\"math-container\">\\$O(N²)\\$</span> in worst case.</p>\n\n<p>Edit: given Henrik's good eye, you have already come up with a solution before that adheres to the optimized complexity. So, apply it here.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T12:17:37.747", "Id": "222400", "ParentId": "222395", "Score": "1" } } ]
{ "AcceptedAnswerId": "222400", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T11:23:11.277", "Id": "222395", "Score": "1", "Tags": [ "c#", "programming-challenge", "interview-questions", "matrix", "complexity" ], "Title": "Rotate matrix clockWise and counter clockWise" }
222395
<p>I am new to C programming and wrote the following algorithm for the calculation of the Jacobi Symbol. Though there are some faster versions of this algorithm available I am only looking for some feedback on my coding style. I should mention that I was taught to ONLY USE ONE return statement in functions and NOT to use things like <code>break</code>, <code>continue</code> or <code>go-to</code>. This is a "philosophy" I also believe in.</p> <ol> <li>How could I improve?</li> <li>Is anything unclearly formulated?</li> </ol> <p>One point I could think of would be to use "long long" instead of only "long" since this algorithm is used in cryptography and should thus be suited for very large integers. </p> <p>Any kind of feedback would be welcome.</p> <p>EDIT: There is still a (commented) print statement in this code that helps to visualize the algorithm.</p> <pre class="lang-c prettyprint-override"><code> #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; /* +***************************************************************************** * Function Name: jacobi * Function: Calculate the Jacobi Symbol * Arguments: a = numerator n = denominator * Return: (a|n) * Notes: This function evaluates the Jacobi Symbol for two integers a and n. It is based on the same idea as the Euclidean alogrithm for the gcd. The bit complexity is O(log^2(p)). -****************************************************************************/ short jacobi(long a, long n) { // The two if-conditions below terminate the function in case of wrong inputs, i.e.: n &lt; 3 or 2 | n. if (n&lt;3) { printf("Wrong input for the Jacobi Symbol: The denominator has to be greater than 2.\n"); exit(0); } if (n%2 == 0) { printf("Wrong input for the Jacobi Symbol: The denominator has to be coprime to 2.\n"); exit(0); } long n_mod8 = 0; short result = 1; short condition = 1; while (condition == 1) { // printf("(%d|%d) and result = %d \n", a, n, result); a = a % n; // The The if-condition below utilises the fact that (0|n) = 0. if (a == 0) { condition = 0; result = 0; } else { // The while-loop below utilises the Second Supplement // to extract the 2’s out of a. while (a % 2 == 0) { a = a / 2; n_mod8 = n % 8; if (n_mod8 == 3 || n_mod8 == 5) { result = -result; } } // The if-condition below utilises the fact (1|n) = 1. if ( a == 1) { condition = 0; } else { // This else-condition utilises the Law of // Quadratic Reciprocity to transfer (a|n) to (n|a). long tmp = a; a = n; n = tmp; if (a % 4 == 3 &amp;&amp; n % 4 == 3) { result = -result; } } } } return result; } int main() { printf("%d", jacobi(4852777,12408107)); return 0; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T15:12:01.933", "Id": "430405", "Score": "1", "body": "As chux indicated below, it would be better if the variables result and condition were int variables to improve performance, result could be cast to short if the function absolutely has to return short." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T20:25:54.083", "Id": "430447", "Score": "7", "body": "Refusing to use `break` in a loop to...break out of the loop is a curious anti-pattern you've developed, especially considering that you use `exit` inside of pre-condition checks to break out of the entire program! I've seen this sort of code before, setting flags to indicate when the loop was done instead of actually just breaking out. It was a horrible spaghetti mess. Fortunately, it wasn't generated by a human; it was generated by a tool. I promptly rewrote it, reduced the number of lines by about half, and made it much more readable in the process. Also easier for compiler to optimize." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T01:09:20.760", "Id": "430462", "Score": "2", "body": "“taught to ONLY USE ONE return statement”—This (perennial) advice is an unfortunate misunderstanding of historical context. The phrase “single return”/“single exit” means that you should only return *to* one address, not only *from* one address. [Please read this answer for more details.](https://softwareengineering.stackexchange.com/a/118793/)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T09:19:40.140", "Id": "430518", "Score": "1", "body": "If those `exits` are error exist you should use `exit(EXIT_FAILURE)` instead of `exit(0)`. It may be useful for shell `&&`/`||` combinations. And those `printf`'s should go to `stderr`: `printf(…)` => `fprintf(stderr, …)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T09:22:51.020", "Id": "430520", "Score": "1", "body": "@user28434, the box for answers is further down the page." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T09:24:43.253", "Id": "430522", "Score": "0", "body": "@PeterTaylor, it's not full answer, just comment of few lines of code." } ]
[ { "body": "<blockquote>\n <p>I am only looking for some feedback on my coding style.</p>\n</blockquote>\n\n<p>Formatting is good. I hope it is auto formatted.</p>\n\n<p><strong>Respect the presentation width</strong></p>\n\n<p>Rather than oblige a horizontal scroll bar, auto format to a narrower width to avoid that.</p>\n\n<p><strong>Avoid dogma</strong></p>\n\n<p>\"to ONLY USE ONE return statement in functions and NOT to use things like break, continue or go-to.\" --> This is a reasonable goal, but better to code for clarity. Use <code>break, continue</code> and even sometimes <code>goto</code> when it provides cleaner code.</p>\n\n<hr>\n\n<blockquote>\n <p>How could I improve?</p>\n</blockquote>\n\n<p><strong>Use <code>short</code> to save space in arrays - not here</strong> </p>\n\n<p><code>short jacobi(long a, long n)</code> returns 0,1,-1. There is no space, code, performance savings expected with <code>short</code>. Recommend returning <code>int</code> here. <code>int</code> is often the optimal type for an <em>integer</em>.</p>\n\n<pre><code>// short result = 1;\nint result = 1;\n...\nreturn result;\n</code></pre>\n\n<p><strong>Cryptography begs for unsigned types</strong></p>\n\n<p>Instead of <code>long</code>, consider the widest <em>unsigned</em> type of <code>uintmax_t</code> or the widest fixed size type: <code>uint64_t</code>.</p>\n\n<p><em>Unsigned</em> types will improve code performance.</p>\n\n<p><code>long n ... n_mod8 = n % 8;</code> requires a division as <code>n % 8</code> has 15 different results [-7 ... 7]. With <code>unsigned long n</code>, <code>n % 8</code> is simply a mask operation.</p>\n\n<p><strong>Consider <code>bool</code></strong></p>\n\n<p>For clarity, use <code>bool</code>.</p>\n\n<pre><code>//short condition = 1;\n//while (condition == 1) {\nbool condition = true;\nwhile (condition) {\n</code></pre>\n\n<p><strong>Remove debug code</strong></p>\n\n<p>e.g. <code>// printf(\"(%d|%d) and result = %d \\n\", a, n, result);</code>.</p>\n\n<p><strong>Error messages: consider <code>stderr</code></strong></p>\n\n<pre><code>// printf(\"Wrong input for the Jacobi Symbol:...\nfprintf(stderr, \"Wrong input for the Jacobi Symbol: ...\n</code></pre>\n\n<p><strong>Post expected test code results</strong></p>\n\n<p>What should <code>printf(\"%d\", jacobi(4852777,12408107));</code> print? </p>\n\n<p>Consider a few more test cases.</p>\n\n<p><strong>Post compilable code</strong></p>\n\n<p>Trailing ``` breaks compilation.</p>\n\n<p><strong>Minor</strong></p>\n\n<pre><code>// The The if-condition below utilises the fact that (0|n) = 0.\nto\n// The if-condition below utilises the fact that (0|n) = 0.\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>Is anything unclearly formulated?</p>\n</blockquote>\n\n<p>I'd add a reference for <a href=\"https://en.wikipedia.org/wiki/Jacobi_symbol\" rel=\"noreferrer\">Jacobi symbol</a>.</p>\n\n<pre><code>// https://en.wikipedia.org/wiki/Jacobi_symbol\n</code></pre>\n\n<p><strong><code>n == 1</code>?</strong></p>\n\n<p>Hmmm. <a href=\"https://en.wikipedia.org/wiki/Jacobi_symbol\" rel=\"noreferrer\">Jacobi symbol</a> allows <code>n==1</code>. Code here does not.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T15:46:43.000", "Id": "430417", "Score": "0", "body": "Thanks for your answers, I will try to apply your suggestions. And concerning the case n == 1: My textbooks never mentioned this convention, but thanks for pointing that out. Again many thanks for your time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T10:19:46.453", "Id": "430540", "Score": "1", "body": "Actually, the widest fixed-size type may be `std::uint_fast64_t` (in practice, that's unlikely, though)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T13:35:49.370", "Id": "222405", "ParentId": "222396", "Score": "14" } }, { "body": "<blockquote>\n <p>One point I could think of would be to use \"long long\" instead of only \"long\" since this algorithm is used in cryptography and should thus be suited for very large integers.</p>\n</blockquote>\n\n<p><em>Very large integers</em> means using GMP or a similar library, not using <code>long long</code>. Although if you're using GMP then you might as well use <code>mpz_jacobi</code>.</p>\n\n<p>This may be controversial, but in my opinion all new C code should use the types from <code>stdint.h</code> unless forced to use less specific types for interoperability with legacy code.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> a = a % n;\n</code></pre>\n</blockquote>\n\n<p>This is buggy. The first time this is executed, <code>a</code> might be negative, but the rest of the algorithm requires <code>a</code> to be non-negative. As a test case consider <code>jacobi(-1, 3)</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T11:23:58.037", "Id": "430721", "Score": "0", "body": "Thanks a lot for pointing that out, I fixed it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T10:13:29.580", "Id": "222452", "ParentId": "222396", "Score": "1" } } ]
{ "AcceptedAnswerId": "222405", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T11:27:16.003", "Id": "222396", "Score": "11", "Tags": [ "beginner", "algorithm", "c", "cryptography" ], "Title": "Implementation of the Jacobi Symbol in C" }
222396
<p>I started learning c and wanted to challenge myself by making a linked list. I am stil new to the concept of pointers and pointers to pointers, so there might be something in my code that I could have done differently, but hey, I'm still learning. I would like to hear any advice or tips so I can improve my programming skills.</p> <p>Code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #define TRUE 1 #define FALSE 0 typedef struct node{ int val; struct node * next; } node_t; /** Prints out all the elements **/ void print_nodes(node_t * head) { if(head == NULL) printf("Head is null"); node_t * current = head; printf("Node values\n"); while(current != NULL) { printf("%d\n",current-&gt;val); current = current-&gt;next; } printf("\n"); } /** Removes the current head node **/ void pop(node_t ** head_node) { printf("val: %d\n",(*head_node)-&gt;val); node_t * new_head = (*head_node)-&gt;next; *head_node = new_head; } /** Removes a node at he given index **/ void remove_node_at(node_t ** head_node,int index) { node_t * current = *head_node; node_t * node_after_del; node_t * prev_node; int run = TRUE; int counter = 0; if(index == 0) { pop(head_node); run = FALSE; } while(run == TRUE) { if(counter == index) { if(current-&gt;next == NULL) { prev_node-&gt;next = NULL; free(current); } else { node_after_del = current-&gt;next; prev_node-&gt;next = node_after_del; free(current); } run = FALSE; } if(current-&gt;next != NULL) { prev_node = current; current = current-&gt;next; } else { run = FALSE; printf("Node to delete not found\n\n"); } counter++; } } /** Free up all the memory allocated by the nodes**/ void clear_nodes(node_t * head_node) { node_t * current = head_node; int run = TRUE; while(run == TRUE) { node_t * temp = current; if(temp-&gt;next != NULL) { current = temp-&gt;next; } else { run = FALSE; } temp = NULL; free(temp); } head_node = NULL; free(head_node); } /** Pushes a node to the front **/ void push_front(node_t ** heade_node, int val) { node_t * new_head = malloc(sizeof(node_t)); new_head-&gt;val = val; new_head-&gt;next = *heade_node; *heade_node = new_head; } /** Adds a new node at the end **/ void push_end(node_t * head_node,int val) { node_t * current = head_node; int run = TRUE; while(run == TRUE) { if(current-&gt;next == NULL) { run = FALSE; } else current = current-&gt;next; } node_t * next = malloc(sizeof(node_t)); if(next == NULL) exit(1); next-&gt;val = val; next-&gt;next = NULL; current-&gt;next = next; } /** Inserts a node at the given position, if its to big it gets added at the end **/ void insert_node_after(node_t * head_node, int insert_location, int val) { node_t * current = head_node; int run = TRUE; int counter = 0; while(run) { if(current-&gt;next == NULL) run = FALSE; if(counter == insert_location) { node_t * new_node = malloc(sizeof(node_t)); if(new_node == NULL) exit(1); new_node-&gt;val = val; new_node-&gt;next = current-&gt;next; current-&gt;next = new_node; run = FALSE; } if(current-&gt;next == NULL) { /** Adds the node at the end if we reached the end **/ node_t * new_node = malloc(sizeof(node_t)); if(new_node == NULL) exit(1); current-&gt;next = malloc(sizeof(node_t)); current-&gt;next-&gt;val = val; current-&gt;next-&gt;next = NULL; run == FALSE; } else { current = current-&gt;next; } counter++; } } int main() { node_t * head = NULL; head = malloc(sizeof(node_t)); if(head == NULL) return 1; head-&gt;val = 0; head-&gt;next = NULL; for(int i = 1; i &lt; 13; i++) { push_end(head,i); } push_front(&amp;head,17); print_nodes(head); remove_node_at(&amp;head,0); pop(&amp;head); pop(&amp;head); print_nodes(head); insert_node_after(head,1,199); print_nodes(head); clear_nodes(head); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T15:13:06.793", "Id": "430407", "Score": "0", "body": "I think `pop(&head)` leaks memory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T15:15:22.567", "Id": "430410", "Score": "0", "body": "@CrisLuengo could you explain why? And how it should be done then?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T15:18:17.267", "Id": "430412", "Score": "1", "body": "Because you're no longer referencing the old head node, and there’s no `free`. I might see this wrong, haven’t combed through the code in fine detail. You might want `pop` to call `remove_node_at(...,0)` or something similar to have only one bit of code that removes a node." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T12:26:46.457", "Id": "430551", "Score": "0", "body": "@CrisLuengo is correct,, there is a memory leak there. One thing I left out of my review is there should be a delete_node() function to complement the create_node() function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T12:34:53.100", "Id": "430554", "Score": "0", "body": "@vnp is also correct in the comments under my review, several of the functions in this implementation should return values that indicate the success or failure of the action and error handling should be handled at a higher level. Neither `exit` nor `setjmp/longjmp` is necessary in this program. You need to figure out a strategy for handling errors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T13:18:40.733", "Id": "430562", "Score": "0", "body": "@CrisLuengo I have updated the code, however i am not sure if i fixed the leak." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T13:22:20.250", "Id": "430563", "Score": "0", "body": "Welcome to Code Review! Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T13:25:20.170", "Id": "430564", "Score": "0", "body": "Mod note: Please use the Answer box to write answers. Observations about nontrivial changes to code that don't make the question off-topic are generally answers. @CrisLuengo" } ]
[ { "body": "<p><strong>BUG Report</strong><br>\nThe function <code>void insert_node_after(node_t * head_node, int insert_location, int val)</code> contains at least one bug, which is a typo and may contain more bugs in the <code>then</code> clause of the third if statement. The typo is</p>\n\n<pre><code> run == FALSE;\n</code></pre>\n\n<p>which should be an assignment statement with a single equal sign. The full context is shown below:</p>\n\n<pre><code> if (current-&gt;next == NULL)\n {\n /** Adds the node at the end if we reached the end **/\n node_t * new_node = (node_t *) malloc(sizeof(node_t));\n\n if (new_node == NULL)\n exit(1);\n\n current-&gt;next = (node_t *) malloc(sizeof(node_t));\n current-&gt;next-&gt;val = val;\n current-&gt;next-&gt;next = NULL;\n run == FALSE;\n }\n else\n {\n current = current-&gt;next;\n }\n</code></pre>\n\n<p><strong>Report Errors</strong><br>\nThe code checks for a failed call to <code>malloc(size_t)</code> in some instances and exits, however, it never reports that <code>malloc</code> failed so anyone using the program would wonder why the program failed. Prior to calling exit(1) it might be better to report the error to <code>stderr</code>. Note that the error check is not performed in <code>void push_front(node_t ** head_node, int val)</code>, and it is missing after the third <code>malloc</code> in <code>void insert_node_after(node_t * head_node, int insert_location, int val)</code>.</p>\n\n<p><strong>Prefer setjmp and longjmp Over exit(1)</strong><br>\nSome programs such as operating systems should never call <code>exit(int status)</code>. Many more programs may need to clean up things, such as closing files, detaching from databases or deleting memory. It might be better to <a href=\"http://www.cplusplus.com/reference/csetjmp/setjmp/\" rel=\"nofollow noreferrer\">call setjmp() in main() and then execute a longjmp</a> if <code>malloc(size_t)</code> fails. This is discussed in greater detail in this <a href=\"https://stackoverflow.com/questions/14685406/practical-usage-of-setjmp-and-longjmp-in-c\">stackoverflow question</a>.</p>\n\n<p><strong>Use System Defined Symbolic Constants Rather than Magic Numbers</strong><br>\nThe code already references stdlib.h, which contains the system defined constants <a href=\"https://stackoverflow.com/questions/8867871/should-i-return-exit-success-or-0-from-main\">EXIT_SUCCESS and EXIT_FAILURE</a>. Since these constants are always defined in stdlib.h the code will be more portable if they are used, and it also makes the code more readable:</p>\n\n<pre><code>main()\n{\n ...\n return EXIT_SUCCESS;\n}\n\nexit(EXIT_FAILURE);\n</code></pre>\n\n<p><strong>Basic Principles When Writing Code</strong><br>\nOne of the earliest principles all programmers learn is <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself</a>, usually shortened to DRY code. Basically anytime you have code that repeats it would be better to put it into a loop or a function where the code is reused.</p>\n\n<p>A second principle that should be taught early but is part of more complex programming is the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> which states that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated within the function, module or class. This reduces the size of functions which allows functions to be more readable, maintainable and easier to debug. It also allows the programmer to debug the code only once rather than multiple times.</p>\n\n<p>The code to create and fill a node is repeated 5 times, it might be better to write a function that creates and fills a node:</p>\n\n<pre><code>node_t * create_node(int val, node_t *next_node)\n{\n node_t * new_node = malloc(sizeof(*new_node));\n if (new_node == NULL)\n {\n fprintf(stderr, \"malloc for new_node failed.\\n\");\n exit(EXIT_FAILURE); // replace with call to longjmp here.\n }\n\n new_node-&gt;val = val;\n new_node-&gt;next = next_node;\n\n return new_node;\n}\n</code></pre>\n\n<p>In the function above sizeof(*new_node) was used for the size of the <code>malloc()</code> this allow the programmer to edit once to change the type of a variable rather than edit in two places this can prevent some programming errors when maintaining code.</p>\n\n<p><strong>Keep It Simple</strong><br>\nThe function <code>void print_nodes(node_t * head)</code> contains a simpler loop to traverse the linked list. This might be better than using the variable <code>run</code> that is used in the other traversals of the linked list.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T21:06:36.567", "Id": "430453", "Score": "1", "body": "The `setjmp/longjmp` recommendation is seriously off, especially given the skill level of the OP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T00:26:06.037", "Id": "430460", "Score": "0", "body": "@vnp I can definitely see your point about the skill level, what would you suggest?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T04:14:07.060", "Id": "430465", "Score": "0", "body": "@pacmaninbw Report an error, just as you said, and let the caller decide. `*jmp` has its use case, but it is not here." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T14:57:40.637", "Id": "222410", "ParentId": "222402", "Score": "4" } } ]
{ "AcceptedAnswerId": "222410", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T12:28:14.447", "Id": "222402", "Score": "2", "Tags": [ "beginner", "c", "linked-list" ], "Title": "First attempt at making linkedlist in c" }
222402
<p>I wrote the following code which when executed prints the score of <a href="https://github.com/dhh" rel="nofollow noreferrer">https://github.com/dhh</a>.</p> <pre><code>require 'typhoeus' require 'json' class DHHScoreChallenge def getData req = Typhoeus.get("https://api.github.com/users/dhh/events/public") body = req.body json_body = JSON.parse(body) end def calculateScore json_body type_and_score = { :IssuesEvent =&gt; 7, :IssueCommentEvent =&gt; 6, :PushEvent =&gt; 5, :PullRequestReviewCommentEvent =&gt; 4, :WatchEvent =&gt; 3, :CreateEvent =&gt; 2 } score = 0 json_body.each do |commit| commit_type = commit['type'] if type_and_score.has_key? commit_type.to_sym score = score + type_and_score[commit_type.to_sym] else score = score + 1 end end score end def showScore score puts "DHH's github score is #{score}" end end begin d = DHHScoreChallenge.new json_body = d.getData score = d.calculateScore(json_body) d.showScore(score) end </code></pre> <p>I am a beginner in ruby programming and would like to know the best practices of Ruby. I am trying to include portability, encapsulation, reusability in my code. Please let me know if they have been achieved and if there are any improvements that I can make. Thanks in advance!</p>
[]
[ { "body": "<p>The major thing I see is, <strong>the code is imperative</strong>. But things will be lot more easier to read and follow, if you practise <strong><em>declarative way of writing code.</em></strong></p>\n\n<p>I would not name the class as DHHScoreChallenge. It should be ScoreChallenge, so that it can be used for any user that we pass in :)</p>\n\n<p>I would make the method getData private, in order to externalise the service layer dependency.</p>\n\n<p>Also I would move the <code>type_and_score</code> into a class level map</p>\n\n<p>This logic is too complex to read</p>\n\n<pre><code>if type_and_score.has_key? commit_type.to_sym\n score = score + type_and_score[commit_type.to_sym] \nelse\n score = score + 1\nend\n</code></pre>\n\n<p>This could have eliminated by using a combination of dig and fetch. Dig will return nil if you cannot find the key in hash and fetch on a hash can return a value if the value of the key returns nil</p>\n\n<p>Also I see that you are converting the event key to symbol and trying to find the symbol in hash. Instead you might as well have created a hash with strings as symbols, it won't be much of a over head if you freeze the hash.</p>\n\n<p>Something like this</p>\n\n<pre><code> EVENTS_SCORE_MAP = {\n 'IssuesEvent' =&gt; 7,\n 'IssueCommentEvent' =&gt; 6,\n 'PushEvent' =&gt; 5,\n 'PullRequestReviewCommentEvent' =&gt; 4,\n 'WatchEvent' =&gt; 3,\n 'CreateEvent' =&gt; 2\n }.freeze\n\n EVENTS_SCORE_MAP.fetch(event.dig('type'), 1)\n</code></pre>\n\n<p>I rewrote the whole thing in a manner which I would in my production system</p>\n\n<pre><code>require 'typhoeus'\nrequire 'json'\n\n# Github service dealing with all the requests to github\nclass Github\n def events(user_name)\n url = \"https://api.github.com/users/#{user_name}/events/public\"\n send_request(\n lambda {\n Typhoeus.get(url)\n }, url\n )\n end\n\n private\n\n def send_request(request, path)\n request.call\n rescue Timeout::Error\n raise GatewayTimeoutError.new(gateway: 'github api timed out', path: path)\n end\nend\n\n# This class deals calculating the score\nclass ScoreChallenge\n EVENTS_SCORE_MAP = {\n 'IssuesEvent' =&gt; 7,\n 'IssueCommentEvent' =&gt; 6,\n 'PushEvent' =&gt; 5,\n 'PullRequestReviewCommentEvent' =&gt; 4,\n 'WatchEvent' =&gt; 3,\n 'CreateEvent' =&gt; 2\n }.freeze\n\n def initialize(user_name, score = 0)\n @user_name = user_name\n @score = score\n end\n\n def pretty_score\n calculate\n puts \"#{@user_name} github score is #{@score}\"\n end\n\n private\n\n def calculate\n events_of_user = JSON.parse(github_service.events(@user_name).body)\n events_of_user.each do |event|\n @score += EVENTS_SCORE_MAP.fetch(event.dig('type'), 1)\n end\n end\n\n def github_service\n @github_service = Github.new\n end\nend\n\nscore_challenge = ScoreChallenge.new('DHH')\nscore_challenge.pretty_score\n</code></pre>\n\n<p>As you can see, I have exposed only one method called <code>pretty_score</code>. Which does everything that we need. This is the declarative style of programming I was talking about. I am letting my code figure out what to do, rather than me telling it do something step by step</p>\n\n<p>Also Github is a service class I have created. It should ideally sit under a services folder. I have not implemented GatewayTimeoutError here, but for all practical purposes we should assume that these third party services can timeout/error out we should be able to handle them. You can also look into passing blocks, and custom errors as part of the above code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T14:14:00.117", "Id": "222406", "ParentId": "222403", "Score": "3" } }, { "body": "<p>First thing I'd like to tackle right away is the name convention for method names and variables.</p>\n\n<p>In ruby, we use <code>underscore_style</code> instead of <code>camelCaseStyle</code> - this makes a huge difference.</p>\n\n<p>Now, let's tackle the code itself. One thing that I see that could be improved here is the fact that you aren't leveraging the power of ruby collections and classes.</p>\n\n<p>So, let's start from the beginning.\nFirst, here is what I see that you coding is doing (needs to be done):</p>\n\n<ol>\n<li>Get data from http</li>\n<li>Parsing JSON</li>\n<li>Calculate score</li>\n<li>Show score</li>\n</ol>\n\n<p>Those are 4 different responsibilities that can be separated into mini-classes/modules whatever. It's important to make this distinction, so then you can have a more modular system.</p>\n\n<p>What I like to do is to create very small specialised classes and build on top of them creating more and more complex layers of abstractions.</p>\n\n<p>For instance, starting from 1. We can create a class that only handle http requests, and knows nothing about the endpoints it needs to consume.</p>\n\n<pre><code>class Http\n attr_reader :client\n\n def initialize(client = Typhoeus)\n @client = client\n end\n\n def get(url)\n client.get(url).body\n end\nend\n</code></pre>\n\n<p>Here I pass the client option, making this class some sort of a adapter. So then, down the road, if I want to I can change my http library without breaking the other classes that depends on this one - Also, Since I own <code>Http</code> class I have more control over its API and I can more easily upgrade Typhoeus to a new version since this is the only place where I interact with this gem.</p>\n\n<p>Next up, consuming the Github JSON Api:</p>\n\n<pre><code>class Github\n BASE_URI = \"https://api.github.com\"\n\n attr_reader :http\n\n def initialize(http: Http.new)\n @http = http\n end\n\n def events(user)\n parse http.get(URI.join(BASE_URI, \"/users/#{user}/events/public\"))\n end\n\n private\n\n def parse(body)\n json(body).map { |entry| OpenStruct.new(entry) }\n end\n\n def json(body)\n JSON.parse(body)\n end\nend\n</code></pre>\n\n<p>As you can see, this class tries to be very generic as well. In this case, we expose the events endpoint, but we can as well expose different endpoints of this API. Up to now there's no reference of scores or anything, so this class can be safely used for other purposes when interacting with Github API.</p>\n\n<p>At this point we are left to the meat of the project, where the business logic comes into place.</p>\n\n<p>One thing I'd like to point out is the usage of hash mapping for the scores:</p>\n\n<pre><code> type_and_score = {\n :IssuesEvent =&gt; 7,\n :IssueCommentEvent =&gt; 6,\n :PushEvent =&gt; 5,\n :PullRequestReviewCommentEvent =&gt; 4,\n :WatchEvent =&gt; 3,\n :CreateEvent =&gt; 2\n }\n</code></pre>\n\n<p>I'd say this kinda works fine, but I believe there are better ways to handle that. This is usually what we call Primitive Obsession and here, I can clearly see that this hash contains too much knowledge about something (and this something is the core of the business logic - which is the score).</p>\n\n<p>On this scenario, I'd rather create a class to represent the Score itself and make this class a bit smarter, instead of relying solely in the hash provided by ruby. Also, using it together with ruby <code>Enumerable's</code> module we can simplify the score calculation by a bunch, here's how:</p>\n\n<p>First, I simply create a class that represents a score:</p>\n\n<pre><code>class Score\n attr_reader :name, :weight\n\n def initialize(name, weight)\n @name = name\n @weight = weight\n end\nend\n</code></pre>\n\n<p>This class is very simple, and its sole purpose is to store information in a nice manner.</p>\n\n<p>Then, I have something that I called ScoreSet (for lack of better name) which is a collection of scores.</p>\n\n<pre><code>class ScoreSet\n include Enumerable\n\n attr_reader :scores\n\n def initialize(scores)\n @scores = scores\n end\n\n def each(&amp;block)\n @scores.each(&amp;block)\n end\n\n def for(name)\n find { |s| s.name == name } || Score.new(name, 1)\n end\nend\n</code></pre>\n\n<p>This class leverages the powerful <code>Enumerable</code> module, that gives us for free methods like <code>map</code>, <code>sum</code> and so son after implementing the <code>each</code> method in it.</p>\n\n<p>Also, See how the factory method <code>for</code> decides which score to select as well as default one.</p>\n\n<p>Finally, to keep things tidy, I calculate the score itself:</p>\n\n<pre><code>class CalculateUserScore\n def initialize(events, score_set)\n @events = events\n @score_set = score_set\n end\n\n def call\n @events.map { |e| @score_set.for(e.type) }.sum(&amp;:weight)\n end\nend\n</code></pre>\n\n<p>And the calculation is a simple map over the score set calling sum in the end (thanks to Enumerable module)</p>\n\n<p>I'd say this is definetly a bit over-complex version of the problem and I wouldn't do this for such a small script. However, I do believe those patterns can be used in larger applications to have a more modular and robust system.</p>\n\n<p>The full source is available here: <a href=\"https://gist.github.com/jonduarte/017121fa4804189091769eaf9fe7fdc9\" rel=\"nofollow noreferrer\">https://gist.github.com/jonduarte/017121fa4804189091769eaf9fe7fdc9</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-25T13:09:28.837", "Id": "431741", "Score": "0", "body": "Welcome to Code Review! I think you did a great job on your first answer. Keep it coming!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-25T13:04:56.800", "Id": "222924", "ParentId": "222403", "Score": "1" } } ]
{ "AcceptedAnswerId": "222406", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T12:54:30.330", "Id": "222403", "Score": "1", "Tags": [ "beginner", "object-oriented", "ruby", "community-challenge" ], "Title": "github page/ DHH Score Challenge in ruby" }
222403
<p>As I'm learning elixir, I wrote some code for printing elements in the spiral of a matrix(2D array). I was wondering if there is any room for improvements with regards to its performance or refactoring of any kind.</p> <pre><code>defmodule MatrixSpiralPrint do @moduledoc """ Solution to Spiral print of elements of a matrix(2D array) """ @doc """ prints elements of matrix(2D array) in a spiral ## Examples iex&gt; matrix = [[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]] iex&gt; MatrixSpiralPrint.spriral_print_matrix(matrix) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] """ def spriral_print_matrix(matrix) do case List.improper?(matrix) do true -&gt; "Not a valid matrix" false -&gt; has_rows(matrix) end end def has_rows(matrix) do row = Enum.at(matrix, 0) case List.improper?(row) do true -&gt; "Does not contain a row" false -&gt; spiral_print(matrix) end end def spiral_print(matrix) do row_min = 0 row_max = length(matrix) - 1 column_min = 0 column_max = length(Enum.at(matrix, 0, 0)) - 1 matrix |&gt; spiral_print(row_min, row_max, column_min, column_max) end def spiral_print(matrix, row_min, row_max, column_min, column_max) do print_matrix(row_min &lt; row_max and column_min &lt; column_max, matrix, row_min, row_max, column_min, column_max) end def print_matrix(true, matrix, row_min, row_max, column_min, column_max) do # IO.puts(:stdio, "row_min: #{row_min}, row_max: #{row_max} column_min: #{column_min}, column_max: #{column_max}") print_left_to_right(column_min &lt;= column_max, matrix, row_min, column_min, column_max) row_min = row_min + 1 # IO.puts(:stdio, "row_min: #{row_min}, row_max: #{row_max} column_min: #{column_min}, column_max: #{column_max}") print_top_to_bottom(row_min &lt;= row_max, matrix, row_min, column_max, row_max) column_max = column_max - 1 # IO.puts(:stdio, "row_min: #{row_min}, row_max: #{row_max} column_min: #{column_min}, column_max: #{column_max}") print_right_to_left(column_min &lt;= column_max, matrix, row_max, column_max, column_min) row_max = row_max - 1 # IO.puts(:stdio, "row_min: #{row_min}, row_max: #{row_max} column_min: #{column_min}, column_max: #{column_max}") print_bottom_to_top(row_min &lt;= row_max, matrix, row_max, column_min, row_min) column_min = column_min + 1 # IO.puts(:stdio, "==============================================================") # IO.puts(:stdio, "row_min: #{row_min}, row_max: #{row_max} column_min: #{column_min}, column_max: #{column_max}") print_matrix(row_min &lt; row_max and column_min &lt; column_max, matrix, row_min, row_max, column_min, column_max) end def print_matrix(false, _matrix, _row_min, _row_max, _column_min, _column_max) do :ok # IO.puts(:stdio, "End of the matrix") end def print_left_to_right(true, matrix, row, column, limit) do # IO.puts(:stdio, "row: #{row}, column: #{column}, limit: #{limit}") IO.puts(:stdio, Enum.at(Enum.at(matrix, row), column)) print_left_to_right(column &lt; limit, matrix, row, column+1, limit) end def print_left_to_right(false, _matrix, _row, _column, _limit) do :ok # do nothing end def print_top_to_bottom(true, matrix, row, column, limit) do # IO.puts(:stdio, "row: #{row}, column: #{column}, limit: #{limit}") IO.puts(:stdio, Enum.at(Enum.at(matrix, row), column)) print_top_to_bottom(row &lt; limit, matrix, row+1, column, limit) end def print_top_to_bottom(false, _matrix, _row, _column, _limit) do :ok # do nothing end def print_right_to_left(true, matrix, row, column, limit) do # IO.puts(:stdio, "row: #{row}, column: #{column}, limit: #{limit}") IO.puts(:stdio, Enum.at(Enum.at(matrix, row), column)) print_right_to_left(limit &lt; column, matrix, row, column-1, limit) end def print_right_to_left(false, _matrix, _row, _column, _limit) do :ok # do nothing end def print_bottom_to_top(true, matrix, row, column, limit) do # IO.puts(:stdio, "row: #{row}, column: #{column}, limit: #{limit}") IO.puts(:stdio, Enum.at(Enum.at(matrix, row), column)) print_bottom_to_top(limit &lt; row, matrix, row-1, column, limit) end def print_bottom_to_top(false, _matrix, _row, _column, _limit) do :ok # do nothing end end </code></pre> <p>Code is also available for review on gist. <a href="https://gist.github.com/suryart/c92aaca868078e9256b8bd145d6944cd" rel="nofollow noreferrer">Link to the gist</a>.</p> <p><strong>Edit:</strong></p> <p>Updated code by removing <code>if</code> conditions in favor of pattern matching. Please let me know if there's something that I can learn to improve the coding. For example, I was wondering if there could be a neater way to get rid-off of the long arguments list for each print function.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T14:37:48.623", "Id": "222409", "Score": "2", "Tags": [ "performance", "beginner", "matrix", "elixir" ], "Title": "Spiral printing elements of a matrix" }
222409
<p>This is a question that I encountered in one of the competitive coding tests. The question goes as follows:</p> <blockquote> <p>A 2-player game is being played. There is a single pile of stones. Every stone has an amount (positive) written on top of it. At every turn, a player can take the top 1 or 2 or 3 stones and add to his kitty. Both players want to maximize their winnings. Assuming both players play the game optimally and Player 1 starts the game, what is the maximum amount that Player 1 can win?</p> </blockquote> <p>I have devised the following recursive approach:</p> <pre><code>class Main { public static void main(String[] args) { int a[] = {1,2,3,7,4,8,1,8,1,9,10,2,5,2,3}; int sum = 0; for (int i=0;i&lt;a.length; i++) { sum += a[i]; } System.out.println(maxPlayer1(a, 0, sum, 0, a.length)); } public static int maxPlayer1(int[] a, int currSum, int sum, int start, int len) { if (len-start &lt;=3) { int val = 0; for (int i=start; i&lt;len; i++) { val += a[i]; } return val; } int v1 = a[start] + (sum - currSum - a[start]) - maxPlayer1(a, currSum + a[start], sum, start + 1, a.length); int v2 = a[start] + a[start+1] + (sum - currSum - a[start] - a[start+1]) - maxPlayer1(a, currSum + a[start] + a[start+1], sum, start + 2, a.length); int v3 = a[start] + a[start+1] + a[start+2] + (sum - currSum - a[start] - a[start+1] - a[start+2]) - maxPlayer1(a, currSum + a[start] + a[start+1] + a[start+2], sum, start + 3, a.length); return Math.max(v1, Math.max(v2, v3)); } } </code></pre> <p>I have checked my solution on a few inputs. <strong>Is my algorithm correct</strong>?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T16:25:30.167", "Id": "430423", "Score": "5", "body": "A few inputs? Nope. You need a lot of inputs. One thing to do is to test your solution against more inputs. This way, you won't need to ask whether your algorithm is correct or not; you **know** your algorithm is right. Therefore, test some more inputs, so that you know your algorithm works correctly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T16:34:22.183", "Id": "430424", "Score": "8", "body": "There is nothing wrong with posting the unit tests you already implemented as an appendix in your question. This makes our task helping you easier. When asking whether your algorithm is correct, this rings bells here. I suggest to read the policy: https://codereview.stackexchange.com/help/on-topic" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T22:53:49.117", "Id": "430459", "Score": "3", "body": "A \"pile of stones\" together with \"written on top\" sounds a lot like the players would only be able to look at the top stone, with the scores of all other stones being a secret until the top stone is removed. This should be clarified before the algorithm can be analyzed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T08:58:08.580", "Id": "430508", "Score": "2", "body": "@RolandIllig There are very few scenarios where you gain by not taking all 3 stones - I don't think that can be the intention. I can see just the few options where you know you will end up with the same number of stones and tactically not take one with low number in hope you can get a higher one instead… but this is subject to luck. So, strategy would be fairly simple - take the maximum number of stones, except don't take stones with 1 in case you still end up with the same number of stones in the end. (anything else depends on luck)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T10:05:49.477", "Id": "430537", "Score": "3", "body": "Why do you need to pass `a.length` as a separate argument?" } ]
[ { "body": "<h3>Usability</h3>\n\n<p>I have a remark about defining recursive functions. \nYou don't want consumers of your API to think about the intermediate variables and their initial value. The consumer does not care you are using recursion internally.</p>\n\n<p>Make your recursive function <code>private</code>.</p>\n\n<pre><code>private static int maxPlayer1(int[] a, int currSum, int sum, int start, int len) \n</code></pre>\n\n<p>And create a <code>public</code> API entrypoint.</p>\n\n<pre><code>public static int maxPlayer1(int[] a) {\n final int sum = IntStream.of(a).sum();\n return maxPlayer1(a, 0, sum, 0, a.length);\n}\n</code></pre>\n\n<p>The consumer can now call your API without getting a headache:</p>\n\n<pre><code>public static void main(String[] args) {\n final int a[] = {1,2,3,7,4,8,1,8,1,9,10,2,5,2,3};\n System.out.println(maxPlayer1(a));\n}\n</code></pre>\n\n<p>As compared to the original code the consumer had to write.</p>\n\n<blockquote>\n<pre><code>public static void main(String[] args) {\n int a[] = {1,2,3,7,4,8,1,8,1,9,10,2,5,2,3};\n int sum = 0;\n for (int i=0;i&lt;a.length; i++) {\n sum += a[i];\n }\n System.out.println(maxPlayer1(a, 0, sum, 0, a.length));\n }\n</code></pre>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T17:23:14.303", "Id": "222419", "ParentId": "222413", "Score": "22" } }, { "body": "<p>A note on efficiency. Currently the code exhibit an exponential time complexity. It can be reduced significantly.</p>\n\n<p>Notice that the same position is inspected more than once. For example, the opening sequences <code>3, 1</code>, <code>2, 2</code> and <code>1, 3</code> all lead to the same position. Further down the game the situation aggravates.</p>\n\n<p>Keep track of the positions already inspected, and before diving into the recursion check whether it is still unknown. Since the position is just an integer (an amount of stones remaining), the cost of tracking is <span class=\"math-container\">\\$O(n)\\$</span> space.</p>\n\n<p>Further improvement is of course <a href=\"https://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning\" rel=\"noreferrer\">alpha-beta pruning</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T20:57:05.643", "Id": "222423", "ParentId": "222413", "Score": "9" } }, { "body": "<p>The natural way to tackle this problem (as in many similar games) is starting from the final position.</p>\n\n<p>Let <code>B[k]</code> be the maximum score that Player 1 can get if the game starts with only the last <code>k</code> stones left. <code>B[1]</code>, <code>B[2]</code>, <code>B[3]</code> are initial values that can be computed directly (just take all remaining stones), and then you can fill in <code>B[4], B[5], B[6], ...</code> in this order, since <code>B[k]</code> only depends on <code>B[k-1], B[k-2], B[k-3]</code>; so you can write your code as a loop <code>for k=4,5,6,..., a.length</code>. The resulting algorithm is linear, without no recursion, branching, or approximations required. </p>\n\n<p>Instead, it looks like you are trying to compute the entries <code>B[i]</code> starting from <code>B[a.length]</code>. This leads to a more complicated structure where you make recursive calls, and re-compute the same values <code>B[i]</code> multiple times, as pointed out also by @vnp's answer.</p>\n\n<p>Once you have figured out how to fill the <code>B</code> array in this way, a further improvement is realizing that you only need to keep the last three values <code>B[k], B[k-1], B[k-2]</code> at each step (and possibly also the partial sum <code>a[k-2] + ... + a[a.length]</code>). This gives a solution in <span class=\"math-container\">\\$O(1)\\$</span> space.</p>\n\n<p>If you want to compare with another famous function in which f(n) depends on its previous values, what you wrote is like computing Fibonacci numbers recursively via <code>return fibonacci(n-1) + fibonacci(n-2)</code>. What I suggest above is computing iteratively <code>f[0], f[1], f[2], ...</code> starting from <code>f[0]</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T16:47:39.650", "Id": "430615", "Score": "2", "body": "fantastic answer and explanation. +1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T09:34:10.173", "Id": "222448", "ParentId": "222413", "Score": "8" } }, { "body": "<p>I am not too happy about the variable name <code>currSum</code>, it is hard to see the meaning of this variable from the name alone.</p>\n\n<p>Consider <code>takenValue</code> or something similar as a variable name.</p>\n\n<p>Note that</p>\n\n<p><code>a[start] + (sum - currSum - a[start])</code></p>\n\n<p>Simplifies to </p>\n\n<p><code>sum - currSum</code></p>\n\n<p>And similarily for the other cases so;</p>\n\n<pre><code> int v1 = a[start] + (sum - currSum - a[start]) - \n maxPlayer1(a, currSum + a[start], sum, start + 1, a.length);\n\n int v2 = a[start] + a[start+1] + (sum - currSum - a[start] - a[start+1]) - \n maxPlayer1(a, currSum + a[start] + a[start+1], sum, start + 2, a.length);\n\n int v3 = a[start] + a[start+1] + a[start+2] + (sum - currSum - a[start] - a[start+1] - a[start+2]) - \n maxPlayer1(a, currSum + a[start] + a[start+1] + a[start+2], sum, start + 3, a.length);\n</code></pre>\n\n<p>simplifies to</p>\n\n<pre><code> int v1 = sum - currSum - \n maxPlayer1(a, currSum + a[start], sum, start + 1, a.length);\n\n int v2 = sum - currSum - \n maxPlayer1(a, currSum + a[start] + a[start+1], sum, start + 2, a.length);\n\n int v3 = sum - currSum - \n maxPlayer1(a, currSum + a[start] + a[start+1] + a[start+2], sum, start + 3, a.length);\n</code></pre>\n\n<p>We should also try to capture the meaning of <code>a[start]+...a[start+n]</code>, we can do this by introducing a new variable <code>takenInCurrentStep</code></p>\n\n<p>Also</p>\n\n<pre><code> int val = 0;\n for (int i=start; i&lt;len; i++) {\n val += a[i];\n }\n return val;\n</code></pre>\n\n<p>Is needlessly complicated. We can write this as :</p>\n\n<pre><code> return sum-currSum;\n</code></pre>\n\n<p>Bringing this all together :</p>\n\n<pre><code> public static int maxPlayer1(int[] a, int takenValue, int sum, int start, int len) {\n if (len-start &lt;=3) {\n return sum-takenValue;\n }\n\n int valueTakenInCurrentStep = 0;\n int lasttokensTakenInCurrentStep = start;\n int valueTakenInCurrentStep = a[lasttokensTakenInCurrentStep];\n\n int v1 = sum - takenValue -\n maxPlayer1(a, takenValue+ valueTakenInCurrentStep, sum, lasttokensTakenInCurrentStep+1 , a.length);\n\n int lasttokensTakenInCurrentStep ++;\n int valueTakenInCurrentStep = valueTakenInCurrentStep + a[lasttokensTakenInCurrentStep ];\n\n int v2 = sum - takenValue -\n maxPlayer1(a, takenValue+ valueTakenInCurrentStep, sum, lasttokensTakenInCurrentStep+1 , a.length);\n\n int lasttokensTakenInCurrentStep ++;\n int valueTakenInCurrentStep = valueTakenInCurrentStep + a[lasttokensTakenInCurrentStep ];\n int v3 = sum - takenValue - \n maxPlayer1(a, takenValue+ valueTakenInCurrentStep, sum, lasttokensTakenInCurrentStep+1 , a.length);\n\n return Math.max(v1, Math.max(v2, v3));\n }\n}\n</code></pre>\n\n<p>The algorithm can be described as;</p>\n\n<p>We have a method that calculates the maximum that the current player can get from the remaining of the game. The method takes the value of all the tokens, the value of the tokens that are no longer available, the value of all tokens, the index of the first currently available token, and the total number of tokens.</p>\n\n<p>It works by if there are 3 or less tokens left return the value of the remaining tokens, which is equal to the value of all tokens minus the value of the tokens already taken.\nIf there are more than 3 tokens return the maximum of the value of remaining tokens minus the amount that the other player gets if current player takes 1,2 or 3 tokens. </p>\n\n<p>This is a correct algorithm, and we can prove this by incursion.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T11:26:26.313", "Id": "222456", "ParentId": "222413", "Score": "3" } } ]
{ "AcceptedAnswerId": "222448", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T15:54:16.233", "Id": "222413", "Score": "9", "Tags": [ "java", "algorithm", "programming-challenge", "recursion" ], "Title": "\"What is the maximum that Player 1 can win?\"" }
222413
<p>I built a small project using Django-Rest-Framework. Please comment on the best practice style for the code below, which will make it simpler.</p> <pre class="lang-py prettyprint-override"><code>class LoginSerializer(serializers.Serializer): phone = serializers.CharField() password = serializers.CharField() def validate(self, data): phone = data.get("phone", "") password = data.get("password", "") # need simplify the structure below if phone and password: user = authenticate(phone=phone, password=password) if user: if user.is_active: data['user'] = user else: raise exceptions.ValidationError('User is deactivated.') else: raise exceptions.ValidationError( 'Unable to login with given credentials.') else: raise exceptions.ValidationError( 'Must provide username and password both.') return data </code></pre> <p>How I can make this more Pythonic? </p>
[]
[ { "body": "<ul>\n<li>Returning early makes code not follow the arrow anti-pattern. And makes the flow of the code simpler.</li>\n<li>There's otherwise not much to comment on.</li>\n</ul>\n\n<pre><code>class LoginSerializer(serializers.Serializer):\n phone = serializers.CharField()\n password = serializers.CharField()\n\n def validate(self, data):\n phone = data.get(\"phone\", \"\")\n password = data.get(\"password\", \"\")\n # need simplify the structure below\n if not (phone and password):\n raise exceptions.ValidationError('Must provide username and password both.')\n\n user = authenticate(phone=phone, password=password)\n if not user:\n raise exceptions.ValidationError('Unable to login with given credentials.')\n\n if not user.is_active:\n raise exceptions.ValidationError('User is deactivated.')\n\n data['user'] = user\n return data\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T17:19:33.817", "Id": "222417", "ParentId": "222416", "Score": "1" } } ]
{ "AcceptedAnswerId": "222417", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T17:09:18.860", "Id": "222416", "Score": "1", "Tags": [ "python", "validation", "django", "serialization", "rest" ], "Title": "Sign-up serialization in Python" }
222416
<p>So, I decided to write my own little command line argument parser for various other projects I work on. I am aware that there are many good command line parser libraries, but I did wrote my own anyway (practice &amp; implementation specific reasons). </p> <p>The parser works fine, but I have a feeling that it can be improved a lot, mainly the following things come to mind </p> <ol> <li>Mainly the actual parser, <em>CommandLineParser.cs</em>. It seems very badly structured and I find it hard to read myself.</li> <li>Abstraction. I wonder if I can abstract it a bit more without making it a pain to use? Maybe by introducing some interfaces?</li> <li>Naming. I went with <em>Option</em> for the command line switch and with <em>Value</em> for the possible parameters. Are my methods/classes self-descriptive?</li> <li>Optimizations. I am sure there are segments that can be done more efficiently, mainly in <code>CommandLineParser.ParseArguments(string[] args)</code></li> </ol> <p>A couple of things to note:</p> <ol> <li>I'd like to keep the structure for the <em>CommandLineValue.cs</em> and <em>CommandLineOption.cs</em> mostly the same as they are part of a plugin architecture to communicate command line arguments between the plugins and the main application.</li> <li>No usage of Attributes to store the command line options.</li> <li>I did write a couple of unit tests to verify the parsers functionality. Despite them being not the main class to review, I am appreciate feedback there too :)</li> </ol> <p><strong>Parser:</strong></p> <pre><code>public class CommandLineParser { /// &lt;summary&gt; /// Defines all possible command line options the plugin can can process /// &lt;/summary&gt; public List&lt;CommandLineOption&gt; SupportedOptions { get; } /// &lt;summary&gt; /// Initialize the commandline parser with a list of commandline options the plugin exposes /// &lt;/summary&gt; /// &lt;param name="supportedOptions"&gt;&lt;/param&gt; public CommandLineParser(List&lt;CommandLineOption&gt; supportedOptions) { SupportedOptions = supportedOptions; } /// &lt;summary&gt; /// Parse the command line arguments and returns a list of commandline values that can be passed to the /// plugin for further processing. The function also handles invalid amount and/or format of options, values /// as well as missing required arguments etc /// &lt;/summary&gt; /// &lt;param name="args"&gt;The arguments to parse&lt;/param&gt; /// &lt;returns&gt;A list of parsed commandline values + options&lt;/returns&gt; /// &lt;exception cref="InvalidCommandLineOptionException"&gt;&lt;/exception&gt; /// &lt;exception cref="InsufficientCommandLineValuesException"&gt;&lt;/exception&gt; /// &lt;exception cref="InvalidCommandLineValueException"&gt;&lt;/exception&gt; /// &lt;exception cref="MissingRequiredCommandLineOptionException"&gt;&lt;/exception&gt; public IEnumerable&lt;CommandLineValue&gt; ParseArguments(string[] args) { var result = new List&lt;CommandLineValue&gt;(); if (args.Length == 0) return Enumerable.Empty&lt;CommandLineValue&gt;(); // Process all command line arguments for (int i = 0; i &lt; args.Length; i++) { CommandLineOption option = null; if (!IsSupportedOption(args[i], out option)) throw new InvalidCommandLineOptionException($"{args[i]} is not a valid command line option"); // Verify if the option expects additional values if (HasAdditionalValues(option)) { // Check if enough additional values are given int additionalValues = option.ParameterTypes.Count; if (i + additionalValues + 1 &gt; args.Length) throw new InsufficientCommandLineValuesException( $"{args[i]} expects {additionalValues} values."); // Check if the additional values are in the right format // ToDo: Find more elegant solution var values = args.ToList().GetRange(i + 1, i + additionalValues).ToList(); var types = option.ParameterTypes.ToList(); var castedValues = values.Zip(types, (value, type) =&gt; { try { return Convert.ChangeType(value, type); } catch { throw new InvalidCommandLineValueException( $"Cannot cast between value {value} to type {type}"); } }); result.Add(new CommandLineValue(option, castedValues.ToList())); // Increase i to skip to the next option i += additionalValues; } else { result.Add(new CommandLineValue(option, null)); } } // Collect required arguments List&lt;string&gt; requiredOptions = new List&lt;string&gt;(); foreach (var option in SupportedOptions) { if (option.Required) foreach (var tag in option.Tags) { requiredOptions.Add(tag); } } // Check that no required arguments are missing (or occur twice) var missing = GetMissingRequiredArgs&lt;string&gt;(requiredOptions, args.ToList()); if (missing == null) return result; throw new MissingRequiredCommandLineOptionException( $"The required arument(s) {string.Join(",", missing)} occured multiple times"); } /// &lt;summary&gt; /// Check that all required options are used and that they (the required options) dont occur multiple times are no duplicates /// &lt;/summary&gt; /// &lt;param name="required"&gt;A list of required options&lt;/param&gt; /// &lt;param name="arguments"&gt;&lt;The args to check&lt;/param&gt; /// &lt;typeparam name="T"&gt;Any primitive type&lt;/typeparam&gt; /// &lt;exception cref="MissingRequiredCommandLineOptionException"&gt;Thrown if any distinct required arguments exist more then once&lt;/exception&gt; /// &lt;returns&gt;A list of missing required args, if any. Null if none are missing.&lt;/returns&gt; static List&lt;T&gt; GetMissingRequiredArgs&lt;T&gt;(List&lt;T&gt; required, List&lt;T&gt; arguments) { // convert to Dictionary where we store the required item as a key against count for an item var requiredDict = required.ToDictionary(k =&gt; k, v =&gt; 0); foreach (var item in arguments) { if (!requiredDict.ContainsKey(item)) continue; requiredDict[item]++; // if we have required, adding to count if (requiredDict[item] &lt;= 1) continue; throw new DuplicateRequiredCommandLineOptionException( $"Required option {item} appeared more than once!"); } var result = new List&lt;T&gt;(); // now we are checking for missing items foreach (var key in requiredDict.Keys) { if (requiredDict[key] == 0) { result.Add(key); } } return result.Any() ? result : null; } /// &lt;summary&gt; /// Verify if given option is part of the supported options /// &lt;/summary&gt; /// &lt;returns&gt;true if the option is supported otherwise false&lt;/returns&gt; private bool IsSupportedOption(string optionIdentifier, out CommandLineOption option) { for (var index = 0; index &lt; SupportedOptions.Count; index++) { var supportedOption = SupportedOptions[index]; if (supportedOption.Tags.Any(tag =&gt; tag == optionIdentifier)) { option = SupportedOptions[index]; return true; } } option = null; return false; } /// &lt;summary&gt; /// Indicates if a command line option has multiple values or if its just a flag /// &lt;/summary&gt; /// &lt;param name="option"&gt;Commandlineoption to check&lt;/param&gt; /// &lt;returns&gt;true if the option has multiple values, otherwise false&lt;/returns&gt; private bool HasAdditionalValues(CommandLineOption option) { var noParameters = option.ParameterTypes == null || option.ParameterTypes.Count == 0; return !noParameters; } } </code></pre> <p><strong>Classes to store commandline information:</strong></p> <pre><code>public class CommandLineOption { /// &lt;summary&gt; /// The identifier of the commandline option, e.g. -h or --help /// &lt;/summary&gt; public ICollection&lt;string&gt; Tags { get; } /// &lt;summary&gt; /// Description of the commandline option /// &lt;/summary&gt; public string Description { get; } /// &lt;summary&gt; /// Indicates if the argument is optional or required /// &lt;/summary&gt; public bool Required { get; } /// &lt;summary&gt; /// Types of the additional provided values such as directory paths, values etc .. /// &lt;/summary&gt; public IList&lt;Type&gt; ParameterTypes { get; } /// &lt;summary&gt; /// Create a new true/false commandline option /// &lt;/summary&gt; /// &lt;param name="tags"&gt;Identifier of the command line option&lt;/param&gt; /// &lt;param name="description"&gt;Description of the command line option&lt;/param&gt; /// &lt;param name="required"&gt;Indicates if the command line option is optional or not&lt;/param&gt; public CommandLineOption(IEnumerable&lt;string&gt; tags, string description, bool required = false) { Tags = tags.ToList(); Description = description; Required = required; } /// &lt;summary&gt; /// Create a new true/false commandline option /// &lt;/summary&gt; /// &lt;param name="tags"&gt;Identifier of the command line option&lt;/param&gt; /// &lt;param name="description"&gt;Description of the command line option&lt;/param&gt; /// &lt;param name="required"&gt;Indicates if the command line option is optional or not&lt;/param&gt; public CommandLineOption(IEnumerable&lt;string&gt; tags, string description, bool required = false, params Type[] parameterTypes): this(tags, description, required) { ParameterTypes = new List&lt;Type&gt;(parameterTypes); } } </code></pre> <pre><code>public class CommandLineValue : IEqualityComparer&lt;CommandLineValue&gt; { /// &lt;summary&gt; /// Holds all the values specified after a command line option /// &lt;/summary&gt; public IList&lt;object&gt; Values { get; } /// &lt;summary&gt; /// The command line option the value(s) belong to /// &lt;/summary&gt; public CommandLineOption Option { get; set; } /// &lt;summary&gt; /// Stores the values that correspond to a commandline option /// &lt;/summary&gt; /// &lt;param name="option"&gt;The commandline option the values refer to&lt;/param&gt; /// &lt;param name="values"&gt;The values that are stored&lt;/param&gt; public CommandLineValue(CommandLineOption option, IList&lt;object&gt; values) { Option = option; Values = values; } public bool Equals(CommandLineValue x, CommandLineValue y) { if (x.Option.Description == y.Option.Description &amp;&amp; x.Option.Required == y.Option.Required &amp;&amp; x.Option.Tags.SequenceEqual(y.Option.Tags) &amp;&amp; x.Option.ParameterTypes.SequenceEqual(y.Option.ParameterTypes) &amp;&amp; x.Values.SequenceEqual(x.Values)) return true; return false; } public int GetHashCode(CommandLineValue obj) { return base.GetHashCode(); } } </code></pre> <p><strong>Custom Exception Classes:</strong></p> <pre><code>public class DuplicateRequiredCommandLineOptionException : Exception { public DuplicateRequiredCommandLineOptionException(string message) : base(message) { } } public class InsufficientCommandLineValuesException : Exception { public InsufficientCommandLineValuesException(string message) : base(message) { } } public class InvalidCommandLineOptionException : Exception { public InvalidCommandLineOptionException(string message) : base(message) { } } public class InvalidCommandLineValueException : Exception { public InvalidCommandLineValueException(string message) : base(message) { } } public class MissingRequiredCommandLineOptionException : Exception { public MissingRequiredCommandLineOptionException(string message) : base(message) { } } </code></pre> <p><strong>Unit Tests:</strong></p> <pre><code>public class CommandLineParserTests { [Fact] public void ParseDuplicateRequiredArguments() { var args = new[] {"--randomize", "-o", "/home/user/Documents", "--randomize", "-d"}; var supportedOptions = new List&lt;CommandLineOption&gt; { new CommandLineOption( new[] {"-r", "--randomize"}, "Random flag", true), new CommandLineOption( new[] {"-o", "--output-directory"}, "Specifies the output directory", true, typeof(string)), new CommandLineOption( new[] {"-d", "--dummy"}, "Just another unused flag"), }; var parser = new CommandLineParser(supportedOptions); Assert.Throws&lt;DuplicateRequiredCommandLineOptionException&gt;(() =&gt; parser.ParseArguments(args) ); } [Fact] public void ParseMissingRequiredArguments() { var args = new[] {"--randomize", "--output-directory", "/home/user/Documents"}; var supportedOptions = new List&lt;CommandLineOption&gt; { new CommandLineOption( new[] {"-r", "--randomize"}, "Random flag"), new CommandLineOption( new[] {"-o", "--output-directory"}, "Specifies the output directory", true, typeof(string)), new CommandLineOption( new[] {"-d", "--dummy"}, "Just another unused flag"), }; var parser = new CommandLineParser(supportedOptions); Assert.Throws&lt;MissingRequiredCommandLineOptionException&gt;(() =&gt; parser.ParseArguments(args) ); } [Fact] public void ParseMatchingTypeCommandLineValues() { var args = new[] {"--log", "info", "1337", "3.1415"}; var supportedOptions = new List&lt;CommandLineOption&gt; { new CommandLineOption( new[] {"-l", "--log"}, "Logs info from exactly three data sources", false, typeof(string), typeof(int), typeof(float)) }; var parser = new CommandLineParser(supportedOptions); var expectedValue = new CommandLineValue(new CommandLineOption( new[] {"-l", "--log"}, "Logs info from exactly three data sources", false, typeof(string), typeof(int), typeof(float)), new object[] {"info", 1337, (float) 3.1415}); var actualValue = parser.ParseArguments(args).ToList()[0]; Assert.True(expectedValue.Equals(actualValue, expectedValue)); } [Fact] public void ParseMismatchingTypeCommandLineValues() { var args = new[] {"--log", "info", "1337", "3.1415"}; var supportedOptions = new List&lt;CommandLineOption&gt; { new CommandLineOption( new[] {"-l", "--log"}, "Logs info from exactly three data sources", false, typeof(string), typeof(int), typeof(long)), }; var parser = new CommandLineParser(supportedOptions); Assert.Throws&lt;InvalidCommandLineValueException&gt;(() =&gt; parser.ParseArguments(args) ); } [Fact] public void ParseInsufficientCommandLineValues() { var args = new[] {"-l", "info", "info2"}; var supportedOptions = new List&lt;CommandLineOption&gt; { new CommandLineOption( new[] {"-l", "--log"}, "Logs info from exactly three data sources", false, typeof(string), typeof(string), typeof(string)), }; var parser = new CommandLineParser(supportedOptions); Assert.Throws&lt;InsufficientCommandLineValuesException&gt;(() =&gt; parser.ParseArguments(args) ); } [Fact] public void ParseInvalidCommandLineOption() { var args = new[] {"--force"}; var supportedOptions = new List&lt;CommandLineOption&gt; { new CommandLineOption(new[] {"-h", "--help"}, "Show the help menu"), }; var parser = new CommandLineParser(supportedOptions); Assert.Throws&lt;InvalidCommandLineOptionException&gt;(() =&gt; parser.ParseArguments(args) ); } [Fact] public void ParseNoCommandLineOptions() { var args = new string[] { }; var parser = new CommandLineParser(null); var result = parser.ParseArguments(args); Assert.Equal(Enumerable.Empty&lt;CommandLineValue&gt;(), result); } } </code></pre> <p>I appreciate all suggestions. Feel free to be very nitpicky. :)</p>
[]
[ { "body": "<h2>Design Issues</h2>\n<p>There are a couple of issues concerning your design.</p>\n<h3>Lack of specification</h3>\n<p>It is unclear which features should be supported by your API. This makes reviewing a bit fuzzy.</p>\n<h3>Dependencies</h3>\n<p>The parser depends on arguments already pre-parsed correctly by a shell. This limits the control you have over command line parsing.</p>\n<blockquote>\n<p><code>var args = new[] {&quot;--log&quot;, &quot;info&quot;, &quot;1337&quot;, &quot;3.1415&quot;};</code></p>\n</blockquote>\n<p>Consider breaking free from the shell and take on pre-parsing yourself.</p>\n<pre><code>var args = &quot;--log info 1337 3.1415&quot;; // &lt;- unparsed command line string\n</code></pre>\n<h3>Pollution</h3>\n<p>The API mixes language structs with user-defined options.</p>\n<blockquote>\n<p><code>new CommandLineOption(new[] {&quot;-l&quot;, &quot;--log&quot;}</code></p>\n</blockquote>\n<p>You do not want <code>-</code> and <code>--</code> to be part of the <code>Tags</code>. These are delimiters in the lexing phase of your parser. By seperating lexing from parsing, you could extend the API more fluently by allowing other command line languages. For instance <code>/log</code>.</p>\n<hr />\n<h2>Review</h2>\n<h3>Exception Classes</h3>\n<p>Define a base class for all your exceptions <code>CommandLineException</code>. This way, you allow calling code to determine the granularity of exception handling. Since you make several custom exceptions, take advantage of storing some data on them. <code>DuplicateRequiredCommandLineOptionException</code> could store the duplicate option, and so on. Also provide constructors that take an inner exception.</p>\n<pre><code>public class DuplicateRequiredCommandLineOptionException : CommandLineException\n{\n public CommandLineOption Option { get; }\n // include more constructors ..\n public DuplicateRequiredCommandLineOptionException(\n string messageCommandLineOption option) : base(message) { Option = option; }\n}\n</code></pre>\n<h3>CommandLineOption &amp; CommandLineValue</h3>\n<p>You have addressed you don't want to see too many changes for legacy reasons. I do propose to override the default <code>Equals</code> and <code>GetHashCode</code> on both classes and substitute <code>IEqualityComparer</code> with <code>IEquatable</code>. This way, you could improve your code.</p>\n<pre><code> public bool Equals(CommandLineValue other)\n {\n return Option.Equals(other.Option) &amp;&amp; Values.SequenceEqual(other.Values);\n }\n</code></pre>\n<h3>CommandLineParser</h3>\n<p>You have indicated yourself you have problems parsing a flattened list to a hierarchical structure. There are common techniques for handling such situations. Have a look at <a href=\"https://en.wikipedia.org/wiki/Abstract_syntax_tree\" rel=\"nofollow noreferrer\">Abstract Syntax Tree</a>. You should create a syntax tree from the provided <code>string[] args</code>. This can be done with a <em>Stack</em> and <em>Iterator</em>. There are tons of examples online how to create an AST.</p>\n<blockquote>\n<pre><code>// Check if the additional values are in the right format\n// ToDo: Find more elegant solution\nvar values = args.ToList().GetRange(i + 1, i + additionalValues).ToList();\nvar types = option.ParameterTypes.ToList();\n</code></pre>\n</blockquote>\n<p>The second issue is - what I called <em>pollution</em> before - the lack of seperation of concerns. Your API is basically a simple <a href=\"https://en.wikipedia.org/wiki/Compiler\" rel=\"nofollow noreferrer\">compiler</a>. The link shows you it's good practice to provide the following phases when building a compiler:</p>\n<ul>\n<li>pre-processing</li>\n<li>lexing</li>\n<li>parsing</li>\n<li>optimizing</li>\n<li>pretty printing</li>\n</ul>\n<p>Your API should definitely include lexing and parsing as seperate phases.</p>\n<ul>\n<li>lexing: create command line tokens and strip all the keywords and language-specific delimiters</li>\n<li>parsing: create an AST from the lexed tokens, then create <code>CommandLineValue</code> instances from the AST.</li>\n</ul>\n<hr />\n<h3>Conclusion</h3>\n<p>In the end, the quality of the API depends on a good specification covered by many unit tests. I feel you haven't established this yet.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T20:34:49.267", "Id": "430449", "Score": "1", "body": "Thanks. You really got me interested on compiler creation now :D\nI'll try to write my own lexer and parser." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T20:37:03.653", "Id": "430450", "Score": "1", "body": "Good to hear! Looking forward to a follow-up question ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T20:42:27.543", "Id": "430847", "Score": "0", "body": "I took your suggestions and made a follow up question. It is now using a lexer and a parser :) You can find it here: https://codereview.stackexchange.com/questions/222550/compact-command-line-argument-parser-revisited" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T19:17:39.500", "Id": "222421", "ParentId": "222418", "Score": "4" } } ]
{ "AcceptedAnswerId": "222421", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T17:22:45.143", "Id": "222418", "Score": "2", "Tags": [ "c#", "parsing", "reinventing-the-wheel", "console" ], "Title": "Compact command line argument parser" }
222418
<p>I am beginning to learn rust and I created this snake game for practice. I am looking for some feedback on my code.</p> <h3>main.rs</h3> <pre><code>extern crate rand; extern crate crossterm; mod canvas; mod snake; use std::{thread, time}; use rand::Rng; use crossterm::{cursor, terminal, input, ClearType, RawScreen, InputEvent, KeyEvent}; use canvas::Canvas; use snake::*; fn modulo(n: i16, m: i16) -&gt; i16 { return ((n % m) + m) % m; } fn main() { let terminal = terminal(); let size: (u16, u16) = terminal.terminal_size(); let width: usize = (size.0 / 2) as usize; let height: usize = (size.1) as usize; let input = input(); let _screen = RawScreen::into_raw_mode(); let mut stdin = input.read_async(); let mut canvas = Canvas::new(width, height, ' '); let mut player = Snake::new((width / 2) as i16, (height / 2) as i16, 'X', 'O'); let mut food = Piece::new( rand::thread_rng().gen_range(0, width) as i16, rand::thread_rng().gen_range(0, height) as i16, '0' ); let mut time = 0; terminal.clear(ClearType::All).expect("failed to clear terminal"); loop { time += 1; time %= 7; let cursor = cursor(); let mut should_update: bool = true; cursor.hide().expect("failed to hide cursor"); if let Some(evt) = stdin.next() { match evt { InputEvent::Keyboard(e) =&gt; { should_update = false; match e { KeyEvent::Up =&gt; player.set_vel(0, -1), KeyEvent::Down =&gt; player.set_vel(0, 1), KeyEvent::Left =&gt; player.set_vel(-1, 0), KeyEvent::Right =&gt; player.set_vel(1, 0), _ =&gt; (), } }, _ =&gt; (), } } canvas.fill(' '); if time == 0 &amp;&amp; should_update { player.update(); } player.body[0].x = modulo(player.body[0].x, width as i16); player.body[0].y = modulo(player.body[0].y, height as i16); canvas.write(1, 1, format!("Length: {}", player.body.len())); canvas.draw(food.x as usize, food.y as usize, food.ch); if player.body[0].collides(&amp;food) { food.x = rand::thread_rng().gen_range(0, width) as i16; food.y = rand::thread_rng().gen_range(0, height) as i16; player.grow(); } for (i, piece) in player.body.iter().enumerate() { canvas.draw(piece.x as usize, piece.y as usize, piece.ch); if i &gt; 0 &amp;&amp; piece.collides(&amp;player.body[0]) { player.body.truncate(i); break; } } canvas.render(cursor); thread::sleep(time::Duration::from_millis(15)); } } </code></pre> <h3>canvas.rs</h3> <pre><code>use crossterm::TerminalCursor; pub struct Canvas { w: usize, h: usize, display: Vec&lt;Vec&lt;char&gt;&gt;, } impl Canvas { pub fn new(w: usize, h: usize, fillch: char) -&gt; Canvas { return Canvas { w: w, h: h, display: vec![vec![fillch; w]; h] }; } pub fn render(&amp;self, cursor: TerminalCursor) { cursor.goto(0, 0).expect("failed to move cursor"); for row in self.display.iter() { for item in row { print!("{} ", item); } println!(""); } } pub fn draw(&amp;mut self, x: usize, y: usize, ch: char) { if x &lt; self.w &amp;&amp; y &lt; self.h { self.display[y][x] = ch; } } pub fn fill(&amp;mut self, fillch: char) { for y in 0..self.h { for x in 0..self.w { self.draw(x, y, fillch); } } } pub fn write(&amp;mut self, mut x: usize, y: usize, text: String) { for c in text.chars() { self.draw(x, y, c); x += 1; } } } </code></pre> <h3>snake.rs</h3> <pre><code>pub struct Piece { pub x: i16, pub y: i16, pub ch: char, } pub struct Snake { pub body: Vec&lt;Piece&gt;, bodych: char, vel_x: i16, vel_y: i16, } impl Piece { pub fn new(x: i16, y: i16, ch: char) -&gt; Piece { return Piece { x: x, y: y, ch: ch, }; } pub fn collides(&amp;self, piece: &amp;Piece) -&gt; bool { return self.x == piece.x &amp;&amp; self.y == piece.y; } } impl Snake { pub fn new(x: i16, y: i16, ch: char, ch2: char) -&gt; Snake { return Snake { body: vec![Piece::new(x, y, ch), Piece::new(x, y + 1, ch2)], bodych: ch2, vel_x: 0, vel_y: -1, }; } pub fn update(&amp;mut self) { for i in (1..self.body.len()).rev() { self.body[i].x = self.body[i - 1].x; self.body[i].y = self.body[i - 1].y; } self.body[0].x += self.vel_x; self.body[0].y += self.vel_y; } pub fn set_vel(&amp;mut self, x: i16, y: i16) { self.vel_x = x; self.vel_y = y; self.update(); } pub fn grow(&amp;mut self) { self.body.push(Piece::new( self.body[self.body.len() - 1].x, self.body[self.body.len() - 1].y, self.bodych )); } } </code></pre> <h3>cargo.toml</h3> <pre><code>[dependencies] crossterm = "0.9.4" rand = "0.6.5" </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T22:14:22.777", "Id": "222426", "Score": "3", "Tags": [ "beginner", "console", "rust", "snake-game" ], "Title": "Console Snake Game" }
222426
<p>To keep in practice with good techniques of java programming, I've decided to write a database. All it does it stores employees, allows users that are logged in to get/set employees, and has a login mechanism that prevents any methods from being used if you are not logged in. I'm looking for feedback in the following areas:</p> <ul> <li><strong>Structure</strong> Is the overall structure of the program good? Are there any improvements that can be made to make the structure of the program more efficient/compact?</li> <li><strong>Login Mechanism</strong> Is the way I implemented this system okay? Is there a better way I can implement this login system?</li> <li><strong>Exceptions</strong> I created two custom exceptions for this program. Is the way I coded these exceptions acceptable? Should I have had a <code>CustomException</code> class that they could inherit from, so I can just have the message in <code>printErrorMessage</code> as a parameter/hard coded? I used <code>Eclipse</code> while writing these exceptions, so the <code>serialVersionUID</code> is auto-generated.</li> <li><strong>Efficiency/Compactness</strong> Is there any way this program can be made more efficient? Such as the <code>getHighestSalary</code> method in the Database class.</li> </ul> <p>Any and all suggestions are invited and appreciated. Style and other neatness tips are encouraged as well.</p> <p><strong>Database.java</strong></p> <pre><code>package database; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Database { private ArrayList&lt;Employee&gt; employees; private final String username; private final String password; private boolean loggedIn; public Database() { this.employees = new ArrayList&lt;Employee&gt;(); this.username = generateUsername(); this.password = generatePassword(); this.loggedIn = false; populateEmployees(); } public void addEmployee(Employee employee) throws LoginException { if(loggedIn) { this.employees.add(employee); sortEmployees(); return; } throw new LoginException("Not Logged In!"); } public Employee getHighestSalary() throws LoginException { if(loggedIn) { Employee highest = this.employees.get(0); for(Employee employee : this.employees) { if(employee.getSalary() &gt; highest.getSalary()) { highest = employee; } } return highest; } throw new LoginException("Not Logged In!"); } @SuppressWarnings("unchecked") public void sortEmployees() throws LoginException { if(loggedIn) { Collections.sort((List)this.employees); return; } throw new LoginException("Not Logged In!"); } public Employee getEmployee(String name) throws EmployeeNotFoundException, LoginException { if(loggedIn) { for(Employee employee : this.employees) { if(employee.getName().equals(name)) { return employee; } } throw new EmployeeNotFoundException("Employee Not Found!"); } throw new LoginException("Not Logged In!"); } //Filler for tester class private void populateEmployees() { for(int i = 0; i &lt; 10; i++) { this.employees.add(new Employee("Employee" + i)); } } public void login(String username, String password) { if(this.username.equals(username) &amp;&amp; this.password.equals(password)) { this.loggedIn = true; } } public ArrayList&lt;Employee&gt; getEmployees() throws LoginException { if(loggedIn) { return this.employees; } throw new LoginException("Not Logged In!"); } //Used for testing private String generateUsername() { return "username123"; } //Used for testing private String generatePassword() { return "password123"; } } </code></pre> <p><strong>Employee.java</strong></p> <pre><code>package database; public class Employee { private final String name; private int age; private int salary; public Employee(String name) { this.name = name; } public Employee(String name, int age) { this.name = name; this.age = age; } public Employee(String name, int age, int salary) { this.name = name; this.age = age; this.salary = salary; } public String getName() { return this.name; } public int getAge() { return this.age; } public int getSalary() { return this.salary; } public String toString() { return "Name: " + this.name; } } </code></pre> <p><strong>LoginException.java</strong></p> <pre><code>package database; public class LoginException extends Exception { private static final long serialVersionUID = 1L; public LoginException(String message) { super(message); } public void printErrorMessage() { System.out.println("LoginException: Not logged in!"); } } </code></pre> <p><strong>EmployeeNotFoundException.java</strong></p> <pre><code>package database; public class EmployeeNotFoundException extends Exception { private static final long serialVersionUID = 1L; public EmployeeNotFoundException(String message) { super(message); } public void printErrorMessage() { System.out.println("EmployeNotFoundException: The employee you are searching for could not be found!"); } } </code></pre> <p><strong>Tester.java</strong></p> <pre><code>package database; public class Tester { @SuppressWarnings("unused") public static void main(String[] args) { Database database = new Database(); database.login("username1234", "password123"); //Should throw `LoginException` try { for(Employee employee : database.getEmployees()) { System.out.println(employee); } } catch (LoginException e) { e.printErrorMessage(); } //Should throw `EmployeeNotFoundException` try { Employee test = database.getEmployee("Ben"); } catch (EmployeeNotFoundException e) { e.printErrorMessage(); } catch (LoginException e) { e.printErrorMessage(); } } } </code></pre>
[]
[ { "body": "<h2>Structure</h2>\n\n<p><code>Database</code> does not adhere to the concept of Single Responsibility. Ignoring the test code, there are some considerations to make. I would only keep the autenthication methods and perhaps add DBMS methods as transaction functionality in this class. All ORM-related methods should be put in seperate <code>Repository</code> classes.</p>\n\n<pre><code>public class EmployeeRepository : Repository&lt;Employee&gt; {\n public void save(Employee employee) { /* .. */ }\n public void delete(int employeeId) { /* .. */ }\n public Employee Get(int employeeId) { /* .. */ }\n // and so on ..\n}\n</code></pre>\n\n<p><code>Employee</code> is an entity, but does not have a primary key. I would add an <code>int employeeId;</code>. Some fields are final, others aren't, but only getters are available. You are inconsistent. Always override <code>equals</code> and <code>hashcode</code> for entities, in order to distinguish them from other instances.</p>\n\n<hr>\n\n<h2>Login Mechanism</h2>\n\n<p>You check a plain password against a stored plain password. <strong>This is as bad a practice I can think of</strong>. Fortunately for you, many companies wouldn't even mind this flow ;-)</p>\n\n<p>You are much better of hashing the password, using a salt, perhaps some pepper using key stretching. And please don't try to implement this yourself, use <a href=\"https://howtodoinjava.com/security/how-to-generate-secure-password-hash-md5-sha-pbkdf2-bcrypt-examples/\" rel=\"nofollow noreferrer\">existing APIs</a>.</p>\n\n<hr>\n\n<h2>Exceptions</h2>\n\n<p>Your <code>*Exception</code> classes provide utility methods that write to the console. I can understand why you add them for a trivial example as this, but they wouldn't make sense otherwise. There already is the <code>message</code>. I don't understand why you don't print the message, but a hardcoded string instead.</p>\n\n<blockquote>\n<pre><code>public void printErrorMessage() {\n System.out.println(\"LoginException: Not logged in!\");\n}\n</code></pre>\n</blockquote>\n\n<pre><code> public void printErrorMessage() {\n System.out.println(e.getMessage());\n }\n</code></pre>\n\n<blockquote>\n <p>I used Eclipse while writing these exceptions, so the serialVersionUID\n is auto-generated.</p>\n</blockquote>\n\n<p>If your IDE generates code for you, do you want to know <a href=\"https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it\">why this was done</a>?</p>\n\n<hr>\n\n<h2>Efficiency/Compactness</h2>\n\n<p>Your loops can be refactored. Let's take one example.</p>\n\n<blockquote>\n<pre><code> Employee highest = this.employees.get(0);\n for(Employee employee : this.employees) {\n if(employee.getSalary() &gt; highest.getSalary()) {\n highest = employee;\n }\n }\n</code></pre>\n</blockquote>\n\n<pre><code>Employee highest = Collections.max(employees, Comparator.comparing(c -&gt; c.getSalary()));\n</code></pre>\n\n<p>How efficient is it to sort entities on the repository? This is something calling code should bother with, not the repository.</p>\n\n<pre><code> public void sortEmployees() { /* .. */ }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T13:15:28.447", "Id": "430560", "Score": "0", "body": "I would not even put the authentication methods in the repository itself. It is possible to separate the responsibility of restricting access control completely by defining the repository as an interface and storing the access control information in a thread local. Access control can then be implemented as an invisible proxy for the repository. This approach does not bind the repository to a specific kind of authentication method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T14:16:06.460", "Id": "430570", "Score": "0", "body": "@TorbenPutkonen My point exactly was to keep authentication and DBMS related stuff out of the Repository. I would see this Database class as a proxy class for all non-ORM related database actions, such as authentication. Its implementation may very well use the strategy you described." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T04:49:38.880", "Id": "222434", "ParentId": "222427", "Score": "4" } } ]
{ "AcceptedAnswerId": "222434", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T23:00:53.683", "Id": "222427", "Score": "2", "Tags": [ "java", "reinventing-the-wheel", "database", "authentication", "exception" ], "Title": "Employee database" }
222427
<p>Here is my code in Python for to find a common ancestor between two nodes in a particular tree. This is a question from Cracking the Coding Interview that I decided to implement on my own. No one has talked about the solution that I implemented below. </p> <pre><code>import unittest from Tree import * from list2BST import * def traverse_DFS(root, target_node_value, hash_route): # print('looking at node ' + str(root.value)) if root.value == target_node_value: # print('found node ' + str(target_node_value)) hash_route[root.value] = 1 return 1 else: if root.left_child: left_result = traverse_DFS(root.left_child, target_node_value, hash_route) if left_result == 1: hash_route[root.value] = 1 return 1 if root.right_child: right_result = traverse_DFS(root.right_child, target_node_value, hash_route) if right_result == 1: hash_route[root.value] = 1 return 1 common_ancestor = None def hash_check_DFS(root, target_node_value, hash_route): global common_ancestor if root.value == target_node_value: if root.value in hash_route: print('Found a common ancestor ' + str(root.value)) if common_ancestor is None: common_ancestor = root.value return 1 else: if root.left_child: left_result = hash_check_DFS(root.left_child, target_node_value, hash_route) if left_result == 1: if root.value in hash_route: if common_ancestor is None: print('Found a common ancestor ' + str(root.value)) common_ancestor = root.value return 1 if root.right_child: right_child = hash_check_DFS(root.right_child, target_node_value, hash_route) if right_child == 1: if root.value in hash_route: if common_ancestor is None: print('Found a common ancestor ' + str(root.value)) common_ancestor = root.value return 1 def find_common_node(Tree, node1, node2): global common_ancestor print('Running the common ancestry finder') # First run DFS v1 with Hash hash_route= {} print('This value of node1 is ' + str(node1)) traverse_DFS(Tree.root, node1, hash_route) print(hash_route) common_ancestor = None hash_check_DFS(Tree.root, node2, hash_route) if common_ancestor: return common_ancestor else: return None class Test(unittest.TestCase): def test_basic_odd_case(self): array = [1, 4, 5, 8, 11, 15, 18] result_tree = BinaryTree(insert_list_BST(0, array)) result_node = find_common_node(result_tree, 1, 18) self.assertEqual(result_node, 8) def test_basic_even_case(self): array = [1, 4, 5, 8, 11, 15, 18, 20] result_tree = BinaryTree(insert_list_BST(0, array)) result_node = find_common_node(result_tree, 1, 8) self.assertEqual(result_node, 5) if __name__ == '__main__': unittest.main() </code></pre> <p>Basically, I do a DFS (depth-first search) of the tree for the first node (Time: <span class="math-container">\$O(n)\$</span> and Space: <span class="math-container">\$O(1)\$</span>) and then I get the recursive callbacks to add the path to a hashmap (Time: <span class="math-container">\$O(logn)\$</span> Space: <span class="math-container">\$O(n)\$</span>). The second time around while using DFS for the second node, once I find it — I check with the hashmap till a collision occurs, indicating the lowest common ancestor. </p> <p>My Tree class is <a href="https://github.com/sd12832/ctci/blob/d3dd7a2a5de9bd53f61bf36305e60cbbb3ce4848/Tree.py" rel="noreferrer">here</a>, while my list2BST function is <a href="https://github.com/sd12832/ctci/blob/d3dd7a2a5de9bd53f61bf36305e60cbbb3ce4848/list2BST.py" rel="noreferrer">here</a>. I am looking for feedback on a couple of things: </p> <ul> <li>Performance of code and how it could possibly be improved. </li> <li>My coding style and the readability of the said code.</li> </ul> <p><strong>Notes</strong></p> <p><em>I forgot to mention that the tree does not necessarily have to be a Binary Search Tree. The only condition is that it is a Binary Tree.</em></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T06:33:43.693", "Id": "430477", "Score": "0", "body": "Since you are owner of the Tree and BinaryTree classes, is it possible to to change the implementation and add a Parent reference to them? In other words, is there a reason you did not include this property?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T08:34:40.053", "Id": "430502", "Score": "0", "body": "There is no particular reason except for the fact that a parent pointer is usually not common (from my limited experience). I am the owner of both those classes, yes. How would having a pointer to the parent improve performance?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T08:42:58.530", "Id": "430503", "Score": "3", "body": "By traversing both nodes up the ancestor list until a match in ancestors is found. This way, you don't need to traverse the entire tree all the time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T02:48:15.870", "Id": "430657", "Score": "0", "body": "Not sure what libraries/environments you work with, in things like Unity (3D engine), objects typically have a reference to their parent. Having a reference to the parent is probably much more common than you think, for the reason @dfhwze mentioned" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T10:06:29.263", "Id": "430712", "Score": "0", "body": "Got it @Mars Would it be too much to ask for an implementation with the reference to the parent?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T10:54:42.753", "Id": "430716", "Score": "1", "body": "Yeah it would ;p" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T10:56:38.007", "Id": "430718", "Score": "0", "body": "But feel free to check out this. Simply add one more property, \"parent.\" Then replace the part of `this.right/left = ` with `this.setRight(Node(data))` and set both `right` and `parent` in that function" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T02:54:03.493", "Id": "430867", "Score": "0", "body": "Wow, sorry, totally forgot to post the link for the above comment: https://www.tutorialspoint.com/python/python_binary_tree.htm" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T02:54:18.163", "Id": "430868", "Score": "0", "body": "Look at that code and the comment should make sense!" } ]
[ { "body": "<h1>Code readability and style</h1>\n\n<p>Your code has nothing wrong with style (as far as I know). It seems to be (99.9999...%) <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> compliant. </p>\n\n<p>I ran a PEP 8 checker over your code and this is what it picked up -</p>\n\n<p><a href=\"https://i.stack.imgur.com/XovGb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XovGb.png\" alt=\"enter image description here\"></a></p>\n\n<p>Which basically tells you to add a space before the operator '<code>=</code>' here -</p>\n\n<pre><code>hash_route= {}\n# hash_route = {}\n</code></pre>\n\n<p>As for the missing newline at the end of the file - there is no Python specific reason why you <em>have</em> to do this. It's just that most people <em>tend to</em> do this. pylint's <a href=\"http://pylint-messages.wikidot.com/messages:c0304\" rel=\"nofollow noreferrer\">help page on that message</a> tells you more about it:</p>\n\n<blockquote>\n <p>While Python interpreters typically do not require line end character(s) on the last line, other programs processing Python source files may do, and it is simply good practice to have it. This is confirmed in <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#line-structure\" rel=\"nofollow noreferrer\">Python docs: Line Structure</a> which states that a physical line is ended by the respective line end character(s) of the platform.</p>\n</blockquote>\n\n<hr>\n\n<p>Now let's introduce you to <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\"><em><code>f</code></em>-strings</a> -</p>\n\n<blockquote>\n <p>To create an f-string, prefix the string with the letter “ <em><code>f</code></em> ”.\n The string itself can be formatted in much the same way that you would\n with\n <a href=\"https://www.geeksforgeeks.org/python-format-function/\" rel=\"nofollow noreferrer\"><code>str.format()</code></a>.\n <em><code>f</code></em>-strings provide a concise and convenient way to embed python\n expressions inside string literals for formatting.</p>\n</blockquote>\n\n<p>Which means, instead of using the outdated way of formatting strings -</p>\n\n<pre><code>print('Found a common ancestor ' + str(root.value))\n</code></pre>\n\n<p>You could simply write it out as -</p>\n\n<pre><code>print(f'Found a common ancestor {root.value}')\n</code></pre>\n\n<p>Also, good use of the <a href=\"https://www.geeksforgeeks.org/what-does-the-if-__name__-__main__-do/\" rel=\"nofollow noreferrer\"><code>if __name__ == __'main__':</code></a> guard. Most people don't even attempt to use it.</p>\n\n<hr>\n\n<p>Another thing <a href=\"https://www.python.org/dev/peps/pep-0008/#programming-recommendations\" rel=\"nofollow noreferrer\">PEP 8</a> says that -</p>\n\n<blockquote>\n <p>Comparisons to singletons like <code>None</code> should always be done with <code>is</code> or\n <code>is not</code>, never the equality operators.</p>\n</blockquote>\n\n<p>which you have implemented really well. Most people don't do this (including me). You can read more about it <a href=\"http://jaredgrubb.blogspot.com/2009/04/python-is-none-vs-none.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<hr>\n\n<p>Overall, in terms of code readability and style, this is a well-built code (probably needs more work on performance). Good work!</p>\n\n<p>Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T04:22:58.910", "Id": "430466", "Score": "0", "body": "I mentioned a new note on my question. The question did not necessarily require me to create a binary search tree. I did it for my convenience." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T04:25:22.680", "Id": "430468", "Score": "0", "body": "f-strings, on the other hand, is very legitimate advice. I read through the article and am totally convinced that this the way to go - especially with the multiline stuff." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T04:26:42.940", "Id": "430469", "Score": "0", "body": "I guess it doesn't help me :( Sorry, it is my mistake for not including that crucial detail." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T04:27:39.660", "Id": "430470", "Score": "1", "body": "@SharanDuggirala - I have removed the content. I have left anything that might help you. Hope this helps!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T04:29:09.457", "Id": "430471", "Score": "1", "body": "Thanks for the compliment on using the `__name__ == '__main__'`. I believe that it is essential for using the Python style unit testing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T04:30:54.717", "Id": "430472", "Score": "1", "body": "@SharanDuggirala - Yes, it is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T04:32:38.817", "Id": "430473", "Score": "1", "body": "It really does help though. Exactly the kind of advice I came here looking for." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T13:00:05.810", "Id": "430558", "Score": "3", "body": "I believe there is some part of POSIX that specifies that text files end with a newline. So, if you don't have the newline, then your file is technically not a text file, which means that technically, the OS is not required to process it as a script, which means that if some OS vendor is an extreme stickler for the rules, then a shebang line will not work. (Although the shebang line isn't specified anywhere, so such an extreme OS will probably not implement them anyway.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T13:04:10.627", "Id": "430559", "Score": "3", "body": "@JörgWMittag Yes, [it’s a POSIX rule](https://stackoverflow.com/a/729795/1968). However, the implication isn’t that the system could legally refuse to treat it as a script (at least I’m not aware of any such rule, even implicitly). Rather, the issue is simply that some tools will not correctly handle the file; for instance, a conforming `sed` implementation might not handle the last line. In practice, up to date GNU sed and BSD sed both do (though slightly differently)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T14:29:50.013", "Id": "430572", "Score": "0", "body": "@Toby Speight - Thanks for the edit. I might have been in a hurry." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T03:55:08.503", "Id": "222432", "ParentId": "222429", "Score": "7" } }, { "body": "<p>You seem to make use often <code>return 1</code>. It would be better to use booleans to show a clear intention of what you want to return.</p>\n\n<p>Also, your <code>hash_route</code>, which you build as a <code>dict</code>, has a constant value that is never used, making it effectively a <code>set</code>, which is fine if all you care is the lowest common ancestor.</p>\n\n<p>I would go for:</p>\n\n<pre><code>def traverse_DFS(root, target_node_value, ancestor_set):\n # print('looking at node ' + str(root.value))\n if root.value == target_node_value:\n # print('found node ' + str(target_node_value))\n ancestor_set.add(root.value)\n return True\n else:\n if root.left_child:\n left_result = traverse_DFS(root.left_child, target_node_value,\n ancestor_set)\n if left_result:\n ancestor_set.add(root.value)\n return True\n if root.right_child:\n right_result = traverse_DFS(root.right_child, target_node_value,\n ancestor_set)\n if right_result:\n ancestor_set.add(root.value)\n return True\n return False\n</code></pre>\n\n<p>I would also get rid of <code>common_ancestor</code> global variable (avoid them whenever you can, and also when you think you cannot, since you most probably can anyway). You can easily carry that information in the return value, together with the flag for the found node.</p>\n\n<pre><code>def hash_find_ancestor_DFS(root, target_node_value, ancestor_set):\n\n if root.value == target_node_value:\n if root.value in ancestor_set:\n return (True, root.value)\n else:\n return (True, None)\n else:\n if root.left_child:\n (found, ancestor) = hash_find_ancestor_DFS(root.left_child, target_node_value,\n ancestor_set)\n if found:\n if ancestor:\n return (True, ancestor)\n elif root.value in ancestor_set:\n return (True, root.value)\n else:\n return (True, None)\n\n if root.right_child:\n (found, ancestor) = hash_find_ancestor_DFS(root.right_child, target_node_value,\n ancestor_set)\n if found:\n if ancestor:\n return (True, ancestor)\n elif root.value in ancestor_set:\n return (True, root.value)\n else:\n return (True, None)\n\n return (False, None)\n</code></pre>\n\n<p>For completeness, this would be the other function:</p>\n\n<pre><code>def find_common_node(Tree, node1, node2):\n print('Running the common ancestry finder')\n\n # First run DFS v1 with Hash\n hash_route= set()\n print('This value of node1 is ' + str(node1))\n found = traverse_DFS(Tree.root, node1, hash_route)\n\n if not found:\n return None\n print(hash_route)\n (found, common_ancestor) = hash_find_ancestor_DFS(Tree.root, node2, hash_route)\n\n return common_ancestor\n</code></pre>\n\n<p>I added a check to shortcut the second search if the node is not found in the first.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T09:44:27.843", "Id": "222450", "ParentId": "222429", "Score": "5" } }, { "body": "<p>The main piece of advice I feel I can offer is to avoid using the asterix\n<code>from list2BST import *</code></p>\n\n<p>This makes it much harder for other users to work out where individual functions are coming from. It is much better practice to say</p>\n\n<p><code>import list2BST</code> </p>\n\n<p>and then </p>\n\n<p><code>list2BST.&lt;function name&gt;</code> </p>\n\n<p>or \n<code>from list2BST import &lt;function_1&gt;, &lt;function_2&gt;</code></p>\n\n<p>I have copied below my own implementation of this if you are interested in looking. The code is much shorter and I build, print and search the BST in a single module. I also use fewer variables and I think my approach is fairly intuitive. I have added this for comparison though because other than my comment above, I cannot think of anything else you can do to improve your code</p>\n\n<pre><code>\"\"\"\"Module to find lowest common ancestor of BST\"\"\"\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Node:\n \"\"\"BST class\"\"\"\n\n value: int\n left: None = None\n right: None = None\n\n def add_child(self, value):\n \"\"\"Add child to BST\"\"\"\n if self.value:\n if value &lt; self.value:\n if self.left:\n self.left.add_child(value)\n else:\n self.left = Node(value)\n else:\n if self.right:\n self.right.add_child(value)\n else:\n self.right = Node(value)\n\n def print_tree(self, level=0):\n \"\"\"Print the BST\"\"\"\n if self.value:\n print(\" \" * level, self.value)\n if self.left:\n self.left.print_tree(level + 1)\n if self.right:\n self.right.print_tree(level + 1)\n\n def explore(self, node, lst_ancestors):\n \"\"\"Explore BST to find ancestors of node\"\"\"\n if self.value:\n if self.value == node:\n lst_ancestors.append(self.value)\n return True, lst_ancestors\n if self.left:\n left_true = self.left.explore(node, lst_ancestors)\n if left_true:\n lst_ancestors.append(self.value)\n return True, lst_ancestors\n if self.right:\n right_true = self.right.explore(node, lst_ancestors)\n if right_true:\n lst_ancestors.append(self.value)\n return True, lst_ancestors\n\n def common_ancestor(self, node1, node2):\n \"\"\"Find common ancestors\"\"\"\n _, list_1 = self.explore(node1, [])\n _, list_2 = self.explore(node2, [])\n common_nodes = set(list_1).intersection(list_2)\n if common_nodes:\n print(f\"The LCA node of {node1} and {node2} is {list(common_nodes)[0]}\")\n else:\n print(f\"There is no LCA for {node1} and {node2}\")\n\n\nif __name__ == \"__main__\":\n n = Node(5)\n n.add_child(3)\n n.add_child(4)\n n.add_child(2)\n n.add_child(7)\n n.add_child(6)\n n.add_child(8)\n\n node1 = 2\n node2 = 6\n n.common_ancestor(node1, node2)\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T12:37:09.460", "Id": "430736", "Score": "0", "body": "@SharanDuggirala I have included my code for this problem too for comparison" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T09:58:45.607", "Id": "222514", "ParentId": "222429", "Score": "2" } } ]
{ "AcceptedAnswerId": "222450", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T00:33:25.600", "Id": "222429", "Score": "11", "Tags": [ "python", "performance", "python-3.x", "tree", "hash-map" ], "Title": "Find the common ancestor between two nodes of a tree" }
222429
<p>I'm studying Object-oriented Programming and decided to apply some things doing an Object-oriented Tic-Tac-Toe.<br> I wanted to know if you have some hints of what to improve and why! </p> <pre><code>class Board: """Represents one board to a Tic-Tac-Toe game.""" def __init__(self): """Initializes a new board. A board is a dictionary which the key is the position in the board and the value can be 'X', 'O' or ' ' (representing an empty position in the board.)""" self.board = { "TL": " ", "TM": " ", "TR": " ", "ML": " ", "MM": " ", "MR": " ", "BL": " ", "BM": " ", "BR": " "} def print_board(self): """Prints the board.""" print(self.board["TL"] + "|" + self.board["TM"] \ + "|" + self.board["TR"] + "|") print("-+" * 3) print(self.board["ML"] + "|" + self.board["MM"] \ + "|" + self.board["MR"] + "|") print("-+" * 3) print(self.board["BL"] + "|" + self.board["BM"] \ + "|" + self.board["BR"] + "|") def _is_valid_move(self, position): if self.board[position] is " ": return True return False def change_board(self, position, type): """Receive a position and if the player is 'X' or 'O'. Checks if the position is valid, modifies the board and returns the modified board. Returns None if the move is not valid.""" if self._is_valid_move(position): self.board[position] = type return self.board return None def is_winner(self, player): """Returns True if the player won and False otherwise.""" if self.board["TL"] == player.type and self.board["TM"] == player.type and self.board["TR"] == player.type or \ self.board["ML"] == player.type and self.board["MM"] == player.type and self.board["MR"] == player.type or \ self.board["BL"] == player.type and self.board["BM"] == player.type and self.board["BR"] == player.type or \ self.board["TL"] == player.type and self.board["ML"] == player.type and self.board["BL"] == player.type or \ self.board["TM"] == player.type and self.board["MM"] == player.type and self.board["BM"] == player.type or \ self.board["TR"] == player.type and self.board["MR"] == player.type and self.board["BR"] == player.type or \ self.board["TL"] == player.type and self.board["MM"] == player.type and self.board["BR"] == player.type or \ self.board["BL"] == player.type and self.board["MM"] == player.type and self.board["TR"] == player.type: return True return False class Player: """Represents one player.""" def __init__(self, type): """Initializes a player with type 'X' or 'O'.""" self.type = type def __str__(self): return "Player {}".format(self.type) class Game: """Represents a Tic-Tac-Toe game. The game defines player 1 always playing with 'X'.""" def __init__(self): """Initilize 2 Players and one Board.""" self.player1 = Player("X") self.player2 = Player("O") self.board = Board() def print_valid_entries(self): """Prints the valid inputs to play the game.""" print(""" TL - top left | TM - top middle | TR - top right ML - middle left | MM - center | MR - middle right BL - bottom left | BM - bottom middle | BR - bottom right""") def printing_board(self): """Prints the board.""" self.board.print_board() def change_turn(self, player): """Changes the player turn. Receives a player and returns the other.""" if player is self.player1: return self.player2 else: return self.player1 def won_game(self, player): """Returns True if the player won the game, False otherwise.""" return self.board.is_winner(player) def modify_board(self, position, type): """Receives position and player type ('X' or 'O'). Returns modified board if position was valid. Asks to player try a different position otherwise.""" if self.board.change_board(position, type) is not None: return self.board.change_board(position, type) else: position = input("Not available position. Please, try again: ") return self.board.change_board(position, type) def play(): game = Game() game.print_valid_entries() player = game.player1 num = 9 while num &gt; 0: num -= 1 game.printing_board() position = input("{} turn, what's your move? ".format(player)) game.modify_board(position, player.type) if game.won_game(player): print("{} is the Winner!".format(player)) break else: player = game.change_turn(player) if num == 0: print("Game over! It's a tie!") if __name__ == "__main__": play() </code></pre>
[]
[ { "body": "<h1>Code readability and style</h1>\n\n<p>I would recommend you have a look at <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP 8</a>, which is Python's official style guide.</p>\n\n<p>Let's introduce you to <a href=\"https://realpython.com/python-f-strings/\" rel=\"noreferrer\"><em><code>f-strings</code></em></a> -</p>\n\n<blockquote>\n <p>To create an f-string, prefix the string with the letter “ <em><code>f</code></em> ”.\n The string itself can be formatted in much the same way that you would\n with\n <a href=\"https://www.geeksforgeeks.org/python-format-function/\" rel=\"noreferrer\"><code>str.format()</code></a>.\n <em>f-strings</em> provide a concise and convenient way to embed python\n expressions inside string literals for formatting.</p>\n</blockquote>\n\n<p>So, I would write these three statements -</p>\n\n<blockquote>\n<pre><code># rest of the code\ndef __str__(self):\n return \"Player {}\".format(self.type)\n# rest of the code\n\nposition = input(\"{} turn, what's your move? \".format(player))\n# rest of the code\nprint(\"{} is the Winner!\".format(player))\n</code></pre>\n</blockquote>\n\n<p>Like this -</p>\n\n<pre><code># rest of the code\ndef __str__(self):\n return f\"Player {self.type}\"\n# rest of the code \n\nposition = input(f\"{player} turn, what's your move? \")\n# rest of the code\nprint(f\"{player} is the Winner!\")\n</code></pre>\n\n<p>See how concise it can get?</p>\n\n<hr>\n\n<p>From <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"noreferrer\">PEP 8</a> -</p>\n\n<blockquote>\n <p><a href=\"https://www.python.org/dev/peps/pep-0257\" rel=\"noreferrer\">PEP 257</a> describes good\n docstring conventions. Note that most importantly, the <code>\"\"\"</code> that ends\n a multiline docstring should be on a line by itself -</p>\n\n<pre><code>\"\"\"Return a foobang\n\nOptional plotz says to frobnicate the bizbaz first.\n\"\"\"\n</code></pre>\n \n <p>For one liner docstrings, please keep the closing <code>\"\"\"</code> on the same\n line.</p>\n</blockquote>\n\n<p>So, for example, this -</p>\n\n<blockquote>\n<pre><code>\"\"\"Receives position and player type ('X' or 'O').\nReturns modified board if position was valid.\nAsks to player try a different position otherwise.\"\"\"\n</code></pre>\n</blockquote>\n\n<p>Should actually be written as -</p>\n\n<pre><code>\"\"\"Receives position and player type ('X' or 'O').\nReturns modified board if position was valid.\nAsks to player try a different position otherwise.\n\"\"\"\n</code></pre>\n\n<hr>\n\n<p>Also, since you have descriptively named functions, you don't need those unnecessary comments explaining what your function does. For example, this does not need a comment - </p>\n\n<blockquote>\n<pre><code>def printing_board(self):\n \"\"\"Prints the board.\"\"\"\n self.board.print_board()\n</code></pre>\n</blockquote>\n\n<p>We know you're printing the board; it says in the function itself - <code>def printing_board(self)</code>.</p>\n\n<p>Also, good use of the <a href=\"https://www.geeksforgeeks.org/what-does-the-if-__name__-__main__-do/\" rel=\"noreferrer\"><code>if '__name__' == __'main__':</code></a> guard. Most people don't even attempt to use it.</p>\n\n<hr>\n\n<p>Note that the trailing <code>\\</code> solutions are not recommended by PEP 8. One reason is that if space is added by mistake after a <code>\\</code> it might not show in your editor, and the code becomes syntactically incorrect.</p>\n\n<p>The PEP changed at <a href=\"https://hg.python.org/peps/rev/7a48207aaab6\" rel=\"noreferrer\">https://hg.python.org/peps/rev/7a48207aaab6</a> to explicitly discourage backslashes.</p>\n\n<blockquote>\n <p>The preferred way of wrapping long lines is by using Python's implied\n line continuation inside parentheses, brackets, and braces. Long lines\n can be broken over multiple lines by wrapping expressions in\n parentheses. These should be used in preference to using a backslash\n for line continuation.</p>\n</blockquote>\n\n<p>Another thing is that, here (for example) -</p>\n\n<blockquote>\n<pre><code>if self.board[\"TL\"] == player.type and self.board[\"TM\"] == player.type and self.board[\"TR\"] == player.type or \\\nself.board[\"ML\"] == player.type and self.board[\"MM\"] == player.type and self.board[\"MR\"] == player.type or \\\nself.board[\"BL\"] == player.type and self.board[\"BM\"] == player.type and self.board[\"BR\"] == player.type or \\\nself.board[\"TL\"] == player.type and self.board[\"ML\"] == player.type and self.board[\"BL\"] == player.type or \\\nself.board[\"TM\"] == player.type and self.board[\"MM\"] == player.type and self.board[\"BM\"] == player.type or \\\nself.board[\"TR\"] == player.type and self.board[\"MR\"] == player.type and self.board[\"BR\"] == player.type or \\\nself.board[\"TL\"] == player.type and self.board[\"MM\"] == player.type and self.board[\"BR\"] == player.type or \\\nself.board[\"BL\"] == player.type and self.board[\"MM\"] == player.type and self.board[\"TR\"] == player.type:\n</code></pre>\n</blockquote>\n\n<p>the lines are too long. According to <a href=\"https://www.python.org/dev/peps/pep-0008/#maximum-line-length\" rel=\"noreferrer\">PEP 8</a> -</p>\n\n<blockquote>\n <p>Limit all lines to a maximum of 79 characters.</p>\n</blockquote>\n\n<p>Therefore, these statements could alternatively be written as -</p>\n\n<pre><code>def is_winner(self, player):\n player_type = player.type\n runs = [\n # horizontal\n [\"TL\", \"TM\", \"TR\"],\n [\"ML\", \"MM\", \"MR\"],\n [\"BL\", \"BM\", \"BR\"],\n # vertical\n [\"TL\", \"ML\", \"BL\"],\n [\"TM\", \"MM\", \"BM\"],\n [\"TR\", \"MR\", \"BR\"],\n # diagonal\n [\"TL\", \"MM\", \"BR\"],\n [\"BL\", \"MM\", \"TR\"]\n ]\n for a, b, c in runs:\n if self.board[a] == self.board[b] == self.board[c] == player_type:\n return True\n return False\n</code></pre>\n\n<hr>\n\n<p>Overall, in terms of code readability and style, this is what you need to improve. You should make your code more PEP 8 compliant.</p>\n\n<p>Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T05:50:58.287", "Id": "430475", "Score": "1", "body": "Thank you!! That was really helpful, I'll look PEP 8 now, with more attention." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T12:28:30.920", "Id": "430552", "Score": "1", "body": "So, I was changing my code using those hints but the last one didn't work in here. Now, it doesn't access the value player.type correctly, so 'X O X' is a win point. I tried ```self.board[\"TL\"] and self.board[\"TM\"] and self.board[\"TR\"] == player.type ``` too, but it didn't work as well. Any idea of what happened??" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T15:49:01.527", "Id": "430598", "Score": "1", "body": "@AndressaCabistani - I have edited my answer to make some changes. This should definitely work. Sorry for any confusion :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T16:03:10.610", "Id": "430605", "Score": "1", "body": "Thank you so much again!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T16:09:24.927", "Id": "430607", "Score": "1", "body": "Now it works perfectly!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T16:09:49.050", "Id": "430609", "Score": "1", "body": "@AndressaCabistani - I'm glad it helped you :)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T04:23:01.150", "Id": "222433", "ParentId": "222431", "Score": "5" } }, { "body": "<p>You can use list comprehension as well as the built-in <code>all()</code> and <code>any()</code> methods to make your <code>is_winner()</code> method more concise and readable:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def is_winner(self, player):\n \"\"\"Returns True if the player won and False otherwise.\"\"\"\n row1 = [self.board[val] for val in [\"TL\",\"TM\",\"TR\"]]\n row2 = [self.board[val] for val in [\"ML\",\"MM\",\"MR\"]]\n row3 = [self.board[val] for val in [\"BL\",\"BM\",\"BR\"]]\n col1 = [self.board[val] for val in [\"TL\",\"ML\",\"BL\"]]\n col2 = [self.board[val] for val in [\"TM\",\"MM\",\"BM\"]]\n col3 = [self.board[val] for val in [\"TR\",\"MR\",\"BR\"]]\n dia1 = [self.board[val] for val in [\"TL\",\"MM\",\"BR\"]]\n dia2 = [self.board[val] for val in [\"TR\",\"MM\",\"BL\"]]\n wins = [row1, row2, row3, col1, col2, col3, dia1, dia2]\n\n isPlayer = lambda cell: cell == player.type\n isWinner = lambda seq: all(map(isPlayer, seq))\n if any(map(isWinner, wins)):\n ''' Returns true if any possible win is a win '''\n return True\n else:\n return False\n</code></pre>\n\n<p>The code to get all of the possible win combinations could have been made more concise if the board was represented by a 2D array rather than a <code>dict</code> as you have it; but the explicit nature of assigning the values of each row still has its benefits.</p>\n\n<hr>\n\n<p>Messed around and made a more DRY way of building the <code>wins</code> array, but the nested list comprehension is arguably less readable/understandable. Nonetheless, here it is just for fun:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>wins = [[self.board[cell] for cell in seq] \n for seq in [ \n [\"TL\",\"TM\",\"TR\"], # Row 1\n [\"ML\",\"MM\",\"MR\"], # Row 2\n [\"BL\",\"BM\",\"BR\"], # Row 3\n [\"TL\",\"ML\",\"BL\"], # Col 1\n [\"TM\",\"MM\",\"BM\"], # Col 2\n [\"TR\",\"MR\",\"BR\"], # Col 3\n [\"TL\",\"MM\",\"BR\"], # Dia 1\n [\"TR\",\"MM\",\"BL\"] # Dia 2\n ] \n]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T23:20:38.700", "Id": "240659", "ParentId": "222431", "Score": "3" } } ]
{ "AcceptedAnswerId": "222433", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T03:14:16.983", "Id": "222431", "Score": "8", "Tags": [ "python", "beginner", "python-3.x", "object-oriented", "tic-tac-toe" ], "Title": "Python3 OOP Tic-Tac-Toe" }
222431
<p>Monitors DB2 for changes in table data. It doesn't take any actions with the data just yet, only checks to see if new data is available every 2 seconds.</p> <pre><code>const { dbconn, dbstmt } = require('idb-connector');// require idb-connector // global for storing row data in var data = '' async function queryDB() { const sSql = `SELECT * FROM LIBNAME.TABLE`; // create new promise let promise = new Promise ( function(resolve, reject) { // create new connection const connection = new dbconn(); connection.conn("*LOCAL"); const statement = new dbstmt(connection); statement.exec(sSql, (rows, err) =&gt; { if (err) { throw err; } // check if data is new if (data === rows) { resolve('no new data') } else { data = rows; resolve('new data arrived'); }; // close DB connections statement.close(); connection.disconn(); connection.close(); }) }); let result = await promise;// await promise return result; }; async function checkDB2() { const status = await queryDB();// check for new data if (status === 'new data arrived') { // new data action }; setTimeout(checkDB2, 2000);// check again in 2 seconds }; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T05:56:55.917", "Id": "222437", "Score": "1", "Tags": [ "javascript", "node.js", "async-await", "promise", "db2" ], "Title": "DB2 monitor using idb-connector" }
222437
<p>I have created dynamic Bootstrap 4 modal using JavaScript OOP. Please verify and give your reviews how I can improve the code. I have passed four parameters to create a dynamic modal:</p> <ol> <li><code>openPopup</code> class (for click)</li> <li><code>data-title</code> (dynamic title)</li> <li><code>data-href</code> (dynamic load html in modal)</li> <li><code>data-target</code> (target id if i have multiple modal)</li> </ol> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> class Modal{ constructor(id,url,title){ this.id = id; this.url = url; this.title = title; } } class UI{ static addModal(){ $('body').on('click', '.openPopup', function(e) { const id = $(this).attr('data-target'), url = $(this).attr('data-href'), title = $(this).attr('data-title') const modal = new Modal(id, url, title); console.log(modal) if($('#'+ modal.id).length){ $('#'+ modal.id).modal({show:true}); } else{ let html = ` &lt;div class="modal fade" id="${modal.id}" tabindex="-1" role="dialog"&gt; &lt;div class="modal-dialog modal-dialog-centered" role="document"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;h5 class="modal-title" id="exampleModalLongTitle"&gt;${modal.title} &lt;/h5&gt; &lt;button type="button" class="close" data-dismiss="modal" aria- label="Close"&gt; &lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt; &lt;/button&gt; &lt;/div&gt; &lt;div id="${modal.id}body" class="modal-body"&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button type="button" class="btn btn-secondary" data- dismiss="modal"&gt;Close&lt;/button&gt; &lt;button type="button" id="save" class="btn btn-primary"&gt;Save changes&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;`; $('body').append(html); $('#'+ modal.id + 'body').load(modal.url,function(){ $('#'+ modal.id).modal({show:true}); }); } }) }} class ModalApp{ static init(){ console.log('App Started...'); UI.addModal() } } ModalApp.init();</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;button type="button" class="btn btn-primary openPopup" data-title="Test about" data-href="partial/about.html" data-toggle="modal" data- target="myModal1"&gt; Launch demo about &lt;/button&gt;</code></pre> </div> </div> </p> <p>See the fiddle below</p> <p><a href="https://jsfiddle.net/5cgm1axp/" rel="nofollow noreferrer">JSfiddle</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T07:10:21.793", "Id": "430483", "Score": "0", "body": "i want you guys review my JavaScript code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T07:53:46.790", "Id": "430499", "Score": "0", "body": "What were your objectives when you created this code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T08:28:15.310", "Id": "430501", "Score": "0", "body": "quality of code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T10:02:47.773", "Id": "430535", "Score": "0", "body": "Take a look at [this coding style guide](https://javascript.info/coding-style)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T06:13:46.090", "Id": "222438", "Score": "3", "Tags": [ "javascript", "object-oriented", "jquery", "html", "twitter-bootstrap" ], "Title": "Dynamic Bootstrap 4 modal using JavaScript OOP" }
222438
<p>I started to have HUGE doubts regarding my code and I need some advice from more experienced programmers and architects.</p> <p>On the button click, the application runs a method, that is running a <code>ScrapJockeys</code> with parameters:</p> <p><code>if (UpdateJockeysPl) await ScrapJockeys(JPlFrom, JPlTo + 1, "jockeysPl"); //1 - 1049</code></p> <p>Purpose of this is to scrap some data from web service and parse it with a model:</p> <pre><code>public class LoadedJockey { public string Name { get; set; } public string Link { get; set; } public List&lt;JockeyRaceDetails&gt; AllRaces { get; set; } } </code></pre> <p>When the data is parsed, object is added to <code>ObeservableCollection&lt;LoadedJockey&gt;</code> and the collection is saved. Thanks to this, and based on the data the application can do computation of Jockey performace in the past.</p> <p>And now more about the method and problems with the method:</p> <p>I have a method, that is triggering a <code>for</code> loop, repeating between 20K - 150K times. Inside the loop I need to call a service method, that execution of the method takes a lot of time. Also I wanted to have ability of canellation of the loop and everyting what is going on inside of the loop/method.</p> <p>Right now I have a method with list of tasks, and inside of the loop is trigerred a <code>Task.Run</code>. And inside of each task I am calling awaited service method. Also each task has assigned cancellation token, like <a href="https://github.com/przemyslawbak/Horse_Picker/blob/190f4549375c9e499c393dc2f3b734a0b802dd8a/Horse_Picker/ViewModels/MainViewModel.cs#L1657" rel="nofollow noreferrer">IN THE EXAMPE</a>:</p> <pre><code>public async Task ScrapJockeys(int startIndex, int stopIndex, string dataType) { //init values and controls CommandStartedControlsSetup("UpdateDataCommand"); List&lt;Task&gt; tasks = new List&lt;Task&gt;(); int loopCounter = 0; ProgressBarTick("Looking for jockeys", loopCounter, stopIndex, startIndex); for (int i = startIndex; i &lt; stopIndex; i++) { if (TaskCancellation == true) { break; } int j = i; Task task = Task.Run(async () =&gt; { LoadedJockey jockey = new LoadedJockey(); CancellationToken.ThrowIfCancellationRequested(); if (dataType == "jockeysPl") jockey = await _scrapServices.ScrapSingleJockeyPlAsync(j); if (dataType == "jockeysCz") jockey = await _scrapServices.ScrapSingleJockeyCzAsync(j); if (jockey.Name != null) { lock (((ICollection)Jockeys).SyncRoot) { //if objects are already in the List if (Jockeys.Any(h =&gt; h.Name.ToLower() == jockey.Name.ToLower())) { LoadedJockey doubledJockey = Jockeys.Where(h =&gt; h.Name.ToLower() == jockey.Name.ToLower()).FirstOrDefault(); Jockeys.Remove(doubledJockey); MergeJockeysData(doubledJockey, jockey); } else { Jockeys.Add(jockey); } } } loopCounter++; //saves all every 1000 records, just in case if (loopCounter % 1000 == 0) { await _dataServices.SaveAllJockeysAsync(Jockeys.ToList()); } ProgressBarTick("Looking for jockeys", loopCounter, stopIndex, startIndex); }, TokenSource.Token); tasks.Add(task); } try { await Task.WhenAll(tasks); } catch (OperationCanceledException) { // } finally { await _dataServices.SaveAllJockeysAsync(Jockeys.ToList()); //saves everything to JSON file AllControlsEnabled = true; CommandCompletedControlsSetup(); VisibilityCancellingMsg = Visibility.Collapsed; } } </code></pre> <p>So my question is, is everything fine with my code? According to <a href="https://blog.stephencleary.com/2013/10/taskrun-etiquette-and-proper-usage.html" rel="nofollow noreferrer">THIS ARTICLE</a>:</p> <blockquote> <p>Many async newbies start off by trying to treat asynchronous tasks the same as parallel (TPL) tasks, and this is a major misstep.</p> </blockquote> <p>What should I use then?</p> <p>And according to <a href="https://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-dont-use.html" rel="nofollow noreferrer">THIS ARTICLE</a>:</p> <blockquote> <p>On a busy server, this kind of implementation can kill scalability.</p> </blockquote> <p>So how am I supposed to do it?</p> <p>Please be noted, that service interface method signature is <code>Task&lt;LoadedJockey&gt; ScrapSingleJockeyPlAsync(int index);</code></p> <p>And also i am not 100% sure that I am using <code>Task.Run</code> correctly within my service class. The methods inside are wrapping the code inside <code>await Task.Run(() =&gt;</code>, like <a href="https://github.com/przemyslawbak/Horse_Picker/blob/190f4549375c9e499c393dc2f3b734a0b802dd8a/Horse_Picker/DataServices/ScrapDataServices.cs#L566" rel="nofollow noreferrer">IN THE EXAMPLE</a>:</p> <pre><code>public async Task&lt;LoadedJockey&gt; ScrapSingleJockeyPlAsync(int index) { LoadedJockey jockey = new LoadedJockey(); await Task.Run(() =&gt; { int n; List&lt;JockeyRaceDetails&gt; allRaces = new List&lt;JockeyRaceDetails&gt;(); for (int year = DateTime.Now.Year; year &gt; 2013; year--) { StringBuilder sb = new StringBuilder(); sb.Append("https://koniewyscigowe.pl/dzokej?d="); sb.Append(index); sb.Append("&amp;sezon="); sb.Append(year); sb.Append("#wyniki_koni"); string link = sb.ToString(); HtmlAgilityPack.HtmlWeb web = new HtmlAgilityPack.HtmlWeb(); HtmlAgilityPack.HtmlDocument doc = web.Load(link); //gets the name of the jockey if (jockey.Name == null) { try { HtmlNode singleNode = doc.DocumentNode.SelectSingleNode("/html/body/main/section[1]/div[1]/h3"); string racersName = singleNode.OuterHtml.ToString(); if (racersName.Contains("Jeździec") &amp;&amp; racersName.Length &gt; 65) { racersName = racersName.Split('&gt;')[1].Split(new string[] { " - " }, StringSplitOptions.None)[1].Split('&lt;')[0].Trim(' '); if (racersName.Contains(" ")) { char letter = racersName[0]; racersName = racersName.Split(' ')[1].Trim(' '); racersName = letter + ". " + racersName; } racersName = MakeTitleCase(racersName); jockey.Name = racersName; //jockeys name } else { racersName = ""; } } catch (Exception e) { } } //scrap races HtmlNode[] tableRow = doc.DocumentNode.SelectNodes("//*[@id=\"wykaz_list\"]/tbody/tr").ToArray(); if (tableRow != null &amp;&amp; tableRow.Length &gt; 0) { foreach (var row in tableRow) { string stringTableRow = row.OuterHtml.ToString(); //all races //if row not contains 'brak startow' and contains m (meters) if (!stringTableRow.Contains("Brak danych") &amp;&amp; (stringTableRow.Contains("&amp;nbsp;m") || stringTableRow.Contains(" m"))) { try { JockeyRaceDetails race = new JockeyRaceDetails(); string raceDate = stringTableRow.Split('&gt;')[3].Split('&lt;')[0].Trim(' '); string raceDistance = stringTableRow.Split('&gt;')[8].Split(' ')[0].Trim(' '); string horsesName = stringTableRow.Split('&gt;')[10].Split('&lt;')[0].Trim(' '); horsesName = MakeTitleCase(horsesName); string raceScore = stringTableRow.Split('&gt;')[12].Split('&lt;')[0].Trim(' '); string racePlace = raceScore.Split('/')[0].Trim(' '); string raceCompetitors = raceScore.Split('/')[1].Trim(' '); race = ParseJockeyRaceData(raceDate, raceDistance, horsesName, raceScore, racePlace, raceCompetitors); allRaces.Add(race); } catch (Exception e) { } } } } } jockey.AllRaces = allRaces; //jockeys races between 2015-2019 jockey.Link = "https://koniewyscigowe.pl/dzokej?d=" + index; //racers link if (jockey.AllRaces.Count == 0) { jockey.Name = null; } }); return jockey; } </code></pre> <p>As far as I understand from the articles, this is kind of anti-pattern. But I am confused a bit. Basing on <a href="https://stackoverflow.com/a/56187088/11027921">THIS SO REPLY</a>, it should be fine...? If not, how to replace it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T07:33:41.857", "Id": "430493", "Score": "1", "body": "@dfhwze i saw your reply. With `j` I was passing proper `ID` to the service. It is based on similar case: https://stackoverflow.com/a/33275940/11027921" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T07:46:35.753", "Id": "430496", "Score": "1", "body": "@bakunet It seems my knowledge of C# is rusty. My answer is only valid for very old versions and will never see daylight again! :p" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T07:49:39.750", "Id": "430497", "Score": "1", "body": "@dfhwze hehe, cool :) My biggest concern is about proper using of `Task.Run`. Mr **Stephen Cleary** is suggesting in his articles, that I am doing it wrong. But in his **SO** reply he said nothing about that. So I am confused now." } ]
[ { "body": "<blockquote>\n<pre><code> if (TaskCancellation == true)\n {\n break;\n }\n</code></pre>\n</blockquote>\n\n\n\n<blockquote>\n<pre><code> CancellationToken.ThrowIfCancellationRequested();\n</code></pre>\n</blockquote>\n\n<p>Some comments explaining why two different cancellation methods are necessary would be useful.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (jockey.Name != null)\n {\n lock (((ICollection)Jockeys).SyncRoot)\n {\n //if objects are already in the List\n if (Jockeys.Any(h =&gt; h.Name.ToLower() == jockey.Name.ToLower()))\n {\n LoadedJockey doubledJockey = Jockeys.Where(h =&gt; h.Name.ToLower() == jockey.Name.ToLower()).FirstOrDefault();\n Jockeys.Remove(doubledJockey);\n MergeJockeysData(doubledJockey, jockey);\n }\n else\n {\n Jockeys.Add(jockey);\n }\n }\n }\n</code></pre>\n</blockquote>\n\n<p>There are at least four code smells here:</p>\n\n<ol>\n<li>Using <code>Name</code> as a primary key. With real world data, what prevents two jockeys from having the same name?</li>\n<li>Using an <code>ICollection</code> for something which clearly needs to be an <code>IDictionary</code>, given the way its contents are looked up.</li>\n<li><pre><code>if (collection.Any(predicate))\n{\n variable = collection.Where(predicate).FirstOrDefault();\n</code></pre>\n\n<p>searches twice, when one search suffices:</p>\n\n<pre><code>variable = collection.FirstOrDefault(predicate);\nif (variable != null)\n{\n</code></pre></li>\n<li>If <code>MergeJockeysData</code> doesn't modify <code>Jockeys</code> then data would seem to be lost, but if it does modify then the data flow is being obfuscated.</li>\n</ol>\n\n<hr>\n\n<blockquote>\n<pre><code> try\n {\n await Task.WhenAll(tasks);\n }\n catch (OperationCanceledException)\n {\n //\n }\n finally\n {\n await _dataServices.SaveAllJockeysAsync(Jockeys.ToList()); //saves everything to JSON file\n</code></pre>\n</blockquote>\n\n<p><code>Task.WhenAll</code> is a blunt weapon. If there could be hundreds of tasks, you may find that you get better performance by placing a cap on the number of tasks which are executed simultaneously. This requires a lazy enumerator of tasks and a loop with <code>Task.WhenAny</code>.</p>\n\n<p>If an <code>OperationCanceledException</code> is thrown, does it really make sense to save the partial results?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> HtmlAgilityPack.HtmlWeb web = new HtmlAgilityPack.HtmlWeb();\n HtmlAgilityPack.HtmlDocument doc = web.Load(link);\n</code></pre>\n</blockquote>\n\n<p>This seems to me to be missing the point of <code>async</code>. It would make a lot more sense to me to first use <code>System.Net.WebClient.DownloadStringAsync</code> to do the IO asynchronously, and then load the string into HtmlAgilityPack for the CPU-bound part. In fact, unless memory consumption is an issue it probably makes sense to have a producer-consumer setup where multiple async tasks do IO and a single <code>Task.Run</code> does the parsing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T08:56:10.603", "Id": "430507", "Score": "0", "body": "For more info about that `WhenAny` part, Microsoft describes it as Interleaving/Throttling: https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/consuming-the-task-based-asynchronous-pattern" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T09:39:01.853", "Id": "430531", "Score": "0", "body": "`TaskCancellation == true` breaks started loops; `CancellationToken.ThrowIfCancellationRequested();` cancels tasks; But I will double check, if I REALLY have to use the first one...; **Using Name as a primary key.** for data scrapping, if in returned object I will not get the name, the object is useless. And not each html document provides it; **Using an ICollection** why dictionary, if `Jockeys` is a collection? **3.** where did you find this? **4.** I will have to verify it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T08:39:01.957", "Id": "222441", "ParentId": "222439", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T07:10:49.403", "Id": "222439", "Score": "5", "Tags": [ "c#", "performance", "async-await", "mvvm", "task-parallel-library" ], "Title": "Scraping an parsing jockeys data using Task.Run" }
222439
<p>I am a newcomer to the Julia world, so I started trying to implement a very simple program:</p> <ul> <li>Sample a signal</li> <li>Reconstruct it (various ways, just rectangular for now)</li> <li>Plot it</li> </ul> <p>Everything is fine and 'working' properly, but coming from a OOP (java) and functional (python) background, I'm thinking that the following snippet can be improved to be in a more julia-ish style:</p> <pre><code>(required packages: DSP, Plots, PyPlot) # parameters Ts = 0.02; n = 0:(100 / Ts); f0 = 5; dt = 0.001; t = 0:dt:10; # sampling x = sin.(2 * pi * f0 * Ts * n); # target signal to sample # reconstruct (need improvement) rectangular_reconstr(i) = x[floor(Int, i * (length(n) / length(t)) + 1)] x_recon_sinc = [rectangular_reconstr(e) for e in 1:(length(t)-1)] </code></pre> <p>I'm concerned about this list comprehension. Essentially, create a function that maps indices from <code>(sampled) -&gt; reconstructed</code> is the whole idea here. If you were to do other kinds of interpolation (via spline, triangular or whatever), you can even access all the elements of the sampled array. </p> <p>Is there any better alternative than this loop-comprehension version?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-25T04:21:02.810", "Id": "431664", "Score": "1", "body": "You can get a 5-fold improvement in performance by using a `const` in place of `length(n) / length(t)` in your function, thus avoiding a recalculation of that ratio for every invocation. Because your method simply replicates the data points in the middle of `x` point by point, you can get an additional improvement by simply interleaving the middle values and concatenating with `x[1]` and `x[5000]` as follows: `vcat(x[1], [x[2:5000] x[2:5000]]'[:], x[5001])`. The `[x[2:5000] x[2:5000]]'[:]` does the interleave. Benchmark means are 2.227 ms, 444.37 μs, and 277.84 μs, respectively." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-25T10:18:43.703", "Id": "431707", "Score": "0", "body": "@EdwardCarney That interleaving would implicitly only render this feasible for a reconstruction frequency that is only 2 times the sampling frequency. Can you do a dynamic interleaving with n arrays/vectors?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T08:55:10.370", "Id": "222443", "Score": "2", "Tags": [ "beginner", "signal-processing", "julia" ], "Title": "Sampling and Reconstructing a signal in Julia" }
222443
<p>The other day I ran into <a href="https://stackoverflow.com/questions/11468333/linux-threads-suspend-resume/56607278">this question on stackoverflow</a>. Just for curiosity I wanted to implement suspending and resuming the thread, so I used signals and used <code>pause()</code> in the signal handler.</p> <p>Is it OK to use this way? This question has many answers how to suspend/resume a thread, but I want to know what is wrong with my approach.</p> <p>As far as I know signal handlers should be treated as interrupts i.e. minimum code and immediate return from it.</p> <p>According to <a href="https://docs.oracle.com/cd/E19455-01/806-5257/gen-26/index.html" rel="nofollow noreferrer">this</a>, <code>pause()</code> is async-signal safe system call.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;unistd.h&gt; #include &lt;pthread.h&gt; #include &lt;signal.h&gt; // Since I have only 2 threads so using two variables, // array of bools will be more useful for `n` number of threads. static int is_th1_ready = 0; static int is_th2_ready = 0; static void cb_sig(int signal) { switch(signal) { case SIGUSR1: pause(); break; case SIGUSR2: break; } } static void *thread_job(void *t_id) { int i = 0; struct sigaction act; pthread_detach(pthread_self()); sigemptyset(&amp;act.sa_mask); act.sa_flags = 0; act.sa_handler = cb_sig; if (sigaction(SIGUSR1, &amp;act, NULL) == -1) printf("unable to handle siguser1\n"); if (sigaction(SIGUSR2, &amp;act, NULL) == -1) printf("unable to handle siguser2\n"); if (t_id == (void *)1) is_th1_ready = 1; if (t_id == (void *)2) is_th2_ready = 1; while (1) { printf("thread id: %p, counter: %d\n", t_id, i++); sleep(1); } return NULL; } int main() { int terminate = 0; int user_input; pthread_t thread1, thread2; pthread_create(&amp;thread1, NULL, thread_job, (void *)1); // Spawned thread2 just to make sure it isn't suspended/paused // when thread1 received SIGUSR1/SIGUSR2 signal pthread_create(&amp;thread2, NULL, thread_job, (void *)2); while (!is_th1_ready &amp;&amp; !is_th2_ready); while (!terminate) { // to test, I am sensing signals depending on input from STDIN printf("0: pause thread1, 1: resume thread1, -1: exit\n"); scanf("%d", &amp;user_input); switch(user_input) { case -1: printf("terminating\n"); terminate = 1; break; case 0: printf("raising SIGUSR1 to thread1\n"); pthread_kill(thread1, SIGUSR1); break; case 1: printf("raising SIGUSR2 to thread1\n"); pthread_kill(thread1, SIGUSR2); break; } } pthread_kill(thread1, SIGKILL); pthread_kill(thread2, SIGKILL); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T10:10:10.220", "Id": "430538", "Score": "0", "body": "I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have." } ]
[ { "body": "<p>This is a useful question because it illustrates how a seemingly working program using pthreads can be loaded with pitfalls. I hope that you take this answer in the spirit in which it is intended, which is to help you improve your programming. I didn't see any major problems with the way you're using signals.</p>\n\n<h2>Consider using standard threads</h2>\n\n<p>You may already know this, but since C11, threads are now <a href=\"https://en.cppreference.com/w/c/thread\" rel=\"nofollow noreferrer\">part of the standard</a>. Using them instead of POSIX threads (pthreads) could make the program, in theory anyway, somewhat more portable. I'll make no further mention of that, however, and the rest will deal with pthreads, although most of the suggestions still apply.</p>\n\n<h2>Think carefully about using non-standard calls</h2>\n\n<p><strike>The <code>sigemptyset()</code> call is neither a C nor a POSIX standard. While it's widely supported, it isn't really portable, strictly speaking. That may be fine for your purposes, but it's important to know which calls are standard and which are not to improve the portability of your program.</strike> (I was actually thinking of <code>sigisemptyset</code> here — my mistake!)</p>\n\n<h2>Use a mutex to access shared resources</h2>\n\n<p>Both threads are attempting to use <code>printf</code> but that's a problem because that requires access to a <em>shared resource</em>, namely <code>stdout</code>. Access <code>printf</code> within POSIX threads are <a href=\"https://stackoverflow.com/questions/467938/stdout-thread-safe-in-c-on-linux\">guaranteed to be thread safe</a>, but the output could be scrambled (that is, the letters from two different threads could be intermixed). One could use a <code>mutex</code> to assure that only one thread at a time is using that resource. Here's one way to do that:</p>\n\n<pre><code>#include &lt;stdarg.h&gt;\n\nstatic pthread_mutex_t stdout_mutex = PTHREAD_MUTEX_INITIALIZER;\n\nstatic int locking_printf(const char *format, ...) {\n va_list args;\n va_start(args, format);\n pthread_mutex_lock(&amp;stdout_mutex);\n int retval = vprintf(format, args);\n pthread_mutex_unlock(&amp;stdout_mutex);\n va_end(args);\n return retval;\n}\n</code></pre>\n\n<p>Then replace every instance of <code>printf</code> with <code>locking_printf</code>, including the ones in <code>main</code> since that's a thread, too.</p>\n\n<h2>Match return types with function</h2>\n\n<p>There's no need to write <code>return NULL;</code> at the end of <code>thread_job</code> because it's a <code>void</code> function. Also, it's my view that one should omit <code>return 0;</code> from the end of main. It's always contentious because others disagree (often very passionately!), but <a href=\"https://stackoverflow.com/a/43558724/3191481\">here's the rationale.</a></p>\n\n<h2>Use <code>bool</code> types where appropriate</h2>\n\n<p>The <code>is_th1_ready</code> and <code>is_th2_ready</code> variables are more appropriately described as <code>bool</code> rather than <code>int</code> variables. For that reason, I'd recommend using <code>&lt;stdbool.h&gt;</code> and writing their declaration and initialization like this:</p>\n\n<pre><code>static bool is_th1_ready = false;\nstatic bool is_th2_ready = false;\n</code></pre>\n\n<h2>Think about casting</h2>\n\n<p>Creating the threads uses this kind of call:</p>\n\n<pre><code>pthread_create(&amp;thread2, NULL, thread_job, (void *)2);\n</code></pre>\n\n<p>That's fine and appropriate. However, the later use of that data within the thread is a bit unusual:</p>\n\n<pre><code>if (t_id == (void *)1)\n is_th1_ready = 1;\n</code></pre>\n\n<p>It's perfectly technically valid, but the more conventional approach is to cast the passed <code>void *</code> into something intelligible to the local thread -- often this is a pointer to a <code>struct</code> containing multiple values. In this case, I'd probably write it like this instead:</p>\n\n<pre><code>if ((int)t_id == 1)\n is_th1_ready = true;\n</code></pre>\n\n<p>On my machine this causes a compiler warning because <code>int</code> and <code>void *</code> are not the same size (on this machine, with this compiler), but that's not a problem because we know with certainty that this is, in fact, an <code>int</code>. Another approach would be to do the cast once in the creation of a local <code>int</code> variable.</p>\n\n<h2>Rethink the use of <code>scanf</code></h2>\n\n<p>If the user enters a letter or some other non-numeric input, the <code>scanf</code> input fails and the user loses control of the application. It's well known that <code>scanf</code> <a href=\"https://stackoverflow.com/questions/32393392/when-do-we-need-to-clear-the-scanf-buffer\">has problems</a>. For that reason, I'd recommend instead using <code>fgets</code> and then <code>strtod</code>.</p>\n\n<pre><code>char buf[5]; // we don't need a big buffer\nfgets(buf, sizeof buf, stdin);\nswitch(strtol(buf, NULL, 10)) {\n</code></pre>\n\n<p>This will interpret any \"garbage\" input as 0, but that's probably OK for this program. Note also that for POSIX systems, non-numeric input can be detected by looking at the <code>errno</code> value.</p>\n\n<h2>Prefer <code>for</code> to <code>while</code> where appropriate</h2>\n\n<p>The only use of <code>terminate</code> is within the loop, so I'd suggest changing from <code>while</code> to <code>for</code> like this:</p>\n\n<pre><code>for (bool running = true; running; ) {\n</code></pre>\n\n<p>Note that I've inverted the sense to eliminate the need to negate. The compiler would probably have done something like that anyway, but I think it's more clear for human readers this way.</p>\n\n<h2>Don't bother killing threads at exit</h2>\n\n<p>The return from <code>main</code> or a call to <code>exit()</code> will both cause the threads to be cleaned up and resources returned, so I would probably omit the two <code>pthread_kill</code> calls at the end of <code>main</code>.</p>\n\n<h2>Consider more robust error handling</h2>\n\n<p>It's nice that the code is checking the return value of <code>sigaction</code>, but should the thread even launch if we can't handle the signals? It's a design choice, but one worth considering, in my opinion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T17:34:29.963", "Id": "430623", "Score": "0", "body": "One possible reason to clean up when exiting is if using Valgrind or similar tool, and don't want these to show up as unreleased resources. In which case, it should be an *optional* behaviour (not the default)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T17:49:43.593", "Id": "430625", "Score": "0", "body": "@TobySpeight: True. Another approach is to not detach the threads and to use join instead. If I were writing this, that's how I'd do it because in this case, there is no reason that one would want the threads truly running detached (e.g. running independently after `main` ends)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T18:10:27.177", "Id": "430632", "Score": "0", "body": "Quite right - that was a general comment on motivation, without actually studying the code! I was extrapolating from \"unnecessary\" memory release. Yes, joining is the most appropriate way to clean up worker threads." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T03:44:43.167", "Id": "430658", "Score": "0", "body": "I Understood the point of not using standard functions for the ease of portability. `sigemptyset` is confirming to POSIX.1-2001, POSIX.1-2008 standards. -- from the man page." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T03:46:19.407", "Id": "430659", "Score": "0", "body": "@Edward, what about using `pause()` in signal handler?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T04:57:52.667", "Id": "430661", "Score": "1", "body": "The use of `pause` looks fine to me, and you’re right about `sigemptyset` - it’s `sigisemptyset` (which your code doesn’t use) that’s not POSIX. I’ll correct my answer." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T17:00:17.187", "Id": "222476", "ParentId": "222451", "Score": "3" } } ]
{ "AcceptedAnswerId": "222476", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T09:59:46.687", "Id": "222451", "Score": "4", "Tags": [ "c", "multithreading", "signal-handling" ], "Title": "Suspend and resume a thread using signals" }
222451
<p>I am new to Javascript and Node.js but wanted to create a minifier in order to minify and escape double quotes in the HTML file. Could you let me know what I could improve in the code and how I can make it more efficient.</p> <p>Here is my code:</p> <pre><code>'use strict'; var minify = require('html-minifier').minify; const fs = require('fs'); var dir = './minifiedHTML'; if (!fs.existsSync(dir)){ fs.mkdirSync(dir); } var tagsToReplace = { '"': '\"' }; var htmlFile = fs.readFileSync("testminify.html", "utf8"); var result = minify(htmlFile, { collapseWhitespace: true, minifyCSS: true, processConditionalComments: true }); result = addslashes(result) fs.writeFile('minifiedHTML/minified.html', result, (err) =&gt; { // throws an error, you could also catch it here if (err) throw err; // success case, the file was saved console.log('HTML file saved!'); }); function addslashes( str ) { return (str + '').replace(/[\\"]/g, '\\$&amp;').replace(/\u0000/g, '\\0'); } </code></pre>
[]
[ { "body": "<pre><code>var minify = require('html-minifier').minify;\nconst fs = require('fs');\nvar dir = './minifiedHTML';\n</code></pre>\n\n<p>Try consistently using <code>const</code>, <code>let</code> or <code>var</code> when declaring variables. Also, try using <code>const</code> first. That way, you're ensured that you are always dealing with the same thing through that variable throughout the lifetime of the app, and that any attempts to replace it would warn you. Use <code>let</code> if the value needs replacing (i.e. a counter) and <code>var</code> if the variable has to be function-scoped.</p>\n\n<pre><code>fs.writeFile('minifiedHTML/minified.html', result, (err) =&gt; { \n // throws an error, you could also catch it here\n if (err) throw err;\n\n // success case, the file was saved\n console.log('HTML file saved!');\n});\n</code></pre>\n\n<p>You're using synchronous APIs for everything except when writing to the file. I recommend also using the synchronous version of writing to a file, <code>fs.writeFileSync()</code> to keep it consistent. Your script is simple, and it's not blocking anything else, so making everything synchronous should be fine.</p>\n\n<p>I'm making a big guess. You're trying to embed this HTML in JSON or JavaScript, and you're escaping the quotes so that it won't terminate the script mid-string. If possible, don't embed HTML (or any arbitrary string really). Just have it carry data, and let the receiving page do the rendering instead. Or you could encode the data in base64 so that it doesn't have quotes at all.</p>\n\n<hr>\n\n<p>My initial guess was not that far from the intended goal. Building JSON with HTML content IS NOT an issue if you're building the JSON correctly. <code>JSON.stringify()</code> will correctly escape content that would otherwise break the resulting JSON (i.e. it will escape quotes). The only time escaping becomes an issue is when you're building the JSON <em>manually</em>.</p>\n\n<p>Do NOT do the following:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const title = 'your title'\nconst subject = 'your subject'\nconst html = '&lt;html lang=\"en\"&gt;&lt;body class=\"has-content\"&gt;Hello, World!&lt;/body&gt;&lt;/html&gt;'\nconst json = `{ \"title\": \"${title}\", \"subject\": \"${subject}\", \"html\": \"${html}\" }`\n\nconsole.log('Invalid JSON:', json)\n\n// This will blow up\nconsole.log('Test parse', JSON.parse(json))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Instead, use <code>JSON.stringify()</code>:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const title = 'your title'\nconst subject = 'your subject'\nconst html = '&lt;html lang=\"en\"&gt;&lt;body class=\"has-content\"&gt;Hello, World!&lt;/body&gt;&lt;/html&gt;'\nconst json = JSON.stringify({ title, subject, html })\n\nconsole.log('Valid JSON:', json)\nconsole.log('Test parse', JSON.parse(json))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T12:58:00.120", "Id": "430557", "Score": "0", "body": "@Joesph I don't know if this should be a separate question, but the goal of this is to create an email template which is a JSON file with Subject and text. the html part is in the middle '{\n \"subject\": \"subject line\",\n \"html\": \"html\",\n \"text\": \"text.\"\n}'" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T13:51:41.663", "Id": "430565", "Score": "1", "body": "@user6248190 Updated answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T12:34:24.027", "Id": "222459", "ParentId": "222457", "Score": "3" } } ]
{ "AcceptedAnswerId": "222459", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T11:47:49.957", "Id": "222457", "Score": "2", "Tags": [ "javascript", "beginner", "node.js" ], "Title": "HTML & CSS Minifier" }
222457
<p>I'm a bit new to PowerShell (version 5) and was wondering if there are any improvements I could make to the following script. Any suggestions for style, code, etc. are all welcome.</p> <p>The script creates a csv of file attributes and extended properties recursively from a directory parameter. I'm going to then load the csv files into SQL Server. </p> <p>I'm not sure if there is a more efficient way of filtering the files by last modified date. I need to run it against 30 million files in batches of 500,000.</p> <p>I've included an example of the UNC path that I use to produce the results file name in the <code>$searchPath</code> variable.</p> <p>I'm currently running this script in a <code>.bat</code> file. Is there a better way of running these scripts concurrently?</p> <h3>PowerShell Script</h3> <pre><code>$searchPath = '\\server\ca$\los angeles\documents\*.*'; #An example of the path format used as a parameter for $args[0] $resultsFileName = ''; $startDate = '01-Jul-2018'; $endDate = '31-Jul-2019'; $shell = New-Object -COMObject Shell.Application; #set date defaults $dateTimeFormat = 'dd-MMM-yyyy HH:mm:ss.fff'; $executeStart = Get-Date; $executeStart = $executeStart.ToString($dateTimeFormat); Write-Host 'Execute Start:' $executeStart; #get the parent folder from the search path Write-Host 'Search Path:' $searchPath; $folder = ($searchPath).Substring(1, ($searchPath).Length - 4); $parent = Split-Path $folder; #if the path is not in the expected format dont set the results file name if($parent.Length -gt 2) { #get the state name $state = Split-Path $parent; $state = Split-Path $state -Leaf; $state = $state -replace '\$',''; $state = $state.ToLower(); #get the office name $office = Split-Path $parent -Leaf; $office = $office -replace '\W','-'; $office = $office.ToLower(); $resultsFileName = $state + '_' + $office; }; #format the result file name and path $resultFileTimestamp = Get-Date -format 'yyyyMMdd_HHmmss.fff'; if($resultsFileName -eq '') {$resultsFileName = 'results_' + $resultsFileName + '_' + $resultFileTimestamp}; $resultsFile = "C:\Temp\Results\$resultsFileName.csv"; Write-Host 'Results File:' $resultsFile; $linenumber = 1; #get the file attributes from the recursively from the search path Get-Childitem -recurse -Path $searchPath | ? {($_.LastWriteTime -gt $startDate -AND $_.LastWriteTime -lt $endDate) -OR ($_.CreationTime -gt $startDate -AND $_.CreationTime -lt $endDate)} | ForEach-Object { $fullName = $_.FullName; $folder = Split-Path $fullName; $file = Split-Path $fullName -Leaf; $shell = New-Object -COMObject Shell.Application; $shellfolder = $shell.Namespace($folder); $shellfile = $shellfolder.ParseName($file); #loop through the extended properties looking for the columns we want for ($a ; $a -le 325; $a++) { if($shellfolder.getDetailsOf($File, $a)) { $keyValue = $shellfolder.GetDetailsOf($null, $a) switch ( $keyValue ) { 'Attributes' { $Attributes = $shellfolder.GetDetailsOf($shellfile, $a) } 'Title' { $Title = $shellfolder.GetDetailsOf($shellfile, $a) } 'Authors' { $Authors = $shellfolder.GetDetailsOf($shellfile, $a) } 'Last printed' { $LastPrinted = $shellfolder.GetDetailsOf($shellfile, $a) } 'Date last saved' { $DateLastSaved = $shellfolder.GetDetailsOf($shellfile, $a) } 'Pages' { $Pages = $shellfolder.GetDetailsOf($shellfile, $a) } 'Word count' { $WordCount = $shellfolder.GetDetailsOf($shellfile, $a) } 'Total editing time' { $TotalEditingTime = $shellfolder.GetDetailsOf($shellfile, $a) } 'File count' { $FileCount = $shellfolder.GetDetailsOf($shellfile, $a) } } } } $a=0; #format extended properties $LastPrinted = $LastPrinted -replace '[^\p{L}\p{Nd}/(/}/_/:/ ]', ''; #replace non date characters if($LastPrinted -ne '') {$LastPrinted = [datetime]::parseexact($LastPrinted, 'd/MM/yyyy h:mm tt', $null).ToString($dateTimeFormat) } else {$LastPrinted = 'NULL'}; $DateLastSaved = $DateLastSaved -replace '[^\p{L}\p{Nd}/(/}/_/:/ ]', ''; #replace non date characters if($DateLastSaved -ne '') {$DateLastSaved = [datetime]::parseexact($DateLastSaved, 'd/MM/yyyy h:mm tt', $null).ToString($dateTimeFormat) } else {$DateLastSaved = 'NULL'}; $Title = $Title.replace("`n","").replace("`r",""); #remove carriage return line feed from string $Authors = $Authors.replace("`n","").replace("`r",""); #remove carriage return line feed from string #show the user what file number the script is on $currentFileDateTime = Get-Date -format $dateTimeFormat; Write-Host $linenumber, $currentFileDateTime, $fullName; #format the output of the csv file Get-Content $fullName | Measure-Object -Character -Word | ` Select-Object -ExcludeProperty Property ` @{ Name = 'LineNumber'; Expression={$linenumber}} ` , @{ Name = 'ExtractTime'; Expression={ Get-Date -format $dateTimeFormat }} ` , @{ Name = 'FullName'; Expression={ $fullName }} ` , @{ Name = 'FilePath'; Expression={ $folder }} ` , @{ Name = 'FileName'; Expression={ $file }} ` , @{ Name = 'FileSizeKb'; Expression={ (Get-Item $fullName).length / 1024 }} ` , @{ Name = 'CreationTime'; Expression={(Get-ChildItem $fullName).CreationTime.ToString($dateTimeFormat) }} ` , @{ Name = 'LastWriteTime'; Expression={(Get-ItemProperty $fullName).LastWriteTime.ToString($dateTimeFormat) }} ` , @{ Name = 'Attributes'; Expression={ $Attributes.ToString() }} ` , @{ Name = 'Title'; Expression={ $Title.ToString() }} ` , @{ Name = 'Authors'; Expression={ $Authors.ToString() }} ` , @{ Name = 'LastPrinted'; Expression={ $LastPrinted.ToString() }} ` , @{ Name = 'LastSaved'; Expression={ $DateLastSaved.ToString() }} ` , @{ Name = 'PageCount'; Expression={ $Pages.ToString() }} ` , @{ Name = 'WordCount'; Expression={ $WordCount.ToString() }} ` , Characters ` , @{ Name = 'TotalEditingTime'; Expression={ $TotalEditingTime.ToString() }} ` , @{ Name = 'FileCount'; Expression={ $FileCount.ToString() }}; ` $linenumber ++ ` } | Export-Csv -NoTypeInformation -Path $resultsFile; $executeEnd = Get-Date; $executeEnd = $executeEnd.ToString($dateTimeFormat); Write-Host 'Execute End:' $executeEnd; </code></pre> <h3>Example of CSV file</h3> <p><a href="https://i.stack.imgur.com/TqHWS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TqHWS.png" alt="screenshot"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T14:24:21.797", "Id": "430571", "Score": "1", "body": "What is the purpose of the script?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T15:02:25.637", "Id": "430579", "Score": "0", "body": "To create a CSV of file attributes from multiple directories. I'm going to then load the CSV files into SQL server." } ]
[ { "body": "<p>As <code>ForEach-Object</code> and <code>Where-Object</code> are slow, you had better to use the <code>foreach</code> statement instead of them when working with large data.<br/>\nAlso, because it is useless to get all extended properties, narrow down the property numbers to be obtained in advance.<br/>\nAlthough <code>Select-Object</code> is useful, it will be slower if you use \"calculated property\", so it is better to create a new object directly using <code>[pscustomobject]@{}</code>.</p>\n\n<pre><code># settings\n$startDate = Get-Date \"01-Jul-2018\"\n$endDate = Get-Date \"31-Mar-2029\"\n$resultDir = mkdir \"E:\\tets\\Results\" -Force\n$dateTimeFormat = \"dd-MMM-yyyy HH:mm:ss.fff\"\n$pathList = @(\n \"\\\\server\\ca$\\los angeles\\documents\"\n \"\\\\server\\ca$\\san diego\\documents\"\n \"\\\\server\\ca$\\san francisco\\documents\"\n)\n\n$exAttr = @{\n Title = 21\n Authors = 20\n LastPrinted = 200\n LastSaved = 154\n Pages = 157\n WordCount = 160\n TotalEditingTime = 159\n FileCount = 163\n}\n\n\n# start\n\"Execute Start: {0}\" -f (Get-Date -Format $dateTimeFormat) | Write-Host\n\n$shell = New-Object -Com Shell.Application\n\nforeach ($path in $pathList) {\n\n # create a result file.\n $targetDir = Get-Item -LiteralPath $path\n $resultFileName = \"{0}_{1}_{2}.csv\" -f @(\n $targetDir.Parent.Parent.Name.TrimEnd(\"$\").ToLower()\n $targetDir.Parent.Name.ToLower() -replace \"\\W\",\"-\"\n Get-Date -Format yyyyMMdd_HHmmss.fff\n )\n $resultsFile = New-Item -Path $resultDir -Name $resultFileName -Force\n\n $lineNumber = 1\n\n # create customized file information objects.\n $list = foreach ($file in Get-Childitem $targetDir -File -Recurse) {\n\n if ($file.LastWriteTime -le $startDate -or $file.LastWriteTime -ge $endDate) { continue }\n\n $exData = @{}\n\n # get extended properties of office file.\n if ($file.Extension -in \".docx\",\".xlsx\") {\n $dirObj = $shell.NameSpace($file.DirectoryName)\n $itemObj = $dirObj.ParseName($file.Name)\n $exAttr.GetEnumerator() | &amp; { process { $exData[$_.Key] = $dirObj.GetDetailsOf($itemObj, $_.Value) -replace \"\\p{Cf}\" } }\n\n [void][Runtime.InteropServices.Marshal]::ReleaseComObject($itemObj)\n [void][Runtime.InteropServices.Marshal]::ReleaseComObject($dirObj)\n }\n\n [pscustomobject]@{\n LineNumber = $lineNumber++\n ExtractTime = Get-Date -format $dateTimeFormat\n FullName = $file.FullName\n FilePath = $file.DirectoryName\n FileName = $file.Name\n FileSize = $file.Length / 1KB\n CreationTime = $file.CreationTime.ToString($dateTimeFormat)\n LastWriteTime = $file.LastWriteTime.ToString($dateTimeFormat)\n Attributes = -join ($file.Attributes.Split(\",\") | &amp; { process { $_.TrimStart()[0] } })\n Title = $exData.Title\n Authors = $exData.Authors\n LastPrinted = if ($exData.LastPrinted) { Get-Date $exData.LastPrinted -Format $dateTimeFormat } else { $null }\n LastSaved = if ($exData.LastSaved) { Get-Date $exData.LastSaved -Format $dateTimeFormat } else { $null }\n PageCount = $exData.Pages\n WordCount = $exData.WordCount\n TotalEditingTime = $exData.TotalEditingTime\n FileCount = $exData.FileCount\n }\n }\n\n # output to csv file.\n $list | Export-Csv $resultsFile -NoTypeInformation\n $resultsFile\n}\n\n[void][Runtime.InteropServices.Marshal]::ReleaseComObject($shell)\n\n\"`nExecute End: {0}`n\" -f (Get-Date -Format $dateTimeFormat) | Write-Host\n</code></pre>\n\n<p>If you want to run in parallel, there is a way to use <code>Start-Job</code>.</p>\n\n<pre><code>$scriptBlock = {\n param(\n $path,\n $startDate,\n $endDate,\n $resultDir,\n $dateTimeFormat\n )\n\n $exAttr = @{\n ...\n }\n $shell = New-Object -Com Shell.Application\n\n # create a result file.\n $targetDir = Get-Item -LiteralPath $path\n ...\n ...\n}\n\n$pathList | foreach { $i = 0 } { Start-Job -Name $_ -ScriptBlock $scriptBlock -ArgumentList $_,$startDate,$endDate,$resultDir,$dateTimeFormat }\n</code></pre>\n\n<p>If file retrieval and filtering is a bottleneck, you can write partially in C#.</p>\n\n<pre><code>Add-Type -TypeDefinition @\"\nusing System;\nusing System.IO;\nusing System.Collections.Generic;\n\npublic static class MyFileIO\n{\n public static List&lt;FileInfo&gt; GetFiles(DirectoryInfo dir, DateTime startDate, DateTime endDate)\n {\n var files = new List&lt;FileInfo&gt;();\n var queue = new Queue&lt;DirectoryInfo&gt;();\n queue.Enqueue(dir);\n while (queue.Count &gt; 0)\n {\n dir = queue.Dequeue();\n foreach (var subDir in dir.GetDirectories()) queue.Enqueue(subDir);\n foreach(var file in dir.GetFiles())\n if(file.LastWriteTime &gt; startDate &amp;&amp; file.LastWriteTime &lt; endDate) files.Add(file);\n }\n return files;\n }\n}\n\"@\n\nforeach ($file in [MyFileIO]::GetFiles($targetDir, $startDate, $endDate)) {\n ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-23T23:29:52.063", "Id": "431483", "Score": "0", "body": "This is amazing! Thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-23T23:24:25.143", "Id": "222830", "ParentId": "222458", "Score": "2" } } ]
{ "AcceptedAnswerId": "222830", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T12:33:38.737", "Id": "222458", "Score": "2", "Tags": [ "beginner", "powershell", "properties" ], "Title": "Create a csv of file attributes recursively from a directory parameter in PowerShell" }
222458
<p>I am having some trouble figuring out how to modularize this code without rewriting it entirely. I know I should be able to break it up into modules for main, gathering info, doing calculation and the example sum array that's out of place, but in to meet requirements.</p> <pre><code> #include &lt;iostream&gt; #include &lt;iomanip&gt; // Going to use for width and precision #include &lt;cmath&gt; // Going to use for monthly payment calc for the power function #include &lt;string&gt; using namespace std; int main() { // Variables Declared string name; // Name of user float loanAmt = 0; // Requested loan Amount int years = 0; // Loan term in years float interestRate = 0; // Annual APR, I think I need to take this number, divide by 100 to get decimal, and use decimal in calculations double months2Pay = 0; // years *12 double interestMonthlyRate = 0; // interest rate / 12 double monthlyPayments = 0; // Final Monthly Payments double interestRateDecimal = 0; // interest rate /100 double totalInterestPaid = 0; double finalTotalPaid = 0; char yes; const int loanInformation = 1, seeLoanInfo = 2, exitProgram = 3; int pickAChoice; int arrayExample[8]; int arraySum = 0; cout &lt;&lt; "\n\n ***********************************************" &lt;&lt; endl; cout &lt;&lt; " * *" &lt;&lt; endl; cout &lt;&lt; " * Monthly Payment Calculator *" &lt;&lt; endl; cout &lt;&lt; " * *" &lt;&lt; endl; cout &lt;&lt; " ***********************************************" &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; "Greetings and welcome to the loan calculator!\n" &lt;&lt; endl; // Main Menu - options 1,2,3,4 do { cout &lt;&lt; "Main Menu\n\n" &lt;&lt; "1. Enter loan information.\n" &lt;&lt; "2. View loan results.\n" &lt;&lt; "3. Adding with arrays example.\n" &lt;&lt; "3. Exit\n\n" &lt;&lt; "Select an option: "; cin &gt;&gt; pickAChoice; while (pickAChoice &lt; loanInformation || pickAChoice &gt; exitProgram) { cout &lt;&lt; "Invalid selection. Please renter choice 1, 2 or 3: "; cin &gt;&gt; pickAChoice; } if (pickAChoice == 1) { // Loan Information here cout &lt;&lt; "\nWhat is your name: "; cin &gt;&gt; name; cout &lt;&lt; "\nTotal loan amount: $"; cin &gt;&gt; loanAmt; cout &lt;&lt; "\nLoan term (in years): "; cin &gt;&gt; years; cout &lt;&lt; "\nInterest Rate per year: % "; cin &gt;&gt; interestRate; // Loan Calculations here interestRateDecimal = interestRate / 100; months2Pay = years * 12; interestMonthlyRate = interestRateDecimal / 12; monthlyPayments = (loanAmt * pow(interestMonthlyRate + 1, months2Pay) * interestMonthlyRate) / (pow(interestMonthlyRate + 1, months2Pay) - 1); finalTotalPaid = monthlyPayments * months2Pay; totalInterestPaid = finalTotalPaid - loanAmt; cout &lt;&lt; "\nPlease select option 2 to view results.\n"; } if (pickAChoice == 2) { // 2 decimal points for currency format in output cout.setf(ios::fixed); // 2 decimal points for currency format cout.setf(ios::showpoint); cout.precision(2); // Display results, format this nicer cout &lt;&lt; endl; cout &lt;&lt; "Hello " &lt;&lt; name &lt;&lt; "!" &lt;&lt; " Your request loan results are below." &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; " Total Loan Amount: $" &lt;&lt; loanAmt &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; " You will have " &lt;&lt; months2Pay &lt;&lt; " total payments." &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; " Your monthly payment is $" &lt;&lt; monthlyPayments &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; " The total amount paid back is $" &lt;&lt; finalTotalPaid &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; " Your total interest paid is $" &lt;&lt; totalInterestPaid &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; "\nTo enter different loan information, select option 1.\n"; } if (pickAChoice == 3) { cout &lt;&lt; endl; cout &lt;&lt; "This will calculate the sum of all 8 of your number choices.\n\n"; for (int x = 0; x &lt; 8; x++) { cout &lt;&lt; "Enter 8 intergers to calculate the sum: "; cin &gt;&gt; arrayExample[x]; arraySum += arrayExample[x]; } cout &lt;&lt; "\nThe total sum of your 8 integers is " &lt;&lt; arraySum &lt;&lt; "." &lt;&lt; endl &lt;&lt; endl; } } while (pickAChoice != exitProgram); system("pause"); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T14:37:57.877", "Id": "430573", "Score": "2", "body": "If you're looking for help re-writing your code, then this probably isn't the right place. If you want a review of **any and all aspects of the code** (perhaps, but not necessarily, with suggestions), then welcome to Code Review!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T14:39:07.703", "Id": "430574", "Score": "2", "body": "I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T14:58:42.250", "Id": "430577", "Score": "0", "body": "You have already basically modularized the code. You have 4 fairly well defined functions if you look at the code. If you move the large chunks of code within the if statements into functions it will be modular. Beyond this we can't help as the question is right now except to review the code as it currently exists." } ]
[ { "body": "<p>When looking at code like this, the first thing that comes to mind is the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> Every function module should be responsible for doing one thing. </p>\n\n<p>In this case, you can start with <code>main</code> calling the function that starts the program.</p>\n\n<p>You can have the string literals that you want to print to the screen as string arrays and a function that prints a string array to the screen.</p>\n\n<p>Parsing the choices is easier, when done with a <code>switch</code> block.</p>\n\n<p>Each choice should also call a function specific to that choice.</p>\n\n<p><a href=\"http://www.cplusplus.com/articles/j3wTURfi/\" rel=\"nofollow noreferrer\">Get out of the habit of using <code>system()</code></a>. It is very insecure since there is no way to confirm that the called function will do what you expect on every machine.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T16:28:38.020", "Id": "222474", "ParentId": "222462", "Score": "3" } }, { "body": "<p>I like your clear variable names (though I'd prefer <code>Amount</code> rather than abbreviating to <code>Amt</code>).</p>\n\n<p>Avoid <code>using namespace std</code> - it's a big (and growing) namespace that's not intended for wholesale import like that, and doing so can unexpectedly change the meaning of your program. <code>std::</code> is intentionally very short, so get used to typing it.</p>\n\n<p>Don't use <code>std::endl</code> unless you really mean to flush the output - it's much cheaper to write a <code>\\n</code> instead. Many of the multiline strings can be combined - e.g.</p>\n\n<pre><code>std::cout &lt;&lt; \"\\n\\n\"\n \" ***********************************************\\n\"\n \" * *\\n\"\n \" * Monthly Payment Calculator *\\n\"\n \" * *\\n\"\n \" ***********************************************\\n\\n\"\n \"Greetings and welcome to the loan calculator!\\n\\n\";\n</code></pre>\n\n<p>When reading inputs, it's vital to check that the read was successful:</p>\n\n<pre><code>cin &gt;&gt; name;\nif (!cin) {\n std::cerr &lt;&lt; \"Invalid input\\n\";\n return 1;\n}\n</code></pre>\n\n<p>Better would be to recover and re-ask for the input, but that's a little more advanced.</p>\n\n<p>Does it make any sense to view results when no data have been entered? Option 2 probably shouldn't be available until option 1 has been used. In fact, it probably makes sense not to have a menu - just read the input values and produce the corresponding outputs. For multiple runs, just invoke the program again (\"<em>do one thing well</em>\").</p>\n\n<p>I'm not sure what Option 3 is for - perhaps that should be a separate program?</p>\n\n<p><code>std::system()</code> is declared in <code>&lt;cstdlib&gt;</code>. I'd avoid it, though - how do you know the user has a program called <code>pause</code> in their path (I don't, for one), and how do you know it does what you expect?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T18:44:38.830", "Id": "430635", "Score": "0", "body": "Thank you for your response!\n\nLet me address Option 3 first, it was for a requirement to add an array to the program. I really had no idea what to do an array with, so I added it as an example for Option 3 to meet that requirement. Still don't know how to use an array here. \n\nI have been told by some programmer friends to not use using namespace std as well, basically saying the same thing you have. However, it seems like my school does want us to use it. The same with system(\"pause\") as well, so it'll stop so I can screen shot the work. Otherwise, both would not be included." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T17:51:13.137", "Id": "222480", "ParentId": "222462", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T14:35:00.330", "Id": "222462", "Score": "2", "Tags": [ "c++", "calculator", "finance" ], "Title": "Loan repayment calculator" }
222462
<p>Because I'm quite naive regarding C#'s Task Asynchronous Programming and concurrency in general, and because it's so difficult to test, I'm concerned about the safety of this code. It's likely that those topics, or something even more esoteric to me (e.g. processor-specific issues like volatility rules), caused me to overlook something obvious to you. Please help me understand what I missed here!</p> <p><strong>Intent</strong></p> <p>Given a <code>Func&lt;T&gt;</code> that does not support concurrency, we can safely initate the function concurrently, and receive <code>Task&lt;T&gt;</code>. Concurrent initiations are "joined" to one of two iterations of the function; the active iteration, or the single pending iteration. The caller may disallow joining an ongoing iteration, to avoid inconsistent outcomes.</p> <p><strong>Contract</strong></p> <ul> <li>This <code>ExclusiveFunc</code> class requires a <code>Func&lt;T&gt;</code>, which is set at construction and cannot be changed.</li> <li><code>ExclusiveFunc</code> has one public instance method, <code>Task&lt;T&gt; Run(bool joinLate = false)</code>, used to initiate, or "trigger", the <code>Func&lt;T&gt;</code>.</li> <li><code>ExclusiveFunc</code> is safe for multi-threaded use. Multiple instances of <code>Func&lt;T&gt;</code> will never run concurrently from any concurrent calls to <code>Run</code>. When proxied through <code>ExclusiveFunc.Run</code>, the <code>Func&lt;T&gt;</code> is protected from self-concurrency issues that might be caused by scheduled tasks or other concurrent use.</li> <li>There will also never be more than one <em>pending</em> <code>Func&lt;T&gt;</code>. That is, there will at most be one <code>Func&lt;T&gt;</code> running, and one waiting to run. The <code>Func&lt;T&gt;</code> must be implemented such that the side-effects and return value of any single future iteration is sufficient for all pending callers.</li> <li>Callers receive <code>Task&lt;T&gt;</code> for the iteration they have joined, whether joining the running or the pending operation. <code>T</code> must be safe for concurrent use if concurrent callers will use the result.</li> <li>Because "joining a run late" may result in unacceptable dirty / stale information or missed processing, the default operation when <code>Func&lt;T&gt;</code> is already running is to instead set <em>one</em> iteration of <code>Func&lt;T&gt;</code> to run when the active operation is complete. In this default operation, the caller is guaranteed that <code>Func&lt;T&gt;</code> will begin some time <em>after</em> the request was made.</li> <li>Optionally, the caller may <code>joinLate</code> if knowledge of an ongoing iteration (including its return value and side effects) is sufficient, and initiating an additional iteration is not required.</li> <li><code>ExclusiveFunc.Run</code> need not be awaited, if a "fire and forget" implementation is required. However, this implementation is not ideal for heavy usage as such, since every call to <code>Run</code> will internally <code>await</code> for the result on its own thread.</li> <li>All callers joined on any iteration of <code>Func&lt;T&gt;</code> will receive exceptions thrown by the specific iteration they await.</li> <li>Awaiting callers will not wait unnecessarily (such as for subsequent runs), and specifically a queued request will not be forced onto the thread that was running <code>Func&lt;T&gt;</code> at the moment it was queued, but instead will run on the thread that queued it.</li> <li>The <code>ExclusiveFunc</code> class is not vulnerable to internal transition race conditions. It will not halt if <code>Func&lt;T&gt;</code> throws or the queue runs dry.</li> </ul> <p><strong>Specific Concerns</strong></p> <ul> <li>Are there cross-platform issues caused by the <code>lock</code>-less implementation? For example, should <code>queue</code> be marked <code>volatile</code>?</li> <li>Are there exception-handling problems? For example, the caller does not receive exceptions, or exceptions crash the queue.</li> <li>Are there defects in where the work happens that cause unexpected results? For example, the a Task never completes because its thread also runs pending requests.</li> <li>Is the lack of Task methods options a problem? For example, does this cause incorrect SynchronizationContext?</li> <li>Is this likely to cause a thread pool problem? For example, using twice as many threads as the caller expects?</li> <li>Is there a problem with using one Task to synchronize multiple threads in this way?</li> </ul> <p><strong>Code</strong></p> <pre><code>using System; using System.Threading; using System.Threading.Tasks; public class ExclusiveFunc&lt;T&gt; { public ExclusiveFunc(Func&lt;T&gt; func) { queue = new Queue(() =&gt; { try { return func(); } finally { queue = queue.Next(); } }); } public async Task&lt;T&gt; Run(bool joinLate = false) { var a = queue; if (a.Current.Acquire()) { a.Current.Acquired.Start(); return await a.Current.Acquired; } if (joinLate) { return await a.Current.Acquired; } if (a.Pending.Acquire()) { await a.Current.Acquired; a.Pending.Acquired.Start(); } return await a.Pending.Acquired; } private Queue queue; private class Queue { public readonly State Current; public readonly State Pending; public Queue(Func&lt;T&gt; func) : this(func, new State(func)) { } public Queue Next() { return new Queue(func, Pending); } private readonly Func&lt;T&gt; func; private Queue(Func&lt;T&gt; func, State pending) { this.func = func; Current = pending; Pending = new State(func); } } private class State { public Task&lt;T&gt; Acquired; public State(Func&lt;T&gt; func) { this.func = func; } public bool Acquire() { return Interlocked.CompareExchange(ref Acquired, new Task&lt;T&gt;(func), null) == null; } private readonly Func&lt;T&gt; func; } } </code></pre> <p><strong>Tests</strong></p> <pre><code>using System.Threading; using System.Threading.Tasks; using Xunit; public class ExclusiveIncrementer { private int locked = 0; private int count = 0; public int Slow() { Assert.Equal(0, Interlocked.Exchange(ref locked, 1)); Thread.Sleep(100); Assert.Equal(1, Interlocked.Exchange(ref locked, 0)); return Interlocked.Increment(ref count); } } public class ExclusiveFuncTest_WithoutThreads { protected delegate Task&lt;int&gt; RunEf(bool joinLate = false); protected virtual RunEf GetRun() { return new ExclusiveFunc&lt;int&gt;(new ExclusiveIncrementer().Slow).Run; } [Fact] public async Task ConcurrentRequestCanJoinOngoing() { var run = GetRun(); var master = run(); var slave = run(true); Assert.Equal(1, await master); Assert.Equal(1, await slave); } [Fact] public async Task ConcurrentRequestCanQueueIfOngoing() { var run = GetRun(); var immediate = run(); var queued = run(); Assert.Equal(1, await immediate); Assert.Equal(2, await queued); } [Fact] public async Task ProceedsAfterQueueEmpty() { var run = GetRun(); var first = run(); Assert.Equal(1, await first); var second = run(); Assert.Equal(2, await second); } [Fact] public async Task FireAndForgetCompletes() { var run = GetRun(); var first = run(); var second = run(); Assert.Equal(2, await second); } [Fact] public async Task OrderDeterminedByCallNotAwait() { var run = GetRun(); var first = run(); var second = run(); Assert.Equal(2, await second); Assert.Equal(1, await first); } [Fact] public async Task MultiplePendingShareOperation() { var run = GetRun(); var blocking = run(); var firstPending = run(); var secondPending = run(); Assert.Equal(2, await firstPending); Assert.Equal(2, await secondPending); } [Fact] public async Task JoinWillStartIfRequired() { var run = GetRun(); var only = run(true); Assert.Equal(1, await only); } } public class ExclusiveFuncTest_WithThreads : ExclusiveFuncTest_WithoutThreads { protected override RunEf GetRun() { var run = base.GetRun(); return runThread; Task&lt;int&gt; runThread(bool joinLate = false) { // We enforce order with Sleep, to allow human-readable test outcomes Thread.Sleep(30); return Task.Run(() =&gt; run(joinLate)); } } } </code></pre> <p><strong>Background</strong> (not the main question, but ofc comments welcome):</p> <p>I would like to separate the locking logic from several schedulable tasks in my system (e.g. scheduled conference call setups, due e-mails). While unlikely, very closely-scheduled tasks may run concurrently. Rather than artificially restricting the scheduling resolution to an arbitrary "almost certainly safe" value, I want to ensure there is at most one running. The caller may determine whether joining an ongoing run is sufficient or not.</p> <p>I understand domain-specific idempotency/synchronization is typically preferable.</p> <p><strong>Related:</strong> (for Node.js) <a href="https://codereview.stackexchange.com/questions/196971/concurrent-fire-and-forget-async-task-queue">Concurrent fire and forget async task queue</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T15:53:59.997", "Id": "430601", "Score": "2", "body": "We don't expect deterministic test results, just a clear description and a trivial example which people can relate to." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T17:22:51.987", "Id": "430621", "Score": "1", "body": "@dfhwze I've add several tests for human consumption. The ones I'd posted earlier were really for my own use, intended to make it easier for me to test complex time-dependent sequencing. Please let me know if these are well-suited to this forum." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T15:26:10.927", "Id": "430783", "Score": "2", "body": "While most of the edits have been for clarification, be aware that in the future, it is advised to not make edits to the code after an answer is received, per [the Help center page _What should I do when someone answers my question?_](https://codereview.stackexchange.com/help/someone-answers)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T16:01:12.523", "Id": "430790", "Score": "0", "body": "Ah, I did not know. Note that the edit did not apply an other-person-discovered fix, and I did give the existing answerer an opportunity to correct that specific defect I discovered, indicated in the comments on his/her answer (which did not make significant revisions) below. Perhaps what the more appropriate response would have been, would be to revert that edit and answer the question myself?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T16:21:58.377", "Id": "430792", "Score": "0", "body": "mhmm... isn't this the same as if you run a task and chained the next one with `ContinueWith` and then used its task to chain the next one and so on...? Alternatively, wouldn't the `ConcurrentQueue<T>` be here easier to use?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T17:24:17.280", "Id": "430795", "Score": "0", "body": "@t3chb0t `ContinueWith` has a different threading and `SynchronizationContext` consequence than `await`; you can see more about that in this chat: https://chat.stackexchange.com/rooms/95070/discussion-between-dfhwze-and-shannon . If you think that difference is better, I'd love to understand why. Also, this implementation restricts the queue depth to 1, which makes ConcurrentQueue actually more difficult to implement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T18:37:13.437", "Id": "430813", "Score": "0", "body": "Maybe another time as I'm not sure I entirely understand its purpose as the tests are pretty academic and I'm not able to come-up with any real-world scenario where this code might be useful. Can you help out with that and name some use-case where this is handy (other than in the _Background_ part - or reframe them)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T17:39:41.910", "Id": "431076", "Score": "0", "body": "Thanks @t3chb0t; The background isn't really the main point of the question, and consequently the UnitTests are meant to illuminate the usage contract, rather than use cases. To address your concern, I added a \"bigger picture\" section named \"Intent\". Does that help? I can give a simple usage example, although it's not my situation: multiple visitors of a web site request the weather, which is proxied to an external service. Alternately, imagine two scheduled task end up running at the same time for any reason; but the task internals cause inconsistency if run concurrently." } ]
[ { "body": "<h3>Foreword</h3>\n\n<p>I appreciate you taking the effort to edit your question time and again to clarify your goal. At first, I thought you were making a <em>synchronous task scheduler</em> using whatever thread is available at any given time, which would have been really cool as well! In fact, your smartly designed API could be augmented to become one if you allow:</p>\n\n<ul>\n<li>chaining pending executions</li>\n<li>a specific <code>Func&lt;T&gt;</code> instance for each <code>Run</code></li>\n</ul>\n\n<h3>Review</h3>\n\n<p>I haven't found any scheduling-related or other major issues. I only have a couple of small remarks.</p>\n\n<p>Designing private classes allows you to have more leverage in defining access modifiers and validating arguments of internal state and methods. However, I would include some sort of debug-only checks on validating arguments to detect bad design early in unit tests.</p>\n\n<pre><code>private class State\n{\n public Task&lt;T&gt; Acquired; // &lt;- OK, since your API does not allow public access to it\n public State(Func&lt;T&gt; func)\n {\n Debug.Assert(func != null); // or use Contracts API in Debug Mode\n this.func = func;\n }\n}\n</code></pre>\n\n<p>A public API should use argument checks.</p>\n\n<pre><code>public ExclusiveFunc(Func&lt;T&gt; func)\n{\n func = func ?? throw new ArgumentNullException(nameof(func)); // &lt;- a MUST in public API\n queue = new Queue(() =&gt; {\n try {\n return func();\n }\n finally {\n queue = queue.Next();\n }\n });\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T19:39:41.997", "Id": "430642", "Score": "1", "body": "My pleasure and thanks for requesting clarification; it has yielded documentation that will help consumers if we keep this functionality in our library. Regarding `func != null`, you are right, that was lazy of me. C# 8.0 where are you ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T20:09:55.447", "Id": "430645", "Score": "1", "body": "I'm thinking further about your chaining variable `Func<T>` comments. I'd given it some consideration. One concern I ran into early was defeating garbage collection on a deep graph. Another was complexity when limiting depth on the obvious `ConcurrentQueue`. I definitely see the value (e.g. read and write operations might be components of a longer process that can be interleaved, but not concurrent)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T13:23:18.463", "Id": "430750", "Score": "0", "body": "FYI, found a place where exceptions will crash the scheduler, lmk if you want to search for it yourself as a puzzle before I edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T14:37:48.057", "Id": "430766", "Score": "0", "body": "It can throw on the line before `a.Pending.Acquired.Start();`, causing the queue to block. I'll add a catch block in a moment after you've had a chance to look." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T14:45:00.237", "Id": "430767", "Score": "0", "body": "@shannon you await a Task not started because current is already pending?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T14:52:13.853", "Id": "430768", "Score": "0", "body": "Close. Each Task is owned (or `Acquired`) by the first thread to join it. That thread is responsible for running it, and is also has exclusive rights to advance the `queue`. However, in the case of `Pending` it has to first `await` the `Running` Task, before calling `Task.Start` and entering `Func<T>`. If the `Pending` task throws while awaiting the `Running` task (before calling `Task.Start`), the `Pending` `Task<T>` will not start (or finish), and the `queue` will also not advance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T14:55:03.340", "Id": "430772", "Score": "0", "body": "so you not only need a try finally with the func, but also with the start pending after await current" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T14:56:23.543", "Id": "430774", "Score": "0", "body": "Right, the `Pending` requires a `try ... catch {}` (rather than `finally`). It should not rethrow the exception." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T14:57:12.443", "Id": "430775", "Score": "0", "body": "then how should you handle the exception? each thread awaiting handles the exception itself and the API just silently catches it? Perhaps a ContinueWith is more appropriate then in this case" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T15:00:32.183", "Id": "430778", "Score": "0", "body": "Right, the exceptions are returned with every completed `Task<T>`. The scheduler should just swallow it (or possibly log them, but ultimately that is probably the caller's job), because it is conceptually a copy of the exception, only relevant for completion notice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T15:01:34.570", "Id": "430779", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/95070/discussion-between-dfhwze-and-shannon)." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T19:29:38.967", "Id": "222484", "ParentId": "222463", "Score": "3" } }, { "body": "<p>A few fixes / possible improvements:</p>\n\n<hr>\n\n<p><strong>Scheduler Crash on Exception</strong></p>\n\n<p>This is the most significant I've found. The thread responsible for Starting the Pending Task first awaits the Current Task completion, but an exception will abort this continuation, leaving the queue in a hung state. The exception should be caught.</p>\n\n<pre><code>if (a.Pending.Acquire()) {\n try {\n await a.Current.Acquired;\n }\n catch {}\n a.Pending.Acquired.Start();\n}\n</code></pre>\n\n<p>(After discovering this defect, I first incorrectly edited the code, which a moderator pointed out to me. I've reverted the fix and moved it to this answer.)</p>\n\n<hr>\n\n<p><strong>Contract-stated thread assignment mismatch</strong></p>\n\n<p><strong>Disagreement between Pending and Current SynchronizationContext</strong></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T14:55:36.250", "Id": "222711", "ParentId": "222463", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T14:35:51.540", "Id": "222463", "Score": "5", "Tags": [ "c#", "thread-safety", "concurrency", "async-await", "task-parallel-library" ], "Title": "Async concurrency prevention class" }
222463
<p>I want to run the function <code>addItem()</code> for every item. Multiple items will belong to the same slot (category). For each category I have to run the function with the same slot. I don't want to manually write down the slot for each and every item, because there could be 100's for each category.</p> <p>The goal is to get the best result in terms of: readability, maintainability and effort to add items.</p> <p>Here is my current code:</p> <pre><code>let equipment = { head: {}, cape: {}, neck: {}, ammunition: {}, weapon: {}, body: {}, shield: {}, legs: {}, hand: {}, feet: {}, ring: {} }; function createShortName(name) { return name.toLowerCase().replace(/\s/g, ''); } function addItem(slot, name, cost, img, income=0, atk_bonus=0, str_bonus=0, def_bonus=0, rngd_bonus=0, mage_bonus=0) { let newItem = { slot: slot, name: name, cost: cost, img: img, income: income, atk_bonus: atk_bonus, str_bonus: str_bonus, def_bonus: def_bonus, rngd_bonus: rngd_bonus, mage_bonus: mage_bonus } equipment[slot][createShortName(name)] = newItem; } let currentSlot = 'head'; addItem(currentSlot, 'head_item_1', 100, 'img'); addItem(currentSlot, 'head_item_2', 200, 'img'); currentSlot = 'cape'; addItem(currentSlot, 'cape_item_1', 100, 'img'); currentSlot = 'neck'; addItem(currentSlot, 'neck_item_1', 100, 'img'); addItem(currentSlot, 'neck_item_2', 200, 'img'); addItem(currentSlot, 'neck_item_3', 400, 'img'); addItem(currentSlot, 'neck_item_4', 800, 'img'); // etc. etc. etc. </code></pre> <p>As you can see, I add items to the <code>equipment</code> object at the bottom of the code. Is there a better approach?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T15:09:29.853", "Id": "430581", "Score": "0", "body": "For what reason don't you want to write down the `currentSlot` as a string literal? It would make the code even easier to read since then the calls to `addItem` would have only literal parameters. As a reader I could then focus on the meaning of the values, without having to search half of them in the preceding lines of code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T15:13:46.800", "Id": "430584", "Score": "0", "body": "@RolandIllig I have 100's of items for each slot, I prefer not to write (copy+paste) it every single time and I am looking for the best solution in terms of effort, readability, and maintainability." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T15:20:49.290", "Id": "430585", "Score": "0", "body": "What about removing all this data from the code, and putting it in a spreadsheet instead? That allows for quick editing, and the main code would just have to read the spreadsheet data. Also, your current code does not demonstrate how the optional parameters of `addItem´ are used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T18:02:06.940", "Id": "430631", "Score": "0", "body": "@RolandIllig The optional parameters are used exactly the same, for example: `addItem(currentSlot, 'neck_item_2', 200, 'img', 1, 5, 10, 0, 2, 4);` It's simply adding all stats to the object and then I can read it on another file with `equipment.head.head_item_1` for example. Or I can retrieve all head items by `equipment.head`. How would putting it in a spreadsheet work?" } ]
[ { "body": "<p>With regards to the last couple of lines, one thing you could do from a functional perspective is to bind the first argument like so:</p>\n\n<pre><code>function bindFirst(func, firstArgument) {\n return function(...arguments) {\n return func(firstArgument, ...arguments);\n }\n}\n\nconst addToHead = bindFirst(addItem, 'head');\n\naddToHead('head_item_1', 100, 'img');\n...\n</code></pre>\n\n<p>You could also use data structure like a Map and loop through it:</p>\n\n<pre><code>let newItems = new Map([\n [\n 'head',\n [{\n name: 'head_item_1',\n cost: 100,\n img: 'img'\n },\n {\n name: 'head_item_1',\n cost: 100,\n img: 'img'\n }]\n ], [\n 'cape',\n [{\n name: 'cape_item_1',\n cost: 100,\n img: 'img'\n },\n {\n name: 'cape_item_1',\n cost: 200,\n img: 'img'\n }]\n ]\n]);\n\nitems.forEach((items, slot) =&gt; {\n const addToSlot = bindFirst(addItem, slot);\n items.forEach(item =&gt; {\n addToSlot(item.name, item.cost, item.img);\n });\n});\n</code></pre>\n\n<p>Have you considered that maybe <code>equipment</code> and <code>item</code> should be classes? A class called <code>Equipment</code> could have a method like <code>addItem(slot, item)</code> where <code>item</code> is an object of type <code>Item</code>, which has a constructor with a similar signature to your <code>addItem</code> function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T18:00:32.137", "Id": "430629", "Score": "0", "body": "The reason why I did a function was because all these `slot, name, cost, img, income, atk_bonus, str_bonus, def_bonus, rngd_bonus, mage_bonus` parameters are possible for the items. If I had to write all parameters for each item, it would be even more work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T19:22:04.077", "Id": "430640", "Score": "0", "body": "If I have an object like `let o = {x: 1}`, `o.y` returns `undefined`. If you pass `undefined` to a function, the default value takes its place. So you can replace the line with `addToSlot(item.name, item.cost, item.img, item.income, ...)` and it will behave fine even for the items that don't have `income` supplied." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T15:18:30.923", "Id": "222465", "ParentId": "222464", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T14:36:43.333", "Id": "222464", "Score": "3", "Tags": [ "javascript" ], "Title": "Adding multiple items of different categories to one object" }
222464
<p>I'm just getting into functional programming (as in, just started reading the <a href="https://github.com/getify/Functional-Light-JS" rel="nofollow noreferrer">book</a>) and as practice I'm trying to refactor <a href="https://stackoverflow.com/a/51636258/1243041">a past answer I wrote</a> to fit in line with the functional style. </p> <p>The function is intended to be a template literal tag, like so:</p> <pre><code>let myString = withoutWhitespace`This is a really long string, that needs to wrap over several lines. With a normal template literal you can't do that, but you can use a template literal tag to get rid of line breaks and indents.`; </code></pre> <p>Here's the original:</p> <pre><code>function withoutWhitespace(strings, ...placeholders) { // Build the string as normal, combining all the strings and placeholders: let withSpace = strings.reduce((result, string, i) =&gt; (result + placeholders[i - 1] + string)); let withoutSpace = withSpace.replace(/\s\s+/g, ' '); return withoutSpace; } </code></pre> <p>And here's my new version:</p> <pre><code>function withoutWhitespace(strings, ...placeholders) { return trimWhitespace(merge(strings, placeholders).join()); } function trimWhitespace(input) { return input.replace(/\s\s+/g, ' '); } function merge(one, two) { let result = []; for(let i = 0; i &lt; Math.max(one.length, two.length) - 1; i++) { pushIfTruthy(result, one[i]); pushIfTruthy(result, two[i]); } return result; } function pushIfTruthy(array, item) { if(item) { array.push(item); } return array; } </code></pre> <p>How does this look so far? What improvements could I make?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T15:28:07.873", "Id": "430588", "Score": "0", "body": "What do you mean by 'so far'? Is there functionality you haven't included yet?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T15:31:25.487", "Id": "430590", "Score": "0", "body": "@dfhwze It *works* as-is; I'm just new to functional programming style and wanted to hear from others on how well this matches that style and what could be improved." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T15:23:41.783", "Id": "222466", "Score": "0", "Tags": [ "javascript", "beginner", "strings", "functional-programming" ], "Title": "Create a template literal tag to remove whitespace from a string" }
222466
<p>I have a controller for Post and Put request for the same entity: <code>MyModelDTO</code> with some ModelState's attributes.</p> <p>The users can make a <code>Post</code> request without the <code>Id</code> attribute, because it is being generated on server side, but for <code>Put</code> request the <code>Id</code> attribute is needed (And has to be different than an empty guid).</p> <p>I want to allow get a Post request without the "Id" property, and still use the <code>ModelState</code> functionality, the best solution I've came across is overriding the <code>OnActionExecuting</code> and removing the specific key:</p> <pre><code>public class ExceptPropertiesAttribute : ActionFilterAttribute { private IEnumerable&lt;string&gt; _propertiesKeys; public ExceptPropertiesAttribute(string commaSeperatedPropertiesKeys) { if (!string.IsNullOrEmpty(commaSeperatedPropertiesKeys)) { this._propertiesKeys = commaSeperatedPropertiesKeys.Split(','); } } public override void OnActionExecuting(ActionExecutingContext actionContext) { if (this._propertiesKeys != null) { foreach (var propertyKey in this._propertiesKeys) { if (actionContext.ModelState.ContainsKey(propertyKey)) { actionContext.ModelState.Remove(propertyKey); } } } } } </code></pre> <p><code>MyModelDTO</code> class:</p> <pre><code>public class EventModelDTO : IBaseModel { [IsNotEmpty(ErrorMessage = "Guid Id Is Empty")] public Guid Id { get; set; } [Required] public string Name { get; set; } } public class IsNotEmptyAttribute : ValidationAttribute { public override bool IsValid(object value) { if (value == null) return false; var valueType = value.GetType(); var emptyField = valueType.GetField("Empty"); if (emptyField == null) return true; var emptyValue = emptyField.GetValue(null); return !value.Equals(emptyValue); } } </code></pre> <p>Usage:</p> <pre><code>[HttpPost] [ExceptPropertiesAttribute("Id")] public ActionResult Post([FromBody] MyModelDTO itemDTO = null) { try { if (!ModelState.IsValid) { return BadRequest(); } MyModel item = _mapper.Map&lt;MyModel&gt;(itemDTO); ResultService result = this._myService.Insert(item); if (result.Success) { return CreatedAtAction("Post", new { item.Id }, itemDTO); } else { return StatusCode(500, result.ErrorCode); } } catch (Exception ex) { return StatusCode(500, ErrorCode.Unknown); } } [HttpPut("{id}")] public ActionResult Put([FromBody] MyModelDTO itemDTO) { try { if (!ModelState.IsValid) { return BadRequest(); } MyModel item = _mapper.Map&lt;MyModel&gt;(itemDTO); ResultService result = this._eventsService.Update(item); if (result.Success) { return Ok(); } else { return StatusCode(500, result.ErrorCode); } } catch (Exception ex) { return StatusCode(500, ErrorCode.Unknown); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T15:29:01.017", "Id": "430589", "Score": "1", "body": "How is `ModelState` bound to an `Id` that you need this workaround? Please describe the problem you are solving with more details." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T16:09:27.993", "Id": "430608", "Score": "0", "body": "@t3chb0t see updated question, it checks if the Id is not null or empty guid" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T16:12:26.317", "Id": "430611", "Score": "1", "body": "If I understand it correctly your entities have an `Id` property that is decorated with the `IsNotEmptyAttribute` and for certain requests you'd like to exclude this validation of the model?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T17:52:21.340", "Id": "430626", "Score": "0", "body": "Hey guys, see updated question" } ]
[ { "body": "<p>While your approach might work, I consider it a <strong><em>hack</em></strong>. The preferred solution would be to <strong>create different models for <em>each</em> request</strong> so that the user does not have a chance of passing values that might not only not be required but even be forbidden.</p>\n\n<p>Your new entities could be:</p>\n\n<pre><code>class NewUser\n{\n public string Name { get; set; }\n}\n</code></pre>\n\n<p>Where there are is no <code>Id</code> if the AIP does not require it.</p>\n\n<hr>\n\n<p>It is a very bad idea to expose your database models to the caller. Create more specific models and map their properties to your database entities. </p>\n\n<p>If you let the user the possibility of passing anything he wants, you would need to validate even more values to be sure he does not try to do something else than you want him to.</p>\n\n<p>One such example could be when you have an API for updating <code>User.Name</code> but that user has a navigation property <code>Books</code> and the caller sends you some books too that will also get updated... just because he can. This might cause you a lot of trouble.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T17:55:24.543", "Id": "430627", "Score": "0", "body": "So you are saying to create a `MyModelPostRequest` and a `MyModelPutRequest`, I didn't exposed my db model to users, see the DTO suffix and the Mapper in updated question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T17:59:27.157", "Id": "430628", "Score": "0", "body": "@ShaharShokrani you might not use db-entities directly but these dtos look a lot like the entities; I bet they are identical... if they weren't then you wouldn't have to create workarounds for ignoring some properties that obviously don't belong there in certain requests." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T18:01:59.000", "Id": "430630", "Score": "1", "body": "I see, agreed, the lesson for me is to create separate request classes for Put and Post, leave the DTO only for Get request..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T16:16:27.630", "Id": "222473", "ParentId": "222467", "Score": "2" } } ]
{ "AcceptedAnswerId": "222473", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T15:26:08.523", "Id": "222467", "Score": "2", "Tags": [ "c#", "asp.net-core" ], "Title": "Removing a specific key of ModelState for a specific controller's method" }
222467
<p>I have an entity which has a list of other entities in it.</p> <p>for example:</p> <pre><code>class Library { public virtual List&lt;Book&gt; Books{get;set;} } </code></pre> <p>And I would like to update the entity and also the list of entities inside.</p> <p>I came up with this solution:</p> <pre><code>private void UpdateChild&lt;T&gt;(DbSet&lt;T&gt; dbset, ICollection&lt;T&gt; existingItems, ICollection&lt;T&gt; newItems, Func&lt;T, T, bool&gt; isEqual) where T : class { dbset.RemoveRange(existingItems); foreach (var newItem in newItems) { T oldItem = existingItems.FirstOrDefault(x =&gt; isEqual(newItem, x)); if (null != oldItem) { oldItem = newItem; dbset.Update(oldItem); } else { dbset.Add(newItem); } } } </code></pre> <p>But I am not sure if this solution is a good approach.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T15:55:07.663", "Id": "430602", "Score": "0", "body": "Does this solution work?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T16:08:23.807", "Id": "430606", "Score": "0", "body": "Yes, But not tested carefully for every case." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T15:53:35.150", "Id": "222471", "Score": "0", "Tags": [ "c#", "entity-framework" ], "Title": "Entity Framework C# updating an entity list generic solution" }
222471
<p>I have a python <code>print</code> statement and inside the string I wish to print are four digits. I would like to apply the same formatting function to each param. I am not familiar with the latest and greatest features of python PEPs. </p> <h3>Is there a slick way to do this?</h3> <h2>Code</h2> <pre><code>statement = "Splitting up the {} file into {} chunks, with the filesystem block size of {}, causing {} extra space to be used" print(statement.format( sizeof_fmt(input_file_size), sizeof_fmt(chunk_size), sizeof_fmt(block_size), sizeof_fmt(surrendered_space))) </code></pre> <h2>Format Function</h2> <pre><code>def sizeof_fmt(num, suffix='B'): for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']: if abs(num) &lt; 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T16:29:07.677", "Id": "430612", "Score": "1", "body": "This is not really a code review type question, and would be better asked on StackOverflow. But the slick way you are looking for is the [`map()`](https://docs.python.org/3.7/library/functions.html#map) function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T02:33:44.150", "Id": "430656", "Score": "0", "body": "@AJNeufeld - I have been told something here - https://codereview.stackexchange.com/questions/222292/character-picture-grid-exercise-automatetheboringstuff/222307#222307. Is it true?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T04:19:12.303", "Id": "430660", "Score": "3", "body": "@Justin Ah. PEP 279 ... written in 2002, contains no mention of deprecating `map`, but a comment by GvR on the PEP suggested it should die. A discussion in 2005 suggested it might be gone by Python 3.0 ... which was released in December 2008. Now it is 11 years later, and I still see no signs of `map` being deprecated. True: you can use list comprehension instead of map, and in some cases it might be faster and clearer, but in others it can be slower and/or less clear. YMMV, but I don’t expect map will ever go away." } ]
[ { "body": "<p>Time will tell if your question is considered a worthy Code Review question, but till then I'ld like you to give a short review on your code nevertheless.</p>\n\n<h1>Format function</h1>\n\n<p>You could reduce the code duplication in the format function and make use of <code>.format</code> or f-strings (from Python 3.6 onwards).</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def sizeof_fmt_rev(num, suffix='B'):\n for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:\n if abs(num) &lt; 1024.0:\n break\n num /= 1024.0\n else:\n # this part is only executed if the loop was not left with a break\n unit = 'Yi'\n return f\"{num:.1f}{unit}{suffix}\"\n</code></pre>\n\n<p>This uses <a href=\"https://stackoverflow.com/a/9980160/5682996\"><code>for ... else</code></a>, one of the less well-known features of Python and only has a single line where the format expression has to be written. <strike>I see a chance to build something using <a href=\"https://docs.python.org/3/library/math.html#math.log\" rel=\"nofollow noreferrer\"><code>math.log</code></a> instead of that loop, but I will leave that as an exercise to you.</strike> You can even build something that works without a loop, but at least the version I came up with (found below) is actually slower than the original implementation.</p>\n\n<pre><code>def sizeof_fmt_rev_log(num, suffix='B'):\n exponent = min(int(math.log(abs(num), 1024)), 8)\n num /= 1024**exponent\n unit = ('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi')[exponent]\n return f\"{num:.1f}{unit}{suffix}\"\n</code></pre>\n\n<p>I used</p>\n\n<pre><code>for i in range(10):\n num = 3.8 * 1024**i\n print(sizeof_fmt_rev(num))\n assert sizeof_fmt(num) == sizeof_fmt_rev(num)\n assert sizeof_fmt(-num) == sizeof_fmt_rev(-num)\n</code></pre>\n\n<p>to test the revised version.</p>\n\n<h1>Code</h1>\n\n<p>As <a href=\"https://codereview.stackexchange.com/users/100620/\">@AJNeufeld</a> mentions in his comment, you could use <a href=\"https://docs.python.org/3/library/functions.html#map\" rel=\"nofollow noreferrer\"><code>map</code></a> to save yourself some typing</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(\n statement.format(*map(sizeof_fmt, (input_file_size, chunk_size, block_size, surrendered_space)))\n)\n</code></pre>\n\n<p>which is functionally equivalent to using a list comprehension:</p>\n\n<pre><code>print(\n statement.format(*[\n sizeof_fmt(i)\n for i in (input_file_size, chunk_size, block_size, surrendered_space)\n ])\n)\n</code></pre>\n\n<p>Both build upon a technique called <a href=\"https://stackoverflow.com/a/2238361/5682996\">tuple unpacking</a>, but as you can see it can also be used with lists, other sequences, and <strike>maybe</strike> also iterables (if it is a generator, it will be consumed - thanks <a href=\"https://codereview.stackexchange.com/users/98493/\">@Graipher</a>, who confirmed it/pointed it out in a <a href=\"https://codereview.stackexchange.com/questions/222472/apply-same-format-function-to-each-python-print-parameter/222486?noredirect=1#comment430937_222486\">comment</a>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T14:53:58.957", "Id": "430937", "Score": "0", "body": "Tuple unpacking can indeed be used with any iterable. It will be consumed by it if it is a generator." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T19:42:41.920", "Id": "222486", "ParentId": "222472", "Score": "2" } } ]
{ "AcceptedAnswerId": "222486", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T16:09:03.077", "Id": "222472", "Score": "3", "Tags": [ "python", "python-3.x", "formatting" ], "Title": "Apply same format function to each python print() parameter" }
222472
<p>Little history to give context to the problem:</p> <p><strong>The Krusty-Burgers</strong></p> <p>Homer Simpson is a smart guy who likes to eat Krusty-Burgers, and it takes <code>m</code> minutes for Homer to eat a Krusty-Burger. However, there is a new type of burger on the market, the Apu-Burger. Homer likes them too, and takes <code>n</code> minutes to eat one. Given just minutes, you have to figure out the maximum number of burgers that Homer can eat without wasting time. If he has idle time, he can drink beer.</p> <p><strong>Input</strong></p> <p>The input consists of several test cases. Each test case consists of three integers <code>m</code>, <code>n</code>, <code>t</code> (<code>0 &lt;= m, n, t &lt;= 1000</code>).</p> <p><strong>Output</strong></p> <p>For each test case, the maximum number of burgers that Homer can eat without beer should be written on a single line. If Homer drinks beer by spare time, one should also print the time he has to drink, separated by a blank. It is preferable for Homer to drink as little beer as possible, as Marge does not like it when he arrives drunk at home.</p> <p><strong>Input example</strong></p> <blockquote> <p>3 5 54</p> <p>3 5 55</p> </blockquote> <p><strong>Example of output</strong></p> <blockquote> <p>18</p> <p>17</p> </blockquote> <p>I would like to know if I can improve my code in some way in terms of performance or writing</p> <pre class="lang-java prettyprint-override"><code>import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.sql.Date; import java.text.SimpleDateFormat; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileFilter; public class ChallangePerformance { private static File archive; private static BufferedReader rdFont; static String fileLine = null; static int structuresNumber; public static void main(String[] args) { openFile(); long start = System.currentTimeMillis(); boolean still_has = true; while ( still_has ) { readFileLine(); if ( fileLine == null ) { still_has = false; } else { String array[] = fileLine.split(" "); int kb = Integer.parseInt( array[0] ); int ab = Integer.parseInt( array[1] ); int total = Integer.parseInt( array[2] ); int na = 0; int nk = (int) Math.floor(total/kb); int dif = total-nk*kb; int mk = nk; int ma = na; int ms = dif; while ( nk &gt; 0 ) { nk--; int leftover = total-nk*kb; na = (int) Math.floor(leftover/ab); dif = total - (nk*kb + na*ab); if ( dif &lt; ms &amp;&amp; ms &gt; 0) { mk = nk; ma = na; ms = dif; } } System.out.println( fileLine ); System.out.println( " " + mk + " " + ma ); } } long end = System.currentTimeMillis(); System.out.println(new SimpleDateFormat("ss.SSS").format(new Date(end - start))); } static void readFileLine() { try { fileLine = rdFont.readLine(); } catch (IOException e) { e.printStackTrace(); } } private static void openFile() { JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY ); Filter7 filtro = new Filter7(); fileChooser.addChoosableFileFilter( filtro ); int result = fileChooser.showOpenDialog( null ); if( result == JFileChooser.CANCEL_OPTION ) { return; } archive = fileChooser.getSelectedFile(); openFont( archive ); } private static boolean openFont( File fileName ) { if( archive == null || fileName.getName().trim().equals( "" ) ) { JOptionPane.showMessageDialog( null, "Invalid file name", "Invalid file name", JOptionPane.ERROR_MESSAGE ); return false; } else { try { FileReader fr = new FileReader( archive ); rdFont = new BufferedReader( fr ); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; } } } class Filter7 extends FileFilter { public boolean accept(File arg0) { if(arg0 != null) { if(arg0.isDirectory()) { return true; } if( getExtensao(arg0) != null) { if ( getExtensao(arg0).equalsIgnoreCase( "est" ) ) { return true; } }; } return false; } /** * Returns which extensions can be chosen */ public String getDescription() { return "*.est"; } /** * Returns the part with the extension of an archive */ public String getExtensao(File arq) { if(arq != null) { String filename = arq.getName(); int i = filename.lastIndexOf('.'); if(i&gt;0 &amp;&amp; i&lt;filename.length()-1) { return filename.substring(i+1).toLowerCase(); }; } return null; } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T18:29:57.070", "Id": "430633", "Score": "3", "body": "Your logic is extremely hard to understand due to your variable naming e.g., `kb, mk, ma`. You should consider variable names that do not need explanation and outsource computations to methods so you can give them names." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T09:46:54.847", "Id": "430706", "Score": "0", "body": "The spec seems to be missing an explanation of what `t` is." } ]
[ { "body": "<p>The use of static variables to read the input file is kind of ugly and makes it harder to reason about what the code is doing. I'd ditch the <code>archives</code>, <code>rdFont</code> and <code>fileLine</code> variables, moving them into the main method. The <code>openFont</code> and <code>readFileLine</code> methods don't feel necessary either - <code>openFile</code> could just return the File that was picked and let the caller do whatever it wants with it.</p>\n\n<p>The two-letter variable names make your code much harder to read. Yes, it's possible to figure out what it's doing, and even get a decent idea of why you chose the letters you did, but there's no need to put the people reading your code through that.</p>\n\n<p>When you divide two <code>int</code>s, the result will be an <code>int</code> and thus rounded down if it has to. <code>(int) Math.floor(a / b)</code> can be written as simply <code>a / b</code> if <code>a</code> and <code>b</code> are <code>int</code>s.</p>\n\n<p>When you initialise the variables, you do more or less the same logic as you do inside the loop later. I'd usually recommend keeping that logic in just one place to make it easier to change if necessary, with values in <code>mk</code>, <code>ma</code> and <code>ms</code> that will always be replaced on the first pass of the loop (though that does admittedly fail if one Krusty-burger takes longer to eat than the time you have available - more on that in a moment)</p>\n\n<p>If there's a solution that leaves 0 time for beer, your algorithm will pick the first one it encounters, which might not be the one where you eat the most burgers. The input <code>5 1 15</code> should return <code>15</code> (as you can eat 15 entire Apu-burgers) but your code would return <code>3</code> (as eating 3 Krusty-burgers is the first solution you test, and that also leaves no time for beer). To get around this you could either iterate through all options every time, or you could have your loop start from \"maximise whichever-burger-Homer-eats-faster\" (which could be either of the two types) instead of \"maximise Krusty-burgers\".</p>\n\n<p>If you do decide to go with the latter, you can end a loop early using the <code>break</code> statement. Your</p>\n\n<pre><code>if ( dif &lt; ms &amp;&amp; ms &gt; 0) {\n mk = nk;\n ma = na;\n ms = dif;\n}\n</code></pre>\n\n<p>could instead have been</p>\n\n<pre><code>if (dif &lt; ms) {\n mk = nk;\n ma = na;\n ms = dif;\n if (dif == 0) break; // Don't bother going through the rest of the loop at all!\n}\n</code></pre>\n\n<p>The <code>Filter7</code> class could probably be removed in favour of using a <code>javax.swing.filechooser.FileNameExtensionFilter</code>.</p>\n\n<p>It's usually considered good practice to define variables only in the block that needs them - the <code>nk</code>, <code>na</code> and <code>dif</code> variables can be moved into the loop pretty easily.</p>\n\n<p>Both of those while loops seem to me like they'd be better suited as for loops. There's simple initialisation that really doesn't matter outside of the loop itself, and simple statements you want to execute as part of just keeping the loop going rather than as part of the logic <em>within</em> the loop.</p>\n\n<p>If you do all this, you might end up with something like:</p>\n\n<pre><code>import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.sql.Date;\nimport java.text.SimpleDateFormat;\n\nimport javax.swing.JFileChooser;\nimport javax.swing.JOptionPane;\nimport javax.swing.filechooser.FileNameExtensionFilter;\n\npublic class ChallangePerformance {\n\n public static void main(String[] args) throws IOException\n { \n // This try-with-resources syntax is usually considered good practice because it takes care of closing files for you - not really an issue in a program like this though.\n try (BufferedReader rdFont = new BufferedReader(new FileReader(openFile()))) {\n long start = System.currentTimeMillis(); \n\n for (String line = rdFont.readLine(); line != null; line = rdFont.line()) { // Alternatively, `for (String line; (line = rdFont.readLine()) != null;)` also works if you want to be all fancy.\n String[] array = line.split(\" \"); \n int krustyBurgerTime = Integer.parseInt(array[0]); // Used to be kb\n int apuBurgerTime = Integer.parseInt(array[1]); // Used to be ab\n int initialTime = Integer.parseInt(array[2]); // Used to be total\n\n boolean krustyBurgersAreFastest = krustyBurgerTime &lt;= apuBurgerTime;\n int fastestBurgerTime;\n int slowestBurgerTime;\n if (krustyBurgersAreFastest) {\n fastestBurgerTime = krustyBurgerTime;\n slowestBurgerTime = apuBurgerTime;\n } else {\n fastestBurgerTime = apuBurgerTime;\n slowestBurgerTime = krustyBurgerTime;\n }\n\n // Sensible defaults in case there's not enough time to eat even a single burger - no need to duplicate the loop's logic as the loop will replace these anyway.\n int bestBeerTime = initialTime; // Used to be ms\n int bestFastBurgers = 0; // Used to be mk\n int bestSlowBurgers = 0; // Used to be ma\n\n // Replaced while loop with for loop\n for (int fastBurgers = initialTime / fastestBurgerTime; fastBurgers &gt; 0; fastBurgers--) {\n int leftover = initialTime - fastBurgers * fastestBurgerTime;\n int slowBurgers = leftover / slowestBurgerTime;\n int beerTime = initialTime - (fastBurgers * fastestBurgerTime + slowBurgers * slowestBurgerTime);\n if ( beerTime &lt; bestBeerTime &amp;&amp; bestFastBurgers + bestSlowBurgers &lt; fastBurgers + slowBurgers) {\n bestFastBurgers = fastBurgers;\n bestSlowBurgers = slowBurgers;\n bestBeerTime = beerTime;\n if (beerTime == 0) break; // Since the first perfect solution will be the best perfect solution, we can stop here.\n }\n }\n\n if (krustyBurgersAreFastest) {\n System.out.println(\" \" + bestFastBurgers + \" \" + bestSlowBurgers);\n } else {\n System.out.println(\" \" + bestSlowBurgers + \" \" + bestFastBurgers);\n }\n }\n\n\n long end = System.currentTimeMillis(); \n System.out.println(new SimpleDateFormat(\"ss.SSS\").format(new Date(end - start))); \n\n } catch (FileNotFoundException ex) {\n JOptionPane.showMessageDialog( null, \"Invalid file name\", \"Invalid file name\", JOptionPane.ERROR_MESSAGE );\n }\n }\n\n private static File openFile() {\n JFileChooser fileChooser = new JFileChooser();\n\n fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );\n\n fileChooser.addChoosableFileFilter( new FileNameExtensionFilter(\"*.est\", \"est\") );\n int result = fileChooser.showOpenDialog( null );\n\n if( result == JFileChooser.CANCEL_OPTION ) {\n return null;\n }\n\n return fileChooser.getSelectedFile();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T06:55:04.950", "Id": "430670", "Score": "0", "body": "'or you could have your loop start from \"maximise whichever-burger-Homer-eats-faster\" (which could be either of the two types) instead of \"maximise Krusty-burgers\".'\n\nI would even say that \"eat as many of the fastest burgers as possible\" is always the optimal solution - you will never have enough time left to eat another slow burger, as that would mean you also have time to eat one (or more!) fast burgers" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T01:01:42.137", "Id": "222494", "ParentId": "222475", "Score": "4" } }, { "body": "<h1>General</h1>\n\n<p>It's a good idea to give it a day or two before you accept an answer. Accepting too early discourages other people from answering.</p>\n\n<p>Use @Override when overriding methods in a parent type. This makes the code easier to read and helps the compiler to warn you when something is amiss.</p>\n\n<p>Your variable names are mostly meaningless, which makes your code hard to read and understand. That makes it more likely somebody editing it in the future will make a mistake. Use clear, meaningful variable names.</p>\n\n<p>Your use of whitespace is inconsistent and non-idiomatic. There should be whitespace between a control flow keyword (<code>if</code>, <code>for</code>, ..) and the opening parenthesis. There should be whitespace on either side of a binary operator (<code>+</code>, <code>-</code>, ..). There should be no whitespace after an opening parenthesis. Again, this makes the code easier to read.</p>\n\n<p>You should use guard clauses to return early and keep your code relatively flat. It's easy to get lost in code that looks like a <code>&gt;</code>.</p>\n\n<p>It's confusing that you have one method name in Portuguese and the rest in English.</p>\n\n<h1>ChallangePerformance</h1>\n\n<p>Challenge is misspelled.</p>\n\n<p>Curly braces belong on the same line as the method declaration.</p>\n\n<p>In java, we use camelCase, not snake_case.</p>\n\n<p>All your math and looping is extraneous. The maximum number of burgers that can be consumed is <code>time / min(timeToEatBurger1, timeToEatBurger2)</code>. The amount of time left over is <code>time % min(timeToEatBurger1, timeToEatBurger2)</code>.</p>\n\n<p>The <code>still_has</code> variable isn't necessary. Just <code>break</code> out of the loop.</p>\n\n<p>Your handling of readers is dangerous. You should always make sure that readers get closed in a <code>finally</code> block or, preferably, using a <code>try-with-resources</code>.</p>\n\n<p>Don't use class variables to save state that you need to pipe from one internal method to another. Use return variables from the methods and pass the values.</p>\n\n<p>With some refactoring, you can loop over the reading of lines. The canonical way to do that is <code>String line; while ((line = bufferedReader.readLine() != null) {</code></p>\n\n<p>Declare arrays as <code>String[] array</code>, not <code>String array[]</code>. Both are legal, but the first is idiomatic and the second is rare.</p>\n\n<p><code>openFile</code> doesn't really need a <code>Filter7</code> as a variable.</p>\n\n<p><code>openFile</code> really wants to check for <code>ACCEPT_OPTION</code>, since both <code>CANCEL_OPTION</code> and <code>ERROR_OPTION</code> are bad cases handled the same way. And if you modify the method to return the File, you can just always return <code>getSelectedFile()</code>, which will return null in either of those cases.</p>\n\n<p><code>openFont</code> is confusing. A <code>font</code> in English is a specific thing unrelated to your usage here.</p>\n\n<p>Remove system-generated TODOs.</p>\n\n<h1>Filter7</h1>\n\n<p>The name of this class is not meaningful. Why 7? Why not EstFilter?</p>\n\n<p>Hopefully Filter7 is defined in its own file. If not, it should be either a member of <code>ChallengePerformance</code> or defined in a separate file. While it's permissible to declare multiple classes in the same file, it's highly frowned upon and potentially problematic.</p>\n\n<p><code>if</code> statements don't need a <code>;</code> at the end.</p>\n\n<p>It appears that <code>getExtensao()</code> is designed to be used only by <code>Filter7</code>. In that case, it should be <code>private</code>. Try to minimize the scope of variables and methods wherever possible.</p>\n\n<p>The second half of <code>accept</code> could be written <code>return \"est\".equalsIgnoreCase(getExtensao(file));</code></p>\n\n<p><code>getExtensao</code> would be a little cleaner if you passed in a filename rather than a file.</p>\n\n<p>The condition in the <code>getExtensao</code> <code>if</code> clause would be clearer if you used optional parentheses.</p>\n\n<p>With all these modifications, your code might look more like:</p>\n\n<pre><code>public class ChallengePerformance {\n\n public static void main(final String[] args) {\n\n final File archive = findArchive();\n if (archive == null || archive.getName().trim().isEmpty()) {\n JOptionPane.showMessageDialog(null, \"Invalid file name\", \"Invalid file name\", JOptionPane.ERROR_MESSAGE);\n return;\n }\n\n final long start = System.currentTimeMillis();\n\n try (final FileReader fileReader = new FileReader(archive);\n final BufferedReader bufferedReader = new BufferedReader(fileReader)) {\n\n String line;\n while ((line = bufferedReader.readLine()) != null) {\n final String[] array = line.split(\" \");\n final int timeToEatKrustyBurger = Integer.parseInt(array[0]);\n final int timeToEatApuBurger = Integer.parseInt(array[1]);\n final int timeToEatFastestBurger = Math.min(timeToEatKrustyBurger, timeToEatApuBurger);\n\n final int timeAvailable = Integer.parseInt(array[2]);\n final int burgersEaten = timeAvailable / timeToEatFastestBurger;\n final int beersDrunk = timeAvailable % timeToEatFastestBurger;\n\n System.out.println(line);\n System.out.println(\" \" + burgersEaten + \" \" + beersDrunk);\n }\n } catch (final IOException e) {\n e.printStackTrace();\n }\n\n final long end = System.currentTimeMillis();\n System.out.println(new SimpleDateFormat(\"ss.SSS\").format(new Date(end - start)));\n\n }\n\n private static File findArchive() {\n final JFileChooser fileChooser = new JFileChooser();\n fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );\n fileChooser.addChoosableFileFilter(new EstFilter());\n\n return fileChooser.getSelectedFile();\n }\n}\n</code></pre>\n\n<p>With a filter class:</p>\n\n<pre><code>final class EstFilter extends FileFilter {\n\n @Override\n public boolean accept(final File file) {\n if (file == null) {\n return false;\n }\n\n if (file.isDirectory()) {\n return true;\n }\n\n return \"est\".equalsIgnoreCase(getExtension(file.getName()));\n }\n\n /**\n * Returns which extensions can be chosen\n */\n @Override\n public String getDescription() {\n return \"*.est\";\n }\n\n /**\n * Returns the part with the extension of an archive\n */\n private String getExtension(final String filename) {\n if (filename == null) {\n return null;\n }\n\n final int extensionIndex = filename.lastIndexOf('.');\n if ((extensionIndex &gt; 0) &amp;&amp; (extensionIndex &lt; filename.length() - 1)) {\n return filename.substring(extensionIndex + 1).toLowerCase();\n }\n\n return null;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T18:13:56.107", "Id": "222541", "ParentId": "222475", "Score": "3" } } ]
{ "AcceptedAnswerId": "222494", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T16:30:58.743", "Id": "222475", "Score": "3", "Tags": [ "java", "algorithm", "programming-challenge", "dynamic-programming" ], "Title": "Optimal burger-eating challenge" }
222475
<p>I'm trying to create a binary search tree that would be used to insert my Packet objects'. It holds information like <code>partId</code>, <code>description</code>, <code>price</code>, and <code>partCount</code>. It's a basic binary search tree. Could you take a look and tell me if there's nothing odd in the code? Because I'm trying to brush up on my BST. Please give me your comments and reviews. </p> <p><strong>I'm not doing anything complicated, just simple BST. I haven't done C++ in months, trying to review everything again.</strong></p> <p>This is my testing program:</p> <pre><code>#include &lt;iostream&gt; #include "BST.h" #include "Packet.h" using namespace std; int main() { BST test1; cout &lt;&lt; "-------------------------------------------------------" &lt;&lt; endl; cout &lt;&lt; "Testing BST" &lt;&lt; endl; cout &lt;&lt; "-------------------------------------------------------" &lt;&lt; endl; Packet packetTest(123, "This is a packet of cheese.", 12.95, 10); Packet packetTest1(321, "This is a packet of cheese.", 12.95, 10); Packet packetTest2(456, "This is a packet of cheese.", 12.95, 10); Packet packetTest3(7, "This is a packet of cheese.", 12.95, 10); Packet packetTest4(119, "This is a packet of cheese.", 12.95, 10); Packet packetTest5(456, "This is a packet of cheese.", 12.95, 10); test1.insert(packetTest); test1.insert(packetTest1); test1.insert(packetTest2); test1.insert(packetTest3); test1.insert(packetTest4); test1.insert(packetTest5); test1.preorderTraversal(); system("pause"); } </code></pre> <p>Here's my BST.h:</p> <pre><code>#pragma once #include &lt;string&gt; #include &lt;iostream&gt; #include &lt;stack&gt; #include "Packet.h" using namespace std; class Node { friend class BST; public: Node() : packet(packet), rlink(nullptr), llink(nullptr) {} ~Node() {} private: Packet *packet; Node *rlink, *llink; }; class BST { public: BST(); void BST::insert(Packet&amp; packet); void BST::insert(Node* &amp;p, Node *newNode); void preorderTraversal() const; private: Node *root; void preorderTraversal(const Node *p) const; }; </code></pre> <p>The BST.cpp <strong>Careful with this part, I might have done some things here, can you take an extra look here?</strong>:</p> <pre><code>#include "BST.h" BST::BST() : root(nullptr) {} void BST::insert(Packet&amp; thisPacket) { Node *newNode = new Node; newNode-&gt;packet = &amp;thisPacket; insert(root, newNode); } void BST::insert(Node *&amp;p, Node *newNode) { if (p == nullptr) p = newNode; else if (p-&gt;packet-&gt;getPartId() &lt; newNode-&gt;packet-&gt;getPartId()) insert(p-&gt;llink, newNode); else insert(p-&gt;rlink, newNode); } void BST::preorderTraversal() const { if (root == nullptr) cerr &lt;&lt; "There is no tree."; else { preorderTraversal(root); } } void BST::preorderTraversal(const Node *p) const { if (p != nullptr) { cout &lt;&lt; p-&gt;packet-&gt;getPartId() &lt;&lt; " "; preorderTraversal(p-&gt;llink); preorderTraversal(p-&gt;rlink); } } </code></pre> <p>And finally Packet.h:</p> <pre><code>#pragma once #include &lt;string&gt; using namespace std; class Packet { public: Packet(int partId, string description, double price, int partCount) : partId(partId), description(description), price(price), partCount(partCount) {} int getPartId() const {return partId;} private: int partId; string description; double price; int partCount; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T17:34:34.583", "Id": "430800", "Score": "1", "body": "Welcome to Code Review! Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<h2>Stop using namespace std;</h2>\n\n<p>Having <code>using namespace std;</code>, especially in a header file is considered bad practice. <a href=\"https://stackoverflow.com/q/1452721/5682996\">This</a> Stack Overflow post explains the reasoning quite well. In your case it's especially unnecessary since you do not even use something from this namespace in <code>BST.h</code> and only <code>std::string</code> in <code>Packet.h</code>.</p>\n\n<h2>Unnecessary includes</h2>\n\n<p>Again <code>BST.h</code>. There are a lot of unused includes in there. The only one that might serve a purpose would be <code>Packet.h</code> which could easily be replaced by <a href=\"https://stackoverflow.com/q/4757565/5682996\">a forward declaration</a>. Most of the include should go to the corresponding <code>.cpp</code> file.</p>\n\n<h2>The BST</h2>\n\n<p>I'm not sure about the interface. If your intended usage is to pass packages by reference, it would be desirable to declare <code>BST::insert(Node *&amp;p, Node *newNode)</code> as private, similar to the public and private versions of <code>preorderTraversal</code>. <code>preorderTraversal</code> might also be better called <code>printPreorder</code> or something like this since it only prints the nodes and does not allow to access them.</p>\n\n<p>There is also a <strike>small</strike> memleak in <code>insert</code> since those <code>Node*</code>s created with <code>Node *newNode = new Node;</code> will never get deleted. <a href=\"http://www.valgrind.org/\" rel=\"nofollow noreferrer\">valgrind</a> confirms this. As <a href=\"https://codereview.stackexchange.com/users/75307\">@TobySpeight</a> rightfully pointed out in his comment and <a href=\"https://codereview.stackexchange.com/a/222509/92478\">detailed in his answer</a>, one can argue if leaking all of the tree's nodes should really be considered as a \"small\" memleak. A possible solution for this is to use smart pointers from <code>&lt;memory&gt;</code>. There is a good overview in <a href=\"https://herbsutter.com/2013/06/05/gotw-91-solution-smart-pointer-parameters/\" rel=\"nofollow noreferrer\">this blog post</a> by Herb Sutter on which type of smart pointer (e.g. <code>std::unique_ptr</code> or <code>std::shared_ptr</code>) as well as the type of parameter passing (by-reference vs. by-value) should be used to express a certain \"meaning\".</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T05:15:31.090", "Id": "430662", "Score": "0", "body": "Completely disagree with the comment about the interface. Pass by reference to indicate you are **not** transferring ownership. If you pass a pointer its not obvious were ownership is supposed to be and this will lead to errors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T05:25:26.533", "Id": "430664", "Score": "0", "body": "@MartinYork: I do not advocate to use pointers. The point I was trying to make was to provide either interface, not both of them, and make the other one (preferably the pointer version) private for the exact same reason you gave. Maybe my wording is off or I misunderstood your comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T07:54:30.137", "Id": "430683", "Score": "1", "body": "The memory leak is not \"small\" - it's the *entire content* of the tree! (As I'm currently writing in my answer)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T08:02:52.083", "Id": "430689", "Score": "0", "body": "@TobySpeight: Since he takes the `Packet` by reference, they are ATM cleaned up correctly and only the `Node*` are leaked, or am I missing something here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T08:04:00.083", "Id": "430690", "Score": "0", "body": "Yes, I meant all the nodes. I didn't consider the packets to be part of the tree, since they are owned by `main()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T08:11:16.627", "Id": "430691", "Score": "0", "body": "@TobySpeight: \"small\" was not meant to downplay the significance of the memleak, but more on the amount of memory that is actually leaked. I have seen memleaks with arrays and large matrices that would eat your RAM in under a second. Compared to them, it's \"small\", but significant nevertheless." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T19:00:52.840", "Id": "222482", "ParentId": "222481", "Score": "4" } }, { "body": "<h1>Don't import the standard namespace</h1>\n<p>Namespace <code>std</code> is a large, and growing, namespace. Do you know every identifier in it? Including the ones to be defined in C++20 and beyond? Bringing all its names into the global namespace not only eliminates the benefits of using namespaces, but also has the potential to silently and subtly change the meaning of your program in future (e.g. by supplying an unambiguously better match for one of your function calls).</p>\n<p>It's an especially bad practice in a header file, as now you're inflicting the breakage on <em>every single user</em> of that header file, with no way to correct it.</p>\n<h1>Syntax errors</h1>\n<p>This doesn't compile:</p>\n<blockquote>\n<pre><code>class BST {\n void BST::insert(Packet&amp; packet);\n void BST::insert(Node* &amp;p, Node *newNode);\n};\n</code></pre>\n</blockquote>\n<p>Remove the extra qualification from the members.</p>\n<h1>Self-initialization</h1>\n<p>It's useless to initialize <code>packet</code> using its own (uninitialized) value here:</p>\n<blockquote>\n<pre><code>Node() : packet(packet), rlink(nullptr), llink(nullptr) {}\n</code></pre>\n</blockquote>\n<h1>Memory leak</h1>\n<p>I'm not sure how you exercised the test program, but when I ran it with Valgrind, it immediately told me about this leak:</p>\n<pre class=\"lang-none prettyprint-override\"><code>==31705== HEAP SUMMARY:\n==31705== in use at exit: 144 bytes in 6 blocks\n==31705== total heap usage: 20 allocs, 14 frees, 74,208 bytes allocated\n==31705== \n==31705== 144 (24 direct, 120 indirect) bytes in 1 blocks are definitely lost in loss record 6 of 6\n==31705== at 0x4835DEF: operator new(unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==31705== by 0x10A276: BST::insert(Packet&amp;) (222481.cpp:54)\n==31705== by 0x10A744: main (222481.cpp:104)\n</code></pre>\n<p>If we're owning raw pointers, we need to be absolutely sure every <code>new</code> is paired with exactly one <code>delete</code>. It's much better to use the smart pointers provided in <code>&lt;memory&gt;</code> than to try to do this on our own.</p>\n<h1>Encapsulation</h1>\n<p><code>Node</code> isn't part of the public interface. If we make it a private struct within <code>BST</code>, then <code>BST</code> gets full access (not needing a <code>friend</code> declaration), but no other code does. That's what we really want.</p>\n<h1>Flexibility</h1>\n<p><code>preorderTraversal()</code> hard-codes the action to take for each node (printing it). What we want is to use the <em>Visitor pattern</em>, where we pass the action as a parameter to the call.</p>\n<h1>Ease of use</h1>\n<p>We've made the interface unnecessarily hard to use, by insisting that packets are passed by reference. This means that the calling code is obliged to ensure that every packet outlives the tree. If packets could be copied/moved to the tree, then it would be much easier for other code to use it.</p>\n<h1>Clean output</h1>\n<p>Is there any reason not to end the output with a newline? It's very annoying when commands leave the next shell prompt dangling halfway across the terminal.</p>\n<h1>Portability</h1>\n<p>Don't use <code>std::system()</code> if you can avoid it:</p>\n<pre class=\"lang-none prettyprint-override\"><code>sh: 1: pause: not found\n</code></pre>\n<p>Even if such a program was present in my search path, how do you know what function it performs? I'm guessing it's a program that waits forever (like <code>sleep inf</code> on a GNU system). That sounds like a real obstruction to using the test (e.g. it will prevent <code>make test</code> from ever completing successfully). Is that really what's desired?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T08:19:39.233", "Id": "430692", "Score": "0", "body": "Very good points. I'm so used to autofixing some of them that they're out of my mind before I start to compile the code for the first time." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T08:05:26.500", "Id": "222509", "ParentId": "222481", "Score": "3" } } ]
{ "AcceptedAnswerId": "222509", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T18:12:03.027", "Id": "222481", "Score": "2", "Tags": [ "c++", "tree" ], "Title": "Binary Search Tree to store objects by object ID" }
222481
<p><strong>Concrete Context:</strong> I parse the header information from curl execution/request and get the array named <code>$headerARR</code>. At this point it looks like the next example, but it can vary and the content-type can be on any index (not have a certain order). I need to work around this, because it is the format accepted by the software engine and I not have the authority to change it:</p> <pre><code>array ( 0 =&gt; 'HTTP/1.1 200 OK', 1 =&gt; 'Date: Mon, 17 Jun 2019 19:32:37 GMT', 2 =&gt; 'Server: Apache/2.4.38 (Win32) OpenSSL/1.1.1a PHP/7.2.15', 3 =&gt; 'X-Powered-By: PHP/7.2.15', 4 =&gt; 'Set-Cookie: Avisistema=ihk9t1ms6r8i0u1j5t6jpjrqei; path=/; HttpOnly', 5 =&gt; 'Expires: Thu, 19 Nov 1981 08:52:00 GMT', 6 =&gt; 'Cache-Control: no-store, no-cache, must-revalidate', 7 =&gt; 'Pragma: no-cache', 8 =&gt; 'Set-Cookie: Avisistema=ihk9t1ms6r8i0u1j5t6jpjrqei; expires=Tue, 18-Jun-2019 03:32:37 GMT; Max-Age=28799; path=/; HttpOnly', 9 =&gt; 'Set-Cookie: SageFirmeware=Avisistema.A.0.2015.01.10; expires=Tue, 18-Jun-2019 03:32:37 GMT; Max-Age=28799; path=/; HttpOnly', 10 =&gt; 'Content-Length: 232', 11 =&gt; 'Content-Type: application/json', ) </code></pre> <p>I determine wich <code>Content-Type</code> I use with this code:</p> <pre><code> //array construct: $ch = curl_init(); $Data = curl_exec($ch); $Body = substr($Data, curl_getinfo($ch, CURLINFO_HEADER_SIZE)); $headers = $Data; $headerARR = array_filter(explode(PHP_EOL, substr($headers, 0, curl_getinfo($ch, CURLINFO_HEADER_SIZE)))); //can update anything after this line.... $head = ''; foreach ($headerARR as $line) { $leed = explode(':', $line); if (strpos($leed[0], "Content-Type") !== false) { $head = str_replace(' ', '', $leed[1]); } } </code></pre> <p><strong>Is there any shorter alternative?</strong></p> <p><strong>Is there any way to get better performance?</strong></p> <p><strong>I can not change before or during the generation of the array, since the content-type is wanted to carry a separate function in the future.</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T21:25:56.177", "Id": "430648", "Score": "0", "body": "Your code is incomplete. Where do `$Data` and `$ch` come from? Otherwise all we can work with is the array search, and that's not much. Also: Shorter code is not always faster or better code, so shortness shouldn't be your main goal. One example: Once you've found the header you could `break` out of the loop. That would make your code faster/better, but also longer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T21:38:12.140", "Id": "430649", "Score": "0", "body": "`$Data` and `$ch` come from the execution of the curls" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T07:48:03.330", "Id": "430682", "Score": "0", "body": "Show us the `$Data` string and we might be able to show you a more direct approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T14:52:51.407", "Id": "430769", "Score": "0", "body": "@mickmackusa I do not know what string string you are talking about, I show you the array that is what you should use to search for the text, I do not know if you understand the approach or you want to do something else that I have not indicated what I should do ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T21:04:59.157", "Id": "430852", "Score": "0", "body": "I am assuming that you have posted `$headerARR`. KIKO was saying that we can explain a very basic technique and show you how to perform an early `break` in a loop, or you can provide the raw input before you chop and filter it. With the raw `$Data` string we may be able to show you a more direct solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T09:15:27.990", "Id": "430906", "Score": "1", "body": "this assignment is pointless and just adds confusion and bloat to your code `$headers = $Data;` --- if you just need the content type, maybe a regex will work, something like this `preg_match(\"/Content-Type: (?P<content_type>[^\\n]+)/\", substr($Data, 0, curl_getinfo($ch, CURLINFO_HEADER_SIZE)), $match)` instead of exploding and iteration. [Regex Example](https://regex101.com/r/uGqjeY/1)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T10:39:21.470", "Id": "430913", "Score": "2", "body": "That's kind of what I was going to suggest (not that exact pattern), but we aren't meant to post answers as comments. @Artistic https://meta.stackexchange.com/a/296481/352329" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-22T04:01:43.923", "Id": "431265", "Score": "0", "body": "@walternuñez Your question will probably qualify for reopening if you simply include \"concrete context\" by providing the input string." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-22T15:30:22.487", "Id": "431333", "Score": "0", "body": "@mickmackusa i dont have a the string; i have and array. can you view the array `$headerARR`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-22T15:41:47.990", "Id": "431334", "Score": "0", "body": "@mickmackusa Check Again.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-22T20:38:31.260", "Id": "431375", "Score": "1", "body": "That edit will not get your question reopened. Why are you been resistant? I don't understand your motivation. My answer shows that splitting the `$Data` on the end of line characters is unnecessary work. I cannot vote to reopen until you have posted the `$Data` string." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-22T21:47:18.843", "Id": "431382", "Score": "0", "body": "@mickmackusa ok" } ]
[ { "body": "<p>You can directly isolate and extract the content type by matching the start of the line, the label and a space, then restart the fullstring match, then match one or more non-newline characters.</p>\n\n<p>Pattern Demo: <a href=\"https://regex101.com/r/QZz9IE/1/\" rel=\"nofollow noreferrer\">https://regex101.com/r/QZz9IE/1/</a></p>\n\n<p>PHP: (<a href=\"https://3v4l.org/jZsFd\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>echo preg_match('~^Content-Type: \\K.+~m', $Data, $match) ? $match[0] : 'fail';\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>application/json\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T11:09:49.107", "Id": "430917", "Score": "0", "body": "We should refrain from answering clearly off-topic questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T13:41:05.067", "Id": "430928", "Score": "0", "body": "@dfhwze why the question is off-topic ??" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T13:46:59.900", "Id": "430930", "Score": "0", "body": "@mickmackusa thank you for the answer i tha i look." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T20:46:31.297", "Id": "430969", "Score": "1", "body": "@dfhwze I agree that the OP should have provided a more complete question. I felt that my hand was forced after Artistic's commented solution. Question resolving comments lead to page abandonment. I would not have answered if I could have deleted Artistic's comment. I will not be offended if diamond mods want to scrub this page." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T20:49:21.730", "Id": "430970", "Score": "0", "body": "@mickmackusa I get your point. Let's wait and see how the community handles this one :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T22:30:01.610", "Id": "430977", "Score": "0", "body": "@walter , KIKO and I were very clear about wanting to see the `$Data` string and why it was important to providing the most direct solution (and highest quality review). I was going to withhold my answer until the question was complete, but when a suboptimal (IMO) solution was provided there would be little motivation for you to give your question any more attention. Because I didn't want future researchers to copy-paste the commented solution, I posted what I felt was best after fabricating some semblence of your input. You should complete your question with the required ingredient." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T06:28:50.163", "Id": "430999", "Score": "0", "body": "@mickmackusa I do not have a text string; I have an array with which you must work. I'm not going to give you something that is not inside the data or the structure presented. it's as if someone tells you how to sumo numbers and you answer does not want number give me letters ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T06:52:16.333", "Id": "431000", "Score": "0", "body": "In your posted code, `$Data` is immediately processed by `substr()`. This means you have a string or your code does not work because `substr()` ONLY works on a string. I don't how to explain it any clearer. https://php.net/manual/en/function.substr.php We would like you to post your string before you `explode()` it." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T10:56:35.793", "Id": "222576", "ParentId": "222485", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T19:37:30.943", "Id": "222485", "Score": "-2", "Tags": [ "php", "array", "parsing" ], "Title": "Parse header information" }
222485
<p>The code shown below takes the partial derivative of each pixel of the output fused image of a neural network with respect to input image of the neural network using tensorflow's <code>tf.gradients(Y, X)</code> and compute a Jacobian matrix for each of the two input images MRI and PET. However, the code is really slow since I currently define a for loop by iterating through each pixel to compute the Jacobian matrix.</p> <pre><code>jacob_matrix_mri = np.zeros((65536,256,256)) jacob_matrix_pet = np.zeros((65536,256,256)) count = 0 saver = tf.train.Saver() with tf.Session() as sess: sess.run(tf.global_variables_initializer()) saver.restore(sess,'/home/nora/Desktop/MBIA 2019/Checkpoint/') for i in range(image_width): for j in range(image_length): grad_mri = tf.gradients(fused_image[0,i,j,0],images_mri) grad_pet = tf.gradients(fused_image[0,i,j,0],images_pet) gradients_mri, gradients_pet, _ =sess.run([grad_mri,grad_pet,fused_image], feed_dict{images_mri:test_mri, images_pet:test_pet}) jacob_matrix_mri[count,:,:] = np.squeeze(gradients_mri[0][0,:]) jacob_matrix_pet[count,:,:] = np.squeeze(gradients_pet[0][0,:]) count = count+1 if count % 1000 == 0: print count t2 = time.time() print (t2-t1) t3 = time.time() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T02:00:57.833", "Id": "430866", "Score": "0", "body": "What are you looking to get out of a review? The “however it’s very slow” bit makes it sound like you’d like tips on speeding up the code, but you don’t actually ask this... Wherever you post a question, the more explicit you are, the more likely you are of getting a useful answer!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T20:30:05.370", "Id": "222488", "Score": "5", "Tags": [ "python", "performance", "image", "tensorflow" ], "Title": "Tensorflow loop to analyze gradients derived from MRI and PET images" }
222488
<p>Can someone please help me modify this script to generate and modify the document faster? It currently takes about 5-10 seconds to create the variables. About 10 seconds for the entire script to run.</p> <p>Here is the code for the script:</p> <h1>Copy Word Template to Local C Drive:</h1> <pre><code>Copy-Item \\172.16.0.75\allaccess\Scripts\transfer2.docx C:\ </code></pre> <h1>Create Replace-Word Function:</h1> <pre><code>function Replace-Word( [string]$Document, [string]$FindText, [string]$ReplaceText ) { $ReplaceAll = 2 $FindContinue = 1 $MatchCase = $false $MatchWholeWord = $true $MatchWildcards = $false $MatchSoundsLike = $false $MatchAllWordForms = $false $Forward = $true $Wrap = $FindContinue $Format = $false $Word = New-Object -ComObject Word.Application $Word.Visible = $false $OpenDoc = $Word.Documents.Open($Document) $Selection = $Word.Selection $Selection.Find.Execute( $FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $ReplaceAll ) | Out-Null $OpenDoc.Close() $Word.Quit() } #Prompt user for information and generate several variables: $assettag = Read-Host -Prompt 'Input Asset Tag' $fullasset = id : 3973 name : XTX-L-25677 asset_tag : 25677 serial : XXXXXX model : @{id=1440; name=Dell Latitude 5591} model_number : eol : @{date=2018-08-06; formatted=Aug 6, 2018} status_label : @{id=6; name=Deployed; status_type=deployable; status_meta=deployed} category : @{id=1; name=Laptop} manufacturer : @{id=1; name=Dell} supplier : @{id=6; name=Dell} notes : order_number : company : @{id=2; name=SITE} location : rtd_location : @{id=287; name= Technology Division} image : assigned_to : @{id=2672; username=first; name=first last; first_name=First; last_name=last; warranty_months : warranty_expires : created_at : @{datetime=2018-08-14 09:41:00; formatted=Aug 14, 2018 9:41AM} updated_at : @{datetime=2019-06-11 10:23:38; formatted=Jun 11, 2019 10:23AM} last_audit_date : next_audit_date : deleted_at : purchase_date : @{date=2018-08-06; formatted=Aug 6, 2018} last_checkout : @{datetime=2019-06-10 08:40:22; formatted=Jun 10, 2019 8:40AM} expected_checkin : purchase_cost : checkin_counter : 2 checkout_counter : 3 requests_counter : 0 user_can_checkout : False custom_fields : @{User=; Computer Type=; OS=; Memory=; Processor=; Wired MAC=; Wireless MAC=} available_actions : @{checkout=True; checkin=True; clone=True; restore=False; update=True; delete=True} foreach ($fullasset in $fullasset) { $model = (($fullasset).model).name $serial = ($fullasset).serial $location = (($fullasset).rtd_location).name $category = (($fullasset).category).name $status = (($fullasset).status_label).name } $date = Get-Date -Format "M-dd-yy" $dom = $env:userdomain $usr = $env:username $name = ([ADSI]"WinNT://$dom/$usr,user").FullName </code></pre> <h1>Use generated variables and Replace-Word function to modify document:</h1> <pre><code>Replace-Word -Document C:\transfer2.docx -FindText '$assettag' -ReplaceText $assettag Replace-Word -Document C:\transfer2.docx -FindText '$model' -ReplaceText $model Replace-Word -Document C:\transfer2.docx -FindText '$location' -ReplaceText $location Replace-Word -Document C:\transfer2.docx -FindText '$date' -ReplaceText $date Replace-Word -Document C:\transfer2.docx -FindText '$serial' -ReplaceText $serial Replace-Word -Document C:\transfer2.docx -FindText '$x' -ReplaceText $x Replace-Word -Document C:\transfer2.docx -FindText '$status' -ReplaceText $status Replace-Word -Document C:\transfer2.docx -FindText '$category' -ReplaceText $category Replace-Word -Document C:\transfer2.docx -FindText '$name' -ReplaceText $name </code></pre> <p>Please let me know if there is anything I can consolidate or modify to improve speed. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-25T18:12:52.453", "Id": "431792", "Score": "0", "body": "I modified some parts of the script for speed. Does anyone have recommendations on how to improve the replace-word function?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T20:37:35.163", "Id": "222489", "Score": "2", "Tags": [ "powershell" ], "Title": "Powershell script to find and replace words based on asset tag input" }
222489
<p>I wrote this program to make a simple in-memory database using SQLite and JDBC. Requirements I was trying to accomplish are below.</p> <ol> <li>It should consume a CSV file, parse the data, and insert it into the in-memory database.</li> <li>Table name is X and it has 10 columns (named A - J).</li> <li>If any of the columns in a row of the CSV file are blank, it should be written into a <code>bad-data-&lt;timestamp&gt;.csv</code> file and not inserted into the database.</li> <li>At the end of the process, write statistics to a log file: <ol> <li>Number of records received</li> <li>Number of successful records (records allowed to be inserted to database)</li> <li>Number of failed records (records written to <code>bad-data-&lt;timestamp&gt;.csv</code> file).</li> </ol></li> </ol> <p>The "sample.csv" file can be found <a href="https://filebin.net/aib6j3s9lsxez50u" rel="nofollow noreferrer">here</a>.</p> <p>This is my first time trying to do anything with databases or OpenCSV so let me know if I can structure it better or anything else. I would really appreciate some constructive criticism.</p> <pre><code>package com.ms3.dbx; import com.opencsv.CSVReader; import com.opencsv.CSVReaderBuilder; import com.opencsv.CSVWriter; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.nio.file.Files; import java.nio.file.Paths; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.Statement; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; public class SQLiteTest { private final String url = "jdbc:sqlite::memory:"; private Connection connection = null; private final String csvPath = "/Users/home/eclipse-workspace/dbx/src/main/java/com/ms3/dbx/sample.csv"; private final String badDataPath = "/Users/home/eclipse-workspace/dbx/src/main/java/com/ms3/dbx/bad-data-"; private final String badDataExt = ".csv"; private final DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss"); private final String badDataFilename = badDataPath + df.format(new Date()) + badDataExt; private final String logFilePath = "/Users/home/eclipse-workspace/dbx/src/main/java/com/ms3/dbx/logFile.log"; private int recordsReceived = 0; private int recordsSuccessful = 0; private int recordsFailed = 0; static { try { Class.forName("org.sqlite.JDBC"); } catch (ClassNotFoundException e) { throw new ExceptionInInitializerError(e); } } // Opens connection to in-memory database private void openConnection() throws SQLException { if (connection == null || connection.isClosed()) { connection = DriverManager.getConnection(url); } } // Closes connection to database private void closeConnection() throws SQLException { connection.close(); } // Creates a table X in database private void createTable() { try { final Statement statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS X" + "(A TEXT," + " B TEXT," + " C TEXT," + " D TEXT," + " E TEXT," + " F TEXT," + " G TEXT," + " H TEXT," + " I TEXT," + " J TEXT);"); } catch (SQLException e) { e.getMessage(); } } // Reads data from sample.csv file using OpenCSV // If there is a blank column in a row, write it to "bad-data-&lt;timestamp&gt;.csv" file // Else insert the row into the database // Increment recordsReceived for each row in sample.csv file // Increment recordsSuccessful for each row that has every column filled with data // Increment recordsFailed for each row that has at least one blank column private void insertFromCSV() { try { Reader reader = Files.newBufferedReader(Paths.get(csvPath)); CSVReader csvReader = new CSVReaderBuilder(reader).withSkipLines(1).build(); Writer writer = Files.newBufferedWriter(Paths.get(badDataFilename)); CSVWriter csvWriter = new CSVWriter(writer, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END); String[] headerRecord = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"}; csvWriter.writeNext(headerRecord); PreparedStatement pstatement = connection.prepareStatement("INSERT INTO X(A,B,C,D,E,F,G,H,I,J) " + "VALUES(?,?,?,?,?,?,?,?,?,?);"); String[] nextRecord; while ((nextRecord = csvReader.readNext()) != null) { recordsReceived++; if (!Arrays.asList(nextRecord).contains("")) { recordsSuccessful++; pstatement.setString(1, nextRecord[0]); pstatement.setString(2, nextRecord[1]); pstatement.setString(3, nextRecord[2]); pstatement.setString(4, nextRecord[3]); pstatement.setString(5, nextRecord[4]); pstatement.setString(6, nextRecord[5]); pstatement.setString(7, nextRecord[6]); pstatement.setString(8, nextRecord[7]); pstatement.setString(9, nextRecord[8]); pstatement.setString(10, nextRecord[9]); pstatement.executeUpdate(); } else { recordsFailed++; csvWriter.writeNext(nextRecord); } } csvWriter.close(); } catch (SQLException | IOException e) { e.getMessage(); } } // Query the database and print everything to make sure the data is actually being inserted private void testDB() { try { final Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery("SELECT * FROM X;"); ResultSetMetaData rsmd = rs.getMetaData(); int numColumns = rsmd.getColumnCount(); while(rs.next()) { for (int i = 1; i &lt;= numColumns; i++) { System.out.print(rs.getString(i) + " "); } System.out.println(); } } catch (SQLException e) { e.getMessage(); } } // Log the received, successful, and failed records in a log file private void logStats() { try { FileWriter fw = new FileWriter(logFilePath); fw.write("Records Received: " + recordsReceived + "\n"); fw.write("Records Successful: " + recordsSuccessful + "\n"); fw.write("Records Failed: " + recordsFailed); fw.close(); } catch (IOException e) { e.getMessage(); } } public static void main(String[] args) throws SQLException { SQLiteTest obj = new SQLiteTest(); obj.openConnection(); obj.createTable(); obj.insertFromCSV(); obj.testDB(); obj.logStats(); obj.closeConnection(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T21:06:10.567", "Id": "430853", "Score": "0", "body": "Anyone have any suggestions or critiques? Could really use the help, thanks!" } ]
[ { "body": "<p>You can consider the following points:</p>\n\n<ol>\n<li><p>For <code>insertFromCSV()</code> you can set param using loop instend of hard coded <code>pstatement.setString(1, nextRecord[0]);</code> You will get benefited in case of nextRecord array size is change(increase)</p></li>\n<li><p><code>recordsReceived++</code> its get increment 3 times check for that and no need to put it in <code>if..else..</code></p></li>\n<li>Inside of while(...) if and else both parts have some code then no\nneed to put negation(!) simply swap your code block for <code>Arrays.asList(nextRecord).contains(\"\")</code></li>\n<li>You can use looger framework for logging. </li>\n<li>Use try-with-resources if using Java 7 or above.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T09:59:48.797", "Id": "224961", "ParentId": "222491", "Score": "2" } } ]
{ "AcceptedAnswerId": "224961", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T21:20:42.953", "Id": "222491", "Score": "7", "Tags": [ "java", "programming-challenge", "sqlite", "maven" ], "Title": "SQLite In-memory Database That Inserts Data Read From a CSV File" }
222491
<p>Here is a set of classes that are used to build <code>where</code> clause for SQL Server and Oracle for different field types e.g. <code>text</code>, <code>numeric</code> and <code>date</code>.</p> <pre><code>public interface IConditionBuilder { bool CanHandle(FilterAction filterAction); string BuildCondition(SearchCondition filterCondition); } public abstract class ConditionBuilder&lt;TContext&gt; : IConditionBuilder where TContext : FieldSearchContext { public abstract string OperatorSymbol { get; } public string BuildCondition(SearchCondition searchCondition) { var conditionBuilder = new StringBuilder(); var context = searchCondition.GetContext&lt;TContext&gt;(); conditionBuilder.Append(context.FieldId); conditionBuilder.Append(OperatorSymbol); conditionBuilder.Append(GetValue(context)); return conditionBuilder.ToString(); } public abstract bool CanHandle(FilterAction filterAction); public abstract object GetValue(TContext context); } public class TextLikeConditionBuilder : ConditionBuilder&lt;TextContext&gt; { public override string OperatorSymbol =&gt; " LIKE "; public override bool CanHandle(FilterAction action) =&gt; action == FilterAction.TextLike; public override object GetValue(TextContext context) { if (context.Text == null) { return null; } return string.Concat("%", context.Text, "%"); } } public class TextEqualsConditionBuilder : ConditionBuilder&lt;TextContext&gt; { public override string OperatorSymbol =&gt; " = "; public override bool CanHandle(FilterAction action) =&gt; action == FilterAction.TextEqual; public override object GetValue(TextContext context) { if (context.Text == null) { return null; } return "'" + context.Text + "'"; } } public class NumericLessThanConditionBuilder : ConditionBuilder&lt;NumericContext&gt; { public override string OperatorSymbol =&gt; " &lt; "; public override bool CanHandle(FilterAction action) =&gt; action == FilterAction.NumericLessThan; public override object GetValue(NumericContext context) { return context.Number; } } public class DateGreaterThanAndLessThanEqualConditionBuilder : IConditionBuilder { public const string GREATER_THAN = " &gt; "; public const string LESS_THAN_EQUAL = " &lt;= "; public string BuildCondition(SearchCondition filterCondition) { var conditionBuilder = new StringBuilder(); var context = filterCondition.GetContext&lt;DateContext&gt;(); conditionBuilder.Append(context.FieldId); conditionBuilder.Append(GREATER_THAN); conditionBuilder.Append("'" + context.FromDate + "'"); conditionBuilder.Append(LESS_THAN_EQUAL); conditionBuilder.Append("'" + context.EndDate + "'"); return conditionBuilder.ToString(); } public bool CanHandle(FilterAction action) =&gt; action == FilterAction.DateGreaterThanLessThan; } </code></pre> <p>I want to extend the functionality so that context.FieldId is sanitized before it is used to build the <code>condition</code> statement for e.g. these classes will build a statement like <code>Name = 'Aashish'</code>, I want the classes to build statement as <code>[Name] = 'Aashish'</code>. These classes are consumed by other developers so I don't want to break the functionality for consumers as a result of the changes I will make, basically adhere to Open-Closed principle. So, here is how I implemented these changes. Notice how I added a virtual function <code>SanitizeFieldId</code> in <code>ConditionBuilder</code> and <code>DateGreaterThanAndLessThanEqualConditionBuilder</code>.</p> <pre><code>public abstract class ConditionBuilder&lt;TContext&gt; : IConditionBuilder where TContext : FieldSearchContext { public abstract string OperatorSymbol { get; } public string BuildCondition(SearchCondition searchCondition) { var conditionBuilder = new StringBuilder(); var context = searchCondition.GetContext&lt;TContext&gt;(); conditionBuilder.Append(SanitizeFieldId(context.FieldId)); conditionBuilder.Append(OperatorSymbol); conditionBuilder.Append(GetValue(context)); return conditionBuilder.ToString(); } public abstract bool CanHandle(FilterAction filterAction); public abstract object GetValue(TContext context); protected virtual string SanitizeFieldId(string fieldId) { return fieldId; } } public class DateGreaterThanAndLessThanEqualConditionBuilder : IConditionBuilder { public const string GREATER_THAN = " &gt; "; public const string LESS_THAN_EQUAL = " &lt;= "; public string BuildCondition(SearchCondition filterCondition) { var conditionBuilder = new StringBuilder(); var context = filterCondition.GetContext&lt;DateContext&gt;(); conditionBuilder.Append(SanitizeFieldId(context.FieldId)); conditionBuilder.Append(GREATER_THAN); conditionBuilder.Append("'" + context.FromDate + "'"); conditionBuilder.Append(LESS_THAN_EQUAL); conditionBuilder.Append("'" + context.EndDate + "'"); return conditionBuilder.ToString(); } public bool CanHandle(FilterAction action) =&gt; action == FilterAction.DateGreaterThanLessThan; protected virtual string SanitizeFieldId(string fieldId) { return fieldId; } } public class SanitizedFieldConditionBuiler&lt;TContext&gt; : ConditionBuilder&lt;TContext&gt; where TContext : FieldSearchContext { private ConditionBuilder&lt;TContext&gt; _baseConditionBuilder; private IColumnSanitizer _columnSanitizer; public SanitizedFieldConditionBuiler(ConditionBuilder&lt;TContext&gt; baseConditionBuilder, IColumnSanitizer columnSanitizer) { _baseConditionBuilder = baseConditionBuilder; _columnSanitizer = columnSanitizer; } public override string OperatorSymbol =&gt; _baseConditionBuilder.OperatorSymbol; public override bool CanHandle(FilterAction filterAction) =&gt; _baseConditionBuilder.CanHandle(filterAction); public override object GetValue(TContext context) =&gt; _baseConditionBuilder.GetValue(context); protected override string SanitizeFieldId(string fieldId) { return _columnSanitizer.Sanitize(fieldId); } } public class SanitizedDateFieldGreaterThanAndLessThanEqualConditionBuilder : DateGreaterThanAndLessThanEqualConditionBuilder { private IColumnSanitizer _columnSanitizer; public SanitizedDateFieldGreaterThanAndLessThanEqualConditionBuilder(IColumnSanitizer columnSanitizer) { _columnSanitizer = columnSanitizer; } protected override string SanitizeFieldId(string fieldId) { return _columnSanitizer.Sanitize(fieldId); } } </code></pre> <p>I use extension methods to initialize <code>SanitizedFieldConditionBuiler</code>and <code>SanitizedDateFieldGreaterThanAndLessThanEqualConditionBuilder</code>as shown below:</p> <pre><code>public static class Extensions { public static SanitizedFieldConditionBuiler&lt;TContext&gt; SanitizeField&lt;TContext&gt;(this ConditionBuilder&lt;TContext&gt; source, IColumnSanitizer columnSanitizer) where TContext : FieldSearchContext { return new SanitizedFieldConditionBuiler&lt;TContext&gt;(source, columnSanitizer); } public static SanitizedDateFieldGreaterThanAndLessThanEqualConditionBuilder SanitizeField(this IConditionBuilder source, IColumnSanitizer columnSanitizer) { return new SanitizedDateFieldGreaterThanAndLessThanEqualConditionBuilder(columnSanitizer); } } </code></pre> <p>The Sanitization is available by means of an interface <code>IColumnSanitizer</code> and has two different implementations, for Sql Server and Oracle respectively</p> <pre><code> public interface IColumnSanitizer { string Sanitize(string columnName); } public class SqlSanitizer : IColumnSanitizer { public string Sanitize(string columnName) { return "[" + columnName + "]"; } } public class OracleSanitizer : IColumnSanitizer { public string Sanitize(string columnName) { return "\"" + columnName + "\""; } } </code></pre> <p>Below is how context classes are implemented:</p> <pre><code>public abstract class FieldSearchContext { public virtual string FieldId { get; } protected FieldSearchContext(string fieldId) { FieldId = fieldId; } } public class DateContext : FieldSearchContext { public DateContext(string fieldId, DateTime? fromDate, DateTime? endDate) : base(fieldId) { FromDate = fromDate; EndDate = endDate; } public DateTime? FromDate { get; } public DateTime? EndDate { get; } } public class TextContext : FieldSearchContext { public TextContext(string fieldId, string text) : base(fieldId) { Text = text; } public string Text { get; } } public class NumericContext : FieldSearchContext { public NumericContext(string fieldId, decimal number) : base(fieldId) { Number = number; } public decimal Number { get; } } </code></pre> <p>These changes work perfectly fine but I want to find out if this can be achieved in a different and better way.</p> <p>Use the code below to see it in action:</p> <pre><code> class Program { static void Main(string[] args) { var conditions = new List&lt;SearchCondition&gt;() { new SearchCondition(new NumericContext("Numeric Field", 1234), FilterAction.NumericLessThan), new SearchCondition(new TextContext("Text Field", "ASDF"), FilterAction.TextEqual), new SearchCondition(new TextContext("Text Field", "QWERTY"), FilterAction.TextLike), new SearchCondition(new DateContext("Date Field", DateTime.Now, DateTime.Now.AddYears(1)), FilterAction.DateGreaterThanLessThan) }; Console.WriteLine(BuildWhereClause(Operation.AND, conditions)); Console.Read(); } private static string BuildWhereClause(Operation operation, IList&lt;SearchCondition&gt; conditions) { var returnValue = new List&lt;string&gt;(); var conditionBuilders = new List&lt;IConditionBuilder&gt;() { new TextEqualsConditionBuilder().SanitizeField(new SqlSanitizer()), new NumericLessThanConditionBuilder().SanitizeField(new SqlSanitizer()), new TextLikeConditionBuilder().SanitizeField(new SqlSanitizer()), new DateGreaterThanAndLessThanEqualConditionBuilder().SanitizeField(new SqlSanitizer()) }; foreach (var condition in conditions) { var context = condition.GetContext&lt;FieldSearchContext&gt;(); var conditionBuilder = conditionBuilders.FirstOrDefault(u =&gt; u.CanHandle(condition.FilterAction)); returnValue.Add(conditionBuilder.BuildCondition(condition)); } if (returnValue.Any()) return string.Join(Convert.ToString(" " + operation + " "), returnValue); return string.Empty; } } enum Operation : int { AND = 1, OR = 2 } </code></pre> <p>EDIT: </p> <p>Added SearchCondition</p> <pre><code>public class SearchCondition { private readonly FieldSearchContext _fieldSearchContext; private FilterAction _filterAction; public FilterAction FilterAction { get { return _filterAction; } } public SearchCondition(FieldSearchContext fieldSearchContext, FilterAction action) { _fieldSearchContext = fieldSearchContext; _filterAction = action; } public T GetContext&lt;T&gt;() where T : FieldSearchContext { return (T)_fieldSearchContext; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T07:01:14.043", "Id": "430671", "Score": "0", "body": "Could you show the implementation of `SearchCondition`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T14:12:54.843", "Id": "430763", "Score": "0", "body": "@HenrikHansen just added SearchCondition also." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T15:21:25.440", "Id": "430782", "Score": "0", "body": "Post titles should reflect the purpose of the code - I would suggest \"SQL Injection Framework\" ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T15:34:33.567", "Id": "430784", "Score": "0", "body": "Would be nice to see the definition for `FilterAction`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T15:35:23.897", "Id": "430785", "Score": "0", "body": "And the code snippets are a PITA to copy-paste in an IDE because of your incremental changes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T17:31:16.250", "Id": "430798", "Score": "1", "body": "Please don't edit the original post in response to existing answers, it invalidates them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T17:45:26.283", "Id": "430804", "Score": "0", "body": "I'm voting to close this question as off-topic because OP confirmed in a comment that some parts of it aren't real and were edited." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T19:08:34.227", "Id": "430828", "Score": "0", "body": "@t3chb0t they were edited because it was not possible to put all of it here. I added 4 of them here `TextEqualsConditionBuilder`, `NumericLessThanConditionBuilder`, `TextLikeConditionBuilder`, and `DateGreaterThanAndLessThanEqualConditionBuilder` so that I can explain my question clearly. Also it allowed me to put a working copy of the code here which would not have been possible otherwise. If you are saying codereview.stackexchange.com is not meant for such situations then that's fine, but I think that is not right." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T19:13:47.247", "Id": "430829", "Score": "3", "body": "It's always nice when the code can be run but it's optional. More important is that the code is unchanged becuase otherwise reviewing it ends in _The other things you mentioned regarding return \"'\" + context.Text + \"'\";, I don't have it that way in the actual code._ which is counterproductive." } ]
[ { "body": "<p><code>Sanitizer</code> is a dangerous misnommer IMO. A better name could be <code>NameQuoter</code>, since that's what it does: it uses the RDBMS-specific syntax for <em>quoting</em> identifiers - SQL Server using square brackets, MySQL using backticks, Oracle using backslashes: this has nothing to do with <em>sanitizing</em>, which from what I can tell is essentially impossible to achieve with this framework that I would dub \"SQL Injection Framework\".</p>\n\n<p><code>FieldId</code> is also a misnommer - I don't know about Oracle, but on SQL Server every database object has an ID, and I would read \"field ID\" as a value that's referring to that ID. What you have is a <code>ColumnName</code>, not an ID.</p>\n\n<p><code>Context</code> is also a confusing name: in Entity Framework, <code>Context</code> refers to the unit of work; it encapsulates a transaction and exposes the repositories - as far as client code is concernd, it <em>is</em> the database connection... anyone remotely familiar with standard .NET data access code will raise an eyebrow at \"context\" being used to refer to what's essentially a wrapper object for various types of values. Why can't a <code>decimal</code> be <code>null</code>, but a <code>DateTime</code> can?</p>\n\n<p>This is a problem:</p>\n\n<pre><code>public abstract class FieldSearchContext\n{\n public virtual string FieldId { get; }\n\n protected FieldSearchContext(string fieldId)\n {\n FieldId = fieldId;\n }\n}\n</code></pre>\n\n<p>You're assigning a <code>virtual</code> property in the base constructor. That property should not be <code>virtual</code> at all. Here's why it's a problem:</p>\n\n<pre><code>public class BrokenSearchContext : FieldSearchContext\n{\n public BrokenSearchContext() : base(\"Foo\") { }\n\n public override string FieldId =&gt; \"Bar\";\n}\n</code></pre>\n\n<p>The base constructor runs first, receives <code>\"Foo\"</code>, invokes the <code>FieldId</code> property... which is overridden in the derived class... as an immutable getter. How is the base class assigning its <code>FieldId</code> now? Right: it doesn't... and that merely makes things confusing <em>in this case</em> (value read isn't the value written) - but in other situations it could mean a bug that's very hard to track down.</p>\n\n<p>Avoid <code>virtual</code> member calls in a constructors - might be innocuous in this particular case, but one day you'll be invoking a side-effecting virtual method in a base constructor, and you're not going to like it. <code>FieldId</code> has no reason to be <code>virtual</code> in the first place.</p>\n\n<p>But of all problems, this is the single most dangerous one:</p>\n\n<pre><code>public override object GetValue(TextContext context)\n{\n if (context.Text == null)\n {\n return null;\n }\n\n return \"'\" + context.Text + \"'\";\n}\n</code></pre>\n\n<p>See, I like Irish whiskey, and code like this makes me want to order a double. What happens when <code>context.Text</code> is <code>Elizabeth O'Connor</code>? Or <code>Patrick O'Neil</code>?</p>\n\n<p>Or <a href=\"https://xkcd.com/327/\" rel=\"noreferrer\"><code>Robert';DROP TABLE Students;--</code></a>?</p>\n\n<p>I'm sorry to say, the most pressing issue with this code isn't how bloated this whole \"criteria builder\" tooling works, nor how well it does or doesn't adhere to OCP: the most pressing issue with this code is that it's literally a <em>SQL Injection Framework</em>, making it child's play to generate SQL statements that can - and if this goes anywhere near a public-facing client, eventually <em>will</em> - contain malicious data... all while the consuming C# code looks and reads very much like it's perfectly safe &amp; secure.</p>\n\n<p>The biggest problem with this code, is that <em>it exists</em> - concatenating parameter values into SQL statements <strong>is not the job of the client connection</strong>. It's the job of the server, and doing this in a secure way involves commands and parameters - not string concatenations.</p>\n\n<p>I wouldn't worry about breaking existing code - the existing code <em>is already broken</em>, beyond repair. </p>\n\n<p>To be clear: the solution isn't to escape single quotes or make sure SQL keywords aren't present in the string - the solution is to stop concatenating WHERE clauses in SQL strings.</p>\n\n<p>Consider using an ORM, e.g. Entity Framework - or Dapper.NET if you want a lightweight but performant solution, to generate properly parameterized SQL statements without any concatenation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T17:04:06.333", "Id": "430793", "Score": "0", "body": "This review clears the queue of potential other reviewers. At least for me, I'm out :) On to the next question for me.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T17:27:31.197", "Id": "430796", "Score": "0", "body": "@Mathieu Guindon, Thank you for your review, I appreciate your feedback. I liked the suggestion of changing the name from Sanitizer to NameQuoter. Also that line `public virtual string FieldId { get; }` was placed mistakenly, I was trying a few things in a small sample and forgot to remove it before I posted here . I don't have it in the actual application. The other things you mentioned regarding `return \"'\" + context.Text + \"'\";`, I don't have it that way in the actual code. Thanks again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T17:30:22.347", "Id": "430797", "Score": "5", "body": "@AashishUpadhyay see, this is exactly why we **require** that you submit your real, actual, working code for peer review. For the record, there is no secure way to concatenate WHERE clause values into a SQL string. Do not do this. I don't know what your \"actual code\" is actually doing, but I'm pretty sure it doesn't involve commands and parameters, otherwise you wouldn't have written any of this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T17:35:16.650", "Id": "430802", "Score": "0", "body": "@MathieuGuindon Noted. Yes it doesn't take care of parameters and I don't think it can be changed also." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T20:06:19.397", "Id": "430841", "Score": "1", "body": "*I don't think it can be changed* - read up on the [Sunk Cost Fallacy](https://en.m.wikipedia.org/wiki/Sunk_cost) - string-concatenating WHERE clauses is a plague that needs to be eradicated with all the firepower you can throw at it. It will cost more in the long run to keep doing that, than rewriting everything to implement data access code *properly*, and that's been proven many times over - just ask any company victim of a data breach. String-concatenating WHERE clauses is a *very* serious security issue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T17:08:01.423", "Id": "430950", "Score": "0", "body": "_string-concatenating WHERE clauses is a plague that needs to be eradicated_ - sure, only how? Have you seen any resonable and working solution to this problem? I myslef do this in a couple of places because neither EF nor Dapper are better than doing this manually yourself. In fact, none of the ORMs can deal with any danymic SQL so you always have to fallback to ordinary string concatenation and if you need anything more fancy than this is your only option. I find string-concating WHERE is as dangerous as anything else in coding so there is no reason to panic ;-]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T17:15:09.453", "Id": "430951", "Score": "0", "body": "I'd even say that doing this is like building file paths. One bad move and you've deleted/overwritten an import directory and nobody is trying to avoid dynamic paths, or anything dynamic that no matter what you do, it can always go sideways." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T17:19:15.830", "Id": "430952", "Score": "0", "body": "@t3chb0t map each \"dynamic field name + value\" to an object that gives you a `@namedParameter` with its value, and assuming the field names aren't user inputs then there should be a way to build your dynamic SQL into a parameterized command string that can be safely executed without concatenating any criterion. Heck I bet I could write this in VBA with `?` positional parameters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T17:23:02.217", "Id": "430953", "Score": "2", "body": "*string-concating WHERE is as dangerous as anything else in coding so there is no reason to panic* - tell that to Mrs.Null and Mr.O'Neil ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T17:50:59.940", "Id": "430954", "Score": "0", "body": "Not buying it ;-] I'm sure there's been incidents with any API but only because people used them irresponsibly like by ignoring edge cases etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T17:52:25.077", "Id": "430955", "Score": "0", "body": "@t3chb0t I'm not making this up. http://www.bbc.com/future/story/20160325-the-names-that-break-computer-systems" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T18:07:29.913", "Id": "430957", "Score": "0", "body": "@t3chb0t your file path analogy falls apart because you don't have outsiders providing parts of the file path, giving them an opportunity to be malicious. With concatenated `WHERE` clauses that take end user input, I can [_intentionally_](https://xkcd.com/327/) add SQL statements that weren't anticipated by the developer and cause major damage." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T18:21:41.147", "Id": "430959", "Score": "0", "body": "@FreeMan _your file path analogy falls apart_ - does it? I could build a web-service allowing users to upload files and do all kinds of freaky directory and file manipulation stuff... I can let them upload json that I deserialize without validating types... I can let them call .net framework functions for some calculator etc without validating whether they are allowed... everything is dangerous when done the wrong way or simply carelessly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T18:36:46.987", "Id": "430962", "Score": "0", "body": "@t3chb0t except some dangerous things are very niche, and others extremely widespread. Directory manipulation through JSON deserialization is one, glaring SQL injection vulnerabilities are the other." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T19:04:05.570", "Id": "430966", "Score": "1", "body": "@t3chb0t I guess my point is, in the spirit of \"making wrong code look wrong\", if you're going to have dynamic-SQL with string-concatenated parameters, don't make it look like a sophisticated SQL-generator engine. If you're going to concatenate SQL WHERE clauses, *just concatenate SQL WHERE clauses* - that way it's wrong, *and it looks that way*. The problem I have with something like what the OP has built is that it's hiding the vulnerability behind 20 layers of abstraction, using terminology that makes it *look* like the consuming code might be perfectly fine." } ], "meta_data": { "CommentCount": "15", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T16:52:26.883", "Id": "222535", "ParentId": "222492", "Score": "9" } }, { "body": "<p>Just one thing...</p>\n<h3>Use db-provider's <em>sanitizer</em></h3>\n<p>There is already a <em>sanitizer</em> that the <code>DbCommandBuilder</code> provides. You can use it like this:</p>\n<pre><code>using (var commandBuilder = DbProviderFactories.GetFactory(sqlConnection).CreateCommandBuilder())\n{\n return commandBuilder.QuoteIdentifier(name);\n}\n</code></pre>\n<p>I'm pretty sure the <code>Oracle</code> provider has it too (when you install its NuGet package). You should use these instead of inventing your own.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T17:16:28.823", "Id": "222536", "ParentId": "222492", "Score": "5" } } ]
{ "AcceptedAnswerId": "222535", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T22:03:30.553", "Id": "222492", "Score": "2", "Tags": [ "c#", "t-sql", "extension-methods", "oracle" ], "Title": "Build WHERE clause for search conditions" }
222492
<p>With the following interface in mind</p> <pre><code>EasyRandom&lt;unsigned int&gt; prng(a, b); auto x = prng(); // scalar auto v = prng(10); // vector </code></pre> <p>I wrote the following class:</p> <pre><code>// https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution template &lt;typename T = unsigned int&gt; class EasyRandom { private: std::random_device rd; std::unique_ptr&lt;std::mt19937&gt; gen; std::unique_ptr&lt;std::uniform_int_distribution&lt;T&gt;&gt; dist; public: EasyRandom(T a, T b) { gen = std::make_unique&lt;std::mt19937&gt;(rd()); dist = std::make_unique&lt;std::uniform_int_distribution&lt;T&gt;&gt;(a, b); } T operator()() { return (*dist)(*gen); } std::vector&lt;T&gt; operator()(size_t n) { std::vector&lt;T&gt; v; for (; n &gt; 0; v.push_back(operator()()), --n); return v; } }; </code></pre> <p>I also have a few specific questions:</p> <ol> <li>Is there a way to instantiate <code>EasyRandom</code> without the use of pointers?</li> <li>Is it possible to change <code>operator()(size_t n)</code> to return any user-specified <a href="https://en.cppreference.com/w/cpp/named_req/SequenceContainer" rel="nofollow noreferrer">SequenceContainer</a> (e.g. vector, list, deque) instead of hard-coding it to a particular implementation (e.g. <code>std::vector</code>)?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T07:57:53.633", "Id": "430686", "Score": "0", "body": "As **@1201ProgramAlarm** already pointed out the second part of your question is off-topic and could lead to your entire question being closed. Please revise your question if you want to prevent this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T10:55:14.030", "Id": "430717", "Score": "1", "body": "Adding a non-working implementation does not make the question on topic for Code Review. We require the code be working. For more information, see the [help/on-topic]. I have rolled back the edit you made to avoid incurring closevotes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T19:31:10.397", "Id": "430967", "Score": "1", "body": "Some notes on what you've got so far: 1. Keeping the instance of `std::random_device` that you use only once wastes space. 2. Instantiating one `std::unique_ptr<std::mt19937>` per distribution wastes **a lot** of space and makes creating distributions really slow. You typically want exactly one generator per thread that is generating random numbers, so make the generator `[static] thread_local`." } ]
[ { "body": "<p><code>gen</code> and <code>dist</code> don't need to be pointers. Just declare them as members, and use the member initializer list in the constructor to initialize them.</p>\n\n<pre><code>std::random_device rd;\nstd::mt19937 gen;\nstd::uniform_int_distribution&lt;T&gt; dist;\n\nEasyRandom(T a, T b): gen(rd()), dist(a, b) {\n}\n</code></pre>\n\n<p>In the <code>operator()</code> that returns a vector, you can reserve space for the vector to avoid memory reallocations during the insertions (<code>v.reserve(n)</code>). While not an issue with ints, if you use <code>emplace_back</code> rather than <code>push_back</code> that can avoid potential extra copies of a value for non-simple types.</p>\n\n<p>The second question is off topic (code not implemented).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T05:28:16.653", "Id": "430665", "Score": "0", "body": "Added implementation for second question. Thank you for your feedback so far." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T05:02:08.387", "Id": "222500", "ParentId": "222495", "Score": "3" } } ]
{ "AcceptedAnswerId": "222500", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T01:22:38.767", "Id": "222495", "Score": "4", "Tags": [ "c++", "random", "template", "wrapper" ], "Title": "C++ wrapper around uniform mt19937 SequenceContainer" }
222495
<p>Here is the working code for my Spring service:</p> <pre><code>@Service public class UploadService { @Inject @Qualifier("session") Session session; @Inject AsyncImageConvertService asyncImageConvertService; @Value("${aws.bucket-name}") String awsBucketName; @Inject AmazonS3 amazonS3; @Inject ImageMapper imageMapper; @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED) public void uploadImage(Image image, String url, Runnable fnSaveObject) { File file = new File(System.getProperty("java.io.tmpdir"), image.getUrl()); image.setUrl(url); image.setCreator(session.getUser()); PutObjectRequest request = new PutObjectRequest(awsBucketName, image.getUrl(), file); request.setCannedAcl(CannedAccessControlList.PublicRead); amazonS3.putObject(request); TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { public void afterCommit() { // Database has a newly inserted (and committed) image data here. asynceImageConvertService will select and update it. // fnSaveObject function should run in current transaction. asyncImageConvertService.processImage(image.getId(), file); } }); imageMapper.insert(image); // image's id will be generated here. fnSaveObject.run(); // image's id should exists here. } } </code></pre> <p>It is called from the following code:</p> <pre><code>uploadService.uploadImage( profileImage, "/user/" + user.getId() + "/" + profileImage.getUrl(), () -&gt; userMapper.insertImage(user, profileImage) // generated image's id will be applied. ); </code></pre> <p>The <code>Runnable</code> functional interface will run in transaction and invoke async service method after transaction committed.</p> <p><code>*Mapper</code> is injected instance also, via spring-mybatis. </p> <p>This code looks like it's working well, but I'm afraid it's not safe.</p> <p>Is it safe to use functional interface arguments in methods of services injected via Spring?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T02:02:34.980", "Id": "222496", "Score": "3", "Tags": [ "java", "dependency-injection", "spring" ], "Title": "Using functional interface arguments in methods of services injected via Spring" }
222496
<p>I'm in the midst of re-learning python. My current effort is an implementation around prime factorization. I am attempting to reproduce something similar to the table found here (in binary): <a href="https://math.stackexchange.com/questions/586010/relative-size-of-most-factors-of-semiprimes-close">https://math.stackexchange.com/questions/586010/relative-size-of-most-factors-of-semiprimes-close</a></p> <p>Performance seems to be rather dreadful. I've looked at profiling of the code in cProfile but I don't see any obvious improvements.</p> <p>I'm considering: (a) Installing PyPy to see if that improves performance and (b) Leveraging Numpy further, although precisely how is a little vague to me. I'm working through the following to see if it can help: <a href="https://www.freecodecamp.org/news/if-you-have-slow-loops-in-python-you-can-fix-it-until-you-cant-3a39e03b6f35/" rel="nofollow noreferrer">https://www.freecodecamp.org/news/if-you-have-slow-loops-in-python-you-can-fix-it-until-you-cant-3a39e03b6f35/</a></p> <p>I've already refactored to eliminate the need for a list of semiprimes and that helped a bit, but I'm not sure if there are obvious inefficiencies that I'm not seeing.</p> <p>miller_rabin.py is not mine. I include it here for completeness. My effort centers on the performance of prime_stats_bin.py. I recognize that primality testing is going to be a large component of the cost, I'm just not understanding why I can't even get to 32 bits within a reasonable amount of time. I'm running this on a 5 year old Windows 10 laptop (Core i5, 2.5GHz, 8GB RAM), under Python 3.7.3 (installed yesterday).</p> <p>Any comments would be appreciated.</p> <p>As for the goal of this effort, I'd like to know whether its reasonable to expect output for primes up to 32 bits from this program within a day. </p> <p>With 32 bits in the prime expansion, the list of primes I generate is about 2xe^8 which given my 32 bit installation of Python, I'm not sure it will maintain.</p> <pre><b>prime_stats_bin.py</b></pre> <pre><code>import math import random import hashlib import numpy from miller_rabin import * from time import process_time time1 = process_time() iexp = 2 #init exponent poe = 2 #pieces of eight mexp = 8*poe #max exponent cexp = 2 #curr exponent primes = [2] #list of primes counts = [] #list of counts (num primes, num of semiprimes, num of close semiprimes) f = open("prime_stats_bin.txt", "w", encoding="utf-8") f.write("BinDigits\tPrimes\tSemiprimes\tClose semiPrimes\n") for x in range(iexp, mexp+1): #initialize lists for all exponents counts.append([1,1,1]) #since are loop looks only at odd primes, initialize with 1s in all counts for x in range(3, pow(2,mexp), 2): if numpy.log2(x) &gt;= cexp: #output to file when we pass a power of 2 f.write(str(cexp)+":\t"+str(counts[cexp-2][0])+"("+str(round((counts[cexp-2][0]*numpy.log(pow(2,cexp)))/pow(2,cexp),4))+")\t"+ str(counts[cexp-2][1])+" ("+str(round((counts[cexp-2][1]*numpy.log(pow(2,cexp)))/(pow(2,cexp)*numpy.log(numpy.log(pow(2,cexp)))),4))+")\t"+ str(counts[cexp-2][2])+" ("+str(round((counts[cexp-2][2]*numpy.log(pow(2,cexp)))/pow(2,cexp),4))+";"+str(round((100*counts[cexp-2][2])/counts[cexp-2][1],4))+")\n") if cexp%8==0: f.write('time elapsed: %f seconds'%(process_time()-time1)+"\n") cexp += 1 if is_prime(x): primes.append(x) for z in range(iexp, mexp+1): if x &lt;= pow(2,z): counts[z-2][0] += 1 #increment count of primes less than z taken to the power of 2 for y in primes: if y*x &gt; pow(2,mexp): #only need to worry about semiprimes that are less than our upper bound break for w in range(iexp, mexp+1): if y*x &lt;= pow(2,w): counts[w-2][1] += 1 #increment count of semiprimes less than w taken to the power of 2 if x &lt;= pow(y,2): counts[w-2][2] += 1 #increment count of close (p*q=N, where p&lt;q and q&lt;=p^2) semiprimes less than w taken to the power of 2 f.write(str(mexp)+":\t"+str(counts[mexp-2][0])+"("+str(round((counts[mexp-2][0]*numpy.log(pow(2,mexp)))/pow(2,mexp),4))+")\t"+ str(counts[mexp-2][1])+" ("+str(round((counts[mexp-2][1]*numpy.log(pow(2,mexp-1)))/(pow(2,mexp)*numpy.log(numpy.log(pow(2,mexp)))),4))+")\t"+ str(counts[mexp-2][2])+" ("+str(round((counts[mexp-2][2]*numpy.log(pow(2,mexp-1)))/pow(2,mexp),4))+";"+str(round((100*counts[mexp-2][2])/counts[mexp-2][1],4))+")\n") f.write('time elapsed: %f seconds'%(process_time()-time1)+"\n") f.close </code></pre> <pre><b>miller_rabin.py</b></pre> <pre><code>def _try_composite(a, d, n, s): if pow(a, d, n) == 1: return False for i in range(s): if pow(a, 2**i * d, n) == n-1: return False return True # n is definitely composite def is_prime(n, _precision_for_huge_n=16): if n in _known_primes: return True if any((n % p) == 0 for p in _known_primes) or n in (0, 1): return False d, s = n - 1, 0 while not d % 2: d, s = d &gt;&gt; 1, s + 1 # Returns exact according to http://primes.utm.edu/prove/prove2_3.html if n &lt; 1373653: return not any(_try_composite(a, d, n, s) for a in (2, 3)) if n &lt; 25326001: return not any(_try_composite(a, d, n, s) for a in (2, 3, 5)) if n &lt; 118670087467: if n == 3215031751: return False return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7)) if n &lt; 2152302898747: return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11)) if n &lt; 3474749660383: return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11, 13)) if n &lt; 341550071728321: return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11, 13, 17)) # otherwise return not any(_try_composite(a, d, n, s) for a in _known_primes[:_precision_for_huge_n]) _known_primes = [2, 3] _known_primes += [x for x in range(5, 1000, 2) if is_prime(x)] </code></pre> <pre><b>output and timing</b></pre> <pre><code>BinDigits Primes Semiprimes Close semiPrimes 2: 2(0.6931) 1 (1.061) 1 (0.3466;100.0) 3: 4(1.0397) 2 (0.7101) 2 (0.5199;100.0) 4: 6(1.0397) 6 (1.0196) 4 (0.6931;66.6667) 5: 11(1.1913) 10 (0.8714) 6 (0.6498;60.0) 6: 18(1.1697) 22 (1.0031) 9 (0.5848;40.9091) 7: 31(1.1751) 42 (1.008) 17 (0.6444;40.4762) 8: 54(1.1697) 82 (1.0369) 28 (0.6065;34.1463) time elapsed: 0.140625 seconds 9: 97(1.1819) 157 (1.0449) 47 (0.5727;29.9363) 10: 172(1.1643) 304 (1.0629) 89 (0.6024;29.2763) 11: 309(1.1504) 589 (1.0795) 171 (0.6366;29.0323) 12: 564(1.1453) 1124 (1.0775) 311 (0.6315;27.669) 13: 1028(1.1308) 2186 (1.0937) 584 (0.6424;26.7155) 14: 1900(1.1253) 4192 (1.0926) 1086 (0.6432;25.9065) 15: 3512(1.1143) 8110 (1.099) 2093 (0.6641;25.8076) 16: 6542(1.1071) 15658 (1.1013) 4023 (0.6808;25.6929) time elapsed: 27.906250 seconds 17: 12251(1.1014) 30253 (1.1026) 7617 (0.6848;25.1777) 18: 23000(1.0947) 58546 (1.1041) 14597 (0.6947;24.9325) 19: 43390(1.0899) 113307 (1.1041) 27817 (0.6987;24.5501) 20: 82025(1.0844) 219759 (1.105) 53301 (0.7047;24.2543) 21: 155611(1.0801) 426180 (1.1046) 101532 (0.7047;23.8237) 22: 295947(1.076) 827702 (1.1045) 195376 (0.7103;23.6046) 24: 1077871(1.0688) 3129211 (1.1036) 721504 (0.7154;23.0571) time elapsed: 292.140625 seconds </code></pre> <pre><b>Update: 6/22/2019</b></pre> <p>Many iterations later...</p> <ul> <li>Found that my initial code wouldn't operate beyond 2^27 due to memory limitations so I installed Python 64 bit</li> <li>With Python 64 bit, I still encountered that my code aborted due to memory limitations between 2^30 and 2^31</li> <li>I jettisoned the Miller_Rabin as it was counterproductive since I was already calculating primes, replacing it with a Sieve of Eratosthenes</li> </ul> <p>At this point, getting this thing to run up to 2**32 was a matter of pride</p> <p>I found that trying to keep 200M primes in memory @8 bytes per prime was leading to interminable delay as it was swapped to disk</p> <p>Tried a bitstring solution which didn't function as maintaining a 2**32 bit long int didn't perform</p> <p>Finally, resolved to use a segmented bitstring within a list to minimize the memory footprint while simultaneously limiting the length of the bit shifts that would be entailed</p> <p><b>Success!</b> </p> <p>While it takes 8 hours to run on my machine, I can count precisely the number of close semiprimes less than or equal to 2^32.</p> <p>With respect to the good suggestions I received, I have:</p> <ul> <li>implemented black formatting</li> <li>used f-string formatting of output</li> <li>refactored code to create functions, making the code more understandable</li> <li>modified my code import strategy, eliminated unused module and making clear the source of the functions I was leveraging</li> </ul> <p>@TODO:</p> <ul> <li>typing</li> <li>investigate Sieve of Atkin</li> </ul> <p>Feel free to make whatever additional comments you see fit.</p> <p>Thanks. Updated code below.</p> <pre><b>primes_bit.py</b></pre> <pre><code>from time import process_time from math import sqrt from math import floor from math import ceil from numpy import log2 from numpy import log time1 = process_time() # initialize list of bitstring segments as all '1's [TRUE] def init_prime_bits(): for n in range(limit // num_per_segment): prime_bits.append(2 ** bit_per_segment - 1) # populate list of prime bitstrings up to [limit] def pop_prime_bits(): print(f"limit: {limit}") for x in range(3, sub_limit, 2): segmnt = x // num_per_segment locatn = x % num_per_segment // 2 if not (prime_bits[segmnt] &gt;&gt; locatn &amp; 1): continue for y in range(x * x, limit, x * 2): segmnt = y // num_per_segment locatn = y % num_per_segment // 2 prime_bits[segmnt] &amp;= ~(1 &lt;&lt; locatn) print(f"List of bitstring primes up to 2**{power_of_two} generated") print(f"time elapsed: {process_time()-time1:.6f} seconds") # initialize list of prime counts to '0' for each power of two being calculated # 3 registers included: num of primes, num of semiprimes, num of close semiprimes def init_prime_cnts(): for p in range(power_of_two): prime_cnts.append([0, 0, 0]) def output_header(): digits_hdr = "Limit(Bin)" primes_hdr = "Primes" sprimes_hdr = "Semiprimes" close_sprimes_hdr = "Close semiprimes" print(f"{digits_hdr:^10}{primes_hdr:^20}{sprimes_hdr:^20}{close_sprimes_hdr:^20}") def output_body(idx): digits = idx + 2 # count of primes &lt;= 2**digits primes = prime_cnts[idx][0] # how close is (primes) to estimate prime_est = (primes * log(2 ** digits)) / 2 ** digits # count of semiprimes &lt;= 2**digits sprimes = prime_cnts[idx][1] # how close is (sprimes) to estimate sprime_est = (sprimes * log(2 ** digits)) / (2 ** digits * log(log(2 ** digits))) # count of close semiprimes close_sprimes = prime_cnts[idx][2] # how close is (close_sprimes) to estimate -- #1 csprimes_est1 = (close_sprimes * log(2 ** digits)) / 2 ** digits # how close is (close_sprimes) to estimate -- #2 csprimes_est2 = 0 if sprimes == 0 else (100 * close_sprimes) / sprimes print( f"{digits:&gt;10}{primes:&gt;10} ({prime_est:.4f}){sprimes:&gt;10} ({sprime_est:.4f}){close_sprimes:&gt;10} ({csprimes_est1:.4f}; {csprimes_est2:.4f})" ) prime_cnts[idx + 1][0] += prime_cnts[idx][0] prime_cnts[idx + 1][1] += prime_cnts[idx][1] prime_cnts[idx + 1][2] += prime_cnts[idx][2] if digits % 8 == 0: print(f"time elapsed: {process_time()-time1:.6f} seconds") def outer_loop(): for n in range(0, limit, 2): segmnt = n // num_per_segment locatn = n % num_per_segment // 2 if n % num_per_segment == 0: outer_loop_primes = format( prime_bits[segmnt], "0" + str(bit_per_segment) + "b" )[::-1] if int(outer_loop_primes[locatn]): outer_loop_num = n + 1 # this code implements a trick which labels the first bit in the bitstring, '1', # as a prime and treats it for the purposes of the loops as '2' if outer_loop_num == 1: outer_loop_num = 2 outer_loop_idx = int(log2(outer_loop_num)) - 1 prime_cnts[outer_loop_idx][0] += 1 inner_loop(n, outer_loop_num, outer_loop_primes) # print results when the power of two advances -- starting with 2 bits if n != 0 and ceil(log2(n + 2)) == floor(log2(n + 2)): output_body(int(log2(n + 2)) - 2) def inner_loop(idx, o_loop_num, inner_loop_primes): for p in range(idx, limit, 2): segmnt_innr = p // num_per_segment locatn_innr = p % num_per_segment // 2 if p % num_per_segment == 0: inner_loop_primes = format( prime_bits[segmnt_innr], "0" + str(bit_per_segment) + "b" )[::-1] if int(inner_loop_primes[locatn_innr]): inner_loop_num = p + 1 # same trick as above, applied to the inner loop if inner_loop_num == 1: inner_loop_num = 2 inner_loop_prd = o_loop_num * inner_loop_num if inner_loop_prd &gt; limit: break inner_loop_idx = int(log2(inner_loop_prd)) - 1 prime_cnts[inner_loop_idx][1] += 1 if inner_loop_num &lt;= o_loop_num ** 2: prime_cnts[inner_loop_idx][2] += 1 def main(): init_prime_bits() pop_prime_bits() output_header() init_prime_cnts() outer_loop() print(f"time elapsed: {process_time()-time1:.6f} seconds") # limit is restricted to a power of 2 power_of_two = 32 limit = 2 ** power_of_two sub_limit = int(limit ** 0.5) # bitstring segment length within the list is a power of 2 bit_per_segment = 2 ** 7 # numbers per bitstring segment are doubled as we only store odd numbers num_per_segment = (bit_per_segment) * 2 # list of bitstring segments to maintain prime flags prime_bits = [] # list of counts of primes by powers of two prime_cnts = [] if __name__ == "__main__": main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T02:19:57.663", "Id": "430655", "Score": "0", "body": "Change poe to 3 to see what I'm currently limited to. poe of 4 is what I'm attempting to get to." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-22T19:39:31.367", "Id": "431373", "Score": "0", "body": "I tested this varying the bit_per_segment value and came to the conclusion that, even though it has a wide and shallow trough, 2**7 seems to offer me the best results from a performance perspective (e.g. shortest total execution time)" } ]
[ { "body": "<p>Some suggestions related to <em>review</em> performance:</p>\n\n<ul>\n<li>This code is really hard to read. As far as I can tell every single variable except for <code>primes</code> is abbreviated to the point where I need to hold the entire program in memory in order to reason about any part of it. Naming is <em>really</em> important for readability, and readability is really important for comprehensibility. <a href=\"https://en.wikiquote.org/wiki/Brian_Kernighan\" rel=\"noreferrer\">Relevant quote</a>:\n\n<blockquote>\n <p>Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?</p>\n</blockquote></li>\n<li>Pulling out functions should also make the code much easier to understand. I would recommend adding <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"noreferrer\">type hints</a> and validating them using a strict <a href=\"https://github.com/python/mypy\" rel=\"noreferrer\"><code>mypy</code></a> configuration</li>\n<li><a href=\"https://github.com/ambv/black\" rel=\"noreferrer\"><code>black</code></a> can format your code to be much more idiomatic.</li>\n<li><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"noreferrer\"><code>flake8</code></a> can give you some hints about writing idiomatic Python.</li>\n<li>There are at least three unused imports.</li>\n<li>I would recommend avoiding <code>import *</code> in general; in a dynamic language like Python it's harder to reason about the code in that case, and it's easier to run into naming conflicts.</li>\n</ul>\n\n<p>Performance-related suggestions:</p>\n\n<ul>\n<li>It looks like <code>mexp</code> is only set once, but <code>pow(2,mexp)</code> is calculated in a bunch of places. This can be calculated once outside both loops. There are other duplicate calculations - they should all be run only once, and in the outermost context.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T05:47:34.407", "Id": "430666", "Score": "1", "body": "That answer might be worth a bounty just for the quote on debugging ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-22T19:40:27.313", "Id": "431374", "Score": "0", "body": "Unfortunately, I don't yet have a reputation that will allow me to grant a bounty." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-23T06:21:14.870", "Id": "431404", "Score": "0", "body": "XD No worries @WolfLarson" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T04:28:46.520", "Id": "222498", "ParentId": "222497", "Score": "13" } }, { "body": "<blockquote>\n <p>My current effort is an implementation around prime factorization. I am attempting to reproduce something similar to the table found here</p>\n</blockquote>\n\n<p>Prime factorisation is the wrong approach to build that table. The efficient way to build it is to generate a list of primes using a sieve of some kind (a good implementation of Eratosthenes is definitely good enough up to 24 bits, but for 32 bits you might want to think about Atkins-Bernstein, and for 64 bits I would definitely prefer Atkins-Bernstein).</p>\n\n<p>Then with the list of primes you can generate a list of semiprimes with a double-loop (making sure to break early from the inner loop when you pass the threshold!) There are about 600 million 32-bit semiprimes, so this should meet your performance requirements.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> f.write(str(cexp)+\":\\t\"+str(counts[cexp-2][0])+\"(\"+str(round((counts[cexp-2][0]*numpy.log(pow(2,cexp)))/pow(2,cexp),4))+\")\\t\"+\n str(counts[cexp-2][1])+\" (\"+str(round((counts[cexp-2][1]*numpy.log(pow(2,cexp)))/(pow(2,cexp)*numpy.log(numpy.log(pow(2,cexp)))),4))+\")\\t\"+\n str(counts[cexp-2][2])+\" (\"+str(round((counts[cexp-2][2]*numpy.log(pow(2,cexp)))/pow(2,cexp),4))+\";\"+str(round((100*counts[cexp-2][2])/counts[cexp-2][1],4))+\")\\n\")\n</code></pre>\n</blockquote>\n\n<p>That is frankly illegible. Pull out some variables for the calculations, and then look at <a href=\"//www.python.org/dev/peps/pep-0498/\" rel=\"noreferrer\">f strings</a>. And rather than copy-pasting it, define a function to compose the string.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> for z in range(iexp, mexp+1):\n if x &lt;= pow(2,z):\n counts[z-2][0] += 1 #increment count of primes less than z taken to the power of 2\n</code></pre>\n</blockquote>\n\n<p>This probably isn't a major bottleneck, but it's still inefficient. If you maintain a count of how many integers in the ranges <code>[a, b), [b, c), [c, d)</code> etc. have property P then you can produce the counts for integers in the ranges <code>[a, b), [a, c), [a, d)</code> with the property P with just two additions when you output the tables, rather than two additions <em>for each</em> such integer in <code>[a, b)</code> and one for each in <code>[b, c)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T08:51:55.427", "Id": "222511", "ParentId": "222497", "Score": "7" } } ]
{ "AcceptedAnswerId": "222498", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T02:18:08.347", "Id": "222497", "Score": "9", "Tags": [ "python", "performance", "primes" ], "Title": "Primes and SemiPrimes in Binary" }
222497
<p>A couple of weeks ago I started a little project, I was learning Node/Express/Mongo and I though it was a good idea to start building some app so at least I could refresh my basic React knowledge.</p> <p>The app is just something to keep track of your weight, something not too complicated. You can tell that the main/only Component was <code>Weightlogger.jsx</code> until not that long ago.</p> <p>Is it time to migrate state to one component or time to learn Redux/Context?</p> <pre class="lang-html prettyprint-override"><code>import React from 'react'; import './WeightLogger.css' import axios from 'axios' import TimeAgo from 'timeago-react' import { auth } from './Login.jsx' class WeightLogger extends React.Component { constructor(props){ super(props) this.state = { weight: "", weightLog: [] } this.changeHandle = this.changeHandle.bind(this) this.submitHandle = this.submitHandle.bind(this) } componentDidMount(){ if (auth) axios.get('http://localhost:5000/api/users/weights', { headers: { 'x-auth-token': auth } }) .then(res=&gt;{ this.setState({weightLog:res.data}) } ) .catch(err =&gt; console.log(err)) } changeHandle(event){ this.setState({weight: event.target.value}) } submitHandle(event){ axios.post('http://localhost:5000/api/users/weights', {"weight":this.state.weight.toString()}, { headers: { 'x-auth-token': auth } }) .then(res=&gt;{ this.setState({weightLog:res.data})}) event.preventDefault() } render(){ return ( &lt;div&gt; &lt;WeightLogDisplay weightLog={this.state.weightLog} unit="kg" /&gt; &lt;WeightOutput weightObj={this.state.weightLog[this.state.weightLog.length - 1]}/&gt; &lt;WeightInput changeHandle={this.changeHandle} weight={this.state.weight} submit={this.submitHandle}/&gt; &lt;/div&gt; ) } } const WeightOutput = ({weightObj})=&gt;{ return (&lt;h1&gt;Your current weight is...{weightObj ? weightObj.weight : null}&lt;/h1&gt; )} const WeightLogDisplay = ({weightLog, unit})=&gt;{ const weightList = weightLog.map(weightObject =&gt; { const date = new Date(weightObject.date) const day = date.getDay(), month = date.getMonth(), year = date.getFullYear() const hours = date.getHours(), minutes = date.getMinutes(); return (&lt;div className="weightAndTime"&gt; &lt;div className="weightBlock"&gt; {weightObject.weight}&lt;span className="units"&gt;{unit}s.&lt;/span&gt; &lt;/div&gt; &lt;div className="timeBlock"&gt; &lt;span className="time"&gt;{day}/{month}/{year} - {hours}:{minutes}&lt;/span&gt; &lt;div&gt;&lt;TimeAgo datetime={weightObject.date} style={{color:"silver"}}/&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;)}) return &lt;div className="WeightLogDisplay"&gt;{weightList}&lt;/div&gt; } const WeightInput =({changeHandle, weight, submit})=&gt; { return ( &lt;form onSubmit={submit}&gt; &lt;input onChange={changeHandle} value={weight}/&gt; &lt;/form&gt; )} export default WeightLogger </code></pre> <p>Then I learned on the node course how to organise data so I wanted to make a multi user app with logins etc. I learnt the basics of react-router so I could protect <code>WeightLogger</code> from people not logged in.</p> <p>(I know you can do that without react-router but I though it was a good excuse to learn a bit of it)</p> <pre class="lang-html prettyprint-override"><code>import './App.css'; import { BrowserRouter as Router, Route, Link, Redirect } from 'react-router-dom' import React from 'react'; import axios from 'axios'; import { auth } from './components/Login.jsx' import WeightLogger from './components/WeightLogger.jsx'; import { Login } from './components/Login.jsx' function App() { return ( &lt;Router&gt; &lt;div className="App"&gt; {/* &lt;WeightLogger/&gt; */} &lt;ul&gt; &lt;li&gt;&lt;Link to="/public"&gt;Public Page&lt;/Link&gt;&lt;/li&gt; &lt;li&gt;&lt;Link to="/protected"&gt;Protected Page&lt;/Link&gt;&lt;/li&gt; &lt;li&gt;&lt;Link to="/testing"&gt;Testing Page&lt;/Link&gt;&lt;/li&gt; &lt;/ul&gt; &lt;Route path="/public" component={Public}/&gt; &lt;Route path="/login" component={Login}/&gt; &lt;Route path="/register" component={Register}/&gt; &lt;PrivateRoute path="/protected" component={WeightLogger} /&gt; {/* &lt;PrivateRoute path="/testing" component={Testing} color="red"/&gt; */} &lt;/div&gt; &lt;/Router&gt; ); } const Public = () =&gt; &lt;h3&gt;Public&lt;/h3&gt; // const Testing = ({color}) =&gt; &lt;h3&gt;testing Here {color} &lt;/h3&gt; const PrivateRoute = ({ component: Component, ...rest }) =&gt; ( &lt;Route {...rest} render={(props)=&gt; ( (auth) ? &lt;Component {...props}{...rest} /&gt; : &lt;Redirect to='/login' /&gt; )} /&gt; ) export default App </code></pre> <p>I <strong>assumed</strong> the <code>Login</code> component had to do post requests, so I supposed it had to be a component with state.</p> <p>Then I realised that the <code>Registration</code> component is going the same way... but then I remember that it is not a good idea to have too many different states running in the app.</p> <p>So my question is, <strong>should I move the states to a main Component... maybe App.js and make the others components functional?</strong> I was going to start doing that, but I did not even know how to start. Or maybe it is about time to learn something like Redux or the Context API?</p> <p>If you are curious to look at the app, it is <a href="https://github.com/josepagan/weight-logger" rel="nofollow noreferrer">here</a> and the server in case you are extra curious is <a href="https://github.com/josepagan/weight-logger-server" rel="nofollow noreferrer">here</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T08:40:50.310", "Id": "430695", "Score": "0", "body": "Welcome to Code Review! Your question title has already been shortened, but I would recommend to have a look at [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask): *State what your code does in your title, not your main concerns about it. Be descriptive and interesting, and you'll attract more views to your question.* The concept of your app sounds way more interesting than what the current title lets readers expect." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-23T09:47:49.833", "Id": "435953", "Score": "0", "body": "Doing requests is not state. Move state up if multiple children require access to it. Allow them to access/modify the shared state by providing callbacks through props. You definitely don't need redux here. Check out the React hooks API for modern examples of React state, context, and reducer. For this project, that's all you probably need. https://reactjs.org/docs/hooks-reference.html" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T07:19:36.127", "Id": "222503", "Score": "0", "Tags": [ "javascript", "beginner", "react.js" ], "Title": "Weight-tracking app" }
222503
<p>I'm trying to organize my gallery, and I have certain folders rife with copies.</p> <p>My daily work is mostly javascript and php, being your generic web developer. However I took this as an opportunity to bodge something in python, a language I normally do not use, but have always wanted to pick up at least a little bit. You easily bodge things in it - just open a file and write shit, and evidently has absolutely marvellous standard library for my purposes here (heavy, weird filesystem operations).</p> <p>Anyway, just for reference, a lot of what I'm trying to do overlaps with this (how I found this site in the first place): <a href="https://codereview.stackexchange.com/questions/27652/replacing-duplicate-files-with-hard-links?newreg=f1e63a6fefb649b39f849a19783199f3">Replacing duplicate files with hard links</a> but I do a lot of my own things.</p> <p>There's 2 goals here:</p> <ol> <li>Build a set of tools/functions to easily let me organize shit.</li> <li>In this specific case, dedupe the files in a specific directory by making them hardlinks to a different source directory.</li> </ol> <p>Code is below:</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/python3 import sys import zlib import os import hashlib import imghdr ''' 1. Make file things 2. Build cross-reference tables. 3. Take all the matching hashes from the source and target. if hashes match, check if hardlink between source and target if not hardlink, make hardlink TODO?: Can use WSL/bash to do a reliable file type check - using the file command. ''' source_dir = r'C:\!The Gallery' target_dir = r'C:\Games\PnP DnD' only_these_extensions = ['jpg', 'png', 'gif', 'jpeg', 'bmp', 'tif', 'tiff', 'webp'] # Define a main() function that prints a little greeting. def main(): print('Finding files: ', end='') source_files = get_dir_contents(source_dir, extensions=only_these_extensions) target_files = get_dir_contents(target_dir, extensions=only_these_extensions) print('Done') print('Collected ' + str(len(target_files) + len(source_files)) + ' files.') file_things = make_file_things(target_files + source_files) (hash_table, node_table, name_table) = build_tables(file_things) print(len(hash_table)) print(len(node_table)) print(len(name_table)) # Hardlink from target to source for thing in file_things: # Take all the target files if os.path.commonpath([target_dir, os.path.split(thing.fpath)[0]]) == target_dir: target_thing = thing if len(hash_table[thing.fhash]) &gt; 1: # Get all hash matches that matched more than one file. for hash_matched_thing in hash_table[thing.fhash]: # Get any matches in the source dir. if os.path.commonpath([source_dir, os.path.split(hash_matched_thing.fpath)[0]]) == source_dir: source_thing = hash_matched_thing # Unlink target and link from source os.unlink(target_thing.fpath) os.link(source_thing.fpath, target_thing.fpath) return def make_file_things(file_paths): file_things = [] for file_path in file_paths: progress('Reading files', len(file_things), len(file_paths), 1) with open(file_path, "rb") as file: content = file.read() digest = crc32(content) file_things.append(file_thing(file_path, os.stat(file_path), digest)) return file_things def build_tables(files): hash_table = {} node_table = {} name_table = {} print('Building reference tables:', end='') # i = 0 for file in files: # progress('Building tables', i, len(files), 25) # i = i + 1 hashy = file.fhash inode = file.fstat.st_ino name = os.path.split(file.fpath)[1] if hashy in hash_table: hash_table[hashy] = file else: hash_table[hashy] = [file] if inode in node_table: node_table[inode] = file else: node_table[inode] = [file] if name in name_table: name_table[name] = file else: name_table[name] = [file] print(' Done!') return (hash_table, node_table, name_table) ################################################# # Helpers ################################################# class file_thing: fpath = '' fstat = 0 fhash = 0 def __init__(self, fpath, fstat, fhash): self.fstat = fstat self.fpath = fpath self.fhash = fhash def __str__(self): return str([self.fpath, self.fhash, self.fstat]) def __repr__(self): return str([self.fpath, self.fhash, self.fstat]) def enum_hardlinks(dupe_files): # Expects all files given to be duplicates hardlink_sets = {} for dupe in dupe_files: file_index = os.stat(dupe).st_ino # Inode on unix, file index on windows. if file_index in hardlink_sets: hardlink_sets[file_index].append(dupe) else: hardlink_sets[file_index] = [dupe] return hardlink_sets # The old version, before I knew about st_ino def enum_hardlinks2(dupe_files): # Expects all files given to be duplicates hardlink_sets = [] for dupe in dupe_files: done = False hardlink_num = os.stat(dupe).st_nlink if (hardlink_num &gt; 1): for hl_set in hardlink_sets: if (os.path.samefile(hl_set[0], dupe)): hl_set.append(dupe) done = True break if (not done): hardlink_sets.append([dupe]) return hardlink_sets def get_dir_contents(dir, root=None, extensions=None, follow_symlinks=True): def link_check(path): return not os.path.islink(path) or (os.path.islink(path) and follow_symlinks) try: extensions = [ext.lower() for ext in extensions] except TypeError: pass result = [] allfiles = os.listdir(dir) # num = len(allfiles) for obj in allfiles: if (root is None): fullpath = dir + '\\' + obj if (os.path.isfile(fullpath) and link_check(fullpath)): ext = get_ext(fullpath) if (extensions is None or ext in extensions): result.append(fullpath) elif (os.path.isdir(fullpath) and link_check(fullpath)): result.extend(get_dir_contents(fullpath, root, extensions, follow_symlinks)) else: # TODO: Following symlinks outside the root here can get nasty. Need to handle. relpath = dir[len(root)+1:] + '\\' + obj fullpath = root + '\\' + relpath if (os.path.isfile(fullpath) and link_check(fullpath)): ext = get_ext(fullpath) if (extensions is None or ext in extensions): result.append(relpath[1:]) elif (os.path.isdir(fullpath) and link_check(fullpath)): result.extend(get_dir_contents(fullpath, root, extensions, follow_symlinks)) return result def enum_extensions(files, exclude_extensions=None): ext_set = set() for file in files: ext = get_ext(file) if (exclude_extensions is None or ext not in exclude_extensions): ext_set.add(ext) return ext_set def group_by_extension(files, exclude_extensions=None): ext_dict = {} for file in files: ext = get_ext(file) if (exclude_extensions is None or ext not in exclude_extensions): if (ext in ext_dict): ext_dict[ext].append(file) else: ext_dict[ext] = [file] return ext_dict # Fails in ~8% of cases. Meh. def unreliable_filetype_check(files): type_dict = {} mismatches = [] for file in files: ext = get_ext(file) img_type = imghdr.what(file) if (ext == 'jpg'): ext = 'jpeg' if (ext == 'tif'): ext = 'tiff' if (img_type is not None and ext != img_type): mismatches.append(file) print(ext + ' vs ' + img_type) if (img_type in type_dict): type_dict[img_type].append(file) else: type_dict[img_type] = [file] print(str(len(type_dict[None])) + ' images whose type could not be determined.') print(type_dict[None]) return mismatches def crc32(data): return hex(zlib.crc32(data) &amp; 0xffffffff) def sha265(data): return hashlib.sha256(data).hexdigest() def get_ext(file): return os.path.splitext(file)[1][1:].lower() ''' The point is to only print when we are very close to a value we want. But we can't guarantee equality, so we have to use some kind of range around which we trigger the print. The upper bound for this range is 1/total, half below and half above our real value. There's edge cases where we end up with 2 consecutive values within our range, but those are rare. Basically on odd numbered items, around 50%, when we have enough precision to accurately represent both ends of the range. ''' def progress(prefix, current, total, step=1): temp = current / total * (100/step) delta = 1 / total * (50/step) # Half above and below each target value, for a total range of 1/total if abs(temp - round(temp)) &gt; delta and current != total-1: return temp = temp*step # Mult by step again to get back to a scale of 100 # Random edge case where both the nearest below and above values end up in our target range if (round(temp) == 50 and temp - round(temp) &lt; 0): return if env == 'sub': if current == 0: print(prefix + ': ' + '{:2.0f}'.format(temp) + '%', end='') elif current == (total-1): print(' ' + '{:2.0f}'.format(temp) + '%') else: print(' ' + '{:2.0f}'.format(temp) + '%', end='') sys.stdout.flush() elif env == 'cli': if round(temp) &gt; progress: print('Processing: ' + '{:2.0f}'.format(temp) + '%', end='\r') progress = round(temp) # This is the standard boilerplate that calls the main() function. env = '' if __name__ == '__main__': if (sys.version_info[0] &lt; 3): raise Exception('Your frickin python version is so very WROOOOOOOONG') try: os.environ['PYTHONSUBLIMEBUILDSYSTEM'] #If this exists, we're in our custom build sublime environment. Plz don't try to ask for input here. env = 'sub' except: env = 'cli' main() </code></pre> <p>What I'm looking for is: </p> <ul> <li><strong>advice on the general approach</strong> - e.g. the algorithm on line 41+ could probably use work (below the <code>Hardlink from target to source</code> comment). I wonder if I'm missing any considerations here.</li> <li><strong>performance</strong> - I think I can get away with crc32, which is fast. Def don't need cryptographically strong hashing tho. Also, any bit of performance is welcome - the size of the input is 120K items and 150GB in size, and it's only gonna grow.</li> <li><strong>organizing code</strong> - pretty new to python. This is maybe the third thing I've made that's more complex than 5 lines of code in python. Probably not gonna use it in any professional capacity any time soon, but any advice for "bodge projects" welcome.</li> <li><strong>libraries</strong> - finally, an alternative to <code>imghdr</code> would be welcome. Chokes on way too many images.</li> </ul> <p>Personal idiosyncrasies: I'm used to line lengths of 120 characters (inb4 someone says stick to 80).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-25T05:53:56.293", "Id": "431668", "Score": "0", "body": "Welcome to Code Review. I have rolled back your latest edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-25T06:00:32.313", "Id": "431669", "Score": "0", "body": "Ah, ok. I suppose that means I should to post a new question with the revised code...?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-25T06:06:27.813", "Id": "431670", "Score": "0", "body": "You can give this question a little bit more time as well. Here on Code Review answers usually take mor time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-25T06:09:26.537", "Id": "431671", "Score": "0", "body": "Cool. What is a reasonable time to wait before it's a good idea to post an updated version?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-25T06:10:42.247", "Id": "431672", "Score": "1", "body": "Give it one more week." } ]
[ { "body": "<p>I was interested in this as it's a cool idea. However the demeanor in your question and code makes me not want to review this.</p>\n\n<blockquote>\n <p>Your frickin python version is so very WROOOOOOOONG</p>\n</blockquote>\n\n<p>That's really mature.</p>\n\n<hr>\n\n<p><code>get_dir_contents</code> is just a verbose version of <code>os.walk</code>. What's worse is <code>root</code> is unused and bizarre. If you change <code>only_these_extensions</code> to start with a dot then you can also further simplify your code.</p>\n\n<pre><code>import os\nimport pathlib\nfrom typing import Set, Iterator\n\nonly_these_extensions = {'.jpg', '.png', '.gif', '.jpeg', '.bmp', '.tif', '.tiff', '.webp'}\n\n\ndef get_dir_contents(path: str,\n extensions: Set[str],\n followlinks: bool = True,\n ) -&gt; Iterator[pathlib.Path]:\n for dir_path, _, file_names in os.walk(path, followlinks=followlinks):\n dir_path = pathlib.Path(dir_path)\n for file_name in file_names:\n full_path = dir_path / file_name\n if full_path.suffix in extensions:\n yield full_path\n</code></pre>\n\n<p>After this I started looking at the rest of your code and I didn't get far until I saw <code>build_tables</code> which looks to have a massive bug. <code>node_table[inode] = file</code> should probably be <code>node_table[inode].append(file)</code>. And unhelpful classes called <code>file_thing</code>.</p>\n\n<p>Change your code to use <code>pathlib</code>, <code>os.path</code> and <a href=\"http://mypy-lang.org/\" rel=\"nofollow noreferrer\"><code>mypy</code></a>, remove all your useless <code>print</code>s and remove your \"I'm better than you\" demeanor and I'd give you a better followup review.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-25T05:44:58.780", "Id": "431665", "Score": "0", "body": "First, thanks for taking the time. But you have me thoroughly confused. <\"I'm better than you\" demeanor>? You will have to elaborate because I have no idea what you are referring to. Can't remove it if I don't know what to remove. If you're referring to that version comment - that is a comment to myself and no one else. I've removed it now. `pathlib` is quite the neat library, and thanks for that. I think for the couple of lines of elementary path manipulation, `os.path` is enough for now. Cont'd..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-25T05:45:20.563", "Id": "431666", "Score": "0", "body": "`mypy` is an interesting idea, but I don't think I have a use for it in this instance. It's a hassle to setup and it isn't worth it for these types of projects, where you're just prototying things. It's also additional syntax baggage who someone new at python doesn't need right now. Someone actually removed the `beginner` tag from the question, and I'm not sure why TBH. I really am a beginner on python. Onto code comments..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-25T05:45:48.570", "Id": "431667", "Score": "0", "body": "Thanks for pointing out `os.walk`. I remember I made `get_dir_contents` for a different script, just copied here, hence the unused `root`. `build_tables` -> valid bug, should be `.append()`. `file_thing` is named as such, because there are already enough identifiers named `file`, and I didn't want to overload the word any further. Renamed to `file_meta`, hopefully that makes it clearer. Finally, I have no idea what you mean by useless prints. I want some kind of feedback while the program is running. What else do you suggest?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-25T10:51:12.017", "Id": "431713", "Score": "0", "body": "@martixy Go over your comments and strings and remove any others that are just rude - like the example I gave. If you'd be embarrassed to say it to your mom, it's probably not a good idea to put it in your program. `mypy` would have found the `.append()` bug, this says to me that it's not _useless_. Yes it has a bit of a learning curve, but given that C, C# and Java all use static typing and beginners learn those I don't think `mypy` it not beginner friendly, you can even tell it to not type things if it's out of your depth." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-25T19:26:51.000", "Id": "431794", "Score": "0", "body": "Point to *any* other example. You failed to elaborate and keep getting hung up on that single line. And how would `mypy` help with that bug? I did try it. It detected nothing. As much as I appreciate bringing `mypy` to my attention, I choose to use vanilla python here. Someone pointed out that I shouldn't be editing the code, so the question remains as is. I did however rewrite `get_dir_contents` as you suggested, and fixed a couple of bugs, `append` included. Still looking for performance tips. The largest bottleneck is remains in the file read and hashing phase." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-25T20:58:59.123", "Id": "431800", "Score": "0", "body": "@martixy Post a new question. If you fully type your code mypy would find it." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T15:05:22.950", "Id": "222713", "ParentId": "222504", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T07:33:49.397", "Id": "222504", "Score": "3", "Tags": [ "python", "performance", "algorithm", "python-3.x", "file-system" ], "Title": "Deduping files using hardlinks" }
222504
<p>Here's my updated version of the problem I posted at <a href="https://codereview.stackexchange.com/questions/222072/calculating-time-windows-for-entities">Calculating time windows for entities</a>, adding in suggested changes as well as a change I did so that the Reflection is 'cached' in a ConcurrentDictionary and happens only once per Type.</p> <pre><code>using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; namespace Services.Helpers { #region Custom Attributes [AttributeUsage(AttributeTargets.Property)] public class DoNotCopyIntoTimeWindow : Attribute { } // leave default [AttributeUsage(AttributeTargets.Property)] public class IsProcessedIntoTimeWindow : Attribute { } // calculate time window for this property [AttributeUsage(AttributeTargets.Property)] public class IsTimeWindowDate : Attribute { } // attribute to mark property as the datetime [AttributeUsage(AttributeTargets.Property)] public class IsTimeWindowIdentifier : Attribute { } // this is the time window property #endregion public class TimeWindow { #region Structs public struct TimeWindowDictionary { public PropertyInfo PropertyInfo { get; set; } public Dictionary&lt;NullObject&lt;dynamic&gt;, int&gt; Dictionary { get; set; } } public struct NullObject&lt;T&gt; { [DefaultValue(true)] private readonly bool isnull; // default property initializers are not supported for structs private NullObject(T item, bool isnull) : this() { this.isnull = isnull; Item = item; } public NullObject(T item) : this(item, item == null) { } public static NullObject&lt;T&gt; Null() { return new NullObject&lt;T&gt;(); } public T Item { get; private set; } public bool IsNull() { return isnull; } public static implicit operator T(NullObject&lt;T&gt; nullObject) { return nullObject.Item; } public static implicit operator NullObject&lt;T&gt;(T item) { return new NullObject&lt;T&gt;(item); } public override string ToString() { return (Item != null) ? Item.ToString() : "NULL"; } public override bool Equals(object obj) { if (obj == null) return IsNull(); if (!(obj is NullObject&lt;T&gt;)) return false; var no = (NullObject&lt;T&gt;)obj; if (IsNull()) return no.IsNull(); if (no.IsNull()) return false; return Item.Equals(no.Item); } public override int GetHashCode() { if (IsNull()) return 0; var result = Item.GetHashCode(); if (result &gt;= 0) result++; return result; } } public struct Properties { public List&lt;PropertyInfo&gt; PropertiesToProcess { get; set; } public List&lt;PropertyInfo&gt; CopyProperties { get; set; } public PropertyInfo TimeWindowIdentifier { get; set; } public PropertyInfo DatePropertyInfo { get; set; } public int Size { get; set; } } #endregion #region Class Members private static readonly ConcurrentDictionary&lt;Type, Properties&gt; PropertiesDictionary = new ConcurrentDictionary&lt;Type, Properties&gt;(); #endregion #region Methods public static IEnumerable&lt;T&gt; CalculateTimeWindows&lt;T&gt;(DateTime dateFrom, DateTime dateTo, List&lt;T&gt; stateModels) where T : new() { if (stateModels.Count() == 0) return new List&lt;T&gt;(); dateFrom = GetPropertiesAndDictionaries( dateFrom, stateModels, out PropertyInfo datePropertyInfo, out List&lt;PropertyInfo&gt; copyProperties, out PropertyInfo timeWindowIdentifier, out int size, out TimeWindowDictionary[] dictionaries); byte[] windowDurations = { 5, 15, 60 }; return windowDurations.SelectMany(wd =&gt; CalculateTimeWindow( dateFrom, dateTo, stateModels, wd, datePropertyInfo, copyProperties, timeWindowIdentifier, size, dictionaries)); } public static IEnumerable&lt;T&gt; CalculateTimeWindow&lt;T&gt;(DateTime dateFrom, DateTime dateTo, List&lt;T&gt; stateModels, byte timeWindowMinutes, PropertyInfo datePropertyInfo, List&lt;PropertyInfo&gt; copyProperties, PropertyInfo timeWindowIdentifier, int size, TimeWindowDictionary[] dictionaries) where T : new() { if (stateModels.Count() &gt; 0) { DateTime currentWindowFrom, currentWindowTo, nextWindowFrom; nextWindowFrom = dateFrom; int itemPointer = 0; T prevItem = default; T prevTimeWindow = default; int j = 1; do // one time window { for (int i = 0; i &lt; size; i++) dictionaries[i].Dictionary = new Dictionary&lt;NullObject&lt;dynamic&gt;, int&gt;(); currentWindowFrom = nextWindowFrom; nextWindowFrom = currentWindowFrom.AddMinutes(timeWindowMinutes); currentWindowTo = nextWindowFrom.AddSeconds(-1); var calculateTime = currentWindowFrom; for (; itemPointer &lt; stateModels.Count(); itemPointer++) { var item = stateModels.ElementAt(itemPointer); var date = (DateTime)datePropertyInfo.GetValue(item); if (date &gt;= currentWindowTo) break; var endDate = (date &gt; currentWindowTo) ? nextWindowFrom : date; // state might extend more than the end of the time window CalculateStateSeconds(prevItem, dictionaries, calculateTime, endDate); prevItem = item; calculateTime = (date &lt; currentWindowFrom) ? currentWindowFrom : date; // to fix the 'yesterday' date } if (calculateTime &lt; currentWindowTo) CalculateStateSeconds(prevItem, dictionaries, calculateTime, nextWindowFrom); if (dictionaries[0].Dictionary.Count &gt; 0) { bool sameAsPrevious = (prevTimeWindow != null); var output = new T(); foreach (var dictionary in dictionaries) { var maxValue = dictionary.Dictionary.First(); for (j = 1; j &lt; dictionary.Dictionary.Count; j++) { var valuePair = dictionary.Dictionary.ElementAt(j); if (valuePair.Value &gt; maxValue.Value) maxValue = valuePair; } var valToSet = maxValue.Key.Item; if (sameAsPrevious) { var prevVal = GetValue(prevTimeWindow, dictionary.PropertyInfo); if (!(valToSet == null &amp;&amp; prevVal == null)) sameAsPrevious = (valToSet == prevVal); } SetValue(output, dictionary.PropertyInfo, valToSet); } if (!sameAsPrevious) { foreach (var copyProperty in copyProperties) SetValue(output, copyProperty, copyProperty.GetValue(prevItem)); timeWindowIdentifier.SetValue(output, timeWindowMinutes); datePropertyInfo.SetValue(output, currentWindowFrom); prevTimeWindow = output; yield return output; } } } while (nextWindowFrom &lt;= dateTo); } } private static DateTime GetPropertiesAndDictionaries&lt;T&gt;(DateTime dateFrom, List&lt;T&gt; stateModels, out PropertyInfo datePropertyInfo, out List&lt;PropertyInfo&gt; copyProperties, out PropertyInfo timeWindowIdentifier, out int size, out TimeWindowDictionary[] dictionaries) where T : new() { Type tType = typeof(T); if (!PropertiesDictionary.TryGetValue(tType, out Properties properties)) { var propInfos = tType.GetProperties(); datePropertyInfo = propInfos.Single(p =&gt; p.GetCustomAttributes(typeof(IsTimeWindowDate), true).Any()); var propertiesToProcess = propInfos.Where(p =&gt; p.GetCustomAttributes(typeof(IsProcessedIntoTimeWindow), true).Any()).ToList(); copyProperties = propInfos.Where(p =&gt; !p.GetCustomAttributes(typeof(IsTimeWindowIdentifier), true).Any() &amp;&amp; !p.GetCustomAttributes(typeof(DoNotCopyIntoTimeWindow), true).Any() &amp;&amp; !p.GetCustomAttributes(typeof(IsTimeWindowDate), true).Any() &amp;&amp; !p.GetCustomAttributes(typeof(IsProcessedIntoTimeWindow), true).Any() &amp;&amp; p.CanWrite &amp;&amp; !p.GetMethod.IsVirtual).ToList(); timeWindowIdentifier = propInfos.Single(p =&gt; p.GetCustomAttributes(typeof(IsTimeWindowIdentifier), true).Any()); size = propertiesToProcess.Count(); properties = new Properties() { CopyProperties = copyProperties, DatePropertyInfo = datePropertyInfo, PropertiesToProcess = propertiesToProcess, TimeWindowIdentifier = timeWindowIdentifier, Size = size }; PropertiesDictionary.TryAdd(tType, properties); } else { datePropertyInfo = properties.DatePropertyInfo; copyProperties = properties.CopyProperties; timeWindowIdentifier = properties.TimeWindowIdentifier; size = properties.Size; } dictionaries = properties.PropertiesToProcess .Select(p =&gt; new TimeWindowDictionary { PropertyInfo = p }) .ToArray(); var firstDate = (DateTime)datePropertyInfo.GetValue(stateModels.First()); if (firstDate &lt; dateFrom) dateFrom = new DateTime(firstDate.Year, firstDate.Month, firstDate.Day, firstDate.Hour, 0, 0, DateTimeKind.Utc); return dateFrom; } private static dynamic GetValue(object inputObject, PropertyInfo propertyInfo) { return propertyInfo.GetValue(inputObject); } //private static void SetValue(object inputObject, string propertyName, object propertyVal) private static void SetValue(object inputObject, PropertyInfo propertyInfo, object propertyVal) { if (propertyVal != null) { //find the property type Type propertyType = propertyInfo.PropertyType; //Convert.ChangeType does not handle conversion to nullable types //if the property type is nullable, we need to get the underlying type of the property var targetType = IsNullableType(propertyType) ? Nullable.GetUnderlyingType(propertyType) : propertyType; //Returns an System.Object with the specified System.Type and whose value is //equivalent to the specified object. propertyVal = Convert.ChangeType(propertyVal, targetType); } //Set the value of the property propertyInfo.SetValue(inputObject, propertyVal, null); } private static bool IsNullableType(Type type) { return type.IsGenericType &amp;&amp; type.GetGenericTypeDefinition().Equals(typeof(Nullable&lt;&gt;)); } private static void CalculateStateSeconds&lt;T&gt;(T prevItem, IEnumerable&lt;TimeWindowDictionary&gt; dictionaries, DateTime calculateTime, DateTime endDate) { if (prevItem != null) { var seconds = Convert.ToInt32(endDate.Subtract(calculateTime).TotalSeconds); foreach (var dictionary in dictionaries) { var key = dictionary.PropertyInfo.GetValue(prevItem); dictionary.Dictionary.TryGetValue(key, out int existingSeconds); dictionary.Dictionary[key] = existingSeconds + seconds; } } } #endregion } } </code></pre> <p>Now the problem I'm having is that when I call the method in this way:</p> <pre><code>var stopWatchTW = new Stopwatch(); stopWatchTW.Start(); CalculateTimeWindows(); stopWatchTW.Stop(); ConsoleLogger.WriteLine($"Processing time windows took {stopWatchTW.ElapsedMilliseconds}ms"); private void CalculateTimeWindows() { myList1.AddRange(TimeWindow.CalculateTimeWindows(dateFrom, dateTo, myList1).ToList()); myList2.AddRange(TimeWindow.CalculateTimeWindows(dateFrom, dateTo, myList2).ToList()); myList3.AddRange(TimeWindow.CalculateTimeWindows(dateFrom, dateTo, myList3).ToList()); myList4.AddRange(TimeWindow.CalculateTimeWindows(dateFrom, dateTo, myList4).ToList()); myList5.AddRange(TimeWindow.CalculateTimeWindows(dateFrom, dateTo, myList5).ToList()); myList6.AddRange(TimeWindow.CalculateTimeWindows(dateFrom, dateTo, myList6).ToList()); myList7.AddRange(TimeWindow.CalculateTimeWindows(dateFrom, dateTo, myList7).ToList()); myList8.AddRange(TimeWindow.CalculateTimeWindows(dateFrom, dateTo, myList8).ToList()); myList9.AddRange(TimeWindow.CalculateTimeWindows(dateFrom, dateTo, myList9).ToList()); myList10.AddRange(TimeWindow.CalculateTimeWindows(dateFrom, dateTo, myList10).ToList()); myList11.AddRange(TimeWindow.CalculateTimeWindows(dateFrom, dateTo, myList11).ToList()); myList12.AddRange(TimeWindow.CalculateTimeWindows(dateFrom, dateTo, myList12).ToList()); myList13.AddRange(TimeWindow.CalculateTimeWindows(dateFrom, dateTo, myList13).ToList()); myList14.AddRange(TimeWindow.CalculateTimeWindows(dateFrom, dateTo, myList14).ToList()); myList15.AddRange(TimeWindow.CalculateTimeWindows(dateFrom, dateTo, myList15).ToList()); myList16.AddRange(TimeWindow.CalculateTimeWindows(dateFrom, dateTo, myList16).ToList()); } </code></pre> <p>where each <code>myList</code> would be an empty list, the code is taking a very long time to run when deployed as an Azure WebJob (4.5 to 8 SECONDS to run), despite that I have this at the very top of the CalculateTimeWindows method:</p> <pre><code>if (stateModels.Count() == 0) return new List&lt;T&gt;(); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T08:58:53.897", "Id": "430701", "Score": "0", "body": "It can't possible be a problem with `CalculateTimeWindows`. What if you only have one or two lists, does that reduce the latency?Do you have any time consuming static initialization on the data model or in some attributes?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T09:02:13.500", "Id": "430702", "Score": "0", "body": "When I debug the code on my machine, I never experience such delays. It's only when it's in the production environment deployed as an Azure WebJob that this happens. I can't test with 2 lists, it needs to be all 16 because it's exactly in a production environment. I'm not sure what you mean by the static initialization? To note that this process (of doing these 16 calls) doesn't happen just once, but I'm doing it repeatedly, thousands of times. It's not the first one which is slow; it remains slow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T09:53:53.197", "Id": "430709", "Score": "1", "body": "You don't really have 16 lines of the same code, do you?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T10:10:50.043", "Id": "430714", "Score": "0", "body": "@t3chb0t, I do have 16 lines. Of course the variables are named differently, and there's about 11 different types in all (`List<Type1>`, `List<Type2>` etc). I needed to keep them separate because they need to be processed and handled differently." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T10:49:28.273", "Id": "430715", "Score": "2", "body": "How do you know it's exactly this method that is slow? Have you measured it? It is virtually impossible that it takes that much time with that empty-list guard at the top." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T12:19:48.260", "Id": "430729", "Score": "0", "body": "Yes, @t3chb0t, I am measuring it with a stopwatch that I .start() right before the calls and .stop() right after the calls." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T12:24:25.657", "Id": "430731", "Score": "0", "body": "You really should post more code and definitely better explain the current one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T12:33:43.973", "Id": "430735", "Score": "0", "body": "@t3chb0t, edited the code (second block). There really isn't much of a difference though, the code is really simple." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T12:40:41.593", "Id": "430737", "Score": "0", "body": "Put the stopwatch around each of the `AddRange` calls. Perhaps one of these is the bottleneck." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T12:43:11.070", "Id": "430738", "Score": "0", "body": "I'll try @dfhwze. Thing is I did a Unit test to see how long it will take in Debug and on my machine and it's consistently taking 4 milliseconds. I just don't understand why it would take up to 2000 times longer in release deployed as an Azure WebJob." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T12:47:18.463", "Id": "430740", "Score": "0", "body": "What's with the NullObject? Could you bring light into this? For a null-object it's pretty complex so I think it does much more than anyone would expect." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T12:54:37.850", "Id": "430742", "Score": "0", "body": "@t3chb0t I got the NullObject from https://stackoverflow.com/a/22261282/9945524. It allows you to have a nullable dynamic dictionary key. Sometimes the properties that need to be processed into time windows have a nullable type, and therefore some values would be set to null and thus I need to keep track of how many NULL values there were to see if it was the most popular value within that time window. Theoretically though, it should not be hit now, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T12:57:25.830", "Id": "430743", "Score": "0", "body": "Not sure if this has any relevance at all, but the TimeWindow class is in a separate solution which is being packaged as a NuGet package and referenced that way. It shouldn't make any difference, I guess." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T13:14:59.367", "Id": "430746", "Score": "1", "body": "Calling it nullable-key would be much wiser and more intuitive." } ]
[ { "body": "<p>Well, this is embarrassing. Turns out, that the lists weren't empty after all, but they had 1 item, with its date property (having the attribute <code>IsTimeWindowDate</code>) preceding the <code>dateFrom</code>. The result of <code>CalculateTimeWindows</code> would still be an empty list, and at the end I was only counting the rows inserted in the database (taking for example <code>myList1.Where(x =&gt; x.Date &gt;= dateFrom)</code>).</p>\n\n<p>Still, this is taking a wee bit too much for 1 row.</p>\n\n<p><strong>EDIT:</strong> An improvement with this code whilst debugging locally, but actually taking longer when deployed live on Azure:</p>\n\n<p>(first setting <code>lastWindow = false;</code> inside the <code>CalculateTimeWindows</code>)</p>\n\n<pre><code> ...\n if (itemPointer == stateModels.Count())\n lastWindow = true;\n else if (lastWindow)\n break;\n }\n while (nextWindowFrom &lt;= dateTo);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T13:14:10.687", "Id": "430745", "Score": "4", "body": "lol, this is why you always should post all relevant code, maybe next time ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T13:20:21.937", "Id": "430749", "Score": "0", "body": "aye @t3chb0t, still it doesn't explain why 16 lists with 1 item each, all preceding the dateFrom, should take up to 8 seconds though, does it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T13:32:47.320", "Id": "430754", "Score": "0", "body": "In fact, my updated Unit test is now taking 44ms during debugging. Never anywhere close to 8 seconds." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T14:54:09.803", "Id": "430771", "Score": "0", "body": "Just now, even with the improvement in the edit of this answer, the 16 calls to CalculateTimeWindows which yielded 0 rows took 12344ms; that's over 12 seconds." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T14:57:16.207", "Id": "430776", "Score": "0", "body": "Run it multiple times within the same session. First unmeasured then with the benchmark. There might be some initialization or JIT time added to the result." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T15:03:54.043", "Id": "430780", "Score": "0", "body": "@t3chb0t what I did was compare the logs of the first 10 iterations with the new code to the logs of the code processing the exact same data with the previous algorithm. The first iteration took longer because it was applying the reflection and creating the dictionaries, that's understandable even though it took 5408ms. The 2nd iteration should've been faster, but it took 4565ms (compared to 2314ms before). The other 8 iterations all took longer (ranging from as little difference as 133->142ms to a big difference as 139->665ms)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T13:11:37.700", "Id": "222525", "ParentId": "222505", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T07:35:55.513", "Id": "222505", "Score": "2", "Tags": [ "c#", "performance", "linq", "generics", "interval" ], "Title": "Performance issue with empty lists" }
222505
<p>I want to create a dynamic query to display:</p> <ul> <li>all the invoices if the user has moderator rank </li> <li>only his invoices if the user is a simple member</li> </ul> <p>code </p> <pre><code> public function getAllBill($user_rank, $user_id){ $sql = 'SELECT * FROM invoice_user INNER JOIN users on users.user_id = invoice_user.user_id'; $sql_clause = 'WHERE user_id = :user_id)'; $sql_group = 'GROUP BY invoice_number ORDER BY invoicedate DESC'; if ($user_rank === 'member') { $final_sql = $sql.' '.$sql_clause.' '.$sql_group; $parameters = array(':user_id' =&gt; $user_id); } else if ($user_rank === 'moderator'){ $final_sql = $sql.' '.$sql_group; $parameters = array(); } else { $error = TRUE; } if (!isset($error)) { $request = $this-&gt;bdd-&gt;prepare($final_sql); $request-&gt;execute($parameters); return $request-&gt;fetchAll(); } else return array(); } </code></pre> <p>script </p> <pre><code>&lt;?php $table = getAllBill($_SESSION ['rank'], $_SESSION ['id']); foreach ($table as $row) { # code... } </code></pre> <p>I would like to know if there is a more elegant way to do this, but <strong>especially to know if everything is safe</strong> knowing that the rank and the ID come from the user session (<code>$_SESSION ['rank']</code>, <code>$_SESSION ['id']</code>)</p> <p>Does it pose a problem not to put my parameter table in a condition?</p> <p>PS : I use MySQL</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T08:44:40.120", "Id": "430696", "Score": "0", "body": "\"... but especially to know if everything is safe knowing that the rank and the ID come from the user session `($_SESSION ['rank'], $_SESSION ['id'])`\" --> Why not add `getAllBill($_SESSION ['rank'], $_SESSION ['id'])` as an example how you would call this function then?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T09:20:32.843", "Id": "430703", "Score": "1", "body": "@AlexV I just added the call to the function in my post, I would especially like to know if there is no risk of SQL injection" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T06:30:22.757", "Id": "430882", "Score": "0", "body": "Use a `SHOW COLUMNS FROM table` query or `DESCRIBE table` then you can use the list of columns to whitelist incoming column names. I forget exactly what these return, but you can use something like `array_intersect_key`, to remove fields that don't have an actual column, such as a field like this `\"' OR 1 --` (classic SQL injection) You also have an error in your SQL right here `$sql_clause = 'WHERE user_id = :user_id)';` no opening `(`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T07:19:26.877", "Id": "430888", "Score": "1", "body": "@Rocstar - if you allow the columns to be dynamic then yes there is possibility of SQL injection because you cannot parameterize the columns. If it's just arguments then you can prepare those with no issue. For example if you allow them to pick what column a sort is done on `SELECT * FROM ... SORT BY $foo` that can absolutely be injected by altering the keys passed to the query building bit." } ]
[ { "body": "<p>If you allow users to pass in arguments that are column names (for example array keys that you turn into column names). Then the keys could be modified to allow SQL Injection. It's not clear in the question if you plan to do this. If you just want to have dynamic arguments (with known columns) then preparing the query should suffice as all the user data can be parameterized without issue.</p>\n\n<p>As preparing the values is not an issue, I will assume you want to make the columns and/or tables dynamic.</p>\n\n<p><strong>Problem</strong></p>\n\n<p>Imagine you create a dynamic Select query like this, where the keys from the input args are used for column names and the table name is dynamic as well (fully dynamic):</p>\n\n<pre><code>class foo{\n function Select($table, $args){\n $query = \"SELECT * FROM {$table}\";\n $where = [];\n $params = [];\n\n foreach($allowedArgs as $col =&gt; $arg){\n $where[] = \"{$col} = :{$col}\";\n $params[$col] = $arg;\n }\n\n if(!empty($where)) $query .= ' WHERE '.implode(' AND ', $where);\n\n print_r($query);\n }\n}\n</code></pre>\n\n<p>Output would be something like this:</p>\n\n<pre><code> //------- intended behaviour\n $foo-&gt;Select('someTable', ['ID' =&gt; 32, 'user' =&gt; 'someUser']);\n \"SELECT * FROM someTable WHERE ID = :ID AND user = :user\"\n //after executing with parameters\n \"SELECT * FROM someTable WHERE ID = '32' AND user = 'someUser'\"\n\n //------- unintended behaviour\n $foo-&gt;Select('someTable', ['ID' =&gt; 32, '1 OR 1 --' =&gt; null]);\n \"SELECT * FROM someTable WHERE ID = :ID AND 1 OR 1 -- = :1 OR 1 --\"\n //the DB would execute this:\n \"SELECT * FROM someTable WHERE ID = 32 AND 1 OR 1\"\n</code></pre>\n\n<p>To explain the SQLInjection:</p>\n\n<ul>\n<li>The first <code>1</code> completes the <code>AND</code> </li>\n<li>Then the <code>OR 1</code> is always true. </li>\n<li>Everything after the SQL comment <code>--</code> is ignored. </li>\n</ul>\n\n<p>So this would return all records in that table regardless of the other arguments. This is how basic SQLInjection works.</p>\n\n<p>Here <code>$table</code> is also susceptible to SQLInjection, so if you did (this is a bad example but you get the point):</p>\n\n<pre><code> $foo-&gt;Select('admin WHERE 1 --', []);\n//\"SELECT * FROM admin WHERE 1 --\"\n</code></pre>\n\n<p><strong>Solution</strong> </p>\n\n<p>However, you can query the DB schema, by using <code>DESCRIBE {$table}</code> and <code>SHOW TABLES</code>, to build a whitelist of column names and tables. And than, store that data so you can filter out any bad \"stuff\" like this:</p>\n\n<pre><code>//eg. results of DESCRIBE \nField Type Null Key Default Extra \n ID int(10) unsigned NO PRI NULL auto_increment\n\n//eg. SHOW TABLES\nTables_in_{database}\n someTable\n</code></pre>\n\n<p>From this you can build something like:</p>\n\n<pre><code>class foo{\n //get the schema\n public static $fields;\n public static $tables;\n\n public function ckTable($table){\n if(!self::$tables){\n $smtp = $this-&gt;db-&gt;query(\"SHOW TABLES\");\n self::$tables = $stmt-&gt;fetchAll(PDO::FETCH_COLUMN); //['someTable', \"admin\", ...]\n }\n if(!in_array($table, self::$tables)) throw new UnknownTable($table);\n }//end ckTable()\n\n public function getFields($table){\n $this-&gt;ckTable($table);\n\n //only query this once per request\n if(!self::$fields[$table]){\n\n self::$fields[$table] = [];\n\n $smtp = $this-&gt;db-&gt;query(\"DESCRIBE $table\");\n\n $fields = [];\n while($row = $smtp-&gt;fetch(PDO::FETCH_ARRAY)){\n\n //technically we only need the Keys or the \"Field\" for this\n //but I felt like showing how you can parse the type too... \n preg_match('/^(?P&lt;type&gt;\\w+)(?:\\((?P&lt;size&gt;\\d+)\\))?/', $row['Type'], $match);\n\n $fields[$table][$row['Field']] = [\n 'type' =&gt; $match['type'],\n 'size' =&gt; isset($match['size']) ? (int)$match['size'] : false,\n 'key' =&gt; $row['Key']\n ];\n }//end while\n }//end if self::$fields\n\n return self::$fields[$table];\n }//end getFields()\n }//end foo\n</code></pre>\n\n<p><a href=\"https://regex101.com/r/FaA5HD/1\" rel=\"nofollow noreferrer\">Regex Sandbox</a></p>\n\n<p>Which should give you something like this:</p>\n\n<pre><code> //-note- we're returning only $fields['someTable'] in the example\n $fields = [\n 'someTable' =&gt; [\n 'ID' =&gt; ['type' =&gt; 'int', 'size' =&gt; 10, 'key' =&gt; 'PRI']\n ], [...]\n ], [...]\n ];\n</code></pre>\n\n<p>Then when you make your dynamic query:</p>\n\n<pre><code> class foo{\n //eg inputs (with sql injection) \n //$table = 'someTable';\n //$args = ['ID' =&gt; 1, '1 OR 1 --' =&gt; '']\n public function Select($table, array $args){\n $fields = $this-&gt;getFields($table); //retuns ['ID' =&gt; [...]]\n\n $allowedArgs = array_intersect_key($args, $fields); //results in ['ID' =&gt; 1], removing key '1 OR 1 --'\n\n //escaping with backtic ` is a good idea, it adds a tiny bit of security too.\n //eg. \"SELECT * FROM `admin WHERE 1 --`\" this is a sql error\n //that said it's mostly for reserved words and spaces in table names etc..\n $query = \"SELECT * FROM `{$table}`\";\n\n $where = [];\n $params = [];\n\n foreach($allowedArgs as $col =&gt; $arg){\n //backtic column names too\n $where[] = \"`{$col}` = :{$col}\"; // 'ID = :ID'\n $params[$col] = $arg;\n }\n\n if(!empty($where)) $query .= ' WHERE '.implode(' AND ', $where);\n\n $this-&gt;db-&gt;prepare($query);\n return $this-&gt;db-&gt;execute($params);\n } //end Select()\n }//end foo\n</code></pre>\n\n<p>Output would be something like this:</p>\n\n<pre><code>$foo-&gt;Select('someTable', ['ID' =&gt; 1, '1 OR 1 --' =&gt; '']);\n//note the SQLInjection key is removed by array_intersect_key\n$query = \"SELECT * FROM `someTable` WHERE `ID` = :ID\"\n//in PDO the ':' for execute arguments are optional\n$params = ['ID' =&gt; 1];\n</code></pre>\n\n<blockquote>\n <p><a href=\"https://www.php.net/manual/en/function.array-intersect-key.php\" rel=\"nofollow noreferrer\">array_intersect_key()</a> returns an array containing all the entries of array1 which have keys that are present in all the arguments.</p>\n</blockquote>\n\n<p>So by having the schema dynamically pulled from the DB we can filter out bad Keys that would become column names in the SQL. Also because it's dynamic (you should store it once per request, so do the describe query once) if we modify the schema we don't have any issues with our code. It just adapts based on the arguments and the schema.</p>\n\n<p>The only problem with this (the tables being dynamic) is they could potentially access other tables you don't want them too. But only if they are valid tables. If that is a concern you can always create the table array manually or explicitly remove those tables you don't want end users having access to, with unset etc... </p>\n\n<p><strong>Additional Error checking</strong></p>\n\n<p>You can also throw an exception by comparing the count of <code>$args</code> and <code>$allowedArgs</code> Like this:</p>\n\n<pre><code>class foo{\n\n //eg inputs (with sql injection) ['ID' =&gt; 1, '1 OR 1 --' =&gt; '']\n public function Select($table, array $args){\n $fields = $this-&gt;getFields($table);\n $allowedArgs = array_intersect_key($args, $fields);\n\n if(count($args) != count($allowedArgs)){\n $diff = array_diff_key($args, $allowedArgs);\n throw new UnknownColumn(implode(',', array_keys($diff)));\n }\n ....\n }//end Select()\n}//end foo\n</code></pre>\n\n<p>The above would throw a <code>UnknownColumn</code> (assuming that exception exists) that says something like this:</p>\n\n<pre><code>//$foo-&gt;Select('someTable', ['ID' =&gt; 1, '1 OR 1 --' =&gt; '']);\nException UnknownColumn: \"1 OR 1 --\" IN somefile.php ON line 123\n</code></pre>\n\n<p>If you did some table that doesn't exist (as I showed above) you would get an exception from <code>ckTable()</code> which is chained through <code>getFields</code>:</p>\n\n<pre><code>//$foo-&gt;Select('1 OR 1', ['ID' =&gt; 1, '1 OR 1 --' =&gt; '']);\nException UnknownTable: \"1 OR 1\" IN somefile.php ON line 123\n</code></pre>\n\n<p>Obviously you can add more complexity such as if it's and <code>AND</code> or an <code>OR</code>. Argument groups such as exclusive ORs. Type checks, size checks etc. Basically whatever you want as you will have all the schema data at your fingertips.</p>\n\n<p>I actually have a DB class that basically does this to build dynamic Insert and Update queries. For example in the above I know that <code>ID</code> is the Pkey of the table so if its present in the arguments, I know that is an update of row with {x} ID. If not then it's an insert etc... Unfortunately my DB class has some dependencies and I can't share it without removing some of my employers requirements. It does a lot of other things too, like handling multiple databases, different comparison operators, logical groups etc. I should refactor it and put it on Git (one of these days).</p>\n\n<p>Anyway, I should re-iterate you can also do this with a simple array (instead of getting the schema) that you manually built. Essentially a whitelist the columns or tables. But, if you edit the schema you will likely have to modify your code.</p>\n\n<p>Cheers!</p>\n\n<p>PS. I didn't test any of this, I like PDO so I used it for the code. But it should be pretty close.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T06:53:29.187", "Id": "222568", "ParentId": "222507", "Score": "3" } }, { "body": "<p>For improved readability and for reduced processing &amp; memory, I recommend an early return and no single-use variables.</p>\n\n<pre><code>public function getAllBill($user_rank, $user_id) {\n\n if (!in_array($user_rank, ['member', 'moderator'])) {\n return [];\n }\n\n $parameters = [];\n $sql = 'SELECT *\n FROM invoice_user\n INNER JOIN users on users.user_id = invoice_user.user_id';\n\n if ($user_rank === 'member') {\n $sql .= ' WHERE user_id = :user_id';\n $parameters[':user_id'] = $user_id;\n }\n\n $sql .= ' GROUP BY invoice_number\n ORDER BY invoicedate DESC';\n\n $request = $this-&gt;bdd-&gt;prepare($sql);\n $request-&gt;execute($parameters);\n return $request-&gt;fetchAll();\n}\n</code></pre>\n\n<p>You are properly implementing a prepared statement so security is good. Now your code is free from convolution and excess variables. (Snippet: untested)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T22:54:07.203", "Id": "222608", "ParentId": "222507", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T07:58:00.537", "Id": "222507", "Score": "3", "Tags": [ "php", "mysql", "security", "pdo" ], "Title": "Elegant and secure way to create a dynamic query" }
222507
<p>My goal is to write a smaller compiler-like program, which allows me to draw geometric shapes into a 3D Diagram. There is no need for <a href="https://en.wikipedia.org/wiki/Turing_completeness" rel="noreferrer">turing-completeness</a> and the program should only be viewed as an exercise and not as a program used by anybody. However, I want the program to have a compiler-like nature.</p> <p>At the moment the user provides a text file like this:</p> <pre><code>(1,45,6) (7,8,5) (10,77,88) (99999,1,1) (5,7,6) (1,2,3) (4,5,6) </code></pre> <p>These points will be translated into a python file, which will later display all points in a 3D-Diagram when executed. For the moment, I just want it to print out a list of points when executed.</p> <blockquote> <p>--> [(1, 45, 6), (7, 8, 5), (10, 77, 88), (99999, 1, 1), (5, 7, 6), (1, 2, 3), (4, 5, 6)]</p> </blockquote> <p>The python file looks like this:</p> <pre><code>list = [] list.append((1,45,6)) list.append((7,8,5)) list.append((10,77,88)) list.append((99999,1,1)) list.append((5,7,6)) list.append((1,2,3)) list.append((4,5,6)) print(list) </code></pre> <p>Therefore, I build the following code using C (just to improve C-skills, I am aware that writing it in python would be more applicable)</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; size_t seek(char* buffer, size_t start, const size_t end, char to_be_seeked); int translateString2Number(char* c, long length); int power(int base, int exponent); int main(int argc, const char * argv[]) { if(argc &lt;= 2)return -1; char file_name[100]; strncpy(file_name, argv[1], 100); FILE* fp = fopen(file_name, "read"); if(!fp)return -1; fseek(fp, 0, SEEK_END); const size_t elements_num = ftell(fp); rewind(fp); remove("translation.py"); FILE * python_file_pointer = fopen("translation.py", "ab+"); fprintf(python_file_pointer, "list = []\n"); //Do parsing char* buffer = malloc(sizeof(char) * elements_num); fread(buffer, elements_num, 1, fp); size_t start = 0; while(start &lt; elements_num){ if(buffer[start] != '(') return -1; size_t end = seek(buffer, start, elements_num, ')'); if(end == -1) return -1; size_t comma_pos[2]; comma_pos[0] = seek(buffer, start, end, ','); comma_pos[1] = seek(buffer, comma_pos[0]+1, end, ','); if(comma_pos[0] == -1 || comma_pos[1] == -1 )return -1; char first_number_size = comma_pos[0]-start-1; char first_number[first_number_size]; for(size_t i = 0; i &lt; first_number_size; i++){ first_number[i] = buffer[start+1+i]; } char second_number_size = comma_pos[1]-comma_pos[0]-1; char second_number[second_number_size]; for(size_t i = 0; i &lt; second_number_size; i++){ second_number[i] = buffer[comma_pos[0]+1+i]; } char third_number_size = end - comma_pos[1]-1; char third_number[third_number_size]; for(size_t i = 0; i &lt; third_number_size; i++){ third_number[i] = buffer[comma_pos[1]+1+i]; } if( (first_number_size &lt; 0) || second_number_size &lt; 0|| third_number_size &lt; 0){ return -1; } if( (first_number_size &gt; 11) || second_number_size &gt; 11|| third_number_size &gt; 11){ //Avoid potential overflow return -1; } int first = translateString2Number(first_number, first_number_size); int second = translateString2Number(second_number, second_number_size); int third = translateString2Number(third_number, third_number_size); fprintf(python_file_pointer, "list.append((%d,%d,%d))\n", first,second,third); const size_t value = seek(buffer, end, elements_num, '\n'); if(value == -1)break; start = value+1; } fprintf(python_file_pointer, "print(list)\n"); fclose(python_file_pointer); system("python3 translation.py"); fclose(fp); } int power(int base, int exponent){ int result = 1; for(int i = 0; i &lt; exponent; i++){ result *= base; } return result; } int translateString2Number(char* c, long length){ int res = 0; for(int i = 0; i &lt; length; i++){ res += (c[i]-'0')*power(10, (int)(length-i-1)); //printf("\n%d", res); } return res; } size_t seek(char* buffer, size_t start, const size_t end, char to_be_seeked){ do{ if(buffer[start] == to_be_seeked)return start; } while(++start &lt; end); return -1; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T08:52:33.367", "Id": "430698", "Score": "2", "body": "Sure, you are right. But actually, this is happening already only in a redundant form. How would you call it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T08:52:38.103", "Id": "430699", "Score": "3", "body": "@dfhwze: To be fair, the code actually seems to emit executable Python code, since the OP actually does `system(\"python3 translation.py\");` to generate the output." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T08:54:33.540", "Id": "430700", "Score": "0", "body": "@AlexV You guys are right :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T14:59:44.690", "Id": "430940", "Score": "0", "body": "Very good example for code review, thanks for sharing and thanks to all these good anseers" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-23T08:06:11.227", "Id": "431407", "Score": "0", "body": "The prototype `size_t seek(char* buffer, size_t start, const size_t end, char to_be_seeked);` has a `const` parameter (`const size_t end`), which is weird. From the point of view of the caller, that is redundant, as only pointers can be used to modify arguments of a function. It makes some sense from the point of view of the function itself, but it kind of clutters the code, and I've never seen that being used; mostly because functions are (or should be) so short that that information is usually obvious. It's weirder given that `to_be_seeked` isn't modified in the function, but isn't `const`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-24T10:30:44.500", "Id": "431542", "Score": "0", "body": "@CacahueteFrito\nMy intention is that the compiler can optimize- I heard that, if you do not change something make it constant so that the compiler can optimize" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-24T11:58:57.553", "Id": "431564", "Score": "1", "body": "@TVSuchty That's true for pointers, because if not, the caller doesn't know if the function changed the value pointed by the pointer. But variables can't be changed by a function, so the caller knows it will be constant. And for the function itself, the compiler is smart enough to read the whole function and know if it is being used in the function or not. In the specific case of this function it would make sense to make the pointer const (actually, not the pointer, but the type pointed by the pointer): `size_t seek(const char *buffer, size_t start, size_t end, char to_be_seeked);`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-01T19:10:37.227", "Id": "432685", "Score": "0", "body": "I have never heard the term \"Premature Compiler\" before and Google isn't showing any other instances of it on the Internet. Is \"Precompiler\" what was intended here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-02T09:59:10.567", "Id": "432735", "Score": "0", "body": "Nah, it is not that the term \"premature compiler\" exists. I am just saying that I build a compiler because technically I did. But this compiler is not able to do all thing it is used to do, because I have not implemented a needed \"aspects\". So he is not mature, therefore premature..." } ]
[ { "body": "<h1>Allocations can fail</h1>\n<p>Don't use <code>buffer</code> until we know it's not null. (And no need to multiply by <code>sizeof (char)</code>, since that's automatically a no-op).</p>\n<p>Please remember to <code>free()</code> it too (at least as an option). That reduces false positives with Valgrind's memory checker.</p>\n<h1>I/O operations can fail</h1>\n<p>Always check that your I/O succeeds.</p>\n<p>Consider this scenario: we run the program in a directory containing a (hostile) <code>translation.py</code>. The directory and the file are both read-only, so the <code>remove()</code> and the <code>fopen()</code> both fail, as do all the <code>fprintf()</code> calls using the invalid file descriptor.</p>\n<p>Then we get to the call to <code>system()</code>. What's the Python code that's executed?</p>\n<h1>Use a temporary file</h1>\n<p>Instead of assuming it's possible and desirable to overwrite <code>translation.py</code> in the current directory, perhaps we should <code>mktemp()</code> or similar, and remove the temporary file when we exit?</p>\n<h1>Python source files are text</h1>\n<p>It makes no difference on a POSIX system, but it's misleading to use <code>&quot;b&quot;</code> in the <code>fopen()</code> call. We don't ever read from it, so don't need the <code>&quot;+&quot;</code>, and want to replace any existing file, not append (so we wouldn't need to <code>remove()</code>), so the open mode really should be plain <code>&quot;w&quot;</code>.</p>\n<h1>Use the standard library</h1>\n<p><code>translateString2Number</code> (and therefore also <code>power()</code>) can be replaced with a simple call to <code>sscanf</code> (since we know the numbers are all terminated by a non-digit).</p>\n<p>In fact, if we can rely on the input being correctly formatted (and simply error out if it's wrong), we can just read all the input using <code>scanf()</code>, rather than allocating <code>buffer</code> to hold the entire input stream.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T09:39:38.093", "Id": "430705", "Score": "0", "body": "Consider this scenario: we run the program in a directory containing a (hostile) translation.py. The directory and the file are both read-only, so the remove() and the fopen() both fail, as do all the fprintf() calls using the invalid file descriptor.\n\nThen we get to the call to system(). What's the Python code that's executed?\n\nAre you a security engineer? WTF! Hella Smart! Blow my mind.\n\nThanks for your answer,." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T09:51:01.357", "Id": "430707", "Score": "0", "body": "So could you further explain how you would read without a buffer and how to assure the allocation has happened correctly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T11:54:18.823", "Id": "430724", "Score": "0", "body": "Well, the simple way to read without allocating our own buffer is to `fscanf()` directly from the input stream. That would greatly limit our options for error reporting, so I'd likely recommend using a fixed-size line buffer instead: read a line at a time, fail if line is too long or if `fscanf(buffer, \" (%d,%d,%d)\", &a, &b, &c) != 3)`, maintain a line counter (for the error reporting). Oh, and I do have some experience in security analysis on various Unix platforms, but it's not my current main job." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T04:53:48.687", "Id": "430873", "Score": "0", "body": "You further said that you suggest making a temporary file. However, I have not figured out what that accomplishes? What do I do with the temp file afterwards?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T07:21:27.890", "Id": "430889", "Score": "0", "body": "`mktemp()` will give you a file that's writeable and not already in use, so it reduces the likelihood of a few foreseeable failure cases. After use, it's considered polite to remove the temporary file (many installations have a \"tmpreaper\" daemon to clean up old files from `/tmp` or equivalent, but treat that as a last resort)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T09:38:16.100", "Id": "430909", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/95118/discussion-between-tvsuchty-and-toby-speight)." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T09:34:13.207", "Id": "222512", "ParentId": "222510", "Score": "15" } }, { "body": "<p>I see a number of things that may help you improve your program. Since the existing review covered a lot of good points, this review will cover the parts not already mentioned.</p>\n\n<h2>Use the correct form for <code>main</code></h2>\n\n<p>There are exactly two allowed version of <code>main</code>, according to the standard, and yours isn't one of them. This code has this:</p>\n\n<pre><code>int main(int argc, const char * argv[]) {\n</code></pre>\n\n<p>But we need to remove the <code>const</code> here. See <a href=\"https://stackoverflow.com/questions/2108192/what-are-the-valid-signatures-for-cs-main-function/\">this question</a> for details.</p>\n\n<h2>Use whitespace to make code more readable</h2>\n\n<p>Code lines like this:</p>\n\n<pre><code>if(argc &lt;= 2)return -1;\n</code></pre>\n\n<p>are generally more readable if they include a little more whitespace. I'd write that like this:</p>\n\n<pre><code>if(argc &lt; 2) {\n return -1;\n}\n</code></pre>\n\n<p>Note that we only need <code>argc</code> to be <em>at least</em> two -- exactly 2 arguments is just fine and <strong>not</strong> an error.</p>\n\n<h2>Don't make pointless copies</h2>\n\n<p>The first few lines of the code are these:</p>\n\n<pre><code>int main(int argc, const char * argv[]) {\n if(argc &lt;= 2)return -1;\n\n char file_name[100];\n strncpy(file_name, argv[1], 100);\n FILE* fp = fopen(file_name, \"read\");\n if(!fp)return -1;\n</code></pre>\n\n<p>First, 100 is an awfully arbitrary limit that might not be an entire path. Second, and most importantly, there's no need for the copy at all. This could all be reduced to this:</p>\n\n<pre><code>int main(int argc, char * argv[]) {\n if(argc &lt; 2) {\n return -1;\n }\n FILE *in = fopen(argv[1], \"r\");\n if (!in) {\n return errno;\n }\n</code></pre>\n\n<p>The read mode is \"r\" and not \"read\". Note that we return <code>errno</code> (which is set by <code>fopen</code>) on error to give a slightly higher chance that the user can figure out what went wrong.</p>\n\n<h2>Don't do more work than needed</h2>\n\n<p>There's no real reason to seek to the end of the file to find out how big it is. Instead, one could parse the file character at a time and just look for the special <code>EOF</code> (end of file) token while parsing.</p>\n\n<h2>Don't leak memory</h2>\n\n<p>The buffer is allocated with this line</p>\n\n<pre><code>char* buffer = malloc(sizeof(char) * elements_num);\n</code></pre>\n\n<p>But there is no corresponding call to <code>free()</code> so this creates a memory leak. Also <code>sizeof(char)</code> is defined by the standard to be 1, so multiplying it here is pointless.</p>\n\n<h2>Write more concise Python</h2>\n\n<p>One could write this, as the current program does:</p>\n\n<pre><code>list = []\nlist.append((1,1,1))\nlist.append((2,2,2))\n</code></pre>\n\n<p>Or it could be written instead like this:</p>\n\n<pre><code>list = [(1,1,1), (2,2,2)]\n</code></pre>\n\n<p>I'd prefer the latter form, perhaps limiting the output line length to no more than 70 or so characters.</p>\n\n<h2>Don't convert numbers from text only to convert them back</h2>\n\n<p>There's no need to convert the input text to a number only to then re-convert to text on output. Instead, write each character directly as a character.</p>\n\n<h2>Use a state machine for parsing</h2>\n\n<p>A parser can often be implemented as an explicit state machine. Such parsers are often easier to reason about and to debug and augment. For that reason, I'd suggest writing this as a state machine.</p>\n\n<h2>Don't hardcode file names</h2>\n\n<p>Since there's only one output file, why not let the user specify its name instead of hardcoding it? Even better, don't use file names or handlers at all. Simply read from <code>stdin</code> and write to <code>stdout</code> and let the user redirect the files as needed. This gives the user complete control and allows you to simplify the code.</p>\n\n<h2>Eliminate \"magic numbers\"</h2>\n\n<p>There are a few numbers in the code, such as <code>2</code> and <code>100</code> that have a specific meaning in their particular context. By using named constants instead, the program becomes easier to read and maintain. For cases in which the constant is not used to size a static array, use <code>#define</code>; otherwise use <code>const</code>.</p>\n\n<h2>An example</h2>\n\n<p>Here's one alternative using all of these suggestions:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;ctype.h&gt;\n\nint main(void) {\n printf(\"list = [\");\n enum { openparen, num, comma, closeparen, error } state = openparen;\n // expected number of additional numbers beyond the first\n const int expected = 2;\n int numbers = expected;\n for (char ch = getchar(); ch != EOF; ch = getchar()) {\n if (isspace(ch)) {\n continue;\n }\n switch (state) {\n case openparen:\n if (ch == '(') {\n putchar(ch);\n state = num;\n } else {\n state = error;\n }\n break;\n case num:\n if (isdigit(ch)) {\n putchar(ch);\n if (numbers == 0) {\n numbers = expected;\n state = closeparen;\n } else {\n state = comma;\n }\n } else {\n state = error;\n }\n break;\n case comma:\n if (isdigit(ch)) {\n putchar(ch);\n } else if (ch == ',' &amp;&amp; numbers) {\n putchar(ch);\n --numbers;\n state = num;\n } else {\n state = error;\n }\n break;\n case closeparen:\n if (isdigit(ch)) {\n putchar(ch);\n } else if (ch == ')') {\n putchar(ch);\n putchar(',');\n state = openparen;\n } else {\n state = error;\n }\n break;\n default:\n fprintf(stderr, \"Error in input data.\\n\");\n return 1;\n break;\n }\n }\n printf(\"]\\n\");\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T13:33:37.207", "Id": "430755", "Score": "6", "body": "@TVSuchty These are 2 separate answers by 2 separate members of Code Review, there is no way to merge the answers. Be happy because 2 of the best C/C++ experts on code review answered your question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T18:09:16.237", "Id": "430809", "Score": "0", "body": "I don't understand why you can't use `const` in `main`'s definition. You can use `const` in a definition when you've previously declared it without a `const` (in a body-less prototype), so I don't see how this situation is different." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T18:43:05.133", "Id": "430817", "Score": "2", "body": "@wizzwizz4: your instincts are good -- if you had defined your own function like this, it would indeed make sense to have it `const`, but there are a number of C language rules that make `main` unique and that is one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T18:51:59.497", "Id": "430823", "Score": "0", "body": "@Edward From your linked question: \"although it does mention the phrase \"or equivalent\" with the following footnote:\" How is the with-`const` version not equivalent? It's _functionally_ equivalent, and not `gcc` nor `clang` nor Pelles C have ever complained about it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T18:56:22.453", "Id": "430824", "Score": "0", "body": "@wizzwizz4: Read carefully the section that says \"The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination.\" That would seem to me to clearly prohibit the use of `const` and thus I conclude that the use of `const` is not compliant with the standard, regardless of what our particular compilers actually accept." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T20:13:00.993", "Id": "430844", "Score": "1", "body": "@Edward They are modifiable, but the program simply chooses not to. The prototype does not have `const`, but the implementation does." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T20:56:14.620", "Id": "430849", "Score": "2", "body": "I ‘ll note that the linked answer got the same question (as a comment) and the same answer: `const argv` does not seem to be allowed by the standard." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T07:26:38.600", "Id": "430892", "Score": "0", "body": "@wizzwizz4 - yes, a prototype with a `const` version of an argument is compatible, but that's not what's happening here - the `const` applies to the pointed-to `char`, not to the array(-pointer) that is the argument. That would be the difference between `char const * *` and `char * *const` (the latter is an acceptable, equivalent, declaration for `argv`; the former is not). And there are good language-level reasons that they can't be considered equivalent; I'm sure [so] has a good question on this somewhere." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T07:57:15.903", "Id": "430897", "Score": "0", "body": "+1 for State Machine rewrite, for the love of all that is holy. Parsers that don't make use of formal languages are merely offerings to chaos gods and _will_ lash out at any and all maintainers if they get near." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T11:31:12.913", "Id": "430918", "Score": "0", "body": "Should I cover \\n in the file? Since you have not in the example and I am not sure if it is needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T11:40:50.470", "Id": "430919", "Score": "1", "body": "Actually, this code does handle `\\n` and spaces and tabs by skipping all of them in using `if (isspace(ch)) { continue; }` This may or may not be what you want, because it would accept input such as \"( 9 9 9, 3 2 1, 1 1 1 )\" as \"(999,321,111)\". Also any of those spaces could also be newline characters or formfeed characters, making for some really ugly input! On output, only a single newline is issued with the closing bracket." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T13:05:04.627", "Id": "430924", "Score": "0", "body": "So is \\n = space?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T13:18:37.587", "Id": "430927", "Score": "0", "body": "Yes, see https://en.cppreference.com/w/cpp/string/byte/isspace for details" } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T11:36:53.630", "Id": "222519", "ParentId": "222510", "Score": "17" } }, { "body": "<p>Another point that hasn't been fleshed out by other reviewers is the generated python code.</p>\n\n<p><code>list</code> is a <a href=\"https://docs.python.org/3/library/functions.html\" rel=\"noreferrer\">built-in function</a> in python - by calling your list <code>list</code> you are overriding it. That's generally considered bad form in the python community, mostly because someone could be stung if they try to use the <code>list</code> constructor later in the code.</p>\n\n<p>So instead, let's name the list after what it contains. I'm thinking <code>points</code>.</p>\n\n<p>Creating a list and then manually appending every item could be rather slow for a large list - so lets create the list in one go. You could do this as a one liner - that way it's all in the first line and (assuming you don't word wrap) you can skip past it to the flesh of the program. But if we're going for neatness - I'd arrange it like this;</p>\n\n<pre><code>points = [\n (1,45,6),\n (7,8,5),\n (10,77,88),\n (99999,1,1),\n (5,7,6),\n (1,2,3),\n (4,5,6),\n]\n</code></pre>\n\n<p>This is pretty easy to generate - as all you need to do is:</p>\n\n<ul>\n<li>Write the header (<code>points = [</code>)</li>\n<li>The leading indentation, the value, then a trailing comma (<code>    {line},</code>)</li>\n<li>Then the footer (<code>]</code>).</li>\n<li>Then you can write the rest of the program as you were planning to anyway (In this case, <code>print(points)</code>).</li>\n</ul>\n\n<p>Note that trailing commas on the last item is accepted in python (some even encourage it, like myself) so you don't need to worry about detecting where you are in the file.</p>\n\n<p>Lastly, if you want to keep your main python code separate to your list - consider using imports. Assuming you call your generated file <code>points.py</code>, your main code could start with the following:</p>\n\n<pre><code>from points import points\nprint(points)\n</code></pre>\n\n<p>This has the advantage of not having to write your python code in a large C string.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T03:52:15.797", "Id": "222561", "ParentId": "222510", "Score": "8" } } ]
{ "AcceptedAnswerId": "222512", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T08:43:15.293", "Id": "222510", "Score": "10", "Tags": [ "c", "coordinate-system", "compiler" ], "Title": "Heavily limited premature compiler translates text into excecutable python code" }
222510
<p>I created this simple macro that works fine for its purpose: allow the user to create a list of updates that need to be made based on groups in a target table (to basically do mass updates). </p> <p>However, I am very concerned about the performance of this macro, it would take less time to do it manually if the list of updates becomes significantly long. I started optimizing the code using <strong>arrays</strong> but that seems not be enough.</p> <p>What I am going to look into next is the <strong>use of dictionaries</strong>, is anyone aware of the <strong>most optimal way</strong> to achieve this?</p> <pre><code>Sub UpdateManualUpdates() Application.ScreenUpdating = False Dim lookUpSheet As Worksheet, updateSheet As Worksheet Dim valueToSearch As String Dim i As Long, t As Long Set lookUpSheet = Worksheets("Manual price changes") Set updateSheet = Worksheets("Price Build-up") Dim lookUpSheetArray As Variant Dim updateSheetArray As Variant lastRowLookup = lookUpSheet.Cells(Rows.Count, "F").End(xlUp).Row lastRowUpdate = updateSheet.Cells(Rows.Count, "B").End(xlUp).Row lookUpSheetArray = lookUpSheet.Range("A1:F" &amp; lastRowLookup).Value updateSheetArray = updateSheet.Range("A1:AW" &amp; lastRowUpdate).Value For i = 6 To lastRowLookup 'i = 2 to last to omit the first row as that row is for headers valueType = lookUpSheetArray(i, 5) 'lookUpSheet.Cells(i, 5) 'Type of update - Both, Planning group or GC valueGroup = lookUpSheetArray(i, 3) 'Family group valueGC = lookUpSheetArray(i, 4) 'GC ValueChange = lookUpSheetArray(i, 6) 'What is the % change 'above get the values from the four column into variables For t = 6 To lastRowUpdate 'AW is column 49 target column to update 'M is target column for group, 13 'C is target column for GC, 3 If valueType = "Both" Then If updateSheetArray(t, 13) = valueGroup And updateSheetArray(t, 3) = valueGC Then updateSheet.Cells(t, 49) = ValueChange End If End If If valueType = "Planning group" Then If updateSheetArray(t, 13) = valueGroup Then updateSheet.Cells(t, 49) = ValueChange End If End If If valueType = "GC" Then If updateSheetArray(t, 3) = valueGC Then updateSheet.Cells(t, 49) = ValueChange End If End If Next t Next i Application.ScreenUpdating = True End Sub </code></pre>
[]
[ { "body": "<p>It looks like you'll have to set up three dictionaries that reference the same data. In your case, the dictionaries are based on your TARGET data that should change: <code>updateSheetArray</code>. You need three dictionaries because you want to access the data three different ways. The trick is in choosing a <strong><em>unique</em></strong> value from the data to be used as the key into the data. The first two values are simple, single column values: PlanningGroup and GC.</p>\n\n<p>Since one of your choices is \"Both\", you have to create a key from the data that combines both of those fields into a single value. This can be done on the worksheet itself in the form of a visible or hidden column (and thus also pulled into a memory array), or you can combine the fields in your VBA code. My preferred method for this is to combine the two (or more) fields into a single string in the code, though each situation is different. You can do a simple concatenate or concatenate with a delimiter, it does't matter.</p>\n\n<p>Before we get to the dictionary part of the answer, I will suggest a few items in the code review part of this answer.</p>\n\n<ol>\n<li><a href=\"https://www.excel-easy.com/vba/examples/option-explicit.html\" rel=\"nofollow noreferrer\">Always use <code>Option Explicit</code></a>. You might be doing this, but it's good to make sure it's visible in your questions (or answers) so it doesn't come up like this.</li>\n<li>Declare your variables as close as possible to the first use of the variable. It saves lots of back and forth searching for declarations, plus your code is now a little grouped into \"logic blocks\".</li>\n<li>Define constants for \"magic numbers\". These are typically a straight numerical value you've hard-coded into your routines. Any other developer that comes along will have to scratch their head to figure out why you're starting a loop from index 6. You also might need to use the same value in multiple places, so creating a <code>Const</code> once isolates the definition and then you only have to change it once.</li>\n</ol>\n\n<p>The constants I've defined for my example solution are:</p>\n\n<pre><code>Private Const LOOKUP_TYPE_COL As Long = 5\nPrivate Const LOOKUP_GROUP_COL As Long = 3\nPrivate Const LOOKUP_GC_COL As Long = 4\nPrivate Const LOOKUP_CHANGE_COL As Long = 6\nPrivate Const UPDATE_GROUP_COL As Long = 13\nPrivate Const UPDATE_GC_COL As Long = 3\nPrivate Const UPDATE_CHANGE_COL As Long = 49\nPrivate Const START_OF_LOOKUP_DATA As Long = 2\nPrivate Const START_OF_UPDATE_DATA As Long = 6\n</code></pre>\n\n<p>I've made these constants <code>Private</code> at the global module level, but they easily could be restricted in scope to the single <code>Sub</code> in the code. (The example <code>Sub</code> below is a bit long and I could have separated it into smaller functions, I'll leave that as an exercise for the reader :) ).</p>\n\n<p>One problem I noticed in your code is when you're calculating the last row. Your statement is good but you've missed a worksheet reference when using <code>Rows.Count</code>. Since the <code>Rows</code> is not qualified with a worksheet reference, it is counting the rows on the currently active sheet. My habit is to wrap the statement in a <code>With</code> block, just to make sure I have to correct reference:</p>\n\n<pre><code>Dim lookUpSheet As Worksheet\nDim lastRowLookup As Long\nDim lookUpSheetRange As Range\nDim lookUpSheetArray As Variant\nSet lookUpSheet = Worksheets(\"Manual price changes\")\nWith lookUpSheet\n lastRowLookup = .Cells(.Rows.Count, \"F\").End(xlUp).Row\n Set lookUpSheetRange = .Range(\"A1\").Resize(lastRowLookup, 6)\n lookUpSheetArray = lookUpSheetRange.value\nEnd With\n\nDim updateSheet As Worksheet\nDim lastRowUpdate As Long\nDim updateSheetRange As Range\nDim updateSheetArray As Variant\nSet updateSheet = Worksheets(\"Price Build-up\")\nWith updateSheet\n lastRowUpdate = .Cells(.Rows.Count, \"B\").End(xlUp).Row\n Set updateSheetRange = .Range(\"A1\").Resize(lastRowUpdate, 49)\n updateSheetArray = updateSheetRange.value\nEnd With\n</code></pre>\n\n<p>You are copying data from the worksheet <code>Range</code> into a memory-based array, and that will give you a much faster execution. The bonus is that you're not interacting with the screen, so <code>Application.ScreenUpdating = False</code> is not necessary. (You'll see another change to support this below)</p>\n\n<p>Now comes the <code>Dictionary</code> build up. We're working with your target data, which is the sheet that needs to be updated. You want to be able to find any row in your data with a single reference. I'm assuming the data on your <code>updateSheet</code> could be hundreds or thousands of lines long. Notice in the loop below that I'm creating three dictionaries, including using a combination key to pick up the option to reference entries for \"both\".</p>\n\n<p>Also, I figured that there could be more than one row in the data that may match the update criteria. So the dictionary keeps track by building a (string) list of row numbers to use later.</p>\n\n<pre><code>Dim groupKeys As Dictionary\nDim gcKeys As Dictionary\nDim bothKeys As Dictionary\nSet groupKeys = New Dictionary\nSet gcKeys = New Dictionary\nSet bothKeys = New Dictionary\n\nDim updateGroup As String\nDim updateGC As String\nDim bothKey As String\nDim existingList As String\nDim i As Long\nFor i = START_OF_UPDATE_DATA To UBound(updateSheetArray, 1)\n updateGroup = updateSheetArray(i, UPDATE_GROUP_COL)\n updateGC = updateSheetArray(i, UPDATE_GC_COL)\n\n If Not groupKeys.Exists(updateGroup) Then\n groupKeys.Add updateGroup, CStr(i)\n Else\n existingList = groupKeys(updateGroup)\n groupKeys(updateGroup) = existingList &amp; \",\" &amp; CStr(i)\n End If\n\n If Not gcKeys.Exists(updateGC) Then\n gcKeys.Add updateGC, CStr(i)\n Else\n existingList = gcKeys(updateGC)\n gcKeys(updateGC) = existingList &amp; \",\" &amp; CStr(i)\n End If\n\n bothKey = updateGroup &amp; updateGC\n If Not bothKeys.Exists(bothKey) Then\n bothKeys.Add bothKey, CStr(i)\n Else\n existingList = bothKeys(bothKey)\n bothKeys(bothKey) = existingList &amp; \",\" &amp; CStr(i)\n End If\nNext i\n</code></pre>\n\n<p>Now that we have the dictionaries complete, we only need a single pass through the <code>lookUpSheet</code> data. We'll get the list of rows from the selected dictionary, then update only those rows in the memory-based array <strong><em>NOT</em></strong> directly on the worksheet. So this inside loop is restricted to ONLY the rows needing updated values. This is where you get your other burst of speed.</p>\n\n<pre><code>Dim valueGroup As String\nDim valueGC As String\nDim valueType As String\nDim valueChange As Double\nDim updateRows As Variant\nFor i = START_OF_LOOKUP_DATA To UBound(lookUpSheetArray, 1)\n valueType = lookUpSheetArray(i, LOOKUP_TYPE_COL)\n valueGroup = lookUpSheetArray(i, LOOKUP_GROUP_COL)\n valueGC = lookUpSheetArray(i, LOOKUP_GC_COL)\n bothKey = valueGroup &amp; valueGC\n\n valueChange = lookUpSheetArray(i, LOOKUP_CHANGE_COL)\n\n updateRows = -1 'reset to a non-array value\n Select Case valueType\n Case \"Planning group\"\n If groupKeys.Exists(valueGroup) Then\n updateRows = Split(groupKeys(valueGroup), \",\")\n End If\n\n Case \"GC\"\n If gcKeys.Exists(valueGC) Then\n updateRows = Split(gcKeys(valueGC), \",\")\n End If\n\n Case \"Both\"\n If bothKeys.Exists(bothKey) Then\n updateRows = Split(bothKeys(bothKey), \",\")\n End If\n\n End Select\n\n '--- update the values if we found the rows to update\n If IsArray(updateRows) Then\n Dim j As Long\n For j = LBound(updateRows, 1) To UBound(updateRows, 1)\n updateSheetArray(CLng(updateRows(j)), UPDATE_CHANGE_COL) = valueChange\n Next j\n End If\nNext i\n</code></pre>\n\n<p>The final step is to copy the modified memory array back to the worksheet (which is why I created the <code>updateSheetRange</code> variable earlier).</p>\n\n<pre><code>updateSheetRange.value = updateSheetArray\n</code></pre>\n\n<p>Here is the whole solution in a single module:</p>\n\n<pre><code>Option Explicit\n\nPrivate Const LOOKUP_TYPE_COL As Long = 5\nPrivate Const LOOKUP_GROUP_COL As Long = 3\nPrivate Const LOOKUP_GC_COL As Long = 4\nPrivate Const LOOKUP_CHANGE_COL As Long = 6\nPrivate Const UPDATE_GROUP_COL As Long = 13\nPrivate Const UPDATE_GC_COL As Long = 3\nPrivate Const UPDATE_CHANGE_COL As Long = 49\nPrivate Const START_OF_LOOKUP_DATA As Long = 2\nPrivate Const START_OF_UPDATE_DATA As Long = 6\n\nSub UpdateManualUpdates()\n Dim lookUpSheet As Worksheet\n Dim lastRowLookup As Long\n Dim lookUpSheetRange As Range\n Dim lookUpSheetArray As Variant\n Set lookUpSheet = Worksheets(\"Manual price changes\")\n With lookUpSheet\n lastRowLookup = .Cells(.Rows.Count, \"F\").End(xlUp).Row\n Set lookUpSheetRange = .Range(\"A1\").Resize(lastRowLookup, 6)\n lookUpSheetArray = lookUpSheetRange.value\n End With\n\n Dim updateSheet As Worksheet\n Dim lastRowUpdate As Long\n Dim updateSheetRange As Range\n Dim updateSheetArray As Variant\n Set updateSheet = Worksheets(\"Price Build-up\")\n With updateSheet\n lastRowUpdate = .Cells(.Rows.Count, \"B\").End(xlUp).Row\n Set updateSheetRange = .Range(\"A1\").Resize(lastRowUpdate, 49)\n updateSheetArray = updateSheetRange.value\n End With\n\n '--- build up the dictionaries for the UPDATE array where the keys\n ' are single or multiple fields and the entry is CSV list of\n ' row numbers that match the given key\n Dim groupKeys As Dictionary\n Dim gcKeys As Dictionary\n Dim bothKeys As Dictionary\n Set groupKeys = New Dictionary\n Set gcKeys = New Dictionary\n Set bothKeys = New Dictionary\n\n Dim updateGroup As String\n Dim updateGC As String\n Dim bothKey As String\n Dim existingList As String\n Dim i As Long\n For i = START_OF_UPDATE_DATA To UBound(updateSheetArray, 1)\n updateGroup = updateSheetArray(i, UPDATE_GROUP_COL)\n updateGC = updateSheetArray(i, UPDATE_GC_COL)\n\n If Not groupKeys.Exists(updateGroup) Then\n groupKeys.Add updateGroup, CStr(i)\n Else\n existingList = groupKeys(updateGroup)\n groupKeys(updateGroup) = existingList &amp; \",\" &amp; CStr(i)\n End If\n\n If Not gcKeys.Exists(updateGC) Then\n gcKeys.Add updateGC, CStr(i)\n Else\n existingList = gcKeys(updateGC)\n gcKeys(updateGC) = existingList &amp; \",\" &amp; CStr(i)\n End If\n\n bothKey = updateGroup &amp; updateGC\n If Not bothKeys.Exists(bothKey) Then\n bothKeys.Add bothKey, CStr(i)\n Else\n existingList = bothKeys(bothKey)\n bothKeys(bothKey) = existingList &amp; \",\" &amp; CStr(i)\n End If\n Next i\n\n '--- now compare each row of the lookup data to find it in the update\n ' data and make the appropriate change to the memory array\n Dim valueGroup As String\n Dim valueGC As String\n Dim valueType As String\n Dim valueChange As Double\n Dim updateRows As Variant\n For i = START_OF_LOOKUP_DATA To UBound(lookUpSheetArray, 1)\n valueType = lookUpSheetArray(i, LOOKUP_TYPE_COL)\n valueGroup = lookUpSheetArray(i, LOOKUP_GROUP_COL)\n valueGC = lookUpSheetArray(i, LOOKUP_GC_COL)\n bothKey = valueGroup &amp; valueGC\n\n valueChange = lookUpSheetArray(i, LOOKUP_CHANGE_COL)\n\n updateRows = -1 'reset to a non-array value\n Select Case valueType\n Case \"Planning group\"\n If groupKeys.Exists(valueGroup) Then\n updateRows = Split(groupKeys(valueGroup), \",\")\n End If\n\n Case \"GC\"\n If gcKeys.Exists(valueGC) Then\n updateRows = Split(gcKeys(valueGC), \",\")\n End If\n\n Case \"Both\"\n If bothKeys.Exists(bothKey) Then\n updateRows = Split(bothKeys(bothKey), \",\")\n End If\n\n End Select\n\n '--- update the values if we found the rows to update\n If IsArray(updateRows) Then\n Dim j As Long\n For j = LBound(updateRows, 1) To UBound(updateRows, 1)\n updateSheetArray(CLng(updateRows(j)), UPDATE_CHANGE_COL) = valueChange\n Next j\n End If\n Next i\n\n '--- all of the requested updates are complete, copy the array back to the worksheet\n updateSheetRange.value = updateSheetArray\nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-03T09:44:09.243", "Id": "432939", "Score": "0", "body": "Hi, thanks this looks and functions very fast. However when the macro finishes to run it deletes all formulas and tables from the updated sheet. Do you know the reason?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-28T15:01:49.483", "Id": "223148", "ParentId": "222517", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T11:20:14.200", "Id": "222517", "Score": "3", "Tags": [ "vba", "excel" ], "Title": "Update a table based on other table" }
222517
<p>I was trying to write Sieve for the first time and I came up with this code:</p> <pre><code>def sieve(num): numbers = set(range(3, num, 2)) for i in range(3, int(num**(1/2)) + 1 , 2): num_set = set(i*c for c in range(3, num//2, 2)) numbers = numbers - num_set return list(sorted((2, *numbers))) </code></pre> <p>The problem is that for <code>num &gt; 10**6</code> the time to create prime numbers increases. </p> <p><strong>Also, when I tried <code>num = 10**8</code> my computer stopped working, started to make awkward noises and I had to restart it.</strong> </p> <p>I think the problem is that I am dealing with sets. For large numbers (for instance, in <code>num = 10**8</code> case) the set cannot be produced since my computer cannot process that much information, hence it stops.</p> <p>Is there a way to solve this memory or time problem using my code or should use a different algorithm?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T13:52:50.747", "Id": "430759", "Score": "3", "body": "Say each number in a set in Python takes up 80 bytes - 10 64bit registers - then your program is going to need 10GB of memory. What, you don't have 10GB of memory, well then your PC's just offed itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T15:54:50.880", "Id": "430789", "Score": "5", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T19:42:09.380", "Id": "430834", "Score": "0", "body": "@Vogel612 I am sorry, I did not know that. I'll be more careful from now on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T20:09:34.980", "Id": "430842", "Score": "0", "body": "Is this Python 2 or 3? The `//` implies 3 to me, but I'd like that confirmed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T20:45:56.643", "Id": "430848", "Score": "0", "body": "@NicHartley The `*numbers` uses the unpacking operator, which is only in Python3" } ]
[ { "body": "<p>I think your performance problems at 10**6 elements start here:</p>\n\n<pre><code>for i in range(3, int(num**(1/2)) + 1 , 2):\n</code></pre>\n\n<p>This generates a list of numbers that you then build a set of multiples from and remove those multiples from the numbers set. But this generates a set [3,5,7,9,11,13,15,...] so when you've removed all the multiples of 3 you still try and remove multiples of [9,15,21,...] all of which went when you removed the multiples of three.</p>\n\n<p>In a classic implementation of sieve you would find the next smallest prime and remove that, then find the next smallest prime and remove that until you get to the square root of num.</p>\n\n<p>For example with num = 25 :</p>\n\n<ul>\n<li>[], [3,5,7,9,11,13,15,17,19,21,23,25] -- remove multiples of 3</li>\n<li>[3], [5,7,11,13,17,19,23,25] - 5 is next lowest so remove its multiples </li>\n<li>[3,5], [7,11,13,17,19,23] - we've reached the square root\nof num, only primes left</li>\n</ul>\n\n<p>So after each removal you want to find the new minimal element left in numbers but the problem with the set is that it's unordered so operation like min() is an O(N) operation, the entire set has to be scanned. You may be able to get round this by looking for an OrderedSet implementation, in which case each time you find a prime you remove it's multiples, remove the prime itself to a separate set say, and the next prime to remove is the minimal value in the numbers set.</p>\n\n<p>As Peilonrayz points out in a comment, when you start to get toward 10*8 elements you need to think about how much memory these sets are going to need. You might well need a data structure that uses a lot less memory.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T15:46:45.990", "Id": "430786", "Score": "0", "body": "thanks my code now runs 8x faster. It can calculate up to `10**6` in 3.5 sec" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T20:10:41.520", "Id": "430843", "Score": "1", "body": "Depending on the Python version, this might or might not generate a `list` (the Python type). I'm pretty sure this is Python 3, which means that, no, memory isn't a concern with the `range` statement, as it'll always be stored as just 3 ints in a special object, and the iterator will probably just store 1 int (the index). It's still a _performance_ concern to hit all those unnecessary numbers, of course, just not a _memory_ one. What might be causing memory issues is the `set(...)` bit, which _does_ store that whole thing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T20:57:03.467", "Id": "430850", "Score": "0", "body": "@ I agree with you" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T13:28:17.887", "Id": "222528", "ParentId": "222518", "Score": "9" } }, { "body": "<blockquote>\n <p>Is there a way to solve this memory or time problem using my code or should use a different algorithm?</p>\n</blockquote>\n\n<p>The <em>algorithm</em> is fine for the kind of scale you're talking about. It's the <em>implementation</em> of the algorithm which needs optimisation.</p>\n\n<p>To tackle the memory issue, look at <code>set</code>. Given that the elements of the set are integers from a fixed range and moderately dense in that range (about 1 in 18 numbers up to <span class=\"math-container\">\\$10^8\\$</span> are prime) the ideal would be a data structure which uses 1 bit per number. (I'm not sure whether one is available in Python. In the worst case, since it has big integers you can use bit manipulations on numbers). But failing that, a simple array of Boolean values probably has less overhead than a set.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>return list(sorted((2, *numbers)))\n</code></pre>\n</blockquote>\n\n<p>This is actually quite heavy-weight. It's probably not the bottleneck, but it might be worth asking yourself whether the caller needs a list. Perhaps you can use <code>yield</code> inside the main loop and skip the post-processing altogether. Perhaps the memory pressure isn't so bad as to prevent you from accumulating the list in order. And if the memory pressure is a problem, perhaps you can break the set into <em>pages</em>, something like (<strong>warning:</strong> code not tested, and this doesn't include the other ideas I've mentioned):</p>\n\n<pre><code>primes = [2]\npage_size = 1000000\nfor page_start in range(3, num, page_size):\n page_end = min(num, page_start + page_size)\n page = set(range(page_start, page_end, 2))\n for p in primes:\n remove multiples of p from page\n for p in range(page_start, page_end, 2):\n if p in page:\n primes.append(p)\n remove multiples of p from page\n</code></pre>\n\n<hr>\n\n<p>Note: I've thrown out several ideas. I understand that you're doing this as a learning exercise, and trying out various different directions should be useful for that purpose even if you conclude that there isn't enough benefit to compensate for the added complexity.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T19:59:19.667", "Id": "430839", "Score": "0", "body": "In general I dont need to turn set into list however when I need indexing, for instance, I will need to turn it to list. I dont know much anything about the bit manupilation..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T00:13:10.447", "Id": "430864", "Score": "0", "body": "[My versions](https://codereview.stackexchange.com/q/221659) which uses a Boolean list can't work with \\$n=10^8\\$ with 32GB of memory. Chunking up the values is a good idea tho, probably could get it so it uses a list with vectorization pretty easily." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T16:39:25.350", "Id": "222534", "ParentId": "222518", "Score": "10" } }, { "body": "<p>Using a <code>set()</code> is your bottleneck, memory-wise.</p>\n\n<pre><code>&gt;&gt;&gt; numbers = set(range(3, 10**8, 2))\n&gt;&gt;&gt; sys.getsizeof(numbers)\n2147483872\n&gt;&gt;&gt; sys.getsizeof(numbers) + sum(map(sys.getsizeof, numbers))\n3547483844\n</code></pre>\n\n<p>A <code>set</code> of odd numbers up to 100 million is consuming <strike>2GB</strike> 3.5GB (thank-you @ShadowRanger) of memory. When you do an operation like <code>numbers = numbers - num_set</code>, you'll need to have 3 sets in memory at once. One for the original set, one for the set of numbers you are removing, and one for the resulting set. This will be greater than <strike>4GB</strike> 7GB of memory, since some of the numbers you are removing aren't in the original set.</p>\n\n<p>You don't need to realize the entire set of numbers you are removing in memory. You could simply remove the numbers from the set one at a time:</p>\n\n<pre><code>for c in range(3, num // 2, 2):\n numbers.remove(i * c)\n</code></pre>\n\n<p>This is modifying the set in place, so the memory requirement will not exceed the initial 2GB of memory for the set.</p>\n\n<hr>\n\n<p>Why are you looping <code>c</code> over <code>range(3, num // 2, 2)</code>? This is doing way too much work. The maximum value <code>c</code> should obtain should satisfy <code>i*c &lt; num</code>, since no product <code>i*c</code> larger than <code>num</code> will be in the original set.</p>\n\n<p>You should instead loop over <code>range(3, num // i + 1, 2)</code>. This will decrease the size of the set of numbers you are removing as the prime numbers you find increase.</p>\n\n<hr>\n\n<p>Why start removing primes at <code>3*i</code>? When <code>i</code> is 97, you've already removed multiples of 3, 5, 7, 11, 13, 17, ... up to 89. The first multiple you need to remove is <code>97*97</code>. You would then continue with <code>99*97</code>, <code>101*97</code>, and so on, up to <code>num</code>. So the <code>range</code> should begin with <code>i</code>, not <code>3</code>. </p>\n\n<pre><code>for c in range(i, num // i + 1, 2):\n numbers.remove(i * c)\n</code></pre>\n\n<p>Actually, this is still too complicated. Let's get rid of the multiplication. This also greatly simplifies the upper limit of the range.</p>\n\n<pre><code>for multiple in range(i*i, num, 2*i):\n numbers.remove(multiple)\n</code></pre>\n\n<p>Or equivalently, passing a generator to <code>difference_update</code> to remove items in bulk, but without realizing the set of numbers to be removed in memory simultaneously.</p>\n\n<pre><code>numbers.difference_update(multiple for multiple in range(i*i, num, 2*i))\n</code></pre>\n\n<hr>\n\n<p>Even with all of the above changes, you still require 2GB of memory to compute the primes up to 100 million. And since a <code>set</code> is unordered, you still have to <code>sort</code> the surviving numbers afterwards to get your ordered list of primes.</p>\n\n<p>A better way is to maintain an array of flags, one per candidate number. With 100 million candidate numbers, if each flag used only a single byte, you'd only require 100 MB of memory, a savings of a factor of 20. And since the array of flags is ordered, no sorting of the array would be required.</p>\n\n<p>The <a href=\"https://docs.python.org/3.7/library/stdtypes.html?highlight=bytearray#bytearray\" rel=\"nofollow noreferrer\"><code>bytearray</code></a> is one such structure. It is an array of bytes. You can store your candidates in the array as a <code>1</code>, and any non-primes (multiples of other primes) as <code>0</code>.</p>\n\n<pre><code>def sieve(num):\n flags = bytearray(num) # Initially, all bytes are zero\n\n flags[2] = 1 # Two is prime\n for i in range(3, num, 2):\n flags[i] = 1 # Odd numbers are prime candidates\n\n # Find primes and eliminate multiples of those primes\n for i in range(3, int(num ** 0.5) + 1, 2):\n if flags[i]:\n for multiple in range(i * i, num, 2 * i):\n flags[multiple] = 0\n\n return [ i for i, flag in enumerate(flags) if flag ]\n</code></pre>\n\n<hr>\n\n<p>Conserving a little bit more memory, you can store your list of primes in an <a href=\"https://docs.python.org/3.7/library/array.html\" rel=\"nofollow noreferrer\"><code>array</code></a></p>\n\n<pre><code>import array\n\ndef sieve(num):\n flags = bytearray(num) # Initially, all bytes are zero\n\n flags[2] = 1 # Two is prime\n for i in range(3, num, 2):\n flags[i] = 1 # Odd numbers are prime candidates\n\n # Find primes and eliminate multiples of those primes\n for i in range(3, int(num ** 0.5) + 1, 2):\n if flags[i]:\n for multiple in range(i * i, num, 2 * i):\n flags[multiple] = 0\n\n return array.array('I', (i for i, flag in enumerate(flags) if flag))\n</code></pre>\n\n<p>For primes up to <span class=\"math-container\">\\$10^8\\$</span>, the <code>array.array('I', ...)</code> stores the 5.7 million primes in a mere 23MB of memory. The list version takes a whopping 212MB.</p>\n\n<p><strong>Note</strong>: If you are using a 32-bit version of Python, you may need the type-code <code>'L'</code> instead of <code>'I'</code> to get storage for 4-byte integers in the array.</p>\n\n<hr>\n\n<p>For the truly memory conscious, install the <code>bitarray</code> module.</p>\n\n<pre><code>pip3 install bitarray\n</code></pre>\n\n<p>In addition to using only a single bit per flag, for 1/8th the memory usage in the sieve, it allows some truly fantastic slice assignments from a single boolean scalar, which makes clearing all multiples of a prime number into a simple single statement.</p>\n\n<pre><code>import array\nfrom bitarray import bitarray\n\ndef sieve(num):\n\n flags = bitarray(num)\n flags.setall(False)\n flags[2] = True # Two is prime\n flags[3::2] = True # Odd numbers are prime candidates\n\n for i in range(3, int(num ** 0.5) + 1, 2):\n if flags[i]:\n flags[i*i:num:2*i] = False # Eliminate multiples of this prime\n\n primes = array.array('I', (i for i, flag in enumerate(flags) if flag))\n\n return primes\n</code></pre>\n\n<p>Timings:</p>\n\n<pre><code>10^3: 0.000\n10^4: 0.000\n10^5: 0.004\n10^6: 0.051\n10^7: 0.428\n10^8: 4.506\n</code></pre>\n\n<p><strong>Note</strong>: Updated timing info. I just noticed I had <code>for i in range(3, num + 1, 2)</code> in the last implementation instead of <code>for i in range(3, int(num ** 0.5) + 1, 2)</code>, resulting in a lot of wasted time doing nothing.</p>\n\n<p><strong>Python 3.8 Update</strong>: Using <a href=\"https://docs.python.org/3/library/math.html?highlight=isqrt#math.isqrt\" rel=\"nofollow noreferrer\"><code>math.isqrt(num)</code></a> is better than <code>int(num ** 0.5)</code>:</p>\n\n<pre><code> for i in range(3, math.isqrt(num) + 1, 2):\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T03:43:52.413", "Id": "430869", "Score": "2", "body": "A note: `sys.getsizeof(numbers)` is only telling you the size of the `set` structure itself, not all the `int`s stored in it. The very smallest `int`s are singletons, (CPython implementation detail), but you'd have to pay the memory cost of all the rest, so the memory used is `sys.getsizeof(numbers) + sum(map(sys.getsizeof, numbers))`, which on a 64 bit build of Python adds just shy of another 1.4 GB of memory onto the cost, starting at 28 bytes per `int` for magnitudes of 30 bits and below, adding four more bytes for every additional 30 bits of magnitude or part thereof." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T05:14:24.867", "Id": "430875", "Score": "0", "body": "@ShadowRanger Excellent point. I did that for the list to get the 212MB, but neglected to do so for the `numbers` set." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T11:03:13.690", "Id": "430916", "Score": "0", "body": "Great answer. Exactly what I needed. I actually changed my code a bit after the Jackson's answer (that range parts). However it was against the rules so I couldn't change my code in the post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T13:12:53.777", "Id": "430926", "Score": "0", "body": "What does `flags[i*i:num:2*i]` do exactly? You say it removes multiples of a prime, but I'm not exactly sure how this notation works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T13:50:56.817", "Id": "430931", "Score": "2", "body": "@Nzall `flags[start:stop:step]` references a “slice” of the `flags` bit array, beginning with the `start` element, then the `start+step` element, then the `start+2*step` element, all the way up to (but not including) the `stop` element. Since we start at a multiple of the current prime, and go up by a multiple of the prime, these elements all have indices which are multiples of the prime. The `= False` assigns all of those elements in the bit array to false, which doesn’t remove those elements, but flags them as not prime candidates, so “removes” them from consideration." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T14:46:53.123", "Id": "430935", "Score": "1", "body": "@AJNeufeld I see. I now also realize that you start at the square of the prime because every multiple of the prime before that has already been falsified by earlier prime falsifications." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T14:50:55.100", "Id": "430936", "Score": "0", "body": "For `flags = bytearray(num)` you might want to look at `type(flags[0])` and `sys.getsizeof(flags[0)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T15:28:33.040", "Id": "430943", "Score": "0", "body": "@DavidCullen You might want to try `flags[0] = 300`. Even though `flags[0]` returns an integer (`type(flags[0])` returns `<class 'int'>`), it can only hold a value between 0 and 255, because the storage for it is a single byte. Compare `sys.getsizeof(bytearray(1))` and `sys.getsizeof(bytearray(1001))`. 57 bytes of overhead, but then 1 byte of memory per element in the array." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T02:04:58.433", "Id": "222556", "ParentId": "222518", "Score": "21" } } ]
{ "AcceptedAnswerId": "222556", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T11:30:25.227", "Id": "222518", "Score": "13", "Tags": [ "python", "performance", "python-3.x", "primes", "sieve-of-eratosthenes" ], "Title": "Prime sieve in Python" }
222518
<p>I am writing a class for delayed operations on variables which are resolved at a later time. I am using pythons operator overloading but my class definition seems very boilerplatey.</p> <p>Is there a more succinct way to define the following class?</p> <pre><code>from functools import partialmethod import operator class Forward: def resolve(self, env): raise NotImplementedError() def op(self, op, rhs): if not isinstance(rhs, Forward): raise TypeError('"{}" not of type `Forward`'.format(rhs)) return Evaluation(op, self, rhs) __eq__ = partialmethod(op, operator.__eq__) __gt__ = partialmethod(op, operator.__gt__) __lt__ = partialmethod(op, operator.__lt__) __ge__ = partialmethod(op, operator.__ge__) __le__ = partialmethod(op, operator.__le__) __add__ = partialmethod(op, operator.__add__) __sub__ = partialmethod(op, operator.__sub__) __mul__ = partialmethod(op, operator.__mul__) __truediv__ = partialmethod(op, operator.__truediv__) __floordiv__ = partialmethod(op, operator.__floordiv__) __pow__ = partialmethod(op, operator.__pow__) __iadd__ = partialmethod(op, operator.__iadd__) __isub__ = partialmethod(op, operator.__isub__) __imul__ = partialmethod(op, operator.__imul__) __itruediv__ = partialmethod(op, operator.__itruediv__) __ifloordiv__ = partialmethod(op, operator.__ifloordiv__) __ipow__ = partialmethod(op, operator.__ipow__) class Evaluation(Forward): def __init__(self, op, lhs, rhs): self.op = op self.lhs = lhs self.rhs = rhs def resolve(self, env): return self.op(self.lhs.resolve(env), self.rhs.resolve(env)) class Constant(Forward): def __init__(self, value): self.value = value def resolve(self, env): return self.value class Variable(Forward): def __init__(self, name): self.name = name def resolve(self, env): return env[self.name] if __name__ == "__main__": print((Variable('a') + Variable('b')).resolve({'a': 1, 'b': 2}) </code></pre> <p>This code is part of a larger project which operates on time series data, I wanted a small way to add conditions that would evaluate whether or not to perform some other action based on the data (<code>env</code>) at that time, for example.</p> <pre><code># All stages in a `pipeline` run each time a new entry is available. # Log when simply logs the current data when `func` returns `True`. pipeline.add(LogWhen(level=error, func=Variable('cash') &lt; Constant(0))) </code></pre> <p>I have included enough code to demonstrate the purpose of this code but I am mainly concerned with defining the <strong>magic_methods</strong> on the <code>Forward</code> class. However review on any parts of the code is welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T13:05:22.810", "Id": "430744", "Score": "0", "body": "I Didn't want to add the full code as it was just adding methods to the class that I wasn't entirely happy with, a full example with some testcases can be seen here https://gist.github.com/justinfay/de189fc136ebf3d11261106b6f50bce5" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T14:04:41.270", "Id": "430762", "Score": "2", "body": "I think your question could be improved by including at least a few lines of the test/example code so that people that are interested in your question see what it is about without looking at the repo." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T11:59:34.187", "Id": "222520", "Score": "2", "Tags": [ "python", "python-3.x", "overloading" ], "Title": "Python adding partialmethods to a class at compile time" }
222520
<p>I'm just finished my version of iterable hashtable. I want to review code in general (code style, data structures, remarks about the algorithms) and I have some questions:</p> <ol> <li>I don't know how to implement errors in return-value way. So, I chose way when we contain error flag variable in struct. Is it correct? </li> <li>What functions are missing in interface? Maybe <code>pop()</code> or something like this?</li> <li>Where do I need includind headers like <code>stddef.h</code> or <code>string.h</code>? (e.g. I don't use functions from <code>string.h</code> in my header, do I need include it in <code>htable.h</code>?)</li> </ol> <p><strong>htable.h</strong>:</p> <pre><code>#ifndef HTABLE_H #define HTABLE_H #include &lt;stdio.h&gt; #include &lt;stddef.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;stdint.h&gt; #include &lt;stdbool.h&gt; typedef struct node_t { void* el; struct node_t* nextp; } node_t; typedef enum hterror_t { HTE_OK, HTE_MEM_EXHAUST, HTE_REMOVE, HTE_TOTAL } hterror_t; typedef struct index_t index_t; enum { HTABLE_SIZE = 8191 }; typedef struct htable_t { node_t* table[HTABLE_SIZE]; index_t* indexes; hterror_t err_f; uint32_t (*hash)(void *); int32_t (*cmp)(void *, void *); } htable_t; htable_t* htable_create(uint32_t (*hash)(void *), int32_t (*cmp)(void *, void *)); node_t* htable_lookup(htable_t* ht, void* el, bool create); void htable_remove(htable_t* ht, void* el); void htable_foreach(htable_t* ht, void (*fn)(node_t *, void *), void *arg); void htable_destroy(htable_t* ht); #endif // HTABLE_H </code></pre> <p><strong>htable.c</strong>:</p> <pre><code>#include "htable.h" typedef struct index_t { size_t index; struct index_t* nextp; } index_t; htable_t* htable_create(uint32_t (*hash)(void *), int32_t (*cmp)(void *, void *)) { htable_t* htable = malloc(sizeof(htable_t)); if (htable == NULL) return NULL; memset(htable-&gt;table, 0, sizeof(htable-&gt;table[0]) * HTABLE_SIZE); htable-&gt;indexes = NULL; htable-&gt;err_f = HTE_OK; htable-&gt;hash = hash; htable-&gt;cmp = cmp; return htable; } node_t* htable_lookup(htable_t* ht, void* el, bool create) { node_t* tmp; uint32_t h; h = ht-&gt;hash(el) % HTABLE_SIZE; for (tmp = ht-&gt;table[h]; tmp != NULL; tmp = tmp-&gt;nextp) if (ht-&gt;cmp(tmp-&gt;el, el) == 0) return tmp; if (create) { if (ht-&gt;table[h] == NULL) { /* if there's no node for hash h */ index_t* ni = malloc(sizeof(index_t)); if (ni == NULL) { ht-&gt;err_f = HTE_MEM_EXHAUST; return NULL; } ni-&gt;index = h; ni-&gt;nextp = ht-&gt;indexes; ht-&gt;indexes = ni; } node_t* newnode = malloc(sizeof(node_t)); if (newnode == NULL) { ht-&gt;err_f = HTE_MEM_EXHAUST; return NULL; } newnode-&gt;el = el; newnode-&gt;nextp = ht-&gt;table[h]; ht-&gt;table[h] = newnode; } return tmp; } void htable_remove(htable_t* ht, void* el) { node_t* p, * prev; uint32_t h; h = ht-&gt;hash(el) % HTABLE_SIZE; prev = NULL; for (p = ht-&gt;table[h]; p != NULL; p = p-&gt;nextp) { if (ht-&gt;cmp(p-&gt;el, el) == 0) { if (prev == NULL) ht-&gt;table[h] = p-&gt;nextp; else prev-&gt;nextp = p-&gt;nextp; free(p); return ; } prev = p; } ht-&gt;err_f = HTE_REMOVE; } void htable_foreach(htable_t* ht, void (*fn)(node_t *, void *), void *arg) { index_t* prev, * p; node_t* cur_n; prev = NULL; for (p = ht-&gt;indexes; p != NULL; p = p-&gt;nextp) { if (ht-&gt;table[p-&gt;index] == NULL) { if (prev == NULL) { ht-&gt;indexes = p-&gt;nextp; free(p); p = ht-&gt;indexes; } else { prev-&gt;nextp = p-&gt;nextp; free(p); p = prev; } } for (cur_n = ht-&gt;table[p-&gt;index]; cur_n != NULL; cur_n = cur_n-&gt;nextp) fn(cur_n, arg); } } void htable_destroy(htable_t* ht) { index_t* buf_i; for (; ht-&gt;indexes != NULL; ht-&gt;indexes = buf_i) { buf_i = ht-&gt;indexes-&gt;nextp; if (ht-&gt;table[ht-&gt;indexes-&gt;index] != NULL) { node_t* buf_n; for (; ht-&gt;table[ht-&gt;indexes-&gt;index] != NULL; ht-&gt;table[ht-&gt;indexes-&gt;index] = buf_n) { buf_n = ht-&gt;table[ht-&gt;indexes-&gt;index]-&gt;nextp; free(ht-&gt;table[ht-&gt;indexes-&gt;index]); } } free(ht-&gt;indexes); } free(ht); } </code></pre> <p>Simple usage of htable:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdint.h&gt; #include &lt;math.h&gt; #include "htable.h" /* ihash and icmp are needed for construct htable */ uint32_t ihash(void* y) { uint32_t x = *(uint32_t *) y; x = ((x &gt;&gt; 16) ^ x) * 0x45d9f3b; x = ((x &gt;&gt; 16) ^ x) * 0x45d9f3b; x = (x &gt;&gt; 16) ^ x; return x; } int32_t icmp(void* a, void* b) { return *(int *) a - *(int *) b; } /* icopy, ifree and iprint are not necessary */ void* icopy(void* i) { int* _i = malloc(sizeof(int)); if (_i == NULL) return NULL; *_i = *(int *) i; return _i; } void ifree(node_t* n, void* arg) { (void) arg; if (n-&gt;el != NULL) free(n-&gt;el); } void iprint(node_t* np, void* arg) { printf((char *) arg, (np == NULL) ? 0 : *(int *) np-&gt;el); } int main() { htable_t* ht = htable_create(ihash, icmp); for (int i = 0; i &lt; 255; ++i) htable_lookup(ht, icopy(&amp;i), true); int k = 12; iprint(htable_lookup(ht, &amp;k, false), "lookup: %d\n"); ifree(htable_lookup(ht, &amp;k, false), NULL); htable_remove(ht, &amp;k); iprint(htable_lookup(ht, &amp;k, false), "lookup: %d\n"); /* returns NULL */ htable_foreach(ht, iprint, "foreach: %d\n"); htable_foreach(ht, ifree, NULL); /* freeing memory that we allocated from the loop above */ htable_destroy(ht); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T14:34:02.027", "Id": "430765", "Score": "1", "body": "Could you please include code that calls these functions so that we can perform a better review?" } ]
[ { "body": "<ul>\n<li><p>Combining lookup and insertion functionality in one function looks like an unnecessary violation of SRP. I strongly recommend to separate them.</p></li>\n<li><p>Keeping the error inside the structure is indeed questionable. Notice that once you split lookup and insert, <code>return errcode;</code> becomes natural: every function besides <code>insert</code> would just return an error code, and <code>insert</code> would return <code>NULL</code> on failure.</p>\n\n<p>If you still want to keep the error flag, you should at least clear it in the beginning of any function which may set it, and provide a function to check it. As of now, the client must directly access <code>ht-&gt;err_f</code>, which breaks the encapsulation.</p></li>\n<li><p>Speaking of encapsulation, the standard practice is to forward declare <code>typedef struct htable_t htable_t;</code> in the <code>htable.h</code>, and define it in <code>htable.c</code>. The client has no business knowing how exactly the table is organized.</p></li>\n<li><p><code>htable_foreach</code> apparently attempts to compact the list of indices. It is a very strange place to do so. Removing an index is more natural in <code>htable_remove</code>. Meanwhile, I am not sure what benefits does the list of indices provide.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T06:40:25.083", "Id": "430884", "Score": "0", "body": "Thank you for the answer!\n\nI saw this method (when we putting insert and lookup in one function) in book \"The Practice of Programming\" (c.2, p.56). Now I understand that way that used in the book is intended for concrete data, and not for abstract data.t.\n\nI remove indices in `foreach()` function because I think it will be faster to remove items like this, rather than going through the list every time when we calling `remove()`. Also, if you don't need to iterate over the table, you'll never remove indieces, except the call function `destroy()`.\n\nCorrect me if I'm wrong. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T10:38:09.603", "Id": "430912", "Score": "0", "body": "SRP acronym deserves definition/link" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T12:35:33.503", "Id": "430922", "Score": "0", "body": "I think he meant The Single Responsibility Principle from SOLID" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T17:26:24.730", "Id": "222537", "ParentId": "222521", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T12:27:34.010", "Id": "222521", "Score": "4", "Tags": [ "beginner", "algorithm", "c", "iterator", "hash-map" ], "Title": "Iterable hashtable implementation in C" }
222521
<p><strong>I have set of points on the coordinate plane. I need to find the 4 points which form a square with the biggest area.</strong></p> <p>I'm new in JavaScript so I'd like to get any suggestions about code style, patterns, code idioms, etc. Thank you in advance!</p> <pre><code>"use strict"; /* * Point */ (function() { function numbersEqual(a, b) { return Math.abs(a - b) &lt; Number.EPSILON; } function Point(x, y) { this.x = x; this.y = y; } Point.distance = function(a, b) { return Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2); } Point.equal = function(a, b) { return numbersEqual(a.x, b.x) &amp;&amp; numbersEqual(a.y, b.y); } Point.pointsFormsQuadrangle = function(a, b, c, d) { if (Point.equal(a, b) || Point.equal(a, c) || Point.equal(a, d)) return false; if (Point.equal(b, c) || Point.equal(b, d)) return false; if (Point.equal(c, d)) return false; const center = new Point((a.x + b.x + c.x + d.x) / 4, (a.y + b.y + c.y + d.y) / 4); const ac = Point.distance(a, center); const bc = Point.distance(b, center); const cc = Point.distance(c, center); const dc = Point.distance(d, center); return numbersEqual(ac, bc) &amp;&amp; numbersEqual(bc, cc) &amp;&amp; numbersEqual(cc, dc); } Point.pointsFormsSquare = function(a, b, c, d) { if (!Point.pointsFormsQuadrangle(a, b, c, d)) return false; const ab = Point.distance(a, b) const ac = Point.distance(a, c); const ad = Point.distance(a, d); const triangle = [ab, ac, ad].sort((a, b) =&gt; a - b); return numbersEqual(triangle[0], triangle[1]); } window.Point = Point; })(); /* * Square */ (function () { function Square(a, b, c, d) { this.a = a; this.b = b; this.c = c; this.d = d; } Square.prototype.area = function() { const findSquareDiagonalLength = (a, b, c, d) =&gt; { const ab = Point.distance(a, b); const ac = Point.distance(a, c); const ad = Point.distance(a, d); return Math.max(ab, ac, ad); }; const d = findSquareDiagonalLength(this.a, this.b, this.c, this.d); return d * d / 2; } window.Square = Square; })(); /* * Solution */ function formSquaresFromPoints(points) { let squares = []; for (let a = 0; a &lt; points.length; a++) for (let b = a + 1; b &lt; points.length; b++) for (let c = b + 1; c &lt; points.length; c++) for (let d = c + 1; d &lt; points.length; d++) if (Point.pointsFormsSquare(points[a], points[b], points[c], points[d])) squares.push(new Square(points[a], points[b], points[c], points[d])); return squares; } function sortSquaresByArea(squares) { squares.sort((a, b) =&gt; { if (a.area() &gt; b.area()) return 1; else if (a.area() &lt; b.area()) return -1; else return 0; }); return squares; } const POINTS = [ new Point(1, 1), new Point(1, 3), new Point(3, 1), new Point(3, 3), new Point(1, 6), new Point(6, 1), new Point(6, 6), new Point(1, 9), new Point(9, 1), new Point(9, 9), new Point(4, 5), new Point(4, 8), new Point(7, 8), new Point(7, 5), new Point(6, 3), new Point(5, 3), new Point(5, 1) ]; const sortedSquares = sortSquaresByArea(formSquaresFromPoints(POINTS)); const squareWithBiggestArea = sortedSquares[sortedSquares.length - 1]; console.log(squareWithBiggestArea); // Gives: {(1, 1), (1, 9), (9, 1), (9, 9)} </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T17:55:17.213", "Id": "430805", "Score": "0", "body": "This is written as a piece of art." } ]
[ { "body": "<p>I have some nitpicks to talk about before getting in a bigger thing :</p>\n\n<ul>\n<li><p><code>distance</code> should be named <code>distanceTo</code>, <code>equal</code> should be <code>areEqual</code>.</p></li>\n<li><p>OOP wise, the function <code>pointsFormsQuadrangle</code> shouldn't be in the class <code>Point</code>, because it breaks single responsibility principle, you could extract it to someplace else. </p></li>\n</ul>\n\n<p>Nitpicks are over.</p>\n\n<p>In <code>pointsFormsSquare</code>, you call <code>pointsFormsQuadrangle</code>. The verifications that you do, to assert that you have a square, are the following :</p>\n\n<ul>\n<li>No points are the same.</li>\n<li>All the distances to the center of your points are equal.</li>\n<li>You check if two sides of the quadrangle are equal (I believe).</li>\n</ul>\n\n<p>The two last parts are the important one and they seem to work pretty well. But is it the most efficient way to figure out if something is a square? Probably not. Computing the euclidean distance is kind of expensive. There a lots of solution on internet that don't rely on computing distances 7 times.</p>\n\n<p>Finally, the function <code>formSquaresFromPoints</code> probably iterates over way more points than it should. At the moment you have 3 points, you can start excluding the possibility that they form a square. If you know for sure that the 3 points can't possibly form a square, you'll try combinations with every other points with no reason, because it's already impossible for them to make a square. You don't test with many points right now, so maybe it doesn't matter. I'm not sure I explained myself correctly on this point, but don't hesitate to ask questions if you didn't understand.</p>\n\n<p>I can't comment much on the \"Javascriptness\" of your code because I'm not good enough with this language, but it looks clean.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T06:24:01.193", "Id": "430997", "Score": "0", "body": "Thanks a lot for the answer! It seems I understand what did you mean about the function `formSquaresFromPoints`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T18:35:37.537", "Id": "222544", "ParentId": "222526", "Score": "3" } }, { "body": "<p>You're coding javascript the \"old\" way. With <a href=\"/questions/tagged/es6\" class=\"post-tag\" title=\"show questions tagged &#39;es6&#39;\" rel=\"tag\">es6</a> you have a lot of new features available. Take a look at <a href=\"http://es6-features.org/#Constants\" rel=\"nofollow noreferrer\">them</a>.</p>\n\n<hr>\n\n<p>Don't use self-invoking anonymous functions i.e. IIFEs</p>\n\n<pre><code>/// bad\n(function(){\n // code here\n})();\n</code></pre>\n\n<p>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block\" rel=\"nofollow noreferrer\">blocks</a></p>\n\n<pre><code>/// good\n{\n // code here\n}\n</code></pre>\n\n<hr>\n\n<p>Give meaningful names to your variables and methods. Functions should <strong>not</strong> have more than 2 parameters. If they do, you need to put them in an object.</p>\n\n<pre><code>/// bad\n... pointsFormsQuadrangle = function(a, b, c, d){}\n\n/// good\nstatic FormsQuadrangle([point1, point2, point3, point4]){\n\n}\n</code></pre>\n\n<hr>\n\n<p>Use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\" rel=\"nofollow noreferrer\"><code>class</code> syntax</a> instead of <code>function/prototype</code>.</p>\n\n<pre><code>class Utils {\n static NumbersEqual(a, b){\n return Math.abs(a - b) &lt; Number.EPSILON;\n }\n}\n\nclass Point {\n constructor(x, y) {\n this.x = x;\n this.y = y;\n }\n\n distance(point) {\n return Math.sqrt((this.x - point.x) ** 2 + (this.y - point.y) ** 2);\n }\n\n equal(point) {\n return Utils.NumbersEqual(this.x, point.x) &amp;&amp; Utils.NumbersEqual(this.y, point.y);\n }\n\n static FormsQuadrangle(a, b, c, d) {\n if (a.equal(b) || a.equal(c) || a.equal(d)) return false;\n\n if (b.equal(c) || b.equal(d)) return false;\n\n if (c.equal(d)) return false;\n\n const center = new Point((a.x + b.x + c.x + d.x) / 4, (a.y + b.y + c.y + d.y) / 4);\n\n const ac = a.distance(center);\n const bc = b.distance(center);\n const cc = c.distance(center);\n const dc = d.distance(center);\n\n return Utils.NumbersEqual(ac, bc) &amp;&amp; Utils.NumbersEqual(bc, cc) &amp;&amp; Utils.NumbersEqual(cc, dc);\n }\n\n static FormsSquare(a, b, c, d) {\n if (!Point.FormsQuadrangle(a, b, c, d))\n return false;\n\n const ab = a.distance(b)\n const ac = a.distance(c);\n const ad = a.distance(d);\n const [tr1, tr2] = [ab, ac, ad].sort((a, b) =&gt; a - b);\n\n return Utils.NumbersEqual(tr1, tr2);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T06:24:36.570", "Id": "430998", "Score": "0", "body": "Thanks a lot for the answer!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T19:16:28.200", "Id": "222547", "ParentId": "222526", "Score": "4" } } ]
{ "AcceptedAnswerId": "222544", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T13:20:42.410", "Id": "222526", "Score": "4", "Tags": [ "javascript", "beginner", "algorithm", "computational-geometry", "coordinate-system" ], "Title": "Find 4 points which form a square with the biggest area" }
222526
<p>I'm writing code for embedded systems (IAR compiler) and it should adhere to Misra C++ 2008. This limits the available features of the language quite a bit: </p> <ul> <li>no C++1x features</li> <li>use of the standard library is banned as well</li> <li>no dynamic memory (no heap)</li> </ul> <p>We use PC-Lint to check for adherence.</p> <p>Rule 5-0-15 of Misra states: </p> <blockquote> <p>Array indexing is the only acceptable form of pointer arithmetic, because it is clearer and hence less error prone than pointer manipulation. This rule bans the explicit calculation of pointer values. <strong>Array indexing shall only be applied to objects defined as an array type.</strong> [...]</p> </blockquote> <p>I have marked the sentence which my question is revolving around. I've written a small file system for our external flash memory and the file table itself resides in an EEPROM. The way to access the external EEPROM is a bit awkward. I have to derive the class from CConfigElement and I get handed a byte pointer and a data size and that array of bytes will be synchronized to the EEPROM. The complete system behind config elements and how they are working would result in probably a whole project review.</p> <p>I have a known maximum number of files, I know the data size is sufficient for the number of file entries I want. My table is basically just an array of file entries. So I cast the byte pointer to a file entry pointer and work on that with array indexing.</p> <p>That is clearly forbidden by the rule because the table is just a pointer and not an array. Often we are using an exception to the rule and just move on, like it is done in the code below.</p> <p>A file is identified with a selector. To verify that the file stored in the file system and the requested file are actually the same, the maximum size of the file is used as a verification. The user of the code works on the external flash based on the file information provided by the file system (base address and current file size). The user also has to report back the amount of bytes written, so that the current file size can be updated.</p> <p>The file system creates a new file if an unknown file is requested and aligns the base address of the new file to the 4 kiB sectors of the flash. Currently only a full reset is supported, not a deletion of single files.</p> <p>We define our own types in <code>vtypes.h</code> which is included in all compilations:</p> <ul> <li><code>vtypes.h</code></li> </ul> <pre><code>#ifndef VTypes_H #define VTypes_H typedef unsigned char VBOOL; typedef char VCHAR; typedef signed char VS8; typedef unsigned char VU8; typedef signed short VS16; typedef unsigned short VU16; typedef signed long VS32; typedef unsigned long VU32; typedef signed long long VS64; typedef unsigned long long VU64; typedef float VFLT32; typedef double VDBL64; static const VS8 VS8_MIN = -128; static const VS8 VS8_MAX = 127; static const VU8 VU8_MAX = 255; static const VS16 VS16_MIN = -32768; static const VS16 VS16_MAX = 32767; static const VU16 VU16_MAX = 65535U; static const VS32 VS32_MIN = (-2147483647L -1); static const VS32 VS32_MAX = 2147483647L; static const VU32 VU32_MAX = 4294967295UL; static const VS64 VS64_MAX = 9223372036854775807LL; static const VS64 VS64_MIN = (-9223372036854775807LL -1); static const VU64 VU64_MAX = 18446744073709551615ULL; static const VFLT32 VFLT32_MIN = 1.18e-38F; static const VFLT32 VFLT32_MAX = 3.39e38F; static const VDBL64 VDBL64_MIN = 2.23e-308; static const VDBL64 VDBL64_MAX = 1.79e308; #ifdef __cplusplus #define NULL 0 #define VEXTERN_C extern "C" #define VEXTERN_C_BEGIN extern "C" { #define VEXTERN_C_END } #undef TRUE #undef FALSE static const VBOOL TRUE = 1; static const VBOOL FALSE = 0; #else /* __cplusplus */ #define NULL ((void *)0) #define TRUE 1U #define FALSE 0U #define VEXTERN_C #define VEXTERN_C_BEGIN #define VEXTERN_C_END #endif /* __cplusplus */ #endif </code></pre> <hr> <h2>Before</h2> <p>This is the implementation before trying to adhere to all the Misra rules.</p> <ul> <li><code>CConfigElement.h</code> stripped for just the essentials</li> </ul> <pre><code>#ifndef CCONFIGELEMENT_H #define CCONFIGELEMENT_H #include "IConfigElement.h" class CConfigElement : public IConfigElement { public: virtual void SetItsData(VU8* const d, const VU32 size) { VASSERT(size &gt;= dataSize); data = d; } //lint -esym(1960,data,dataSize) // must be visible in derived classes protected: VU8* data; VU32 dataSize; }; #endif /* CCONFIGELEMENT_H */ </code></pre> <ul> <li><code>CCeMiniFileSystem.h</code></li> </ul> <pre><code>#ifndef CCEMINIFILESYSTEM_H #define CCEMINIFILESYSTEM_H #include "CConfigElement.h" class CConfig; class CCeMiniFileSystem : public CConfigElement { public: struct SoftwareImageSelector_t { StorageLocation_t StorageLocation; ControllerIdentifier_t ControllerIdentifier; ImageIdentifier_t ImageIdentifier; }; static inline VBOOL operator==(const SoftwareImageSelector_t&amp; lhs, const SoftwareImageSelector_t&amp; rhs) { return (lhs.StorageLocation == rhs.StorageLocation) &amp;&amp; (lhs.ControllerIdentifier == rhs.ControllerIdentifier) &amp;&amp; (lhs.ImageIdentifier == rhs.ImageIdentifier); } static inline VBOOL operator!=(const SoftwareImageSelector_t&amp; lhs, const SoftwareImageSelector_t&amp; rhs) { return !operator==(lhs, rhs); } public: CCeMiniFileSystem(); virtual ~CCeMiniFileSystem(); VBOOL GetFileInfo(SoftwareImageSelector_t fileSelector, VU32 fileMaxSize, VBOOL&amp; isNewFile, VU32&amp; baseAddress, VU32&amp; currentSize); void UpdateCurrentSize(SoftwareImageSelector_t fileSelector, VU32 fileMaxSize, VU32 additionalBytesWritten); void SetConfig(CConfig* const configThisElementIsAttachedTo); virtual void SetItsData(VU8* const d, const VU32 size); void ResetFileSystem(); private: VBOOL FindFile(SoftwareImageSelector_t fileSelector, VU32 fileMaxSize, VBOOL&amp; fileExists, VU32&amp; fileEntryIndex); #pragma pack(push,1) struct FileEntry_t { SoftwareImageSelector_t selector; VU32 baseAddressInFlash; VU32 currentSizeInFlash; VU32 MaxSize; }; #pragma pack(pop) const VU32 MAX_NUMBER_OF_FILES; FileEntry_t* fileTable; CConfig* config; private: CCeMiniFileSystem(const CCeMiniFileSystem&amp;); // Only declaration -&gt; linker error on usage CCeMiniFileSystem&amp; operator=(const CCeMiniFileSystem&amp;); // Only declaration -&gt; linker error on usage }; #endif /* CCEMINIFILESYSTEM_H_ */ </code></pre> <ul> <li><code>CCeMiniFileSystem.cpp</code></li> </ul> <pre><code>#include "CCeMiniFileSystem.h" #include "CConfig.h" CCeMiniFileSystem::CCeMiniFileSystem() : CConfigElement(), MAX_NUMBER_OF_FILES(7), fileTable(NULL), config(NULL) { dataSize = MAX_NUMBER_OF_FILES * sizeof(FileEntry_t); } void CCeMiniFileSystem::SetItsData(VU8* const d, const VU32 size) { CConfigElement::SetItsData(d, size); fileTable = reinterpret_cast&lt;FileEntry_t*&gt;(data); } CCeMiniFileSystem::~CCeMiniFileSystem() { } VBOOL CCeMiniFileSystem::FindFile(SoftwareUpdate::SoftwareImageSelector_t fileSelector, VU32 fileMaxSize, VBOOL&amp; fileExists, VU32&amp; fileEntryIndex) { fileExists = FALSE; for (fileEntryIndex = 0U; fileEntryIndex &lt; MAX_NUMBER_OF_FILES; fileEntryIndex++) { if (fileTable[fileEntryIndex].selector.StorageLocation != 2U) { // all files in flash have StorageLocation 2, so no files after this index // abort here --&gt; fileEntryIndex is index for new file break; } if (fileTable[fileEntryIndex].selector == fileSelector) { if (fileTable[fileEntryIndex].MaxSize != fileMaxSize) { return FALSE; //lint !e904 file exists but has different size } else { fileExists = TRUE; break; } } } return TRUE; } VBOOL CCeMiniFileSystem::GetFileInfo(SoftwareUpdate::SoftwareImageSelector_t fileSelector, VU32 fileMaxSize, VBOOL&amp; isNewFile, VU32&amp; baseAddress, VU32&amp; currentSize) { // Search file VBOOL fileExists; VU32 fileEntryIndex; if (FALSE == FindFile(fileSelector, fileMaxSize, fileExists, fileEntryIndex)) { return FALSE; //lint !e904 file exists but has different size } FileEntry_t&amp; entryToUse = fileTable[fileEntryIndex]; if (FALSE == fileExists) { // new file isNewFile = TRUE; entryToUse.selector = fileSelector; entryToUse.MaxSize = fileMaxSize; entryToUse.currentSizeInFlash = 0U; // get new baseAddress if (fileEntryIndex == 0U) { // first file entryToUse.baseAddressInFlash = 0U; } else { const VU32 indexBefore = fileEntryIndex - 1U; const VU32 endOfFileBefore = fileTable[indexBefore].baseAddressInFlash + fileTable[indexBefore].MaxSize; const VU32 newBaseAddress = (endOfFileBefore / 4096U + 1U) * 4096U; // align to next sector in flash entryToUse.baseAddressInFlash = newBaseAddress; baseAddress = newBaseAddress; } if (FALSE == config-&gt;Synchronize(this)) // write fileTable to EEPROM { return FALSE; //lint !e904 error synchronizing fileTable to EEPROM } } else { // existing file isNewFile = FALSE; baseAddress = entryToUse.baseAddressInFlash; currentSize = entryToUse.currentSizeInFlash; } return TRUE; } void CCeMiniFileSystem::UpdateCurrentSize(SoftwareUpdate::SoftwareImageSelector_t fileSelector, VU32 fileMaxSize, VU32 additionalBytesWritten) { // Search file VBOOL fileExists; VU32 fileEntryIndex; if (FALSE == FindFile(fileSelector, fileMaxSize, fileExists, fileEntryIndex)) { return; //lint !e904 file exists but has different size } FileEntry_t&amp; entryToUse = fileTable[fileEntryIndex]; entryToUse.currentSizeInFlash += additionalBytesWritten; config-&gt;Synchronize(this); // write fileTable to EEPROM } void CCeMiniFileSystem::SetConfig(CConfig* const configThisElementIsAttachedTo) { config = configThisElementIsAttachedTo; } void CCeMiniFileSystem::ResetFileSystem() { for (VU32 i = 0; i &lt; dataSize; i++) { data[i] = 0U; } config-&gt;Synchronize(this); // write fileTable to EEPROM } </code></pre> <hr> <p>The offending lines are all those containing <code>fileTable[fileEntryIndex]</code> and usually in this case we would probably just add a <code>//lint !e1960 5-0-15</code> comment with a justification behind it.</p> <p>But I asked myself: Can I do better - can I write code that complies with the rule?</p> <p>So I changed the simple pointer to <code>FileEntry_t</code> to a pointer to an array of known number of elements. This required to change the cast when I get the data pointer and it requires that I now dereference the pointer before I can access the element of the array. And while I was at it, I changed the loop in <code>FindFile</code> to have just a single <code>break</code> (another Misra rule).</p> <h2>After</h2> <ul> <li><code>CCeMiniFileSystem.h</code></li> </ul> <pre><code>#ifndef CCEMINIFILESYSTEM_H #define CCEMINIFILESYSTEM_H #include "CConfigElement.h" class CConfig; class CCeMiniFileSystem : public CConfigElement { public: struct SoftwareImageSelector_t { StorageLocation_t StorageLocation; ControllerIdentifier_t ControllerIdentifier; ImageIdentifier_t ImageIdentifier; }; static inline VBOOL operator==(const SoftwareImageSelector_t&amp; lhs, const SoftwareImageSelector_t&amp; rhs) { return (lhs.StorageLocation == rhs.StorageLocation) &amp;&amp; (lhs.ControllerIdentifier == rhs.ControllerIdentifier) &amp;&amp; (lhs.ImageIdentifier == rhs.ImageIdentifier); } static inline VBOOL operator!=(const SoftwareImageSelector_t&amp; lhs, const SoftwareImageSelector_t&amp; rhs) { return !operator==(lhs, rhs); } public: CCeMiniFileSystem(); virtual ~CCeMiniFileSystem(); VBOOL GetFileInfo(SoftwareImageSelector_t fileSelector, VU32 fileMaxSize, VBOOL&amp; isNewFile, VU32&amp; baseAddress, VU32&amp; currentSize); void UpdateCurrentSize(SoftwareImageSelector_t fileSelector, VU32 fileMaxSize, VU32 additionalBytesWritten); void SetConfig(CConfig* const configThisElementIsAttachedTo); virtual void SetItsData(VU8* const d, const VU32 size); void ResetFileSystem(); private: VBOOL FindFile(SoftwareImageSelector_t fileSelector, VU32 fileMaxSize, VBOOL&amp; fileExists, VU32&amp; fileEntryIndex); #pragma pack(push,1) struct FileEntry_t { SoftwareImageSelector_t selector; VU32 baseAddressInFlash; VU32 currentSizeInFlash; VU32 MaxSize; }; #pragma pack(pop) static const VU32 MAX_NUMBER_OF_FILES = 7U; FileEntry_t (* fileTable)[MAX_NUMBER_OF_FILES]; //Pointer to a FileEntry_t-array with MAX_NUMBER_OF_FILES Elements CConfig* config; private: CCeMiniFileSystem(const CCeMiniFileSystem&amp;); // Only declaration -&gt; linker error on usage CCeMiniFileSystem&amp; operator=(const CCeMiniFileSystem&amp;); // Only declaration -&gt; linker error on usage }; #endif /* CCEMINIFILESYSTEM_H_ */ </code></pre> <ul> <li><code>CCeMiniFileSystem.cpp</code></li> </ul> <pre><code>#include "CCeMiniFileSystem.h" #include "CConfig.h" CCeMiniFileSystem::CCeMiniFileSystem() : CConfigElement(), fileTable(NULL), config(NULL) { dataSize = MAX_NUMBER_OF_FILES * sizeof(FileEntry_t); } void CCeMiniFileSystem::SetItsData(VU8* const d, const VU32 size) { CConfigElement::SetItsData(d, size); fileTable = reinterpret_cast&lt;FileEntry_t(*)[MAX_NUMBER_OF_FILES]&gt;(data); } CCeMiniFileSystem::~CCeMiniFileSystem() { } VBOOL CCeMiniFileSystem::FindFile(const SoftwareUpdate::SoftwareImageSelector_t fileSelector, const VU32 fileMaxSize, VBOOL&amp; fileExists, VU32&amp; fileEntryIndex) const { fileExists = FALSE; fileEntryIndex = 0U; while ((fileExists == FALSE) &amp;&amp; (fileEntryIndex &lt; MAX_NUMBER_OF_FILES)) { FileEntry_t&amp; entry = (*fileTable)[fileEntryIndex]; if (entry.selector.StorageLocation != 2U) { // all files in flash have StorageLocation 2, so no files after this index // abort here --&gt; fileEntryIndex is index for new file break; } if (TRUE == (entry.selector == fileSelector)) { if (entry.MaxSize != fileMaxSize) { return FALSE; //lint !e904 file exists but has different size } else { fileExists = TRUE; } } else { fileEntryIndex++; // increment only when file not found } } return TRUE; } VBOOL CCeMiniFileSystem::GetFileInfo(const SoftwareUpdate::SoftwareImageSelector_t fileSelector, const VU32 fileMaxSize, VBOOL&amp; isNewFile, VU32&amp; baseAddress, VU32&amp; currentSize) { // Search file VBOOL fileExists; VU32 fileEntryIndex; if (FALSE == FindFile(fileSelector, fileMaxSize, fileExists, fileEntryIndex)) { return FALSE; //lint !e904 file exists but has different size } FileEntry_t&amp; entryToUse = (*fileTable)[fileEntryIndex]; if (FALSE == fileExists) { // new file isNewFile = TRUE; entryToUse.selector = fileSelector; entryToUse.MaxSize = fileMaxSize; entryToUse.currentSizeInFlash = 0U; // determine baseAddress if (fileEntryIndex == 0U) { // first file entryToUse.baseAddressInFlash = 0U; } else { const VU32 indexBefore = fileEntryIndex - 1U; FileEntry_t&amp; fileBefore = (*fileTable)[indexBefore]; const VU32 endOfFileBefore = fileBefore.baseAddressInFlash + fileBefore.MaxSize; const VU32 newBaseAddress = ((endOfFileBefore / 4096U) + 1U) * 4096U; // align to next sector in flash entryToUse.baseAddressInFlash = newBaseAddress; baseAddress = newBaseAddress; } if (FALSE == config-&gt;Synchronize(this)) { return FALSE; //lint !e904 error synchronizing fileTable to EEPROM } } else { // existing file isNewFile = FALSE; baseAddress = entryToUse.baseAddressInFlash; currentSize = entryToUse.currentSizeInFlash; } return TRUE; } void CCeMiniFileSystem::UpdateCurrentSize(const SoftwareUpdate::SoftwareImageSelector_t fileSelector, const VU32 fileMaxSize, const VU32 additionalBytesWritten) { // Search file VBOOL fileExists; VU32 fileEntryIndex; if (FALSE == FindFile(fileSelector, fileMaxSize, fileExists, fileEntryIndex)) { return; //lint !e904 file exists but has different size } FileEntry_t&amp; entryToUse = (*fileTable)[fileEntryIndex]; entryToUse.currentSizeInFlash += additionalBytesWritten; config-&gt;Synchronize(this); //lint !e534 no possibility to use return value in a helpful way } void CCeMiniFileSystem::SetConfig(CConfig* const configThisElementIsAttachedTo) { config = configThisElementIsAttachedTo; } void CCeMiniFileSystem::ResetFileSystem() { for (VU32 i = 0U; i &lt; dataSize; i++) { data[i] = 0U; //lint !e1960 5-0-15 size of array behind pointer handled with dataSize } config-&gt;Synchronize(this); //lint !e534 no possibility to use return value in a helpful way } </code></pre> <hr> <p>So now I'm not really impressed with this. </p> <p>The doubts I'm having:</p> <ul> <li><code>FileEntry_t (* fileTable)[MAX_NUMBER_OF_FILES];</code> is not going to be very well understood by everyone around me</li> <li>the necessary dereferenciation makes it not easier to read or understand</li> </ul> <p>So is code quality (performance is not an issue, it's readability, maintainability and being less error prone) really improved by adhering to the rule in this case?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T13:51:07.393", "Id": "430758", "Score": "1", "body": "The use of ellipsis may cause some reviewers on this website to flag a question for lack of definition. In this case you are trying to not repeat things from the first section of code but this may be mistaken. You have also not included the definition of the base class that might help reviewers review the code. It would also be better if there was code showing how this was used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T08:34:38.900", "Id": "430899", "Score": "0", "body": "@pacmaninbw I tried a minimalist approach to keep my zombie count low and to focus on my main problem. I've now edited my question to give a more complete view of my class in question. I cannot provide more information on the base class. I'm also not sure how I can show an example usage without going into full project review mode (which I'm not allowed to do)." } ]
[ { "body": "<p>This was difficult to review because so many pieces were missing and had to be inferred. For that reason, you may find some of these comments off the mark because they are necessarily based on incomplete information. With that said, here are some thoughts that may help you improve your program.</p>\n\n<h2>Be clear about what's allowed</h2>\n\n<p>While your description said that no C++11 features are allowed, the use of <code>long long</code> types is a C++11 feature. While that may be supported by your compiler, it's probably worth explicitly noting the exceptions.</p>\n\n<h2>Don't write empty destructors</h2>\n\n<p>Even before C++11, the compiler would automatically generate empty destructors if needed, so there is no need to explicitly write <code>~CCeMiniFileSystem()</code> unless that's also a rule in MISRA (the last time I looked at MISRA rules was when it only covered C).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T21:46:12.837", "Id": "430972", "Score": "0", "body": "`long long` was probably supported as an extension of the IAR compiler long (no pun intended) before C++11, wasn't actually aware that that is a new feature. You are mixing up the source file before the changes with the header file after the changes, that's why your compiler doesn't like it. What kind of context would improve the question to make it easier to review? I find it very hard to cut out enough context without making the whole thing explode. Maybe the heart of my question is better asked somewhere else..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T22:00:29.130", "Id": "430973", "Score": "0", "body": "You're right -- I had mixed old and new content. Fixed now (and updated the review to match). I'll look at this more later and add to the review if I can." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T00:30:35.033", "Id": "430983", "Score": "0", "body": "Since you asked, context that would help people review the code would include: brief descriptions of the four public members of the main class -- is there sequencing required? What are the parameters supposed to do? Just a sample stub showing the sequence of calls and the expected result would be useful." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T21:23:45.583", "Id": "222605", "ParentId": "222529", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T13:28:50.660", "Id": "222529", "Score": "6", "Tags": [ "c++", "array", "comparative-review", "file-system", "embedded" ], "Title": "EEPROM-based filesystem, aiming for Misra C++ 2008 compliance" }
222529
<p>I implemented a prime number finder using the Miller-Rabin prime test in Haskell and it seems to be working. You enter a number and it finds the next prime following that number.</p> <p>I also tried to make it parallel and I'm looking for some advice for how I can speed up the parallel version. Right now it runs much slower than the not parallel version.</p> <p>Compiled with <code>ghc -threaded -O2 miller_rabin.hs -o miller_rabin</code></p> <p>Run with <code>./miller_rabin startnumber npar +RTS -N4</code> (I have a 4-core processor). <code>npar</code> is the parameter for <code>parBuffer</code>. If <code>npar</code> is 1 then the program runs single-threaded, otherwise is runs with multiple threads.</p> <pre><code>module Main where import System.Random (StdGen, getStdGen, randomRs) import System.Environment (getArgs) import Control.Parallel.Strategies main :: IO () main = do g &lt;- getStdGen args &lt;- getArgs let number = read . head $ args :: Integer npar = read $ args !! 1 :: Int p &lt;- case npar of 1 -&gt; do putStrLn "Run single thread" return $ find_prime g 20 number _ -&gt; do putStrLn "Run multi-threaded" return $ head $ primeList npar g 20 number putStrLn . show $ p miller_rabin :: StdGen -&gt; Int -&gt; Integer -&gt; Bool miller_rabin g k n = all (not . trial_composite n d r) $ take k (randomRs (2, n-2) g) where (d, r) = decompose (n-1) 0 trial_composite :: Integer -&gt; Integer -&gt; Integer -&gt; Integer -&gt; Bool trial_composite n d r a = let x = fastPow a d n in if (x == 1) || (x==n-1) then False else all ((/=) (n-1)) $ map (\i -&gt; fastPow a (d*(2^i)) n) [0..r-1] decompose :: Integer -&gt; Integer -&gt; (Integer, Integer) decompose d r | d `mod` 2 == 0 = decompose (d `div` 2) (r+1) | otherwise = (d, r) fastPow :: Integer -&gt; Integer -&gt; Integer -&gt; Integer fastPow base 1 m = mod base m fastPow base pow m | even pow = mod ((fastPow base (div pow 2) m) ^ 2) m | odd pow = mod ((fastPow base (div (pow-1) 2) m) ^ 2 * base) m primeList :: Int -&gt; StdGen -&gt; Int -&gt; Integer -&gt; [Integer] primeList npar g k n = let primes = filter (miller_rabin g k) [m,m+2..] primesP = primes `using` parBuffer npar rdeepseq m = if even n then n+1 else n in primesP find_prime :: StdGen -&gt; Int -&gt; Integer -&gt; Integer find_prime g k n | even n = find_prime g k (n+1) | otherwise = case miller_rabin g k n of True -&gt; n False -&gt; find_prime g k (n+2) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T18:44:04.907", "Id": "430819", "Score": "0", "body": "It seems to me like the parallel version is slower because it computes the list elements in parallel, rather than only needing to compute the first list element like the serial version. Make `find_prime` and `primeList` calculate and output the same and `find_prime` shouldn't complete faster anymore." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T21:00:09.027", "Id": "430851", "Score": "0", "body": "@Gurkenglas, I’ll try to do a rewrite, but I thought that the parallel list version would allow the list to be computed quickly and there would only be a penalty at the final chunk." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T14:21:37.617", "Id": "222530", "Score": "2", "Tags": [ "multithreading", "haskell", "reinventing-the-wheel", "primes" ], "Title": "Parallel Miller-Rabin Prime Test in Haskell" }
222530
<p>I wrote a quick sodoku solver as an exercise and am curious how to make it faster. Parsing and printing is largely irrelevant only there for readability. How can I make the code cleaner and faster?</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;array&gt; #include &lt;tuple&gt; #include &lt;bitset&gt; #include &lt;cassert&gt; #include &lt;optional&gt; #include &lt;iostream&gt; constexpr std::size_t blocks_per_side = 3; constexpr std::size_t numbers = blocks_per_side * blocks_per_side; using Value = std::bitset&lt;numbers&gt;; using Row = std::array&lt;Value, numbers&gt;; using Grid = std::array&lt;Row, numbers&gt;; using NiceRow = std::array&lt;std::size_t, numbers&gt;; using NiceGrid = std::array&lt;NiceRow, numbers&gt;; namespace MapArrayDetail { template &lt;std::size_t index, typename Callable, typename... Args&gt; constexpr auto MapIndex(const Callable&amp; cal, const Args&amp;... args) { return cal(std::get&lt;index&gt;(args)...); } template &lt;typename OutType, std::size_t size, typename Callable, std::size_t... Is, typename... Arrays&gt; constexpr std::array&lt;OutType, size&gt; MapWithIndex( const Callable&amp; cal, std::index_sequence&lt;Is...&gt;, const Arrays&amp;... arrays) { return {MapIndex&lt;Is&gt;(cal, arrays...)...}; } } template &lt;typename Callable, typename... Arrays&gt; constexpr auto Map(const Callable&amp; cal, const Arrays&amp;... arrays) { using OutType = std::invoke_result_t&lt;decltype(cal), typename Arrays::value_type...&gt;; constexpr auto size = std::get&lt;0&gt;(std::make_tuple(std::tuple_size_v&lt;Arrays&gt;...)); return MapArrayDetail::MapWithIndex&lt;OutType, size&gt;( cal, std::make_index_sequence&lt;size&gt;(), arrays...); } constexpr Value DeSerialize(std::size_t s) { Value v{}; if (s != 0) { v.set(s - 1); } return v; } std::size_t Serialize(Value s) { assert(s.count() &lt;= 1); for (std::size_t v = 0; v &lt; numbers; v++) { if (s[v]) { return v + 1; } } return 0; } constexpr Grid DeSerialize(NiceGrid nice) { return Map( [](const auto&amp; r) constexpr { return Map([](const auto&amp; v) constexpr { return DeSerialize(v); }, r); }, nice); } NiceGrid Serialize(Grid g) { return Map( [](const auto&amp; r) -&gt; NiceRow { return Map([](const auto&amp; v) { return Serialize(v); }, r); }, g); } void print(NiceGrid g) { for (std::size_t row = 0; row &lt; numbers; row++) { for (std::size_t col = 0; col &lt; numbers; col++) { std::cout &lt;&lt; g[row][col] &lt;&lt; ","; } std::cout &lt;&lt; std::endl; } std::cout &lt;&lt; std::endl; } constexpr Row GetRow(const Grid&amp; grid, std::size_t i) { return grid.at(i); } template &lt;std::size_t... indexes&gt; constexpr Row GetColImpl( const Grid&amp; grid, std::size_t i, std::index_sequence&lt;indexes...&gt;) { return {grid[indexes][i]...}; } constexpr Row GetCol(const Grid&amp; grid, std::size_t i) { return GetColImpl(grid, i, std::make_index_sequence&lt;numbers&gt;()); } template &lt;std::size_t i&gt; using ValFromIndex = Value; template &lt;std::size_t... indexes&gt; constexpr std::tuple&lt;ValFromIndex&lt;indexes&gt;...&gt; GetBlockCol(const Grid&amp; grid, std::size_t row, std::size_t top_col, std::index_sequence&lt;indexes...&gt;) { return {grid.at(row).at(top_col + indexes)...}; } template &lt;std::size_t... indexes&gt; constexpr Row GetBlockImpl(const Grid&amp; grid, std::size_t row, std::size_t col, std::index_sequence&lt;indexes...&gt;) { constexpr auto seq = std::index_sequence&lt;indexes...&gt;{}; const auto top_row = (row / blocks_per_side) * blocks_per_side; const auto top_col = (col / blocks_per_side) * blocks_per_side; return std::apply([](const auto&amp;... v) { return Row{v...}; }, std::tuple_cat(GetBlockCol(grid, top_row + indexes, top_col, seq)...)); } constexpr Row GetBlock(const Grid&amp; grid, std::size_t row, std::size_t col) { return GetBlockImpl( grid, row, col, std::make_index_sequence&lt;blocks_per_side&gt;()); } Value GetRemaining(const Grid&amp; grid, std::size_t row_ind, std::size_t col_ind) { Value v{}; constexpr auto or_op = [](const auto&amp;... a) { return (a | ...); }; const auto ored = Map(or_op, GetCol(grid, col_ind), GetRow(grid, row_ind), GetBlock(grid, row_ind, col_ind)); for (const auto&amp; c : ored) { v = v | c; } return ~v; } using StartStop = std::tuple&lt;std::size_t, std::size_t, Value&gt;; constexpr StartStop start{numbers + 1, numbers + 1, {}}; StartStop GetMinPos(const Grid&amp; grid) { auto count = 2 * numbers; StartStop row_col = start; for (std::size_t row = 0; row &lt; numbers; row++) { for (std::size_t col = 0; col &lt; numbers; col++) { if (grid[row][col].none()) { auto r = GetRemaining(grid, row, col); const auto rcount = r.count(); if (rcount &lt; count) { count = rcount; row_col = {row, col, r}; } } } } return row_col; } bool Done(const Grid&amp; g) { constexpr auto row_has_zero = [](const Row&amp; r) { return std::find_if(r.begin(), r.end(), [](const auto&amp; a) { return a.none(); }) != r.end(); }; return std::find_if(g.begin(), g.end(), row_has_zero) == g.end(); } std::optional&lt;Grid&gt; BruteForce(const Grid&amp; g) { if (Done(g)) { return g; } const auto[row, col, val] = GetMinPos(g); if ((row &gt; numbers) | val.none()) { return std::nullopt; } for (std::size_t i = 0; i &lt; numbers; i++) { if (val[i]) { auto g2 = g; assert(g2[row][col].count() == 0); g2[row][col].set(i); auto res = BruteForce(g2); if (res) { return res; } } } return std::nullopt; } constexpr NiceGrid ex1_nice{ NiceRow{4, 0, 3, 0, 0, 0, 7, 1, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 9}, {7, 0, 0, 0, 1, 9, 3, 4, 8}, {0, 0, 0, 7, 4, 0, 0, 0, 3}, {0, 0, 4, 0, 0, 0, 1, 0, 0}, {8, 0, 0, 0, 2, 3, 0, 0, 0}, {1, 6, 7, 3, 9, 0, 0, 0, 2}, {3, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 5, 2, 0, 0, 0, 6, 0, 1}}; const Grid ex1 = DeSerialize(ex1_nice); int main(int argc, char** argv) { auto z = BruteForce(ex1); if (!z) { std::cout &lt;&lt; "Failed" &lt;&lt; std::endl; } print(Serialize(*z)); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T15:49:59.533", "Id": "430787", "Score": "0", "body": "Do you want a faster solution without changing strategy (brute force), or is a complete re-write an option?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T15:52:08.913", "Id": "430788", "Score": "0", "body": "I'm interested in all options, potentially I might wish to extend it to be 16*16 however" } ]
[ { "body": "<p>I've put this through a profiler (the built in one in VS2017), though I had to significantly amplify the signal by doing 10k calls to the solver, otherwise it is too quick. It's also quite a simple puzzle, here is a harder one for this type of solver:</p>\n\n<pre><code>constexpr NiceGrid ex2_nice{\nNiceRow{0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 3, 0, 8, 5},\n {0, 0, 1, 0, 2, 0, 0, 0, 0},\n {0, 0, 0, 5, 0, 7, 0, 0, 0},\n {0, 0, 4, 0, 0, 0, 1, 0, 0},\n {0, 9, 0, 0, 0, 0, 0, 0, 0},\n {5, 0, 0, 0, 0, 0, 0, 7, 3},\n {0, 0, 2, 0, 1, 0, 0, 0, 0},\n {0, 0, 0, 0, 4, 0, 0, 0, 9} };\n</code></pre>\n\n<p>The main result is that most time is spent calling <code>GetMinPos</code> and <code>GetRemaining</code> (85%), which down the line spends a significant amount of time in <code>GetBlockImpl</code>. Of course <code>GetRemaining</code> is expected to take some time as it does a significant amount of useful work, but <code>GetBlockImpl</code> - that's not so good. Apparently MSVC could not see the forest through the C++ templated algorithm trees. You probably won't like this suggestion if you like writing this style of C++, but I recommend not trying to be so clever with index sequences and apply and so on and just write raw loops.. With that change, not only is there less code, the solver now takes about <strong>one third</strong> of the time, bringing it down from 0.15ms per solve to 0.05ms on my PC for the easy puzzle, and from 60ms down to 20ms for the hard puzzle.</p>\n\n<p>There are algorithmic tricks too. A common principle for solving constraint satisfaction problems is to try the most-constrained variable first (MCV), while choosing the least-constraining value (LCV). These may sound like opposites, but they're not. The goal of both of them is \"move pruning up in the tree\". MCV moves pruning up by trying to make hard choices early, leaving \"easy decisions\" for later, hoping that hard choices lead to contradictions early. LCV moves pruning up by trying to \"make later choices easier\".</p>\n\n<p>Pruning high in the tree means the effect of skipping a branch is as high as possible, skipping as much of the search space as possible. In order to do this, the entire approach of <code>GetRemaining</code> would have to change, since the MCV branching heuristic needs access to the current \"set of possibilities\" for all cells so it can choose which of them to work on. Calling <code>GetRemaining</code> on all cells is a waste, instead an other technique can be used: maintaining the sets at all times, removing options when a cell in the same row/col/block is filled in and restoring them when un-filling the cell.</p>\n\n<p>Additionally, the sets of remaining possibilities per cell may be filtered down more by looking for Naked Pairs, Hidden Pairs, Hidden Singles, and so forth. Naked Singles are even picked up by MCV automatically, but why recurse when you can filter. Using the Dual Sets can help with some of these. A dual set is a set associated with a value, indicating which cell(s) of a row/col/block it can go into (in contrast with the primal sets: for each cell, the set of values it can have). A Hidden Single for example would take a non-trivial algorithm to detect in the primal sets, but in the dual sets a Hidden Single manifests as a singleton set which is trivial to detect. In the extreme, full <code>all_different</code> global constraint pruning can be applied to every column, row, and block.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T02:03:47.213", "Id": "222677", "ParentId": "222531", "Score": "1" } } ]
{ "AcceptedAnswerId": "222677", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T15:06:24.950", "Id": "222531", "Score": "5", "Tags": [ "c++", "performance", "c++17", "sudoku" ], "Title": "Sodoku solver with arrays of bitsets" }
222531
<p>This function converts a Javascript Object into a CSV.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var dataFromAPI = [{"name":"first"},{"name":"sec,ond"},{"name":"third 'jibberish"},{"name":"fourth, jibberish"}] function convertToCSVandDownload(objArray) { var csvOutput = ""; Object.keys(objArray).forEach(function(key) { if (csvOutput.length == 0) { csvOutput = "Index,Field Value\n"; csvOutput = csvOutput + JSON.stringify(key) + "," + JSON.stringify(objArray[key]["name"]) + "\n"; } else { csvOutput = csvOutput + JSON.stringify(key) + "," + JSON.stringify(objArray[key]["name"]) + "\n"; } }) return csvOutput; } console.log(convertToCSVandDownload(dataFromAPI));</code></pre> </div> </div> </p>
[]
[ { "body": "<p>Skimming through your code I believe ya may not need that <code>if</code>/<code>else</code> check within the <code>.forEach</code> loop...</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var dataFromAPI = [{\"name\":\"first\"},{\"name\":\"sec,ond\"},{\"name\":\"third 'jibberish\"},{\"name\":\"fourth, jibberish\"}]\n\nfunction convertToCSVandDownload(objArray) {\n var csvOutput = \"Index,Field Value\\n\";\n Object.keys(objArray).forEach(function(key) {\n csvOutput = csvOutput + JSON.stringify(key) + \",\" + JSON.stringify(objArray[key][\"name\"]) + \"\\n\";\n })\n return csvOutput;\n}\n\nconsole.log(convertToCSVandDownload(dataFromAPI));\n</code></pre>\n\n<p>... and one thing that might be an improvement may be allowing for converting other <em><code>target_key</code>s</em>...</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var dataFromAPI = [{\"name\":\"first\"},{\"name\":\"sec,ond\"},{\"name\":\"third 'jibberish\"},{\"name\":\"fourth, jibberish\"}]\n\nfunction convertToCSVandDownload(objArray, target_key) {\n var csvOutput = \"Index,Field Value\\n\";\n Object.keys(objArray).forEach(function(i) {\n csvOutput += JSON.stringify(i) + \",\" + JSON.stringify(objArray[i][target_key]) + \"\\n\";\n })\n return csvOutput;\n}\n\nconsole.log(convertToCSVandDownload(dataFromAPI, 'name'));\n</code></pre>\n\n<p>... other than those two things I think you code is good, and the only other thing ya might want to consider is what ya want to do with data structures that have more <em>layers</em> than <code>dataFromAPI</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T18:36:50.047", "Id": "430812", "Score": "1", "body": "Is 'ya' Jamaican?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T18:43:46.897", "Id": "430818", "Score": "0", "body": "The [urbandictionary](https://www.urbandictionary.com/define.php?term=ya%20man) says something like _\"Term for \"yes\" used in Jamaica\"_, but that is just something that I read online somewhere. Personally I use it for that as well as a less direct form of _`you`_, eg. _\"ya ya could do that'_, which when spoken would have a more `uh` like sound on the second `ya`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T18:12:02.003", "Id": "222540", "ParentId": "222532", "Score": "1" } }, { "body": "<h1>Description</h1>\n\n<p>It would appear that your current solution is a bit complicated. Using <code>JSON.parse</code> just to ensure that you escape <code>,</code> is overkill.</p>\n\n<p>The overall solution can be drastically simplified as you will see in this post.</p>\n\n<h3><code>const</code> before <code>let</code> and <code>let</code> before <code>var</code></h3>\n\n<p>All variables should be declared by default with <code>const</code>. If a variable is going to be mutated then use <code>let</code>. Don't use <code>var</code> unless that is what you intended.</p>\n\n<pre><code>/// bad\nvar dataFromAPI = ...\n</code></pre>\n\n<pre><code>/// good\nconst dataFromAPI = ...\n</code></pre>\n\n<p><em>note: pushing an element to a list will only mutate the array and not the variable, thus no error</em></p>\n\n<hr>\n\n<p>Work with arrays and not with strings.</p>\n\n<pre><code>/// bad\ncsvOutput = \"Index,Field Value\\n\";\n</code></pre>\n\n<pre><code>/// good\nconst csvOutput = [\n [\"Index\", \"Field\", \"Value\"]\n];\n</code></pre>\n\n<hr>\n\n<p>Function names should describe what they do.</p>\n\n<p>The <code>convertToCSVandDownload</code> method only converts to CSV but doesn't download. Change the name to <code>convertToCSV</code></p>\n\n<hr>\n\n<h1>Working Solution</h1>\n\n<p>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce\" rel=\"nofollow noreferrer\">Array#reduce</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">destructuring assignment</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\">Array#map</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join\" rel=\"nofollow noreferrer\">Array#join</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">spread syntax</a></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const dataFromAPI = [{\"name\":\"first\"},{\"name\":\"sec,ond\"},{\"name\":\"third 'jibberish\"},{\"name\":\"fourth, jibberish\"}]\n\nfunction convertToCSV(data, headers) {\n return data\n .reduce((a,{name},i)=&gt;[...a, [i, `\"${name}\"`]], [headers])\n .map(row=&gt;row.join(\",\"))\n .join(\"\\n\");\n}\n\nconst res = convertToCSV(dataFromAPI, [\"Index\", \"Field Value\"]);\n\nconsole.log(res)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T18:35:57.390", "Id": "222545", "ParentId": "222532", "Score": "3" } }, { "body": "<p><em>I'd like to propose a solution using <code>flatMap</code>. Be aware that this is definitely not a cross-browser solution.</em></p>\n\n<hr>\n\n<p>Let's create a function that given <em>n</em> arguments returns a CSV line:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const row = (...args) =&gt; args.map(JSON.stringify).join(',');\n\nconsole.log(row('foo'));\nconsole.log(row('foo', 'bar'));\nconsole.log(row('foo', 'bar', 'baz'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Then let's use <code>flatMap</code> to append (or prepend) stuff while we map over an array. e.g.:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const pair = arr =&gt; arr.flatMap(n =&gt; [n, n]);\n\nconsole.log(pair([1]));\nconsole.log(pair([1, 2]));\nconsole.log(pair([1, 2, 3]));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>As you can see we can use <code>flatMap</code> to \"add\" more items as we iterate. Let's use this to add the headers during the first iteration.</p>\n\n<p><strong>Complete solution</strong></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const dataFromAPI = [\n {\"name\": \"first\"},\n {\"name\": \"sec,ond\"},\n {\"name\": \"third 'jibberish\"},\n {\"name\": \"fourth, jibberish\"}];\n \n\nconst row = (...args) =&gt; args.map(JSON.stringify).join(',');\n\nconst csv =\n dataFromAPI\n .flatMap((obj, idx) =&gt;\n idx === 0 ?\n [row('Index', 'Field Value'), row(idx, obj.name)] :\n [row(idx, obj.name)])\n .join('\\n');\n \nconsole.log(csv);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T21:47:48.673", "Id": "222551", "ParentId": "222532", "Score": "2" } } ]
{ "AcceptedAnswerId": "222545", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T15:24:21.157", "Id": "222532", "Score": "3", "Tags": [ "javascript", "json", "csv" ], "Title": "Function to parse a Javascript object and return a CSV" }
222532
<p>In the following code we use the function <code>Incrementer</code> (capitalized for clarity, despite that it's to be used without <code>new</code>), to instantiate a number.</p> <p><code>Incrementer</code> provides a method <code>increment</code> to augment a counter in a <code>span</code>. We have two such counters, and so we define <code>Incrementer</code> to avoid code duplication (although it would be nice to program always like this, even in the absence of the worry of duplication).</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function Incrementer(name, value) { let that = {}; // Constructor that.name = name; let mydiv = document.getElementById('mydiv'); mydiv.appendChild(document.createElement('br')); that.span = document.createElement('span'); that.span.id = '#num' + name; that.span.innerHTML = value; mydiv.appendChild(that.span); that.increment = function() { var i = parseInt(that.span.textContent) + 1; that.span.innerHTML = i; } return that; } var incrementer1 = Incrementer('one', 10); var incrementer2 = Incrementer('two', 20); function double_increment() { incrementer1.increment(); incrementer2.increment(); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="mydiv"&gt; &lt;button id="inc" onclick="double_increment()"&gt;Increment&lt;/button&gt;&lt;br /&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>The function <code>double_increment()</code> is then used to increment both numbers.</p> <p>I'm seeking critique of this code, in particular:</p> <ol> <li>The block marked "Constructor" is directly inside the function <code>Incrementer</code> rather than in a function called <code>Constructor</code>. What is the right basis for cleaner code?</li> <li>The function <code>double_increment()</code> seems awkward. It exists at the global scope merely to respond to events (from user input in general, whether a button or otherwise). Is this an adequate basis for a (larger) code base?</li> </ol>
[]
[ { "body": "<p><em>disclaimer: \"bad\" is simply a way of saying it's not the best way.</em></p>\n\n<p>If we were in the early 2000s this would probably be relatively clean code, however javascript has advanced a lot since then (current version: <a href=\"/questions/tagged/es6\" class=\"post-tag\" title=\"show questions tagged &#39;es6&#39;\" rel=\"tag\">es6</a>)</p>\n\n<p>Take some time to check what's <a href=\"http://es6-features.org/#Constants\" rel=\"nofollow noreferrer\">new</a>.</p>\n\n<hr>\n\n<p>Best practices today is to completely separate HTML / JS / CSS (unless you're using <a href=\"/questions/tagged/vue\" class=\"post-tag\" title=\"show questions tagged &#39;vue&#39;\" rel=\"tag\">vue</a>, <a href=\"/questions/tagged/react\" class=\"post-tag\" title=\"show questions tagged &#39;react&#39;\" rel=\"tag\">react</a>, <a href=\"/questions/tagged/angular\" class=\"post-tag\" title=\"show questions tagged &#39;angular&#39;\" rel=\"tag\">angular</a>)</p>\n\n<ul>\n<li>Cleaner code</li>\n<li>Logic separation</li>\n<li>Reusability</li>\n<li>Easier to maintain</li>\n</ul>\n\n<p>So the following should not appear in your HTML.</p>\n\n<pre><code>/// bad\nonclick=\"double_increment()\"\n</code></pre>\n\n<pre><code>/// good\nconst button = document.getElementById(\"some_id\");\nbutton.addEventListener(\"click\", double_increment);\n</code></pre>\n\n<hr>\n\n<p>There is <strong>always</strong> a better alternative than <code>&lt;br/&gt;</code> and it's not <a href=\"https://en.wikipedia.org/wiki/Semantic_Web\" rel=\"nofollow noreferrer\">semantic</a></p>\n\n<p>Don't use it.</p>\n\n<hr>\n\n<p><code>const</code> before <code>let</code> and <code>let</code> before <code>var</code></p>\n\n<p>Always declare your variables with <code>const</code> by default. If you're ok with the variable mutating then use <code>let</code>. Don't use <code>var</code> unless you know what you're doing and you actually need it.</p>\n\n<p><em>note: <code>push</code>ing an element to an array (declared with <code>const</code>) does not mutate the variable, just the array. Thus no error.</em></p>\n\n<hr>\n\n<p>Do <strong>not</strong> hardcode your html element id in your function.</p>\n\n<pre><code>function Incrementer(name, value) {\n /// bad\n let mydiv = document.getElementById('mydiv'); \n}\n</code></pre>\n\n<p>It either needs to be sent via the parameter or accessed statically using <code>class</code></p>\n\n<pre><code>class Incrementer {\n /// still bad though\n static target = \"mydiv\"\n}\n</code></pre>\n\n<hr>\n\n<p>Object methods should do what their name infers.</p>\n\n<p>Here, the increment function is supposed to increment the variable, but it does more than that.</p>\n\n<ol>\n<li>Gets the text value of the span</li>\n<li>Parses the text value</li>\n<li>Increases by one</li>\n<li>Updates the UI</li>\n</ol>\n\n<p>(1) is <em>hacky</em>\n(2) completely unneeded\n(3) the actual thing your function is supposed to do\n(4) updates UI ? not what your function says it does</p>\n\n<pre><code>/// bad\nthat.increment = function() {\n var i = parseInt(that.span.textContent) + 1;\n that.span.innerHTML = i;\n}\n</code></pre>\n\n<pre><code>/// better\nthat.i = value;\n\n//increments value\nthat.increment = function() {\n that.i++;\n}\n\n//updates UI\nthat.update = function(){\n that.span.innerHTML = that.i;\n}\n\n// Method that should be called on button click\nthat.handleOnClick = function(){\n that.increment();\n that.update();\n}\n</code></pre>\n\n<hr>\n\n<p>A <code>double_increment</code> function doesn't need to exist. Each Incrementer should add an event listener to the button click.</p>\n\n<pre><code>/// bad\nfunction double_increment() {\n incrementer1.increment();\n incrementer2.increment();\n}\n</code></pre>\n\n<p><em>See next section add event listener for solution</em></p>\n\n<hr>\n\n<h1>Using class and working example</h1>\n\n<p><a href=\"/questions/tagged/es6\" class=\"post-tag\" title=\"show questions tagged &#39;es6&#39;\" rel=\"tag\">es6</a> has introduced <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\" rel=\"nofollow noreferrer\"><code>class</code></a></p>\n\n<blockquote>\n <p>JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.</p>\n</blockquote>\n\n<p>Thus your <code>Incremental</code> function should be a class instead.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class Incrementer {\n\n constructor(incrementId, options) {\n \n const {\n name = \"N/A\",\n value = 0,\n target\n } = options;\n \n this.name = name;\n this.counter = value;\n this.view = document.createElement(\"span\");\n \n this.view.id = `#num_${name}`\n \n const button = document.getElementById(incrementId);\n button.addEventListener(\"click\", ()=&gt;this.handleOnClick())\n\n this.update(); \n\n const container = document.getElementById(target);\n container.appendChild(this.view);\n }\n \n handleOnClick(){\n this.increment();\n this.update();\n }\n\n increment() {\n this.counter++;\n }\n\n update() {\n this.view.innerText = this.counter;\n }\n}\n\nconst incrementer1 = new Incrementer(\n \"increment\", \n {name: \"Hello World\", value: 3, target: \"container\"}\n);\n\nconst incrementer2 = new Incrementer(\n \"increment\", \n {name: \"Hello World\", value: 0, target: \"container\"}\n)</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#container {\n display: flex;\n flex-direction: row;\n justify-content: space-evenly;\n align-items: center;\n background-color: darkblue;\n}\n\n#container &gt; span {\n padding: 10px;\n background-color: lightblue;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;button id=\"increment\"&gt;Increment&lt;/button&gt;\n&lt;div id=\"container\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T18:06:28.960", "Id": "430806", "Score": "0", "body": "Would you prefer Incrementer inject an element in the dom or work on an existing element?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T18:08:19.753", "Id": "430807", "Score": "0", "body": "@dfhwze depends on the use case, but in the OP's situation it would appear that it's dynamic content so `inject an element in the dom`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T18:09:09.573", "Id": "430808", "Score": "1", "body": "my case? I'm just an editor of the OP, not the poster :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T00:02:41.880", "Id": "430862", "Score": "0", "body": "Nice reply that covers a lot of ground, but I wanted to remain within function invocations, not constructor invocation (whether new or old styles). I'm loath to amend the question to specify this after you put so much effort. It's probably worth a distinct question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T00:03:36.050", "Id": "430863", "Score": "0", "body": "My only reservation to your answer is that you introduced strong coupling between Incrementer and the button. At the outset we want Incrementer to know nothing about what triggers it. We may change our mind and experiment with the event coming in from one of many sources until we're happy with the UI, and we'd like to wrap Incrementer and let it be, while we move forward with the experimentations." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T18:01:27.100", "Id": "222539", "ParentId": "222533", "Score": "2" } } ]
{ "AcceptedAnswerId": "222539", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T16:21:40.660", "Id": "222533", "Score": "4", "Tags": [ "javascript", "html", "dom" ], "Title": "Modularized JavaScript event handler to increment counters" }
222533
<p><strong>Objective</strong>:</p> <p>I'm trying to create a BST in order to insert Packet objects for search purposes. Packet holds information like <code>partId</code>, <code>description</code>, <code>price</code>, and <code>partCount</code>.</p> <p>This is a follow up question of <a href="https://codereview.stackexchange.com/questions/222481/binary-search-tree-to-store-objects-by-object-id">this post.</a> I have since revised it so that:</p> <ul> <li>No or minimal memory leaks</li> <li>Includes minimized</li> <li>Namespace usage is minimized or removed altogether</li> </ul> <p>Now I want to ask some more questions:</p> <p>As you can see here,</p> <blockquote> <p><code>void BST::insert(Packet &amp;data) {</code></p> </blockquote> <p>I have to do this within the function,</p> <blockquote> <p><code>newNode-&gt;data = &amp;data;</code></p> </blockquote> <p>Is there a way to make that a more elegant solution or improve it? Because as you can see I'm using reference twice and I'd like to fix that or improve it. Could I get an example or be shown how this could be fixed?</p> <p>In <a href="https://codereview.stackexchange.com/a/222509">an answer</a> to the other post, it was said:</p> <blockquote> <p>Node isn't part of the public interface. If we make it a private struct within BST, then BST gets full access (not needing a friend declaration), but no other code does. That's what we really want.</p> </blockquote> <p>I have never done this before. Could I be shown an example or directly?</p> <p><strong>Main.cpp</strong>:</p> <pre><code>#include &lt;iostream&gt; #include "BST.h" #include "Packet.h" using namespace std; int main() { BST test1; cout &lt;&lt; "-------------------------------------------------------" &lt;&lt; endl; cout &lt;&lt; "Testing BST" &lt;&lt; endl; cout &lt;&lt; "-------------------------------------------------------" &lt;&lt; endl; Packet packetTest(123, "This is a packet of cheese.", 12.95, 10); Packet packetTest1(321, "This is a packet of cheese.", 12.95, 10); Packet packetTest2(456, "This is a packet of cheese.", 12.95, 10); Packet packetTest3(7, "This is a packet of cheese.", 12.95, 10); Packet packetTest4(119, "This is a packet of cheese.", 12.95, 10); Packet packetTest5(456, "This is a packet of cheese.", 12.95, 10); test1.insert(packetTest); test1.insert(packetTest1); test1.insert(packetTest2); test1.insert(packetTest3); test1.insert(packetTest4); test1.insert(packetTest5); test1.preorderTraversal(); system("pause"); } </code></pre> <p><strong>BST.h</strong>:</p> <pre><code>#pragma once #include "Packet.h" class Node { friend class BST; public: Node() : data(nullptr), rlink(nullptr), llink(nullptr) {} ~Node() {} private: Packet *data; Node *rlink, *llink; }; class BST { public: BST(); void BST::insert(Packet &amp;data); void BST::insert(Node *&amp;p, Node *newNode); void preorderTraversal() const; void destroyTree(); ~BST(); private: Node *root; void destroyTree(Node *&amp;p); void preorderTraversal(const Node *p) const; }; </code></pre> <p><strong>BST.cpp</strong>:</p> <pre><code>#include "BST.h" #include &lt;iostream&gt; BST::BST() : root(nullptr) {} void BST::insert(Packet &amp;data) { Node *newNode = new Node; newNode-&gt;data = &amp;data; insert(root, newNode); } void BST::insert(Node *&amp;p, Node *newNode) { if (p == nullptr) p = newNode; else if (p-&gt;data-&gt;getPartId() &gt; newNode-&gt;data-&gt;getPartId()) insert(p-&gt;llink, newNode); else insert(p-&gt;rlink, newNode); } void BST::preorderTraversal() const { if (root == nullptr) std::cerr &lt;&lt; "There is no tree."; else { preorderTraversal(root); } } void BST::preorderTraversal(const Node *p) const { if (p != nullptr) { std::cout &lt;&lt; p-&gt;data-&gt;getPartId() &lt;&lt; " "; preorderTraversal(p-&gt;llink); preorderTraversal(p-&gt;rlink); } } void BST::destroyTree(Node *&amp;p) { if (p != nullptr) { destroyTree(p-&gt;llink); destroyTree(p-&gt;rlink); delete p; p = nullptr; } } void BST::destroyTree() { destroyTree(root); } BST::~BST() { destroyTree(root); } </code></pre> <p><strong>Packet.h</strong>:</p> <pre><code>#pragma once #include &lt;string&gt; class Packet { public: Packet(int partId, std::string description, double price, int partCount) : partId(partId), description(description), price(price), partCount(partCount) {} int getPartId() const {return partId;} private: int partId; std::string description; double price; int partCount; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T18:41:29.893", "Id": "430815", "Score": "1", "body": "Are you sure that this is the right code? There is still `using namespace std;` which both answers strictly advised to avoid. Apart from that, the code as presented here still won't compile because of the extra qualifier `BST::` on `insert` in `BST.h`. Also `BST.cpp` does not know where to look for `cout` and `cerr` since you dropped `using namespace std;` but did not change their usage to `std::cout` or added `using std::cout;` at the beginning." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T19:15:31.900", "Id": "430830", "Score": "0", "body": "Take a look. It should be good now. Regarding the namespace thing, I will look into it. But this is what it is now. It's compiling finely for me and I can run it. My IDE is Visual Studio. I'm not sure why you can't compile it? Can you look at my question about Packet& on the above post (main post)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T19:46:01.130", "Id": "430835", "Score": "0", "body": "See **Syntax error** in [Toby Speight's answer](https://codereview.stackexchange.com/a/222509/92478) on your previous question." } ]
[ { "body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Remove extra qualifications in class member declarations</h2>\n<p>My compiler complains:</p>\n<pre><code>error: extra qualification ‘BST::’ on member ‘insert’\n</code></pre>\n<p>and it is absolutely right. What it's pointing out is that this line,</p>\n<pre><code>void BST::insert(Packet &amp;data);\n</code></pre>\n<p>coming as it does within the declaration of the <code>BST</code> class, should not have the <code>BST::</code> prefix. Instead just write it like this:</p>\n<pre><code>void insert(Packet &amp;data);\n</code></pre>\n<p>It might compile with your compiler (today anyway), but it's an error and should be fixed.</p>\n<h2>Use include guards</h2>\n<p>There should be an include guard in each <code>.h</code> file. That is, start the file with:</p>\n<pre><code>#ifndef BST_H\n#define BST_H\n// file contents go here\n#endif // BST_H\n</code></pre>\n<p>The use of <code>#pragma once</code> is a common extension, but it's not in the standard and thus represents at least a potential portability problem. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf8-use-include-guards-for-all-h-files\" rel=\"nofollow noreferrer\">SF.8</a></p>\n<h2>Don't use <code>system(&quot;pause&quot;)</code></h2>\n<p>There are two reasons not to use <code>system(&quot;cls&quot;)</code> or <code>system(&quot;pause&quot;)</code>. The first is that it is not portable to other operating systems which you may or may not care about now. The second is that it's a security hole, which you absolutely <strong>must</strong> care about. Specifically, if some program is defined and named <code>cls</code> or <code>pause</code>, your program will execute that program instead of what you intend, and that other program could be anything. First, isolate these into a seperate functions <code>cls()</code> and <code>pause()</code> and then modify your code to call those functions instead of <code>system</code>. Then rewrite the contents of those functions to do what you want using C++. An example:</p>\n<pre><code>void pause {\n std::getchar();\n}\n</code></pre>\n<h2>Don't abuse <code>using namespace std</code></h2>\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid.</p>\n<h2>Don't use <code>std::endl</code> if you don't really need it</h2>\n<p>The difference betweeen <code>std::endl</code> and <code>'\\n'</code> is that <code>'\\n'</code> just emits a newline character, while <code>std::endl</code> actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to <em>only</em> use <code>std::endl</code> when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using <code>std::endl</code> when <code>'\\n'</code> will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.</p>\n<h2>Use constant string concatenation</h2>\n<p>The <code>main</code> routine currently has these lines:</p>\n<pre><code>cout &lt;&lt; &quot;-------------------------------------------------------&quot; &lt;&lt; endl;\ncout &lt;&lt; &quot;Testing BST&quot; &lt;&lt; endl;\ncout &lt;&lt; &quot;-------------------------------------------------------&quot; &lt;&lt; endl;\n</code></pre>\n<p>But you don't really need to do it that way which potentially calls the <code>&lt;&lt;</code> operator six times. Instead, you could express the same thing as this:</p>\n<pre><code>std::cout &lt;&lt;\n &quot;-------------------------------------------------------\\n&quot; \n &quot;Testing BST\\n&quot;\n &quot;-------------------------------------------------------\\n&quot;;\n</code></pre>\n<p>This only calls <code>&lt;&lt;</code> once. The compiler automatically concatenates the string literals together.</p>\n<h2>Rethink the interface</h2>\n<p>Do interfacing programs really need for this method to be public?</p>\n<pre><code>void insert(Node *&amp;p, Node *newNode);\n</code></pre>\n<p>I would say they do not, and that further, <code>Node</code> is an implementation detail that could be a private class within <code>BST</code>. Also, the zero-argument <code>destroyTree</code> seems entirely redundant; you already have a destructor with identical code. Here's how to make the <code>Node</code> private:</p>\n<pre><code>class BST {\n struct Node {\n Packet *data = nullptr;\n Node *rlink = nullptr, *llink = nullptr;\n };\n</code></pre>\n<h2>Prefer in-class initializers to trivial constructors</h2>\n<p>As shown above, the <code>Node class</code> above can be quite trivially rewritten as a <code>struct</code> with no explicit constructor or destructor. We let the compiler provide defaults. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c45-dont-define-a-default-constructor-that-only-initializes-data-members-use-in-class-member-initializers-instead\" rel=\"nofollow noreferrer\">C.45</a> for details.</p>\n<h2>Decide on ownership</h2>\n<p>When a <code>Packet</code> is given to the tree, does the tree <code>own</code> it? That is, when the tree is destroyed, should the <code>Packet</code>s also be destroyed? If the answer is yes, which is the usual case, then there should be a <code>move</code> constructor for <code>Node</code>. If the answer is no, then you should be using a <code>std::shared_ptr</code> or the like. In almost no case should you be passing and storing pointers to references. I would suggest looking carefully at the interfaces for standard containers such as <code>std::vector</code> and <code>std::array</code> and emulate those.</p>\n<h2>Fix the bug</h2>\n<p>The current code has a problem. When the second item with a part ID of 456 is added, we get a tree like this. In this diagram, left links are green and right links are red. The right link that points from the 456 node to itself is an error which breaks the tree. Binary trees must have no loops.<br />\n<a href=\"https://i.stack.imgur.com/RMYYt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RMYYt.png\" alt=\"bad tree with loop\" /></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-19T14:00:43.130", "Id": "253661", "ParentId": "222543", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T18:14:58.203", "Id": "222543", "Score": "3", "Tags": [ "c++", "tree", "binary-search" ], "Title": "Binary Search Tree to store objects now with improvements" }
222543
<p>`Boggle is a word game in which letters are randomly placed in a 4x4 grid e.g:</p> <pre><code>A D Q P N L E M O S R T V K J H </code></pre> <p>Words can be started from any letter and are formed by finding a sequence of connecting letters. Letters may connect diagonally, vertically or horizontally. </p> <p>Example words on the above board are "son", lad" and "land". Letters may not be re-used.</p> <p>Below is a recursive solution to the boggle board. The problem with my solution is it is very slow. I had to limit word length to 8 otherwise it takes far too long. </p> <p>Please can you comment on general style improvements and if you can think of another method to solve this game, a hint as to what I should do for my next attempt.</p> <p>The dictionary is from <a href="https://github.com/EML-student/Dictionary-" rel="nofollow noreferrer">here</a></p> <pre><code>"""Boggle game solver""" import copy def words_from(board, row, column, running_string="", list_words=[]): """Calculate all possible words from a given starting position [row, column]""" if row in (4, -1) or column in (4, -1): return if len(running_string) &gt; 4: return if board[row][column] != "-": new_string = running_string + board[row][column] new_board = copy.deepcopy(board) new_board[row][column] = "-" # Add new word if len(new_string) &gt;= 3: list_words.append(new_string.lower()) # Find next word next_move = [ (1, 1), (-1, -1), (1, -1), (-1, 1), (1, 0), (0, 1), (-1, 0), (0, -1), ] for dx, dy in next_move: words_from(new_board, row + dx, column + dy, new_string, list_words) return list_words def get_permutations(board): """Get all permutations """ set_permutations = set() counter = 0 print("Working..", end = "") for row in range(4): for column in range(4): print(".", end="") counter += 1 words = words_from(board, row, column, list_words=[]) if words: for word in words: set_permutations.add(word) words = None return sorted(list(set_permutations)) def dictionary_check(set_permuations): """Check set_permutations for valid English words""" dictionary = {} with open("en-dict.txt", "r", encoding="utf8") as file: for line in file: dictionary[line.strip()] = 0 counter = 0 for word in set_permuations: if word.lower() in dictionary: counter += 1 print(word) print(f"======\n{counter} words") def find_words(board): """Find words on the boggle board""" set_permutations = get_permutations(board) print("Performing dictionary check....") dictionary_check(set_permutations) def build_board(string): """Build board from string""" if len(string) != 16: print("Error. Must enter 4*4 grid (16 characters)") return board = [[*string[0:4]], [*string[4:8]], [*string[8:12]], [*string[12:16]]] find_words(board) if __name__ == "__main__": string_board = "playthiswordgame" build_board(string_board) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T19:06:02.627", "Id": "430826", "Score": "0", "body": "Please tell us which python version this is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T19:06:35.063", "Id": "430827", "Score": "2", "body": "Python 3.7. Sorry" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T21:13:23.610", "Id": "430854", "Score": "0", "body": "When I ran it no words were printed. Perhaps you preprocessed your downloaded word list to make it lowercase? If that's not in the instructions, you should ensure you use the same case (upper or lower) in your dictionary as you're querying." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T21:16:04.423", "Id": "430855", "Score": "0", "body": "@Josiah I am so sorry. I linked the wrong dictionary. I have updated the link. Sorry" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T22:40:29.567", "Id": "430861", "Score": "0", "body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back [Rev 14 → 12](https://codereview.stackexchange.com/posts/222546/revisions#rev-arrow-5c481d9e-decf-443e-a8cd-3b3dc6cd56b9)" } ]
[ { "body": "<p>The problem that you observe with this program is speed, so let's look at that. </p>\n\n<p>Running the program, I immediately noticed that the <code>get_permutations</code> section was slow, and the <code>dictionary_check</code> section was many times faster. That immediately tells me that it's not worth looking for faster ways to do the <code>dictionary_check</code> until <code>get_permutations</code> is much faster. After all, even if we could make <code>dictionary_check</code> take no time at all, the program would take almost as long to run!</p>\n\n<p>Of course, I've been a bit naughty there. I went with my internal clock, when what I should do is use a tool. This is the result of running cprofile. </p>\n\n<pre><code>python -m cProfile -s cumtime boggle.py\n\n 116983186 function calls (93930898 primitive calls) in 32.455 seconds\n\n Ordered by: cumulative time\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 32.455 32.455 {built-in method builtins.exec}\n 1 0.052 0.052 32.455 32.455 boggle.py:1(&lt;module&gt;)\n 1 0.009 0.009 32.403 32.403 boggle.py:62(find_words)\n 1 0.085 0.085 31.945 31.945 boggle.py:34(get_permutations)\n5763088/16 4.231 0.000 31.726 1.983 boggle.py:15(words_from)\n15128064/720384 12.915 0.000 27.119 0.000 copy.py:132(deepcopy)\n3601920/720384 5.565 0.000 25.605 0.000 copy.py:210(_deepcopy_list)\n 30256128 3.207 0.000 3.207 0.000 {method 'get' of 'dict' objects}\n 3601920 1.764 0.000 2.288 0.000 copy.py:252(_keep_alive)\n 23052288 1.619 0.000 1.619 0.000 {built-in method builtins.id}\n 18009500 1.261 0.000 1.261 0.000 {method 'append' of 'list' objects}\n 11526144 0.840 0.000 0.840 0.000 copy.py:190(_deepcopy_atomic)\n 1 0.289 0.289 0.448 0.448 boggle.py:50(dictionary_check)\n 4431757 0.324 0.000 0.324 0.000 {built-in method builtins.len}\n 720284 0.131 0.000 0.131 0.000 {method 'add' of 'set' objects}\n 173 0.076 0.000 0.076 0.000 {built-in method builtins.print}\n 712738 0.067 0.000 0.067 0.000 {method 'lower' of 'str' objects}\n 178691 0.017 0.000 0.017 0.000 {method 'strip' of 'str' objects}\n 240 0.000 0.000 0.003 0.000 cp1252.py:22(decode)\n 240 0.003 0.000 0.003 0.000 {built-in method _codecs.charmap_decode}\n 1 0.000 0.000 0.000 0.000 {built-in method io.open}\n 1 0.000 0.000 0.000 0.000 _bootlocale.py:11(getpreferredencoding)\n 1 0.000 0.000 0.000 0.000 {built-in method _locale._getdefaultlocale}\n 1 0.000 0.000 0.000 0.000 boggle.py:5(check_board)\n 1 0.000 0.000 0.000 0.000 codecs.py:259(__init__)\n 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n</code></pre>\n\n<p>The first few lines are just the call sequence in: for example there's a lot of time (cumtime) spent in <code>find_words</code> but almost all of it is in functions that it's calling and very little in the function directly (tottime). That's not where you want to cut down. </p>\n\n<p>Instead, a huge amount of time is spent within <code>deepcopy</code>: 27 of 32 seconds. That is genuine time expenditure, and a good place to start hitting. Two options occur to me: either look for a simpler board representation that is cheaper and easier to copy, or try to avoid the copies. </p>\n\n<p>For option 1, the obvious simpler thing is a flat list or tuple with sixteen elements, which you then index into as [row * 4 + column]. The data would be the same, but you'd avoid the overhead of copying all the extra lists. </p>\n\n<p>For option 2, you'd want to use one board and keep track of what you're changing (and, depending on your implementation, perhaps exactly one copy of the board you never change). When you use a letter you'd stub it out; when you come back up the tree you'd replace the stub symbol with the original letter. </p>\n\n<p>I haven't done it myself and it's always dangerous guessing at performance, but I would be optimistic about getting four to five times faster with that second change. </p>\n\n<hr>\n\n<p>The above is trying for efficiency gains with minimal changes to the underlying algorithm. If you want to get much faster, however, you'll need to change your approach to the problem. The first rule of getting a job done faster is \"The fastest work is the work you don't do.\" </p>\n\n<p>Although I said earlier and stand by that you don't need to start optimising <code>dictionary_check</code>, there may be some opportunities to benefit from knowing your word list while you explore the grid. For example, there are no words that start with \"plt\". If, then, your <code>running_string</code> is \"plt\" then all future strings you find are guaranteed to get filtered out at the end. One option would be to read your word list at the start, and prepare a dictionary of all the prefixes that appear. As you recursively call <code>words_from</code>, if the <code>running_string</code> is not in the prefix dictionary, return immediately. That would probably offer enough gains that you could remove your limit to length 8 words. </p>\n\n<hr>\n\n<p>I notice that the question and code have been editted several times since I started this answer. I'm just going to post it as is, and hope that except in the most fiddly details it is still helpful.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T22:25:59.520", "Id": "430858", "Score": "0", "body": "Thanks. Its nice to know where the program was slow. As for the changes I made they were just brushing up the code rather than changing the implementation. I will see if I can change the deepcopy method to get a faster result" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T22:31:39.773", "Id": "430859", "Score": "0", "body": "as you can see from the update now, the code is much faster! Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T22:35:13.987", "Id": "430860", "Score": "0", "body": "I will now work on trying to block recursive builds for word prefixes that will never form a word such as \"plt\"" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T22:20:18.743", "Id": "222553", "ParentId": "222546", "Score": "3" } } ]
{ "AcceptedAnswerId": "222553", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T18:51:13.560", "Id": "222546", "Score": "5", "Tags": [ "python", "python-3.x", "strings", "recursion" ], "Title": "A recursive Boggle solver" }
222546
<p>Is the code below an efficient way to get the zip file from the server? The code works fine but I'm wondering if I should throw some exceptions for the following conditions:</p> <ol> <li><p><code>if(param1 == null || param2 == null)</code></p></li> <li><p><code>} else if ("".equals(param1) || "".equals(param2)) {</code></p></li> </ol> <p>The way I call this servlet from a web browser is as follows:</p> <pre><code>https://myserver.com/DownloadFileFromServer/DownloadFileServlet?filename=my_users_files_1560866090.zip&amp;user=TAN </code></pre> <p>Eventually, I'll call the above URL from my user interface when a user would have clicked a <code>Download</code> button, maybe using Javascript's <a href="https://www.w3schools.com/jsref/met_win_settimeout.asp" rel="nofollow noreferrer">setTimeout()</a> method. The reason I plan on calling it again and again for sometime is because the file might not be available on the server and I would have to keep on checkiing it again and again. Do I need to handle this part in my servlet code somehow? I mean, I would keep on callling the above URL until I get the file from the server. </p> <pre><code>@WebServlet("/DownloadFileServlet") public class DownloadFileServlet extends HttpServlet { final String[][] contentTypes = {{"zip" ,"application/zip"},{"csv" ,"text/csv"},{"pdf","application/pdf"}}; private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param1 = request.getParameter("filename"); String param2 = request.getParameter("user"); System.out.println("File Name Retrieved is:"+param1); System.out.println("User Name Retrieved is:"+param2); final String FILE_LOCATION = "/srv/my_users/param2/"; if(param1 == null || param2 == null) { // The Request Parameters Were Not Present In The Query String. Do Something Or Exception Handling !! System.out.println("Request Parameter Not Found in first if!"); } else if ("".equals(param1) || "".equals(param2)) { // The Request Parameters Were Present In The Query String But Has No Value. Do Something Or Exception Handling !! System.out.println("Request Parameter Not Found in second if!"); } else { /*if (param1 != null &amp;&amp; param2 !=null) {*/ String fileName = (String) param1; String contentType = getContentType(fileName.split("\\.")[1]); File file = new File(FILE_LOCATION + "/" +fileName); response.setContentType(contentType); response.addHeader("Content-Disposition","attachment; filename=" + fileName); response.setContentLength((int) file.length()); ServletOutputStream servletOutputStream = response.getOutputStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file)); int bytesRead = bufferedInputStream.read(); while (bytesRead != -1) { servletOutputStream.write(bytesRead); bytesRead = bufferedInputStream.read(); } if (servletOutputStream != null) servletOutputStream.close(); if(bufferedInputStream != null) bufferedInputStream.close(); } //response.getWriter().append("Served at: ").append(request.getContextPath()); } private String getContentType(String fileType) { String returnType = null; for(int i = 0; i &lt; contentTypes.length; i++) { if(fileType.equals(contentTypes[i][0])) returnType = contentTypes[i][1]; } return returnType; } } </code></pre>
[]
[ { "body": "<p>If the parameters are required then they need to be checked and their invalidity must be reported to the caller. There is a HTTP status code for it: <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400\" rel=\"nofollow noreferrer\">400/BAD REQUEST</a>.</p>\n\n<p>The file transfer is done one byte at a time. This is very inefficient. This kind of transer is usually done in 4096 byte blocks. There are libraries for this task too. For example <a href=\"https://commons.apache.org/proper/commons-io/\" rel=\"nofollow noreferrer\">Apache Commons IO</a> <code>IOUtil.copy(InputStream, OutputStream)</code>.</p>\n\n<p>The content type mappings are inefficient. A Map would be a natural fit for the use case instead of a 2D array. But this is something you don't need to do yourself: <a href=\"https://stackoverflow.com/questions/51438/getting-a-files-mime-type-in-java\">https://stackoverflow.com/questions/51438/getting-a-files-mime-type-in-java</a></p>\n\n<p>Calling the servlet repeatedly is called polling. A polling service should be quick and lightweight to not cause excessive load. The client should implement waiting between the polling. The servlet doesn't really need to know about the polling interval. If the servlet should implement throttling of \"too eager clients\", then you need to implement authentication to identify clients. Depending on the infrastructure you have, you might want to use a firewall or an API gateway for throttling.</p>\n\n<p>By creating the file path by concatenating input from a URL parameter to a path constant you allow the caller to add directories to the path name. E.g. a file name <code>\"../../some/sensitive/file.txt\"</code> might reveal data you want to keep hidden. It is safer to get a file list from the directory with <code>File.list(FileNameFilter)</code> and use the filter find the file that matches the requested file. Other approach is to sanitize the input, but in mny opinion this is a much more robust solution. If there are a lot of files in the directory and there are a lot of requiests, you might want to cache the file list for a few seconds.</p>\n\n<p>Closing the servlet output stream may have <a href=\"https://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter\">unwanted side effects</a>, so you should just leave it to the servlet container.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T13:54:10.943", "Id": "430932", "Score": "0", "body": "Thanks. So, I'll remove this line `if (servletOutputStream != null) servletOutputStream.close();` and it's okay to leave this line `if(bufferedInputStream != null) bufferedInputStream.close();` as it is?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T05:53:20.067", "Id": "430995", "Score": "0", "body": "Yes, but you can remove the null check too. A constructor either returns an object or throws an exception, so if you get that far, bufferedInputStream is guaranteed to be non-null." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T13:59:12.173", "Id": "431044", "Score": "0", "body": "Oh, when you say `but you can remove the null check too`, you mean I can get rid of this line `if(bufferedInputStream != null) bufferedInputStream.close();` as well ? Basically, I can remove both the lines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-24T07:25:07.860", "Id": "431517", "Score": "0", "body": "No, just the null check before bufferedInputStream.close();." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T06:52:46.487", "Id": "222567", "ParentId": "222548", "Score": "1" } } ]
{ "AcceptedAnswerId": "222567", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T19:20:14.343", "Id": "222548", "Score": "3", "Tags": [ "java", "validation", "servlets" ], "Title": "Servlet to let a user download a file" }
222548
<p>This question is a follow up to my previous one which can be found <a href="https://codereview.stackexchange.com/questions/222418/compact-command-line-argument-parser">here</a>. The user <a href="https://codereview.stackexchange.com/users/200620/dfhwze">dfhwze</a> suggested me to look into compiler construction and recommended me to write a lexer and a parser that would process the input step by step. I am very grateful that he pointed me into this direction, because I have the feeling everything is much more robust now. As this is my first time implementing a lexer and a parser I am convinced there are still things that can be optimized a lot.</p> <p>A few things things that come to my mind:</p> <ol> <li>Are my naming conventions fine? Are all identifiers self-descriptive?</li> <li>Can I abstract the project more? I'd like it to be as flexible as possible.</li> <li>Are there performance optimizations that can be made?</li> </ol> <p>Notes:</p> <ol> <li>Comma separated lists are intentionally processed as one argument.</li> </ol> <p>To test the code run the unit tests (xUnit).</p> <p><strong>CommandLineLexer.cs</strong></p> <pre><code>public class CommandLineLexer { /// &lt;summary&gt; /// To read a stream if characters /// &lt;/summary&gt; private readonly TextReader _reader; /// &lt;summary&gt; /// The current token that is processed /// &lt;/summary&gt; private CommandLineToken? _currentToken; /// &lt;summary&gt; /// Create a new lexer for an incoming character stream /// &lt;/summary&gt; /// &lt;param name="reader"&gt;The text reader that processes the data&lt;/param&gt; public CommandLineLexer(TextReader reader) { _reader = reader; } /// &lt;summary&gt; /// Gets the next character in the stream /// &lt;/summary&gt; /// &lt;returns&gt;Read the next character&lt;/returns&gt; private char ReadCharacter() { char c = (char) _reader.Read(); return c; } /// &lt;summary&gt; /// Reads next CommandLineToken /// &lt;/summary&gt; /// &lt;returns&gt;The next lexed token&lt;/returns&gt; public CommandLineToken Next() { var nextToken = Peek(); _currentToken = null; return nextToken; } /// &lt;summary&gt; /// Check next token but doesn't read it yet /// &lt;/summary&gt; /// &lt;returns&gt;The next token&lt;/returns&gt; public CommandLineToken Peek() { if (_currentToken == null) _currentToken = ReadNextToken(); return _currentToken.Value; } /// &lt;summary&gt; /// Verifies if there are more character is the inputstream /// &lt;/summary&gt; /// &lt;returns&gt;true if there are more characters, false if end of inputstream&lt;/returns&gt; public bool HasNext() { if (_currentToken == null) { SkipWhitespaces(); return _reader.Peek() != -1; } return true; } /// &lt;summary&gt; /// Do not process whitespaces in the input unless they are part of an argument /// &lt;/summary&gt; private void SkipWhitespaces() { while (true) { int c = _reader.Peek(); if (c == -1 || !char.IsWhiteSpace((char) c)) break; ReadCharacter(); } } /// &lt;summary&gt; /// Read the next token /// &lt;/summary&gt; /// &lt;returns&gt;The next lexed token&lt;/returns&gt; /// &lt;exception cref="EndOfStreamException"&gt;&lt;/exception&gt; private CommandLineToken ReadNextToken() { SkipWhitespaces(); int peakedChar = _reader.Peek(); if (peakedChar == -1) throw new EndOfStreamException(nameof(_reader)); char character = (char) peakedChar; // Parsing Logic switch (character) { case '-': return ReadSwitch(); case '"': return ReadQuotedArg(); case ',': return ReadCommaSeparator(); default: return ReadArg(); } } /// &lt;summary&gt; /// Reads arguments that start and end with a quotionmark /// &lt;/summary&gt; /// &lt;returns&gt;The lexed argument token&lt;/returns&gt; private CommandLineToken ReadQuotedArg() { var stringBuilder = new StringBuilder(); while (true) { stringBuilder.Append(ReadCharacter()); int chr = _reader.Peek(); if (chr == -1 || chr == '"') { stringBuilder.Append("\""); ReadCharacter(); break; } } return new CommandLineToken(CommandLineTerminal.Argument, stringBuilder.ToString()); } /// &lt;summary&gt; /// Reads a comma separator token /// &lt;/summary&gt; /// &lt;returns&gt;The lexed comma token&lt;/returns&gt; private CommandLineToken ReadCommaSeparator() { return new CommandLineToken(CommandLineTerminal.Comma, ReadCharacter().ToString()); } /// &lt;summary&gt; /// Reads an argument token /// &lt;/summary&gt; /// &lt;returns&gt;The lexed comma token&lt;/returns&gt; private CommandLineToken ReadArg() { var stringBuilder = new StringBuilder(); var allowedChars = "abcdefghijklmonopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!:!?.".ToList(); while (true) { int chr = _reader.Peek(); if (chr == -1) break; if (chr == ',' || chr == ' ') break; if (!allowedChars.Contains((char) chr)) throw new FormatException($"Illegal character in argument"); stringBuilder.Append(ReadCharacter()); } return new CommandLineToken(CommandLineTerminal.Argument, stringBuilder.ToString()); } /// &lt;summary&gt; /// Reads an argument token /// &lt;/summary&gt; /// &lt;returns&gt;The lexed switch token&lt;/returns&gt; private CommandLineToken ReadSwitch() { var stringBuilder = new StringBuilder(); var allowedChars = "abcdefghijklmonopqrstuvxyz-".ToList(); while (true) { int chr = _reader.Peek(); if (chr == -1 || chr == ' ') break; if (!allowedChars.Contains((char) chr)) throw new FormatException($"Illegal character in switch: {(char) chr}"); stringBuilder.Append(ReadCharacter()); } if (stringBuilder.ToString().All(x =&gt; x == '-')) throw new FormatException("Switch does not have a name"); return new CommandLineToken(CommandLineTerminal.Switch, stringBuilder.ToString()); } } </code></pre> <p><strong>CommandLineToken.cs</strong></p> <pre><code>public struct CommandLineToken { public CommandLineTerminal Terminal { get; } public string Text { get; } public CommandLineToken(CommandLineTerminal terminal, string text) { Terminal = terminal; Text = text; } } </code></pre> <p><strong>CommandLineTerminal.cs</strong></p> <pre><code>public enum CommandLineTerminal { /// &lt;summary&gt; /// Switch /// &lt;/summary&gt; Switch, /// &lt;summary&gt; /// Argument of a switch /// &lt;/summary&gt; Argument, /// &lt;summary&gt; /// Separator for a list of arguments /// &lt;/summary&gt; Comma, } </code></pre> <p><strong>CommandLineParser.cs</strong></p> <pre><code>public class CommandLineParser { /* Grammar: * * switches &lt;- switch+ * switch &lt;- SWITCH args * args &lt;- ARGUMENT (COMMA ARGUMENT)* */ private readonly CommandLineLexer _lexer; public CommandLineParser(CommandLineLexer lexer) { _lexer = lexer ?? throw new ArgumentNullException(nameof(lexer)); } public CommandLineParser(TextReader reader) : this(new CommandLineLexer(reader)) { } public CommandLineParser(string input) : this(new StringReader(input)) { } public IEnumerable&lt;CommandLineExpression&gt; ParseAll() { var parsed = new List&lt;CommandLineExpression&gt;(); while (_lexer.HasNext()) parsed.Add(Parse()); return parsed; } private CommandLineExpression Parse() { var @switch = ExpectOneOf(CommandLineTerminal.Switch); // Switch without args if (!_lexer.HasNext()) return new CommandLineExpression(@switch.Text, null); // Verify if there are more args after switch while (true) { var next = _lexer.Peek(); switch (next.Terminal) { case CommandLineTerminal.Switch: break; case CommandLineTerminal.Argument: { var allArgs = ParseAllArgs(); return new CommandLineExpression(@switch.Text, allArgs); } default: throw new FormatException("Invalid character"); } } } private IList&lt;IArgument&gt; ParseAllArgs() { var allArgs = new List&lt;IArgument&gt;(); while (true) { if (!_lexer.HasNext()) return allArgs; var next = _lexer.Peek(); switch (next.Terminal) { case CommandLineTerminal.Switch: return allArgs; case CommandLineTerminal.Argument: { // Check if we are dealing with an ArgList var token = _lexer.Next(); if (!_lexer.HasNext()) { allArgs.Add(new CommandLineArgument(token.Text)); return allArgs; } var next2 = _lexer.Peek(); if (next2.Terminal == CommandLineTerminal.Comma) { var argList = ParseArgList(token); allArgs.Add(new CommandLineArgumentList(argList)); break; } // Add arg normally - its not part of a list allArgs.Add(new CommandLineArgument(token.Text)); break; } default: throw new FormatException("Invalid character"); } } } private List&lt;CommandLineArgument&gt; ParseArgList(CommandLineToken token) { bool commaExpected = true; var argList = new List&lt;CommandLineArgument&gt;() {new CommandLineArgument(token.Text)}; while (true) { if (!_lexer.HasNext()) return argList; var next = _lexer.Peek(); switch (@next.Terminal) { case CommandLineTerminal.Switch: { return argList; // kk, new swithc starts we are done processing the arglist } case CommandLineTerminal.Argument: { if (commaExpected) { // end of arg list but there is more args that do not belong to the list return argList; } argList.Add(new CommandLineArgument(_lexer.Next().Text)); commaExpected = true; break; } case CommandLineTerminal.Comma: { if (commaExpected) { commaExpected = false; // consume comma _lexer.Next(); // ?? break; } throw new FormatException(); // two commas after each other? } } } } private CommandLineToken ExpectOneOf(params CommandLineTerminal[] terminals) { var token = _lexer.Next(); if (!terminals.Contains(token.Terminal)) throw new FormatException($"Expected {string.Join(",", "terminals")}"); return token; } } </code></pre> <p><strong>CommandLineExpression.cs</strong></p> <pre><code>public class CommandLineExpression { public string Switch { get; } public IList&lt;IArgument&gt; Args { get; } public CommandLineExpression(string @switch, IList&lt;IArgument&gt; args) { Switch = @switch; Args = args; } // Can this be optimized? public override bool Equals(object obj) { var cmp = obj as CommandLineExpression ?? throw new ArgumentNullException(nameof(obj)); if (Switch != cmp.Switch) return false; if (Args == null ^ cmp.Args == null) return false; if (Args == null &amp;&amp; cmp.Args == null) return true; if (Args.Count != cmp.Args.Count) return false; for (var index = 0; index &lt; Args.Count; index++) { // Verify if both args are arglists if (Args[index] is CommandLineArgumentList) { // Compare args and arglists too if (cmp.Args[index] is CommandLineArgumentList) { // Iterate arg lists of both args for (var index2 = 0; index2 &lt; ((CommandLineArgumentList) Args[index]).Arg.Count; index2++) { var argListItem1 = ((CommandLineArgumentList) Args[index]).Arg[index2]; var argListItem2 = ((CommandLineArgumentList) cmp.Args[index]).Arg[index2]; if (argListItem1.Argument != argListItem2.Argument) return false; } } else { return false; } continue; } if (cmp.Args[index] is CommandLineArgumentList) { // Compare args and arglists too if (Args[index] is CommandLineArgumentList) { // Compare args and arglists too for (var index2 = 0; index2 &lt; ((CommandLineArgumentList) Args[index]).Arg.Count; index2++) { var argListItem1 = ((CommandLineArgumentList) Args[index]).Arg[index2]; var argListItem2 = ((CommandLineArgumentList) cmp.Args[index]).Arg[index2]; if (argListItem1.Argument != argListItem2.Argument) return false; } } else { return false; } continue; } // If argument is not a list do the normal comparison var arg = (CommandLineArgument) Args[index]; var arg2 = (CommandLineArgument) cmp.Args[index]; if (arg.Argument != arg2.Argument) return false; } return true; } } </code></pre> <p><strong>CommandLineArgumentList.cs</strong></p> <pre><code>public class CommandLineArgumentList : IArgument { public IList&lt;CommandLineArgument&gt; Arg { get; } public CommandLineArgumentList(IList&lt;CommandLineArgument&gt; arg) { Arg = arg; } } </code></pre> <p><strong>CommandLineArgument.cs</strong></p> <pre><code>public class CommandLineArgument : IArgument { public string Argument { get; } public CommandLineArgument(string argument) { Argument = argument; } } </code></pre> <p><strong>IArgument.cs</strong></p> <pre><code>public interface IArgument { } </code></pre> <p>Unit tests for verification:</p> <p><strong>CommandLineParserTest.cs</strong></p> <pre><code>using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace TinyCommandLineParser.Core.Tests { public class CommandLineParserTest { [Fact] public void ParseSwitchNoArgumentTest() { var parser = new CommandLineParser("--verbose"); var actual = parser.ParseAll().ToList()[0]; var expected = new CommandLineExpression("--verbose", null); Assert.Equal(actual, expected); } [Fact] public void ParseShit() { var parser = new CommandLineParser("--test --values file1 file2 --data A,B,C"); var actual = parser.ParseAll().ToList(); var expected = new List&lt;CommandLineExpression&gt; { new CommandLineExpression("--verbose", null), new CommandLineExpression("--values", new List&lt;IArgument&gt;() { new CommandLineArgument("file1"), new CommandLineArgument("file2") }), new CommandLineExpression("--data", new List&lt;IArgument&gt;() { new CommandLineArgumentList(new List&lt;CommandLineArgument&gt;() { new CommandLineArgument("A"), new CommandLineArgument("B"), new CommandLineArgument("C") }), }) }; Assert.All(actual, x =&gt; Assert.Equal(actual, expected)); } [Fact] public void ParseSwitchMultipleArgumentTest() { var parser = new CommandLineParser("--data file1.txt file2.txt file3.txt"); var actual = parser.ParseAll().ToList(); var expected = new List&lt;CommandLineExpression&gt; { new CommandLineExpression("--data", new List&lt;IArgument&gt;() { new CommandLineArgument("file1.txt"), new CommandLineArgument("file2.txt"), new CommandLineArgument("file3.txt"), }) }; Assert.All(actual, x =&gt; Assert.Equal(actual, expected)); } [Fact] public void ParseSwitchesWithArgumentListsTest() { var stringBuilder = new StringBuilder(); stringBuilder.Append("--data start.txt file1.txt,file2.txt,file3.txt end.txt "); stringBuilder.Append("--output-dir \"/home/user/my docs/\""); stringBuilder.Append("--more-data start2.txt file4.txt,file5.txt end2.txt "); stringBuilder.Append("--verbose"); var parser = new CommandLineParser(stringBuilder.ToString()); var actual = parser.ParseAll().ToList(); var expected = new List&lt;CommandLineExpression&gt; { new CommandLineExpression("--data", new List&lt;IArgument&gt;() { new CommandLineArgument("start.txt"), new CommandLineArgumentList(new List&lt;CommandLineArgument&gt;() { new CommandLineArgument("file1.txt"), new CommandLineArgument("file2.txt"), new CommandLineArgument("file3.txt") }), new CommandLineArgument("end.txt"), }), new CommandLineExpression("--output-dir", new List&lt;IArgument&gt;() { new CommandLineArgument("\"/home/user/my docs/\"") }), new CommandLineExpression("--more-data", new List&lt;IArgument&gt;() { new CommandLineArgument("start2.txt"), new CommandLineArgumentList(new List&lt;CommandLineArgument&gt;() { new CommandLineArgument("file4.txt"), new CommandLineArgument("file5.txt"), }), new CommandLineArgument("end2.txt"), }), new CommandLineExpression("--verbose", null) }; Assert.All(actual, x =&gt; Assert.Equal(actual, expected)); } } } </code></pre> <p><strong>CommandLineLexerTest.cs</strong></p> <pre><code>using System; using System.Collections.Generic; using System.IO; using Xunit; namespace TinyCommandLineParser.Core.Tests { public class CommandLineLexerTest { [Fact] public void LexIncorrectlyFormattedSwitchTest() { Assert.Throws&lt;FormatException&gt;(() =&gt; { var lexer = new CommandLineLexer(new StringReader("--ver´bose")); lexer.Next(); }); Assert.Throws&lt;FormatException&gt;(() =&gt; { var lexer = new CommandLineLexer(new StringReader("--")); lexer.Next(); }); Assert.Throws&lt;FormatException&gt;(() =&gt; { var lexer = new CommandLineLexer(new StringReader("-")); lexer.Next(); }); } [Fact] public void LexQuotedArgTest() { var input = "--phrase \"this is a test\" --info \"this is cool\""; var lexer = new CommandLineLexer(new StringReader(input)); var tokens = new List&lt;CommandLineToken&gt;(); while (lexer.HasNext()) tokens.Add(lexer.Next()); var expected = new List&lt;CommandLineToken&gt;() { new CommandLineToken(CommandLineTerminal.Switch, "--phrase"), new CommandLineToken(CommandLineTerminal.Argument, "\"this is a test\""), new CommandLineToken(CommandLineTerminal.Switch, "--info"), new CommandLineToken(CommandLineTerminal.Argument, "\"this is cool\"") }; Assert.Equal(expected, tokens); } [Fact] public void LexMultipleArgsTest() { var input = "--load valueA valueB valueC 0x0600001"; var lexer = new CommandLineLexer(new StringReader(input)); var tokens = new List&lt;CommandLineToken&gt;(); while (lexer.HasNext()) tokens.Add(lexer.Next()); var expected = new List&lt;CommandLineToken&gt;() { new CommandLineToken(CommandLineTerminal.Switch, "--load"), new CommandLineToken(CommandLineTerminal.Argument, "valueA"), new CommandLineToken(CommandLineTerminal.Argument, "valueB"), new CommandLineToken(CommandLineTerminal.Argument, "valueC"), new CommandLineToken(CommandLineTerminal.Argument, "0x0600001") }; Assert.Equal(expected, tokens); } [Fact] public void LexLongSwitchesTest() { var input = "--output-directory --verbose -i -rt"; var lexer = new CommandLineLexer(new StringReader(input)); var tokens = new List&lt;CommandLineToken&gt;(); while (lexer.HasNext()) tokens.Add(lexer.Next()); var expected = new List&lt;CommandLineToken&gt;() { new CommandLineToken(CommandLineTerminal.Switch, "--output-directory"), new CommandLineToken(CommandLineTerminal.Switch, "--verbose"), new CommandLineToken(CommandLineTerminal.Switch, "-i"), new CommandLineToken(CommandLineTerminal.Switch, "-rt") }; Assert.Equal(expected, tokens); } [Fact] public void LexCommaSeparatedArgsTest() { var input = "--data here,is,some,random,data,123,\"more stuff\",cool"; var lexer = new CommandLineLexer(new StringReader(input)); var tokens = new List&lt;CommandLineToken&gt;(); while (lexer.HasNext()) tokens.Add(lexer.Next()); var expected = new List&lt;CommandLineToken&gt;() { new CommandLineToken(CommandLineTerminal.Switch, "--data"), new CommandLineToken(CommandLineTerminal.Argument, "here"), new CommandLineToken(CommandLineTerminal.Comma, ","), new CommandLineToken(CommandLineTerminal.Argument, "is"), new CommandLineToken(CommandLineTerminal.Comma, ","), new CommandLineToken(CommandLineTerminal.Argument, "some"), new CommandLineToken(CommandLineTerminal.Comma, ","), new CommandLineToken(CommandLineTerminal.Argument, "random"), new CommandLineToken(CommandLineTerminal.Comma, ","), new CommandLineToken(CommandLineTerminal.Argument, "data"), new CommandLineToken(CommandLineTerminal.Comma, ","), new CommandLineToken(CommandLineTerminal.Argument, "123"), new CommandLineToken(CommandLineTerminal.Comma, ","), new CommandLineToken(CommandLineTerminal.Argument, "\"more stuff\""), new CommandLineToken(CommandLineTerminal.Comma, ","), new CommandLineToken(CommandLineTerminal.Argument, "cool"), }; Assert.Equal(expected, tokens); } } } </code></pre> <p>Please be nitpicky in the review :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T04:42:40.333", "Id": "430871", "Score": "1", "body": "I quickly glanced over the code and I'm impressed :) Could you include some unit tests to see how this parser/lexer works?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T07:42:54.963", "Id": "430894", "Score": "0", "body": "@dfhwze I totally forgot to attach the tests :D\nI've added unit tests for the lexer and for the parser." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T07:50:11.620", "Id": "430895", "Score": "0", "body": "I don't have time to review it today, but I will get to it asap. I do have a question for you. Do you want quoted arguments to remain quoted after being parsed into CommandLineArgument? I can image the token keeping the quotes, but the parsed results should not. Also think about literals that have quotes inside them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T07:55:38.587", "Id": "430896", "Score": "1", "body": "Yeah, I guess it would make sense to remove the quotes. I left them because the lexer should process every character, however it would make sense to remove them in the parser as they could be seen as pollution of the output.." } ]
[ { "body": "<h3>API</h3>\n\n<ul>\n<li>Calling code has to pass input to <code>CommandLineParser</code>'s constructor, but do the actual parsing with <code>ParseAll</code>. Calling <code>ParseAll</code> a second time then returns an empty output. A static <code>CommandLineParser.Parse(input)</code> method that creates that instance internally would be more sensible.</li>\n<li>It's not clear what syntax this parser supports. Both <code>\"/?\"</code> and <code>\"--file C:\\test.txt\"</code> result in a <code>FormatException: Illegal character in argument</code>. It's a good idea to document this for the users of your API.</li>\n<li>Likewise, it's not clear what constructs are supported. It looks like every switch must have one or more values? Except when it's the last switch? And switches can have multiple groups of multiple values?</li>\n<li><code>\"-switch arg\"</code> results in a <code>FormatException: Illegal character in switch: w</code>. <code>\"-h1 arg\"</code> fails in a similar manner, and so do <code>\"-a=b\"</code> and <code>\"-a:b\"</code>. Not to mention other languages like <code>\"-号 123\"</code>.</li>\n<li>The API is relatively low-level, with callers having to search through a list of switches and arguments and having to remove hyphens and quotes. A higher-level approach that lets callers describe the options that they support would be more useful. It may also be a good idea to support multiple input formats, such as <code>-f</code>, <code>/f</code> and <code>--file</code>, and have them all map to the same <code>file</code> option.</li>\n<li>Switch arguments are not very intuitive due to their <code>IArgument</code> type. Why not use a simple array of strings instead?</li>\n</ul>\n\n<h3>Lexer</h3>\n\n<ul>\n<li>It's clear that a lot of care went into the lexer. Good first impression.</li>\n<li>I'd remove some of the field comments - names like <code>_reader</code> and <code>_currentToken</code> are descriptive enough on their own.</li>\n<li><code>_currentToken</code> should probably be named <code>_nextToken</code> or <code>_peekedToken</code>.</li>\n<li><code>ReadCharacter</code> doesn't check if <code>_reader</code> is exhausted (<code>_reader.Read() == -1</code>).</li>\n<li><code>Next</code> and <code>Peek</code> can throw an <code>EndOfStreamException</code> if there's nothing left. You may want to document that.</li>\n<li><code>ReadArg</code> and <code>ReadSwitch</code> create a list of allowed characters on every call. Those lists should be static, but Linq's <code>Contains</code> method also allows you to work with just strings. Still, a whitelist approach is very restrictive. I'd go for blacklisting specific characters or perhaps specific Unicode categories.</li>\n<li><code>TextReader</code> should be disposed after use.</li>\n</ul>\n\n<h3>Parser</h3>\n\n<ul>\n<li>I'd rename <code>parsed</code> to <code>expressions</code> and <code>Parse</code> to <code>ParseExpression</code>.</li>\n<li><code>Parse</code> gets stuck in its <code>while</code> loop when a switch is followed by another switch. Parsing <code>\"-a -b\"</code> never ends.</li>\n<li><code>ExpectOneOf</code> joins the string <code>\"terminals\"</code>, instead of the parameter <code>terminals</code>. This results in a not very helpful exception message.</li>\n</ul>\n\n<h3>Arguments</h3>\n\n<ul>\n<li><code>CommandLineExpression</code>, <code>CommandLineArgumentList</code> and <code>CommandLineArgument</code> look like you intended them to be immutable. That's a good idea. There's one problem though: those <code>IList</code> properties may not be settable, but they are mutable. <code>IReadOnlyList</code> is better.</li>\n<li>Regarding <code>CommandLineExpression.Equals</code>:\n\n<ul>\n<li>Why do you need an equality check for this? If it's useful, why not also implement <code>IEquatable&lt;CommandLineExpression&gt;</code>?</li>\n<li>If you override <code>Equals</code>, you're also supposed to override <code>GetHashCode</code>.</li>\n<li>I don't expect <code>Equals</code> to throw, and throwing an <code>ArgumentNullException</code> when <code>obj</code> is of a different type is misleading.</li>\n<li>This method can indeed be simplified a lot. Implement <code>Equals</code> in both <code>CommandLineArgumentList</code> and <code>CommandLineArgument</code>, so you can use <code>Enumerable.SequenceEqual</code> to compare the <code>Args</code> lists.</li>\n<li>Instead of <code>if (condition) { ... } else { return ..; }</code>, you can use early-out returns to reduce nesting depth: <code>if (!condition) return ..; ...</code>. This often makes code easier to read.</li>\n</ul></li>\n<li><code>IArgument</code> and the classes that implement it seem more complicated than necessary. What's the use of <code>\"-a 1,2 3,4\"</code> returning a list of argument-lists? How do callers know that they won't have to process a tree of arbitrary depth?</li>\n</ul>\n\n<h3>Tests</h3>\n\n<ul>\n<li>In <code>ParseSwitchNoArgumentTest</code>, <code>parser.ParseAll().ToList()[0]</code> can be simplified to <code>parser.ParseAll().First()</code>. However, what if the result is empty, or what if it contains extra unexpected items? It's better to compare the whole result instead of picking the first item.</li>\n<li>The next test is poorly named. It can also be simplified by writing a few helper methods that can create (lists of) expressions and arguments. <code>params</code> is useful here.</li>\n<li>I don't have XUnit here to verify, but in that test it looks like you're comparing each expression against the full list of expected expressions. Also, the names of the first switch items don't match. Are these tests actually passing?</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T22:21:11.233", "Id": "430976", "Score": "0", "body": "Thank you for the in-depth feedback. I'll definitely apply some of these suggestions. Can you again elaborate on the optimization of the Equals() method? I am not so sure if I got that. Also I definitely have to write a unit test for that bug you found!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T07:19:49.700", "Id": "431002", "Score": "0", "body": "`bool Equals(object obj) => obj is CommandLineExpression other && Switch == other.Switch && ((Args == null) == (other.Args == null)) && (Args == null || Args.SequenceEqual(other.Args));` - a bit too long for `=>` notation, but you get the idea. The other `IArgument` classes also need to implement `Equals` for the `SequenceEqual` call here to work as intended." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T11:34:30.933", "Id": "222577", "ParentId": "222550", "Score": "4" } }, { "body": "<h2>Follow-up</h2>\n\n<p>In your <a href=\"https://codereview.stackexchange.com/questions/222418/compact-command-line-argument-parser\">previous post</a>, I described some design issues I found. \nI'm happy to see your new design is cleaner (specially the lexer) \nand no longer depends on an already parsed array of tokens!</p>\n\n<p><a href=\"https://codereview.stackexchange.com/users/51173/pieter-witvoet\">Pieter Witvoet</a> has already went through your code and detected many edge cases\nyour API falls short. (No need for me to re-iterate them)\nThis is mainly because you still have a \"<strong>lack of clear specification</strong>\".\nI can't stress enough how important this is, specially since you state yourself</p>\n\n<blockquote>\n <p>you want to provide several layers of abstraction and allow for a flexible design.</p>\n</blockquote>\n\n<p>Without going into much detail (I'm mostly using pseudo-code), I will walk you through the steps required to\ncreate a compiler, reflecting back to your code.</p>\n\n<p>But first, we need a <strong>clear specification</strong>.</p>\n\n<hr>\n\n<h2>Specification</h2>\n\n<p>We need to establish a specification. And since we are creating a compiler\nfrom scratch, why not be ambitious about it? \nAs starting point, we have the following snippet with <code>cmd_line_args</code> being the command line arguments string\nand <code>cmd</code> the object graph representing the compiled string.</p>\n\n<p>In pseudo-code:</p>\n\n<p><code>var cmd = compile(cmd_line_args);</code></p>\n\n<h3>Context-bound language</h3>\n\n<p>Consider the following command line: <code>cmd/ioc:\\temp\\</code></p>\n\n<p>It's written in \"<strong>compact form</strong>\", a form with the highest density. \nIt could be normalized to \"<strong>friendly form</strong>\", a form that has optimal readability.</p>\n\n<p>But how should we interpret this? In other words, what is our friendly form?\nThis brings us to our first design decision. Do we require a \"<strong>context</strong>\" or is our\nlanguage \"<strong>context-free</strong>\"?</p>\n\n<ul>\n<li><p>If our language is context-free, the command line above is ill-defined. \nThe compact form would be the same as the friendly form: <code>cmd /io c:\\temp\\</code></p></li>\n<li><p>If on the other hand, our language is context-bound, the command line above would\nhave a different friendly form depending on the context. The context could specify\nthe known switches, which would allow us to combine switches. </p></li>\n</ul>\n\n<p>Some possibilities include:</p>\n\n<ul>\n<li><p>If the context specifies a verb \"cmd\" \nwith switches \"i\" and \"o\"\nwith the former having an argument \"path\", \nthe friendly form would be: <code>cmd /o /i c:\\temp\\</code></p></li>\n<li><p>If the context specifies a verb \"cmd\" \nwith switches \"i\" and \"o\"\nwith the latter having an argument \"path\", \nthe friendly form would be: <code>cmd /i /o c:\\temp\\</code></p></li>\n<li><p>If the context specifies a verb \"cmd\" \nwith switch \"io\" having an argument \"path\", \nthe friendly form would be: <code>cmd /io c:\\temp\\</code></p></li>\n</ul>\n\n<blockquote>\n <p>Let's make sure our compiler is context-free, but can be augmented with an optional context.</p>\n</blockquote>\n\n<p>In pseudo-code:</p>\n\n<p><code>var cmd = compile(cmd_line_args, context = null);</code></p>\n\n<h3>Lexicon</h3>\n\n<p>Next up, we need to determine which delimiters and other keywords are allowed.\nThe command line <code>cmd /o c:\\temp\\</code> could be formatted in different styles.\nNote that the \"<strong>system path seperator</strong>\" influences the delimiters.</p>\n\n<p>Some possibilities include:</p>\n\n<ul>\n<li>win style: <code>cmd /o c:\\temp\\</code></li>\n<li>win posix style: <code>cmd -o c:\\temp\\</code></li>\n<li>win posix long style: <code>cmd --output c:\\temp\\</code></li>\n<li>unix posix style: <code>cmd -o /c/temp/</code></li>\n<li>unix posix long style: <code>cmd --output /c/temp/</code></li>\n</ul>\n\n<p>Furthermore, a switch and its arguments could be formatted in different styles.</p>\n\n<p>Some possibilities include:</p>\n\n<ul>\n<li><code>cmd /o:c:\\temp\\</code></li>\n<li><code>cmd /o=c:\\temp\\</code></li>\n<li><code>cmd /o c:\\temp\\</code></li>\n<li><code>cmd /o c:\\temp\\out1\\ c:\\temp\\out2\\</code></li>\n<li><code>cmd /o c:\\temp\\out1\\,c:\\temp\\out2\\</code></li>\n</ul>\n\n<blockquote>\n <p>Let's make sure our compiler uses a \"<strong>lexicon</strong>\", based on style preference and system path separator.</p>\n</blockquote>\n\n<p>In pseudo-code:</p>\n\n<p><code>var cmd = compile(cmd_line_args, lexicon = default, context = null);</code></p>\n\n<h3>Features</h3>\n\n<p>There is no universal set of features a command line tool must comprise. This means the compiler can\nbe as simple or complex as we decide. The more complex compilers (like Powershell) allow for\nexpressions, piping, and more exotic stuff. Perhaps this is a bridge too far for our use case.</p>\n\n<p>I propose to use the a superset of the most common features found across compilers.</p>\n\n<p>Feature list:</p>\n\n<ul>\n<li>verbs: <code>cmd get-logs</code></li>\n<li>flags: <code>cmd /a -q --verbose</code></li>\n<li>options: <code>cmd /input c:\\in\\ -o=c:\\out\\</code></li>\n<li>arguments: <code>cmd -o c:\\logs\\ c:\\out\\</code></li>\n<li>operands: <code>cmd -o c:\\logs\\ -- readme.txt</code></li>\n<li>combined switches: <code>cmd /aqo c:\\out\\</code> </li>\n<li>repeating options: <code>cmd -o c:\\in\\ -o c:\\in\\nested\\</code></li>\n<li>help: <code>cmd get-logs -? /h --help</code></li>\n<li>about: <code>cmd -! --version</code></li>\n<li>escape sequence: <code>cmd a\\r\\nb</code> ~ a[newline]b</li>\n<li>unicode escape sequence: <code>cmd get-logs \\u002Dq</code> ~ <code>cmd get-logs -q</code></li>\n<li>literal unicode escape sequence: <code>cmd get-logs c:\\temp\\\\x69\\x6E\\</code> ~ <code>cmd get-logs c:\\temp\\in\\</code></li>\n<li>quoted literal: <code>cmd \"my \\\"quoted\\\" literal\"</code></li>\n<li>alt quoted literal: <code>cmd 'my \"quoted\" literal'</code></li>\n</ul>\n\n<p>Definitions:</p>\n\n<ul>\n<li><p><strong>Verb</strong>: defines a group of shared functionality and operations.</p></li>\n<li><p><strong>Switch</strong>: the union of flags and options with their arguments.</p></li>\n<li><p><strong>Flag</strong>: a switch that does not have an argument. It's considered a boolean.</p></li>\n<li><p><strong>Option</strong>: a switch that takes 0..* arguments. Some arguments may be mandatory, others optional.</p></li>\n<li><p><strong>Argument</strong>: the value or one of the values linked to a parent option.</p></li>\n<li><p><strong>Operand</strong>: the value or one of the values linked to the verb, or default verb is none specified.</p></li>\n</ul>\n\n<p>Syntax:</p>\n\n<ul>\n<li>Escaping unicode: <code>\\u[n,4]</code> or <code>\\U[n,8]</code> -> <code>\\u002D</code>, <code>\\U00020B20</code></li>\n<li>Escaping unicode in literal: <code>\\x[n,1-4]</code> -> <code>\\x0</code>, <code>\\x01</code>, <code>\\x001</code>, <code>\\x0001</code></li>\n<li>Quoting literal: \"A string with whitespace, and other delimiters and \\\"escaped\\\" quotes\"</li>\n<li>Alt quoting literal: 'A string with whitespace, and other delimiters and \"no need to escape\" quotes'</li>\n<li>Operand delimiter: <code>cmd -o c:\\logs\\ -- readme.txt</code> -> -- forces all remaining tokens to be operands</li>\n</ul>\n\n<hr>\n\n<h2>Compiler</h2>\n\n<p>Having our specification, we should let a command line go through a set of layers to get it compiled.\nIdeally, we would like to end up with our compiler doing:</p>\n\n<p>In pseudo-code:</p>\n\n<pre><code>// input\nvar cmd_line_args = \"cmd get-logs \\u002Dq -ab c:\\temp\\in\\ -- out.txt\";\n\n// compiler\nvar cmd = compile(cmd_line_args, lexicon = default, context = null);\n\n// print command line back to string, using some style\ncmd.print(win, short) -&gt; \"cmd get-logs -q -a -b c:\\temp\\in\\ -- out.txt\"\ncmd.print(posix, long) -&gt; \"cmd get-logs --quiet --all --binary -c /c/temp/in/ -- out.txt\"\"\n\nlet compile(cmd_line_args, lexicon = default, context = null) = \n{\n var cmd_line_sanitized = preprocess(cmd_line_args);\n var tokens = lex(cmd_line_sanitized, lexicon, context);\n var astTree = parse(tokens, lexicon, context).optmize();\n var graph = materialize(astTree);\n}\n</code></pre>\n\n<h3>1. Pre-processor</h3>\n\n<ul>\n<li>unescape unicode escape sequences: <code>get-logs -q -ab c:\\temp\\in\\ -- out.txt</code></li>\n</ul>\n\n<blockquote>\n <p>Your API does not have a pre-processor defined.</p>\n</blockquote>\n\n<h3>2. Lexer</h3>\n\n<ul>\n<li>create tokens from pre-processed command line string</li>\n</ul>\n\n<blockquote>\n <p>Your API provides a set of tokens.</p>\n\n<pre><code> public enum CommandLineTerminal\n {\n Switch,\n Argument,\n Comma,\n }\n</code></pre>\n</blockquote>\n\n<p>Given our specification, we should extend this:</p>\n\n<pre><code>public enum CommandLineTerminal\n{\n Verb,\n Switch, // could be flag, combined flags, option (lexer might not know the difference)\n Flag,\n Option, \n Argument,\n Operand,\n // keyword terminals (many lexers include these, but keep them hidden from higher layers)\n Whitespace, // contextual\n SwitchPrefix // '-' '/' '--'\n OptionArgumentSeparator, // ':' '=' \n ArgumentDelimiter, // ','\n OperandDelimiter, // '--' (without an option attached)\n}\n</code></pre>\n\n<p>yielding us:</p>\n\n<pre><code>- verb: get-logs\n- whitespace\n- switch prefix: -\n- switch: q\n- whitespace\n- switch prefix: -\n- switch: ab\n- whitespace\n- argument: c:\\temp\\in\\\n- whitespace\n- operand delimiter: --\n- whitespace\n- operand: out.txt\n</code></pre>\n\n<blockquote>\n <p>Your API stores tokens as follow:</p>\n\n<pre><code>public struct CommandLineToken\n{\n public CommandLineTerminal Terminal { get; }\n public string Text { get; }\n\n public CommandLineToken(CommandLineTerminal terminal, string text)\n {\n Terminal = terminal;\n Text = text;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>I would extend this, and keep track of:</p>\n\n<ul>\n<li>line number -> allows for better exception output to consumer</li>\n<li>token type (hidden or normal) -> hidden: white space, delimiters, ..</li>\n</ul>\n\n<h3>3. AST Parser</h3>\n\n<ul>\n<li>create an abstract syntax tree from the tokens</li>\n<li>could use the context of a tree to further refine tokens (switch -> flag or option)</li>\n<li>not all tokens from the lexer end up in the AST</li>\n</ul>\n\n<blockquote>\n <p>Your API does not include this step, instead goes on to materialize directly.</p>\n\n<pre><code> private IList&lt;IArgument&gt; ParseAllArgs()\n {\n // impl ..\n }\n</code></pre>\n</blockquote>\n\n<p>An AST might look like this:</p>\n\n<p>In pseudo-code:</p>\n\n<pre><code> // `get-logs -q -ab c:\\temp\\in\\ -- out.txt`\n Node-&gt;verb: name=get-logs\n child: Node-&gt;flag: name=q longname=quiet\n child: Node-&gt;combined flag: name=ab longname=all\n child: Node-&gt;argument: name=path value=c:\\temp\\in\\\n child: Node-&gt;operand delimiter\n child: Node-&gt;operand: name=logfile value=out.txt\n</code></pre>\n\n<p>In fact, by not using the AST parser, you are working yourself a bit in trouble.\nThis next quote by you makes me think you try to have a flattened parser, rather than\na tree parser.</p>\n\n<blockquote>\n <p>Comma separated lists are intentionally processed as one argument.</p>\n</blockquote>\n\n<p><strong>AST Node</strong></p>\n\n<p>You were struggling to build a tree structure. I suggest a class in the likes of:</p>\n\n<pre><code>class AstNode \n{\n internal AstNode Parent;\n internal List&lt;AstNode&gt; Children;\n internal CommandLineToken Token;\n internal CommandLineTerminal Terminal;\n}\n</code></pre>\n\n<p>Building the AST from a flattened list of lexed tokens requires a common parsing technique <em>shift-reduce</em>. See links for parsing and examples.</p>\n\n<p>Links:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/25049751/constructing-an-abstract-syntax-tree-with-a-list-of-tokens\">How to parse an AST</a></li>\n<li><a href=\"https://stackoverflow.com/questions/21064599/building-parse-trees-with-shift-reduce-parsing\">How to parse an AST using Shift-Reduce</a></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Abstract_syntax_tree\" rel=\"nofollow noreferrer\">AST Wiki</a></li>\n</ul>\n\n<h3>4. AST Optimizer</h3>\n\n<p>A set of predefined optimizers should be run on the AST to normalize the graph.</p>\n\n<p>In our example:</p>\n\n<p>Combined flag <code>ab</code> can be uncombined. The context might show us that the argument belongs to <code>b</code>.</p>\n\n<pre><code>child: Node-&gt;flag: name=a longname=all\nchild: Node-&gt;option: name=b longname=binary\n child: Node-&gt;argument: name=path value=c:\\temp\\in\\\n</code></pre>\n\n<h3>5. Parser / Materializer</h3>\n\n<ul>\n<li>Map the AST to a concrete object graph, usable by consumers of the API.</li>\n</ul>\n\n<blockquote>\n <p>Your API has such classes as <code>CommandLineArgument</code>.</p>\n</blockquote>\n\n<h3>6. Printer</h3>\n\n<ul>\n<li>the materialized graph can be printed back to a command line string</li>\n<li>using tree walkers the graph can be transformed to a string</li>\n</ul>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T23:08:25.337", "Id": "430981", "Score": "0", "body": "Thanks for the review. A lot I need to change ;) Regarding testing, what cases would you recommend me to cover? I've the feeling that I am missing a lot of cases, especially for the parser?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T01:18:06.027", "Id": "430984", "Score": "0", "body": "Another things that I struggle with is to come up with a good tree-like output. As already mentioned in a previous reply the argument lists makes me end up with a very weird data structure. I'd like to encapsulate the output in a class object that allows me for easy access to every switch as well as all the corresponding arguments / argument lists (if any). The main issue with the lists if I don't nest them is, that I can't decide where the list starts. Is the previous element part of the list or not? Can you maybe suggest me a rough class outline, how a parse result class could look like?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T04:28:06.697", "Id": "430990", "Score": "1", "body": "I have always wondered which _genius_ has invented the double-dash argument prefix for full names and single-dash for short ones. I guess he must have hated people because there is nothing more annoying than `--` ;-] @766F6964 be nice to the users of your command-line interpreter and save them from typing something that has absolutely no value. It looks like its only purpose is to allow combining flags which you do like never but always trip up on that damn `--` :-]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T04:39:29.927", "Id": "430991", "Score": "0", "body": "I have included a template for an AstNode and some links describing how to parse AST using shift-reduce. Regarding unit tests, I would make a list of all possible friendly, compact an exotic command lines I can think of that the lexer should allow to handle. For each lexer unit test, include a parser unit test." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T04:41:48.757", "Id": "430992", "Score": "0", "body": "Besides, there are 2 main groups of people that use command lines. System administrators that love compact forms `cmd/abcc:\\temp` and normal humans that want readable command lines `cmd -a -b -c c:\\temp`. Make sure to please both :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T20:29:34.057", "Id": "222600", "ParentId": "222550", "Score": "2" } } ]
{ "AcceptedAnswerId": "222577", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T20:41:29.307", "Id": "222550", "Score": "6", "Tags": [ "c#", "parsing", "reinventing-the-wheel", "console", "lexer" ], "Title": "Compact command line argument parser : Revisited" }
222550
<p>In a game of Connect4:</p> <ul> <li>we start with an empty grid</li> <li>two players place pieces X and O on the grid</li> <li>the first player to achieve 4 pieces in a line wins!</li> <li>this is a text based console game</li> </ul> <p>Here is the code I wrote to print each cell in the grid:</p> <pre><code>def asText(grid: Grid) = { def asText(x:Int, y:Int) = { val isTop = y == 0 &amp;&amp; x != grid.x + 1 &amp;&amp; x != 0 val newLine = x == grid.x + 1 val isBottom = y == grid.y + 1 &amp;&amp; x != 0 val isLeft = x == 0 val isX = grid.pieces.contains(Piece("X", x,y)) val isY = grid.pieces.contains(Piece("O", x,y)) List(isTop, newLine, isBottom, isLeft, isX, isY) match { case true::_ =&gt; "-" case _::true::_ =&gt; "|\n" case _::_::true::_ =&gt; "-" case _::_::_::true::_ =&gt; "|" case _::_::_::_::true::_ =&gt; "X" case _::_::_::_::_::true::_ =&gt; "O" case _ =&gt; "." } } val v = for { y &lt;- 0 to grid.y + 1 x &lt;- 0 to grid.x + 1 text = asText(x, y) } yield text v.mkString("") } </code></pre> <p><strong>I don't like this</strong> <code>_::_::_::_::_::true::_</code> <strong>but can't think of a way to improve it. Can this style be improved? Is there a more Scala idiomatic style to do this?</strong></p> <p>Example output:</p> <pre><code>|------| |XO....| |......| |......| |......| |......| |......| |......| |------| </code></pre> <p>Edit: As requested</p> <pre><code>case class Piece(symbol:String, x:Int, y:Int) case class Grid(x:Int = 6, y:Int = 7, pieces:List[Piece] = List()) </code></pre>
[]
[ { "body": "<p>Is the graphic representation of a data structure an integral part of that data structure (<code>val gString = myGrid.asText</code>) or separate and independent from the data structure (<code>val gString = asText(myGrid)</code>)?</p>\n\n<p>I tend to favor the former, but if the <code>Grid</code> API is solid and supplies everything needed for one or more graphic representations, then the latter is probably the better choice. It's a little hard to judge here as you haven't provided the <code>Grid</code> (or <code>Piece</code>) code.</p>\n\n<p>I question the choice of iterating through coordinates that <em>are known</em> to be outside the <code>Grid</code> just for the purpose of drawing a border. Wouldn't it be easier to get the grid contents and simply \"wrap\" them with border characters?</p>\n\n<pre><code>def asText(grid :Grid) :String = {\n val border = \"|\" + \"-\"*grid.x + \"|\"\n (1 to grid.y).map{ y =&gt;\n (1 to grid.x).map{ x =&gt;\n if (grid.pieces.contains(Piece(\"X\", x, y))) \"X\"\n else if (grid.pieces.contains(Piece(\"O\", x, y))) \"O\"\n else \".\"\n }.mkString(\"|\", \"\", \"|\")\n }.mkString(s\"$border\\n\", \"\\n\", s\"\\n$border\")\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T08:44:27.057", "Id": "430902", "Score": "0", "body": "To answer your question: object Connect4Game {\n def asText(grid :Grid): String = { ... }" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T02:30:35.510", "Id": "222557", "ParentId": "222552", "Score": "3" } } ]
{ "AcceptedAnswerId": "222557", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T22:13:02.780", "Id": "222552", "Score": "4", "Tags": [ "functional-programming", "formatting", "scala", "ascii-art", "connect-four" ], "Title": "Print a Connect 4 grid based on some rules for each cell" }
222552
<p><strong>The task</strong></p> <p>is taken from LeetCode</p> <blockquote> <p>In a row of trees, the <em>i</em>-th tree produces fruit with type <code>tree[i]</code>. You start at any tree of your choice, then repeatedly perform the following steps:</p> <ol> <li>Add one piece of fruit from this tree to your baskets.  If you cannot, stop.</li> <li>Move to the next tree to the right of the current tree.  If there is no tree to the right, stop.</li> </ol> <p>Note that you do not have any choice after the initial choice of starting tree: you must perform step 1, then step 2, then back to step 1, then step 2, and so on until you stop.</p> <p>You have two baskets, and each basket can carry any quantity of fruit, but you want each basket to only carry one type of fruit each. What is the total amount of fruit you can collect with this procedure?  </p> <p><strong>Example 1:</strong></p> <pre><code>Input: [1,2,1] Output: 3 // Explanation: We can collect [1,2,1]. </code></pre> <p><strong>Example 2:</strong></p> <pre><code>Input: [0,1,2,2] Output: 3 // Explanation: We can collect [1,2,2]. // If we started at the first tree, we would only collect [0, 1]. </code></pre> <p><strong>Example 3:</strong></p> <pre><code>Input: [1,2,3,2,2] Output: 4 // Explanation: We can collect [2,3,2,2]. // If we started at the first tree, we would only collect [1, 2]. </code></pre> <p><strong>Example 4:</strong></p> <pre><code>Input: [3,3,3,1,2,1,1,2,3,3,4] Output: 5 // Explanation: We can collect [1,2,1,1,2]. // If we started at the first tree or the eighth tree, we would only collect 4 fruits. </code></pre> <p>  <strong>Note:</strong></p> <ol> <li>1 &lt;= tree.length &lt;= 40000</li> <li>0 &lt;= tree[i] &lt; tree.length</li> </ol> </blockquote> <p><strong>My solution:</strong></p> <p>has time and space complexity of <span class="math-container">\$O(n)\$</span>. At first I thought it was easy. But then, I got confused with the one of the test cases (i.e. <code>I = [3,3,3,1,2,1,1,2,3,3,4];</code>) and everything inside the <code>else</code>-block is a bit hacky afterwards. Maybe there is a more elegant solution to that.</p> <pre><code>/** * @param {number[]} tree * @return {number} */ var totalFruit = function(tree) { const set = new Set(tree); if (set.size &lt;= 2) { return tree.length; } const fruits = new Set(); let i = 0; let j = 0; let max = 0; let count = 0; while (j &lt; tree.length) { if (fruits.size &lt;= 2 &amp;&amp; !fruits.has(tree[j])) { fruits.add(tree[j]); } if (fruits.size &lt;= 2) { count++; max = Math.max(max, count); j++; } else { fruits.delete(tree[i]); const lastIndex = tree.slice(i, j - 1).lastIndexOf(tree[i]); i += lastIndex + 1; count-= lastIndex + 1; } } return max; }; let I = [1,2,1]; I = [0,1,2,2]; I = [3,3,3,1,2,1,1,2,3,3,4]; console.log(totalFruit(I)); </code></pre> <p><strong>Update</strong>: I made a mistake. This should be the accurate solution:</p> <pre><code>/** * @param {number[]} tree * @return {number} */ var totalFruit = function(tree) { let max = 0, count = 0; for (let i = 0, first = 0, second = -1; i &lt; tree.length; i++) { count++; if (tree[i] === tree[first]) { first = i; } else if (second === -1 || tree[i] === tree[second]) { second = i; } else { max = Math.max(count - 1, max); count = Math.abs(first - second) + 1; first = i - 1; second = i; } } return Math.max(count, max); }; </code></pre> <p>Time complexity <span class="math-container">\$O(n)\$</span> and space complexity <span class="math-container">\$O(1)\$</span></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T01:48:45.730", "Id": "430865", "Score": "2", "body": "\\$O(n)\\$ space seems like an overkill. I see no reason to keep the entire set of trees. You only really care of the two fruits you currently carry. Three indices (two for the last time each fruit was picked, and one for a current position) shall do it in constant space." } ]
[ { "body": "<p>Your second solution is good and fast, but you asked about more elegant solution, so I am suggesting mine. Firstly, I solved this task by <strong>Python</strong>, then convert all logic into <strong>Javascript</strong>. It is a little slower, than your (20 ms) and use more memory, but I think it more straightforward and understandable.</p>\n\n<p>The code only answers do not liked on this site, so I add some comparisons:</p>\n\n<ul>\n<li><p><strong>Algorithm.</strong> Both algorithms are similar but:</p>\n\n<ul>\n<li><strong>Mine:</strong> keeps track of every number changing positions. The <code>start1</code> position changes every time the number was changed, so I always know the position, where the previous number was started. The <code>start2</code> position changes only when third number occurs, so I just subtract the <code>start2</code> from the current index and get the needed two number sequence length.</li>\n<li><strong>Your:</strong> keeps track of last occurrences the first and second numbers, so you miss their start positions, and thus, you should use the <code>count</code> variable for storing the length of the current two number sequence. When the third number appears, you need to calculate the value of the last uninterruptible one number sequence by <code>Math.abs(first - second)</code>. Also, you don't know which number was last - <code>first</code> or <code>second</code>, so the <code>Math.abs</code> function is needed.</li>\n</ul></li>\n<li><p><strong>The way of access to array items.</strong> </p>\n\n<ul>\n<li><strong>Mine:</strong> uses the <strong>iterator</strong> - <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\">for...of statement</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries\" rel=\"nofollow noreferrer\">Array.entries()</a>. It relieves us from <code>tree[i]</code> and <code>tree[second]</code> like constructions.</li>\n<li><strong>Your:</strong> Uses <strong>counter and array indexes</strong> to access the needed item.</li>\n</ul></li>\n</ul>\n\n<p><strong>The Javascript code:</strong></p>\n\n<pre><code>var totalFruit = function(tree) {\n let n1 = -1;\n let n2 = -1;\n\n let start1 = 0;\n let start2 = 0;\n\n let maxim = 1;\n # Add extra element in the end of array (which is not occured in array)\n # to get rid of the second 'Math.max(maxim, k - start2)' call\n tree.push(-2);\n\n for (let [k, num] of tree.entries()) {\n if (num !== n1) {\n if (num !== n2) {\n maxim = Math.max(maxim, k - start2);\n start2 = start1;\n }\n\n n2 = n1;\n n1 = num;\n\n start1 = k;\n }\n }\n\n return maxim;\n}\n</code></pre>\n\n<p><strong>The original Python code:</strong></p>\n\n<pre><code>class Solution:\n def totalFruit(self, tree):\n n1 = -1\n n2 = -1\n\n start1 = 0\n start2 = 0\n\n maxim = 1\n tree.append(-2)\n\n for k, num in enumerate(tree):\n if num != n1:\n if num != n2:\n maxim = max(maxim, k - start2)\n\n start2 = start1\n\n n2 = n1\n n1 = num\n\n start1 = k\n\n return maxim\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T15:51:39.337", "Id": "222718", "ParentId": "222554", "Score": "1" } } ]
{ "AcceptedAnswerId": "222718", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T23:22:50.803", "Id": "222554", "Score": "3", "Tags": [ "javascript", "algorithm", "programming-challenge" ], "Title": "Collect maximum fruits in two baskets of at most 2 types of fruits" }
222554
<p>I'm seeking a critique of the simple program below, which displays two counters and increments them through a button, using D3.js. In real life of course no one has a need for displaying buttons that increment counters. It's a stand-in to talk about how to craft the code over the scaffold of a trivial problem.</p> <p>I would like to remain within function invocations, and to generally fit in seamlessly with D3. In particular, I do not wish to use constructor invocation or prototypal patterns. More concretely, I would like to use neither <code>class</code> nor <code>new</code>.</p> <p>I would also like to avoid constantly asking myself "what is <code>this</code> in this instant?" by initializing <code>that</code>, as you see in the code (let's leave arguing that <code>this</code> is sometimes entirely compelling for another occasion).</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function Incrementer(name, value) { let that = {}; that.init = function() { that.name = name; that.span = d3.select('body') .append('span') .attr('id', '#num' + name) .text(value); } that.init(); that.increment = function() { let i = parseInt(that.span.text()) + 1; that.span .text(i); } return that; } var incrementer1 = Incrementer('one', 10); var incrementer2 = Incrementer('two', 20); function double_increment() { incrementer1.increment(); incrementer2.increment(); } d3.select('#inc') .on('click', double_increment); // d3.select('#inc') // .on('click', incrementer1.increment); // d3.select('#inc') // .on('click', incrementer2.increment);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>span { margin-left: 40px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"&gt;&lt;/script&gt; &lt;button id="inc"&gt;Increment&lt;/button&gt;&lt;br /&gt;</code></pre> </div> </div> </p> <p>At this point I'm lacking a nice way to avoid the function <code>double_increment</code>. Of course without that function—were we to use the commented out pair of on-click handlers instead—we would have a bug. Only one on-click handler can be set. We have no mechanism for adding multiple <code>addEventListener</code>s.</p> <p>So to summarize:</p> <ol> <li>We define <code>that.init</code> as our initializer. That seems tidier than letting the initialization code loose in the body of the function. But defining it then immediately calling it seems odd. Can you improve on this?</li> <li>How would you avoid the ugly <code>double_increment</code> function within a D3 program?</li> </ol> <p><code>that.span.text()</code> should probably be replaced by <code>that.span.datum</code>, if I can find the datum in there. But we'd like to avoid duplicating the counter within <code>Incrementer</code>. This way we do not need to worry about the counter and its view going out of sync. The datum itself, once located, is already a bit of a (necessary) duplication.</p>
[]
[ { "body": "<p>The simple way of avoiding needing to define a named function like <code>double_increment</code> is just to use a lambda. You could simply write</p>\n\n<pre><code>d3.select('#inc').on('click',\n () =&gt; {\n incrementer1.increment();\n incrementer2.increment();\n });\n</code></pre>\n\n<p>You could also get fancy and loop through the incrementers too</p>\n\n<pre><code>var incrementors = [incrementer1, incrementer2]\n\nd3.select('#inc').on('click',\n () =&gt; {\n for (inc of incrementors) {\n inc.increment();\n } \n };\n</code></pre>\n\n<p>This lets you easily add new incrementors later if needed. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T13:58:51.323", "Id": "430933", "Score": "0", "body": "That's cool, and it nicely avoids writing a JS abstraction of the Button (one that would store the incrementers). The `init` business remains. Maybe that was a 2-in-1 questions. I'm happy to trim this question, mark the answer, and ask again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T14:56:00.567", "Id": "430939", "Score": "0", "body": "@Calaf \"That seems tidier than letting the initialization code loose in the body of the function. But defining it then immediately calling it seems odd.\". In a case like this, I think loose would be fine. At the top of the function it should be well understood that that's \"constructor code\". The neater, modern solution though would be to make `Incrementor` a [`class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/class), and write up an official [`constructor`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T15:20:58.230", "Id": "430942", "Score": "0", "body": "You're probably right. Yielding would be simpler. Sometimes I worry that I've been much too indoctrinated by the Crockford-Bostock dogma, to the point of getting blasted for it (https://stackoverflow.com/q/56546011/704972)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T03:39:46.877", "Id": "222559", "ParentId": "222558", "Score": "2" } }, { "body": "<p>A short review;</p>\n\n<ul>\n<li>You are mixing model and view functionality in that one function</li>\n<li>The style where you newline at every dot makes your code hard to read</li>\n<li>I would suggest you look in to currying</li>\n</ul>\n\n<p>The below splits out model and view functionality (somewhat) and reduces the amount of newlines.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function createNumberLabel(name, value) {\n\n return d3.select('body').append('span').attr('id', '#num' + name).text(value);\n}\n\nfunction incrementNumberLabel(label){\n\n return () =&gt; label.text(parseInt(label.text()) + 1);\n}\n\n\nvar incrementer1 = incrementNumberLabel(createNumberLabel('one', 10));\nvar incrementer2 = incrementNumberLabel(createNumberLabel('two', 20));\n\nfunction double_increment() {\n incrementer1();\n incrementer2();\n}\n\nd3.select('#inc').on('click', double_increment);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>span { margin-left: 40px; }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js\"&gt;&lt;/script&gt;\n&lt;button id=\"inc\"&gt;Increment&lt;/button&gt;&lt;br /&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T16:05:18.563", "Id": "222588", "ParentId": "222558", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T02:33:46.060", "Id": "222558", "Score": "2", "Tags": [ "javascript", "functional-programming", "html5", "d3.js" ], "Title": "Seeking the seeds for writing tidy event handlers in JS" }
222558
<p>I don't know why in most of the interviews, interviewers are asking this question commonly. </p> <p>The question is: There are <code>n</code> number of persons standing in a circle. The first person has a gun and he kills the very next person who is alive and hands over the gun to the next person. Who will remain?</p> <p>Here is my code for the above scenario. It works, if anyone needs to ask.</p> <pre><code>public static void void main(String ar[]) { int numberOfGuys = 10000; List&lt;Integer&gt; list = new ArrayList&lt;&gt;(); for ( int i = 1; i &lt;= numberOfGuys; i++ ) { list.add( i ); } boolean isNeighbour = false; System.out.println( list ); Iterator&lt;Integer&gt; i = list.iterator(); list = new ArrayList&lt;&gt;(); boolean isTrue = true; while ( isTrue ) { int k = i.next(); if ( isNeighbour ) i.remove(); else { list.add( k ); } if ( !i.hasNext() ) { System.out.println( list ); i = list.iterator(); if ( list.size() == 1 ) isTrue = false; list = new ArrayList&lt;&gt;(); } isNeighbour = !isNeighbour; } } </code></pre>
[]
[ { "body": "<h3>Style review</h3>\n<ul>\n<li><p>I think <code>numberOfGuys</code> should be a parameter obtained in the <code>main</code> args, so that you respect the possibility to obtain <code>n</code> from an external source.</p>\n</li>\n<li><p>As pointed in the comments, don't do <code>isTrue = false</code>, that's... weird. <code>True</code> is <em>always</em> <code>true</code>, period. You could rename it <code>hasRemainingGuys</code> or something like that.</p>\n</li>\n</ul>\n<h3>Data structure</h3>\n<p>Using an <code>ArrayList</code> probably isn't the best data structure for your problem. This data structure is fast when it comes to obtaining data, but removing elements form it, which you do a lot, is slower. You'd want a structure where <code>Remove</code> is an <span class=\"math-container\">\\$O(1)\\$</span> operation and, obviously, where it's easy to navigate from one element to the next. The <code>LinkedList</code> sounds like a good idea, as I'll point out below.</p>\n<h3>Alternative algorithm</h3>\n<p>I'd recommend creating some sort of circular linked list, so you wouldn't need to recreate the iterator when you reach the end of the list and to simplify some conditions. The idea is to have a linked list, where the last node's &quot;next node&quot; is the first one. This way, your generator could run until there's no next values.</p>\n<pre><code>Iterator&lt;Integer&gt; iterator = circularLinkedList.iterator();\n//To start with the &quot;first guy&quot;\nint k = -1;\nwhile (iterator.hasNext()) {\n\n //Move on to the next shooter\n k = iterator.next();\n\n if (!iterator.hasNext()) {\n break;\n }\n\n //Move to the next shoot...ee?\n iterator.next();\n iterator.remove();\n}\n</code></pre>\n<p>And... yeah, that's all. <code>k</code> contains the last guy standing.</p>\n<p>Now, you need to implement a circular linked list and create an iterator that works with it. There are many examples on internet on how to do this.</p>\n<p>You could also explore an option where you don't actually remove the element from the list, but simply keep a <code>boolean</code> where an index is flagged as dead or not. This might also be faster.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T16:40:06.860", "Id": "430946", "Score": "0", "body": "That's still way more complicated than it needs to be. The optimal solution doesn't use any arrays or lists at all; but even if you want to tackle it explicitly rather than mathematically, since each shot reduces the number of people present by 1 there will be n-1 shots fired, so you just need an array of length 2n-1 looped once." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T16:55:53.247", "Id": "430949", "Score": "0", "body": "@PeterTaylor I agree that there're much faster solutions, it's a pretty simple problem, but I wanted to keep an algorithm similar to the one OP posted." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T15:20:43.720", "Id": "222585", "ParentId": "222563", "Score": "2" } }, { "body": "<h3>Bug</h3>\n\n<p>This code doesn't compile. That's a really low bar which you should be sure you cross before submitting it for review.</p>\n\n<h3>Structure</h3>\n\n<p>The <code>main</code> method should at most handle I/O. The calculation should be in a separate method which takes an argument (the number of people in the circle) and returns the solution. There shouldn't be any debug printing.</p>\n\n<p>Looking at the guard on the <code>while</code> loop, I would conclude that you don't know the <code>break</code> keyword. As an interviewer, that would be a red flag unless the job was advertised as open to people who don't know programming on the expectation that the company will train them. (Actually even <code>break</code> is unnecessary: the loop just needs to check the break condition).</p>\n\n<h3>Names</h3>\n\n<p><code>isTrue</code> has been mentioned in comments and another answer. <code>isNeighbour</code> also warrants inspection: <em>everyone</em> is a neighbour. What matters is whether the person is a <em>shooter</em> or not.</p>\n\n<h3>Code complexity</h3>\n\n<p>There's no need to keep discarding <code>list</code> and refilling it.</p>\n\n<p>Refactoring your code, we get down to</p>\n\n<pre><code>public static int josephus2(int numberOfGuys) {\n List&lt;Integer&gt; list = new ArrayList&lt;&gt;();\n for ( int i = 1; i &lt;= numberOfGuys; i++ ) {\n list.add( i );\n }\n\n boolean isShooter = true;\n Iterator&lt;Integer&gt; i = list.iterator();\n while (list.size() &gt; 1) {\n int k = i.next();\n if ( !isShooter ) i.remove();\n if ( !i.hasNext() ) i = list.iterator();\n isShooter = !isShooter;\n }\n\n return list.get(0);\n}\n</code></pre>\n\n<p>As mentioned in another answer, <code>LinkedList</code> would be much more efficient for this than <code>ArrayList</code> because of all of the calls to <code>Iterator.remove()</code>.</p>\n\n<p>Even this is more complex than an approach which appends to a longer array and does one loop, trading memory for simplicity:</p>\n\n<pre><code>public static void flat(int numberOfGuys) {\n int[] pos = new int[numberOfGuys * 2 - 1];\n for (int i = 0; i &lt; numberOfGuys; i++) pos[i] = i + 1;\n for (int shot = 0; shot &lt; numberOfGuys - 1; shot++)\n {\n // Person at position 2*shot shoots person at position 2*shot+1 and goes to end of queue\n pos[numberOfGuys + shot] = pos[2 * shot];\n }\n return pos[numberOfGuys * 2 - 2];\n}\n</code></pre>\n\n<h3>Algorithmic complexity</h3>\n\n<p>These approaches loop once per shot, and there are <span class=\"math-container\">\\$n - 1\\$</span> shots fired, so it takes <span class=\"math-container\">\\$O(n)\\$</span> time and space. It's possible to solve the problem in <span class=\"math-container\">\\$O(\\lg n)\\$</span> time by thinking about who survives an entire turn round the circle.</p>\n\n<ul>\n<li>If there's only one person, they survive.</li>\n<li>If there's an even number of people, those in odd positions (one-indexed) survive and it's person 1's turn to shoot again.</li>\n<li>If there's an odd number of people, those in odd positions (one-indexed) survive and it's person <span class=\"math-container\">\\$n\\$</span>'s turn to shoot.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T08:48:32.657", "Id": "222622", "ParentId": "222563", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T05:46:15.433", "Id": "222563", "Score": "2", "Tags": [ "java", "interview-questions" ], "Title": "The last standing gunman in a circle" }
222563
<p>I was recently given a task to implement a data-checker script which given an input file containing (date, last_price) values should check for 3 different kind of errors - missing values, stale values and outliers and returns list of errors. I wrote the code below and the feedback I got was that it was not "pythonic" enough. Can someone please let me know how I can make this more pythonic? What parts look good, what don't? Will be extremely helpful as I write more python code in future.</p> <pre><code>#!/usr/bin/python3.6 import sys import csv import pprint import statistics from datetime import date class DataChecker: class DatePrice: def __init__(self, input_date, price): try: day, month, year = input_date.split("/") self._price_date = date(int(year), int(month), int(day)) except ValueError: # Don't tolerate invalid date raise try: self._price = float(price) except (TypeError, ValueError): self._price = 0 @property def date(self): return self._price_date.strftime("%d/%m/%Y") @property def date_obj(self): return self._price_date @property def price(self): return self._price def __repr__(self): return f"{self.date}, {self.price}" def __init__(self, input_date_price_values): self._date_price_values = [] for date, price in input_date_price_values: try: self._date_price_values.append(self.DatePrice(date, price)) except ValueError: pass self._date_price_values.sort(key=lambda x: x.date_obj) self._stale_price_dict = {} self._outlier_low, self._outlier_high = self._calculate_outlier_thresholds_using_iqr( self._date_price_values ) def check_for_errors(self): """ returns -&gt; List[tuple(date, float, error)] errors = 'missing value', 'stale value' or 'outlier' Uses 3 different error checkers to check for errors in data 1. Checks for missing values in data -&gt; categorises missing values as any value == 0, or empty string or nulls 2. Checks for stale values in data -&gt; categorises stale values as any value that remains unchanged for 5 business days. For stale values it returns the last date on which it was repeated 3. Checks for outlier values in data -&gt; Uses Interquartile range (IQR) and a low threshold of first-quartile-value - 1.2 x IQR and high-threshold of third-quartile-value + 1.2 x IQR. Any values outside this range are deemed as outliers """ errors = [] for datePrice in self._date_price_values: if self._is_value_missing(datePrice.price): self._add_to_errors(datePrice, "missing value", errors) elif self._is_value_stale(datePrice.price): self._add_to_errors(datePrice, "stale value", errors) elif self._is_value_outlier(datePrice.price): self._add_to_errors(datePrice, "outlier", errors) else: continue return errors def _add_to_errors(self, datePrice, error_string, errors): error_tuple = (datePrice.date, datePrice.price, error_string) errors.append(error_tuple) def _is_value_missing(self, price): if price is None or price == 0: return True return False def _is_value_stale(self, price): if price in self._stale_price_dict: self._stale_price_dict[price] += 1 if self._stale_price_dict[price] &gt;= 5: # 5 business days in week return True else: self._stale_price_dict.clear() self._stale_price_dict[price] = 1 return False def _is_value_outlier(self, price): if price &lt; self._outlier_low or price &gt; self._outlier_high: return True return False def _calculate_outlier_thresholds_using_iqr(self, data_price_values): price_values = sorted([dataPrice.price for dataPrice in data_price_values]) median_index = len(price_values) // 2 first_quartile = statistics.median(price_values[:median_index]) third_quartile = statistics.median(price_values[median_index + 1 :]) iqr = third_quartile - first_quartile low_iqr = first_quartile - 1.2 * iqr high_iqr = third_quartile + 1.2 * iqr return low_iqr, high_iqr def _calculate_outlier_thresholds_using_mean_deviation(self, data_price_values): price_values = sorted([dataPrice.price for dataPrice in data_price_values]) mean_value = statistics.mean(price_values) std_dev = statistics.stdev(price_values) low_iqr = mean_value - 2 * std_dev high_iqr = mean_value + 2 * std_dev return low_iqr, high_iqr def check_file_data(file_path): with open(file_path) as data_file: raw_data = csv.DictReader(data_file) input_data = [] for row in raw_data: input_data.append((row["Date"], row["Last Price"])) data_checker = DataChecker(input_data) errors = data_checker.check_for_errors() pp = pprint.PrettyPrinter(indent=4) pp.pprint(errors) print(f"Total Errors Found: {len(errors)}") return errors if __name__ == "__main__": if len(sys.argv) &lt; 2: print("Please provide filepath") sys.exit() file_path = sys.argv[1] check_file_data(file_path) </code></pre> <p>To test put the above code in a file called "data_checker.py" and test code below in a file called "test_data_checker.py" in the same directory and run: </p> <blockquote> <p>python3.6 -m pytest -v test_data_checker.py</p> </blockquote> <pre><code>import pytest from data_checker import DataChecker test_data = [ ( pytest.param( [("01/02/2010", "10"), ("02/02/2010", "10.09"), ("03/02/2010", "10.12")], [], id="no-errors-in-data", ) ), ( pytest.param( [("01/02/2010", "0.0"), ("02/02/2010", ""), ("03/02/2010", "10.12")], [("01/02/2010", 0, "missing value"), ("02/02/2010", 0, "missing value")], id="2-zero-values", ) ), ( pytest.param( [ ("01/02/2010", "2"), ("02/02/2010", "1.12"), ("03/02/2010", "1.12"), ("04/02/2010", "1.12"), ("05/02/2010", "1.12"), ("06/02/2010", "1.11"), ], [], id="4-repeated-values-no-stale", ) ), ( pytest.param( [ ("01/02/2010", "1.10"), ("02/02/2010", "1.12"), ("03/02/2010", "1.12"), ("04/02/2010", "1.12"), ("05/02/2010", "1.12"), ("06/02/2010", "1.12"), ("07/02/2010", "1.11"), ], [("06/02/2010", 1.12, "stale value")], id="1-stale-value", ) ), ( pytest.param( [ ("01/02/2010", "0"), ("02/02/2010", "1.12"), ("03/02/2010", "1.12"), ("04/02/2010", "1.12"), ("05/02/2010", "1.12"), ("06/02/2010", "1.12"), ("07/02/2010", "1.11"), ], [("01/02/2010", 0, "missing value"), ("06/02/2010", 1.12, "stale value")], id="1-missing-1-stale-value", ) ), ( pytest.param( [ ("01/02/2010", "1.11"), ("02/02/2010", "5"), ("03/02/2010", "1.12"), ("04/02/2010", "1.11"), ("05/02/2010", "1.12"), ("06/02/2010", "1.12"), ("07/02/2010", "1.11"), ], [("02/02/2010", 5, "outlier")], id="1-outlier-value", ) ), ( pytest.param( [ ("01/02/2010", "0"), ("02/02/2010", "5"), ("03/02/2010", "1.12"), ("04/02/2010", "1.11"), ("05/02/2010", "1.12"), ("06/02/2010", "1.12"), ("07/02/2010", "1.12"), ("08/02/2010", "1.12"), ("09/02/2010", "1.12"), ], [ ("01/02/2010", 0, "missing value"), ("02/02/2010", 5, "outlier"), ("09/02/2010", 1.12, "stale value"), ], id="missing-stale-outlier-value", ) ), ] @pytest.mark.parametrize("input_data, expected_value", test_data) def test_check_for_error(input_data, expected_value): data_checker = DataChecker(input_data) errors = data_checker.check_for_errors() assert errors == expected_value </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T06:28:06.603", "Id": "430881", "Score": "0", "body": "Welcome to Code Review! You can help reviewers if you provide a short example input for the code so that it can be actually tested. Apart from that, great question. Also at first glance your code looks very good compared to many things I usually see." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T07:23:22.803", "Id": "430891", "Score": "0", "body": "Thanks for the comment @AlexV . I added the tests that I wrote for this script so someone can run it" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T06:08:53.440", "Id": "222565", "Score": "2", "Tags": [ "python", "python-3.x", "validation", "csv" ], "Title": "Pricing data checker script" }
222565
<p>I am building a Python client for an alert process engine. The users can use this client to publish and clear the alerts. The client exposes two methods publish and clear to the users. These methods accept some parameters which would define the alerts from the users and enriches them with a few more fields and validates it. But so far there is no logical validation needed other than the type checking of the fields input by the users. The scripts also converts this data to a json fromat. The json data will be sent to the downstream process. Before sending, this data will be validated against a json schema which I haven't implemented yet. The client will be packaged as a library eventually and made available to the users. This is how the current version of the main script looks like.</p> <pre><code># -*- coding: utf-8 -*- """Main module.""" from enum import Enum import json import datetime class AlertStatus(Enum): OPEN = 0 CLOSED = 1 class AlertSeverity(Enum): EXCEPTION = 1 WARNING = 2 NOTIFICATION = 3 class AlertRequest: def __init__(self, run_date, application_id, data_process_key): self.param_dict = {"run_date": run_date, "application_id": application_id, "data_process_key": data_process_key} def _to_json(self, input_dict): return json.dumps(input_dict) def prepare_to_publish(self, severity, **kwargs): self.param_dict["status"] = AlertStatus.OPEN.name self.param_dict["severity"] = severity self.param_dict["owner"] = kwargs.get("owner", None) self.param_dict["data"] = kwargs.get("data", None) self.param_dict["alert_links"] = kwargs.get("alert_links", None) self.param_dict["event_date_time"] = datetime.datetime.now().isoformat() return self._to_json(self.param_dict) def prepare_to_clear(self): """Update the status of alert to closed""" self.param_dict["status"] = AlertStatus.CLOSED.name return self._to_json(self.param_dict) def publish(run_date, application_id, data_process_key, severity="WARNING", **kwargs): """ :param run_date: Run date of the data process in a sring format specified in the json schema :param application_id: :param data_process_key: :param severity: A number of optional keyword arguments may be specified Owner Two types - 1. functional group (research group or data owner) and 2 a set of functional groups a user is interested in (data rotation) Data Custom dictionary to specify any additional attributes. Alert Links List of links for action or sourcing debug data for display in custom views :return: """ alert_req_obj = AlertRequest(run_date, application_id, data_process_key) req_payload = alert_req_obj.prepare_to_publish(severity, **kwargs) print(req_payload) return True def clear(run_date, application_id, data_process_key): alert_req_obj = AlertRequest(run_date, application_id, data_process_key) req_payload = alert_req_obj.prepare_to_clear() print(req_payload) return True if __name__ == "__main__": publish('2019-07-01', 1234, 'alert') clear('2019-07-01', 1234, 'alert') </code></pre> <p>This is the first time I am trying to make use of the enum class in Python. But so far I don't think they are actually making the code better if not complicating it. I would really appreciate some constructive criticism on the structure, design, the methods implemented or the approach. Please let me know how can I make this better. The downstream process would be a REST end point or a queue. But the process expects that data is a valid json format. Is there a type checking needed in this case to ensure that the json is valid?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T06:21:15.867", "Id": "222566", "Score": "2", "Tags": [ "python", "python-3.x", "json", "enum" ], "Title": "Client wrapper for sending data to a downstream process" }
222566
<p>I have a couple of projects:</p> <ol> <li><a href="https://github.com/coderodde/GameAI" rel="nofollow noreferrer">GameAI</a></li> <li><a href="https://github.com/coderodde/ConnectFour" rel="nofollow noreferrer">ConnectFour</a></li> </ol> <p><code>GameAI</code> implements a couple of algorithms: Minimax, Alpha-beta pruning and Alpha-beta pruning with state ordering.</p> <p>The actual game tree search algorithms seems to be in order, yet when I play against the bot connected to such an algorithm, it acts rather dumb. My best guess is that the problem lies in the evalutation function. Here is my code:´</p> <p><strong><em><code>net.coderodde.zerosum.ai.impl.AlphaBetaPruningGameEngine</code></em></strong></p> <pre><code>package net.coderodde.zerosum.ai.impl; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import net.coderodde.zerosum.ai.EvaluatorFunction; import net.coderodde.zerosum.ai.GameEngine; import net.coderodde.zerosum.ai.State; /** * This class implements the * &lt;a href="https://en.wikipedia.org/wiki/Minimax"&gt;Minimax&lt;/a&gt; algorithm for * zero-sum two-player games. * * @param &lt;S&gt; the game state type. * @param &lt;P&gt; the player color type. * @author Rodion "rodde" Efremov * @version 1.6 (May 26, 2019) */ public final class AlphaBetaPruningGameEngine&lt;S extends State&lt;S&gt;, P extends Enum&lt;P&gt;&gt; extends GameEngine&lt;S, P&gt; { /** * Stores the terminal node or a node at the depth zero with the best value * so far, which belongs to the maximizing player moves. */ private S bestTerminalMaximizingState; /** * Stores the value of {@code bestTerminalMaximizingState}. */ private double bestTerminalMaximizingStateValue; /** * Stores the terminal node or a node at the depth zero with the best value * so far, which belongs to the minimizing player moves. */ private S bestTerminalMinimizingState; /** * Stores the value of {@code bestTerminalMinimizingState}. */ private double bestTerminalMinimizingStateValue; /** * Indicates whether we are computing a next ply for the minimizing player * or not. If not, we are computing a next ply for the maximizing player. */ private boolean makingPlyForMinimizingPlayer; /** * Maps each visited state to its parent state. */ private final Map&lt;S, S&gt; parents = new HashMap&lt;&gt;(); /** * Constructs this minimax game engine. * @param evaluatorFunction the evaluator function. * @param depth the search depth. */ public AlphaBetaPruningGameEngine(EvaluatorFunction&lt;S&gt; evaluatorFunction, int depth) { super(evaluatorFunction, depth, Integer.MAX_VALUE); } /** * {@inheritDoc } */ @Override public S makePly(S state, P minimizingPlayer, P maximizingPlayer, P initialPlayer) { // Reset the best known values: bestTerminalMaximizingStateValue = Double.NEGATIVE_INFINITY; bestTerminalMinimizingStateValue = Double.POSITIVE_INFINITY; makingPlyForMinimizingPlayer = initialPlayer != minimizingPlayer; // Do the game tree search: makePlyImpl(state, depth, Double.NEGATIVE_INFINITY, // intial alpha Double.POSITIVE_INFINITY, // intial beta minimizingPlayer, maximizingPlayer, initialPlayer); // Find the next game state starting from 'state': S returnState = inferBestState( initialPlayer == minimizingPlayer ? bestTerminalMinimizingState : bestTerminalMaximizingState); // Release the resources: parents.clear(); bestTerminalMaximizingState = null; bestTerminalMinimizingState = null; // We are done with a single move: return returnState; } private S inferBestState(S bestTerminalState) { List&lt;S&gt; statePath = new ArrayList&lt;&gt;(); S state = bestTerminalState; while (state != null) { statePath.add(state); state = parents.get(state); } if (statePath.size() == 1) { // The root node is terminal. Return null: return null; } // Return the second upmost state: Collections.&lt;S&gt;reverse(statePath); return statePath.get(1); } /** * Performs a single step down the game tree branch. * * @param state the starting state. * @param depth the maximum depth of the game tree. * @param minimizingPlayer the minimizing player. * @param maximizingPlayer the maximizing player. * @param currentPlayer the current player. * @return the value of the best ply. */ private double makePlyImpl(S state, int depth, double alpha, double beta, P minimizingPlayer, P maximizingPlayer, P currentPlayer) { if (depth == 0 || state.isTerminal()) { double value = evaluatorFunction.evaluate(state); if (!makingPlyForMinimizingPlayer) { if (bestTerminalMinimizingStateValue &gt; value) { bestTerminalMinimizingStateValue = value; bestTerminalMinimizingState = state; } } else { if (bestTerminalMaximizingStateValue &lt; value) { bestTerminalMaximizingStateValue = value; bestTerminalMaximizingState = state; } } return value; } if (currentPlayer == maximizingPlayer) { double value = Double.NEGATIVE_INFINITY; for (S child : state.children()) { value = Math.max( value, makePlyImpl(child, depth - 1, alpha, beta, minimizingPlayer, maximizingPlayer, minimizingPlayer)); parents.put(child, state); alpha = Math.max(alpha, value); if (alpha &gt;= beta) { break; } } return value; } else { // Here, 'initialPlayer == minimizingPlayer'. double value = Double.POSITIVE_INFINITY; for (S child : state.children()) { value = Math.min( value, makePlyImpl(child, depth - 1, alpha, beta, minimizingPlayer, maximizingPlayer, maximizingPlayer)); parents.put(child, state); beta = Math.min(beta, value); if (alpha &gt;= beta) { break; } } return value; } } } </code></pre> <p><strong><em><code>net.coderodde.games.connect.four.impl.BruteForceConnectFourStateEvaluatorFunction</code></em></strong></p> <pre><code>package net.coderodde.games.connect.four.impl; import net.coderodde.games.connect.four.ConnectFourState; import net.coderodde.games.connect.four.PlayerColor; import net.coderodde.zerosum.ai.EvaluatorFunction; /** * This class implements the default Connect Four state evaluator. The white * player wants to maximize, the red player wants to minimize. * * @author Rodion "rodde" Efremov * @version 1.6 (May 24, 2019) */ public final class BruteForceConnectFourStateEvaluatorFunction implements EvaluatorFunction&lt;ConnectFourState&gt; { private static final double NEGATIVE_WIN_VALUE = -1e6; private static final double POSITIVE_WIN_VALUE = 1e6; private static final double BASE_VALUE = 1e1; /** * The weight matrix. Maps each position to its weight. We need this in * order to */ private final double[][] weightMatrix; /** * The winning length. */ private final int winningLength; /** * Constructs the default heuristic function for Connect Four game states. * * @param width the game board width. * @param height the game board height. * @param maxWeight the maximum weight in the weight matrix. * @param winningPatternLength the winning pattern length. */ public BruteForceConnectFourStateEvaluatorFunction(final int width, final int height, final double maxWeight, final int winningPatternLength) { this.weightMatrix = getWeightMatrix(width, height, maxWeight); this.winningLength = winningPatternLength; } /** * Evaluates the given input {@code state} and returns the estimate. * @param state the state to estimate. * @return the estimate. */ @Override public double evaluate(ConnectFourState state) { // 'minimizingPatternCounts[i]' gives the number of patterns of // length 'i': int[] minnimizingPatternCounts = new int[state.getWinningLength() + 1]; int[] maximizingPatternCounts = new int[minnimizingPatternCounts.length]; // Do not consider patterns of length one! for (int targetLength = 2; targetLength &lt;= winningLength; targetLength++) { int count = findRedPatternCount(state, targetLength); if (count == 0) { // Once here, it is not possible to find patterns of larger // length than targetLength: break; } minnimizingPatternCounts[targetLength] = count; } for (int targetLength = 2; targetLength &lt;= state.getWinningLength(); targetLength++) { int count = findWhitePatternCount(state, targetLength); if (count == 0) { // Once here, it is not possible to find patterns of larger // length than targetLength: break; } maximizingPatternCounts[targetLength] = count; } double score = computeBaseScore(minnimizingPatternCounts, maximizingPatternCounts); return score + getWeights(weightMatrix, state); } /** * Finds the number of red patterns of length {@code targetLength}. * @param state the target state. * @param targetLength the length of the pattern to find. * @return the number of red patterns of length {@code targetLength}. */ private static final int findRedPatternCount(ConnectFourState state, int targetLength) { return findPatternCount(state, targetLength, PlayerColor.MINIMIZING_PLAYER); } /** * Finds the number of white patterns of length {@code targetLength}. * @param state the target state. * @param targetLength the length of the pattern to find. * @return the number of white patterns of length {@code targetLength}. */ private static final int findWhitePatternCount(ConnectFourState state, int targetLength) { return findPatternCount(state, targetLength, PlayerColor.MAXIMIZING_PLAYER); } /** * Implements the target pattern counting function for both the player * colors. * @param state the state to search. * @param targetLength the length of the patterns to count. * @param playerColor the target player color. * @return the number of patterns of length {@code targetLength} and color * {@code playerColor}. */ private static final int findPatternCount(ConnectFourState state, int targetLength, PlayerColor playerColor) { int count = 0; count += findHorizontalPatternCount(state, targetLength, playerColor); count += findVerticalPatternCount(state, targetLength, playerColor); count += findAscendingDiagonalPatternCount(state, targetLength, playerColor); count += findDescendingDiagonalPatternCount(state, targetLength, playerColor); return count; } /** * Scans the input state for diagonal &lt;b&gt;descending&lt;/b&gt; patterns and * returns the number of such patterns. * @param state the target state. * @param patternLength the target pattern length. * @param playerColor the target player color. * @return the number of patterns. */ private static final int findDescendingDiagonalPatternCount(ConnectFourState state, int patternLength, PlayerColor playerColor) { int patternCount = 0; for (int y = 0; y &lt; state.getWinningLength() - 1; y++) { inner: for (int x = 0; x &lt;= state.getWidth() - state.getWinningLength(); x++) { for (int i = 0; i &lt; patternLength; i++) { if (state.readCell(x + i, y + i) != playerColor) { continue inner; } } patternCount++; } } return patternCount; } /** * Scans the input state for diagonal &lt;b&gt;ascending&lt;/b&gt; patterns and returns * the number of such patterns. * @param state the target state. * @param patternLength the target pattern length. * @param playerColor the target player color. * @return the number of patterns. */ private static final int findAscendingDiagonalPatternCount(ConnectFourState state, int patternLength, PlayerColor playerColor) { int patternCount = 0; for (int y = state.getHeight() - 1; y &gt; state.getHeight() - state.getWinningLength(); y--) { inner: for (int x = 0; x &lt;= state.getWidth() - state.getWinningLength(); x++) { for (int i = 0; i &lt; patternLength; i++) { if (state.readCell(x + i, y - i) != playerColor) { continue inner; } } patternCount++; } } return patternCount; } /** * Scans the input state for diagonal &lt;b&gt;horizontal&lt;/b&gt; patterns and returns * the number of such patterns. * @param state the target state. * @param patternLength the target pattern length. * @param playerColor the target player color. * @return the number of patterns. */ private static final int findHorizontalPatternCount( ConnectFourState state, int patternLength, PlayerColor playerColor) { int patternCount = 0; for (int y = state.getHeight() - 1; y &gt;= 0; y--) { inner: for (int x = 0; x &lt;= state.getWidth() - patternLength; x++) { if (state.readCell(x, y) == null) { continue inner; } for (int i = 0; i &lt; patternLength; i++) { if (state.readCell(x + i, y) != playerColor) { continue inner; } } patternCount++; } } return patternCount; } /** * Scans the input state for diagonal &lt;b&gt;vertical&lt;/b&gt; patterns and returns * the number of such patterns. * @param state the target state. * @param patternLength the target pattern length. * @param playerColor the target player color. * @return the number of patterns. */ private static final int findVerticalPatternCount(ConnectFourState state, int patternLength, PlayerColor playerColor) { int patternCount = 0; outer: for (int x = 0; x &lt; state.getWidth(); x++) { inner: for (int y = state.getHeight() - 1; y &gt; state.getHeight() - state.getWinningLength(); y--) { if (state.readCell(x, y) == null) { continue outer; } for (int i = 0; i &lt; patternLength; i++) { if (state.readCell(x, y - i) != playerColor) { continue inner; } } patternCount++; } } return patternCount; } /** * Gets the state weight. We use this in order to discourage the positions * that are close to borders/far away from the center of the game board. * @param weightMatrix the weighting matrix. * @param state the state to weight. * @return the state weight. */ private static final double getWeights(final double[][] weightMatrix, final ConnectFourState state) { double score = 0.0; outer: for (int x = 0; x &lt; state.getWidth(); x++) { for (int y = state.getHeight() - 1; y &gt;= 0; y--) { PlayerColor playerColor = state.readCell(x, y); if (playerColor == null) { continue outer; } if (playerColor == PlayerColor.MINIMIZING_PLAYER) { score -= weightMatrix[y][x]; } else { score += weightMatrix[y][x]; } } } return score; } /** * Computes the base scorer that relies on number of patterns. For example, * {@code redPatternCounts[i]} will denote the number of patterns of length * [@code i}. * @param minimizingPatternCounts the pattern count map for red patterns. * @param maximizingPatternCounts the pattern count map for white patterns. * @return the base estimate. */ private static final double computeBaseScore( int[] minimizingPatternCounts, int[] maximizingPatternCounts) { final int winningLength = minimizingPatternCounts.length - 1; double value = 0.0; if (minimizingPatternCounts[winningLength] != 0) { value = NEGATIVE_WIN_VALUE; } if (maximizingPatternCounts[winningLength] != 0) { value = POSITIVE_WIN_VALUE; } for (int length = 2; length &lt; minimizingPatternCounts.length; length++) { int minimizingCount = minimizingPatternCounts[length]; value -= minimizingCount * Math.pow(BASE_VALUE, length); int maximizingCount = maximizingPatternCounts[length]; value += maximizingCount * Math.pow(BASE_VALUE, length); } return value; } /** * Computes the weight matrix. The closer the entry in the board is to the * center of the board, the closer the weight of that position will be to * {@code maxWeight}. * * @param width the width of the matrix. * @param height the height of the matrix. * @param maxWeight the maximum weight. The minimum weight will be always * 1.0. * @return the weight matrix. */ private static final double[][] getWeightMatrix(final int width, final int height, final double maxWeight) { final double[][] weightMatrix = new double[height][width]; for (int y = 0; y &lt; weightMatrix.length; y++) { for (int x = 0; x &lt; weightMatrix[0].length; x++) { int left = x; int right = weightMatrix[0].length - x - 1; int top = y; int bottom = weightMatrix.length - y - 1; int horizontalDifference = Math.abs(left - right); int verticalDifference = Math.abs(top - bottom); weightMatrix[y][x] = 1.0 + (maxWeight - 1.0) / (horizontalDifference + verticalDifference); } } return weightMatrix; } } </code></pre> <p><strong>Critique request</strong></p> <p>Any comments on my code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T08:33:31.690", "Id": "430898", "Score": "0", "body": "Would you say the code works as intended?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T08:37:16.053", "Id": "430900", "Score": "0", "body": "Most likely not. The alpha-beta pruning seems to work, but the evaluation function favors suboptimal game states." } ]
[ { "body": "<p>I'm just going to do a detailed review of the more general class. With respect to Connect Four, have you read the paper by the person who solved it? They took a strategy-based approach, but there may be some tips for the evaluation function.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> /**\n * Maps each visited state to its parent state.\n */\n private final Map&lt;S, S&gt; parents = new HashMap&lt;&gt;();\n</code></pre>\n</blockquote>\n\n<p>Game trees aren't actually trees but digraphs. In the case of Connect Four there's an obvious parameter to show that they're layered digraphs. But a position at depth 4 might have various parents, and they might not be equally good choices. (Compare noughts and crosses / tic-tac-toe: it's a draw, but some moves give your opponent more chances to make mistakes).</p>\n\n<p>I suspect that this is more an optimisation opportunity than a bug, but it would depend on the equality implementation of the state.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> // Do the game tree search:\n makePlyImpl(state,\n depth,\n Double.NEGATIVE_INFINITY, // intial alpha\n Double.POSITIVE_INFINITY, // intial beta\n minimizingPlayer,\n maximizingPlayer,\n initialPlayer);\n</code></pre>\n</blockquote>\n\n<p>Shouldn't <code>depth</code> be <code>getDepth()</code> in case a subclass overrides <code>getDepth</code> and <code>setDepth</code>?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (currentPlayer == maximizingPlayer) {\n double value = Double.NEGATIVE_INFINITY;\n\n for (S child : state.children()) {\n value = Math.max(\n value, \n makePlyImpl(child, \n depth - 1, \n alpha,\n beta,\n minimizingPlayer, \n maximizingPlayer, \n minimizingPlayer));\n\n parents.put(child, state);\n alpha = Math.max(alpha, value);\n\n if (alpha &gt;= beta) {\n break;\n }\n }\n\n return value;\n</code></pre>\n</blockquote>\n\n<p>I don't see the value to having a variable for <code>value</code> rather than just reusing <code>alpha</code>. As I see it, <code>makePlyImpl</code> is called in two places: once with <code>alpha = Double.NEGATIVE_INFINITY</code> and the recursive call here. Eliminating <code>value</code> in favour of <code>alpha</code> would change the behaviour of the recursive calls slightly, equivalently to changing <code>return value;</code> to <code>return Math.max(alpha, value);</code>. But at the level up, this wouldn't cause <code>alpha</code> to increase where it wouldn't already have increased.</p>\n\n<p>I also think it would be better to reduce duplication by merging both sides of the <code>if</code>. Reusing <code>alpha</code> and <code>beta</code> would reduce the differences between the two sides, giving:</p>\n\n<pre><code> P otherPlayer = currentPlayer == maximizingPlayer\n ? minimizingPlayer\n : maximisingPlayer;\n\n for (S child : state.children()) {\n double value =\n makePlyImpl(child, \n depth - 1, \n alpha,\n beta,\n minimizingPlayer, \n maximizingPlayer, \n otherPlayer);\n\n parents.put(child, state); // See earlier comments\n\n if (currentPlayer == maximizingPlayer) {\n alpha = Math.max(alpha, value);\n } else {\n beta = Math.min(beta, value);\n }\n\n if (alpha &gt;= beta) {\n break;\n }\n }\n\n return currentPlayer == maximizingPlayer ? alpha : beta;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T08:47:10.713", "Id": "430903", "Score": "0", "body": "What do you think about correctness of my implementation of Alpha-beta pruning?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T09:41:10.903", "Id": "430910", "Score": "0", "body": "I'd have to research alpha-beta. I'm more interested in the theoretical value of games than in AIs, so I've only ever implemented unpruned searches." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T08:00:09.120", "Id": "222571", "ParentId": "222569", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T06:54:25.643", "Id": "222569", "Score": "2", "Tags": [ "java", "algorithm", "game", "connect-four" ], "Title": "A Connect Four evaluation function in Java is not smart enough" }
222569
<p><strong>The task</strong> is <a href="https://leetcode.com/problems/shortest-way-to-form-string/" rel="nofollow noreferrer">taken from LeetCode</a> (subscription required) -</p> <blockquote> <p>From any string, we can form a subsequence of that string by deleting some number of characters (possibly no deletions).</p> <p>Given two strings source and target, return the minimum number of subsequences of source such that their concatenation equals target. If the task is impossible, return <code>-1</code>.</p> <p><strong>Example 1:</strong></p> <pre><code>Input: source = &quot;abc&quot;, target = &quot;abcbc&quot; Output: 2 // Explanation: The target &quot;abcbc&quot; can be formed by &quot;abc&quot; and &quot;bc&quot;, which are subsequences of source &quot;abc&quot;. </code></pre> <p><strong>Example 2:</strong></p> <pre><code>Input: source = &quot;abc&quot;, target = &quot;acdbc&quot; Output: -1 // Explanation: The target string cannot be constructed from the subsequences of source string due to the character &quot;d&quot; in target // string. </code></pre> <p><strong>Example 3:</strong></p> <pre><code>Input: source = &quot;xyz&quot;, target = &quot;xzyxz&quot; Output: 3 // Explanation: The target string can be constructed as follows &quot;xz&quot; + &quot;y&quot; + &quot;xz&quot;. </code></pre> <p><strong>Note:</strong></p> <p>Both the source and target strings consist of only lowercase English letters from &quot;a&quot;-&quot;z&quot;. The lengths of source and target string are between 1 and 1000.</p> </blockquote> <p><strong>My solution</strong> has space complexity of <span class="math-container">\$O(n)\$</span> and time complexity of <span class="math-container">\$O(n^2)\$</span> (I think...)</p> <pre><code>/** * @param {string} source * @param {string} target * @return {number} */ var shortestWay = function(source, target) { const map = new Map(); for (let i = 0; i &lt; source.length; i++) { if (map.get(source[i])) { const arr = map.get(source[i]); arr.push(i); map.set(source[i], arr); } else { map.set(source[i], [i]); } } let occurrences = 0; for (let i = 0; i &lt; target.length; i++) { const indexes = map.get(target[i]); if (indexes === void 0) return -1; occurrences++; let max = 0; indexes.forEach(index =&gt; { let j = 0; let ignore = 0; while(source[index + j + ignore] !== void 0) { if(target[i + j] !== source[index + j + ignore]) { ignore++; } else { max = Math.max(max, j++); } } }); i += max; } return occurrences; }; </code></pre>
[]
[ { "body": "<p>I believe your code is <code>O(n^2*m)</code>, where <code>n</code> is the target and <code>m</code> is the source. Overall, though, I think there are a lot of readability improvements that could be made here by separating functions and renaming variables (<code>j</code> is a particularly bad contender).</p>\n<pre><code>// indexCharacters('hello')\n// = {'h':[0],'e':[1],'l':[2,3],'o':[4]}\nconst indexCharacters = source =&gt; {\n const map = new Map();\n for (let i = 0; i &lt; source.length; i++) {\n const char = source[i];\n if (!map.get(char)) map.set(char,[]);\n map.get(char).push(i);\n }\n return map;\n}\n\n// matchLength('abc','abeee') = 2\nconst matchLength = (source,target) =&gt; {\n let count = 0;\n for (let i=0;i&lt;source.length;++i)\n if (target[count] === source[i])\n ++count;\n return count;\n}\n\nconst shortestWay = (source, target) =&gt; {\n const all_character_indices = indexCharacters(source);\n let occurrences = 0;\n let targetIndex = 0;\n while (targetIndex &lt; target.length) {\n const starting_indices = all_character_indices.get(target[targetIndex]);\n if (!starting_indices) return -1;\n \n const match_lengths = starting_indices.map(\n sourceIndex=&gt;matchLength(\n source.substr(sourceIndex),\n target.substr(targetIndex)\n )\n );\n \n targetIndex += Math.max(...match_lengths);\n ++occurrences;\n }\n return occurrences;\n};\n\nconsole.log(shortestWay('abc','abcbc'))\nconsole.log(shortestWay('abc','acdbc'))\nconsole.log(shortestWay('xyz','xzyxz'))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-14T05:11:18.490", "Id": "254684", "ParentId": "222570", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T07:07:32.740", "Id": "222570", "Score": "3", "Tags": [ "javascript", "algorithm", "programming-challenge", "strings", "ecmascript-6" ], "Title": "Shortest way to form a string out of a subsequence of a string" }
222570
<p>I am working on a Monte Carlo simulation using OpenMP multithreading. To avoid race conditions when multiple threads work on the same resolution element, I have implemented the following <code>module</code> to atomically (using OMP <code>atomic</code>, since AFAIK there's no easy way to do atomic operations directly in Fortran) acquire and release a lock:</p> <pre><code>module portability use, intrinsic :: iso_fortran_env implicit none integer, parameter :: al=ATOMIC_LOGICAL_KIND end module portability module atomic_lock use portability implicit none contains subroutine acquire_atomic_lock(have_lck, lck, error, blocking) logical(al), intent(inout) :: have_lck logical(al), intent(inout) :: lck integer, intent(out), optional :: error logical(al), intent(in), optional :: blocking logical(al) :: lck_copy, blk integer :: err if(present(blocking)) then blk = blocking else blk = .true. endif lck_copy = .true. err = 0 if(have_lck) then ! already have a lock, can not acquire new one err = 1 else if(blk) then ! PROBLEM: busy waiting here do while(lck_copy) !$omp atomic capture lck_copy = lck lck = .true. !$omp end atomic end do have_lck = .true. else !$omp atomic capture lck_copy = lck lck = .true. !$omp end atomic have_lck = .not. lck_copy end if end if if(present(error)) then error = err end if end subroutine acquire_atomic_lock subroutine release_atomic_lock(have_lck, lck, error) logical(al), intent(inout) :: have_lck logical(al), intent(inout) :: lck integer, intent(out), optional :: error logical(al) :: lck_copy integer :: err err = 0 if(.not. have_lck) then ! can not release a lock we do not have err = 1 else !$omp atomic capture lck_copy = lck lck = .false. !$omp end atomic if(.not. lck_copy) then ! lock was released while we thought we had it err = 2 end if end if if(present(error)) then error = err end if end subroutine release_atomic_lock end module atomic_lock </code></pre> <p>Here's an MWE:</p> <pre><code>program main use portability use atomic_lock use omp_lib implicit none logical(al) :: lock_sum, have_lock integer :: sum integer :: nthreads=4 call omp_set_num_threads(nthreads) lock_sum = .false. have_lock = .false. sum = 0 !$omp parallel default(none) shared(lock_sum, sum) firstprivate(have_lock) call acquire_atomic_lock(have_lock, lock_sum) sum = sum + omp_get_thread_num() call release_atomic_lock(have_lock, lock_sum) !$omp end parallel write(*,*) sum == (nthreads*(nthreads-1))/2 end program main </code></pre> <p>It works well even with 20000 or so threads on my four core processor and is, unsurprisingly, much faster than using OMP <code>critical</code> instead of <code>atomic</code>.</p> <p>However, I would still like to know what shortcomings you can identify in my implementation and how you would fix them. One problem I see and don't know how to fix is that <code>acquire_atomic_lock</code> does busy waiting if the lock isn't available. In my case this will not be a huge problem, I presume, since I have many more resolution elements than threads and consequently collisions will be unlikely but it would be nice to fix it anyway.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T09:02:07.473", "Id": "430904", "Score": "2", "body": "Welcome to Code Review! That seems to be a great question and I hope you get good feedback as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T12:41:16.410", "Id": "431032", "Score": "0", "body": "This is quite an advanced code (from the point of OpenMP) so it will be harder to find good advice. The Fortran itself is written nicely." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T08:05:04.337", "Id": "431161", "Score": "0", "body": "@VladimirF thank you, I'm glad to hear that. I was hoping an OMP expert could maybe give me some insight on how to solve the busy waiting problem. Let's see." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T08:43:51.303", "Id": "222573", "Score": "4", "Tags": [ "multithreading", "locking", "openmp", "fortran" ], "Title": "Lightweight lock using OMP atomic" }
222573
<p>Here is an update to my <a href="https://codereview.stackexchange.com/questions/222546/a-recursive-boggle-solver">previous</a> boggle solver. The new version has an almost instantaneous output, removing the need to limit the length of words being searched for. </p> <p>Any comments on my general coding implementation or layout would be appreciated. </p> <pre><code>"""Boggle game solver""" class Trie: """Trie class to speed up programme by stopping exploration of non-existent prefixes""" def __init__(self): """Initialise the trie""" self.child = {} def insert(self, word): """Insert word into trie""" current = self.child for char in word: if char not in current: current[char] = {} current = current[char] def search(self, word): """Search the trie""" current = self.child for char in word: if char not in current: return False current = current[char] return True def words_from(board, row, column, running_string, list_words): """Calculate all possible words from a given starting position [row, column]""" if row in (4, -1) or column in (4, -1): return # Search the Trie if not trie.search(running_string): return if board[row][column] != "-": new_string = running_string + board[row][column] board[row][column] = "-" # Add new word if len(new_string) &gt;= 3: list_words.append(new_string.lower()) # Find next word next_move = [ (1, 1), (-1, -1), (1, -1), (-1, 1), (1, 0), (0, 1), (-1, 0), (0, -1), ] for dx, dy in next_move: words_from(board, row + dx, column + dy, new_string, list_words) board[row][column] = new_string[-1] return list_words def get_permutations(board): """Get all permutations """ set_permutations = set() # Build Trie global trie trie = Trie() with open("en-dict.txt", "r", encoding="utf8") as file: for line in file: trie.insert(line) #Search for words from each starting position for row in range(4): for column in range(4): # Search for words words = words_from(board, row, column, running_string="", list_words=[]) if words: for word in words: set_permutations.add(word) words = None return sorted(list(set_permutations)) def dictionary_check(set_permuations): """Check set_permutations for valid English words""" dictionary = {} with open("en-dict.txt", "r", encoding="utf8") as file: for line in file: dictionary[line.strip()] = 0 counter = 0 for word in set_permuations: if word.lower() in dictionary: counter += 1 print(word) print(f"======\n{counter} words") def find_words(board): """Find words on the boggle board""" set_permutations = get_permutations(board) print("\nPerforming dictionary check....") dictionary_check(set_permutations) def build_board(string): """Build board from string""" if len(string) != 16: print("Error. Must enter 4*4 grid (16 characters)") return board = [[*string[0:4]], [*string[4:8]], [*string[8:12]], [*string[12:16]]] find_words(board) if __name__ == "__main__": string_board = "playthiswordgame" build_board(string_board) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T07:00:10.450", "Id": "431001", "Score": "1", "body": "A trie is a great option for this. I don't have time for a proper review, but one thing that sticks out as worth mentioning: the same trie structure can both indicate prefixes and indicate whole words in the dictionary. If you added that distinction, you could avoid adding any invalid words to `list_words` in `words_from` in the first place, and therefore avoid needing the additional `dictionary_check` to take them out again afterwards." } ]
[ { "body": "<ul>\n<li><p>Rather than a global <code>Trie</code> object I would make a <code>TrieNode</code> object that inherits from <code>dict</code>.</p>\n\n<ul>\n<li>This can inherit from <code>dict</code>.</li>\n<li>This can overload <code>__missing__</code> to simplify <code>insert</code>.</li>\n<li>Search isn't needed in the way I used it.</li>\n</ul></li>\n<li><p>Make a function <code>build_trie</code>, that builds and populates the trie from \"en-dict.txt\".</p></li>\n<li><code>build_board</code> should really be called <code>main</code> and the code that builds the board should be moved into it's own function.</li>\n<li><code>find_words</code> should be moved into <code>main</code>.</li>\n<li><p><code>build_trie</code> should be called from <code>main</code> and passed to where it needs to be used.</p>\n\n<p>When possible don't use <code>global</code>. If you think it's impossible, then you're likely wrong.</p>\n\n<p>In this case you can move the value out of the function into <code>main</code> and pass it where it's needed.</p>\n\n<p>In other cases using a class, a closure or other ways can solve the issue.</p></li>\n<li><p><code>dictionary_check</code> should only display words. And the first part of the function can be removed with the new <code>TrieNode</code>.</p></li>\n<li>Move <code>next_move</code> out of <code>words_from</code>, just make it a global constant.</li>\n<li><code>board[row][column] != \"-\"</code> relies on mutating <code>board</code> I would recommend not mutating input to functions.</li>\n<li><code>words_from</code> can be simplified by passing the current <code>node</code>, as then you're not <code>trie.search</code>ing.</li>\n<li>In <code>words_from</code> <code>len(new_string) &gt;= 3</code> is an artificial limitation, that should be moved out of the function.</li>\n<li><code>get_permutations</code> can be simplified by changing <code>words_from</code> to return an empty list on bad input.</li>\n<li>I would move <code>set_permutations</code> out of <code>get_permutations</code>, as it doesn't have much purpose in that function.</li>\n<li>I merged <code>words_from</code> and <code>set_permutations</code> to use a <code>while</code> loop, I found this to make the code easier to understand and make.</li>\n<li>Don't <code>print</code> and <code>return</code>, use <code>raise</code>.</li>\n</ul>\n\n<hr>\n\n<p>For the most part your code seems to be fairly good, there's some pitfalls your falling down. But on a micro - line by line - scale your code is pretty good.</p>\n\n<p>The problem I saw with your code is not seeing the big picture, and not following SRP.</p>\n\n<p>Improving SRP should be fairly easy for you. If you're thinking of putting a comment that says the code is performing a different task, move it into a function.</p>\n\n<p>To help with the big picture, when you follow SRP think to yourself if you should split the code into 2/3 functions and should call the three functions in succession. Like I changed <code>main</code> to do.</p>\n\n<hr>\n\n<pre><code>class TrieNode(dict):\n def __init__(self, value=None):\n super().__init__()\n self.value = value\n\n def __missing__(self, key):\n value = TrieNode()\n self[key] = value\n return value\n\n def insert(self, word):\n current = self\n for char in word:\n current = current[char]\n current.value = word\n\n\ndef build_trie():\n trie = TrieNode()\n with open(\"en-dict.txt\", \"r\", encoding=\"utf8\") as file:\n for line in file:\n trie.insert(line.strip())\n return trie\n\n\ndef board_from_string(string):\n if len(string) != 16:\n raise ValueError(\"Must enter 4*4 grid (16 characters)\")\n return [\n [*string[0:4]],\n [*string[4:8]],\n [*string[8:12]],\n [*string[12:16]]\n ]\n\n\nAROUND = [\n (dx, dy)\n for dx in range(-1, 2)\n for dy in range(-1, 2)\n if not (dx == dy == 0)\n]\n\n\ndef get_words(trie, board):\n stack = []\n for row in range(4):\n for column in range(4):\n stack.append((trie, row, column, set()))\n while stack:\n node, row, column, parents = stack.pop()\n if row in (4, -1) or column in (4, -1) or (row, column) in parents:\n continue\n char = board[row][column]\n if char not in node:\n continue\n node = node[char]\n if node.value is not None:\n yield node.value\n for dx, dy in AROUND:\n stack.append((node, row + dx, column + dy, parents | {(row, column)}))\n\n\ndef display(words):\n words = sorted({w for w in words if len(w) &gt;= 3})\n print('\\n'.join(words))\n print(f\"======\\n{len(words)} words\")\n\n\ndef main():\n string = \"playthiswordgame\"\n trie = build_trie()\n board = board_from_string(string)\n words = get_words(trie, board)\n display(words)\n\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T10:08:48.213", "Id": "431172", "Score": "0", "body": "Using the binary operator is pretty smart. Also very clever to inherit the ```dict``` class. Didn't think about that. Thank you" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T22:27:25.780", "Id": "222665", "ParentId": "222578", "Score": "1" } } ]
{ "AcceptedAnswerId": "222665", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T11:39:51.400", "Id": "222578", "Score": "3", "Tags": [ "python", "python-3.x", "trie" ], "Title": "Boggle solver - Updated (with Trie)" }
222578
<p>I've got the following component structure:</p> <p><strong>Component hierarchy:</strong></p> <pre><code>&lt;AdminBlogPostContainer&gt; &lt;AdminBlogPostPage&gt; &lt;BlogPostForm&gt; </code></pre> <p><strong>AdminBlogPostContainer.js</strong></p> <ul> <li>Contains all the functions to make the API calls, get posts from database, save posts, delete posts, upload images, etc. It also sets the <code>loading</code> and <code>error</code> states.</li> </ul> <p>When I'm editing a <code>blogPost</code>, before rendering the <code>&lt;BlogPostForm/&gt;</code> I need to get the <code>blogPost</code> from the database (using the <code>blog-post-slug</code> from the route), store in the <code>blogPost</code> state object.</p> <p>Note: This is a Single Page App and I'm using <code>react-router-dom</code> for client-side routing.</p> <p>The way I'm currently doing is this:</p> <p>I have an "action" function that handles the setting of the <code>loading</code> and <code>error</code> status. </p> <p><strong>function ACTION_getBlogPost()</strong></p> <pre><code>async function ACTION_getBlogPost() { try { setLoading(true); setError(null); await getBlogPostFromFirestore(props.match.params.slug); setLoading(false); } catch(err) { console.log(err); setError(err); setLoading(false); } } </code></pre> <p>And that "action" function calls the actual function <code>getBlogPostFromFirestore()</code> that retrieves the <code>blogPost</code>.</p> <p><strong>function getBlogPostFromFirestore(slug)</strong></p> <pre><code>function getBlogPostFromFirestore(slug) { return new Promise(async (resolve,reject) =&gt; { try { const querySnapshot = await firebase.firestore().collection('blog').where('slug','==',slug).get(); const blogPostData = querySnapshot.docs[0].data(); setFirestoreID(querySnapshot.docs[0].id); setBlogPost(blogPostData ); resolve(); } catch(err) { reject(err); } }); } </code></pre> <p><strong>QUESTION</strong></p> <p>I think I could still improve the readability on this code. Maybe keep the "action" function like it is, but change the <code>getBlogPostFromFirestore</code> to this:</p> <pre><code>function getBlogPostFromFirestore() { return firebase.firestore().collection('blog').where('slug','==',slug).get() .then((querySnapshot) =&gt; { const blogPostData = querySnapshot.docs[0].data(); setFirestoreID(querySnapshot.docs[0].id); setBlogPost(blogPostData); }) .catch((err) =&gt; throw err); } </code></pre> <p>What do you think? Which one is the best? Any other suggestions?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T14:45:52.603", "Id": "222581", "Score": "1", "Tags": [ "javascript", "react.js", "async-await", "firebase" ], "Title": "Functions to handle async calls and also handle loading and error status in React component" }
222581
<p>I'm working with SQL Server 2008 and wanted to make table builder, similar to Laravel's migration classes. I would like to be able to expand this down the road but the main purpose of this code will be to initialize the database. It will likely only be run a few times in production, but likely more for development work.</p> <p>The main interface should be easily accessible for creating and dropping tables. I was thinking of something like this: </p> <p>(NOTE: I can't use autoloading on this project for reasons)</p> <p>/* Snipped none abstracted class */</p> <p>I felt creating class for each table like laravel's migrations was a bit overkill, so I simplified it to a single Class that has the PDO instance and configuration passed in. Any advice on simplifying queries, better abstractions, or glaring security flaws would be appreciated!</p> <pre><code>// db-init.php /* Generate PDO instance */ /** * Create User Table */ $UserTable = new CreateTable($pdo, 'Employee'); $UserTable-&gt;up([ "userId INT NOT NULL", "firstName VARCHAR(32) NOT NULL", "lastName VARCHAR(32) NOT NULL", "email VARCHAR(64) NOT NULL", "password VARCHAR(72) NOT NULL DEFAULT '!test@12345'", "PRIMARY KEY (userId)", ]); $UserTable-&gt;createIndex([ 'userId', 'email', ]); </code></pre> <p>Abstracted table class</p> <pre><code>&lt;?php class CreateTable { protected $db; protected $table; /** * Use dependency injection to pass in dependencies (ie. pdo instance) * and core configurations (ie. table name). * * @param PDO $pdo * @param string $table */ public function __construct(PDO $pdo, string $table) { $this-&gt;db = $pdo; $this-&gt;table = $table; } /** * Creates table if it doesn't already exist * * @return void */ public function up(array $columns) { if ($this-&gt;tableExists()) { echo "`{$this-&gt;table}` table already exists: create table aborted.&lt;br&gt;"; return; } $query = "CREATE TABLE {$this-&gt;table} ( " . implode(',', $columns) . ")"; $statement = $this-&gt;db-&gt;prepare($query); $statement-&gt;execute(); } /** * Drops table if it exists * * @return void */ public function down() { if (!$this-&gt;tableExists()) { echo "`{$this-&gt;table}` table does not exist: drop aborted.&lt;br&gt;"; return; } $query = "DROP TABLE {$this-&gt;table}"; $statement = $this-&gt;db-&gt;prepare($query); $statement-&gt;execute(); echo "`{$this-&gt;table}` table was dropped successfully&lt;br&gt;"; } /** * Checks this table exists * * @return boolean */ protected function tableExists() { $query = "SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{$this-&gt;table}'"; $statement = $this-&gt;db-&gt;prepare($query); $statement-&gt;execute(); $results = $statement-&gt;fetchAll(); if (empty($results)) { return false; } return true; } /** * Undocumented function * * @param array $indexes * * @return void */ public function createIndex(array $indexes) { foreach($indexes as $index) { $index_id = strtolower($this-&gt;table . '_' . $index); if ($this-&gt;indexExists($index_id)) { continue; } try { $query = "CREATE INDEX {$index_id} ON {$this-&gt;table} ({$index})"; $statement = $this-&gt;db-&gt;prepare($query); $statement-&gt;execute(); } catch (PDOException $e) { echo "There was a problem indexing {$this-&gt;table} ({$index}). " . $e-&gt;getMessage(); } } } /** * Check if table index already exists * * @param [string] $index_id * * @return boolean */ protected function indexExists($index_id) { $query = "SELECT * FROM sys.indexes WHERE name='{$index_id}' AND object_id = OBJECT_ID('[dbo].[{$this-&gt;table}]')"; $statement = $this-&gt;db-&gt;prepare($query); $statement-&gt;execute(); $results = $statement-&gt;fetchAll(); if (empty($results)) { return false; } return true; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T22:01:35.290", "Id": "430974", "Score": "0", "body": "There is a bug in your code, a logical one in `class CreateUserTable`. In your method `up()` it says `Creates table if it doesn't already exist` However you bail if the table exists returns false `if (!$this->tableExists()) return false`. I believe this should bail if the table exists (returns true). It's done correctly in `class CreateTable`. This could also be done using `IF NOT EXISTS` such as `CREATE TABLE IF NOT EXISTS {$this->table} (...)` But you won't be able to do the output then. Just wanted to point those 2 things out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T22:08:32.697", "Id": "430975", "Score": "0", "body": "I've been wanted to build a table creator that uses XML as the config file for the table. Basically build the table schema using XML and then have a class parse it and create/modify the table. One of these days." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T12:39:59.113", "Id": "431031", "Score": "0", "body": "@ArtisticPhoenix Good catch. Yeah that was a mistake. I added the bail checks right before posting and missed that the up() one was reversed initially." } ]
[ { "body": "<p>This is code review, we didn't need to see your non-abstracted class since it doesn't need reviewing.</p>\n\n<p>I will not do a complete review of the abstracted class, but I have a few comments and tips. </p>\n\n<p>First of all, your class is called <code>CreateTable</code>, but this class can also destroy a table. That is the opposite of what it says on the tin. I think a better name would be <code>ManipulateTable</code>. </p>\n\n<pre><code>$employeeTable = new ManipulateTable($pdo, 'Employee');\n</code></pre>\n\n<p>Which is just another way of saying: \"I want to work on the table 'Employee' now.\". </p>\n\n<p>I don't like the lump methods <code>up()</code> and <code>down()</code>. They are not very flexible or abstract. I would, instead, use methods to create or delete one column:</p>\n\n<pre><code>$employeeTable-&gt;deleteColumn(\"password\")\n -&gt;commitToDatabase();\n\n$employeeTable-&gt;createColumn(\"passwordHash\", \"VARCHAR(64)\")\n -&gt;commitToDatabase();\n</code></pre>\n\n<p>After all, columns are the most important things when manipulating tables, so you want to be able to manipulate them individually. The <code>commitToDatabase()</code> method is used to update any changes to the database. To create multiple columns you would do:</p>\n\n<pre><code>$employeeTable-&gt;createColumn(\"userId\", \"INT\")\n -&gt;createColumn(\"firstName\", \"VARCHAR(32)\")\n -&gt;createColumn(\"lastName\", \"VARCHAR(32)\")\n -&gt;createColumn(\"email\", \"VARCHAR(64)\")\n -&gt;createColumn(\"password\", \"VARCHAR(72)\", false, \"!test@12345\")\n -&gt;createColumn(\"PRIMARY KEY (userId)\")\n -&gt;createPrimaryIndex(\"userId\")\n -&gt;commitToDatabase();\n</code></pre>\n\n<p>In other words, I would take your approach one step further. The <code>ManipulateTable</code> class is now more than a wrapper around the \"CREATE TABLE\" statement and has become a general purpose class for manipulating tables. It actually makes it easier to work with tables. I could, for instance, use it to add a column to an existing table. You can't do that with your class because you can only do <code>up([columns])</code> or <code>down()</code>.</p>\n\n<p>As for the code in your class: Your <code>up()</code> method doesn't return anything. If a table already exists it does nothing, and the user of that method will never know that. Why not return <code>false</code> in that case and <code>true</code> when the table was correctly created? </p>\n\n<p>I also think that:</p>\n\n<pre><code>if (empty($results)) {\n return false;\n}\nreturn true;\n</code></pre>\n\n<p>is the same as:</p>\n\n<pre><code>return !empty($results);\n</code></pre>\n\n<p>you use this construction twice.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T12:55:04.403", "Id": "431034", "Score": "0", "body": "Good remarks. I noticed the same thing with the class adopting more responsibilities beyond table creation, so I simplified the class name to just Table. I think you make a good point about just adding a column editor to complete the class. For the return !empty() part, I felt while it is more verbose to write it my way, the logic is more straight forward for individuals across skill levels to understand what's happening, albeit marginally, and is also open for extension." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T13:19:56.847", "Id": "431039", "Score": "1", "body": "I made the assumption you were using MySQL, but you're using SQL Server 2012, so I'll delete those last remarks about the schema tables. My mistake." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T13:22:13.773", "Id": "431040", "Score": "1", "body": "Of course, once you have something like `createColumn()` you can still make a `createColumns()` method, that accepts an array of column definitions, and calls `createColumn()` multiple times." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T11:01:04.263", "Id": "222628", "ParentId": "222583", "Score": "3" } } ]
{ "AcceptedAnswerId": "222628", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T14:49:08.750", "Id": "222583", "Score": "2", "Tags": [ "php", "sql", "design-patterns" ], "Title": "Abstracting a SQL Server Table builder" }
222583
<p>There is a problem which discusses in how many ways can the words in a sentence be permuted . I wrote a code as follows which works for the sentences (I think so) . It would be helpful if anyone can assure me if it's actually correct or not . Besides , any suggestion regarding the shortening of code or easing the logic is appreciated . Thanks...</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; int factorial(int x) { if(x&lt;=0) return 1; else return x*factorial(x-1); }; int main(void) { int T;//number of test cases scanf("%d",&amp;T); while(T--){ char str[20]; scanf(" %[^\n]",str); int i,j,k,m,count=0,l,p=1,n; l=strlen(str); for(i=0;i&lt;l;i++){ if(str[i]==' '){ count++; } } m=count+1; char arr[m][50]; int check[m],func[m]; for(i=0,k=0,j=0;j&lt;=l;j++){ if(str[j]==' '||j==l){ check[i]=0;func[i]=1; arr[i][k]='\0'; i++; k=0; } else{ arr[i][k]=str[j]; k++; } } for(i=0;i&lt;m;i++){ for(j=i+1;j&lt;m;j++){ if(check[i]==0&amp;&amp;strcmp(arr[i],arr[j])==0){ check[j]++; func[i]++; } } } for(i=0;i&lt;m;i++){ p*=factorial(func[i]); } n=factorial(m)/p; printf("%d/%d\n",1,n); } return 0; } </code></pre> <p><strong>Input:</strong></p> <pre><code> 2 I eat rice no game no life </code></pre> <p><strong>Output:</strong></p> <pre><code> 1/6 1/12 </code></pre> <p><strong>N.B.:</strong> The permutation within a word is to be ignored . </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T16:34:37.953", "Id": "430945", "Score": "1", "body": "Note, you should have verified correctness before posting, as that's a requirement here. If you can verify that it's working as expected, we can review what you have. And whats the output that you're expecting?" } ]
[ { "body": "<p>Some comments on the style of your code. </p>\n\n<ol>\n<li><p><strong>Formatting</strong>. Your code is hard to read because there are no spaces.\nAlso the formatting seems to be off. It might be easier to read like this:</p>\n\n<pre><code>int main(void)\n{\n int T;//number of test cases\n scanf(\"%d\", &amp;T);\n while (T--) {\n\n char str[20];\n scanf(\" %[^\\n]\", str);\n\n int i, j, k, m, count = 0, l, p = 1, n;\n l = strlen(str);\n\n for (i = 0; i &lt; l; i++) {\n if (str[i] == ' ') {\n count++;\n }\n }\n\n m = count + 1;\n char arr[m][50];\n int check[m], func[m];\n\n for (i = 0, k = 0, j = 0; j &lt;= l; j++) {\n if (str[j] == ' ' || j == l) {\n check[i] = 0; func[i] = 1;\n arr[i][k] = '\\0';\n i++;\n k = 0;\n }\n else {\n arr[i][k] = str[j];\n k++;\n }\n }\n\n for (i = 0; i &lt; m; i++) {\n for (j = i + 1; j &lt; m; j++) {\n if (check[i] == 0 &amp;&amp; strcmp(arr[i], arr[j]) == 0) {\n check[j]++;\n func[i]++;\n }\n }\n }\n\n for (i = 0; i &lt; m; i++) {\n p *= factorial(func[i]);\n }\n\n n = factorial(m) / p;\n printf(\"%d/%d\\n\", 1, n);\n }\n return 0;\n}\n</code></pre></li>\n<li><p><strong>Don't use comments for what could be described in the code directly</strong>. This:</p>\n\n<pre><code> int T;//number of test cases\n scanf(\"%d\", &amp;T);\n while (T--) {\n</code></pre>\n\n<p>Should be really this:</p>\n\n<pre><code> int number_of_test_cases;\n scanf(\"%d\", &amp;number_of_test_cases);\n while (number_of_test_cases--) {\n</code></pre></li>\n<li><p><strong>Avoid long functions for maintainability and readability.</strong> You wrote one function for the factorial calculation; good. But now take a look\n at the <code>main()</code> function. Can you guess what the steps are in the <code>while</code>\n by looking at it? There's too much stuff going on in the <code>main()</code>.\n Isolate parts which do one thing into a function. For example this\n piece:</p>\n\n<pre><code> int i, j, k, m, count = 0, l, p = 1, n; \n l = strlen(str);\n\n for (i = 0; i &lt; l; i++) { \n if (str[i] == ' ') {\n count++; \n } \n }\n</code></pre>\n\n<p>First of all I would write the variables on several lines to have it more readable:</p>\n\n<pre><code> int i;\n int j;\n int k;\n int m;\n int count = 0;\n int l; \n int p = 1;\n int n;\n l = strlen(str);\n\n for (i = 0; i &lt; l; i++) {\n if (str[i] == ' ') {\n count++;\n }\n }\n</code></pre>\n\n<p>Then we realize that <code>j</code>, <code>k</code>, <code>m</code>, <code>p</code> and <code>n</code> are not even needed yet at this point, so we put \n them after all this:</p>\n\n<pre><code> int i;\n int count = 0;\n int l; \n l = strlen(str);\n\n for (i = 0; i &lt; l; i++) {\n if (str[i] == ' ') {\n count++;\n }\n }\n\n int p = 1;\n int j;\n int k;\n int m;\n int n;\n</code></pre>\n\n<p>Then another thing is <code>l</code> can be directly initialized with <code>strlen(str)</code>. Also I renamed \nit everywhere in the program to <code>length</code> which states more easily for a reader what it \ndoes.</p>\n\n<p>This gives us this:</p>\n\n<pre><code> int i;\n int count = 0;\n int length = strlen(str);\n\n for (i = 0; i &lt; length; i++) {\n if (str[i] == ' ') {\n count++;\n }\n }\n</code></pre>\n\n<p>Now we should make it a function so it looks like this:</p>\n\n<pre><code> int length = strlen(str);\n int count = get_count_of_whitespace(&amp;str, length);\n</code></pre>\n\n<p>Proceed with the rest of the <code>main</code> function like that by refactoring it into \nmanageable chunks, and probably with that alone you will find some mistakes or improvements \nfor your algorithm.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T17:47:50.700", "Id": "222596", "ParentId": "222584", "Score": "3" } }, { "body": "<h1>Dangerous bug</h1>\n\n<p>Always take care to avoid buffer overruns such as this one:</p>\n\n<blockquote>\n<pre><code>char str[20];\nscanf(\" %[^\\n]\",str);\n</code></pre>\n</blockquote>\n\n<p>If you have a fixed-size buffer like that, you need to ensure that the input is limited to its length:</p>\n\n<pre><code>char str[20];\nscanf(\" %19[^\\n]\", str);\n</code></pre>\n\n<p>This is the kind of bug that leads to remote code execution or local privilege escalation in servers and setuid programs, respectively. Get into the habit of coding defensively, so that you're not inviting attacks when your code is used in such a target system.</p>\n\n<p>It's generally a good idea to examine the value returned by <code>scanf</code> - if it's not the number of variables you expected to assign, then reading has failed (perhaps you reached end-of-file?), and you can't expect to proceed normally.</p>\n\n<h1>Prefer iteration to recursion</h1>\n\n<p>Some algorithms are naturally recursive (such as Quicksort). Even implementations of those iterate as much as possible (typically in Quicksort, we recurse for the smaller partition, and iterate for the larger one). For computation of factorial, there's really no need to recurse:</p>\n\n<pre><code>unsigned long factorial(unsigned n)\n{\n unsigned long x = n;\n while (--n) {\n x *= n;\n }\n return x;\n}\n</code></pre>\n\n<p>That said, computing factorial and then dividing by the appropriate amount to account for duplicates is prone to unnecessary overflow (consider a pathological case of <em>N</em> identical words, where <em>N</em>! is greater than <code>ULONG_MAX</code>). It may be worth finding a safer algorithm for this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T18:41:32.003", "Id": "431082", "Score": "0", "body": "Can you give me hint regarding any other algorithm...?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T20:54:06.747", "Id": "222601", "ParentId": "222584", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T14:57:24.037", "Id": "222584", "Score": "2", "Tags": [ "c", "array" ], "Title": "Permutation of words in a sentence" }
222584
<p>I wanted something equivalent to this Java program: </p> <blockquote> <pre><code>TreeMap&lt;Integer,Integer&gt; map = new TreeMap&lt;Integer,Integer&gt;(); map.put(10, 100); map.put(20, 200); map.put(30, 300); map.put(40, 400); map.put(50, 500); map.put(60, 600); map.put(70, 700); map.put(80, 800); System.out.println(map.floorKey(5)); System.out.println(map.floorKey(9)); System.out.println(map.floorKey(10)); System.out.println(map.floorKey(11)); System.out.println(map.floorKey(90)); </code></pre> </blockquote> <p>output:</p> <blockquote> <pre><code>null null 10 10 80 </code></pre> </blockquote> <p>As there is no direct API to achieve the same in C++, I wrote the following code to implement a similar <code>floorKey()</code> function:</p> <pre><code>template &lt;typename key,typename value&gt; int floorKey(map&lt;key, value&gt; input, int key) { auto begin = input.begin(); if (begin-&gt;first &gt; key)//if key is less than the first key. It must retrun -1; return -1; auto end = input.end(); end--; if (end-&gt;first &lt; key)//if key is greater than last key, it must return last key return end-&gt;first; //if key is equal to any existing key, it should return the key auto find = input.find(key); if (find != input.end()) return key; //Return the floor key for the given key auto lower = input.lower_bound(key); lower--; return lower-&gt;first; } </code></pre> <p>Here's the test program:</p> <pre><code>int main() { map&lt;int, int&gt; map; map.insert({ 10, 100 }); map.insert({ 20, 200 }); map.insert({ 30, 300 }); map.insert({ 40, 400 }); map.insert({ 50, 500 }); map.insert({ 60, 600 }); map.insert({ 70, 700 }); map.insert({ 80, 800 }); cout &lt;&lt; floorKey(map, 5) &lt;&lt; endl; cout &lt;&lt; floorKey(map, 9) &lt;&lt; endl; cout &lt;&lt; floorKey(map, 10) &lt;&lt; endl; cout &lt;&lt; floorKey(map, 11) &lt;&lt; endl; cout &lt;&lt; floorKey(map, 90) &lt;&lt; endl; return 0; } </code></pre> <p>output:</p> <blockquote> <pre><code>-1 -1 10 10 80 </code></pre> </blockquote> <p>Is there any better way to get the same? Anything else I can improve?</p>
[]
[ { "body": "<p>You know about <code>lower_bound</code>/<code>upper_bound</code>; why not use just once and then see if the iterator is at the beginning and where the key in the returned iterator lands compared to the given key?</p>\n\n<pre><code>template &lt;typename key,typename value&gt;\nint floorKey(map&lt;key, value&gt; input, int key)\n{\n auto greater = input.upper_bound(key);\n\n if(greater == input.begin()) \n return -1;\n\n assert(greater-&gt;first &gt; key);\n\n --greater;\n return greater-&gt;first;\n}\n</code></pre>\n\n<p><code>upper_bound</code> always returns an iterator that is just past the key. So decrement it to get the floor.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T16:14:54.933", "Id": "222589", "ParentId": "222587", "Score": "3" } }, { "body": "<p>Your code is obviously wrong:</p>\n\n<pre><code>template &lt;typename key,typename value&gt;\n</code></pre>\n\n<p>This line suggests that the code works for arbitrary maps, yet you require an <code>int key</code>, no matter what the key type of the map is.</p>\n\n<p>Returning <code>-1</code> is not proper C++ style. You should return an iterator, as all other container functions do.</p>\n\n<p>Passing the map by value makes an unnecessary copy of the whole map. Use a <code>const &amp;</code> instead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T16:35:03.030", "Id": "222590", "ParentId": "222587", "Score": "9" } }, { "body": "<h1>Headers and namespaces</h1>\n<p>The function is missing a definition of <code>map</code>. This is probably what you want:</p>\n<pre><code>#include &lt;map&gt;\n\nusing std::map;\n</code></pre>\n<p>Similarly, the <code>main()</code> needs:</p>\n<pre><code>#include &lt;iostream&gt;\nusing std::cout;\nusing std::endl;\n</code></pre>\n<p>That said, there's no good reason for <code>std::endl</code> in this code: an ordinary newline is sufficient, and we don't need the extra flushing behaviour of <code>std::endl</code>.</p>\n<h1>Naming</h1>\n<p>It's an error to use the typename <code>key</code> as the name of a parameter here:</p>\n<blockquote>\n<pre><code>template &lt;typename key,typename value&gt;\nint floorKey(map&lt;key, value&gt; input, int key)\n</code></pre>\n</blockquote>\n<p>It's pretty idiomatic to use PascalCase for template arguments, to distinguish them from function parameters:</p>\n<pre><code>template&lt;typename Key, typename Value&gt;\nint floorKey(std::map&lt;Key, Value&gt; input, Key key)\n</code></pre>\n<p>(I've also corrected the function to accept the correct type for the <code>key</code> argument).</p>\n<p>There's a similar problem in <code>main()</code>, where we have a conflict between the type <code>map</code> and our identifier <code>map</code>. This is one of the reasons I'd argue against bringing the type name into the global namespace.</p>\n<h1>Don't pass containers by value</h1>\n<p>We have a potentially large map, which we don't need to modify. That suggests that it's better passed as a reference to a const object. As we don't know the type of the key, we should probably assume that it's also better passed by reference (it could plausibly be a <code>std::string</code>, for example). That gives us:</p>\n<pre><code>template&lt;typename Key, typename Value&gt;\nint floorKey(const std::map&lt;Key, Value&gt;&amp; input, const Key&amp; key)\n</code></pre>\n<p>It's good that we used <code>auto</code> for the iterators <code>begin</code> and <code>end</code>, as it means that we don't need to change the body of the function to deal with them both now being const iterators.</p>\n<h1>Don't over-constrain templates</h1>\n<p>This template will only match when the <code>key</code> argument has <em>exactly</em> the same type as the <code>input</code> argument's key. That means that if we has a <code>std::map&lt;long, char&gt;</code>, we can't call passing an <code>int</code> key, even though <code>int</code> can be promoted to <code>long</code>.</p>\n<p>And do we really need a <code>std::map()</code>? Or would we like it to work with other map classes (e.g. <code>QMap</code> from Qt)?</p>\n<p>A fix for this (using Concepts introduced in C++20 to help give better error messages when misused):</p>\n<pre><code>template&lt;typename Map, typename Key&gt;\nauto floorKey(const Map&amp; input, const Key&amp; key)\n -&gt; typename Map::key_type\n requires std::totally_ordered_with&lt;Key,typename Map::key_type&gt;\n</code></pre>\n<h1>Consider returning a map node</h1>\n<p>What's the use of having the lower-bound key? In many cases, the caller will also want the corresponding value from the map. It's easy to return these both at once using the map's <code>value_type</code>, saving a second lookup.</p>\n<p>We can then provide convenience functions based on that to return just the key or just the value.</p>\n<h1>Think about edge cases</h1>\n<p>What happens in this code when the <code>input</code> argument is an empty map? We dereference <code>input.first()</code> without checking whether it's equal to <code>input.end()</code>, giving Undefined Behaviour at that point.</p>\n<h1>Prefer prefix decrement</h1>\n<p>We have:</p>\n<blockquote>\n<pre><code>auto end = input.end();\nend--;\n</code></pre>\n</blockquote>\n<p>It's slightly better to use <code>--end</code> there, as it eliminates any need to keep a copy for the value we're discarding. Or we can avoid the need to mutate the variable, if we include <code>&lt;iterator&gt;</code>:</p>\n<pre><code>auto const end = std::prev(input.end());\n</code></pre>\n<h1>Algorithm</h1>\n<p>There's really no need to search for an exactly matching key if we then go on to call <code>lower_bound()</code> - we could just call <code>upper_bound()</code> instead, which will find the first key that's strictly greater than <code>key</code>, then decrement (if doing so is valid) to get the result:</p>\n<pre><code>auto it = input.upper_bound(key);\n\nreturn it == input.begin()\n ? -1\n : (--it)-&gt;first;\n</code></pre>\n<p>Note that we have a problem here: if <code>Key</code> isn't a signed numeric type, then we can't return <code>-1</code>. We really need a type-dependent value for this. Better still, return a <code>std::optional</code>, so a defaulted value can be clearly distinguished from an actual result.</p>\n<hr />\n<h1>Modified code</h1>\n<pre><code>#include &lt;concepts&gt;\n#include &lt;map&gt;\n#include &lt;optional&gt;\n\ntemplate&lt;typename Map, typename Key&gt;\nauto floorNode(const Map&amp; input, const Key&amp; key)\n -&gt; std::optional&lt;typename Map::value_type&gt;\n requires std::totally_ordered_with&lt;Key,typename Map::key_type&gt;\n{\n if (auto it = input.upper_bound(key); it != input.begin()) {\n return *--it;\n }\n // not found\n return std::nullopt;\n}\n\ntemplate&lt;typename Map, typename Key&gt;\nauto floorKey(const Map&amp; input, const Key&amp; key)\n -&gt; std::optional&lt;typename Map::key_type&gt;\n{\n if (auto const node = floorNode(input, key); node) {\n return node-&gt;first;\n }\n // not found\n return std::nullopt;\n}\n\ntemplate&lt;typename Map, typename Key&gt;\nauto floorValue(const Map&amp; input, const Key&amp; key)\n -&gt; std::optional&lt;typename Map::mapped_type&gt;\n{\n if (auto const node = floorNode(input, key); node) {\n return node-&gt;second;\n }\n // not found\n return std::nullopt;\n}\n</code></pre>\n\n<pre><code>#include &lt;iostream&gt;\n\nint main()\n{\n std::map&lt;long, const char*&gt; const map =\n {\n { 10, &quot;G&quot; },\n { 20, &quot;F&quot; },\n { 30, &quot;E&quot; },\n { 40, &quot;D&quot; },\n { 50, &quot;C&quot; },\n { 60, &quot;B&quot; },\n { 70, &quot;A&quot; },\n { 80, &quot;A+&quot; },\n };\n\n for (auto val: {5, 9, 10, 11, 90}) {\n std::cout &lt;&lt; val &lt;&lt; &quot; -&gt; &quot;\n &lt;&lt; floorValue(map, val).value_or(&quot;U&quot;) &lt;&lt; '\\n';\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T17:26:21.553", "Id": "222593", "ParentId": "222587", "Score": "14" } } ]
{ "AcceptedAnswerId": "222593", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T15:37:13.483", "Id": "222587", "Score": "8", "Tags": [ "c++", "search", "library" ], "Title": "Java TreeMap.floorKey() equivalent for std::map" }
222587
<p>This is the task I am working on:</p> <blockquote> <p>In this assignment you will implement the K-Nearest Neighbour and Naïve Bayes algorithms and evaluate them on a real dataset using the stratified cross validation method. You will also evaluate the performance of other classifiers on the same dataset using Weka. Finally, you will investigate the effect of feature selection, in particular the Correlation-based Feature Selection method (CFS) from Weka.</p> </blockquote> <p>I have done the weka part and also written seperate code for performance evaluation. Here, I need help with the main code where I am implementing kNN and NB algorithm.</p> <p>Here is my code! I want to reduce the number of lines and possibly make it look more neat. Please help as much as you can. I have tried splitting into more functions and then calling them to do the work but is there a way I can do more? Also, is there a way the for loops can be written more compactly?</p> <pre><code>import heapq import sys import math as m from decimal import Decimal </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T16:52:09.607", "Id": "430948", "Score": "4", "body": "Welcome to Code Review! This question lacks any indication of what the code is intended to achieve. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T18:08:08.733", "Id": "430958", "Score": "1", "body": "Thanks for editing. It would also be helpful to reviewers if you provided a sample of what the input files look like." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T14:15:02.150", "Id": "431203", "Score": "0", "body": "Anyone can help?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T14:26:21.457", "Id": "431208", "Score": "0", "body": "@RafiulNakib is this a homework? Can you use ML packages like sklearn or at least numpy or does it need to be done in pure Python only?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T14:34:43.957", "Id": "431211", "Score": "0", "body": "Yes this is a homework assignment, I am not allowed to use any of the built-in classification libraries." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T16:42:12.197", "Id": "222591", "Score": "2", "Tags": [ "python", "algorithm", "machine-learning", "clustering" ], "Title": "Machine learning, kNN and Naïve Bayes algorithm" }
222591
<p>Can you please review my code and suggest why it may or may not be a professional looking code? I am just starting out as a programmer I am able to write code but I don't really know where I am right and where I am wrong.</p> <p>Also, I have heard that using the MVC approach in code is a smart way. Please suggest what changes this code would have if it were to comply with the MVC approach.</p> <p><strong>About the Code:</strong> This application is part of a cat scoring app. You score the cats by clicking on them. This way the most liked cat can be determined. This code does not currently store the score. So, as soon as the refresh button is clicked, the score is lost.</p> <p>This app is also available on <a href="https://codepen.io/anon/pen/BgQdMy#anon-login" rel="nofollow noreferrer">CodePen</a>.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const imageBasePath = "https://raw.githubusercontent.com/smartcoder2/CatClickerApp/master/images/"; const imageNameArrary = [ "tom.jpg", "jack.jpeg", "zoe.jpeg", "simba.jpg", "george.jpeg" ]; let catScore = [0, 0, 0, 0, 0]; // this keeps the score of each cat. index of array determines the cat let htmlUpdate; let ddl; const imageVar = document.getElementById("cat-image"); const textVar = document.getElementById("show-click-value"); imageVar.addEventListener("click", incrementClickVar); function incrementClickVar() { ddl = document.getElementById("select-cat"); catScore[ddl.selectedIndex]++; htmlUpdate = catScore[ddl.selectedIndex] == 0 ? "zero" : catScore[ddl.selectedIndex]; textVar.innerHTML = htmlUpdate; // } function validate() { ddl = document.getElementById("select-cat"); htmlUpdate = catScore[ddl.selectedIndex] == 0 ? "zero" : catScore[ddl.selectedIndex]; textVar.innerHTML = htmlUpdate; let selectedValue = ddl.options[ddl.selectedIndex].value; imageVar.src = imageBasePath + imageNameArrary[ddl.selectedIndex]; }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.outer-box { height: 100vh; display: grid; grid-template-columns: 1fr 1fr 1fr; grid-template-rows: 1fr 1fr 1fr; grid-gap: 2vw; align-items: center; } .outer-box&gt;div, img { max-width: 25vw; min-height: 10vh; max-height: 44vh; justify-self: center; } .outer-box&gt;div { text-align: center; } #show-click-value { font-size: 6vh; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" href="styles\style.css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="outer-box"&gt; &lt;div class="item1"&gt;&lt;/div&gt; &lt;div class="item2"&gt; &lt;label class="cat-label" for="select-cat"&gt;Select a cat&lt;/label&gt; &lt;select id="select-cat" name="cats" onchange="validate()"&gt; &lt;option value="Tom"&gt;Tom&lt;/option&gt; &lt;option value="Jack"&gt;Jack&lt;/option&gt; &lt;option value="Zoe"&gt;Zoe&lt;/option&gt; &lt;option value="Simba"&gt;Simba&lt;/option&gt; &lt;option value="George"&gt;George&lt;/option&gt; &lt;/select&gt; &lt;br /&gt; &lt;/div&gt; &lt;div class="item3"&gt;&lt;/div&gt; &lt;div class="item4"&gt;&lt;/div&gt; &lt;img id="cat-image" src="https://raw.githubusercontent.com/smartcoder2/CatClickerApp/master/images/tom.jpg" alt="image not loaded" /&gt; &lt;div class="item6"&gt;&lt;/div&gt; &lt;div class="item7"&gt;&lt;/div&gt; &lt;div id="show-click-value"&gt;zero&lt;/div&gt; &lt;div class="item9"&gt;&lt;/div&gt; &lt;/div&gt; &lt;!-- srr-to-do-later: position the image and other elements properly --&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T08:24:08.517", "Id": "431014", "Score": "1", "body": "Lovely cats. The [MVC approach](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) is not aimed at simple interactions like this, it would be overkill. It is used in more complex applications with lots of user interactions and a bigger database in the background." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T14:22:06.547", "Id": "431207", "Score": "0", "body": "What is your code supposed to do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T15:16:07.523", "Id": "431216", "Score": "1", "body": "@IEatBagels - you score the cats by clicking on them. This way the most liked cat can be determined. This code is not complete because I am not storing the score and as soon as the refresh button is clicked the score is lost." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T15:25:18.827", "Id": "431217", "Score": "1", "body": "@DeskiRey You should edit your question to include a description of what your code **currently** does." } ]
[ { "body": "<p><strong>Group cat data together in object, have a single source.</strong></p>\n\n<p>You have two arrays and an element, all joined together by a common index. I would move things around so all the details are coming from a single source. This means if you want to add a cat, you add it in one place. It also allows for an easy upgrade if you wanted to start storing this data somewhere that is not hard-coded.</p>\n\n<p>I have created a new <code>cats</code> array. This contains all the cats and their data:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const cats = [{\n name: \"Tom\",\n image: \"tom.jpg\",\n score: 0\n}];\n</code></pre>\n\n<p>For now we will stick with hard-coded data, however this could just as easily be a response from an API. For example:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>fetch('https://example.com/cats.json')\n .then(function (response) {\n return response.json();\n })\n .then(function (cats) {\n //... do something with the cats\n });\n</code></pre>\n\n<p>The <code>cats</code> array stores all the details we need to populate our dropdown:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const catSelect = document.getElementById(\"cat-select\");\n\ncats.forEach(function(cat, index) {\n const option = document.createElement(\"option\");\n option.value = index;\n option.text = cat.name;\n catSelect.add(option);\n});\n</code></pre>\n\n<hr>\n\n<p><strong>Handling user interaction</strong></p>\n\n<p>You have right idea with storing <code>document.getElementById(\"cat-select\")</code> in a variable, however, you are redefining it on every user interaction (<code>ddl = document.getElementById(\"cat-select\");</code>). Instead, lets define some constants. I have also added a new variable to keep track of the currently selected cat.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const catImage = document.getElementById(\"cat-image\");\nconst catScore = document.getElementById(\"cat-score\");\nconst catSelect = document.getElementById(\"cat-select\");\n\nlet selectedCat;\n</code></pre>\n\n<p>Now we can use these in our functions. I have modified your two functions and also added one new one:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>/*\nThis simple function is just to update the display of the score.\nI thought it was nicer to put it in a function to avoid duplicating the code.\nIf you wanted to change it in the future, you would only have to change it in one place.\n*/\nfunction displayCatScore(score) {\n catScore.innerText = score == 0 ? \"zero\" : score;\n}\n\n\n/*\nThis simply updates the score of the currently selected cat and then displays it.\n*/\nfunction incrementSelectedCatScore() {\n displayCatScore(++selectedCat.score);\n}\n\n\n/*\nThis function updates `selectedCat` and displays that cat's score and image.\n`cat` is the index of the cat that should be displayed.\n*/\nfunction displayCat(cat) {\n selectedCat = cats[cat];\n\n displayCatScore(selectedCat.score);\n\n catImage.src = imageBasePath + selectedCat.image;\n catImage.alt = selectedCat.name;\n}\n</code></pre>\n\n<p>Now for event listeners - I have moved them from your HTML to the Javascript. It's easier when everything is kept together and in my opinion, it is just much cleaner.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>catImage.addEventListener(\"click\", incrementSelectedCatScore);\n\ncatSelect.addEventListener(\"change\", function() {\n displayCat(this.value); // this.value will be the index of the selected cat\n});\n\ndisplayCat(0); // Display the first cat\n</code></pre>\n\n<hr>\n\n<p><strong>Full working example</strong>:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function displayCatScore(score) {\n catScore.innerText = score == 0 ? \"zero\" : score;\n}\n\nfunction incrementSelectedCatScore() {\n displayCatScore(++selectedCat.score);\n}\n\nfunction displayCat(cat) {\n selectedCat = cats[cat];\n\n displayCatScore(selectedCat.score);\n\n catImage.src = imageBasePath + selectedCat.image;\n catImage.alt = selectedCat.name;\n}\n\nconst imageBasePath = \"https://raw.githubusercontent.com/smartcoder2/CatClickerApp/master/images/\";\n\nconst cats = [{\n name: \"Tom\",\n image: \"tom.jpg\",\n score: 0\n },\n {\n name: \"Jack\",\n image: \"jack.jpeg\",\n score: 0\n },\n {\n name: \"Zoe\",\n image: \"zoe.jpeg\",\n score: 0\n },\n {\n name: \"Simba\",\n image: \"simba.jpg\",\n score: 0\n },\n {\n name: \"George\",\n image: \"george.jpeg\",\n score: 0\n }\n];\n\nconst catImage = document.getElementById(\"cat-image\");\nconst catScore = document.getElementById(\"cat-score\");\nconst catSelect = document.getElementById(\"cat-select\");\n\nlet selectedCat;\n\ncats.forEach(function(cat, index) {\n const option = document.createElement(\"option\");\n option.value = index;\n option.text = cat.name;\n catSelect.add(option);\n});\n\ncatImage.addEventListener(\"click\", incrementSelectedCatScore);\n\ncatSelect.addEventListener(\"change\", function() {\n displayCat(this.value);\n});\n\ndisplayCat(0);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.outer-box {\n height: 100vh;\n display: grid;\n grid-template-columns: 1fr 1fr 1fr;\n grid-template-rows: 1fr 1fr 1fr;\n grid-gap: 2vw;\n align-items: center;\n}\n\n.outer-box&gt;div,\nimg {\n max-width: 25vw;\n min-height: 10vh;\n max-height: 44vh;\n justify-self: center;\n}\n\n.outer-box&gt;div {\n text-align: center;\n}\n\n#show-click-value {\n font-size: 6vh;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;html&gt;\n\n&lt;head&gt;\n &lt;link rel=\"stylesheet\" href=\"styles\\style.css\" /&gt;\n&lt;/head&gt;\n\n&lt;body&gt;\n &lt;div class=\"outer-box\"&gt;\n &lt;div class=\"item1\"&gt;&lt;/div&gt;\n &lt;div class=\"item2\"&gt;\n &lt;label class=\"cat-label\" for=\"cat-select\"&gt;Select a cat&lt;/label&gt;\n &lt;select id=\"cat-select\" name=\"cats\"&gt;&lt;/select&gt;\n &lt;br /&gt;\n &lt;/div&gt;\n &lt;div class=\"item3\"&gt;&lt;/div&gt;\n &lt;div class=\"item4\"&gt;&lt;/div&gt;\n &lt;img id=\"cat-image\"&gt;\n &lt;div class=\"item6\"&gt;&lt;/div&gt;\n &lt;div class=\"item7\"&gt;&lt;/div&gt;\n &lt;div id=\"cat-score\"&gt;&lt;/div&gt;\n &lt;div class=\"item9\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;!-- srr-to-do-later: position the image and other elements properly --&gt;\n\n&lt;/body&gt;\n\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<p>If you have any questions or would like any further clarification, please let me know and I will be happy to help :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T14:20:22.127", "Id": "431206", "Score": "0", "body": "wow ! really grateful for this help. I'm still trying to absorb all the suggestions, but this is definitely going to improve my approach towards coding. thanks again, i might get back with some questions once i complete with implementing these suggestions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T16:03:43.127", "Id": "431219", "Score": "0", "body": "And the format of the first callback function to the `fetch()` promise can be simplified to an arrow function: `.then(response => response.json())`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T13:48:27.737", "Id": "222637", "ParentId": "222595", "Score": "4" } }, { "body": "<h2>About your HTML</h2>\n\n<p>You are missing the DOCTYPE. The first line should be:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;!DOCTYPE html&gt;\n</code></pre>\n\n<p>It’s a good idea to declare the primary language of the document. In case of English:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;html lang=\"en\"&gt;\n</code></pre>\n\n<p>It’s a good idea to specify the character encoding. The first element in the <code>head</code> element should be (in case of UTF-8):</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;meta charset=\"utf-8\" /&gt;\n</code></pre>\n\n<p>The <code>title</code> element is required. It belongs to the <code>head</code> element:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;title&gt;Cat Scoring&lt;/title&gt;\n</code></pre>\n\n<p>For linking your stylesheet, you probably mean <code>styles/style.css</code> instead of <code>styles\\style.css</code> (the backslash is not allowed in the URL path, unless percent-encoded).</p>\n\n<p>It’s not a big issue, but the <code>br</code> element is probably misused in this context. It should only be used for meaningful line breaks, not just for styling purposes. In your case, you should probably use CSS (e.g., <code>margin-bottom</code>).</p>\n\n<p>Unless \"image not loaded\" is the content of the image, this doesn’t seem to be an appropriate <code>alt</code> value. The <code>alt</code> value should serve as an alternative (that conveys the meaning/purpose of the image) to users who can’t access it (e.g., because they are blind).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T08:13:14.137", "Id": "477424", "Score": "0", "body": "and for html code, modify to semantic html instead of div tag, use section tag" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T14:25:18.927", "Id": "477591", "Score": "0", "body": "@MehrdadKianiAnbohi: Depends on what the `div` contains. Not every `div` element should be a `section`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T09:03:50.250", "Id": "477771", "Score": "0", "body": "Your page skeleton must have a semantic html bro @unor" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T01:07:20.033", "Id": "477843", "Score": "1", "body": "@MehrdadKianiAnbohi: It’s perfectly fine to have a page without a `section` element; in fact, it could even be wrong to use a `section`, namely if the content doesn’t necessitate it. And from the little bit of content in OP’s example, a `section` element would not be warranted, as all of the page content seems to be part of *one* section, which the `body` element (being a sectioning root element) represents." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T12:29:35.277", "Id": "222705", "ParentId": "222595", "Score": "3" } } ]
{ "AcceptedAnswerId": "222637", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T17:35:14.947", "Id": "222595", "Score": "3", "Tags": [ "javascript", "beginner", "html", "css" ], "Title": "Cat Scoring app" }
222595