Gribouillis 1,391 Programming Explorer Team Colleague

Here is a python script, if you have python

#!/usr/bin/env python
# -*-coding: utf8-*-
from __future__ import (absolute_import, division,
                        print_function, unicode_literals)

__doc__ = '''
'''

import argparse
import os

def main(args):
    d = args.directory
    for n in os.listdir(d):
        f = os.path.join(d, n)
        if os.path.islink(f):
            os.unlink(f)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
      description="""Remove symbolic links in a directory"""
    )
    parser.add_argument('directory',
        action = 'store',
        help = 'target directory',
        metavar = 'DIRECTORY',
    )
    main(parser.parse_args())

save it as rmsymlinks and make it executable

Gribouillis 1,391 Programming Explorer Team Colleague

I bought three Acer Aspire laptops with i7 and i5 processors. They were sold with windows 8, which I replaced with kubuntu 64 bits and they work very well.

Gribouillis 1,391 Programming Explorer Team Colleague

In a Prius, there is a small battery which is the same as in other cars and cost the same price. I changed it only once. There is also a huge battery for the hybrid system, but you never change it.

Gribouillis 1,391 Programming Explorer Team Colleague

Because your home directory is /home/weber. If you want the other path, use

os.path.join(os.path.expanduser('~'), 'jbwrk', 'xsend.py')

However, I think /home/weber/.xsend was probably meant. It may be a configuration file or directory. Try

ls -a ~

to see if there is a .xsend in your home directory.

Gribouillis 1,391 Programming Explorer Team Colleague

It means a string representing the file system path to the file or directory .xsend in your home directory. A better way to obtain it is

os.path.join(os.path.expanduser('~'), '.xsend')

This code is better because it is cross-platform.

Gribouillis 1,391 Programming Explorer Team Colleague

I have 2 Toyotas: a Prius, great great great hybrid car ! and an Aygo.

Gribouillis 1,391 Programming Explorer Team Colleague

Sometimes there are errors in a postscript or pdf document. There are several things you can try. If you can open the document with several programs, it may print with one of these programs and not with another. For example a pdf may print from a qpdfview window but not from an okular window.

Another thing you can try is to install a pdf printer. In ubuntu, it is done with

sudo apt-get install cups-pdf

You can then select the pdf printer when you want to print a document. It will create a pdf file in a folder (probably ~/PDF), then you can open this pdf with say qpdfview and try to print again with your printer.

Gribouillis 1,391 Programming Explorer Team Colleague

If you do >>> help(chr) in python 3, you get

Help on built-in function chr in module builtins:

chr(...)
    chr(i) -> Unicode character

    Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.

Now we can get a set of numbers with

>>> s = [i for i in range(0x10ffff) if unicodedata.category(chr(i)) == 'Lu']
>>> len(s)
1441
>>> s
[65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 216, 217, 218, 219, 220, 221, 222, 256, 258, 260, 262, 264, 266, 268, 270, 272, 274, 276, 278, 280, 282, 284, 286, 288, 290, 292, 294, 296, 298, 300, 302, 304, 306, 308, 310,...]
Gribouillis 1,391 Programming Explorer Team Colleague

Start with

Write a program that asks the user to enter a series of 20 numbers.

then post your code in this thread :)

Gribouillis 1,391 Programming Explorer Team Colleague

b64encode() return a bytes. Convert it to str with decode

result = base64.b64encode(username).decode('utf8')+'\n'

Notice that result has type str, while username is a bytes. I suggest not to use the same variable name in order to avoid type confusion.

Gribouillis 1,391 Programming Explorer Team Colleague

Try

sudo apt-get install trash-cli

It works for me in kde, providing commands

trash-put
trash-empty
trash-list
restore-trash

See Click Here.

Gribouillis 1,391 Programming Explorer Team Colleague

Don't print directly, use strings operations to create new strings with your data instead, for example

>>> args = (1,2,3,4)
>>> L = [str(n) for n in args]
>>> L
['1', '2', '3', '4']
>>> s = '+'.join(L)
>>> s
'1+2+3+4'
Gribouillis 1,391 Programming Explorer Team Colleague

When python says invalid syntax, it shows a point in code near the point where there is an error

File "foo.py", line 11
    print("Therefore, your total shipping charge would be " total)
                                                                ^
SyntaxError: invalid syntax

If you look at your code at line 11, you will see the error. Conclusion: take the time to analyse python's error messages. You can also post these error messages in the forum. They are very useful for helpers.

