The def keyword always seems to give me an error feedback - python-3.7

def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Syntax Error: invalid syntax

Your code should be working.
I tried below in PyCharm IDE, It worked for me.
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
# Output = I am from Sweden
Tried below code from Command line:
C:\Users\OmkarJ>python
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def my_function(country = "Norway"):
... print("I am from " + country)
...
>>> my_function("Sweden")
I am from Sweden
>>> my_function("India")
I am from India
>>>

Related

Pycuda test_driver.py raises Attribute Error

I'm trying to install pycuda on Linux Mint with a GeForce 960M and Cuda 8.0 installed. When I run the test_driver.py script it outputs the following error:
============================= test session starts ==============================
platform linux2 -- Python 2.7.12, pytest-3.0.3, py-1.4.31, pluggy-0.4.0
rootdir: /home/milton/Downloads/pycuda-2016.1.2, inifile:
collected 28 items
test_driver.py ...................x.....F..
=================================== FAILURES ===================================
________________________ TestDriver.test_multi_context _________________________
args = (,), kwargs = {}
pycuda = <module 'pycuda' from '/home/milton/miniconda2/lib/python2.7/site-packages/pycuda-2016.1.2-py2.7-linux-x86_64.egg/pycuda/init.pyc'>
ctx = <pycuda._driver.Context object at 0x7f540e39d758>
clear_context_caches = <function clear_context_caches at 0x7f540ee26758>
collect =<built-in function collect>
def f(*args, **kwargs):
import pycuda.driver
# appears to be idempotent, i.e. no harm in calling it more than once
pycuda.driver.init()
ctx = make_default_context()
try:
assert isinstance(ctx.get_device().name(), str)
assert isinstance(ctx.get_device().compute_capability(), tuple)
assert isinstance(ctx.get_device().get_attributes(), dict)
inner_f(*args, **kwargs)
../../../miniconda2/lib/python2.7/site-packages/pycuda-2016.1.2-py2.7-linux-x86_64.egg/pycuda/tools.py:460:
self = <test_driver.TestDriver instance at 0x7f540c21fc20>
#mark_cuda_test
def test_multi_context(self):
if drv.get_version() < (2,0,0):
return
if drv.get_version() >= (2,2,0):
if drv.Context.get_device().compute_mode == drv.compute_mode.EXCLUSIVE:
E AttributeError: type object 'compute_mode' has no attribute 'EXCLUSIVE'
test_driver.py:638: AttributeError
================ 1 failed, 26 passed, 1 xfailed in 6.92 seconds ================
python driver compute mode only supports following modes:
DEFAULT,
PROHIBITED,
EXCLUSIVE_PROCESS
so please change this:
if drv.Context.get_device().compute_mode == drv.compute_mode.EXCLUSIVE:
to
if drv.Context.get_device().compute_mode == drv.compute_mode.EXCLUSIVE_PROCESS:
in your test_driver.py file

Get ipython notebook filename in function

