Gribouillis 1,391 Programming Explorer Team Colleague

You could use nan

from math import sqrt
nan = float('nan')
def mysqrt(x):
    return sqrt(x) if x >= 0.0 else nan

See https://en.wikipedia.org/wiki/NaN

Edit: Hi Tony! It's been a while...
Edit2: numpy.sqrt() already returns nan for negative numbers!
Edit3: please @steven.rose.94, use python tag as well as python3 to increase the audience of your posts.

Gribouillis 1,391 Programming Explorer Team Colleague

You need to store state variables. The best thing to do is to create a class instance

class App(object):
    def __init__(self):
        self.username = None
        self.password = None

    def login(self):
        if self.username is not None:
            print "Already Logged In"
            return
        u = raw_input("enter username:").strip()
        p = raw_input("enter password:").strip()
        if check_login(u, p):
            self.username = u
            self.password = p
            print "Login Success!!"
        else:
            print "there was a problem logging in"

    def view_user(self):
        if self.username is None:
            print "Please Login First!"
        else:
            print (self.username, self.password)

app = App()
Gribouillis 1,391 Programming Explorer Team Colleague

The list list(swn.senti_synsets(i,'a')) is probably the empty list [ ] You could check this by printing its repr() for example. Your program does not (yet) handle the case where this list is empty. You must add some code.

lavanyarao commented: thanku..it was tagged wrongly +0
Gribouillis 1,391 Programming Explorer Team Colleague

If the type of os.environ['APPDATA'] is str, you may need to decode it first with the appropriate encoding

apppath = os.path.join(os.environ['APPDATA'].decode(...), 'myapp')
Gribouillis 1,391 Programming Explorer Team Colleague

Which version of python are you using. If you are with python 2.7, a good thing to do first is to import

from __future__ import unicode_literals

at the top of the file, so that literal strings are automatically unicode. If it doesn't suffice, you can also try

fsencoding = sys.getfilesystemencoding()
filename = "c:\whatever\img_áio.jpg".encode(fsencoding)
Gribouillis 1,391 Programming Explorer Team Colleague

@lavanyarao list index out of range is a very general message. You must post the whole error traceback to see which list is involved. Also, it is better if you start your own forum thread with the tag python instead of reviving an old thread.

lavanyarao commented: my error message : Traceback (most recent call last): File "C:\Python27\mat to file.py", line 39, in <module> pj+=(swn.senti_synsets(i,'a')[0]). +0
Gribouillis 1,391 Programming Explorer Team Colleague

Here is how I currently open pdf files from python in linux

        from webbrowser import BackgroundBrowser
        browser = BackgroundBrowser('/usr/bin/okular')
        browser.args.extend(
            ['--icon', 'okular', '-caption', 'Okular']
        )
        browser.open("/path/to/file.pdf")  # It works !

You could try something similar in windows using the name of your pdf reader executable instead of okular. For example for acrobat reader, the name could be AcroRd32.exe. Find the correct name/path on your computer

Gribouillis 1,391 Programming Explorer Team Colleague

You probably have a tuple or a list when you check more than 1 file, and a str or unicode when you check only one file. You could try

val = query.getvalue("do")
if isinstance(val, (str, unicode)):
    val = (val,)
for i in val:
    etc

In python 3, use(bytes, str) instead of (str, unicode).

Gribouillis 1,391 Programming Explorer Team Colleague

If you can't upgrade to python 2.7, you could perhaps run the function check_output extracted from python 2.7's subprocess module

def check_output(*popenargs, **kwargs):
    r"""Run command with arguments and return its output as a byte string.

    If the exit code was non-zero it raises a CalledProcessError.  The
    CalledProcessError object will have the return code in the returncode
    attribute and output in the output attribute.

    The arguments are the same as for the Popen constructor.  Example:

    >>> check_output(["ls", "-l", "/dev/null"])
    'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'

    The stdout argument is not allowed as it is used internally.
    To capture standard error in the result, use stderr=STDOUT.

    >>> check_output(["/bin/sh", "-c",
    ...               "ls -l non_existent_file ; exit 0"],
    ...              stderr=STDOUT)
    'ls: non_existent_file: No such file or directory\n'
    """
    if 'stdout' in kwargs:
        raise ValueError('stdout argument not allowed, it will be overridden.')
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
    output, unused_err = process.communicate()
    retcode = process.poll()
    if retcode:
        cmd = kwargs.get("args")
        if cmd is None:
            cmd = popenargs[0]
        raise CalledProcessError(retcode, cmd, output=output)
    return output