Gribouillis 1,391 Programming Explorer Team Colleague

I have a fast function in this snippet click here.

Gribouillis 1,391 Programming Explorer Team Colleague

I read about a python module named SaltStack yesterday. I think it can distribute commands the way you want.

Gribouillis 1,391 Programming Explorer Team Colleague

If you want to round the number for printed output, the correct way is to use string formatting operations. Click here to see some examples.

Gribouillis 1,391 Programming Explorer Team Colleague

Think about where you are going to insert op if the phrase is street. You are going to insert op when you meet the first e, because it is not a consonant and the previous letter is a consonant. You are also going to insert op at the end of the string because the previous letter is a consonnant. So, an algorithm would go this way, in pseudo-code.

previous_is_a_consonant = False
for letter in phrase:
    if letter is a consonant:
        previous_is_a_consonant = True
    else:
        if previous_is_a_consonant:
            append 'op'
        previous_is_a_consonant = False
    append letter
if previous_is_a_consonant:
    append 'op'
Gribouillis 1,391 Programming Explorer Team Colleague

import MetaMP3.py should be import MetaMP3.

Gribouillis 1,391 Programming Explorer Team Colleague

I have this but I dont know how to code it so that it works with only two clicks, 4 works but not 2.

There is a line missing somewhere, such as

    win = GraphWin("My Rectangle", 300, 300)

Apart from that, this is good python code

You can do it with 2 clicks if you realize that 2 points give you 2 values for x and 2 values for y. With these values, you can build 4 different points and draw the rectangle.

As this thread is 3 years old and Fo.katia is probably not waiting for an answer, you could write the complete running solution with 2 clicks in a code snippet. (select the type Code Snippet after you click Start a new discussion).

Gribouillis 1,391 Programming Explorer Team Colleague

write

export PYTHONPATH="$HOME/bin/libpy:$PYTHONPATH"

at the end of the file /home/garrett/.bashrc

Then restart the terminal.

Gribouillis 1,391 Programming Explorer Team Colleague

I dont see a return statement in cadena_aletoria(). It means that it returns None instead of a string.

Gribouillis 1,391 Programming Explorer Team Colleague

I wrote a code snippet some time ago with a base class for functors in python, click here. I use this class quite often to code reasonably-sized tasks which can be divided into smaller tasks sharing a temporary common state.

As an example, the following code defines a functor to count the number of lines of code (LOC) in the standard library.

#!/usr/bin/env python
# -*-coding: utf8-*-
from __future__ import (absolute_import, division,
                        print_function, unicode_literals)

__doc__ = '''
'''
from functors import functor
import io, os

class count_stdlib_LOC(functor):
    def __call__(self):
        result = 0
        for filename in self.python_source_files():
            result += sum(1 for line in io.open(filename, 'rb'))
        return result

    def python_source_files(self):
        root = self.get_stdlib_dir()
        for dir, subdirs, files in os.walk(root):
            for f in files:
                if f.endswith('.py'):
                    yield os.path.join(dir, f)
            subdirs[:] = [d for d in subdirs if not d.endswith('-packages')]

    def get_stdlib_dir(self):
        from distutils.sysconfig import get_python_lib
        return get_python_lib(standard_lib=True)

if __name__ == '__main__':
    print(count_stdlib_LOC())

""" my output -->
242389
"""

In my model, subclassing functor creates a callable instead of a class. Every time count_stdlib_LOC() is called, a new instance is created and the __call__() method is executed.

The advantage of having a functor instead of a function is that the task can be split into smaller tasks ran by other methods. This provides a handy way to encapsulate helper functions. These functions can share variables stored in self, which exist only during the execution of the task. The functor thus provides a short-lived namespace for the task.

These functors can …

Gribouillis 1,391 Programming Explorer Team Colleague

I couldn't concatenate a list & a string so I forced 'poisonous' into a list by adding brackets

A more common way is

poisonous = flowers[-1:]

Notice that this gives an empty list if flowers is empty, unlike your code which raises an exception.

Gribouillis 1,391 Programming Explorer Team Colleague

The conversion specifier is not the single character %. It has 7 components, most of them optional, as described in the documentation: click here.

So, for example %s and %d are valid conversion specifiers.

Gribouillis 1,391 Programming Explorer Team Colleague

Did you try googling for similar issues in ubuntu forums ? Start by reading threads such as this one click here, where you can find solutions that worked for others.

