Go Premium for a chance to win a PS4. Enter to Win

x

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

Hi,
We are looking for an option to convert RTF file to TXT.  Please suggest any tool.
Tried python...any option

Thanks!
CPH
0
Important Lessons on Recovering from Petya
LVL 11
Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

I am trying to write a python script to verify whether or not a proper security constraint was applied in AWS. The script seems to be working, however, it is returning a duplicate output (code is attached)

Here is a sample log output when it is run in AWS Lambda:

START RequestId: 8edc3e6d-c727-11e7-ad8e-07aa7f7d4c10 Version: $LATEST
port-7dheonjnhtxci

Listing constraints.........
Checking for valid SG template constraint....
['port-7dheonjnhtxci'] Contains a valid SG template constraint....
Listing constraints.........
Checking for valid SG template constraint....
['port-7dheonjnhtxci'] Contains a valid SG template constraint....

END RequestId: 8edc3e6d-c727-11e7-ad8e-07aa7f7d4c10

As you can see, it is returning the same information twice.  I am relatively new to Python so I am sure it is just a simple oversight on my part. Any assistance would be greatly appreciated.
Code.txt
0
Dear Experts,

Actually trying to analyze the machine learning logics behind in algorithms, for example the KNeighborsClassifier():

import pandas
from sklearn.neighbors import KNeighborsClassifier
model = KNeighborsClassifier()
print(model)

Open in new window


Could you please advise would it be possible to list the content of an algorithm in Python and with which syntax concretely? The above print(model) of course just provides some overall information about the algorithm, but not the content

Thanks in advance,
0
I am new to Python and I am trying to understand the FOR loop.

I am have created a function that searches whether a particular name is in a list. If it is, it should return true.
I understand that break exits the loop .. but why does it not in my case?

def nameSearch(names, target):
    for x in names:
        if x == target:
            return True
            break
        else:
            return False

Open in new window


This is how I call the code:


nameList = ['Smith', 'Jones', 'Turing', 'Bloggs', 'Meyer', 'Hampden']

print()
print('Testing nameSearch()')
print(nameSearch(nameList, 'Turing'))

Open in new window


Even though Turing is in the list, the compiler returns False.

What am I missing?
0
Dear Experts,

I have the following Python code which predicts result on the iris dataset in the frame of machine learning.

# -*- coding: utf-8 -*-

# Load libraries
import pandas
from pandas.tools.plotting import scatter_matrix
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC

# Load dataset
path = "C:\\Users\\zc\\Downloads\\Daily files\\Machine Learning\\IrisGenerated.csv"
names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']
dataset = pandas.read_csv(path, names=names)

# Split-out validation dataset
array = dataset.values
X = array[:,0:4]
Y = array[:,4]
validation_size = 0.20
seed = 7
X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=validation_size, random_state=seed)

# Test options and evaluation metric
seed = 7
scoring = 'accuracy'

# Fit the model
model = KNeighborsClassifier()
model.fit(X_validation, Y_validation)

# save the model to disk
filename = 'finalized_model.sav'
joblib.dump(model, filename)

# load the model from disk
loaded_model = 

Open in new window

0
I have a variable which outputs

Happy Gilmore
Silly Monkey
Funny Donkey

I would look like to load these into a dictionary so I can use

print(variable.get("Happy"))
0
plot where y = x**2 for x over the interval 1 to 5, properly labelled

Create a histogram where the mean = 0, std. dev. = 1, n = 300, and there are sqrt(n) bins

Create a line plot of your choosing with an appropriate legend which displays the formula of the curve depicted.
The formula should be formatted using TeX syntax to create a professional presentation.
0
help me to understand the below lines in below shell script..

Why we need to use virtualenv "$ANSIBLE_ROOT" .... and what is the use of virtualenv here ....

and how activate and deactivate worked ...i am bit confused how activate and deactivate keywords worked here..
. "$ANSIBLE_ROOT/bin/activate"
deactivate


and also how pip works with -i option...i.e. below

pip install docker-compose==1.15.0 -i https://artifactory.global.raju.com/artifactory/api/pypi/pypi-release/simple


#!/usr/bin/env sh

ANSIBLE_ROOT=${ANSIBLE_ROOT:-~/ansible}
scl enable python27 bash <<!
set -e
export https_proxy=https://10.198.140.122:8080
if [ ! -d "$ANSIBLE_ROOT/bin" ]
then
    virtualenv "$ANSIBLE_ROOT"
    . "$ANSIBLE_ROOT/bin/activate"
    echo "Installing latest version of ansible"
    pip install ansible -i https://artifactory.global.raju.com/artif4actory/api/pypi/pypi-release/simple
    pip install docker-py -i https://artifactory.global.raju.com/artifactory/api/pypi/pypi-release/simple
    pip install docker-compose==1.15.0 -i https://artifactory.global.raju.com/artifactory/api/pypi/pypi-release/simple
    deactivate
