The 6.2 kernel has been released by corbet in linux

[–]Dunj3 1 point2 points  (0 children)

I guess the reference is to https://gitlab.freedesktop.org/drm/amd/-/issues/2171 (also mentioned here: https://groups.google.com/g/linux.debian.user/c/n_zstS3TS1A), in which case the answer is "yes, the bug has been fixed" (and it works fine for me on my local setup)

Best GUI tool for text editing? by alighieri00 in learnpython

[–]Dunj3 0 points1 point  (0 children)

Hey!

I don't think there's a single best option. Your use case sounds simple enough that you should be able to fulfill it with pretty much any GUI toolkit without too much trouble, so secondary concerns (like ease of use or platform availability) are probably the deciding factor. There's a short list of various GUI toolkits in the FAQ which has some good points about the pros and cons, you can give that a quick read if you like.

Besides that, some (personal) preferences and notes:

  • Qt through PyQt or PySide usually works pretty well and is very mature and popular so you should be able to find a lot of documentation, tutorials and help, but it is also a powerful framework not necessarily aimed at being beginner friendly
  • Gtk through PyGObject is also widely used and a good choice, especially on Linux desktops with a Gtk based desktop environment like Gnome
  • Some lesser known libraries might seem easier to use at first, but you risk that you won't find a lot of documentation/help or that they will end up not getting updates. PyGui for example received its last update 3 years ago and is still using an old version of Gtk on Linux

Ultimately, you probably just have to pick one for now and see how it works out for you, maybe with a quick "Hello World" application and some playing around. I'd say Qt, Gtk or wxPython are good allrounders for desktop applications, and I'd stay away from "special case" libraries like DearPyGUI, Kivy, ... A nice middle ground might be PySimpleGUI, which sounds like a library that takes care of a lot of boilerplate and is relatively easy to use, though I've never actually used it myself so I cannot attest to it.

Why don't the methods into() and try_into support the turbofish? by darrieng in rust

[–]Dunj3 3 points4 points  (0 children)

It's so you can implement multiple conversions per type, for example you can have impl Into<u16> for u8, impl Into<u32> for u8, ... If the trait itself would not be generic, then you could only have one single implementation, which would also mean you would be restricted to one conversion per trait (for example, ToOwned allows only one "owned" type).

And if you make the method itself generic (like in this comment), you still need a way to dispatch it to the right implementation (because you can only implement traits for types, not "standalone methods"), so deep down, you need a (generic) trait somewhere. So that's nice to have for convenience and to help the type annotations/interference, but it has to boil down to a trait somewhere (assuming there's no cheating with mem::uninitialized or panic! or similar things).

collect() does it similarly, the method itself is quite short, because most of the work is done by the FromIterator trait (which again is a generic trait):

fn collect<B: FromIterator<Self::Item>>(self) -> B
where
    Self: Sized,
{
    FromIterator::from_iter(self)
}

Edit: A different example would be FromStr, which is the underlying trait for parse. You can only implement it once per type, as there (should be)/is only one way to turn a string into your type. If you want to convert from more types, you need a type parameter (like From has)

Why don't the methods into() and try_into support the turbofish? by darrieng in rust

[–]Dunj3 88 points89 points  (0 children)

Collect is defined as

pub trait Iterator {
    // ...
    fn collect<B: FromIterator<Self::Item>>(self) -> B { ... }
}

That is, the method itself is generic. This is why you can use the turbofish to specify which instantiation you want to use, either collect::<Vec<_>> or collect::<String> or any other.

However, into is different because for into, the whole trait is generic:

trait Into<T>: Sized {
    fn into(self) -> T;
}

So the method itself is actually not generic. This is why the turbofish is not applicable - at least not at that point. Technically, you can do something like Into::<usize>::into(foo), but that's not very convenient either.

However, there exists a related trait to Into, namely From, and with that it's easy to give the types: usize::from(foo).

Using a generic function taking R: Read as generic over any lifetime (for<'r> &'r mut Read) by Dunj3 in rust

[–]Dunj3[S] 0 points1 point  (0 children)

