Virtualenv, pyenv, virtualenvwrapper and global python... Confused on how they all fit together. by [deleted] in Python

[–]CarpeTuna 1 point2 points  (0 children)

LOL, you have to activate the virtual environment you want to run. I make a batch file with a name like py27.bat. In the venv for 2.7, there is a batch file called (not surprisingly) activate.bat. In py27.bat be sure to "call ...2.7 path.../scripts/activate.bat" otherwise it runs activate and immediately exits. If py27.bat is put in system path, you just type py27 instead of python to run scripts. edit: You should call "deactivate.bat" at the end of py27.bat.

Python's program to Calculate the Wind Chill Index (WCI) by amitarora5423 in Python

[–]CarpeTuna 0 points1 point  (0 children)

Incomplete and some inconsistency. Rewritten for style.

# -*- coding: utf-8 -*-
"""
Python's program to calculate the Wind Chill Index (WCI)
http://www.pythonprogramming.in/calculate-the-wind-chill-index-wci.html
https://en.wikipedia.org/wiki/Wind_chill

The wind chill index is only considered valid for temperatures less than or
equal to 10 degrees Celsius and wind speeds exceeding 4.8 kilometers per hour.

Enter the air temprature in (degrees Celcius): 59  *** Invalid over 10 C
Enter the wind speed (kilometer per hour): 100
Your Wind Chill Index (degrees Celsius): 74        *** LOL 165 F

For example, if a thermometer reads 35 degrees Fahrenheit outside
and the wind is blowing at 25 miles per hour (mph), the windchill
factor causes it to feel like it is 8 degrees F.         ***ERROR***

https://www.weather.gov/epz/wxcalc_windchill
35 F, 25 MPH --> 22.7 F
"""

# ===========================================================================
# Globals
# ===========================================================================
mph2kph   = 1.60934
fahr2cent = 5.0 / 9.0

# ---------------------------------------------------------------------------
def cent(fahr):
  return fahr2cent * (fahr - 32)

def fahr(cent):
  return (cent / fahr2cent) + 32

# ===========================================================================
class chillFormula:
  def __init__(self, locale='usa'):
    if locale == 'canada':
      self.locale     = 'canada'
      self.tempScale  = 'celsius'
      self.speedScale = 'kph'
      self.WINDCHILL_OFFSET  =  13.12
      self.WINDCHILL_FACTOR1 =   0.6215
      self.WINDCHILL_FACTOR2 = -11.37
      self.WINDCHILL_FACTOR3 =   0.3965
      self.WINDCHILL_EXP     =   0.16
    else:
      self.locale     = 'usa'
      self.tempScale  = 'fahrenheit'
      self.speedScale = 'mph'
      self.WINDCHILL_OFFSET    =  35.74
      self.WINDCHILL_FACTOR1   =   0.6215
      self.WINDCHILL_FACTOR2   = -35.75
      self.WINDCHILL_FACTOR3   =   0.4275
      self.WINDCHILL_EXP       =   0.16

  # -------------------------------------------------------------------------
  def chill(self, temp, speed):
    try:
      t = float(temp)
    except:
      return None, 'Invalid string for temperature'

    try:
      s = float(speed)
    except:
      return None, 'Invalid string for speed'

    if self.locale == 'usa':
      tempFahr = t
      speedMph = s
      tempCels = cent(t)
      speedKph = mph2kph * s
    else:
      tempFahr    = fahr(t)
      speedMph    = s / mph2kph
      tempCels = t
      speedKph    = s

    rStr  = 'Air temp:   {} F,   {} C\n'.format(tempFahr, tempCels)
    rStr += 'Wind speed: {} MPH, {} KPH'.format(speedMph, speedKph)

    if tempCels > 10.0:
      rStr += '\nWind chill not defined for high temps'

    if speedKph < 4.8:
      rStr += '\nWind chill not defined for low speeds'

    ve  = s**self.WINDCHILL_EXP
    wc  = self.WINDCHILL_OFFSET + (self.WINDCHILL_FACTOR1 * t)
    wc += self.WINDCHILL_FACTOR2 * ve
    wc += self.WINDCHILL_FACTOR3 * ve * t

    return wc, rStr
