Python

Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in other languages. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive set of standard libraries, including NumPy, SciPy, Django, PyQuery, and PyLibrary.

Share tech news, updates, or what's on your mind.

Sign up to Post

import serial

import os, time
 
# Enable Serial Communication
port = serial.Serial("/dev/ttyS0", baudrate=38400, timeout=1)

# Transmitting AT Commands to the Modem
# '\r\n' indicates the Enter key
 
port.write('AT'+'\r\n')
rcv = port.read(10)
print (rcv)

Open in new window

Hi, I am trying to establish communication raspberry pi 3 with SIM 900. I am facing encode issues. I did try many solution from online but didn't get through. the code are as follows with compile results; Please do advice, thanks.
-------------------------------------------------------------------------------------------------------------------
>>> 
======================= RESTART: /home/pi/my_serial.py =======================
Traceback (most recent call last):
  File "/home/pi/my_serial.py", line 11, in <module>
    port.write('AT'+'\r\n')
  File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 518, in write
    d = to_bytes(data)
  File "/usr/lib/python3/dist-packages/serial/serialutil.py", line 63, in to_bytes
    raise TypeError('unicode strings are not supported, please encode to bytes: {!r}'.format(seq))
TypeError: unicode strings are not supported, please encode to bytes: 'AT\r\n'
>>>
0
New feature and membership benefit!
LVL 11
New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

I have a multiclass classification problem for time series data and I am using MLP as classifier giving as output either the predicted class label or the predicted probability for each class for the test examples.
Now I want to put on top of this and HMM to smooth a bit the predictions.
If I use the predicted labels I can use the python package hmmlearn and I see already better performances for the classification task.
However I would like to use as emissions probabilities the probabilities gives as output of the MLP and see if using this makes any difference in the smoothing.
I read many papers where they say we can use as emissions probabilities the likelihoods obtained by applying the Bayes' rule to the posterior that the MLP gives as output.