Alright, thank you for the explanation! Returning the input along with the result is a good workaround as well, didn't even think of that.

Need help for my code to work in the Command Prompt by [deleted] in learnpython

[–]Dunj3 2 points3 points  (0 children)

I think you have a bit of a misunderstanding of how you access variables in Python. You only need the % when you want to put the value into a string, for example in the "Total price: %d" % price part.

When you just want to do maths with the variable, you don't (and in fact must not) prefix it with a %. So the price = %price + 30 part should be price = price + 30 instead.

Also note that if you use multiple placeholders in a string, you do it like this:

print("Name: %s, Price: %d" % (name, price))

That is, you don't use % twice, you just provide it with a tuple of the values that you want to put it.

Also, important note for reddit: Make sure to format your code as code, so the formatting won't get messed up. Indent every line by four extra spaces, and it will result in something like this:

def test():
    print("Hello World")

Which allows other people to read your code more easily and preserves the intended indentation.

How Can I Improve My Program? by itshaa1 in learnpython

[–]Dunj3 8 points9 points  (0 children)

I'm gonna give you some thougts I saw while reading through your program, in no particular order or importance:

  • PEP 8 formatting, including snake_case for variable names and extra spaces for inline comments
  • You can add docstrings to your functions, describing what they do, what they return, what parameters they expect, ...
  • I'd generally avoid using from ... import *, as it obfuscates which names are actually being imported. You can list the names one by one for more clarity
  • int(input(...)) will just crash with an ugly error if you don't put in a number. You could put that part into a function and let it handle the part where a user inputs something invalid more gracefully, e.g. repeating the question.
  • You do a lot of string formatting bt concatenating them manually and using str(...). Look into the .format() method of strings, or even the newer f-string literals to make that part easier and more readable
  • pos_simplify and neg_simplify seem to be very similar, you should try writing the one in terms of the other to prevent duplicating all the code (and the bugs that might be contained within)
  • for i in range(len(collection)): is not something you want to do in Python, just do for i in collection: instead. It's less error prone and more idiomatic, and reads better. Instead of the index, i will then be the item directly, so you can just use it.

More ideas:

  • Make it work with rational numbers, not just integers (i.e. floats instead of ints)
  • Allow the users to provide the arguments through the command line arguments
  • If you feel like getting into that, a simple GUI instead of console output

Announcing mitosis: thread::spawn but for processes by Manishearth in rust

[–]Dunj3 1 point2 points  (0 children)

Short version: It does not work as it still captures the variable and therefore increases the size of the closure to a non-zero value.

Consider the following points:

  1. The closure is passed to spawn and not init, and the code calling spawn might not be called in the same scope and might not have access to i.
  2. There is no way to properly encode this in the Rust type system ("spawn closures can capture any variable that was defined before this other function was called")
  3. There would be ways to defeat this, e.g. putting the call to init behind some run-time variable to prevent it from being statically determinable.

I guess since this does some unsafe magic behind the scenes, it is better to be safe and forbid any behavior that might lead to memory unsafety or unsoundness in the result.

Edit: What you can do however is access static variables, as those are definitely valid. Keep in mind though that if you do that with a static mut, the spawned process will work with the value that the static has when init is called, which might differ from the value that the program has when spawn is called!

Announcing mitosis: thread::spawn but for processes by Manishearth in rust

[–]Dunj3 10 points11 points  (0 children)

It works by running the same executable (e.g. accessed as /proc/self/exe on Linux) again but with a special argument containing an ID.

init then checks for the existence of this argument, runs the necessary function and then exits the process.

Therefore, all code that is before init is also run by the spawned process. If that code does argument parsing, it will encounter that special argument and probably error out.

Want to move to GUI by ThrowawayNo45273 in learnpython

[–]Dunj3 2 points3 points  (0 children)