This code works fine in an Ipython/Juypter cell to get the notebook filename:
js = """var kernel = IPython.notebook.kernel;
var thename = window.document.getElementById("notebook_name").innerHTML;
var command = "theNotebook2 = " + "'"+thename+"'";
kernel.execute(command);"""
display(Javascript(js))
theNotebook2 + '.ipynb'
'techela.ipynb'
If I define a function in a cell and call it:
def get_filename():
"""Get the notebook filename."""
js = """var kernel = IPython.notebook.kernel;
var thename = window.document.getElementById("notebook_name").innerHTML;
var command = "theNotebook2 = " + "'"+thename+"'";
kernel.execute(command);"""
display(Javascript(js))
return theNotebook2 + '.ipynb'
get_filename()
'techela.ipynb'
It also seems to work fine and give me the filename.
However, if I put that function in a module, and import it, then it stops working.
from techela import get_filename
get_filename()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-17-42ee37d0d253> in <module>()
1 from techela import get_filename
----> 2 get_filename()
/Users/jkitchin/techela/ipynb/techela.py in get_filename()
11 kernel.execute(command);"""
12 display(Javascript(js))
---> 13 return theNotebook2 + '.ipynb'
14
15
NameError: name 'theNotebook2' is not defined
Any idea why this is failing?

Boost.Python invalid keyword argument crashing the interpreter

I'm trying to define a class with multiple constructors methods, some of which take keyword arguments. Everything works as expected/intended until the constructor is passed a bad parameter list, in which case the interpreter dies instead of throwing an exception. Here's a minimal example:
#include <boost/python.hpp>
#include <string>
class Crash {
public:
Crash(std::string) { }
Crash(int, int) { }
};
BOOST_PYTHON_MODULE(mymodule) {
using namespace boost::python;
class_<Crash>("Crash", init<std::string>())
.def(init<int, int>((arg("i") = 3)))
;
}
Output:
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win 32
Type "help", "copyright", "credits" or "license" for more information.
>>> import mymodule as mm
>>> mm.Crash("asdf")
<mymodule.Crash object at 0x00D9FB70>
>>> mm.Crash(3)
<mymodule.Crash object at 0x00D9FE10>
>>> mm.Crash(4, i=5)
<mymodule.Crash object at 0x00D9FB70>
>>> mm.Crash(i=3) # kills the interpreter
Putting in an invalid keyword, e.g., Crash(blah=4), also kills the interpreter.
Is this a Boost.Python bug, or am I doing something wrong?
I'm using Boost 1.51 / Python 2.7.3 / MSVC 9.0.

Selenium find_element_by_id returns None

I am using selenium and i have properly installed the selenium module on redhat linux 6.
Below is my script:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
import unittest, time, re
import zlib
class Sele1(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "https://bugzilla.example.com/"
self.verificationErrors = []
def test_sele1(self):
driver = self.driver
driver.get(self.base_url + "/")
driver.find_element_by_id("Bugzilla_login").clear()
driver.find_element_by_id("Bugzilla_login").send_keys("username")
driver.find_element_by_id("Bugzilla_password").clear()
driver.find_element_by_id("Bugzilla_password").send_keys("password")
driver.find_element_by_id("log_in").click()
driver.find_element_by_id("quicksearch").clear()
driver.find_element_by_id("quicksearch").send_keys("new bugs is bugzilla tool")
driver.find_element_by_xpath("//input[#value='Find Bugs']").click()
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException, e: return False
return True
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
When i am running this script it is showing errors:
ERROR: test_sele1 (main.Sele1)
Traceback (most recent call last):
File "sele1.py", line 19, in test_sele1
driver.find_element_by_id("Bugzilla_login").clear()
AttributeError: 'NoneType' object has no attribute 'clear'
Ran 1 test in 2.018s
FAILED (errors=1)
Plateform: Redhat
Python Version: 2.6
Note: while running the same script in windows7, it is running fine but not running in linux with python2.6
Please help me for this...
Thanks in advance!
Simple: Selenium can't find an element called "Bugzilla_login".
There could be hundreds of reasons this may be happening. I'd start with checking whether you're loading the correct page.

Is there a unicodedata module for IronPython?

I'm trying to get the generic sample code for the selenium2 Sauce OnDemand service working with IronPython, for some test work I'm doing, and I've run into a problem I can't quite figure out.
First, Here's the environment:
Windows 7 Home Premium, 64bit.
IronPython 2.7.0.40 on .Net 4.0.30319.225
My path:
>>> sys.path
['.', 'C:\\users\\me\\scripts\\python', 'C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Common7\\IDE\\Extensions\\Microsoft\\IronStudio\\0.4\\Lib', 'C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Common7\\IDE\\Extensions\\Microsoft\\IronStudio\\0.4\\DLLs', 'C:\\opt\\win\\ipy\\Lib', 'C:\\opt\\win\\ipy\\DLLs', 'C:\\opt\\win\\ipy']
I'm aware that IronPython has issues using compressed eggs, so I've extracted the following libraries into the \Lib directory on the sys.path:
selenium (2.0b4dev)
rdflib (3.1.0)
Now, the sample code from Sauce Labs:
import unittest
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
class Selenium2OnSauce(unittest.TestCase):
def setUp(self):
desired_capabilities = dict(platform="WINDOWS",
browserName="firefox",
version="3.6",
name="Hello, Selenium 2!")
self.driver = webdriver.Remote(
desired_capabilities=desired_capabilities,
command_executor="http://me:my-site-access-key#ondemand.saucelabs.com:80/wd/hub")
def test_sauce(self):
self.driver.get('http://example.saucelabs.com')
assert "Sauce Labs" in self.driver.title
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()
Here's the error I'm getting:
Traceback (most recent call last):
File "selenium2_test.py", line 3, in <module>
File "c:\opt\win\ipy\Lib\selenium\webdriver\__init__.py", line 18, in <module>
File "c:\opt\win\ipy\Lib\selenium\webdriver\firefox\webdriver.py", line 24, in <module>
File "c:\opt\win\ipy\Lib\selenium\webdriver\firefox\firefox_profile.py", line 23, in <module>
File "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\IronStudio\0.4\Lib\rdflib\__init__.py", line 65, in <module>
File "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\IronStudio\0.4\Lib\rdflib\namespace.py", line 282, in <module>
ImportError: No module named unicodedata
I've tried searching for packages with unicodedata in them (such as FePY), but none of them seem to work. I've tried copying the .pyd from my Python27 installation, but that didn't work either.
Is this something that's not yet available in IronPython 2.7? Alternatively, is there a library or namespace I can reference to accomplish the same task?
If not, I guess I'll have to go without selenium2 until the Iron guys get a unicodedata for IP27. :(
Thanks,
Greg.
Alas, the unicodedata module is currently not included in IronPython. But fear not! For the upcoming 2.7.1 release will have it, and all of your troubles shall be no more.
Sorry about that. As for when 2.7.1 will be released, I'm thinking early June. You can check https://github.com/IronLanguages/main/commit/5395af28b5794b0acf982ab87d17466925ab819f for the patch, but it's fairly large and fiddly because of the included Unicode database.
See #Micheal Greene's comments on the original question. Here is the module with the edits as directed:
# Copyright (c) 2006 by Seo Sanghyeon
# 2006-07-13 sanxiyn Created
# 2006-07-19 sanxiyn Added unidata_version, normalize
# Modified 2011 - Greg Gauthier - To provide needed functionality for rdflib
# and other utilities, in IronPython 2.7.0
unidata_version = '3.2.0'
# --------------------------------------------------------------------
# Normalization
from System import String
from System.Text import NormalizationForm
def normalize(form, string):
return String.Normalize(string, _form_mapping[form])
_form_mapping = {
'NFC': NormalizationForm.FormC,
'NFKC': NormalizationForm.FormKC,
'NFD': NormalizationForm.FormD,
'NFKD': NormalizationForm.FormKD,
}
# --------------------------------------------------------------------
# Character properties
from System.Globalization import CharUnicodeInfo
def _handle_default(function):
def wrapper(unichr, default=None):
result = function(unichr)
if result != -1:
return result
if default is None:
raise ValueError()
return default
return wrapper
decimal = _handle_default(CharUnicodeInfo.GetDecimalDigitValue)
digit = _handle_default(CharUnicodeInfo.GetDigitValue)
numeric = _handle_default(CharUnicodeInfo.GetNumericValue)
def category(unichr):
uc = CharUnicodeInfo.GetUnicodeCategory(unichr)
return _category_mapping[int(uc)]
_category_mapping = {
0: 'Lu',
1: 'Ll',
2: 'Lt',
3: 'Lm',
4: 'Lo',
5: 'Mn',
6: 'Mc',
7: 'Me',
8: 'Nd',
9: 'Nl',
10: 'No',
11: 'Zs',
12: 'Zl',
13: 'Zp',
14: 'Cc',
15: 'Cf',
16: 'Cs',
17: 'Co',
18: 'Pc',
19: 'Pd',
20: 'Ps',
21: 'Pe',
22: 'Pi',
23: 'Pf',
24: 'Po',
25: 'Sm',
26: 'Sc',
27: 'Sk',
28: 'So',
29: 'Cn',
}
# added for rdflib/ironpython
def decomposition(unichr):
return String.Normalize(unichr.ToString(), NormalizationForm.FormD)