I am a bit confused on some points:

 -  I converted the Matlab Viterbi algorithm (as in python I haven't found an implementation) and used it with input (other than the transition matrix and prior) the emission probabilities being the likelihood. The performances however are not good as when using the predicted labels.
 - if I use the posterior given by MLP as output instead of the likelihood the performance are better and closer to the one obtained if I use the hmmlearn pkg.

I would like to better understand or confirm why I should use the likelihood instead of the posterior. For what I understand we use the likelihood as we want a scaled version of the predictions wrt the class frequency (prior) and we have hidden …
0
Hi
I am nearly ready to begin my foray into games in Python. However, is it more advisable to incorporate a JFrame for the game Window? Is Python GUI up to speed?

Thanks
0
Hi folks,

I have a piece of code that is trying to read out member details from a file and then use a date in that file together with today's date to work out the approximate difference in months (I have not yet started to tackle the exact days in a given month yet) and see if they are over 12 months therefore I can class them as an 'overdue' payment.

I have tried a number of different ways and seem to end up looping around back to TypeError: an integer is required (got type str).

I have attached a cut down version with just the part of the code with an error. I think the issues is within these following lines however I could be wrong:

d = datetime.datetime.now()

lastdatepaid = int(datetime.datetime("%Y-%m-%d"))

newldp = datetime.datetime.strptime(lastdatepaid,"%Y-%m-%d").date()

datechange =(d - lastdatepaid).days

It might help to have the JSON file data:

[[{"DOB:": "2001-11-17", "FeeType:": "SP", "Firstname:": "Joe", "Last Date Paid:": "2016-11-01", "Money Owed: \u00a3": 100, "Months Overdue:": 0, "Months til Overdue:": 12, "Surname:": "Bloggs", "Times Overdue:": 1}]]

N.B. Not all aspects of the project are fully completed but this is my biggest problem I have not been able to solve.

Thank you very much in advance for you help.
Cut-down-version.py
0
Hello,
 
I am adding four different GIS datasets as grid/raster files: RasterA + RasterB + RasterC + RasterD; and am interested in expressing uncertainty in the results based on uncertainties in each of the input grids.
 
All grids are in the same units and all values are positive in the range of zero to about 200.
 
The values in each grid have different ranges of uncertainty, such as:
+/- 6 for RasterA
+/- 10 for RasterB
+/- 12 for RasterC
+/- 5 for RasterD
 
I would like to run a monte carlo style analysis whereby the grids are added to together multiple times (e.g. n = 1000) based on values for each grid cell that are randomly selected from within the uncertainty range around each input grid cell value.
 
It seems like a good problem for a solution using python/numpy/scipy.

Does anyone know of (or can develop) code to implement this?

Thanks in advance.
0
Hello

How can I print the output of an element to a text file using xml.etree.elementtree from https://docs.python.org/2/library/xml.etree.elementtree.html

Please look at the first FOR loop section. In the example below I want to print or pipe child.tag and child.attrib to separate files.

>>> for child in root:
...     print child.tag, child.attrib

Open in new window

0
does any one have simple code for testing  DOS for python ?
0
good day, I am testing serial port communciation on raspberry pi 3 interface with SIM 900 module. The code are attached with error message. Thanks

import serial
import os, time
 
# Enable Serial Communication
port = serial.Serial("/dev/ttyS0", baudrate=38400, timeout=1)
 
# Transmitting AT Commands to the Modem
# '\r\n' indicates the Enter key
 
port.write('AT'+'\r\n')
rcv = port.read(10)
print (rcv)

>>> 
======================== RESTART: /home/pi/SIM900.py ========================
Traceback (most recent call last):
  File "/home/pi/SIM900.py", line 1, in <module>
    import serial
  File "/home/pi/serial.py", line 5, in <module>
    port = serial.Serial("/dev/ttyS0", baudrate=38400, timeout=1)
AttributeError: module 'serial' has no attribute 'Serial'
>>>
0
I have been building a Python script with several interactive menus to run powershell commands. If someone selects the wrong menu item (say, stop a service instead of start a service), is there a way to cancel and return to the menu without cancelling out of the entire script? I have a computername = input ("Which Pc would you like to start the service on?") and a service = input ("Which service would you like to start?") in the script - If I could add in something like "C" to cancel out of inputting and continuing with the script, that would be great.
0
**GOAL:**
I would like to get my script total execution time down from 4 minutes to less than 30 secs. I have a large 1d array (3000000+) of distances with many duplicate distances. I am trying to write the swiftest function that returns all distances that appear n times in the array. I have written a function in numpy but there is a bottleneck at one line in the code. Swift performance is an issue because the calculations are done in a for loop for 2400 different large distance arrays.


   
 import numpy as np
    for t in range(0, 2400):
     a=np.random.randint(1000000000, 5000000000, 3000000)
     b=np.bincount(a,minlength=np.size(a))
     c=np.where(b == 3)[0] #SLOW STATEMENT/BOTTLENECK
     return c

Open in new window


**EXPECTED RESULTS:**
Given a 1d array of distances [2000000000,3005670000,2000000000,12345667,4000789000,12345687,12345667,2000000000,12345667]
I would expect back an array of [2000000000,12345667] when queried to return an array of all distances that appear 3 times in the main array.

What should I do?
0
Free Tool: Port Scanner
LVL 11
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

How to install SMTP and MSQLDB package in Python 3

I already use pip command but it says error :
pip install smtplib
Collecting smtplib
  Could not find a version that satisfies the requirement smtplib (from versions: )
No matching distribution found for smtplib

C:\Users\133586>easy_install smtplib
Searching for smtplib
Reading https://pypi.python.org/simple/smtplib/
Couldn't find index page for 'smtplib' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading https://pypi.python.org/simple/
No local packages or working download links found for smtplib
error: Could not find suitable distribution for Requirement.parse('smtplib')

...

Please help
0
i got this error while running my script  
 requests.exceptions.ConnectionError

Open in new window

, now i want create except for it  , is this way is true ?

except (BaseException, Exception, AttributeError, requests.exceptions.ConnectionError, ConnectionError) as err:
                    pass

Open in new window

0
I am learning the BigO notation and I have a question which is related to homework:

def __str__(self):
return str(self.list)

Open in new window


If I cast an object, does Python iterate over it?
That is, would I have a O(n) here or is it just O(1)?

Thanks for your help
0
i want know how do it ? is it possible write it to file and i look at it later ?
0
Can do the following command in Python

 awk '{print $1,$2}' | cut -f1 -d'.' " "| sed '1d' | sed /^-/d | sed '/_/!d' | sed 's/ /:/g' | uniq
0
Hi
Installing Pycharm w/ a Youtube vid suggests I'll need 3.6.2 interpreter. I couldn't find an automatic update in the sections.

Is that necessary? It seems to be so. in the vid   ( here )

In preferences, there is no Pygame in the easy install type list - should it be there?
Thanks
0
I'm working on a project for my bioinformatics course for which there is no reference guide due to its De novo approach. Whenever I run my code of the 3732 test sequences it is supposed to go through, the program runs through about 20-25 sequences before quitting and outputting this error:

/anaconda3/lib/python3.6/site-packages/Bio/Seq.py:152: BiopythonWarning: Biopython Seq objects now use string comparison. Older versions of Biopython used object comparison. During this transition, please use hash(id(my_seq)) or my_dict[id(my_seq)] if you want the old behaviour, or use hash(str(my_seq)) or my_dict[str(my_seq)] for the new string hashing behaviour.
  "the new string hashing behaviour.", BiopythonWarning)

