Declare encoding in Open AI Gym implementation on Python 3 - reinforcement-learning

I am learning reinforcement learning and following this tutorial. I am trying to run an instance of CartPole-v0 environment and getting this error.
import gym
env = gym.make('CartPole-v0')
env.reset()
for _ in range(1000):
env.render()
env.step(env.action_space.sample())
SyntaxError: Non-ASCII character '\xc2' in file /home/kshitizsahay26/gym/gym/envs/classic_control/cartpole.py on line 27, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
I read that the default encoding in Python 3 is UTF-8 but it doesn't seem so in this case. I looked up at the URL mentioned in the error message but it 's applicable for Python 2.6. How should I change the encoding in this script?

I fixed this error by adding:
# -*- coding: utf-8 -*-
to the beginning of cartpole.py file

Related

Is there a way to load Python 3.6 pickle in Python 3.8?

I have a pickle file created in Python 3.6 with protocol=pickle.HIGHEST_PROTOCOL, which is 4.
with open(file_path, 'wb') as ff:
pickle.dump(data, ff, protocol=pickle.HIGHEST_PROTOCOL)
I am trying load the file in Python 3.8, where pickle.DEFAULT_PROTOCOL = 4.
with open(file_path, 'rb') as ff:
data = pickle.load(ff)
I am getting TypeError: an integer is required (got type bytes).
I tried adding different encodings to the pickle.load call (pickle.load(ff, encodings=...)) but I have no idea what is the problem with the file.
Is this some backward-incompatibility with Python 3.8?

generating items from json file in robot framework

At the moment I have a custom library to read a json file and output a list. For example
def get(f):
with open(f) as fd:
data=json.load(fd)
return [ k for k in data['d']['a'] ]
Then in RF, I call it like this
#{items}= get "f.json"
Is there a way I can do this natively in Robotframework without my custom function? I looked thru HttpLibrary but couldn't find anything relevant.
yes, it is possible. Here is how to do it without HttpLibrary, but using OperatingSystem Robot Framework Library (to open the file), and json Python library (to load the JSON):
*** Settings ***
# Import Robot Framework Libraries
Library OperatingSystem
# Import Python Library
Library json
*** test cases ***
mytest
# no need for double quote around file name. Variables are string by default
#{item} = get_in_robot f.json
*** Keywords ***
get_in_robot
[Arguments] ${file_path}
${data_as_string} = Get File ${file_path}
${data_as_json} = json.loads ${data_as_string}
# looking into the dict at ["d"]["a"] will return the list
[Return] ${data_as_json["d"]["a"]}
Hope this helps

Python error: argument -c/--conf is required

I'm new in python, my native language is C. I'm doing a code in python for a surveillance system triggered by motion using OpenCV. I based my code in the one made by Adrian Rosebrock in his blog pyimagesearch.com. Originally the code was developed for a Raspiberry Pi with a Pi Camera module attached to it, now I'm trying to adapt to my notebook's webcam. He made a easier tutorial about a simple code for motion detection and it worked very nicely in my PC. But I'm having a hardtime with this other code. Probably it's a silly mistake, but as begginer I couldn't found a specific answer to this issue.
This image have the part of the code that is causing the error (line 15) and the structure of the project on the left side of the screen. Image of python project for surveillance.
Similar part, originall code:
# import the necessary packages
from pyimagesearch.tempimage import TempImage
from dropbox.client import DropboxOAuth2FlowNoRedirect
from dropbox.client import DropboxClient
from picamera.array import PiRGBArray
from picamera import PiCamera
import argparse
import warnings
import datetime
import imutils
import json
import time
import cv2
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-c", "--conf", required=True,
help="path to the JSON configuration file")
args = vars(ap.parse_args())
# filter warnings, load the configuration and initialize the Dropbox
# client
warnings.filterwarnings("ignore")
conf = json.load(open(args["conf"]))
client = None
Until now I only change these things:
Exclude the imports relatives to pi camera.
Change camera = PiCamera() by camera = cv2.VideoCapture(0). This way I use notebook's webcam.
Exclude:
camera.resolution = tuple(conf["resolution"])
camera.framerate = conf["fps"]
rawCapture = PiRGBArray(camera, size=tuple(conf["resolution"]))
Substitute the line for f in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): by while True:.
Exclude two lines in program that was rawCapture.truncate(0).
Probably there is more things to repair, if you now please tell me, but first I'd like to understand how solve that mensage error. I use PyCharm in Windows 7 with Python 2.7 and OpenCV 3.1. Sorry for not post the entire code, but once that this is my first question in the site and I have 0 reputation, apparently I can just post 2 links. The entire originall code is in the pyimagesearch.com. Thank you for your time!
I think you probably not running it properly. Error message is clear. You are adding argument that means you need to provide them while running which you are not doing.
Check this how he ran this in tutorial link you provided
http://www.pyimagesearch.com/2015/06/01/home-surveillance-and-motion-detection-with-the-raspberry-pi-python-and-opencv#crayon-56d3c5551ac59089479643
Notice on the Figure 6 screen capture in #Rhoit's link.
python pi_surveillance.py --conf conf.json
The program was initialized with the name and these --conf conf.json words.
In your code:
ap = argparse.ArgumentParser()
ap.add_argument("-c", "--conf", required=True,
help="path to the JSON configuration file")
ap is a piece of code that reads these inputs from the commandline, and parses the information. This definition specifies that a --conf argument is required, as demonstrated in Figure 6.
The error indicates that you omitted this information:
argument -c/--conf is required

