22 votes

Programming Q&A Thread

An experiment I've been thinking about lately: a (recurring?) Q&A thread! Ask any questions about programming, answer other users' questions, or post suggestions for future threads.

Don't forget to format your code using the triple backticks or tildes:

Here is my schema:

```sql
CREATE TABLE article_to_warehouse (
  article_id   INTEGER
, warehouse_id INTEGER
)
;
```

How do I add a `UNIQUE` constraint?

Meta questions:

  • Should I turn this into a recurring thread?
  • If yes, should it be a weekly or a monthly thing?
  • Should DBA and SysAdmin questions be allowed or should someone else make a separate recurring thread for these?

28 comments

  1. [3]
    clone1
    Link
    Anybody have tips for learning to read code? Whenever I try to read a project I just get lost in the maze of objects and method calls and can't actually figure out what anything is doing. I know...

    Anybody have tips for learning to read code? Whenever I try to read a project I just get lost in the maze of objects and method calls and can't actually figure out what anything is doing. I know that the next steps in learning to program are understanding and contributing to open source projects, but I get stuck trying to gain a good enough understanding of a program to contribute to it.

    9 votes
    1. [2]
      Deimos
      Link Parent
      It's really not an easy thing. Honestly, I think the difficulty of it is why it's so common for people to think that rewriting entire systems is necessary. Someone new comes into a project, tries...

      It's really not an easy thing. Honestly, I think the difficulty of it is why it's so common for people to think that rewriting entire systems is necessary. Someone new comes into a project, tries to understand the code and has trouble following it, and jumps to, "this code is garbage, we need to rewrite this from scratch." Of course, even if they do rewrite it, the next person that comes in will almost certainly think exactly the same thing about the new code too.

      Overall, the ideal of easily-understandable, "beautiful" code is almost impossible for anything beyond extremely focused systems that deal with small, well-defined problems. Larger systems have to deal with a ton of edge cases and unexpected difficulties that lead to complexity. Understanding those systems will never be easy. That being said, I do have a couple pieces of advice, but I want to go off on a tangent first (which may not actually apply to you, I don't know how experienced you are):

      Even though it's common advice, I don't think that trying to contribute to open-source projects is necessarily a good idea for relatively new developers. A lot of open-source projects are hugely complex systems that have built up over many years and are often trying to serve the needs of many different groups of people. This makes them hard to understand, especially if you don't know the history of the project and how they evolved.

      Personally, the advice I usually give is that people should try to build something by themselves, from scratch, for a problem or use that they're interested in. It doesn't have to be anything amazing or unique, but it's important that it's something you want to exist and would use personally. That's what will keep you motivated to figure out how to implement new capabilities. The nice part about building it by yourself from scratch is that you will understand everything about the system. When you want to add something new, the only new things you have to learn are relevant to that specific addition. You don't have to work through 10 attached concerns in someone else's project before you can even start figuring out how to add the actual update.

      If it's one of the first larger projects you've worked on, it will probably end up being a mess, but that's totally fine. It gives you a base to learn with, and will also help by giving you a frame of reference when you do start looking at other people's code. You'll see how they do some things and be able to think, "oh, that would have been a much better way of doing X in my program." You'll also start to get an idea of what seems to work well or poorly based on how hard some parts of your program end up being to keep working with as you keep updating it.

      Anyway, tangent over. Here's my advice for if you do need to figure out a complicated system:

      • If at all possible, learn how to use a debugger for whatever language/platform you're working on. It can be much easier to get an understanding by setting breakpoints and/or stepping through the program while it's running to be able to watch what it does, examine variables to see what their values are and how they change, and so on. Stepping through code in a debugger can be more like getting pulled through the code instead of needing to find your own way through it, and even though it's confusing in other ways, it can help a lot with understanding what's going on. A lot of people don't seem to learn how to use debuggers, but they're extremely powerful tools.
      • If it is an open-source project and you have trouble figuring out some section of code but eventually work it out, consider writing some comments in that code that explain what's happening. Think about what information would have helped you understand it more easily, and write comments with that. Then make a pull request with those comments. If you're nervous about doing this, ask the maintainers first, but most open-source projects would love to have more comments added to their code, since that makes the same process easier for every new contributor in the future. It's not the same as contributing actual code, but it can be extremely helpful too. As a nice side benefit of it, it will also end up with more-knowledgeable people about the project confirming that you're understanding it correctly, since they'll review your comments and tell you if they're correct or missing anything.
      12 votes
      1. aphoenix
        Link Parent
        @clone1 I just want to highlight this tangent from Deimos, which is just fantastic advice, and I'm not just saying it because it's one of the same pieces of advice that I give to people. As the...

        @clone1 I just want to highlight this tangent from Deimos, which is just fantastic advice, and I'm not just saying it because it's one of the same pieces of advice that I give to people.

        the advice I usually give is that people should try to build something by themselves, from scratch, for a problem or use that they're interested in. It doesn't have to be anything amazing or unique, but it's important that it's something you want to exist and would use personally. That's what will keep you motivated to figure out how to implement new capabilities. The nice part about building it by yourself from scratch is that you will understand everything about the system. When you want to add something new, the only new things you have to learn are relevant to that specific addition.

        As the technical lead at a company, I actually do this professionally when I introduce junior developers to a new framework or language, and then about once per year to hone skills: come up with an idea, sell me on it, then build it, but the key is that you should actually want to use it. I review the code, and we work through any learning issues together. It's a fantastic system for getting people used to a language or framework.

        Once you know a framework, and have learned a bit of a language, then reading the code becomes more and more natural.

        Obviously, everything else Deimos said was also valuable. I'd add that a good set of tools is really important, so investing in learning to use your editor is a good idea. Whatever your editor is, it should help you not get lost in the maze of methods and classes; you shouldn't get sidetracked by "what's this" you should be able to immediately see what the thing giving you problems is, and deal with it.

        4 votes
  2. [3]
    Eric_the_Cerise
    Link
    I actually just posted a "Go or Rust?" question over here. Perhaps more appropriate to discuss it here? Meta ... is cross-posting cool?

    I actually just posted a "Go or Rust?" question over here. Perhaps more appropriate to discuss it here?

    Meta ... is cross-posting cool?

    7 votes
    1. unknown user
      Link Parent
      Exploring many languages is good, so I agree @ainar-g's advice. The great thing with Go is that it is blazing fast to get started if you know any ALGOL-like language, be it C or Java or Python or...

      Exploring many languages is good, so I agree @ainar-g's advice.

      The great thing with Go is that it is blazing fast to get started if you know any ALGOL-like language, be it C or Java or Python or Ruby. I recall it taking me a couple days to write a file system watcher CLI app from almost zero practical knowledge of the language to completion.

      Interfaces are a great idea that I love.

      If I was to pick one of them as my main tool, I'd look at what I genrally want to do: if I value correctness over developer comfort and speed, I'd pick Rust; if I wanted to get started quickly and Go's tradeoffs don't pose a problem, I'd pick Go.

      5 votes
    2. unknown user
      (edited )
      Link Parent
      EDIT: Forgot to add: you can ask me any questions regarding Go development. I'll gladly respond. I think reposts from other threads are okay, as long as you repeat the question in your post, so...

      EDIT: Forgot to add: you can ask me any questions regarding Go development. I'll gladly respond.

      I think reposts from other threads are okay, as long as you repeat the question in your post, so that people don't have to follow the link.

      Awesome. I'm actually right in the middle of trying to choose which one I should learn.

      I'd love to have a conversation with people here who already use one or (ideally) both ... any informed opinions?

      I am a professional Go developer, and I love Go. I've dabbled a little bit in Rust, and I've already written here about Rust before. In short, my opinion is that Rust is still growing, and there is a big chance that the code you write right now will have to be rewritten later, when async/HKT/constexpr/what-have-you becomes a part of the next edition.

      With that in mind, I would recommend learning both. Because they are very different languages with philosophies that are sometimes complete opposite of one another. Both will make you a better programmer, in different ways.

      In fact, don't stop there. Learn C. Learn Scheme. Learn POSIX shell. Tinker and explore. Solve real problems. Then solve them better, with less parts. Follow guidelines. Then write your own.

      3 votes
  3. [5]
    unknown user
    Link
    I'm an okay hacker: I'll put together scripts and Emacs modes that solve my problems. But when it comes to designing actual systems, with many parts and a proper structure to them, I fail. For...

    I'm an okay hacker: I'll put together scripts and Emacs modes that solve my problems. But when it comes to designing actual systems, with many parts and a proper structure to them, I fail. For example when I try to build an extensible class library or an app, I fail to come up with good designs. Why is that and how can I remedy it?

    Meta:

    1. Sure!
    2. Consider biweekly, it was the best fit for the ~books threads. But it's not hard to imagine that programming stuff will be way more popular, so weekly may work better. I'd say a month in between is too long.
    3. I guess they could be allowed until somebody takes the initiative to make a separate thread for them.
    6 votes
    1. DataWraith
      Link Parent
      I'm not sure if I qualify as someone who has good design, so take the following with a grain of salt, but I find it useful to do outside-in or "wish driven" development. I think Peter Norvig...

      I'm not sure if I qualify as someone who has good design, so take the following with a grain of salt, but I find it useful to do outside-in or "wish driven" development. I think Peter Norvig articulated the idea best, but unfortunately I can't seem to find the source again right now, so I might be mistaken.

      The idea is to start with a high-level wish, "I wish the program did X". And then you write a class or procedure that does X by making additional wishes: "I wish I already had a function/class/subroutine that did Y". You complete functionality X by making use of non-existent functionality Y. Then the compiler yells at you that Y doesn't exist, so you write Y the same way you wrote X, recursing until the program is complete.

      This can be formalized using Unit tests (c.f. Test Driven Design). Instead of merely saying "I wish I had X", you write a test that establishes a contract for what X does before building it. This makes you think hard about what X's responsibilities are.

      While I often have a general idea of what I want to build, the specifics tend to only emerge as I gain understanding of the task by solving parts of it. When I'm not under time-pressure, I often go as far as writing a spike, an initial version of the program that is meant to be thrown away once you learn from it what does and doesn't work.

      5 votes
    2. [2]
      unknown user
      Link Parent
      “Good Design” is an overloaded phrase. How do you define it for your personal projects?

      “Good Design” is an overloaded phrase. How do you define it for your personal projects?

      3 votes
      1. unknown user
        Link Parent
        Basically a good plan which helps me not get stuck as I go further when writing code. I think where I fail is I fail to translate the general mockups in my head into program components, and maybe...

        Basically a good plan which helps me not get stuck as I go further when writing code. I think where I fail is I fail to translate the general mockups in my head into program components, and maybe that's because I haven't put in the time to learn my tools in depth, especially languages and frameworks.

        I wonder if I just pick up Python 3 and decide to write say ten basic apps to completion with various libraries (like e.g. a simple outliner with Django, Flask, GTK, QT, etc.), would that help?

        4 votes
    3. Omnicrola
      Link Parent
      Why? Dunno. How to fix? First, know your design patterns. This book is the definitive work, but it's very dry and academic:...

      I fail to come up with good designs. Why is that and how can I remedy it?

      Why? Dunno. How to fix? First, know your design patterns. This book is the definitive work, but it's very dry and academic: https://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612 This one is much more approchable and is pretty popular: https://www.amazon.com/Head-First-Design-Patterns-Brain-Friendly/dp/0596007124

      You did also get feedback from co-workers in how they might design something for problem X.

      Another good tactic if to sit down with a developer who's more Jr and ask them if they understand it. Observing what is confusing to them and having to explain it often highlights when something is too complicated. The vast majority of the time making something easier to read and understand even if it's not the "optimal", "fastest", or most "efficient" is better. This is especially true in teams, but still applies when working solo. Relatively minor hits in performance are worth not having to spend hours or days of debugging or explaining code to co-workers.

      1 vote
  4. [2]
    unknown user
    Link
    Probably a tangential question, but has anyone here had any luck with spinning off a piece of software they've developed into a sustainable business, or even better, helped lead or develop a SaaS...

    Probably a tangential question, but has anyone here had any luck with spinning off a piece of software they've developed into a sustainable business, or even better, helped lead or develop a SaaS product? I have an inordinate number of questions about approaches to your development lifecycle, and how you decided what point it became viable to sell, where your MVP was, etc.

    6 votes
    1. Micycle_the_Bichael
      Link Parent
      I'm going to level with you right now, I'm so fucking tired I can't remember how to send a PM. I don't personally have any knowledge but I know a guy who knows a whole lot about doing exactly...

      I'm going to level with you right now, I'm so fucking tired I can't remember how to send a PM. I don't personally have any knowledge but I know a guy who knows a whole lot about doing exactly that. Shoot me a message and we can chat a bit and I can get some vague details you're willing to share and I can reach out and see if he can help.

      5 votes
  5. Eric_the_Cerise
    Link
    Meta-answers: . Yes . Lets see how much traffic it gets. . No, programming-specific.

    Meta-answers:
    . Yes
    . Lets see how much traffic it gets.
    . No, programming-specific.

    5 votes
  6. [3]
    gpl
    Link
    Always love a good Q&A. I've recently run into the issue of having to dump large amounts of data to disk using MPI and have yet to find a very good solution to it. I was looking at HDF5 since it...

    Always love a good Q&A.

    I've recently run into the issue of having to dump large amounts of data to disk using MPI and have yet to find a very good solution to it. I was looking at HDF5 since it seems to be a relatively popular data format, and it has a support MPI API that makes it somewhat appealing. However, the C++ wrapper for the parallel version isn't supported and that makes compilation somewhat of a nightmare since most of my simulation is written in C++ (you have to compile the HDF5 parallel code with a certain fork of mpicc, whereas the rest of my code is compiled with mpicxx). In any case, the tests I've run so far have been a little slow.

    Does anyone have experience dumping large amounts of data to disk (~100s of GB) every 5-10ish minutes or so, and if so how do you avoid I/O bottle-necking your application?

    Meta Questions:

    • If this gets a decent amount of attention I wouldn't mind it as a recurring thread. I always like seeing what questions and answers people come up with.
    • Probably monthly, unless of course we see a ton of activity.
    • I think they should be allowed since I don't foresee so much activity that the space gets cluttered. But if things get confusing it might make sense to section things off a bit.
    5 votes
    1. [2]
      arghdos
      Link Parent
      That seems way too frequent to be honest. Even my large scale CFD runs would only dump once or twice a reservation; admittedly the time step was very small due to combustion so this still worked...

      Does anyone have experience dumping large amounts of data to disk (~100s of GB) every 5-10ish minutes or so, and if so how do you avoid I/O bottle-necking your application?

      That seems way too frequent to be honest. Even my large scale CFD runs would only dump once or twice a reservation; admittedly the time step was very small due to combustion so this still worked out to pretty good time resolution. The first thing I would do is see if you can reduce the amount of info you're writing to disk, either by decreasing the I/O frequency or pruning the data if possible.

      From there, OLCF (PDF Warning) has some good info on common IO strategies for MPI. One obvious one you may have overlooked: have an HDF file per rank and worry about combining them into the full dataset after the simulation is complete.

      6 votes
      1. gpl
        Link Parent
        It's the unfortunate state of affairs: these are large scale cosmology simulations and at the initial stage I have to dump the entire mesh data for post processing into something more manageable....

        It's the unfortunate state of affairs: these are large scale cosmology simulations and at the initial stage I have to dump the entire mesh data for post processing into something more manageable. The bigger simulations are petabytes of data, but mine are much smaller - "100s" is probably an exaggeration. For my bigger runs it will actually be more like ~75-100 GB per step.

        Thanks for the link though, this seems helpful. I have seen the NERSC guide on parallel IO but it was somewhat lacking. I might end up using the in-house IO that was written for other simulations in my group even though I'll have to kind of hack it for my setup. I/O is such a headache tbh.

        6 votes
  7. [3]
    moocow1452
    Link
    Put this in an earlier thread, might be an answer here. Also I might be putting some weird Java on Mindstorms questions here since I'm training some new kids on how to Java.

    Put this in an earlier thread, might be an answer here.

    I know that Humble Bundle released a Web Version of FTL as part of a Humble Mozilla bundle that can run on a Mobile phone, but has to have mouse controls. Is there an Addin or a Developer tool in Firefox for Android that will let it emulate mouse controls on a mobile phone, since Mobile FTL has kind of been my white whale for a while?

    Also I might be putting some weird Java on Mindstorms questions here since I'm training some new kids on how to Java.

    4 votes
    1. [2]
      Greg
      Link Parent
      Depending on how much work you're willing to put into this, you could build a wrapper around Android WebView (or GeckoView) that sends spoofed mouse events based on an onscreen controller. I've...

      Depending on how much work you're willing to put into this, you could build a wrapper around Android WebView (or GeckoView) that sends spoofed mouse events based on an onscreen controller. I've seen it done to allow cursor navigation on an AndroidTV D-pad, for example, but sadly I don't know of any off the shelf implementations. Not to say they don't exist, of course.

      It's that or carry around a bluetooth trackball in your bag, anyway...

      3 votes
      1. moocow1452
        Link Parent
        So make a giant invisible widget in an Android app that tracks to Mouse Control? That might work...

        So make a giant invisible widget in an Android app that tracks to Mouse Control? That might work...

        3 votes
  8. actionscripted
    Link
    Meta: Yes, recurring. Weekly. Yes, allow DBA/systems stuff.

    Meta:

    • Yes, recurring.
    • Weekly.
    • Yes, allow DBA/systems stuff.
    4 votes
  9. [7]
    HydoTypo
    Link
    I'm currently an A-Level student in my second year of computer science. We have a personal project to design and develop and what really concerns me is the fact that I still can not get the hang...

    I'm currently an A-Level student in my second year of computer science. We have a personal project to design and develop and what really concerns me is the fact that I still can not get the hang of when to use classes when programming. I also want to break out of solely just using python but I honestly can't break out of it. Could anyone give me a pointer? Cheers

    3 votes
    1. [4]
      timo
      Link Parent
      I'm always debating using classes. They can quickly become a big mess, but can also provide very useful functionality. To contain certain functionality together, a module (file) is already good...

      I'm always debating using classes. They can quickly become a big mess, but can also provide very useful functionality. To contain certain functionality together, a module (file) is already good enough. When I use classes, they need to have a state. This state needs to be remembered, or can change. This can be some sort of login or open session with a webserver, or simply a user's karma/votes and what not.

      Let's take a game as an example: Our game has heroes. These hero have some attributes. Some may change, some never do.

      Let's define our class, with the name attribute. This name doesn't change.

      class Hero:
          def __init__(self, name):
              self.name = name
      

      Now, we can create one or multiple of these heroes.

      you = Hero(name="HydoTypo")
      me = Hero(name="timo")
      

      Let's say we want our heroes to fight each other. Let's give our hero some health (a state that changes). We want to keep track of our health during the game.
      We could use a function:

      class Hero:
          def __init__(self, name):
              self.name = name
              self.health = 100
      

      Let's say we want our heroes to battle it out in a fist fight. We can make punching a function of the Hero. For that, we use a class method:

      class Hero:
          def __init__(self, name):
              self.name = name
              self.health = 100
      
          def punch(self, target, damage):
              print(f"{self.name} punches {target.name} with {damage} damage")
              target.health = target.health - damage
      
      you.punch(target=me, damage=10)
      
      print(f"{me.name} has {me.health} health")
      "timo has 90 health"
      print(f"{you.name} has {you.health} health")
      "HydoTypo has 100 health"
      

      Now, you can see that the state of your hero stays the same, but my hero's state has changed. This is a simplified but typical example of when a class can be useful.

      Hope this helps a little :)

      4 votes
      1. [3]
        arghdos
        Link Parent
        Side note: you're using f-strings (which I love, but are 3.6+?) but the python2.1 style class syntax

        Side note: you're using f-strings (which I love, but are 3.6+?) but the python2.1 style class syntax

        1. [2]
          timo
          Link Parent
          I actually thought this was only something in Python 2. Here I'm reading that classes in Python 3 inherit from object by default:...

          I actually thought this was only something in Python 2. Here I'm reading that classes in Python 3 inherit from object by default:
          https://stackoverflow.com/questions/4015417/python-class-inherits-object

          1 vote
          1. arghdos
            Link Parent
            TIL, thanks! Relics from python2 compatibly in my code I guess :p

            TIL, thanks! Relics from python2 compatibly in my code I guess :p

            1 vote
    2. somewaffles
      Link Parent
      So it depends on what you're trying to accomplish, especially with a language like python that supports multiple paradigms. Object orientation is a hard concept to grasp for most people...

      what really concerns me is the fact that I still can not get the hang of when to use classes when programming.

      So it depends on what you're trying to accomplish, especially with a language like python that supports multiple paradigms. Object orientation is a hard concept to grasp for most people originally. If you're second year, I'm assuming that you've touched on OOP, at least a bit. Classes allow you to abstract your code especially when you start using inheritance/polymorphism/etc. If you're writing a straight-forward, functional script in python (ex a simple input/output school project thing), I'd say there is no reason to use classes. However, if your doing something more complicated, classes can help modularize your code and allow for re-usability.

      I also want to break out of solely just using python but I honestly can't break out of it.

      Kind of related to the first part but you should try more object oriented languages like java, C#, or C++. While python certainly supports OOP, it doesn't enforce it like the other languages. You're going to want something compilable rather than interpreted. Python is a great language, so I don't think there's any problem with you learning to code with it, but you learn a lot about programming concepts by learning other languages, especially ones that delve into other paradigms.

      3 votes
    3. DataWraith
      Link Parent
      This may sound obvious, but consider doing the same small project in several different programming languages. This allows you to compare and contrast what you like and dislike. In my experience,...

      I also want to break out of solely just using python but I honestly can't break out of it.

      This may sound obvious, but consider doing the same small project in several different programming languages. This allows you to compare and contrast what you like and dislike.

      In my experience, something of limited scope, but that is non-trivial, works best to learn a new programming language. I like to write game-playing programs; those can be as simple as Noughts and Crosses or Connect4 or as complicated as a chess engine.

      The best task I found was writing bots for online challenges such as Vindinium (sadly defunct now) or Halite (possibly defunct now?). It's really motivating to climb the leaderboards, and it is a task that is challenging enough to illuminate the potential of each programming language.

      If that is too time-consuming, you could look at Exercism. They have small exercises in just about any programming language.

      1 vote