Questions tagged [python-2.7]

Python 2.7, the final major release in the 2.x series, ceased receiving official support as of January 1st, 2020. It is advised to employ the generic [python] tag when posting Python-related queries. However, attaching this tag solely to indicate your version of Python is unnecessary unless the inquiry specifically pertains to Python 2.7.

Searching for precise string delimited by spaces in Python

Unique Example: words_to_check = ['dog', 'cat', 'bird chirp'] full_word_list = ['doggy dog cat', 'meow cat purr', 'bird chirp tweet tweet', 'chirp bird'] for word in words_to_check: print(list(map(lambda x: re.findall(word, x), full_word_list))) Aft ...

Trying to combine three columns in CSV and then updating the original CSV file

Here is some sample data: name1|name2|name3|name4|combined test|data|here|and test|information|343|AND ",3|record|343|and My coding solution: import csv import StringIO storedoutput = StringIO.StringIO() fields = ('name1', 'name2', 'name3', 'name4', ' ...

Parser for arguments that includes an optional parameter within a mutually exclusive group

My goal is fairly straightforward - I want to have two options that are mutually exclusive: -p and -c. These options may or may not include an argument. The objective is to do th...is with an optional argument or do th...at without one. This is the code sn ...

The strategic placement of the modulo operation within a programming algorithm

I've been grappling with a certain problem that ultimately boils down to calculating the value of https://i.stack.imgur.com/ovS3p.png (n+m-2 Combinations m-1). Here's what I have so far. In situations where the result exceeds 10^9+7, I must output my_ans ...

Python-based Selenium WebDriver

Assistance required in retrieving the value from a specific tag. Provided below is the element along with its xpath The element: <a href="/pages/viewpage.action?pageId=37129112">Sprint1 AC/AT's</a> xpath: .//*[@id='content']/div[5]/ul/li/ul ...

Encountering an error when trying to switch between tabs and close a tab in a window

Currently, my code is designed to perform a sequence of actions: open a window, navigate to a link on the page, extract some data from that page, and then close the tab. However, I am encountering an issue with closing the tab after completing these step ...

Eliminate duplicate elements in various lists (compress multiple lists) based on their values