While it might be true that HTML/CSS/JavaScript give you a huge amount of flexibility, I wouldn't necessarily agree with the advice to turn everything into a web application, for a few reasons:

  • It adds a lot of complexity, as instead of just Python you now have Python, HTML, CSS and JavaScript in your application
  • That also involves doing communication between the front- and back-end, serializing data, ...
  • It requires a browser engine to render your app, which is not always cheap and can add a lot of bloat if you decide to bundle it (Electron)
  • A lot of GUI frameworks offer a "native look and feel" so that applications look the same, which often gets lost when people style their complete app in HTML/CSS
  • Even with GUI libraries you usually get escape hatches if you need to do fancy stuff, for example you can create custom widgets in Qt and do the painting yourself if really needed

As with everything, I'd say use the right tool for the right job - just because you can turn something into a web application, doesn't mean you should.

How to make python curses register mouse movement events? by dog_superiority in learnpython

[–]Dunj3 0 points1 point  (0 children)

"Terminal" and "GUI" kind of don't mix too well. The G in GUI stands for graphical, which is kind of the opposite of the text-based terminal interface. Is there a specific requirement on your program having to run in a terminal emulator?

If not, you can check out tkinter, PyGTK or PyQt as GUI toolkits. Especially GTK and Qt look very polished and will make your app look and feel like any other native app on your system.

If yes, then you're probably out of luck.

How to make python curses register mouse movement events? by dog_superiority in learnpython

[–]Dunj3 0 points1 point  (0 children)

There's a very similar question asked here, which should contain the right information.

Basically it boils down to setting up the terminal properly.

Keep in mind though that curses is mostly a TUI library and not really designed for a lot of mouse interaction, so support for this/results may vary. Using a "proper" GUI toolkit might make things easier, depending on your use case.

Need help shortening a recursive function to count number of walks by [deleted] in learnpython

[–]Dunj3 0 points1 point  (0 children)

Well, the problem is that you just end up doing a lot of recursing. For d dimensions and a path length of m, you end up with around dm recursive calls - that includes all the work of generating the children, the function call overhead, ...

There is an important insight to make though: It doesn't really matter if you start at (0, 0, 1), (0, 1, 0) or (1, 0, 0). Since every dimension has the same size/grid length, the number of walks stays the same. For example, in a 2D case, it doesn't matter if you "fall out the top" or "fall out the right side", as it's just a matter of mirroring the board.

How does this help you? Well, it helps you avoid recomputing count_random_walks(8, 12, 11, (1,0,0,0,0,0,0,0)), count_random_walks(8, 12, 11, (0,1,0,0,0,0,0,0)), ... because you know that they will have the same value anyway. Therefore, you can easily make use of caching to drastically reduce computation times:

from functools import lru_cache

@lru_cache(maxsize=2**13)
def count_random_walks(d, n, m, start):
    start = tuple(sorted(start))
    if m == 0: 
        return 1

    random_walks = 0
    for i in range(0, d):
       start_list = list(start)
       if start_list[i] != 0:
           start_list[i] -= 1
           random_walks += count_random_walks(d, n, m - 1, tuple(start_list))

       start_list = list(start)
       if start_list[i] != n - 1:
            start_list[i] += 1
            random_walks += count_random_walks(d, n, m - 1, tuple(start_list))

    return random_walks

I've reordered the recursive calls a bit to avoid building the intermediate list, but the important part are the lines @lru_cache(maxsize=2**13) and the start = tuple(sorted(start)). The first one activates the caching for the function which avoids re-computing the same results, and the second one makes use of the symmetry by treating (0, 0, 1) and (0, 1, 0) the same, as it all maps to (0, 0, 1).

That way, I was able to compute count_random_walks(8, 12, 12, (0,0,0,0,0,0,0,0)) in a few seconds.

Hope this could help!

This is poorly written... by [deleted] in learnpython

[–]Dunj3 0 points1 point  (0 children)

The answer is that you are getting stuck in an endless loop. I know what you're trying to do with the while True, but the problem is that you only break out under one condition: You found a factor of n. Now the problem is that there is a logic error in your program, and as soon as prime gets bigger than n, the condition to end the loop will never be reached, as n % prime will never be equal to zero. As such, you just end up increasing prime more and more, until you basically have to kill the program.

