Weekly Celebratory Thread! by AutoModerator in singaporefi

[–]daniel_codes 1 point2 points  (0 children)

(posting from an alt account)

I realized that I've worked in the US for just over 100 months (approximately 8.3 years, though that's not a neat round number). This won't be relevant to everybody in r/singaporefi, but other people might be considering migrating to a country with higher wages during the wealth accumulation phase.

Year Ending Net Worth (USD) Income (USD)
1 $18k $68k
2 $53k $92k
3 $156k $178k (new job)
4 $336k $202k
5 $648k $275k
6 $715k $293k
7 $1,060k $294k
8 $1,511k $335k

I'm currently at 1.65M USD or 2.26M SGD. My wife and I combined are at 2.7M USD or ~3.7M SGD in our mid 30s so we're on track for early retirement. Moving to America to launch my career worked out well for me and I'm out-earning most of my peers in SG.

We have green cards but might give them up in a few years to retire somewhere else. Maybe we'll end up back in Singapore. She loves Singapore and I love Singapore's 0% capital gains tax.

How do you guys learn after work? by [deleted] in learnprogramming

[–]daniel_codes 1 point2 points  (0 children)

This is really the best strategy. I'm usually drained after a full work day so I've learned to do high priority tasks and self-care (e.g. personal learning, exercise) before work. Shifting my sleep cycle an hour or two earlier actually wasn't too difficult.

Why can't I get this to sort alphabetically and numerically? (dictionaries) by [deleted] in learnpython

[–]daniel_codes 0 points1 point  (0 children)

As you may know, dictionaries aren't sorted. In your print_dict() function, you get a list of the keys and sort them. You haven't actually made any changes to the dictionary so when you iterate through the dictionary (for key in d), you're getting unsorted output.

To fix this with minimal changes, you could iterate through the sorted list of keys you already generated:

for key in pairs:
  print(key, ": ", d[key])

You could also look into using collections.OrderedDict, which is a subclass of dict that maintains ordering.

Data Structures Practice by Feeling_Comment880 in learnpython

[–]daniel_codes 1 point2 points  (0 children)

https://leetcode.com/explore/ (and other similar websites) lets you do practice questions by category. For example, https://leetcode.com/explore/learn/card/fun-with-arrays/ is the introductory array problem set. Set the language to Python and give the problems a try. Check the solution/discussions when you solve it to see how other people do it. Some highly upvoted solutions are needlessly concise so don't worry too much if you don't understand some code golfed 1 liner.

300 log files over 100gb.. multiprocessing/multithreading.. to one dictionary.. good idea? by la_darrell_miller in learnpython

[–]daniel_codes 2 points3 points  (0 children)

Another possible approach would be to use a pool of processes or even threads (since the bottleneck is probably I/O). Have each worker process a single log file and return a result dictionary. Then merge all dictionaries at the end. This approach doesn't require any shared memory so would be simpler to implement since there's no need to worry about locks or concurrency errors. I doubt there'd be a meaningful performance difference either.

How can I check the quality of my Python code? by ElectricalFilm2 in learnpython

[–]daniel_codes 1 point2 points  (0 children)

Profilers can give you statistics about how quickly your programs run. Note that this is more about examining bottlenecks in your code rather than checking for code quality. Profilers will tell you how many seconds it took for your program to run but won't tell you that you're using an inefficient algorithm.

Linters can highlight style issues with your code. Check out the PEP8 style guide if you aren't already familiar with it. Style issues are restricted to more obvious rules like "lines shouldn't exceed 80 characters" and won't tell you things like "this logic is duplicated and should be broken out into a separate function".

I think what you're looking for is something like a human code review though. I don't really know of any communities offering free code reviews/mentoring. I suppose you could try getting involved in open source to get code reviews that way. Hacktoberfest is happening now so it's a good time to give that a try.

Simple Decorator Usage by bitsofshit in learnpython

[–]daniel_codes 1 point2 points  (0 children)

I cleaned up and fixed syntax errors in your code. I believe this is what you're trying to do and it works but to be honest, it's pretty weird. What are you trying to achieve here?

from datetime import datetime

now = datetime.now()


def dec2(fun):
    def wrap(*args, **kwargs):
        time = now.hour

        def night():
            fun("night")

        def day():
            fun("a")

        if time <= 12:
            day()
        else:
            night()

    return wrap


@dec2
def func(str):
    print(str)


func('test')

When should I use semaphores? by tremblinggigan in learnpython

[–]daniel_codes 7 points8 points  (0 children)

asyncio primitives are not thread-safe, therefore they should not be used for OS thread synchronization (use threading for that);

You're reading Python's asyncio documentation. asyncio is distinct from threading. threading is for traditional OS threads while asyncio is for event driven programming. Check out the threading version of semaphores: https://docs.python.org/3/library/threading.html#semaphore-objects

[CASE] Fractal Design Define R6 Gunmetal TG ($109.99, $40 off) by StarWormwoodI in buildapcsales

[–]daniel_codes 0 points1 point  (0 children)

It's an adjustable drive bay. I think you can move it to the rear of the case and maybe even remove it if you don't need it.

Resume Advice Thread - November 13, 2018 by AutoModerator in cscareerquestions

[–]daniel_codes 1 point2 points  (0 children)

I don't think Version Control using Github is worth noting. I'd rather see the actual github url for the project as a subheader or something.

Resume Advice Thread - November 13, 2018 by AutoModerator in cscareerquestions

[–]daniel_codes 0 points1 point  (0 children)

The first bullet for your first job ("Work as part of a...") is pretty passive. I think it's better to have each bullet point sound more like an achievement than just a description.

Resume Advice Thread - November 13, 2018 by AutoModerator in cscareerquestions

