We help IT Professionals succeed at work.

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.

I have python code doesn't working on my ubuntu 16 what is the problem, is there any change I can do to run the code on my ubuntu 16

from Crypto.Cipher import AES

# inputs
text = "This is a top secret."
enc = "764aa26b55a4da654df6b19e4bce00f4ed05e09346fb0e762583cb7da2ac93a2"
iv = "aabbccddeeff00998877665544332211"

# changing string type to bytes
dec_iv = bytes.fromhex(iv)

# padding text with ascii 11
while (len(text) % 16 != 0):
    text = text + chr(11)

# scanning all the keys
f = open("words.txt", "r")
lines = f.read().splitlines()

# Iterating over all the keys
for key in lines:
    word = key
    # ignore if key length is greater than 16
    if len(word) > 16:
        continue
    # padding the key with '#'
    while (len(word) % 16) != 0:
        word += "#"

    # encrypt and check whether it matches or not
    temp_enc = AES.new(str.encode(word), AES.MODE_CBC, dec_iv).encrypt(text)
    print(key, temp_enc.hex())
    if temp_enc.hex() == enc:
        print("Bingo! Match found")
        print("key:", key)
        break

Open in new window

python-code-error.png
0
Hi all ia am going well with my script to check for a program and if its not there then run another program, my issue is that even if its find that the program is there it will try to run it any way, on a leavel of 1 to 100 how good am at code maybe 40 so forgive me if it is a dumb mistake, here isthe code , i might be completely wrong so pelase tell me if i am

# Created By ADBY IT AND MEDIA SOLUTIONS
# Adam R Wolarczuk
# 19th March 2020
# Version 0.1
# Beta


# Class for Detect if program is running
import psutil
import subprocess
import pyautogui
import time

for p in psutil.process_iter(attrs=['pid', 'name']):
    if p.info['name'] == "Discord.exe":
        print("yes", (p.info['name']))

    else:
        print("I am here")
        subprocess.Popen(r"C:\FrazerClient\FrazerClient.exe")
        #print("no", (p.info['name']))


# If Program is running
# if the program is not running
# Log to file
# send email to imporm report
0
Hi, I have  question about python. With the code below I can create a csv file: my.csv, but for some reason that when system insert rows to csv file, it always skip one row in csv file.  So in the csv file, there is one more extra empty row. How can I remove the empty row?  
Below is the code:

with open ('my.csv','w') as awriter:
        fieldnames = ['id', 'la', 'lo', 'state', 'zip']
        csvwriter = csv.DictWriter(awriter, fieldnames=fieldnames)

        csvwriter.writeheader()

        for row in results:
 
            id = row['id']  //error start here, can't retrieve the value for fields
            la = row['la']
            lo = row['lo']
            state = row['state']
            zip1 = row['zip']
           csvwriter.writerow({'site_id': site_id, 'latitude': latitude, 'longitude': longitude, 'state': state, 'zip': zip1})
my.csv
0
I am new to python and have a question about python.
I have some python code :  after get results from db, then need write each row to a csv file.  but I got an error when I try to access each row, I got an error: "tuple indices must be integers or slices, not str"
sample data for each row is like this:
150, Decimal('80'), Decimal('-25'), 'NJ', '00700')

Below is the code:
    with open ('my.csv','w') as awriter:
        fieldnames = ['id', 'la', 'lo', 'state', 'zip']
        csvwriter = csv.DictWriter(awriter, fieldnames=fieldnames)

        csvwriter.writeheader()

        for row in results:
 
            id = row['id']  //error start here, can't retrieve the value for fields
            la = row['la']
            lo = row['lo']
            state = row['state']
            zip1 = row['zip']
            line = ''.join([id, ",", la, ",", lo, ",", state, ",", zip1]).split(",")
            ln_dict = OrderedDict(zip(fieldnames, line))
            csvwriter.writerow(ln_dict)

Any inputs are appreciated!
0
Hello, Experts,

