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

Using python to change number formats in Excel (Openpyxl)


The script is reading excel, to add an additional three zeros, which it does,
it also updates cell format to a custom value, the change does not reflect to the cell, as the cell does not identify itself as a number.
How do I update the cell to reflect it is an [int] format?

I've attached a copy of the xlsx file pre script change.  

from bs4 import BeautifulSoup
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.styles import Color, PatternFill, Font, Border
from openpyxl.styles import colors
from openpyxl.cell import Cell
from termcolor import colored
import colorama
from colorama import Fore, Style
import os


wb = Workbook()
xlfile = "Test.xlsx"
wb = load_workbook(xlfile)
dash = "-"

for xws in wb.sheetnames:
	worksheet = wb[xws]

	tuple(worksheet['B3':'E5'])
	for rowOfCellObjects in worksheet['B3':'E5']:
		for cellObj in rowOfCellObjects:
			print(cellObj.coordinate, cellObj.value)
		print('--- END OF ROW BEFORE---')

for xws in wb.sheetnames:
	worksheet = wb[xws]
	tuple(worksheet['B3':'E5'])
	for rowOfCellObjects in worksheet['B3':'E5']:
		for cellObj in rowOfCellObjects:
			cellValue = cellObj.value
			if cellValue != dash:
				x = cellValue
				print(Fore.RED + x)
				y = str(x) + ",000"
				print(Fore.WHITE + y)
				#z = (format(int(y),","))
				#print(Fore.GREEN + z)
				#cellObj = y
				#print(Fore.WHITE + cellObj)
				cellObj.value = y
				

Open in new window

0
OWASP: Threats Fundamentals
LVL 13
OWASP: Threats Fundamentals

Learn the top ten threats that are present in modern web-application development and how to protect your business from them.

Hi I'm seeking help to create an if statement in python

Three problems

1. if the cell in column B contains a dash '-', and the adjacent cells in columns 'C', 'D', 'E', have values then, I wanted to replace the dash with an average from the three cells.

Example from picture.
Row 2 Column B contains a dash, but data is present in Columns C, D and E


2. If the cell is populated with a number and not a formula then I wanted to append the cell, and add an additional three zeros

Example from picture.
 Row 2 Column B now contains a formula, but data is present in Columns C, D and E
 The number in Row 2, Column C is 42,746,000. I would like to update the value with an extra three zeros e.g. ',000'.
 This will update the value in Row 2, Column C  is 42,746,000,000

3. In Columns B, C, D and E, Rows 3, 4 and 5. I wanted to format the number according to either a positive or negative number
 If a positive number then the cell format is updated to [<999950] 0.0,"K";[<999950000]0.0,,"M";0.0,,,"B"
 If a negative number then the cell format is updated to [>-999950]0.0,"K";[>-999950000]0.0,,"M";0.0,,,"B"


from openpyxl import Workbook
from openpyxl.styles import Color, PatternFill, Font, Border
from openpyxl.styles import colors
from openpyxl.cell import Cell
import os

xlfile = "/Users/User1/Documents/NewFolder/Test.xlsx"
if os.path.exists(xlfile):
    os.remove(xlfile)

wb = Workbook()
filepath = "Test.xlsx"

Open in new window

Screen-Shot-2019-04-19-at-12.13.14.png
0
Hi Experts,

I have the following details when I debug the django application.

(Pdb) Contributor.objects.all()
<QuerySet [<Contributor: Contributor object>, <Contributor: Contributor object>, <Contributor: Contributor object>, <Contributor: Contributor object>, <Contributor: Contributor object>, <Contributor: Contributor object>, <Contributor: Contributor object>, <Contributor: Contributor object>, <Contributor: Contributor object>, <Contributor: Contributor object>, <Contributor: Contributor object>, <Contributor: Contributor object>, <Contributor: Contributor object>, <Contributor: Contributor object>, <Contributor: Contributor object>, <Contributor: Contributor object>, <Contributor: Contributor object>, <Contributor: Contributor object>, <Contributor: Contributor object>, <Contributor: Contributor object>, '...(remaining elements truncated)...']>