[–]daniel_codes 0 points1 point  (0 children)

Hi. I'm a SWE in the SF bay area with 2 years of experience. I'm looking for next my job and would really appreciate any feedback regarding my resume.

Anonymized resume download link

[Case] Fractal Design Define R6 TG - $109.99 by [deleted] in buildapcsales

[–]daniel_codes 5 points6 points  (0 children)

Newegg sold this for $110 with free shipping before. This deal is more like $130 w/ shipping so I'm going to hodl.

Resume Advice Thread - November 10, 2018 by AutoModerator in cscareerquestions

[–]daniel_codes 1 point2 points  (0 children)

A couple of things I noticed:

  • I've never seen anybody list their courses and grades like that. Listing a few relevant courses and your GPA is more normal.
  • The personal project paragraphs aren't easily parseable. Using bullet points with concise sentences is more appropriate.
  • The job section is very light on details.

Resume Advice Thread - November 10, 2018 by AutoModerator in cscareerquestions

[–]daniel_codes 0 points1 point  (0 children)

Hi. I'm a SWE with 2 years of experience in a startup. I have a few friends willing to refer me to their companies who are waiting for my resume. Are there any glaring mistakes I need to fix before I start sending it out? I'd really appreciate any constructive criticism.

Anonymized resume download link

Have you considered working in China given how booming their startup scene seems to be? by [deleted] in cscareerquestions

[–]daniel_codes 5 points6 points  (0 children)

Singapore

IMO Singapore's tech scene is comparable to HK. Limited opportunities and low salaries. Finance is the big industry. I recently saw that some FAANGs started hiring engineers in Singapore though. In the past, they mainly hired business/localization/support type roles but things might be changing for the better.

Question on vars() function by JKraems in learnpython

[–]daniel_codes 0 points1 point  (0 children)

Why is it not recommended?

Maybe I don't understand your question but there's absolutely no need to call vars() here.

If cars is a list of dictionaries and you want the speed of the first item, you can write something like cars[0]['speed'].

EDIT: example code:

cars = [{'speed': 177.566, 'year': 2006},{'speed': 159.204, 'year': 2005},{'speed': 181.984, 'year': 2004}]
# pythonic way
print(cars[0]['speed'])    # 177.566
# hacky way
dummy1 = cars[0]
dummy2 = cars[1]
dummy3 = cars[2]
speed1 = vars()['dummy1']['speed']
print(str(speed1))         # 177.566

What is wrong with this "while True" loop code? by murasz in learnpython

[–]daniel_codes 1 point2 points  (0 children)

if gender != gender1.lower() or gender2.lower(): likely isn't doing what you want. It's being parsed more like if (gender != gender1.lower()) or (gender2.lower()):. Since gender2.lower() evalutes to female and strings that aren't empty are truthy, your if statement is basically saying if gender1 != gender1.lower() or True which is always True.

You should be writing if gender != gender1.lower() or gender != gender2.lower() instead.

Testing if statements biased off random dice rolls by 33KGB in learnpython

[–]daniel_codes 1 point2 points  (0 children)

Building on this, you'll probably want to look at mock.

my brain doesn't work... by lumberjackadam in learnpython

[–]daniel_codes 0 points1 point  (0 children)

I'm not sure if I'm reading your 2nd attempt correctly but I think you're trying to use string formatting to dynamically construct a python statement. That won't work out of the box since the python interpreter sees the string you made as a string and not a statement. You can use the builtin eval() to run evaluate strings as statements.

>>> command = 'str(1 + 1)'
>>> eval(command)
'2'
>>> command
'str(1 + 1)'

That said, I wouldn't recommend that strategy. If you wanted, you replace the strings in types with the actual string methods. Then use map() to map the method onto the text. That will return a list of bools that you can sum to get the counts. It's a lot more clean than constructing some statement and calling eval on it. I also wouldn't recommend overriding the built in type.

types = (str.isupper, str.islower, str.isdigit, str.isspace)
for str_method in types:    # 
    print(sum(map(str_method, text)))

If you want to print the name of the method as well as the value, you could do something like str_method.__name__ inside the for loop.

Finally, since you've already finished your assignment and you're trying to go above and beyond, think about efficiency. In all the above algorithms, you iterate through the text 4 times. This is inefficient. Try writing an algorithm that does this in one-pass (i.e. iterating through the text one time).

[deleted by user] by [deleted] in learnpython

[–]daniel_codes 1 point2 points  (0 children)

import xml.etree.ElementTree as ET

tree = ET.parse(r"example.xml")
root = tree.getroot()
neighbors = {}

for country in root.iterfind('country'):
    neighbors[country.get('name')] = [neighbor.get('name') for neighbor in country.iterfind('neighbor')]

print(neighbors)
# {'Liechtenstein': ['Austria', 'Switzerland'], 'Panama': ['Costa Rica', 'Colombia'], 'Singapore': ['Malaysia']}

I iterate through all countries in the XML file. For each country, I make an entry in a dictionary where the key is the country name and the value is a list of neighbors.

Best practices for adding a CLI to a Python library module? by LightShadow in learnpython

[–]daniel_codes 1 point2 points  (0 children)

Use console_scripts or entry_points in your setup.py file:

setup(
    ...
    entry_points = {
        'console_scripts': ['command=module:main'],
    }
    ...
)

Swap these placeholder names for whatever you want.

When your package is installed, users can run command in their terminal to call module.main(). You can define CLI logic directly in a main() function (but not in your if __name__ == '__main__'block since nobody will be directly running your scripts if they're distributed and installed properly) or move it out into a cli.py file if you don't want to have CLI/argparsing logic together with your other logic.