I have a question to ask regarding a python script I have built to find a file, put in an array and SFTP that to a remote location that is running errors. The error I am getting is below.

Traceback (most recent call last):
  File "/Users/isaiah.melendez/Documents/python/alr_to_ho.py", line 38, in <module>
    ftpTransmit()
  File "/Users/isaiah.melendez/Documents/python/alr_to_ho.py", line 34, in ftpTransmit
    sftp.put(ftpALR[i], 'C:\CBASYNC')
  File "/Users/isaiah.melendez/Documents/python/venv/lib/python3.7/site-packages/pysftp/__init__.py", line 364, in put
    confirm=confirm)
  File "/Users/isaiah.melendez/Documents/python/venv/lib/python3.7/site-packages/paramiko/sftp_client.py", line 759, in put
    return self.putfo(fl, remotepath, file_size, callback, confirm)
  File "/Users/isaiah.melendez/Documents/python/venv/lib/python3.7/site-packages/paramiko/sftp_client.py", line 714, in putfo
    with self.file(remotepath, "wb") as fr:
  File "/Users/isaiah.melendez/Documents/python/venv/lib/python3.7/site-packages/paramiko/sftp_client.py", line 372, in open
    t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
  File "/Users/isaiah.melendez/Documents/python/venv/lib/python3.7/site-packages/paramiko/sftp_client.py", line 813, in _request
    return self._read_response(num)
  File "/Users/isaiah.melendez/Documents/python/venv/lib/python3.7/site-packages/paramiko/sftp_client.py", line 865, in _read_response
    self._convert_status(msg)

Open in new window

0
I need assistance to figure out the issue in python code
question.jpg
error.png
0
Hi Team,

Iam trying to run the below code in python , Iam getting an error while calculating the ca value .Kindly help me with the casue of the error
''' write a program to calulate the gross salary of the employee
if his basic salary less than 2000 then HRA 10% of basic salary
DA 90% of basic salary , ca=10
> 2000 , hra 5%  bs and da 20 percent of basic salary '''

basicSalary=int(input("Enter the basic salary"))
if basicSalary < 2000:
      hra=basicSalary * 0.1
      da=basicSalary * 0.9
      ca=10
else:
      hra=basicSalary * 0.05
      da=basicSalary * 0.2

grossSalary=basicSalary+hra+da+ca
print (" the gross salary of employees is ",grossSalary)


C:\Users\sam\Desktop\MyPythonPrograms>python mypythonIf3.py
Enter the basic salary2300
Traceback (most recent call last):
  File "mypythonIf3.py", line 15, in <module>
    grossSalary=basicSalary+hra+da+ca
NameError: name 'ca' is not defined
0
hi am geting this error
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-95-d05cc6ee7707> in <module>
----> 1 from sklearn.cross_validation import train_test_split

ModuleNotFoundError: No module named 'sklearn.cross_validation'
0
hi am geting this error
TypeError                                 Traceback (most recent call last)
<ipython-input-32-f71465f74ff4> in <module>
----> 1 plt.figure(figsize=(10))
      2 sns.boxplot(x='Pclass',y='Age',data=train)

TypeError: 'module' object is not callable

object3
0
hi am geting the following error
titanic
0
How to use groupby function in python

Below is my source file

File1
Fruits|country|count
Apple|countryA|100
Orange|countryA|20
Apple|countryB|200
Orange|countryB|12

I want to group records based on country and I want below output.

Output1
Country|Fruits|count
countryA|Apple|100
countryB|Apple|200
countryA|Orange|20
countryB|Orange|12

I tried below code but it is not working.

