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

when select employee= administrator it work correctly but when select apart from administrator thenn i does not work. i use the following code:
@api.onchange('number_of_days_temp')
      def _half_day_allowed(self):

            date_from = self.date_from
            date_to = self.date_to
            current = self.env['hr_leave_rules.leave_rules'].search([(
                        'holiday_status_id','=',self.holiday_status_id.id)])
            if current.half_day_allowed == 'no':
                  self.number_of_days_temp = ceil(self._get_number_of_days(
                        date_from, date_to, self.employee_id.id))
                  return {'value':{},'warning': {
                        'title': 'Please note :',
                        'message': 'You are  not allowed to take half day leave !'
                        }}
Screenshot-from-2017-08-14-17-33-01.png
0
Enroll in August's Course of the Month
LVL 9
Enroll in August's Course of the Month

August's CompTIA IT Fundamentals course includes 19 hours of basic computer principle modules and prepares you for the certification exam. It's free for Premium Members, Team Accounts, and Qualified Experts!

USB GPS Detection on Raspberry PI

I have some python code that scans WIFI packets and in my receiver code I have an instance of a GPSPoller class.

The issue I am having is that withing the gps library gpscommon.read() blocks when there is no GPS dongle connected to the Pi.

I couldn't seem to find an elegant way to check to see if gpds has any devices added to its device pool so I could skip my code that starts polling gpsd for position data.

I don't want to write code to check for /dev/ttyUSB0 as that does not seem like a very elegant solution.

Can anyone provide advice?
0
 

Author Comment

by:spencerturbine
lsusb would list my device but then I would have to write software that looks for the specific device. If I swapped out the receiver for a different kind I would have to change the code to take that into account.

I hope there is a better way to do it that lsusb.
0
 

Expert Comment

by:Mark Wieder
Yeah, if you want the code to be more generic (how often do you intend to swap out a different gps dongle?) then lsusb probably won't help here. You might try setting up a socket connection to port 2947 and trap the error, but you'll have to do this before instantiating the gps class because the class initializer does that as well.
0
pip install twilio
works perfectly on a Pi2.   Just bought a new Pi3 with the latest NOOB.  
same version of python (2.7.9), same version of pip (1.5.6).  I keep getting the error:

TypeError: __str__ returned non-string (type Error)

Googling around, I checked and verified that
- no network issue, Chromium connects to https://pypi.python.org/simple/twilio/
- my date/time on the computer is correct
- some talk about --trusted-host=http://pypi.python.org/simple/ but that parameter is not valid on pip
- some talk about creating an /etc/pip.conf file and adding trusted-host=pypi.python.org but that makes no difference (assuming pip every reads that file...)

My guess is that it has something to do with the SSL certificates... but I have no idea how to solve it.  
sudo apt-get install libssl-dev did not help

Thoughts?
pip.log
0
Hi: Don't you just hate banks?
We have changed bank and I download all the data  for analysis.  Our new bank offers only csv format. No problem...EXCEPT that for direct debits and standing orders the text field has a comma inserted! It looks to me that the comma is inserted just prior to the word MANDATE.
Dopes anybody know how to write something in python that deletes (or replaces with a semi colon) a comma that appears just before the word MANDATE in a csv file?
Here is a snippet of the text field:
"DIRECT DEBIT PAYMENT TO XXXX PENSION REF 09999999991, MANDATE NO 9999"
See that stupid comma in the middle?
The text before the comma changes every time.

Thanks!
0
from flask.ext.api import FlaskAPI
from flask import request, current_app, abort
from functools import wraps

app = FlaskAPI(__name__)
app.config.from_object('settings')