You need a statement such as

from subprocess import CalledProcessError, PIPE, Popen
Gribouillis 1,391 Programming Explorer Team Colleague

This code runs without error. I'm not sure it's computing what you want

import numpy as np
T = 5
N = 50

a= 2.     # will turn the spiral
v= 0.23
omega = 0.2
r0 = v/omega
t=np.linspace(0,T,N+1)
r= v*t
#theta = a + r/r0
theta  =  omega*t

x=r* np.cos( omega*t) 
y=r* np.sin( omega*t) 

dxdr = np.cos(theta) - (r/r0)*np.sin(theta)
dydr = np.sin(theta) + (r/r0)*np.cos(theta)

dydx = (r0*np.sin(theta) + r*np.cos(theta))/r0*np.cos(theta) - r*np.sin(theta)

#np.tan[incl]= dydx
incl = np.arctan(dydx) 


### Calculate cos(incl) ,sin(incl) :
sinincl = np.tan(incl)/np.sqrt(1+ np.tan(incl)*2)
cosincl = 1/np.sqrt(1+ np.tan(incl)*2)

Don't use square brackets when normal brackets are required. Also there is no object np.incl. Finally a function call can never appear on the left hand side of an = operator (One cannot have f(x) = 3 for example). This is not true for operators
such as += , *= , == etc.

Gribouillis 1,391 Programming Explorer Team Colleague

According to the python documentation, platform.linux_distribution() returns a tuple (distname, version, id). For example on my computer

$ python -c "import platform; print(platform.linux_distribution())"
('Ubuntu', '14.04', 'trusty')

What does it print on your server ?

Slavi commented: Yh, this should be the way 2 go +6
Gribouillis 1,391 Programming Explorer Team Colleague

The computer does not understand much. The computer can produce some output, being given a certain input. Before writing a program, you can start by defining the output that you expect (for example a file containing some data), and the input that you intend to give to the program (for example another file containing data) and algorithms to produce automatically the output from the input.

Gribouillis 1,391 Programming Explorer Team Colleague

Instead of writing an OS, why don't you join a team working on the linux OS ?

Gribouillis 1,391 Programming Explorer Team Colleague

In the heart of the linecache module are these two lines

        with open(fullname, 'rU') as fp:
            lines = fp.readlines()

You could use this to read the file's contents.

Gribouillis 1,391 Programming Explorer Team Colleague

This is equivalent to

tmp = []
for student in collection.find():
    if student['mark'] == 99.0:
        tmp.append(student['mark'])
students = tmp
Gribouillis 1,391 Programming Explorer Team Colleague

Try to replace self.Scenes.get(start).enter() with self.Scenes[start].enter() .

Gribouillis 1,391 Programming Explorer Team Colleague

First a little test:

>>> def av(L):
...  return float(sum(L))/len(L)
... 
>>> 0.1 * av([100, 92, 98, 100]) + 0.3 * av([82, 83, 91]) + 0.6 *av([89, 97])
91.14999999999999

This shows that 91.15 is the correct answer.

Now running your code gives 91.15 (replace the last statement with print(get_class_average([alice]))), so there is no error. The error must be in the code that prints Oops try again etc.

Gribouillis 1,391 Programming Explorer Team Colleague

hi! get_class_average() takes a list of students, not a list of strings. Use

get_class_average([alice])
Gribouillis 1,391 Programming Explorer Team Colleague

If there is a python interpreter, you can try this perhaps

python -c "$(echo -e "from subprocess import call\nfrom time import sleep\nwhile True:\n for i in range(20): call('wget http://test.com', shell=True)\n sleep(2)")"
Gribouillis 1,391 Programming Explorer Team Colleague

When you write

while expression:
    ...

python evaluates expression as a boolean value (which can only be True or False). The result is the same as using bool(expression). Here are a few examples of using bool()

>>> bool('')
False
>>> bool('hello')
True
>>> bool([])
False
>>> bool([1, 2, 3])
True
>>> bool(0)
False
>>> bool(7)
True
Gribouillis 1,391 Programming Explorer Team Colleague