If I have a collection of lists: [[0,0,0,1,2,3],[0,0,0,4,5,6],[0,0,0,0,7,8],[0,0,0,0,0,9]] I am looking to create a new list where common null, zero, or specific values are removed from each inner list to achieve the desired output: [[1,2,3],[4,5,6],[0, ...

Identifying the sources of temporary files generated by my Python code: a guide

When working on my Python code, I utilized various libraries such as pathos, arcpy, and numpy. However, I have noticed that each time I run the code, approximately 0.5 GB of free space on my C drive decreases, even though the Python file itself is located ...

Unable to get json.dumps() function to function properly

import json def serialize_json(name, type, filepath): data = [] data.append({ 'name': name, 'type': type }) with open(filepath, "w") as file: json.dumps({'profile_info': data}, file) ...

What is the best way to create a Python program that automates clicking a specific link?

My program is designed to take user input and search a specific webpage. Once the desired link is located, I want it to navigate to that page and download the file available there. For example: The webpage: The search term: "1AW0" After performing a se ...

Issue with invoking Selenium module

Currently, I am attempting to create a script that will log into a website and click a button without the need for opening a browser. However, every time I try to set up my selenium remote case, I encounter an error stating 'module' object is not callable. ...

Leveraging the power of bash to execute a python script

I wrote a python script that takes a .txt file as input and produces another .txt file as output. My goal is to create a bash script that I can simply click on from my desktop to run the python script. This is what I have done so far: #!/bin/bash cd /Des ...

Chaco dynamically updates plot ranges

I am working with a series of dynamically updated chaco plots using a timer object. My goal is to set the Y (referred to as "value" in chaco) limits when the data changes. Upon initializing the plot object, I call: obj.alldata = ArrayPlotData(frequency=f ...

Is it possible to invoke a Python local function from an HTML document?

After creating a Python file with multiple functions, I am now working on designing a web page where I aim to trigger one of the functions mentioned earlier by clicking a button. However, I am unsure about how to go about this process. Is there anyone who ...

Python 2.7 does not support the use of the newline function

After crafting a Python script to format a text file for SQL importation, I discovered that it perfectly runs with python 3.5. However, when attempting to execute the script with python 2.7 (as required), an error is thrown which reads: TypeError: 'newline ...

Tips for extracting user stories from a project using Pyral

I am attempting to retrieve all the UserStories associated with a specific Project (let's say project 'Bolt' in workspace 'ABC'). Once I establish the connections (using username, password, and server) and set my workspace to the ...

Exploring the world of Python and Selenium with questions about chromedriver

I am planning to share my Python program with others and I would like to convert it into a .exe file using py2exe. However, I encountered an issue while using Selenium. chrome_path = r"C:UsersViktorDesktopchromedriver.exe" If users do not have the sa ...

Encountered issue while transferring the result of urllib.urlopen to json.load

Trying to learn Python and utilizing urllib to download tweets, I encountered a recurring error while following a tutorial. Here is the code snippet causing the issue: import urllib import json response = urllib.urlopen("https://twitter.com/search?q=Micro ...

Python AssertionError: The argument passed to the write() function in GAE must be a

Currently, I am utilizing Sublime Text 2 as my primary editor to develop a brand new Google App Engine project. UPDATE: While testing this code via localhost, I encountered an issue when accessing the app on appspot: Status: 500 Internal Server Error ...

Extracting information from dynamically generated tables using Python 2.7, Beautiful Soup, and Selenium

I am in need of assistance with scraping a JavaScript generated table and saving specific data to a csv file. The tools available to me are limited to python 2.7, Beautiful Soup, and/or Selenium. Although I have referred to the code provided in question 14 ...

How can I specifically extract data from certain columns in an HTML table using BeautifulSoup? Currently, my code is pulling data from every column

I need help extracting specific data from an HTML table. I want to extract the information from the columns with the text "Total" and the value "93" only, rather than extracting all column data as my current code does. For example, the current output is: ...

Python's interactive shell offers the capability to easily write and export data to a local file

For example, let's say I have a dictionary: >>> gtf['mykey1'] {'name': {'apple': '20', 'eat': ['Leo', 'Amy', 'Lily', 'Lucy']} I am looking to save th ...

Python Selenium: Variable encoding gets altered by XPath

I am facing an issue with my code that uses XPath to search through text. The problem arises when the text being searched contains special Latin characters like ñ or í. After encoding the text, it displays correctly when printed. However, the issue occu ...

Guide on extracting JSON data from a POST request in cherrypy using Python 2.7

I'm attempting to learn how to handle JSON POST data in Python 2.7 with a cherrypy setup that can serve both html and json content Here is the script I'm using to send a sample JSON request: import urllib2 import json def mytest(): d = { ...

Is there a way to utilize Selenium in Python to click on numeric buttons with the onclick event?

Here is the HTML code I am working with: <ul aria-hidden="false" aria-labelledby="resultsPerPage-button" id="resultsPerPage-menu" role="listbox" tabindex="0" class="ui-menu ui-corner-bottom ui-widget ui-widget-content" aria-activedescendant="ui-id-2" a ...

Analyzing two sets of data to identify unique pairings

I am currently working on comparing two lists that have varying sublists sizes, and I need to find pairs (enclosed in round brackets) that are present in one list but not the other. Check out the code snippet below: s1 = [ [('RESOLVED - DUPLICAT ...

Is Python 2.7 still on my Mac? How can I check if Python 3.3 installation removes the older version?

Is it possible that there are concealed files lingering around? And is a re-installation of Python 2.7 necessary in order to use it? Appreciate your help! ...

Issues with SocketIO message reception in JavaScript

My current project involves setting up a FlaskSocketIO with socket.io.js application to facilitate real-time communication between the frontend and my web socket server. Here is a snippet of the frontend code: $(document).ready(function() { name ...

Retrieve the value from a checkbox using Flask and then transfer the extracted data to a different template

I am currently working with Weasyprint to showcase some Jinja templates within a Flask Web App. Here is the JSON data I am using: value=["1","2","3","4"] My goal is to pass the 'value' variable to another Jinja template within an if statement. {% if (v ...

Is it possible to execute various actions in Python unittest based on the outcome of the test?

How can I adjust my python unittest module to execute specific actions depending on the outcome of the test? My scenario involves running automated selenium webdriver tests, and I want to be able to take a screenshot in case of any failures or errors. ...

Converting JSON arrays into Python lists

I am encountering difficulties in parsing a JSON array I created into a Python list. Despite my efforts, I have not been successful in achieving this. Is there a way to convert my JSON array into a Python list? The structure of the json data I want to pa ...

How can a unique identifier be defined and effectively utilized for selection purposes?

I'm utilizing Selenium to automate a task on a website, and I'm facing a challenge in selecting an item using the following: select = driver.find_element_by_*whatever* Unfortunately, the available whatevers like find_element_by_id, by name, by tag name, ...

Guide to using a boolean operator effectively while evaluating a string within an if-condition

When I need to verify if different parts of a string are in a value, it seems that I must specify the value for each part of the string in order for it to work correctly within an if statement. It appears that the correct method is the one utilized in my ...

Is "pass" equivalent to "return None" when using Python?

I've recently started delving into the realm of Python coding, and I have a question for you: Code def Foo(): pass def Bar(): return None Usage a = Foo() print(a) # None b = Bar() print(b) # None Question: 1. Despite having return None, ...

Choosing a versatile model field in a Django CMS plugin

Currently, I am developing a Django CMS plugin that includes a model choice field dependent on another field in the form. To update the choices in the model choice field based on the trigger field selection, I am using AJAX. However, when submitting the fo ...

What is the best way to create an executable file from a Python package using pyinstaller?

I have developed a Python command line program that is open source and compatible with Python 2.7, Python3+, and works across different platforms. My goal now is to package this program into an executable for my Windows users in a more user-friendly way. ...

Condense Python Dictionary to Boolean Values

Imagine having a Python dictionary with nested dictionaries to any level and a mix of keys representing boolean choices and others that don't. For example: {'Key1': 'none', 'Key2': {'Key2a': True, 'Key2b& ...

Guide on implementing argparse in Python with the use of abstract base class

Recently, I've begun exploring Python and am interested in using a Parser for handling command line options, arguments, and subcommands. I want my command structure to resemble the following: If storing in S3 or Swift: $snapshotter S3 [-h] [-v] --a ...

Exploring the tarfile library functionality with unique symbols

I am encountering an issue while trying to create a tarfile that contains Turkish characters like "ö". I am currently working with Python 2.7 on a Windows 8.1 system. Below is the code snippet causing the error: # -*- coding: utf-8 -*- import tarfile im ...

Encountered an OverflowError when attempting to solve the problem of calculating the total number of subsets without consecutive numbers

I'm currently working on solving a challenge in TalentBuddy using Python Here is the problem statement: Given an integer N, you need to find the total number of subsets that can be created using the set {1,2..N}, ensuring that none of the subsets conta ...

Using IronPython to make a POST request with JSON data

Currently, I am working on coding in IronPython and facing an issue while attempting to send an HTTP POST request to the server with JSON in the request body. To achieve this, I am utilizing the C# method: HttpWebRequest. Despite knowing that there are mor ...

`isinstance isn't returning any output`

I am facing an issue where my code does not display any output when using isinstance. This problem is highlighted at the end of the code snippet. I attempted to input year 1 and tla_2=1, yet no output was generated. Could the issue lie with my isinstance s ...

Leveraging BeautifulSoup for extracting information from HTML documents

I'm working on a project to calculate the distance between Voyager 1 and Earth. NASA has detailed information available on their website at this link: ... I've been struggling to access the data within the specified div element. Here's the code for the div ...

Differences between Local and Global importing in Python

Is there a way to force my interpreter (2.7) to import a module from site packages in case of a conflict? Let's say you are working with a directory structure like this: top_level ----cool_mod ----init.py ----sweet_module.py You already have swee ...

invoking the parent class in a subclass in Python version 2.7

Recently, I've been delving into the world of OOP in Python and trying to grasp some basic concepts. One question that popped up was related to subclassing a class like list and how to properly invoke the parent constructor. After experimenting a bit, ...

Definition of a 3D array in Python 2.7

I attempted the following approach but it appears to be ineffective. If numpy is not an option, what would be the correct alternative? Appreciate your help. y = [[1]*4 for _ in range (4) for _ in range(4)] Thank you in advance, Alice ...

Error: The specified element is not found in the list when attempting to remove it, although it actually exists within the

I am currently going through the O'Reilly book "Exploring Everyday Things in R and Ruby" and my task is to convert all of the Ruby code into Python. I started with a model that determines the number of bathrooms required for a building, and here's the code ...

There appears to be an issue with generating an HTML report using nosetests in Python as the option `--html--

Hi there, I'm having some trouble with my Selenium Python regression test script. My HTMLTestRunner isn't working as expected for generating the test report, so I decided to give the Nose plugin a try instead. I've gone ahead and installed Nose, as well a ...

Efficiently removing and re-adding elements in a list in Python based on a specific condition

I have a list of URLs to crawl. ['','', ''] Here is the code snippet: prev_domain = '' while urls: url = urls.pop() if base_url(url) == prev_domain: urls.append(url) continue else: cr ...

What is the best way to insert a priority queue in this particular format?

Consider an array with 5 elements: [4, 8, 1, 7, 3]. These elements need to be inserted into a max-priority queue. Starting with an empty priority queue, the first element inserted is 4. Next, when 8 is inserted, it becomes the new front element since it is ...

Converting bytes into encoded strings in Python 3

Presently, my Python 2.7 code is set up to handle <str> objects received over a socket connection. Throughout the codebase, we heavily rely on <str> objects for various operations and comparisons. Transitioning to Python 3 has revealed that soc ...

Tips for efficiently zipping lists of varying sizes

I currently have 3 different lists. >>> list1 = [1,2,3,4,5] >>> list2 = ['a','b','c','d'] >>> list3 = ['x','y','z'] Is there a Python function that can zip these lists together without leaving any elements out? I am looking for ...

ERROR: Cannot call the LIST object

https://i.stack.imgur.com/jOSgE.png Can someone assist me in resolving this issue with my code: "I'm getting an error message saying 'TypeError: 'list' object is not callable'" ...

"Creating a mock method in a test file located in a separate directory using Python

Encountering challenges while trying to mock a method, as the mock function is actually overwriting it. In app/tests/test_file.py we currently have the following unit test: @mock.patch('app.method', return_value='foo') def test(self, ...

Develop a script that filters the load information and stock market data contained in target.csv for specific subsets

Create a program that extracts specific data subsets from the target.csv file related to stock market information. Load the contents of target.csv into a variable named 'target'. From the 'target' data, create a new dataframe called &ap ...

Python Requests encountered an error with too many redirects, surpassing the limit of 30 redirects

I attempted to scrape data from this webpage using the python-requests library. import requests from lxml import etree,html url = 'http://www.amazon.in/b/ref=sa_menu_mobile_elec_all?ie=UTF8&node=976419031' r = requests.get(url) tree = etree.HTML(r.te ...

Port Scanner Script Malfunctioning

I'm feeling quite perplexed as to why my script is not functioning properly. This particular script is designed to search for servers with port 19 open (CHARGEN). You need to input a list of IPs in the following format: 1.1.1.1 2.2.2.2 3.3.3.3 4.4.4.4 5 ...

Formatting blocks of data using xlsxwriter in Python with loop iterations

My goal is to impress my colleagues at work by creating a spreadsheet (.xlsx) using Python, even though I am still relatively new to the language. Can someone help me figure out how to format specific cells in my code using xlsxwriter? In the snippet bel ...

How can I determine the smallest word value among multiple files using Python?

I have a collection of 1000 .txt files, each containing data that I need to process using the following code. My goal is to identify the largest value associated with ENSG in each file and remove any other occurrences of ENSG with values lower than the hig ...

Downloading files automatically from a webpage

Seeking a way to automatically download a file from a website, as the current manual process is cumbersome. Each time involves logging in, navigating to the file, and clicking download. If anyone has advice on automating this task using tools like MS DOS ...

My Python script utilizing Selenium is failing to execute

Why is the loop not functioning correctly after opening the initial element based on the xpath? I keep receiving the following exception: raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: Una ...

What is the method for "raw text" a variable in Python?

When opening a workbook using openpyxl, I typically use the following code: wb = load_workbook(r'seven.xlsx', data_only=True) However, there are times when the name of the spreadsheet is not known in advance, requiring me to modify the hardcoding to acco ...

Flash player is not compatible with PhantomJS on Windows devices

I am currently working on a project where I need to capture screenshots from multiple websites using a Python script. To accomplish this task, I am utilizing the following tools: - PhantomJS with Selenium - Python - Windows PC Initially, I trie ...

"Configuration options" for a Python function

Not sure what to title this, but look at the example below: def example(): """ Good """ pass If I were to print example.__doc__, it would display " Good ". Is it possible to create additional 'variables' like this for other purposes? ...

Unable to assign a default value of an object variable in an object method - Python

Using Windows 10, x64, and Python 2.7.8. I'm trying to implement the code below: class TrabGraph: def __init__(self): self.radius = 1.0 def circle(self, rad=self.radius): print(rad) test = TrabGraph() test.circ ...

Python code to find all combinations of pairs for a given function's values

I have multiple sets of coordinates and I am looking to calculate the distance between each pair. Despite being able to compute the distances, I am struggling to display the corresponding coordinate pairs in my program. import itertools import math point1 ...

Encountered a TypeError while attempting to calculate the power of a 'NoneType' and an 'int'

I tried implementing this code in Python 2.7 to generate a new number: def Algorithm(num): num = ((num**2) - 1)/4 return num However, it resulted in the following error message: TypeError: unsupported operand type(s) for ** or pow(): 'NoneT ...

Stop child classes from running inherited test methods

I currently have two functional test classes set up for testing. class VehicleTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() def test_math(self): self.assertEqual(1+1, 2) class VehicleTestCa ...

Discovering the clickable widget index in pyqt4: A beginner's guide

In my application, I am working on creating multiple widget orders using a list of dictionaries to create a list of widgets. I have implemented a mouse release event for clickable widgets, but I am facing issues in identifying the clicked widget index. C ...

Bringing in a function from a library in Python 2.7

I need assistance with importing the foo function from the mod.py file. In an attempt to resolve this, I have created a new empty file called init.py within the directory C/Users/me/Desktop/NF. I also tried using __init__.py My understanding was that hav ...

Disabling the parent checkbox feature in PyGTK

I have successfully created a Treestore in pygtk, but I am facing an issue with a checkbox that I do not want to appear. It can be seen in the image below. Computer1 [ ]-----This checkbox is unwanted C drive [ ] D drive [ ] E drive [ ] Here i ...

What is the purpose of incorporating the ‘yield’ keyword into this Python autobahn code?

Why is the python autobahn example code using yield sleep(1) rather than simply sleep(1)? class Component(ApplicationSession): """ An application component that publishes an event every second. """ @inlineCallbacks def onJoin(self, d ...

Eliminate duplicate items from a list without relying on a set

Is there a way to efficiently remove all duplicate items in a list? For instance: a = [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2] I'm looking to eliminate all occurrences of the value 1, resulting in: a = [2, 2, 2, 2, 2, 2] While I attempted using a.remo ...

Exploring websites with Python's mechanize library by utilizing __doPostBack functions for

Is it possible to navigate a table on a web page using mechanize if the table uses __doPostBack functions? Here is my code snippet: import mechanize br = mechanize.Browser() br.set_handle_robots(False) br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U ...

List with dynamic substrings. Ten elements preceding the variable

I am struggling with dynamic substrings. My list can vary in size, containing anywhere from 20 to 1000 elements. I want to create a new list based on a variable number that includes elements starting from -10 up to that variable. For instance (using pseudo ...