using python to parse colon (:) delimited string to an object

i have a string which is a return value of REST API ( and is using colon seperated key/value pairs. id: 123414 name: Peter message: bla bla bla bla How can i parse this string to an object? is there an existing python parser that i can use?? Here's the string that i want to parse: 'RT/3.8.8 200 Ok\n\nid: ticket/46863\nQueue: customer-test\nOwner: Nobody\nCreator: young.park\nSubject: testing\nStatus: new\nPriority: 0\nInitialPriority: 0\nFinalPri

Catch gaierror in Django / Python?

How do I properly catch a gaierror in Django or Python? This error is brought up when a request to a 3rd party API is made and no connection can be made. I tried a try with an empty except but the gaierror was not caught. Advice? Thanks!

Pause Python Generator

I have a python generator that does work that produces a large amount of data, which uses up a lot of ram. Is there a way of detecting if the processed data has been "consumed" by the code which is using the generator, and if so, pause until it is consumed? def multi_grab(urls,proxy=None,ref=None,xpath=False,compress=True,delay=10,pool_size=50,retries=1,http_obj=None): if proxy is not None: proxy = web.ProxyManager(proxy,delay=delay) pool_size = len(pool_size.records) wo

Python Identical shebang not working

So I'm trying to create some scripts that I want to run without manually specifying the interpreter each time I run it. #!/usr/bin/python Above is the shebang on an existing script that runs like I want it to. Below is the shebang of a script I wrote from scratch #!/usr/bin/python To me they look identical, but running the second one gives me a permission denied Both have been created using kate, utf-8 and unix lines. Both are identical to me. Any ideas?

Python PyCrypto RSA Blind and Unblind

I am trying to perform blinding and unblinding on a hash. Following: I have: messageHashed ='MyMessage').digest() print 'Message MD5:%s' % messageHashed blindSigned = loadedPublic.blind(messageHashed,123) print 'Blinded: %s' % blindSigned blindSigned = loadedPrivate.sign(blindSigned,loadedPrivate.n) print 'Blinded Signed: %s' % str(blindSigned) unblind = loadedPrivate.unblind(blindS

Python (Matplotlib) - show multiple figures (plots) with an x and/or y offset (so without overlapping)

I'm trying to show multiple figures at once, but with an offset so I don't have to move the first figure to check that it showed all the figures (plots). So here's an example: from pylab import * figure(0) plot() figure(1) plot() show() These figures are shown on top of each other, but I want them to look like this when I run my program: EDIT: Any suggestions?

Python D-Bus and Tkinter main loop integration

I have a Python app that uses Tkinter GUI and Twisted. Twisted has support for a Tkinter main loop, so the two are working together nicely. Now I'd like to add some D-Bus code into the app. But looking at the docs, I can't see how to integrate D-Bus into the Tkinter main loop. The Python D-Bus tutorial says it has main loop support for: glib main loop Qt main loop What would be involved in making Python D-Bus work with a Tkinter main loop?

Python ImportError: Could not import settings (Is it on > sys.path? Is there an import error in the settings file?) on AWS Elastic Beanstalk

This seems to be a common problem, but still none of the answers to the replies so far have worked for me. Django:1.6.2 Python:2.7.5 I am trying to deploy a Django application on AWS Elastic beanstalk. My current Django project structure is- requirements.txt .ebextensions |-myproject.config myproject | | | |-settings | (all common settings param) | (to select which of production or development settings to choose) |-prod

Stop ConfigParser adding spaces to delims after upgrade from python 2.7.3 to 2.7.9

After being forced to use a later version of python, ConfigParser now insists on adding spaces to each side of any delims when modifying a configuration file. e.g. setting=90 becomes: setting = 90 This was not the behavior in the earlier version, and I cannot find a way of controlling this behavior, can anyone help? My test code looks like this: import ConfigParser import os config = ConfigParser.ConfigParser() cfgfile = '/home/osmc/bin/test/config.txt' os.system('sudo echo "[section]"

How can i use a different file and make it used in a other ?? (Python)

I'am new to python, and im trying to get the user to input their message through a file that will be encrypted or decrypted. I have tried to research on how i could do it but i'am lost to what to do ! Here is my code: print("Welcome! Would you like to encrypt a message or decrypt message ? ") print("1. encrypt message") print("2. decrypt message") print("3. exit programme") print("Selection 1 or 2 or 3? Please enter your selection:") while True: choice = int(input()) if choice == 1:

Python PyCharm Vagrant SSH custom command

I have ran successfully a Django application(which I made myself, following the official Django tutorial) in PyCharm using Vagrant. I set custom remote Python interpreter then created a custom Django run configuration. If I were to run it without PyCharm I'd do this: vagrant up vagrant ssh cd /vagrant/project python runserver It all worked perfectly and made it possible to debug the application with PyCharm. Now, I've been given a real code and a real application. I ca

type error python unhashable type

I am trying to get the difference between dict1 and dict2 but i keep getting error any help? ret = {} third_value_list =[0,1] for i in third_value_list: #print i num_list = [1,2] val_list = [0,1] dict1 = dict((k, [v]+[i]) for (k, v) in zip(num_list,val_list)) print dict1 num_list2= [1,2] val_list2 = [0,6] dict2 = dict((k, [v]+[i]) for (k, v) in zip(num_list2,val_list2)) print dict2 if set(dict2.items()) - set(dict1.items()): print 'true' a = set(dict

Python Best way to handle flask POST unit test

I have the following code, that accepts a POST request and processes it. @app.route('/route', methods=['POST']) def route_post(): try: data = request.get_data() j = json.loads(data) except Exception as e: ... Basically, I want access to request.get_data() so I can change the value. I'm invoking the test as shown below, which is dead simple. def test_route(): assert(("Bad Request\r\n", 400) == route_post()) But doesn't allow me to

Strange Python Scope Issue

I thought that I understood Python variable scope pretty well, but then I ran into this code today. from __future__ import print_function def main(): v_Matrix =[[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(v_Matrix) print() f_Rotate(v_Matrix) print(v_Matrix) hh = 3 f_This(hh) print(hh) def f_Swap(v_Matrix, r1, c1, r2, c2): v_Matrix[r1][c1], v_Matrix[r2][c2] = v_Matrix[r2][c2], v_Matrix[r1][c1] def f_Transpose(v_Matrix): for r

Python How to run a cancellable function when a new Tkinter window opens

In tkinter, I would like to create the following: When the button foo is pressed, the function foo begins running immediately. A new window will pop up with a a "cancel" button that lets the user terminate the process midway through (as my actual process can take up to 30 minutes). If foo runs to completion, the window closes itself and notifies the user that the process completed. Here is code that demonstrates my toy problem: from tkinter import ttk, messagebox, Toplevel, Tk import time i

How to compile my python code in cython with external python libs like pybrain

I need more perfomance running my neural network, so I thinked that building it with cython will be good idea. I am building my code like this: from distutils.core import setup from Cython.Build import cythonize setup( ext_modules = cythonize("my_code.pyx") ) But will it build external python files that I use? Like pybrain, skimage and PIL in my case. If not, how to force cython to build them.

Error reinstalling python3 in ubuntu 16.04

I am using ubuntu 16.04 and I removed the preinstalled python3 and want to install it again. However, I'm getting an error when using sudo apt-get -f install python3 : Reading package lists... Done Building dependency tree Reading state information... Done python3.5 is already the newest version (3.5.2-2~16.01). python3.5 set to manually installed. The following packages were automatically installed and are no longer required: dictionaries-common emacsen-common gir1.2-appindicator3-0.1

Python - Low Level USB Port Control

I want to make a simple python program, which controls my laptop's usb hubs. Nothing extra, just put first usb port's DATA+ channel into HIGH (aka 5V) or LOW (aka 0 V) state.

python fit_transform index error for large dataset

I am doing text classification on sentiment analysis, where I have a large training set and test set test_data_df.shape (46346, 2) train_data_df.shape (69518, 2) The first column of train_data_df is label, which has value 1 if email is a personal attack and 0 if not. The second column of train_data_df is comment, which is the email content. However, when I try to use fit_transform to transform corpus into feature vectors, I got corpus_data_features = vectorizer.fit_transform(

how to avoid repeated calls to init when passing a subclass to inherit in python

consider class class Grid(): def __init__(self,r,z,t): self.rgrid = r self.zgrid = z self.tgrid = t self.otherstuff = long_computation(r,t,z) class Solution(Grid): def __init__(self,r,g): self.zones = r Grid.__init__(self,g.r,g.z,g.t) g = Grid(my_r,my_z,my_t) sol = Solution(r,g) This creates what I want, except the "long_computation" is done twice. What would be a clean way to structure the classes that would work whether I called just

Is it bad practice to mix OOP and procedural programming in Python (or to mix programming styles in general)

I have been working on a program to solve a Rubik's cube, and I found myself unsure of a couple of things. Firstly, if I have a bunch of functions that have general applications (e.g., clearing the screen), and don't know whether or not I should change them to methods inside of a class. Part of my code is OOP and the other part is procedural. Does this violate PEP8/is it a bad practice? And I guess in broader terms, is it a bad idea to mix two styles of programming (OOP, functional, procedural,

Python Splitting a pandas column into two keeping the original column in place

I have a dataframe that I need to split into two columns keeping the original column in place. import pandas as pd df = {'assigned_to': [ {'display_value': 'Michael', 'link': ''}, {'display_value': 'Vinod', 'link': ''}, {'display_value': 'Vinod', 'link': ''}, {'display_value': 'Carrie', 'link': ''}, {'display_value': 'Carrie', 'link': ''}]} df = pd.DataFrame(df) Currently I'm tr

resetting iteration over dictionary python

I want to implement a code that will reset the iteration over a dictionary given a condition inside the current iteration. It should look something like this for index in range(1, max_index): for phrase in rules: for constituents in rules[phrase]: if mem_list[-index:] == constituents: del mem_list[-index:] mem_list.append(phrase) # reset all of the three for loops The variables are as follows: index: integer that is dec

Python Where does query.filter code go in a Flask-AppBuilder view?

Lets assume we have the following simple view in Flask-AppBuilder : class Table_AView(ModelView): datamodel = SQLAInterface(Table_A) label_columns = {'Field_A':'A'} list_columns = ['Field_A'] We want the column listing all the data from Field_A to return all the fields equal to "some text". Assuming the query below is correct where in our code above would we place this line of code to achieve the desired result? result = session.query(Table_A).filter_by(Field_A = 'some text').al

Python Django how to sum the scores of single user for different activities and display in front end only total score

i am posting my from django.db import models from django.contrib.auth.models import User class Activity(models.Model): activity = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True) score = models.IntegerField(default=0) def __str__(self): return self.activity class Name(models.Model): name = models.CharField(max_length=30) designation = models.CharField(max_length=1

Python how to fix "TypeError: main() takes 0 positional arguments but 1 was given"?

I've been trying to convert image labels that have been saved as .csv to the tensorflow.record format for object recognition. I'm fairly new to both tensorflow and using stackoverflow, please excuse my etiquette if it is out of place. This is the code that I am using from __future__ import division from __future__ import print_function from __future__ import absolute_import import os import io import pandas as pd import tensorflow as tf from PIL import Image from object_detection.utils import

Python How to stop parameters from changing after painting on an image?

The program that I’m trying to write gets some input and has to insert images into cells according to the input(which are parameters for a square). It has an add button which, after you change the parameters, inserts another row with the information + image. I have a QPainter which paints the parameters next to the square/image everytime someone changes them. The problem is that when the parameters are changed, all the images are changed and I want only the last one to be. This is a part of m

Python define path to a file in my google drive in a colab notebook

I'm just starting with python and I'm trying to adapt a code from a colab notebook that is : path_to_zip = tf.keras.utils.get_file( '', origin='', extract=True) path_to_dataset = os.path.join( os.path.dirname(path_to_zip), "cornell movie-dialogs corpus") path_to_movie_lines = os.path.join(path_to_dataset, 'movie_lines.txt') path_to_movie_conversations = os.path.join(path_to_datase

Python How to get the shortest path in a weighted graph with NetworkX?

I'm trying to get the shortest path in a weighted graph defined as import networkx as nx import matplotlib.pyplot as plt g = nx.Graph() g.add_edge(131,673,weight=673) g.add_edge(131,201,weight=201) g.add_edge(673,96,weight=96) g.add_edge(201,96,weight=96) nx.draw(g,with_labels=True,with_weight=True) to do so I use nx.shortest_path(g,source=131,target=96) The expected answer is 131,201,96 because for that path I have the least sum of weights. I'm getting 131,673,96 instead. I tried c

Python cursor.fetchone() returning None after attempting to insert?

I have a table in an SQLite3 Database that looks like this: CREATE TABLE "user" ( "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, "discriminator" TEXT NOT NULL, "userid" INTEGER NOT NULL UNIQUE, "username" TEXT NOT NULL, "matches_played" INTEGER NOT NULL, "match_wins" INTEGER NOT NULL, "match_losses" INTEGER NOT NULL, "match_draws" INTEGER NOT NULL, "rating" REAL NOT NULL, "plays_game" INTEGER, FOREIGN KEY("plays_game") R

Python Is it possible to add a postgresql trigger to notify my Django app when a table changes?

My Django app connects to a PostgreSQL 9.x database. To this database, a legacy Java app is connected, too. So two different apps use the same database. Is it possible for PostgreSQL to notify my Django (2.2.x) app when a table changes? I know that I can create a cron job to check on tables on a timely basis, but the Server administrator does not let me do cron jobs (why?) and the Java guy is too busy on other things to do code rewiring (so I can't ask him him to send me url requests after tab

Python TensorFlow 2.1 returns Warnings when loaded from terminal and Error when loaded from Jupyter

I have installed tensorflow 2.1.0 in a virtualenv on my home laptop (Ubuntu 18.04). When I import tensorflow as tf from terminal I get the following warning: 2020-03-12 12:17:56.485098: W tensorflow/stream_executor/platform/default/] Could not load dynamic library ''; dlerror: cannot open shared object file: No such file or directory 2020-03-12 12:17:56.485179: W tensorflow/stream_executor/platform/default/] Could

how can I get a specific element in json with python

I want to access a specific element with python, but I can't import json import requests search_book = str(input("search a book: ")) request = requests.get("" + search_book) request_text = request.text data = request_text print(data['items']['volumeInfo']['title']) the mistake is: Traceback (most recent call last): File "C:/Users/ddvit/Documents/programming/python/books/", line 9, in print(data['items']['volumeInfo']['t

Integrate python appium with robot framework (passing Appium driver to multiple python definitions)

No keyword with name error using python appium with Robot Framework. I am new to this appium Library and started learning the integration with Robot Framework with Python appium Library. Really Appreciate your response . import appium from AppiumLibrary import AppiumLibrary class Android(AppiumLibrary): def __init__(self): """ Initializing all the Android definitions """ pass def get_driver_instance(self): return self._curre

Getting all values from an Enum, when values are callables in Python 3.7

I have an Enum class in Python 3.7 defined as such: # activation functions def relu(x: float) -> float: return x * (x > 0) def sigmoid(x: float) -> float: return 1 / (1 + math.exp(-x)) class Activation(Enum): SIGMOID = sigmoid RELU = relu def __call__(self, x): return self.value(x) @classmethod def values(cls): return [function.value for function in cls] I have tried some approaches from other similar questions online, like list(Activ

Python Pygame Window is black

I am writing a simple mandelbrot renderer. After the program calculates and draws everything, it saves the surface and blits it. This worked fine, but after I added the update display function, it only shows a black screen. I will need to update every iteration because I will add some text and other things. I only included the important parts of the program. Does anyone know why this is happening? def keys(): #Recognises key-presses global x global y global zoom global mdb g

Logging as JSON lines with python

I have developed a function to create log files with python into JSON line files: import logging import sys from datetime import datetime def log_start(log_prefix): now = log_id = str(now).replace(':', '').replace(' ', '').replace('.', '').replace('-', '')[:14] log_name = '/mnt/jarvis/logs/{}_{}.txt'.format(log_prefix, log_id) root = logging.getLogger() if root.handlers: root.handlers = [] logging.basicConfig(level=logging.INFO, filename=log_nam

Python How to use multiple conditions in a for loop in a function?

I'm still new to python and have just started learning. The task given is to find the amount of punctuation, vowels, and constants in a given text. But whenever I run the code it just gives me a 0. def getInfo(text): pun = [".", ",", " ", "\'", "\"", "!"] vowels = ["a", "e", "i", "o", "u"] count = 0 count2 = 0 count3 = 0 for char in text: if char in

How do I execute Python file from SQL Server?

I wrote a Trigger in SQL Server such that if values in one table updates, the trigger updates values in another table. I want a python script to kick off and push that updated data to SharePoint. I searched online but couldn't find anything that calls a Python script or ways to execute Python script right upon completion of a trigger. I know I can schedule the script but is there a way to kick off a job in SQL Server upon completion of a trigger? Thanks

Converting Text Tables Into CSVs in Python

I'm looking to convert tabular data into CSVs, but I'm hitting a roadblock when the table has rows with certain missing values. Input looks like the following table, systemd 1 root cwd DIR 8|1 4096 2 / systemd 1 root rtd DIR 8|1 4096 2 / systemd 1 root txt REG 8|1 1612152 101375 /lib/systemd/systemd systemd 1

How to check OCSP client certificate revocation using Python Requests library?

How do I make a simple request for certificate revocation status to an EJBCA OSCP Responder using the Python requests library? Example: # Determine if certificate has been revoked ocsp_url = req_cert.extensions[2].value[0].access_location.value ocsp_headers = {"whatGoes: here?"} ocsp_body = {"What goes here?"} ocsp_response = requests.get(ocsp_url, ocsp_headers, ocsp_body) if (ocsp_response == 'revoked'): return func.HttpResponse( "

Python Truncate the strings in a dataframe column using the integers present in another column

Basically I'd like to perform a string manipulation on the elements in one column using another. Here's some basic code to set up an example: from random import seed,choices,sample,choice from string import ascii_letters import pandas as pd seed(1) strings = ["".join(choices(list(ascii_letters),k=4)) for i in range(10)] values = [choice(range(4)) for i in strings] df = {"strings":strings,"values":values} df = pd.DataFrame(df) And here's the output: I want to man

Python Airflow read the trigger dag dag_run.conf content

I am new to Airflow.I would like read the Trigger DAG configuration passed by user and store as a variable which can be passed as job argument to the actual code. Would like to access all the parameters passed while triggering the DAG. def get_execution_date(**kwargs): if ({{kwargs["dag_run"].conf["execution_date"]}}) is not None: execution_date = kwargs["dag_run"].conf["execution_date"] print(f" execution date given by user{execut

Storing a python script output to a variable in linux and run a wget command

So I made a python script that retrieves a url link and returns it as an output. Just to keep it simple, the content of the python script would be just: print("") For example, if i execute the python script in my terminal: python it outputs: So I then would like to utilize the "wget" command in linux with the url that is returned by my python script, so that i could d

Parse file up to a certain content in Python

I have a file that contains names and numbers. Ex: 25 27 90 Robert 34 Liam What I want to do is to add all the numbers before the name and store them along with the name they are assigned to. I wanted to make it a little like a tuple list. For example for the name Robert, you should get (142, Robert). Any suggestion?

  1    2   3   4   5   6  ... 下一页 最后一页 共 6311 页