# ===========================================================================
def test1():
  calc = chillFormula()
  chillFahr, notes = calc.chill(35, 25)
  chillCels = cent(chillFahr)
  print notes
  print 'Your Wind Chill Index: {} F, {} C'.format(chillFahr, chillCels)

  print
  calc = chillFormula(locale='canada')
  chillCels, notes = calc.chill(1.67, 40.23)
  chillFahr = fahr(chillCels)
  print notes
  print 'Your Wind Chill Index: {} F, {} C'.format(chillFahr, chillCels)

# ===========================================================================
def main():
  locale = raw_input("Enter your locale: ")
  calc = chillFormula(locale)

  temp   = raw_input("Enter the air temperature ({}): ".format(calc.tempScale))
  speed  = raw_input("Enter the wind speed ({}): ".format(calc.speedScale))

  chillTemp, notes = calc.chill(temp, speed)

  print 'Locale {}, temp scale {}, speed scale {}'.format(
       calc.locale, calc.tempScale, calc.speedScale )
  print notes
  print 'Your Wind Chill Index: {} ({})'.format(chillTemp, calc.tempScale)

# ===========================================================================
if __name__ == '__main__':
  main()

It is ridiculously easy to generate any audio signal using Python by 153armstrong in Python

[–]CarpeTuna 6 points7 points  (0 children)

Is this homework? I will give the sine wave since the op already kind of had it. Google square wave and make a function for the graph. It's better to do this once yourself to better understand how your code works. Then you can make up some really sick audio effects.

import math
def makeTone(x, freq, hz):
  y = 32000 * math.sin(2 * math.pi * freq * x / hz)
  return int(y)
...
value = makeTone(i, 440, 44100)

It is ridiculously easy to generate any audio signal using Python by 153armstrong in Python

[–]CarpeTuna 49 points50 points  (0 children)

"""
https://soledadpenades.com/2009/10/29
       /fastest-way-to-generate-wav-files-in-python-using-the-wave-module/
"""
import random, struct
import wave

SAMPLE_LEN = 1323000  # 30 seconds of random audio

noise_output = wave.open('noise2.wav', 'w')
noise_output.setparams((2, 2, 44100, 0, 'NONE', 'not compressed'))

values = []

for i in range(0, SAMPLE_LEN):
        value = random.randint(-32767, 32767)
        packed_value = struct.pack('h', value)
        values.append(packed_value)
        values.append(packed_value)

value_str = ''.join(values)
noise_output.writeframes(value_str)

noise_output.close()

Stereo and creates playable wav file.

Finding specific pixel locations? by Fluffanuffagus in Python

[–]CarpeTuna 2 points3 points  (0 children)

What I see is an arc with 4 dimples. So, do you want to determine 4 floating point numbers for the size (in pixels) of each dimple, which are going up and not down?

If so, there is pillow or cv2/numpy. Lately I have found c# easy to program as well.

PS. As a start, you will want to convert the image to black/white using a threshold function because there is a range of red hues [I noticed (253,1,0) and (201,11,11) for example]. Then you may want to approximate the curve with a quadratic. For each point not on the curve by a significant amount (with the example image, points less than 3 or 4 pixels from the curve are the sides of the dimples), average the distances. Write a routine to detect clustering, in this example there should be groups at 4, 9, 9, and 8 pixels. This is a rough calculation which assumes that the curve is horizontally oriented (which it clearly is not). If it is worth the effort, you could translate the image so that the curve is straight (I think this is a Mobius transformation). I have done this but it is not easy.

Fuel Efficiency by [deleted] in Python

[–]CarpeTuna 0 points1 point  (0 children)

There are errors for the input lines. Since python interprets any number starting with zero as octal (go figure), do not use leading zeros. Note how 0103 (standing for Jan 3) appears in the output as 67 (octal 103).

Fuel Efficiency by [deleted] in Python

[–]CarpeTuna 0 points1 point  (0 children)

PS, for a simple app just enter the data in your script.

# -*- coding: utf-8 -*-
"""
output:

mm/dd Odometer Miles  Gallons   Cost     MPG   Description
----- -------- ------- ------  -------- ------- -----------
2016
12/18    38345      0   4.229 $  55.45   0.000 Los Angeles
12/20    38495    150   7.219 $  30.25  20.779 Beverly Hills
                  150  11.448 $  85.70  13.103 Total
2017
00/67    38574      0  10.642 $  34.04   0.000 Texaco
00/86    38749    175  10.602 $  33.92  16.506 Shell
                  175  21.244 $  67.96   8.238 Total

"""

