prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>test_media_utils.py<|end_file_name|><|fim▁begin|>""" Test suite for the embedded <script> extraction """ from BeautifulSoup import BeautifulSoup from nose.tools import raises, eq_ from csxj.datasources.parser_tools import media_utils from csxj.datasources.parser_tools import twitter_utils from tests.datasources.parser_tools import test_twitter_utils def make_soup(html_data): return BeautifulSoup(html_data) class TestMediaUtils(object): def setUp(self): self.netloc = 'foo.com' self.internal_sites = {} def test_embedded_script(self): """ The embedded <script> extraction works on a simple embedded script with <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> * <noscript> <a href='http://bar.com/some_resource'>Disabled JS, go here</a> </noscript> </div> """ soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) eq_(tagged_URL.URL, "http://bar.com/some_resource") @raises(ValueError) def test_embedded_script_without_noscript_fallback(self): """ The embedded <script> extraction raises a ValueError exception when encountering a script without <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> </div> """ soup = make_soup(html_data) media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) def test_embeded_tweet_widget(self): """ The embedded <script> extraction returns a link to a twitter resource when the script is a twitter widget """ html_data = """ <div> <script src={0}> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) @raises(ValueError) def test_embedded_javascript_code(self): """ The embedded <script> extraction raises a ValueError when processing a <script> tag with arbitrary Javascript code inside """ js_content = """<script type='text/javascript'>var pokey='penguin'; </script>""" soup = make_soup(js_content) media_utils.extract_tagged_url_from_embedded_script(soup, self.netloc, self.internal_sites) def test_embedded_tweet_widget_splitted(self): """ The embedded <script> extraction should work when an embedded tweet is split between the widget.js inclusion and the actual javascript code to instantiate it.""" html_data = """ <div> <script src={0}></script> <script> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) class TestDewPlayer(object): <|fim_middle|> <|fim▁end|>
def test_simple_url_extraction(self): """ media_utils.extract_source_url_from_dewplayer() can extract he url to an mp3 file from an embedded dewplayer object. """ dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?mp3=http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" expected_mp3_url = "http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" extracted_url = media_utils.extract_source_url_from_dewplayer(dewplayer_url) eq_(expected_mp3_url, extracted_url) @raises(ValueError) def test_empty_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an empty string """ media_utils.extract_source_url_from_dewplayer("") @raises(ValueError) def test_bad_query_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an unknown dewplayer query """ wrong_dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?foo=bar" media_utils.extract_source_url_from_dewplayer(wrong_dewplayer_url)
<|file_name|>test_media_utils.py<|end_file_name|><|fim▁begin|>""" Test suite for the embedded <script> extraction """ from BeautifulSoup import BeautifulSoup from nose.tools import raises, eq_ from csxj.datasources.parser_tools import media_utils from csxj.datasources.parser_tools import twitter_utils from tests.datasources.parser_tools import test_twitter_utils def make_soup(html_data): return BeautifulSoup(html_data) class TestMediaUtils(object): def setUp(self): self.netloc = 'foo.com' self.internal_sites = {} def test_embedded_script(self): """ The embedded <script> extraction works on a simple embedded script with <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> * <noscript> <a href='http://bar.com/some_resource'>Disabled JS, go here</a> </noscript> </div> """ soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) eq_(tagged_URL.URL, "http://bar.com/some_resource") @raises(ValueError) def test_embedded_script_without_noscript_fallback(self): """ The embedded <script> extraction raises a ValueError exception when encountering a script without <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> </div> """ soup = make_soup(html_data) media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) def test_embeded_tweet_widget(self): """ The embedded <script> extraction returns a link to a twitter resource when the script is a twitter widget """ html_data = """ <div> <script src={0}> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) @raises(ValueError) def test_embedded_javascript_code(self): """ The embedded <script> extraction raises a ValueError when processing a <script> tag with arbitrary Javascript code inside """ js_content = """<script type='text/javascript'>var pokey='penguin'; </script>""" soup = make_soup(js_content) media_utils.extract_tagged_url_from_embedded_script(soup, self.netloc, self.internal_sites) def test_embedded_tweet_widget_splitted(self): """ The embedded <script> extraction should work when an embedded tweet is split between the widget.js inclusion and the actual javascript code to instantiate it.""" html_data = """ <div> <script src={0}></script> <script> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) class TestDewPlayer(object): def test_simple_url_extraction(self): <|fim_middle|> @raises(ValueError) def test_empty_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an empty string """ media_utils.extract_source_url_from_dewplayer("") @raises(ValueError) def test_bad_query_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an unknown dewplayer query """ wrong_dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?foo=bar" media_utils.extract_source_url_from_dewplayer(wrong_dewplayer_url) <|fim▁end|>
""" media_utils.extract_source_url_from_dewplayer() can extract he url to an mp3 file from an embedded dewplayer object. """ dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?mp3=http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" expected_mp3_url = "http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" extracted_url = media_utils.extract_source_url_from_dewplayer(dewplayer_url) eq_(expected_mp3_url, extracted_url)
<|file_name|>test_media_utils.py<|end_file_name|><|fim▁begin|>""" Test suite for the embedded <script> extraction """ from BeautifulSoup import BeautifulSoup from nose.tools import raises, eq_ from csxj.datasources.parser_tools import media_utils from csxj.datasources.parser_tools import twitter_utils from tests.datasources.parser_tools import test_twitter_utils def make_soup(html_data): return BeautifulSoup(html_data) class TestMediaUtils(object): def setUp(self): self.netloc = 'foo.com' self.internal_sites = {} def test_embedded_script(self): """ The embedded <script> extraction works on a simple embedded script with <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> * <noscript> <a href='http://bar.com/some_resource'>Disabled JS, go here</a> </noscript> </div> """ soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) eq_(tagged_URL.URL, "http://bar.com/some_resource") @raises(ValueError) def test_embedded_script_without_noscript_fallback(self): """ The embedded <script> extraction raises a ValueError exception when encountering a script without <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> </div> """ soup = make_soup(html_data) media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) def test_embeded_tweet_widget(self): """ The embedded <script> extraction returns a link to a twitter resource when the script is a twitter widget """ html_data = """ <div> <script src={0}> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) @raises(ValueError) def test_embedded_javascript_code(self): """ The embedded <script> extraction raises a ValueError when processing a <script> tag with arbitrary Javascript code inside """ js_content = """<script type='text/javascript'>var pokey='penguin'; </script>""" soup = make_soup(js_content) media_utils.extract_tagged_url_from_embedded_script(soup, self.netloc, self.internal_sites) def test_embedded_tweet_widget_splitted(self): """ The embedded <script> extraction should work when an embedded tweet is split between the widget.js inclusion and the actual javascript code to instantiate it.""" html_data = """ <div> <script src={0}></script> <script> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) class TestDewPlayer(object): def test_simple_url_extraction(self): """ media_utils.extract_source_url_from_dewplayer() can extract he url to an mp3 file from an embedded dewplayer object. """ dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?mp3=http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" expected_mp3_url = "http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" extracted_url = media_utils.extract_source_url_from_dewplayer(dewplayer_url) eq_(expected_mp3_url, extracted_url) @raises(ValueError) def test_empty_url(self): <|fim_middle|> @raises(ValueError) def test_bad_query_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an unknown dewplayer query """ wrong_dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?foo=bar" media_utils.extract_source_url_from_dewplayer(wrong_dewplayer_url) <|fim▁end|>
""" media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an empty string """ media_utils.extract_source_url_from_dewplayer("")
<|file_name|>test_media_utils.py<|end_file_name|><|fim▁begin|>""" Test suite for the embedded <script> extraction """ from BeautifulSoup import BeautifulSoup from nose.tools import raises, eq_ from csxj.datasources.parser_tools import media_utils from csxj.datasources.parser_tools import twitter_utils from tests.datasources.parser_tools import test_twitter_utils def make_soup(html_data): return BeautifulSoup(html_data) class TestMediaUtils(object): def setUp(self): self.netloc = 'foo.com' self.internal_sites = {} def test_embedded_script(self): """ The embedded <script> extraction works on a simple embedded script with <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> * <noscript> <a href='http://bar.com/some_resource'>Disabled JS, go here</a> </noscript> </div> """ soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) eq_(tagged_URL.URL, "http://bar.com/some_resource") @raises(ValueError) def test_embedded_script_without_noscript_fallback(self): """ The embedded <script> extraction raises a ValueError exception when encountering a script without <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> </div> """ soup = make_soup(html_data) media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) def test_embeded_tweet_widget(self): """ The embedded <script> extraction returns a link to a twitter resource when the script is a twitter widget """ html_data = """ <div> <script src={0}> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) @raises(ValueError) def test_embedded_javascript_code(self): """ The embedded <script> extraction raises a ValueError when processing a <script> tag with arbitrary Javascript code inside """ js_content = """<script type='text/javascript'>var pokey='penguin'; </script>""" soup = make_soup(js_content) media_utils.extract_tagged_url_from_embedded_script(soup, self.netloc, self.internal_sites) def test_embedded_tweet_widget_splitted(self): """ The embedded <script> extraction should work when an embedded tweet is split between the widget.js inclusion and the actual javascript code to instantiate it.""" html_data = """ <div> <script src={0}></script> <script> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) class TestDewPlayer(object): def test_simple_url_extraction(self): """ media_utils.extract_source_url_from_dewplayer() can extract he url to an mp3 file from an embedded dewplayer object. """ dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?mp3=http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" expected_mp3_url = "http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" extracted_url = media_utils.extract_source_url_from_dewplayer(dewplayer_url) eq_(expected_mp3_url, extracted_url) @raises(ValueError) def test_empty_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an empty string """ media_utils.extract_source_url_from_dewplayer("") @raises(ValueError) def test_bad_query_url(self): <|fim_middle|> <|fim▁end|>
""" media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an unknown dewplayer query """ wrong_dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?foo=bar" media_utils.extract_source_url_from_dewplayer(wrong_dewplayer_url)
<|file_name|>test_media_utils.py<|end_file_name|><|fim▁begin|>""" Test suite for the embedded <script> extraction """ from BeautifulSoup import BeautifulSoup from nose.tools import raises, eq_ from csxj.datasources.parser_tools import media_utils from csxj.datasources.parser_tools import twitter_utils from tests.datasources.parser_tools import test_twitter_utils def <|fim_middle|>(html_data): return BeautifulSoup(html_data) class TestMediaUtils(object): def setUp(self): self.netloc = 'foo.com' self.internal_sites = {} def test_embedded_script(self): """ The embedded <script> extraction works on a simple embedded script with <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> * <noscript> <a href='http://bar.com/some_resource'>Disabled JS, go here</a> </noscript> </div> """ soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) eq_(tagged_URL.URL, "http://bar.com/some_resource") @raises(ValueError) def test_embedded_script_without_noscript_fallback(self): """ The embedded <script> extraction raises a ValueError exception when encountering a script without <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> </div> """ soup = make_soup(html_data) media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) def test_embeded_tweet_widget(self): """ The embedded <script> extraction returns a link to a twitter resource when the script is a twitter widget """ html_data = """ <div> <script src={0}> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) @raises(ValueError) def test_embedded_javascript_code(self): """ The embedded <script> extraction raises a ValueError when processing a <script> tag with arbitrary Javascript code inside """ js_content = """<script type='text/javascript'>var pokey='penguin'; </script>""" soup = make_soup(js_content) media_utils.extract_tagged_url_from_embedded_script(soup, self.netloc, self.internal_sites) def test_embedded_tweet_widget_splitted(self): """ The embedded <script> extraction should work when an embedded tweet is split between the widget.js inclusion and the actual javascript code to instantiate it.""" html_data = """ <div> <script src={0}></script> <script> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) class TestDewPlayer(object): def test_simple_url_extraction(self): """ media_utils.extract_source_url_from_dewplayer() can extract he url to an mp3 file from an embedded dewplayer object. """ dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?mp3=http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" expected_mp3_url = "http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" extracted_url = media_utils.extract_source_url_from_dewplayer(dewplayer_url) eq_(expected_mp3_url, extracted_url) @raises(ValueError) def test_empty_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an empty string """ media_utils.extract_source_url_from_dewplayer("") @raises(ValueError) def test_bad_query_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an unknown dewplayer query """ wrong_dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?foo=bar" media_utils.extract_source_url_from_dewplayer(wrong_dewplayer_url) <|fim▁end|>
make_soup
<|file_name|>test_media_utils.py<|end_file_name|><|fim▁begin|>""" Test suite for the embedded <script> extraction """ from BeautifulSoup import BeautifulSoup from nose.tools import raises, eq_ from csxj.datasources.parser_tools import media_utils from csxj.datasources.parser_tools import twitter_utils from tests.datasources.parser_tools import test_twitter_utils def make_soup(html_data): return BeautifulSoup(html_data) class TestMediaUtils(object): def <|fim_middle|>(self): self.netloc = 'foo.com' self.internal_sites = {} def test_embedded_script(self): """ The embedded <script> extraction works on a simple embedded script with <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> * <noscript> <a href='http://bar.com/some_resource'>Disabled JS, go here</a> </noscript> </div> """ soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) eq_(tagged_URL.URL, "http://bar.com/some_resource") @raises(ValueError) def test_embedded_script_without_noscript_fallback(self): """ The embedded <script> extraction raises a ValueError exception when encountering a script without <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> </div> """ soup = make_soup(html_data) media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) def test_embeded_tweet_widget(self): """ The embedded <script> extraction returns a link to a twitter resource when the script is a twitter widget """ html_data = """ <div> <script src={0}> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) @raises(ValueError) def test_embedded_javascript_code(self): """ The embedded <script> extraction raises a ValueError when processing a <script> tag with arbitrary Javascript code inside """ js_content = """<script type='text/javascript'>var pokey='penguin'; </script>""" soup = make_soup(js_content) media_utils.extract_tagged_url_from_embedded_script(soup, self.netloc, self.internal_sites) def test_embedded_tweet_widget_splitted(self): """ The embedded <script> extraction should work when an embedded tweet is split between the widget.js inclusion and the actual javascript code to instantiate it.""" html_data = """ <div> <script src={0}></script> <script> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) class TestDewPlayer(object): def test_simple_url_extraction(self): """ media_utils.extract_source_url_from_dewplayer() can extract he url to an mp3 file from an embedded dewplayer object. """ dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?mp3=http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" expected_mp3_url = "http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" extracted_url = media_utils.extract_source_url_from_dewplayer(dewplayer_url) eq_(expected_mp3_url, extracted_url) @raises(ValueError) def test_empty_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an empty string """ media_utils.extract_source_url_from_dewplayer("") @raises(ValueError) def test_bad_query_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an unknown dewplayer query """ wrong_dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?foo=bar" media_utils.extract_source_url_from_dewplayer(wrong_dewplayer_url) <|fim▁end|>
setUp
<|file_name|>test_media_utils.py<|end_file_name|><|fim▁begin|>""" Test suite for the embedded <script> extraction """ from BeautifulSoup import BeautifulSoup from nose.tools import raises, eq_ from csxj.datasources.parser_tools import media_utils from csxj.datasources.parser_tools import twitter_utils from tests.datasources.parser_tools import test_twitter_utils def make_soup(html_data): return BeautifulSoup(html_data) class TestMediaUtils(object): def setUp(self): self.netloc = 'foo.com' self.internal_sites = {} def <|fim_middle|>(self): """ The embedded <script> extraction works on a simple embedded script with <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> * <noscript> <a href='http://bar.com/some_resource'>Disabled JS, go here</a> </noscript> </div> """ soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) eq_(tagged_URL.URL, "http://bar.com/some_resource") @raises(ValueError) def test_embedded_script_without_noscript_fallback(self): """ The embedded <script> extraction raises a ValueError exception when encountering a script without <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> </div> """ soup = make_soup(html_data) media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) def test_embeded_tweet_widget(self): """ The embedded <script> extraction returns a link to a twitter resource when the script is a twitter widget """ html_data = """ <div> <script src={0}> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) @raises(ValueError) def test_embedded_javascript_code(self): """ The embedded <script> extraction raises a ValueError when processing a <script> tag with arbitrary Javascript code inside """ js_content = """<script type='text/javascript'>var pokey='penguin'; </script>""" soup = make_soup(js_content) media_utils.extract_tagged_url_from_embedded_script(soup, self.netloc, self.internal_sites) def test_embedded_tweet_widget_splitted(self): """ The embedded <script> extraction should work when an embedded tweet is split between the widget.js inclusion and the actual javascript code to instantiate it.""" html_data = """ <div> <script src={0}></script> <script> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) class TestDewPlayer(object): def test_simple_url_extraction(self): """ media_utils.extract_source_url_from_dewplayer() can extract he url to an mp3 file from an embedded dewplayer object. """ dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?mp3=http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" expected_mp3_url = "http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" extracted_url = media_utils.extract_source_url_from_dewplayer(dewplayer_url) eq_(expected_mp3_url, extracted_url) @raises(ValueError) def test_empty_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an empty string """ media_utils.extract_source_url_from_dewplayer("") @raises(ValueError) def test_bad_query_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an unknown dewplayer query """ wrong_dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?foo=bar" media_utils.extract_source_url_from_dewplayer(wrong_dewplayer_url) <|fim▁end|>
test_embedded_script
<|file_name|>test_media_utils.py<|end_file_name|><|fim▁begin|>""" Test suite for the embedded <script> extraction """ from BeautifulSoup import BeautifulSoup from nose.tools import raises, eq_ from csxj.datasources.parser_tools import media_utils from csxj.datasources.parser_tools import twitter_utils from tests.datasources.parser_tools import test_twitter_utils def make_soup(html_data): return BeautifulSoup(html_data) class TestMediaUtils(object): def setUp(self): self.netloc = 'foo.com' self.internal_sites = {} def test_embedded_script(self): """ The embedded <script> extraction works on a simple embedded script with <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> * <noscript> <a href='http://bar.com/some_resource'>Disabled JS, go here</a> </noscript> </div> """ soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) eq_(tagged_URL.URL, "http://bar.com/some_resource") @raises(ValueError) def <|fim_middle|>(self): """ The embedded <script> extraction raises a ValueError exception when encountering a script without <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> </div> """ soup = make_soup(html_data) media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) def test_embeded_tweet_widget(self): """ The embedded <script> extraction returns a link to a twitter resource when the script is a twitter widget """ html_data = """ <div> <script src={0}> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) @raises(ValueError) def test_embedded_javascript_code(self): """ The embedded <script> extraction raises a ValueError when processing a <script> tag with arbitrary Javascript code inside """ js_content = """<script type='text/javascript'>var pokey='penguin'; </script>""" soup = make_soup(js_content) media_utils.extract_tagged_url_from_embedded_script(soup, self.netloc, self.internal_sites) def test_embedded_tweet_widget_splitted(self): """ The embedded <script> extraction should work when an embedded tweet is split between the widget.js inclusion and the actual javascript code to instantiate it.""" html_data = """ <div> <script src={0}></script> <script> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) class TestDewPlayer(object): def test_simple_url_extraction(self): """ media_utils.extract_source_url_from_dewplayer() can extract he url to an mp3 file from an embedded dewplayer object. """ dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?mp3=http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" expected_mp3_url = "http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" extracted_url = media_utils.extract_source_url_from_dewplayer(dewplayer_url) eq_(expected_mp3_url, extracted_url) @raises(ValueError) def test_empty_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an empty string """ media_utils.extract_source_url_from_dewplayer("") @raises(ValueError) def test_bad_query_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an unknown dewplayer query """ wrong_dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?foo=bar" media_utils.extract_source_url_from_dewplayer(wrong_dewplayer_url) <|fim▁end|>
test_embedded_script_without_noscript_fallback
<|file_name|>test_media_utils.py<|end_file_name|><|fim▁begin|>""" Test suite for the embedded <script> extraction """ from BeautifulSoup import BeautifulSoup from nose.tools import raises, eq_ from csxj.datasources.parser_tools import media_utils from csxj.datasources.parser_tools import twitter_utils from tests.datasources.parser_tools import test_twitter_utils def make_soup(html_data): return BeautifulSoup(html_data) class TestMediaUtils(object): def setUp(self): self.netloc = 'foo.com' self.internal_sites = {} def test_embedded_script(self): """ The embedded <script> extraction works on a simple embedded script with <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> * <noscript> <a href='http://bar.com/some_resource'>Disabled JS, go here</a> </noscript> </div> """ soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) eq_(tagged_URL.URL, "http://bar.com/some_resource") @raises(ValueError) def test_embedded_script_without_noscript_fallback(self): """ The embedded <script> extraction raises a ValueError exception when encountering a script without <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> </div> """ soup = make_soup(html_data) media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) def <|fim_middle|>(self): """ The embedded <script> extraction returns a link to a twitter resource when the script is a twitter widget """ html_data = """ <div> <script src={0}> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) @raises(ValueError) def test_embedded_javascript_code(self): """ The embedded <script> extraction raises a ValueError when processing a <script> tag with arbitrary Javascript code inside """ js_content = """<script type='text/javascript'>var pokey='penguin'; </script>""" soup = make_soup(js_content) media_utils.extract_tagged_url_from_embedded_script(soup, self.netloc, self.internal_sites) def test_embedded_tweet_widget_splitted(self): """ The embedded <script> extraction should work when an embedded tweet is split between the widget.js inclusion and the actual javascript code to instantiate it.""" html_data = """ <div> <script src={0}></script> <script> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) class TestDewPlayer(object): def test_simple_url_extraction(self): """ media_utils.extract_source_url_from_dewplayer() can extract he url to an mp3 file from an embedded dewplayer object. """ dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?mp3=http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" expected_mp3_url = "http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" extracted_url = media_utils.extract_source_url_from_dewplayer(dewplayer_url) eq_(expected_mp3_url, extracted_url) @raises(ValueError) def test_empty_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an empty string """ media_utils.extract_source_url_from_dewplayer("") @raises(ValueError) def test_bad_query_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an unknown dewplayer query """ wrong_dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?foo=bar" media_utils.extract_source_url_from_dewplayer(wrong_dewplayer_url) <|fim▁end|>
test_embeded_tweet_widget
<|file_name|>test_media_utils.py<|end_file_name|><|fim▁begin|>""" Test suite for the embedded <script> extraction """ from BeautifulSoup import BeautifulSoup from nose.tools import raises, eq_ from csxj.datasources.parser_tools import media_utils from csxj.datasources.parser_tools import twitter_utils from tests.datasources.parser_tools import test_twitter_utils def make_soup(html_data): return BeautifulSoup(html_data) class TestMediaUtils(object): def setUp(self): self.netloc = 'foo.com' self.internal_sites = {} def test_embedded_script(self): """ The embedded <script> extraction works on a simple embedded script with <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> * <noscript> <a href='http://bar.com/some_resource'>Disabled JS, go here</a> </noscript> </div> """ soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) eq_(tagged_URL.URL, "http://bar.com/some_resource") @raises(ValueError) def test_embedded_script_without_noscript_fallback(self): """ The embedded <script> extraction raises a ValueError exception when encountering a script without <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> </div> """ soup = make_soup(html_data) media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) def test_embeded_tweet_widget(self): """ The embedded <script> extraction returns a link to a twitter resource when the script is a twitter widget """ html_data = """ <div> <script src={0}> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) @raises(ValueError) def <|fim_middle|>(self): """ The embedded <script> extraction raises a ValueError when processing a <script> tag with arbitrary Javascript code inside """ js_content = """<script type='text/javascript'>var pokey='penguin'; </script>""" soup = make_soup(js_content) media_utils.extract_tagged_url_from_embedded_script(soup, self.netloc, self.internal_sites) def test_embedded_tweet_widget_splitted(self): """ The embedded <script> extraction should work when an embedded tweet is split between the widget.js inclusion and the actual javascript code to instantiate it.""" html_data = """ <div> <script src={0}></script> <script> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) class TestDewPlayer(object): def test_simple_url_extraction(self): """ media_utils.extract_source_url_from_dewplayer() can extract he url to an mp3 file from an embedded dewplayer object. """ dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?mp3=http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" expected_mp3_url = "http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" extracted_url = media_utils.extract_source_url_from_dewplayer(dewplayer_url) eq_(expected_mp3_url, extracted_url) @raises(ValueError) def test_empty_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an empty string """ media_utils.extract_source_url_from_dewplayer("") @raises(ValueError) def test_bad_query_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an unknown dewplayer query """ wrong_dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?foo=bar" media_utils.extract_source_url_from_dewplayer(wrong_dewplayer_url) <|fim▁end|>
test_embedded_javascript_code
<|file_name|>test_media_utils.py<|end_file_name|><|fim▁begin|>""" Test suite for the embedded <script> extraction """ from BeautifulSoup import BeautifulSoup from nose.tools import raises, eq_ from csxj.datasources.parser_tools import media_utils from csxj.datasources.parser_tools import twitter_utils from tests.datasources.parser_tools import test_twitter_utils def make_soup(html_data): return BeautifulSoup(html_data) class TestMediaUtils(object): def setUp(self): self.netloc = 'foo.com' self.internal_sites = {} def test_embedded_script(self): """ The embedded <script> extraction works on a simple embedded script with <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> * <noscript> <a href='http://bar.com/some_resource'>Disabled JS, go here</a> </noscript> </div> """ soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) eq_(tagged_URL.URL, "http://bar.com/some_resource") @raises(ValueError) def test_embedded_script_without_noscript_fallback(self): """ The embedded <script> extraction raises a ValueError exception when encountering a script without <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> </div> """ soup = make_soup(html_data) media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) def test_embeded_tweet_widget(self): """ The embedded <script> extraction returns a link to a twitter resource when the script is a twitter widget """ html_data = """ <div> <script src={0}> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) @raises(ValueError) def test_embedded_javascript_code(self): """ The embedded <script> extraction raises a ValueError when processing a <script> tag with arbitrary Javascript code inside """ js_content = """<script type='text/javascript'>var pokey='penguin'; </script>""" soup = make_soup(js_content) media_utils.extract_tagged_url_from_embedded_script(soup, self.netloc, self.internal_sites) def <|fim_middle|>(self): """ The embedded <script> extraction should work when an embedded tweet is split between the widget.js inclusion and the actual javascript code to instantiate it.""" html_data = """ <div> <script src={0}></script> <script> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) class TestDewPlayer(object): def test_simple_url_extraction(self): """ media_utils.extract_source_url_from_dewplayer() can extract he url to an mp3 file from an embedded dewplayer object. """ dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?mp3=http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" expected_mp3_url = "http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" extracted_url = media_utils.extract_source_url_from_dewplayer(dewplayer_url) eq_(expected_mp3_url, extracted_url) @raises(ValueError) def test_empty_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an empty string """ media_utils.extract_source_url_from_dewplayer("") @raises(ValueError) def test_bad_query_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an unknown dewplayer query """ wrong_dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?foo=bar" media_utils.extract_source_url_from_dewplayer(wrong_dewplayer_url) <|fim▁end|>
test_embedded_tweet_widget_splitted
<|file_name|>test_media_utils.py<|end_file_name|><|fim▁begin|>""" Test suite for the embedded <script> extraction """ from BeautifulSoup import BeautifulSoup from nose.tools import raises, eq_ from csxj.datasources.parser_tools import media_utils from csxj.datasources.parser_tools import twitter_utils from tests.datasources.parser_tools import test_twitter_utils def make_soup(html_data): return BeautifulSoup(html_data) class TestMediaUtils(object): def setUp(self): self.netloc = 'foo.com' self.internal_sites = {} def test_embedded_script(self): """ The embedded <script> extraction works on a simple embedded script with <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> * <noscript> <a href='http://bar.com/some_resource'>Disabled JS, go here</a> </noscript> </div> """ soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) eq_(tagged_URL.URL, "http://bar.com/some_resource") @raises(ValueError) def test_embedded_script_without_noscript_fallback(self): """ The embedded <script> extraction raises a ValueError exception when encountering a script without <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> </div> """ soup = make_soup(html_data) media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) def test_embeded_tweet_widget(self): """ The embedded <script> extraction returns a link to a twitter resource when the script is a twitter widget """ html_data = """ <div> <script src={0}> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) @raises(ValueError) def test_embedded_javascript_code(self): """ The embedded <script> extraction raises a ValueError when processing a <script> tag with arbitrary Javascript code inside """ js_content = """<script type='text/javascript'>var pokey='penguin'; </script>""" soup = make_soup(js_content) media_utils.extract_tagged_url_from_embedded_script(soup, self.netloc, self.internal_sites) def test_embedded_tweet_widget_splitted(self): """ The embedded <script> extraction should work when an embedded tweet is split between the widget.js inclusion and the actual javascript code to instantiate it.""" html_data = """ <div> <script src={0}></script> <script> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) class TestDewPlayer(object): def <|fim_middle|>(self): """ media_utils.extract_source_url_from_dewplayer() can extract he url to an mp3 file from an embedded dewplayer object. """ dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?mp3=http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" expected_mp3_url = "http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" extracted_url = media_utils.extract_source_url_from_dewplayer(dewplayer_url) eq_(expected_mp3_url, extracted_url) @raises(ValueError) def test_empty_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an empty string """ media_utils.extract_source_url_from_dewplayer("") @raises(ValueError) def test_bad_query_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an unknown dewplayer query """ wrong_dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?foo=bar" media_utils.extract_source_url_from_dewplayer(wrong_dewplayer_url) <|fim▁end|>
test_simple_url_extraction
<|file_name|>test_media_utils.py<|end_file_name|><|fim▁begin|>""" Test suite for the embedded <script> extraction """ from BeautifulSoup import BeautifulSoup from nose.tools import raises, eq_ from csxj.datasources.parser_tools import media_utils from csxj.datasources.parser_tools import twitter_utils from tests.datasources.parser_tools import test_twitter_utils def make_soup(html_data): return BeautifulSoup(html_data) class TestMediaUtils(object): def setUp(self): self.netloc = 'foo.com' self.internal_sites = {} def test_embedded_script(self): """ The embedded <script> extraction works on a simple embedded script with <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> * <noscript> <a href='http://bar.com/some_resource'>Disabled JS, go here</a> </noscript> </div> """ soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) eq_(tagged_URL.URL, "http://bar.com/some_resource") @raises(ValueError) def test_embedded_script_without_noscript_fallback(self): """ The embedded <script> extraction raises a ValueError exception when encountering a script without <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> </div> """ soup = make_soup(html_data) media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) def test_embeded_tweet_widget(self): """ The embedded <script> extraction returns a link to a twitter resource when the script is a twitter widget """ html_data = """ <div> <script src={0}> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) @raises(ValueError) def test_embedded_javascript_code(self): """ The embedded <script> extraction raises a ValueError when processing a <script> tag with arbitrary Javascript code inside """ js_content = """<script type='text/javascript'>var pokey='penguin'; </script>""" soup = make_soup(js_content) media_utils.extract_tagged_url_from_embedded_script(soup, self.netloc, self.internal_sites) def test_embedded_tweet_widget_splitted(self): """ The embedded <script> extraction should work when an embedded tweet is split between the widget.js inclusion and the actual javascript code to instantiate it.""" html_data = """ <div> <script src={0}></script> <script> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) class TestDewPlayer(object): def test_simple_url_extraction(self): """ media_utils.extract_source_url_from_dewplayer() can extract he url to an mp3 file from an embedded dewplayer object. """ dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?mp3=http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" expected_mp3_url = "http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" extracted_url = media_utils.extract_source_url_from_dewplayer(dewplayer_url) eq_(expected_mp3_url, extracted_url) @raises(ValueError) def <|fim_middle|>(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an empty string """ media_utils.extract_source_url_from_dewplayer("") @raises(ValueError) def test_bad_query_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an unknown dewplayer query """ wrong_dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?foo=bar" media_utils.extract_source_url_from_dewplayer(wrong_dewplayer_url) <|fim▁end|>
test_empty_url
<|file_name|>test_media_utils.py<|end_file_name|><|fim▁begin|>""" Test suite for the embedded <script> extraction """ from BeautifulSoup import BeautifulSoup from nose.tools import raises, eq_ from csxj.datasources.parser_tools import media_utils from csxj.datasources.parser_tools import twitter_utils from tests.datasources.parser_tools import test_twitter_utils def make_soup(html_data): return BeautifulSoup(html_data) class TestMediaUtils(object): def setUp(self): self.netloc = 'foo.com' self.internal_sites = {} def test_embedded_script(self): """ The embedded <script> extraction works on a simple embedded script with <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> * <noscript> <a href='http://bar.com/some_resource'>Disabled JS, go here</a> </noscript> </div> """ soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) eq_(tagged_URL.URL, "http://bar.com/some_resource") @raises(ValueError) def test_embedded_script_without_noscript_fallback(self): """ The embedded <script> extraction raises a ValueError exception when encountering a script without <noscript> fallback """ html_data = """ <div> <script src='http://bar.com/some_widget.js'> </script> </div> """ soup = make_soup(html_data) media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) def test_embeded_tweet_widget(self): """ The embedded <script> extraction returns a link to a twitter resource when the script is a twitter widget """ html_data = """ <div> <script src={0}> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) @raises(ValueError) def test_embedded_javascript_code(self): """ The embedded <script> extraction raises a ValueError when processing a <script> tag with arbitrary Javascript code inside """ js_content = """<script type='text/javascript'>var pokey='penguin'; </script>""" soup = make_soup(js_content) media_utils.extract_tagged_url_from_embedded_script(soup, self.netloc, self.internal_sites) def test_embedded_tweet_widget_splitted(self): """ The embedded <script> extraction should work when an embedded tweet is split between the widget.js inclusion and the actual javascript code to instantiate it.""" html_data = """ <div> <script src={0}></script> <script> {1} </script> </div> """.format(twitter_utils.TWITTER_WIDGET_SCRIPT_URL, test_twitter_utils.SAMPLE_TWIMG_PROFILE) soup = make_soup(html_data) tagged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites) expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded']) eq_(tagged_URL.tags, expected_tags) class TestDewPlayer(object): def test_simple_url_extraction(self): """ media_utils.extract_source_url_from_dewplayer() can extract he url to an mp3 file from an embedded dewplayer object. """ dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?mp3=http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" expected_mp3_url = "http://podcast.dhnet.be/articles/audio_dh_388635_1331708882.mp3" extracted_url = media_utils.extract_source_url_from_dewplayer(dewplayer_url) eq_(expected_mp3_url, extracted_url) @raises(ValueError) def test_empty_url(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an empty string """ media_utils.extract_source_url_from_dewplayer("") @raises(ValueError) def <|fim_middle|>(self): """ media_utils.extract_source_url_from_dewplayer() raises ValueError when fed an unknown dewplayer query """ wrong_dewplayer_url = "http://download.saipm.com/flash/dewplayer/dewplayer.swf?foo=bar" media_utils.extract_source_url_from_dewplayer(wrong_dewplayer_url) <|fim▁end|>
test_bad_query_url
<|file_name|>Crypto.py<|end_file_name|><|fim▁begin|><|fim▁hole|>import bcrypt def hash_password(password): default_rounds = 14 bcrypt_salt = bcrypt.gensalt(default_rounds) hashed_password = bcrypt.hashpw(password, bcrypt_salt) return hashed_password def check_password(password, hashed): return bcrypt.checkpw(password, hashed)<|fim▁end|>
<|file_name|>Crypto.py<|end_file_name|><|fim▁begin|>import bcrypt def hash_password(password): <|fim_middle|> def check_password(password, hashed): return bcrypt.checkpw(password, hashed) <|fim▁end|>
default_rounds = 14 bcrypt_salt = bcrypt.gensalt(default_rounds) hashed_password = bcrypt.hashpw(password, bcrypt_salt) return hashed_password
<|file_name|>Crypto.py<|end_file_name|><|fim▁begin|>import bcrypt def hash_password(password): default_rounds = 14 bcrypt_salt = bcrypt.gensalt(default_rounds) hashed_password = bcrypt.hashpw(password, bcrypt_salt) return hashed_password def check_password(password, hashed): <|fim_middle|> <|fim▁end|>
return bcrypt.checkpw(password, hashed)
<|file_name|>Crypto.py<|end_file_name|><|fim▁begin|>import bcrypt def <|fim_middle|>(password): default_rounds = 14 bcrypt_salt = bcrypt.gensalt(default_rounds) hashed_password = bcrypt.hashpw(password, bcrypt_salt) return hashed_password def check_password(password, hashed): return bcrypt.checkpw(password, hashed) <|fim▁end|>
hash_password
<|file_name|>Crypto.py<|end_file_name|><|fim▁begin|>import bcrypt def hash_password(password): default_rounds = 14 bcrypt_salt = bcrypt.gensalt(default_rounds) hashed_password = bcrypt.hashpw(password, bcrypt_salt) return hashed_password def <|fim_middle|>(password, hashed): return bcrypt.checkpw(password, hashed) <|fim▁end|>
check_password
<|file_name|>cornetto-client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008-2013 by # Erwin Marsi and Tilburg University<|fim▁hole|> # Pycornetto is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # Pycornetto is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ A simple client to connect to the Cornetto database server. Reads queries from standard input and writes results to standard output. """ # BUGS: # - there is no way interrupt a query that goes bad on the server, as obviously # a local Ctrl-C does not work __author__ = 'Erwin Marsi <[email protected]>' __version__ = '0.6.1' # using optparse instead of argparse so client can run stand-alone from sys import stdin, stdout, stderr, exit from optparse import OptionParser, IndentedHelpFormatter import xmlrpclib from pprint import pformat from socket import error as SocketError class MyFormatter(IndentedHelpFormatter): """to prevent optparse from messing up the epilog text""" def format_epilog(self, epilog): return epilog or "" def format_description(self, description): return description.lstrip() epilog = """ Interactive usage: $ cornetto-client.py $ cornetto-client.py -a File processing: $ echo 'ask("pijp")' | cornetto-client.py $ cornetto-client.py <input >output """ try: parser = OptionParser(description=__doc__, version="%(prog)s version " + __version__, epilog=epilog, formatter=MyFormatter()) except TypeError: # optparse in python 2.4 has no epilog keyword parser = OptionParser(description=__doc__ + epilog, version="%(prog)s version " + __version__) parser.add_option("-a", "--ask", action='store_true', help="assume all commands are input the 'ask' function, " "- so you can type 'query' instead of 'ask(\"query\") - '" "but online help is no longer accessible" ) parser.add_option("-H", "--host", default="localhost:5204", metavar="HOST[:PORT]", help="name or IP address of host (default is 'localhost') " "optionally followed by a port number " "(default is 5204)") parser.add_option('-n', '--no-pretty-print', dest="pretty_print", action='store_false', help="turn off pretty printing of output " "(default when standard input is a file)") parser.add_option("-p", "--port", type=int, default=5204, help='port number (default is 5204)') parser.add_option('-P', '--pretty-print', dest="pretty_print", action='store_true', help="turn on pretty printing of output " "(default when standard input is a tty)") parser.add_option("-e", "--encoding", default="utf8", metavar="utf8,latin1,ascii,...", help="character encoding of output (default is utf8)") parser.add_option('-V', '--verbose', action='store_true', help="verbose output for debugging") (opts, args) = parser.parse_args() if opts.host.startswith("http://"): opts.host = opts.host[7:] try: host, port = opts.host.split(":")[:2] except ValueError: host, port = opts.host, None # XMP-RPC requires specification of protocol host = "http://" + (host or "localhost") try: port = int(port or 5204) except ValueError: exit("Error: %s is not a valid port number" % repr(port)) server = xmlrpclib.ServerProxy("%s:%s" % (host, port), encoding="utf-8", verbose=opts.verbose) try: eval('server.echo("test")') except SocketError, inst: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?" % ( inst, host, port), "See cornetto-server.py -h" exit(1) help_text = """ Type "?" to see his message. Type "help()" for help on available methods. Type "Ctrl-D" to exit. Restart with "cornetto-client.py -h" to see command line options. """ startup_msg = ( "cornetto-client.py (version %s)\n" % __version__ + "Copyright (c) Erwin Marsi\n" + help_text ) if stdin.isatty(): prompt = "$ " if opts.pretty_print is None: opts.pretty_print = True print startup_msg else: prompt = "" if opts.pretty_print is None: opts.pretty_print = False # use of eval might allow arbitrary code execution - probably not entirely safe if opts.ask: process = lambda c: eval('server.ask("%s")' % c.strip()) else: process = lambda c: eval("server." + c.strip()) if opts.pretty_print: formatter = pformat else: formatter = repr # This is nasty way to enforce encoleast_common_subsumers("fiets", "auto")ding of strings embedded in lists or dicts. # For examample [u'plafonnière'] rather than [u"plafonni\xe8re"] encoder = lambda s: s.decode("unicode_escape").encode(opts.encoding, "backslashreplace") while True: try: command = raw_input(prompt) if command == "?": print help_text else: result = process(command) print encoder(formatter(result)) except EOFError: print "\nSee you later alligator!" exit(0) except KeyboardInterrupt: print >>stderr, "\nInterrupted. Latest command may still run on the server though..." except SyntaxError: print >>stderr, "Error: invalid syntax" except NameError, inst: print >>stderr, "Error:", inst, "- use quotes?" except xmlrpclib.Error, inst: print >>stderr, inst except SocketError: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?\n" % ( inst, host, port), "See cornetto-server.py -h"<|fim▁end|>
# This file is part of the Pycornetto package.
<|file_name|>cornetto-client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008-2013 by # Erwin Marsi and Tilburg University # This file is part of the Pycornetto package. # Pycornetto is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # Pycornetto is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ A simple client to connect to the Cornetto database server. Reads queries from standard input and writes results to standard output. """ # BUGS: # - there is no way interrupt a query that goes bad on the server, as obviously # a local Ctrl-C does not work __author__ = 'Erwin Marsi <[email protected]>' __version__ = '0.6.1' # using optparse instead of argparse so client can run stand-alone from sys import stdin, stdout, stderr, exit from optparse import OptionParser, IndentedHelpFormatter import xmlrpclib from pprint import pformat from socket import error as SocketError class MyFormatter(IndentedHelpFormatter): <|fim_middle|> epilog = """ Interactive usage: $ cornetto-client.py $ cornetto-client.py -a File processing: $ echo 'ask("pijp")' | cornetto-client.py $ cornetto-client.py <input >output """ try: parser = OptionParser(description=__doc__, version="%(prog)s version " + __version__, epilog=epilog, formatter=MyFormatter()) except TypeError: # optparse in python 2.4 has no epilog keyword parser = OptionParser(description=__doc__ + epilog, version="%(prog)s version " + __version__) parser.add_option("-a", "--ask", action='store_true', help="assume all commands are input the 'ask' function, " "- so you can type 'query' instead of 'ask(\"query\") - '" "but online help is no longer accessible" ) parser.add_option("-H", "--host", default="localhost:5204", metavar="HOST[:PORT]", help="name or IP address of host (default is 'localhost') " "optionally followed by a port number " "(default is 5204)") parser.add_option('-n', '--no-pretty-print', dest="pretty_print", action='store_false', help="turn off pretty printing of output " "(default when standard input is a file)") parser.add_option("-p", "--port", type=int, default=5204, help='port number (default is 5204)') parser.add_option('-P', '--pretty-print', dest="pretty_print", action='store_true', help="turn on pretty printing of output " "(default when standard input is a tty)") parser.add_option("-e", "--encoding", default="utf8", metavar="utf8,latin1,ascii,...", help="character encoding of output (default is utf8)") parser.add_option('-V', '--verbose', action='store_true', help="verbose output for debugging") (opts, args) = parser.parse_args() if opts.host.startswith("http://"): opts.host = opts.host[7:] try: host, port = opts.host.split(":")[:2] except ValueError: host, port = opts.host, None # XMP-RPC requires specification of protocol host = "http://" + (host or "localhost") try: port = int(port or 5204) except ValueError: exit("Error: %s is not a valid port number" % repr(port)) server = xmlrpclib.ServerProxy("%s:%s" % (host, port), encoding="utf-8", verbose=opts.verbose) try: eval('server.echo("test")') except SocketError, inst: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?" % ( inst, host, port), "See cornetto-server.py -h" exit(1) help_text = """ Type "?" to see his message. Type "help()" for help on available methods. Type "Ctrl-D" to exit. Restart with "cornetto-client.py -h" to see command line options. """ startup_msg = ( "cornetto-client.py (version %s)\n" % __version__ + "Copyright (c) Erwin Marsi\n" + help_text ) if stdin.isatty(): prompt = "$ " if opts.pretty_print is None: opts.pretty_print = True print startup_msg else: prompt = "" if opts.pretty_print is None: opts.pretty_print = False # use of eval might allow arbitrary code execution - probably not entirely safe if opts.ask: process = lambda c: eval('server.ask("%s")' % c.strip()) else: process = lambda c: eval("server." + c.strip()) if opts.pretty_print: formatter = pformat else: formatter = repr # This is nasty way to enforce encoleast_common_subsumers("fiets", "auto")ding of strings embedded in lists or dicts. # For examample [u'plafonnière'] rather than [u"plafonni\xe8re"] encoder = lambda s: s.decode("unicode_escape").encode(opts.encoding, "backslashreplace") while True: try: command = raw_input(prompt) if command == "?": print help_text else: result = process(command) print encoder(formatter(result)) except EOFError: print "\nSee you later alligator!" exit(0) except KeyboardInterrupt: print >>stderr, "\nInterrupted. Latest command may still run on the server though..." except SyntaxError: print >>stderr, "Error: invalid syntax" except NameError, inst: print >>stderr, "Error:", inst, "- use quotes?" except xmlrpclib.Error, inst: print >>stderr, inst except SocketError: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?\n" % ( inst, host, port), "See cornetto-server.py -h" <|fim▁end|>
"""to prevent optparse from messing up the epilog text""" def format_epilog(self, epilog): return epilog or "" def format_description(self, description): return description.lstrip()
<|file_name|>cornetto-client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008-2013 by # Erwin Marsi and Tilburg University # This file is part of the Pycornetto package. # Pycornetto is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # Pycornetto is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ A simple client to connect to the Cornetto database server. Reads queries from standard input and writes results to standard output. """ # BUGS: # - there is no way interrupt a query that goes bad on the server, as obviously # a local Ctrl-C does not work __author__ = 'Erwin Marsi <[email protected]>' __version__ = '0.6.1' # using optparse instead of argparse so client can run stand-alone from sys import stdin, stdout, stderr, exit from optparse import OptionParser, IndentedHelpFormatter import xmlrpclib from pprint import pformat from socket import error as SocketError class MyFormatter(IndentedHelpFormatter): """to prevent optparse from messing up the epilog text""" def format_epilog(self, epilog): <|fim_middle|> def format_description(self, description): return description.lstrip() epilog = """ Interactive usage: $ cornetto-client.py $ cornetto-client.py -a File processing: $ echo 'ask("pijp")' | cornetto-client.py $ cornetto-client.py <input >output """ try: parser = OptionParser(description=__doc__, version="%(prog)s version " + __version__, epilog=epilog, formatter=MyFormatter()) except TypeError: # optparse in python 2.4 has no epilog keyword parser = OptionParser(description=__doc__ + epilog, version="%(prog)s version " + __version__) parser.add_option("-a", "--ask", action='store_true', help="assume all commands are input the 'ask' function, " "- so you can type 'query' instead of 'ask(\"query\") - '" "but online help is no longer accessible" ) parser.add_option("-H", "--host", default="localhost:5204", metavar="HOST[:PORT]", help="name or IP address of host (default is 'localhost') " "optionally followed by a port number " "(default is 5204)") parser.add_option('-n', '--no-pretty-print', dest="pretty_print", action='store_false', help="turn off pretty printing of output " "(default when standard input is a file)") parser.add_option("-p", "--port", type=int, default=5204, help='port number (default is 5204)') parser.add_option('-P', '--pretty-print', dest="pretty_print", action='store_true', help="turn on pretty printing of output " "(default when standard input is a tty)") parser.add_option("-e", "--encoding", default="utf8", metavar="utf8,latin1,ascii,...", help="character encoding of output (default is utf8)") parser.add_option('-V', '--verbose', action='store_true', help="verbose output for debugging") (opts, args) = parser.parse_args() if opts.host.startswith("http://"): opts.host = opts.host[7:] try: host, port = opts.host.split(":")[:2] except ValueError: host, port = opts.host, None # XMP-RPC requires specification of protocol host = "http://" + (host or "localhost") try: port = int(port or 5204) except ValueError: exit("Error: %s is not a valid port number" % repr(port)) server = xmlrpclib.ServerProxy("%s:%s" % (host, port), encoding="utf-8", verbose=opts.verbose) try: eval('server.echo("test")') except SocketError, inst: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?" % ( inst, host, port), "See cornetto-server.py -h" exit(1) help_text = """ Type "?" to see his message. Type "help()" for help on available methods. Type "Ctrl-D" to exit. Restart with "cornetto-client.py -h" to see command line options. """ startup_msg = ( "cornetto-client.py (version %s)\n" % __version__ + "Copyright (c) Erwin Marsi\n" + help_text ) if stdin.isatty(): prompt = "$ " if opts.pretty_print is None: opts.pretty_print = True print startup_msg else: prompt = "" if opts.pretty_print is None: opts.pretty_print = False # use of eval might allow arbitrary code execution - probably not entirely safe if opts.ask: process = lambda c: eval('server.ask("%s")' % c.strip()) else: process = lambda c: eval("server." + c.strip()) if opts.pretty_print: formatter = pformat else: formatter = repr # This is nasty way to enforce encoleast_common_subsumers("fiets", "auto")ding of strings embedded in lists or dicts. # For examample [u'plafonnière'] rather than [u"plafonni\xe8re"] encoder = lambda s: s.decode("unicode_escape").encode(opts.encoding, "backslashreplace") while True: try: command = raw_input(prompt) if command == "?": print help_text else: result = process(command) print encoder(formatter(result)) except EOFError: print "\nSee you later alligator!" exit(0) except KeyboardInterrupt: print >>stderr, "\nInterrupted. Latest command may still run on the server though..." except SyntaxError: print >>stderr, "Error: invalid syntax" except NameError, inst: print >>stderr, "Error:", inst, "- use quotes?" except xmlrpclib.Error, inst: print >>stderr, inst except SocketError: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?\n" % ( inst, host, port), "See cornetto-server.py -h" <|fim▁end|>
return epilog or ""
<|file_name|>cornetto-client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008-2013 by # Erwin Marsi and Tilburg University # This file is part of the Pycornetto package. # Pycornetto is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # Pycornetto is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ A simple client to connect to the Cornetto database server. Reads queries from standard input and writes results to standard output. """ # BUGS: # - there is no way interrupt a query that goes bad on the server, as obviously # a local Ctrl-C does not work __author__ = 'Erwin Marsi <[email protected]>' __version__ = '0.6.1' # using optparse instead of argparse so client can run stand-alone from sys import stdin, stdout, stderr, exit from optparse import OptionParser, IndentedHelpFormatter import xmlrpclib from pprint import pformat from socket import error as SocketError class MyFormatter(IndentedHelpFormatter): """to prevent optparse from messing up the epilog text""" def format_epilog(self, epilog): return epilog or "" def format_description(self, description): <|fim_middle|> epilog = """ Interactive usage: $ cornetto-client.py $ cornetto-client.py -a File processing: $ echo 'ask("pijp")' | cornetto-client.py $ cornetto-client.py <input >output """ try: parser = OptionParser(description=__doc__, version="%(prog)s version " + __version__, epilog=epilog, formatter=MyFormatter()) except TypeError: # optparse in python 2.4 has no epilog keyword parser = OptionParser(description=__doc__ + epilog, version="%(prog)s version " + __version__) parser.add_option("-a", "--ask", action='store_true', help="assume all commands are input the 'ask' function, " "- so you can type 'query' instead of 'ask(\"query\") - '" "but online help is no longer accessible" ) parser.add_option("-H", "--host", default="localhost:5204", metavar="HOST[:PORT]", help="name or IP address of host (default is 'localhost') " "optionally followed by a port number " "(default is 5204)") parser.add_option('-n', '--no-pretty-print', dest="pretty_print", action='store_false', help="turn off pretty printing of output " "(default when standard input is a file)") parser.add_option("-p", "--port", type=int, default=5204, help='port number (default is 5204)') parser.add_option('-P', '--pretty-print', dest="pretty_print", action='store_true', help="turn on pretty printing of output " "(default when standard input is a tty)") parser.add_option("-e", "--encoding", default="utf8", metavar="utf8,latin1,ascii,...", help="character encoding of output (default is utf8)") parser.add_option('-V', '--verbose', action='store_true', help="verbose output for debugging") (opts, args) = parser.parse_args() if opts.host.startswith("http://"): opts.host = opts.host[7:] try: host, port = opts.host.split(":")[:2] except ValueError: host, port = opts.host, None # XMP-RPC requires specification of protocol host = "http://" + (host or "localhost") try: port = int(port or 5204) except ValueError: exit("Error: %s is not a valid port number" % repr(port)) server = xmlrpclib.ServerProxy("%s:%s" % (host, port), encoding="utf-8", verbose=opts.verbose) try: eval('server.echo("test")') except SocketError, inst: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?" % ( inst, host, port), "See cornetto-server.py -h" exit(1) help_text = """ Type "?" to see his message. Type "help()" for help on available methods. Type "Ctrl-D" to exit. Restart with "cornetto-client.py -h" to see command line options. """ startup_msg = ( "cornetto-client.py (version %s)\n" % __version__ + "Copyright (c) Erwin Marsi\n" + help_text ) if stdin.isatty(): prompt = "$ " if opts.pretty_print is None: opts.pretty_print = True print startup_msg else: prompt = "" if opts.pretty_print is None: opts.pretty_print = False # use of eval might allow arbitrary code execution - probably not entirely safe if opts.ask: process = lambda c: eval('server.ask("%s")' % c.strip()) else: process = lambda c: eval("server." + c.strip()) if opts.pretty_print: formatter = pformat else: formatter = repr # This is nasty way to enforce encoleast_common_subsumers("fiets", "auto")ding of strings embedded in lists or dicts. # For examample [u'plafonnière'] rather than [u"plafonni\xe8re"] encoder = lambda s: s.decode("unicode_escape").encode(opts.encoding, "backslashreplace") while True: try: command = raw_input(prompt) if command == "?": print help_text else: result = process(command) print encoder(formatter(result)) except EOFError: print "\nSee you later alligator!" exit(0) except KeyboardInterrupt: print >>stderr, "\nInterrupted. Latest command may still run on the server though..." except SyntaxError: print >>stderr, "Error: invalid syntax" except NameError, inst: print >>stderr, "Error:", inst, "- use quotes?" except xmlrpclib.Error, inst: print >>stderr, inst except SocketError: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?\n" % ( inst, host, port), "See cornetto-server.py -h" <|fim▁end|>
return description.lstrip()
<|file_name|>cornetto-client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008-2013 by # Erwin Marsi and Tilburg University # This file is part of the Pycornetto package. # Pycornetto is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # Pycornetto is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ A simple client to connect to the Cornetto database server. Reads queries from standard input and writes results to standard output. """ # BUGS: # - there is no way interrupt a query that goes bad on the server, as obviously # a local Ctrl-C does not work __author__ = 'Erwin Marsi <[email protected]>' __version__ = '0.6.1' # using optparse instead of argparse so client can run stand-alone from sys import stdin, stdout, stderr, exit from optparse import OptionParser, IndentedHelpFormatter import xmlrpclib from pprint import pformat from socket import error as SocketError class MyFormatter(IndentedHelpFormatter): """to prevent optparse from messing up the epilog text""" def format_epilog(self, epilog): return epilog or "" def format_description(self, description): return description.lstrip() epilog = """ Interactive usage: $ cornetto-client.py $ cornetto-client.py -a File processing: $ echo 'ask("pijp")' | cornetto-client.py $ cornetto-client.py <input >output """ try: parser = OptionParser(description=__doc__, version="%(prog)s version " + __version__, epilog=epilog, formatter=MyFormatter()) except TypeError: # optparse in python 2.4 has no epilog keyword parser = OptionParser(description=__doc__ + epilog, version="%(prog)s version " + __version__) parser.add_option("-a", "--ask", action='store_true', help="assume all commands are input the 'ask' function, " "- so you can type 'query' instead of 'ask(\"query\") - '" "but online help is no longer accessible" ) parser.add_option("-H", "--host", default="localhost:5204", metavar="HOST[:PORT]", help="name or IP address of host (default is 'localhost') " "optionally followed by a port number " "(default is 5204)") parser.add_option('-n', '--no-pretty-print', dest="pretty_print", action='store_false', help="turn off pretty printing of output " "(default when standard input is a file)") parser.add_option("-p", "--port", type=int, default=5204, help='port number (default is 5204)') parser.add_option('-P', '--pretty-print', dest="pretty_print", action='store_true', help="turn on pretty printing of output " "(default when standard input is a tty)") parser.add_option("-e", "--encoding", default="utf8", metavar="utf8,latin1,ascii,...", help="character encoding of output (default is utf8)") parser.add_option('-V', '--verbose', action='store_true', help="verbose output for debugging") (opts, args) = parser.parse_args() if opts.host.startswith("http://"): <|fim_middle|> try: host, port = opts.host.split(":")[:2] except ValueError: host, port = opts.host, None # XMP-RPC requires specification of protocol host = "http://" + (host or "localhost") try: port = int(port or 5204) except ValueError: exit("Error: %s is not a valid port number" % repr(port)) server = xmlrpclib.ServerProxy("%s:%s" % (host, port), encoding="utf-8", verbose=opts.verbose) try: eval('server.echo("test")') except SocketError, inst: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?" % ( inst, host, port), "See cornetto-server.py -h" exit(1) help_text = """ Type "?" to see his message. Type "help()" for help on available methods. Type "Ctrl-D" to exit. Restart with "cornetto-client.py -h" to see command line options. """ startup_msg = ( "cornetto-client.py (version %s)\n" % __version__ + "Copyright (c) Erwin Marsi\n" + help_text ) if stdin.isatty(): prompt = "$ " if opts.pretty_print is None: opts.pretty_print = True print startup_msg else: prompt = "" if opts.pretty_print is None: opts.pretty_print = False # use of eval might allow arbitrary code execution - probably not entirely safe if opts.ask: process = lambda c: eval('server.ask("%s")' % c.strip()) else: process = lambda c: eval("server." + c.strip()) if opts.pretty_print: formatter = pformat else: formatter = repr # This is nasty way to enforce encoleast_common_subsumers("fiets", "auto")ding of strings embedded in lists or dicts. # For examample [u'plafonnière'] rather than [u"plafonni\xe8re"] encoder = lambda s: s.decode("unicode_escape").encode(opts.encoding, "backslashreplace") while True: try: command = raw_input(prompt) if command == "?": print help_text else: result = process(command) print encoder(formatter(result)) except EOFError: print "\nSee you later alligator!" exit(0) except KeyboardInterrupt: print >>stderr, "\nInterrupted. Latest command may still run on the server though..." except SyntaxError: print >>stderr, "Error: invalid syntax" except NameError, inst: print >>stderr, "Error:", inst, "- use quotes?" except xmlrpclib.Error, inst: print >>stderr, inst except SocketError: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?\n" % ( inst, host, port), "See cornetto-server.py -h" <|fim▁end|>
opts.host = opts.host[7:]
<|file_name|>cornetto-client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008-2013 by # Erwin Marsi and Tilburg University # This file is part of the Pycornetto package. # Pycornetto is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # Pycornetto is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ A simple client to connect to the Cornetto database server. Reads queries from standard input and writes results to standard output. """ # BUGS: # - there is no way interrupt a query that goes bad on the server, as obviously # a local Ctrl-C does not work __author__ = 'Erwin Marsi <[email protected]>' __version__ = '0.6.1' # using optparse instead of argparse so client can run stand-alone from sys import stdin, stdout, stderr, exit from optparse import OptionParser, IndentedHelpFormatter import xmlrpclib from pprint import pformat from socket import error as SocketError class MyFormatter(IndentedHelpFormatter): """to prevent optparse from messing up the epilog text""" def format_epilog(self, epilog): return epilog or "" def format_description(self, description): return description.lstrip() epilog = """ Interactive usage: $ cornetto-client.py $ cornetto-client.py -a File processing: $ echo 'ask("pijp")' | cornetto-client.py $ cornetto-client.py <input >output """ try: parser = OptionParser(description=__doc__, version="%(prog)s version " + __version__, epilog=epilog, formatter=MyFormatter()) except TypeError: # optparse in python 2.4 has no epilog keyword parser = OptionParser(description=__doc__ + epilog, version="%(prog)s version " + __version__) parser.add_option("-a", "--ask", action='store_true', help="assume all commands are input the 'ask' function, " "- so you can type 'query' instead of 'ask(\"query\") - '" "but online help is no longer accessible" ) parser.add_option("-H", "--host", default="localhost:5204", metavar="HOST[:PORT]", help="name or IP address of host (default is 'localhost') " "optionally followed by a port number " "(default is 5204)") parser.add_option('-n', '--no-pretty-print', dest="pretty_print", action='store_false', help="turn off pretty printing of output " "(default when standard input is a file)") parser.add_option("-p", "--port", type=int, default=5204, help='port number (default is 5204)') parser.add_option('-P', '--pretty-print', dest="pretty_print", action='store_true', help="turn on pretty printing of output " "(default when standard input is a tty)") parser.add_option("-e", "--encoding", default="utf8", metavar="utf8,latin1,ascii,...", help="character encoding of output (default is utf8)") parser.add_option('-V', '--verbose', action='store_true', help="verbose output for debugging") (opts, args) = parser.parse_args() if opts.host.startswith("http://"): opts.host = opts.host[7:] try: host, port = opts.host.split(":")[:2] except ValueError: host, port = opts.host, None # XMP-RPC requires specification of protocol host = "http://" + (host or "localhost") try: port = int(port or 5204) except ValueError: exit("Error: %s is not a valid port number" % repr(port)) server = xmlrpclib.ServerProxy("%s:%s" % (host, port), encoding="utf-8", verbose=opts.verbose) try: eval('server.echo("test")') except SocketError, inst: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?" % ( inst, host, port), "See cornetto-server.py -h" exit(1) help_text = """ Type "?" to see his message. Type "help()" for help on available methods. Type "Ctrl-D" to exit. Restart with "cornetto-client.py -h" to see command line options. """ startup_msg = ( "cornetto-client.py (version %s)\n" % __version__ + "Copyright (c) Erwin Marsi\n" + help_text ) if stdin.isatty(): <|fim_middle|> else: prompt = "" if opts.pretty_print is None: opts.pretty_print = False # use of eval might allow arbitrary code execution - probably not entirely safe if opts.ask: process = lambda c: eval('server.ask("%s")' % c.strip()) else: process = lambda c: eval("server." + c.strip()) if opts.pretty_print: formatter = pformat else: formatter = repr # This is nasty way to enforce encoleast_common_subsumers("fiets", "auto")ding of strings embedded in lists or dicts. # For examample [u'plafonnière'] rather than [u"plafonni\xe8re"] encoder = lambda s: s.decode("unicode_escape").encode(opts.encoding, "backslashreplace") while True: try: command = raw_input(prompt) if command == "?": print help_text else: result = process(command) print encoder(formatter(result)) except EOFError: print "\nSee you later alligator!" exit(0) except KeyboardInterrupt: print >>stderr, "\nInterrupted. Latest command may still run on the server though..." except SyntaxError: print >>stderr, "Error: invalid syntax" except NameError, inst: print >>stderr, "Error:", inst, "- use quotes?" except xmlrpclib.Error, inst: print >>stderr, inst except SocketError: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?\n" % ( inst, host, port), "See cornetto-server.py -h" <|fim▁end|>
prompt = "$ " if opts.pretty_print is None: opts.pretty_print = True print startup_msg
<|file_name|>cornetto-client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008-2013 by # Erwin Marsi and Tilburg University # This file is part of the Pycornetto package. # Pycornetto is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # Pycornetto is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ A simple client to connect to the Cornetto database server. Reads queries from standard input and writes results to standard output. """ # BUGS: # - there is no way interrupt a query that goes bad on the server, as obviously # a local Ctrl-C does not work __author__ = 'Erwin Marsi <[email protected]>' __version__ = '0.6.1' # using optparse instead of argparse so client can run stand-alone from sys import stdin, stdout, stderr, exit from optparse import OptionParser, IndentedHelpFormatter import xmlrpclib from pprint import pformat from socket import error as SocketError class MyFormatter(IndentedHelpFormatter): """to prevent optparse from messing up the epilog text""" def format_epilog(self, epilog): return epilog or "" def format_description(self, description): return description.lstrip() epilog = """ Interactive usage: $ cornetto-client.py $ cornetto-client.py -a File processing: $ echo 'ask("pijp")' | cornetto-client.py $ cornetto-client.py <input >output """ try: parser = OptionParser(description=__doc__, version="%(prog)s version " + __version__, epilog=epilog, formatter=MyFormatter()) except TypeError: # optparse in python 2.4 has no epilog keyword parser = OptionParser(description=__doc__ + epilog, version="%(prog)s version " + __version__) parser.add_option("-a", "--ask", action='store_true', help="assume all commands are input the 'ask' function, " "- so you can type 'query' instead of 'ask(\"query\") - '" "but online help is no longer accessible" ) parser.add_option("-H", "--host", default="localhost:5204", metavar="HOST[:PORT]", help="name or IP address of host (default is 'localhost') " "optionally followed by a port number " "(default is 5204)") parser.add_option('-n', '--no-pretty-print', dest="pretty_print", action='store_false', help="turn off pretty printing of output " "(default when standard input is a file)") parser.add_option("-p", "--port", type=int, default=5204, help='port number (default is 5204)') parser.add_option('-P', '--pretty-print', dest="pretty_print", action='store_true', help="turn on pretty printing of output " "(default when standard input is a tty)") parser.add_option("-e", "--encoding", default="utf8", metavar="utf8,latin1,ascii,...", help="character encoding of output (default is utf8)") parser.add_option('-V', '--verbose', action='store_true', help="verbose output for debugging") (opts, args) = parser.parse_args() if opts.host.startswith("http://"): opts.host = opts.host[7:] try: host, port = opts.host.split(":")[:2] except ValueError: host, port = opts.host, None # XMP-RPC requires specification of protocol host = "http://" + (host or "localhost") try: port = int(port or 5204) except ValueError: exit("Error: %s is not a valid port number" % repr(port)) server = xmlrpclib.ServerProxy("%s:%s" % (host, port), encoding="utf-8", verbose=opts.verbose) try: eval('server.echo("test")') except SocketError, inst: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?" % ( inst, host, port), "See cornetto-server.py -h" exit(1) help_text = """ Type "?" to see his message. Type "help()" for help on available methods. Type "Ctrl-D" to exit. Restart with "cornetto-client.py -h" to see command line options. """ startup_msg = ( "cornetto-client.py (version %s)\n" % __version__ + "Copyright (c) Erwin Marsi\n" + help_text ) if stdin.isatty(): prompt = "$ " if opts.pretty_print is None: <|fim_middle|> print startup_msg else: prompt = "" if opts.pretty_print is None: opts.pretty_print = False # use of eval might allow arbitrary code execution - probably not entirely safe if opts.ask: process = lambda c: eval('server.ask("%s")' % c.strip()) else: process = lambda c: eval("server." + c.strip()) if opts.pretty_print: formatter = pformat else: formatter = repr # This is nasty way to enforce encoleast_common_subsumers("fiets", "auto")ding of strings embedded in lists or dicts. # For examample [u'plafonnière'] rather than [u"plafonni\xe8re"] encoder = lambda s: s.decode("unicode_escape").encode(opts.encoding, "backslashreplace") while True: try: command = raw_input(prompt) if command == "?": print help_text else: result = process(command) print encoder(formatter(result)) except EOFError: print "\nSee you later alligator!" exit(0) except KeyboardInterrupt: print >>stderr, "\nInterrupted. Latest command may still run on the server though..." except SyntaxError: print >>stderr, "Error: invalid syntax" except NameError, inst: print >>stderr, "Error:", inst, "- use quotes?" except xmlrpclib.Error, inst: print >>stderr, inst except SocketError: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?\n" % ( inst, host, port), "See cornetto-server.py -h" <|fim▁end|>
opts.pretty_print = True
<|file_name|>cornetto-client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008-2013 by # Erwin Marsi and Tilburg University # This file is part of the Pycornetto package. # Pycornetto is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # Pycornetto is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ A simple client to connect to the Cornetto database server. Reads queries from standard input and writes results to standard output. """ # BUGS: # - there is no way interrupt a query that goes bad on the server, as obviously # a local Ctrl-C does not work __author__ = 'Erwin Marsi <[email protected]>' __version__ = '0.6.1' # using optparse instead of argparse so client can run stand-alone from sys import stdin, stdout, stderr, exit from optparse import OptionParser, IndentedHelpFormatter import xmlrpclib from pprint import pformat from socket import error as SocketError class MyFormatter(IndentedHelpFormatter): """to prevent optparse from messing up the epilog text""" def format_epilog(self, epilog): return epilog or "" def format_description(self, description): return description.lstrip() epilog = """ Interactive usage: $ cornetto-client.py $ cornetto-client.py -a File processing: $ echo 'ask("pijp")' | cornetto-client.py $ cornetto-client.py <input >output """ try: parser = OptionParser(description=__doc__, version="%(prog)s version " + __version__, epilog=epilog, formatter=MyFormatter()) except TypeError: # optparse in python 2.4 has no epilog keyword parser = OptionParser(description=__doc__ + epilog, version="%(prog)s version " + __version__) parser.add_option("-a", "--ask", action='store_true', help="assume all commands are input the 'ask' function, " "- so you can type 'query' instead of 'ask(\"query\") - '" "but online help is no longer accessible" ) parser.add_option("-H", "--host", default="localhost:5204", metavar="HOST[:PORT]", help="name or IP address of host (default is 'localhost') " "optionally followed by a port number " "(default is 5204)") parser.add_option('-n', '--no-pretty-print', dest="pretty_print", action='store_false', help="turn off pretty printing of output " "(default when standard input is a file)") parser.add_option("-p", "--port", type=int, default=5204, help='port number (default is 5204)') parser.add_option('-P', '--pretty-print', dest="pretty_print", action='store_true', help="turn on pretty printing of output " "(default when standard input is a tty)") parser.add_option("-e", "--encoding", default="utf8", metavar="utf8,latin1,ascii,...", help="character encoding of output (default is utf8)") parser.add_option('-V', '--verbose', action='store_true', help="verbose output for debugging") (opts, args) = parser.parse_args() if opts.host.startswith("http://"): opts.host = opts.host[7:] try: host, port = opts.host.split(":")[:2] except ValueError: host, port = opts.host, None # XMP-RPC requires specification of protocol host = "http://" + (host or "localhost") try: port = int(port or 5204) except ValueError: exit("Error: %s is not a valid port number" % repr(port)) server = xmlrpclib.ServerProxy("%s:%s" % (host, port), encoding="utf-8", verbose=opts.verbose) try: eval('server.echo("test")') except SocketError, inst: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?" % ( inst, host, port), "See cornetto-server.py -h" exit(1) help_text = """ Type "?" to see his message. Type "help()" for help on available methods. Type "Ctrl-D" to exit. Restart with "cornetto-client.py -h" to see command line options. """ startup_msg = ( "cornetto-client.py (version %s)\n" % __version__ + "Copyright (c) Erwin Marsi\n" + help_text ) if stdin.isatty(): prompt = "$ " if opts.pretty_print is None: opts.pretty_print = True print startup_msg else: <|fim_middle|> # use of eval might allow arbitrary code execution - probably not entirely safe if opts.ask: process = lambda c: eval('server.ask("%s")' % c.strip()) else: process = lambda c: eval("server." + c.strip()) if opts.pretty_print: formatter = pformat else: formatter = repr # This is nasty way to enforce encoleast_common_subsumers("fiets", "auto")ding of strings embedded in lists or dicts. # For examample [u'plafonnière'] rather than [u"plafonni\xe8re"] encoder = lambda s: s.decode("unicode_escape").encode(opts.encoding, "backslashreplace") while True: try: command = raw_input(prompt) if command == "?": print help_text else: result = process(command) print encoder(formatter(result)) except EOFError: print "\nSee you later alligator!" exit(0) except KeyboardInterrupt: print >>stderr, "\nInterrupted. Latest command may still run on the server though..." except SyntaxError: print >>stderr, "Error: invalid syntax" except NameError, inst: print >>stderr, "Error:", inst, "- use quotes?" except xmlrpclib.Error, inst: print >>stderr, inst except SocketError: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?\n" % ( inst, host, port), "See cornetto-server.py -h" <|fim▁end|>
prompt = "" if opts.pretty_print is None: opts.pretty_print = False
<|file_name|>cornetto-client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008-2013 by # Erwin Marsi and Tilburg University # This file is part of the Pycornetto package. # Pycornetto is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # Pycornetto is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ A simple client to connect to the Cornetto database server. Reads queries from standard input and writes results to standard output. """ # BUGS: # - there is no way interrupt a query that goes bad on the server, as obviously # a local Ctrl-C does not work __author__ = 'Erwin Marsi <[email protected]>' __version__ = '0.6.1' # using optparse instead of argparse so client can run stand-alone from sys import stdin, stdout, stderr, exit from optparse import OptionParser, IndentedHelpFormatter import xmlrpclib from pprint import pformat from socket import error as SocketError class MyFormatter(IndentedHelpFormatter): """to prevent optparse from messing up the epilog text""" def format_epilog(self, epilog): return epilog or "" def format_description(self, description): return description.lstrip() epilog = """ Interactive usage: $ cornetto-client.py $ cornetto-client.py -a File processing: $ echo 'ask("pijp")' | cornetto-client.py $ cornetto-client.py <input >output """ try: parser = OptionParser(description=__doc__, version="%(prog)s version " + __version__, epilog=epilog, formatter=MyFormatter()) except TypeError: # optparse in python 2.4 has no epilog keyword parser = OptionParser(description=__doc__ + epilog, version="%(prog)s version " + __version__) parser.add_option("-a", "--ask", action='store_true', help="assume all commands are input the 'ask' function, " "- so you can type 'query' instead of 'ask(\"query\") - '" "but online help is no longer accessible" ) parser.add_option("-H", "--host", default="localhost:5204", metavar="HOST[:PORT]", help="name or IP address of host (default is 'localhost') " "optionally followed by a port number " "(default is 5204)") parser.add_option('-n', '--no-pretty-print', dest="pretty_print", action='store_false', help="turn off pretty printing of output " "(default when standard input is a file)") parser.add_option("-p", "--port", type=int, default=5204, help='port number (default is 5204)') parser.add_option('-P', '--pretty-print', dest="pretty_print", action='store_true', help="turn on pretty printing of output " "(default when standard input is a tty)") parser.add_option("-e", "--encoding", default="utf8", metavar="utf8,latin1,ascii,...", help="character encoding of output (default is utf8)") parser.add_option('-V', '--verbose', action='store_true', help="verbose output for debugging") (opts, args) = parser.parse_args() if opts.host.startswith("http://"): opts.host = opts.host[7:] try: host, port = opts.host.split(":")[:2] except ValueError: host, port = opts.host, None # XMP-RPC requires specification of protocol host = "http://" + (host or "localhost") try: port = int(port or 5204) except ValueError: exit("Error: %s is not a valid port number" % repr(port)) server = xmlrpclib.ServerProxy("%s:%s" % (host, port), encoding="utf-8", verbose=opts.verbose) try: eval('server.echo("test")') except SocketError, inst: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?" % ( inst, host, port), "See cornetto-server.py -h" exit(1) help_text = """ Type "?" to see his message. Type "help()" for help on available methods. Type "Ctrl-D" to exit. Restart with "cornetto-client.py -h" to see command line options. """ startup_msg = ( "cornetto-client.py (version %s)\n" % __version__ + "Copyright (c) Erwin Marsi\n" + help_text ) if stdin.isatty(): prompt = "$ " if opts.pretty_print is None: opts.pretty_print = True print startup_msg else: prompt = "" if opts.pretty_print is None: <|fim_middle|> # use of eval might allow arbitrary code execution - probably not entirely safe if opts.ask: process = lambda c: eval('server.ask("%s")' % c.strip()) else: process = lambda c: eval("server." + c.strip()) if opts.pretty_print: formatter = pformat else: formatter = repr # This is nasty way to enforce encoleast_common_subsumers("fiets", "auto")ding of strings embedded in lists or dicts. # For examample [u'plafonnière'] rather than [u"plafonni\xe8re"] encoder = lambda s: s.decode("unicode_escape").encode(opts.encoding, "backslashreplace") while True: try: command = raw_input(prompt) if command == "?": print help_text else: result = process(command) print encoder(formatter(result)) except EOFError: print "\nSee you later alligator!" exit(0) except KeyboardInterrupt: print >>stderr, "\nInterrupted. Latest command may still run on the server though..." except SyntaxError: print >>stderr, "Error: invalid syntax" except NameError, inst: print >>stderr, "Error:", inst, "- use quotes?" except xmlrpclib.Error, inst: print >>stderr, inst except SocketError: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?\n" % ( inst, host, port), "See cornetto-server.py -h" <|fim▁end|>
opts.pretty_print = False
<|file_name|>cornetto-client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008-2013 by # Erwin Marsi and Tilburg University # This file is part of the Pycornetto package. # Pycornetto is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # Pycornetto is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ A simple client to connect to the Cornetto database server. Reads queries from standard input and writes results to standard output. """ # BUGS: # - there is no way interrupt a query that goes bad on the server, as obviously # a local Ctrl-C does not work __author__ = 'Erwin Marsi <[email protected]>' __version__ = '0.6.1' # using optparse instead of argparse so client can run stand-alone from sys import stdin, stdout, stderr, exit from optparse import OptionParser, IndentedHelpFormatter import xmlrpclib from pprint import pformat from socket import error as SocketError class MyFormatter(IndentedHelpFormatter): """to prevent optparse from messing up the epilog text""" def format_epilog(self, epilog): return epilog or "" def format_description(self, description): return description.lstrip() epilog = """ Interactive usage: $ cornetto-client.py $ cornetto-client.py -a File processing: $ echo 'ask("pijp")' | cornetto-client.py $ cornetto-client.py <input >output """ try: parser = OptionParser(description=__doc__, version="%(prog)s version " + __version__, epilog=epilog, formatter=MyFormatter()) except TypeError: # optparse in python 2.4 has no epilog keyword parser = OptionParser(description=__doc__ + epilog, version="%(prog)s version " + __version__) parser.add_option("-a", "--ask", action='store_true', help="assume all commands are input the 'ask' function, " "- so you can type 'query' instead of 'ask(\"query\") - '" "but online help is no longer accessible" ) parser.add_option("-H", "--host", default="localhost:5204", metavar="HOST[:PORT]", help="name or IP address of host (default is 'localhost') " "optionally followed by a port number " "(default is 5204)") parser.add_option('-n', '--no-pretty-print', dest="pretty_print", action='store_false', help="turn off pretty printing of output " "(default when standard input is a file)") parser.add_option("-p", "--port", type=int, default=5204, help='port number (default is 5204)') parser.add_option('-P', '--pretty-print', dest="pretty_print", action='store_true', help="turn on pretty printing of output " "(default when standard input is a tty)") parser.add_option("-e", "--encoding", default="utf8", metavar="utf8,latin1,ascii,...", help="character encoding of output (default is utf8)") parser.add_option('-V', '--verbose', action='store_true', help="verbose output for debugging") (opts, args) = parser.parse_args() if opts.host.startswith("http://"): opts.host = opts.host[7:] try: host, port = opts.host.split(":")[:2] except ValueError: host, port = opts.host, None # XMP-RPC requires specification of protocol host = "http://" + (host or "localhost") try: port = int(port or 5204) except ValueError: exit("Error: %s is not a valid port number" % repr(port)) server = xmlrpclib.ServerProxy("%s:%s" % (host, port), encoding="utf-8", verbose=opts.verbose) try: eval('server.echo("test")') except SocketError, inst: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?" % ( inst, host, port), "See cornetto-server.py -h" exit(1) help_text = """ Type "?" to see his message. Type "help()" for help on available methods. Type "Ctrl-D" to exit. Restart with "cornetto-client.py -h" to see command line options. """ startup_msg = ( "cornetto-client.py (version %s)\n" % __version__ + "Copyright (c) Erwin Marsi\n" + help_text ) if stdin.isatty(): prompt = "$ " if opts.pretty_print is None: opts.pretty_print = True print startup_msg else: prompt = "" if opts.pretty_print is None: opts.pretty_print = False # use of eval might allow arbitrary code execution - probably not entirely safe if opts.ask: <|fim_middle|> else: process = lambda c: eval("server." + c.strip()) if opts.pretty_print: formatter = pformat else: formatter = repr # This is nasty way to enforce encoleast_common_subsumers("fiets", "auto")ding of strings embedded in lists or dicts. # For examample [u'plafonnière'] rather than [u"plafonni\xe8re"] encoder = lambda s: s.decode("unicode_escape").encode(opts.encoding, "backslashreplace") while True: try: command = raw_input(prompt) if command == "?": print help_text else: result = process(command) print encoder(formatter(result)) except EOFError: print "\nSee you later alligator!" exit(0) except KeyboardInterrupt: print >>stderr, "\nInterrupted. Latest command may still run on the server though..." except SyntaxError: print >>stderr, "Error: invalid syntax" except NameError, inst: print >>stderr, "Error:", inst, "- use quotes?" except xmlrpclib.Error, inst: print >>stderr, inst except SocketError: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?\n" % ( inst, host, port), "See cornetto-server.py -h" <|fim▁end|>
process = lambda c: eval('server.ask("%s")' % c.strip())
<|file_name|>cornetto-client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008-2013 by # Erwin Marsi and Tilburg University # This file is part of the Pycornetto package. # Pycornetto is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # Pycornetto is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ A simple client to connect to the Cornetto database server. Reads queries from standard input and writes results to standard output. """ # BUGS: # - there is no way interrupt a query that goes bad on the server, as obviously # a local Ctrl-C does not work __author__ = 'Erwin Marsi <[email protected]>' __version__ = '0.6.1' # using optparse instead of argparse so client can run stand-alone from sys import stdin, stdout, stderr, exit from optparse import OptionParser, IndentedHelpFormatter import xmlrpclib from pprint import pformat from socket import error as SocketError class MyFormatter(IndentedHelpFormatter): """to prevent optparse from messing up the epilog text""" def format_epilog(self, epilog): return epilog or "" def format_description(self, description): return description.lstrip() epilog = """ Interactive usage: $ cornetto-client.py $ cornetto-client.py -a File processing: $ echo 'ask("pijp")' | cornetto-client.py $ cornetto-client.py <input >output """ try: parser = OptionParser(description=__doc__, version="%(prog)s version " + __version__, epilog=epilog, formatter=MyFormatter()) except TypeError: # optparse in python 2.4 has no epilog keyword parser = OptionParser(description=__doc__ + epilog, version="%(prog)s version " + __version__) parser.add_option("-a", "--ask", action='store_true', help="assume all commands are input the 'ask' function, " "- so you can type 'query' instead of 'ask(\"query\") - '" "but online help is no longer accessible" ) parser.add_option("-H", "--host", default="localhost:5204", metavar="HOST[:PORT]", help="name or IP address of host (default is 'localhost') " "optionally followed by a port number " "(default is 5204)") parser.add_option('-n', '--no-pretty-print', dest="pretty_print", action='store_false', help="turn off pretty printing of output " "(default when standard input is a file)") parser.add_option("-p", "--port", type=int, default=5204, help='port number (default is 5204)') parser.add_option('-P', '--pretty-print', dest="pretty_print", action='store_true', help="turn on pretty printing of output " "(default when standard input is a tty)") parser.add_option("-e", "--encoding", default="utf8", metavar="utf8,latin1,ascii,...", help="character encoding of output (default is utf8)") parser.add_option('-V', '--verbose', action='store_true', help="verbose output for debugging") (opts, args) = parser.parse_args() if opts.host.startswith("http://"): opts.host = opts.host[7:] try: host, port = opts.host.split(":")[:2] except ValueError: host, port = opts.host, None # XMP-RPC requires specification of protocol host = "http://" + (host or "localhost") try: port = int(port or 5204) except ValueError: exit("Error: %s is not a valid port number" % repr(port)) server = xmlrpclib.ServerProxy("%s:%s" % (host, port), encoding="utf-8", verbose=opts.verbose) try: eval('server.echo("test")') except SocketError, inst: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?" % ( inst, host, port), "See cornetto-server.py -h" exit(1) help_text = """ Type "?" to see his message. Type "help()" for help on available methods. Type "Ctrl-D" to exit. Restart with "cornetto-client.py -h" to see command line options. """ startup_msg = ( "cornetto-client.py (version %s)\n" % __version__ + "Copyright (c) Erwin Marsi\n" + help_text ) if stdin.isatty(): prompt = "$ " if opts.pretty_print is None: opts.pretty_print = True print startup_msg else: prompt = "" if opts.pretty_print is None: opts.pretty_print = False # use of eval might allow arbitrary code execution - probably not entirely safe if opts.ask: process = lambda c: eval('server.ask("%s")' % c.strip()) else: <|fim_middle|> if opts.pretty_print: formatter = pformat else: formatter = repr # This is nasty way to enforce encoleast_common_subsumers("fiets", "auto")ding of strings embedded in lists or dicts. # For examample [u'plafonnière'] rather than [u"plafonni\xe8re"] encoder = lambda s: s.decode("unicode_escape").encode(opts.encoding, "backslashreplace") while True: try: command = raw_input(prompt) if command == "?": print help_text else: result = process(command) print encoder(formatter(result)) except EOFError: print "\nSee you later alligator!" exit(0) except KeyboardInterrupt: print >>stderr, "\nInterrupted. Latest command may still run on the server though..." except SyntaxError: print >>stderr, "Error: invalid syntax" except NameError, inst: print >>stderr, "Error:", inst, "- use quotes?" except xmlrpclib.Error, inst: print >>stderr, inst except SocketError: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?\n" % ( inst, host, port), "See cornetto-server.py -h" <|fim▁end|>
process = lambda c: eval("server." + c.strip())
<|file_name|>cornetto-client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008-2013 by # Erwin Marsi and Tilburg University # This file is part of the Pycornetto package. # Pycornetto is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # Pycornetto is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ A simple client to connect to the Cornetto database server. Reads queries from standard input and writes results to standard output. """ # BUGS: # - there is no way interrupt a query that goes bad on the server, as obviously # a local Ctrl-C does not work __author__ = 'Erwin Marsi <[email protected]>' __version__ = '0.6.1' # using optparse instead of argparse so client can run stand-alone from sys import stdin, stdout, stderr, exit from optparse import OptionParser, IndentedHelpFormatter import xmlrpclib from pprint import pformat from socket import error as SocketError class MyFormatter(IndentedHelpFormatter): """to prevent optparse from messing up the epilog text""" def format_epilog(self, epilog): return epilog or "" def format_description(self, description): return description.lstrip() epilog = """ Interactive usage: $ cornetto-client.py $ cornetto-client.py -a File processing: $ echo 'ask("pijp")' | cornetto-client.py $ cornetto-client.py <input >output """ try: parser = OptionParser(description=__doc__, version="%(prog)s version " + __version__, epilog=epilog, formatter=MyFormatter()) except TypeError: # optparse in python 2.4 has no epilog keyword parser = OptionParser(description=__doc__ + epilog, version="%(prog)s version " + __version__) parser.add_option("-a", "--ask", action='store_true', help="assume all commands are input the 'ask' function, " "- so you can type 'query' instead of 'ask(\"query\") - '" "but online help is no longer accessible" ) parser.add_option("-H", "--host", default="localhost:5204", metavar="HOST[:PORT]", help="name or IP address of host (default is 'localhost') " "optionally followed by a port number " "(default is 5204)") parser.add_option('-n', '--no-pretty-print', dest="pretty_print", action='store_false', help="turn off pretty printing of output " "(default when standard input is a file)") parser.add_option("-p", "--port", type=int, default=5204, help='port number (default is 5204)') parser.add_option('-P', '--pretty-print', dest="pretty_print", action='store_true', help="turn on pretty printing of output " "(default when standard input is a tty)") parser.add_option("-e", "--encoding", default="utf8", metavar="utf8,latin1,ascii,...", help="character encoding of output (default is utf8)") parser.add_option('-V', '--verbose', action='store_true', help="verbose output for debugging") (opts, args) = parser.parse_args() if opts.host.startswith("http://"): opts.host = opts.host[7:] try: host, port = opts.host.split(":")[:2] except ValueError: host, port = opts.host, None # XMP-RPC requires specification of protocol host = "http://" + (host or "localhost") try: port = int(port or 5204) except ValueError: exit("Error: %s is not a valid port number" % repr(port)) server = xmlrpclib.ServerProxy("%s:%s" % (host, port), encoding="utf-8", verbose=opts.verbose) try: eval('server.echo("test")') except SocketError, inst: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?" % ( inst, host, port), "See cornetto-server.py -h" exit(1) help_text = """ Type "?" to see his message. Type "help()" for help on available methods. Type "Ctrl-D" to exit. Restart with "cornetto-client.py -h" to see command line options. """ startup_msg = ( "cornetto-client.py (version %s)\n" % __version__ + "Copyright (c) Erwin Marsi\n" + help_text ) if stdin.isatty(): prompt = "$ " if opts.pretty_print is None: opts.pretty_print = True print startup_msg else: prompt = "" if opts.pretty_print is None: opts.pretty_print = False # use of eval might allow arbitrary code execution - probably not entirely safe if opts.ask: process = lambda c: eval('server.ask("%s")' % c.strip()) else: process = lambda c: eval("server." + c.strip()) if opts.pretty_print: <|fim_middle|> else: formatter = repr # This is nasty way to enforce encoleast_common_subsumers("fiets", "auto")ding of strings embedded in lists or dicts. # For examample [u'plafonnière'] rather than [u"plafonni\xe8re"] encoder = lambda s: s.decode("unicode_escape").encode(opts.encoding, "backslashreplace") while True: try: command = raw_input(prompt) if command == "?": print help_text else: result = process(command) print encoder(formatter(result)) except EOFError: print "\nSee you later alligator!" exit(0) except KeyboardInterrupt: print >>stderr, "\nInterrupted. Latest command may still run on the server though..." except SyntaxError: print >>stderr, "Error: invalid syntax" except NameError, inst: print >>stderr, "Error:", inst, "- use quotes?" except xmlrpclib.Error, inst: print >>stderr, inst except SocketError: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?\n" % ( inst, host, port), "See cornetto-server.py -h" <|fim▁end|>
formatter = pformat
<|file_name|>cornetto-client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008-2013 by # Erwin Marsi and Tilburg University # This file is part of the Pycornetto package. # Pycornetto is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # Pycornetto is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ A simple client to connect to the Cornetto database server. Reads queries from standard input and writes results to standard output. """ # BUGS: # - there is no way interrupt a query that goes bad on the server, as obviously # a local Ctrl-C does not work __author__ = 'Erwin Marsi <[email protected]>' __version__ = '0.6.1' # using optparse instead of argparse so client can run stand-alone from sys import stdin, stdout, stderr, exit from optparse import OptionParser, IndentedHelpFormatter import xmlrpclib from pprint import pformat from socket import error as SocketError class MyFormatter(IndentedHelpFormatter): """to prevent optparse from messing up the epilog text""" def format_epilog(self, epilog): return epilog or "" def format_description(self, description): return description.lstrip() epilog = """ Interactive usage: $ cornetto-client.py $ cornetto-client.py -a File processing: $ echo 'ask("pijp")' | cornetto-client.py $ cornetto-client.py <input >output """ try: parser = OptionParser(description=__doc__, version="%(prog)s version " + __version__, epilog=epilog, formatter=MyFormatter()) except TypeError: # optparse in python 2.4 has no epilog keyword parser = OptionParser(description=__doc__ + epilog, version="%(prog)s version " + __version__) parser.add_option("-a", "--ask", action='store_true', help="assume all commands are input the 'ask' function, " "- so you can type 'query' instead of 'ask(\"query\") - '" "but online help is no longer accessible" ) parser.add_option("-H", "--host", default="localhost:5204", metavar="HOST[:PORT]", help="name or IP address of host (default is 'localhost') " "optionally followed by a port number " "(default is 5204)") parser.add_option('-n', '--no-pretty-print', dest="pretty_print", action='store_false', help="turn off pretty printing of output " "(default when standard input is a file)") parser.add_option("-p", "--port", type=int, default=5204, help='port number (default is 5204)') parser.add_option('-P', '--pretty-print', dest="pretty_print", action='store_true', help="turn on pretty printing of output " "(default when standard input is a tty)") parser.add_option("-e", "--encoding", default="utf8", metavar="utf8,latin1,ascii,...", help="character encoding of output (default is utf8)") parser.add_option('-V', '--verbose', action='store_true', help="verbose output for debugging") (opts, args) = parser.parse_args() if opts.host.startswith("http://"): opts.host = opts.host[7:] try: host, port = opts.host.split(":")[:2] except ValueError: host, port = opts.host, None # XMP-RPC requires specification of protocol host = "http://" + (host or "localhost") try: port = int(port or 5204) except ValueError: exit("Error: %s is not a valid port number" % repr(port)) server = xmlrpclib.ServerProxy("%s:%s" % (host, port), encoding="utf-8", verbose=opts.verbose) try: eval('server.echo("test")') except SocketError, inst: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?" % ( inst, host, port), "See cornetto-server.py -h" exit(1) help_text = """ Type "?" to see his message. Type "help()" for help on available methods. Type "Ctrl-D" to exit. Restart with "cornetto-client.py -h" to see command line options. """ startup_msg = ( "cornetto-client.py (version %s)\n" % __version__ + "Copyright (c) Erwin Marsi\n" + help_text ) if stdin.isatty(): prompt = "$ " if opts.pretty_print is None: opts.pretty_print = True print startup_msg else: prompt = "" if opts.pretty_print is None: opts.pretty_print = False # use of eval might allow arbitrary code execution - probably not entirely safe if opts.ask: process = lambda c: eval('server.ask("%s")' % c.strip()) else: process = lambda c: eval("server." + c.strip()) if opts.pretty_print: formatter = pformat else: <|fim_middle|> # This is nasty way to enforce encoleast_common_subsumers("fiets", "auto")ding of strings embedded in lists or dicts. # For examample [u'plafonnière'] rather than [u"plafonni\xe8re"] encoder = lambda s: s.decode("unicode_escape").encode(opts.encoding, "backslashreplace") while True: try: command = raw_input(prompt) if command == "?": print help_text else: result = process(command) print encoder(formatter(result)) except EOFError: print "\nSee you later alligator!" exit(0) except KeyboardInterrupt: print >>stderr, "\nInterrupted. Latest command may still run on the server though..." except SyntaxError: print >>stderr, "Error: invalid syntax" except NameError, inst: print >>stderr, "Error:", inst, "- use quotes?" except xmlrpclib.Error, inst: print >>stderr, inst except SocketError: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?\n" % ( inst, host, port), "See cornetto-server.py -h" <|fim▁end|>
formatter = repr
<|file_name|>cornetto-client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008-2013 by # Erwin Marsi and Tilburg University # This file is part of the Pycornetto package. # Pycornetto is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # Pycornetto is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ A simple client to connect to the Cornetto database server. Reads queries from standard input and writes results to standard output. """ # BUGS: # - there is no way interrupt a query that goes bad on the server, as obviously # a local Ctrl-C does not work __author__ = 'Erwin Marsi <[email protected]>' __version__ = '0.6.1' # using optparse instead of argparse so client can run stand-alone from sys import stdin, stdout, stderr, exit from optparse import OptionParser, IndentedHelpFormatter import xmlrpclib from pprint import pformat from socket import error as SocketError class MyFormatter(IndentedHelpFormatter): """to prevent optparse from messing up the epilog text""" def format_epilog(self, epilog): return epilog or "" def format_description(self, description): return description.lstrip() epilog = """ Interactive usage: $ cornetto-client.py $ cornetto-client.py -a File processing: $ echo 'ask("pijp")' | cornetto-client.py $ cornetto-client.py <input >output """ try: parser = OptionParser(description=__doc__, version="%(prog)s version " + __version__, epilog=epilog, formatter=MyFormatter()) except TypeError: # optparse in python 2.4 has no epilog keyword parser = OptionParser(description=__doc__ + epilog, version="%(prog)s version " + __version__) parser.add_option("-a", "--ask", action='store_true', help="assume all commands are input the 'ask' function, " "- so you can type 'query' instead of 'ask(\"query\") - '" "but online help is no longer accessible" ) parser.add_option("-H", "--host", default="localhost:5204", metavar="HOST[:PORT]", help="name or IP address of host (default is 'localhost') " "optionally followed by a port number " "(default is 5204)") parser.add_option('-n', '--no-pretty-print', dest="pretty_print", action='store_false', help="turn off pretty printing of output " "(default when standard input is a file)") parser.add_option("-p", "--port", type=int, default=5204, help='port number (default is 5204)') parser.add_option('-P', '--pretty-print', dest="pretty_print", action='store_true', help="turn on pretty printing of output " "(default when standard input is a tty)") parser.add_option("-e", "--encoding", default="utf8", metavar="utf8,latin1,ascii,...", help="character encoding of output (default is utf8)") parser.add_option('-V', '--verbose', action='store_true', help="verbose output for debugging") (opts, args) = parser.parse_args() if opts.host.startswith("http://"): opts.host = opts.host[7:] try: host, port = opts.host.split(":")[:2] except ValueError: host, port = opts.host, None # XMP-RPC requires specification of protocol host = "http://" + (host or "localhost") try: port = int(port or 5204) except ValueError: exit("Error: %s is not a valid port number" % repr(port)) server = xmlrpclib.ServerProxy("%s:%s" % (host, port), encoding="utf-8", verbose=opts.verbose) try: eval('server.echo("test")') except SocketError, inst: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?" % ( inst, host, port), "See cornetto-server.py -h" exit(1) help_text = """ Type "?" to see his message. Type "help()" for help on available methods. Type "Ctrl-D" to exit. Restart with "cornetto-client.py -h" to see command line options. """ startup_msg = ( "cornetto-client.py (version %s)\n" % __version__ + "Copyright (c) Erwin Marsi\n" + help_text ) if stdin.isatty(): prompt = "$ " if opts.pretty_print is None: opts.pretty_print = True print startup_msg else: prompt = "" if opts.pretty_print is None: opts.pretty_print = False # use of eval might allow arbitrary code execution - probably not entirely safe if opts.ask: process = lambda c: eval('server.ask("%s")' % c.strip()) else: process = lambda c: eval("server." + c.strip()) if opts.pretty_print: formatter = pformat else: formatter = repr # This is nasty way to enforce encoleast_common_subsumers("fiets", "auto")ding of strings embedded in lists or dicts. # For examample [u'plafonnière'] rather than [u"plafonni\xe8re"] encoder = lambda s: s.decode("unicode_escape").encode(opts.encoding, "backslashreplace") while True: try: command = raw_input(prompt) if command == "?": p <|fim_middle|> else: result = process(command) print encoder(formatter(result)) except EOFError: print "\nSee you later alligator!" exit(0) except KeyboardInterrupt: print >>stderr, "\nInterrupted. Latest command may still run on the server though..." except SyntaxError: print >>stderr, "Error: invalid syntax" except NameError, inst: print >>stderr, "Error:", inst, "- use quotes?" except xmlrpclib.Error, inst: print >>stderr, inst except SocketError: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?\n" % ( inst, host, port), "See cornetto-server.py -h" <|fim▁end|>
rint help_text
<|file_name|>cornetto-client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008-2013 by # Erwin Marsi and Tilburg University # This file is part of the Pycornetto package. # Pycornetto is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # Pycornetto is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ A simple client to connect to the Cornetto database server. Reads queries from standard input and writes results to standard output. """ # BUGS: # - there is no way interrupt a query that goes bad on the server, as obviously # a local Ctrl-C does not work __author__ = 'Erwin Marsi <[email protected]>' __version__ = '0.6.1' # using optparse instead of argparse so client can run stand-alone from sys import stdin, stdout, stderr, exit from optparse import OptionParser, IndentedHelpFormatter import xmlrpclib from pprint import pformat from socket import error as SocketError class MyFormatter(IndentedHelpFormatter): """to prevent optparse from messing up the epilog text""" def format_epilog(self, epilog): return epilog or "" def format_description(self, description): return description.lstrip() epilog = """ Interactive usage: $ cornetto-client.py $ cornetto-client.py -a File processing: $ echo 'ask("pijp")' | cornetto-client.py $ cornetto-client.py <input >output """ try: parser = OptionParser(description=__doc__, version="%(prog)s version " + __version__, epilog=epilog, formatter=MyFormatter()) except TypeError: # optparse in python 2.4 has no epilog keyword parser = OptionParser(description=__doc__ + epilog, version="%(prog)s version " + __version__) parser.add_option("-a", "--ask", action='store_true', help="assume all commands are input the 'ask' function, " "- so you can type 'query' instead of 'ask(\"query\") - '" "but online help is no longer accessible" ) parser.add_option("-H", "--host", default="localhost:5204", metavar="HOST[:PORT]", help="name or IP address of host (default is 'localhost') " "optionally followed by a port number " "(default is 5204)") parser.add_option('-n', '--no-pretty-print', dest="pretty_print", action='store_false', help="turn off pretty printing of output " "(default when standard input is a file)") parser.add_option("-p", "--port", type=int, default=5204, help='port number (default is 5204)') parser.add_option('-P', '--pretty-print', dest="pretty_print", action='store_true', help="turn on pretty printing of output " "(default when standard input is a tty)") parser.add_option("-e", "--encoding", default="utf8", metavar="utf8,latin1,ascii,...", help="character encoding of output (default is utf8)") parser.add_option('-V', '--verbose', action='store_true', help="verbose output for debugging") (opts, args) = parser.parse_args() if opts.host.startswith("http://"): opts.host = opts.host[7:] try: host, port = opts.host.split(":")[:2] except ValueError: host, port = opts.host, None # XMP-RPC requires specification of protocol host = "http://" + (host or "localhost") try: port = int(port or 5204) except ValueError: exit("Error: %s is not a valid port number" % repr(port)) server = xmlrpclib.ServerProxy("%s:%s" % (host, port), encoding="utf-8", verbose=opts.verbose) try: eval('server.echo("test")') except SocketError, inst: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?" % ( inst, host, port), "See cornetto-server.py -h" exit(1) help_text = """ Type "?" to see his message. Type "help()" for help on available methods. Type "Ctrl-D" to exit. Restart with "cornetto-client.py -h" to see command line options. """ startup_msg = ( "cornetto-client.py (version %s)\n" % __version__ + "Copyright (c) Erwin Marsi\n" + help_text ) if stdin.isatty(): prompt = "$ " if opts.pretty_print is None: opts.pretty_print = True print startup_msg else: prompt = "" if opts.pretty_print is None: opts.pretty_print = False # use of eval might allow arbitrary code execution - probably not entirely safe if opts.ask: process = lambda c: eval('server.ask("%s")' % c.strip()) else: process = lambda c: eval("server." + c.strip()) if opts.pretty_print: formatter = pformat else: formatter = repr # This is nasty way to enforce encoleast_common_subsumers("fiets", "auto")ding of strings embedded in lists or dicts. # For examample [u'plafonnière'] rather than [u"plafonni\xe8re"] encoder = lambda s: s.decode("unicode_escape").encode(opts.encoding, "backslashreplace") while True: try: command = raw_input(prompt) if command == "?": print help_text else: r <|fim_middle|> except EOFError: print "\nSee you later alligator!" exit(0) except KeyboardInterrupt: print >>stderr, "\nInterrupted. Latest command may still run on the server though..." except SyntaxError: print >>stderr, "Error: invalid syntax" except NameError, inst: print >>stderr, "Error:", inst, "- use quotes?" except xmlrpclib.Error, inst: print >>stderr, inst except SocketError: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?\n" % ( inst, host, port), "See cornetto-server.py -h" <|fim▁end|>
esult = process(command) print encoder(formatter(result))
<|file_name|>cornetto-client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008-2013 by # Erwin Marsi and Tilburg University # This file is part of the Pycornetto package. # Pycornetto is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # Pycornetto is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ A simple client to connect to the Cornetto database server. Reads queries from standard input and writes results to standard output. """ # BUGS: # - there is no way interrupt a query that goes bad on the server, as obviously # a local Ctrl-C does not work __author__ = 'Erwin Marsi <[email protected]>' __version__ = '0.6.1' # using optparse instead of argparse so client can run stand-alone from sys import stdin, stdout, stderr, exit from optparse import OptionParser, IndentedHelpFormatter import xmlrpclib from pprint import pformat from socket import error as SocketError class MyFormatter(IndentedHelpFormatter): """to prevent optparse from messing up the epilog text""" def <|fim_middle|>(self, epilog): return epilog or "" def format_description(self, description): return description.lstrip() epilog = """ Interactive usage: $ cornetto-client.py $ cornetto-client.py -a File processing: $ echo 'ask("pijp")' | cornetto-client.py $ cornetto-client.py <input >output """ try: parser = OptionParser(description=__doc__, version="%(prog)s version " + __version__, epilog=epilog, formatter=MyFormatter()) except TypeError: # optparse in python 2.4 has no epilog keyword parser = OptionParser(description=__doc__ + epilog, version="%(prog)s version " + __version__) parser.add_option("-a", "--ask", action='store_true', help="assume all commands are input the 'ask' function, " "- so you can type 'query' instead of 'ask(\"query\") - '" "but online help is no longer accessible" ) parser.add_option("-H", "--host", default="localhost:5204", metavar="HOST[:PORT]", help="name or IP address of host (default is 'localhost') " "optionally followed by a port number " "(default is 5204)") parser.add_option('-n', '--no-pretty-print', dest="pretty_print", action='store_false', help="turn off pretty printing of output " "(default when standard input is a file)") parser.add_option("-p", "--port", type=int, default=5204, help='port number (default is 5204)') parser.add_option('-P', '--pretty-print', dest="pretty_print", action='store_true', help="turn on pretty printing of output " "(default when standard input is a tty)") parser.add_option("-e", "--encoding", default="utf8", metavar="utf8,latin1,ascii,...", help="character encoding of output (default is utf8)") parser.add_option('-V', '--verbose', action='store_true', help="verbose output for debugging") (opts, args) = parser.parse_args() if opts.host.startswith("http://"): opts.host = opts.host[7:] try: host, port = opts.host.split(":")[:2] except ValueError: host, port = opts.host, None # XMP-RPC requires specification of protocol host = "http://" + (host or "localhost") try: port = int(port or 5204) except ValueError: exit("Error: %s is not a valid port number" % repr(port)) server = xmlrpclib.ServerProxy("%s:%s" % (host, port), encoding="utf-8", verbose=opts.verbose) try: eval('server.echo("test")') except SocketError, inst: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?" % ( inst, host, port), "See cornetto-server.py -h" exit(1) help_text = """ Type "?" to see his message. Type "help()" for help on available methods. Type "Ctrl-D" to exit. Restart with "cornetto-client.py -h" to see command line options. """ startup_msg = ( "cornetto-client.py (version %s)\n" % __version__ + "Copyright (c) Erwin Marsi\n" + help_text ) if stdin.isatty(): prompt = "$ " if opts.pretty_print is None: opts.pretty_print = True print startup_msg else: prompt = "" if opts.pretty_print is None: opts.pretty_print = False # use of eval might allow arbitrary code execution - probably not entirely safe if opts.ask: process = lambda c: eval('server.ask("%s")' % c.strip()) else: process = lambda c: eval("server." + c.strip()) if opts.pretty_print: formatter = pformat else: formatter = repr # This is nasty way to enforce encoleast_common_subsumers("fiets", "auto")ding of strings embedded in lists or dicts. # For examample [u'plafonnière'] rather than [u"plafonni\xe8re"] encoder = lambda s: s.decode("unicode_escape").encode(opts.encoding, "backslashreplace") while True: try: command = raw_input(prompt) if command == "?": print help_text else: result = process(command) print encoder(formatter(result)) except EOFError: print "\nSee you later alligator!" exit(0) except KeyboardInterrupt: print >>stderr, "\nInterrupted. Latest command may still run on the server though..." except SyntaxError: print >>stderr, "Error: invalid syntax" except NameError, inst: print >>stderr, "Error:", inst, "- use quotes?" except xmlrpclib.Error, inst: print >>stderr, inst except SocketError: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?\n" % ( inst, host, port), "See cornetto-server.py -h" <|fim▁end|>
format_epilog
<|file_name|>cornetto-client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008-2013 by # Erwin Marsi and Tilburg University # This file is part of the Pycornetto package. # Pycornetto is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # Pycornetto is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ A simple client to connect to the Cornetto database server. Reads queries from standard input and writes results to standard output. """ # BUGS: # - there is no way interrupt a query that goes bad on the server, as obviously # a local Ctrl-C does not work __author__ = 'Erwin Marsi <[email protected]>' __version__ = '0.6.1' # using optparse instead of argparse so client can run stand-alone from sys import stdin, stdout, stderr, exit from optparse import OptionParser, IndentedHelpFormatter import xmlrpclib from pprint import pformat from socket import error as SocketError class MyFormatter(IndentedHelpFormatter): """to prevent optparse from messing up the epilog text""" def format_epilog(self, epilog): return epilog or "" def <|fim_middle|>(self, description): return description.lstrip() epilog = """ Interactive usage: $ cornetto-client.py $ cornetto-client.py -a File processing: $ echo 'ask("pijp")' | cornetto-client.py $ cornetto-client.py <input >output """ try: parser = OptionParser(description=__doc__, version="%(prog)s version " + __version__, epilog=epilog, formatter=MyFormatter()) except TypeError: # optparse in python 2.4 has no epilog keyword parser = OptionParser(description=__doc__ + epilog, version="%(prog)s version " + __version__) parser.add_option("-a", "--ask", action='store_true', help="assume all commands are input the 'ask' function, " "- so you can type 'query' instead of 'ask(\"query\") - '" "but online help is no longer accessible" ) parser.add_option("-H", "--host", default="localhost:5204", metavar="HOST[:PORT]", help="name or IP address of host (default is 'localhost') " "optionally followed by a port number " "(default is 5204)") parser.add_option('-n', '--no-pretty-print', dest="pretty_print", action='store_false', help="turn off pretty printing of output " "(default when standard input is a file)") parser.add_option("-p", "--port", type=int, default=5204, help='port number (default is 5204)') parser.add_option('-P', '--pretty-print', dest="pretty_print", action='store_true', help="turn on pretty printing of output " "(default when standard input is a tty)") parser.add_option("-e", "--encoding", default="utf8", metavar="utf8,latin1,ascii,...", help="character encoding of output (default is utf8)") parser.add_option('-V', '--verbose', action='store_true', help="verbose output for debugging") (opts, args) = parser.parse_args() if opts.host.startswith("http://"): opts.host = opts.host[7:] try: host, port = opts.host.split(":")[:2] except ValueError: host, port = opts.host, None # XMP-RPC requires specification of protocol host = "http://" + (host or "localhost") try: port = int(port or 5204) except ValueError: exit("Error: %s is not a valid port number" % repr(port)) server = xmlrpclib.ServerProxy("%s:%s" % (host, port), encoding="utf-8", verbose=opts.verbose) try: eval('server.echo("test")') except SocketError, inst: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?" % ( inst, host, port), "See cornetto-server.py -h" exit(1) help_text = """ Type "?" to see his message. Type "help()" for help on available methods. Type "Ctrl-D" to exit. Restart with "cornetto-client.py -h" to see command line options. """ startup_msg = ( "cornetto-client.py (version %s)\n" % __version__ + "Copyright (c) Erwin Marsi\n" + help_text ) if stdin.isatty(): prompt = "$ " if opts.pretty_print is None: opts.pretty_print = True print startup_msg else: prompt = "" if opts.pretty_print is None: opts.pretty_print = False # use of eval might allow arbitrary code execution - probably not entirely safe if opts.ask: process = lambda c: eval('server.ask("%s")' % c.strip()) else: process = lambda c: eval("server." + c.strip()) if opts.pretty_print: formatter = pformat else: formatter = repr # This is nasty way to enforce encoleast_common_subsumers("fiets", "auto")ding of strings embedded in lists or dicts. # For examample [u'plafonnière'] rather than [u"plafonni\xe8re"] encoder = lambda s: s.decode("unicode_escape").encode(opts.encoding, "backslashreplace") while True: try: command = raw_input(prompt) if command == "?": print help_text else: result = process(command) print encoder(formatter(result)) except EOFError: print "\nSee you later alligator!" exit(0) except KeyboardInterrupt: print >>stderr, "\nInterrupted. Latest command may still run on the server though..." except SyntaxError: print >>stderr, "Error: invalid syntax" except NameError, inst: print >>stderr, "Error:", inst, "- use quotes?" except xmlrpclib.Error, inst: print >>stderr, inst except SocketError: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?\n" % ( inst, host, port), "See cornetto-server.py -h" <|fim▁end|>
format_description
<|file_name|>UART01.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # uart-eg01.py # # to run on the other end of the UART # screen /dev/ttyUSB1 115200 import serial def readlineCR(uart): line = b'' while True: byte = uart.read() line += byte<|fim▁hole|> uart = serial.Serial('/dev/ttyUSB0', baudrate=115200, timeout=1) while True: uart.write(b'\r\nSay something: ') line = readlineCR(uart) if line != b'exit\r': lineStr = '\r\nYou sent : {}'.format(line.decode('utf-8')) uart.write(lineStr.encode('utf-8')) else: uart.write(b'\r\nexiting\r\n') uart.close() exit(0)<|fim▁end|>
if byte == b'\r': return line
<|file_name|>UART01.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # uart-eg01.py # # to run on the other end of the UART # screen /dev/ttyUSB1 115200 import serial def readlineCR(uart): <|fim_middle|> uart = serial.Serial('/dev/ttyUSB0', baudrate=115200, timeout=1) while True: uart.write(b'\r\nSay something: ') line = readlineCR(uart) if line != b'exit\r': lineStr = '\r\nYou sent : {}'.format(line.decode('utf-8')) uart.write(lineStr.encode('utf-8')) else: uart.write(b'\r\nexiting\r\n') uart.close() exit(0) <|fim▁end|>
line = b'' while True: byte = uart.read() line += byte if byte == b'\r': return line
<|file_name|>UART01.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # uart-eg01.py # # to run on the other end of the UART # screen /dev/ttyUSB1 115200 import serial def readlineCR(uart): line = b'' while True: byte = uart.read() line += byte if byte == b'\r': <|fim_middle|> uart = serial.Serial('/dev/ttyUSB0', baudrate=115200, timeout=1) while True: uart.write(b'\r\nSay something: ') line = readlineCR(uart) if line != b'exit\r': lineStr = '\r\nYou sent : {}'.format(line.decode('utf-8')) uart.write(lineStr.encode('utf-8')) else: uart.write(b'\r\nexiting\r\n') uart.close() exit(0) <|fim▁end|>
return line
<|file_name|>UART01.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # uart-eg01.py # # to run on the other end of the UART # screen /dev/ttyUSB1 115200 import serial def readlineCR(uart): line = b'' while True: byte = uart.read() line += byte if byte == b'\r': return line uart = serial.Serial('/dev/ttyUSB0', baudrate=115200, timeout=1) while True: uart.write(b'\r\nSay something: ') line = readlineCR(uart) if line != b'exit\r': <|fim_middle|> else: uart.write(b'\r\nexiting\r\n') uart.close() exit(0) <|fim▁end|>
lineStr = '\r\nYou sent : {}'.format(line.decode('utf-8')) uart.write(lineStr.encode('utf-8'))
<|file_name|>UART01.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # uart-eg01.py # # to run on the other end of the UART # screen /dev/ttyUSB1 115200 import serial def readlineCR(uart): line = b'' while True: byte = uart.read() line += byte if byte == b'\r': return line uart = serial.Serial('/dev/ttyUSB0', baudrate=115200, timeout=1) while True: uart.write(b'\r\nSay something: ') line = readlineCR(uart) if line != b'exit\r': lineStr = '\r\nYou sent : {}'.format(line.decode('utf-8')) uart.write(lineStr.encode('utf-8')) else: <|fim_middle|> <|fim▁end|>
uart.write(b'\r\nexiting\r\n') uart.close() exit(0)
<|file_name|>UART01.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # uart-eg01.py # # to run on the other end of the UART # screen /dev/ttyUSB1 115200 import serial def <|fim_middle|>(uart): line = b'' while True: byte = uart.read() line += byte if byte == b'\r': return line uart = serial.Serial('/dev/ttyUSB0', baudrate=115200, timeout=1) while True: uart.write(b'\r\nSay something: ') line = readlineCR(uart) if line != b'exit\r': lineStr = '\r\nYou sent : {}'.format(line.decode('utf-8')) uart.write(lineStr.encode('utf-8')) else: uart.write(b'\r\nexiting\r\n') uart.close() exit(0) <|fim▁end|>
readlineCR
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() foo = property(**foo()) def bar(): doc = "The bar property." def fget(self): return self._bar def fset(self, value): self._bar = value def fdel(self): del self._bar return locals() bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo')<|fim▁hole|><|fim▁end|>
#print(tc.foo) #print(dir(tc))
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): <|fim_middle|> tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
def foo(): doc = "The foo property." def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() foo = property(**foo()) def bar(): doc = "The bar property." def fget(self): return self._bar def fset(self, value): self._bar = value def fdel(self): del self._bar return locals() bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!'
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): <|fim_middle|> foo = property(**foo()) def bar(): doc = "The bar property." def fget(self): return self._bar def fset(self, value): self._bar = value def fdel(self): del self._bar return locals() bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
doc = "The foo property." def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals()
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def fget(self): <|fim_middle|> def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() foo = property(**foo()) def bar(): doc = "The bar property." def fget(self): return self._bar def fset(self, value): self._bar = value def fdel(self): del self._bar return locals() bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
return self._foo
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def fget(self): return self._foo def fset(self, value): <|fim_middle|> def fdel(self): del self._foo return locals() foo = property(**foo()) def bar(): doc = "The bar property." def fget(self): return self._bar def fset(self, value): self._bar = value def fdel(self): del self._bar return locals() bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
self._foo = value
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): <|fim_middle|> return locals() foo = property(**foo()) def bar(): doc = "The bar property." def fget(self): return self._bar def fset(self, value): self._bar = value def fdel(self): del self._bar return locals() bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
del self._foo
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() foo = property(**foo()) def bar(): <|fim_middle|> bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
doc = "The bar property." def fget(self): return self._bar def fset(self, value): self._bar = value def fdel(self): del self._bar return locals()
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() foo = property(**foo()) def bar(): doc = "The bar property." def fget(self): <|fim_middle|> def fset(self, value): self._bar = value def fdel(self): del self._bar return locals() bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
return self._bar
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() foo = property(**foo()) def bar(): doc = "The bar property." def fget(self): return self._bar def fset(self, value): <|fim_middle|> def fdel(self): del self._bar return locals() bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
self._bar = value
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() foo = property(**foo()) def bar(): doc = "The bar property." def fget(self): return self._bar def fset(self, value): self._bar = value def fdel(self): <|fim_middle|> return locals() bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
del self._bar
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() foo = property(**foo()) def bar(): doc = "The bar property." def fget(self): return self._bar def fset(self, value): self._bar = value def fdel(self): del self._bar return locals() bar = property(**bar()) def __init__(self, foo, bar): <|fim_middle|> def test_method(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
self.foo = "foo" self.bar = "bar"
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() foo = property(**foo()) def bar(): doc = "The bar property." def fget(self): return self._bar def fset(self, value): self._bar = value def fdel(self): del self._bar return locals() bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): <|fim_middle|> tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!'
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() foo = property(**foo()) def bar(): doc = "The bar property." def fget(self): return self._bar def fset(self, value): self._bar = value def fdel(self): del self._bar return locals() bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: <|fim_middle|> else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
prop = self.foo
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() foo = property(**foo()) def bar(): doc = "The bar property." def fget(self): return self._bar def fset(self, value): self._bar = value def fdel(self): del self._bar return locals() bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: prop = self.foo else: <|fim_middle|> print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
prop = self.bar
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def <|fim_middle|>(): doc = "The foo property." def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() foo = property(**foo()) def bar(): doc = "The bar property." def fget(self): return self._bar def fset(self, value): self._bar = value def fdel(self): del self._bar return locals() bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
foo
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def <|fim_middle|>(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() foo = property(**foo()) def bar(): doc = "The bar property." def fget(self): return self._bar def fset(self, value): self._bar = value def fdel(self): del self._bar return locals() bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
fget
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def fget(self): return self._foo def <|fim_middle|>(self, value): self._foo = value def fdel(self): del self._foo return locals() foo = property(**foo()) def bar(): doc = "The bar property." def fget(self): return self._bar def fset(self, value): self._bar = value def fdel(self): del self._bar return locals() bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
fset
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def fget(self): return self._foo def fset(self, value): self._foo = value def <|fim_middle|>(self): del self._foo return locals() foo = property(**foo()) def bar(): doc = "The bar property." def fget(self): return self._bar def fset(self, value): self._bar = value def fdel(self): del self._bar return locals() bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
fdel
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() foo = property(**foo()) def <|fim_middle|>(): doc = "The bar property." def fget(self): return self._bar def fset(self, value): self._bar = value def fdel(self): del self._bar return locals() bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
bar
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() foo = property(**foo()) def bar(): doc = "The bar property." def <|fim_middle|>(self): return self._bar def fset(self, value): self._bar = value def fdel(self): del self._bar return locals() bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
fget
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() foo = property(**foo()) def bar(): doc = "The bar property." def fget(self): return self._bar def <|fim_middle|>(self, value): self._bar = value def fdel(self): del self._bar return locals() bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
fset
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() foo = property(**foo()) def bar(): doc = "The bar property." def fget(self): return self._bar def fset(self, value): self._bar = value def <|fim_middle|>(self): del self._bar return locals() bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
fdel
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() foo = property(**foo()) def bar(): doc = "The bar property." def fget(self): return self._bar def fset(self, value): self._bar = value def fdel(self): del self._bar return locals() bar = property(**bar()) def <|fim_middle|>(self, foo, bar): self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
__init__
<|file_name|>proptest.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() foo = property(**foo()) def bar(): doc = "The bar property." def fget(self): return self._bar def fset(self, value): self._bar = value def fdel(self): del self._bar return locals() bar = property(**bar()) def __init__(self, foo, bar): self.foo = "foo" self.bar = "bar" def <|fim_middle|>(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc)) <|fim▁end|>
test_method
<|file_name|>examples.py<|end_file_name|><|fim▁begin|><|fim▁hole|> class Tile(Split): class left(Stack): weight = 3 priority = 0 limit = 1 class right(TileStack): pass class Max(Split): class main(Stack): tile = False class InstantMsg(Split): class left(TileStack): # or maybe not tiled ? weight = 3 class roster(Stack): limit = 1 priority = 0 # probably roster created first class Gimp(Split): class toolbox(Stack): limit = 1 size = 184 class main(Stack): weight = 4 priority = 0 class dock(Stack): limit = 1 size = 324<|fim▁end|>
from .tile import Split, Stack, TileStack
<|file_name|>examples.py<|end_file_name|><|fim▁begin|>from .tile import Split, Stack, TileStack class Tile(Split): <|fim_middle|> class Max(Split): class main(Stack): tile = False class InstantMsg(Split): class left(TileStack): # or maybe not tiled ? weight = 3 class roster(Stack): limit = 1 priority = 0 # probably roster created first class Gimp(Split): class toolbox(Stack): limit = 1 size = 184 class main(Stack): weight = 4 priority = 0 class dock(Stack): limit = 1 size = 324 <|fim▁end|>
class left(Stack): weight = 3 priority = 0 limit = 1 class right(TileStack): pass
<|file_name|>examples.py<|end_file_name|><|fim▁begin|>from .tile import Split, Stack, TileStack class Tile(Split): class left(Stack): <|fim_middle|> class right(TileStack): pass class Max(Split): class main(Stack): tile = False class InstantMsg(Split): class left(TileStack): # or maybe not tiled ? weight = 3 class roster(Stack): limit = 1 priority = 0 # probably roster created first class Gimp(Split): class toolbox(Stack): limit = 1 size = 184 class main(Stack): weight = 4 priority = 0 class dock(Stack): limit = 1 size = 324 <|fim▁end|>
weight = 3 priority = 0 limit = 1
<|file_name|>examples.py<|end_file_name|><|fim▁begin|>from .tile import Split, Stack, TileStack class Tile(Split): class left(Stack): weight = 3 priority = 0 limit = 1 class right(TileStack): <|fim_middle|> class Max(Split): class main(Stack): tile = False class InstantMsg(Split): class left(TileStack): # or maybe not tiled ? weight = 3 class roster(Stack): limit = 1 priority = 0 # probably roster created first class Gimp(Split): class toolbox(Stack): limit = 1 size = 184 class main(Stack): weight = 4 priority = 0 class dock(Stack): limit = 1 size = 324 <|fim▁end|>
pass
<|file_name|>examples.py<|end_file_name|><|fim▁begin|>from .tile import Split, Stack, TileStack class Tile(Split): class left(Stack): weight = 3 priority = 0 limit = 1 class right(TileStack): pass class Max(Split): <|fim_middle|> class InstantMsg(Split): class left(TileStack): # or maybe not tiled ? weight = 3 class roster(Stack): limit = 1 priority = 0 # probably roster created first class Gimp(Split): class toolbox(Stack): limit = 1 size = 184 class main(Stack): weight = 4 priority = 0 class dock(Stack): limit = 1 size = 324 <|fim▁end|>
class main(Stack): tile = False
<|file_name|>examples.py<|end_file_name|><|fim▁begin|>from .tile import Split, Stack, TileStack class Tile(Split): class left(Stack): weight = 3 priority = 0 limit = 1 class right(TileStack): pass class Max(Split): class main(Stack): <|fim_middle|> class InstantMsg(Split): class left(TileStack): # or maybe not tiled ? weight = 3 class roster(Stack): limit = 1 priority = 0 # probably roster created first class Gimp(Split): class toolbox(Stack): limit = 1 size = 184 class main(Stack): weight = 4 priority = 0 class dock(Stack): limit = 1 size = 324 <|fim▁end|>
tile = False
<|file_name|>examples.py<|end_file_name|><|fim▁begin|>from .tile import Split, Stack, TileStack class Tile(Split): class left(Stack): weight = 3 priority = 0 limit = 1 class right(TileStack): pass class Max(Split): class main(Stack): tile = False class InstantMsg(Split): <|fim_middle|> class Gimp(Split): class toolbox(Stack): limit = 1 size = 184 class main(Stack): weight = 4 priority = 0 class dock(Stack): limit = 1 size = 324 <|fim▁end|>
class left(TileStack): # or maybe not tiled ? weight = 3 class roster(Stack): limit = 1 priority = 0 # probably roster created first
<|file_name|>examples.py<|end_file_name|><|fim▁begin|>from .tile import Split, Stack, TileStack class Tile(Split): class left(Stack): weight = 3 priority = 0 limit = 1 class right(TileStack): pass class Max(Split): class main(Stack): tile = False class InstantMsg(Split): class left(TileStack): # or maybe not tiled ? <|fim_middle|> class roster(Stack): limit = 1 priority = 0 # probably roster created first class Gimp(Split): class toolbox(Stack): limit = 1 size = 184 class main(Stack): weight = 4 priority = 0 class dock(Stack): limit = 1 size = 324 <|fim▁end|>
weight = 3
<|file_name|>examples.py<|end_file_name|><|fim▁begin|>from .tile import Split, Stack, TileStack class Tile(Split): class left(Stack): weight = 3 priority = 0 limit = 1 class right(TileStack): pass class Max(Split): class main(Stack): tile = False class InstantMsg(Split): class left(TileStack): # or maybe not tiled ? weight = 3 class roster(Stack): <|fim_middle|> class Gimp(Split): class toolbox(Stack): limit = 1 size = 184 class main(Stack): weight = 4 priority = 0 class dock(Stack): limit = 1 size = 324 <|fim▁end|>
limit = 1 priority = 0 # probably roster created first
<|file_name|>examples.py<|end_file_name|><|fim▁begin|>from .tile import Split, Stack, TileStack class Tile(Split): class left(Stack): weight = 3 priority = 0 limit = 1 class right(TileStack): pass class Max(Split): class main(Stack): tile = False class InstantMsg(Split): class left(TileStack): # or maybe not tiled ? weight = 3 class roster(Stack): limit = 1 priority = 0 # probably roster created first class Gimp(Split): <|fim_middle|> <|fim▁end|>
class toolbox(Stack): limit = 1 size = 184 class main(Stack): weight = 4 priority = 0 class dock(Stack): limit = 1 size = 324
<|file_name|>examples.py<|end_file_name|><|fim▁begin|>from .tile import Split, Stack, TileStack class Tile(Split): class left(Stack): weight = 3 priority = 0 limit = 1 class right(TileStack): pass class Max(Split): class main(Stack): tile = False class InstantMsg(Split): class left(TileStack): # or maybe not tiled ? weight = 3 class roster(Stack): limit = 1 priority = 0 # probably roster created first class Gimp(Split): class toolbox(Stack): <|fim_middle|> class main(Stack): weight = 4 priority = 0 class dock(Stack): limit = 1 size = 324 <|fim▁end|>
limit = 1 size = 184
<|file_name|>examples.py<|end_file_name|><|fim▁begin|>from .tile import Split, Stack, TileStack class Tile(Split): class left(Stack): weight = 3 priority = 0 limit = 1 class right(TileStack): pass class Max(Split): class main(Stack): tile = False class InstantMsg(Split): class left(TileStack): # or maybe not tiled ? weight = 3 class roster(Stack): limit = 1 priority = 0 # probably roster created first class Gimp(Split): class toolbox(Stack): limit = 1 size = 184 class main(Stack): <|fim_middle|> class dock(Stack): limit = 1 size = 324 <|fim▁end|>
weight = 4 priority = 0
<|file_name|>examples.py<|end_file_name|><|fim▁begin|>from .tile import Split, Stack, TileStack class Tile(Split): class left(Stack): weight = 3 priority = 0 limit = 1 class right(TileStack): pass class Max(Split): class main(Stack): tile = False class InstantMsg(Split): class left(TileStack): # or maybe not tiled ? weight = 3 class roster(Stack): limit = 1 priority = 0 # probably roster created first class Gimp(Split): class toolbox(Stack): limit = 1 size = 184 class main(Stack): weight = 4 priority = 0 class dock(Stack): <|fim_middle|> <|fim▁end|>
limit = 1 size = 324
<|file_name|>example.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import time from flask import Flask, session, url_for from flask_debugtoolbar import DebugToolbarExtension<|fim▁hole|>from weblablib import WebLab, requires_active, weblab_user, poll app = Flask(__name__) # XXX: IMPORTANT SETTINGS TO CHANGE app.config['SECRET_KEY'] = 'something random' # e.g., run: os.urandom(32) and put the output here app.config['WEBLAB_USERNAME'] = 'weblabdeusto' # This is the http_username you put in WebLab-Deusto app.config['WEBLAB_PASSWORD'] = 'password' # This is the http_password you put in WebLab-Deusto # XXX You should change... # Use different cookie names for different labs app.config['SESSION_COOKIE_NAME'] = 'lab' # app.config['WEBLAB_UNAUTHORIZED_LINK'] = 'https://weblab.deusto.es/weblab/' # Your own WebLab-Deusto URL # The URL for this lab (e.g., you might have two labs, /lab1 and /lab2 in the same server) app.config['SESSION_COOKIE_PATH'] = '/lab' # The session_id is stored in the Flask session. You might also use a different name app.config['WEBLAB_SESSION_ID_NAME'] = 'lab_session_id' # These are optional parameters # Flask-Debug: don't intercept redirects (go directly) app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False # app.config['WEBLAB_BASE_URL'] = '' # If you want the weblab path to start by /foo/weblab, you can put '/foo' # app.config['WEBLAB_REDIS_URL'] = 'redis://localhost:6379/0' # default value # app.config['WEBLAB_REDIS_BASE'] = 'lab1' # If you have more than one lab in the same redis database # app.config['WEBLAB_CALLBACK_URL'] = '/lab/public' # If you don't pass it in the creator # app.config['WEBLAB_TIMEOUT'] = 15 # in seconds, default value # app.config['WEBLAB_SCHEME'] = 'https' weblab = WebLab(app, callback_url='/lab/public') toolbar = DebugToolbarExtension(app) @weblab.initial_url def initial_url(): """ This returns the landing URL (e.g., where the user will be forwarded). """ return url_for('.lab') @weblab.on_start def on_start(client_data, server_data): """ In this code, you can do something to setup the experiment. It is called for every user, before they start using it. """ print("New user!") print(weblab_user) @weblab.on_dispose def on_stop(): """ In this code, you can do something to clean up the experiment. It is guaranteed to be run. """ print("User expired. Here you should clean resources") print(weblab_user) @app.route('/lab/') @requires_active def lab(): """ This is your code. If you provide @requires_active to any other URL, it is secured. """ user = weblab_user return "Hello %s. You didn't poll in %.2f seconds (timeout configured to %s). Total time left: %s" % (user.username, user.time_without_polling, weblab.timeout, user.time_left) @app.route("/") def index(): return "<html><head></head><body><a href='{}'>Access to the lab</a></body></html>".format(url_for('.lab')) if __name__ == '__main__': print("Run the following:") print() print(" (optionally) $ export FLASK_DEBUG=1") print(" $ export FLASK_APP={}".format(__file__)) print(" $ flask run") print()<|fim▁end|>
<|file_name|>example.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import time from flask import Flask, session, url_for from flask_debugtoolbar import DebugToolbarExtension from weblablib import WebLab, requires_active, weblab_user, poll app = Flask(__name__) # XXX: IMPORTANT SETTINGS TO CHANGE app.config['SECRET_KEY'] = 'something random' # e.g., run: os.urandom(32) and put the output here app.config['WEBLAB_USERNAME'] = 'weblabdeusto' # This is the http_username you put in WebLab-Deusto app.config['WEBLAB_PASSWORD'] = 'password' # This is the http_password you put in WebLab-Deusto # XXX You should change... # Use different cookie names for different labs app.config['SESSION_COOKIE_NAME'] = 'lab' # app.config['WEBLAB_UNAUTHORIZED_LINK'] = 'https://weblab.deusto.es/weblab/' # Your own WebLab-Deusto URL # The URL for this lab (e.g., you might have two labs, /lab1 and /lab2 in the same server) app.config['SESSION_COOKIE_PATH'] = '/lab' # The session_id is stored in the Flask session. You might also use a different name app.config['WEBLAB_SESSION_ID_NAME'] = 'lab_session_id' # These are optional parameters # Flask-Debug: don't intercept redirects (go directly) app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False # app.config['WEBLAB_BASE_URL'] = '' # If you want the weblab path to start by /foo/weblab, you can put '/foo' # app.config['WEBLAB_REDIS_URL'] = 'redis://localhost:6379/0' # default value # app.config['WEBLAB_REDIS_BASE'] = 'lab1' # If you have more than one lab in the same redis database # app.config['WEBLAB_CALLBACK_URL'] = '/lab/public' # If you don't pass it in the creator # app.config['WEBLAB_TIMEOUT'] = 15 # in seconds, default value # app.config['WEBLAB_SCHEME'] = 'https' weblab = WebLab(app, callback_url='/lab/public') toolbar = DebugToolbarExtension(app) @weblab.initial_url def initial_url(): <|fim_middle|> @weblab.on_start def on_start(client_data, server_data): """ In this code, you can do something to setup the experiment. It is called for every user, before they start using it. """ print("New user!") print(weblab_user) @weblab.on_dispose def on_stop(): """ In this code, you can do something to clean up the experiment. It is guaranteed to be run. """ print("User expired. Here you should clean resources") print(weblab_user) @app.route('/lab/') @requires_active def lab(): """ This is your code. If you provide @requires_active to any other URL, it is secured. """ user = weblab_user return "Hello %s. You didn't poll in %.2f seconds (timeout configured to %s). Total time left: %s" % (user.username, user.time_without_polling, weblab.timeout, user.time_left) @app.route("/") def index(): return "<html><head></head><body><a href='{}'>Access to the lab</a></body></html>".format(url_for('.lab')) if __name__ == '__main__': print("Run the following:") print() print(" (optionally) $ export FLASK_DEBUG=1") print(" $ export FLASK_APP={}".format(__file__)) print(" $ flask run") print() <|fim▁end|>
""" This returns the landing URL (e.g., where the user will be forwarded). """ return url_for('.lab')
<|file_name|>example.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import time from flask import Flask, session, url_for from flask_debugtoolbar import DebugToolbarExtension from weblablib import WebLab, requires_active, weblab_user, poll app = Flask(__name__) # XXX: IMPORTANT SETTINGS TO CHANGE app.config['SECRET_KEY'] = 'something random' # e.g., run: os.urandom(32) and put the output here app.config['WEBLAB_USERNAME'] = 'weblabdeusto' # This is the http_username you put in WebLab-Deusto app.config['WEBLAB_PASSWORD'] = 'password' # This is the http_password you put in WebLab-Deusto # XXX You should change... # Use different cookie names for different labs app.config['SESSION_COOKIE_NAME'] = 'lab' # app.config['WEBLAB_UNAUTHORIZED_LINK'] = 'https://weblab.deusto.es/weblab/' # Your own WebLab-Deusto URL # The URL for this lab (e.g., you might have two labs, /lab1 and /lab2 in the same server) app.config['SESSION_COOKIE_PATH'] = '/lab' # The session_id is stored in the Flask session. You might also use a different name app.config['WEBLAB_SESSION_ID_NAME'] = 'lab_session_id' # These are optional parameters # Flask-Debug: don't intercept redirects (go directly) app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False # app.config['WEBLAB_BASE_URL'] = '' # If you want the weblab path to start by /foo/weblab, you can put '/foo' # app.config['WEBLAB_REDIS_URL'] = 'redis://localhost:6379/0' # default value # app.config['WEBLAB_REDIS_BASE'] = 'lab1' # If you have more than one lab in the same redis database # app.config['WEBLAB_CALLBACK_URL'] = '/lab/public' # If you don't pass it in the creator # app.config['WEBLAB_TIMEOUT'] = 15 # in seconds, default value # app.config['WEBLAB_SCHEME'] = 'https' weblab = WebLab(app, callback_url='/lab/public') toolbar = DebugToolbarExtension(app) @weblab.initial_url def initial_url(): """ This returns the landing URL (e.g., where the user will be forwarded). """ return url_for('.lab') @weblab.on_start def on_start(client_data, server_data): <|fim_middle|> @weblab.on_dispose def on_stop(): """ In this code, you can do something to clean up the experiment. It is guaranteed to be run. """ print("User expired. Here you should clean resources") print(weblab_user) @app.route('/lab/') @requires_active def lab(): """ This is your code. If you provide @requires_active to any other URL, it is secured. """ user = weblab_user return "Hello %s. You didn't poll in %.2f seconds (timeout configured to %s). Total time left: %s" % (user.username, user.time_without_polling, weblab.timeout, user.time_left) @app.route("/") def index(): return "<html><head></head><body><a href='{}'>Access to the lab</a></body></html>".format(url_for('.lab')) if __name__ == '__main__': print("Run the following:") print() print(" (optionally) $ export FLASK_DEBUG=1") print(" $ export FLASK_APP={}".format(__file__)) print(" $ flask run") print() <|fim▁end|>
""" In this code, you can do something to setup the experiment. It is called for every user, before they start using it. """ print("New user!") print(weblab_user)
<|file_name|>example.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import time from flask import Flask, session, url_for from flask_debugtoolbar import DebugToolbarExtension from weblablib import WebLab, requires_active, weblab_user, poll app = Flask(__name__) # XXX: IMPORTANT SETTINGS TO CHANGE app.config['SECRET_KEY'] = 'something random' # e.g., run: os.urandom(32) and put the output here app.config['WEBLAB_USERNAME'] = 'weblabdeusto' # This is the http_username you put in WebLab-Deusto app.config['WEBLAB_PASSWORD'] = 'password' # This is the http_password you put in WebLab-Deusto # XXX You should change... # Use different cookie names for different labs app.config['SESSION_COOKIE_NAME'] = 'lab' # app.config['WEBLAB_UNAUTHORIZED_LINK'] = 'https://weblab.deusto.es/weblab/' # Your own WebLab-Deusto URL # The URL for this lab (e.g., you might have two labs, /lab1 and /lab2 in the same server) app.config['SESSION_COOKIE_PATH'] = '/lab' # The session_id is stored in the Flask session. You might also use a different name app.config['WEBLAB_SESSION_ID_NAME'] = 'lab_session_id' # These are optional parameters # Flask-Debug: don't intercept redirects (go directly) app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False # app.config['WEBLAB_BASE_URL'] = '' # If you want the weblab path to start by /foo/weblab, you can put '/foo' # app.config['WEBLAB_REDIS_URL'] = 'redis://localhost:6379/0' # default value # app.config['WEBLAB_REDIS_BASE'] = 'lab1' # If you have more than one lab in the same redis database # app.config['WEBLAB_CALLBACK_URL'] = '/lab/public' # If you don't pass it in the creator # app.config['WEBLAB_TIMEOUT'] = 15 # in seconds, default value # app.config['WEBLAB_SCHEME'] = 'https' weblab = WebLab(app, callback_url='/lab/public') toolbar = DebugToolbarExtension(app) @weblab.initial_url def initial_url(): """ This returns the landing URL (e.g., where the user will be forwarded). """ return url_for('.lab') @weblab.on_start def on_start(client_data, server_data): """ In this code, you can do something to setup the experiment. It is called for every user, before they start using it. """ print("New user!") print(weblab_user) @weblab.on_dispose def on_stop(): <|fim_middle|> @app.route('/lab/') @requires_active def lab(): """ This is your code. If you provide @requires_active to any other URL, it is secured. """ user = weblab_user return "Hello %s. You didn't poll in %.2f seconds (timeout configured to %s). Total time left: %s" % (user.username, user.time_without_polling, weblab.timeout, user.time_left) @app.route("/") def index(): return "<html><head></head><body><a href='{}'>Access to the lab</a></body></html>".format(url_for('.lab')) if __name__ == '__main__': print("Run the following:") print() print(" (optionally) $ export FLASK_DEBUG=1") print(" $ export FLASK_APP={}".format(__file__)) print(" $ flask run") print() <|fim▁end|>
""" In this code, you can do something to clean up the experiment. It is guaranteed to be run. """ print("User expired. Here you should clean resources") print(weblab_user)
<|file_name|>example.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import time from flask import Flask, session, url_for from flask_debugtoolbar import DebugToolbarExtension from weblablib import WebLab, requires_active, weblab_user, poll app = Flask(__name__) # XXX: IMPORTANT SETTINGS TO CHANGE app.config['SECRET_KEY'] = 'something random' # e.g., run: os.urandom(32) and put the output here app.config['WEBLAB_USERNAME'] = 'weblabdeusto' # This is the http_username you put in WebLab-Deusto app.config['WEBLAB_PASSWORD'] = 'password' # This is the http_password you put in WebLab-Deusto # XXX You should change... # Use different cookie names for different labs app.config['SESSION_COOKIE_NAME'] = 'lab' # app.config['WEBLAB_UNAUTHORIZED_LINK'] = 'https://weblab.deusto.es/weblab/' # Your own WebLab-Deusto URL # The URL for this lab (e.g., you might have two labs, /lab1 and /lab2 in the same server) app.config['SESSION_COOKIE_PATH'] = '/lab' # The session_id is stored in the Flask session. You might also use a different name app.config['WEBLAB_SESSION_ID_NAME'] = 'lab_session_id' # These are optional parameters # Flask-Debug: don't intercept redirects (go directly) app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False # app.config['WEBLAB_BASE_URL'] = '' # If you want the weblab path to start by /foo/weblab, you can put '/foo' # app.config['WEBLAB_REDIS_URL'] = 'redis://localhost:6379/0' # default value # app.config['WEBLAB_REDIS_BASE'] = 'lab1' # If you have more than one lab in the same redis database # app.config['WEBLAB_CALLBACK_URL'] = '/lab/public' # If you don't pass it in the creator # app.config['WEBLAB_TIMEOUT'] = 15 # in seconds, default value # app.config['WEBLAB_SCHEME'] = 'https' weblab = WebLab(app, callback_url='/lab/public') toolbar = DebugToolbarExtension(app) @weblab.initial_url def initial_url(): """ This returns the landing URL (e.g., where the user will be forwarded). """ return url_for('.lab') @weblab.on_start def on_start(client_data, server_data): """ In this code, you can do something to setup the experiment. It is called for every user, before they start using it. """ print("New user!") print(weblab_user) @weblab.on_dispose def on_stop(): """ In this code, you can do something to clean up the experiment. It is guaranteed to be run. """ print("User expired. Here you should clean resources") print(weblab_user) @app.route('/lab/') @requires_active def lab(): <|fim_middle|> @app.route("/") def index(): return "<html><head></head><body><a href='{}'>Access to the lab</a></body></html>".format(url_for('.lab')) if __name__ == '__main__': print("Run the following:") print() print(" (optionally) $ export FLASK_DEBUG=1") print(" $ export FLASK_APP={}".format(__file__)) print(" $ flask run") print() <|fim▁end|>
""" This is your code. If you provide @requires_active to any other URL, it is secured. """ user = weblab_user return "Hello %s. You didn't poll in %.2f seconds (timeout configured to %s). Total time left: %s" % (user.username, user.time_without_polling, weblab.timeout, user.time_left)
<|file_name|>example.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import time from flask import Flask, session, url_for from flask_debugtoolbar import DebugToolbarExtension from weblablib import WebLab, requires_active, weblab_user, poll app = Flask(__name__) # XXX: IMPORTANT SETTINGS TO CHANGE app.config['SECRET_KEY'] = 'something random' # e.g., run: os.urandom(32) and put the output here app.config['WEBLAB_USERNAME'] = 'weblabdeusto' # This is the http_username you put in WebLab-Deusto app.config['WEBLAB_PASSWORD'] = 'password' # This is the http_password you put in WebLab-Deusto # XXX You should change... # Use different cookie names for different labs app.config['SESSION_COOKIE_NAME'] = 'lab' # app.config['WEBLAB_UNAUTHORIZED_LINK'] = 'https://weblab.deusto.es/weblab/' # Your own WebLab-Deusto URL # The URL for this lab (e.g., you might have two labs, /lab1 and /lab2 in the same server) app.config['SESSION_COOKIE_PATH'] = '/lab' # The session_id is stored in the Flask session. You might also use a different name app.config['WEBLAB_SESSION_ID_NAME'] = 'lab_session_id' # These are optional parameters # Flask-Debug: don't intercept redirects (go directly) app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False # app.config['WEBLAB_BASE_URL'] = '' # If you want the weblab path to start by /foo/weblab, you can put '/foo' # app.config['WEBLAB_REDIS_URL'] = 'redis://localhost:6379/0' # default value # app.config['WEBLAB_REDIS_BASE'] = 'lab1' # If you have more than one lab in the same redis database # app.config['WEBLAB_CALLBACK_URL'] = '/lab/public' # If you don't pass it in the creator # app.config['WEBLAB_TIMEOUT'] = 15 # in seconds, default value # app.config['WEBLAB_SCHEME'] = 'https' weblab = WebLab(app, callback_url='/lab/public') toolbar = DebugToolbarExtension(app) @weblab.initial_url def initial_url(): """ This returns the landing URL (e.g., where the user will be forwarded). """ return url_for('.lab') @weblab.on_start def on_start(client_data, server_data): """ In this code, you can do something to setup the experiment. It is called for every user, before they start using it. """ print("New user!") print(weblab_user) @weblab.on_dispose def on_stop(): """ In this code, you can do something to clean up the experiment. It is guaranteed to be run. """ print("User expired. Here you should clean resources") print(weblab_user) @app.route('/lab/') @requires_active def lab(): """ This is your code. If you provide @requires_active to any other URL, it is secured. """ user = weblab_user return "Hello %s. You didn't poll in %.2f seconds (timeout configured to %s). Total time left: %s" % (user.username, user.time_without_polling, weblab.timeout, user.time_left) @app.route("/") def index(): <|fim_middle|> if __name__ == '__main__': print("Run the following:") print() print(" (optionally) $ export FLASK_DEBUG=1") print(" $ export FLASK_APP={}".format(__file__)) print(" $ flask run") print() <|fim▁end|>
return "<html><head></head><body><a href='{}'>Access to the lab</a></body></html>".format(url_for('.lab'))
<|file_name|>example.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import time from flask import Flask, session, url_for from flask_debugtoolbar import DebugToolbarExtension from weblablib import WebLab, requires_active, weblab_user, poll app = Flask(__name__) # XXX: IMPORTANT SETTINGS TO CHANGE app.config['SECRET_KEY'] = 'something random' # e.g., run: os.urandom(32) and put the output here app.config['WEBLAB_USERNAME'] = 'weblabdeusto' # This is the http_username you put in WebLab-Deusto app.config['WEBLAB_PASSWORD'] = 'password' # This is the http_password you put in WebLab-Deusto # XXX You should change... # Use different cookie names for different labs app.config['SESSION_COOKIE_NAME'] = 'lab' # app.config['WEBLAB_UNAUTHORIZED_LINK'] = 'https://weblab.deusto.es/weblab/' # Your own WebLab-Deusto URL # The URL for this lab (e.g., you might have two labs, /lab1 and /lab2 in the same server) app.config['SESSION_COOKIE_PATH'] = '/lab' # The session_id is stored in the Flask session. You might also use a different name app.config['WEBLAB_SESSION_ID_NAME'] = 'lab_session_id' # These are optional parameters # Flask-Debug: don't intercept redirects (go directly) app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False # app.config['WEBLAB_BASE_URL'] = '' # If you want the weblab path to start by /foo/weblab, you can put '/foo' # app.config['WEBLAB_REDIS_URL'] = 'redis://localhost:6379/0' # default value # app.config['WEBLAB_REDIS_BASE'] = 'lab1' # If you have more than one lab in the same redis database # app.config['WEBLAB_CALLBACK_URL'] = '/lab/public' # If you don't pass it in the creator # app.config['WEBLAB_TIMEOUT'] = 15 # in seconds, default value # app.config['WEBLAB_SCHEME'] = 'https' weblab = WebLab(app, callback_url='/lab/public') toolbar = DebugToolbarExtension(app) @weblab.initial_url def initial_url(): """ This returns the landing URL (e.g., where the user will be forwarded). """ return url_for('.lab') @weblab.on_start def on_start(client_data, server_data): """ In this code, you can do something to setup the experiment. It is called for every user, before they start using it. """ print("New user!") print(weblab_user) @weblab.on_dispose def on_stop(): """ In this code, you can do something to clean up the experiment. It is guaranteed to be run. """ print("User expired. Here you should clean resources") print(weblab_user) @app.route('/lab/') @requires_active def lab(): """ This is your code. If you provide @requires_active to any other URL, it is secured. """ user = weblab_user return "Hello %s. You didn't poll in %.2f seconds (timeout configured to %s). Total time left: %s" % (user.username, user.time_without_polling, weblab.timeout, user.time_left) @app.route("/") def index(): return "<html><head></head><body><a href='{}'>Access to the lab</a></body></html>".format(url_for('.lab')) if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
print("Run the following:") print() print(" (optionally) $ export FLASK_DEBUG=1") print(" $ export FLASK_APP={}".format(__file__)) print(" $ flask run") print()
<|file_name|>example.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import time from flask import Flask, session, url_for from flask_debugtoolbar import DebugToolbarExtension from weblablib import WebLab, requires_active, weblab_user, poll app = Flask(__name__) # XXX: IMPORTANT SETTINGS TO CHANGE app.config['SECRET_KEY'] = 'something random' # e.g., run: os.urandom(32) and put the output here app.config['WEBLAB_USERNAME'] = 'weblabdeusto' # This is the http_username you put in WebLab-Deusto app.config['WEBLAB_PASSWORD'] = 'password' # This is the http_password you put in WebLab-Deusto # XXX You should change... # Use different cookie names for different labs app.config['SESSION_COOKIE_NAME'] = 'lab' # app.config['WEBLAB_UNAUTHORIZED_LINK'] = 'https://weblab.deusto.es/weblab/' # Your own WebLab-Deusto URL # The URL for this lab (e.g., you might have two labs, /lab1 and /lab2 in the same server) app.config['SESSION_COOKIE_PATH'] = '/lab' # The session_id is stored in the Flask session. You might also use a different name app.config['WEBLAB_SESSION_ID_NAME'] = 'lab_session_id' # These are optional parameters # Flask-Debug: don't intercept redirects (go directly) app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False # app.config['WEBLAB_BASE_URL'] = '' # If you want the weblab path to start by /foo/weblab, you can put '/foo' # app.config['WEBLAB_REDIS_URL'] = 'redis://localhost:6379/0' # default value # app.config['WEBLAB_REDIS_BASE'] = 'lab1' # If you have more than one lab in the same redis database # app.config['WEBLAB_CALLBACK_URL'] = '/lab/public' # If you don't pass it in the creator # app.config['WEBLAB_TIMEOUT'] = 15 # in seconds, default value # app.config['WEBLAB_SCHEME'] = 'https' weblab = WebLab(app, callback_url='/lab/public') toolbar = DebugToolbarExtension(app) @weblab.initial_url def <|fim_middle|>(): """ This returns the landing URL (e.g., where the user will be forwarded). """ return url_for('.lab') @weblab.on_start def on_start(client_data, server_data): """ In this code, you can do something to setup the experiment. It is called for every user, before they start using it. """ print("New user!") print(weblab_user) @weblab.on_dispose def on_stop(): """ In this code, you can do something to clean up the experiment. It is guaranteed to be run. """ print("User expired. Here you should clean resources") print(weblab_user) @app.route('/lab/') @requires_active def lab(): """ This is your code. If you provide @requires_active to any other URL, it is secured. """ user = weblab_user return "Hello %s. You didn't poll in %.2f seconds (timeout configured to %s). Total time left: %s" % (user.username, user.time_without_polling, weblab.timeout, user.time_left) @app.route("/") def index(): return "<html><head></head><body><a href='{}'>Access to the lab</a></body></html>".format(url_for('.lab')) if __name__ == '__main__': print("Run the following:") print() print(" (optionally) $ export FLASK_DEBUG=1") print(" $ export FLASK_APP={}".format(__file__)) print(" $ flask run") print() <|fim▁end|>
initial_url
<|file_name|>example.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import time from flask import Flask, session, url_for from flask_debugtoolbar import DebugToolbarExtension from weblablib import WebLab, requires_active, weblab_user, poll app = Flask(__name__) # XXX: IMPORTANT SETTINGS TO CHANGE app.config['SECRET_KEY'] = 'something random' # e.g., run: os.urandom(32) and put the output here app.config['WEBLAB_USERNAME'] = 'weblabdeusto' # This is the http_username you put in WebLab-Deusto app.config['WEBLAB_PASSWORD'] = 'password' # This is the http_password you put in WebLab-Deusto # XXX You should change... # Use different cookie names for different labs app.config['SESSION_COOKIE_NAME'] = 'lab' # app.config['WEBLAB_UNAUTHORIZED_LINK'] = 'https://weblab.deusto.es/weblab/' # Your own WebLab-Deusto URL # The URL for this lab (e.g., you might have two labs, /lab1 and /lab2 in the same server) app.config['SESSION_COOKIE_PATH'] = '/lab' # The session_id is stored in the Flask session. You might also use a different name app.config['WEBLAB_SESSION_ID_NAME'] = 'lab_session_id' # These are optional parameters # Flask-Debug: don't intercept redirects (go directly) app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False # app.config['WEBLAB_BASE_URL'] = '' # If you want the weblab path to start by /foo/weblab, you can put '/foo' # app.config['WEBLAB_REDIS_URL'] = 'redis://localhost:6379/0' # default value # app.config['WEBLAB_REDIS_BASE'] = 'lab1' # If you have more than one lab in the same redis database # app.config['WEBLAB_CALLBACK_URL'] = '/lab/public' # If you don't pass it in the creator # app.config['WEBLAB_TIMEOUT'] = 15 # in seconds, default value # app.config['WEBLAB_SCHEME'] = 'https' weblab = WebLab(app, callback_url='/lab/public') toolbar = DebugToolbarExtension(app) @weblab.initial_url def initial_url(): """ This returns the landing URL (e.g., where the user will be forwarded). """ return url_for('.lab') @weblab.on_start def <|fim_middle|>(client_data, server_data): """ In this code, you can do something to setup the experiment. It is called for every user, before they start using it. """ print("New user!") print(weblab_user) @weblab.on_dispose def on_stop(): """ In this code, you can do something to clean up the experiment. It is guaranteed to be run. """ print("User expired. Here you should clean resources") print(weblab_user) @app.route('/lab/') @requires_active def lab(): """ This is your code. If you provide @requires_active to any other URL, it is secured. """ user = weblab_user return "Hello %s. You didn't poll in %.2f seconds (timeout configured to %s). Total time left: %s" % (user.username, user.time_without_polling, weblab.timeout, user.time_left) @app.route("/") def index(): return "<html><head></head><body><a href='{}'>Access to the lab</a></body></html>".format(url_for('.lab')) if __name__ == '__main__': print("Run the following:") print() print(" (optionally) $ export FLASK_DEBUG=1") print(" $ export FLASK_APP={}".format(__file__)) print(" $ flask run") print() <|fim▁end|>
on_start
<|file_name|>example.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import time from flask import Flask, session, url_for from flask_debugtoolbar import DebugToolbarExtension from weblablib import WebLab, requires_active, weblab_user, poll app = Flask(__name__) # XXX: IMPORTANT SETTINGS TO CHANGE app.config['SECRET_KEY'] = 'something random' # e.g., run: os.urandom(32) and put the output here app.config['WEBLAB_USERNAME'] = 'weblabdeusto' # This is the http_username you put in WebLab-Deusto app.config['WEBLAB_PASSWORD'] = 'password' # This is the http_password you put in WebLab-Deusto # XXX You should change... # Use different cookie names for different labs app.config['SESSION_COOKIE_NAME'] = 'lab' # app.config['WEBLAB_UNAUTHORIZED_LINK'] = 'https://weblab.deusto.es/weblab/' # Your own WebLab-Deusto URL # The URL for this lab (e.g., you might have two labs, /lab1 and /lab2 in the same server) app.config['SESSION_COOKIE_PATH'] = '/lab' # The session_id is stored in the Flask session. You might also use a different name app.config['WEBLAB_SESSION_ID_NAME'] = 'lab_session_id' # These are optional parameters # Flask-Debug: don't intercept redirects (go directly) app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False # app.config['WEBLAB_BASE_URL'] = '' # If you want the weblab path to start by /foo/weblab, you can put '/foo' # app.config['WEBLAB_REDIS_URL'] = 'redis://localhost:6379/0' # default value # app.config['WEBLAB_REDIS_BASE'] = 'lab1' # If you have more than one lab in the same redis database # app.config['WEBLAB_CALLBACK_URL'] = '/lab/public' # If you don't pass it in the creator # app.config['WEBLAB_TIMEOUT'] = 15 # in seconds, default value # app.config['WEBLAB_SCHEME'] = 'https' weblab = WebLab(app, callback_url='/lab/public') toolbar = DebugToolbarExtension(app) @weblab.initial_url def initial_url(): """ This returns the landing URL (e.g., where the user will be forwarded). """ return url_for('.lab') @weblab.on_start def on_start(client_data, server_data): """ In this code, you can do something to setup the experiment. It is called for every user, before they start using it. """ print("New user!") print(weblab_user) @weblab.on_dispose def <|fim_middle|>(): """ In this code, you can do something to clean up the experiment. It is guaranteed to be run. """ print("User expired. Here you should clean resources") print(weblab_user) @app.route('/lab/') @requires_active def lab(): """ This is your code. If you provide @requires_active to any other URL, it is secured. """ user = weblab_user return "Hello %s. You didn't poll in %.2f seconds (timeout configured to %s). Total time left: %s" % (user.username, user.time_without_polling, weblab.timeout, user.time_left) @app.route("/") def index(): return "<html><head></head><body><a href='{}'>Access to the lab</a></body></html>".format(url_for('.lab')) if __name__ == '__main__': print("Run the following:") print() print(" (optionally) $ export FLASK_DEBUG=1") print(" $ export FLASK_APP={}".format(__file__)) print(" $ flask run") print() <|fim▁end|>
on_stop
<|file_name|>example.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import time from flask import Flask, session, url_for from flask_debugtoolbar import DebugToolbarExtension from weblablib import WebLab, requires_active, weblab_user, poll app = Flask(__name__) # XXX: IMPORTANT SETTINGS TO CHANGE app.config['SECRET_KEY'] = 'something random' # e.g., run: os.urandom(32) and put the output here app.config['WEBLAB_USERNAME'] = 'weblabdeusto' # This is the http_username you put in WebLab-Deusto app.config['WEBLAB_PASSWORD'] = 'password' # This is the http_password you put in WebLab-Deusto # XXX You should change... # Use different cookie names for different labs app.config['SESSION_COOKIE_NAME'] = 'lab' # app.config['WEBLAB_UNAUTHORIZED_LINK'] = 'https://weblab.deusto.es/weblab/' # Your own WebLab-Deusto URL # The URL for this lab (e.g., you might have two labs, /lab1 and /lab2 in the same server) app.config['SESSION_COOKIE_PATH'] = '/lab' # The session_id is stored in the Flask session. You might also use a different name app.config['WEBLAB_SESSION_ID_NAME'] = 'lab_session_id' # These are optional parameters # Flask-Debug: don't intercept redirects (go directly) app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False # app.config['WEBLAB_BASE_URL'] = '' # If you want the weblab path to start by /foo/weblab, you can put '/foo' # app.config['WEBLAB_REDIS_URL'] = 'redis://localhost:6379/0' # default value # app.config['WEBLAB_REDIS_BASE'] = 'lab1' # If you have more than one lab in the same redis database # app.config['WEBLAB_CALLBACK_URL'] = '/lab/public' # If you don't pass it in the creator # app.config['WEBLAB_TIMEOUT'] = 15 # in seconds, default value # app.config['WEBLAB_SCHEME'] = 'https' weblab = WebLab(app, callback_url='/lab/public') toolbar = DebugToolbarExtension(app) @weblab.initial_url def initial_url(): """ This returns the landing URL (e.g., where the user will be forwarded). """ return url_for('.lab') @weblab.on_start def on_start(client_data, server_data): """ In this code, you can do something to setup the experiment. It is called for every user, before they start using it. """ print("New user!") print(weblab_user) @weblab.on_dispose def on_stop(): """ In this code, you can do something to clean up the experiment. It is guaranteed to be run. """ print("User expired. Here you should clean resources") print(weblab_user) @app.route('/lab/') @requires_active def <|fim_middle|>(): """ This is your code. If you provide @requires_active to any other URL, it is secured. """ user = weblab_user return "Hello %s. You didn't poll in %.2f seconds (timeout configured to %s). Total time left: %s" % (user.username, user.time_without_polling, weblab.timeout, user.time_left) @app.route("/") def index(): return "<html><head></head><body><a href='{}'>Access to the lab</a></body></html>".format(url_for('.lab')) if __name__ == '__main__': print("Run the following:") print() print(" (optionally) $ export FLASK_DEBUG=1") print(" $ export FLASK_APP={}".format(__file__)) print(" $ flask run") print() <|fim▁end|>
lab
<|file_name|>example.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import time from flask import Flask, session, url_for from flask_debugtoolbar import DebugToolbarExtension from weblablib import WebLab, requires_active, weblab_user, poll app = Flask(__name__) # XXX: IMPORTANT SETTINGS TO CHANGE app.config['SECRET_KEY'] = 'something random' # e.g., run: os.urandom(32) and put the output here app.config['WEBLAB_USERNAME'] = 'weblabdeusto' # This is the http_username you put in WebLab-Deusto app.config['WEBLAB_PASSWORD'] = 'password' # This is the http_password you put in WebLab-Deusto # XXX You should change... # Use different cookie names for different labs app.config['SESSION_COOKIE_NAME'] = 'lab' # app.config['WEBLAB_UNAUTHORIZED_LINK'] = 'https://weblab.deusto.es/weblab/' # Your own WebLab-Deusto URL # The URL for this lab (e.g., you might have two labs, /lab1 and /lab2 in the same server) app.config['SESSION_COOKIE_PATH'] = '/lab' # The session_id is stored in the Flask session. You might also use a different name app.config['WEBLAB_SESSION_ID_NAME'] = 'lab_session_id' # These are optional parameters # Flask-Debug: don't intercept redirects (go directly) app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False # app.config['WEBLAB_BASE_URL'] = '' # If you want the weblab path to start by /foo/weblab, you can put '/foo' # app.config['WEBLAB_REDIS_URL'] = 'redis://localhost:6379/0' # default value # app.config['WEBLAB_REDIS_BASE'] = 'lab1' # If you have more than one lab in the same redis database # app.config['WEBLAB_CALLBACK_URL'] = '/lab/public' # If you don't pass it in the creator # app.config['WEBLAB_TIMEOUT'] = 15 # in seconds, default value # app.config['WEBLAB_SCHEME'] = 'https' weblab = WebLab(app, callback_url='/lab/public') toolbar = DebugToolbarExtension(app) @weblab.initial_url def initial_url(): """ This returns the landing URL (e.g., where the user will be forwarded). """ return url_for('.lab') @weblab.on_start def on_start(client_data, server_data): """ In this code, you can do something to setup the experiment. It is called for every user, before they start using it. """ print("New user!") print(weblab_user) @weblab.on_dispose def on_stop(): """ In this code, you can do something to clean up the experiment. It is guaranteed to be run. """ print("User expired. Here you should clean resources") print(weblab_user) @app.route('/lab/') @requires_active def lab(): """ This is your code. If you provide @requires_active to any other URL, it is secured. """ user = weblab_user return "Hello %s. You didn't poll in %.2f seconds (timeout configured to %s). Total time left: %s" % (user.username, user.time_without_polling, weblab.timeout, user.time_left) @app.route("/") def <|fim_middle|>(): return "<html><head></head><body><a href='{}'>Access to the lab</a></body></html>".format(url_for('.lab')) if __name__ == '__main__': print("Run the following:") print() print(" (optionally) $ export FLASK_DEBUG=1") print(" $ export FLASK_APP={}".format(__file__)) print(" $ flask run") print() <|fim▁end|>
index
<|file_name|>vis.py<|end_file_name|><|fim▁begin|>""" Visualize possible stitches with the outcome of the validator. """ import math import random import matplotlib.pyplot as plt import networkx as nx import numpy as np from mpl_toolkits.mplot3d import Axes3D import stitcher SPACE = 25 TYPE_FORMAT = {'a': '^', 'b': 's', 'c': 'v'} def show(graphs, request, titles, prog='neato', size=None, type_format=None, filename=None): """ Display the results using matplotlib. """ if not size: size = _get_size(len(graphs)) fig, axarr = plt.subplots(size[0], size[1], figsize=(18, 10)) fig.set_facecolor('white') x_val = 0 y_val = 0 index = 0 if size[0] == 1: axarr = np.array(axarr).reshape((1, size[1])) for candidate in graphs: # axarr[x_val, y_val].axis('off') axarr[x_val, y_val].xaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].yaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].xaxis.set_ticks([]) axarr[x_val, y_val].yaxis.set_ticks([]) axarr[x_val, y_val].set_title(titles[index]) # axarr[x_val, y_val].set_axis_bgcolor("white") if not type_format: type_format = TYPE_FORMAT _plot_subplot(candidate, request.nodes(), prog, type_format, axarr[x_val, y_val]) y_val += 1 if y_val > size[1] - 1: y_val = 0 x_val += 1 index += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close()<|fim▁hole|> Plot a single candidate graph. """ pos = nx.nx_agraph.graphviz_layout(graph, prog=prog) # draw the nodes for node, values in graph.nodes(data=True): shape = 'o' if values[stitcher.TYPE_ATTR] in type_format: shape = type_format[values[stitcher.TYPE_ATTR]] color = 'g' alpha = 0.8 if node in new_nodes: color = 'b' alpha = 0.2 elif 'rank' in values and values['rank'] > 7: color = 'r' elif 'rank' in values and values['rank'] < 7 and values['rank'] > 3: color = 'y' nx.draw_networkx_nodes(graph, pos, nodelist=[node], node_color=color, node_shape=shape, alpha=alpha, ax=axes) # draw the edges dotted_line = [] normal_line = [] for src, trg in graph.edges(): if src in new_nodes and trg not in new_nodes: dotted_line.append((src, trg)) else: normal_line.append((src, trg)) nx.draw_networkx_edges(graph, pos, edgelist=dotted_line, style='dotted', ax=axes) nx.draw_networkx_edges(graph, pos, edgelist=normal_line, ax=axes) # draw labels nx.draw_networkx_labels(graph, pos, ax=axes) def show_3d(graphs, request, titles, prog='neato', filename=None): """ Show the candidates in 3d - the request elevated above the container. """ fig = plt.figure(figsize=(18, 10)) fig.set_facecolor('white') i = 0 size = _get_size(len(graphs)) for graph in graphs: axes = fig.add_subplot(size[0], size[1], i+1, projection=Axes3D.name) axes.set_title(titles[i]) axes._axis3don = False _plot_3d_subplot(graph, request, prog, axes) i += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close() def _plot_3d_subplot(graph, request, prog, axes): """ Plot a single candidate graph in 3d. """ cache = {} tmp = graph.copy() for node in request.nodes(): tmp.remove_node(node) pos = nx.nx_agraph.graphviz_layout(tmp, prog=prog) # the container for item in tmp.nodes(): axes.plot([pos[item][0]], [pos[item][1]], [0], linestyle="None", marker="o", color='gray') axes.text(pos[item][0], pos[item][1], 0, item) for src, trg in tmp.edges(): axes.plot([pos[src][0], pos[trg][0]], [pos[src][1], pos[trg][1]], [0, 0], color='gray') # the new nodes for item in graph.nodes(): if item in request.nodes(): for nghb in graph.neighbors(item): if nghb in tmp.nodes(): x_val = pos[nghb][0] y_val = pos[nghb][1] if (x_val, y_val) in list(cache.values()): x_val = pos[nghb][0] + random.randint(10, SPACE) y_val = pos[nghb][0] + random.randint(10, SPACE) cache[item] = (x_val, y_val) # edge axes.plot([x_val, pos[nghb][0]], [y_val, pos[nghb][1]], [SPACE, 0], color='blue') axes.plot([x_val], [y_val], [SPACE], linestyle="None", marker="o", color='blue') axes.text(x_val, y_val, SPACE, item) for src, trg in request.edges(): if trg in cache and src in cache: axes.plot([cache[src][0], cache[trg][0]], [cache[src][1], cache[trg][1]], [SPACE, SPACE], color='blue') def _get_size(n_items): """ Calculate the size of the subplot layouts based on number of items. """ n_cols = math.ceil(math.sqrt(n_items)) n_rows = math.floor(math.sqrt(n_items)) if n_cols * n_rows < n_items: n_cols += 1 return int(n_rows), int(n_cols)<|fim▁end|>
def _plot_subplot(graph, new_nodes, prog, type_format, axes): """
<|file_name|>vis.py<|end_file_name|><|fim▁begin|> """ Visualize possible stitches with the outcome of the validator. """ import math import random import matplotlib.pyplot as plt import networkx as nx import numpy as np from mpl_toolkits.mplot3d import Axes3D import stitcher SPACE = 25 TYPE_FORMAT = {'a': '^', 'b': 's', 'c': 'v'} def show(graphs, request, titles, prog='neato', size=None, type_format=None, filename=None): <|fim_middle|> def _plot_subplot(graph, new_nodes, prog, type_format, axes): """ Plot a single candidate graph. """ pos = nx.nx_agraph.graphviz_layout(graph, prog=prog) # draw the nodes for node, values in graph.nodes(data=True): shape = 'o' if values[stitcher.TYPE_ATTR] in type_format: shape = type_format[values[stitcher.TYPE_ATTR]] color = 'g' alpha = 0.8 if node in new_nodes: color = 'b' alpha = 0.2 elif 'rank' in values and values['rank'] > 7: color = 'r' elif 'rank' in values and values['rank'] < 7 and values['rank'] > 3: color = 'y' nx.draw_networkx_nodes(graph, pos, nodelist=[node], node_color=color, node_shape=shape, alpha=alpha, ax=axes) # draw the edges dotted_line = [] normal_line = [] for src, trg in graph.edges(): if src in new_nodes and trg not in new_nodes: dotted_line.append((src, trg)) else: normal_line.append((src, trg)) nx.draw_networkx_edges(graph, pos, edgelist=dotted_line, style='dotted', ax=axes) nx.draw_networkx_edges(graph, pos, edgelist=normal_line, ax=axes) # draw labels nx.draw_networkx_labels(graph, pos, ax=axes) def show_3d(graphs, request, titles, prog='neato', filename=None): """ Show the candidates in 3d - the request elevated above the container. """ fig = plt.figure(figsize=(18, 10)) fig.set_facecolor('white') i = 0 size = _get_size(len(graphs)) for graph in graphs: axes = fig.add_subplot(size[0], size[1], i+1, projection=Axes3D.name) axes.set_title(titles[i]) axes._axis3don = False _plot_3d_subplot(graph, request, prog, axes) i += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close() def _plot_3d_subplot(graph, request, prog, axes): """ Plot a single candidate graph in 3d. """ cache = {} tmp = graph.copy() for node in request.nodes(): tmp.remove_node(node) pos = nx.nx_agraph.graphviz_layout(tmp, prog=prog) # the container for item in tmp.nodes(): axes.plot([pos[item][0]], [pos[item][1]], [0], linestyle="None", marker="o", color='gray') axes.text(pos[item][0], pos[item][1], 0, item) for src, trg in tmp.edges(): axes.plot([pos[src][0], pos[trg][0]], [pos[src][1], pos[trg][1]], [0, 0], color='gray') # the new nodes for item in graph.nodes(): if item in request.nodes(): for nghb in graph.neighbors(item): if nghb in tmp.nodes(): x_val = pos[nghb][0] y_val = pos[nghb][1] if (x_val, y_val) in list(cache.values()): x_val = pos[nghb][0] + random.randint(10, SPACE) y_val = pos[nghb][0] + random.randint(10, SPACE) cache[item] = (x_val, y_val) # edge axes.plot([x_val, pos[nghb][0]], [y_val, pos[nghb][1]], [SPACE, 0], color='blue') axes.plot([x_val], [y_val], [SPACE], linestyle="None", marker="o", color='blue') axes.text(x_val, y_val, SPACE, item) for src, trg in request.edges(): if trg in cache and src in cache: axes.plot([cache[src][0], cache[trg][0]], [cache[src][1], cache[trg][1]], [SPACE, SPACE], color='blue') def _get_size(n_items): """ Calculate the size of the subplot layouts based on number of items. """ n_cols = math.ceil(math.sqrt(n_items)) n_rows = math.floor(math.sqrt(n_items)) if n_cols * n_rows < n_items: n_cols += 1 return int(n_rows), int(n_cols) <|fim▁end|>
""" Display the results using matplotlib. """ if not size: size = _get_size(len(graphs)) fig, axarr = plt.subplots(size[0], size[1], figsize=(18, 10)) fig.set_facecolor('white') x_val = 0 y_val = 0 index = 0 if size[0] == 1: axarr = np.array(axarr).reshape((1, size[1])) for candidate in graphs: # axarr[x_val, y_val].axis('off') axarr[x_val, y_val].xaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].yaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].xaxis.set_ticks([]) axarr[x_val, y_val].yaxis.set_ticks([]) axarr[x_val, y_val].set_title(titles[index]) # axarr[x_val, y_val].set_axis_bgcolor("white") if not type_format: type_format = TYPE_FORMAT _plot_subplot(candidate, request.nodes(), prog, type_format, axarr[x_val, y_val]) y_val += 1 if y_val > size[1] - 1: y_val = 0 x_val += 1 index += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close()
<|file_name|>vis.py<|end_file_name|><|fim▁begin|> """ Visualize possible stitches with the outcome of the validator. """ import math import random import matplotlib.pyplot as plt import networkx as nx import numpy as np from mpl_toolkits.mplot3d import Axes3D import stitcher SPACE = 25 TYPE_FORMAT = {'a': '^', 'b': 's', 'c': 'v'} def show(graphs, request, titles, prog='neato', size=None, type_format=None, filename=None): """ Display the results using matplotlib. """ if not size: size = _get_size(len(graphs)) fig, axarr = plt.subplots(size[0], size[1], figsize=(18, 10)) fig.set_facecolor('white') x_val = 0 y_val = 0 index = 0 if size[0] == 1: axarr = np.array(axarr).reshape((1, size[1])) for candidate in graphs: # axarr[x_val, y_val].axis('off') axarr[x_val, y_val].xaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].yaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].xaxis.set_ticks([]) axarr[x_val, y_val].yaxis.set_ticks([]) axarr[x_val, y_val].set_title(titles[index]) # axarr[x_val, y_val].set_axis_bgcolor("white") if not type_format: type_format = TYPE_FORMAT _plot_subplot(candidate, request.nodes(), prog, type_format, axarr[x_val, y_val]) y_val += 1 if y_val > size[1] - 1: y_val = 0 x_val += 1 index += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close() def _plot_subplot(graph, new_nodes, prog, type_format, axes): <|fim_middle|> def show_3d(graphs, request, titles, prog='neato', filename=None): """ Show the candidates in 3d - the request elevated above the container. """ fig = plt.figure(figsize=(18, 10)) fig.set_facecolor('white') i = 0 size = _get_size(len(graphs)) for graph in graphs: axes = fig.add_subplot(size[0], size[1], i+1, projection=Axes3D.name) axes.set_title(titles[i]) axes._axis3don = False _plot_3d_subplot(graph, request, prog, axes) i += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close() def _plot_3d_subplot(graph, request, prog, axes): """ Plot a single candidate graph in 3d. """ cache = {} tmp = graph.copy() for node in request.nodes(): tmp.remove_node(node) pos = nx.nx_agraph.graphviz_layout(tmp, prog=prog) # the container for item in tmp.nodes(): axes.plot([pos[item][0]], [pos[item][1]], [0], linestyle="None", marker="o", color='gray') axes.text(pos[item][0], pos[item][1], 0, item) for src, trg in tmp.edges(): axes.plot([pos[src][0], pos[trg][0]], [pos[src][1], pos[trg][1]], [0, 0], color='gray') # the new nodes for item in graph.nodes(): if item in request.nodes(): for nghb in graph.neighbors(item): if nghb in tmp.nodes(): x_val = pos[nghb][0] y_val = pos[nghb][1] if (x_val, y_val) in list(cache.values()): x_val = pos[nghb][0] + random.randint(10, SPACE) y_val = pos[nghb][0] + random.randint(10, SPACE) cache[item] = (x_val, y_val) # edge axes.plot([x_val, pos[nghb][0]], [y_val, pos[nghb][1]], [SPACE, 0], color='blue') axes.plot([x_val], [y_val], [SPACE], linestyle="None", marker="o", color='blue') axes.text(x_val, y_val, SPACE, item) for src, trg in request.edges(): if trg in cache and src in cache: axes.plot([cache[src][0], cache[trg][0]], [cache[src][1], cache[trg][1]], [SPACE, SPACE], color='blue') def _get_size(n_items): """ Calculate the size of the subplot layouts based on number of items. """ n_cols = math.ceil(math.sqrt(n_items)) n_rows = math.floor(math.sqrt(n_items)) if n_cols * n_rows < n_items: n_cols += 1 return int(n_rows), int(n_cols) <|fim▁end|>
""" Plot a single candidate graph. """ pos = nx.nx_agraph.graphviz_layout(graph, prog=prog) # draw the nodes for node, values in graph.nodes(data=True): shape = 'o' if values[stitcher.TYPE_ATTR] in type_format: shape = type_format[values[stitcher.TYPE_ATTR]] color = 'g' alpha = 0.8 if node in new_nodes: color = 'b' alpha = 0.2 elif 'rank' in values and values['rank'] > 7: color = 'r' elif 'rank' in values and values['rank'] < 7 and values['rank'] > 3: color = 'y' nx.draw_networkx_nodes(graph, pos, nodelist=[node], node_color=color, node_shape=shape, alpha=alpha, ax=axes) # draw the edges dotted_line = [] normal_line = [] for src, trg in graph.edges(): if src in new_nodes and trg not in new_nodes: dotted_line.append((src, trg)) else: normal_line.append((src, trg)) nx.draw_networkx_edges(graph, pos, edgelist=dotted_line, style='dotted', ax=axes) nx.draw_networkx_edges(graph, pos, edgelist=normal_line, ax=axes) # draw labels nx.draw_networkx_labels(graph, pos, ax=axes)
<|file_name|>vis.py<|end_file_name|><|fim▁begin|> """ Visualize possible stitches with the outcome of the validator. """ import math import random import matplotlib.pyplot as plt import networkx as nx import numpy as np from mpl_toolkits.mplot3d import Axes3D import stitcher SPACE = 25 TYPE_FORMAT = {'a': '^', 'b': 's', 'c': 'v'} def show(graphs, request, titles, prog='neato', size=None, type_format=None, filename=None): """ Display the results using matplotlib. """ if not size: size = _get_size(len(graphs)) fig, axarr = plt.subplots(size[0], size[1], figsize=(18, 10)) fig.set_facecolor('white') x_val = 0 y_val = 0 index = 0 if size[0] == 1: axarr = np.array(axarr).reshape((1, size[1])) for candidate in graphs: # axarr[x_val, y_val].axis('off') axarr[x_val, y_val].xaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].yaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].xaxis.set_ticks([]) axarr[x_val, y_val].yaxis.set_ticks([]) axarr[x_val, y_val].set_title(titles[index]) # axarr[x_val, y_val].set_axis_bgcolor("white") if not type_format: type_format = TYPE_FORMAT _plot_subplot(candidate, request.nodes(), prog, type_format, axarr[x_val, y_val]) y_val += 1 if y_val > size[1] - 1: y_val = 0 x_val += 1 index += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close() def _plot_subplot(graph, new_nodes, prog, type_format, axes): """ Plot a single candidate graph. """ pos = nx.nx_agraph.graphviz_layout(graph, prog=prog) # draw the nodes for node, values in graph.nodes(data=True): shape = 'o' if values[stitcher.TYPE_ATTR] in type_format: shape = type_format[values[stitcher.TYPE_ATTR]] color = 'g' alpha = 0.8 if node in new_nodes: color = 'b' alpha = 0.2 elif 'rank' in values and values['rank'] > 7: color = 'r' elif 'rank' in values and values['rank'] < 7 and values['rank'] > 3: color = 'y' nx.draw_networkx_nodes(graph, pos, nodelist=[node], node_color=color, node_shape=shape, alpha=alpha, ax=axes) # draw the edges dotted_line = [] normal_line = [] for src, trg in graph.edges(): if src in new_nodes and trg not in new_nodes: dotted_line.append((src, trg)) else: normal_line.append((src, trg)) nx.draw_networkx_edges(graph, pos, edgelist=dotted_line, style='dotted', ax=axes) nx.draw_networkx_edges(graph, pos, edgelist=normal_line, ax=axes) # draw labels nx.draw_networkx_labels(graph, pos, ax=axes) def show_3d(graphs, request, titles, prog='neato', filename=None): <|fim_middle|> def _plot_3d_subplot(graph, request, prog, axes): """ Plot a single candidate graph in 3d. """ cache = {} tmp = graph.copy() for node in request.nodes(): tmp.remove_node(node) pos = nx.nx_agraph.graphviz_layout(tmp, prog=prog) # the container for item in tmp.nodes(): axes.plot([pos[item][0]], [pos[item][1]], [0], linestyle="None", marker="o", color='gray') axes.text(pos[item][0], pos[item][1], 0, item) for src, trg in tmp.edges(): axes.plot([pos[src][0], pos[trg][0]], [pos[src][1], pos[trg][1]], [0, 0], color='gray') # the new nodes for item in graph.nodes(): if item in request.nodes(): for nghb in graph.neighbors(item): if nghb in tmp.nodes(): x_val = pos[nghb][0] y_val = pos[nghb][1] if (x_val, y_val) in list(cache.values()): x_val = pos[nghb][0] + random.randint(10, SPACE) y_val = pos[nghb][0] + random.randint(10, SPACE) cache[item] = (x_val, y_val) # edge axes.plot([x_val, pos[nghb][0]], [y_val, pos[nghb][1]], [SPACE, 0], color='blue') axes.plot([x_val], [y_val], [SPACE], linestyle="None", marker="o", color='blue') axes.text(x_val, y_val, SPACE, item) for src, trg in request.edges(): if trg in cache and src in cache: axes.plot([cache[src][0], cache[trg][0]], [cache[src][1], cache[trg][1]], [SPACE, SPACE], color='blue') def _get_size(n_items): """ Calculate the size of the subplot layouts based on number of items. """ n_cols = math.ceil(math.sqrt(n_items)) n_rows = math.floor(math.sqrt(n_items)) if n_cols * n_rows < n_items: n_cols += 1 return int(n_rows), int(n_cols) <|fim▁end|>
""" Show the candidates in 3d - the request elevated above the container. """ fig = plt.figure(figsize=(18, 10)) fig.set_facecolor('white') i = 0 size = _get_size(len(graphs)) for graph in graphs: axes = fig.add_subplot(size[0], size[1], i+1, projection=Axes3D.name) axes.set_title(titles[i]) axes._axis3don = False _plot_3d_subplot(graph, request, prog, axes) i += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close()
<|file_name|>vis.py<|end_file_name|><|fim▁begin|> """ Visualize possible stitches with the outcome of the validator. """ import math import random import matplotlib.pyplot as plt import networkx as nx import numpy as np from mpl_toolkits.mplot3d import Axes3D import stitcher SPACE = 25 TYPE_FORMAT = {'a': '^', 'b': 's', 'c': 'v'} def show(graphs, request, titles, prog='neato', size=None, type_format=None, filename=None): """ Display the results using matplotlib. """ if not size: size = _get_size(len(graphs)) fig, axarr = plt.subplots(size[0], size[1], figsize=(18, 10)) fig.set_facecolor('white') x_val = 0 y_val = 0 index = 0 if size[0] == 1: axarr = np.array(axarr).reshape((1, size[1])) for candidate in graphs: # axarr[x_val, y_val].axis('off') axarr[x_val, y_val].xaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].yaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].xaxis.set_ticks([]) axarr[x_val, y_val].yaxis.set_ticks([]) axarr[x_val, y_val].set_title(titles[index]) # axarr[x_val, y_val].set_axis_bgcolor("white") if not type_format: type_format = TYPE_FORMAT _plot_subplot(candidate, request.nodes(), prog, type_format, axarr[x_val, y_val]) y_val += 1 if y_val > size[1] - 1: y_val = 0 x_val += 1 index += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close() def _plot_subplot(graph, new_nodes, prog, type_format, axes): """ Plot a single candidate graph. """ pos = nx.nx_agraph.graphviz_layout(graph, prog=prog) # draw the nodes for node, values in graph.nodes(data=True): shape = 'o' if values[stitcher.TYPE_ATTR] in type_format: shape = type_format[values[stitcher.TYPE_ATTR]] color = 'g' alpha = 0.8 if node in new_nodes: color = 'b' alpha = 0.2 elif 'rank' in values and values['rank'] > 7: color = 'r' elif 'rank' in values and values['rank'] < 7 and values['rank'] > 3: color = 'y' nx.draw_networkx_nodes(graph, pos, nodelist=[node], node_color=color, node_shape=shape, alpha=alpha, ax=axes) # draw the edges dotted_line = [] normal_line = [] for src, trg in graph.edges(): if src in new_nodes and trg not in new_nodes: dotted_line.append((src, trg)) else: normal_line.append((src, trg)) nx.draw_networkx_edges(graph, pos, edgelist=dotted_line, style='dotted', ax=axes) nx.draw_networkx_edges(graph, pos, edgelist=normal_line, ax=axes) # draw labels nx.draw_networkx_labels(graph, pos, ax=axes) def show_3d(graphs, request, titles, prog='neato', filename=None): """ Show the candidates in 3d - the request elevated above the container. """ fig = plt.figure(figsize=(18, 10)) fig.set_facecolor('white') i = 0 size = _get_size(len(graphs)) for graph in graphs: axes = fig.add_subplot(size[0], size[1], i+1, projection=Axes3D.name) axes.set_title(titles[i]) axes._axis3don = False _plot_3d_subplot(graph, request, prog, axes) i += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close() def _plot_3d_subplot(graph, request, prog, axes): <|fim_middle|> def _get_size(n_items): """ Calculate the size of the subplot layouts based on number of items. """ n_cols = math.ceil(math.sqrt(n_items)) n_rows = math.floor(math.sqrt(n_items)) if n_cols * n_rows < n_items: n_cols += 1 return int(n_rows), int(n_cols) <|fim▁end|>
""" Plot a single candidate graph in 3d. """ cache = {} tmp = graph.copy() for node in request.nodes(): tmp.remove_node(node) pos = nx.nx_agraph.graphviz_layout(tmp, prog=prog) # the container for item in tmp.nodes(): axes.plot([pos[item][0]], [pos[item][1]], [0], linestyle="None", marker="o", color='gray') axes.text(pos[item][0], pos[item][1], 0, item) for src, trg in tmp.edges(): axes.plot([pos[src][0], pos[trg][0]], [pos[src][1], pos[trg][1]], [0, 0], color='gray') # the new nodes for item in graph.nodes(): if item in request.nodes(): for nghb in graph.neighbors(item): if nghb in tmp.nodes(): x_val = pos[nghb][0] y_val = pos[nghb][1] if (x_val, y_val) in list(cache.values()): x_val = pos[nghb][0] + random.randint(10, SPACE) y_val = pos[nghb][0] + random.randint(10, SPACE) cache[item] = (x_val, y_val) # edge axes.plot([x_val, pos[nghb][0]], [y_val, pos[nghb][1]], [SPACE, 0], color='blue') axes.plot([x_val], [y_val], [SPACE], linestyle="None", marker="o", color='blue') axes.text(x_val, y_val, SPACE, item) for src, trg in request.edges(): if trg in cache and src in cache: axes.plot([cache[src][0], cache[trg][0]], [cache[src][1], cache[trg][1]], [SPACE, SPACE], color='blue')
<|file_name|>vis.py<|end_file_name|><|fim▁begin|> """ Visualize possible stitches with the outcome of the validator. """ import math import random import matplotlib.pyplot as plt import networkx as nx import numpy as np from mpl_toolkits.mplot3d import Axes3D import stitcher SPACE = 25 TYPE_FORMAT = {'a': '^', 'b': 's', 'c': 'v'} def show(graphs, request, titles, prog='neato', size=None, type_format=None, filename=None): """ Display the results using matplotlib. """ if not size: size = _get_size(len(graphs)) fig, axarr = plt.subplots(size[0], size[1], figsize=(18, 10)) fig.set_facecolor('white') x_val = 0 y_val = 0 index = 0 if size[0] == 1: axarr = np.array(axarr).reshape((1, size[1])) for candidate in graphs: # axarr[x_val, y_val].axis('off') axarr[x_val, y_val].xaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].yaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].xaxis.set_ticks([]) axarr[x_val, y_val].yaxis.set_ticks([]) axarr[x_val, y_val].set_title(titles[index]) # axarr[x_val, y_val].set_axis_bgcolor("white") if not type_format: type_format = TYPE_FORMAT _plot_subplot(candidate, request.nodes(), prog, type_format, axarr[x_val, y_val]) y_val += 1 if y_val > size[1] - 1: y_val = 0 x_val += 1 index += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close() def _plot_subplot(graph, new_nodes, prog, type_format, axes): """ Plot a single candidate graph. """ pos = nx.nx_agraph.graphviz_layout(graph, prog=prog) # draw the nodes for node, values in graph.nodes(data=True): shape = 'o' if values[stitcher.TYPE_ATTR] in type_format: shape = type_format[values[stitcher.TYPE_ATTR]] color = 'g' alpha = 0.8 if node in new_nodes: color = 'b' alpha = 0.2 elif 'rank' in values and values['rank'] > 7: color = 'r' elif 'rank' in values and values['rank'] < 7 and values['rank'] > 3: color = 'y' nx.draw_networkx_nodes(graph, pos, nodelist=[node], node_color=color, node_shape=shape, alpha=alpha, ax=axes) # draw the edges dotted_line = [] normal_line = [] for src, trg in graph.edges(): if src in new_nodes and trg not in new_nodes: dotted_line.append((src, trg)) else: normal_line.append((src, trg)) nx.draw_networkx_edges(graph, pos, edgelist=dotted_line, style='dotted', ax=axes) nx.draw_networkx_edges(graph, pos, edgelist=normal_line, ax=axes) # draw labels nx.draw_networkx_labels(graph, pos, ax=axes) def show_3d(graphs, request, titles, prog='neato', filename=None): """ Show the candidates in 3d - the request elevated above the container. """ fig = plt.figure(figsize=(18, 10)) fig.set_facecolor('white') i = 0 size = _get_size(len(graphs)) for graph in graphs: axes = fig.add_subplot(size[0], size[1], i+1, projection=Axes3D.name) axes.set_title(titles[i]) axes._axis3don = False _plot_3d_subplot(graph, request, prog, axes) i += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close() def _plot_3d_subplot(graph, request, prog, axes): """ Plot a single candidate graph in 3d. """ cache = {} tmp = graph.copy() for node in request.nodes(): tmp.remove_node(node) pos = nx.nx_agraph.graphviz_layout(tmp, prog=prog) # the container for item in tmp.nodes(): axes.plot([pos[item][0]], [pos[item][1]], [0], linestyle="None", marker="o", color='gray') axes.text(pos[item][0], pos[item][1], 0, item) for src, trg in tmp.edges(): axes.plot([pos[src][0], pos[trg][0]], [pos[src][1], pos[trg][1]], [0, 0], color='gray') # the new nodes for item in graph.nodes(): if item in request.nodes(): for nghb in graph.neighbors(item): if nghb in tmp.nodes(): x_val = pos[nghb][0] y_val = pos[nghb][1] if (x_val, y_val) in list(cache.values()): x_val = pos[nghb][0] + random.randint(10, SPACE) y_val = pos[nghb][0] + random.randint(10, SPACE) cache[item] = (x_val, y_val) # edge axes.plot([x_val, pos[nghb][0]], [y_val, pos[nghb][1]], [SPACE, 0], color='blue') axes.plot([x_val], [y_val], [SPACE], linestyle="None", marker="o", color='blue') axes.text(x_val, y_val, SPACE, item) for src, trg in request.edges(): if trg in cache and src in cache: axes.plot([cache[src][0], cache[trg][0]], [cache[src][1], cache[trg][1]], [SPACE, SPACE], color='blue') def _get_size(n_items): <|fim_middle|> <|fim▁end|>
""" Calculate the size of the subplot layouts based on number of items. """ n_cols = math.ceil(math.sqrt(n_items)) n_rows = math.floor(math.sqrt(n_items)) if n_cols * n_rows < n_items: n_cols += 1 return int(n_rows), int(n_cols)
<|file_name|>vis.py<|end_file_name|><|fim▁begin|> """ Visualize possible stitches with the outcome of the validator. """ import math import random import matplotlib.pyplot as plt import networkx as nx import numpy as np from mpl_toolkits.mplot3d import Axes3D import stitcher SPACE = 25 TYPE_FORMAT = {'a': '^', 'b': 's', 'c': 'v'} def show(graphs, request, titles, prog='neato', size=None, type_format=None, filename=None): """ Display the results using matplotlib. """ if not size: <|fim_middle|> fig, axarr = plt.subplots(size[0], size[1], figsize=(18, 10)) fig.set_facecolor('white') x_val = 0 y_val = 0 index = 0 if size[0] == 1: axarr = np.array(axarr).reshape((1, size[1])) for candidate in graphs: # axarr[x_val, y_val].axis('off') axarr[x_val, y_val].xaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].yaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].xaxis.set_ticks([]) axarr[x_val, y_val].yaxis.set_ticks([]) axarr[x_val, y_val].set_title(titles[index]) # axarr[x_val, y_val].set_axis_bgcolor("white") if not type_format: type_format = TYPE_FORMAT _plot_subplot(candidate, request.nodes(), prog, type_format, axarr[x_val, y_val]) y_val += 1 if y_val > size[1] - 1: y_val = 0 x_val += 1 index += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close() def _plot_subplot(graph, new_nodes, prog, type_format, axes): """ Plot a single candidate graph. """ pos = nx.nx_agraph.graphviz_layout(graph, prog=prog) # draw the nodes for node, values in graph.nodes(data=True): shape = 'o' if values[stitcher.TYPE_ATTR] in type_format: shape = type_format[values[stitcher.TYPE_ATTR]] color = 'g' alpha = 0.8 if node in new_nodes: color = 'b' alpha = 0.2 elif 'rank' in values and values['rank'] > 7: color = 'r' elif 'rank' in values and values['rank'] < 7 and values['rank'] > 3: color = 'y' nx.draw_networkx_nodes(graph, pos, nodelist=[node], node_color=color, node_shape=shape, alpha=alpha, ax=axes) # draw the edges dotted_line = [] normal_line = [] for src, trg in graph.edges(): if src in new_nodes and trg not in new_nodes: dotted_line.append((src, trg)) else: normal_line.append((src, trg)) nx.draw_networkx_edges(graph, pos, edgelist=dotted_line, style='dotted', ax=axes) nx.draw_networkx_edges(graph, pos, edgelist=normal_line, ax=axes) # draw labels nx.draw_networkx_labels(graph, pos, ax=axes) def show_3d(graphs, request, titles, prog='neato', filename=None): """ Show the candidates in 3d - the request elevated above the container. """ fig = plt.figure(figsize=(18, 10)) fig.set_facecolor('white') i = 0 size = _get_size(len(graphs)) for graph in graphs: axes = fig.add_subplot(size[0], size[1], i+1, projection=Axes3D.name) axes.set_title(titles[i]) axes._axis3don = False _plot_3d_subplot(graph, request, prog, axes) i += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close() def _plot_3d_subplot(graph, request, prog, axes): """ Plot a single candidate graph in 3d. """ cache = {} tmp = graph.copy() for node in request.nodes(): tmp.remove_node(node) pos = nx.nx_agraph.graphviz_layout(tmp, prog=prog) # the container for item in tmp.nodes(): axes.plot([pos[item][0]], [pos[item][1]], [0], linestyle="None", marker="o", color='gray') axes.text(pos[item][0], pos[item][1], 0, item) for src, trg in tmp.edges(): axes.plot([pos[src][0], pos[trg][0]], [pos[src][1], pos[trg][1]], [0, 0], color='gray') # the new nodes for item in graph.nodes(): if item in request.nodes(): for nghb in graph.neighbors(item): if nghb in tmp.nodes(): x_val = pos[nghb][0] y_val = pos[nghb][1] if (x_val, y_val) in list(cache.values()): x_val = pos[nghb][0] + random.randint(10, SPACE) y_val = pos[nghb][0] + random.randint(10, SPACE) cache[item] = (x_val, y_val) # edge axes.plot([x_val, pos[nghb][0]], [y_val, pos[nghb][1]], [SPACE, 0], color='blue') axes.plot([x_val], [y_val], [SPACE], linestyle="None", marker="o", color='blue') axes.text(x_val, y_val, SPACE, item) for src, trg in request.edges(): if trg in cache and src in cache: axes.plot([cache[src][0], cache[trg][0]], [cache[src][1], cache[trg][1]], [SPACE, SPACE], color='blue') def _get_size(n_items): """ Calculate the size of the subplot layouts based on number of items. """ n_cols = math.ceil(math.sqrt(n_items)) n_rows = math.floor(math.sqrt(n_items)) if n_cols * n_rows < n_items: n_cols += 1 return int(n_rows), int(n_cols) <|fim▁end|>
size = _get_size(len(graphs))
<|file_name|>vis.py<|end_file_name|><|fim▁begin|> """ Visualize possible stitches with the outcome of the validator. """ import math import random import matplotlib.pyplot as plt import networkx as nx import numpy as np from mpl_toolkits.mplot3d import Axes3D import stitcher SPACE = 25 TYPE_FORMAT = {'a': '^', 'b': 's', 'c': 'v'} def show(graphs, request, titles, prog='neato', size=None, type_format=None, filename=None): """ Display the results using matplotlib. """ if not size: size = _get_size(len(graphs)) fig, axarr = plt.subplots(size[0], size[1], figsize=(18, 10)) fig.set_facecolor('white') x_val = 0 y_val = 0 index = 0 if size[0] == 1: <|fim_middle|> for candidate in graphs: # axarr[x_val, y_val].axis('off') axarr[x_val, y_val].xaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].yaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].xaxis.set_ticks([]) axarr[x_val, y_val].yaxis.set_ticks([]) axarr[x_val, y_val].set_title(titles[index]) # axarr[x_val, y_val].set_axis_bgcolor("white") if not type_format: type_format = TYPE_FORMAT _plot_subplot(candidate, request.nodes(), prog, type_format, axarr[x_val, y_val]) y_val += 1 if y_val > size[1] - 1: y_val = 0 x_val += 1 index += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close() def _plot_subplot(graph, new_nodes, prog, type_format, axes): """ Plot a single candidate graph. """ pos = nx.nx_agraph.graphviz_layout(graph, prog=prog) # draw the nodes for node, values in graph.nodes(data=True): shape = 'o' if values[stitcher.TYPE_ATTR] in type_format: shape = type_format[values[stitcher.TYPE_ATTR]] color = 'g' alpha = 0.8 if node in new_nodes: color = 'b' alpha = 0.2 elif 'rank' in values and values['rank'] > 7: color = 'r' elif 'rank' in values and values['rank'] < 7 and values['rank'] > 3: color = 'y' nx.draw_networkx_nodes(graph, pos, nodelist=[node], node_color=color, node_shape=shape, alpha=alpha, ax=axes) # draw the edges dotted_line = [] normal_line = [] for src, trg in graph.edges(): if src in new_nodes and trg not in new_nodes: dotted_line.append((src, trg)) else: normal_line.append((src, trg)) nx.draw_networkx_edges(graph, pos, edgelist=dotted_line, style='dotted', ax=axes) nx.draw_networkx_edges(graph, pos, edgelist=normal_line, ax=axes) # draw labels nx.draw_networkx_labels(graph, pos, ax=axes) def show_3d(graphs, request, titles, prog='neato', filename=None): """ Show the candidates in 3d - the request elevated above the container. """ fig = plt.figure(figsize=(18, 10)) fig.set_facecolor('white') i = 0 size = _get_size(len(graphs)) for graph in graphs: axes = fig.add_subplot(size[0], size[1], i+1, projection=Axes3D.name) axes.set_title(titles[i]) axes._axis3don = False _plot_3d_subplot(graph, request, prog, axes) i += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close() def _plot_3d_subplot(graph, request, prog, axes): """ Plot a single candidate graph in 3d. """ cache = {} tmp = graph.copy() for node in request.nodes(): tmp.remove_node(node) pos = nx.nx_agraph.graphviz_layout(tmp, prog=prog) # the container for item in tmp.nodes(): axes.plot([pos[item][0]], [pos[item][1]], [0], linestyle="None", marker="o", color='gray') axes.text(pos[item][0], pos[item][1], 0, item) for src, trg in tmp.edges(): axes.plot([pos[src][0], pos[trg][0]], [pos[src][1], pos[trg][1]], [0, 0], color='gray') # the new nodes for item in graph.nodes(): if item in request.nodes(): for nghb in graph.neighbors(item): if nghb in tmp.nodes(): x_val = pos[nghb][0] y_val = pos[nghb][1] if (x_val, y_val) in list(cache.values()): x_val = pos[nghb][0] + random.randint(10, SPACE) y_val = pos[nghb][0] + random.randint(10, SPACE) cache[item] = (x_val, y_val) # edge axes.plot([x_val, pos[nghb][0]], [y_val, pos[nghb][1]], [SPACE, 0], color='blue') axes.plot([x_val], [y_val], [SPACE], linestyle="None", marker="o", color='blue') axes.text(x_val, y_val, SPACE, item) for src, trg in request.edges(): if trg in cache and src in cache: axes.plot([cache[src][0], cache[trg][0]], [cache[src][1], cache[trg][1]], [SPACE, SPACE], color='blue') def _get_size(n_items): """ Calculate the size of the subplot layouts based on number of items. """ n_cols = math.ceil(math.sqrt(n_items)) n_rows = math.floor(math.sqrt(n_items)) if n_cols * n_rows < n_items: n_cols += 1 return int(n_rows), int(n_cols) <|fim▁end|>
axarr = np.array(axarr).reshape((1, size[1]))
<|file_name|>vis.py<|end_file_name|><|fim▁begin|> """ Visualize possible stitches with the outcome of the validator. """ import math import random import matplotlib.pyplot as plt import networkx as nx import numpy as np from mpl_toolkits.mplot3d import Axes3D import stitcher SPACE = 25 TYPE_FORMAT = {'a': '^', 'b': 's', 'c': 'v'} def show(graphs, request, titles, prog='neato', size=None, type_format=None, filename=None): """ Display the results using matplotlib. """ if not size: size = _get_size(len(graphs)) fig, axarr = plt.subplots(size[0], size[1], figsize=(18, 10)) fig.set_facecolor('white') x_val = 0 y_val = 0 index = 0 if size[0] == 1: axarr = np.array(axarr).reshape((1, size[1])) for candidate in graphs: # axarr[x_val, y_val].axis('off') axarr[x_val, y_val].xaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].yaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].xaxis.set_ticks([]) axarr[x_val, y_val].yaxis.set_ticks([]) axarr[x_val, y_val].set_title(titles[index]) # axarr[x_val, y_val].set_axis_bgcolor("white") if not type_format: <|fim_middle|> _plot_subplot(candidate, request.nodes(), prog, type_format, axarr[x_val, y_val]) y_val += 1 if y_val > size[1] - 1: y_val = 0 x_val += 1 index += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close() def _plot_subplot(graph, new_nodes, prog, type_format, axes): """ Plot a single candidate graph. """ pos = nx.nx_agraph.graphviz_layout(graph, prog=prog) # draw the nodes for node, values in graph.nodes(data=True): shape = 'o' if values[stitcher.TYPE_ATTR] in type_format: shape = type_format[values[stitcher.TYPE_ATTR]] color = 'g' alpha = 0.8 if node in new_nodes: color = 'b' alpha = 0.2 elif 'rank' in values and values['rank'] > 7: color = 'r' elif 'rank' in values and values['rank'] < 7 and values['rank'] > 3: color = 'y' nx.draw_networkx_nodes(graph, pos, nodelist=[node], node_color=color, node_shape=shape, alpha=alpha, ax=axes) # draw the edges dotted_line = [] normal_line = [] for src, trg in graph.edges(): if src in new_nodes and trg not in new_nodes: dotted_line.append((src, trg)) else: normal_line.append((src, trg)) nx.draw_networkx_edges(graph, pos, edgelist=dotted_line, style='dotted', ax=axes) nx.draw_networkx_edges(graph, pos, edgelist=normal_line, ax=axes) # draw labels nx.draw_networkx_labels(graph, pos, ax=axes) def show_3d(graphs, request, titles, prog='neato', filename=None): """ Show the candidates in 3d - the request elevated above the container. """ fig = plt.figure(figsize=(18, 10)) fig.set_facecolor('white') i = 0 size = _get_size(len(graphs)) for graph in graphs: axes = fig.add_subplot(size[0], size[1], i+1, projection=Axes3D.name) axes.set_title(titles[i]) axes._axis3don = False _plot_3d_subplot(graph, request, prog, axes) i += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close() def _plot_3d_subplot(graph, request, prog, axes): """ Plot a single candidate graph in 3d. """ cache = {} tmp = graph.copy() for node in request.nodes(): tmp.remove_node(node) pos = nx.nx_agraph.graphviz_layout(tmp, prog=prog) # the container for item in tmp.nodes(): axes.plot([pos[item][0]], [pos[item][1]], [0], linestyle="None", marker="o", color='gray') axes.text(pos[item][0], pos[item][1], 0, item) for src, trg in tmp.edges(): axes.plot([pos[src][0], pos[trg][0]], [pos[src][1], pos[trg][1]], [0, 0], color='gray') # the new nodes for item in graph.nodes(): if item in request.nodes(): for nghb in graph.neighbors(item): if nghb in tmp.nodes(): x_val = pos[nghb][0] y_val = pos[nghb][1] if (x_val, y_val) in list(cache.values()): x_val = pos[nghb][0] + random.randint(10, SPACE) y_val = pos[nghb][0] + random.randint(10, SPACE) cache[item] = (x_val, y_val) # edge axes.plot([x_val, pos[nghb][0]], [y_val, pos[nghb][1]], [SPACE, 0], color='blue') axes.plot([x_val], [y_val], [SPACE], linestyle="None", marker="o", color='blue') axes.text(x_val, y_val, SPACE, item) for src, trg in request.edges(): if trg in cache and src in cache: axes.plot([cache[src][0], cache[trg][0]], [cache[src][1], cache[trg][1]], [SPACE, SPACE], color='blue') def _get_size(n_items): """ Calculate the size of the subplot layouts based on number of items. """ n_cols = math.ceil(math.sqrt(n_items)) n_rows = math.floor(math.sqrt(n_items)) if n_cols * n_rows < n_items: n_cols += 1 return int(n_rows), int(n_cols) <|fim▁end|>
type_format = TYPE_FORMAT