Df = pd.read_csv('file1.txt, sep="|")
Grouped = Df.groupby('Country', axis='Columns')
Grouped.to_csv('output1.txt', sep="|",index=False)

But I am getting error. What is the correct way for group data in python.
0
I want to do this through Python. I have two files, one employees and the second one "Evaluation", both are in notepad. I want to create arrays where it should
give me the results like below, should match the employee number in evaluation file and if it is there then it should add all the score and divide it by how many lines for that employee and get the average score,  if the score is above between 90 to 100 then Excellent, if 80 to 89 Very Good, If 70 to 79 then Good and if 60 to 69 then fair, otherwise poor.


[['1215', 'John', 'Davis', '87', '84', '90', '78', '86', '85.0', 'Very Good'], ['1244', 'Kerry', 'David',
'79', '96', '83', '89', '88', '72', '84.5', 'Very Good'], ['1400', 'Smith', 'Harris', '86', '96', '73', '74', '89',
'86', '92', '85.14', 'Very Good'], ['3458', 'Wood', 'John', '88', '68', '70', '89', '77', '84', '93', '67',
'79.5', 'Good']]
employees.txt
Evaluation.txt
0
Hello, Experts,

I am new to the encryption world. I have some python experience under my belt but not much when it comes to encrypting passwords. I have compiled a python script that is very simple. It queries a directory > grabs a specific type of file > starts a FTP transmission > ends.

Currently, in testing, my python script has the URL, username, password in cleartext. For obvious reasons, I want to move away from that. What is the best practice to encrypt my data?

Assumptions:
  • Script will be downloaded from an FTP host to various machines
  • The script will be placed in a hidden dir
  • Service will run to kick off-script during an interval

It would make sense for me since this script will be deployed globally to encrypt password once, store in some sort of file, then reference later in the script.

I am looking for some pointers, examples, and best practices.

#import libraries
import os
import pysftp

# query for file to ftp
alr_file = '/Users/path/to/file/to_ftp'
ftpALR = []

def findFile():

    for item in os.listdir(alr_file):
        if item.endswith('.mdb'):
            ftpALR.append(alr_file + '/' + item)

# ftp transmission function
def ftpTransmit():
    # list ftp dir
    cnopts = pysftp.CnOpts()
    cnopts.hostkeys = None
    with pysftp.Connection(host='ftp.acme.com',
                              username='cloudUser',
                              password='NOT_A_REAL_PWD',
             

Open in new window

0
I want to extract only those rows where specific column values are duplicated.

For example, my source file is

File 1 : CountryA.txt
fruits|count
apple|100
orange|200
orange|245
grapes|230

I need following output
output1.txt
fruits|count
orange|200
orange|245

My code is, is this the correct way of doing this ?

Df1 = pd.read_csv('CountryA.txt',sep="|")
Df1 = Df1[Df1['fruits'].duplicated()]
Df1.to_csv('output1.txt',sep="|")
0
Hi,
I have 2 files. I want to compare these 2 files and select only those that doesn't match.

For example, my 2 source files are File 1 : CountryA.txt
fruits|count
apple|100
orange|200
grapes|230

File 2 : CountryB.txt
fruits|count
apple|20
orange|15
peach|20

I need below 2 outputs
Output1.txt
fruits|count
grapes|230

Output2.txt
fruits|count
peach|20

I am trying to use outer join concept but it is not working. What is correct way of doing this ?
0
I want to do this through Python. I have two files, one employees and the second one "Evaluation", both are in notepad. I want to create third text file(notepad) where it should
give me the results like below, should match the employee number in evaluation file and if it is there then it should add all the score and divide it by how many lines for that employee and get the average score,  if the score is above between 90 to 100 then Excellent, if 80 to 89 Very Good, If 70 to 79 then Good and if 60 to 69 then fair, otherwise poor.

 John, Davis - 93.6 - Excellent
Kerry, David - 79.8 - Good
Smith, Harris - 86.6 - Very Good
Wood, John - 74.6 - Good
Berry, Carl - 0 - Poor
employees.txt
Evaluation.txt
0
I have this statement that I would like to run in python as a for each loop then insert all of the data into a table...… I'd like to use pyodbc and maybe pull the data into dataframes…. ?? then take the panda df and insert into a table, but the first thing is to get this running for every table

the first query would be to get the tables then loop thru each table and run the last query

select * from sys.tables- Get this into a variable or list and loop thru and run the below query 

--Filter out all of dates, and the id attributes metadata
 DECLARE @Table SYSNAME = 'ArrestInfo'
-- REVERSE and STUFF used to remove trailing UNION in string
SELECT REVERSE(STUFF(REVERSE((SELECT 'SELECT distinct ' + name 
                                     + ', COUNT(DISTINCT(' 
                                     + QUOTENAME(name) + ')) AS [Count] FROM '
                                     + QUOTENAME(@Table) + ' Group by ' + name + '' + ' UNION ' 
                              -- get column name from sys.columns  
                              FROM   sys.columns 
							  WHERE  object_id = Object_id(@Table) 

                              -- concatenate result strings with FOR XML PATH
                              FOR XML PATH (''))), 1, 7, ';'));

Open in new window

0
How to append to an existing csv file? I have a csv file that is the result of looping through a folder and extracting data from named excel sheets within the folder. The the dataframe is saved as a csv file. Everytime the process runs it overwrites the content in the csv--I want to append to the file with new rows of data from each run, , not overwrite it. Please advise.
0
How to extract a substring from column and add it back as new column.

For example, I have file1 with 2 column. I want extract first 3 character from fullname column and then I need to add it as new column.

File1
FullName|count
APPLE|100
ORANG|200
GRAPES|300

I need below output
Output1
FullName|ShortName|count
APPLE |APP|100
ORANGE |ORA|200
GRAPES|GRA|300

Is below is correct way of doing this.
Script
df = pd.read_csv('File1', sep='|')
df['ShortName'] = df['FullName'].str.slice[0:3]
df.out_csv('output1')
0

Using Python to Insert Filename into Column


I have  a folder full of two-column  excel files. Column A has  attributes, Column B has values. I want to loop through the folder and insert a row at the top of the worksheet ("Sheet1")
and enter the values "Filename" in column A and  the actual filename in Column B (without the full path, just the file name). I have tried  creating two data frames, using concat, but has not worked.  Please  advise.
0
Stacking a bar chart in matplotlib using a loop, I can do it for one set of data but struggling to loop the bottom parameter to stack the data.

Data



N =9
ind = np.arrange(N)

stacker = 0
for idx, ev in enumerate(sample):
      
    r = [int(t.seconds/3600 for t in ev.duration]
    if idx ==0:
        plt.bar(ind, r)
        stacker =r
    else:
         plt.bar(ind, r, bottom=stacker)
         stacker = r

plt.show


   
      

Open in new window

0
using the below code, i'm getting the ordinal positions for the barchart produced instead of the column names from the .csv(dataframe) i can't figure out how to get to column names into the chart

import pyodbc
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.read_csv('c:/python/incidents_hist.csv')
dfPandaBarChargdf.plot.bar()
1
i'm looking to plot Timedelta in a bar graph using matplotlib from Pandas

[Timedelta('0 days 08:43:07'),
Timedelta('0 days 04:43:07'),
Timedelta('0 days 03:43:07')]

Open in new window


matplot lib see's these as strings and won't plot them?
0
I am new to Python. try to learn. I want to create program where it should ask for birthday just day and month using input function and if the birthday is in the future then should give message that how many days left for your birthday, if it   is already passed then it should give message that your birthday was that many days ago and if it is today then should show message ‘happy birthday’
I spent lot of time but no luck
0
How to concat 2 column in pandas dataframe

My input file is
File1
CountryA|Apple|200
CountryB|Apple|100
CountryA|Orange|150

Output I need is below
CountryAApple|200
CountryBApple|100
CountryAOrange|150

I tried below code. Is this the correct way of doing this..
df1 = pd.read_csv('file1','|')
df2 = df1.iloc[:,:0]
df3 = df1.iloc[0:,:1]
df4 = df1.iloc[1:,:2]

df5 = pd.concat([df2, df3])
df6 = df5+"|"+df4
Print(df6)
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.