fi
!

Open in new window

0
bins = [0, 10, 20, 30, 40, 50, 60, 70, 80]

df['AgeBin'] = pd.cut(df['Age'], bins)

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-16-0750c69cbf65> in <module>()
      1 bins = [0, 10, 20, 30, 40, 50, 60, 70, 80]
      2
----> 3 df['AgeBin'] = {pd.cut(df['Age'], bins)}

NameError: name 'pd' is not defined
0
i appear to be having issues using anaconda.
i have copied the code into Jupyter note as follows:
In [1]:
def CryptoDataCSV(symbol, frequency):

#Params: String symbol, int frequency = 300,900,1800,7200,14400,86400

#Returns: df from first available date

url ='https://poloniex.com/public?command=returnChartData¤cyPair='+symbol+'&end=9999999999&period='+str(frequency)+'&start=0'

df = pd.read_json(url)

df.set_index('date',inplace=True)

df.to_csv(symbol + '.csv')

print('Processed: ' + symbol)
In [2]:
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
In [3]:
tickers = ['USDT_BTC','USDT_ETC','USDT_XMR','USDT_ETH','USDT_DASH',
'USDT_XRP','USDT_LTC','USDT_NXT','USDT_STR','USDT_REP','USDT_ZEC']
In [4]:
crypto_df = pd.DataFrame()
for ticker in tickers:
crypto_df[ticker] = pd.read_csv(ticker+'.csv', index_col = 'date')['close']
crypto_df.dropna(inplace=True)
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-4-b59f4116fa1a> in <module>()
      1 crypto_df = pd.DataFrame()
      2 for ticker in tickers:
----> 3     crypto_df[ticker] = pd.read_csv(ticker+'.csv', index_col = 'date')['close']
      4 crypto_df.dropna(inplace=True)
~\Anaconda3\lib\site-packages\pandas\io\parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, …
0
Keep up with what's happening at Experts Exchange!
LVL 11
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Hi,

I’m looking over inserting a variable into subprocess.

command=r"""ifcobfig server| tail -1 """
output=subprocess.check_output(command, shell=True)
0
Issue:
Python Script will not run because sshtunnel import to Python 3 does not seem import properly to the Pi.
I am thinking we are using the wrong version of ssh module python script for the Pi but I am struggling.  

 Hardware :
Raspberry Pi 3 Model B -  V 1.2  2015