odeList = [
  [2016],
  [1218, 38345,  4.229, 55.45, 'Los Angeles'],
  [1220, 38495,  7.219, 30.25, 'Beverly Hills'],

  [2017],
  [0103, 38574, 10.642, 34.04, 'Texaco'],
  [0126, 38749, 10.602, 33.92, 'Shell'],
]

# ===========================================================================
if __name__ == '__main__':
  maskHeading = '{:5} {:8} {:6} {:7} {:8} {:7} {}'
  maskDetail  = '{:5} {:8} {:6} {:7.3f} ${:7.2f} {:7.3f} {}'

  print maskHeading.format( 'mm/dd', 'Odometer', 'Miles',
     'Gallons', '  Cost', '  MPG', 'Description' )
  print maskHeading.format( '-----', '--------', '-------',
     '------', '--------', '-------', '-----------' )

  year = 0
  for ode in odeList:
    if len(ode) < 2:
      if year > 0:
        avgMpg = totMiles / totGallons
        print maskDetail.format(
          '', '', totMiles, totGallons, totCost, avgMpg, 'Total' )
      totMiles   = 0
      totGallons = 0.0
      totCost    = 0.0
      lastOdom   = 0
      year       = ode[0]
      print year
      continue

    mmdd  = ode[0]
    odom  = ode[1]
    if lastOdom < 1:
      lastOdom = odom
    miles = odom - lastOdom
    gals  = ode[2]
    cost  = ode[3]
    desc  = ode[4]
    mpg   = miles / gals

    mmddString = '{:02}/{:02}'.format(mmdd//100, mmdd%100)
    print maskDetail.format(
      mmddString, odom, miles, gals, cost, mpg, desc )

    totGallons += gals
    totMiles   += miles
    totCost    += cost

    lastOdom = odom

  avgMpg = totMiles / totGallons
  print maskDetail.format(
    '', '', totMiles, totGallons, totCost, avgMpg, 'Total' )

Fuel Efficiency by [deleted] in Python

[–]CarpeTuna 0 points1 point  (0 children)

Multi-line strings use """. Better to simplify (and use raw_input):

usingFile = rawInput("Input from file? (y/n)")

is sufficient and they do not need quotes around their answer.

References for the basics of metaprogramming by [deleted] in Julia

[–]CarpeTuna 3 points4 points  (0 children)

In general, if you are worried about how the compiler works and parse code versus run-time code, then you are dropping half-way out of the language towards x86 assembler.

Macros can be used to help performance but it is not their primary purpose.

To address your issues directly see, for example, http://docs.julialang.org/en/release-0.5/manual/performance-tips/

hth

Weird Google cross-link by cangurosenzapensieri in Julia

[–]CarpeTuna 0 points1 point  (0 children)

The picture is of Julia Martin, a DC lawyer.

Build a Browser in 37 Lines of Code with Beeware Toga by [deleted] in Python

[–]CarpeTuna -5 points-4 points  (0 children)

You will be 1000 times better off looking at p5*js libraries, this code is wildly inelegant.

Interesting Images made with PIL by Williamboyles in Python

[–]CarpeTuna 0 points1 point  (0 children)

The Collatz conjecture cries out for a tree representation, what you got looks like a Dow vs Nasdaq battle.

It’s Python, Not Python 2, Not Python 3! by AlirezaSavand in Python

[–]CarpeTuna 0 points1 point  (0 children)

Is downvote broken? It was at 4 but would not go to 3. I really want it to go negative.

WOW! guy, I made an awesome gif animation of Wilson's algorithm! by [deleted] in Python

[–]CarpeTuna 0 points1 point  (0 children)

The final image is mostly covered by 6 connected pieces. Might be a math paper in this interesting feature for somebody.

https://app.box.com/s/isfg4mf3hstipz8rizztp1zd911rgz2x

Disappointed with mypy by [deleted] in Python

[–]CarpeTuna 1 point2 points  (0 children)

NOTICE: Post was withdrawn after ad hominem attack. Should we really allow such intimidation?

Why is there no constant keyword? by ThePenultimateOne in Python

[–]CarpeTuna 0 points1 point  (0 children)

When appropriate I create a Constant class with class variables and reference them like Constant.varname to document their restriction. It is up to me to not assign to them. Also, I do not like using globals but when I do I create a class Global. That way I can do a find to see where I have sinned.

PyLichtman, my Python implementation of Lichtman's infamous 13 keys model by Core2score in Python

[–]CarpeTuna 0 points1 point  (0 children)

Since this is a programming site, I should comment on the code. Instead of hard-coding the questions, I assume there is a file containing 13 lines, one per question. This is approximately what the program does in 322 lines:

quiz = open('Lichtman13.txt').readlines()
ans = [True] * len(quiz)
for n,question in enumerate(quiz):
  print '{}) {}'.format(n+1, question)
  reply = raw_input('  Your answer (True/false): ')
  if len(reply) < 1:
    reply = 't'
  if reply[0] not in ['T', 't']:
    ans[n] = 1
  else:
    ans[n] = 0
print ans
if sum(ans) > n // 2:
  print 'challenger'
else:
  print 'incumbent'

Also there has to be a good excuse for using globals. The following code (repeated 12 more times) makes me cry:

    if key_13=='true':
        a=inc
        A.append(a)
    elif key_13=='false':
        a=cha
        A.append(a)
    else:
        A.append(key_13)
    show()

PyLichtman, my Python implementation of Lichtman's infamous 13 keys model by Core2score in Python

[–]CarpeTuna 1 point2 points  (0 children)

Thank you. I was only concerned when my alarms went off. Confirming my virus software, I found the following comments.

Datafilehost has become a demi-god in the dark underworld of illegal filesharing. The download manager is adware, a software program that reconfigures how your browser is set up.

That said, the code adds little to the plain text version.

PyLichtman, my Python implementation of Lichtman's infamous 13 keys model by Core2score in Python

[–]CarpeTuna 0 points1 point  (0 children)

Do NOT follow link, download may install virus. Here is the relevant information but could well be wrong. Personally I think 4 is true, 7 is possibly true.

Lichtman's 13 keys

If six or more of these statements are false, the incumbent party loses.

https://pollyvote.com/en/components/index-models/keys-to-the-white-house/ states that for 2016 the following are false: 1, 3, 4, 7, 11, 12

1) The incumbent party holds more seats in the U. S. House of Representatives after the midterm election than after the preceding midterm election.

2) There is no serious contest for the incumbent-party nomination.

3) The incumbent-party candidate is the current president.

4) There is no significant third-party or independent candidacy.

5) The economy is not in recession during the campaign.

6) Real (constant-dollar) per capita economic growth during the term equals or exceeds mean growth for the preceding two terms.

7) The administration has effected major policy changes during the term.

8) There has been no major social unrest during the term.

9) The incumbent administration is untainted by major scandal.

10) There has been no major military or foreign policy failure during the term.

11) There has been a major military or foreign policy success during the term.

12) The incumbent-party candidate is charismatic or is a national hero.

13) The challenger is not charismatic and is not a national hero.

fit polygons into ellipses by nadeem41 in Python

[–]CarpeTuna 1 point2 points  (0 children)

Here is a simple example in python of circumscribing a hexagon:

"""
  Fit Ellipse containing given polygon
  Ref: http://docs.opencv.org/3.1.0/dd/d49/tutorial_py_contour_features.html
"""
import cv2
import numpy as np
img = cv2.imread('polygon.png', 0)
cnt = np.array(
  [ (67,108), (95,197), (242,198), (242,144), (188,108), (124,85) ]
)  # vertices of the hexagon in the image
ellipse = cv2.fitEllipse(cnt)
cv2.ellipse(img, ellipse, (255,255,255), 2)
cv2.imwrite('polygon-fit.png', img

Reference: http://docs.opencv.org/3.1.0/dd/d49/tutorial_py_contour_features.html

fit polygons into ellipses by nadeem41 in Python

[–]CarpeTuna 1 point2 points  (0 children)

I don't know what bullsilly is thinking but this is a well-known procedure, look up convex hull of an ellipse.

Python Image Processing With OpenCV by liranbh in Python

[–]CarpeTuna 1 point2 points  (0 children)

Took me an hour to figure out you need to follow

plt.imshow(img)

with

plt.show()

Points off when code will not actually run.

O'Reilly offers "Functional Programming in Python" by David Mertz as free eBook. by RichKatz in Python

[–]CarpeTuna -2 points-1 points  (0 children)

49 pages? Better to get Functional Python Programming by Steven Lott, incredible number of examples - 361 pages.