Open in new window


I am not able to see the values of the contributor values.  Please correct me where I am making wrong.

Thanks
0
ValueError: "port" must be None or a string, not <type 'int'>

Open in new window


keep getting this error when I run my python 2.7  code to find and connect with my port which I have a gps tracker connected ... I'm using 2.7 ... I figured once I get this working I can translate it into python3..

this is the error .. as I try is tell my laptop what port my GPS trackers in connected to
  File "C:\Users\clayr\Anaconda3\envs\maps.py\lib\site-packages\serial\serialutil.py", line 264, in port
    raise ValueError('"port" must be None or a string, not {}'.format(type(port)))
ValueError: "port" must be None or a string, not <type 'int'>

Open in new window


this code I am starting with
import serial

#####Global Variables######################################
#be sure to declare the variable as 'global var' in the fxn
ser = 0

#####FUNCTIONS#############################################
#initialize serial connection 
def init_serial():
    COMNUM = 3 #set you COM port # here
    global ser #must be declared in each fxn used
    ser = serial.Serial()
    ser.baudrate = 9600
    ser.port = COMNUM - 1 #starts at 0, so subtract 1
    #ser.port = '/dev/ttyUSB0' #uncomment for linux

    #you must specify a timeout (in seconds) so that the
    # serial port doesn't hang
    ser.timeout = 1
    ser.open() #open the serial port

    # print port open or closed
    if ser.isOpen():
        print 'Open: ' + ser.portstr
#####SETUP################################################
#this is a 

Open in new window

0
Hello,
The goal is to get the data into a sql table. I just need help parsing the text file into 2 columns, multi row.  I don't care how they are delineated I can figure out the import side.
 I have written python, t-sql and powershell so ideally the solution would use one of those tools.

The files are not large and are text files.  Assume I'll need to run process once a month but not consistently.
Data between {} is one record, 2 columns.  No cr at row end.