def token_auth(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if request.headers.get('X-API-TOKEN', None) != current_app.config['API_TOKEN']:
            abort(403)
        return f(*args, **kwargs)
    return decorated_function

@app.route('/predict', methods=['POST'])
@token_auth
def predict():
    from big_model import model
    item = request.data.get('item')
    total_predictions = request.data.get('num', 100)
    if not item:
        return []
    return model.predict(str(item), total_predictions)


@app.route('/train')
@token_auth
def train():
    from big_model import model
    data_url = request.data.get('data-url', None)
    model.train(data_url)
    return {"message": "Success!", "success": 1}

if __name__ == '__main__':
    app.debug = True
    app.run()
0
[('01', ['name abc', 'age 32', 'address addr123']), ('02', ['name def', 'age 22', 'address addr456'])]

   I want this list to be written in CSV file in below format. Some time list may contain more values.So no hard codings.
    Expected output in csv in table format
   
    id    name   age   address
    01   abc     32     addr123
    02   def     22     addr456
0
Are there any instructors like
simon allardice
from lynda.com, plursight.com
who explain computer science concepts without using a scripting language.

Just verbally.

Please add (or subtract) zones
0
I installed Visual Studio Code & I would like to program in python when I go to compile my code I get these error messages

errorI am confused what to add.
When it goes to that point, I do not know what to put in.
Can someone help.

I debug my code, and press run and I get those 2 error messages, but the code successfully runs.
0
I have below python script
response = ''
ascii_map = 'abcdefghijklmnopqrstuvwxyz012345'
for j in range(7):
    response += ascii_map[(int('3996146930') >> (5*j)) & 31]
print response

Open in new window

I give output as below
shxadxd

Open in new window

0
For a school project, I've been tasked with setting up an attendance-taking program. I've done some research and have come to a conclusion: I need some help.

I've got a bit of a plan but I'm not sure if it will work since I've got next to no experience in this type of thing. I want to use a barcode scanner to scan a specific barcode for a student and then input that into some sort of python program and log attendance.

I'm confident I can write the python code but I don't know how to connect a barcode scanner to the IDE, I'm also not sure which IDE to use.  I have considered trying to use Arduino connected to a webcam (or something similar).

Nevertheless, I need some expert advice, so any input will be met with extreme gratitude since I've been stuck at this point for weeks.
Thanks in advance.
0
Free Tool: Port Scanner
LVL 9
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.

Hello,

I have a OID as below
30.118.115.58.115.105.110.103.108.101.58.116.101.115.116.45.109.97.99.104.105.110.101.58.104.116.116.112.64.56.48

Open in new window


I would like to know how can I convert it to it's name using python? I do not want to make any network or localhost call.

this OID is mapped to one of the VSERVER's Name in NetScaler.
0
So long story short I think it MAY have something to do with my shebang in my python. I know on our server we have a few different versions of Python and I installed my modules (paramiko and pysftp) in the correct place I believe. Honestly I have researched and am having trouble understanding how exactly the shebang works and knowing what interpreter it is pulling from or why the cron job is failing for that script (is there a log file perhaps to help determine the cause?)

Cron listing:
* * * * * /usr/local/mlb_cdt_download_newv2.py > /dev/null 2>&1
(Yes for testing purposes I am trying to have it run every minute just to see if it runs)

Script:
#!/usr/local/lib/python2.7
import os
import pysftp
import os.path
import paramiko

HOST=""
USER=""
PASSWORD=""
SUFFIX_TO_FETCH__AND_DELETE=".csv"
DESTINATION_PATH="/mnt/sas/ftp_mlb"

srv = pysftp.Connection(host=HOST, username=USER, password=PASSWORD)

def do_nothing(fname):
        return  " "

def fetch_and_remove(fname):
    if not fname.endswith(SUFFIX_TO_FETCH__AND_DELETE):
        return # skip files with wrong suffix
    dst_fname = os.path.join(DESTINATION_PATH, fname)
    dst_dirname = os.path.dirname(dst_fname)
    if os.path.isfile(dst_fname):
        return " "
    else:
        srv.get(fname, dst_fname)
        srv.remove(fname)

srv.walktree('.', fetch_and_remove, do_nothing, do_nothing)

srv.close()

Open in new window


For the record, running this script from the commando line works instantly and perfectly. But when trying to automate it through the cron I have no luck.

Any help trying to understand which interpreter my cron is trying to use and the location of such would be greatly appreciated.
0
Hi all!

I wrote a little python code to continously check if the user is active and, if not, lock the computer screen.

This works well.

I've then decided to use a small systray icon to enable / disable the endless loop that is checking for user activity but it seems like showing the systray icon is an endless loop itself.

Therefore if I run my current code:

# Instructions
#
# Pair your phone to your pc's bluetooth as first step
#
# Then scroll down and customize the locker's parameters before running
# the script. Simply search for "Customize me" to make your life easier :)
#
# 1st parameter is your phone name (in my case 'G4') and 2nd is maximum
# number of seconds that the user is not active before the screen
# is autolocked
#

# Importing classes
from autolocker_class import *
from systray_icon_class import *

# Customize me!
locker = ScreenLock('G4', 10)

# Minimal self test. You'll need a bunch of ICO files in the current working
# directory in order for this to work...
if __name__ == '__main__':
    hover_text = "IPAutolocker"
    bluetooth_icon = 'Checked.ico'
    def autolocker_on(sysTrayIcon):
        locker.is_autolocker_enabled = True
        print "Autolocker enabled"
    def autolocker_off(sysTrayIcon):
        locker.is_autolocker_enabled = False
        print "Autolocker disabled"
    def bluetooth_on(sysTrayIcon):
        is_bluetooth_on = True
        print "Bluetooth enabled"
    def bluetooth_off(sysTrayIcon):
        is_bluetooth_on = 

Open in new window

0
Hello Python Individuals,

I need to connect to the Lotus Notes and do some operations (Send/Receive mail with Attachments).
However, I am not able to get past even the ‘Dispatch’ step:

import os, sys, stat, shutil
import os.path
import string
from configparser import SafeConfigParser
import tempfile
import logging
import getpass
import time
from win32com.client import makepy
from win32com.client import Dispatch
import win32com.client
import pywintypes
import smtplib
import csv # imports the csv module
makepy.GenerateFromTypeLibSpec('Lotus Domino Objects')
makepy.GenerateFromTypeLibSpec('IBM Notes Automation Classes')
Session = win32com.client.Dispatch('Lotus.NotesSession')

Open in new window


This rises an exception (Traceback)
File ..\Anaconda3\Lib\site-packages\win32com\client\dynamic.py in _GetGoodDispatch
IDispatch = pythoncom.connect(IDispatch)
Pywinttypes.com.error: (-2147221021, ‘Operation unavailable’, None, None)

During handling of above exception, another exception occurred:

Traceback
File My file
Session = win32com.client.Dispatch('Lotus.NotesSession')
File ..\Anaconda3\Lib\site-packages\win32com\client\__init__.py in Dispatch
  dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
File ..\Anaconda3\Lib\site-packages\win32com\client\dynamic.py in _GetGoodDispatchAndUserName
      return (_GetGoodDispatch(IDispatch, clsctx), userName)
File ..\Anaconda3\Lib\site-packages\win32com\client\dynamic.py in  _GetGoodDispatch
      IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
Pywinttypes.com.error: (-2147221164, ‘Class not registered’, None, None)


Thanks in advance for any ideas or aid.

Doug
0
Hi,

I am expected to propose the EDIFACT solution for a company that starts from scratch (regarding EDIFACT).

Communication via OFTP2 ready to be used (on Linux)


The only thing that is already decided and ready to be used is the OFTP2 communication (on Linux machine, OS4X by c-works if it matters, ODETTE ID assigned).

This way, message splitting or even parsing can use UNIX-based tools. Anyway...

MS SQL and procession on Microsoft Server


... the original message (before parsing) will also be saved on Microsoft based server (as a blob in the SQL table).

The database and the Enterprise applications is running on a different computer -- Microsoft Windows Server, MS SQL Server.

First messages to be processed


The Delivery schedule message (DELFOR) and Despatch advice message (DESADV) are the first one to be received. I am aware of versions of the EDIFACT messages (about two releases each year).

I am aware of X12 being the predecessor of EDIFACT, of the other standards like Tradacom, VDA, ... and the consequences of having tools for transformation of the messages. However, the decision was made to use the pure UN/EDIFACT only.

Differences based on a partner decisions


I am partly aware of (future) problems with _the same kind of message from a different …
0
-------my code-----

import xml.dom
import xml.dom.minidom
doc = xml.dom.minidom.parseString('''
<root>
   <person id="01">
      <name> abc</name>
      <age>32</age>
      <address>addr123</address>
      <siblings>
        <name></name>
        <name></name>
      </siblings>
   </person>
   <person id="02">
      <name> def</name>
      <age>44</age>
      <address>addr456</address>
      <siblings>
        <name></name>
        <name></name>
        <name></name>
      </siblings>
   </person>
</root>

''')


def innerHtml(root):
    text = ''
    nodes = [ root ]
    while not nodes==[]:
        node = nodes.pop()
        if node.nodeType==xml.dom.Node.TEXT_NODE:
            text += node.wholeText
        else:
            nodes.extend(node.childNodes)
    return text

for statusNode in doc.getElementsByTagName('person'):
    for childNode in statusNode.childNodes:
        if childNode.nodeType==xml.dom.Node.ELEMENT_NODE:
            print("{}={}".format(childNode.nodeName, innerHtml(childNode)))

-------------output i got is------------------
name= abc
age=32
address=addr123
siblings=
                     
name= def
age=44
address=addr456
siblings=

---------but expected output should be in tableformat-----
i need to get the person id attribute also...pls answer

person id         name         age      address
01                abc          32      addr123
02                def          44       addr456
0
Basically I am an Electrical Engineer. I am doing estimation & Design.

I am repeating the same work again and again. I decide to automate my boring works

From google i found Python to make the script.

Since I need output in .xls & .dxf i selected xlxwriter and dxf write module.

To create user interface i selected Pyqt..

But I got stuck how to convert this all files as a single file. So i can distribute the same company with commercial befit.

Can you please advice the next step..
0
Does anybody know of an implementation in C#, python, or JAVA of the NEAR function in SQL Server?

Search for Words Close to Another Word with NEAR
0
Hi,

I am using Jupiter to write a read csv line.

So far,I wrote>>

(1)      import pandas as pd
(2)      pd.read_csv('C:/Users/USER1/Documents/Exports/ItemStatus.csv', sep=',')

but its giving me error. See text file. What I need to change to make this work…
python-read-error.txt
0
On Demand Webinar: Networking for the Cloud Era
LVL 9
On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

input xml can be any. It is dynamic file. so there is no pre determined tags. it should be created depending on the input xml file.

And i need the code for following requierments.

Parse XML file to create a tree of objects
   - create an object for each xml element
   -object mainly contains xml element name, value, attributes, list of sub elements where each member in the list is another xml element object
   - a function to create object tree
  - a function to iterate
0
I want to import a huge number of very small text files (content is 1 line per file) parse the line and convert it to another text file using delphi. Using the simplest assign(f) etc approach will take several weeks to execute. The bottleneck might probably be the opening/closing of each file. Is there any other way of doing this a lot faster?  maybe using another scripting language? which one?
0
how to calculate the time difference between date-time have single field only in python. it is like :-i have one row and column which field name is puch time here is the list of date-time 07/13/2017 18:41:24,       07/13/2017 18:57:31, 07/13/2017 17:29:27 now calculate time between 07/13/2017 18:41:24,       07/13/2017 18:57:31 in a and 07/13/2017 18:57:31, 07/13/2017 17:29:27  in b.
0
Below code works perfectly now I want to provide ObjectType(ObjectIdentity()) as a variable which will be constructed as a list of OID

from pysnmp.hlapi import *

g = getCmd(SnmpEngine(),
           CommunityData('myPa$$word'),
           UdpTransportTarget(('loadbalancer-staging.com', 161)),
           ContextData(),
           ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0')),
		   ObjectType(ObjectIdentity('1.3.6.1.2.1.1.6.0')))

for x in next(g)[3]:
    print x

Open in new window

I have a list of OID as below and somehow I want to put that in getCmd method as a variable
mibs = ['1.3.6.1.2.1.1.1.0', '1.3.6.1.2.1.1.6.0']

Open in new window

so basically I have a dynamic list of OID (minimum 3 and maximum 9 ) and I want to supple them as a variable in above code so that in ONE SNMP call I will get output of all the OIDs. Is there a way I can do it? Thanks!
0
i want to use winpcap lib in python, but prompt :

Traceback (most recent call last):
  File "D:\1_AutoTest\7_Pyhon\1_Code\Winpcap\src\winpcapy.py", line 12, in <module>
    import sysloglib
ImportError: No module named sysloglib
0
I want to be data analyst.
but i don't know, what should i learn first?

what are basic capabilities  should i have ?
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.