nltk pos_tag usage

I am trying to use speech tagging in NLTK and have used this command:
>>> text = nltk.word_tokenize("And now for something completely different")
>>> nltk.pos_tag(text)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
nltk.pos_tag(text)
File "C:\Python27\lib\site-packages\nltk\tag\__init__.py", line 99, in pos_tag
tagger = load(_POS_TAGGER)
File "C:\Python27\lib\site-packages\nltk\data.py", line 605, in load
resource_val = pickle.load(_open(resource_url))
File "C:\Python27\lib\site-packages\nltk\data.py", line 686, in _open
return find(path).open()
File "C:\Python27\lib\site-packages\nltk\data.py", line 467, in find
raise LookupError(resource_not_found)
LookupError:
**********************************************************************
Resource 'taggers/maxent_treebank_pos_tagger/english.pickle' not
found. Please use the NLTK Downloader to obtain the resource:
However, I get an error message which shows:
engish.pickle not found.
I have download the whole corpora and the english.pickle file is there in the maxtent_treebank_pos_tagger
What can I do to get this to work?
Your Python installation is not able to reach maxent or treemap.
First, check if the tagger is indeed there:
Start Python from the command line.
>>> import nltk
Then you can check using
>>> dir (nltk)
Look through the list to see if maxent and treebank are both there.
Easier would be to type
>>> "maxent" in dir(nltk)
>>> True
>>> "treebank" in dir(nltk)
>>> True
Use nltk.download() --> Models tab and check to see if the treemap tagger shows as installed.
You should also try downloading the tagger again.
If you don't want to use the downloader gui, you can just use the following commands in a python or ipython shell:
import nltk
nltk.download('punkt')
nltk.download('maxent_treebank_pos_tagger')
Over 50 corpora and lexical resources such as WordNet: http://www.nltk.org/nltk_data/ for free.
Use http://nltk.github.com/nltk_data/ as server index instead of googlecode
Google code 401: Authorization Required

installing an Ocaml hump library on mutualized server

I am trying to use the Ocaml csv library. I downloaded csv-1.2.3 and followed the installation instructions after installing findlib:
Uncompress the source archive and go to the root of the package,
Run 'ocaml setup.ml -configure',
Run 'ocaml setup.ml -build',
Run 'ocaml setup.ml -install'
Now I have META, csv.a, csv.cma, csv.cmi, csv.cmx, csv.cmxa, csv.mli files in ~/opt/lib/ocaml/site-lib/csv repertory. The shell command ocamlfind list -describe gives csv A pure OCaml library to read and write CSV files. (version: 1.2.3) which I believe means that csv is installed properly.
BUT when I add
let data = Csv.load "foo.csv" in
in my compute.ml module and try to compile it within the larger program package I have the compilation error :
File "_none_", line 1, characters 0-1:
Error: No implementations provided for the following modules:
Csv referenced from compute.cmx"
and if I simply type
let data = load "foo.csv" in
i get :
File "compute.ml", line 74, characters 13-17:
Error: Unbound value load
I have the same type of errors when I use Csv.load or load directly in the Ocaml terminal. Would somebody have an idea of what is wrong in my code or library installation?
My guess is that you're using ocamlfind for compilation (ocamlfind ocamlc -package csv ...), because you have a linking error, not a type-checking one (which would be the case if you had not specified at all where csv is). The solution may be, in this case, to add a -linkall option to the final compilation line producing an executable, to ask it to link csv.cmx with it. Otherwise, please try to use ocamlfind and yes, tell us what your compilation command is.
For the toplevel, it is very easy to use ocamlfind from it. Watch this toplevel interaction:
% ocaml
Objective Caml version 3.12.1
# #use "topfind";;
- : unit = ()
Findlib has been successfully loaded. Additional directives:
#require "package";; to load a package
#list;; to list the available packages
#camlp4o;; to load camlp4 (standard syntax)
#camlp4r;; to load camlp4 (revised syntax)
#predicates "p,q,...";; to set these predicates
Topfind.reset();; to force that packages will be reloaded
#thread;; to enable threads
- : unit = ()
# #require "csv";;
/usr/lib/ocaml/csv: added to search path
/usr/lib/ocaml/csv/csv.cma: loaded
# Csv.load;;
- : ?separator:char -> ?excel_tricks:bool -> string -> Csv.t = <fun>
To be explicit. What I typed once in the toplevel was:
#use "topfind";;
#require "csv";;
Csv.load;; (* or anything else that uses Csv *)