There can be any number of filenames in the text file with 0 to 30 pieces of information so empty [] is a possibility.  
I want each comma separated value in information to be a new row.  i want all {'': to be removed

example:Input  shows 2 records
{'filename':'colors','information':[red,blue,yellow]}, {'filename':'colors','information':[pink,orange]}, etc.

required output  for first one
filename    Information
colors        red
colors        blue
colors        yellow
0
Parsing nested json. I am looking for help to parsing the nested json elements.

I attached a json file I need to output all of the data fields, however some are nested and I don't know the HOW-TO output the nested values. Can you help ?

I also include the start a python script
parser.py
file.json
0
I was recently asked to prepare a bunch of CSV files for import into ArcGIS.

I managed to do what was asked using VBA/ADO but it took 2 days to complete the task.

Wonder if anyone had any ideas on how I could have speeded up the process?

Can't post the code I used right now but I've attached a small example file.
0
I am trying to track a player and object in the same frame/video/camera...ultimately camera only ... using KCF for now to track the player and work ok ...unless the player leaves the frame completely ...long term that will not be a problem see code below

import cv2
import sys
import imutils
 
if __name__ == '__main__' :
 
    # Set up tracker.
    # Instead of MIL, you can also use
    
	
    
   
    tracker_types = ['KSF ']
    tracker_type = tracker_types[0]
    tracker = cv2.TrackerKCF_create()
   
 
    # Read video
    video = cv2.VideoCapture("tennisVid_Trim_Trim.mp4")
 
    # Exit if video not opened.
    if not video.isOpened():
        print ("Could not open video")
        sys.exit()
 
    # Read first frame.
    
    ok, frame = video.read()
    frame = imutils.resize(frame, width= 720)
	#frame = imutils.resize(frame, height= 720)
    if not ok:
        print ('Cannot read video file')
        sys.exit()
     
    # Define an initial bounding box
    bbox = (320, 230, 230, 320)
 
    # Uncomment the line below to select a different bounding box
    #bbox = cv2.selectROI(frame, False)
 
    # Initialize tracker with first frame and bounding box
    ok = tracker.init(frame, bbox)
 
    while True:
        # Read a new frame
        ok, frame = video.read()
        if not ok:
            break
         
        # Start timer
        timer = cv2.getTickCount()
 
        # Update tracker
        ok, bbox = tracker.update(frame)
 
        # Calculate Frames 

Open in new window

0
I am new to Python. I have an python project, I need to debug. The program was developed and run with an older version of python (2.7 or earlier) .
I have python 3.7 installed in my windows 7.
I want to install python 2 alongside python 3 and debug the program using python 2.

How can i achieve this?
is virtual env used for this?
0
HI

I've asked other questions about Javascript,
but I saw that one advice page said that I must get a special eclipse IDE for web development.... but I already have eclipse Kepler. Is that not enough?

...down at Getting Eclipse IDE for JavaScript and Web Developers

here

That's quite a surprise...
Thanks
0
CompTIA Security+
LVL 13
CompTIA Security+

Learn the essential functions of CompTIA Security+, which establishes the core knowledge required of any cybersecurity role and leads professionals into intermediate-level cybersecurity jobs.

Hi ..
I need to run some commands on a remote machine using ssh . What is the best way to automate this in Python?
I need to log in with a (known) password to the remote machine, so I can't just use ssh user@remotehost.
I'm wondering if there's a built-in module in python I could use or I need to install one.
If you have a sample script is highly appreciated.

Thank you for your help.
0
Hi
I'm curious..

I have made a few network game projects w help of sporadic legends on this site.

Now, a Python network game.

It seems Pygame can do adequate 2D gaming, side scroller / maze etc
How about a networking game client?
It looks like all the usual abilities are available.
I might make my server in Java, but my game clients in Python?

A plan?
Thanks
0
i spent 6 hours yesterday trying to figure out sorting in python.


i get that:
for k in sorted(djTime.items(), key=lambda x(-x[1], x[0])):
should take every instance of k in djTime and perform something on something else.
i've understood the same of
for line in sorted(djTime):
should take a logfile previously broken into lines by the rstrip('\n') method and see the items as lines
i understand *line* or *k* in any circumstance can be any variable (i.e.) for JohnDoe in sorted(djTime):

i don't understand how or what python is looking for to differentiate between items either in a list or in a dictionary

i believe if you say:
for k, v in sorted(djTime.items())
...and this is a tuple, the k is representative of the key, and the v is representative of the value? but i'm not really clear

do you have to specify 2 variables/objects to sort a tuple? is a single non nested dictionary always a tuple? (i.e. for k, v in sorted(djTime)
do you have to use .items? what if i want to sort by key? can i sort like this:  for k, v in sorted(djItems.keys())  can i do it by values? : for k, v in sorted(djItems.values()

as for the remainder of the command up there :     x(-x[1], x[0])
i have no idea what the first x is, but the second seems to me to denote the position in the tuple? where counting begins with 0 so x[1] is the second item and x[0] is the first item? kinda backwards?? and the - negative in front of the main -x[1] mean sort from bottom to top



what i'm …
0
I am trying to use MatLibPlot to plot the x,y cordinates .... using opencv I have collected x,y coordinates of an object ... saved the coordinates in a sqlite db ... Connected to the db abd retrieved the coordinates ... I have placed a sample of my code below showing how I retrieved the coordinate ... I also tried retieving just the x -coor the retrieve the y- coordinates...
 coordinat_y [('289', '98'), ('304', '105'), ('289', '174'), ('921', '111'), ('786', '116'), ('772', '129'), ('740', '139'), ('633', '148'), ('469', '311'), ('466', '304'), ('443', '137'), ('439', '200'), ('444', '339'), ('433', '225'), ('429', '185'), ('424', '166'), ('423', '191'), ('424', '281'), ('421', '329'), ('409', '250'), ('397', '218'), ('388', '245'), ('383', '348'), ('366', '323'), ('347', '275'), ('325', '321'), ('304', '389'), ('269', '330'), ('237', '357'), ('190', '444'), ('162', '400'), ('77', '490'), ('4', '486'), ('326', '267'), ('271', '107'), ('114', '130'), ('85', '232'), ('46', '328'), ('573', '96'), ('573', '282'), ('559', '148'), ('460', '132'), ('461', '301'), ('442', '218'), ('429', '155'), ('396', '184'), ('392', '269'), ('381', '288'), ('177', '111'), ('167', '208'), ('102', '192'), ('518', '106'), ('563', '256'), ('779', '94'), ('846', '360'), ('875', '169'), ('349', '119'), ('363', '291'), ('361', '234'), ('393', '107'), ('415', '327'), ('418', '182'), ('513', '99'), ('582', '362'), ('613', '146'), ('365', '231'), ('342', '157'), ('269', '95'), ('268', '281'), ('256',

Open in new window

0
using telnetlib in python to configure a router. i'm using cgi to display the python script to a browser.
i'm having trouble troubleshooting the code because cgi just display's an error screen 'internal server error'
so, i really don't see where i'm making the mistake. i can run the python script through the python interpreter, but that's just a hassle.

any suggestions on how to troubleshoot the output? i've tried using
print "Content-type:text/plain\n" as opposed to "Content-type:text/html\n" so as to just display the unformatted output without html formatting, but i still am not seeing where i'm making mistakes.

i know i can cat /var/log/httpd/error_log

but i guess what i'm asking is if anyone can give me some more specifics about what is actually going on.
i understand this:
telnetlib is a module that'll open a socket to the router or switch.  the physical and data link connection we're not going to see, the network layer is addressed by the ip which i have set to a variable and is here
host = "192.168.1.1"
tn = telnetlib.Telnet(HOST, timeout=TIMEOUT)
any further specifics of communication is held within the actual module telnetlib -- socket or transport layer tcp settings.

the server 'sends' the message, encapsulated at what? layer 7 down through layer 2 as the data communications model/osi specifies.. it goes over the wire and over to the client which decapsulates the packet and sends it back up to the telnet application.

i understand i can't see…
0
Hi
My last Disney question concerned their ruthlessness protecting their IP.
This one concerns how seriously they take criticism.
They sued an elderly couple in Florida for $1000,000 for using an image of Mickey on their kindergarten wall.

Obviously, if they were super sensitive about criticism, Youtube would be buried in lawsuits concerning fan mega-criticism of Star Wars.
Would they be as ruthless concerning an inconspicuous site criticizing their Star wars decisions and plans?
My dad said it's just free-speech and they cant do anything (no IP infringement) I won't use any images on the site.
Thanks
1
For my Android Phone I need to be able to quickly turn on or turn off wifi calling.
The Problem:
When a call comes in and the phone is set to my home office to WiFi calling. The quality and sound of the call is better.
However if you need to record the call for business purposes it is difficult to switch the WiFi calling off for the recording app to work.
The apps I have require WiFi to be off in order to record both sides of the call.
Two way calling is not possible as I only hear my side of the call & not my clients.

Is it possible or am I dreaming as I know nothing of apps but learning Python lately. Can a single button (like an app on my phone screen)  be made that performs like a macro.
Which will allow me to touch one button instead of 4 switching screens each time to turn on or off wifi calling?
0
Hi
This simple Pygame window init and fill doesn't work. .
why?
Thanks
import pygame, time
class ChessEngine:
    def __init__(self):

        pygame.init()
        (width, height) = (1300, 600)
        screen = pygame.display.set_mode((width, height))

        screen.fill((0, 0, 0))
        pygame.draw.line(screen, (0, 0, 255), (0, 0), (639, 479))
        pygame.draw.aaline(screen, (0, 0, 255), (639, 0), (0, 479))
        pygame.display.flip()



C = ChessEngine()
time.sleep(30)

Open in new window

0
Hi Experts,

I get the following error for python application.

django.db.utils.OperationalError: FATAL:  remaining connection slots are reserved for non-replication superuser connections

Open in new window


I use dj_database_url.py for configuring database.   I am using Postgres as a database

I had set connection_max_age to 0 in the config. dj_database_url.py

Still, I get this error.

I had checked the entire source code by using grep there is no connection in the source code.

I getting this error from inside docker container.  the database is outside the docker container.

the connection string I use to connect is DATABASE=postgres://test:*****@172.17.0.1/test where 172.17.0.1 is docker gateway.

max_connection =100 in postgresql.conf which located inside /etc/postgresql/9.5/main/

Any help is greatly appreciated.
0
Exploring ASP.NET Core: Fundamentals
LVL 13
Exploring ASP.NET Core: Fundamentals

Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and  exploring the core foundations for app libraries.

Can I create code in Python that will allow me to build a list of records that I can them import into Excel or a database that will do the following.
1. Generate Names or Words for a field. Say the name Robert or the words 205 Walnut Lane
2. Modify existing records in order to change and existing name in a field Say First Name from Mary to Frances? Having it modify randomly each name.
3. Finally. How can I Generate a list of records for a currency field to generate random values set between a range. Say $20,000 to millions of dollars?

Can python do that and if so any ideas on what the code would look like or how to get examples of it. I could play around with.
The goal is to build a fictitious dataset for this excel file or to add to a DB.
0
I started learning Python. I created this simple code which involves concatenating a string and an integer. I just found out that Python doesn't like that. Here is the code I'm typing. Python gave me an error message because of line 4.
     character_name = "John"
     character_age = 35
     print("There was a man named " + character_name + ".")
     print("He was " + character_age + " years old")
     character_name = "Mike"
     print("There was someone else named " + character_name + ".")
     print("But he didn't like being 35")
How do I concatenate a string an in int
0
how to make python pyqt5 qtableview cell like excel conditional formatting? the greater the value, deeper color. lesser the value, lighter color
0
I am interested in learning and writing some Python code. I am looking for a Python compiler which I can install and which is stable and won't interfere with my system. So I also want it to be easy to uninstall if I choose to uninstall it.

I don't mind paying for a python compiler, but would prefer not to spend over $150.00. I currently own Visual Studio 2012, and I don't know if there is just some type of plugin which I can install, which will work with Visual Studio 2012? Can someone help me out, and make some recommendations?
0
Android Phone I need to be able to quickly turn on or turn off wifi calling.
When a call comes in and the phone is set to my home office to WiFi calling. The quality and sound of the call is better. However if you need to record the call for business purposes it is hard to switch the WiFi calling off for the recording app to work. Apparently the ones I have both require WiFi to be off in order to record both sides of the call.
Two way calling is not possible. All you hear is me saying um hum.

Is it possible or am I dreaming as I know nothing of apps but learning Python lately. Can a single button (like an app on my phone screen)  be made that performs like a macro.
Which will allow me to touch one button instead of trying to listen to the client and going in and selecting all those choices. I have hung up on people trying to turn off wifi.
1
My ansible.cfg file points to /etc/ansible/hosts and there is a "group" called [bigip] and it contains two entries: ltm and ltm2, yet when I run a job, where the inventory file is selected that contains two hosts defined (ltm and ltm2), the job only runs against the ltm host.

Ansible Tower - 3.4.1, Ansible - 2.7.6

I can't seem to figure out how to run a job that "hits" both ltm and ltm2. What am I doing wrong?

Thanks,
Steve J
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.