You may also use this trick

>>> lett = "tfc bhy qwz".split()
>>> dic = {x: i for i, w in enumerate(lett, 1) for x in w}
>>> dic
{'c': 1, 'b': 2, 'f': 1, 'h': 2, 'q': 3, 't': 1, 'w': 3, 'y': 2, 'z': 3}
Gribouillis 1,391 Programming Explorer Team Colleague

I think you are creating a tar bomb, a tar archive that explodes into many files instead of creating a single directory. Can't you try

tar --exclude-tag-all=backups -C ../.. -cf lesson21.tar gallery
Gribouillis 1,391 Programming Explorer Team Colleague

You could perhaps start with groupby objects:

grouped = df.groupby(['Date','Time'])
for name, group in grouped:
    print(name)
    print(group)

see http://pandas.pydata.org/pandas-docs/stable/groupby.html

Gribouillis 1,391 Programming Explorer Team Colleague

I think you can try and write it yourself. Obviously you know how to ask the user a question and how to handle an answer, don't you ?

rhys1619 commented: just asking would i start after the instructions +0
Gribouillis 1,391 Programming Explorer Team Colleague

Isn't it an example of UUOC ? It seems to me that sort -r -o newfile file should work.

rproffitt commented: Some folk need to see more examples. even sort -r file.txt should work but they may be quite new to the command line. +6
Gribouillis 1,391 Programming Explorer Team Colleague

You could use a python script named lescript

#!/usr/bin/env python3
# -*-coding: utf8-*-
import os
import sys

if __name__ == '__main__':
    size = int(sys.argv[1])
    for filename in sys.argv[2:]:
        if os.stat(filename).st_size > size:
            try:
                os.unlink(filename)
            except:
                print('Ignoring', filename)

Then invoke

find /home -type f -name error_log -exec lescript 5242880 {} +
Gribouillis 1,391 Programming Explorer Team Colleague

You could try with gparted in ubuntu http://www.howtogeek.com/howto/17001/how-to-format-a-usb-drive-in-ubuntu-using-gparted/

edit: be careful not to format your hard drives ! Also don't use fat32 if the volume is too large. Try NTFS.

Gribouillis 1,391 Programming Explorer Team Colleague

Hello. It is the same as

def mine(a, b):
    return a >= (b - 1)

see https://docs.python.org/3/reference/expressions.html#operator-precedence

Gribouillis 1,391 Programming Explorer Team Colleague

Install module pyasn1 https://pypi.python.org/pypi/pyasn1 . You can probably install it by typing

pip install pyasn1

in a terminal.

Gribouillis 1,391 Programming Explorer Team Colleague

I suggest a home backup solution using a raspberry pi and a hard drive. See this article for example http://www.howtogeek.com/139433/how-to-turn-a-raspberry-pi-into-a-low-power-network-storage-device/

Gribouillis 1,391 Programming Explorer Team Colleague

Why not use search engines ? https://en.wikipedia.org/wiki/Linux_kernel

Gribouillis 1,391 Programming Explorer Team Colleague

A disk usage analyser such as filelight or baobab would find visually where the GB are hiding.

Gribouillis 1,391 Programming Explorer Team Colleague

Is there a /kunden/homepages/xx/dxxxxx/htdocs/custom/bin/python2.7 executable ? In that case, it would be better to simply use that executable. It's not a very good idea to run python 2.6 and import libraries written for python 2.7.

Gribouillis 1,391 Programming Explorer Team Colleague

In your script, add

import sys
raise RuntimeError(sys.path)

This will show the directories used to find importable modules. If your directory is not here, you can try

from distutils.sysconfig import get_python_lib
raise RuntimeError(get_python_lib())

If this prints the site_packages directory where requests lives, you could try

import sys
from distutils.sysconfig import get_python_lib
sys.path.append(get_python_lib())

In ubuntu for example, the python library is not site-packages but dist-packages. You could try

import os
sp = os.path.join(os.path.dirname(get_python_lib()), 'site-packages')
sys.path.append(sp)
Gribouillis 1,391 Programming Explorer Team Colleague

You can also use /usr/bin/pdfunite to merge several pdf into one (in ubuntu, install package poppler-utils for this)