OS Software :
pi@raspberrypi:~ $ cat /etc/*-release
PRETTY_NAME="Raspbian GNU/Linux 8 (jessie)"
NAME="Raspbian GNU/Linux"
VERSION_ID="8"
VERSION="8 (jessie)"
ID=raspbian
ID_LIKE=debian

Script:
import sshtunnel #import SSHTunnelForwarder
import mysql.connector

ID_String_Last = ["0"]

sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0

with sshtunnel.SSHTunnelForwarder(
    ('**********this is the host in here **********'),
    ssh_username='', ssh_password='**********************',
    remote_bind_address=('127.0.0.1,', 3306)
) as tunnel:
    connection = mysql.connector.connect(
        user='*********username**********', password='*****************',
        host='127.0.0.1', port=tunnel.local_bind_port,
        database='northgm7_489.log_1001',
    )


Output:
Python 3.4.2 (/usr/bin/python3)
>>> %Run '17-10- 15 V6.1 Pi mySQL to Ash server.py'
Traceback (most recent call last):
  File "/home/pi/Desktop/17-10- 15 V6.1 Pi mySQL to Ash server.py", line 3, in <module>
    import sshtunnel #import SSHTunnelForwarder
ImportError: No module named 'sshtunnel'


Question:
Does anybody know what version of module is required for this platform so that it …
0
hi

just started learning python. installed python and pycham and wrote hello world kind of application.

can you please point me to good links, resources, free video courses, trainings available on python.

Please advise
pythin.png
pythin.png
0
#I am trying to add strings if they start with the "<" character. I get "cannot assign to a literal" when I press "enter" after teh "return" statement.

def tag_count(xml_tags):
      xml_tags_sum=0
... for "xml_tag" in xml_tags:
          if xml_tag[0]=="<"
                xml_tags+=xml_tag
      return xml_tags_sum

# I suspect the error is in line 2, but I cannot fix it.
0
def counter (n):
    while (n<1000):
        if ((n*11) % 7==0):
            print (n)
            break
        else:
            n+=1
    counter (15)

I do  not understand this code?
0
How to download the audio file from google meaning using python platform?  

I tried using ffmeg package but it's not working. Any small sample script could help me.


Thanks in Advance!!!
0
Hi, this is my code:

def sumanu(numeros):
      sumat+=numero
      numeros=[]
      for numero in numeros:
                  return sumat

#This code generates an error once I type the argument inside the function.
0
Hi, this is my code:

def how_many_days(month_number):
            days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]
            print(how_many_days[8])

When I try to run it, I get an error message: "function object is not subscriptable".

Thanks for your help!
0
I tried to Run but DB not connected i am using Xampp mysql server,  any idea for this?

Send Querys like

#!/usr/bin/python
from Tkinter import *
import MySQLdb
#-----------------------------------------------------------
## Connect to DB
conn = MySQLdb.connect(host='localhost', user='root', db='mind0')
##Create a cursor
curs = conn.cursor()
## *****************************************************
# Root level form
class MyApp:
  def __init__(self):
    window = Tk()
    window.title('Data Entry Form')  
    frame = Frame(window)
    frame.pack()
## BEGIN Fields ***********************************************    
    self.fields = {}
#--------------    
    l = Label(frame, text="vendID:")
    l.grid(row=0, column=0)    
    self.fields['vendID'] = Entry(frame)
    self.fields['vendID'].grid(row=0, column=1)    
#--------------      
    l = Label(frame, text="vendName:")
    l.grid(row=2, column=0)  
    self.fields['vendName'] = Entry(frame)
    self.fields['vendName'].grid(row=2, column=1)
## END Fields ************************************************    
 
## BEGIN Buttons ########
    clearbtn = Button(frame, text="Clear", command=self.do_clear)
    clearbtn.grid(row=11, column=0)
       
    submitbtn = Button(frame, text="Submit", command=self.do_insert)
    submitbtn.grid(row=11, column=1)
 
    updatebtn = Button(frame, text="Update", command=self.do_update)
    updatebtn.grid(row=11, column=2)
## END Buttons ##########…
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.

from MySQLdb import *
from Tkinter import *
#Standard Imports (IMO)
import sys, random, math

class dataStoreTest:

    def __init__(self):

        self.root = Tk()
        self.root.title("Database Test")
        self.inputFrame = Frame(self.root)

        #TextVariables
        self.fName = StringVar()
        self.lName = StringVar()
        self.DOB = StringVar()
        self.email = StringVar()

        #MySQLdb Variables
        self.connection = connect("localhost", "root", "", "test")

        self.setupGUI()

        self.root.mainloop()

    def setupGUI(self):

        #Title/Header
        title = Label(self.root, text="DataBase Test", fg="Black")
        title.pack()

        #Input Fields
        fNameLab = Label(self.root, text="First Name: ", width=14, fg="steelblue")
        fNameLab.pack()
        fNameEnt = Entry(self.root, textvariable=self.fName, width=14, bg="gray")
        fNameEnt.pack()

        lNameLab = Label(self.root, text="Last Name: ", width=14, fg="steelblue")
        lNameLab.pack()
        lNameEnt = Entry(self.root, textvariable=self.lName, width=14, bg="gray")
        lNameEnt.pack()

        dobLab = Label(self.root, text="DOB (YYYY-DD-MM):", width=18, fg="steelblue")
        dobLab.pack()
        dobEnt = Entry(self.root, textvariable=self.DOB, width=14, bg="gray")
        dobEnt.pack()

        emailLab = Label(self.root, text="E-Mail Address:", width=20, fg="steelblue")
        …
0
Hi, this is my code:

def top_three(lista=[2,4,6,8,10,12]):
    sorted(top_three)
    print(top_three=lista[-3:])

Note: this is intended to be a function. Its purpose is to return or print the three largest values. First, my purpose is that the user type the values, but if I do this I get more errors.
0
s= 70
if (s < 50):
    print ('you failed')
else (s > 50):
    print ('great, you passed')

File "<ipython-input-21-b663449d306a>", line 4
    else (s > 50):
         ^
SyntaxError: invalid syntax
0
Hello there,

I wrote a small Python script to send email and push notifications.

It clearly needs the user to store his email user and password and his push services access data.

How can I secure this data in a good way?

At the moment being I save the user and pass on a separate file and make that file readable only by the user that will run the script.

Is this sufficient?

Thanks for your time and help
1
I am doing a loop using Python3 and BeautifulSoup4 and I want to be able to print out the next 10 lines after I found a word in the output.  I am using find_all to pull our all the text in the TR tag.  I mainly want the text in the TD tag, but what I have seems to be giving me what I want.  If I can improve, suggestion are always welcomed

But my first issue is just getting it to print when I found the word I am looking for.  If I remove the IF statement, then I can see I am getting all the text I want.

Here is what I have so far.

from bs4 import BeautifulSoup
import requests

 
url = 'http://www.somewebsite.com'
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, 'html.parser')


for table in soup.find_all('tr'):
    if table.text == 'Actuals':
        print(table.text)

Open in new window




Thank you
0
mylist = []

mylist

mylist.append ('0,1,2,3,4,5')

mylist

and then if I want to reverse it,

mylist.reverse ()
mylist

I don't get an output.
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.