I have tried everything I could think of to fix this. Essentially, once this code figures out all the palindromes in the test sequences while making sure to remove duplicates, it then sorts the list and goes out and searches for those palindromes in specified genes. It is then supposed to output a hit table for each palindrome and sequence if that palindrome exists and where it exists.
I am very new to python so any help would be appreciated. my code is as follows:

from Bio import Entrez, SeqIO
from Bio.Seq import Seq
import time
from nbconvert.preprocessors import ExecutePreprocessor
ep = ExecutePreprocessor(timeout=6000, kernel_name='python3')
def reverse_complement(string):
    seq_dict = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'}
    return 

Open in new window

0
Hi
I need to be able to install Pygame in Pycharm (4.0.5), but it seems Pycharm has come out with newer versions.
Pygame is no longer in 2.9, but 3.3

One example on Youtube suggested I re- install Python? Will this all automatically link up in pyCharm?
Last time it tried, the console installation instructions didn't seem to affect the behavior in pycharm.

What is the best way to get it working in Pycharm?
Thanks
0
Good day, I am newbie in python programming. Can get some information on treading (multi processing). I am doing project with raspberry pi 3 to monitor the following sensor: -
1. temperature
2.humidity
3. CO
At same time using 3g USB dongle to push data to cloud. My critical issue is 3g USB dongle, need to monitor that everytime.
0
[Webinar] Cloud and Mobile-First Strategy
LVL 11
[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

What are the risks associated with installing the above on a PC/laptop for doing data analysis?

Are the following mitigating measures valid?

a) apply regular patches for R & Python to fix vulnerabilities: as they're opensource, are the patches
               released quite timely/regularly.  I tend to think opensource is lacking in this area
b) if patches are not applied regularly, can we isolate the PCs such that they have no Internet
    access & no email clients to mitigate?  I tend to think most breaches result from Internet,
    emails activities & infected USB devices
c) is it common that emails contain malicious python attachments?
d) Where can we subscribe to  vulnerabilities news/updates for these 2 softwares?
e) Python and Ruby are dynamic platforms (free ware) , have to tighten the web application security if it’s being used for web applications, Python has flexible features that make it particularly useful for hacking?  
    Can we harden these & where to obtain such a hardening guide?
0
I'm looking to make a specific graph layout from a specific **format** of **Python** data, but where the **data may be text, string, or another Python object**.

It has to be able to do it on the **fly**, and make visual formatting decisions based on whether the data is "the same" (regardless of numerically, text or another Python object).

It doesn't matter if Excel is used to make the image (*.xls or .csv) or ```matplotlib```or anything else.

***The coloring in the cells*** is based on whether the items within ```{1:"A", 2:"A"}```are **equivalent** (not the same object). **Green** for ```True```, **red** for ```False```. For example: ```"A" == "A"``` (as in the preceding sentences), or ```(10/5) == (20/10)```, or ```["A", 1, <test object at 0x1052c9b70>] == ["A", 1, <test object at 0x1052c9b70>]``` would all be green.

The text that appears in the cells is just the \__str__ representation of the object.

EDIT: I'm not so much looking for someone to do the work for me, but a recommendation of which tool (```XLS```, ```matplotlib```, ```whathaveyou```) would be best suited - and maybe a link to a tutorial on how to do some of those more difficult features (like the cell coloring).

I.e. ...
   
    {
        1000:{
              "Sample1":{1:"A", 2:"A"},
              "Sample2":{1:"A", 2:"A"},
              "Sample3":{1:"A", 2:"A"},
              },

        1001:{
              "Sample1":{1:"A", 2:"A"},
              "Sample2":{1:"A", 2:"A"},…
0
Hi

All the Python learning pages say that printf'ing must be done:
here

for x in range(0, 3):
    print "We're on time %d" % (x)


But, in pyCharm, I have to use brackets:

print("age = ",24)

for x in range(0,5) :
    print(x)
    print("squared=",x*x,'_')

Why does pycharm require this break from examples?
It will seem lame to try and explain that to a student.

Thanks
0
Currently built a website that contain field for user to input number in time format.user input This input goes into mysql database when button is clicked. database
I'm currently looking into how I can use this value insert by user and use it as timer to execute a python script, the python script is motor.py which will spin the motor, how can I make it work similar to cronjob. I have tried many different crontab web interface but they do not work as I would like it too. Is there any ways of achieving this? Thank You
0
else:
                try:
                    response_data = (r.json())['message']
                except:
                    # sleep for some seconds to let recover
                    time.sleep(3)
                    return True

Open in new window


what is exactly message mean ?
0
I had this question after viewing Inserting dir/filename to mysql from Python.
I retrieve all the paths of the images from the database but now i am stuck to pass the paths to Image.open() to open the images and show them because the query result for single image is:D:\\Final\\Sample Pictures\\Lighthouse.jpg
0

Python

Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in other languages. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive set of standard libraries, including NumPy, SciPy, Django, PyQuery, and PyLibrary.