Gribouillis 1,391 Programming Explorer Team Colleague

Your installer is not executable. Run

chmod a+x xampp*
ls -l xampp*

In linux one uses ls instead of dir. You should see

-rwxr-xr-x 1 rik rik 124487989 aug  30 18:58 xampp-linux-x64-1.8.3-5-installer.run
Gribouillis 1,391 Programming Explorer Team Colleague

what is the output of ls -l xampp*

Edit: by the way, why don't you install lamp instead of xampp ?

Gribouillis 1,391 Programming Explorer Team Colleague

do sudo chmod 755 xampp-linux-*-installer.run first.

Gribouillis 1,391 Programming Explorer Team Colleague

Nice, but it shortens the list if the length is not a multiple of 3.

Gribouillis 1,391 Programming Explorer Team Colleague

It was my first code snippet in daniweb :). Here we go

>>> splitIt =  lambda d, s: [s[i:i+d] for i in range(0, len(s), d)]
>>> mylist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> splitIt(3, mylist)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]

See also the grouper() iterable in the recipes at the end of itertools documentation.

Gribouillis 1,391 Programming Explorer Team Colleague

Great! let us know if PyUserInput suits your needs.

Gribouillis 1,391 Programming Explorer Team Colleague

You need to install setuptools. Follow these instructions.

Gribouillis 1,391 Programming Explorer Team Colleague

Sorry, the folder must be added to PATH (provided there is a file C:\Python33\Scripts\pip.exe)

Gribouillis 1,391 Programming Explorer Team Colleague

For pip, you need C:\Python33\Scripts in the PYTHONPATH

Gribouillis 1,391 Programming Explorer Team Colleague

PATH and PYTHONPATH are 2 different things. You must update the PATH to contain C:\Python33, but be careful not to remove useful folders.

Edit: this tutorial may help you.

Gribouillis 1,391 Programming Explorer Team Colleague

You must set the PATH environment variable. It must contain a python directory (C:\Python34). Also, if you dont need 2 versions of python 3, you could uninstall python 3.3.

Gribouillis 1,391 Programming Explorer Team Colleague

I see that you have several installs of python on your computer. First type

python -c "import sys; print(sys.executable)"

in a cmd prompt, to see which is the default python. Assuming it is python 3.4, make sure the environment variable PATH contains the folders C:\Python34 and C:\Python34\Scripts (and not the other pythons). Then the pip command should be available. You should also check that the PYTHONPATH variable exists and contains your python library folders(perhaps C:\Python34\Lib).

See this page on python in windows.

Gribouillis 1,391 Programming Explorer Team Colleague

I agree with Slavi that gparted is probably the tool you need. What you can do is burn a boot-repair-disk. Apart from repairing boots, it contains a few tools, among which gparted. I used it today to resize and move a 300 GB partition (it took a few hours, but it worked). My experience with gparted is that it is better than other partition managers.

Gribouillis 1,391 Programming Explorer Team Colleague