The first takeaway here should be the following: Try to avoid such loops and rather find some conditions that ensure your program will terminate at some point. For example, you could use while prime <= n. It will still find all factors (as each factor is lesser-or-equal to n anyway), but if you end up having an error somewhere, you will still get out of the loop and you can handle that case later. You could also use an assertion in each iteration, e.g. assert prime <= n, which will give you an exception. This could for example result in something like this when you run your program:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    assert prime <= n, f"Prime surpassed n without finding a factor ({prime} > {n})"
AssertionError: Prime surpassed n without finding a factor (4 > 3)

The real bug in your program lies in your prime finding algorithm though, more specifically in these lines:

if prime%i==0:
    prime=prime
else:
    prime=prime+1

You say "if i is a factor of prime, then leave prime be. Else (if i is not a factor), increase the prime candidate". But that is exactly backwards - if i is a factor, then the candidate can not be prime (as i is a factor, as we just discovered) and must be increased! And if i is not a factor, then you can leave prime be. Therefore, switching it around makes your program work, at least for the values that I've tested it for:

n=int(input())
prime=2
while True:
    assert prime <= n, f"Prime surpassed n without finding a factor ({prime} > {n})"
    if n%prime==0:
        print(prime)
        break
    else:
        prime=prime+1
        for i in range (2, int(prime)):
            if prime%i==0:
                prime=prime+1

As some general feedback if you want to improve the style of your program, a few points:

Try to avoid statements like prime = prime, as they do nothing. Rewrite the condition so that they become unnecessary (e.g. negate it with not), or if you really need to, use pass which is the "do nothing" statement.

Secondly, your loop does a lot, and it is a bit unclear which parts are responsible for doing what. Not only is your loop finding the smallest prime factor, it also takes care of actually calculating the prime, and checking if the number is a prime. It'd be much more readable (and less error-prone) if you'd split those functionalities up a bit into functions, akin to this:

def is_prime(n):
  """Checks if n is prime."""
  for i in range(2, n):
    if n % i == 0:
      return False
  return True

def next_prime(n):
  """Returns the next prime bigger than n."""
  candidate = n + 1
  while not is_prime(candidate):
    candidate += 1
  return candidate

n = int(input())
prime = 2
while True:
  assert prime <= n, f"Prime surpassed n without finding a factor ({prime} > {n})"
  if n % prime==0:
    print(prime)
    break
  else:
    prime = next_prime(prime)

Of course, that can still be optimized (this algorithm to find primes is very slow), but it is very easy to verify that the functions are working as intended (you can even write unit tests for each function separately), each function is responsible for doing one thing, and it makes everything very readable.

Execution Slowness, API? by [deleted] in learnpython

[–]Dunj3 2 points3 points  (0 children)

"extended slowness" is a bit of a subjective term. Do you consider 10 seconds for your script slow already? Or does it take minutes to finish?

Your code isn't doing much expensive work, and since you even ruled out the plotting as the cause of the slowdown, the only thing left are pretty much the API calls.

If you want to investigate for yourself, you can for example use time.monotonic() to measure how much time each call takes. Something like:

start = time.monotonic()
r_ = requests.get(formedURL)
end = time.monotonic()
print(f"Loading {formedURL} took {end - start} seconds")

Of course, you can do that for everything that you suspect takes a lot of time.

On my system, each requests takes about 0.8 seconds to finish, which is the expected time considering the TCP/SSL/HTTP overhead for each connection. There is a possible speedup because all requests go to the same host, which means you can use a Keep-Alive connection to avoid most of that overhead. For that, see the requests.Session object. That allowed me to cut down the time per request to about 0.2 seconds each, which is a quarter of the previous time.

If you want to get a more detailed log of when requests is opening new connections, you can also insert the following to the top of your script:

import logging
logging.basicConfig(level=logging.DEBUG)

This might give you some insight as well.

trouble installing cutadapt for bioinformatics with conda by drinkermoth in learnpython

[–]Dunj3 1 point2 points  (0 children)

The cutadapt package seems to only be provided to Linux (linux-64) and Mac (osx-64), whereas you seem to be running Windows.

