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

I must connect to an old Microsoft Access DB (.mdb) using python pyodbc.

Here's what i've installed on my computer:
  • Microsoft Access 2019, 64-bit
  • Microsoft Visual Studio Code
  • Python 3.7.4, 64-bit
  • I've done the pip install pyodbc

I've tried several connection strings, but none of them work.  I always get an error message
('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
.


Here's some code i've tried:
_ConnStr = 'Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\TEMP\\MYFILE.MDB;Persist Security Info=False;'
_conn = pyodbc.connect(_ConnStr)

Open in new window


I've seen previous post about people using 32 bits of python vs access 64 bits, but it's not my case.  I'm using 64 bits for python and for access.

Thanks you
0
In the below script I like to add if someone guess number less than 0 or more than 20 then it should give message and terminate the program. How I can do that? thanks

import random
n = random.randint(1, 20)
guess = int(input("Enter an integer from 1 to 20: "))
while n != "guess":
    print
    if guess < n:
        print ("guess is low")
        guess = int(input("Enter an integer from 1 to 20: "))
    elif guess > n:
        print ("guess is high")
        guess = int(input("Enter an integer from 1 to 20: "))
    else:
        print ("you guessed it!")
        break
    print
0
Hi Guys

I'm using Python 3.8.1 and below is a script I use

import glob
import numpy as np # for numerical operations
from moviepy.editor import VideoFileClip, concatenate

clip = VideoFileClip (print(glob.glob("*.mp4")))
cut = lambda i: clip.audio.subclip(i,i+1).to_soundarray(fps=22000) 
volume = lambda array: np.sqrt(((1.0*array)**2).mean())
volumes = [volume(cut(i)) for i in range(0,int(clip.audio.duration-2))]
averaged_volumes = np.array([sum(volumes[i:i+10])/10
                             for i in range(len(volumes)-10)])

increases = np.diff(averaged_volumes)[:-1]>=0
decreases = np.diff(averaged_volumes)[1:]<=0
peaks_times = (increases * decreases).nonzero()[0]
peaks_vols = averaged_volumes[peaks_times]
peaks_times = peaks_times[peaks_vols>np.percentile(peaks_vols,90)]

final_times=[peaks_times[0]]
for t in peaks_times:
    if (t - final_times[-1]) < 60:
        if averaged_volumes[t] > averaged_volumes[final_times[-1]]:
            final_times[-1] = t
    else:
        final_times.append(t)

final = concatenate([clip.subclip(max(t-5,0),min(t+5, clip.duration))
                     for t in final_times])
final.to_videofile('iFLY - Cut.mp4') # low quality is the default

Open in new window


When I run the script, I get an error, see below

['movie.mp4']
Traceback (most recent call last):
  File "C:\Highlights\soccer_cuts.py", line 16, in <module>
    clip = VideoFileClip (print(glob.glob("*.mp4")))
  File "C:\Python38\lib\site-packages\moviepy\video\io\VideoFileClip.py", line 88, in __init__
    self.reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt,
  File "C:\Python38\lib\site-packages\moviepy\video\io\ffmpeg_reader.py", line 32, in __init__
    infos = ffmpeg_parse_infos(filename, print_infos, check_duration,
  File "C:\Python38\lib\site-packages\moviepy\video\io\ffmpeg_reader.py", line 245, in ffmpeg_parse_infos
    is_GIF = filename.endswith('.gif')
AttributeError: 'NoneType' object has no attribute 'endswith'

Open in new window


Looking through the error I found line 16 to be the issue

clip = VideoFileClip (print(glob.glob("*.mp4")))

Open in new window


What I'm trying to do with line 16 is set a variable, the file name movie may be called movie1 or movie 2 though there will always be just the 1 mp4 file within the folder called Highlights. I'm hoping you can assist me with this.

Any help is greatly appreciated.
0
Hi Guys

I have a python script that takes a video file called video.mp4 and cuts it down based on sound activity. See below. The python script is saved as PythonVideo.py in directory C:\Users\user\Desktop\Video

import numpy as np # for numerical operations
from moviepy.editor import VideoFileClip, concatenate

clip = VideoFileClip("video.mp4")
cut = lambda i: clip.audio.subclip(i,i+1).to_soundarray(fps=22000) 
volume = lambda array: np.sqrt(((1.0*array)**2).mean())
volumes = [volume(cut(i)) for i in range(0,int(clip.duration-1))]

increases = np.diff(averaged_volumes)[:-1]>=0
decreases = np.diff(averaged_volumes)[1:]<=0
peaks_times = (increases * decreases).nonzero()[0]
peaks_vols = averaged_volumes[peaks_times]
peaks_times = peaks_times[peaks_vols>np.percentile(peaks_vols,90)]

final_times=[peaks_times[0]]
for t in peaks_times:
    if (t - final_times[-1]) < 60:
        if averaged_volumes[t] > averaged_volumes[final_times[-1]]:
            final_times[-1] = t
    else:
        final_times.append(t)

final = concatenate([clip.subclip(max(t-5,0),min(t+5, clip.duration))
                     for t in final_times])
final.to_videofile('video1.mp4') # low quality is the default 

Open in new window


The issue here is when I run PythonVideo.py I get lines of error, see below. Is there something wrong I'm doing here? The python version I'm using 3.6.6

Traceback (most recent call last):
  File "C:\Users\user\Desktop\Video\PythonVideo.py", line 7, in <module>
    volumes = 

Open in new window

0
Hi,
I got 2 files i.e File1 and File2, as shown below

File1
A | APPLE
B | ORANGE
C | GRAPES

File2
A | 10
B | 15
D | 20

I need following 2 outputs,
Output 1
A | APPLE | 10
B | ORANGE | 15

Output 2
C | GRAPES | NA

I got the output1 using below below script.
Script1

for line1 in file1:
Data1 = line1.split("|")
Data10 = Data1[0]
Data11 = Data1[1]
 for line2 in file2:
 Data2 = line2.split("|")
 Data20 = Data2[0]
 Data21 = Data2[1]
  If Data10 == Data20:
  Print ( Data10, "|", Data11, "|", Data21)

My question is, how can I get my output2. I tired putting if data10 != data 20, i tired break and continue function but still I am not getting my output. Can advice what is best way to get my output2.
0
So with the inputs being from_date=2019-01-01 and to_date=today

I need

2019-01-01 - 2019-03-31
2019-04-01 - 2019-06-30
2019-07-01 - 2019-09-30
2019-10-01 - 2019-12-31
2020-01-01 - 2020-02-04

I don't really know any python, but this is the closest I can come up with so far.
The dates are there, I just don't know how to access them or fill in today's date on the last item....

    def get_date_ranges(self, fr_date, to_date):
        qtr_beg = pd.date_range(start=fr_date, end=datetime.date.today(), freq='QS')
        qtr_end = pd.date_range(start=fr_date, end=datetime.date.today(), freq='Q')
        date_range = zip(qtr_beg, qtr_end)
        return date_range

Open in new window

0
How would you code for this problem?

Define the function check(s). The function returns 1 when string 's' contains at least one digit and returns 0 otherwise.
0
How can we make a python application which will run interactively over SSH? Like I will login via SSH this python would be automatically started and ask some user inputs and continue to run or just continue to tail a log file. Please let me know if it is possible
0
I'm very new to Python but I've learned enough to print out the data in a specified range on Sheet 1 in a specified Excel workbook. The current code below will do that but in the Terminal window, each 5 column row is printed vertically in one long column so to speak. How would I modify the code to get it to print out with each 5 column row spread out horizontally as it is in Excel? I'm interested in doing that because 1) it would be easier to read, and 2) just to see if Python will do that.

path = r'C:\Users\t0122059\Documents\ACDetails.xlsx'

f = open(path, 'rb')
print(f.read())

# https://openpyxl.readthedocs.io/en/stable/usage.html

from openpyxl import load_workbook
wb = load_workbook(path)

for row in range(1, 12):
    for col in range(1, 6):
        print(wb.worksheets[0].cell(row, col).value)
print('inspect')

Open in new window

Thanks,
John
0
The attached image contains 2 csv files (csv1 and csv2). I want to combine 2 csv files to get the output csv attached in image. values in the output csv should be on the basis of finding closest years in csv2 to that in csv1. i.e what is the closest year to 2010 (in csv2) among (2012, 2009) (in csv1)? 2010 year in csv2 has 2009 as the closest year in csv1. so, in output csv, 2010 year has values from year 2009 in csv1 as it closest to 2010 than 2012 (highlighted in green). all the other years in output csv have closest year as 2012 from csv1, so output contains values from years 2012 (highlighted in red).
img.png
0
I have a column which contains geometry values (maps) like 01030009777700000000BCA142E2ABD08A2C0CA9466D8B4B4CC. I wanted to convert it into latitude and longitude coordinates. I tried using geopandas but didn't click for me. Any help is appreciated.
0
We're working with an API that has been giving us trouble from the very beginning. The support people informed us of a bug in which their servers expect a content-type of 'application/json' in the header but for the data to actually be passed using the 'form-data' or application/x-www-urlencoded' content type. No matter what I do I get either a 500 response or an error about the content-type in the response from their server when using the python requests library. I did have this working in javascript/node.js and postman, but we need it to work in python.

Here's the code:
import requests

API_URL = "https://api.kenect.com/v1/conversations/messages/"

headers = {
    'x-api-token': '1130FxmIcc6uZWcq8OXoCZZPCpq8ODQo',
    'x-api-key': 'pdwz0naW5hyCeG9SyJ3PpnOf26BZFS28'
}

data = {
    "locationId": 2045,
    "messageBody": 'test',
    "contactPhone": 15857396811       
}

r=requests.post(url=API_URL, headers=headers, data=data)
print(headers)
print(data)
print(r)

Open in new window

0
I remotely connect to Linux virtual box from secure shell (ssh).  I have smallest bitbake project.

I type bitbake from shell prompt.  
The output is as follows:
Nothing to do.  Use 'bitbake world' to build everything, or run 'bitbake --help' for usage information.

Bitbake document says default build task will be executed.
build default task is in Base.bbclass file.

How can I be sure this task actually executed?  How do I print something to the screen from this task?
base.bbclass
bblayers.conf
bitbake.conf
layer.conf
0
Hi all i am having some massive brain farts at the moment and i cant work out the issue i am having, i have been starting at the code for hours and i know its on a small issue, i am getting a error on line 58, i know its got to do with formatting but for the life of me i ant get it to work correctly
#****
# *****
# VERSION 1.0
# DATE 6 Jan 2020
# UPDATED 6 Jan 2020
# *****


import mysql.connector
import pandas as pd
import mysql.connector
import urllib.parse
import requests
import finddatatime  # Getting the date from the second script called finddatetime.py

currentdatetime = finddatatime.date_time

print ("The Current time date is" + " " + currentdatetime)

from mysql.connector import Error
from __main__ import *

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="A*****1",
    database="flightdata"
)

mycursor = mydb.cursor()

fnumber = (input("Please enter flight number:  "))

sql = 'SELECT * FROM flightdata.flightinfo where flightnumbers =' + "'" + fnumber + "'"
# print(sql)

mycursor.execute(sql)
# connection.commit()

myresult = mycursor.fetchall()

for x in myresult:
    flightnumber = x[3]
    orgin = x[10]
    dest = x[2]
    departtime = x[4]
    status = x[8]

answer = (input("Flight #: " + str(flightnumber) + " From: " + str(orgin) + " To: " + str(dest) + " At: " + str(
    departtime) + "is that correct? yes/no: "))
# if statment for answer start
if answer == "yes":
    print("Current status of your flight as of " + 

Open in new window

0
Hi Bash experts,

Trying to parse multiple xml files in a directory.
Extract an attribute value from available xml files. e.g liferay-version="20.0.1.5"
sort them and get the greatest value from the identified list. e.g "20.0.1.8" and store them in a variable

Was trying using python, but due to restriction on my work server. couldn't install additional packages, so couldn't use python.

Is it possible using sed/awk/bash or any way please.

file1.txt
<?xml version="1.0" encoding="utf-8"?>
<package date-created="26/11/2019" liferay-version="20.0.1.5" patch-version="5.0">
  <description />
  <system />
</package>

Open in new window


file2.txt
<?xml version="1.0" encoding="utf-8"?>
<package date-created="26/11/2019" liferay-version="20.0.1.6" patch-version="6.0">
  <description />
  <system />
</package>

Open in new window



file3.txt
<?xml version="1.0" encoding="utf-8"?>
<package date-created="26/11/2019" liferay-version="20.0.1.7" patch-version="7.0">
  <description />
  <system />
</package>

Open in new window


file4.txt
<?xml version="1.0" encoding="utf-8"?>
<package date-created="26/11/2019" liferay-version="20.0.1.8" patch-version="8.0">
  <description />
  <system />
</package>

Open in new window

0
what is TCP blocking and non-blocking mode in socket module in python

I am trying to understand what it means and under which situation we should use it. I am not able to find a proper example to understand it. I really appreciate if any example can be shared to understand it better.

Thank you!
0
Understanding Python Functions

I have this Python code :
import random
class Dice:
    def Roll(self):
     first=random.randint(1,6)
     second=random.randint(1,6)
     return  first,second


dice=Dice()
print(dice.Roll())

Open in new window


I would like to know the meaning of Self in : the function Roll. is it a parameter that needs an argument passed to it ? if so what argument was it passed to it in the above example?

I also want to understand the Return keyword.  in the example above the result from variables first and second will be returned but where does it get stored ?
it should be store in the function Roll, but where ? in the Self parameter ?

Any clarification will be very much appreciated.


Thank you
0
using Python Modules

I have this Python Code:

def test1(weight):
    return weight * 0.45
print(test1())

def test2(weight):
    return weight/ 0.45
print(test2())

Open in new window


I want to call the methods above from this program and pass the wight argument for instance 200
from mod1 import test1,test2
test1(200)
test2(200)

Open in new window


however, it seems like if I do not specify the weight  in Mod1.py   the calling code will fail.

C:\Users\user\AppData\Local\Programs\Python\Python38\python.exe C:/Python-Projects/Mydjangoproject/test.py
Traceback (most recent call last):
  File "C:/Python-Projects/Mydjangoproject/test.py", line 1, in <module>
    from mod1 import test1,test2
  File "C:\Python-Projects\Mydjangoproject\mod1.py", line 3, in <module>
    print(test1())
TypeError: test1() missing 1 required positional argument: 'weight'

Process finished with exit code 1[code]

Open in new window


[/code]
0
Trying to display just the "From" and "Subject" items from all unread emails. What I've got in the code reads
<code>
          def getmail(server):
               select_info = server.select_folder(MAILBOX)
               messages  = server.search(['UNSEEN'])
               print("getting mail")
               for uid, message_data in server.fetch(messages, 'RFC822').items():
                    print("number of messages %d" % len(messages))
                    email_message = email.message_from_bytes(message_data[b'RFC822'])
                    print(email_message.get('From'), email_message.get('Subject'))
          return messages
</code>

However, what's happening is an error is occurring. Output listing is

getting mail
number of messages 1
"Rob PL" <rob@xxxxxxxxx.com> test
number of messages 1
Exception triggered: b'RFC822'

Just can't find a way of getting rid of the error.

Can anyone help here?
0
Python Classes

in the example  below, when I run the program, it shows what it is supposed to be printed to the screen, but it also add the word "None"
not sure why, though I followed the same example from a tutorial, but I did not see the program displaying the word "None" in that tutorial.

Any idea?

Thank you

c
0
I have a dataframe with the customer Id, first name, address1, address2 etc and I would like to merge all the address columns into one single address column.

How do I skip columns that have an empty string or None in their address1 column?

I use the following function but somehow but it looks like the loop enters the else part of the loop even though I add a break statement:

for index, row in customers_df.iterrows():
    if customers_df['address1'][index] != "None":
        customers_df['complete_address'] = customers_df["address1"].map(str) + ", " + customers_df["address2"].map(str) + ", " + customers_df["zip"].map(str) + ", " + customers_df["town"].map(str) + ", Switzerland"
        break
    else:
        customers_df['complete_address'] = np.nan

Open in new window

0
hello, expert.
there is one home listings site.
I would like to receive some information within this site.
this site's url is https: =  //www.hurriyetemlak.com/satilik
I marked the information I want with a red square.
I want to get the data I marked with beautifulsoup.
and I want to get this data in json format.
I'm new to python.
import bs4
import requests

r=requests.get("https://www.hurriyetemlak.com/satilik")
print(r.status_code)
soup=bs4.BeautifulSoup(r.content,"html.parser")
#print(soup.find_all("div",attrs={"class":"col-lg-12 mt-1 box list-container"}))
adresler=(soup.find_all("div",attrs={"class":"col-lg-12 mt-1 box list-container"}))
for x in adresler:
    print(x)

Open in new window

ı did something in its own right.
but I didn't make much progress
I don't know how.
I need your help.
thanks
Ads-z.png
0
Hi Python experts

this is reference to this conversation

https://www.experts-exchange.com/questions/29167463/python-convert-currency.html?anchor=a42998667¬ificationFollowed=242733822#a42998667

how to convert "float(amount)" from USD to AUD please :)

#!/usr/bin/env python2.7

import argparse
import boto3
import datetime
from currency_converter import CurrencyConverter

parser = argparse.ArgumentParser()
parser.add_argument('--days', type=int, default=30)
args = parser.parse_args()


now = datetime.datetime.utcnow()
start = (now - datetime.timedelta(days=args.days)).strftime('%Y-%m-%d')
end = now.strftime('%Y-%m-%d')
dtemplate="{:10} {:14} {:40} {:16.10f} {:6} {:10}"
htemplate="{:10} {:14} {:40} {:16} {:6} {:10}"

cd = boto3.client('ce', 'ap-southeast-2')

results = []

token = None
while True:
    if token:
        kwargs = {'NextPageToken': token}
    else:
        kwargs = {}
    data = cd.get_cost_and_usage(TimePeriod={'Start': start, 'End':  end}, Granularity='DAILY', Metrics=['UnblendedCost'], GroupBy=[{'Type': 'DIMENSION', 'Key': 'LINKED_ACCOUNT'}, {'Type': 'DIMENSION', 'Key': 'SERVICE'}], **kwargs)
    results += data['ResultsByTime']
    token = data.get('NextPageToken')
    if not token:
        break

print(htemplate.format("TimePeriod", "LinkedAccount", "Service", "Amount", "Unit", "Estimated"))

for result_by_time in results:
    for group in result_by_time['Groups']:
        amount = group['Metrics']['UnblendedCost']['Amount']
        unit = 

Open in new window

0
Hi Python experts,
Trying to convert an amount from USD to AUD

I tried below using interactive python and it worked

pip install --user currencyconverter

Open in new window


$ python
Python 2.7.5 (default, Aug  7 2019, 00:51:29)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux2

>>> from currency_converter import CurrencyConverter
>>> c = CurrencyConverter()
>>> c.convert(100, 'USD', 'AUD')
146.9260630134513

Open in new window


However, trying to incorporate this into a python file but getting an error

convert.py
#!/usr/bin/env python3

import argparse
import boto3
import datetime
from currency_converter import CurrencyConverter

Open in new window


Traceback (most recent call last):
  File "/usr/local/bin/aws_cost_explorer.py", line 6, in <module>
    import CurrencyConverter
ImportError: No module named CurrencyConverter


please help
0
https://www.experts-exchange.com/questions/29166962/Delete-unwanted-records.html#a42997133

id         X              year
45      1375      2018
23      1514      2018
67      1516      2017
32      1516      2018
78      1502      2018
54      1908      2017
11      1908      2018
24      1908      2015
98      1908      2016
85      1908      2018
52      1908      2016

for above data, the above code generates the following output.


id      X      year
54      1908      2017
11      1908      2018
24      1908      2015
98      1908      2016
85      1908      2018
52      1908      2016

I wanted to delete the duplicate records from the above output when X and year are same so that the output should be

id          X              year
54      1908      2017
11      1908      2018
24      1908      2015
98      1908      2016
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.

Top Experts In
Python
<
Monthly
>