Perhaps the pip executable is not on your path. Find the location of pip.exe in your file system. (If you can't find it, install Locate32 to find it)

Gribouillis 1,391 Programming Explorer Team Colleague

Did you run the pip installer first ?

Gribouillis 1,391 Programming Explorer Team Colleague

To use pip, in Windows, execute the program cmd, and type

pip install PyUserInput

in cmd's terminal window.

In ubuntu linux, open a terminal and type

sudo pip install PyUserInput

give your login password on request.

entropicII commented: I opened command prompt and typed in "pip install PyUserInput" and it returns: "'pip' is not recongnized as an internal or external command, operable program or batch file." Whats going on I downloaded it before and it doesn't seem to be working? +0
Gribouillis 1,391 Programming Explorer Team Colleague

You can use lambda line: bool(re.match(r"^\d", line)), but following woooee's idea of not using lambda, you can also write

def starts_with_digit(line):
    return bool(re.match(r"^\d", line))

RDD2 = RDD1.filter(starts_with_digit)
Gribouillis 1,391 Programming Explorer Team Colleague

It means that none of the calls to .find() finds anything.

Gribouillis 1,391 Programming Explorer Team Colleague

I would do it this way

>>> def shift_right(list_in, offset):
...     offset = offset % len(list_in) if list_in else 0
...     return list_in[-offset:] + list_in[:-offset]
... 
>>> one = [1,2,3,4,5,6,7]
>>> for i in range(-3, 10):
...     print(shift_right(one, i))
... 
[4, 5, 6, 7, 1, 2, 3]
[3, 4, 5, 6, 7, 1, 2]
[2, 3, 4, 5, 6, 7, 1]
[1, 2, 3, 4, 5, 6, 7]
[7, 1, 2, 3, 4, 5, 6]
[6, 7, 1, 2, 3, 4, 5]
[5, 6, 7, 1, 2, 3, 4]
[4, 5, 6, 7, 1, 2, 3]
[3, 4, 5, 6, 7, 1, 2]
[2, 3, 4, 5, 6, 7, 1]
[1, 2, 3, 4, 5, 6, 7]
[7, 1, 2, 3, 4, 5, 6]
[6, 7, 1, 2, 3, 4, 5]

Notice that in python, it is much better to raise an exception than to handle error via the return value. Instead of an error code, use

if offset >= len(list_in):
    raise ValueError(("shift value too large", offset))
Gribouillis 1,391 Programming Explorer Team Colleague

Here is a progran to create an example hierarchy of folders and search a correct folder. The idea is to extract a pair of numbers from the names and compare this pair to a target pair

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import os
import os.path
import re

def random_folder_names(cnt):
    """this function was used to create random folder names"""
    import random
    def year():
        day = datetime.timedelta(days = 1)
        start = datetime.date(2012, 1, 1)
        for i in range(366):
            yield start
            start += day
    year = list(year())
    def names():
        for day in year:
            m, d = day.month, day.day
            for fmt in ("{}-{}","{:0>2s}-{}","{}-{:0>2s}","{:0>2s}-{:0>2s}"):
                yield fmt.format(str(m), str(d))
    names = sorted(set(names()))
    return random.sample(names, cnt)

def create_example_hierarchy():
    """Create a random hierarchy of directories for testing purposes"""
    import shutil
    base = 'example_base'
    beds = 'beds'
    other = 'other'
    folder_names = [
        '6-5', '6-14', '5-03', '7-8', '5-21',
        '09-02', '03-27', '08-14', '06-30', '4-20',
        '06-13', '07-30', '11-07', '12-01', '10-29',
        '10-03', '12-5', '3-04', '7-26', '10-14',
        '01-14', '3-28', '5-09', '10-21', '6-18'
        ]
    try:
        shutil.rmtree(base)
    except OSError:
        pass
    os.makedirs(os.path.join(base, beds))
    os.makedirs(os.path.join(base, other))
    for name in folder_names:
        os.mkdir(os.path.join(base, beds, name))

def dir_sequence():
    """returns the sequence of subdirs"""
    return next(os.walk('example_base/beds'))[1]

def extract_md(dirname):
    """extracts month and day as a tuple of 2 integers"""
    t = tuple(int(x) for x in re.findall(r'\d+', dirname))
    assert len(t) == 2
    return t

if __name__ == '__main__':
    create_example_hierarchy()
    print "directories:", dir_sequence()
    file_date = '3-4'
    pair = extract_md(file_date)
    correct_dir = [d for d in dir_sequence() if extract_md(d) == pair][0]
    print 'correct_dir:', correct_dir

The output is

directories: ['10-29', …
Gribouillis 1,391 Programming Explorer Team Colleague

This does not tell us which one is the correct subfolder and why. We don't have the names of the folders.

Gribouillis 1,391 Programming Explorer Team Colleague

Perhaps you could describe a small hierarchy of folders, then tell us which one is the good one and why, assuming that you are searching a single folder in the hierarchy.

Gribouillis 1,391 Programming Explorer Team Colleague

how do i get it to retunr the largest of the numbers cuase i ran it on the files i have which are 08-1, 8-02, 8-3, and 08-04 it returns them all and i jsut need it returnign the largest of the number sets

I don't see anywhere in your code where you are looking for the largest of the number sets, whatever that means. There is no call to max(). You must describe the issue more precisely.

Gribouillis 1,391 Programming Explorer Team Colleague

Instead of getints(), define your own score function

def score(dirname):
    """return a value extracted from the dirname"""
    value = ??? # your code here
    return value

thedir = max(L, key=score)
Gribouillis 1,391 Programming Explorer Team Colleague

In python, the largest of a sequence can be obtained with the max() function with a key argument to compute the score of an item.

>>> import re
>>> def getints(string):
...  return tuple(int(x) for x in re.findall(r'\d+', string))
... 
>>> L = ['test02-05','test01-15','test03-2','test02-17',]
>>> max(L, key = getints)
'test03-2'