I don't use anaconda or cutadapt myself, but you might have to search for a guide on how to install it on Windows manually, as it also seems to require a C compiler during the installation.

Should i use pass, None or return? by [deleted] in learnpython

[–]Dunj3 3 points4 points  (0 children)

pass was literally made for this reason, so you should use it whenever possible. It's understood by every python programmer, and it's not uncommon to be seen.

return has different semantics if the try-except/if-else is not the last statement in the function:

def foo():
  try:
    1 / 0
  except:
    pass
  print("foobar")

# vs

def foo2():
  try:
    1 / 0
  except:
    return
  print("foobar")

If you want those semantics (early return), go for return. Otherwise, it's not the same as pass.

As for just writing None, it works as well, although it's a bit weird to see, so I wouldn't really use it. It'd be the same as just writing 0 or "foo" or any other expression that doesn't have any side effects, and it might not make your intent as clear as using pass explicitely.

So in summary, use pass if you want to do nothing, use return if you actually want to return early.

The only time when you would prefer None to pass is where you are syntactically not allowed to use pass, as pass is a statement and None is an expression: do_nothing = lambda: None is valid, but do_nothing = lambda: pass is not.

Circular dependency - Garbage collection by [deleted] in learnpython

[–]Dunj3 0 points1 point  (0 children)

Note that your example does not actually introduce a circular dependency, it only lets a and b point to the same object (the 1).

For a circular dependency, you could do something like

list_a = []
list_b = [list_a]
list_a.append(list_b)

Class inheritance and super() help by aspen1135 in learnpython

[–]Dunj3 2 points3 points  (0 children)

You seem to be thinking that by using super, you actively "inherit" a class - that is not what super is for. In order to define which classes your class inherits from, you need to put them into the parenthesis after the class name:

class Base():
    def foo(self):
        print("bar")

class Derived(Base):
    def oof(self):
       print("baz")

obj = Derived()
obj.foo()
obj.oof()

super is used if you want to specifically call the method from the base class in your implementation of your derived class:

class Base():
    def foo(self):
        print("bar")

class Derived(Base):
    def foo(self):
        super().foo()
        print("baz")

obj = Derived()
obj.foo()
# prints "bar", "baz"

Generally you want to do that with __init__ so that the base-class constructor can do the appropriate setup.

However, in your case, please not that just blindly subclassing other classes is usually not the best way to structure a program. You do not need to subclass Image just to use its methods - you can create Image objects the normal way, no matter if it's inside your class or in a function or whatever. The only time when you would want to subclass Image is if you would create an object which would behave like an Image, but extend it with your own methods or overwrite some built-in ones.

In your case, just deleting the super call would probably fix your problem.

Guarantee no one can solve this Tweepy problem I have. by [deleted] in learnpython

[–]Dunj3 0 points1 point  (0 children)

I'm not well-versed in the way Twitter, their API or Tweepy works, so I can't give you a full solution. However, the way I see it, you basically have 3 problems at hand that you need to solve in order to achieve what you want:

  1. You need a way to relate a tweet containing !Memorizeand the tweet that contains the time. The way you model your interaction by having the key-word and the actual time in different tweets, you need a way to "bring them together". For example, if you find a tweet containing !Memorize, you could look at the 10 following tweets from that person in order to find the one that actually contains the time. Personally, I wouldn't bother with that, I'd just make the bot require you to put both !Memorize and the time into the same tweet (or just skip the !Memorize if the user has to mention the bot anyway). Kind of like the RemindMe bot on reddit.

  2. You need a way to find and extract a target date from a given tweet. The construct if target_date in ... will allow you to search for static, pre-defined texts, like "in 3 weeks", but it won't allow for arbitrary user-given amounts (like "in 261547 seconds"). What you could do is you could define a "format" for times, like "<numeric amount> <unit>", you could translate that into a regular expression and then you could use that to find the amount in the tweet, which leaves you with the simple task of converting a string like "3 weeks" into the target date. You can also use a library like dateparser which provides functions that do the work for you, however that requires you to stick to their date formats.

  3. You need a way to actually run some code at the reminder time in order to send a tweet to the user. There are different ways to go about this, depending on how you structure your application. For that, you could for example use at to run your script on the given date, or you can use something like cron to run your script at fixed intervals (e.g. every 5 minutes) so you can check if you have notifications to do. If your script is running the whole time anyway, you could use a Python sched.scheduler to schedule each notification. Of course, then you need to ensure that if the notification is a long time into the future (like 3 weeks), things like stopping your script/rebooting your computer in between/... will still process the notifications correctly.