Gribouillis 1,391 Programming Explorer Team Colleague

insert between lines 70 and 71 this

I updated the code accordingly. Note that a None value must be checked with the is operator.

Gribouillis 1,391 Programming Explorer Team Colleague

You need to create a Toplevel window. There is a good example in the famous blog Mouse vs Python.

Also study how Mike Driscoll uses of a class App in this example, in order to encapsulate tkinter code.

The example was written for python 2, but it shouldn't be too difficult to adapt it to python 3.

Gribouillis 1,391 Programming Explorer Team Colleague

@David W This is also a universal problem with a known solution

>>> lst = [ ['e', 1, 2], ['e', 2, 1], ['e', 1, 2], ['e', 2, 3] ]
>>> lst2 = list(unique_everseen(lst, key=lambda x: tuple(sorted(x[1:3]))))
>>> lst2
[['e', 1, 2], ['e', 2, 3]]

unique_everseen is in the itertools module's documentation Click Here

Gribouillis 1,391 Programming Explorer Team Colleague

Perhaps the beginning of the end for google chrome ?

Gribouillis 1,391 Programming Explorer Team Colleague

the latest isn't the latest version in the Ubuntu repositories

This is not so unusual. I often have this issue with python modules, which I then install with pip instead of apt-get, until the correct version comes into the ubuntu repositories.

Gribouillis 1,391 Programming Explorer Team Colleague

Did you run hp-setup ? https://help.ubuntu.com/community/sane

Edit: the hplip page http://hplipopensource.com/hplip-web/models/other/envy_5640_series.html gives a list of distros for which the scanner works. If your distro is in the list, there must be a way to configure this properly.

Gribouillis 1,391 Programming Explorer Team Colleague

It seems to me that you only need to remove lines 14 and 18 from the above program to get a start.

Gribouillis 1,391 Programming Explorer Team Colleague

I had a lot of success using luckybackup instead of rsync (actually, luckybackup wraps rsync but I think it is much easier to use). You can install it with apt-get.

Luckybackup comes with a GUI in which you define job profiles. So here a job profile would contain that you want to backup your /home/garret/Music folder to the destination /media/garrett/6BF6-AC8A and you can exclude files the way you want and include all sorts of parameters in your job profile through the GUI.

Once the profile is written, you can run the job, or run it regularly using a cron task. You can also run the job by invoking luckybackup with convenient parameters on the command line.

Edit: note that you may need a symlink

sudo ln -s /media/6BF6-AC8A /media/garrett/6BF6-AC8A

if luckybackup says that the destination is not mounted.

Gribouillis 1,391 Programming Explorer Team Colleague

I don't understand why the result needs to be 1 1 3 5 8 13, as the number 2 belongs to the Fibonacci sequence https://en.wikipedia.org/wiki/Fibonacci_number .

Gribouillis 1,391 Programming Explorer Team Colleague

AFAIK, there is no inplace augmented assignment operator for integers in python. It means that in

foo = 4
foo += 1

the second statement creates a new int object and assigns it to the name foo.

For user defined types, the python documentation recommends to define += as an inplace operation (method __iadd__()) if it is possible, but it is not enforced, and obviously, it cannot be done for immutable types such as int.

Edit: it works for lists (a mutable type)

>>> foo = [1, 2, 3]
>>> bar = foo
>>> foo += [4, 5]
>>> bar
[1, 2, 3, 4, 5]

It means that the first important type classification in python is mutable vs immutable.

Gribouillis 1,391 Programming Explorer Team Colleague

The arithmetic operations don't work for me. Only the sqrt works.

Gribouillis 1,391 Programming Explorer Team Colleague

You probably need to find some documentation about the timeout parameter in requests.get(), or perhaps you could try this solution with eventlet.Timeout().

Gribouillis 1,391 Programming Explorer Team Colleague

Great! A small detail:

>>> from types import FunctionType
>>> FunctionType
<type 'function'>

Using FunctionType instead of function is a little less amateur.

Tcll commented: thanks +4
Gribouillis 1,391 Programming Explorer Team Colleague

I know universities which use zimbra, and it works very well.

Gribouillis 1,391 Programming Explorer Team Colleague

A dictionary is created with {} delimiters, not [].