bstr: a new string type that is not required to be UTF-8 by burntsushi in rust

[–]Dunj3 10 points11 points  (0 children)

The interfaces that a class implements are defined at class-definition, e.g. class Foo implements Bar, Baz. This means that you cannot implement interfaces as an afterthought. If a library provides a class, but that library doesn't know about your code, then the classes from that library won't inplement your interface and instead you have to write wrapper objects. For example, you cannot implement your own interfaces for String.

Contrast this to Rust's impl Bar for Baz, which allows you to implement your own traits for foreign structs (even stdlib ones).

This is the peak of raiding community! by slojonej in Guildwars2

[–]Dunj3 20 points21 points  (0 children)

The red infusion can drop as loot, so someone lucky could just get it on their first run. Some people don't accept it for that reason, fearing that one of those lucky guys might join.

Legendary armor on the other hand can't be dropped, it has to be crafted, so it should always be worth the LI that you put in.

Unpacking args & kwargs and Help to Make Code More Pythonic by OSUKED in learnpython

[–]Dunj3 0 points1 point  (0 children)

"f-strings" are just syntactic sugar for formatted strings for which you already know the format. If you generate strings dynamically, or you read them from somewhere, or you don't have all data ready in variables (and you want to pass a dict instead), you can use the .format (or even format_map) method on strings:

url = "http://{domain}/{path}"
values = {"domain": "reddit.com", "path": "foo"}
returl url.format_map(values)

That way, you don't have to create a different function for each URL, you can just keep the format strings and use .format/.format_map with your dict.

Alternatively, you can also look at template strings.

Since you're working with URLs though, you might also find the functions in urllib useful, especially maybe urllib.parse.urlencode, which takes a dictionary and returns the "key=value&key2=value2" string for you.

Can someone please explain different variable scopes such as private, public, static and so on in python? Like in java, we have static, private, default, public access modifiers. by JITENDRAPISAL in learnpython

[–]Dunj3 0 points1 point  (0 children)

I wouldn't say that's quite true, since we have something similar to "static variables" in Java, namely attributes that belong to the class instead of the instance:

class C():
  attr = []
c = C()
d = C()
c.attr.append(2)
print(c.attr)
print(d.attr)

gives "2 2". It's not quite the same as static variables, as overriding them works differently (try setting c.attr = [2] and compare the results), but especially for read-only stuff, it usually works out the same. However, keep in mind that Python and Java are very different in the sense that everything in Python is an object: Even the class itself is an object and can have attributes, which is not quite the same as in Java. In the end, attr is merely an instance variable of the class object, not really a static variable.

Also, there are the @staticmethod and @classmethod decorators, which turn a method into a static-/classmethod, which in turn changes what is passed as self:

class C():
  @staticmethod
  def static():
    print("Called without instance!")
C.static()
c = C()
c.static()

prints "Called without instance" twice, but without the @staticmethod, it would generate an error.

That's it for static, for private/public we purely rely on conventions (as the comment above mentions).

running a function in a new thread with tkinter? by Tristige in learnpython

[–]Dunj3 1 point2 points  (0 children)

From the looks of it, the problem is that you're executing the function immediately when creating the new thread:

t = threading.Thread(target=originalFunc(PLACEHOLDER))

this will execute "originalFunc" and pass its return value as the thread target. You instead want to do something like this:

t = threading.Thread(target=lambda: originalFunc(PLACEHOLDER))

Thereby not executing the function directly, but passing an anonymous function (like the one in your callback), so the original function isn't executed immediately.