text stringlengths 4 1.02M | meta dict |
|---|---|
from __future__ import print_function
import sys
import os
if sys.version_info > (2, 7, 0):
import unittest
else:
import unittest2 as unittest
from mock import Mock
from tempfile import NamedTemporaryFile
sys.path.append(os.path.join(os.path.dirname(__file__), '../bin'))
import qds
import qds_sdk
from qds_sdk.connection import Connection
from test_base import print_command
from test_base import QdsCliTestCase
class TestCommandCheck(QdsCliTestCase):
def test_hivecmd(self):
sys.argv = ['qds.py', 'hivecmd', 'check', '123']
print_command()
Connection._api_call = Mock(return_value={})
qds.main()
Connection._api_call.assert_called_with("GET", "commands/123", params=None)
def test_sparkcmd(self):
sys.argv = ['qds.py', 'sparkcmd', 'check', '123']
print_command()
Connection._api_call = Mock(return_value={})
qds.main()
Connection._api_call.assert_called_with("GET", "commands/123", params=None)
def test_hadoopcmd(self):
sys.argv = ['qds.py', 'hadoopcmd', 'check', '123']
print_command()
Connection._api_call = Mock(return_value={})
qds.main()
Connection._api_call.assert_called_with("GET", "commands/123", params=None)
def test_prestocmd(self):
sys.argv = ['qds.py', 'prestocmd', 'check', '123']
print_command()
Connection._api_call = Mock(return_value={})
qds.main()
Connection._api_call.assert_called_with("GET", "commands/123", params=None)
def test_pigcmd(self):
sys.argv = ['qds.py', 'pigcmd', 'check', '123']
print_command()
Connection._api_call = Mock(return_value={})
qds.main()
Connection._api_call.assert_called_with("GET", "commands/123", params=None)
def test_shellcmd(self):
sys.argv = ['qds.py', 'shellcmd', 'check', '123']
print_command()
Connection._api_call = Mock(return_value={})
qds.main()
Connection._api_call.assert_called_with("GET", "commands/123", params=None)
def test_dbexportcmd(self):
sys.argv = ['qds.py', 'dbexportcmd', 'check', '123']
print_command()
Connection._api_call = Mock(return_value={})
qds.main()
Connection._api_call.assert_called_with("GET", "commands/123", params=None)
def test_dbimportcmd(self):
sys.argv = ['qds.py', 'dbimportcmd', 'check', '123']
print_command()
Connection._api_call = Mock(return_value={})
qds.main()
Connection._api_call.assert_called_with("GET", "commands/123", params=None)
def test_dbtapquerycmd(self):
sys.argv = ['qds.py', 'dbtapquerycmd', 'check', '123']
print_command()
Connection._api_call = Mock(return_value={})
qds.main()
Connection._api_call.assert_called_with("GET", "commands/123", params=None)
class TestCommandCancel(QdsCliTestCase):
def test_hivecmd(self):
sys.argv = ['qds.py', 'hivecmd', 'cancel', '123']
print_command()
Connection._api_call = Mock(return_value={'kill_succeeded': True})
qds.main()
Connection._api_call.assert_called_with("PUT", "commands/123",
{'status': 'kill'})
def test_sparkcmd(self):
sys.argv = ['qds.py', 'sparkcmd', 'cancel', '123']
print_command()
Connection._api_call = Mock(return_value={'kill_succeeded': True})
qds.main()
Connection._api_call.assert_called_with("PUT", "commands/123",
{'status': 'kill'})
def test_hadoopcmd(self):
sys.argv = ['qds.py', 'hadoopcmd', 'cancel', '123']
print_command()
Connection._api_call = Mock(return_value={'kill_succeeded': True})
qds.main()
Connection._api_call.assert_called_with("PUT", "commands/123",
{'status': 'kill'})
def test_prestocmd(self):
sys.argv = ['qds.py', 'prestocmd', 'cancel', '123']
print_command()
Connection._api_call = Mock(return_value={'kill_succeeded': True})
qds.main()
Connection._api_call.assert_called_with("PUT", "commands/123",
{'status': 'kill'})
def test_pigcmd(self):
sys.argv = ['qds.py', 'pigcmd', 'cancel', '123']
print_command()
Connection._api_call = Mock(return_value={'kill_succeeded': True})
qds.main()
Connection._api_call.assert_called_with("PUT", "commands/123",
{'status': 'kill'})
def test_shellcmd(self):
sys.argv = ['qds.py', 'shellcmd', 'cancel', '123']
print_command()
Connection._api_call = Mock(return_value={'kill_succeeded': True})
qds.main()
Connection._api_call.assert_called_with("PUT", "commands/123",
{'status': 'kill'})
def test_dbexportcmd(self):
sys.argv = ['qds.py', 'dbexportcmd', 'cancel', '123']
print_command()
Connection._api_call = Mock(return_value={'kill_succeeded': True})
qds.main()
Connection._api_call.assert_called_with("PUT", "commands/123",
{'status': 'kill'})
def test_dbimportcmd(self):
sys.argv = ['qds.py', 'dbimportcmd', 'cancel', '123']
print_command()
Connection._api_call = Mock(return_value={'kill_succeeded': True})
qds.main()
Connection._api_call.assert_called_with("PUT", "commands/123",
{'status': 'kill'})
def test_dbtapquerycmd(self):
sys.argv = ['qds.py', 'dbtapquerycmd', 'cancel', '123']
print_command()
Connection._api_call = Mock(return_value={'kill_succeeded': True})
qds.main()
Connection._api_call.assert_called_with("PUT", "commands/123",
{'status': 'kill'})
class TestCommandGetJobs(QdsCliTestCase):
def test_running(self):
sys.argv = ['qds.py', 'hivecmd', 'getjobs', '123']
print_command()
Connection._api_call = Mock(return_value={'id':123, 'status': 'running'})
Connection._api_call_raw = Mock()
qds.main()
Connection._api_call.assert_called_with('GET', 'commands/123', params=None),
assert not Connection._api_call_raw.called
def test_done(self):
sys.argv = ['qds.py', 'hivecmd', 'getjobs', '123']
print_command()
Connection._api_call = Mock(return_value={'id':123, 'status': "done"})
jobs_response = Mock(text='[{"url":"https://blah","job_stats":{},"job_id":"job_blah"}]')
Connection._api_call_raw = Mock(return_value=jobs_response)
qds.main()
Connection._api_call.assert_called_with('GET', 'commands/123', params=None),
Connection._api_call_raw.assert_called_with('GET', 'commands/123/jobs', params=None),
class TestHiveCommand(QdsCliTestCase):
def test_submit_query(self):
sys.argv = ['qds.py', 'hivecmd', 'submit', '--query', 'show tables']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'tags': None,
'sample_size': None,
'name': None,
'query': 'show tables',
'command_type': 'HiveCommand',
'can_notify': False,
'script_location': None})
def test_submit_script_location(self):
sys.argv = ['qds.py', 'hivecmd', 'submit', '--script_location', 's3://bucket/path-to-script']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'tags': None,
'sample_size': None,
'name': None,
'query': None,
'command_type': 'HiveCommand',
'can_notify': False,
'script_location': 's3://bucket/path-to-script'})
def test_submit_none(self):
sys.argv = ['qds.py', 'hivecmd', 'submit']
print_command()
with self.assertRaises(qds_sdk.exception.ParseError):
qds.main()
def test_submit_both(self):
sys.argv = ['qds.py', 'hivecmd', 'submit', '--query', 'show tables',
'--script_location', 's3://bucket/path-to-script']
print_command()
with self.assertRaises(qds_sdk.exception.ParseError):
qds.main()
def test_submit_macros(self):
sys.argv = ['qds.py', 'hivecmd', 'submit', '--script_location', 's3://bucket/path-to-script',
'--macros', '[{"key1":"11","key2":"22"}, {"key3":"key1+key2"}]']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': [{"key1":"11","key2":"22"}, {"key3":"key1+key2"}],
'label': None,
'tags': None,
'sample_size': None,
'name': None,
'query': None,
'command_type': 'HiveCommand',
'can_notify': False,
'script_location': 's3://bucket/path-to-script'})
def test_submit_tags(self):
sys.argv = ['qds.py', 'hivecmd', 'submit', '--script_location', 's3://bucket/path-to-script',
'--tags', 'abc,def']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'tags': ["abc", "def"],
'sample_size': None,
'name': None,
'query': None,
'command_type': 'HiveCommand',
'can_notify': False,
'script_location': 's3://bucket/path-to-script'})
def test_submit_cluster_label(self):
sys.argv = ['qds.py', 'hivecmd', 'submit', '--query', 'show tables',
'--cluster-label', 'test_label']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': 'test_label',
'tags': None,
'sample_size': None,
'name': None,
'query': 'show tables',
'command_type': 'HiveCommand',
'can_notify': False,
'script_location': None})
def test_submit_name(self):
sys.argv = ['qds.py', 'hivecmd', 'submit', '--query', 'show tables',
'--name', 'test_name']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'tags': None,
'sample_size': None,
'name': 'test_name',
'query': 'show tables',
'command_type': 'HiveCommand',
'can_notify': False,
'script_location': None})
def test_submit_notify(self):
sys.argv = ['qds.py', 'hivecmd', 'submit', '--query', 'show tables',
'--notify']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'tags': None,
'sample_size': None,
'name': None,
'query': 'show tables',
'command_type': 'HiveCommand',
'can_notify': True,
'script_location': None})
def test_submit_sample_size(self):
sys.argv = ['qds.py', 'hivecmd', 'submit', '--query', 'show tables',
'--sample_size', '1024']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'tags': None,
'sample_size': '1024',
'name': None,
'query': 'show tables',
'command_type': 'HiveCommand',
'can_notify': False,
'script_location': None})
class TestSparkCommand(QdsCliTestCase):
def test_submit_query(self):
sys.argv = ['qds.py', 'sparkcmd', 'submit', '--cmdline', '/usr/lib/spark/bin/spark-submit --class Test Test.jar']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'language': None,
'tags': None,
'name': None,
'sql': None,
'program': None,
'app_id': None,
'cmdline':'/usr/lib/spark/bin/spark-submit --class Test Test.jar',
'command_type': 'SparkCommand',
'arguments': None,
'user_program_arguments': None,
'can_notify': False,
'script_location': None})
def test_submit_script_location_aws(self):
sys.argv = ['qds.py', 'sparkcmd', 'submit', '--script_location', 's3://bucket/path-to-script']
print_command()
with self.assertRaises(qds_sdk.exception.ParseError):
qds.main()
def test_submit_script_location_local_py(self):
with NamedTemporaryFile(suffix=".py") as tmp:
tmp.write('print "Hello World!"'.encode("utf8"))
tmp.seek(0)
sys.argv = ['qds.py', 'sparkcmd' , 'submit', '--script_location' , tmp.name]
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'language': "python",
'tags': None,
'name': None,
'sql': None,
'program':'print "Hello World!"',
'app_id': None,
'cmdline':None,
'command_type': 'SparkCommand',
'arguments': None,
'user_program_arguments': None,
'can_notify': False,
'script_location': None})
def test_submit_script_location_local_scala(self):
with NamedTemporaryFile(suffix=".scala") as tmp:
tmp.write('println("hello, world!")'.encode("utf8"))
tmp.seek(0)
sys.argv = ['qds.py', 'sparkcmd' , 'submit', '--script_location' , tmp.name]
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'language': "scala",
'tags': None,
'name': None,
'sql': None,
'program': "println(\"hello, world!\")",
'app_id': None,
'cmdline':None,
'command_type': 'SparkCommand',
'arguments': None,
'user_program_arguments': None,
'can_notify': False,
'script_location': None})
def test_submit_script_location_local_java(self):
with NamedTemporaryFile(suffix=".java") as tmp:
tmp.write('println("hello, world!")'.encode("utf8"))
tmp.seek(0)
sys.argv = ['qds.py', 'sparkcmd' , 'submit', '--script_location' , tmp.name]
print_command()
with self.assertRaises(qds_sdk.exception.ParseError):
qds.main()
def test_submit_script_location_local_R(self):
with NamedTemporaryFile(suffix=".R") as tmp:
tmp.write('cat("hello, world!")'.encode("utf8"))
tmp.seek(0)
sys.argv = ['qds.py', 'sparkcmd' , 'submit', '--script_location' , tmp.name]
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'language': "R",
'tags': None,
'name': None,
'sql': None,
'program': "cat(\"hello, world!\")",
'app_id': None,
'cmdline':None,
'command_type': 'SparkCommand',
'arguments': None,
'user_program_arguments': None,
'can_notify': False,
'script_location': None})
def test_submit_script_location_local_sql(self):
with NamedTemporaryFile(suffix=".sql") as tmp:
tmp.write('show tables'.encode("utf8"))
tmp.seek(0)
sys.argv = ['qds.py', 'sparkcmd', 'submit', '--script_location', tmp.name]
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'language': None,
'tags': None,
'name': None,
'sql': "show tables",
'program': None,
'app_id': None,
'cmdline':None,
'command_type': 'SparkCommand',
'arguments': None,
'user_program_arguments': None,
'can_notify': False,
'script_location': None})
def test_submit_sql(self):
sys.argv = ['qds.py', 'sparkcmd', 'submit', '--sql', 'show dummy']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'language': None,
'tags': None,
'name': None,
'sql': 'show dummy',
'program': None,
'app_id': None,
'cmdline':None,
'command_type': 'SparkCommand',
'arguments': None,
'user_program_arguments': None,
'can_notify': False,
'script_location': None})
def test_submit_sql_with_language(self):
sys.argv = ['qds.py', 'sparkcmd', 'submit', '--language','python', '--sql', 'show dummy']
print_command()
with self.assertRaises(qds_sdk.exception.ParseError):
qds.main()
def test_submit_none(self):
sys.argv = ['qds.py', 'sparkcmd', 'submit']
print_command()
with self.assertRaises(qds_sdk.exception.ParseError):
qds.main()
def test_submit_both(self):
sys.argv = ['qds.py', 'sparkcmd', 'submit', '--cmdline', '/usr/lib/spark/bin/spark-submit --class Test Test.jar',
'--script_location', 'home/path-to-script']
print_command()
with self.assertRaises(qds_sdk.exception.ParseError):
qds.main()
def test_submit_all_three(self):
sys.argv = ['qds.py', 'sparkcmd', 'submit', '--cmdline', '/usr/lib/spark/bin/spark-submit --class Test Test.jar',
'--script_location', '/home/path-to-script', 'program', 'println("hello, world!")']
print_command()
with self.assertRaises(qds_sdk.exception.ParseError):
qds.main()
def test_language(self):
sys.argv = ['qds.py', 'sparkcmd', 'submit', '--program', 'println("hello, world!")',
'--language', 'java']
print_command()
with self.assertRaises(qds_sdk.exception.ParseError):
qds.main()
def test_program_no_language(self):
sys.argv = ['qds.py', 'sparkcmd', 'submit', '--program', 'println("hello, world!")']
print_command()
with self.assertRaises(qds_sdk.exception.ParseError):
qds.main()
def test_submit_macros(self):
sys.argv = ['qds.py', 'sparkcmd', 'submit', '--program',"println(\"hello, world!\")" ,'--language', 'scala',
'--macros', '[{"key1":"11","key2":"22"}, {"key3":"key1+key2"}]']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': [{"key1":"11","key2":"22"}, {"key3":"key1+key2"}],
'label': None,
'language': "scala",
'tags': None,
'name': None,
'sql': None,
'arguments': None,
'user_program_arguments': None,
'program': "println(\"hello, world!\")",
'app_id': None,
'command_type': 'SparkCommand',
'cmdline': None,
'can_notify': False,
'script_location': None})
def test_submit_tags(self):
sys.argv = ['qds.py', 'sparkcmd', 'submit', '--language','scala','--program',"println(\"hello, world!\")",
'--tags', 'abc,def']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'language': 'scala',
'tags': ["abc", "def"],
'name': None,
'sql': None,
'program':"println(\"hello, world!\")" ,
'app_id': None,
'command_type': 'SparkCommand',
'arguments': None,
'user_program_arguments': None,
'cmdline': None,
'can_notify': False,
'script_location': None})
def test_submit_cluster_label(self):
sys.argv = ['qds.py', 'sparkcmd', 'submit', '--cmdline', '/usr/lib/spark/bin/spark-submit --class Test Test.jar',
'--cluster-label', 'test_label']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': 'test_label',
'language' : None,
'cmdline': '/usr/lib/spark/bin/spark-submit --class Test Test.jar',
'tags': None,
'name': None,
'sql': None,
'program' : None,
'app_id': None,
'arguments': None,
'user_program_arguments': None,
'command_type': 'SparkCommand',
'can_notify': False,
'script_location': None})
def test_submit_name(self):
sys.argv = ['qds.py', 'sparkcmd', 'submit', '--cmdline', '/usr/lib/spark/bin/spark-submit --class Test Test.jar',
'--name', 'test_name']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'language' : None,
'cmdline' : '/usr/lib/spark/bin/spark-submit --class Test Test.jar',
'tags': None,
'name': 'test_name',
'sql': None,
'arguments': None,
'user_program_arguments': None,
'program': None,
'app_id': None,
'command_type': 'SparkCommand',
'can_notify': False,
'script_location': None})
def test_submit_notify(self):
sys.argv = ['qds.py', 'sparkcmd', 'submit', '--cmdline', '/usr/lib/spark/bin/spark-submit --class Test Test.jar',
'--notify']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'language' : None,
'tags': None,
'name': None,
'sql': None,
'program': None,
'app_id': None,
'cmdline': '/usr/lib/spark/bin/spark-submit --class Test Test.jar',
'command_type': 'SparkCommand',
'arguments': None,
'user_program_arguments': None,
'can_notify': True,
'script_location': None})
def test_submit_python_program(self):
sys.argv = ['qds.py', 'sparkcmd', 'submit', '--language','python','--program', 'print "hello, world!"']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'language' : 'python',
'tags': None,
'name': None,
'sql': None,
'program': "print \"hello, world!\"",
'app_id': None,
'cmdline': None,
'command_type': 'SparkCommand',
'arguments': None,
'user_program_arguments': None,
'can_notify': False,
'script_location': None})
def test_submit_user_program_arguments(self):
sys.argv = ['qds.py', 'sparkcmd', 'submit', '--language','scala','--program',
"object HelloWorld {\n\n def main(args: Array[String]) {\n \n println(\"Hello, \" + args(0))\n \n }\n}\n",
'--arguments', '--class HelloWorld',
'--user_program_arguments', 'world']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'language' : 'scala',
'tags': None,
'name': None,
'sql': None,
'program': "object HelloWorld {\n\n def main(args: Array[String]) {\n \n println(\"Hello, \" + args(0))\n \n }\n}\n" ,
'app_id': None,
'cmdline': None,
'command_type': 'SparkCommand',
'arguments': '--class HelloWorld',
'user_program_arguments': 'world',
'can_notify': False,
'script_location': None})
def test_submit_scala_program(self):
sys.argv = ['qds.py', 'sparkcmd', 'submit', '--language','scala','--program', 'println("hello, world!")']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'language' : 'scala',
'tags': None,
'name': None,
'sql': None,
'program': "println(\"hello, world!\")",
'app_id': None,
'cmdline': None,
'command_type': 'SparkCommand',
'arguments': None,
'user_program_arguments': None,
'can_notify': False,
'script_location': None})
def test_submit_R_program(self):
sys.argv = ['qds.py', 'sparkcmd', 'submit', '--language','R','--program', 'cat("hello, world!")']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'language' : 'R',
'tags': None,
'name': None,
'sql': None,
'program': "cat(\"hello, world!\")",
'app_id': None,
'cmdline': None,
'command_type': 'SparkCommand',
'arguments': None,
'user_program_arguments': None,
'can_notify': False,
'script_location': None})
def test_submit_program_to_app(self):
sys.argv = ['qds.py', 'sparkcmd', 'submit', '--language', 'scala',
'--program', 'sc.version', '--app-id', '1']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'language': 'scala',
'tags': None,
'name': None,
'sql': None,
'program': "sc.version",
'app_id': 1,
'cmdline': None,
'command_type': 'SparkCommand',
'arguments': None,
'user_program_arguments': None,
'can_notify': False,
'script_location': None})
def test_submit_sql_to_app(self):
sys.argv = ['qds.py', 'sparkcmd', 'submit', '--sql', 'show tables',
'--app-id', '1']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'language': None,
'tags': None,
'name': None,
'sql': 'show tables',
'program': None,
'app_id': 1,
'cmdline': None,
'command_type': 'SparkCommand',
'arguments': None,
'user_program_arguments': None,
'can_notify': False,
'script_location': None})
def test_submit_script_location_local_py_to_app(self):
with NamedTemporaryFile(suffix=".py") as tmp:
tmp.write('print "Hello World!"'.encode("utf8"))
tmp.seek(0)
sys.argv = ['qds.py', 'sparkcmd', 'submit',
'--script_location', tmp.name, '--app-id', '1']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'language': "python",
'tags': None,
'name': None,
'sql': None,
'program':'print "Hello World!"',
'app_id': 1,
'cmdline':None,
'command_type': 'SparkCommand',
'arguments': None,
'user_program_arguments': None,
'can_notify': False,
'script_location': None})
def test_submit_cmdline_to_app(self):
sys.argv = ['qds.py', 'sparkcmd', 'submit', '--cmdline',
'/usr/lib/spark/bin/spark-submit --class Test Test.jar',
'--app-id', '1']
print_command()
with self.assertRaises(qds_sdk.exception.ParseError):
qds.main()
class TestPrestoCommand(QdsCliTestCase):
def test_submit_query(self):
sys.argv = ['qds.py', 'prestocmd', 'submit', '--query', 'show tables']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'tags': None,
'label': None,
'name': None,
'query': 'show tables',
'command_type': 'PrestoCommand',
'can_notify': False,
'script_location': None})
def test_submit_script_location(self):
sys.argv = ['qds.py', 'prestocmd', 'submit', '--script_location', 's3://bucket/path-to-script']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': None,
'tags': None,
'name': None,
'query': None,
'command_type': 'PrestoCommand',
'can_notify': False,
'script_location': 's3://bucket/path-to-script'})
def test_submit_none(self):
sys.argv = ['qds.py', 'prestocmd', 'submit']
print_command()
with self.assertRaises(qds_sdk.exception.ParseError):
qds.main()
def test_submit_both(self):
sys.argv = ['qds.py', 'prestocmd', 'submit', '--query', 'show tables',
'--script_location', 's3://bucket/path-to-script']
print_command()
with self.assertRaises(qds_sdk.exception.ParseError):
qds.main()
def test_submit_macros(self):
sys.argv = ['qds.py', 'prestocmd', 'submit', '--script_location', 's3://bucket/path-to-script',
'--macros', '[{"key1":"11","key2":"22"}, {"key3":"key1+key2"}]']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': [{"key1":"11","key2":"22"}, {"key3":"key1+key2"}],
'tags': None,
'label': None,
'name': None,
'query': None,
'command_type': 'PrestoCommand',
'can_notify': False,
'script_location': 's3://bucket/path-to-script'})
def test_submit_tags(self):
sys.argv = ['qds.py', 'prestocmd', 'submit', '--script_location', 's3://bucket/path-to-script',
'--tags', 't1,t2']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'tags': ["t1", "t2"],
'label': None,
'name': None,
'query': None,
'command_type': 'PrestoCommand',
'can_notify': False,
'script_location': 's3://bucket/path-to-script'})
def test_submit_cluster_label(self):
sys.argv = ['qds.py', 'prestocmd', 'submit', '--query', 'show tables',
'--cluster-label', 'test_label']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'label': 'test_label',
'tags': None,
'name': None,
'query': 'show tables',
'command_type': 'PrestoCommand',
'can_notify': False,
'script_location': None})
def test_submit_name(self):
sys.argv = ['qds.py', 'prestocmd', 'submit', '--query', 'show tables',
'--name', 'test_name']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'tags': None,
'label': None,
'name': 'test_name',
'query': 'show tables',
'command_type': 'PrestoCommand',
'can_notify': False,
'script_location': None})
def test_submit_notify(self):
sys.argv = ['qds.py', 'prestocmd', 'submit', '--query', 'show tables',
'--notify']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'tags': None,
'label': None,
'name': None,
'query': 'show tables',
'command_type': 'PrestoCommand',
'can_notify': True,
'script_location': None})
class TestHadoopCommand(QdsCliTestCase):
def test_submit_jar(self):
sys.argv = ['qds.py', 'hadoopcmd', 'submit', 'jar', 's3://bucket/path-to-jar']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'sub_command': 'jar',
'sub_command_args': "'s3://bucket/path-to-jar'",
'name': None,
'label': None,
'tags': None,
'command_type': 'HadoopCommand',
'can_notify': False})
def test_submit_jar_invalid(self):
sys.argv = ['qds.py', 'hadoopcmd', 'submit', 'jar']
print_command()
with self.assertRaises(qds_sdk.exception.ParseError):
qds.main()
def test_submit_s3distcp(self):
sys.argv = ['qds.py', 'hadoopcmd', 'submit', 's3distcp', '--src', 'source', '--dest', 'destincation']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'sub_command': 's3distcp',
'sub_command_args': "'--src' 'source' '--dest' 'destincation'",
'name': None,
'label': None,
'tags': None,
'command_type': 'HadoopCommand',
'can_notify': False})
def test_submit_s3distcp_invalid(self):
sys.argv = ['qds.py', 'hadoopcmd', 'submit', 's3distcp']
print_command()
with self.assertRaises(qds_sdk.exception.ParseError):
qds.main()
def test_submit_streaming(self):
sys.argv = ['qds.py', 'hadoopcmd', 'submit', 'streaming',
'-files', 's3n://location-of-mapper.py,s3n://location-of-reducer.py',
'-input', 'myInputDirs',
'-output', 'myOutputDir',
'-mapper', 'mapper.py',
'-reducer', 'reducer.py']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'sub_command': 'streaming',
'sub_command_args': "'-files' 's3n://location-of-mapper.py,s3n://location-of-reducer.py' '-input' 'myInputDirs' '-output' 'myOutputDir' '-mapper' 'mapper.py' '-reducer' 'reducer.py'",
'name': None,
'label': None,
'tags': None,
'command_type': 'HadoopCommand',
'can_notify': False})
def test_submit_streaming_invalid(self):
sys.argv = ['qds.py', 'hadoopcmd', 'submit', 'streaming']
print_command()
with self.assertRaises(qds_sdk.exception.ParseError):
qds.main()
def test_submit_jar_cluster_label(self):
sys.argv = ['qds.py', 'hadoopcmd', 'submit', '--cluster-label', 'test_label', 'jar', 's3://bucket/path-to-jar']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'sub_command': 'jar',
'sub_command_args': "'s3://bucket/path-to-jar'",
'name': None,
'label': 'test_label',
'tags': None,
'command_type': 'HadoopCommand',
'can_notify': False})
def test_submit_jar_name(self):
sys.argv = ['qds.py', 'hadoopcmd', 'submit', '--name', 'test_name', 'jar', 's3://bucket/path-to-jar']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'sub_command': 'jar',
'sub_command_args': "'s3://bucket/path-to-jar'",
'name': 'test_name',
'label': None,
'tags': None,
'command_type': 'HadoopCommand',
'can_notify': False})
def test_submit_jar_notify(self):
sys.argv = ['qds.py', 'hadoopcmd', 'submit', '--notify', 'jar', 's3://bucket/path-to-jar']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'sub_command': 'jar',
'sub_command_args': "'s3://bucket/path-to-jar'",
'name': None,
'label': None,
'tags': None,
'command_type': 'HadoopCommand',
'can_notify': True})
def test_submit_tags(self):
sys.argv = ['qds.py', 'hadoopcmd', 'submit', '--name', 'test_name', '--tags', 'abc,def', 'jar', 's3://bucket/path-to-jar']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'sub_command': 'jar',
'sub_command_args': "'s3://bucket/path-to-jar'",
'name': 'test_name',
'tags': ['abc', 'def'],
'label': None,
'command_type': 'HadoopCommand',
'can_notify': False})
class TestShellCommand(QdsCliTestCase):
def test_stub(self):
pass
class TestPigCommand(QdsCliTestCase):
def test_stub(self):
pass
class TestDbExportCommand(QdsCliTestCase):
def test_submit_command(self):
sys.argv = ['qds.py', 'dbexportcmd', 'submit', '--mode', '1', '--dbtap_id', '1',
'--db_table', 'mydbtable', '--hive_table', 'myhivetable']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'export_dir': None,
'name': None,
'db_update_keys': None,
'partition_spec': None,
'fields_terminated_by': None,
'hive_table': 'myhivetable',
'db_table': 'mydbtable',
'mode': '1',
'tags': None,
'command_type': 'DbExportCommand',
'dbtap_id': '1',
'can_notify': False,
'db_update_mode': None})
def test_submit_fail_with_no_parameters(self):
sys.argv = ['qds.py', 'dbexportcmd', 'submit']
print_command()
with self.assertRaises(qds_sdk.exception.ParseError):
qds.main()
def test_submit_with_notify(self):
sys.argv = ['qds.py', 'dbexportcmd', 'submit', '--mode', '1', '--dbtap_id', '1',
'--db_table', 'mydbtable', '--hive_table', 'myhivetable', '--notify']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'export_dir': None,
'name': None,
'db_update_keys': None,
'partition_spec': None,
'fields_terminated_by': None,
'hive_table': 'myhivetable',
'db_table': 'mydbtable',
'mode': '1',
'tags': None,
'command_type': 'DbExportCommand',
'dbtap_id': '1',
'can_notify': True,
'db_update_mode': None})
def test_submit_with_name(self):
sys.argv = ['qds.py', 'dbexportcmd', 'submit', '--mode', '1', '--dbtap_id', '1',
'--db_table', 'mydbtable', '--hive_table', 'myhivetable', '--name', 'commandname']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'export_dir': None,
'name': 'commandname',
'db_update_keys': None,
'partition_spec': None,
'fields_terminated_by': None,
'hive_table': 'myhivetable',
'db_table': 'mydbtable',
'mode': '1',
'tags': None,
'command_type': 'DbExportCommand',
'dbtap_id': '1',
'can_notify': False,
'db_update_mode': None})
def test_submit_with_update_mode_and_keys(self):
sys.argv = ['qds.py', 'dbexportcmd', 'submit', '--mode', '1', '--dbtap_id', '1',
'--db_table', 'mydbtable', '--hive_table', 'myhivetable',
'--db_update_mode', 'updateonly', '--db_update_keys', 'key1']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'export_dir': None,
'name': None,
'db_update_keys': 'key1',
'partition_spec': None,
'fields_terminated_by': None,
'hive_table': 'myhivetable',
'db_table': 'mydbtable',
'mode': '1',
'tags': None,
'command_type': 'DbExportCommand',
'dbtap_id': '1',
'can_notify': False,
'db_update_mode': 'updateonly'})
def test_submit_with_mode_2(self):
sys.argv = ['qds.py', 'dbexportcmd', 'submit', '--mode', '2', '--dbtap_id', '1',
'--db_table', 'mydbtable', '--hive_table', 'myhivetable',
'--export_dir', 's3:///export-path/']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'export_dir': 's3:///export-path/',
'name': None,
'db_update_keys': None,
'partition_spec': None,
'fields_terminated_by': None,
'hive_table': 'myhivetable',
'db_table': 'mydbtable',
'mode': '2',
'tags': None,
'command_type': 'DbExportCommand',
'dbtap_id': '1',
'can_notify': False,
'db_update_mode': None})
class TestDbImportCommand(QdsCliTestCase):
# Not much point adding more test cases as the semantic check in main code is still remaining.
# The test cases might give false positivies
def test_submit_command(self):
sys.argv = ['qds.py', 'dbimportcmd', 'submit', '--mode', '1', '--dbtap_id', '1',
'--db_table', 'mydbtable', '--hive_table', 'myhivetable']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'db_parallelism': None,
'name': None,
'dbtap_id': '1',
'db_where': None,
'db_boundary_query': None,
'mode': '1',
'tags': None,
'command_type': 'DbImportCommand',
'db_split_column': None,
'can_notify': False,
'hive_table': 'myhivetable',
'db_table': 'mydbtable',
'db_extract_query': None})
class TestDbTapQueryCommand(QdsCliTestCase):
def test_submit(self):
sys.argv = ['qds.py', 'dbtapquerycmd', 'submit', '--query', 'show tables', '--db_tap_id', 1]
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'db_tap_id': 1,
'query': 'show tables',
'name': None,
'tags': None,
'macros': None,
'command_type': 'DbTapQueryCommand',
'can_notify': False})
def test_submit_fail_with_no_parameters(self):
sys.argv = ['qds.py', 'dbtapquerycmd', 'submit']
print_command()
with self.assertRaises(qds_sdk.exception.ParseError):
qds.main()
def test_submit_fail_with_only_query_passed(self):
sys.argv = ['qds.py', 'dbtapquerycmd', 'submit', '--query', 'show tables']
print_command()
with self.assertRaises(qds_sdk.exception.ParseError):
qds.main()
def test_submit_fail_with_only_db_tap_id_passed(self):
sys.argv = ['qds.py', 'dbtapquerycmd', 'submit', '--db_tap_id', 1]
print_command()
with self.assertRaises(qds_sdk.exception.ParseError):
qds.main()
def test_submit_with_notify(self):
sys.argv = ['qds.py', 'dbtapquerycmd', 'submit', '--query', 'show tables', '--db_tap_id', 1, '--notify']
print_command()
Connection._api_call = Mock(return_value={'id': 1})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'db_tap_id': 1,
'query': 'show tables',
'tags': None,
'name': None,
'macros': None,
'command_type': 'DbTapQueryCommand',
'can_notify': True})
def test_submit_with_name(self):
sys.argv = ['qds.py', 'dbtapquerycmd', 'submit', '--query', 'show tables', '--db_tap_id', 1, '--name', 'test_name']
print_command()
Connection._api_call = Mock(return_value={'id': 1})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'db_tap_id': 1,
'query': 'show tables',
'tags': None,
'name': 'test_name',
'macros': None,
'command_type': 'DbTapQueryCommand',
'can_notify': False})
def test_submit_with_macros(self):
sys.argv = ['qds.py', 'dbtapquerycmd', 'submit', '--query', "select * from table_1 limit \$limit\$",
'--db_tap_id', 1, '--macros', '[{"a": "1", "b" : "4", "limit":"a + b"}]']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': [{"a": "1", "b" : "4", "limit":"a + b"}],
'db_tap_id': 1,
'query': "select * from table_1 limit \$limit\$",
'tags': None,
'name': None,
'command_type': 'DbTapQueryCommand',
'can_notify': False})
def test_submit_with_tags(self):
sys.argv = ['qds.py', 'dbtapquerycmd', 'submit', '--query', "select * from table_1 limit \$limit\$",
'--db_tap_id', 1, '--tags', 'tag1,tag2']
print_command()
Connection._api_call = Mock(return_value={'id': 1234})
qds.main()
Connection._api_call.assert_called_with('POST', 'commands',
{'macros': None,
'db_tap_id': 1,
'query': "select * from table_1 limit \$limit\$",
'tags': ["tag1", "tag2"],
'name': None,
'command_type': 'DbTapQueryCommand',
'can_notify': False})
if __name__ == '__main__':
unittest.main()
| {
"content_hash": "1875b50b0772557b299d3544951f172b",
"timestamp": "",
"source": "github",
"line_count": 1297,
"max_line_length": 200,
"avg_line_length": 41.98612181958365,
"alnum_prop": 0.4742177170559718,
"repo_name": "adeshr/qds-sdk-py",
"id": "8821585e7170b1480e17bbdbd508bb360da20274",
"size": "54456",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/test_command.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "410814"
}
],
"symlink_target": ""
} |
import os
import copy
import salt.config
DEFAULT_EBI_CONFIG = {
'root': '{0}/ebi'.format(os.getcwd()),
'list': False,
'grains': False,
'pillar': False
}
def ebi_config():
return copy.deepcopy(DEFAULT_EBI_CONFIG)
def ebi_minion_config():
return copy.deepcopy(salt.config.DEFAULT_MINION_OPTS)
| {
"content_hash": "e571d1a584215b93c010dc8c19dec04e",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 57,
"avg_line_length": 19.875,
"alnum_prop": 0.6666666666666666,
"repo_name": "zombiemonkey/ebi",
"id": "7598a5f6acf3ec19c740704710b312a05f648bba",
"size": "339",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ebi/config.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "10981"
},
{
"name": "Scheme",
"bytes": "153"
}
],
"symlink_target": ""
} |
str_to_int = {
'unknown': 0,
'saccade': 1,
'fixation': 2
}
int_to_str = [
'unknown',
'saccade',
'fixation'
]
class ClassError(Exception):
pass
def convert_to_integers(stringclasses):
for s in stringclasses:
if s in str_to_int:
yield str_to_int[s]
else:
raise ClassError('Invalid class string')
def convert_to_strings(intclasses):
for i in intclasses:
if i >= 0 and i < len(int_to_str):
yield int_to_str[i]
else:
raise ClassError('Invalid class integer')
| {
"content_hash": "8b432e28caff5b434f07773b07cb03c8",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 53,
"avg_line_length": 20.5,
"alnum_prop": 0.5627177700348432,
"repo_name": "infant-cognition-tampere/gazeclassifier-py",
"id": "fa80f82278041a62d5e0b64522de2ce6160bf80b",
"size": "575",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gazeclassifier/classes.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "8499"
}
],
"symlink_target": ""
} |
"""Test alarm notifier."""
from aodh import notifier
class TestAlarmNotifier(notifier.AlarmNotifier):
"Test alarm notifier."""
def __init__(self, conf):
super(TestAlarmNotifier, self).__init__(conf)
self.notifications = []
def notify(self, action, alarm_id, alarm_name, severity,
previous, current, reason, reason_data):
self.notifications.append((action,
alarm_id,
alarm_name,
severity,
previous,
current,
reason,
reason_data))
| {
"content_hash": "a3b530232b163baf31dcdc16df75628d",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 60,
"avg_line_length": 33.18181818181818,
"alnum_prop": 0.44246575342465755,
"repo_name": "openstack/aodh",
"id": "0a316fd4e86b8b1e14a81011ae49a55e76f20037",
"size": "1310",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "aodh/notifier/test.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Mako",
"bytes": "1061"
},
{
"name": "Python",
"bytes": "693850"
},
{
"name": "Shell",
"bytes": "12979"
}
],
"symlink_target": ""
} |
import unittest
from distutils.version import LooseVersion
from . import IntegrationTestCase, doxygen_version
class Example(IntegrationTestCase):
def test_cpp(self):
self.run_doxygen(index_pages=[], wildcard='*.xml')
self.assertEqual(*self.actual_expected_contents('path-prefix_2configure_8h_8cmake-example.html'))
self.assertEqual(*self.actual_expected_contents('path-prefix_2main_8cpp-example.html'))
@unittest.skipUnless(LooseVersion(doxygen_version()) > LooseVersion("1.8.13"),
"needs to have file extension exposed in the XML")
def test_other(self):
self.run_doxygen(index_pages=[], wildcard='*.xml')
self.assertEqual(*self.actual_expected_contents('path-prefix_2CMakeLists_8txt-example.html'))
self.assertEqual(*self.actual_expected_contents('a_8txt-example.html'))
| {
"content_hash": "2fbb02dcf48e9a1f4bf22082979360cc",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 105,
"avg_line_length": 43.15,
"alnum_prop": 0.7068366164542295,
"repo_name": "mosra/m.css",
"id": "c6bd279c7889d1e6b94e8746be21f83764dc1058",
"size": "2093",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "documentation/test_doxygen/test_example.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "29"
},
{
"name": "CSS",
"bytes": "139738"
},
{
"name": "HTML",
"bytes": "39793"
},
{
"name": "Python",
"bytes": "340270"
},
{
"name": "Shell",
"bytes": "461"
}
],
"symlink_target": ""
} |
"""Mask schedule functions R."""
import math
import jax
import jax.numpy as jnp
def schedule(ratio, total_unknown, method="cosine"):
"""Generates a mask rate by scheduling mask functions R.
Given a ratio in [0, 1), we generate a masking ratio from (0, 1]. During
training, the input ratio is uniformly sampled; during inference, the input
ratio is based on the step number divided by the total iteration number: t/T.
Based on experiements, we find that masking more in training helps.
Args:
ratio: The uniformly sampled ratio [0, 1) as input.
total_unknown: The total number of tokens that can be masked out. For
example, in MaskGIT, total_unknown = 256 for 256x256 images and 1024 for
512x512 images.
method: implemented functions are ["uniform", "cosine", "pow", "log", "exp"]
"pow2.5" represents x^2.5
Returns:
The mask rate (float).
"""
if method == "uniform":
mask_ratio = 1. - ratio
elif "pow" in method:
exponent = float(method.replace("pow", ""))
mask_ratio = 1. - ratio**exponent
elif method == "cosine":
mask_ratio = jax.lax.cos(math.pi / 2. * ratio)
elif method == "log":
mask_ratio = -jnp.log2(ratio) / jnp.log2(total_unknown)
elif method == "exp":
mask_ratio = 1 - jnp.exp2(-jnp.log2(total_unknown) * (1 - ratio))
# Clamps mask into [epsilon, 1)
mask_ratio = jnp.clip(mask_ratio, 1e-6, 1.)
return mask_ratio
| {
"content_hash": "da405e49bceed56fdfb8634ac67bc8d8",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 80,
"avg_line_length": 37.23684210526316,
"alnum_prop": 0.669964664310954,
"repo_name": "google-research/maskgit",
"id": "2681fde6fe142a1a4aa3200a2b54b87f19a871ce",
"size": "1991",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "maskgit/libml/mask_schedule.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "74392"
},
{
"name": "Python",
"bytes": "65477"
}
],
"symlink_target": ""
} |
"""
Created on Wed Jan 20 16:08:56 2016
@author: Thibault
"""
import pandas as pd
import numpy as np
# Loading the data
data_dir = '../data'
# training and validation sets
train_file = data_dir + '/blocking1114.csv'
# Opening the blocking data
TrainFile = pd.read_csv(train_file, header=None)
TrainFile.columns = ['Application', 'Patent_Blocking']
# Opening the Portfolio database
portf = data_dir + '/SamplePortfolioforBerkeley.csv'
Moto_database = pd.read_csv(portf, sep=',')
# Creating the query
Moto_Patents = np.asarray(Moto_database['Patent #'])
# Returns
def foo(s1):
return "'{}'".format(s1)
def query(table):
query = 'SELECT uspatentcitation.citation_id, uspatentcitation.patent_id FROM uspatentcitation WHERE uspatentcitation.citation_id='
for k in table:
if k != table[-1]:
query += foo(str(k)) + ' OR uspatentapplication.patent_id='
else:
query += foo(str(k))
return query
print(query(Moto_Patents))
# Connecting to the server
"NEED TO CONNECT TO SQL DATABASE USING MySQL"
# Doing the query to get the database
"""
SELECT uspatentcitation.citation_id, uspatentcitation.patent_id
FROM uspatentcitation
WHERE uspatentcitation.citation_id='7046910'
OR uspatentcitation.citation_id='5903133'
OR uspatentcitation.citation_id='8395587'
OR uspatentcitation.citation_id='6408436'
OR uspatentcitation.citation_id='7190956'
OR uspatentcitation.citation_id='6778512'
OR uspatentcitation.citation_id='5794185'
OR uspatentcitation.citation_id='6592696'
OR uspatentcitation.citation_id='8078203'
OR uspatentcitation.citation_id='8229428'
OR uspatentcitation.citation_id='7555696'
OR uspatentcitation.citation_id='5946653'
OR uspatentcitation.citation_id='7675970'
""""
| {
"content_hash": "3a64368f3b3fc5861514afab91ddd9b1",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 135,
"avg_line_length": 23.30666666666667,
"alnum_prop": 0.7362700228832952,
"repo_name": "PatentBlocker/Motorola_Patent_Citations",
"id": "9bbc31f90114e5b4a31b609319b5c902eca7ee0c",
"size": "1772",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/get_citations.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Python",
"bytes": "7700"
},
{
"name": "R",
"bytes": "2944"
}
],
"symlink_target": ""
} |
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('phonelog', '0012_server_date_not_null'),
]
operations = [
migrations.DeleteModel(
name='OldDeviceReportEntry',
),
]
| {
"content_hash": "43896aafba64c7aab040f025640d41e6",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 50,
"avg_line_length": 18.785714285714285,
"alnum_prop": 0.596958174904943,
"repo_name": "dimagi/commcare-hq",
"id": "c538bac77d1b385a46d6dbc079b60917fab073d2",
"size": "313",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "corehq/ex-submodules/phonelog/migrations/0013_delete_olddevicereportentry.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "82928"
},
{
"name": "Dockerfile",
"bytes": "2341"
},
{
"name": "HTML",
"bytes": "2589268"
},
{
"name": "JavaScript",
"bytes": "5889543"
},
{
"name": "Jinja",
"bytes": "3693"
},
{
"name": "Less",
"bytes": "176180"
},
{
"name": "Makefile",
"bytes": "1622"
},
{
"name": "PHP",
"bytes": "2232"
},
{
"name": "PLpgSQL",
"bytes": "66704"
},
{
"name": "Python",
"bytes": "21779773"
},
{
"name": "Roff",
"bytes": "150"
},
{
"name": "Shell",
"bytes": "67473"
}
],
"symlink_target": ""
} |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'RepositoryUser'
db.create_table('repositories_repositoryuser', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('repo', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['repositories.Repository'])),
('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
))
db.send_create_signal('repositories', ['RepositoryUser'])
# Adding unique constraint on 'RepositoryUser', fields ['repo', 'user']
db.create_unique('repositories_repositoryuser', ['repo_id', 'user_id'])
def backwards(self, orm):
# Removing unique constraint on 'RepositoryUser', fields ['repo', 'user']
db.delete_unique('repositories_repositoryuser', ['repo_id', 'user_id'])
# Deleting model 'RepositoryUser'
db.delete_table('repositories_repositoryuser')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'repositories.repository': {
'Meta': {'unique_together': "(('user', 'slug'),)", 'object_name': 'Repository'},
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255', 'db_index': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'repositories.repositoryuser': {
'Meta': {'unique_together': "(('repo', 'user'),)", 'object_name': 'RepositoryUser'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'repo': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['repositories.Repository']"}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
}
}
complete_apps = ['repositories']
| {
"content_hash": "da0bceb448c5004481970cdc4d5d3508",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 182,
"avg_line_length": 63.55294117647059,
"alnum_prop": 0.5638652350981118,
"repo_name": "stephrdev/brigitte",
"id": "bbc930727be94e68dad74bd64b2c630d712f7795",
"size": "5420",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "brigitte/repositories/migrations/0004_auto__add_repositoryuser__add_unique_repositoryuser_repo_user.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "10097"
},
{
"name": "Python",
"bytes": "162658"
}
],
"symlink_target": ""
} |
from math import sin, cos, atan2, sqrt
from datatypes import position, distance, direction
class station:
"""An object representing a weather station."""
def __init__( self, id, city=None, state=None, country=None, latitude=None, longitude=None):
self.id = id
self.city = city
self.state = state
self.country = country
self.position = position(latitude,longitude)
if self.state:
self.name = "%s, %s" % (self.city, self.state)
else:
self.name = self.city
station_file_name = "nsd_cccc.txt"
station_file_url = "http://www.noaa.gov/nsd_cccc.txt"
stations = {}
fh = open(station_file_name,'r')
for line in fh:
f = line.strip().split(";")
stations[f[0]] = station(f[0],f[3],f[4],f[5],f[7],f[8])
fh.close()
if __name__ == "__main__":
for id in [ 'KEWR', 'KIAD', 'KIWI', 'EKRK' ]:
print(id, stations[id].name, stations[id].country)
| {
"content_hash": "69ef53182ddf96a11e84798d3abf4d03",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 94,
"avg_line_length": 27.875,
"alnum_prop": 0.6266816143497758,
"repo_name": "Hotpirsch/tbot",
"id": "604140ed54d1d287b9a7631632a9f859bd5c4a4c",
"size": "1022",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Station.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "63489"
}
],
"symlink_target": ""
} |
import unittest
import numpy as np
import pints
import pints.toy as toy
from shared import StreamCapture
class TestDifferentialEvolutionMCMC(unittest.TestCase):
"""
Tests the basic methods of the differential evolution MCMC method.
"""
@classmethod
def setUpClass(cls):
""" Prepare a problem for testing. """
# Create toy model
cls.model = toy.LogisticModel()
cls.real_parameters = [0.015, 500]
cls.times = np.linspace(0, 1000, 1000)
cls.values = cls.model.simulate(cls.real_parameters, cls.times)
# Add noise
cls.noise = 10
cls.values += np.random.normal(0, cls.noise, cls.values.shape)
cls.real_parameters.append(cls.noise)
cls.real_parameters = np.array(cls.real_parameters)
# Create an object with links to the model and time series
cls.problem = pints.SingleOutputProblem(
cls.model, cls.times, cls.values)
# Create a uniform prior over both the parameters and the new noise
# variable
cls.log_prior = pints.UniformLogPrior(
[0.01, 400, cls.noise * 0.1],
[0.02, 600, cls.noise * 100]
)
# Create a log likelihood
cls.log_likelihood = pints.GaussianLogLikelihood(cls.problem)
# Create an un-normalised log-posterior (log-likelihood + log-prior)
cls.log_posterior = pints.LogPosterior(
cls.log_likelihood, cls.log_prior)
def test_method(self):
# Create mcmc
xs = [
self.real_parameters * 1.1,
self.real_parameters * 1.05,
self.real_parameters * 0.9,
self.real_parameters * 0.95,
]
mcmc = pints.DifferentialEvolutionMCMC(4, xs)
# Perform short run
chains = []
for i in range(100):
xs = mcmc.ask()
fxs = np.array([self.log_posterior(x) for x in xs])
ys, fys, ac = mcmc.tell(fxs)
if i >= 50:
chains.append(ys)
if np.any(ac):
self.assertTrue(np.all(xs[ac] == ys[ac]))
self.assertTrue(np.all(fys[ac] == fxs[ac]))
chains = np.array(chains)
self.assertEqual(chains.shape[0], 50)
self.assertEqual(chains.shape[1], len(xs))
self.assertEqual(chains.shape[2], len(xs[0]))
def test_flow(self):
# Test we have at least 3 chains
n = 2
x0 = [self.real_parameters] * n
self.assertRaises(ValueError, pints.DifferentialEvolutionMCMC, n, x0)
# Test initial proposal is first point
n = 3
x0 = [self.real_parameters] * n
mcmc = pints.DifferentialEvolutionMCMC(n, x0)
self.assertTrue(mcmc.ask() is mcmc._x0)
# Double initialisation
mcmc = pints.DifferentialEvolutionMCMC(n, x0)
mcmc.ask()
self.assertRaises(RuntimeError, mcmc._initialise)
# Tell without ask
mcmc = pints.DifferentialEvolutionMCMC(n, x0)
self.assertRaises(RuntimeError, mcmc.tell, 0)
# Repeated asks should return same point
mcmc = pints.DifferentialEvolutionMCMC(n, x0)
# Get into accepting state
for i in range(100):
mcmc.tell([self.log_posterior(x) for x in mcmc.ask()])
x = mcmc.ask()
for i in range(10):
self.assertTrue(x is mcmc.ask())
# Repeated tells should fail
mcmc.tell([1, 1, 1])
self.assertRaises(RuntimeError, mcmc.tell, [1, 1, 1])
# Bad starting point
mcmc = pints.DifferentialEvolutionMCMC(n, x0)
mcmc.ask()
self.assertRaises(ValueError, mcmc.tell, float('-inf'))
# Use uniform error
mcmc = pints.DifferentialEvolutionMCMC(n, x0)
mcmc.set_gaussian_error(False)
for i in range(10):
mcmc.tell([self.log_posterior(x) for x in mcmc.ask()])
# Use absolute scaling
mcmc = pints.DifferentialEvolutionMCMC(n, x0)
mcmc.set_relative_scaling(False)
for i in range(10):
mcmc.tell([self.log_posterior(x) for x in mcmc.ask()])
def test_set_hyper_parameters(self):
# Tests the hyper-parameter interface for this sampler.
n = 3
x0 = [self.real_parameters] * n
mcmc = pints.DifferentialEvolutionMCMC(n, x0)
self.assertEqual(mcmc.n_hyper_parameters(), 5)
mcmc.set_hyper_parameters([0.5, 0.6, 20, 0, 0])
self.assertEqual(mcmc.gamma(), 0.5)
self.assertEqual(mcmc.scale_coefficient(), 0.6)
self.assertEqual(mcmc.gamma_switch_rate(), 20)
self.assertTrue(not mcmc.gaussian_error())
self.assertTrue(not mcmc.relative_scaling())
mcmc.set_gamma(0.5)
self.assertEqual(mcmc.gamma(), 0.5)
self.assertRaisesRegex(ValueError,
'non-negative', mcmc.set_gamma, -1)
mcmc.set_scale_coefficient(1)
self.assertTrue(not mcmc.relative_scaling())
self.assertRaisesRegex(ValueError,
'non-negative', mcmc.set_scale_coefficient, -1)
mcmc.set_gamma_switch_rate(11)
self.assertEqual(mcmc.gamma_switch_rate(), 11)
self.assertRaisesRegex(
ValueError, 'integer', mcmc.set_gamma_switch_rate, 11.5)
self.assertRaisesRegex(
ValueError, 'exceed 1', mcmc.set_gamma_switch_rate, 0)
mcmc.set_gaussian_error(False)
self.assertTrue(not mcmc.gaussian_error())
mcmc.set_relative_scaling(0)
self.assertTrue(np.array_equal(mcmc._b_star,
np.repeat(mcmc._b, mcmc._n_parameters)))
mcmc.set_relative_scaling(1)
self.assertTrue(np.array_equal(mcmc._b_star,
mcmc._mu * mcmc._b))
# test implicit conversion to int
mcmc.set_hyper_parameters([0.5, 0.6, 20.2, 0, 0])
self.assertEqual(mcmc.gamma_switch_rate(), 20)
self.assertRaisesRegex(
ValueError, 'convertable to an integer',
mcmc.set_hyper_parameters, (0.5, 0.6, 'sdf', 0, 0))
def test_logging(self):
# Test logging includes name and custom fields.
x = [self.real_parameters] * 3
mcmc = pints.MCMCController(
self.log_posterior, 3, x, method=pints.DifferentialEvolutionMCMC)
mcmc.set_max_iterations(5)
with StreamCapture() as c:
mcmc.run()
text = c.text()
self.assertIn('Differential Evolution MCMC', text)
if __name__ == '__main__':
unittest.main()
| {
"content_hash": "249ec7bfdd688b03f80dfa131ca7c59e",
"timestamp": "",
"source": "github",
"line_count": 192,
"max_line_length": 79,
"avg_line_length": 34.333333333333336,
"alnum_prop": 0.5879854368932039,
"repo_name": "martinjrobins/hobo",
"id": "cf00ffb24efa18d33aa36d7b94f35022ec635900",
"size": "6887",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pints/tests/test_mcmc_differential_evolution.py",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "278656"
},
{
"name": "C++",
"bytes": "86361"
},
{
"name": "CMake",
"bytes": "1710"
},
{
"name": "Cuda",
"bytes": "7890"
},
{
"name": "M",
"bytes": "2347"
},
{
"name": "Matlab",
"bytes": "437018"
},
{
"name": "Python",
"bytes": "1841329"
},
{
"name": "Stan",
"bytes": "8353"
},
{
"name": "TeX",
"bytes": "88007"
},
{
"name": "mupad",
"bytes": "73951"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
class CreatedByMixin(models.Model):
"""
Mixin to add created by fields to a model.
"""
created_date = models.DateTimeField(
auto_now_add=True, null=True, blank=True)
created_by = models.ForeignKey(
User, null=True, blank=True, related_name="%(class)s_created_by")
class Meta:
abstract = True
class ModifiedByMixin(models.Model):
"""
Mixin to add modified by fields to a model.
"""
modified_date = models.DateTimeField(
auto_now=True, null=True, blank=True)
modified_by = models.ForeignKey(
User, null=True, blank=True, related_name="%(class)s_modified_by")
class Meta:
abstract = True
class DeletedByMixin(models.Model):
"""
Mixin to add deleted by fields to a model.
"""
deleted_date = models.DateTimeField(
auto_now=False, null=True, blank=True)
deleted_by = models.ForeignKey(
User, null=True, blank=True, related_name="%(class)s_deleted_by")
@property
def deleted(self):
"""
Helper property to return True if this object has been deleted.
"""
return self.deleted_by is not None
class Meta:
abstract = True
class CreateDeleteAuditModel(CreatedByMixin, DeletedByMixin):
"""
Mixin to add created and deleted fields to a model
"""
class Meta:
abstract = True
class FullAuditModel(CreatedByMixin, ModifiedByMixin, DeletedByMixin):
"""
Mixin to add created, modified, and deleted fields to a model
"""
class Meta:
abstract = True
| {
"content_hash": "778cc52b534d285c981c9578d5361cf5",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 74,
"avg_line_length": 25.575757575757574,
"alnum_prop": 0.6481042654028436,
"repo_name": "geosoco/reddit_coding",
"id": "d8d5b20065bf31190b86384f12ed40ebdbd7a6d2",
"size": "1688",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "base/models.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "18804"
},
{
"name": "HTML",
"bytes": "20973"
},
{
"name": "JavaScript",
"bytes": "46619"
},
{
"name": "Python",
"bytes": "68758"
}
],
"symlink_target": ""
} |
import unittest
from application import server, app
import json
class ApplicationTestCase(unittest.TestCase):
def setUp(self):
server.app.config['TESTING'] = True
self.app = server.app.test_client()
headers = {'content-type': 'application/json; charset=utf-8'}
history_data = '{"title_number": "TEST1412258807231" }'
self.app.post('/TEST1412853022495', data=history_data, headers=headers)
def test_that_get_root_fails(self):
self.assertEqual((self.app.get('/')).status, '400 BAD REQUEST')
def test_that_post_root_fails(self):
self.assertEqual((self.app.post('/')).status, '405 METHOD NOT ALLOWED')
def test_that_post_successful(self):
headers = {'content-type': 'application/json; charset=utf-8'}
history_data = '{"title_number": "TEST1412258807231" }'
app.logger.info(history_data)
app.logger.info(json.dumps(history_data, encoding='utf-8'))
res = self.app.post('/TEST1412853022495', data=history_data, headers=headers)
self.assertEqual(res.status, '200 OK')
def test_that_get_list_successful(self):
self.assertEqual((self.app.get('/TEST1412853022495?version=list')).status, '200 OK')
data = json.loads(self.app.get('/TEST1412853022495?version=list').data)
self.assertEqual(json.dumps(data, encoding='utf-8'), '{"versions": []}')
def test_that_get_version_successful(self):
self.assertEqual((self.app.get('/TEST1412853022495?version=0')).status, '404 NOT FOUND')
| {
"content_hash": "774aef75dcaa6e0c197d870c3985e34f",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 96,
"avg_line_length": 41.45945945945946,
"alnum_prop": 0.6642764015645372,
"repo_name": "LandRegistry/historian-alpha",
"id": "8bd64a435a76cb85b5fbf9bfd081a25744d704b0",
"size": "1534",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/tests_get_post.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "0"
},
{
"name": "PHP",
"bytes": "38"
},
{
"name": "Python",
"bytes": "17457"
},
{
"name": "Shell",
"bytes": "1194"
}
],
"symlink_target": ""
} |
from __future__ import absolute_import, division, print_function, unicode_literals
from .common import BaseTest, functional
from c7n.filters import FilterValidationError
class VpcTest(BaseTest):
@functional
def test_flow_logs(self):
factory = self.replay_flight_data(
'test_vpc_flow_logs')
session = factory()
ec2 = session.client('ec2')
logs = session.client('logs')
vpc_id = ec2.create_vpc(CidrBlock="10.4.0.0/16")['Vpc']['VpcId']
self.addCleanup(ec2.delete_vpc, VpcId=vpc_id)
p = self.load_policy({
'name': 'net-find',
'resource': 'vpc',
'filters': [
{'VpcId': vpc_id},
'flow-logs']},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['VpcId'], vpc_id)
log_group = 'vpc-logs'
logs.create_log_group(logGroupName=log_group)
self.addCleanup(logs.delete_log_group, logGroupName=log_group)
ec2.create_flow_logs(
ResourceIds=[vpc_id],
ResourceType='VPC',
TrafficType='ALL',
LogGroupName=log_group,
DeliverLogsPermissionArn='arn:aws:iam::644160558196:role/flowlogsRole')
p = self.load_policy({
'name': 'net-find',
'resource': 'vpc',
'filters': [
{'VpcId': vpc_id},
{'type': 'flow-logs',
'enabled': True,
'status': 'active',
'traffic-type': 'all',
'log-group': log_group}]
}, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
@functional
def test_flow_logs_absent(self):
"""Test that ONLY vpcs with no flow logs are retained
'vpc-4a9ff72e' - has no flow logs
'vpc-d0e386b7' - has flow logs
"""
factory = self.replay_flight_data(
'test_vpc_flow_logs_absent')
vpc_id1 = 'vpc-4a9ff72e'
p = self.load_policy({
'name': 'net-find',
'resource': 'vpc',
'filters': [
{'VpcId': vpc_id1},
'flow-logs']},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['VpcId'], vpc_id1)
@functional
def test_flow_logs_misconfiguration(self):
# Validate that each VPC has at least one valid configuration
#
# In terms of filters, we then want to flag VPCs for which every
# flow log configuration has at least one invalid value
#
# Here - have 2 vpcs ('vpc-4a9ff72e','vpc-d0e386b7')
#
# The first has three flow logs which each have different
# misconfigured properties The second has one correctly
# configured flow log, and one where all config is bad
#
# Only the first should be returned by the filter
factory = self.replay_flight_data(
'test_vpc_flow_logs_misconfigured')
vpc_id1 = 'vpc-4a9ff72e'
traffic_type = 'all'
log_group = '/aws/lambda/myIOTFunction'
status = 'active'
p = self.load_policy({
'name': 'net-find',
'resource': 'vpc',
'filters': [
{'not': [{
'type': 'flow-logs',
'enabled': True,
'op': 'equal',
'set-op': 'or',
'status': status,
'traffic-type': traffic_type,
'log-group': log_group
}]
}
]},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['VpcId'], vpc_id1)
class NetworkLocationTest(BaseTest):
@functional
def test_network_location_sg_missing(self):
self.factory = self.replay_flight_data(
'test_network_location_sg_missing_loc')
client = self.factory().client('ec2')
vpc_id = client.create_vpc(CidrBlock="10.4.0.0/16")['Vpc']['VpcId']
self.addCleanup(client.delete_vpc, VpcId=vpc_id)
web_sub_id = client.create_subnet(
VpcId=vpc_id, CidrBlock="10.4.9.0/24")[
'Subnet']['SubnetId']
self.addCleanup(client.delete_subnet, SubnetId=web_sub_id)
web_sg_id = client.create_security_group(
GroupName="web-tier",
VpcId=vpc_id,
Description="for apps")['GroupId']
self.addCleanup(client.delete_security_group, GroupId=web_sg_id)
sg_id = client.create_security_group(
GroupName="some-tier",
VpcId=vpc_id,
Description="for rabbits")['GroupId']
self.addCleanup(client.delete_security_group, GroupId=sg_id)
nic = client.create_network_interface(
SubnetId=web_sub_id,
Groups=[sg_id, web_sg_id]
)['NetworkInterface']['NetworkInterfaceId']
self.addCleanup(
client.delete_network_interface, NetworkInterfaceId=nic)
client.create_tags(
Resources=[nic, web_sg_id, web_sub_id],
Tags=[{'Key': 'Location', 'Value': 'web'}])
p = self.load_policy({
'name': 'netloc',
'resource': 'eni',
'filters': [
{'NetworkInterfaceId': nic},
{'type': 'network-location',
'key': 'tag:Location'}]
}, session_factory=self.factory)
resources = p.run()
self.assertEqual(len(resources), 1)
matched = resources.pop()
self.assertEqual(
matched['c7n:NetworkLocation'], [{
'reason': 'SecurityGroupLocationAbsent',
'security-groups': {sg_id: None, web_sg_id: 'web'}
}])
@functional
def test_network_location_sg_cardinality(self):
self.factory = self.replay_flight_data(
'test_network_location_sg_cardinality')
client = self.factory().client('ec2')
vpc_id = client.create_vpc(CidrBlock="10.4.0.0/16")['Vpc']['VpcId']
self.addCleanup(client.delete_vpc, VpcId=vpc_id)
web_sub_id = client.create_subnet(
VpcId=vpc_id, CidrBlock="10.4.9.0/24")[
'Subnet']['SubnetId']
self.addCleanup(client.delete_subnet, SubnetId=web_sub_id)
web_sg_id = client.create_security_group(
GroupName="web-tier",
VpcId=vpc_id,
Description="for apps")['GroupId']
self.addCleanup(client.delete_security_group, GroupId=web_sg_id)
db_sg_id = client.create_security_group(
GroupName="db-tier",
VpcId=vpc_id,
Description="for dbs")['GroupId']
self.addCleanup(client.delete_security_group, GroupId=db_sg_id)
nic = client.create_network_interface(
SubnetId=web_sub_id,
Groups=[web_sg_id, db_sg_id])['NetworkInterface']['NetworkInterfaceId']
self.addCleanup(client.delete_network_interface, NetworkInterfaceId=nic)
client.create_tags(
Resources=[web_sg_id, web_sub_id, nic],
Tags=[{'Key': 'Location', 'Value': 'web'}])
client.create_tags(
Resources=[db_sg_id],
Tags=[{'Key': 'Location', 'Value': 'db'}])
p = self.load_policy({
'name': 'netloc',
'resource': 'eni',
'filters': [
{'NetworkInterfaceId': nic},
{'type': 'network-location',
'key': 'tag:Location'}]
}, session_factory=self.factory)
resources = p.run()
self.assertEqual(len(resources), 1)
matched = resources.pop()
self.assertEqual(
matched['c7n:NetworkLocation'],
[{'reason': 'SecurityGroupLocationCardinality',
'security-groups': {db_sg_id: 'db', web_sg_id: 'web'}},
{'reason': 'LocationMismatch',
'security-groups': {db_sg_id: 'db', web_sg_id: 'web'},
'subnets': {web_sub_id: 'web'}}])
@functional
def test_network_location_resource_missing(self):
self.factory = self.replay_flight_data('test_network_location_resource_missing')
client = self.factory().client('ec2')
vpc_id = client.create_vpc(CidrBlock="10.4.0.0/16")['Vpc']['VpcId']
self.addCleanup(client.delete_vpc, VpcId=vpc_id)
web_sub_id = client.create_subnet(
VpcId=vpc_id, CidrBlock="10.4.9.0/24")[
'Subnet']['SubnetId']
self.addCleanup(client.delete_subnet, SubnetId=web_sub_id)
web_sg_id = client.create_security_group(
GroupName="web-tier",
VpcId=vpc_id,
Description="for apps")['GroupId']
self.addCleanup(client.delete_security_group, GroupId=web_sg_id)
nic = client.create_network_interface(
SubnetId=web_sub_id,
Groups=[web_sg_id])['NetworkInterface']['NetworkInterfaceId']
self.addCleanup(client.delete_network_interface, NetworkInterfaceId=nic)
client.create_tags(
Resources=[web_sg_id, web_sub_id],
Tags=[{'Key': 'Location', 'Value': 'web'}])
p = self.load_policy({
'name': 'netloc',
'resource': 'eni',
'filters': [
{'NetworkInterfaceId': nic},
{'type': 'network-location',
'key': 'tag:Location'}]
}, session_factory=self.factory)
resources = p.run()
self.assertEqual(len(resources), 1)
matched = resources.pop()
self.assertEqual(
matched['c7n:NetworkLocation'],
[{'reason': 'ResourceLocationAbsent', 'resource': None}])
@functional
def test_network_location_triple_intersect(self):
self.factory = self.replay_flight_data('test_network_location_intersection')
client = self.factory().client('ec2')
vpc_id = client.create_vpc(CidrBlock="10.4.0.0/16")['Vpc']['VpcId']
self.addCleanup(client.delete_vpc, VpcId=vpc_id)
web_sub_id = client.create_subnet(
VpcId=vpc_id, CidrBlock="10.4.9.0/24")[
'Subnet']['SubnetId']
self.addCleanup(client.delete_subnet, SubnetId=web_sub_id)
web_sg_id = client.create_security_group(
GroupName="web-tier",
VpcId=vpc_id,
Description="for apps")['GroupId']
self.addCleanup(client.delete_security_group, GroupId=web_sg_id)
nic = client.create_network_interface(
SubnetId=web_sub_id,
Groups=[web_sg_id])['NetworkInterface']['NetworkInterfaceId']
self.addCleanup(client.delete_network_interface, NetworkInterfaceId=nic)
client.create_tags(
Resources=[web_sg_id, web_sub_id, nic],
Tags=[{'Key': 'Location', 'Value': 'web'}])
p = self.load_policy({
'name': 'netloc',
'resource': 'eni',
'filters': [
{'NetworkInterfaceId': nic},
{'type': 'network-location',
'key': 'tag:Location'}]
}, session_factory=self.factory)
resources = p.run()
self.assertEqual(len(resources), 0)
class NetworkAclTest(BaseTest):
@functional
def test_s3_cidr_network_acl_present(self):
factory = self.replay_flight_data('test_network_acl_s3_present')
client = factory().client('ec2')
vpc_id = client.create_vpc(CidrBlock="10.4.0.0/16")['Vpc']['VpcId']
self.addCleanup(client.delete_vpc, VpcId=vpc_id)
p = self.load_policy({
'name': 'nacl-check',
'resource': 'network-acl',
'filters': [
{'VpcId': vpc_id},
{'type': 's3-cidr', 'present': True}]},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
@functional
def test_s3_cidr_network_acl_not_present(self):
factory = self.replay_flight_data(
'test_network_acl_s3_missing')
client = factory().client('ec2')
vpc_id = client.create_vpc(CidrBlock="10.4.0.0/16")['Vpc']['VpcId']
self.addCleanup(client.delete_vpc, VpcId=vpc_id)
acls = client.describe_network_acls(
Filters=[{'Name': 'vpc-id', 'Values': [vpc_id]}])['NetworkAcls']
client.delete_network_acl_entry(
NetworkAclId=acls[0]['NetworkAclId'],
RuleNumber=acls[0]['Entries'][0]['RuleNumber'],
Egress=True)
p = self.load_policy({
'name': 'nacl-check',
'resource': 'network-acl',
'filters': [
{'VpcId': vpc_id}, 's3-cidr']},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
class NetworkInterfaceTest(BaseTest):
@functional
def test_interface_subnet(self):
factory = self.replay_flight_data(
'test_network_interface_filter')
client = factory().client('ec2')
vpc_id = client.create_vpc(CidrBlock="10.4.0.0/16")['Vpc']['VpcId']
self.addCleanup(client.delete_vpc, VpcId=vpc_id)
sub_id = client.create_subnet(
VpcId=vpc_id, CidrBlock="10.4.8.0/24")[
'Subnet']['SubnetId']
self.addCleanup(client.delete_subnet, SubnetId=sub_id)
sg_id = client.create_security_group(
GroupName="web-tier",
VpcId=vpc_id,
Description="for apps")['GroupId']
self.addCleanup(client.delete_security_group, GroupId=sg_id)
qsg_id = client.create_security_group(
GroupName="quarantine-group",
VpcId=vpc_id,
Description="for quarantine")['GroupId']
self.addCleanup(client.delete_security_group, GroupId=qsg_id)
net = client.create_network_interface(
SubnetId=sub_id, Groups=[sg_id])['NetworkInterface']
net_id = net['NetworkInterfaceId']
self.addCleanup(
client.delete_network_interface, NetworkInterfaceId=net_id)
p = self.load_policy({
'name': 'net-find',
'resource': 'eni',
'filters': [
{'type': 'subnet',
'key': 'SubnetId',
'value': sub_id},
{'type': 'security-group',
'key': 'Description',
'value': 'for apps'}
],
'actions': [{
'type': 'modify-security-groups',
'remove': 'matched',
'isolation-group': qsg_id}]
}, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['NetworkInterfaceId'], net_id)
self.assertEqual(resources[0]['c7n:matched-security-groups'], [sg_id])
results = client.describe_network_interfaces(
NetworkInterfaceIds=[net_id])['NetworkInterfaces']
self.assertEqual([g['GroupId'] for g in results[0]['Groups']], [qsg_id])
class SecurityGroupTest(BaseTest):
def test_id_selector(self):
p = self.load_policy({
'name': 'sg',
'resource': 'security-group'})
self.assertEqual(
p.resource_manager.match_ids(
['vpc-asdf', 'i-asdf3e', 'sg-1235a', 'sg-4671']),
['sg-1235a', 'sg-4671'])
@functional
def test_stale(self):
# setup a multi vpc security group reference, break the ref
# and look for stale
factory = self.replay_flight_data('test_security_group_stale')
client = factory().client('ec2')
vpc_id = client.create_vpc(CidrBlock="10.4.0.0/16")['Vpc']['VpcId']
vpc2_id = client.create_vpc(CidrBlock="10.5.0.0/16")['Vpc']['VpcId']
peer_id = client.create_vpc_peering_connection(
VpcId=vpc_id, PeerVpcId=vpc2_id)[
'VpcPeeringConnection']['VpcPeeringConnectionId']
client.accept_vpc_peering_connection(
VpcPeeringConnectionId=peer_id)
self.addCleanup(client.delete_vpc, VpcId=vpc_id)
self.addCleanup(client.delete_vpc, VpcId=vpc2_id)
self.addCleanup(client.delete_vpc_peering_connection,
VpcPeeringConnectionId=peer_id)
sg_id = client.create_security_group(
GroupName="web-tier",
VpcId=vpc_id,
Description="for apps")['GroupId']
self.addCleanup(client.delete_security_group, GroupId=sg_id)
t_sg_id = client.create_security_group(
GroupName="db-tier",
VpcId=vpc2_id,
Description="for apps")['GroupId']
client.authorize_security_group_ingress(
GroupId=sg_id,
IpPermissions=[
{'IpProtocol': 'tcp',
'FromPort': 60000,
'ToPort': 62000,
'UserIdGroupPairs': [
{'GroupId': t_sg_id,
'VpcId': vpc2_id,
'VpcPeeringConnectionId': peer_id}]}])
client.delete_security_group(GroupId=t_sg_id)
p = self.load_policy({
'name': 'sg-stale',
'resource': 'security-group',
'filters': ['stale']
}, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['GroupId'], sg_id)
self.assertEqual(
resources[0]['MatchedIpPermissions'],
[{u'FromPort': 60000,
u'IpProtocol': u'tcp',
u'ToPort': 62000,
u'UserIdGroupPairs': [
{u'GroupId': t_sg_id,
u'PeeringStatus': u'active',
u'VpcId': vpc2_id,
u'VpcPeeringConnectionId': peer_id}]}])
def test_used(self):
factory = self.replay_flight_data(
'test_security_group_used')
p = self.load_policy({
'name': 'sg-used',
'resource': 'security-group',
'filters': ['used']
}, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 3)
self.assertEqual(
set(['sg-f9cc4d9f', 'sg-13de8f75', 'sg-ce548cb7']),
set([r['GroupId'] for r in resources]))
def test_unused(self):
factory = self.replay_flight_data(
'test_security_group_unused')
p = self.load_policy({
'name': 'sg-unused',
'resource': 'security-group',
'filters': ['unused'],
}, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
@functional
def test_only_ports(self):
factory = self.replay_flight_data(
'test_security_group_only_ports')
client = factory().client('ec2')
vpc_id = client.create_vpc(CidrBlock="10.4.0.0/16")['Vpc']['VpcId']
self.addCleanup(client.delete_vpc, VpcId=vpc_id)
sg_id = client.create_security_group(
GroupName="web-tier",
VpcId=vpc_id,
Description="for apps")['GroupId']
self.addCleanup(client.delete_security_group, GroupId=sg_id)
client.authorize_security_group_ingress(
GroupId=sg_id,
IpProtocol='tcp',
FromPort=60000,
ToPort=62000,
CidrIp='10.2.0.0/16')
client.authorize_security_group_ingress(
GroupId=sg_id,
IpProtocol='tcp',
FromPort=61000,
ToPort=61000,
CidrIp='10.2.0.0/16')
p = self.load_policy({
'name': 'sg-find',
'resource': 'security-group',
'filters': [
{'type': 'ingress',
'OnlyPorts': [61000]},
{'GroupName': 'web-tier'}]
}, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(
resources[0]['MatchedIpPermissions'],
[{u'FromPort': 60000,
u'IpProtocol': u'tcp',
u'Ipv6Ranges': [],
u'IpRanges': [{u'CidrIp': u'10.2.0.0/16'}],
u'PrefixListIds': [],
u'ToPort': 62000,
u'UserIdGroupPairs': []}])
@functional
def test_self_reference(self):
factory = self.replay_flight_data(
'test_security_group_self_reference')
client = factory().client('ec2')
vpc_id = client.create_vpc(CidrBlock='10.4.0.0/16')['Vpc']['VpcId']
self.addCleanup(client.delete_vpc, VpcId=vpc_id)
# Find the ID of the default security group.
default_sg_id = client.describe_security_groups(Filters=[
{'Name': 'vpc-id', 'Values': [vpc_id]},
{'Name': 'group-name', 'Values': ['default']}]
)['SecurityGroups'][0]['GroupId']
sg1_id = client.create_security_group(
GroupName='sg1',
VpcId=vpc_id,
Description='SG 1')['GroupId']
self.addCleanup(client.delete_security_group, GroupId=sg1_id)
client.authorize_security_group_ingress(
GroupId=sg1_id,
IpPermissions=[{
'IpProtocol': 'tcp',
'FromPort': 80,
'ToPort': 80,
'UserIdGroupPairs': [
{
'GroupId': default_sg_id
},
{
'GroupId': sg1_id
}]
}])
client.authorize_security_group_ingress(
GroupId=sg1_id,
IpProtocol='tcp',
FromPort=60000,
ToPort=62000,
CidrIp='10.2.0.0/16')
client.authorize_security_group_ingress(
GroupId=sg1_id,
IpProtocol='tcp',
FromPort=61000,
ToPort=61000,
CidrIp='10.2.0.0/16')
sg2_id = client.create_security_group(
GroupName='sg2',
VpcId=vpc_id,
Description='SG 2')['GroupId']
self.addCleanup(client.delete_security_group, GroupId=sg2_id)
client.authorize_security_group_egress(
GroupId=sg2_id,
IpPermissions=[{
'IpProtocol': 'tcp',
'FromPort': 443,
'ToPort': 443,
'UserIdGroupPairs': [
{
'GroupId': sg1_id
}]
}])
p = self.load_policy({
'name': 'sg-find0',
'resource': 'security-group',
'filters': [
{'type': 'ingress',
'SelfReference': False},
{'GroupName': 'sg1'}]
}, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 0)
p = self.load_policy({
'name': 'sg-find1',
'resource': 'security-group',
'filters': [
{'type': 'ingress',
'SelfReference': True},
{'GroupName': 'sg1'}]
}, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
p = self.load_policy({
'name': 'sg-find2',
'resource': 'security-group',
'filters': [
{'type': 'egress',
'SelfReference': True},
{'GroupName': 'sg2'}]
}, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 0)
@functional
def test_security_group_delete(self):
factory = self.replay_flight_data(
'test_security_group_delete')
client = factory().client('ec2')
vpc_id = client.create_vpc(CidrBlock="10.4.0.0/16")['Vpc']['VpcId']
self.addCleanup(client.delete_vpc, VpcId=vpc_id)
sg_id = client.create_security_group(
GroupName="web-tier",
VpcId=vpc_id,
Description="for apps")['GroupId']
def delete_sg():
try:
client.delete_security_group(GroupId=sg_id)
except Exception:
pass
self.addCleanup(delete_sg)
p = self.load_policy({
'name': 'sg-delete',
'resource': 'security-group',
'filters': [
{'GroupId': sg_id}],
'actions': [
'delete']}, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['GroupId'], sg_id)
try:
group_info = client.describe_security_groups(GroupIds=[sg_id])
except:
pass
else:
self.fail("group not deleted")
@functional
def test_port_within_range(self):
factory = self.replay_flight_data(
'test_security_group_port_in_range')
client = factory().client('ec2')
vpc_id = client.create_vpc(CidrBlock="10.4.0.0/16")['Vpc']['VpcId']
self.addCleanup(client.delete_vpc, VpcId=vpc_id)
sg_id = client.create_security_group(
GroupName="web-tier",
VpcId=vpc_id,
Description="for apps")['GroupId']
self.addCleanup(client.delete_security_group, GroupId=sg_id)
client.authorize_security_group_ingress(
GroupId=sg_id,
IpProtocol='tcp',
FromPort=60000,
ToPort=62000,
CidrIp='10.2.0.0/16')
p = self.load_policy({
'name': 'sg-find',
'resource': 'security-group',
'filters': [
{'type': 'ingress',
'IpProtocol': 'tcp',
'FromPort': 60000},
{'GroupName': 'web-tier'}]
}, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['GroupName'], 'web-tier')
self.assertEqual(
resources[0]['MatchedIpPermissions'],
[{u'FromPort': 60000,
u'IpProtocol': u'tcp',
u'Ipv6Ranges': [],
u'IpRanges': [{u'CidrIp': u'10.2.0.0/16'}],
u'PrefixListIds': [],
u'ToPort': 62000,
u'UserIdGroupPairs': []}])
@functional
def test_ingress_remove(self):
factory = self.replay_flight_data(
'test_security_group_ingress_filter')
client = factory().client('ec2')
vpc_id = client.create_vpc(CidrBlock="10.4.0.0/16")['Vpc']['VpcId']
sg_id = client.create_security_group(
GroupName="web-tier",
VpcId=vpc_id,
Description="for apps")['GroupId']
self.addCleanup(client.delete_vpc, VpcId=vpc_id)
client.authorize_security_group_ingress(
GroupId=sg_id,
IpProtocol='tcp',
FromPort=0,
ToPort=62000,
CidrIp='10.2.0.0/16')
self.addCleanup(client.delete_security_group, GroupId=sg_id)
p = self.load_policy({
'name': 'sg-find',
'resource': 'security-group',
'filters': [
{'VpcId': vpc_id},
{'type': 'ingress',
'IpProtocol': 'tcp',
'FromPort': 0},
{'GroupName': 'web-tier'}],
'actions': [
{'type': 'remove-permissions',
'ingress': 'matched'}]},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['GroupId'], sg_id)
group_info = client.describe_security_groups(
GroupIds=[sg_id])['SecurityGroups'][0]
self.assertEqual(group_info.get('IpPermissions', []), [])
def test_default_vpc(self):
# preconditions, more than one vpc, each with at least one
# security group
factory = self.replay_flight_data(
'test_security_group_default_vpc_filter')
p = self.load_policy({
'name': 'sg-test',
'resource': 'security-group',
'filters': [
{'type': 'default-vpc'},
{'GroupName': 'default'}]},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
def test_config_source(self):
factory = self.replay_flight_data(
'test_security_group_config_source')
p = self.load_policy({
'name': 'sg-test',
'source': 'config',
'resource': 'security-group',
'filters': [
{'type': 'default-vpc'},
{'GroupName': 'default'}]},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['GroupId'], 'sg-6c7fa917')
def test_only_ports_ingress(self):
p = self.load_policy({
'name': 'ingress-access',
'resource': 'security-group',
'filters': [
{'type': 'ingress', 'OnlyPorts': [80]}
]})
resources = [
{'Description': 'Typical Internet-Facing Security Group',
'GroupId': 'sg-abcd1234',
'GroupName': 'TestInternetSG',
'IpPermissions': [{'FromPort': 53,
'IpProtocol': 'tcp',
'IpRanges': ['10.0.0.0/8'],
'PrefixListIds': [],
'ToPort': 53,
'UserIdGroupPairs': []}],
'IpPermissionsEgress': [],
'OwnerId': '123456789012',
'Tags': [{'Key': 'Value',
'Value': 'InternetSecurityGroup'},
{'Key': 'Key', 'Value': 'Name'}],
'VpcId': 'vpc-1234abcd'}
]
manager = p.get_resource_manager()
self.assertEqual(len(manager.filter_resources(resources)), 1)
def test_multi_attribute_ingress(self):
p = self.load_policy({
'name': 'ingress-access',
'resource': 'security-group',
'filters': [
{'type': 'ingress',
'Cidr': {'value': '10.0.0.0/8'},
'Ports': [53]}
]})
resources = [
{'Description': 'Typical Internet-Facing Security Group',
'GroupId': 'sg-abcd1234',
'GroupName': 'TestInternetSG',
'IpPermissions': [{'FromPort': 53,
'IpProtocol': 'tcp',
'IpRanges': [{'CidrIp': '10.0.0.0/8'}],
'PrefixListIds': [],
'ToPort': 53,
'UserIdGroupPairs': []}],
'IpPermissionsEgress': [],
'OwnerId': '123456789012',
'Tags': [{'Key': 'Value',
'Value': 'InternetSecurityGroup'},
{'Key': 'Key', 'Value': 'Name'}],
'VpcId': 'vpc-1234abcd'}
]
manager = p.get_resource_manager()
self.assertEqual(len(manager.filter_resources(resources)), 1)
def test_ports_ingress(self):
p = self.load_policy({
'name': 'ingress-access',
'resource': 'security-group',
'filters': [
{'type': 'ingress', 'Ports': [53]}
]})
resources = [
{'Description': 'Typical Internet-Facing Security Group',
'GroupId': 'sg-abcd1234',
'GroupName': 'TestInternetSG',
'IpPermissions': [{'FromPort': 53,
'IpProtocol': 'tcp',
'IpRanges': ['10.0.0.0/8'],
'PrefixListIds': [],
'ToPort': 53,
'UserIdGroupPairs': []}],
'IpPermissionsEgress': [],
'OwnerId': '123456789012',
'Tags': [{'Key': 'Value',
'Value': 'InternetSecurityGroup'},
{'Key': 'Key', 'Value': 'Name'}],
'VpcId': 'vpc-1234abcd'}
]
manager = p.get_resource_manager()
self.assertEqual(len(manager.filter_resources(resources)), 1)
def test_permission_expansion(self):
factory = self.replay_flight_data('test_security_group_perm_expand')
client = factory().client('ec2')
vpc_id = client.create_vpc(CidrBlock="10.42.0.0/16")['Vpc']['VpcId']
self.addCleanup(client.delete_vpc, VpcId=vpc_id)
sg_id = client.create_security_group(
GroupName="allow-some-ingress",
VpcId=vpc_id,
Description="inbound access")['GroupId']
sg2_id = client.create_security_group(
GroupName="allowed-reference",
VpcId=vpc_id,
Description="inbound ref access")['GroupId']
self.addCleanup(client.delete_security_group, GroupId=sg2_id)
self.addCleanup(client.delete_security_group, GroupId=sg_id)
client.authorize_security_group_ingress(
GroupId=sg_id,
IpPermissions=[{
'IpProtocol': 'tcp',
'FromPort': 443,
'ToPort': 443,
'IpRanges': [
{
'CidrIp': '10.42.1.0/24'
}]
}])
client.authorize_security_group_ingress(
GroupId=sg_id,
IpPermissions=[{
'IpProtocol': 'tcp',
'FromPort': 443,
'ToPort': 443,
'IpRanges': [
{
'CidrIp': '10.42.2.0/24'
}]
}])
client.authorize_security_group_ingress(
GroupId=sg_id,
IpPermissions=[{
'IpProtocol': 'tcp',
'FromPort': 443,
'ToPort': 443,
'UserIdGroupPairs': [{'GroupId': sg2_id}]
}])
p = self.load_policy({
'name': 'ingress-access',
'resource': 'security-group',
'filters': [
{'type': 'ingress',
'Cidr': {
'value': '10.42.1.1',
'op': 'in',
'value_type': 'cidr'}}]
}, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(
len(resources[0].get('MatchedIpPermissions', [])), 1)
self.assertEqual(
resources[0].get('MatchedIpPermissions', []),
[{u'FromPort': 443,
u'IpProtocol': u'tcp',
u'Ipv6Ranges': [],
u'PrefixListIds': [],
u'UserIdGroupPairs': [],
u'IpRanges': [{u'CidrIp': u'10.42.1.0/24'}],
u'ToPort': 443}])
@functional
def test_cidr_ingress(self):
factory = self.replay_flight_data('test_security_group_cidr_ingress')
client = factory().client('ec2')
vpc_id = client.create_vpc(CidrBlock="10.42.0.0/16")['Vpc']['VpcId']
self.addCleanup(client.delete_vpc, VpcId=vpc_id)
sg_id = client.create_security_group(
GroupName="allow-https-ingress",
VpcId=vpc_id,
Description="inbound access")['GroupId']
self.addCleanup(client.delete_security_group, GroupId=sg_id)
client.authorize_security_group_ingress(
GroupId=sg_id,
IpPermissions=[{
'IpProtocol': 'tcp',
'FromPort': 443,
'ToPort': 443,
'IpRanges': [
{
'CidrIp': '10.42.1.0/24'
}]
}])
p = self.load_policy({
'name': 'ingress-access',
'resource': 'security-group',
'filters': [
{'type': 'ingress',
'Cidr': {
'value': '10.42.1.239',
'op': 'in',
'value_type': 'cidr'}}]
}, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(
len(resources[0].get('MatchedIpPermissions', [])), 1)
@functional
def test_cidr_size_egress(self):
factory = self.replay_flight_data('test_security_group_cidr_size')
client = factory().client('ec2')
vpc_id = client.create_vpc(CidrBlock="10.42.0.0/16")['Vpc']['VpcId']
self.addCleanup(client.delete_vpc, VpcId=vpc_id)
sg_id = client.create_security_group(
GroupName="wide-egress",
VpcId=vpc_id,
Description="unnecessarily large egress CIDR rule")['GroupId']
self.addCleanup(client.delete_security_group, GroupId=sg_id)
client.revoke_security_group_egress(
GroupId=sg_id,
IpPermissions=[
{'IpProtocol': '-1',
'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}])
client.authorize_security_group_egress(
GroupId=sg_id,
IpPermissions=[{
'IpProtocol': 'tcp',
'FromPort': 443,
'ToPort': 443,
'IpRanges': [
{'CidrIp': '10.42.0.0/16'},
{'CidrIp': '10.42.1.0/24'}]}])
p = self.load_policy({
'name': 'wide-egress',
'resource': 'security-group',
'filters': [
{'GroupName': 'wide-egress'},
{'type': 'egress',
'Cidr': {
'value': 24,
'op': 'lt',
'value_type': 'cidr_size'}}]
}, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(
len(resources[0].get('MatchedIpPermissionsEgress', [])), 1)
self.assertEqual(
resources[0]['MatchedIpPermissionsEgress'],
[{u'FromPort': 443,
u'IpProtocol': u'tcp',
u'Ipv6Ranges': [],
u'IpRanges': [
{u'CidrIp': u'10.42.0.0/16'}],
u'PrefixListIds': [],
u'ToPort': 443,
u'UserIdGroupPairs': []}])
def test_egress_validation_error(self):
self.assertRaises(
FilterValidationError,
self.load_policy,
{'name': 'sg-find2',
'resource': 'security-group',
'filters': [
{'type': 'egress',
'InvalidKey': True},
{'GroupName': 'sg2'}]})
def test_vpc_by_security_group(self):
factory = self.replay_flight_data('test_vpc_by_security_group')
p = self.load_policy(
{
'name': 'vpc-sg',
'resource': 'vpc',
'filters': [
{
'type': 'security-group',
'key': 'tag:Name',
'value': 'FancyTestGroupPublic',
},
],
},
session_factory=factory,
)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['Tags'][0]['Value'], 'FancyTestVPC')
| {
"content_hash": "384665481eb53d4d046a06fa0e9ea51f",
"timestamp": "",
"source": "github",
"line_count": 1068,
"max_line_length": 88,
"avg_line_length": 37.254681647940075,
"alnum_prop": 0.5050015079923595,
"repo_name": "VeritasOS/cloud-custodian",
"id": "e2edaf72885e738b370b45070ca047913ccbae65",
"size": "40373",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/test_vpc.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "1247"
},
{
"name": "Python",
"bytes": "1492218"
}
],
"symlink_target": ""
} |
import logging
import xbmc
import xbmcgui
import mythbox.msg as m
import mythbox.ui.toolkit as ui
import Queue
from datetime import datetime, timedelta
from mythbox.mythtv.conn import inject_conn
from mythbox.mythtv.db import inject_db
from mythbox.mythtv.domain import RecordingSchedule, Channel
from mythbox.mythtv.enums import Upcoming
from mythbox.ui.schedules import ScheduleDialog
from mythbox.ui.toolkit import Action, Align, AspectRatio, window_busy
from mythbox.util import catchall_ui, timed, catchall, ui_locked2, safe_str, run_async
from mythbox.bus import Event
log = logging.getLogger('mythbox.ui')
class ProgramCell(object):
def __init__(self, *args, **kwargs):
self.chanid = None # string
self.program = None # Program
self.nodata = None # boolean
self.starttime = None # ???
self.title = None # string
self.start = None # int - starting x coordinate
self.end = None # int - ending x coord
self.control = None # ControlButton
self.label = None # ControlLabel
self.hdOverlay = None # ControlImage
self.scheduleId = None # int
class ChannelCell(object):
def __init__(self, *args, **kwargs):
self.icon = None # ControlImage if channel has icon, otherwise None
self.label = None # ControlLabel of channel name and callsign
self.shade = None # ControlImage of background shade
class Pager(object):
def __init__(self, numChannels, channelsPerPage):
self.nc = numChannels
self.cpp = channelsPerPage
def pageUp(self, currentPosition):
pp = ((currentPosition // self.cpp) - 1)
if pp == -1:
pp = (self.nc // self.cpp)
if (pp * self.cpp) >= self.nc:
pp -=1
return pp * self.cpp
def pageDown(self, currentPosition):
np = (currentPosition // self.cpp) + 1
if np * self.cpp >= self.nc:
np = 0
return np * self.cpp
WIDTH_CHANNEL_ICON = 40
class TvGuideWindow(ui.BaseWindow):
"""
@todo: Don't re-render channels when scrolling page left/right
@todo: possible rendering optimizations - reuse widgets instead of creating them over and over
"""
def __init__(self, *args, **kwargs):
ui.BaseWindow.__init__(self, *args, **kwargs)
[setattr(self,k,v) for k,v in kwargs.iteritems() if k in ('settings','translator','platform','fanArt','cachesByName', 'bus')]
[setattr(self,k,v) for k,v in self.cachesByName.iteritems()]
self._upcomingByProgram = None
self._upcomingStale = True
# =============================================================
self.gridCells = [] # ProgramCell[] for grid of visible programs
self.startTime = None # datetime - start time for visibile grid
self.endTime = None # datetime - end time for visible grid
self.startChan = None # int - index into channels[] of starting channel in visible grid
self.endChan = None # int - index info channels[] of ending channel in visible grid
self.channelsPerPage = 8 # int - number of visible rows aka channels in grid
self.channels = None # Channel[] for all tuners
self.hoursPerPage = 2.0 # float - number of hours visible on grid
self.channelCells = [] # ChannelCell[] for column visible channels
self.timeLabels = [] # ControlLabel[] for row of visible time
self.topCtls = []
self.bottomCtls = []
self.leftCtls = []
self.rightCtls = []
self.prevFocus = None # gridCell.control aka button
self.prevButtonInfo = None # gridCell
self.pager = None # Pager
self.initialized = False
self.bannerQueue = Queue.Queue()
self.bus.register(self)
def onEvent(self, event):
if event['id'] == Event.SCHEDULER_RAN:
self._upcomingStale = True
def upcomingByProgram(self):
if self._upcomingStale:
self._upcomingStale = False
self._upcomingByProgram = {}
for p in self.domainCache.getUpcomingRecordings():
self._upcomingByProgram[p] = p
return self._upcomingByProgram
@catchall_ui
def onInit(self):
log.debug('onInit')
if self.win is None:
self.win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
self.workerBee()
self.loadGuide()
@catchall_ui
@timed
@inject_db
@inject_conn
def loadGuide(self):
"""
Method to load and display the tv guide information. If this is
the first time being called, it initializes the tv guide
parameters.
"""
log.debug('Loading tv guide..')
if self.prevFocus:
for c in self.gridCells:
if c.control == self.prevFocus:
self.prevButtonInfo = c
self.prevFocus = None
break
if not self.initialized:
self.channel_x = 60
self.channel_h = 40
self.channel_w = 340 - 120 + WIDTH_CHANNEL_ICON
self.channel_dx = 5
self.time_y = 140
self.time_h = 40
self.guide_x = 310
self.guide_dx = 12
self.guide_dy = 1
self.guide_y = self.time_y + self.time_h + self.guide_dy
self.guide_w = 1220 - 280
self.guide_h = 530 - 140 - self.time_h - self.guide_dy
# calculate pixels per hour used repeatedly
self.widthPerHour = self.guide_w / self.hoursPerPage
# calculate channels per page based on guide height
# self.channelsPerPage = int(self.guide_h / (self.guide_dy+self.channel_h) )
log.debug("channelSpan=%d" % self.channelsPerPage)
# allocate the remainder to vertical spacing between channels
# TODO: Fix gaps betweek rows:
#remainder = self.guide_h // (self.guide_dy+self.channel_h)
remainder = 0
log.debug('remainder = ' + str(remainder))
self.guide_dy += (remainder / self.channelsPerPage)
# retrieve, consolidate, and sort channels
self.channels = Channel.mergeChannels(self.domainCache.getChannels())
self.channels.sort(key=Channel.getSortableChannelNumber)
self.pager = Pager(len(self.channels), self.channelsPerPage)
self.setChannel(int(self.settings.get('tv_guide_last_selected')))
self.setTime(datetime.now() - timedelta(minutes=30))
self.initialized = True
self._render()
if not self.prevButtonInfo:
# set focus to the first control on the screen
if len(self.gridCells) > 0:
self.prevFocus = self.gridCells[0].control
self.setFocus(self.prevFocus)
else:
raise Exception, self.translator.get(m.NO_EPG_DATA)
@catchall_ui
def onAction(self, action):
log.debug('onAction %s', action.getId())
#log.debug('Key got hit: %s Current focus: %s' % (ui.toString(action), self.getFocusId()))
if not self.initialized:
return
ctl = None
try:
ctl = self.getFocus()
except:
pass
actionConsumed = False
if action.getId() in (Action.PREVIOUS_MENU, Action.PARENT_DIR):
self.closed = True
self.settings.put('tv_guide_last_selected', '%s' % self.startChan)
self.bus.deregister(self)
self.close()
elif action == Action.DOWN : actionConsumed = self._checkPageDown(self.prevFocus)
elif action == Action.UP : actionConsumed = self._checkPageUp(self.prevFocus)
elif action == Action.LEFT : actionConsumed = self._checkPageLeft(self.prevFocus)
elif action == Action.RIGHT : actionConsumed = self._checkPageRight(self.prevFocus)
elif action == Action.PAGE_UP : self.scrollPreviousPage(); actionConsumed = True
elif action == Action.PAGE_DOWN : self.scrollNextPage(); actionConsumed = True
elif action == Action.FORWARD : self.scrollRightPage(); actionConsumed = True # F on keyboard
elif action == Action.REWIND : self.scrollLeftPage(); actionConsumed = True # R on keyboard
elif action == Action.SELECT_ITEM: self.onControlHook(ctl)
else: log.debug('Unconsumed key: %s' % action.getId())
if not actionConsumed and ctl:
self.prevFocus = ctl
def scrollPreviousPage(self):
log.debug('scrollPreviousPage')
self.setChannel(self.pager.pageUp(self.startChan))
self.loadGuide()
#self.prevFocus = self.gridCells[0].control
self.setFocus(self.gridCells[0].control)
def scrollNextPage(self):
log.debug('scrollNextPage')
self.setChannel(self.pager.pageDown(self.startChan))
self.loadGuide()
#self.prevFocus = self.gridCells[0].control
self.setFocus(self.gridCells[0].control)
def scrollRightPage(self, focusTopLeft=True):
log.debug('scrollRightPage')
self.setTime(self.startTime + timedelta(hours=self.hoursPerPage))
self.loadGuide()
if focusTopLeft:
self.setFocus(self.gridCells[0].control)
def scrollLeftPage(self, focusTopLeft=True):
log.debug('scrollLeftPage')
self.setTime(self.startTime - timedelta(hours=self.hoursPerPage))
self.loadGuide()
if focusTopLeft:
self.setFocus(self.gridCells[0].control)
@catchall
def onFocus(self, controlId):
log.debug('onFocus')
if not self.initialized:
return
log.debug('lastfocusid = %s' % controlId)
self.lastFocusId = controlId
try:
control = self.getControl(controlId)
if isinstance(control, xbmcgui.ControlButton):
#if self.cellsByButton.has_key(control):
matches = filter(lambda c: c.control == control, self.gridCells)
#cell = self.cellsByButton[control]
if matches:
self.renderProgramInfo(matches[0].program)
except TypeError, te:
if 'Non-Existent Control' in str(te):
log.warn('onFocus: ' + str(te))
else:
raise
@ui_locked2
def renderProgramInfo(self, program):
if program:
log.debug('Show info for ' + safe_str(program.title()))
self.setWindowProperty('title', program.fullTitle())
self.setWindowProperty('category', program.category())
self.setWindowProperty('description', program.description())
self.setWindowProperty('subtitle', program.subtitle())
self.setWindowProperty('airtime', program.formattedAirTime())
self.setWindowProperty('duration', program.formattedDuration())
self.setWindowProperty('originalAirDate', program.formattedOriginalAirDate())
season, episode = self.fanArt.getSeasonAndEpisode(program)
if not season is None and not episode is None:
self.setWindowProperty('seasonAndEpisode', '%sx%s' % (season, episode))
else:
self.setWindowProperty('seasonAndEpisode', '-')
self.setWindowProperty('banner', u'')
if self.fanArt.hasBanners(program):
bannerPath = self.fanArt.pickBanner(program)
self.setWindowProperty('banner', [u'',bannerPath][bannerPath is not None])
else:
log.debug('Added to bannerqueue: %s' % safe_str(program.title()))
self.bannerQueue.put(program)
else:
self.setWindowProperty('title', u'')
self.setWindowProperty('category', u'')
self.setWindowProperty('description', u'')
self.setWindowProperty('subtitle', u'')
self.setWindowProperty('airtime', u'')
self.setWindowProperty('duration', u'')
self.setWindowProperty('originalAirDate', u'')
self.setWindowProperty('banner', u'')
self.setWindowProperty('seasonAndEpisode', u'')
@run_async
def workerBee(self):
while not self.closed and not xbmc.abortRequested:
try:
if not self.bannerQueue.empty():
log.debug('Banner queue size: %d' % self.bannerQueue.qsize())
program = self.bannerQueue.get(block=True, timeout=1)
bannerPath = self.fanArt.pickBanner(program)
log.debug('workerBee resolved %s to %s' % (safe_str(program.title()), bannerPath))
except Queue.Empty:
pass
@window_busy
@inject_conn
def watchLiveTv(self, program):
if not self.conn().protocol.supportsStreaming(self.platform):
xbmcgui.Dialog().ok(self.translator.get(m.ERROR),
'Watching Live TV is currently not supported',
'with your configuration of MythTV %s and' % self.conn().protocol.mythVersion(),
'XBMC %s. Should be working in XBMC 11.0+' % self.platform.xbmcVersion())
return
channel = filter(lambda c: c.getChannelId() == program.getChannelId(), self.channels).pop()
brain = self.conn().protocol.getLiveTvBrain(self.settings, self.translator)
try:
brain.watchLiveTV(channel)
except Exception, e:
log.exception(e)
xbmcgui.Dialog().ok(self.translator.get(m.ERROR), '', str(e))
@catchall_ui
@inject_db
def onControlHook(self, control):
actionConsumed = True
id = control.getId()
program = None
for c in self.gridCells:
if c.control == control:
program = c.program
break
if program:
if program.isShowing():
log.debug('launching livetv')
self.watchLiveTv(program)
else:
log.debug('launching edit schedule dialog')
# scheduled recording
if c.scheduleId:
schedule = self.db().getRecordingSchedules(scheduleId=c.scheduleId).pop()
# not scheduled but happens to have an existing recording schedule
schedule = self.scheduleForTitle(program)
# new recording schedule
if schedule is None:
schedule = RecordingSchedule.fromProgram(program, self.translator)
d = ScheduleDialog(
'mythbox_schedule_dialog.xml',
self.platform.getScriptDir(),
forceFallback=True,
schedule=schedule,
translator=self.translator,
platform=self.platform,
settings=self.settings,
mythChannelIconCache=self.mythChannelIconCache)
d.doModal()
return actionConsumed
def scheduleForTitle(self, program):
for schedule in self.domainCache.getRecordingSchedules():
if schedule.title() == program.title():
return schedule
return None
def _addGridCell(self, program, cell, relX, relY, width, height):
"""
Adds a control (button overlayed with a label) for a program in the guide
@param program: Program
@param cell: dict with keys ('chanid')
@param relX: relative x position as int
@param relY: relative y position as int
@return: ControlLabel created for the passed in program and cell.
@postcondition: cell[] keys are
'chanid' is ???,
'program' is Program,
'nodata' is boolean,
'starttime' is ???,
'title' is string,
'start' is int starting x coord,
'end' is int ending x coord,
'control' is ControlButton,
'label' is ControlLabel
"""
cell.program = program
if program is None:
cell.nodata = True
cell.starttime = None
cell.title = self.translator.get(m.NO_DATA)
category = None
else:
cell.nodata = False
cell.starttime = program.starttime()
cell.title = program.title()
category = program.category()
cell.start = relX
cell.end = relX + width
# Create a button for navigation and hilighting. For some reason, button labels don't get truncated properly.
cell.control = xbmcgui.ControlButton(
int(relX + self.guide_x),
int(relY + self.guide_y),
int(width-2), # hack for cell dividers
int(height),
label='', # Text empty on purpose. Label overlay responsible for this
focusTexture=self.platform.getMediaPath('gradient_cell.png'),
noFocusTexture=self.platform.getMediaPath('gradient_grid.png'),
alignment=Align.CENTER_Y|Align.TRUNCATED)
if program in self.upcomingByProgram():
cell.title = '[B][COLOR=ffe2ff43]' + cell.title + '[/COLOR][/B]'
cell.scheduleId = self.upcomingByProgram()[program].getScheduleId()
# Create a label to hold the name of the program with insets
# Label text seems to get truncated correctly...
cell.label = xbmcgui.ControlLabel(
int(relX + self.guide_x + 12), # indent 12 px for bumper
int(relY + self.guide_y),
int(width - 12 - 12), # reverse-indent 12px for bumper
int(height),
cell.title,
font='font11',
alignment=Align.CENTER_Y|Align.TRUNCATED)
self.addControl(cell.control)
self.addControl(cell.label)
if program and program.isHD() and width > 50:
overlayWidth = 40
overlayHeight = 15
cell.hdOverlay = xbmcgui.ControlImage(
int(relX + self.guide_x + width - overlayWidth - 5),
int(relY + self.guide_y + 2),
overlayWidth,
overlayHeight,
self.platform.getMediaPath('OverlayHD.png'),
aspectRatio=1)
self.addControl(cell.hdOverlay)
self.gridCells.append(cell)
def _checkPageUp(self, focusControl):
paged = False
if focusControl in self.topCtls:
log.debug('page up detected')
paged = True
self.scrollPreviousPage()
# check if we need to fix focus
if not self.prevFocus:
# find the control in the bottom row where previous button's
# start falls within start/end range of control
chanid = self.gridCells[-1].chanid
start = self.prevButtonInfo.start
for c in reversed(self.gridCells):
if chanid == c.chanid:
if start >= c.start and start < c.end:
self.prevFocus = c.control
self.setFocus(self.prevFocus)
break
else:
break
return paged
def _checkPageDown(self, focusControl):
paged = False
if focusControl in self.bottomCtls:
log.debug('page down detected')
paged = True
self.scrollNextPage()
# check if we need to fix focus
if not self.prevFocus:
# find the control in the top row where previous button's start
# falls within start/end range of control
chanid = self.gridCells[0].chanid
start = self.prevButtonInfo.start
for c in self.gridCells:
if chanid == c.chanid:
if start >= c.start and start < c.end:
self.prevFocus = c.control
self.setFocus(self.prevFocus)
break
else:
break
return paged
def _checkPageLeft(self, focusControl):
paged = False
if focusControl in self.leftCtls:
log.debug("page left detected")
paged = True
self.scrollLeftPage(focusTopLeft=False)
# check if we need to fix focus
if not self.prevFocus:
chanid = self.prevButtonInfo.chanid
found = False
prev = None
# find the right most program on the same channel
for c in self.gridCells:
if not found and c.chanid == chanid:
found = True
elif found and c.chanid != chanid:
break
prev = c
self.prevFocus = prev.control
self.setFocus(self.prevFocus)
self.prevButtonInfo = None
return paged
def _checkPageRight(self, focusControl):
paged = False
if focusControl in self.rightCtls:
log.debug('page right detected')
paged = True
self.scrollRightPage(focusTopLeft=False)
# check if we need to fix focus
if not self.prevFocus:
chanid = self.prevButtonInfo.chanid
found = False
prev = None
# find the left most program on the same channel
for c in reversed(self.gridCells):
if not found and c.chanid == chanid:
found = True
elif found and c.chanid != chanid:
break
prev = c
self.prevFocus = prev.control
self.setFocus(self.prevFocus)
self.prevButtonInfo = None
return paged
def _doNavigation(self):
"""
Method to do navigation between controls and store lists of top,
bottom, left, and right controls to detect when page changes must
occur.
"""
count = 0
self.topCtls = []
self.bottomCtls = []
self.leftCtls = []
self.rightCtls = []
topChanId = None
prevChanId = None
prevCtl = None
#
# Loop through all buttons doing left to right, right to left, and
# top to bottom navigation. Also keep track of top, left, and right
# controls that are used to detect page up, left, and right.
#
log.debug('Gridcell cnt1 = %s' % len(self.gridCells))
for c in self.gridCells:
#log.debug("title=%s"%c.title)
if not topChanId:
topChanId = c.chanid
if c.chanid == topChanId:
# first row of controls are top controls
self.topCtls.append(c.control)
#log.debug("top ctl=%s"%c.control)
# do left to right and right to left navigation
if not prevChanId:
prevChanId = c.chanid
elif prevChanId != c.chanid:
# changed channel rows so previous control is a control on right edge
self.rightCtls.append(prevCtl)
prevCtl = None
prevChanId = c.chanid
if prevCtl:
prevCtl.controlRight(c.control)
c.control.controlLeft(prevCtl)
prevCtl = c.control
if not prevCtl:
# control not set so this must be a control on left edge
self.leftCtls.append(c.control)
prevCtl = c.control
# now find the appropriate control below current one
chanid = None
found = False
for c2 in self.gridCells:
if not found and c2.control == c.control:
found = True
elif found and not chanid and c2.chanid != c.chanid:
chanid = c2.chanid
if found and chanid and chanid == c2.chanid:
if c.start >= c2.start and c.start < c2.end:
c.control.controlDown(c2.control)
#log.debug("%s VVV %s"%(c.title, c2.title))
count += 1
break
elif found and chanid and chanid != c2.chanid:
break
log.debug("down count=%d"%count)
count = 0
log.debug('Gridcell cnt2 = %s' % len(self.gridCells))
#cells = list(self.gridCells)
#cells = cells.reverse()
bottomChanId = None
#log.debug('Gridcell cnt3 = %s' % len(cells))
#
# Loop through all buttons in reverse to do bottom to top navigation.
#
for c in reversed(self.gridCells):
#log.debug("title=%s"%c.title)
if not bottomChanId:
bottomChanId = c.chanid
if c.chanid == bottomChanId:
# first row of controls are bottom controls
self.bottomCtls.append(c.control)
#log.debug("bottom ctl=%s"%c.control)
# now find the control that is above the current one
chanid = None
found = False
for c2 in reversed(self.gridCells):
if not found and c2.control == c.control:
found = True
elif found and not chanid and c2.chanid != c.chanid:
chanid = c2.chanid
if found and chanid and chanid == c2.chanid:
if c.start >= c2.start and c.start < c2.end:
c.control.controlUp(c2.control)
#log.debug("%s ^^^ %s"%(c.title, c2.title))
count += 1
break
elif found and chanid and chanid != c2.chanid:
break
log.debug( "up count=%d"%count )
# if we have any controls, then the very last control on right edge
# was missed in first loop (right controls are detected by row changes
# but the last row quits the loop before detecting the control)
if len(self.gridCells) > 0:
# Note: This grabs last control from the reverse list of controls.
self.rightCtls.append(self.gridCells[-1].control)
#log.debug("right ctl=%s"%cells[0].control)
log.debug("top count = %d" % len(self.topCtls))
log.debug("bottom count = %d" % len(self.bottomCtls))
log.debug("left count = %d" % len(self.leftCtls))
log.debug("right count = %d" % len(self.rightCtls))
@ui_locked2
def _render(self):
"""
Method to draw all the dynamic controls that represent the program
guide information.
"""
self.renderChannels()
self.renderHeader()
self._renderPrograms()
self._doNavigation()
def renderChannels(self):
# deallocate current channel cells
for c in self.channelCells:
if c.icon: self.removeControl(c.icon)
if c.label: self.removeControl(c.label)
if c.shade: self.removeControl(c.shade)
del c
self.channelCells = []
x = self.channel_x
y = self.guide_y
h = (self.guide_h - self.channelsPerPage * self.guide_dy) / self.channelsPerPage
iconW = h
labelW = self.channel_w - iconW - self.guide_dx
for i in range(self.startChan, self.endChan + 1):
c = ChannelCell()
# create shade image around channel label/icon
#c.shade = xbmcgui.ControlImage(
# x,
# y,
# self.channel_w,
# h,
# "shade_50.png")
#
#self.addControl(c.shade)
# create label control
labelText = '%s %s' % (self.channels[i].getChannelNumber(), '') # self.channels[i].getCallSign())
label2Text = '%s' % self.channels[i].getCallSign()
#label2Text = "%s" % self.channels[i].getChannelName()
c.label = xbmcgui.ControlButton(
x + iconW + self.channel_dx,
y,
labelW, # hack for cell dividers
h,
label=labelText, # Text empty on purpose. Label overlay responsible for this
#focusTexture=self.platform.getMediaPath('gradient_maroon.png'),
noFocusTexture=self.platform.getMediaPath('gradient_channel.png'),
#textXOffset=2,
#textYOffset=0,
alignment=Align.CENTER_Y|Align.TRUNCATED)
c.label.setLabel(label=labelText, label2=label2Text)
self.addControl(c.label)
# create channel icon image if icon exists
try:
if self.channels[i].getIconPath():
iconFile = self.mythChannelIconCache.get(self.channels[i])
if iconFile:
hackW = iconW * 2
c.icon = xbmcgui.ControlImage(x + self.channel_w - hackW - 15, y, hackW, h, iconFile, AspectRatio.SCALE_DOWN)
c.label.setLabel(label=labelText, label2='')
self.addControl(c.icon)
except:
log.exception('channel = %s' % self.channels[i])
self.channelCells.append(c)
y += h + self.guide_dy
@timed
@inject_db
def _renderPrograms(self):
"""
Method to draw the program buttons. Also manufactures buttons for missing guide data.
"""
programs = self.db().getTVGuideDataFlattened(self.startTime, self.endTime, self.channels[self.startChan : self.endChan + 1])
log.debug("Num programs = %s" % len(programs))
# dealloc existing grid cells...
for cell in self.gridCells:
self.removeControl(cell.control)
del cell.control
self.removeControl(cell.label)
del cell.label
if cell.hdOverlay:
self.removeControl(cell.hdOverlay)
del cell
self.gridCells = []
self.widthPerHour = self.guide_w / self.hoursPerPage
chanH = (self.guide_h - self.channelsPerPage * self.guide_dy) / self.channelsPerPage
# Loop through each channel filling the tv guide area with cells.
for i in range(self.startChan, self.endChan + 1):
noData = False
chanX = 0
chanY = (i - self.startChan) * (chanH + self.guide_dy)
chanid = self.channels[i].getChannelId()
# loop until we've filled the row for the channel
while chanX < self.guide_w:
cell = ProgramCell()
cell.chanid = chanid
p = None
if not noData:
# find the next program for the channel - this assumes
# programs are sorted in ascending time order for the channel
for prog in programs:
if prog.getChannelId() == chanid:
p = prog
programs.remove(prog)
break
if not p:
# no program found - create a no data control for the rest of the row
noData = True
w = self.guide_w - chanX
self._addGridCell(
program=None,
cell=cell,
relX=chanX,
relY=chanY,
width=w,
height=chanH)
chanX += w
else:
# found a program but we don't know if it starts at the current spot in the row for the channel
# trunc start time
start = p.starttimeAsTime()
if start < self.startTime:
start = self.startTime
# trunc end time
end = p.endtimeAsTime()
if end > self.endTime:
end = self.endTime
# calculate x coord and width of label
start = start - self.startTime
progX = start.seconds / (60.0*60.0) * self.widthPerHour
end = end - self.startTime
progEndX = end.seconds / (60.0*60.0) * self.widthPerHour
progW = progEndX - progX
#log.debug("cell startx=%s endx=%s"%(start,end))
# check if we need a 'No data' spacer before this cell
if progX != chanX:
self._addGridCell(
program=None,
cell=cell, # TODO: Doesn't make sense why setting info for 'no data' cell to cell
relX=chanX,
relY=chanY,
width=(progX - chanX),
height=chanH)
chanX = progX
cell = ProgramCell()
cell.chanid = chanid
# add the control for the program
self._addGridCell(
program=p,
cell=cell,
relX=progX,
relY=chanY,
width=progW,
height=chanH)
chanX += progW
def renderHeader(self):
numCols = int(self.hoursPerPage * 2)
x = self.guide_x
y = self.time_y
h = self.time_h
w = (self.guide_w - numCols * self.guide_dx) / numCols
t = self.startTime
lastDay = t.day
i = 0
log.debug("numCols=%d guide_w=%d"%(numCols, self.guide_w))
if len(self.timeLabels) == 0:
c = xbmcgui.ControlButton(
self.channel_x + self.channel_dx + WIDTH_CHANNEL_ICON + 2,
y,
self.channel_w - self.channel_dx - WIDTH_CHANNEL_ICON - 14,
h,
label='',
font='font13',
noFocusTexture=self.platform.getMediaPath('gradient_header.png'))
self.timeLabels.append(c)
self.addControl(c)
for i in xrange(numCols):
c = xbmcgui.ControlButton(
x, y, w+10, h, label='',
font='font13',
noFocusTexture=self.platform.getMediaPath('gradient_header.png'))
self.timeLabels.append(c)
self.addControl(c)
x = x + w + self.guide_dx
for i,c in enumerate(self.timeLabels):
if i == 0:
c.setLabel(label='', label2=t.strftime('%a %m/%d'))
else:
label = ('%d' % int(t.strftime('%I'))) + t.strftime(':%M %p')
if t.day != lastDay:
label += '+1'
t += timedelta(minutes=30)
lastDay = t.day
c.setLabel(label)
def setTime(self, startTime):
"""
Method to change the starting time of the tv guide. This is used
to change pages horizontally.
"""
self.startTime = startTime - timedelta(seconds=startTime.second, microseconds=startTime.microsecond)
min = self.startTime.minute
if min != 0:
if min > 30:
delta = 60 - min
else:
delta = 30 - min
self.startTime = self.startTime + timedelta(minutes=delta)
self.endTime = self.startTime + timedelta(hours=self.hoursPerPage)
log.debug("startTime = %s endTime = %s" % (self.startTime, self.endTime))
def setChannel(self, chanIndex):
"""
Method to change the starting channel index of the tv guide.
This is used to change pages vertically.
"""
self.startChan = chanIndex
if self.startChan < 0 or self.startChan > len(self.channels)-1:
self.startChan = 0
self.endChan = self.startChan + self.channelsPerPage - 1
if self.endChan > len(self.channels)-1:
self.endChan = len(self.channels)-1
log.debug("start channels[%d] = %s" % (self.startChan, self.channels[self.startChan].getChannelNumber()))
log.debug("end channels[%d] = %s" % (self.endChan, self.channels[self.endChan].getChannelNumber()))
| {
"content_hash": "a07603778f6e7408f4061ef2163970d2",
"timestamp": "",
"source": "github",
"line_count": 951,
"max_line_length": 133,
"avg_line_length": 39.83701366982124,
"alnum_prop": 0.5291804144120364,
"repo_name": "GetSomeBlocks/Score_Soccer",
"id": "63314c499582d6eb1353d90a069cdb5c72798288",
"size": "38902",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "resources/src/mythbox/ui/tvguide.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "930"
},
{
"name": "C",
"bytes": "293000"
},
{
"name": "C#",
"bytes": "9664"
},
{
"name": "CSS",
"bytes": "24716"
},
{
"name": "D",
"bytes": "542"
},
{
"name": "HTML",
"bytes": "374176"
},
{
"name": "Java",
"bytes": "206"
},
{
"name": "Objective-C",
"bytes": "9421"
},
{
"name": "Python",
"bytes": "8744725"
},
{
"name": "Ruby",
"bytes": "6773"
},
{
"name": "Shell",
"bytes": "13600"
}
],
"symlink_target": ""
} |
from runner.koan import *
class AboutDeletingObjects(Koan):
def test_del_can_remove_slices(self):
lottery_nums = [4, 8, 15, 16, 23, 42]
del lottery_nums[1]
del lottery_nums[2:4]
self.assertEqual([4, 15, 42], lottery_nums)
def test_del_can_remove_entire_lists(self):
lottery_nums = [4, 8, 15, 16, 23, 42]
del lottery_nums
with self.assertRaises(NameError): win = lottery_nums
# ====================================================================
class ClosingSale:
def __init__(self):
self.hamsters = 7
self.zebras = 84
def cameras(self):
return 34
def toilet_brushes(self):
return 48
def jellies(self):
return 5
def test_del_can_remove_attributes(self):
crazy_discounts = self.ClosingSale()
del self.ClosingSale.toilet_brushes
del crazy_discounts.hamsters
try:
still_available = crazy_discounts.toilet_brushes()
except AttributeError as e:
err_msg1 = e.args[0]
try:
still_available = crazy_discounts.hamsters
except AttributeError as e:
err_msg2 = e.args[0]
self.assertRegexpMatches(err_msg1, "'ClosingSale' object has no attribute 'toilet_brushes'")
self.assertRegexpMatches(err_msg2, "'ClosingSale' object has no attribute 'hamsters'")
# ====================================================================
class ClintEastwood:
def __init__(self):
self._name = None
def get_name(self):
try:
return self._name
except:
return "The man with no name"
def set_name(self, name):
self._name = name
def del_name(self):
del self._name
name = property(get_name, set_name, del_name, \
"Mr Eastwood's current alias")
def test_del_works_with_properties(self):
cowboy = self.ClintEastwood()
cowboy.name = 'Senor Ninguno'
self.assertEqual('Senor Ninguno', cowboy.name)
del cowboy.name
self.assertEqual('The man with no name', cowboy.name)
# ====================================================================
class Prisoner:
def __init__(self):
self._name = None
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
@name.deleter
def name(self):
self._name = 'Number Six'
def test_another_way_to_make_a_deletable_property(self):
citizen = self.Prisoner()
citizen.name = "Patrick"
self.assertEqual('Patrick', citizen.name)
del citizen.name
self.assertEqual("Number Six", citizen.name)
# ====================================================================
class MoreOrganisedClosingSale(ClosingSale):
def __init__(self):
self.last_deletion = None
super().__init__()
def __delattr__(self, attr_name):
self.last_deletion = attr_name
def tests_del_can_be_overriden(self):
sale = self.MoreOrganisedClosingSale()
self.assertEqual(5, sale.jellies())
del sale.jellies
self.assertEqual('jellies', sale.last_deletion)
| {
"content_hash": "31dd4d654ca921b768b473da8922bee0",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 100,
"avg_line_length": 28.181818181818183,
"alnum_prop": 0.5181818181818182,
"repo_name": "ahartz1/python_koans",
"id": "74c52eecf18872fe121a886ca61d3058b7f830aa",
"size": "3457",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "python3/koans/about_deleting_objects.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1633"
},
{
"name": "Python",
"bytes": "333209"
},
{
"name": "Shell",
"bytes": "167"
}
],
"symlink_target": ""
} |
import numbers
from typing import Any, Union
import pandas as pd
from pandas.api.types import CategoricalDtype
from pyspark.pandas.base import column_op, IndexOpsMixin
from pyspark.pandas._typing import Dtype, IndexOpsLike, SeriesOrIndex
from pyspark.pandas.data_type_ops.base import (
DataTypeOps,
is_valid_operand_for_numeric_arithmetic,
transform_boolean_operand_to_numeric,
_as_bool_type,
_as_categorical_type,
_as_other_type,
_sanitize_list_like,
)
from pyspark.pandas.spark import functions as SF
from pyspark.pandas.typedef.typehints import as_spark_type, extension_dtypes, pandas_on_spark_type
from pyspark.sql import functions as F
from pyspark.sql.column import Column
from pyspark.sql.types import BooleanType, StringType
class BooleanOps(DataTypeOps):
"""
The class for binary operations of pandas-on-Spark objects with spark type: BooleanType.
"""
@property
def pretty_name(self) -> str:
return "bools"
def add(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
if not is_valid_operand_for_numeric_arithmetic(right):
raise TypeError(
"Addition can not be applied to %s and the given type." % self.pretty_name
)
if isinstance(right, bool):
return left.__or__(right)
elif isinstance(right, numbers.Number):
left = transform_boolean_operand_to_numeric(left, spark_type=as_spark_type(type(right)))
return left + right
else:
assert isinstance(right, IndexOpsMixin)
if isinstance(right, IndexOpsMixin) and isinstance(right.spark.data_type, BooleanType):
return left.__or__(right)
else:
left = transform_boolean_operand_to_numeric(left, spark_type=right.spark.data_type)
return left + right
def sub(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
if not is_valid_operand_for_numeric_arithmetic(right, allow_bool=False):
raise TypeError(
"Subtraction can not be applied to %s and the given type." % self.pretty_name
)
if isinstance(right, numbers.Number):
left = transform_boolean_operand_to_numeric(left, spark_type=as_spark_type(type(right)))
return left - right
else:
assert isinstance(right, IndexOpsMixin)
left = transform_boolean_operand_to_numeric(left, spark_type=right.spark.data_type)
return left - right
def mul(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
if not is_valid_operand_for_numeric_arithmetic(right):
raise TypeError(
"Multiplication can not be applied to %s and the given type." % self.pretty_name
)
if isinstance(right, bool):
return left.__and__(right)
elif isinstance(right, numbers.Number):
left = transform_boolean_operand_to_numeric(left, spark_type=as_spark_type(type(right)))
return left * right
else:
assert isinstance(right, IndexOpsMixin)
if isinstance(right, IndexOpsMixin) and isinstance(right.spark.data_type, BooleanType):
return left.__and__(right)
else:
left = transform_boolean_operand_to_numeric(left, spark_type=right.spark.data_type)
return left * right
def truediv(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
if not is_valid_operand_for_numeric_arithmetic(right, allow_bool=False):
raise TypeError(
"True division can not be applied to %s and the given type." % self.pretty_name
)
if isinstance(right, numbers.Number):
left = transform_boolean_operand_to_numeric(left, spark_type=as_spark_type(type(right)))
return left / right
else:
assert isinstance(right, IndexOpsMixin)
left = transform_boolean_operand_to_numeric(left, spark_type=right.spark.data_type)
return left / right
def floordiv(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
if not is_valid_operand_for_numeric_arithmetic(right, allow_bool=False):
raise TypeError(
"Floor division can not be applied to %s and the given type." % self.pretty_name
)
if isinstance(right, numbers.Number):
left = transform_boolean_operand_to_numeric(left, spark_type=as_spark_type(type(right)))
return left // right
else:
assert isinstance(right, IndexOpsMixin)
left = transform_boolean_operand_to_numeric(left, spark_type=right.spark.data_type)
return left // right
def mod(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
if not is_valid_operand_for_numeric_arithmetic(right, allow_bool=False):
raise TypeError(
"Modulo can not be applied to %s and the given type." % self.pretty_name
)
if isinstance(right, numbers.Number):
left = transform_boolean_operand_to_numeric(left, spark_type=as_spark_type(type(right)))
return left % right
else:
assert isinstance(right, IndexOpsMixin)
left = transform_boolean_operand_to_numeric(left, spark_type=right.spark.data_type)
return left % right
def pow(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
if not is_valid_operand_for_numeric_arithmetic(right, allow_bool=False):
raise TypeError(
"Exponentiation can not be applied to %s and the given type." % self.pretty_name
)
if isinstance(right, numbers.Number):
left = transform_boolean_operand_to_numeric(left, spark_type=as_spark_type(type(right)))
return left ** right
else:
assert isinstance(right, IndexOpsMixin)
left = transform_boolean_operand_to_numeric(left, spark_type=right.spark.data_type)
return left ** right
def radd(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
if isinstance(right, bool):
return left.__or__(right)
elif isinstance(right, numbers.Number):
left = transform_boolean_operand_to_numeric(left, spark_type=as_spark_type(type(right)))
return right + left
else:
raise TypeError(
"Addition can not be applied to %s and the given type." % self.pretty_name
)
def rsub(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
if isinstance(right, numbers.Number) and not isinstance(right, bool):
left = transform_boolean_operand_to_numeric(left, spark_type=as_spark_type(type(right)))
return right - left
else:
raise TypeError(
"Subtraction can not be applied to %s and the given type." % self.pretty_name
)
def rmul(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
if isinstance(right, bool):
return left.__and__(right)
elif isinstance(right, numbers.Number):
left = transform_boolean_operand_to_numeric(left, spark_type=as_spark_type(type(right)))
return right * left
else:
raise TypeError(
"Multiplication can not be applied to %s and the given type." % self.pretty_name
)
def rtruediv(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
if isinstance(right, numbers.Number) and not isinstance(right, bool):
left = transform_boolean_operand_to_numeric(left, spark_type=as_spark_type(type(right)))
return right / left
else:
raise TypeError(
"True division can not be applied to %s and the given type." % self.pretty_name
)
def rfloordiv(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
if isinstance(right, numbers.Number) and not isinstance(right, bool):
left = transform_boolean_operand_to_numeric(left, spark_type=as_spark_type(type(right)))
return right // left
else:
raise TypeError(
"Floor division can not be applied to %s and the given type." % self.pretty_name
)
def rpow(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
if isinstance(right, numbers.Number) and not isinstance(right, bool):
left = transform_boolean_operand_to_numeric(left, spark_type=as_spark_type(type(right)))
return right ** left
else:
raise TypeError(
"Exponentiation can not be applied to %s and the given type." % self.pretty_name
)
def rmod(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
if isinstance(right, numbers.Number) and not isinstance(right, bool):
left = transform_boolean_operand_to_numeric(left, spark_type=as_spark_type(type(right)))
return right % left
else:
raise TypeError(
"Modulo can not be applied to %s and the given type." % self.pretty_name
)
def __and__(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
if isinstance(right, IndexOpsMixin) and isinstance(right.dtype, extension_dtypes):
return right.__and__(left)
else:
def and_func(left: Column, right: Any) -> Column:
if not isinstance(right, Column):
if pd.isna(right):
right = SF.lit(None)
else:
right = SF.lit(right)
scol = left & right
return F.when(scol.isNull(), False).otherwise(scol)
return column_op(and_func)(left, right)
def __or__(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
if isinstance(right, IndexOpsMixin) and isinstance(right.dtype, extension_dtypes):
return right.__or__(left)
else:
def or_func(left: Column, right: Any) -> Column:
if not isinstance(right, Column) and pd.isna(right):
return SF.lit(False)
else:
scol = left | SF.lit(right)
return F.when(left.isNull() | scol.isNull(), False).otherwise(scol)
return column_op(or_func)(left, right)
def astype(self, index_ops: IndexOpsLike, dtype: Union[str, type, Dtype]) -> IndexOpsLike:
dtype, spark_type = pandas_on_spark_type(dtype)
if isinstance(dtype, CategoricalDtype):
return _as_categorical_type(index_ops, dtype, spark_type)
elif isinstance(spark_type, BooleanType):
return _as_bool_type(index_ops, dtype)
elif isinstance(spark_type, StringType):
if isinstance(dtype, extension_dtypes):
scol = F.when(
index_ops.spark.column.isNotNull(),
F.when(index_ops.spark.column, "True").otherwise("False"),
)
nullable = index_ops.spark.nullable
else:
null_str = str(pd.NA) if isinstance(self, BooleanExtensionOps) else str(None)
casted = F.when(index_ops.spark.column, "True").otherwise("False")
scol = F.when(index_ops.spark.column.isNull(), null_str).otherwise(casted)
nullable = False
return index_ops._with_new_scol(
scol,
field=index_ops._internal.data_fields[0].copy(
dtype=dtype, spark_type=spark_type, nullable=nullable
),
)
else:
return _as_other_type(index_ops, dtype, spark_type)
def neg(self, operand: IndexOpsLike) -> IndexOpsLike:
return ~operand
def abs(self, operand: IndexOpsLike) -> IndexOpsLike:
return operand
def lt(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
return column_op(Column.__lt__)(left, right)
def le(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
return column_op(Column.__le__)(left, right)
def ge(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
return column_op(Column.__ge__)(left, right)
def gt(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
return column_op(Column.__gt__)(left, right)
def invert(self, operand: IndexOpsLike) -> IndexOpsLike:
return operand._with_new_scol(~operand.spark.column, field=operand._internal.data_fields[0])
class BooleanExtensionOps(BooleanOps):
"""
The class for binary operations of pandas-on-Spark objects with spark type BooleanType,
and dtype BooleanDtype.
"""
@property
def pretty_name(self) -> str:
return "booleans"
def __and__(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
def and_func(left: Column, right: Any) -> Column:
if not isinstance(right, Column):
if pd.isna(right):
right = SF.lit(None)
else:
right = SF.lit(right)
return left & right
return column_op(and_func)(left, right)
def __or__(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
def or_func(left: Column, right: Any) -> Column:
if not isinstance(right, Column):
if pd.isna(right):
right = SF.lit(None)
else:
right = SF.lit(right)
return left | right
return column_op(or_func)(left, right)
def restore(self, col: pd.Series) -> pd.Series:
"""Restore column when to_pandas."""
return col.astype(self.dtype)
def neg(self, operand: IndexOpsLike) -> IndexOpsLike:
raise TypeError("Unary - can not be applied to %s." % self.pretty_name)
def invert(self, operand: IndexOpsLike) -> IndexOpsLike:
raise TypeError("Unary ~ can not be applied to %s." % self.pretty_name)
def abs(self, operand: IndexOpsLike) -> IndexOpsLike:
raise TypeError("abs() can not be applied to %s." % self.pretty_name)
| {
"content_hash": "6380148a0ef5e9c8f3c2bec5c0f5751e",
"timestamp": "",
"source": "github",
"line_count": 350,
"max_line_length": 100,
"avg_line_length": 42.745714285714286,
"alnum_prop": 0.6058418554909432,
"repo_name": "jiangxb1987/spark",
"id": "cb7794531de085fcfd5073666414b3d298a46530",
"size": "15746",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "python/pyspark/pandas/data_type_ops/boolean_ops.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "50024"
},
{
"name": "Batchfile",
"bytes": "31352"
},
{
"name": "C",
"bytes": "1493"
},
{
"name": "CSS",
"bytes": "26836"
},
{
"name": "Dockerfile",
"bytes": "9014"
},
{
"name": "HTML",
"bytes": "41387"
},
{
"name": "HiveQL",
"bytes": "1890736"
},
{
"name": "Java",
"bytes": "4123643"
},
{
"name": "JavaScript",
"bytes": "203741"
},
{
"name": "Makefile",
"bytes": "7776"
},
{
"name": "PLpgSQL",
"bytes": "380679"
},
{
"name": "PowerShell",
"bytes": "3865"
},
{
"name": "Python",
"bytes": "3130521"
},
{
"name": "R",
"bytes": "1186948"
},
{
"name": "Roff",
"bytes": "21950"
},
{
"name": "SQLPL",
"bytes": "9325"
},
{
"name": "Scala",
"bytes": "31707827"
},
{
"name": "Shell",
"bytes": "203944"
},
{
"name": "TSQL",
"bytes": "466993"
},
{
"name": "Thrift",
"bytes": "67584"
},
{
"name": "q",
"bytes": "79845"
}
],
"symlink_target": ""
} |
from setuptools import setup
from pymba import __version__
setup(name='pymba',
version=__version__,
description="Pymba is a Python wrapper for Allied Vision's Vimba C API.",
long_description=(
"Pymba is a Python wrapper for Allied Vision's Vimba C API. It wraps the Vimba C library "
"file included in the Vimba installation to provide a simple Python interface for Allied "
"Vision cameras. It currently supports most of the functionality provided by Vimba."
),
# https://pypi.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Healthcare Industry',
'Intended Audience :: Manufacturing',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Topic :: Multimedia :: Graphics :: Capture :: Digital Camera',
'Topic :: Multimedia :: Video :: Capture',
'Topic :: Scientific/Engineering :: Image Recognition',
'Topic :: Scientific/Engineering :: Visualization',
],
keywords='python, python3, opencv, cv, machine vision, computer vision, image recognition, vimba, allied vision',
author='morefigs',
author_email='morefigs@gmail.com',
url='https://github.com/morefigs/pymba',
license='MIT',
packages=[
'pymba',
],
zip_safe=False,
install_requires=[
'numpy',
],
extras_requires={
'dev': [
'opencv-python',
'pytest',
]
}
)
# python3 -m pip install --user --upgrade setuptools wheel twine
# python3 setup.py sdist bdist_wheel
# python3 -m twine upload dist/*
| {
"content_hash": "ccfee4c0c28c82cf4fc21deb408e48af",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 119,
"avg_line_length": 38.283018867924525,
"alnum_prop": 0.5988171513060621,
"repo_name": "morefigs/pymba",
"id": "aed8a2da50b8aecb3eeb797f773d510a5bbaff5a",
"size": "2029",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "77300"
}
],
"symlink_target": ""
} |
"""
CpuVulns - files ``/sys/devices/system/cpu/vulnerabilities/*``
==============================================================
Parser to parse the output of files ``/sys/devices/system/cpu/vulnerabilities/*``
"""
from insights import Parser
from insights import parser
from insights.specs import Specs
from insights.parsers import SkipException
@parser(Specs.cpu_vulns)
class CpuVulns(Parser):
"""
Base class to parse ``/sys/devices/system/cpu/vulnerabilities/*`` files,
the file content will be stored in a string.
Sample output for files:
``/sys/devices/system/cpu/vulnerabilities/spectre_v1``::
Mitigation: Load fences
``/sys/devices/system/cpu/vulnerabilities/spectre_v2``::
Vulnerable: Retpoline without IBPB
``/sys/devices/system/cpu/vulnerabilities/meltdown``::
Mitigation: PTI
``/sys/devices/system/cpu/vulnerabilities/spec_store_bypass``::
Mitigation: Speculative Store Bypass disabled
Examples:
>>> type(sp_v1)
<class 'insights.parsers.cpu_vulns.CpuVulns'>
>>> type(sp_v1) == type(sp_v2) == type(md) == type(ssb)
True
>>> sp_v1.value
'Mitigation: Load fences'
>>> sp_v2.value
'Vulnerable: Retpoline without IBPB'
>>> md.value
'Mitigation: PTI'
>>> ssb.value
'Mitigation: Speculative Store Bypass disabled'
Attributes:
value (str): The result parsed
Raises:
SkipException: When file content is empty
"""
def parse_content(self, content):
if not content:
raise SkipException("Input content is empty")
self.value = content[0]
| {
"content_hash": "b6374015dbd51a7bb3db49d87c08b85d",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 81,
"avg_line_length": 29.396551724137932,
"alnum_prop": 0.6093841642228739,
"repo_name": "RedHatInsights/insights-core",
"id": "ffee4d6d4fc4929347f8c0293595bcc7a0681bfb",
"size": "1705",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "insights/parsers/cpu_vulns.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "220"
},
{
"name": "Python",
"bytes": "8219046"
},
{
"name": "Shell",
"bytes": "1754"
}
],
"symlink_target": ""
} |
import re
from bisect import bisect
from django.conf import settings
from django.db.models.related import RelatedObject
from django.db.models.fields.related import ManyToManyRel
from django.db.models.fields import AutoField, FieldDoesNotExist
from django.db.models.fields.proxy import OrderWrt
from django.db.models.loading import get_models, app_cache_ready
from django.utils.translation import activate, deactivate_all, get_language, string_concat
from django.utils.encoding import force_unicode, smart_str
from django.utils.datastructures import SortedDict
from django.utils import six
# Calculate the verbose_name by converting from InitialCaps to "lowercase with spaces".
get_verbose_name = lambda class_name: re.sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', ' \\1', class_name).lower().strip()
DEFAULT_NAMES = ('verbose_name', 'verbose_name_plural', 'db_table', 'ordering',
'unique_together', 'permissions', 'get_latest_by',
'order_with_respect_to', 'app_label', 'db_tablespace',
'abstract', 'managed', 'proxy', 'auto_created')
class Options(object):
def __init__(self, meta, app_label=None):
self.local_fields, self.local_many_to_many = [], []
self.virtual_fields = []
self.module_name, self.verbose_name = None, None
self.verbose_name_plural = None
self.db_table = ''
self.ordering = []
self.unique_together = []
self.permissions = []
self.object_name, self.app_label = None, app_label
self.get_latest_by = None
self.order_with_respect_to = None
self.db_tablespace = settings.DEFAULT_TABLESPACE
self.admin = None
self.meta = meta
self.pk = None
self.has_auto_field, self.auto_field = False, None
self.abstract = False
self.managed = True
self.proxy = False
# For any class that is a proxy (including automatically created
# classes for deferred object loading), proxy_for_model tells us
# which class this model is proxying. Note that proxy_for_model
# can create a chain of proxy models. For non-proxy models, the
# variable is always None.
self.proxy_for_model = None
# For any non-abstract class, the concrete class is the model
# in the end of the proxy_for_model chain. In particular, for
# concrete models, the concrete_model is always the class itself.
self.concrete_model = None
self.parents = SortedDict()
self.duplicate_targets = {}
self.auto_created = False
# To handle various inheritance situations, we need to track where
# managers came from (concrete or abstract base classes).
self.abstract_managers = []
self.concrete_managers = []
# List of all lookups defined in ForeignKey 'limit_choices_to' options
# from *other* models. Needed for some admin checks. Internal use only.
self.related_fkey_lookups = []
def contribute_to_class(self, cls, name):
from django.db import connection
from django.db.backends.util import truncate_name
cls._meta = self
self.installed = re.sub('\.models$', '', cls.__module__) in settings.INSTALLED_APPS
# First, construct the default values for these options.
self.object_name = cls.__name__
self.module_name = self.object_name.lower()
self.verbose_name = get_verbose_name(self.object_name)
# Next, apply any overridden values from 'class Meta'.
if self.meta:
meta_attrs = self.meta.__dict__.copy()
for name in self.meta.__dict__:
# Ignore any private attributes that Django doesn't care about.
# NOTE: We can't modify a dictionary's contents while looping
# over it, so we loop over the *original* dictionary instead.
if name.startswith('_'):
del meta_attrs[name]
for attr_name in DEFAULT_NAMES:
if attr_name in meta_attrs:
setattr(self, attr_name, meta_attrs.pop(attr_name))
elif hasattr(self.meta, attr_name):
setattr(self, attr_name, getattr(self.meta, attr_name))
# unique_together can be either a tuple of tuples, or a single
# tuple of two strings. Normalize it to a tuple of tuples, so that
# calling code can uniformly expect that.
ut = meta_attrs.pop('unique_together', self.unique_together)
if ut and not isinstance(ut[0], (tuple, list)):
ut = (ut,)
self.unique_together = ut
# verbose_name_plural is a special case because it uses a 's'
# by default.
if self.verbose_name_plural is None:
self.verbose_name_plural = string_concat(self.verbose_name, 's')
# Any leftover attributes must be invalid.
if meta_attrs != {}:
raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys()))
else:
self.verbose_name_plural = string_concat(self.verbose_name, 's')
del self.meta
# If the db_table wasn't provided, use the app_label + module_name.
if not self.db_table:
self.db_table = "%s_%s" % (self.app_label, self.module_name)
self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
def _prepare(self, model):
if self.order_with_respect_to:
self.order_with_respect_to = self.get_field(self.order_with_respect_to)
self.ordering = ('_order',)
model.add_to_class('_order', OrderWrt())
else:
self.order_with_respect_to = None
if self.pk is None:
if self.parents:
# Promote the first parent link in lieu of adding yet another
# field.
field = next(self.parents.itervalues())
# Look for a local field with the same name as the
# first parent link. If a local field has already been
# created, use it instead of promoting the parent
already_created = [fld for fld in self.local_fields if fld.name == field.name]
if already_created:
field = already_created[0]
field.primary_key = True
self.setup_pk(field)
else:
auto = AutoField(verbose_name='ID', primary_key=True,
auto_created=True)
model.add_to_class('id', auto)
# Determine any sets of fields that are pointing to the same targets
# (e.g. two ForeignKeys to the same remote model). The query
# construction code needs to know this. At the end of this,
# self.duplicate_targets will map each duplicate field column to the
# columns it duplicates.
collections = {}
for column, target in self.duplicate_targets.iteritems():
try:
collections[target].add(column)
except KeyError:
collections[target] = set([column])
self.duplicate_targets = {}
for elt in collections.itervalues():
if len(elt) == 1:
continue
for column in elt:
self.duplicate_targets[column] = elt.difference(set([column]))
def add_field(self, field):
# Insert the given field in the order in which it was created, using
# the "creation_counter" attribute of the field.
# Move many-to-many related fields from self.fields into
# self.many_to_many.
if field.rel and isinstance(field.rel, ManyToManyRel):
self.local_many_to_many.insert(bisect(self.local_many_to_many, field), field)
if hasattr(self, '_m2m_cache'):
del self._m2m_cache
else:
self.local_fields.insert(bisect(self.local_fields, field), field)
self.setup_pk(field)
if hasattr(self, '_field_cache'):
del self._field_cache
del self._field_name_cache
if hasattr(self, '_name_map'):
del self._name_map
def add_virtual_field(self, field):
self.virtual_fields.append(field)
def setup_pk(self, field):
if not self.pk and field.primary_key:
self.pk = field
field.serialize = False
def setup_proxy(self, target):
"""
Does the internal setup so that the current model is a proxy for
"target".
"""
self.pk = target._meta.pk
self.proxy_for_model = target
self.db_table = target._meta.db_table
def __repr__(self):
return '<Options for %s>' % self.object_name
def __str__(self):
return "%s.%s" % (smart_str(self.app_label), smart_str(self.module_name))
def verbose_name_raw(self):
"""
There are a few places where the untranslated verbose name is needed
(so that we get the same value regardless of currently active
locale).
"""
lang = get_language()
deactivate_all()
raw = force_unicode(self.verbose_name)
activate(lang)
return raw
verbose_name_raw = property(verbose_name_raw)
def _fields(self):
"""
The getter for self.fields. This returns the list of field objects
available to this model (including through parent models).
Callers are not permitted to modify this list, since it's a reference
to this instance (not a copy).
"""
try:
self._field_name_cache
except AttributeError:
self._fill_fields_cache()
return self._field_name_cache
fields = property(_fields)
def get_fields_with_model(self):
"""
Returns a sequence of (field, model) pairs for all fields. The "model"
element is None for fields on the current model. Mostly of use when
constructing queries so that we know which model a field belongs to.
"""
try:
self._field_cache
except AttributeError:
self._fill_fields_cache()
return self._field_cache
def _fill_fields_cache(self):
cache = []
for parent in self.parents:
for field, model in parent._meta.get_fields_with_model():
if model:
cache.append((field, model))
else:
cache.append((field, parent))
cache.extend([(f, None) for f in self.local_fields])
self._field_cache = tuple(cache)
self._field_name_cache = [x for x, _ in cache]
def _many_to_many(self):
try:
self._m2m_cache
except AttributeError:
self._fill_m2m_cache()
return self._m2m_cache.keys()
many_to_many = property(_many_to_many)
def get_m2m_with_model(self):
"""
The many-to-many version of get_fields_with_model().
"""
try:
self._m2m_cache
except AttributeError:
self._fill_m2m_cache()
return self._m2m_cache.items()
def _fill_m2m_cache(self):
cache = SortedDict()
for parent in self.parents:
for field, model in parent._meta.get_m2m_with_model():
if model:
cache[field] = model
else:
cache[field] = parent
for field in self.local_many_to_many:
cache[field] = None
self._m2m_cache = cache
def get_field(self, name, many_to_many=True):
"""
Returns the requested field by name. Raises FieldDoesNotExist on error.
"""
to_search = many_to_many and (self.fields + self.many_to_many) or self.fields
for f in to_search:
if f.name == name:
return f
raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, name))
def get_field_by_name(self, name):
"""
Returns the (field_object, model, direct, m2m), where field_object is
the Field instance for the given name, model is the model containing
this field (None for local fields), direct is True if the field exists
on this model, and m2m is True for many-to-many relations. When
'direct' is False, 'field_object' is the corresponding RelatedObject
for this field (since the field doesn't have an instance associated
with it).
Uses a cache internally, so after the first access, this is very fast.
"""
try:
try:
return self._name_map[name]
except AttributeError:
cache = self.init_name_map()
return cache[name]
except KeyError:
raise FieldDoesNotExist('%s has no field named %r'
% (self.object_name, name))
def get_all_field_names(self):
"""
Returns a list of all field names that are possible for this model
(including reverse relation names). This is used for pretty printing
debugging output (a list of choices), so any internal-only field names
are not included.
"""
try:
cache = self._name_map
except AttributeError:
cache = self.init_name_map()
names = cache.keys()
names.sort()
# Internal-only names end with "+" (symmetrical m2m related names being
# the main example). Trim them.
return [val for val in names if not val.endswith('+')]
def init_name_map(self):
"""
Initialises the field name -> field object mapping.
"""
cache = {}
# We intentionally handle related m2m objects first so that symmetrical
# m2m accessor names can be overridden, if necessary.
for f, model in self.get_all_related_m2m_objects_with_model():
cache[f.field.related_query_name()] = (f, model, False, True)
for f, model in self.get_all_related_objects_with_model():
cache[f.field.related_query_name()] = (f, model, False, False)
for f, model in self.get_m2m_with_model():
cache[f.name] = (f, model, True, True)
for f, model in self.get_fields_with_model():
cache[f.name] = (f, model, True, False)
if app_cache_ready():
self._name_map = cache
return cache
def get_add_permission(self):
return 'add_%s' % self.object_name.lower()
def get_change_permission(self):
return 'change_%s' % self.object_name.lower()
def get_delete_permission(self):
return 'delete_%s' % self.object_name.lower()
def get_all_related_objects(self, local_only=False, include_hidden=False,
include_proxy_eq=False):
return [k for k, v in self.get_all_related_objects_with_model(
local_only=local_only, include_hidden=include_hidden,
include_proxy_eq=include_proxy_eq)]
def get_all_related_objects_with_model(self, local_only=False,
include_hidden=False,
include_proxy_eq=False):
"""
Returns a list of (related-object, model) pairs. Similar to
get_fields_with_model().
"""
try:
self._related_objects_cache
except AttributeError:
self._fill_related_objects_cache()
predicates = []
if local_only:
predicates.append(lambda k, v: not v)
if not include_hidden:
predicates.append(lambda k, v: not k.field.rel.is_hidden())
cache = (self._related_objects_proxy_cache if include_proxy_eq
else self._related_objects_cache)
return filter(lambda t: all([p(*t) for p in predicates]), cache.items())
def _fill_related_objects_cache(self):
cache = SortedDict()
parent_list = self.get_parent_list()
for parent in self.parents:
for obj, model in parent._meta.get_all_related_objects_with_model(include_hidden=True):
if (obj.field.creation_counter < 0 or obj.field.rel.parent_link) and obj.model not in parent_list:
continue
if not model:
cache[obj] = parent
else:
cache[obj] = model
# Collect also objects which are in relation to some proxy child/parent of self.
proxy_cache = cache.copy()
for klass in get_models(include_auto_created=True, only_installed=False):
for f in klass._meta.local_fields:
if f.rel and not isinstance(f.rel.to, six.string_types):
if self == f.rel.to._meta:
cache[RelatedObject(f.rel.to, klass, f)] = None
proxy_cache[RelatedObject(f.rel.to, klass, f)] = None
elif self.concrete_model == f.rel.to._meta.concrete_model:
proxy_cache[RelatedObject(f.rel.to, klass, f)] = None
self._related_objects_cache = cache
self._related_objects_proxy_cache = proxy_cache
def get_all_related_many_to_many_objects(self, local_only=False):
try:
cache = self._related_many_to_many_cache
except AttributeError:
cache = self._fill_related_many_to_many_cache()
if local_only:
return [k for k, v in cache.items() if not v]
return cache.keys()
def get_all_related_m2m_objects_with_model(self):
"""
Returns a list of (related-m2m-object, model) pairs. Similar to
get_fields_with_model().
"""
try:
cache = self._related_many_to_many_cache
except AttributeError:
cache = self._fill_related_many_to_many_cache()
return cache.items()
def _fill_related_many_to_many_cache(self):
cache = SortedDict()
parent_list = self.get_parent_list()
for parent in self.parents:
for obj, model in parent._meta.get_all_related_m2m_objects_with_model():
if obj.field.creation_counter < 0 and obj.model not in parent_list:
continue
if not model:
cache[obj] = parent
else:
cache[obj] = model
for klass in get_models(only_installed=False):
for f in klass._meta.local_many_to_many:
if f.rel and not isinstance(f.rel.to, six.string_types) and self == f.rel.to._meta:
cache[RelatedObject(f.rel.to, klass, f)] = None
if app_cache_ready():
self._related_many_to_many_cache = cache
return cache
def get_base_chain(self, model):
"""
Returns a list of parent classes leading to 'model' (order from closet
to most distant ancestor). This has to handle the case were 'model' is
a granparent or even more distant relation.
"""
if not self.parents:
return
if model in self.parents:
return [model]
for parent in self.parents:
res = parent._meta.get_base_chain(model)
if res:
res.insert(0, parent)
return res
raise TypeError('%r is not an ancestor of this model'
% model._meta.module_name)
def get_parent_list(self):
"""
Returns a list of all the ancestor of this model as a list. Useful for
determining if something is an ancestor, regardless of lineage.
"""
result = set()
for parent in self.parents:
result.add(parent)
result.update(parent._meta.get_parent_list())
return result
def get_ancestor_link(self, ancestor):
"""
Returns the field on the current model which points to the given
"ancestor". This is possible an indirect link (a pointer to a parent
model, which points, eventually, to the ancestor). Used when
constructing table joins for model inheritance.
Returns None if the model isn't an ancestor of this one.
"""
if ancestor in self.parents:
return self.parents[ancestor]
for parent in self.parents:
# Tries to get a link field from the immediate parent
parent_link = parent._meta.get_ancestor_link(ancestor)
if parent_link:
# In case of a proxied model, the first link
# of the chain to the ancestor is that parent
# links
return self.parents[parent] or parent_link
def get_ordered_objects(self):
"Returns a list of Options objects that are ordered with respect to this object."
if not hasattr(self, '_ordered_objects'):
objects = []
# TODO
#for klass in get_models(get_app(self.app_label)):
# opts = klass._meta
# if opts.order_with_respect_to and opts.order_with_respect_to.rel \
# and self == opts.order_with_respect_to.rel.to._meta:
# objects.append(opts)
self._ordered_objects = objects
return self._ordered_objects
def pk_index(self):
"""
Returns the index of the primary key field in the self.fields list.
"""
return self.fields.index(self.pk)
| {
"content_hash": "bced90cd4429f9abdcc4f8c3b80916e8",
"timestamp": "",
"source": "github",
"line_count": 518,
"max_line_length": 122,
"avg_line_length": 41.66988416988417,
"alnum_prop": 0.5822561964327079,
"repo_name": "azurestandard/django",
"id": "7308a15c6bd12e7c4324fd13de3f214d72ec6780",
"size": "21585",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "django/db/models/options.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
import unittest
from array import array
from collections import UserDict, UserList, UserString
from collections.abc import Mapping
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from robot.utils import (is_bytes, is_falsy, is_dict_like, is_list_like, is_string,
is_truthy, is_union, PY_VERSION, type_name, type_repr)
from robot.utils.asserts import assert_equal, assert_true
class MyMapping(Mapping):
def __getitem__(self, item):
return 0
def __len__(self):
return 0
def __iter__(self):
return iter([])
def generator():
yield 'generated'
class TestIsMisc(unittest.TestCase):
def test_strings(self):
for thing in ['string', 'hyvä', '']:
assert_equal(is_string(thing), True, thing)
assert_equal(is_bytes(thing), False, thing)
def test_bytes(self):
for thing in [b'bytes', bytearray(b'ba'), b'', bytearray()]:
assert_equal(is_bytes(thing), True, thing)
assert_equal(is_string(thing), False, thing)
def test_is_union(self):
assert is_union(Union[int, str])
assert is_union(Union[int, str], allow_tuple=True)
assert not is_union((int, str))
assert is_union((int, str), allow_tuple=True)
if PY_VERSION >= (3, 10):
assert is_union(eval('int | str'))
assert is_union(eval('int | str'), allow_tuple=True)
for not_union in 'string', 3, [int, str], list, List[int]:
assert not is_union(not_union)
assert not is_union(not_union, allow_tuple=True)
class TestListLike(unittest.TestCase):
def test_strings_are_not_list_like(self):
for thing in ['string', UserString('user')]:
assert_equal(is_list_like(thing), False, thing)
def test_bytes_are_not_list_like(self):
for thing in [b'bytes', bytearray(b'bytes')]:
assert_equal(is_list_like(thing), False, thing)
def test_dict_likes_are_list_like(self):
for thing in [dict(), UserDict(), MyMapping()]:
assert_equal(is_list_like(thing), True, thing)
def test_files_are_not_list_like(self):
with open(__file__) as f:
assert_equal(is_list_like(f), False)
assert_equal(is_list_like(f), False)
def test_iter_makes_object_iterable_regardless_implementation(self):
class Example:
def __iter__(self):
1/0
assert_equal(is_list_like(Example()), True)
def test_only_getitem_does_not_make_object_iterable(self):
class Example:
def __getitem__(self, item):
return "I'm not iterable!"
assert_equal(is_list_like(Example()), False)
def test_iterables_in_general_are_list_like(self):
for thing in [[], (), set(), range(1), generator(), array('i'), UserList()]:
assert_equal(is_list_like(thing), True, thing)
def test_others_are_not_list_like(self):
for thing in [1, None, True, object()]:
assert_equal(is_list_like(thing), False, thing)
def test_generators_are_not_consumed(self):
g = generator()
assert_equal(is_list_like(g), True)
assert_equal(is_list_like(g), True)
assert_equal(list(g), ['generated'])
assert_equal(list(g), [])
assert_equal(is_list_like(g), True)
class TestDictLike(unittest.TestCase):
def test_dict_likes(self):
for thing in [dict(), UserDict(), MyMapping()]:
assert_equal(is_dict_like(thing), True, thing)
def test_others(self):
for thing in ['', u'', 1, None, True, object(), [], (), set()]:
assert_equal(is_dict_like(thing), False, thing)
class TestTypeName(unittest.TestCase):
def test_base_types(self):
for item, exp in [('x', 'string'),
(u'x', 'string'),
(b'x', 'bytes'),
(bytearray(), 'bytearray'),
(1, 'integer'),
(1.0, 'float'),
(True, 'boolean'),
(None, 'None'),
(set(), 'set'),
([], 'list'),
((), 'tuple'),
({}, 'dictionary')]:
assert_equal(type_name(item), exp)
def test_file(self):
with open(__file__) as f:
assert_equal(type_name(f), 'file')
def test_custom_objects(self):
class CamelCase: pass
class lower: pass
for item, exp in [(CamelCase(), 'CamelCase'),
(lower(), 'lower'),
(CamelCase, 'CamelCase')]:
assert_equal(type_name(item), exp)
def test_strip_underscores(self):
class _Foo_: pass
assert_equal(type_name(_Foo_), 'Foo')
def test_none_as_underscore_name(self):
class C:
_name = None
assert_equal(type_name(C()), 'C')
assert_equal(type_name(C(), capitalize=True), 'C')
def test_typing(self):
for item, exp in [(List, 'list'),
(List[int], 'list'),
(Tuple, 'tuple'),
(Tuple[int], 'tuple'),
(Set, 'set'),
(Set[int], 'set'),
(Dict, 'dictionary'),
(Dict[int, str], 'dictionary'),
(Union, 'Union'),
(Union[int, str], 'Union'),
(Optional, 'Optional'),
(Optional[int], 'Union'),
(Any, 'Any')]:
assert_equal(type_name(item), exp)
if PY_VERSION >= (3, 10):
def test_union_syntax(self):
assert_equal(type_name(int | float), 'Union')
def test_capitalize(self):
class lowerclass: pass
class CamelClass: pass
assert_equal(type_name('string', capitalize=True), 'String')
assert_equal(type_name(None, capitalize=True), 'None')
assert_equal(type_name(lowerclass(), capitalize=True), 'Lowerclass')
assert_equal(type_name(CamelClass(), capitalize=True), 'CamelClass')
class TestTypeRepr(unittest.TestCase):
def test_class(self):
class Foo:
pass
assert_equal(type_repr(Foo), 'Foo')
def test_none(self):
assert_equal(type_repr(None), 'None')
def test_ellipsis(self):
assert_equal(type_repr(...), '...')
def test_string(self):
assert_equal(type_repr('MyType'), 'MyType')
def test_no_typing_prefix(self):
assert_equal(type_repr(List), 'List')
def test_generics_from_typing(self):
assert_equal(type_repr(List[Any]), 'List[Any]')
assert_equal(type_repr(Dict[int, None]), 'Dict[int, None]')
assert_equal(type_repr(Tuple[int, ...]), 'Tuple[int, ...]')
if PY_VERSION >= (3, 9):
def test_generics(self):
assert_equal(type_repr(list[Any]), 'list[Any]')
assert_equal(type_repr(dict[int, None]), 'dict[int, None]')
def test_union(self):
assert_equal(type_repr(Union[int, float]), 'int | float')
assert_equal(type_repr(Union[int, None, List[Any]]), 'int | None | List[Any]')
if PY_VERSION >= (3, 10):
assert_equal(type_repr(int | None | list[Any]), 'int | None | list[Any]')
class TestIsTruthyFalsy(unittest.TestCase):
def test_truthy_values(self):
for item in [True, 1, [False], unittest.TestCase, 'truE', 'whatEver']:
for item in self._strings_also_in_different_cases(item):
assert_true(is_truthy(item) is True)
assert_true(is_falsy(item) is False)
def test_falsy_values(self):
class AlwaysFalse:
__bool__ = __nonzero__ = lambda self: False
falsy_strings = ['', 'faLse', 'nO', 'nOne', 'oFF', '0']
for item in falsy_strings + [False, None, 0, [], {}, AlwaysFalse()]:
for item in self._strings_also_in_different_cases(item):
assert_true(is_truthy(item) is False)
assert_true(is_falsy(item) is True)
def _strings_also_in_different_cases(self, item):
yield item
if is_string(item):
yield item.lower()
yield item.upper()
yield item.title()
if __name__ == '__main__':
unittest.main()
| {
"content_hash": "4c8cfe5bb627385ee5d8ba2f485d8a58",
"timestamp": "",
"source": "github",
"line_count": 243,
"max_line_length": 86,
"avg_line_length": 34.75308641975309,
"alnum_prop": 0.5385435168738899,
"repo_name": "robotframework/robotframework",
"id": "2c19d7afa1177e299029db1d982c3794f1637c2f",
"size": "8446",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "utest/utils/test_robottypes.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "44632"
},
{
"name": "HTML",
"bytes": "86871"
},
{
"name": "JavaScript",
"bytes": "162950"
},
{
"name": "Python",
"bytes": "2764220"
},
{
"name": "RobotFramework",
"bytes": "1260097"
}
],
"symlink_target": ""
} |
"""Contrib data iterators for common data formats."""
from __future__ import absolute_import
from ..io import DataIter, DataDesc
from .. import ndarray as nd
class DataLoaderIter(DataIter):
"""Returns an iterator for ``mx.gluon.data.Dataloader`` so gluon dataloader
can be used in symbolic module.
Parameters
----------
loader : mxnet.gluon.data.Dataloader
Gluon dataloader instance
data_name : str, optional
The data name.
label_name : str, optional
The label name.
dtype : str, optional
The dtype specifier, can be float32 or float16
Examples
--------
>>> import mxnet as mx
>>> from mxnet.gluon.data.vision import MNIST
>>> from mxnet.gluon.data import DataLoader
>>> train_dataset = MNIST(train=True)
>>> train_data = mx.gluon.data.DataLoader(train_dataset, 32, shuffle=True, num_workers=4)
>>> dataiter = mx.io.DataloaderIter(train_data)
>>> for batch in dataiter:
... batch.data[0].shape
...
(32L, 28L, 28L, 1L)
"""
def __init__(self, loader, data_name='data', label_name='softmax_label', dtype='float32'):
super(DataLoaderIter, self).__init__()
self._loader = loader
self._iter = iter(self._loader)
data, label = next(self._iter)
self.batch_size = data.shape[0]
self.dtype = dtype
self.provide_data = [DataDesc(data_name, data.shape, dtype)]
self.provide_label = [DataDesc(label_name, label.shape, dtype)]
self._current_batch = None
self.reset()
def reset(self):
self._iter = iter(self._loader)
def iter_next(self):
try:
self._current_batch = next(self._iter)
except StopIteration:
self._current_batch = None
return self._current_batch is not None
def getdata(self):
if self.getpad():
dshape = self._current_batch[0].shape
ret = nd.empty(shape=([self.batch_size] + list(dshape[1:])))
ret[:dshape[0]] = self._current_batch[0].astype(self.dtype)
return [ret]
return [self._current_batch[0].astype(self.dtype)]
def getlabel(self):
if self.getpad():
lshape = self._current_batch[1].shape
ret = nd.empty(shape=([self.batch_size] + list(lshape[1:])))
ret[:lshape[0]] = self._current_batch[1].astype(self.dtype)
return [ret]
return [self._current_batch[1].astype(self.dtype)]
def getpad(self):
return self.batch_size - self._current_batch[0].shape[0]
def getindex(self):
return None
| {
"content_hash": "45387cdaf67d3e391135104bab39cbde",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 94,
"avg_line_length": 34.03896103896104,
"alnum_prop": 0.6001526135062953,
"repo_name": "reminisce/mxnet",
"id": "3364fcd215d198c4736ec15f0c32fbde0338c9dd",
"size": "3423",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "python/mxnet/contrib/io.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "1731"
},
{
"name": "Batchfile",
"bytes": "13130"
},
{
"name": "C",
"bytes": "215572"
},
{
"name": "C++",
"bytes": "7680259"
},
{
"name": "CMake",
"bytes": "99958"
},
{
"name": "Clojure",
"bytes": "622688"
},
{
"name": "Cuda",
"bytes": "970884"
},
{
"name": "Dockerfile",
"bytes": "85151"
},
{
"name": "Groovy",
"bytes": "122800"
},
{
"name": "HTML",
"bytes": "40277"
},
{
"name": "Java",
"bytes": "205196"
},
{
"name": "Julia",
"bytes": "436326"
},
{
"name": "Jupyter Notebook",
"bytes": "3660387"
},
{
"name": "MATLAB",
"bytes": "34903"
},
{
"name": "Makefile",
"bytes": "201597"
},
{
"name": "Perl",
"bytes": "1550163"
},
{
"name": "Perl 6",
"bytes": "7280"
},
{
"name": "PowerShell",
"bytes": "13786"
},
{
"name": "Python",
"bytes": "7842403"
},
{
"name": "R",
"bytes": "357807"
},
{
"name": "Scala",
"bytes": "1305036"
},
{
"name": "Shell",
"bytes": "427407"
},
{
"name": "Smalltalk",
"bytes": "3497"
}
],
"symlink_target": ""
} |
import unittest
from app import hello
class TestHelloApp(unittest.TestCase):
def test_hello(self):
self.assertEqual(hello(), "Hello World!\n")
if __name__ == '__main__':
unittest.main()
| {
"content_hash": "f233c961a9bea19a9564262f249ddc5d",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 47,
"avg_line_length": 19.7,
"alnum_prop": 0.6802030456852792,
"repo_name": "GoogleCloudPlatform/gke-gitops-tutorial-cloudbuild",
"id": "93b0c68bfa4f26dd10ffe0fba30e02130767425a",
"size": "773",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test_app.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "738"
},
{
"name": "Python",
"bytes": "1568"
},
{
"name": "Smarty",
"bytes": "1234"
}
],
"symlink_target": ""
} |
import logging
# Set PYTHONPATH=$PWD
from plottools import *
(root_dir, output_file) = get_args()
# List of all run directories to be processed
rundirs = get_rundirs(root_dir)
logging.info("Found %i directories." % len(rundirs))
# List of events, each a tuple: (timestamp, START|STOP)
events = []
for rundir in rundirs:
Js = get_jsons(rundir)
for J in Js:
record_count = len(J)
record_start = J[0]
record_stop = J[record_count-1]
time_str_start = record_start["start_time"]
time_str_stop = record_stop ["end_time"]["set"]
secs_start = date2secs(time_str_start)
secs_stop = date2secs(time_str_stop)
# Store the event tuples
events.append((secs_start, START))
events.append((secs_stop, STOP ))
logging.info("Found %i events." % len(events))
if len(events) == 0:
abort("No events!")
import json
with open('result1.json', 'w') as fp:
json.dump(events, fp)
# Sort by timestamp
events.sort()
with open('result2.json', 'w') as fp:
json.dump(events, fp)
# Get first event time
first = events[0][0]
fp_out = open(output_file, "w")
fp_out.write("0 0\n")
# Run through the events in timestamp order,
# record load at each transition point
load = 0
for event in events:
t = (event[0] - first)/3600
if event[1] == START:
load = load+1
elif event[1] == STOP:
load = load-1
else:
abort("Unknown event!")
fp_out.write("%0.6f %i\n" % (t, load))
fp_out.close()
logging.info("Wrote %s ." % output_file)
| {
"content_hash": "5d4858755890937ff7ebe14026c0d73d",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 56,
"avg_line_length": 23.119402985074625,
"alnum_prop": 0.6197546804389928,
"repo_name": "ECP-CANDLE/Database",
"id": "be3564f550b539d782bd9f246a9a187158112573",
"size": "1970",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plots/json2load.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "18417"
},
{
"name": "Shell",
"bytes": "922"
}
],
"symlink_target": ""
} |
from __future__ import print_function
import os
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
class Auth:
def __init__(self, scopes, secretFile, applicationName, credentialWindowsFile = 'mydrive.json'):
self.uriScope = scopes
self.clientSecretFile = secretFile
self.appName = applicationName
self.credentialWinFile = credentialWindowsFile
def get_credentials(self):
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir, self.credentialWinFile)
if not os.path.exists(credential_path):
fileCred = open(credential_path, 'w')
fileCred.close()
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(self.clientSecretFile, self.uriScope)
flow.user_agent = self.appName
credentials = tools.run_flow(flow, store)
return credentials
| {
"content_hash": "c0d134af2da5bfe2011949275aa05fdc",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 100,
"avg_line_length": 32.67567567567568,
"alnum_prop": 0.6683209263854425,
"repo_name": "Kyochi/DriveSize",
"id": "4ab65c20e3ca0c9e486a6999cc2a8be4a98b331c",
"size": "1210",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "drivesize/Auth.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "7637"
}
],
"symlink_target": ""
} |
import nose
import subprocess
from stolos import api
from stolos import exceptions
from stolos import queue_backend as qb
from stolos.testing_tools import (
with_setup, inject_into_dag,
enqueue, cycle_queue, consume_queue, get_qb_status,
validate_zero_queued_task, validate_not_exists,
validate_one_failed_task, validate_one_queued_executing_task,
validate_one_queued_task, validate_one_completed_task,
validate_one_skipped_task, validate_n_queued_task
)
CMD = (
'STOLOS_TASKS_JSON={tasks_json}'
' STOLOS_APP_NAME={app_name}'
' python -m stolos.runner '
' {extra_opts}'
)
def run_code(log, tasks_json_tmpfile, app_name, extra_opts='',
capture=False, raise_on_err=True, async=False):
"""Execute a shell command that runs Stolos for a given app_name
`async` - (bool) return Popen process instance. other kwargs do not apply
`capture` - (bool) return (stdout, stderr)
"""
cmd = CMD.format(
app_name=app_name,
tasks_json=tasks_json_tmpfile,
extra_opts=extra_opts)
log.debug('run code', extra=dict(cmd=cmd))
p = subprocess.Popen(
cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
if async:
return p
stdout, stderr = p.communicate()
rc = p.poll()
if raise_on_err and rc:
raise Exception(
"command failed. returncode: %s\ncmd: %s\nstderr: %s\nstdout: %s\n"
% (rc, cmd, stderr, stdout))
log.warn("Ran a shell command and got this stdout and stderr: "
" \nSTDOUT:\n%s \nSTDERR:\n %s"
% (stdout, stderr))
if capture:
return stdout.decode('utf8'), stderr.decode('utf8')
@with_setup
def test_maybe_add_subtask_no_priority(app1, job_id1, job_id2):
api.maybe_add_subtask(app1, job_id1)
api.maybe_add_subtask(app1, job_id2)
nose.tools.assert_equal(consume_queue(app1), job_id1)
nose.tools.assert_equal(consume_queue(app1), job_id2)
@with_setup
def test_maybe_add_subtask_priority_first(app1, job_id1, job_id2):
api.maybe_add_subtask(app1, job_id1, priority=10)
api.maybe_add_subtask(app1, job_id2, priority=20)
nose.tools.assert_equal(consume_queue(app1), job_id1)
nose.tools.assert_equal(consume_queue(app1), job_id2)
@with_setup
def test_maybe_add_subtask_priority_second(app1, job_id1, job_id2):
api.maybe_add_subtask(app1, job_id1, priority=20)
api.maybe_add_subtask(app1, job_id2, priority=10)
nose.tools.assert_equal(consume_queue(app1), job_id2)
nose.tools.assert_equal(consume_queue(app1), job_id1)
@with_setup
def test_bypass_scheduler(bash1, job_id1, log, tasks_json_tmpfile):
validate_zero_queued_task(bash1)
run_code(
log, tasks_json_tmpfile, bash1,
'--bypass_scheduler --job_id %s --bash_cmd echo 123' % job_id1)
validate_zero_queued_task(bash1)
validate_not_exists(bash1, job_id1)
@with_setup
def test_no_tasks(app1, app2, log, tasks_json_tmpfile):
# The script shouldn't fail if it doesn't find any queued tasks
run_code(log, tasks_json_tmpfile, app1)
validate_zero_queued_task(app1)
validate_zero_queued_task(app2)
@with_setup
def test_create_child_task_after_one_parent_completed(
app1, app2, app3, job_id1, log, tasks_json_tmpfile, func_name):
# if you modify the tasks.json file in the middle of processing the dag
# modifications to the json file should be recognized
# the child task should run if another parent completes
# but otherwise should not run until it's manually queued
injected_app = app3
dct = {
injected_app: {
"depends_on": {"app_name": [app1, app2]},
},
}
qb.set_state(
app1, job_id1, completed=True)
validate_one_completed_task(app1, job_id1)
validate_zero_queued_task(injected_app)
consume_queue(app2)
qb.set_state(app2, job_id1, completed=True)
with inject_into_dag(func_name, dct):
validate_zero_queued_task(injected_app)
qb.set_state(app2, job_id1, completed=True)
validate_zero_queued_task(injected_app)
qb.set_state(app1, job_id1, completed=True)
validate_one_queued_task(injected_app, job_id1)
run_code(log, tasks_json_tmpfile, injected_app, '--bash_cmd echo 123')
validate_one_completed_task(injected_app, job_id1)
@with_setup
def test_create_parent_task_after_child_completed(app1, app3, job_id1,
func_name):
# if you modify the tasks.json file in the middle of processing the dag
# modifications to the json file should be recognized appropriately
# we do not re-schedule the child unless parent is completed
qb.set_state(app1, job_id1, completed=True)
validate_one_completed_task(app1, job_id1)
injected_app = app3
child_injapp = 'test_stolos/%s/testX' % func_name
dct = {
injected_app: {
},
child_injapp: {
"depends_on": {"app_name": [injected_app]}
}
}
with inject_into_dag(func_name, dct):
validate_zero_queued_task(injected_app)
qb.set_state(injected_app, job_id1, completed=True)
validate_one_completed_task(injected_app, job_id1)
validate_one_queued_task(child_injapp, job_id1)
@with_setup
def test_should_not_add_queue_while_consuming_queue(app1, job_id1):
# This test guards from doubly queuing jobs
# This protects from simultaneous operations on root and leaf nodes
# ie (parent and child) for the following operations:
# adding, readding or a mix of both
enqueue(app1, job_id1)
q = qb.get_qbclient().LockingQueue(app1)
q.get()
validate_one_queued_task(app1, job_id1)
enqueue(app1, job_id1)
with nose.tools.assert_raises(exceptions.JobAlreadyQueued):
qb.readd_subtask(app1, job_id1)
validate_one_queued_task(app1, job_id1)
# cleanup
q.consume()
@with_setup
def test_push_tasks1(app1, app2, job_id1, log, tasks_json_tmpfile):
"""
Child tasks should be generated and executed properly
if task A --> task B, and we queue & run A,
then we should end up with one A task completed and one queued B task
"""
enqueue(app1, job_id1)
run_code(log, tasks_json_tmpfile, app1)
validate_one_completed_task(app1, job_id1)
# check child
validate_one_queued_task(app2, job_id1)
@with_setup
def test_rerun_pull_tasks1(app1, app2, job_id1, log, tasks_json_tmpfile):
# queue and complete app 1. it queues a child
enqueue(app1, job_id1)
qb.set_state(app1, job_id1, completed=True)
consume_queue(app1)
validate_zero_queued_task(app1)
validate_one_queued_task(app2, job_id1)
# complete app 2
qb.set_state(app2, job_id1, completed=True)
consume_queue(app2)
validate_zero_queued_task(app2)
# readd app 2
qb.readd_subtask(app2, job_id1)
validate_zero_queued_task(app1)
validate_one_queued_task(app2, job_id1)
# run app 2. the parent was previously completed
run_code(log, tasks_json_tmpfile, app2)
validate_one_completed_task(app1, job_id1) # previously completed
validate_one_completed_task(app2, job_id1)
@with_setup
def test_rerun_manual_task1(app1, job_id1):
enqueue(app1, job_id1)
validate_one_queued_task(app1, job_id1)
with nose.tools.assert_raises(exceptions.JobAlreadyQueued):
qb.readd_subtask(app1, job_id1)
@with_setup
def test_rerun_manual_task2(app1, job_id1):
qb.readd_subtask(app1, job_id1)
validate_one_queued_task(app1, job_id1)
@with_setup
def test_rerun_push_tasks_when_manually_queuing_child_and_parent(
app1, app2, job_id1):
_test_rerun_tasks_when_manually_queuing_child_and_parent(
app1, app2, job_id1)
# complete parent first
qb.set_state(app1, job_id1, completed=True)
consume_queue(app1)
validate_one_completed_task(app1, job_id1)
validate_one_queued_task(app2, job_id1)
# child completes normally
qb.set_state(app2, job_id1, completed=True)
consume_queue(app2)
validate_one_completed_task(app1, job_id1)
validate_one_completed_task(app2, job_id1)
@with_setup
def test_rerun_pull_tasks_when_manually_queuing_child_and_parent(
app1, app2, job_id1):
_test_rerun_tasks_when_manually_queuing_child_and_parent(
app1, app2, job_id1)
# complete child first
qb.set_state(app2, job_id1, completed=True)
consume_queue(app2)
# --> parent still queued
validate_one_queued_task(app1, job_id1)
validate_one_completed_task(app2, job_id1)
# then complete parent
qb.set_state(app1, job_id1, completed=True)
consume_queue(app1)
# --> child gets re-queued
validate_one_completed_task(app1, job_id1)
validate_one_queued_task(app2, job_id1)
# complete child second time
qb.set_state(app2, job_id1, completed=True)
consume_queue(app2)
validate_one_completed_task(app1, job_id1)
validate_one_completed_task(app2, job_id1)
def _test_rerun_tasks_when_manually_queuing_child_and_parent(
app1, app2, job_id1):
# complete parent and child
enqueue(app1, job_id1)
qb.set_state(app1, job_id1, completed=True)
consume_queue(app1)
qb.set_state(app2, job_id1, completed=True)
consume_queue(app2)
validate_one_completed_task(app1, job_id1)
validate_one_completed_task(app2, job_id1)
# manually re-add child
qb.readd_subtask(app2, job_id1)
validate_one_queued_task(app2, job_id1)
validate_one_completed_task(app1, job_id1)
# manually re-add parent
qb.readd_subtask(app1, job_id1)
validate_one_queued_task(app1, job_id1)
validate_one_queued_task(app2, job_id1)
@with_setup
def test_rerun_push_tasks1(app1, app2, job_id1):
# this tests recursively deleteing parent status on child nodes
# queue and complete app 1. it queues a child
enqueue(app1, job_id1)
qb.set_state(app1, job_id1, completed=True)
consume_queue(app1)
validate_one_completed_task(app1, job_id1)
validate_one_queued_task(app2, job_id1)
# complete app 2
qb.set_state(app2, job_id1, completed=True)
consume_queue(app2)
validate_one_completed_task(app1, job_id1)
validate_one_completed_task(app2, job_id1)
# readd app 1
qb.readd_subtask(app1, job_id1)
validate_one_queued_task(app1, job_id1)
validate_zero_queued_task(app2)
nose.tools.assert_true(
qb.check_state(app2, job_id1, pending=True))
# complete app 1
qb.set_state(app1, job_id1, completed=True)
consume_queue(app1)
validate_one_completed_task(app1, job_id1)
validate_one_queued_task(app2, job_id1)
# complete app 2
qb.set_state(app2, job_id1, completed=True)
consume_queue(app2)
validate_one_completed_task(app1, job_id1)
validate_one_completed_task(app2, job_id1)
@with_setup
def test_complex_dependencies_pull_push(
depends_on1, depends_on_job_id1, log, tasks_json_tmpfile):
job_id = depends_on_job_id1
enqueue(depends_on1, job_id)
run_code(log, tasks_json_tmpfile, depends_on1, '--bash_cmd echo 123')
parents = api.get_parents(depends_on1, job_id)
parents = list(api.topological_sort(parents))
for parent, pjob_id in parents[:-1]:
qb.set_state(parent, pjob_id, completed=True)
validate_zero_queued_task(depends_on1)
qb.set_state(*parents[-1], completed=True)
validate_one_queued_task(depends_on1, job_id)
run_code(log, tasks_json_tmpfile, depends_on1, '--bash_cmd echo 123')
validate_one_completed_task(depends_on1, job_id)
@with_setup
def test_complex_dependencies_readd(depends_on1, depends_on_job_id1,
log, tasks_json_tmpfile):
job_id = depends_on_job_id1
# mark everything completed. ensure only last completed parent queues child
parents = list(api.topological_sort(api.get_parents(depends_on1, job_id)))
for parent, pjob_id in parents[:-1]:
qb.set_state(parent, pjob_id, completed=True)
validate_zero_queued_task(depends_on1)
qb.set_state(parents[-1][0], parents[-1][1], completed=True)
validate_one_queued_task(depends_on1, job_id)
# --> parents should queue our app
consume_queue(depends_on1)
qb.set_state(depends_on1, job_id, completed=True)
validate_one_completed_task(depends_on1, job_id)
# ok great - ran through pipeline once.
log.warn("OK... Now try complex dependency test with a readd")
# re-complete the very first parent.
# we assume that this parent is a root task
parent, pjob_id = parents[0]
qb.readd_subtask(parent, pjob_id)
validate_one_queued_task(parent, pjob_id)
validate_zero_queued_task(depends_on1)
consume_queue(parent)
qb.set_state(parent, pjob_id, completed=True)
validate_one_completed_task(parent, pjob_id)
# since the parent that re-queues children that may be depends_on1's
# parents, complete those too!
for p2, pjob2 in api.get_children(parent, pjob_id, False):
if p2 == depends_on1:
continue
consume_queue(p2)
qb.set_state(p2, pjob2, completed=True)
# now, that last parent should have queued our application
validate_n_queued_task(
depends_on1, job_id,
job_id.replace('testID1', 'testID3')) # this replace is a hack
run_code(log, tasks_json_tmpfile, depends_on1, '--bash_cmd echo 123')
run_code(log, tasks_json_tmpfile, depends_on1, '--bash_cmd echo 123')
validate_one_completed_task(depends_on1, job_id)
# phew!
@with_setup
def test_pull_tasks1(app1, app2, job_id1, log, tasks_json_tmpfile):
"""
Parent tasks should be generated and executed before child tasks
(The Bubble Up and then Bubble Down test)
If A --> B, and:
we queue and run B, then we should have 0 completed tasks,
but A should be queued
nothing should change until:
we run A and A becomes completed
we then run B and B becomes completed
"""
enqueue(app2, job_id1)
run_code(log, tasks_json_tmpfile, app2)
validate_one_queued_task(app1, job_id1)
validate_zero_queued_task(app2)
run_code(log, tasks_json_tmpfile, app2)
validate_one_queued_task(app1, job_id1)
validate_zero_queued_task(app2)
run_code(log, tasks_json_tmpfile, app1)
validate_one_completed_task(app1, job_id1)
validate_one_queued_task(app2, job_id1)
run_code(log, tasks_json_tmpfile, app2)
validate_one_completed_task(app2, job_id1)
@with_setup
def test_pull_tasks_with_many_children(app1, app2, app3, app4, job_id1,
log, tasks_json_tmpfile):
enqueue(app4, job_id1)
validate_one_queued_task(app4, job_id1)
validate_zero_queued_task(app1)
validate_zero_queued_task(app2)
validate_zero_queued_task(app3)
run_code(log, tasks_json_tmpfile, app4, '--bash_cmd echo app4helloworld')
validate_zero_queued_task(app4)
validate_one_queued_task(app1, job_id1)
validate_one_queued_task(app2, job_id1)
validate_one_queued_task(app3, job_id1)
consume_queue(app1)
qb.set_state(app1, job_id1, completed=True)
validate_zero_queued_task(app4)
validate_one_completed_task(app1, job_id1)
validate_one_queued_task(app2, job_id1)
validate_one_queued_task(app3, job_id1)
consume_queue(app2)
qb.set_state(app2, job_id1, completed=True)
validate_zero_queued_task(app4)
validate_one_completed_task(app1, job_id1)
validate_one_completed_task(app2, job_id1)
validate_one_queued_task(app3, job_id1)
consume_queue(app3)
qb.set_state(app3, job_id1, completed=True)
validate_one_completed_task(app1, job_id1)
validate_one_completed_task(app2, job_id1)
validate_one_completed_task(app3, job_id1)
validate_one_queued_task(app4, job_id1)
consume_queue(app4)
qb.set_state(app4, job_id1, completed=True)
validate_one_completed_task(app1, job_id1)
validate_one_completed_task(app2, job_id1)
validate_one_completed_task(app3, job_id1)
validate_one_completed_task(app4, job_id1)
@with_setup
def test_retry_failed_task(
app1, job_id1, job_id2, log, tasks_json_tmpfile):
"""
Retry failed tasks up to max num retries and then remove self from queue
Tasks should maintain proper task state throughout.
"""
# create 2 tasks in same queue
enqueue(app1, job_id1)
enqueue(app1, job_id2, validate_queued=False)
nose.tools.assert_equal(2, get_qb_status(app1, job_id1)['app_qsize'])
nose.tools.assert_equal(job_id1, cycle_queue(app1))
# run job_id2 and have it fail
run_code(
log, tasks_json_tmpfile, app1,
extra_opts='--bash_cmd "&& notacommand...fail" ')
# ensure we still have both items in the queue
nose.tools.assert_true(get_qb_status(app1, job_id1)['in_queue'])
nose.tools.assert_true(get_qb_status(app1, job_id2)['in_queue'])
# ensure the failed task is sent to back of the queue
nose.tools.assert_equal(2, get_qb_status(app1, job_id1)['app_qsize'])
nose.tools.assert_equal(job_id1, cycle_queue(app1))
# run and fail n times, where n = max failures
run_code(
log, tasks_json_tmpfile, app1,
extra_opts='--max_retry 1 --bash_cmd "&& notacommand...fail"')
# verify that job_id2 is removed from queue
validate_one_queued_task(app1, job_id1)
# verify that job_id2 state is 'failed' and job_id1 is still pending
validate_one_failed_task(app1, job_id2)
@with_setup
def test_valid_if_or_1(app2, job_id1):
"""Invalid tasks should be automatically completed.
This is a valid_if_or test (aka passes_filter )... bad naming sorry!"""
job_id = job_id1.replace('profile', 'content')
enqueue(app2, job_id, validate_queued=False)
validate_one_skipped_task(app2, job_id)
@with_setup
def test_valid_if_or_func1(app3, job_id1, job_id2, job_id3):
"""Verify that the valid_if_or option supports the "_func" option
app_name: {"valid_if_or": {"_func": "python.import.path.to.func"}}
where the function definition looks like: func(**parsed_job_id)
"""
enqueue(app3, job_id2, validate_queued=False)
validate_one_skipped_task(app3, job_id2)
@with_setup
def test_valid_if_or_func2(app3, job_id1, job_id2, job_id3):
"""Verify that the valid_if_or option supports the "_func" option
app_name: {"valid_if_or": {"_func": "python.import.path.to.func"}}
where the function definition looks like: func(**parsed_job_id)
"""
enqueue(app3, job_id3, validate_queued=False)
validate_one_skipped_task(app3, job_id3)
@with_setup
def test_valid_if_or_func3(app3, job_id1, job_id2, job_id3):
"""Verify that the valid_if_or option supports the "_func" option
app_name: {"valid_if_or": {"_func": "python.import.path.to.func"}}
where the function definition looks like: func(**parsed_job_id)
"""
# if the job_id matches the valid_if_or: {"_func": func...} criteria, then:
enqueue(app3, job_id1, validate_queued=False)
validate_one_queued_task(app3, job_id1)
@with_setup
def test_skipped_parent_and_queued_child(app1, app2, app3, app4, job_id1,
log, tasks_json_tmpfile):
qb.set_state(app1, job_id1, skipped=True)
qb.set_state(app3, job_id1, skipped=True)
qb.set_state(app2, job_id1, skipped=True)
enqueue(app4, job_id1)
validate_zero_queued_task(app2)
validate_one_queued_task(app4, job_id1)
# ensure child unqueues itself and raises warning
out, err = run_code(log, tasks_json_tmpfile, app4, capture=True)
nose.tools.assert_in(
"parent_job_id is marked as 'skipped', so should be impossible for me,"
" the child, to exist", err)
validate_zero_queued_task(app4)
validate_zero_queued_task(app2)
@with_setup
def test_valid_task1(app2, job_id1):
"""Valid tasks should be automatically completed"""
enqueue(app2, job_id1, validate_queued=True)
@with_setup
def test_bash1(bash1, job_id1, log, tasks_json_tmpfile):
"""a bash task should execute properly """
# queue task
enqueue(bash1, job_id1)
validate_one_queued_task(bash1, job_id1)
# run failing task
run_code(
log, tasks_json_tmpfile, bash1, '--bash_cmd thiscommandshouldfail')
validate_one_queued_task(bash1, job_id1)
# run successful task
run_code(log, tasks_json_tmpfile, bash1, '--bash_cmd echo 123')
validate_zero_queued_task(bash1)
@with_setup
def test_app_has_command_line_params(
bash1, job_id1, log, tasks_json_tmpfile):
enqueue(bash1, job_id1)
msg = 'output: %s'
# Test passed in params exist
_, logoutput = run_code(
log, tasks_json_tmpfile, bash1,
extra_opts='--redirect_to_stderr --bash_cmd echo newfakereadfp',
capture=True, raise_on_err=True)
nose.tools.assert_in(
'newfakereadfp', logoutput, msg % logoutput)
@with_setup
def test_run_given_specific_job_id(app1, job_id1, log, tasks_json_tmpfile):
enqueue(app1, job_id1)
out, err = run_code(
log, tasks_json_tmpfile, app1,
'--job_id %s' % job_id1, raise_on_err=False, capture=True)
nose.tools.assert_regexp_matches(err, (
'UserWarning: Will not execute this task because it might be'
' already queued or completed!'))
validate_one_queued_task(app1, job_id1)
@with_setup
def test_child_running_while_parent_pending_but_not_executing(
app1, app2, job_id1):
enqueue(app1, job_id1)
enqueue(app2, job_id1)
parents_completed, consume_queue, parent_lock = \
qb.ensure_parents_completed(app2, job_id1)
# ensure lock is obtained by ensure_parents_completed
validate_one_queued_executing_task(app1, job_id1)
validate_one_queued_task(app2, job_id1)
nose.tools.assert_equal(parents_completed, False)
# child should promise to remove itself from queue
nose.tools.assert_equal(consume_queue, True)
nose.tools.assert_is_instance(parent_lock, qb.BaseLock)
# cleanup
parent_lock.release()
@with_setup
def test_child_running_while_parent_pending_and_executing(
app1, app2, job_id1):
enqueue(app1, job_id1)
enqueue(app2, job_id1)
lock = qb.obtain_execute_lock(app1, job_id1)
assert lock
parents_completed, consume_queue, parent_lock = \
qb.ensure_parents_completed(app2, job_id1)
validate_one_queued_executing_task(app1, job_id1)
validate_one_queued_task(app2, job_id1)
nose.tools.assert_equal(parents_completed, False)
# child should not promise to remove itself from queue
nose.tools.assert_equal(consume_queue, False)
nose.tools.assert_is_none(parent_lock)
# cleanup
lock.release()
@with_setup
def test_race_condition_when_parent_queues_child(
app1, app2, job_id1, log, tasks_json_tmpfile):
# The parent queues the child and the child runs before the parent gets
# a chance to mark itself as completed
qb.set_state(app1, job_id1, pending=True)
lock = qb.obtain_execute_lock(app1, job_id1)
assert lock
qb.set_state(app1, job_id1, completed=True)
qb.set_state(app1, job_id1, pending=True)
validate_one_queued_task(app2, job_id1)
validate_zero_queued_task(app1)
# should not complete child. should de-queue child
# should not queue parent.
# should exit gracefully
# stays in the queue (forever) until parent state is completed
run_code(log, tasks_json_tmpfile, app2)
validate_zero_queued_task(app1)
validate_one_queued_task(app2, job_id1)
qb.set_state(
app1, job_id1, completed=True,
_disable_maybe_queue_children_for_testing_only=True)
lock.release()
validate_one_completed_task(app1, job_id1)
validate_one_queued_task(app2, job_id1)
run_code(log, tasks_json_tmpfile, app2)
validate_one_completed_task(app1, job_id1)
validate_one_completed_task(app2, job_id1)
@with_setup
def test_run_multiple_given_specific_job_id(
bash1, job_id1, log, tasks_json_tmpfile):
p = run_code(
log, tasks_json_tmpfile, bash1,
extra_opts='--job_id %s --timeout 1 --bash_cmd sleep 2' % job_id1,
async=True)
p2 = run_code(
log, tasks_json_tmpfile, bash1,
extra_opts='--job_id %s --timeout 1 --bash_cmd sleep 2' % job_id1,
async=True)
# one of them should fail. both should run asynchronously
err = (p.communicate()[1] + p2.communicate()[1]).decode('utf8')
statuses = [p.poll(), p2.poll()]
# one job succeeds. one job fails
nose.tools.assert_regexp_matches(err, 'successfully completed job')
nose.tools.assert_regexp_matches(err, (
'(UserWarning: Will not execute this task because it might'
' be already queued or completed!'
'|Lock already acquired)'))
# failing job should NOT gracefully quit
nose.tools.assert_equal(
list(sorted(statuses)), [0, 1], msg="expected exactly one job to fail")
@with_setup
def test_run_failing_spark_given_specific_job_id(
bash1, job_id1, log, tasks_json_tmpfile):
"""
task should still get queued if --job_id is specified and the task fails
"""
with nose.tools.assert_raises(Exception):
run_code(log, tasks_json_tmpfile, bash1, '--pluginfail')
validate_zero_queued_task(bash1)
run_code(
log, tasks_json_tmpfile, bash1,
'--job_id %s --bash_cmd kasdfkajsdfajaja' % job_id1)
validate_one_queued_task(bash1, job_id1)
@with_setup
def test_failing_task(bash1, job_id1, log, tasks_json_tmpfile):
_, err = run_code(
log, tasks_json_tmpfile, bash1,
' --job_id %s --bash_cmd notacommand...fail' % job_id1,
capture=True)
nose.tools.assert_regexp_matches(
err, "Bash job failed")
nose.tools.assert_regexp_matches(
err, "Task retry count increased")
_, err = run_code(
log, tasks_json_tmpfile, bash1,
'--max_retry 1 --bash_cmd jaikahhaha', capture=True)
nose.tools.assert_regexp_matches(
err, "Task retried too many times and is set as permanently failed")
@with_setup
def test_invalid_queued_job_id(app4, depends_on_job_id1,
log, tasks_json_tmpfile):
job_id = depends_on_job_id1 # this job_id does not match the app
# manually bypass the decorator that validates job_id
qb._set_state_unsafe(app4, job_id, pending=True)
q = qb.get_qbclient().LockingQueue(app4)
q.put(job_id)
validate_one_queued_task(app4, job_id)
run_code(log, tasks_json_tmpfile, app4, '--bash_cmd echo 123')
validate_one_failed_task(app4, job_id)
validate_zero_queued_task(app4)
| {
"content_hash": "551c927ae2c242b4bfc6057ab58ac2cb",
"timestamp": "",
"source": "github",
"line_count": 755,
"max_line_length": 79,
"avg_line_length": 35.25033112582781,
"alnum_prop": 0.6710753738633802,
"repo_name": "sailthru/stolos",
"id": "5854ab04fc40e3743f509155e59a651b53df6413",
"size": "26614",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "stolos/tests/test_stolos.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "250979"
},
{
"name": "Shell",
"bytes": "2837"
}
],
"symlink_target": ""
} |
from collections import OrderedDict
from rest_framework.serializers import CharField
from rest_framework.serializers import IntegerField
from rest_framework.serializers import ListField
from rest_framework.serializers import ModelSerializer
from rest_framework.serializers import PrimaryKeyRelatedField
from rest_framework.serializers import Serializer
from rest_framework.serializers import ValidationError
from kolibri.core import error_constants
from kolibri.core.api import HexUUIDField
from kolibri.core.auth.constants.collection_kinds import ADHOCLEARNERSGROUP
from kolibri.core.auth.models import Collection
from kolibri.core.auth.models import FacilityUser
from kolibri.core.auth.models import Membership
from kolibri.core.auth.utils.users import create_adhoc_group_for_learners
from kolibri.core.exams.models import Exam
from kolibri.core.exams.models import ExamAssignment
from kolibri.core.serializers import DateTimeTzField
class NestedCollectionSerializer(ModelSerializer):
class Meta:
model = Collection
fields = ("id", "name", "kind")
class QuestionSourceSerializer(Serializer):
exercise_id = HexUUIDField(format="hex")
# V0 need not have question_id that is why required=False
question_id = HexUUIDField(format="hex", required=False)
title = CharField()
counter_in_exercise = IntegerField()
class ExamSerializer(ModelSerializer):
assignments = ListField(
child=PrimaryKeyRelatedField(read_only=False, queryset=Collection.objects.all())
)
learner_ids = ListField(
child=PrimaryKeyRelatedField(
read_only=False, queryset=FacilityUser.objects.all()
),
required=False,
)
question_sources = ListField(child=QuestionSourceSerializer(), required=False)
creator = PrimaryKeyRelatedField(
read_only=False, queryset=FacilityUser.objects.all()
)
date_archived = DateTimeTzField(allow_null=True)
date_activated = DateTimeTzField(allow_null=True)
class Meta:
model = Exam
fields = (
"id",
"title",
"question_count",
"question_sources",
"seed",
"active",
"collection",
"archive",
"date_archived",
"date_activated",
"assignments",
"creator",
"data_model_version",
"learners_see_fixed_order",
"learner_ids",
)
read_only_fields = ("data_model_version",)
def validate(self, attrs):
title = attrs.get("title")
# first condition is for creating object, second is for updating
collection = attrs.get("collection") or getattr(self.instance, "collection")
if "learner_ids" in self.initial_data and self.initial_data["learner_ids"]:
if (
len(self.initial_data["learner_ids"])
!= FacilityUser.objects.filter(
memberships__collection=collection,
id__in=self.initial_data["learner_ids"],
).count()
):
raise ValidationError(
"Some learner_ids are not members of the collection that this quiz is contained in",
code=error_constants.INVALID,
)
# if obj doesn't exist, return data
try:
obj = Exam.objects.get(title__iexact=title, collection=collection)
except Exam.DoesNotExist:
return attrs
# if we are updating object, and this `instance` is the same object, return data
if self.instance and obj.id == self.instance.id:
return attrs
else:
raise ValidationError(
"The fields title, collection must make a unique set.",
code=error_constants.UNIQUE,
)
def to_internal_value(self, data):
# Make a new OrderedDict from the input, which could be an immutable QueryDict
data = OrderedDict(data)
if "creator" not in data:
if self.context["view"].action == "create":
data["creator"] = self.context["request"].user.id
else:
# Otherwise we are just updating the exam, so allow a partial update
self.partial = True
return super(ExamSerializer, self).to_internal_value(data)
def create(self, validated_data):
collections = validated_data.pop("assignments")
learners = validated_data.pop("learner_ids", [])
new_exam = Exam.objects.create(**validated_data)
# Create all of the new ExamAssignment
for collection in collections:
self._create_exam_assignment(exam=new_exam, collection=collection)
if learners:
adhoc_group = create_adhoc_group_for_learners(new_exam.collection, learners)
self._create_exam_assignment(exam=new_exam, collection=adhoc_group)
return new_exam
def _create_exam_assignment(self, **params):
return ExamAssignment.objects.create(
assigned_by=self.context["request"].user, **params
)
def update(self, instance, validated_data): # noqa
# Update the scalar fields
instance.title = validated_data.get("title", instance.title)
instance.active = validated_data.get("active", instance.active)
instance.archive = validated_data.get("archive", instance.archive)
instance.date_activated = validated_data.get(
"date_activated", instance.date_activated
)
instance.date_archived = validated_data.get(
"date_archived", instance.date_archived
)
# Add/delete any new/removed Assignments
if "assignments" in validated_data:
collections = validated_data.pop("assignments")
current_group_ids = set(
instance.assignments.exclude(
collection__kind=ADHOCLEARNERSGROUP
).values_list("collection__id", flat=True)
)
new_group_ids = {x.id for x in collections}
for cid in new_group_ids - current_group_ids:
collection = Collection.objects.get(id=cid)
if collection.kind != ADHOCLEARNERSGROUP:
self._create_exam_assignment(exam=instance, collection=collection)
ExamAssignment.objects.filter(
exam_id=instance.id,
collection_id__in=(current_group_ids - new_group_ids),
).exclude(collection__kind=ADHOCLEARNERSGROUP).delete()
# Update adhoc assignment
if "learner_ids" in validated_data:
self._update_learner_ids(instance, validated_data["learner_ids"])
instance.save()
return instance
def _update_learner_ids(self, instance, learners):
try:
adhoc_group_assignment = ExamAssignment.objects.select_related(
"collection"
).get(exam=instance, collection__kind=ADHOCLEARNERSGROUP)
except ExamAssignment.DoesNotExist:
adhoc_group_assignment = None
if not learners:
# Setting learner_ids to empty, so only need to do something
# if there is already an adhoc_group_assignment defined
if adhoc_group_assignment is not None:
# Adhoc group already exists delete it and the assignment
# cascade deletion should also delete the adhoc_group_assignment
adhoc_group_assignment.collection.delete()
else:
if adhoc_group_assignment is None:
# There is no adhoc group right now, so just make a new one
adhoc_group = create_adhoc_group_for_learners(
instance.collection, learners
)
self._create_exam_assignment(exam=instance, collection=adhoc_group)
else:
# There is an adhoc group, so we need to potentially update its membership
original_learner_ids = Membership.objects.filter(
collection=adhoc_group_assignment.collection
).values_list("user_id", flat=True)
original_learner_ids_set = set(original_learner_ids)
learner_ids_set = {learner.id for learner in learners}
if original_learner_ids_set != learner_ids_set:
# Only bother to do anything if these are different
new_learner_ids = learner_ids_set - original_learner_ids_set
deleted_learner_ids = original_learner_ids_set - learner_ids_set
if deleted_learner_ids:
Membership.objects.filter(
collection=adhoc_group_assignment.collection,
user_id__in=deleted_learner_ids,
).delete()
for new_learner_id in new_learner_ids:
Membership.objects.create(
user_id=new_learner_id,
collection=adhoc_group_assignment.collection,
)
| {
"content_hash": "331d3ecdf413bee4d1aff94182771c2e",
"timestamp": "",
"source": "github",
"line_count": 218,
"max_line_length": 104,
"avg_line_length": 42.022935779816514,
"alnum_prop": 0.614561729068879,
"repo_name": "learningequality/kolibri",
"id": "4b31dd94e4e45f54a4c161662d056e24eb1c00b1",
"size": "9161",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "kolibri/core/exams/serializers.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3095586"
},
{
"name": "Dockerfile",
"bytes": "3559"
},
{
"name": "Gherkin",
"bytes": "996801"
},
{
"name": "HTML",
"bytes": "22573"
},
{
"name": "JavaScript",
"bytes": "2233801"
},
{
"name": "Makefile",
"bytes": "12972"
},
{
"name": "Python",
"bytes": "3652744"
},
{
"name": "SCSS",
"bytes": "8551"
},
{
"name": "Shell",
"bytes": "3867"
},
{
"name": "Vue",
"bytes": "2193917"
}
],
"symlink_target": ""
} |
"""
Plugin system for Twisted.
@author: U{Jp Calderone<mailto:exarkun@twistedmatrix.com>}
@author: U{Glyph Lefkowitz<mailto:glyph@twistedmatrix.com>}
"""
from __future__ import generators
import os, errno
from zope.interface import Interface, providedBy
try:
import cPickle as pickle
except ImportError:
import pickle
from twisted.python.components import getAdapterFactory
from twisted.python.reflect import namedAny
from twisted.python.win32 import ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND
from twisted.python.win32 import ERROR_INVALID_NAME, WindowsError
from twisted.python import log
try:
from os import stat_float_times
from os.path import getmtime as _getmtime
def getmtime(x):
sft = stat_float_times()
stat_float_times(True)
try:
return _getmtime(x)
finally:
stat_float_times(sft)
except:
from os.path import getmtime
class IPlugin(Interface):
"""Interface that must be implemented by all plugins.
Only objects which implement this interface will be considered for
return by C{getPlugins}. To be useful, plugins should also
implement some other application-specific interface.
"""
class ITestPlugin(Interface):
"""A plugin for use by the plugin system's unit tests.
Do not use this.
"""
class ITestPlugin2(Interface):
"""See L{ITestPlugin}.
"""
class CachedPlugin(object):
def __init__(self, dropin, name, description, provided):
self.dropin = dropin
self.name = name
self.description = description
self.provided = provided
self.dropin.plugins.append(self)
def __repr__(self):
return '<CachedPlugin %r/%r (provides %r)>' % (
self.name, self.dropin.moduleName,
', '.join([i.__name__ for i in self.provided]))
def load(self):
return namedAny(self.dropin.moduleName + '.' + self.name)
def __conform__(self, interface, registry=None, default=None):
for providedInterface in self.provided:
if providedInterface.isOrExtends(interface):
return self.load()
if getAdapterFactory(providedInterface, interface, None) is not None:
return interface(self.load(), default)
return default
# backwards compat HOORJ
getComponent = __conform__
class CachedDropin(object):
def __init__(self, moduleName, description):
self.moduleName = moduleName
self.description = description
self.plugins = []
def _generateCacheEntry(provider):
dropin = CachedDropin(provider.__name__,
provider.__doc__)
for k, v in provider.__dict__.iteritems():
plugin = IPlugin(v, None)
if plugin is not None:
cachedPlugin = CachedPlugin(dropin, k, v.__doc__, list(providedBy(plugin)))
return dropin
try:
fromkeys = dict.fromkeys
except AttributeError:
def fromkeys(keys, value=None):
d = {}
for k in keys:
d[k] = value
return d
_exts = fromkeys(['.py', '.so', '.pyd', '.dll'])
def getCache(module):
topcache = {}
for p in module.__path__:
dropcache = os.path.join(p, "dropin.cache")
try:
cache = pickle.load(file(dropcache))
lastCached = getmtime(dropcache)
dirtyCache = False
except:
cache = {}
lastCached = 0
dirtyCache = True
try:
dropinNames = os.listdir(p)
except WindowsError, e:
# WindowsError is an OSError subclass, so if not for this clause
# the OSError clause below would be handling these. Windows
# error codes aren't the same as POSIX error codes, so we need
# to handle them differently.
# Under Python 2.5 on Windows, WindowsError has a winerror
# attribute and an errno attribute. The winerror attribute is
# bound to the Windows error code while the errno attribute is
# bound to a translation of that code to a perhaps equivalent
# POSIX error number.
# Under Python 2.4 on Windows, WindowsError only has an errno
# attribute. It is bound to the Windows error code.
# For simplicity of code and to keep the number of paths through
# this suite minimal, we grab the Windows error code under
# either version.
# Furthermore, attempting to use os.listdir on a non-existent
# path in Python 2.4 will result in a Windows error code of
# ERROR_PATH_NOT_FOUND. However, in Python 2.5,
# ERROR_FILE_NOT_FOUND results instead. -exarkun
err = getattr(e, 'winerror', e.errno)
if err in (ERROR_PATH_NOT_FOUND, ERROR_FILE_NOT_FOUND):
continue
elif err == ERROR_INVALID_NAME:
log.msg("Invalid path %r in search path for %s" % (p, module.__name__))
continue
else:
raise
except OSError, ose:
if ose.errno not in (errno.ENOENT, errno.ENOTDIR):
raise
else:
continue
else:
pys = {}
for dropinName in dropinNames:
moduleName, moduleExt = os.path.splitext(dropinName)
if moduleName != '__init__' and moduleExt in _exts:
pyFile = os.path.join(p, dropinName)
try:
pys[moduleName] = getmtime(pyFile)
except:
log.err()
for moduleName, lastChanged in pys.iteritems():
if lastChanged >= lastCached or moduleName not in cache:
dirtyCache = True
try:
provider = namedAny(module.__name__ + '.' + moduleName)
except:
log.err()
else:
entry = _generateCacheEntry(provider)
cache[moduleName] = entry
for moduleName in cache.keys():
if moduleName not in pys:
dirtyCache = True
del cache[moduleName]
topcache.update(cache)
if dirtyCache:
newCacheData = pickle.dumps(cache, 2)
tmpCacheFile = dropcache + ".new"
try:
stage = 'opening'
f = file(tmpCacheFile, 'wb')
stage = 'writing'
f.write(newCacheData)
stage = 'closing'
f.close()
stage = 'renaming'
os.rename(tmpCacheFile, dropcache)
except (OSError, IOError), e:
# A large number of errors can occur here. There's nothing we
# can really do about any of them, but they are also non-fatal
# (they only slow us down by preventing results from being
# cached). Notify the user of the error, but proceed as if it
# had not occurred.
log.msg("Error %s plugin cache file %r (%r): %r" % (
stage, tmpCacheFile, dropcache, os.strerror(e.errno)))
return topcache
import twisted.plugins
def getPlugins(interface, package=twisted.plugins):
"""Retrieve all plugins implementing the given interface beneath the given module.
@param interface: An interface class. Only plugins which
implement this interface will be returned.
@param package: A package beneath which plugins are installed. For
most uses, the default value is correct.
@return: An iterator of plugins.
"""
allDropins = getCache(package)
for dropin in allDropins.itervalues():
for plugin in dropin.plugins:
try:
adapted = interface(plugin, None)
except:
log.err()
else:
if adapted is not None:
yield adapted
# Old, backwards compatible name. Don't use this.
getPlugIns = getPlugins
__all__ = ['getPlugins']
| {
"content_hash": "bd13264f9539bce9208bc3f1108ee1b0",
"timestamp": "",
"source": "github",
"line_count": 239,
"max_line_length": 87,
"avg_line_length": 34.01255230125523,
"alnum_prop": 0.5816213556403002,
"repo_name": "santisiri/popego",
"id": "c867441b21cd398ca9336e9d3bbcc53956b572df",
"size": "8242",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "envs/ALPHA-POPEGO/lib/python2.5/site-packages/twisted/plugin.py",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1246"
},
{
"name": "C",
"bytes": "504141"
},
{
"name": "C++",
"bytes": "26125"
},
{
"name": "CSS",
"bytes": "342653"
},
{
"name": "FORTRAN",
"bytes": "4872"
},
{
"name": "GAP",
"bytes": "13267"
},
{
"name": "Genshi",
"bytes": "407"
},
{
"name": "Groff",
"bytes": "17116"
},
{
"name": "HTML",
"bytes": "383181"
},
{
"name": "JavaScript",
"bytes": "1090769"
},
{
"name": "Makefile",
"bytes": "2441"
},
{
"name": "Mako",
"bytes": "376944"
},
{
"name": "Python",
"bytes": "20895618"
},
{
"name": "Ruby",
"bytes": "3380"
},
{
"name": "Shell",
"bytes": "23581"
},
{
"name": "Smarty",
"bytes": "522"
},
{
"name": "TeX",
"bytes": "35712"
}
],
"symlink_target": ""
} |
from selenium import webdriver
from selenium.test.selenium.webdriver.common import form_handling_tests
from selenium.test.selenium.webdriver.common.webserver import SimpleWebServer
def setup_module(module):
webserver = SimpleWebServer()
webserver.start()
IeFormHandlingTests.webserver = webserver
IeFormHandlingTests.driver = webdriver.Ie()
class IeFormHandlingTests(form_handling_tests.FormHandlingTests):
pass
def teardown_module(module):
IeFormHandlingTests.driver.quit()
IeFormHandlingTests.webserver.stop()
| {
"content_hash": "9c996aeb0a35c9c5a8f0af6ebb50c5e9",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 77,
"avg_line_length": 30.333333333333332,
"alnum_prop": 0.7967032967032966,
"repo_name": "akiellor/selenium",
"id": "f3eb288a2d7106846abcb771a6e9c399f900967b",
"size": "1191",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "py/test/selenium/webdriver/ie/test_ie_form_handling.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "22777"
},
{
"name": "C",
"bytes": "13787069"
},
{
"name": "C#",
"bytes": "1592944"
},
{
"name": "C++",
"bytes": "39839762"
},
{
"name": "Java",
"bytes": "5948691"
},
{
"name": "JavaScript",
"bytes": "15038006"
},
{
"name": "Objective-C",
"bytes": "331601"
},
{
"name": "Python",
"bytes": "544265"
},
{
"name": "Ruby",
"bytes": "557579"
},
{
"name": "Shell",
"bytes": "21701"
}
],
"symlink_target": ""
} |
"""
Django settings for smsgw project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'gj+!@7r31*2(01l_21sspkgbq%ro#%8s0k14akw4mkt^$2razj'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'south',
'core',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'project.urls'
WSGI_APPLICATION = 'project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'smsgw',
'USER': 'smsgw',
'PASSWORD': 'smsgw',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'
| {
"content_hash": "7fa0b17cc77288fc9f15c878708fe7b4",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 71,
"avg_line_length": 23.208791208791208,
"alnum_prop": 0.7002840909090909,
"repo_name": "rafael84/sms-gw",
"id": "293f62725dd8096b0178e93146e33fb3ccb33ff9",
"size": "2112",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/project/settings.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "324"
},
{
"name": "Python",
"bytes": "3402"
}
],
"symlink_target": ""
} |
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../'))
import mw
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.mathjax',
'sphinx.ext.viewcode',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'mediawiki-utilities'
copyright = '2014, Aaron Halfaker'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = mw.__version__
# The full version, including alpha/beta/rc tags.
release = mw.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'mediawiki-utilitiesdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'mediawiki-utilities.tex', 'mediawiki-utilities Documentation',
'Aaron Halfaker', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'mediawiki-utilities', 'mediawiki-utilities Documentation',
['Aaron Halfaker'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'mediawiki-utilities', 'mediawiki-utilities Documentation',
'Aaron Halfaker', 'mediawiki-utilities', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
| {
"content_hash": "0b60c0d35ca3f734967b5a41052a96ef",
"timestamp": "",
"source": "github",
"line_count": 252,
"max_line_length": 79,
"avg_line_length": 31.793650793650794,
"alnum_prop": 0.7061907139291064,
"repo_name": "makoshark/Mediawiki-Utilities",
"id": "08dae411878e9acdd08859e969c0f77c52f8cd43",
"size": "8467",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "doc/conf.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "208521"
}
],
"symlink_target": ""
} |
import numpy as np
import theano
from theano import tensor as T
from theano.tensor.nnet import conv2d
from theano.tensor.signal import downsample
import glob
from PIL import Image, ImageDraw
try:
import cPickle as pickle
except:
import pickle
import sys
sys.setrecursionlimit(10000)
regularization = 0.01
convolutional_layers = 2
feature_maps = [4,5,5]
filter_shapes = [(5,5),(5,5)]
poolsize = [(2,2),(2,2)]
feedforward_layers = 1
feedforward_nodes = [100]
classes = 2
class convolutional_layer(object):
def __init__(self, input, output_maps, input_maps, filter_height, filter_width, poolsize=(2,2)):
self.input = input
self.bound = np.sqrt(6./(input_maps*filter_height*filter_width + output_maps*filter_height*filter_width//np.prod(poolsize)))
self.w = theano.shared(np.asarray(np.random.uniform(low=-self.bound,high=self.bound,size=(output_maps, input_maps, filter_height, filter_width)),dtype=input.dtype))
self.b = theano.shared(np.asarray(np.random.uniform(low=-.5, high=.5, size=(output_maps)),dtype=input.dtype))
self.conv_out = conv2d(input=self.input, filters=self.w)
self.pooled_out = downsample.max_pool_2d(self.conv_out, ds=poolsize, ignore_border=True)
self.output = T.tanh(self.pooled_out + self.b.dimshuffle('x', 0, 'x', 'x'))
def get_params(self):
return self.w,self.b
class feedforward_layer(object):
def __init__(self,input,features,nodes):
self.input = input
self.bound = np.sqrt(1.5/(features+nodes))
self.w = theano.shared(np.asarray(np.random.uniform(low=-self.bound,high=self.bound,size=(features,nodes)),dtype=theano.config.floatX))
self.b = theano.shared(np.asarray(np.random.uniform(low=-.5, high=.5, size=(nodes)),dtype=theano.config.floatX))
self.output = T.nnet.sigmoid(-T.dot(self.input,self.w)-self.b)
def get_params(self):
return self.w,self.b
class neural_network(object):
def __init__(self,convolutional_layers,feature_maps,filter_shapes,poolsize,feedforward_layers,feedforward_nodes,classes,regularization):
self.input = T.tensor4()
self.convolutional_layers = []
self.convolutional_layers.append(convolutional_layer(self.input,feature_maps[1],feature_maps[0],filter_shapes[0][0],filter_shapes[0][1],poolsize[0]))
for i in range(1,convolutional_layers):
self.convolutional_layers.append(convolutional_layer(self.convolutional_layers[i-1].output,feature_maps[i+1],feature_maps[i],filter_shapes[i][0],filter_shapes[i][1],poolsize[i]))
self.feedforward_layers = []
self.feedforward_layers.append(feedforward_layer(self.convolutional_layers[-1].output.flatten(2),flattened,feedforward_nodes[0]))
for i in range(1,feedforward_layers):
self.feedforward_layers.append(feedforward_layer(self.feedforward_layers[i-1].output,feedforward_nodes[i-1],feedforward_nodes[i]))
self.output_layer = feedforward_layer(self.feedforward_layers[-1].output,feedforward_nodes[-1],classes)
self.params = []
for l in self.convolutional_layers + self.feedforward_layers:
self.params.extend(l.get_params())
self.params.extend(self.output_layer.get_params())
self.target = T.matrix()
self.output = self.output_layer.output
self.cost = -self.target*T.log(self.output)-(1-self.target)*T.log(1-self.output)
self.cost = self.cost.mean()
for i in range(convolutional_layers+feedforward_layers+1):
self.cost += regularization*(self.params[2*i]**2).mean()
self.updates = self.adam(self.cost,self.params)
self.propogate = theano.function([self.input,self.target],self.cost,updates=self.updates,allow_input_downcast=True)
self.classify = theano.function([self.input],self.output,allow_input_downcast=True)
def adam(self, cost, params, lr=0.0002, b1=0.1, b2=0.01, e=1e-8):
updates = []
grads = T.grad(cost, params)
self.i = theano.shared(np.float32(0.))
i_t = self.i + 1.
fix1 = 1. - (1. - b1)**i_t
fix2 = 1. - (1. - b2)**i_t
lr_t = lr * (T.sqrt(fix2) / fix1)
for p, g in zip(params, grads):
self.m = theano.shared(p.get_value() * 0.)
self.v = theano.shared(p.get_value() * 0.)
m_t = (b1 * g) + ((1. - b1) * self.m)
v_t = (b2 * T.sqr(g)) + ((1. - b2) * self.v)
g_t = m_t / (T.sqrt(v_t) + e)
p_t = p - (lr_t * g_t)
updates.append((self.m, m_t))
updates.append((self.v, v_t))
updates.append((p, p_t))
updates.append((self.i, i_t))
return updates
def train(self,X,y,batch_size=None):
if batch_size:
indices = np.random.permutation(X.shape[0])[:batch_size]
X = X[indices,:,:,:]
y = y[indices]
target = np.zeros((y.shape[0],len(np.unique(y))))
for i in range(len(np.unique(y))):
target[y==i,i] = 1
return self.propogate(X,target)
def predict(self,X):
prediction = self.classify(X)
return (prediction, np.argmax(prediction,axis=1))
try:
with open("conv_net.dat","rb") as pickle_nn:
nn = pickle.load(pickle_nn)
print "saved convoluation neural network loaded"
except:
print "loading images"
X = np.empty((0,4,200,200))
y = []
dory_path = glob.glob('Dory/*.PNG')
dory = [Image.open(img) for img in dory_path]
dory = [img.resize((200,200), Image.ANTIALIAS) for img in dory]
for image in dory:
img = np.array(image,dtype='float64')/256
img = img.transpose(2, 0, 1).reshape(1,4,200,200)
X = np.concatenate((X,img),axis=0)
y.append(1)
not_dory_path = glob.glob('Not_Dory/*.PNG')
not_dory = [Image.open(img) for img in not_dory_path]
not_dory = [img.resize((200,200), Image.ANTIALIAS) for img in not_dory]
for image in not_dory:
img = np.array(image,dtype='float64')/256
img = img.transpose(2, 0, 1).reshape(1,4,200,200)
X = np.concatenate((X,img),axis=0)
y.append(0)
y = np.array(y)
flattened = list(X.shape[2:])
for i in range(convolutional_layers):
flattened[0] = flattened[0] - filter_shapes[i][0] + 1
flattened[1] = flattened[1] - filter_shapes[i][1] + 1
flattened[0] = flattened[0]/poolsize[i][0]
flattened[1] = flattened[1]/poolsize[i][1]
flattened = np.prod(flattened)
flattened *= feature_maps[-1]
print "building convolutional neural network"
nn = neural_network(convolutional_layers,feature_maps,filter_shapes,poolsize,feedforward_layers,feedforward_nodes,classes,regularization)
for i in range(750):
error = nn.train(X,y,50)
print "step %i training error: %f" % (i+1, error)
with open("conv_net.dat","wb") as f:
pickle.dump(nn,f,pickle.HIGHEST_PROTOCOL)
print "finding dory in scenes"
scene_path = glob.glob('Scenes/*.PNG')
scenes = [Image.open(img) for img in scene_path]
scan_sizes = [500,450,400,350,300,250,200]
for s in range(len(scenes)):
print "scanning scene %i of %i" % (s+1, len(scenes))
max_prob = 0
for scan in scan_sizes:
for i in range(0,scenes[s].size[0]-scan,25):
for j in range(0,scenes[s].size[1]-scan,25):
img = scenes[s].crop((i,j,i+scan,j+scan))
img = img.resize((200,200), Image.ANTIALIAS)
img = np.array(img,dtype='float64')/256
img = img.transpose(2, 0, 1).reshape(1,4,200,200)
probs,pred = nn.predict(img)
if probs[0,1] > max_prob:
dims = (i,j,i+scan,j+scan)
max_prob = probs[0,1]
box = ImageDraw.Draw(scenes[s])
box.rectangle(dims,outline=255)
box.rectangle((dims[0]-1,dims[1]-1,dims[2]+1,dims[3]+1),outline=255)
box.rectangle((dims[0]-2,dims[1]-2,dims[2]+2,dims[3]+2),outline=255)
scenes[s].show()
scenes[s].save('scene%i.jpg' % (int(s)+1),quality=100) | {
"content_hash": "d3130ae4f5fa63b3783d74792555799c",
"timestamp": "",
"source": "github",
"line_count": 176,
"max_line_length": 190,
"avg_line_length": 45.86363636363637,
"alnum_prop": 0.6204162537165511,
"repo_name": "iamshang1/Projects",
"id": "d2dd43bb3dab9be061487be9e26c01920147119b",
"size": "8072",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Advanced_ML/Finding_Dory/conv_net.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "20611"
},
{
"name": "Python",
"bytes": "817324"
}
],
"symlink_target": ""
} |
"""Support for Lutron lights."""
from __future__ import annotations
from homeassistant.components.light import ATTR_BRIGHTNESS, ColorMode, LightEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from . import LUTRON_CONTROLLER, LUTRON_DEVICES, LutronDevice
def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the Lutron lights."""
devs = []
for (area_name, device) in hass.data[LUTRON_DEVICES]["light"]:
dev = LutronLight(area_name, device, hass.data[LUTRON_CONTROLLER])
devs.append(dev)
add_entities(devs, True)
def to_lutron_level(level):
"""Convert the given Home Assistant light level (0-255) to Lutron (0.0-100.0)."""
return float((level * 100) / 255)
def to_hass_level(level):
"""Convert the given Lutron (0.0-100.0) light level to Home Assistant (0-255)."""
return int((level * 255) / 100)
class LutronLight(LutronDevice, LightEntity):
"""Representation of a Lutron Light, including dimmable."""
_attr_color_mode = ColorMode.BRIGHTNESS
_attr_supported_color_modes = {ColorMode.BRIGHTNESS}
def __init__(self, area_name, lutron_device, controller):
"""Initialize the light."""
self._prev_brightness = None
super().__init__(area_name, lutron_device, controller)
@property
def brightness(self):
"""Return the brightness of the light."""
new_brightness = to_hass_level(self._lutron_device.last_level())
if new_brightness != 0:
self._prev_brightness = new_brightness
return new_brightness
def turn_on(self, **kwargs):
"""Turn the light on."""
if ATTR_BRIGHTNESS in kwargs and self._lutron_device.is_dimmable:
brightness = kwargs[ATTR_BRIGHTNESS]
elif self._prev_brightness == 0:
brightness = 255 / 2
else:
brightness = self._prev_brightness
self._prev_brightness = brightness
self._lutron_device.level = to_lutron_level(brightness)
def turn_off(self, **kwargs):
"""Turn the light off."""
self._lutron_device.level = 0
@property
def extra_state_attributes(self):
"""Return the state attributes."""
return {"lutron_integration_id": self._lutron_device.id}
@property
def is_on(self):
"""Return true if device is on."""
return self._lutron_device.last_level() > 0
def update(self):
"""Call when forcing a refresh of the device."""
if self._prev_brightness is None:
self._prev_brightness = to_hass_level(self._lutron_device.level)
| {
"content_hash": "b630338c4fc23cdf999b98b26266a4d1",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 85,
"avg_line_length": 33.88095238095238,
"alnum_prop": 0.6553056921995783,
"repo_name": "toddeye/home-assistant",
"id": "52ff2d7843cc1f2766685ffe113d933f0aea36d1",
"size": "2846",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "homeassistant/components/lutron/light.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "3005"
},
{
"name": "PLSQL",
"bytes": "840"
},
{
"name": "Python",
"bytes": "47414832"
},
{
"name": "Shell",
"bytes": "6252"
}
],
"symlink_target": ""
} |
from msrest.pipeline import ClientRawResponse
from .. import models
class BoolModel(object):
"""BoolModel operations.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An objec model deserializer.
"""
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.config = config
def get_true(
self, custom_headers={}, raw=False, **operation_config):
"""
Get true Boolean value
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: bool
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/bool/true'
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('bool', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
def put_true(
self, bool_body, custom_headers={}, raw=False, **operation_config):
"""
Set Boolean value true
:param bool_body:
:type bool_body: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/bool/true'
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
body_content = self._serialize.body(bool_body, 'bool')
# Construct and send request
request = self._client.put(url, query_parameters)
response = self._client.send(
request, header_parameters, body_content, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def get_false(
self, custom_headers={}, raw=False, **operation_config):
"""
Get false Boolean value
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: bool
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/bool/false'
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('bool', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
def put_false(
self, bool_body, custom_headers={}, raw=False, **operation_config):
"""
Set Boolean value false
:param bool_body:
:type bool_body: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/bool/false'
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
body_content = self._serialize.body(bool_body, 'bool')
# Construct and send request
request = self._client.put(url, query_parameters)
response = self._client.send(
request, header_parameters, body_content, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def get_null(
self, custom_headers={}, raw=False, **operation_config):
"""
Get null Boolean value
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: bool
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/bool/null'
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('bool', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
def get_invalid(
self, custom_headers={}, raw=False, **operation_config):
"""
Get invalid Boolean value
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: bool
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/bool/invalid'
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('bool', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
| {
"content_hash": "7db81538230916bedbcb79c02de46d73",
"timestamp": "",
"source": "github",
"line_count": 283,
"max_line_length": 84,
"avg_line_length": 33.342756183745585,
"alnum_prop": 0.6232513777024162,
"repo_name": "stankovski/AutoRest",
"id": "0ec9dc24c7a63aa3159888e9b0c15bd65faf3743",
"size": "9910",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyBoolean/autorestbooltestservice/operations/bool_model.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "13761"
},
{
"name": "C#",
"bytes": "10152265"
},
{
"name": "CSS",
"bytes": "110"
},
{
"name": "HTML",
"bytes": "274"
},
{
"name": "Java",
"bytes": "4574687"
},
{
"name": "JavaScript",
"bytes": "4537453"
},
{
"name": "PowerShell",
"bytes": "5703"
},
{
"name": "Python",
"bytes": "2190545"
},
{
"name": "Ruby",
"bytes": "230057"
},
{
"name": "Shell",
"bytes": "142"
},
{
"name": "TypeScript",
"bytes": "173987"
}
],
"symlink_target": ""
} |
import _plotly_utils.basevalidators
class NticksValidator(_plotly_utils.basevalidators.IntegerValidator):
def __init__(
self, plotly_name="nticks", parent_name="histogram2dcontour.colorbar", **kwargs
):
super(NticksValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "colorbars"),
min=kwargs.pop("min", 0),
role=kwargs.pop("role", "style"),
**kwargs
)
| {
"content_hash": "f70166ff821c42a6a930154062da42ae",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 87,
"avg_line_length": 34.46666666666667,
"alnum_prop": 0.5938104448742747,
"repo_name": "plotly/python-api",
"id": "ebeddeb66ad7a63f4468c02f5fb912c653b40ebc",
"size": "517",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/python/plotly/plotly/validators/histogram2dcontour/colorbar/_nticks.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "6870"
},
{
"name": "Makefile",
"bytes": "1708"
},
{
"name": "Python",
"bytes": "823245"
},
{
"name": "Shell",
"bytes": "3238"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.db import migrations, models
import picture.models
import picturepay.storage
class Migration(migrations.Migration):
dependencies = [
('picture', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='picture',
name='complete',
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name='picture',
name='covered_image',
field=models.ImageField(blank=True, storage=picturepay.storage.OverwriteStorage(), upload_to=picture.models.covered_picture_path),
),
migrations.AlterField(
model_name='picture',
name='image',
field=models.ImageField(height_field='height', upload_to=picture.models.picture_path, width_field='width'),
),
]
| {
"content_hash": "be1378805820295fb6a9f9823e6d12f0",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 142,
"avg_line_length": 29.8,
"alnum_prop": 0.6174496644295302,
"repo_name": "ZzCalvinzZ/picturepay",
"id": "70fae36b6ed36afc294953eae64b3a4742709cee",
"size": "967",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "picture/migrations/0002_auto_20161010_2322.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1794"
},
{
"name": "HTML",
"bytes": "7661"
},
{
"name": "JavaScript",
"bytes": "460"
},
{
"name": "Python",
"bytes": "27387"
}
],
"symlink_target": ""
} |
import socket
import sys
import struct
import time
class Modbus_TCP_Control:
def __init__( self ):
self.modbus_devices = {}
def connect_socket( self, modbus_device ):
try:
sock = modbus_device["sock"]
sock.connect(modbus_device["address_port"])
modbus_device["connected"] = True
except:
print "connect socket exception --- should not happen"
modbus_device["connected"] = False
def disconnect_socket( self, modbus_device ):
modbus_device["connected"] = False
sock = modbus_device["sock"]
try:
sock.shutdown(1)
sock.close()
except:
print "disconnect exception --- should not happen"
def send_message( self, address, message ):
modbus_device = self.modbus_devices[address]
if modbus_device["connected"] != True:
self.connect_socket( modbus_device )
try:
sock = modbus_device["sock"]
sock.sendall(message)
message = sock.recv(1024)
except:
"this should not happen"
message = ""
return message
def add_device( self, address ,port = 502 ):
self.modbus_devices[address] = {}
self.modbus_devices[address]["address_port"] = ( address,port )
self.modbus_devices[address]["sock"] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect_socket( self.modbus_devices[address] )
def ping_device( self,address ,register ):
slave_id = 1
payload = struct.pack("<BBBBBB",slave_id,3,(register>>8)&255,register&255,0,1) # read register 0 1 length
calculatedChecksum = self._calculateCrcString(payload)
payload = payload+calculatedChecksum
response = self.process_message(address,payload )
receivedChecksum = response[-2:]
responseWithoutChecksum = response[0 : len(response) - 2]
calculatedChecksum = self._calculateCrcString(responseWithoutChecksum)
return_value = receivedChecksum == calculatedChecksum # check checksum
return return_value
def unpack_message( self, message):
payload = message[6:]
calculatedChecksum = self._calculateCrcString(payload)
payload = payload+calculatedChecksum
return payload
def format_message( self, message):
no_crc_msg = message[0:len(message)-2]
no_crc_length = len(no_crc_msg)
length_high = chr( (no_crc_length >> 8)&0xff)
length_low = chr(no_crc_length&0xff)
temp_message = "".join( [chr(0),chr(0),chr(0),chr(0),length_high,length_low,no_crc_msg])
return temp_message
def _calculateCrcString(self,inputstring):
"""Calculate CRC-16 for Modbus.
Args:
inputstring (str): An arbitrary-length message (without the CRC).
Returns:
A two-byte CRC string, where the least significant byte is first.
Algorithm from the document 'MODBUS over serial line specification and implementation guide V1.02'.
"""
# Constant for MODBUS CRC-16
POLY = 0xA001
# Preload a 16-bit register with ones
register = 0xFFFF
for character in inputstring:
# XOR with each character
register = register ^ ord(character)
# Rightshift 8 times, and XOR with polynom if carry overflows
for i in range(8):
carrybit = register & 1
register = register >> 1
if carrybit == 1:
register = register ^ POLY
return struct.pack('<H', register)
def process_message( self, ip_address, message, counters = None ):
message = self.format_message( message)
for i in range(0,10):
try:
response = self.send_message( ip_address, message )
response = self.unpack_message( response)
if len(response ) > 4:
receivedChecksum = response[-2:]
responseWithoutChecksum = response[0 : len(response) - 2]
calculatedChecksum = self._calculateCrcString(responseWithoutChecksum)
if (receivedChecksum == calculatedChecksum):
if counters != None:
counters["counts"] = counters["counts"] +1
return response
else:
if counters != None:
counters["failures"] = counters["failures"] +1
time.sleep(.1)
except:
print "except should not happen"
response = ""
if counters != None:
counters["total_failures"] = counters["total_failures"] +1
return response
if __name__ == "__main__":
tcp_mgr = Modbus_TCP_Control()
tcp_mgr.add_device( "192.168.1.153" )
print tcp_mgr.ping_device("192.168.1.153" ,0 )
#print tcp_mgr.modbus_devices
#tcp_mgr.disconnect_socket(tcp_mgr.modbus_devices["192.168.1.153"])
#print tcp_mgr.modbus_devices
'''
#
# File: rs485_mgr.py
# This file handles low level rs485 communication
#
#
#
#
#
import os
import time
import myModbus
import struct
from myModbus import *
class RS485_Mgr():
def __init__( self ):
pass
def open( self, interface_parameters ):
try:
self.instrument = Instrument(interface_parameters["interface"],31 ) # 10 is instrument address
self.instrument.serial.timeout = interface_parameters["timeout"]
self.instrument.serial.parity = serial.PARITY_NONE
self.instrument.serial.baudrate = interface_parameters["baud_rate"]
self.instrument.debug = None
self.interface_parameters = interface_parameters
return True
except:
return False
def close( self ):
try:
self.instrument.serial.close()
del(self.instrument)
self.params = None
except:
pass
def process_message( self, parameters, message, counters = None ):
print "made it to rs485"
for i in range(0,10):
try:
response = ""
response = self.instrument._communicate( message, 1024)
print "message",[message],len(response),[response]
if len(response ) > 4:
receivedChecksum = response[-2:]
responseWithoutChecksum = response[0 : len(response) - 2]
calculatedChecksum = self._calculateCrcString(responseWithoutChecksum)
print "crc",[receivedChecksum, calculatedChecksum], ord(message[0]),parameters["address"]
if (receivedChecksum == calculatedChecksum) and (ord(message[0]) == parameters["address"] ): # check checksum
print "made it here",counters
if counters != None:
counters["counts"] = counters["counts"] +1
return response
else:
if counters != None:
counters["failures"] = counters["failures"] +1
time.sleep(self.instrument.timeout)
except:
response = ""
if counters != None:
counters["total_failures"] = counters["total_failures"] +1
return response
def find_address( self, parameters):
return parameters["address"]
def probe_register( self, parameters ):
address = parameters["address"]
register = parameters["search_register"]
payload = struct.pack("<BBBBBB",address,3,(register>>8)&255,register&255,0,1) # read register 0 1 length
calculatedChecksum = self._calculateCrcString(payload)
payload = payload+calculatedChecksum
response = self.process_message(parameters,payload )
receivedChecksum = response[-2:]
responseWithoutChecksum = response[0 : len(response) - 2]
calculatedChecksum = self._calculateCrcString(responseWithoutChecksum)
return_value = receivedChecksum == calculatedChecksum # check checksum
if return_value == True :
return_value = address == ord(response[0]) # check address
return return_value
def _rightshift( self, inputInteger):
shifted = inputInteger >> 1
carrybit = inputInteger & 1
return shifted, carrybit
def _calculateCrcString(self,inputstring):
# Constant for MODBUS CRC-16
POLY = 0xA001
# Preload a 16-bit register with ones
register = 0xFFFF
for character in inputstring:
# XOR with each character
register = register ^ ord(character)
# Rightshift 8 times, and XOR with polynom if carry overflows
for i in range(8):
register, carrybit = self._rightshift(register)
if carrybit == 1:
register = register ^ POLY
return struct.pack("<H",register)
if __name__ == "__main__":
rs485_mgr = RS485_Mgr()
interface_parameters = {}
interface_parameters["interface"] = "/dev/ttyACM0"
interface_parameters["baud_rate"] = 38400
interface_parameters["timeout"] = .15
parameters = {}
parameters["address"] = 31
parameters["search_register"] = 0
if rs485_mgr.open(interface_parameters ):
print rs485_mgr.probe_register( parameters )
rs485_mgr.close()
'''
| {
"content_hash": "bd6690af26e79b123b995b393e54053a",
"timestamp": "",
"source": "github",
"line_count": 302,
"max_line_length": 136,
"avg_line_length": 33.026490066225165,
"alnum_prop": 0.5592540605574494,
"repo_name": "glenn-edgar/local_controller_3",
"id": "d6b8aa03ebe67815bba81bc81bd1ffbb051516e5",
"size": "10018",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "modbus_redis_server_py3/modbus_tcp_control_py3.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2510"
},
{
"name": "CSS",
"bytes": "4575415"
},
{
"name": "HTML",
"bytes": "2215958"
},
{
"name": "JavaScript",
"bytes": "9981211"
},
{
"name": "Makefile",
"bytes": "5136"
},
{
"name": "PHP",
"bytes": "124476"
},
{
"name": "Python",
"bytes": "4396570"
},
{
"name": "Shell",
"bytes": "569"
},
{
"name": "Smalltalk",
"bytes": "252"
},
{
"name": "TeX",
"bytes": "3153"
},
{
"name": "TypeScript",
"bytes": "11006"
}
],
"symlink_target": ""
} |
"""This file contains a WinRAR history Windows Registry plugin."""
import re
from plaso.containers import events
from plaso.parsers import winreg_parser
from plaso.parsers.winreg_plugins import interface
class WinRARHistoryEventData(events.EventData):
"""WinRAR history event data attribute container.
Attributes:
entries (str): archive history entries.
key_path (str): Windows Registry key path.
last_written_time (dfdatetime.DateTimeValues): entry last written date and
time.
"""
DATA_TYPE = 'winrar:history'
def __init__(self):
"""Initializes event data."""
super(WinRARHistoryEventData, self).__init__(data_type=self.DATA_TYPE)
self.entries = None
self.key_path = None
self.last_written_time = None
class WinRARHistoryPlugin(interface.WindowsRegistryPlugin):
"""Windows Registry plugin for parsing WinRAR History keys."""
NAME = 'winrar_mru'
DATA_FORMAT = 'WinRAR History Registry data'
FILTERS = frozenset([
interface.WindowsRegistryKeyPathFilter(
'HKEY_CURRENT_USER\\Software\\WinRAR\\ArcHistory'),
interface.WindowsRegistryKeyPathFilter(
'HKEY_CURRENT_USER\\Software\\WinRAR\\DialogEditHistory\\ArcName'),
interface.WindowsRegistryKeyPathFilter(
'HKEY_CURRENT_USER\\Software\\WinRAR\\DialogEditHistory\\ExtrPath')])
_RE_VALUE_NAME = re.compile(r'^[0-9]+$', re.I)
def ExtractEvents(self, parser_mediator, registry_key, **kwargs):
"""Extracts events from a Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfVFS.
registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
"""
entries = []
for registry_value in registry_key.GetValues():
# Ignore any value not in the form: '[0-9]+'.
if (not registry_value.name or
not self._RE_VALUE_NAME.search(registry_value.name)):
continue
# Ignore any value that is empty or that does not contain a string.
if not registry_value.data or not registry_value.DataIsString():
continue
value_string = registry_value.GetDataAsObject()
entries.append('{0:s}: {1:s}'.format(registry_value.name, value_string))
event_data = WinRARHistoryEventData()
event_data.entries = ' '.join(entries) or None
event_data.key_path = registry_key.path
event_data.last_written_time = registry_key.last_written_time
parser_mediator.ProduceEventData(event_data)
winreg_parser.WinRegistryParser.RegisterPlugin(WinRARHistoryPlugin)
| {
"content_hash": "b92bc2d13671e470d2964f1a523552b2",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 79,
"avg_line_length": 34.14473684210526,
"alnum_prop": 0.707514450867052,
"repo_name": "joachimmetz/plaso",
"id": "d3fb5a258d41fe0cb95dc4d09b926125a4993f8f",
"size": "2619",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "plaso/parsers/winreg_plugins/winrar.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "4301"
},
{
"name": "Makefile",
"bytes": "122"
},
{
"name": "PowerShell",
"bytes": "1305"
},
{
"name": "Python",
"bytes": "5345755"
},
{
"name": "Shell",
"bytes": "27279"
},
{
"name": "YARA",
"bytes": "507"
}
],
"symlink_target": ""
} |
from OpenGL.arrays import vbo
from OpenGL.GLES2.VERSION import GLES2_2_0
from OpenGL.GLES2.OES import mapbuffer
class Implementation( vbo.Implementation ):
"""OpenGL-based implementation of VBO interfaces"""
def __init__( self ):
for name in self.EXPORTED_NAMES:
for source in [ GLES2_2_0, mapbuffer ]:
for possible in (name,name+'OES'):
try:
setattr( self, name, getattr( source, possible ))
except AttributeError as err:
pass
else:
found = True
assert found, name
if GLES2_2_0.glBufferData:
self.available = True
Implementation.register()
| {
"content_hash": "eef6e349a6539d3a19489fef75c0023b",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 73,
"avg_line_length": 37.75,
"alnum_prop": 0.5470198675496689,
"repo_name": "alexus37/AugmentedRealityChess",
"id": "fb7811b122904a7fba10519297aa03213ea6aa2e",
"size": "755",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/OpenGL/GLES2/vboimplementation.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "158062"
},
{
"name": "C++",
"bytes": "267993"
},
{
"name": "CMake",
"bytes": "11319"
},
{
"name": "Fortran",
"bytes": "3707"
},
{
"name": "Makefile",
"bytes": "14618"
},
{
"name": "Python",
"bytes": "12813086"
},
{
"name": "Roff",
"bytes": "3310"
},
{
"name": "Shell",
"bytes": "3855"
}
],
"symlink_target": ""
} |
from pyjamas import DOM
from pyjamas import Factory
from CheckBox import CheckBox
class RadioButton(CheckBox):
def __init__(self, group=None, label=None, asHTML=False, **kwargs):
if not kwargs.has_key('StyleName'):kwargs['StyleName']="gwt-RadioButton"
if label:
if asHTML:
kwargs['HTML'] = label
else:
kwargs['Text'] = label
if kwargs.has_key('Element'):
element = kwargs.pop('Element')
else:
element = DOM.createInputRadio(group)
self.initElement(element, **kwargs)
Factory.registerClass('pyjamas.ui.RadioButton', RadioButton)
| {
"content_hash": "0b7dc8bc92ea68a61f774d6ffcfd5c57",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 80,
"avg_line_length": 29.863636363636363,
"alnum_prop": 0.6118721461187214,
"repo_name": "emk/pyjamas",
"id": "f8bc4df1e4e71944ae9d9e32408aabb1e2ee372b",
"size": "1316",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "library/pyjamas/ui/RadioButton.py",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
"""
License: BSD
(c) 2005-2012 ::: www.CodeResort.com - BV Network AS (simon-code@bvnetwork.no)
"""
import unittest
from trac.perm import PermissionSystem, PermissionCache
from trac.test import EnvironmentStub, Mock
from trac.web.api import RequestDone
from trac.web.href import Href
from customfieldadmin.admin import CustomFieldAdminPage
from customfieldadmin.api import CustomFields
class CustomFieldAdminPageTestCase(unittest.TestCase):
def setUp(self):
self.env = EnvironmentStub()
ps = PermissionSystem(self.env)
ps.grant_permission('admin', 'TICKET_ADMIN')
self.plugin = CustomFieldAdminPage(self.env)
self.api = CustomFields(self.env)
def tearDown(self):
if hasattr(self.env, 'destroy_db'):
self.env.destroy_db()
del self.env
def test_create(self):
_redirect_url = ''
def redirect(url):
_redirect_url = url
raise RequestDone
req = Mock(perm=PermissionCache(self.env, 'admin'),
authname='admin',
chrome={},
href=Href('/'),
redirect=redirect,
method='POST',
args={'add': True,
'name': "test",
'type': "textarea",
'label': "testing",
'format': "wiki",
'row': '9',
'columns': '42'})
try:
self.plugin.render_admin_panel(req, 'ticket', 'customfields', None)
except RequestDone, e:
self.assertEquals(
sorted(list(self.env.config.options('ticket-custom'))),
[(u'test', u'textarea'),
(u'test.cols', u'60'),
(u'test.format', u'wiki'),
(u'test.label', u'testing'),
(u'test.options', u''),
(u'test.order', u'1'),
(u'test.rows', u'5'),
(u'test.value', u'')])
def test_add_optional_select(self):
# http://trac-hacks.org/ticket/1834
_redirect_url = ''
def redirect(url):
_redirect_url = url
raise RequestDone
req = Mock(perm=PermissionCache(self.env, 'admin'),
authname='admin',
chrome={},
href=Href('/'),
redirect=redirect,
method='POST',
args={'add': True,
'name': "test",
'type': "select",
'label': "testing",
'options': "\r\none\r\ntwo"})
try:
self.plugin.render_admin_panel(req, 'ticket', 'customfields', None)
except RequestDone, e:
self.assertEquals(
sorted(list(self.env.config.options('ticket-custom'))),
[(u'test', u'select'), (u'test.label', u'testing'),
(u'test.options', u'|one|two'), (u'test.order', u'1'),
(u'test.value', u'')])
def test_apply_optional_select(self):
# Reuse the added custom field that test verified to work
self.test_add_optional_select()
self.assertEquals('select',
self.env.config.get('ticket-custom', 'test'))
# Now check that details are maintained across order change
# that reads fields, deletes them, and creates them again
# http://trac-hacks.org/ticket/1834#comment:5
_redirect_url = ''
def redirect(url):
_redirect_url = url
raise RequestDone
req = Mock(perm=PermissionCache(self.env, 'admin'),
authname='admin',
chrome={},
href=Href('/'),
redirect=redirect,
method='POST',
args={'apply': True,
'order_test': '2'})
try:
self.plugin.render_admin_panel(req, 'ticket', 'customfields', None)
except RequestDone, e:
self.assertEquals(
sorted(list(self.env.config.options('ticket-custom'))),
[(u'test', u'select'), (u'test.label', u'testing'),
(u'test.options', u'|one|two'), (u'test.order', u'2'),
(u'test.value', u'')])
def test_order_with_mismatched_keys(self):
# http://trac-hacks.org/ticket/11540
self.api.create_custom_field({'name': u'one', 'format': 'plain',
'value': '', 'label': u'One', 'type': u'text', 'order': 1})
def redirect(url):
raise RequestDone
req = Mock(perm=PermissionCache(self.env, 'admin'),
authname='admin',
chrome={},
href=Href('/'),
redirect=redirect,
method='POST',
args={'apply': True,
'order_two': '1'})
try:
self.plugin.render_admin_panel(req, 'ticket', 'customfields', None)
except RequestDone, e:
pass
| {
"content_hash": "63101829862243d2868d98a36c0a1745",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 79,
"avg_line_length": 38.72592592592593,
"alnum_prop": 0.4812547819433818,
"repo_name": "jun66j5/trac-customfieldadminplugin",
"id": "73ef29f48c50b230cb737f5596987fd8ccb9edae",
"size": "5252",
"binary": false,
"copies": "1",
"ref": "refs/heads/type-provider",
"path": "customfieldadmin/tests/admin.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "1646"
},
{
"name": "Python",
"bytes": "37542"
}
],
"symlink_target": ""
} |
"""
mfag module which contains the ModflowAg class.
Note that the user can access the ModflowAg class as `flopy.modflow.ModflowAg`.
Additional information for this MODFLOW package can be found at
<https://www.sciencedirect.com/science/article/pii/S1364815219305080>`_.
"""
import os
import numpy as np
from ..pakbase import Package
from ..utils.flopy_io import multi_line_strip
from ..utils.optionblock import OptionBlock
from ..utils.recarray_utils import create_empty_recarray
class ModflowAg(Package):
"""
The ModflowAg class is used to build read, write, and edit data
from the MODFLOW-NWT AG package.
Parameters
----------
model : flopy.modflow.Modflow object
model object
options : flopy.utils.OptionBlock object
option block object
time_series : np.recarray
numpy recarray for the time series block
well_list : np.recarray
recarray of the well_list block
irrdiversion : dict {per: np.recarray}
dictionary of the irrdiversion block
irrwell : dict {per: np.recarray}
dictionary of the irrwell block
supwell : dict {per: np.recarray}
dictionary of the supwell block
extension : str, optional
default is .ag
unitnumber : list, optional
fortran unit number for modflow, default 69
filenames : list, optional
file name for ModflowAwu package to write input
nper : int
number of stress periods in the model
Examples
--------
load a ModflowAg file
>>> import flopy
>>> ml = flopy.modflow.Modflow('agtest')
>>> ag = flopy.modflow.ModflowAg.load('test.ag', ml, nper=2)
"""
_options = dict(
[
("noprint", OptionBlock.simple_flag),
(
"irrigation_diversion",
{
OptionBlock.dtype: np.bool_,
OptionBlock.nested: True,
OptionBlock.n_nested: 2,
OptionBlock.vars: dict(
[
("numirrdiversions", OptionBlock.simple_int),
("maxcellsdiversion", OptionBlock.simple_int),
]
),
},
),
(
"irrigation_well",
{
OptionBlock.dtype: np.bool_,
OptionBlock.nested: True,
OptionBlock.n_nested: 2,
OptionBlock.vars: dict(
[
("numirrwells", OptionBlock.simple_int),
("maxcellswell", OptionBlock.simple_int),
]
),
},
),
(
"supplemental_well",
{
OptionBlock.dtype: np.bool_,
OptionBlock.nested: True,
OptionBlock.n_nested: 2,
OptionBlock.vars: dict(
[
("numsupwells", OptionBlock.simple_int),
("maxdiversions", OptionBlock.simple_int),
]
),
},
),
(
"maxwells",
{
OptionBlock.dtype: np.bool_,
OptionBlock.nested: True,
OptionBlock.n_nested: 1,
OptionBlock.vars: dict(
[("nummaxwell", OptionBlock.simple_int)]
),
},
),
("tabfiles", OptionBlock.simple_tabfile),
("phiramp", OptionBlock.simple_flag),
(
"etdemand",
{
OptionBlock.dtype: np.bool_,
OptionBlock.nested: True,
OptionBlock.n_nested: 1,
OptionBlock.vars: {
"accel": {
OptionBlock.dtype: float,
OptionBlock.nested: False,
OptionBlock.optional: True,
}
},
},
),
("trigger", OptionBlock.simple_flag),
("timeseries_diversion", OptionBlock.simple_flag),
("timeseries_well", OptionBlock.simple_flag),
("timeseries_diversionet", OptionBlock.simple_flag),
("timeseries_wellet", OptionBlock.simple_flag),
(
"diversionlist",
{
OptionBlock.dtype: np.bool_,
OptionBlock.nested: True,
OptionBlock.n_nested: 1,
OptionBlock.vars: dict(
[("unit_diversionlist", OptionBlock.simple_int)]
),
},
),
(
"welllist",
{
OptionBlock.dtype: np.bool_,
OptionBlock.nested: True,
OptionBlock.n_nested: 1,
OptionBlock.vars: dict(
[("unit_welllist", OptionBlock.simple_int)]
),
},
),
(
"wellirrlist",
{
OptionBlock.dtype: np.bool_,
OptionBlock.nested: True,
OptionBlock.n_nested: 1,
OptionBlock.vars: dict(
[("unit_wellirrlist", OptionBlock.simple_int)]
),
},
),
(
"diversionirrlist",
{
OptionBlock.dtype: np.bool_,
OptionBlock.nested: True,
OptionBlock.n_nested: 1,
OptionBlock.vars: dict(
[("unit_diversionirrlist", OptionBlock.simple_int)]
),
},
),
(
"wellcbc",
{
OptionBlock.dtype: np.bool_,
OptionBlock.nested: True,
OptionBlock.n_nested: 1,
OptionBlock.vars: dict(
[("unitcbc", OptionBlock.simple_int)]
),
},
),
]
)
def __init__(
self,
model,
options=None,
time_series=None,
well_list=None,
irrdiversion=None,
irrwell=None,
supwell=None,
extension="ag",
unitnumber=None,
filenames=None,
nper=0,
):
if "nwt" not in model.version:
raise AssertionError(
"Model version must be mfnwt to use the AG package"
)
# setup the package parent class
if unitnumber is None:
unitnumber = ModflowAg._defaultunit()
# call base package constructor
super().__init__(
model,
extension=extension,
name=self._ftype(),
unit_number=unitnumber,
filenames=self._prepare_filenames(filenames),
)
# set up class
self._generate_heading()
self.url = "ag.htm"
# options
self.noprint = None
self.irrigation_diversion = False
self.numirrdiversions = 0
self.maxcellsdiversion = 0
self.irrigation_well = False
self.numirrwells = 0
self.supplemental_well = False
self.numsupwells = 0
self.maxdiversions = 0
self.maxwells = False
self.nummaxwell = 0
self.tabfiles = False
self.numtab = 0
self.maxval = 0
self.phiramp = False
self.etdemand = False
self.trigger = False
self.timeseries_diversion = False
self.timeseries_well = False
self.timeseries_diversionet = False
self.timeseries_wellet = False
self.diversionlist = False
self.unit_diversionlist = None
self.welllist = False
self.unit_welllist = None
self.wellirrlist = False
self.unit_wellirrlist = None
self.diversionirrlist = False
self.unit_diversionirrlist = None
self.wellcbc = False
self.unitcbc = None
if isinstance(options, OptionBlock):
self.options = options
self._update_attrs_from_option_block(options)
else:
self.options = OptionBlock("", ModflowAg)
self.time_series = time_series
self.well_list = well_list
self.irrdiversion = irrdiversion
self.irrwell = irrwell
self.supwell = supwell
self._nper = self.parent.nper
if self.parent.nper == 0:
self._nper = nper
self.parent.add_package(self)
@property
def segment_list(self):
"""
Method to get a unique list of segments from irrdiversion
Returns
-------
list
"""
segments = []
if self.irrdiversion is not None:
for _, recarray in self.irrdiversion.items():
if np.isscalar(recarray):
continue
t = np.unique(recarray["segid"])
for seg in t:
segments.append(seg)
segments = list(set(segments))
return segments
def _update_attrs_from_option_block(self, options):
"""
Method to update option attributes from the
option block
Parameters
----------
options : OptionBlock object
"""
for key, ctx in options._context.items():
if key in options.__dict__:
val = options.__dict__[key]
self.__setattr__(key, val)
if ctx[OptionBlock.nested]:
for k2, _ in ctx[OptionBlock.vars].items():
if k2 in options.__dict__:
v2 = options.__dict__[k2]
self.__setattr__(k2, v2)
def write_file(self, check=False):
"""
Write method for ModflowAg
Parameters
----------
check: bool
not implemented
"""
ws = self.parent.model_ws
name = self.file_name[0]
with open(os.path.join(ws, name), "w") as foo:
foo.write(f"{self.heading}\n")
# update options
self.options.update_from_package(self)
self.options.write_options(foo)
# check if there is a timeseries block and write output
if self.time_series is not None:
foo.write("# ag time series\n")
fmt = "{} {:d} {:d}\n"
foo.write("TIME SERIES \n")
for record in self.time_series:
if record["keyword"] in ("welletall", "wellall"):
foo.write(
f"{record['keyword']} {record['unit']}\n".upper()
)
else:
foo.write(fmt.format(*record).upper())
foo.write("END \n")
# check if item 12 exists and write item 12 - 14
if self.segment_list is not None:
foo.write("# segment list for irrigation diversions\n")
foo.write("SEGMENT LIST\n")
for iseg in self.segment_list:
foo.write(f"{iseg}\n")
foo.write("END \n")
# check if item 15 exists and write item 15 through 17
if self.well_list is not None:
foo.write("# ag well list\n")
foo.write("WELL LIST \n")
if self.tabfiles:
# item 16a
fmt16a = True
fmt16 = "{:d} {:d} {:d} {:d} {:d}\n"
else:
# item 16b
fmt16a = False
fmt16 = "{:d} {:d} {:d} {:f}\n"
for record in self.well_list:
if fmt16a:
foo.write(
fmt16.format(
record["unit"],
record["tabval"],
record["k"] + 1,
record["i"] + 1,
record["j"] + 1,
)
)
else:
foo.write(
fmt16.format(
record["k"] + 1,
record["i"] + 1,
record["j"] + 1,
record["flux"],
)
)
foo.write("END \n")
foo.write("# ag stress period data\n")
for per in range(self._nper):
foo.write(f"STRESS PERIOD {per + 1}\n")
# check for item 18 and write items 18 - 21
if self.irrdiversion is not None:
foo.write("IRRDIVERSION \n")
if self.trigger:
# item 20
fmt20 = "{:d} {:d} {:f} {:f}\n"
else:
# item 20, if trigger option is false we need 0's for
# period and trigger fac.
fmt20 = "{:d} {:d} 0 0\n"
if per in self.irrdiversion:
if np.isscalar(self.irrdiversion[per]):
# write item 19
foo.write("-1 \n")
else:
recarray = self.irrdiversion[per]
# write item 19
foo.write(f"{len(recarray)} \n")
fmt21 = "{:d} {:d} {:f} {:f}\n"
for rec in recarray:
num = rec["numcell"]
if self.trigger:
foo.write(
fmt20.format(
rec["segid"],
rec["numcell"],
rec["period"],
rec["triggerfact"],
)
)
else:
foo.write(
fmt20.format(
rec["segid"], rec["numcell"]
)
)
for i in range(num):
foo.write(
fmt21.format(
rec[f"i{i}"] + 1,
rec[f"j{i}"] + 1,
rec[f"eff_fact{i}"],
rec[f"field_fact{i}"],
)
)
else:
# write item 19
foo.write("0 \n")
# check for item 22 and write 22 - 25
if self.irrwell is not None:
foo.write("IRRWELL \n")
if self.trigger:
# item 24
fmt24 = "{:d} {:d} {:f} {:f}\n"
else:
# item 24
fmt24 = "{:d} {:d} 0 0\n"
if per in self.irrwell:
if np.isscalar(self.irrwell[per]):
foo.write("-1 \n")
else:
recarray = self.irrwell[per]
# write item 23
foo.write(f"{len(recarray)} \n")
fmt25 = "{:d} {:d} {:f} {:f}\n"
for rec in recarray:
num = rec["numcell"]
if self.trigger:
foo.write(
fmt24.format(
rec["wellid"] + 1,
rec["numcell"],
rec["period"],
rec["triggerfact"],
)
)
else:
foo.write(
fmt24.format(
rec["wellid"] + 1, rec["numcell"]
)
)
for i in range(num):
foo.write(
fmt25.format(
rec[f"i{i}"] + 1,
rec[f"j{i}"] + 1,
rec[f"eff_fact{i}"],
rec[f"field_fact{i}"],
)
)
else:
# write item 23
foo.write("0 \n")
# check if item 26 and write items 26 - 29
if self.supwell is not None:
foo.write("SUPWELL \n")
fmt28 = "{:d} {:d}\n"
if per in self.supwell:
if np.isscalar(self.supwell[per]):
foo.write("-1 \n")
else:
recarray = self.supwell[per]
# write item 27
foo.write(f"{len(recarray)} \n")
for rec in recarray:
num = rec["numcell"]
foo.write(
fmt28.format(
rec["wellid"] + 1, rec["numcell"]
)
)
for i in range(num):
if rec[f"fracsupmax{i}"] != -1e10:
foo.write(
"{:d} {:f} {:f}\n".format(
rec["segid{}".format(i)],
rec["fracsup{}".format(i)],
rec["fracsupmax{}".format(i)],
)
)
else:
foo.write(
"{:d} {:f}\n".format(
rec["segid{}".format(i)],
rec["fracsup{}".format(i)],
)
)
else:
# write item 27
foo.write("0 \n")
foo.write("END \n")
@staticmethod
def get_empty(numrecords, maxells=0, block="well"):
"""
Creates an empty record array corresponding to the block data type
it is associated with.
Parameters
----------
numrecords : int
number of records to create recarray with
maxells : int, optional
maximum number of irrigation links
block : str
str which indicates data set valid options are
"well" ,
"tabfile_well" ,
"timeseries" ,
"irrdiversion_modflow" ,
"irrdiversion_gsflow" ,
"irrwell_modflow" ,
"irrwell_gsflow" ,
"supwell"
Returns
-------
np.recarray
"""
dtype = ModflowAg.get_default_dtype(maxells=maxells, block=block)
return create_empty_recarray(numrecords, dtype, default_value=-1.0e10)
@staticmethod
def get_default_dtype(maxells=0, block="well"):
"""
Function that gets a default dtype for a block
Parameters
----------
maxells : int
maximum number of irrigation links
block : str
str which indicates data set valid options are
"well"
"tabfile_well"
"timeseries"
"irrdiversion"
"irrwell"
"supwell"
Returns
-------
dtype : (list, tuple)
"""
if block == "well":
dtype = [
("k", int),
("i", int),
("j", int),
("flux", float),
]
elif block == "tabfile_well":
dtype = [
("unit", int),
("tabval", int),
("k", int),
("i", int),
("j", int),
]
elif block == "time series":
dtype = [("keyword", object), ("id", int), ("unit", int)]
elif block == "irrdiversion":
dtype = [
("segid", int),
("numcell", int),
("period", float),
("triggerfact", float),
]
for i in range(maxells):
dtype += [
(f"i{i}", int),
(f"j{i}", int),
(f"eff_fact{i}", float),
(f"field_fact{i}", float),
]
elif block == "irrwell":
dtype = [
("wellid", int),
("numcell", int),
("period", float),
("triggerfact", float),
]
for i in range(maxells):
dtype += [
(f"i{i}", int),
(f"j{i}", int),
(f"eff_fact{i}", float),
(f"field_fact{i}", float),
]
elif block == "supwell":
dtype = [("wellid", int), ("numcell", int)]
for i in range(maxells):
dtype += [
(f"segid{i}", int),
(f"fracsup{i}", float),
(f"fracsupmax{i}", float),
]
else:
raise NotImplementedError(f"block type {block}, not supported")
return np.dtype(dtype)
@classmethod
def load(cls, f, model, nper=0, ext_unit_dict=None):
"""
Method to load the AG package from file
Parameters
----------
f : str
filename
model : gsflow.modflow.Modflow object
model to attach the ag pacakge to
nper : int
number of stress periods in model
ext_unit_dict : dict, optional
Returns
-------
ModflowAg object
"""
if nper == 0:
nper = model.nper
# open the file if not already open
openfile = not hasattr(f, "read")
if openfile:
filename = f
f = open(filename, "r")
# strip the file header if it exists
while True:
line = multi_line_strip(f)
if line:
break
# read the options block
options = OptionBlock.load_options(f, ModflowAg)
line = multi_line_strip(f)
time_series = None
if "time series" in line:
# read time_series
t = []
while True:
line = multi_line_strip(f)
if line == "end":
line = multi_line_strip(f)
break
else:
t.append(line.split())
if len(t) > 0:
nrec = len(t)
time_series = ModflowAg.get_empty(nrec, block="time series")
for ix, rec in enumerate(t):
if rec[0] in ("welletall", "wellall"):
time_series[ix] = (rec[0], -999, rec[-1])
else:
time_series[ix] = tuple(rec[:3])
# read item 12-14
if "segment list" in line:
# read item 13
t = []
while True:
line = multi_line_strip(f)
if line == "end":
line = multi_line_strip(f)
break
else:
t.append(line.split())
if len(t) > 0:
segments = []
for rec in t:
iseg = int(rec[0])
segments.append(iseg)
# read item 15-17 well_list
well = None
if "well list" in line:
# read item 16
t = []
while True:
line = multi_line_strip(f)
if line == "end":
line = multi_line_strip(f)
break
else:
t.append(line.split())
if len(t) > 0:
nrec = len(t)
# check if this is block 16a
if isinstance(options.tabfiles, np.recarray):
tf = True
well = ModflowAg.get_empty(nrec, block="tabfile_well")
else:
tf = False
well = ModflowAg.get_empty(nrec, block="well")
for ix, rec in enumerate(t):
if not tf:
k = int(rec[0]) - 1
i = int(rec[1]) - 1
j = int(rec[2]) - 1
well[ix] = (k, i, j, rec[3])
else:
k = int(rec[2]) - 1
i = int(rec[3]) - 1
j = int(rec[4]) - 1
well[ix] = (rec[0], rec[1], k, i, j)
maxcellsdiversion = 0
if options.maxcellsdiversion is not None:
maxcellsdiversion = options.maxcellsdiversion
maxcellswell = 0
if options.maxcellswell is not None:
maxcellswell = options.maxcellswell
maxdiversions = 0
if options.maxdiversions is not None:
maxdiversions = options.maxdiversions
irr_diversion = {}
irr_well = {}
sup_well = {}
# get the stress period data from blocks 18 - 29
for per in range(nper):
while True:
if "stress period" in line:
line = multi_line_strip(f)
# block 18
elif "irrdiversion" in line:
# read block 19
nrec = int(multi_line_strip(f).split()[0])
if nrec == -1:
irr = np.copy(irr_diversion[per - 1])
irr = irr.view(type=np.recarray)
else:
irr = ModflowAg.get_empty(
nrec,
maxells=maxcellsdiversion,
block="irrdiversion",
)
# read blocks 20 & 21
irr = _read_block_21_25_or_29(f, nrec, irr, 21)
irr_diversion[per] = irr
line = multi_line_strip(f)
# block 22
elif "irrwell" in line:
# read block 23
nrec = int(multi_line_strip(f).split()[0])
if nrec == -1:
irr = np.copy(irr_well[per - 1])
irr = irr.view(type=np.recarray)
else:
irr = ModflowAg.get_empty(
nrec, maxells=maxcellswell, block="irrwell"
)
# read blocks 24 & 25
irr = _read_block_21_25_or_29(f, nrec, irr, 25)
irr_well[per] = irr
line = multi_line_strip(f)
# block 26
elif "supwel" in line:
# read block 27
nrec = int(multi_line_strip(f).split()[0])
if nrec == -1:
sup = np.copy(sup_well[per - 1])
sup = sup.view(type=np.recarray)
else:
sup = ModflowAg.get_empty(
nrec, maxells=maxdiversions, block="supwell"
)
# read blocks 28 & 29
sup = _read_block_21_25_or_29(f, nrec, sup, 29)
sup_well[per] = sup
line = multi_line_strip(f)
# block 30?
elif "end" in line:
if per == nper - 1:
break
line = multi_line_strip(f)
break
else:
raise ValueError(f"Something went wrong at: {line}")
return cls(
model,
options=options,
time_series=time_series,
well_list=well,
irrwell=irr_well,
irrdiversion=irr_diversion,
supwell=sup_well,
nper=nper,
)
@staticmethod
def _defaultunit():
return 69
@staticmethod
def _ftype():
return "AG"
@property
def plottable(self):
return False
def _read_block_21_25_or_29(fobj, nrec, recarray, block):
"""
Method to read blocks 21, 25, and 29 from the AG package
Parameters
----------
fobj : File object
nrec : int
number of records
recarray : np.recarray
recarray to add data to
block : int
valid options are 21, 25, 29
Returns
-------
recarray : np.recarray
"""
t = []
for _ in range(nrec):
t1 = []
ll = multi_line_strip(fobj).split()
if block in (21,):
# do not zero adjust segid
ll[0] = int(ll[0])
else:
ll[0] = int(ll[0]) - 1
if block in (21, 25):
# correct list length if not using trigger factor
if len(ll) == 2:
ll += [0, 0]
elif len(ll) == 3:
ll += [0]
t1 += ll[:4]
elif block == 29:
t1 += ll[:2]
else:
raise AssertionError("block number must be 21, 25, or 29")
for _ in range(int(ll[1])):
if block == 29:
if len(ll) == 2:
ll += [1e-10]
tmp = multi_line_strip(fobj).split()[:3]
tmp[0] = int(tmp[0])
else:
tmp = multi_line_strip(fobj).split()[:4]
tmp[0:2] = [int(tmp[0]) - 1, int(tmp[1]) - 1]
t1 += tmp
t.append(t1)
if len(t) > 0:
for ix, rec in enumerate(t):
for ix2, name in enumerate(recarray.dtype.names):
if ix2 >= len(rec):
pass
else:
recarray[name][ix] = rec[ix2]
return recarray
| {
"content_hash": "82671944751e7aa1bf726b0803bbc2b7",
"timestamp": "",
"source": "github",
"line_count": 980,
"max_line_length": 79,
"avg_line_length": 33.594897959183676,
"alnum_prop": 0.37192843908513806,
"repo_name": "jentjr/flopy",
"id": "786e2ec37c332da895bc230343df8b5bb3c1732f",
"size": "32923",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "flopy/modflow/mfag.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "832"
},
{
"name": "CSS",
"bytes": "321"
},
{
"name": "Makefile",
"bytes": "634"
},
{
"name": "Python",
"bytes": "6353118"
},
{
"name": "Shell",
"bytes": "292"
}
],
"symlink_target": ""
} |
"""Module houses Modin configs originated from environment variables."""
import os
import sys
from textwrap import dedent
import warnings
from packaging import version
import secrets
from pandas.util._decorators import doc # type: ignore[attr-defined]
from .pubsub import Parameter, _TYPE_PARAMS, ExactStr, ValueSource
from typing import Any, Optional
class EnvironmentVariable(Parameter, type=str, abstract=True):
"""Base class for environment variables-based configuration."""
varname: Optional[str] = None
@classmethod
def _get_raw_from_config(cls) -> str:
"""
Read the value from environment variable.
Returns
-------
str
Config raw value.
Raises
------
TypeError
If `varname` is None.
KeyError
If value is absent.
"""
if cls.varname is None:
raise TypeError("varname should not be None")
return os.environ[cls.varname]
@classmethod
def get_help(cls) -> str:
"""
Generate user-presentable help for the config.
Returns
-------
str
"""
help = f"{cls.varname}: {dedent(cls.__doc__ or 'Unknown').strip()}\n\tProvide {_TYPE_PARAMS[cls.type].help}"
if cls.choices:
help += f" (valid examples are: {', '.join(str(c) for c in cls.choices)})"
return help
class IsDebug(EnvironmentVariable, type=bool):
"""Force Modin engine to be "Python" unless specified by $MODIN_ENGINE."""
varname = "MODIN_DEBUG"
class Engine(EnvironmentVariable, type=str):
"""Distribution engine to run queries by."""
varname = "MODIN_ENGINE"
choices = ("Ray", "Dask", "Python", "Native")
NOINIT_ENGINES = {
"Python",
} # engines that don't require initialization, useful for unit tests
@classmethod
def _get_default(cls) -> str:
"""
Get default value of the config.
Returns
-------
str
"""
from modin.utils import (
MIN_RAY_VERSION,
MIN_DASK_VERSION,
)
if IsDebug.get():
return "Python"
try:
import ray
except ImportError:
pass
else:
if version.parse(ray.__version__) < MIN_RAY_VERSION:
raise ImportError(
"Please `pip install modin[ray]` to install compatible Ray "
+ "version "
+ f"(>={MIN_RAY_VERSION})."
)
return "Ray"
try:
import dask
import distributed
except ImportError:
pass
else:
if (
version.parse(dask.__version__) < MIN_DASK_VERSION
or version.parse(distributed.__version__) < MIN_DASK_VERSION
):
raise ImportError(
f"Please `pip install modin[dask]` to install compatible Dask version (>={MIN_DASK_VERSION})."
)
return "Dask"
try:
# We import ``DbWorker`` from this module since correct import of ``DbWorker`` itself
# from HDK is located in it with all the necessary options for dlopen.
from modin.experimental.core.execution.native.implementations.hdk_on_native.db_worker import ( # noqa
DbWorker,
)
except ImportError:
pass
else:
return "Native"
raise ImportError(
"Please refer to installation documentation page to install an engine"
)
@classmethod
@doc(Parameter.add_option.__doc__)
def add_option(cls, choice: Any) -> Any:
choice = super().add_option(choice)
cls.NOINIT_ENGINES.add(choice)
return choice
class StorageFormat(EnvironmentVariable, type=str):
"""Engine to run on a single node of distribution."""
varname = "MODIN_STORAGE_FORMAT"
default = "Pandas"
choices = ("Pandas", "Hdk", "Pyarrow", "Cudf")
class IsExperimental(EnvironmentVariable, type=bool):
"""Whether to Turn on experimental features."""
varname = "MODIN_EXPERIMENTAL"
class IsRayCluster(EnvironmentVariable, type=bool):
"""Whether Modin is running on pre-initialized Ray cluster."""
varname = "MODIN_RAY_CLUSTER"
class RayRedisAddress(EnvironmentVariable, type=ExactStr):
"""Redis address to connect to when running in Ray cluster."""
varname = "MODIN_REDIS_ADDRESS"
class RayRedisPassword(EnvironmentVariable, type=ExactStr):
"""What password to use for connecting to Redis."""
varname = "MODIN_REDIS_PASSWORD"
default = secrets.token_hex(32)
class CpuCount(EnvironmentVariable, type=int):
"""How many CPU cores to use during initialization of the Modin engine."""
varname = "MODIN_CPUS"
@classmethod
def _get_default(cls) -> int:
"""
Get default value of the config.
Returns
-------
int
"""
import multiprocessing
return multiprocessing.cpu_count()
class GpuCount(EnvironmentVariable, type=int):
"""How may GPU devices to utilize across the whole distribution."""
varname = "MODIN_GPUS"
class Memory(EnvironmentVariable, type=int):
"""
How much memory (in bytes) give to an execution engine.
Notes
-----
* In Ray case: the amount of memory to start the Plasma object store with.
* In Dask case: the amount of memory that is given to each worker depending on CPUs used.
"""
varname = "MODIN_MEMORY"
class NPartitions(EnvironmentVariable, type=int):
"""How many partitions to use for a Modin DataFrame (along each axis)."""
varname = "MODIN_NPARTITIONS"
@classmethod
def _put(cls, value: int) -> None:
"""
Put specific value if NPartitions wasn't set by a user yet.
Parameters
----------
value : int
Config value to set.
Notes
-----
This method is used to set NPartitions from cluster resources internally
and should not be called by a user.
"""
if cls.get_value_source() == ValueSource.DEFAULT:
cls.put(value)
@classmethod
def _get_default(cls) -> int:
"""
Get default value of the config.
Returns
-------
int
"""
if StorageFormat.get() == "Cudf":
return GpuCount.get()
else:
return CpuCount.get()
class SocksProxy(EnvironmentVariable, type=ExactStr):
"""SOCKS proxy address if it is needed for SSH to work."""
varname = "MODIN_SOCKS_PROXY"
class DoLogRpyc(EnvironmentVariable, type=bool):
"""Whether to gather RPyC logs (applicable for remote context)."""
varname = "MODIN_LOG_RPYC"
class DoTraceRpyc(EnvironmentVariable, type=bool):
"""Whether to trace RPyC calls (applicable for remote context)."""
varname = "MODIN_TRACE_RPYC"
class HdkFragmentSize(EnvironmentVariable, type=int):
"""How big a fragment in HDK should be when creating a table (in rows)."""
varname = "MODIN_HDK_FRAGMENT_SIZE"
class OmnisciFragmentSize(EnvironmentVariable, type=int):
"""How big a fragment in OmniSci should be when creating a table (in rows)."""
varname = "MODIN_OMNISCI_FRAGMENT_SIZE"
class DoUseCalcite(EnvironmentVariable, type=bool):
"""Whether to use Calcite for OmniSci queries execution."""
varname = "MODIN_USE_CALCITE"
default = True
class TestDatasetSize(EnvironmentVariable, type=str):
"""Dataset size for running some tests."""
varname = "MODIN_TEST_DATASET_SIZE"
choices = ("Small", "Normal", "Big")
class TestRayClient(EnvironmentVariable, type=bool):
"""Set to true to start and connect Ray client before a testing session starts."""
varname = "MODIN_TEST_RAY_CLIENT"
default = False
class TrackFileLeaks(EnvironmentVariable, type=bool):
"""Whether to track for open file handles leakage during testing."""
varname = "MODIN_TEST_TRACK_FILE_LEAKS"
# Turn off tracking on Windows by default because
# psutil's open_files() can be extremely slow on Windows (up to adding a few hours).
# see https://github.com/giampaolo/psutil/pull/597
default = sys.platform != "win32"
class AsvImplementation(EnvironmentVariable, type=ExactStr):
"""Allows to select a library that we will use for testing performance."""
varname = "MODIN_ASV_USE_IMPL"
choices = ("modin", "pandas")
default = "modin"
class AsvDataSizeConfig(EnvironmentVariable, type=ExactStr):
"""Allows to override default size of data (shapes)."""
varname = "MODIN_ASV_DATASIZE_CONFIG"
default = None
class ProgressBar(EnvironmentVariable, type=bool):
"""Whether or not to show the progress bar."""
varname = "MODIN_PROGRESS_BAR"
default = False
@classmethod
def enable(cls) -> None:
"""Enable ``ProgressBar`` feature."""
cls.put(True)
@classmethod
def disable(cls) -> None:
"""Disable ``ProgressBar`` feature."""
cls.put(False)
@classmethod
def put(cls, value: bool) -> None:
"""
Set ``ProgressBar`` value only if synchronous benchmarking is disabled.
Parameters
----------
value : bool
Config value to set.
"""
if value and BenchmarkMode.get():
raise ValueError("ProgressBar isn't compatible with BenchmarkMode")
super().put(value)
class BenchmarkMode(EnvironmentVariable, type=bool):
"""Whether or not to perform computations synchronously."""
varname = "MODIN_BENCHMARK_MODE"
default = False
@classmethod
def put(cls, value: bool) -> None:
"""
Set ``BenchmarkMode`` value only if progress bar feature is disabled.
Parameters
----------
value : bool
Config value to set.
"""
if value and ProgressBar.get():
raise ValueError("BenchmarkMode isn't compatible with ProgressBar")
super().put(value)
class LogMode(EnvironmentVariable, type=ExactStr):
"""Set ``LogMode`` value if users want to opt-in."""
varname = "MODIN_LOG_MODE"
choices = ("enable", "disable", "enable_api_only")
default = "disable"
@classmethod
def enable(cls) -> None:
"""Enable all logging levels."""
cls.put("enable")
@classmethod
def disable(cls) -> None:
"""Disable logging feature."""
cls.put("disable")
@classmethod
def enable_api_only(cls) -> None:
"""Enable API level logging."""
cls.put("enable_api_only")
class LogMemoryInterval(EnvironmentVariable, type=int):
"""Interval (in seconds) to profile memory utilization for logging."""
varname = "MODIN_LOG_MEMORY_INTERVAL"
default = 5
@classmethod
def put(cls, value: int) -> None:
"""
Set ``LogMemoryInterval`` with extra checks.
Parameters
----------
value : int
Config value to set.
"""
if value <= 0:
raise ValueError(f"Log memory Interval should be > 0, passed value {value}")
super().put(value)
@classmethod
def get(cls) -> int:
"""
Get ``LogMemoryInterval`` with extra checks.
Returns
-------
int
"""
log_memory_interval = super().get()
assert log_memory_interval > 0, "`LogMemoryInterval` should be > 0"
return log_memory_interval
class LogFileSize(EnvironmentVariable, type=int):
"""Max size of logs (in MBs) to store per Modin job."""
varname = "MODIN_LOG_FILE_SIZE"
default = 10
@classmethod
def put(cls, value: int) -> None:
"""
Set ``LogFileSize`` with extra checks.
Parameters
----------
value : int
Config value to set.
"""
if value <= 0:
raise ValueError(f"Log file size should be > 0 MB, passed value {value}")
super().put(value)
@classmethod
def get(cls) -> int:
"""
Get ``LogFileSize`` with extra checks.
Returns
-------
int
"""
log_file_size = super().get()
assert log_file_size > 0, "`LogFileSize` should be > 0"
return log_file_size
class PersistentPickle(EnvironmentVariable, type=bool):
"""Whether serialization should be persistent."""
varname = "MODIN_PERSISTENT_PICKLE"
# When set to off, it allows faster serialization which is only
# valid in current run (i.e. useless for saving to disk).
# When set to on, Modin objects could be saved to disk and loaded
# but serialization/deserialization could take more time.
default = False
class HdkLaunchParameters(EnvironmentVariable, type=dict):
"""
Additional command line options for the HDK engine.
Please visit OmniSci documentation for the description of available parameters:
https://docs.omnisci.com/installation-and-configuration/config-parameters#configuration-parameters-for-omniscidb
"""
varname = "MODIN_HDK_LAUNCH_PARAMETERS"
default = {
"enable_union": 1,
"enable_columnar_output": 1,
"enable_lazy_fetch": 0,
"null_div_by_zero": 1,
"enable_watchdog": 0,
"enable_thrift_logs": 0,
}
@classmethod
def get(cls) -> dict:
"""
Get the resulted command-line options.
Decode and merge specified command-line options with the default one.
Returns
-------
dict
Decoded and verified config value.
"""
if cls == OmnisciLaunchParameters or (
OmnisciLaunchParameters.varname in os.environ
and HdkLaunchParameters.varname not in os.environ
):
return OmnisciLaunchParameters._get()
else:
return HdkLaunchParameters._get()
@classmethod
def _get(cls) -> dict:
"""
Get the resulted command-line options.
Returns
-------
dict
Decoded and verified config value.
"""
custom_parameters = super().get()
result = cls.default.copy()
result.update(
{key.replace("-", "_"): value for key, value in custom_parameters.items()}
)
return result
class OmnisciLaunchParameters(HdkLaunchParameters, type=dict):
"""
Additional command line options for the OmniSci engine.
Please visit OmniSci documentation for the description of available parameters:
https://docs.omnisci.com/installation-and-configuration/config-parameters#configuration-parameters-for-omniscidb
"""
varname = "MODIN_OMNISCI_LAUNCH_PARAMETERS"
class MinPartitionSize(EnvironmentVariable, type=int):
"""
Minimum number of rows/columns in a single pandas partition split.
Once a partition for a pandas dataframe has more than this many elements,
Modin adds another partition.
"""
varname = "MODIN_MIN_PARTITION_SIZE"
default = 32
@classmethod
def put(cls, value: int) -> None:
"""
Set ``MinPartitionSize`` with extra checks.
Parameters
----------
value : int
Config value to set.
"""
if value <= 0:
raise ValueError(f"Min partition size should be > 0, passed value {value}")
super().put(value)
@classmethod
def get(cls) -> int:
"""
Get ``MinPartitionSize`` with extra checks.
Returns
-------
int
"""
min_partition_size = super().get()
assert min_partition_size > 0, "`min_partition_size` should be > 0"
return min_partition_size
class TestReadFromSqlServer(EnvironmentVariable, type=bool):
"""Set to true to test reading from SQL server."""
varname = "MODIN_TEST_READ_FROM_SQL_SERVER"
default = False
class TestReadFromPostgres(EnvironmentVariable, type=bool):
"""Set to true to test reading from Postgres."""
varname = "MODIN_TEST_READ_FROM_POSTGRES"
default = False
class ReadSqlEngine(EnvironmentVariable, type=str):
"""Engine to run `read_sql`."""
varname = "MODIN_READ_SQL_ENGINE"
default = "Pandas"
choices = ("Pandas", "Connectorx")
def _check_vars() -> None:
"""
Check validity of environment variables.
Look out for any environment variables that start with "MODIN_" prefix
that are unknown - they might be a typo, so warn a user.
"""
valid_names = {
obj.varname
for obj in globals().values()
if isinstance(obj, type)
and issubclass(obj, EnvironmentVariable)
and not obj.is_abstract
}
found_names = {name for name in os.environ if name.startswith("MODIN_")}
unknown = found_names - valid_names
if unknown:
warnings.warn(
f"Found unknown environment variable{'s' if len(unknown) > 1 else ''},"
+ f" please check {'their' if len(unknown) > 1 else 'its'} spelling: "
+ ", ".join(sorted(unknown))
)
_check_vars()
| {
"content_hash": "2b4c60b66eb42b09c917e77cd3a0644f",
"timestamp": "",
"source": "github",
"line_count": 631,
"max_line_length": 116,
"avg_line_length": 27.251980982567353,
"alnum_prop": 0.6061874854617353,
"repo_name": "modin-project/modin",
"id": "e287bf411875a96daf1f8f383fba3c17911fe651",
"size": "17979",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modin/config/envvars.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2330"
},
{
"name": "Python",
"bytes": "3914783"
},
{
"name": "Shell",
"bytes": "2377"
}
],
"symlink_target": ""
} |
import json
import os
import platform
import re
import subprocess
import sys
import py
import pytest
import tox
from tox._pytestplugin import ReportExpectMock
from tox.config import parseconfig
from tox.session import Session
pytest_plugins = "pytester"
def test_report_protocol(newconfig):
config = newconfig(
[],
"""
[testenv:mypython]
deps=xy
""",
)
class Popen:
def __init__(self, *args, **kwargs):
pass
def communicate(self):
return "", ""
def wait(self):
pass
session = Session(config, popen=Popen, Report=ReportExpectMock)
report = session.report
report.expect("using")
venv = session.getvenv("mypython")
action = session.newaction(venv, "update")
venv.update(action)
report.expect("logpopen")
class TestSession:
def test_log_pcall(self, mocksession):
mocksession.config.logdir.ensure(dir=1)
assert not mocksession.config.logdir.listdir()
action = mocksession.newaction(None, "something")
action.popen(["echo"])
match = mocksession.report.getnext("logpopen")
assert match[1].outpath.relto(mocksession.config.logdir)
assert match[1].shell is False
def test_summary_status(self, initproj, capfd):
initproj(
"logexample123-0.5",
filedefs={
"tests": {"test_hello.py": "def test_hello(): pass"},
"tox.ini": """
[testenv:hello]
[testenv:world]
""",
},
)
config = parseconfig([])
session = Session(config)
envs = session.venvlist
assert len(envs) == 2
env1, env2 = envs
env1.status = "FAIL XYZ"
assert env1.status
env2.status = 0
assert not env2.status
session._summary()
out, err = capfd.readouterr()
exp = "{}: FAIL XYZ".format(env1.envconfig.envname)
assert exp in out
exp = "{}: commands succeeded".format(env2.envconfig.envname)
assert exp in out
def test_getvenv(self, initproj):
initproj(
"logexample123-0.5",
filedefs={
"tests": {"test_hello.py": "def test_hello(): pass"},
"tox.ini": """
[testenv:hello]
[testenv:world]
""",
},
)
config = parseconfig([])
session = Session(config)
venv1 = session.getvenv("hello")
venv2 = session.getvenv("hello")
assert venv1 is venv2
venv1 = session.getvenv("world")
venv2 = session.getvenv("world")
assert venv1 is venv2
with pytest.raises(LookupError):
session.getvenv("qwe")
def test_notoxini_help_still_works(initproj, cmd):
initproj("example123-0.5", filedefs={"tests": {"test_hello.py": "def test_hello(): pass"}})
result = cmd("-h")
msg = "ERROR: tox config file (either pyproject.toml, tox.ini, setup.cfg) not found\n"
assert result.err == msg
assert result.out.startswith("usage: ")
assert any("--help" in l for l in result.outlines), result.outlines
assert not result.ret
def test_notoxini_help_ini_still_works(initproj, cmd):
initproj("example123-0.5", filedefs={"tests": {"test_hello.py": "def test_hello(): pass"}})
result = cmd("--help-ini")
assert any("setenv" in l for l in result.outlines), result.outlines
assert not result.ret
def test_envdir_equals_toxini_errors_out(cmd, initproj):
initproj(
"interp123-0.7",
filedefs={
"tox.ini": """
[testenv]
envdir={toxinidir}
"""
},
)
result = cmd()
assert result.outlines[1] == "ERROR: ConfigError: envdir must not equal toxinidir"
assert re.match(r"ERROR: venv \'python\' in .* would delete project", result.outlines[0])
assert result.ret, "{}\n{}".format(result.err, result.out)
def test_run_custom_install_command_error(cmd, initproj):
initproj(
"interp123-0.5",
filedefs={
"tox.ini": """
[testenv]
install_command=./tox.ini {opts} {packages}
"""
},
)
result = cmd()
assert re.match(
r"ERROR: invocation failed \(errno \d+\), args: .*[/\\]tox\.ini", result.outlines[-1]
)
assert result.ret, "{}\n{}".format(result.err, result.out)
def test_unknown_interpreter_and_env(cmd, initproj):
initproj(
"interp123-0.5",
filedefs={
"tests": {"test_hello.py": "def test_hello(): pass"},
"tox.ini": """
[testenv:python]
basepython=xyz_unknown_interpreter
[testenv]
changedir=tests
""",
},
)
result = cmd()
assert result.ret, "{}\n{}".format(result.err, result.out)
assert any(
"ERROR: InterpreterNotFound: xyz_unknown_interpreter" == l for l in result.outlines
), result.outlines
result = cmd("-exyz")
assert result.ret, "{}\n{}".format(result.err, result.out)
assert result.out == "ERROR: unknown environment 'xyz'\n"
def test_unknown_interpreter(cmd, initproj):
initproj(
"interp123-0.5",
filedefs={
"tests": {"test_hello.py": "def test_hello(): pass"},
"tox.ini": """
[testenv:python]
basepython=xyz_unknown_interpreter
[testenv]
changedir=tests
""",
},
)
result = cmd()
assert result.ret, "{}\n{}".format(result.err, result.out)
assert any(
"ERROR: InterpreterNotFound: xyz_unknown_interpreter" == l for l in result.outlines
), result.outlines
def test_skip_platform_mismatch(cmd, initproj):
initproj(
"interp123-0.5",
filedefs={
"tests": {"test_hello.py": "def test_hello(): pass"},
"tox.ini": """
[testenv]
changedir=tests
platform=x123
""",
},
)
result = cmd()
assert not result.ret
assert any(
"SKIPPED: python: platform mismatch" == l for l in result.outlines
), result.outlines
def test_skip_unknown_interpreter(cmd, initproj):
initproj(
"interp123-0.5",
filedefs={
"tests": {"test_hello.py": "def test_hello(): pass"},
"tox.ini": """
[testenv:python]
basepython=xyz_unknown_interpreter
[testenv]
changedir=tests
""",
},
)
result = cmd("--skip-missing-interpreters")
assert not result.ret
msg = "SKIPPED: python: InterpreterNotFound: xyz_unknown_interpreter"
assert any(msg == l for l in result.outlines), result.outlines
def test_skip_unknown_interpreter_result_json(cmd, initproj, tmpdir):
report_path = tmpdir.join("toxresult.json")
initproj(
"interp123-0.5",
filedefs={
"tests": {"test_hello.py": "def test_hello(): pass"},
"tox.ini": """
[testenv:python]
basepython=xyz_unknown_interpreter
[testenv]
changedir=tests
""",
},
)
result = cmd("--skip-missing-interpreters", "--result-json", report_path)
assert not result.ret
msg = "SKIPPED: python: InterpreterNotFound: xyz_unknown_interpreter"
assert any(msg == l for l in result.outlines), result.outlines
setup_result_from_json = json.load(report_path)["testenvs"]["python"]["setup"]
for setup_step in setup_result_from_json:
assert "InterpreterNotFound" in setup_step["output"]
assert setup_step["retcode"] == "0"
def test_unknown_dep(cmd, initproj):
initproj(
"dep123-0.7",
filedefs={
"tests": {"test_hello.py": "def test_hello(): pass"},
"tox.ini": """
[testenv]
deps=qweqwe123
changedir=tests
""",
},
)
result = cmd()
assert result.ret, "{}\n{}".format(result.err, result.out)
assert result.outlines[-1].startswith("ERROR: python: could not install deps [qweqwe123];")
def test_venv_special_chars_issue252(cmd, initproj):
initproj(
"pkg123-0.7",
filedefs={
"tests": {"test_hello.py": "def test_hello(): pass"},
"tox.ini": """
[tox]
envlist = special&&1
[testenv:special&&1]
changedir=tests
""",
},
)
result = cmd()
assert result.ret == 0, "{}\n{}".format(result.err, result.out)
pattern = re.compile("special&&1 installed: .*pkg123==0.7.*")
assert any(pattern.match(line) for line in result.outlines), result.outlines
def test_unknown_environment(cmd, initproj):
initproj("env123-0.7", filedefs={"tox.ini": ""})
result = cmd("-e", "qpwoei")
assert result.ret, "{}\n{}".format(result.err, result.out)
assert result.out == "ERROR: unknown environment 'qpwoei'\n"
def test_minimal_setup_py_empty(cmd, initproj):
initproj(
"pkg123-0.7",
filedefs={
"tests": {"test_hello.py": "def test_hello(): pass"},
"setup.py": """
""",
"tox.ini": "",
},
)
result = cmd()
assert result.ret == 1, "{}\n{}".format(result.err, result.out)
assert result.outlines[-1] == "ERROR: setup.py is empty"
def test_minimal_setup_py_comment_only(cmd, initproj):
initproj(
"pkg123-0.7",
filedefs={
"tests": {"test_hello.py": "def test_hello(): pass"},
"setup.py": """\n# some comment
""",
"tox.ini": "",
},
)
result = cmd()
assert result.ret == 1, "{}\n{}".format(result.err, result.out)
assert result.outlines[-1] == "ERROR: setup.py is empty"
def test_minimal_setup_py_non_functional(cmd, initproj):
initproj(
"pkg123-0.7",
filedefs={
"tests": {"test_hello.py": "def test_hello(): pass"},
"setup.py": """
import sys
""",
"tox.ini": "",
},
)
result = cmd()
assert result.ret == 1, "{}\n{}".format(result.err, result.out)
assert any(re.match(r".*ERROR.*check setup.py.*", l) for l in result.outlines), result.outlines
def test_sdist_fails(cmd, initproj):
initproj(
"pkg123-0.7",
filedefs={
"tests": {"test_hello.py": "def test_hello(): pass"},
"setup.py": """
syntax error
""",
"tox.ini": "",
},
)
result = cmd()
assert result.ret, "{}\n{}".format(result.err, result.out)
assert any(
re.match(r".*FAIL.*could not package project.*", l) for l in result.outlines
), result.outlines
def test_no_setup_py_exits(cmd, initproj):
initproj(
"pkg123-0.7",
filedefs={
"tox.ini": """
[testenv]
commands=python -c "2 + 2"
"""
},
)
os.remove("setup.py")
result = cmd()
assert result.ret, "{}\n{}".format(result.err, result.out)
assert any(
re.match(r".*ERROR.*No setup.py file found.*", l) for l in result.outlines
), result.outlines
def test_package_install_fails(cmd, initproj):
initproj(
"pkg123-0.7",
filedefs={
"tests": {"test_hello.py": "def test_hello(): pass"},
"setup.py": """
from setuptools import setup
setup(
name='pkg123',
description='pkg123 project',
version='0.7',
license='MIT',
platforms=['unix', 'win32'],
packages=['pkg123',],
install_requires=['qweqwe123'],
)
""",
"tox.ini": "",
},
)
result = cmd()
assert result.ret, "{}\n{}".format(result.err, result.out)
assert result.outlines[-1].startswith("ERROR: python: InvocationError for command ")
@pytest.fixture
def example123(initproj):
yield initproj(
"example123-0.5",
filedefs={
"tests": {
"test_hello.py": """
def test_hello(pytestconfig):
pass
"""
},
"tox.ini": """
[testenv]
changedir=tests
commands= pytest --basetemp={envtmpdir} \
--junitxml=junit-{envname}.xml
deps=pytest
""",
},
)
def test_toxuone_env(cmd, example123):
result = cmd()
assert not result.ret
assert re.match(
r".*generated\W+xml\W+file.*junit-python\.xml" r".*\W+1\W+passed.*", result.out, re.DOTALL
)
result = cmd("-epython")
assert not result.ret
assert re.match(
r".*\W+1\W+passed.*" r"summary.*" r"python:\W+commands\W+succeeded.*",
result.out,
re.DOTALL,
)
def test_different_config_cwd(cmd, example123, monkeypatch):
# see that things work with a different CWD
monkeypatch.chdir(example123.dirname)
result = cmd("-c", "example123/tox.ini")
assert not result.ret
assert re.match(
r".*\W+1\W+passed.*" r"summary.*" r"python:\W+commands\W+succeeded.*",
result.out,
re.DOTALL,
)
def test_json(cmd, example123):
# see that tests can also fail and retcode is correct
testfile = py.path.local("tests").join("test_hello.py")
assert testfile.check()
testfile.write("def test_fail(): assert 0")
jsonpath = example123.join("res.json")
result = cmd("--result-json", jsonpath)
assert result.ret == 1, "{}\n{}".format(result.err, result.out)
data = json.load(jsonpath.open("r"))
verify_json_report_format(data)
assert re.match(
r".*\W+1\W+failed.*" r"summary.*" r"python:\W+commands\W+failed.*", result.out, re.DOTALL
)
def test_developz(initproj, cmd):
initproj(
"example123",
filedefs={
"tox.ini": """
"""
},
)
result = cmd("-vv", "--develop")
assert not result.ret
assert "sdist-make" not in result.out
def test_usedevelop(initproj, cmd):
initproj(
"example123",
filedefs={
"tox.ini": """
[testenv]
usedevelop=True
"""
},
)
result = cmd("-vv")
assert not result.ret
assert "sdist-make" not in result.out
def test_usedevelop_mixed(initproj, cmd):
initproj(
"example123",
filedefs={
"tox.ini": """
[testenv:devenv]
usedevelop=True
[testenv:nondev]
usedevelop=False
"""
},
)
# running only 'devenv' should not do sdist
result = cmd("-vv", "-e", "devenv")
assert not result.ret
assert "sdist-make" not in result.out
# running all envs should do sdist
result = cmd("-vv")
assert not result.ret
assert "sdist-make" in result.out
@pytest.mark.parametrize("skipsdist", [False, True])
@pytest.mark.parametrize("src_root", [".", "src"])
def test_test_usedevelop(cmd, initproj, src_root, skipsdist, monkeypatch):
name = "example123-spameggs"
base = initproj(
(name, "0.5"),
src_root=src_root,
filedefs={
"tests": {
"test_hello.py": """
def test_hello(pytestconfig):
pass
"""
},
"tox.ini": """
[testenv]
usedevelop=True
changedir=tests
commands=
pytest --basetemp={envtmpdir} --junitxml=junit-{envname}.xml []
deps=pytest"""
+ """
skipsdist={}
""".format(
skipsdist
),
},
)
result = cmd("-v")
assert not result.ret
assert re.match(
r".*generated\W+xml\W+file.*junit-python\.xml" r".*\W+1\W+passed.*", result.out, re.DOTALL
)
assert "sdist-make" not in result.out
result = cmd("-epython")
assert not result.ret
assert "develop-inst-noop" in result.out
assert re.match(
r".*\W+1\W+passed.*" r"summary.*" r"python:\W+commands\W+succeeded.*",
result.out,
re.DOTALL,
)
# see that things work with a different CWD
monkeypatch.chdir(base.dirname)
result = cmd("-c", "{}/tox.ini".format(name))
assert not result.ret
assert "develop-inst-noop" in result.out
assert re.match(
r".*\W+1\W+passed.*" r"summary.*" r"python:\W+commands\W+succeeded.*",
result.out,
re.DOTALL,
)
monkeypatch.chdir(base)
# see that tests can also fail and retcode is correct
testfile = py.path.local("tests").join("test_hello.py")
assert testfile.check()
testfile.write("def test_fail(): assert 0")
result = cmd()
assert result.ret, "{}\n{}".format(result.err, result.out)
assert "develop-inst-noop" in result.out
assert re.match(
r".*\W+1\W+failed.*" r"summary.*" r"python:\W+commands\W+failed.*", result.out, re.DOTALL
)
# test develop is called if setup.py changes
setup_py = py.path.local("setup.py")
setup_py.write(setup_py.read() + " ")
result = cmd()
assert result.ret, "{}\n{}".format(result.err, result.out)
assert "develop-inst-nodeps" in result.out
def _alwayscopy_not_supported():
# This is due to virtualenv bugs with alwayscopy in some platforms
# see: https://github.com/pypa/virtualenv/issues/565
if hasattr(platform, "linux_distribution"):
_dist = platform.linux_distribution(full_distribution_name=False)
(name, version, arch) = _dist
if any((name == "centos" and version[0] == "7", name == "SuSE" and arch == "x86_64")):
return True
return False
@pytest.mark.skipif(_alwayscopy_not_supported(), reason="Platform doesnt support alwayscopy")
def test_alwayscopy(initproj, cmd):
initproj(
"example123",
filedefs={
"tox.ini": """
[testenv]
commands={envpython} --version
alwayscopy=True
"""
},
)
result = cmd("-vv")
assert not result.ret
assert "virtualenv --always-copy" in result.out
def test_alwayscopy_default(initproj, cmd):
initproj(
"example123",
filedefs={
"tox.ini": """
[testenv]
commands={envpython} --version
"""
},
)
result = cmd("-vv")
assert not result.ret
assert "virtualenv --always-copy" not in result.out
@pytest.mark.skipif("sys.platform == 'win32'")
def test_empty_activity_ignored(initproj, cmd):
initproj(
"example123",
filedefs={
"tox.ini": """
[testenv]
list_dependencies_command=echo
commands={envpython} --version
"""
},
)
result = cmd()
assert not result.ret
assert "installed:" not in result.out
@pytest.mark.skipif("sys.platform == 'win32'")
def test_empty_activity_shown_verbose(initproj, cmd):
initproj(
"example123",
filedefs={
"tox.ini": """
[testenv]
list_dependencies_command=echo
commands={envpython} --version
"""
},
)
result = cmd("-v")
assert not result.ret
assert "installed:" in result.out
def test_test_piphelp(initproj, cmd):
initproj(
"example123",
filedefs={
"tox.ini": """
# content of: tox.ini
[testenv]
commands=pip -h
"""
},
)
result = cmd("-vv")
assert not result.ret, "{}\n{}".format(result.err, result.err)
def test_notest(initproj, cmd):
initproj(
"example123",
filedefs={
"tox.ini": """
# content of: tox.ini
[testenv:py26]
basepython=python
"""
},
)
result = cmd("-v", "--notest")
assert not result.ret
assert re.match(r".*summary.*" r"py26\W+skipped\W+tests.*", result.out, re.DOTALL)
result = cmd("-v", "--notest", "-epy26")
assert not result.ret
assert re.match(r".*py26\W+reusing.*", result.out, re.DOTALL)
def test_PYC(initproj, cmd, monkeypatch):
initproj("example123", filedefs={"tox.ini": ""})
monkeypatch.setenv("PYTHONDOWNWRITEBYTECODE", 1)
result = cmd("-v", "--notest")
assert not result.ret
assert "create" in result.out
def test_env_VIRTUALENV_PYTHON(initproj, cmd, monkeypatch):
initproj("example123", filedefs={"tox.ini": ""})
monkeypatch.setenv("VIRTUALENV_PYTHON", "/FOO")
result = cmd("-v", "--notest")
assert not result.ret, result.outlines
assert "create" in result.out
def test_envsitepackagesdir(cmd, initproj):
initproj(
"pkg512-0.0.5",
filedefs={
"tox.ini": """
[testenv]
commands=
python -c "print(r'X:{envsitepackagesdir}')"
"""
},
)
result = cmd()
assert result.ret == 0, "{}\n{}".format(result.err, result.out)
assert re.match(r".*\nX:.*tox.*site-packages.*", result.out, re.DOTALL)
def test_envsitepackagesdir_skip_missing_issue280(cmd, initproj):
initproj(
"pkg513-0.0.5",
filedefs={
"tox.ini": """
[testenv]
basepython=/usr/bin/qwelkjqwle
commands=
{envsitepackagesdir}
"""
},
)
result = cmd("--skip-missing-interpreters")
assert result.ret == 0, "{}\n{}".format(result.err, result.out)
assert re.match(r".*SKIPPED:.*qwelkj.*", result.out, re.DOTALL)
@pytest.mark.parametrize("verbosity", ["", "-v", "-vv"])
def test_verbosity(cmd, initproj, verbosity):
initproj(
"pkgX-0.0.5",
filedefs={
"tox.ini": """
[testenv]
"""
},
)
result = cmd(verbosity)
assert result.ret == 0, "{}\n{}".format(result.err, result.out)
needle = "Successfully installed pkgX-0.0.5"
if verbosity == "-vv":
assert any(needle in line for line in result.outlines), result.outlines
else:
assert all(needle not in line for line in result.outlines), result.outlines
def verify_json_report_format(data, testenvs=True):
assert data["reportversion"] == "1"
assert data["toxversion"] == tox.__version__
if testenvs:
for envname, envdata in data["testenvs"].items():
for commandtype in ("setup", "test"):
if commandtype not in envdata:
continue
for command in envdata[commandtype]:
assert command["output"]
assert command["retcode"]
if envname != "GLOB":
assert isinstance(envdata["installed_packages"], list)
pyinfo = envdata["python"]
assert isinstance(pyinfo["version_info"], list)
assert pyinfo["version"]
assert pyinfo["executable"]
def test_envtmpdir(initproj, cmd):
initproj(
"foo",
filedefs={
# This file first checks that envtmpdir is existent and empty. Then it
# creates an empty file in that directory. The tox command is run
# twice below, so this is to test whether the directory is cleared
# before the second run.
"check_empty_envtmpdir.py": """if True:
import os
from sys import argv
envtmpdir = argv[1]
assert os.path.exists(envtmpdir)
assert os.listdir(envtmpdir) == []
open(os.path.join(envtmpdir, 'test'), 'w').close()
""",
"tox.ini": """
[testenv]
commands=python check_empty_envtmpdir.py {envtmpdir}
""",
},
)
result = cmd()
assert not result.ret
result = cmd()
assert not result.ret
def test_missing_env_fails(initproj, cmd):
initproj("foo", filedefs={"tox.ini": "[testenv:foo]\ncommands={env:VAR}"})
result = cmd()
assert result.ret == 1, "{}\n{}".format(result.err, result.out)
assert result.out.endswith(
"foo: unresolvable substitution(s): 'VAR'."
" Environment variables are missing or defined recursively.\n"
)
def test_tox_console_script(initproj):
initproj("help", filedefs={"tox.ini": ""})
result = subprocess.check_call(["tox", "--help"])
assert result == 0
def test_tox_quickstart_script(initproj):
initproj("help", filedefs={"tox.ini": ""})
result = subprocess.check_call(["tox-quickstart", "--help"])
assert result == 0
def test_tox_cmdline_no_args(monkeypatch, initproj):
initproj("help", filedefs={"tox.ini": ""})
monkeypatch.setattr(sys, "argv", ["caller_script", "--help"])
with pytest.raises(SystemExit):
tox.cmdline()
def test_tox_cmdline_args(initproj):
initproj("help", filedefs={"tox.ini": ""})
with pytest.raises(SystemExit):
tox.cmdline(["caller_script", "--help"])
@pytest.mark.parametrize("exit_code", [0, 6])
def test_exit_code(initproj, cmd, exit_code, mocker):
""" Check for correct InvocationError, with exit code,
except for zero exit code """
import tox.exception
mocker.spy(tox.exception, "exit_code_str")
tox_ini_content = "[testenv:foo]\ncommands=python -c 'import sys; sys.exit({:d})'".format(
exit_code
)
initproj("foo", filedefs={"tox.ini": tox_ini_content})
cmd()
if exit_code:
# need mocker.spy above
assert tox.exception.exit_code_str.call_count == 1
(args, kwargs) = tox.exception.exit_code_str.call_args
assert kwargs == {}
(call_error_name, call_command, call_exit_code) = args
assert call_error_name == "InvocationError"
# quotes are removed in result.out
# do not include "python" as it is changed to python.EXE by appveyor
expected_command_arg = " -c import sys; sys.exit({:d})".format(exit_code)
assert expected_command_arg in call_command
assert call_exit_code == exit_code
else:
# need mocker.spy above
assert tox.exception.exit_code_str.call_count == 0
| {
"content_hash": "8658174fd174e76bad0989c68a59c1d8",
"timestamp": "",
"source": "github",
"line_count": 895,
"max_line_length": 99,
"avg_line_length": 29.230167597765362,
"alnum_prop": 0.5563242995298345,
"repo_name": "Avira/tox",
"id": "ed1ebdb63aa984771758c141bddae9852d56d0fa",
"size": "26161",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/unit/test_z_cmdline.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "380542"
}
],
"symlink_target": ""
} |
import sys
import os
import mxnet as mx
import numpy as np
import unittest
from mxnet.test_utils import assert_almost_equal, default_context, EnvManager
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
sys.path.insert(0, os.path.join(curr_path, '../unittest'))
from common import setup_module, with_seed, teardown
shape = (4, 4)
keys = [5, 7, 11]
str_keys = ['b', 'c', 'd']
def init_kv_with_str(stype='default', kv_type='local'):
"""init kv """
kv = mx.kv.create(kv_type)
# single
kv.init('a', mx.nd.zeros(shape, stype=stype))
# list
kv.init(str_keys, [mx.nd.zeros(shape=shape, stype=stype)] * len(keys))
return kv
# 1. Test seed 89411477 (module seed 1829754103) resulted in a py3-gpu CI runner core dump.
# 2. Test seed 1155716252 (module seed 1032824746) resulted in py3-mkldnn-gpu have error
# src/operator/nn/mkldnn/mkldnn_base.cc:567: Check failed: similar
# Both of them are not reproducible, so this test is back on random seeds.
@with_seed()
@unittest.skipIf(mx.context.num_gpus() < 2, "test_rsp_push_pull needs more than 1 GPU")
def test_rsp_push_pull():
def check_rsp_push_pull(kv_type, sparse_pull, is_push_cpu=True):
kv = init_kv_with_str('row_sparse', kv_type)
kv.init('e', mx.nd.ones(shape).tostype('row_sparse'))
push_ctxs = [mx.cpu(i) if is_push_cpu else mx.gpu(i) for i in range(2)]
kv.push('e', [mx.nd.ones(shape, ctx=context).tostype('row_sparse') for context in push_ctxs])
def check_rsp_pull(kv, ctxs, sparse_pull, is_same_rowid=False, use_slice=False):
count = len(ctxs)
num_rows = shape[0]
row_ids = []
all_row_ids = np.arange(num_rows)
vals = [mx.nd.sparse.zeros(shape=shape, ctx=ctxs[i], stype='row_sparse') for i in range(count)]
if is_same_rowid:
row_id = np.random.randint(num_rows, size=num_rows)
row_ids = [mx.nd.array(row_id)] * count
elif use_slice:
total_row_ids = mx.nd.array(np.random.randint(num_rows, size=count*num_rows))
row_ids = [total_row_ids[i*num_rows : (i+1)*num_rows] for i in range(count)]
else:
for i in range(count):
row_id = np.random.randint(num_rows, size=num_rows)
row_ids.append(mx.nd.array(row_id))
row_ids_to_pull = row_ids[0] if (len(row_ids) == 1 or is_same_rowid) else row_ids
vals_to_pull = vals[0] if len(vals) == 1 else vals
kv.row_sparse_pull('e', out=vals_to_pull, row_ids=row_ids_to_pull)
for val, row_id in zip(vals, row_ids):
retained = val.asnumpy()
excluded_row_ids = np.setdiff1d(all_row_ids, row_id.asnumpy())
for row in range(num_rows):
expected_val = np.zeros_like(retained[row])
expected_val += 0 if row in excluded_row_ids else 2
assert_almost_equal(retained[row], expected_val)
if sparse_pull is True:
kv.pull('e', out=vals_to_pull, ignore_sparse=False)
for val in vals:
retained = val.asnumpy()
expected_val = np.zeros_like(retained)
expected_val[:] = 2
assert_almost_equal(retained, expected_val)
check_rsp_pull(kv, [mx.gpu(0)], sparse_pull)
check_rsp_pull(kv, [mx.cpu(0)], sparse_pull)
check_rsp_pull(kv, [mx.gpu(i//2) for i in range(4)], sparse_pull)
check_rsp_pull(kv, [mx.gpu(i//2) for i in range(4)], sparse_pull, is_same_rowid=True)
check_rsp_pull(kv, [mx.cpu(i) for i in range(4)], sparse_pull)
check_rsp_pull(kv, [mx.cpu(i) for i in range(4)], sparse_pull, is_same_rowid=True)
check_rsp_pull(kv, [mx.gpu(i//2) for i in range(4)], sparse_pull, use_slice=True)
check_rsp_pull(kv, [mx.cpu(i) for i in range(4)], sparse_pull, use_slice=True)
envs = ["","1"]
key = "MXNET_KVSTORE_USETREE"
for val in envs:
with EnvManager(key, val):
if val is "1":
sparse_pull = False
else:
sparse_pull = True
check_rsp_push_pull('local', sparse_pull)
check_rsp_push_pull('device', sparse_pull)
check_rsp_push_pull('device', sparse_pull, is_push_cpu=False)
def test_row_sparse_pull_single_device():
kvstore = mx.kv.create('device')
copy = mx.nd.random_normal(shape=(4,4), ctx=mx.gpu(0))
grad = copy.tostype("row_sparse")
key = 0
kvstore.init(key, grad)
idx = grad.indices
kvstore.push(key, grad)
kvstore.row_sparse_pull(key, out=grad, row_ids=idx)
assert_almost_equal(grad.asnumpy(), copy.asnumpy())
def test_rsp_push_pull_large_rowid():
num_rows = 793470
val = mx.nd.ones((num_rows, 1)).tostype('row_sparse').copyto(mx.gpu())
kv = mx.kv.create('device')
kv.init('a', val)
out = mx.nd.zeros((num_rows,1), stype='row_sparse').copyto(mx.gpu())
kv.push('a', val)
kv.row_sparse_pull('a', out=out, row_ids=mx.nd.arange(0, num_rows, dtype='int64'))
assert(out.indices.shape[0] == num_rows)
if __name__ == '__main__':
import nose
nose.runmodule()
| {
"content_hash": "690b6c5aec5a8ec1b8ccbb9b363e553d",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 107,
"avg_line_length": 43.891666666666666,
"alnum_prop": 0.5897095120561989,
"repo_name": "eric-haibin-lin/mxnet",
"id": "1dddc58896439488466f4c5f5ee124706aa7673c",
"size": "6073",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "tests/python/gpu/test_kvstore_gpu.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "1731"
},
{
"name": "Batchfile",
"bytes": "13130"
},
{
"name": "C",
"bytes": "227904"
},
{
"name": "C++",
"bytes": "9488576"
},
{
"name": "CMake",
"bytes": "157668"
},
{
"name": "Clojure",
"bytes": "622652"
},
{
"name": "Cuda",
"bytes": "1290499"
},
{
"name": "Dockerfile",
"bytes": "100732"
},
{
"name": "Groovy",
"bytes": "165546"
},
{
"name": "HTML",
"bytes": "40277"
},
{
"name": "Java",
"bytes": "205196"
},
{
"name": "Julia",
"bytes": "445413"
},
{
"name": "Jupyter Notebook",
"bytes": "3660357"
},
{
"name": "MATLAB",
"bytes": "34903"
},
{
"name": "Makefile",
"bytes": "148945"
},
{
"name": "Perl",
"bytes": "1558292"
},
{
"name": "PowerShell",
"bytes": "9244"
},
{
"name": "Python",
"bytes": "9642639"
},
{
"name": "R",
"bytes": "357994"
},
{
"name": "Raku",
"bytes": "9012"
},
{
"name": "SWIG",
"bytes": "161870"
},
{
"name": "Scala",
"bytes": "1304647"
},
{
"name": "Shell",
"bytes": "460509"
},
{
"name": "Smalltalk",
"bytes": "3497"
}
],
"symlink_target": ""
} |
import actions as self
import shared
import xbmc
import xbmcaddon
import xbmcgui
# define ISY API actions
__act_names__ = {
'on': 'NodeOn',
'off': 'NodeOff',
'toggle': 'NodeToggle',
'faston': 'NodeFastOn',
'fastoff': 'NodeFastOff',
'bright': 'NodeBright',
'dim': 'NodeDim',
'on25': 'NodeOn25',
'on50': 'NodeOn50',
'on75': 'NodeOn75',
'on100': 'NodeOn100',
'run': 'ProgramRun',
'then': 'ProgramRunThen',
'else': 'ProgramRunElse'}
# define local actions
__act_names_local__ = {
'info': 'ShowNodeInfo',
'pinfo': 'ShowProgramInfo',
'config': 'ShowAddonConfig'}
def DoAction(addr, cmd):
'''
DoAction(addr, cmd)
DESCRIPTION:
This function executes actions on a
given address. This is the function
that is called by the menu items.
'''
try:
fun = getattr(shared.isy, __act_names__[cmd])
except KeyError:
fun = getattr(self, __act_names_local__[cmd])
fun(addr)
# local actions
# these are actions that are performed
# on the nodes that would not be
# appropriate in the ISY API
def ShowNodeInfo(addr):
'''
ShowNodeInfo(addr)
DESCRIPTION:
This action displays node information
on the screen.
'''
data = shared.isy.NodeInfo(addr)
name = data.keys()[0]
type = data[name][0]
status = data[name][2]
if type == 'node':
output = name + ' (' + str(int(float(status) / 255.0 * 100.0)) + '%)' \
+ '\n' + shared.translate(30302) + ': ' + str(addr)
else:
output = name + '\n' + shared.translate(30302) + ': ' + str(addr)
dialog = xbmcgui.Dialog()
dialog.ok(shared.translate(30301), output)
def ShowProgramInfo(addr):
'''
ShowProgramInfo(addr)
DESCRIPTION:
This action displays program information
on the screen.
'''
output = shared.translate(30302) + ': ' + str(addr)
dialog = xbmcgui.Dialog()
dialog.ok(shared.translate(30301), output)
def ShowAddonConfig(addr):
'''
ShowAddonConfig(addr)
DESCRIPTION:
This action opens the configuration for
an XBMC addon on the screen.
'''
xbmcaddon.Addon(id=addr).openSettings()
def RefreshWindow(*args, **kwargs):
'''
RefreshWindow(*)
DESCRIPTION:
This function refreshes the active
window in XBMC. All inputs are ignored
so that it can be called like the
other actions that do require input.
'''
xbmc.executebuiltin('XBMC.Container.Refresh()')
| {
"content_hash": "cb50b4abe6b48ac549ecdcedbb233447",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 79,
"avg_line_length": 22.908256880733944,
"alnum_prop": 0.6139367240688827,
"repo_name": "automicus/XBMC-ISY-Browser",
"id": "21e0408dddcb732b2fe93e8ebb2ba023327971ff",
"size": "2497",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "resources/lib/actions.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "27087"
}
],
"symlink_target": ""
} |
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from createprofile.models import Employee_Profile,Employer_Profile, Document, Profile_Picture, Listing, Logo
class CreateProfileFromEE(forms.ModelForm):
class Meta:
model = Employee_Profile
fields = (
'current_company',
'previous_company',
'highest_qualification',
'institute_hq',
'highschool',
'bio',
'location',
'birth_date',
'sql',
'python',
'r',
'scala',
'julia',
'tableau',)
class CreateProfileFromER(forms.ModelForm):
class Meta:
model = Employer_Profile
fields = (
'company',
'industry',
'bio',
'url', )
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ('description', 'document', )
class ListingForm(forms.ModelForm):
class Meta:
model = Listing
fields = ('description', 'document', )
class ProfilePictureForm(forms.ModelForm):
class Meta:
model = Profile_Picture
fields = ('description', 'photo', )
class LogoForm(forms.ModelForm):
class Meta:
model = Logo
fields = ('description', 'photo', )
| {
"content_hash": "98337488ae7ff8d67dfd9f53e583dadc",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 108,
"avg_line_length": 21.649122807017545,
"alnum_prop": 0.640194489465154,
"repo_name": "coetzeevs/chiron",
"id": "9bdd9f3f79825a22872fe608d7414df9b745388c",
"size": "1234",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mysite/createprofile/forms.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "111"
},
{
"name": "HTML",
"bytes": "18253"
},
{
"name": "Python",
"bytes": "67061"
}
],
"symlink_target": ""
} |
import unittest
from test.test_support import requires
from Tkinter import Tk, Text
import idlelib.AutoComplete as ac
import idlelib.AutoCompleteWindow as acw
import idlelib.macosxSupport as mac
from idlelib.idle_test.mock_idle import Func
from idlelib.idle_test.mock_tk import Event
class AutoCompleteWindow:
def complete():
return
class DummyEditwin:
def __init__(self, root, text):
self.root = root
self.text = text
self.indentwidth = 8
self.tabwidth = 8
self.context_use_ps1 = True
class AutoCompleteTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = Tk()
mac.setupApp(cls.root, None)
cls.text = Text(cls.root)
cls.editor = DummyEditwin(cls.root, cls.text)
@classmethod
def tearDownClass(cls):
del cls.editor, cls.text
cls.root.destroy()
del cls.root
def setUp(self):
self.editor.text.delete('1.0', 'end')
self.autocomplete = ac.AutoComplete(self.editor)
def test_init(self):
self.assertEqual(self.autocomplete.editwin, self.editor)
def test_make_autocomplete_window(self):
testwin = self.autocomplete._make_autocomplete_window()
self.assertIsInstance(testwin, acw.AutoCompleteWindow)
def test_remove_autocomplete_window(self):
self.autocomplete.autocompletewindow = (
self.autocomplete._make_autocomplete_window())
self.autocomplete._remove_autocomplete_window()
self.assertIsNone(self.autocomplete.autocompletewindow)
def test_force_open_completions_event(self):
# Test that force_open_completions_event calls _open_completions
o_cs = Func()
self.autocomplete.open_completions = o_cs
self.autocomplete.force_open_completions_event('event')
self.assertEqual(o_cs.args, (True, False, True))
def test_try_open_completions_event(self):
Equal = self.assertEqual
autocomplete = self.autocomplete
trycompletions = self.autocomplete.try_open_completions_event
o_c_l = Func()
autocomplete._open_completions_later = o_c_l
# _open_completions_later should not be called with no text in editor
trycompletions('event')
Equal(o_c_l.args, None)
# _open_completions_later should be called with COMPLETE_ATTRIBUTES (1)
self.text.insert('1.0', 're.')
trycompletions('event')
Equal(o_c_l.args, (False, False, False, 1))
# _open_completions_later should be called with COMPLETE_FILES (2)
self.text.delete('1.0', 'end')
self.text.insert('1.0', '"./Lib/')
trycompletions('event')
Equal(o_c_l.args, (False, False, False, 2))
def test_autocomplete_event(self):
Equal = self.assertEqual
autocomplete = self.autocomplete
# Test that the autocomplete event is ignored if user is pressing a
# modifier key in addition to the tab key
ev = Event(mc_state=True)
self.assertIsNone(autocomplete.autocomplete_event(ev))
del ev.mc_state
# If autocomplete window is open, complete() method is called
self.text.insert('1.0', 're.')
# This must call autocomplete._make_autocomplete_window()
Equal(self.autocomplete.autocomplete_event(ev), 'break')
# If autocomplete window is not active or does not exist,
# open_completions is called. Return depends on its return.
autocomplete._remove_autocomplete_window()
o_cs = Func() # .result = None
autocomplete.open_completions = o_cs
Equal(self.autocomplete.autocomplete_event(ev), None)
Equal(o_cs.args, (False, True, True))
o_cs.result = True
Equal(self.autocomplete.autocomplete_event(ev), 'break')
Equal(o_cs.args, (False, True, True))
def test_open_completions_later(self):
# Test that autocomplete._delayed_completion_id is set
pass
def test_delayed_open_completions(self):
# Test that autocomplete._delayed_completion_id set to None and that
# open_completions only called if insertion index is the same as
# _delayed_completion_index
pass
def test_open_completions(self):
# Test completions of files and attributes as well as non-completion
# of errors
pass
def test_fetch_completions(self):
# Test that fetch_completions returns 2 lists:
# For attribute completion, a large list containing all variables, and
# a small list containing non-private variables.
# For file completion, a large list containing all files in the path,
# and a small list containing files that do not start with '.'
pass
def test_get_entity(self):
# Test that a name is in the namespace of sys.modules and
# __main__.__dict__
pass
if __name__ == '__main__':
unittest.main(verbosity=2)
| {
"content_hash": "c24259feedf44f1cdc52f572b971dd62",
"timestamp": "",
"source": "github",
"line_count": 142,
"max_line_length": 79,
"avg_line_length": 35.17605633802817,
"alnum_prop": 0.6516516516516516,
"repo_name": "wang1352083/pythontool",
"id": "1e98590b9e4dfd98b037d7a55d9d9963035610de",
"size": "4995",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "python-2.7.12-lib/idlelib/idle_test/test_autocomplete.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "252"
},
{
"name": "Groff",
"bytes": "21"
},
{
"name": "HTML",
"bytes": "153685"
},
{
"name": "PLSQL",
"bytes": "22886"
},
{
"name": "Python",
"bytes": "18207080"
},
{
"name": "Shell",
"bytes": "390"
},
{
"name": "Visual Basic",
"bytes": "481"
}
],
"symlink_target": ""
} |
"""Helpers that interact with the "readelf" tool."""
import re
import subprocess
import path_util
def BuildIdFromElf(elf_path):
"""Returns the Build ID for the given binary."""
args = [path_util.GetReadElfPath(), '-n', elf_path]
stdout = subprocess.check_output(args, encoding='ascii')
match = re.search(r'Build ID: (\w+)', stdout)
assert match, 'Build ID not found from running: ' + ' '.join(args)
return match.group(1)
def ArchFromElf(elf_path):
"""Returns the GN architecture for the given binary."""
args = [path_util.GetReadElfPath(), '-h', elf_path]
stdout = subprocess.check_output(args, encoding='ascii')
machine = re.search('Machine:\s*(.+)', stdout).group(1)
if machine == 'Intel 80386':
return 'x86'
if machine == 'Advanced Micro Devices X86-64':
return 'x64'
if machine == 'ARM':
return 'arm'
if machine == 'AArch64':
return 'arm64'
return machine
def SectionInfoFromElf(elf_path):
"""Finds the address and size of all ELF sections
Returns:
A dict of section_name->(start_address, size).
"""
args = [path_util.GetReadElfPath(), '-S', '--wide', elf_path]
stdout = subprocess.check_output(args, encoding='ascii')
section_ranges = {}
# Matches [ 2] .hash HASH 00000000006681f0 0001f0 003154 04 A 3 0 8
for match in re.finditer(r'\[[\s\d]+\] (\..*)$', stdout, re.MULTILINE):
items = match.group(1).split()
section_ranges[items[0]] = (int(items[2], 16), int(items[4], 16))
return section_ranges
def CollectRelocationAddresses(elf_path):
"""Returns the list of addresses that are targets for relative relocations."""
cmd = [path_util.GetReadElfPath(), '--relocs', elf_path]
ret = subprocess.check_output(cmd, encoding='ascii').splitlines()
# Grab first column from (sample output) '02de6d5c 00000017 R_ARM_RELATIVE'
return [int(l.split(maxsplit=1)[0], 16) for l in ret if 'R_ARM_RELATIVE' in l]
| {
"content_hash": "5e933b02ead166ae64fb6827c19e0466",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 80,
"avg_line_length": 34.654545454545456,
"alnum_prop": 0.670514165792235,
"repo_name": "chromium/chromium",
"id": "f3d7cc5c8a338979ed4a8dc05f5765b1098de53b",
"size": "2046",
"binary": false,
"copies": "7",
"ref": "refs/heads/main",
"path": "tools/binary_size/libsupersize/readelf.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
"""
Test handling of loading external stuff in twanager.
"""
from tiddlyweb.manage import _external_load
from tiddlyweb.config import config as global_config
config = {
'monkey': 'bar',
}
def test_load_file():
args = _external_load(['twanager', '--load', 'test/test_external_load.py', 'foobar'], global_config)
assert args == ['twanager', 'foobar']
assert global_config['monkey'] == 'bar'
def test_load_module():
args = _external_load(['twanager', '--load', 'test.test_external_load', 'foobar'], global_config)
assert args == ['twanager', 'foobar']
assert global_config['monkey'] == 'bar'
| {
"content_hash": "383e5397382afd20bfde7b3a83fd3f23",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 104,
"avg_line_length": 31.65,
"alnum_prop": 0.6461295418641391,
"repo_name": "funkyeah/tiddlyweb",
"id": "2210ea2be047f31a3f56e4bbb1e0f5f663b39d05",
"size": "633",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/test_external_load.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
"""
Configuration file generator for the other scripts. Useful for experiments.
"""
from __future__ import absolute_import, division, print_function
from argparse import ArgumentParser
from builtins import str as text
from itertools import product
from operator import itemgetter
import os
import json
import configobj
from emLam.utils.config import handle_errors, load_config, set_dot_value
from emLam.utils import openall
def parse_arguments():
parser = ArgumentParser(
description='Configuration file generator for the other scripts. '
'Useful for experiments. Note that the schema checking '
'is very general, so the configuration files should be '
'"as valid as possible".')
parser.add_argument('--configuration', '-c', required=True,
help='the configuration file to use as a base.')
parser.add_argument('--schema', '-s', required=True,
help='the schema file.')
parser.add_argument('--replacements', '-r', required=True,
help='the replacement mappings. A JSON dictionary, '
'where the keys are the (full) key paths, '
'and the values are either lists, or '
'a string that contains a '
'single %% character, which gets replaced by the '
'current values of the list-valued parameters '
'separated by hyphens.')
parser.add_argument('--output_dir', '-o', required=True,
help='the output directory.')
return parser.parse_args()
def read_mappings(mapping_file):
"""
Reads the replacement mappings. I know JSON is ugly, but for (usually)
int and float parameters it can be written nicely.
"""
string_mappings, list_mappings = [], []
with openall(mapping_file) as inf:
d = json.load(inf)
for k, v in sorted(d.items()):
if isinstance(v, list):
list_mappings.append((k, v))
elif isinstance(v, text):
string_mappings.append((k, v))
else:
raise ValueError(
'Unsupported value type ({}: {}) for key {}'.format(
v, type(v), k))
if len(list_mappings) == 0:
raise ValueError('No list replacements found in file {}.'.format(
mapping_file))
return string_mappings, list_mappings
def new_file_name(file_name, values_str):
"""
Returns the file name of the new configuration file: the original name, with
values_str appended to it. If the original file had an extension (the part
of the name after the last dot), it will be kept at the end of the file.
"""
base_name, dot, ext = os.path.basename(file_name).rpartition('.')
return base_name + '-' + values_str + dot + ext
def delete_nones(section):
"""
Deletes all None members from a section. This should be called as-is,
not via walk(), because the latter does not allow deletion in its contract.
"""
to_remove = set()
for k, v in section.items():
if v is None:
to_remove.add(k)
elif isinstance(v, dict):
delete_nones(v)
if len(v) == 0:
to_remove.add(k)
for k in to_remove:
del section[k]
def main():
args = parse_arguments()
config, warnings, errors = load_config(args.configuration, args.schema)
handle_errors(warnings, errors)
string_mappings, list_mappings = read_mappings(args.replacements)
if not os.path.isdir(args.output_dir):
os.makedirs(args.output_dir)
keys = list(map(itemgetter(0), list_mappings))
for values in product(*map(itemgetter(1), list_mappings)):
new_config = configobj.ConfigObj(config)
values_str = u'-'.join(text(v) for v in values)
for i, key in enumerate(keys):
set_dot_value(new_config, key, values[i])
for skey, svalue in string_mappings:
set_dot_value(new_config, skey, svalue.replace('%', values_str))
new_config.filename = os.path.join(
args.output_dir, new_file_name(args.configuration, values_str))
delete_nones(new_config)
new_config.write()
if __name__ == '__main__':
main()
| {
"content_hash": "21421f94d336b3fc2ea37388b78ae552",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 80,
"avg_line_length": 38.130434782608695,
"alnum_prop": 0.5963511972633979,
"repo_name": "dlt-rilmta/emLam",
"id": "218e6e1f648c82e391c10f060f361ac2c9182569",
"size": "4441",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "scripts/configuration_generator.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "165160"
}
],
"symlink_target": ""
} |
import sys
import wx
from gooey.gui import events
from gooey.gui.lang import i18n
from gooey.gui.pubsub import pub
class Footer(wx.Panel):
'''
Footer section used on the configuration
screen of the application
'''
def __init__(self, parent, buildSpec, **kwargs):
wx.Panel.__init__(self, parent, **kwargs)
self.buildSpec = buildSpec
self.SetMinSize((30, 53))
# components
self.cancel_button = None
self.start_button = None
self.progress_bar = None
self.close_button = None
self.stop_button = None
self.restart_button = None
self.edit_button = None
self.buttons = []
self.layouts = {}
self._init_components()
self._do_layout()
for button in self.buttons:
self.Bind(wx.EVT_BUTTON, self.dispatch_click, button)
def updateProgressBar(self, *args, **kwargs):
'''
value, disable_animation=False
:param args:
:param kwargs:
:return:
'''
value = kwargs.get('progress')
pb = self.progress_bar
if value is None:
return
if value < 0:
pb.Pulse()
else:
value = min(int(value), pb.GetRange())
if pb.GetValue() != value:
# Windows 7 progress bar animation hack
# http://stackoverflow.com/questions/5332616/disabling-net-progressbar-animation-when-changing-value
if self.buildSpec['disable_progress_bar_animation'] \
and sys.platform.startswith("win"):
if pb.GetRange() == value:
pb.SetValue(value)
pb.SetValue(value - 1)
else:
pb.SetValue(value + 1)
pb.SetValue(value)
def showButtons(self, *buttonsToShow):
for button in self.buttons:
button.Show(False)
for button in buttonsToShow:
getattr(self, button).Show(True)
self.Layout()
def _init_components(self):
self.cancel_button = self.button(i18n._('cancel'), wx.ID_CANCEL, event_id=events.WINDOW_CANCEL)
self.stop_button = self.button(i18n._('stop'), wx.ID_OK, event_id=events.WINDOW_STOP)
self.start_button = self.button(i18n._('start'), wx.ID_OK, event_id=int(events.WINDOW_START))
self.close_button = self.button(i18n._("close"), wx.ID_OK, event_id=int(events.WINDOW_CLOSE))
self.restart_button = self.button(i18n._('restart'), wx.ID_OK, event_id=int(events.WINDOW_RESTART))
self.edit_button = self.button(i18n._('edit'), wx.ID_OK, event_id=int(events.WINDOW_EDIT))
self.progress_bar = wx.Gauge(self, range=100)
self.buttons = [self.cancel_button, self.start_button,
self.stop_button, self.close_button,
self.restart_button, self.edit_button]
if self.buildSpec['disable_stop_button']:
self.stop_button.Enable(False)
def _do_layout(self):
self.stop_button.Hide()
self.restart_button.Hide()
v_sizer = wx.BoxSizer(wx.VERTICAL)
h_sizer = wx.BoxSizer(wx.HORIZONTAL)
h_sizer.Add(self.progress_bar, 1,
wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.LEFT, 20)
self.progress_bar.Hide()
h_sizer.AddStretchSpacer(1)
h_sizer.Add(self.cancel_button, 0, wx.ALIGN_RIGHT | wx.RIGHT, 20)
h_sizer.Add(self.start_button, 0, wx.ALIGN_RIGHT | wx.RIGHT, 20)
h_sizer.Add(self.stop_button, 0, wx.ALIGN_RIGHT | wx.RIGHT, 20)
v_sizer.AddStretchSpacer(1)
v_sizer.Add(h_sizer, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
h_sizer.Add(self.edit_button, 0, wx.ALIGN_RIGHT | wx.RIGHT, 10)
h_sizer.Add(self.restart_button, 0, wx.ALIGN_RIGHT | wx.RIGHT, 10)
h_sizer.Add(self.close_button, 0, wx.ALIGN_RIGHT | wx.RIGHT, 20)
self.edit_button.Hide()
self.restart_button.Hide()
self.close_button.Hide()
v_sizer.AddStretchSpacer(1)
self.SetSizer(v_sizer)
def button(self, label=None, style=None, event_id=-1):
return wx.Button(
parent=self,
id=event_id,
size=(90, 24),
label=i18n._(label),
style=style)
def dispatch_click(self, event):
pub.send_message(event.GetId())
def hide_all_buttons(self):
for button in self.buttons:
button.Hide()
| {
"content_hash": "dd6dca88edc68464a9671927dd12d010",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 116,
"avg_line_length": 34.88805970149254,
"alnum_prop": 0.558716577540107,
"repo_name": "codingsnippets/Gooey",
"id": "6058b519524f14c6bb1fb756f80598c7e6e2cd49",
"size": "4675",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gooey/gui/components/footer.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "132430"
}
],
"symlink_target": ""
} |
def myblock(tw, args):
''' Draw a dotted line of length line_length. '''
try: # make sure line_length is a number
line_length = float(args[0])
except ValueError:
return
if tw.turtles.get_active_turtle().get_pen_state():
dist = 0
pen_size = tw.turtles.get_active_turtle().get_pen_size()
while dist + pen_size < line_length: # repeat drawing dots
tw.turtles.get_active_turtle().set_pen_state(True)
tw.turtles.get_active_turtle().forward(1)
tw.turtles.get_active_turtle().set_pen_state(False)
tw.turtles.get_active_turtle().forward(pen_size * 2 - 1)
dist += pen_size * 2
# make sure we have moved exactly line_length
tw.turtles.get_active_turtle().forward(line_length - dist)
tw.turtles.get_active_turtle().set_pen_state(True)
else:
tw.turtles.get_active_turtle().forward(line_length)
return
| {
"content_hash": "177cf9da03e2498c50e1100fa5004cd0",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 68,
"avg_line_length": 43.09090909090909,
"alnum_prop": 0.6128691983122363,
"repo_name": "walterbender/turtle3D",
"id": "098e0a4872efeb7f9e61790a1cf97c3285003b29",
"size": "6150",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pysamples/dotted_line.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "1757311"
}
],
"symlink_target": ""
} |
import os
import unittest
from __main__ import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
import logging
#
# VesselDisplay
#
class VesselDisplay(ScriptedLoadableModule):
def __init__(self, parent):
ScriptedLoadableModule.__init__(self, parent)
self.parent.title = "Vessel Display"
self.parent.categories = ["Examples"]
self.parent.dependencies = ["SubjectHierarchy"]
self.parent.contributors = [""]
self.parent.helpText = """ """
self.parent.acknowledgementText = """ """
#
# VesselDisplayWidget
#
class VesselDisplayWidget(ScriptedLoadableModuleWidget):
def setup(self):
ScriptedLoadableModuleWidget.setup(self)
# Instantiate and connect widgets ...
#Display Region. Obtained from Subject Hierarchy
displayCollapsibleButton = ctk.ctkCollapsibleButton()
displayCollapsibleButton.text = "Display"
self.layout.addWidget(displayCollapsibleButton)
# Layout within the display collapsible button
displayFormLayout = qt.QHBoxLayout()
displayCollapsibleButton.setLayout(displayFormLayout)
self.subjectHierarchyTreeView = slicer.qMRMLSubjectHierarchyTreeView()
self.subjectHierarchyTreeView.setMRMLScene(slicer.app.mrmlScene())
self.subjectHierarchyTreeView.setColumnHidden(self.subjectHierarchyTreeView.sceneModel().idColumn,True)
displayFormLayout.addWidget(self.subjectHierarchyTreeView)
self.subjectHierarchyTreeView.connect("currentNodeChanged(vtkMRMLNode*)", self.onSubjectHierarchyNodeSelect)
#Properties Region
self.displayPropertiesCollapsibleButton = ctk.ctkCollapsibleButton()
self.displayPropertiesCollapsibleButton.text = "Display Properties"
self.layout.addWidget(self.displayPropertiesCollapsibleButton)
self.displayPropertiesCollapsibleButton.enabled = False
# Layout within the display-properties collapsible button
displayPropertiesFormLayout = qt.QHBoxLayout()
self.displayPropertiesCollapsibleButton.setLayout(displayPropertiesFormLayout)
# Volume display properties
self.volumeDisplayWidget = slicer.qSlicerVolumeDisplayWidget()
displayPropertiesFormLayout.addWidget(self.volumeDisplayWidget)
self.volumeDisplayWidget.hide()
#Spacial Objects display properties
self.spacialObjectsWidget = slicer.qSlicerSpatialObjectsModuleWidget()
displayPropertiesFormLayout.addWidget(self.spacialObjectsWidget)
self.spacialObjectsWidget.hide()
def onSubjectHierarchyNodeSelect(self):
self.displayPropertiesCollapsibleButton.enabled = True
#get current node from subject hierarchy
currentInstance = slicer.qSlicerSubjectHierarchyPluginHandler().instance()
currentNode = currentInstance.currentNode()
if currentNode != None:
#current node is subject hierarchy node
currentAssociatedNode = currentNode.GetAssociatedNode()
if currentAssociatedNode !=None:
currentNodetype = currentAssociatedNode.GetNodeTagName()
print currentNodetype
if 'Volume' in currentNodetype :
self.volumeDisplayWidget.show()
self.spacialObjectsWidget.hide()
self.volumeDisplayWidget.setMRMLVolumeNode(currentAssociatedNode)
slicer.app.layoutManager().setLayout(3)
return
elif 'Spatial' in currentNodetype :
self.volumeDisplayWidget.hide()
self.spacialObjectsWidget.show()
self.spacialObjectsWidget.setSpatialObjectsNode(currentAssociatedNode)
slicer.app.layoutManager().setLayout(4)
return
self.displayPropertiesCollapsibleButton.enabled = False
#
# VesselDisplayLogic
#
class VesselDisplayLogic(ScriptedLoadableModuleLogic):
def hasImageData(self,volumeNode):
"""This is an example logic method that
returns true if the passed in volume
node has valid image data
"""
if not volumeNode:
logging.debug('hasImageData failed: no volume node')
return False
if volumeNode.GetImageData() == None:
logging.debug('hasImageData failed: no image data in volume node')
return False
return True
#
# VesselDisplayTest
#
class VesselDisplayTest(ScriptedLoadableModuleTest):
def runTest(self):
self.test_VesselDisplay1()
def test_VesselDisplay1(self):
self.delayDisplay("Starting the test")
#
# first, get some data
#
import urllib
downloads = (
('http://slicer.kitware.com/midas3/download?items=5767', 'FA.nrrd', slicer.util.loadVolume),
)
for url,name,loader in downloads:
filePath = slicer.app.temporaryPath + '/' + name
if not os.path.exists(filePath) or os.stat(filePath).st_size == 0:
logging.info('Requesting download %s from %s...\n' % (name, url))
urllib.urlretrieve(url, filePath)
if loader:
logging.info('Loading %s...' % (name,))
loader(filePath)
self.delayDisplay('Finished with download and loading')
volumeNode = slicer.util.getNode(pattern="FA")
logic = VesselDisplayLogic()
logic.hasImageData(volumeNode)
self.delayDisplay('Test passed!')
| {
"content_hash": "3173617f8c75d4288ce634ce7fad6bdc",
"timestamp": "",
"source": "github",
"line_count": 141,
"max_line_length": 112,
"avg_line_length": 35.97163120567376,
"alnum_prop": 0.7383675078864353,
"repo_name": "sumedhasingla/VesselView",
"id": "847569353c467f64948e371a72ecb3b85ccda11a",
"size": "5072",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Modules/Scripted/VesselDisplay/VesselDisplay.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "685"
},
{
"name": "C++",
"bytes": "273209"
},
{
"name": "CMake",
"bytes": "153131"
},
{
"name": "Python",
"bytes": "170717"
},
{
"name": "QML",
"bytes": "38383"
},
{
"name": "Shell",
"bytes": "1956"
}
],
"symlink_target": ""
} |
"""
Copyright (c) 2017 Muxr, http://www.eevblog.com/forum/profile/?u=105823
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
"""
import time
import serial
import sys
import argparse
import os
import signal
import itertools
original_sigint = None
class Unbuffered(object):
"""
overwrites the sys.stdout so that the output isn't buffered
generally if you're writting a lot of data you'd want it to be buffered
but in this script we usually only write once a second and the immediate
feedback is prefered
"""
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def writelines(self, datas):
self.stream.writelines(datas)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
sys.stdout = Unbuffered(sys.stdout)
class Progress(object):
def __init__(self):
self.frames = '/-\|'
self.pos = 0
def show(self):
if self.pos >= len(self.frames):
self.pos = 0
sys.stdout.write('\r' + self.frames[self.pos:][0])
sys.stdout.flush()
self.pos += 1
def exit_gracefully(signum, frame):
global original_sigint
# restore the original signal handler as otherwise evil things will happen
# in raw_input when CTRL+C is pressed, and our signal handler is not re-entrant
signal.signal(signal.SIGINT, original_sigint)
try:
if raw_input("\nReally quit? (y/n)> ").lower().startswith('y'):
sys.exit(1)
except KeyboardInterrupt:
print("Ok ok, quitting")
sys.exit(1)
# restore the exit gracefully handler here
signal.signal(signal.SIGINT, exit_gracefully)
def format_time(ts):
return time.strftime("%D %H:%M:%S", time.localtime(int(ts)))
def log(options):
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port=options.device,
baudrate=9600,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.SEVENBITS
)
prog = Progress()
with open(options.outfile, 'w') as the_file:
the_file.write('timestamp;value\n')
while True:
# \r\n is for device terminators set to CR LF
ser.write((':FETCh?\r\n'))
# wait one second before reading output.
time.sleep(options.interval)
out = ''
while ser.inWaiting() > 0:
out += ser.read(1)
if out != '':
out = out.rstrip()
res = "%s;%s\n" % (time.time(), float(out))
the_file.write(res)
the_file.flush()
prog.show()
def main():
global original_sigint
parser = argparse.ArgumentParser()
parser.add_argument('outfile', nargs='?')
parser.add_argument('-d',
'--device',
dest='device',
action='store',
default='/dev/cu.usbserial',
help='Path to the serial device')
parser.add_argument('-i',
'--interval',
dest='interval',
action='store',
default=1,
type=float,
help='Polling interval')
options = parser.parse_args()
# store the original SIGINT handler
original_sigint = signal.getsignal(signal.SIGINT)
signal.signal(signal.SIGINT, exit_gracefully)
index = 1
if os.path.exists(options.outfile):
while os.path.exists(options.outfile + '_' + str(index)):
index += 1
if index > 100:
print "filenames exhausted"
sys.exit(1)
options.outfile = options.outfile + '_' + str(index)
print 'logging to: {}'.format(options.outfile)
log(options)
if __name__ == '__main__':
main()
| {
"content_hash": "73aba4dd8369f390aa9411e8ff7eb014",
"timestamp": "",
"source": "github",
"line_count": 160,
"max_line_length": 99,
"avg_line_length": 31.425,
"alnum_prop": 0.6117740652346858,
"repo_name": "sirmo/muxrplot",
"id": "b66c0b67a0360f020fe1de156561c3d5a734f56f",
"size": "5028",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mplot/logger.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "418"
},
{
"name": "Python",
"bytes": "14491"
}
],
"symlink_target": ""
} |
import pygame
from spritesheet import SpriteSheet
from enemy import Enemy
from directions import Directions
from utils import *
class Ghost(Enemy):
"""Ghost Enemy."""
def __init__(self, width, height, x, y):
Enemy.__init__(self, width, 44, x, y)
self.dir = 'R'
self.speed = 1
# initialize sprite lists
ss = SpriteSheet(path.join(get_art_dir(), 'Ghost', 'Ghost_spritesheet.png'), 12)
self.sprites_walk_left = ss.get_sprites(size=(30, 44))
self.sprites_walk_right = [pygame.transform.flip(s, True, False) for s in self.sprites_walk_left]
self.image = self.sprites_walk_right[0]
def get_sprites(self):
ret = None
if self.heading == Directions.Left:
ret = self.sprites_walk_left
elif self.heading == Directions.Right:
ret = self.sprites_walk_right
return ret
def update(self, c):
super(Ghost, self).update(c)
| {
"content_hash": "ec4c5112a3a66325873c252167b352ea",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 99,
"avg_line_length": 27.548387096774192,
"alnum_prop": 0.6885245901639344,
"repo_name": "450W16/MODACT",
"id": "836b3fd986578e0095880b96f7099086f53a97b7",
"size": "854",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/characters/ghost.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "63777"
}
],
"symlink_target": ""
} |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import fnmatch
import os
import sys
from setuptools import find_packages, setup, Extension
from setuptools.dist import Distribution
_VERSION = '0.6.0'
REQUIRED_PACKAGES = [
'numpy >= 1.8.2',
'six >= 1.10.0',
'protobuf == 3.0.0a3',
]
# python3 requires wheel 0.26
if sys.version_info.major == 3:
REQUIRED_PACKAGES.append('wheel >= 0.26')
else:
REQUIRED_PACKAGES.append('wheel')
# pylint: disable=line-too-long
CONSOLE_SCRIPTS = [
'tensorboard = tensorflow.tensorboard.tensorboard:main',
]
# pylint: enable=line-too-long
TEST_PACKAGES = [
'scipy >= 0.15.1',
]
class BinaryDistribution(Distribution):
def is_pure(self):
return False
matches = []
for root, dirnames, filenames in os.walk('external'):
for filename in fnmatch.filter(filenames, '*'):
matches.append(os.path.join(root, filename))
matches = ['../' + x for x in matches if '.py' not in x]
setup(
name='tensorflow',
version=_VERSION,
description='TensorFlow helps the tensors flow',
long_description='',
url='http://tensorflow.com/',
author='Google Inc.',
author_email='opensource@google.com',
# Contained modules and scripts.
packages=find_packages(),
entry_points={
'console_scripts': CONSOLE_SCRIPTS,
},
install_requires=REQUIRED_PACKAGES,
tests_require=REQUIRED_PACKAGES + TEST_PACKAGES,
# Add in any packaged data.
include_package_data=True,
package_data={
'tensorflow': ['python/_pywrap_tensorflow.so',
'tensorboard/dist/index.html',
'tensorboard/dist/tf-tensorboard.html',
'tensorboard/lib/css/global.css',
] + matches,
},
zip_safe=False,
distclass=BinaryDistribution,
# PyPI package information.
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Software Development :: Libraries',
],
license='Apache 2.0',
keywords='tensorflow tensor machine learning',
)
| {
"content_hash": "fc3c68365c90b6750a26a073b541e0f9",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 71,
"avg_line_length": 28.261363636363637,
"alnum_prop": 0.6385203055890631,
"repo_name": "miyosuda/intro-to-dl-android",
"id": "76f714f8b282c8cf2acea5a26dc48352f9a944dc",
"size": "3165",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "HandWriting/jni-build/jni/include/tensorflow/tools/pip_package/setup.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "286277"
},
{
"name": "C++",
"bytes": "25872569"
},
{
"name": "CSS",
"bytes": "214"
},
{
"name": "HTML",
"bytes": "1249714"
},
{
"name": "Java",
"bytes": "168408"
},
{
"name": "JavaScript",
"bytes": "12988"
},
{
"name": "Jupyter Notebook",
"bytes": "1483370"
},
{
"name": "Makefile",
"bytes": "3180"
},
{
"name": "Objective-C",
"bytes": "2576"
},
{
"name": "Protocol Buffer",
"bytes": "1199784"
},
{
"name": "Python",
"bytes": "5899210"
},
{
"name": "Ruby",
"bytes": "5784"
},
{
"name": "Shell",
"bytes": "45750"
},
{
"name": "TypeScript",
"bytes": "527234"
}
],
"symlink_target": ""
} |
import os
import json
import copasul
# load minimal example config
pth = os.path.dirname(os.path.abspath(__file__))
with open("{}/../minex/config/minex.json".format(pth), "r") as h:
opt = json.load(h)
# init Copasul() object
fex = copasul.Copasul()
# process data specified in config
copa = fex.process(config=opt)
# access output, e.g. local contour feature set
print("local contour features:")
print(copa["export"]["loc"])
| {
"content_hash": "6e5097be3b36daec806a3300bff62c93",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 65,
"avg_line_length": 24.055555555555557,
"alnum_prop": 0.7043879907621247,
"repo_name": "reichelu/copasul",
"id": "7f49f0399a56573c0b8f89872b3754a0eed4038e",
"size": "433",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/example_call.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "500875"
}
],
"symlink_target": ""
} |
"""identify somatic variants in cancer samples
https://qcmg.org/bioinformatics/tiki-index.php?page=qSNP#EXAMPLES
"""
from __future__ import print_function
import os
import shutil
from re import sub
from bcbio import utils
from bcbio.distributed.transaction import file_transaction, tx_tmpdir
from bcbio.pipeline import config_utils
from bcbio.pipeline.shared import subset_variant_regions
from bcbio.provenance import do
from bcbio.variation import annotation, bedutils
from bcbio.variation.vcfutils import get_paired_bams, bgzip_and_index, combine_variant_files, PairedData
import six
def is_installed(config):
"""Check for qsnp installation on machine.
"""
try:
config_utils.get_program("qsnp", config)
return True
except config_utils.CmdNotFound:
return False
def run_qsnp(align_bams, items, ref_file, assoc_files, region=None,
out_file=None):
"""Run qSNP calling on paired tumor/normal.
"""
if utils.file_exists(out_file):
return out_file
paired = get_paired_bams(align_bams, items)
if paired.normal_bam:
region_files = []
regions = _clean_regions(items, region)
if regions:
for region in regions:
out_region_file = out_file.replace(".vcf.gz", _to_str(region) + ".vcf.gz")
region_file = _run_qsnp_paired(align_bams, items, ref_file,
assoc_files, region, out_region_file)
region_files.append(region_file)
out_file = combine_variant_files(region_files, out_file, ref_file, items[0]["config"])
if not region:
out_file = _run_qsnp_paired(align_bams, items, ref_file,
assoc_files, region, out_file)
return out_file
else:
raise ValueError("qSNP only works on paired samples")
def _run_qsnp_paired(align_bams, items, ref_file, assoc_files,
region=None, out_file=None):
"""Detect somatic mutations with qSNP.
This is used for paired tumor / normal samples.
"""
config = items[0]["config"]
if out_file is None:
out_file = "%s-paired-variants.vcf" % os.path.splitext(align_bams[0])[0]
if not utils.file_exists(out_file):
out_file = out_file.replace(".gz", "")
with file_transaction(config, out_file) as tx_out_file:
with tx_tmpdir(config) as tmpdir:
with utils.chdir(tmpdir):
paired = get_paired_bams(align_bams, items)
qsnp = config_utils.get_program("qsnp", config)
resources = config_utils.get_resources("qsnp", config)
mem = " ".join(resources.get("jvm_opts", ["-Xms750m -Xmx4g"]))
qsnp_log = os.path.join(tmpdir, "qsnp.log")
qsnp_init = os.path.join(tmpdir, "qsnp.ini")
if region:
paired = _create_bam_region(paired, region, tmpdir)
_create_input(paired, tx_out_file, ref_file, assoc_files['dbsnp'], qsnp_init)
cl = ("{qsnp} {mem} -i {qsnp_init} -log {qsnp_log}")
do.run(cl.format(**locals()), "Genotyping paired variants with Qsnp", {})
out_file = _filter_vcf(out_file)
out_file = bgzip_and_index(out_file, config)
return out_file
def _clean_regions(items, region):
"""Intersect region with target file if it exists"""
variant_regions = bedutils.population_variant_regions(items, merged=True)
with utils.tmpfile() as tx_out_file:
target = subset_variant_regions(variant_regions, region, tx_out_file, items)
if target:
if isinstance(target, six.string_types) and os.path.isfile(target):
target = _load_regions(target)
else:
target = [target]
return target
def _load_regions(target):
"""Get list of tupples from bed file"""
regions = []
with open(target) as in_handle:
for line in in_handle:
if not line.startswith("#"):
c, s, e = line.strip().split("\t")
regions.append((c, s, e))
return regions
def _create_bam_region(paired, region, tmp_dir):
"""create temporal normal/tumor bam_file only with reads on that region"""
tumor_name, normal_name = paired.tumor_name, paired.normal_name
normal_bam = _slice_bam(paired.normal_bam, region, tmp_dir, paired.tumor_config)
tumor_bam = _slice_bam(paired.tumor_bam, region, tmp_dir, paired.tumor_config)
paired = PairedData(tumor_bam, tumor_name, normal_bam, normal_name, None, None, None)
return paired
def _slice_bam(in_bam, region, tmp_dir, config):
"""Use sambamba to slice a bam region"""
name_file = os.path.splitext(os.path.basename(in_bam))[0]
out_file = os.path.join(tmp_dir, os.path.join(tmp_dir, name_file + _to_str(region) + ".bam"))
sambamba = config_utils.get_program("sambamba", config)
region = _to_sambamba(region)
with file_transaction(out_file) as tx_out_file:
cmd = ("{sambamba} slice {in_bam} {region} -o {tx_out_file}")
do.run(cmd.format(**locals()), "Slice region", {})
return out_file
def _create_input(paired, out_file, ref_file, snp_file, qsnp_file):
"""Create INI input for qSNP"""
ini_file["[inputFiles]"]["dbSNP"] = snp_file
ini_file["[inputFiles]"]["ref"] = ref_file
ini_file["[inputFiles]"]["normalBam"] = paired.normal_bam
ini_file["[inputFiles]"]["tumourBam"] = paired.tumor_bam
ini_file["[ids]"]["normalSample"] = paired.normal_name
ini_file["[ids]"]["tumourSample"] = paired.tumor_name
ini_file["[ids]"]["donor"] = paired.tumor_name
ini_file["[outputFiles]"]["vcf"] = out_file
with open(qsnp_file, "w") as out_handle:
for k, v in ini_file.items():
out_handle.write("%s\n" % k)
for opt, value in v.items():
if value != "":
out_handle.write("%s = %s\n" % (opt, value))
def _has_ambiguous_ref_allele(line):
if not line.startswith("#"):
parts = line.split("\t")
return len(parts) > 4 and parts[3].upper() not in set(["C", "A", "T", "G"])
def _filter_vcf(out_file):
"""Fix sample names, FILTER and FORMAT fields. Remove lines with ambiguous reference.
"""
in_file = out_file.replace(".vcf", "-ori.vcf")
FILTER_line = ('##FILTER=<ID=SBIAS,Description="Due to bias">\n'
'##FILTER=<ID=5BP,Description="Due to 5BP">\n'
'##FILTER=<ID=REJECT,Description="Not somatic due to qSNP filters">\n')
SOMATIC_line = '##INFO=<ID=SOMATIC,Number=0,Type=Flag,Description="somatic event">\n'
if not utils.file_exists(in_file):
shutil.move(out_file, in_file)
with file_transaction(out_file) as tx_out_file:
with open(in_file) as in_handle, open(tx_out_file, "w") as out_handle:
for line in in_handle:
if line.startswith("##normalSample="):
normal_name = line.strip().split("=")[1]
if line.startswith("##patient_id="):
tumor_name = line.strip().split("=")[1]
if line.startswith("#CHROM"):
line = line.replace("Normal", normal_name)
line = line.replace("Tumour", tumor_name)
if line.startswith("##INFO=<ID=FS"):
line = line.replace("ID=FS", "ID=RNT")
if line.find("FS=") > -1:
line = line.replace("FS=", "RNT=")
if "5BP" in line:
line = sub("5BP[0-9]+", "5BP", line)
if line.find("PASS") == -1:
line = _set_reject(line)
if line.find("PASS") > - 1 and line.find("SOMATIC") == -1:
line = _set_reject(line)
if not _has_ambiguous_ref_allele(line):
out_handle.write(line)
if line.startswith("##FILTER") and FILTER_line:
out_handle.write("%s" % FILTER_line)
FILTER_line = ""
if line.startswith("##INFO") and SOMATIC_line:
out_handle.write("%s" % SOMATIC_line)
SOMATIC_line = ""
return out_file
def _to_str(region):
return "_" + "_".join(map(str, list(region)))
def _to_sambamba(region):
return "%s:%s-%s" % (region[0], region[1]+1, region[2]+1)
def _set_reject(line):
"""Set REJECT in VCF line, or add it if there is something else."""
if line.startswith("#"):
return line
parts = line.split("\t")
if parts[6] == "PASS":
parts[6] = "REJECT"
else:
parts[6] += ";REJECT"
return "\t".join(parts)
ini_file = {"[inputFiles]":{
"dbSNP":"",
"ref":"",
"normalBam":"",
"tumourBam":""},
"[parameters]":{
"annotateMode":"vcf",
"runMode":"standard",
"minimumBaseQuality":"10",
"includeIndels": "true"},
"[ids]":{
"donor":"",
"normalSample":"",
"tumourSample":"",
"somaticAnalysis":"",
"germlineAnalysis":""},
"[outputFiles]":{
"vcf":""},
"[rules]":{
"normal1":"0,20,3",
"normal2":"21,50,4",
"normal3":"51,,10",
"tumour1":"0,20,3",
"tumour2":"21,50,4",
"tumour3":"51,,5"}}
| {
"content_hash": "88222cec890dc62c79237378b2021ed3",
"timestamp": "",
"source": "github",
"line_count": 233,
"max_line_length": 104,
"avg_line_length": 40.69098712446352,
"alnum_prop": 0.5613331927011919,
"repo_name": "chapmanb/bcbio-nextgen",
"id": "84cb45cf56be1e7af816f1fbd5e55f6747ae0897",
"size": "9481",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "bcbio/variation/qsnp.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Lua",
"bytes": "3399"
},
{
"name": "Python",
"bytes": "2261466"
},
{
"name": "Ruby",
"bytes": "624"
},
{
"name": "Shell",
"bytes": "16734"
}
],
"symlink_target": ""
} |
"""
pyboard interface
This module provides the Pyboard class, used to communicate with and
control a MicroPython device over a communication channel. Both real
boards and emulated devices (e.g. running in QEMU) are supported.
Various communication channels are supported, including a serial
connection, telnet-style network connection, external process
connection.
Example usage:
import pyboard
pyb = pyboard.Pyboard('/dev/ttyACM0')
Or:
pyb = pyboard.Pyboard('192.168.1.1')
Then:
pyb.enter_raw_repl()
pyb.exec('import pyb')
pyb.exec('pyb.LED(1).on()')
pyb.exit_raw_repl()
Note: if using Python2 then pyb.exec must be written as pyb.exec_.
To run a script from the local machine on the board and print out the results:
import pyboard
pyboard.execfile('test.py', device='/dev/ttyACM0')
This script can also be run directly. To execute a local script, use:
./pyboard.py test.py
Or:
python pyboard.py test.py
"""
import sys
import time
import os
try:
stdout = sys.stdout.buffer
except AttributeError:
# Python2 doesn't have buffer attr
stdout = sys.stdout
def stdout_write_bytes(b):
b = b.replace(b"\x04", b"")
stdout.write(b)
stdout.flush()
class PyboardError(Exception):
pass
class TelnetToSerial:
def __init__(self, ip, user, password, read_timeout=None):
self.tn = None
import telnetlib
self.tn = telnetlib.Telnet(ip, timeout=15)
self.read_timeout = read_timeout
if b"Login as:" in self.tn.read_until(b"Login as:", timeout=read_timeout):
self.tn.write(bytes(user, "ascii") + b"\r\n")
if b"Password:" in self.tn.read_until(b"Password:", timeout=read_timeout):
# needed because of internal implementation details of the telnet server
time.sleep(0.2)
self.tn.write(bytes(password, "ascii") + b"\r\n")
if b"for more information." in self.tn.read_until(
b'Type "help()" for more information.', timeout=read_timeout
):
# login successful
from collections import deque
self.fifo = deque()
return
raise PyboardError("Failed to establish a telnet connection with the board")
def __del__(self):
self.close()
def close(self):
if self.tn:
self.tn.close()
def read(self, size=1):
while len(self.fifo) < size:
timeout_count = 0
data = self.tn.read_eager()
if len(data):
self.fifo.extend(data)
timeout_count = 0
else:
time.sleep(0.25)
if self.read_timeout is not None and timeout_count > 4 * self.read_timeout:
break
timeout_count += 1
data = b""
while len(data) < size and len(self.fifo) > 0:
data += bytes([self.fifo.popleft()])
return data
def write(self, data):
self.tn.write(data)
return len(data)
def inWaiting(self):
n_waiting = len(self.fifo)
if not n_waiting:
data = self.tn.read_eager()
self.fifo.extend(data)
return len(data)
else:
return n_waiting
class ProcessToSerial:
"Execute a process and emulate serial connection using its stdin/stdout."
def __init__(self, cmd):
import subprocess
self.subp = subprocess.Popen(
cmd,
bufsize=0,
shell=True,
preexec_fn=os.setsid,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
)
# Initially was implemented with selectors, but that adds Python3
# dependency. However, there can be race conditions communicating
# with a particular child process (like QEMU), and selectors may
# still work better in that case, so left inplace for now.
#
# import selectors
# self.sel = selectors.DefaultSelector()
# self.sel.register(self.subp.stdout, selectors.EVENT_READ)
import select
self.poll = select.poll()
self.poll.register(self.subp.stdout.fileno())
def close(self):
import signal
os.killpg(os.getpgid(self.subp.pid), signal.SIGTERM)
def read(self, size=1):
data = b""
while len(data) < size:
data += self.subp.stdout.read(size - len(data))
return data
def write(self, data):
self.subp.stdin.write(data)
return len(data)
def inWaiting(self):
# res = self.sel.select(0)
res = self.poll.poll(0)
if res:
return 1
return 0
class ProcessPtyToTerminal:
"""Execute a process which creates a PTY and prints slave PTY as
first line of its output, and emulate serial connection using
this PTY."""
def __init__(self, cmd):
import subprocess
import re
import serial
self.subp = subprocess.Popen(
cmd.split(),
bufsize=0,
shell=False,
preexec_fn=os.setsid,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
pty_line = self.subp.stderr.readline().decode("utf-8")
m = re.search(r"/dev/pts/[0-9]+", pty_line)
if not m:
print("Error: unable to find PTY device in startup line:", pty_line)
self.close()
sys.exit(1)
pty = m.group()
# rtscts, dsrdtr params are to workaround pyserial bug:
# http://stackoverflow.com/questions/34831131/pyserial-does-not-play-well-with-virtual-port
self.ser = serial.Serial(pty, interCharTimeout=1, rtscts=True, dsrdtr=True)
def close(self):
import signal
os.killpg(os.getpgid(self.subp.pid), signal.SIGTERM)
def read(self, size=1):
return self.ser.read(size)
def write(self, data):
return self.ser.write(data)
def inWaiting(self):
return self.ser.inWaiting()
class Pyboard:
def __init__(self, device, baudrate=115200, user="micro", password="python", wait=0):
if device.startswith("exec:"):
self.serial = ProcessToSerial(device[len("exec:") :])
elif device.startswith("execpty:"):
self.serial = ProcessPtyToTerminal(device[len("qemupty:") :])
elif device and device[0].isdigit() and device[-1].isdigit() and device.count(".") == 3:
# device looks like an IP address
self.serial = TelnetToSerial(device, user, password, read_timeout=10)
else:
import serial
delayed = False
for attempt in range(wait + 1):
try:
self.serial = serial.Serial(device, baudrate=baudrate, interCharTimeout=1)
break
except (OSError, IOError): # Py2 and Py3 have different errors
if wait == 0:
continue
if attempt == 0:
sys.stdout.write("Waiting {} seconds for pyboard ".format(wait))
delayed = True
time.sleep(1)
sys.stdout.write(".")
sys.stdout.flush()
else:
if delayed:
print("")
raise PyboardError("failed to access " + device)
if delayed:
print("")
def close(self):
self.serial.close()
def read_until(self, min_num_bytes, ending, timeout=10, data_consumer=None):
# if data_consumer is used then data is not accumulated and the ending must be 1 byte long
assert data_consumer is None or len(ending) == 1
data = self.serial.read(min_num_bytes)
if data_consumer:
data_consumer(data)
timeout_count = 0
while True:
if data.endswith(ending):
break
elif self.serial.inWaiting() > 0:
new_data = self.serial.read(1)
if data_consumer:
data_consumer(new_data)
data = new_data
else:
data = data + new_data
timeout_count = 0
else:
timeout_count += 1
if timeout is not None and timeout_count >= 100 * timeout:
break
time.sleep(0.01)
return data
def enter_raw_repl(self):
self.serial.write(b"\r\x03\x03") # ctrl-C twice: interrupt any running program
# flush input (without relying on serial.flushInput())
n = self.serial.inWaiting()
while n > 0:
self.serial.read(n)
n = self.serial.inWaiting()
self.serial.write(b"\r\x01") # ctrl-A: enter raw REPL
data = self.read_until(1, b"raw REPL; CTRL-B to exit\r\n>")
if not data.endswith(b"raw REPL; CTRL-B to exit\r\n>"):
print(data)
raise PyboardError("could not enter raw repl")
self.serial.write(b"\x04") # ctrl-D: soft reset
data = self.read_until(1, b"soft reboot\r\n")
if not data.endswith(b"soft reboot\r\n"):
print(data)
raise PyboardError("could not enter raw repl")
# By splitting this into 2 reads, it allows boot.py to print stuff,
# which will show up after the soft reboot and before the raw REPL.
data = self.read_until(1, b"raw REPL; CTRL-B to exit\r\n")
if not data.endswith(b"raw REPL; CTRL-B to exit\r\n"):
print(data)
raise PyboardError("could not enter raw repl")
def exit_raw_repl(self):
self.serial.write(b"\r\x02") # ctrl-B: enter friendly REPL
def follow(self, timeout, data_consumer=None):
# wait for normal output
data = self.read_until(1, b"\x04", timeout=timeout, data_consumer=data_consumer)
if not data.endswith(b"\x04"):
raise PyboardError("timeout waiting for first EOF reception")
data = data[:-1]
# wait for error output
data_err = self.read_until(1, b"\x04", timeout=timeout)
if not data_err.endswith(b"\x04"):
raise PyboardError("timeout waiting for second EOF reception")
data_err = data_err[:-1]
# return normal and error output
return data, data_err
def exec_raw_no_follow(self, command):
if isinstance(command, bytes):
command_bytes = command
else:
command_bytes = bytes(command, encoding="utf8")
# check we have a prompt
data = self.read_until(1, b">")
if not data.endswith(b">"):
raise PyboardError("could not enter raw repl")
# write command
for i in range(0, len(command_bytes), 256):
self.serial.write(command_bytes[i : min(i + 256, len(command_bytes))])
time.sleep(0.01)
self.serial.write(b"\x04")
# check if we could exec command
data = self.serial.read(2)
if data != b"OK":
raise PyboardError("could not exec command (response: %r)" % data)
def exec_raw(self, command, timeout=10, data_consumer=None):
self.exec_raw_no_follow(command)
return self.follow(timeout, data_consumer)
def eval(self, expression):
ret = self.exec_("print({})".format(expression))
ret = ret.strip()
return ret
def exec_(self, command, data_consumer=None):
ret, ret_err = self.exec_raw(command, data_consumer=data_consumer)
if ret_err:
raise PyboardError("exception", ret, ret_err)
return ret
def execfile(self, filename):
with open(filename, "rb") as f:
pyfile = f.read()
return self.exec_(pyfile)
def get_time(self):
t = str(self.eval("pyb.RTC().datetime()"), encoding="utf8")[1:-1].split(", ")
return int(t[4]) * 3600 + int(t[5]) * 60 + int(t[6])
def fs_ls(self, src):
cmd = (
"import uos\nfor f in uos.ilistdir(%s):\n"
" print('{:12} {}{}'.format(f[3]if len(f)>3 else 0,f[0],'/'if f[1]&0x4000 else ''))"
% (("'%s'" % src) if src else "")
)
self.exec_(cmd, data_consumer=stdout_write_bytes)
def fs_cat(self, src, chunk_size=256):
cmd = (
"with open('%s') as f:\n while 1:\n"
" b=f.read(%u)\n if not b:break\n print(b,end='')" % (src, chunk_size)
)
self.exec_(cmd, data_consumer=stdout_write_bytes)
def fs_get(self, src, dest, chunk_size=256):
self.exec_("f=open('%s','rb')\nr=f.read" % src)
with open(dest, "wb") as f:
while True:
data = bytearray()
self.exec_("print(r(%u))" % chunk_size, data_consumer=lambda d: data.extend(d))
assert data.endswith(b"\r\n\x04")
data = eval(str(data[:-3], "ascii"))
if not data:
break
f.write(data)
self.exec_("f.close()")
def fs_put(self, src, dest, chunk_size=256):
self.exec_("f=open('%s','wb')\nw=f.write" % dest)
with open(src, "rb") as f:
while True:
data = f.read(chunk_size)
if not data:
break
if sys.version_info < (3,):
self.exec_("w(b" + repr(data) + ")")
else:
self.exec_("w(" + repr(data) + ")")
self.exec_("f.close()")
def fs_mkdir(self, dir):
self.exec_("import uos\nuos.mkdir('%s')" % dir)
def fs_rmdir(self, dir):
self.exec_("import uos\nuos.rmdir('%s')" % dir)
def fs_rm(self, src):
self.exec_("import uos\nuos.remove('%s')" % src)
# in Python2 exec is a keyword so one must use "exec_"
# but for Python3 we want to provide the nicer version "exec"
setattr(Pyboard, "exec", Pyboard.exec_)
def execfile(filename, device="/dev/ttyACM0", baudrate=115200, user="micro", password="python"):
pyb = Pyboard(device, baudrate, user, password)
pyb.enter_raw_repl()
output = pyb.execfile(filename)
stdout_write_bytes(output)
pyb.exit_raw_repl()
pyb.close()
def filesystem_command(pyb, args):
def fname_remote(src):
if src.startswith(":"):
src = src[1:]
return src
def fname_cp_dest(src, dest):
src = src.rsplit("/", 1)[-1]
if dest is None or dest == "":
dest = src
elif dest == ".":
dest = "./" + src
elif dest.endswith("/"):
dest += src
return dest
cmd = args[0]
args = args[1:]
try:
if cmd == "cp":
srcs = args[:-1]
dest = args[-1]
if srcs[0].startswith("./") or dest.startswith(":"):
op = pyb.fs_put
fmt = "cp %s :%s"
dest = fname_remote(dest)
else:
op = pyb.fs_get
fmt = "cp :%s %s"
for src in srcs:
src = fname_remote(src)
dest2 = fname_cp_dest(src, dest)
print(fmt % (src, dest2))
op(src, dest2)
else:
op = {
"ls": pyb.fs_ls,
"cat": pyb.fs_cat,
"mkdir": pyb.fs_mkdir,
"rmdir": pyb.fs_rmdir,
"rm": pyb.fs_rm,
}[cmd]
if cmd == "ls" and not args:
args = [""]
for src in args:
src = fname_remote(src)
print("%s :%s" % (cmd, src))
op(src)
except PyboardError as er:
print(str(er.args[2], "ascii"))
pyb.exit_raw_repl()
pyb.close()
sys.exit(1)
_injected_import_hook_code = """\
import uos, uio
class _FS:
class File(uio.IOBase):
def __init__(self):
self.off = 0
def ioctl(self, request, arg):
return 0
def readinto(self, buf):
buf[:] = memoryview(_injected_buf)[self.off:self.off + len(buf)]
self.off += len(buf)
return len(buf)
mount = umount = chdir = lambda *args: None
def stat(self, path):
if path == '_injected.mpy':
return tuple(0 for _ in range(10))
else:
raise OSError(-2) # ENOENT
def open(self, path, mode):
return self.File()
uos.mount(_FS(), '/_')
uos.chdir('/_')
from _injected import *
uos.umount('/_')
del _injected_buf, _FS
"""
def main():
import argparse
cmd_parser = argparse.ArgumentParser(description="Run scripts on the pyboard.")
cmd_parser.add_argument(
"--device",
default="/dev/ttyACM0",
help="the serial device or the IP address of the pyboard",
)
cmd_parser.add_argument(
"-b", "--baudrate", default=115200, help="the baud rate of the serial device"
)
cmd_parser.add_argument("-u", "--user", default="micro", help="the telnet login username")
cmd_parser.add_argument("-p", "--password", default="python", help="the telnet login password")
cmd_parser.add_argument("-c", "--command", help="program passed in as string")
cmd_parser.add_argument(
"-w",
"--wait",
default=0,
type=int,
help="seconds to wait for USB connected board to become available",
)
group = cmd_parser.add_mutually_exclusive_group()
group.add_argument(
"--follow",
action="store_true",
help="follow the output after running the scripts [default if no scripts given]",
)
group.add_argument(
"--no-follow",
action="store_true",
help="Do not follow the output after running the scripts.",
)
cmd_parser.add_argument(
"-f", "--filesystem", action="store_true", help="perform a filesystem action"
)
cmd_parser.add_argument("files", nargs="*", help="input files")
args = cmd_parser.parse_args()
# open the connection to the pyboard
try:
pyb = Pyboard(args.device, args.baudrate, args.user, args.password, args.wait)
except PyboardError as er:
print(er)
sys.exit(1)
# run any command or file(s)
if args.command is not None or args.filesystem or len(args.files):
# we must enter raw-REPL mode to execute commands
# this will do a soft-reset of the board
try:
pyb.enter_raw_repl()
except PyboardError as er:
print(er)
pyb.close()
sys.exit(1)
def execbuffer(buf):
try:
if args.no_follow:
pyb.exec_raw_no_follow(buf)
ret_err = None
else:
ret, ret_err = pyb.exec_raw(
buf, timeout=None, data_consumer=stdout_write_bytes
)
except PyboardError as er:
print(er)
pyb.close()
sys.exit(1)
except KeyboardInterrupt:
sys.exit(1)
if ret_err:
pyb.exit_raw_repl()
pyb.close()
stdout_write_bytes(ret_err)
sys.exit(1)
# do filesystem commands, if given
if args.filesystem:
filesystem_command(pyb, args.files)
del args.files[:]
# run the command, if given
if args.command is not None:
execbuffer(args.command.encode("utf-8"))
# run any files
for filename in args.files:
with open(filename, "rb") as f:
pyfile = f.read()
if filename.endswith(".mpy") and pyfile[0] == ord("M"):
pyb.exec_("_injected_buf=" + repr(pyfile))
pyfile = _injected_import_hook_code
execbuffer(pyfile)
# exiting raw-REPL just drops to friendly-REPL mode
pyb.exit_raw_repl()
# if asked explicitly, or no files given, then follow the output
if args.follow or (args.command is None and not args.filesystem and len(args.files) == 0):
try:
ret, ret_err = pyb.follow(timeout=None, data_consumer=stdout_write_bytes)
except PyboardError as er:
print(er)
sys.exit(1)
except KeyboardInterrupt:
sys.exit(1)
if ret_err:
pyb.close()
stdout_write_bytes(ret_err)
sys.exit(1)
# close the connection to the pyboard
pyb.close()
if __name__ == "__main__":
main()
| {
"content_hash": "eca819765735affbece9157e836fe4b8",
"timestamp": "",
"source": "github",
"line_count": 646,
"max_line_length": 99,
"avg_line_length": 31.94736842105263,
"alnum_prop": 0.5444810543657331,
"repo_name": "pozetroninc/micropython",
"id": "de8b488368a7d6abd3d352bb109a1356715cffc5",
"size": "21901",
"binary": false,
"copies": "1",
"ref": "refs/heads/stable",
"path": "tools/pyboard.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "10582"
},
{
"name": "C",
"bytes": "14105315"
},
{
"name": "C++",
"bytes": "588898"
},
{
"name": "CMake",
"bytes": "876"
},
{
"name": "JavaScript",
"bytes": "5792"
},
{
"name": "Makefile",
"bytes": "147785"
},
{
"name": "Objective-C",
"bytes": "7411"
},
{
"name": "Python",
"bytes": "1247126"
},
{
"name": "Shell",
"bytes": "16221"
}
],
"symlink_target": ""
} |
__author__ = 'Adward'
"""djcode URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from IMS import views, change_student_personal_info, course_views
urlpatterns = [
url(r'^$', views.loggingin),
#url(r'^hello/', views.startup),
url(r'^add_user/', views.add_user),
url(r'^user_added/', views.user_added),
url(r'^user_auth/', views.user_auth),
url(r'^home/', views.home),
url(r'^logout/', views.loggingout),
url(r'^changeStudentInfo/', change_student_personal_info.changeStudentInfo), #by xyh
url(r'^changePasswd/', change_student_personal_info.changePasswd), #by xyh
url(r'^course/$', course_views.courseMain), #by saltless
url(r'^course/add/$', course_views.courseAdd), #by saltless
url(r'^course/delete/$', course_views.courseDelete), #by saltless
url(r'^course/modify/$', course_views.courseModify), #by saltless
] | {
"content_hash": "0e0915e2e5aae0db40b1a31aae9557a8",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 88,
"avg_line_length": 41.857142857142854,
"alnum_prop": 0.6832764505119454,
"repo_name": "yuanpengX/SE-NE",
"id": "14766f7676b9550b043994b7fc478988ea2d885a",
"size": "1465",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "djcode/IMS/urls.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "646374"
},
{
"name": "HTML",
"bytes": "136464"
},
{
"name": "JavaScript",
"bytes": "557054"
},
{
"name": "Python",
"bytes": "54698"
}
],
"symlink_target": ""
} |
from typing import List, Optional, Union, no_type_check
import importlib
from distutils.version import LooseVersion
import pkg_resources
from autosklearn.util import RE_PATTERN
def verify_packages(packages: Optional[Union[str, List[str]]]) -> None:
if not packages:
return
if isinstance(packages, str):
packages = packages.splitlines()
for package in packages:
if not package:
continue
# Ignore comments
if package.startswith("#"):
continue
match = RE_PATTERN.match(package)
if match:
name = match.group("name")
operation = match.group("operation1")
version = match.group("version1")
_verify_package(name, operation, version)
else:
raise ValueError("Unable to read requirement: %s" % package)
# Module has no attribute __version__ wa
@no_type_check
def _verify_package(name: str, operation: Optional[str], version: str) -> None:
try:
module_dist = pkg_resources.get_distribution(name)
installed_version = LooseVersion(module_dist.version)
except pkg_resources.DistributionNotFound:
try:
module = importlib.import_module(name) # type: ignore
installed_version = LooseVersion(module.__version__)
except ImportError:
raise MissingPackageError(name)
if not operation:
return
required_version = LooseVersion(version)
if operation == "==":
check = required_version == installed_version
elif operation == ">":
check = installed_version > required_version
elif operation == "<":
check = installed_version < required_version
elif operation == ">=":
check = (
installed_version > required_version
or installed_version == required_version
)
else:
raise NotImplementedError("operation '%s' is not supported" % operation)
if not check:
raise IncorrectPackageVersionError(
name, installed_version, operation, required_version
)
class MissingPackageError(Exception):
error_message = "Mandatory package '{name}' not found!"
def __init__(self, package_name: str):
self.package_name = package_name
super(MissingPackageError, self).__init__(
self.error_message.format(name=package_name)
)
class IncorrectPackageVersionError(Exception):
error_message = (
"found '{name}' version {installed_version} but requires {name} version "
"{operation}{required_version}"
)
def __init__(
self,
package_name: str,
installed_version: Union[str, LooseVersion],
operation: Optional[str],
required_version: Union[str, LooseVersion],
):
self.package_name = package_name
self.installed_version = installed_version
self.operation = operation
self.required_version = required_version
message = self.error_message.format(
name=package_name,
installed_version=installed_version,
operation=operation,
required_version=required_version,
)
super(IncorrectPackageVersionError, self).__init__(message)
| {
"content_hash": "aaf2cccac5008671e749dff059a3cd07",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 81,
"avg_line_length": 31.152380952380952,
"alnum_prop": 0.627331091409355,
"repo_name": "automl/auto-sklearn",
"id": "390ac351bb7fef8a6c78710337293922883aa317",
"size": "3271",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "autosklearn/util/dependencies.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Dockerfile",
"bytes": "950"
},
{
"name": "Makefile",
"bytes": "3513"
},
{
"name": "Python",
"bytes": "2008151"
},
{
"name": "Shell",
"bytes": "4744"
}
],
"symlink_target": ""
} |
"""Tests for ParameterServerStrategy."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import threading
from absl.testing import parameterized
from tensorflow.contrib.distribute.python import combinations
from tensorflow.contrib.distribute.python import multi_worker_test_base
from tensorflow.contrib.distribute.python import parameter_server_strategy
from tensorflow.contrib.distribute.python import values
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.distribute import multi_worker_util
from tensorflow.python.eager import context
from tensorflow.python.estimator import run_config
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
from tensorflow.python.layers import core
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import gradients
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
from tensorflow.python.training import device_util
from tensorflow.python.training import distribution_strategy_context
from tensorflow.python.training import training_util
CHIEF = run_config.TaskType.CHIEF
WORKER = run_config.TaskType.WORKER
PS = run_config.TaskType.PS
class ParameterServerStrategyTestBase(
multi_worker_test_base.MultiWorkerTestBase):
def setUp(self):
self._result = 0
self._lock = threading.Lock()
self._init_condition = threading.Condition()
self._init_reached = 0
self._finish_condition = threading.Condition()
self._finish_reached = 0
self._sess_config = config_pb2.ConfigProto(allow_soft_placement=True)
super(ParameterServerStrategyTestBase, self).setUp()
def _get_test_objects(self, task_type, task_id, num_gpus):
distribution = parameter_server_strategy.ParameterServerStrategy(
num_gpus_per_worker=num_gpus)
if not task_type:
return distribution, '', self._sess_config
sess_config = copy.deepcopy(self._sess_config)
distribution.configure(
session_config=sess_config,
cluster_spec=self._cluster_spec,
task_type=task_type,
task_id=task_id)
return (distribution, 'grpc://' + self._cluster_spec[WORKER][task_id],
sess_config)
def _test_device_assignment_distributed(self, task_type, task_id, num_gpus):
worker_device = '/job:%s/replica:0/task:%d' % (task_type, task_id)
d, _, sess_config = self._get_test_objects(task_type, task_id, num_gpus)
with ops.Graph().as_default(), \
self.test_session(target=self._default_target,
config=sess_config) as sess, \
d.scope():
# Define a variable outside the call_for_each_tower scope. This is not
# recommended.
n = variable_scope.get_variable('n', initializer=10.0)
self.assertEqual(n.device, '/job:ps/task:0')
def model_fn():
if num_gpus == 0:
last_part_device = 'device:CPU:0'
else:
last_part_device = (
'device:GPU:%d' %
distribution_strategy_context.get_tower_context().tower_id)
a = constant_op.constant(1.0)
b = constant_op.constant(2.0)
c = a + b
self.assertEqual(a.device, worker_device + '/' + last_part_device)
self.assertEqual(b.device, worker_device + '/' + last_part_device)
self.assertEqual(c.device, worker_device + '/' + last_part_device)
# The device scope is ignored for variables but not for normal ops.
with ops.device('/job:worker/task:0'):
x = variable_scope.get_variable(
'x', initializer=10.0,
aggregation=variable_scope.VariableAggregation.SUM)
x_add = x.assign_add(c)
e = a + c
# The variable x is on the task 1 since the device_function has been
# called once before the model_fn.
self.assertEqual(x.device, '/job:ps/task:1')
self.assertEqual(x_add.device, x.device)
self.assertEqual(e.device,
'/job:worker/replica:0/task:0/%s' % last_part_device)
# The colocate_vars_with can override the distribution's device.
with d.colocate_vars_with(x):
y = variable_scope.get_variable(
'y', initializer=20.0,
aggregation=variable_scope.VariableAggregation.SUM)
# We add an identity here to avoid complaints about summing
# non-distributed values.
y_add = y.assign_add(array_ops.identity(x_add))
self.assertEqual(y.device, '/job:ps/task:1')
self.assertEqual(y_add.device, y.device)
self.assertEqual(y.device, x.device)
z = variable_scope.get_variable(
'z', initializer=10.0,
aggregation=variable_scope.VariableAggregation.SUM)
self.assertEqual(z.device, '/job:ps/task:0')
self.assertNotEqual(z.device, x.device)
with ops.control_dependencies([y_add]):
# We add an identity here to avoid complaints about summing
# non-distributed values.
z_add = z.assign_add(array_ops.identity(y))
with ops.control_dependencies([z_add]):
f = z + c
self.assertEqual(f.device, worker_device + '/' + last_part_device)
# The device scope would merge with the default worker device.
with ops.device('/CPU:1'):
g = e + 1.0
self.assertEqual(g.device, worker_device + '/device:CPU:1')
# Ths ops.colocate_with will be ignored when defining a variale but not
# for a normal tensor.
with ops.colocate_with(x):
u = variable_scope.get_variable('u', initializer=30.0)
v = variable_scope.get_variable('v', initializer=30.0)
h = f + 1.0
self.assertIn('/job:ps/', u.device)
self.assertIn('/job:ps/', v.device)
# u and v are on different parameter servers.
self.assertTrue(u.device != x.device or v.device != x.device)
self.assertTrue(u.device == x.device or v.device == x.device)
# Here h is not on one worker. Note h.device is canonical while x.device
# is not but.
self.assertIn('/job:ps/', h.device)
return y_add, z_add, f
y, z, f = d.call_for_each_tower(model_fn)
self.assertNotEqual(y, None)
self.assertNotEqual(z, None)
self.assertNotEqual(f, None)
if context.num_gpus() >= 1 and num_gpus <= 1:
variables.global_variables_initializer().run()
y_val, z_val, f_val = sess.run([y, z, f])
self.assertEqual(y_val, 33.0)
self.assertEqual(z_val, 43.0)
self.assertEqual(f_val, 46.0)
def _test_device_assignment_local(self,
d,
compute_device='CPU',
variable_device='CPU',
num_gpus=0):
with ops.Graph().as_default(), \
self.test_session(target=self._default_target,
config=self._sess_config) as sess, \
d.scope():
def model_fn():
if 'CPU' in compute_device:
tower_compute_device = '/device:CPU:0'
else:
tower_compute_device = (
'/device:GPU:%d' %
distribution_strategy_context.get_tower_context().tower_id)
tower_compute_device = device_util.canonicalize(tower_compute_device)
if 'CPU' in variable_device:
tower_variable_device = '/device:CPU:0'
else:
tower_variable_device = (
'/device:GPU:%d' %
distribution_strategy_context.get_tower_context().tower_id)
tower_variable_device = device_util.canonicalize(tower_variable_device)
a = constant_op.constant(1.0)
b = constant_op.constant(2.0)
c = a + b
self.assertEqual(a.device, tower_compute_device)
self.assertEqual(b.device, tower_compute_device)
self.assertEqual(c.device, tower_compute_device)
# The device scope is ignored for variables but not for normal ops.
with ops.device('/device:GPU:2'):
x = variable_scope.get_variable(
'x', initializer=10.0,
aggregation=variable_scope.VariableAggregation.SUM)
x_add = x.assign_add(c)
e = a + c
self.assertEqual(
device_util.canonicalize(x.device), tower_variable_device)
self.assertEqual(x_add.device, x.device)
self.assertEqual(e.device, device_util.canonicalize('/device:GPU:2'))
# The colocate_vars_with can override the distribution's device.
with d.colocate_vars_with(x):
y = variable_scope.get_variable(
'y', initializer=20.0,
aggregation=variable_scope.VariableAggregation.SUM)
# We add an identity here to avoid complaints about summing
# non-distributed values.
y_add = y.assign_add(array_ops.identity(x_add))
self.assertEqual(
device_util.canonicalize(y.device), tower_variable_device)
self.assertEqual(y_add.device, y.device)
self.assertEqual(y.device, x.device)
z = variable_scope.get_variable(
'z', initializer=10.0,
aggregation=variable_scope.VariableAggregation.SUM)
self.assertEqual(
device_util.canonicalize(z.device), tower_variable_device)
with ops.control_dependencies([y_add]):
# We add an identity here to avoid complaints about summing
# non-distributed values.
z_add = z.assign_add(array_ops.identity(y))
with ops.control_dependencies([z_add]):
f = z + c
self.assertEqual(f.device, tower_compute_device)
# The device scope would merge with the default worker device.
with ops.device('/CPU:1'):
g = e + 1.0
self.assertEqual(g.device, device_util.canonicalize('/device:CPU:1'))
# Ths ops.colocate_with will be ignored when defining a variale but not
# for a normal tensor.
with ops.colocate_with(x):
u = variable_scope.get_variable('u', initializer=30.0)
h = f + 1.0
self.assertEqual(
device_util.canonicalize(u.device), tower_variable_device)
self.assertEqual(device_util.canonicalize(x.device), h.device)
return y_add, z_add, f
y, z, f = d.call_for_each_tower(model_fn)
self.assertNotEqual(y, None)
self.assertNotEqual(z, None)
self.assertNotEqual(f, None)
if context.num_gpus() >= 1 and num_gpus <= 1:
variables.global_variables_initializer().run()
y_val, z_val, f_val = sess.run([y, z, f])
self.assertEqual(y_val, 33.0)
self.assertEqual(z_val, 43.0)
self.assertEqual(f_val, 46.0)
def _test_simple_increment(self, task_type, task_id, num_gpus):
d, master_target, sess_config = self._get_test_objects(
task_type, task_id, num_gpus)
if hasattr(d, '_cluster_spec') and d._cluster_spec:
num_workers = len(d._cluster_spec.as_dict().get(WORKER))
if 'chief' in d._cluster_spec.as_dict():
num_workers += 1
else:
num_workers = 1
with ops.Graph().as_default(), \
self.test_session(target=master_target,
config=sess_config) as sess, \
d.scope():
def model_fn():
x = variable_scope.get_variable(
'x', initializer=10.0,
aggregation=variable_scope.VariableAggregation.SUM)
y = variable_scope.get_variable(
'y', initializer=20.0,
aggregation=variable_scope.VariableAggregation.SUM)
z = variable_scope.get_variable(
'z', initializer=30.0,
aggregation=variable_scope.VariableAggregation.ONLY_FIRST_TOWER)
# We explicitly make a constant tensor here to avoid complaints about
# summing non-distributed values.
one = constant_op.constant(1.0)
x_add = x.assign_add(one, use_locking=True)
y_add = y.assign_add(one, use_locking=True)
z_add = z.assign_add(one, use_locking=True)
train_op = control_flow_ops.group(x_add, y_add, z_add)
return x, y, z, train_op
x, y, z, train_op = d.call_for_each_tower(model_fn)
train_op = d.group(train_op)
if context.num_gpus() < d._num_gpus_per_worker:
return True
if task_id == 0:
variables.global_variables_initializer().run()
# Workers waiting for chief worker's initializing variables.
self._init_condition.acquire()
self._init_reached += 1
while self._init_reached != num_workers:
self._init_condition.wait()
self._init_condition.notify_all()
self._init_condition.release()
sess.run(train_op)
# Wait for other workers to finish training.
self._finish_condition.acquire()
self._finish_reached += 1
while self._finish_reached != num_workers:
self._finish_condition.wait()
self._finish_condition.notify_all()
self._finish_condition.release()
x_val, y_val, z_val = sess.run([x, y, z])
self.assertEqual(x_val, 10.0 + 1.0 * num_workers * d.num_towers)
self.assertEqual(y_val, 20.0 + 1.0 * num_workers * d.num_towers)
self.assertEqual(z_val, 30.0 + 1.0 * num_workers)
return (x_val == 10.0 + 1.0 * num_workers * d.num_towers and
y_val == 20.0 + 1.0 * num_workers * d.num_towers and
z_val == 30.0 + 1.0 * num_workers)
def _test_minimize_loss_graph(self, task_type, task_id, num_gpus):
d, master_target, sess_config = self._get_test_objects(
task_type, task_id, num_gpus)
assert hasattr(d, '_cluster_spec') and d._cluster_spec
num_workers = len(d._cluster_spec.as_dict().get(WORKER))
if CHIEF in d._cluster_spec.as_dict():
num_workers += 1
with ops.Graph().as_default(), \
self.test_session(target=master_target,
config=sess_config) as sess, \
d.scope():
l = core.Dense(1, use_bias=False)
def loss_fn(x):
y = array_ops.reshape(l(x), []) - constant_op.constant(1.)
return y * y
# TODO(yuefengz, apassos): eager.backprop.implicit_grad is not safe for
# multiple graphs (b/111216820).
def grad_fn(x):
loss = loss_fn(x)
var_list = (
variables.trainable_variables() + ops.get_collection(
ops.GraphKeys.TRAINABLE_RESOURCE_VARIABLES))
grads = gradients.gradients(loss, var_list)
ret = list(zip(grads, var_list))
return ret
def update(v, g):
return v.assign_sub(0.05 * g, use_locking=True)
one = d.broadcast(constant_op.constant([[1.]]))
def step():
"""Perform one optimization step."""
# Run forward & backward to get gradients, variables list.
g_v = d.call_for_each_tower(grad_fn, one)
# Update the variables using the gradients and the update() function.
before_list = []
after_list = []
for g, v in g_v:
fetched = d.read_var(v)
before_list.append(fetched)
with ops.control_dependencies([fetched]):
# TODO(yuefengz): support non-Mirrored variable as destinations.
g = d.reduce(
variable_scope.VariableAggregation.SUM, g, destinations=v)
with ops.control_dependencies(
d.update(v, update, g, grouped=False)):
after_list.append(d.read_var(v))
return before_list, after_list
before_out, after_out = step()
if context.num_gpus() < d._num_gpus_per_worker:
return True
if multi_worker_util.is_chief(d._cluster_spec, task_type, task_id):
variables.global_variables_initializer().run()
# Workers waiting for chief worker's initializing variables.
self._init_condition.acquire()
self._init_reached += 1
while self._init_reached != num_workers:
self._init_condition.wait()
self._init_condition.notify_all()
self._init_condition.release()
for i in range(10):
b, a = sess.run((before_out, after_out))
if i == 0:
before, = b
after, = a
error_before = abs(before - 1)
error_after = abs(after - 1)
# Error should go down
self.assertLess(error_after, error_before)
return error_after < error_before
class ParameterServerStrategyTest(ParameterServerStrategyTestBase,
parameterized.TestCase):
@classmethod
def setUpClass(cls):
cls._cluster_spec = multi_worker_test_base.create_in_process_cluster(
num_workers=3, num_ps=2)
cls._default_target = 'grpc://' + cls._cluster_spec[WORKER][0]
def testDeviceAssignmentLocalCPU(self):
distribution = parameter_server_strategy.ParameterServerStrategy(
num_gpus_per_worker=0)
self._test_device_assignment_local(
distribution, compute_device='CPU', variable_device='CPU', num_gpus=0)
def testDeviceAssignmentLocalOneGPU(self):
distribution = parameter_server_strategy.ParameterServerStrategy(
num_gpus_per_worker=1)
self._test_device_assignment_local(
distribution, compute_device='GPU', variable_device='GPU', num_gpus=1)
def testDeviceAssignmentLocalTwoGPUs(self):
distribution = parameter_server_strategy.ParameterServerStrategy(
num_gpus_per_worker=2)
self._test_device_assignment_local(
distribution, compute_device='GPU', variable_device='CPU', num_gpus=2)
@combinations.generate(
combinations.combine(mode=['graph'], num_gpus=[0, 1, 2]))
def testDeviceAssignmentDistributed(self, num_gpus):
self._test_device_assignment_distributed('worker', 1, num_gpus)
def testSimpleBetweenGraph(self):
self._run_between_graph_clients(self._test_simple_increment,
self._cluster_spec, context.num_gpus())
@combinations.generate(
combinations.combine(mode=['graph'], num_gpus=[0, 1, 2]))
def testLocalSimpleIncrement(self, num_gpus):
self._test_simple_increment(None, 0, num_gpus)
@combinations.generate(
combinations.combine(mode=['graph'], num_gpus=[0, 1, 2]))
def testMinimizeLossGraph(self, num_gpus):
self._run_between_graph_clients(self._test_minimize_loss_graph,
self._cluster_spec, num_gpus)
class ParameterServerStrategyWithChiefTest(ParameterServerStrategyTestBase,
parameterized.TestCase):
@classmethod
def setUpClass(cls):
cls._cluster_spec = multi_worker_test_base.create_in_process_cluster(
num_workers=3, num_ps=2, has_chief=True)
cls._default_target = 'grpc://' + cls._cluster_spec[CHIEF][0]
def testSimpleBetweenGraph(self):
self._run_between_graph_clients(self._test_simple_increment,
self._cluster_spec, context.num_gpus())
@combinations.generate(
combinations.combine(mode=['graph'], num_gpus=[0, 1, 2]))
def testMinimizeLossGraph(self, num_gpus):
self._run_between_graph_clients(self._test_minimize_loss_graph,
self._cluster_spec, num_gpus)
def testGlobalStepIsWrapped(self):
distribution = parameter_server_strategy.ParameterServerStrategy(
num_gpus_per_worker=2)
with ops.Graph().as_default(), distribution.scope():
created_step = training_util.create_global_step()
get_step = training_util.get_global_step()
self.assertEqual(created_step, get_step,
msg=('created_step %s type %s vs. get_step %s type %s' %
(id(created_step), created_step.__class__.__name__,
id(get_step), get_step.__class__.__name__)))
self.assertIs(values.AggregatingVariable, type(created_step))
self.assertIs(values.AggregatingVariable, type(get_step))
if __name__ == '__main__':
test.main()
| {
"content_hash": "0bd3ae87e55d664235e2fc27647cc3a0",
"timestamp": "",
"source": "github",
"line_count": 500,
"max_line_length": 80,
"avg_line_length": 40.188,
"alnum_prop": 0.6244650144321688,
"repo_name": "dancingdan/tensorflow",
"id": "353d11a5831904abd43828f1d9d4abfc61aede60",
"size": "20783",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tensorflow/contrib/distribute/python/parameter_server_strategy_test.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "3325"
},
{
"name": "Batchfile",
"bytes": "10132"
},
{
"name": "C",
"bytes": "339398"
},
{
"name": "C#",
"bytes": "8446"
},
{
"name": "C++",
"bytes": "49741628"
},
{
"name": "CMake",
"bytes": "195409"
},
{
"name": "Dockerfile",
"bytes": "36386"
},
{
"name": "Go",
"bytes": "1254047"
},
{
"name": "HTML",
"bytes": "4681865"
},
{
"name": "Java",
"bytes": "867093"
},
{
"name": "Jupyter Notebook",
"bytes": "2604735"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "Makefile",
"bytes": "58612"
},
{
"name": "Objective-C",
"bytes": "15650"
},
{
"name": "Objective-C++",
"bytes": "99243"
},
{
"name": "PHP",
"bytes": "1357"
},
{
"name": "Perl",
"bytes": "7536"
},
{
"name": "PureBasic",
"bytes": "25356"
},
{
"name": "Python",
"bytes": "41593453"
},
{
"name": "Ruby",
"bytes": "553"
},
{
"name": "Shell",
"bytes": "476832"
},
{
"name": "Smarty",
"bytes": "6976"
}
],
"symlink_target": ""
} |
from GCBcommon import *
from UnitCommands import *
import math
# patrol relative to airbase or carrier location
def CAP(TI):
UI = TI.GetPlatformInterface()
BB = TI.GetBlackboardInterface()
iteration = TI.GetMemoryValue(1) # will return 0 first time
if (iteration == 0): # do initialization
TI.SetMemoryValue(2, UI.GetHeading())
TI.SetMemoryValue(3, 0) # 1 is heading to station, 0 patroling
TI.SetMemoryValue(4, 30.0 + 15.0 * UI.Rand()) # random turn interval in seconds
TI.SetMemoryText('Description', 'Perform surveillance along a zig-zag course')
patrol_range_km = GetMessageParam(BB, 'PatrolRange_km')
patrol_az_rad = deg_to_rad * GetMessageParam(BB, 'PatrolAzimuth_deg') # rel to north
anchor_id = GetMessageParam(BB, 'AnchorPlatformId') # platform id to center patrol about
TI.SetMemoryValue(10, patrol_range_km)
TI.SetMemoryValue(11, patrol_az_rad)
TI.SetMemoryValue(12, anchor_id)
iteration = iteration + 1
TI.SetMemoryValue(1, iteration)
# if low on fuel or out of ammo, rtb
if ((UI.GetFuel() < 0.55) or (not UI.IsEquippedForTargetType(0x0020))):
UI.DeleteTask('EngageAll')
TI.EndTask()
AddRTBtask(UI, '', 0.55, 0)
return
# activate all sensors
can_radiate = GetSensorControl(BB)
if (can_radiate and not UI.IsSub()):
ActivateAllSensors(UI)
else:
ActivatePassiveSensors(UI)
# return if conn is not available
if (not GetConnControl(BB)):
return
# check for nearby air target
intercept_target = 0
closest_id, closest_range, closest_bearing = ClosestOfTypeUnengaged(UI, 0x0020, 120)
if (closest_id != -1):
intercept_target = 1
UI.SetHeading(closest_bearing) # lag intercept
if (UI.GetFuel() > 0.7):
UI.SetThrottle(1.1)
else:
UI.SetThrottle(1.0)
UI.SetActionText('Intercept %d' % closest_id)
return
patrol_range_km = GetMessageParam(BB, 'PatrolRange_km')
patrol_az_rad = deg_to_rad * GetMessageParam(BB, 'PatrolAzimuth_deg') # rel to north
anchor_id = TI.GetMemoryValue(12)
if (UI.IsAir()):
if (UI.GetAlt() < 5500):
UI.SetThrottle(1.0)
SetAlt(UI, 6000)
else:
UI.SetThrottle(0.8)
# calculate station point
anchor_track = UI.GetTrackById(long(anchor_id))
anchor_track.Offset(patrol_range_km, patrol_az_rad)
if (not anchor_track.IsValid()):
TI.EndTask()
return
station_lon = anchor_track.Lon
station_lat = anchor_track.Lat
station_range = UI.GetRangeToDatum(station_lon, station_lat)
isTravelingToStation = TI.GetMemoryValue(3)
if (isTravelingToStation):
range_thresh = 1.0
UI.SetSpeedToMax()
else:
range_thresh = 10.0
if (UI.IsAir()):
range_thresh = range_thresh * 4.0
if (station_range > range_thresh):
new_heading = UI.GetHeadingToDatum(station_lon, station_lat)
TI.SetMemoryValue(3, 1) # to indicate traveling to station
UI.SetActionText('-> Station')
TI.SetUpdateInterval(10.0)
else:
new_heading = UI.GetHeading() + 30
TI.SetMemoryValue(3, 0) # to indicate traveling to station
UI.SetActionText('CAP')
TI.SetUpdateInterval(TI.GetMemoryValue(4))
UI.SetHeading(new_heading)
| {
"content_hash": "2533e882a90efbfca2b8677899e5b3a5",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 96,
"avg_line_length": 31.18018018018018,
"alnum_prop": 0.6266974862756429,
"repo_name": "gcblue/gcblue",
"id": "e45dcb97a2c91a6f2d17a04c73fcce5c27a7c7ef",
"size": "3462",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/AirMissions.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "173"
},
{
"name": "C",
"bytes": "18820"
},
{
"name": "C++",
"bytes": "6366459"
},
{
"name": "GLSL",
"bytes": "13139"
},
{
"name": "Groff",
"bytes": "21"
},
{
"name": "HTML",
"bytes": "111577"
},
{
"name": "NSIS",
"bytes": "13115"
},
{
"name": "Python",
"bytes": "10484037"
},
{
"name": "R",
"bytes": "2528"
},
{
"name": "Visual Basic",
"bytes": "481"
}
],
"symlink_target": ""
} |
"""The tests for the MQTT light platform.
Configuration for RGB Version with brightness:
light:
platform: mqtt
name: "Office Light RGB"
state_topic: "office/rgb1/light/status"
command_topic: "office/rgb1/light/switch"
brightness_state_topic: "office/rgb1/brightness/status"
brightness_command_topic: "office/rgb1/brightness/set"
rgb_state_topic: "office/rgb1/rgb/status"
rgb_command_topic: "office/rgb1/rgb/set"
qos: 0
payload_on: "on"
payload_off: "off"
Configuration for XY Version with brightness:
light:
platform: mqtt
name: "Office Light XY"
state_topic: "office/xy1/light/status"
command_topic: "office/xy1/light/switch"
brightness_state_topic: "office/xy1/brightness/status"
brightness_command_topic: "office/xy1/brightness/set"
xy_state_topic: "office/xy1/xy/status"
xy_command_topic: "office/xy1/xy/set"
qos: 0
payload_on: "on"
payload_off: "off"
config without RGB:
light:
platform: mqtt
name: "Office Light"
state_topic: "office/rgb1/light/status"
command_topic: "office/rgb1/light/switch"
brightness_state_topic: "office/rgb1/brightness/status"
brightness_command_topic: "office/rgb1/brightness/set"
qos: 0
payload_on: "on"
payload_off: "off"
config without RGB and brightness:
light:
platform: mqtt
name: "Office Light"
state_topic: "office/rgb1/light/status"
command_topic: "office/rgb1/light/switch"
qos: 0
payload_on: "on"
payload_off: "off"
config for RGB Version with brightness and scale:
light:
platform: mqtt
name: "Office Light RGB"
state_topic: "office/rgb1/light/status"
command_topic: "office/rgb1/light/switch"
brightness_state_topic: "office/rgb1/brightness/status"
brightness_command_topic: "office/rgb1/brightness/set"
brightness_scale: 99
rgb_state_topic: "office/rgb1/rgb/status"
rgb_command_topic: "office/rgb1/rgb/set"
rgb_scale: 99
qos: 0
payload_on: "on"
payload_off: "off"
config with brightness and color temp
light:
platform: mqtt
name: "Office Light Color Temp"
state_topic: "office/rgb1/light/status"
command_topic: "office/rgb1/light/switch"
brightness_state_topic: "office/rgb1/brightness/status"
brightness_command_topic: "office/rgb1/brightness/set"
brightness_scale: 99
color_temp_state_topic: "office/rgb1/color_temp/status"
color_temp_command_topic: "office/rgb1/color_temp/set"
qos: 0
payload_on: "on"
payload_off: "off"
config with brightness and effect
light:
platform: mqtt
name: "Office Light Color Temp"
state_topic: "office/rgb1/light/status"
command_topic: "office/rgb1/light/switch"
brightness_state_topic: "office/rgb1/brightness/status"
brightness_command_topic: "office/rgb1/brightness/set"
brightness_scale: 99
effect_state_topic: "office/rgb1/effect/status"
effect_command_topic: "office/rgb1/effect/set"
effect_list:
- rainbow
- colorloop
qos: 0
payload_on: "on"
payload_off: "off"
config for RGB Version with white value and scale:
light:
platform: mqtt
name: "Office Light RGB"
state_topic: "office/rgb1/light/status"
command_topic: "office/rgb1/light/switch"
white_value_state_topic: "office/rgb1/white_value/status"
white_value_command_topic: "office/rgb1/white_value/set"
white_value_scale: 99
rgb_state_topic: "office/rgb1/rgb/status"
rgb_command_topic: "office/rgb1/rgb/set"
rgb_scale: 99
qos: 0
payload_on: "on"
payload_off: "off"
config for RGB Version with RGB command template:
light:
platform: mqtt
name: "Office Light RGB"
state_topic: "office/rgb1/light/status"
command_topic: "office/rgb1/light/switch"
rgb_state_topic: "office/rgb1/rgb/status"
rgb_command_topic: "office/rgb1/rgb/set"
rgb_command_template: "{{ '#%02x%02x%02x' | format(red, green, blue)}}"
qos: 0
payload_on: "on"
payload_off: "off"
"""
import unittest
from unittest import mock
from unittest.mock import patch
from homeassistant.setup import setup_component
from homeassistant.const import (
STATE_ON, STATE_OFF, STATE_UNAVAILABLE, ATTR_ASSUMED_STATE)
import homeassistant.components.light as light
import homeassistant.core as ha
from tests.common import (
assert_setup_component, get_test_home_assistant, mock_mqtt_component,
fire_mqtt_message, mock_coro)
class TestLightMQTT(unittest.TestCase):
"""Test the MQTT light."""
# pylint: disable=invalid-name
def setUp(self):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.mock_publish = mock_mqtt_component(self.hass)
def tearDown(self): # pylint: disable=invalid-name
"""Stop everything that was started."""
self.hass.stop()
def test_fail_setup_if_no_command_topic(self):
"""Test if command fails with command topic."""
with assert_setup_component(0, light.DOMAIN):
assert setup_component(self.hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
}
})
self.assertIsNone(self.hass.states.get('light.test'))
def test_no_color_brightness_color_temp_white_xy_if_no_topics(self):
"""Test if there is no color and brightness if no topic."""
with assert_setup_component(1, light.DOMAIN):
assert setup_component(self.hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'test_light_rgb/status',
'command_topic': 'test_light_rgb/set',
}
})
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
self.assertIsNone(state.attributes.get('rgb_color'))
self.assertIsNone(state.attributes.get('brightness'))
self.assertIsNone(state.attributes.get('color_temp'))
self.assertIsNone(state.attributes.get('white_value'))
self.assertIsNone(state.attributes.get('xy_color'))
fire_mqtt_message(self.hass, 'test_light_rgb/status', 'ON')
self.hass.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state)
self.assertIsNone(state.attributes.get('rgb_color'))
self.assertIsNone(state.attributes.get('brightness'))
self.assertIsNone(state.attributes.get('color_temp'))
self.assertIsNone(state.attributes.get('white_value'))
self.assertIsNone(state.attributes.get('xy_color'))
def test_controlling_state_via_topic(self):
"""Test the controlling of the state via topic."""
config = {light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'test_light_rgb/status',
'command_topic': 'test_light_rgb/set',
'brightness_state_topic': 'test_light_rgb/brightness/status',
'brightness_command_topic': 'test_light_rgb/brightness/set',
'rgb_state_topic': 'test_light_rgb/rgb/status',
'rgb_command_topic': 'test_light_rgb/rgb/set',
'color_temp_state_topic': 'test_light_rgb/color_temp/status',
'color_temp_command_topic': 'test_light_rgb/color_temp/set',
'effect_state_topic': 'test_light_rgb/effect/status',
'effect_command_topic': 'test_light_rgb/effect/set',
'white_value_state_topic': 'test_light_rgb/white_value/status',
'white_value_command_topic': 'test_light_rgb/white_value/set',
'xy_state_topic': 'test_light_rgb/xy/status',
'xy_command_topic': 'test_light_rgb/xy/set',
'qos': '0',
'payload_on': 1,
'payload_off': 0
}}
with assert_setup_component(1, light.DOMAIN):
assert setup_component(self.hass, light.DOMAIN, config)
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
self.assertIsNone(state.attributes.get('rgb_color'))
self.assertIsNone(state.attributes.get('brightness'))
self.assertIsNone(state.attributes.get('color_temp'))
self.assertIsNone(state.attributes.get('effect'))
self.assertIsNone(state.attributes.get('white_value'))
self.assertIsNone(state.attributes.get('xy_color'))
self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE))
fire_mqtt_message(self.hass, 'test_light_rgb/status', '1')
self.hass.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state)
self.assertEqual((255, 255, 255), state.attributes.get('rgb_color'))
self.assertEqual(255, state.attributes.get('brightness'))
self.assertEqual(150, state.attributes.get('color_temp'))
self.assertEqual('none', state.attributes.get('effect'))
self.assertEqual(255, state.attributes.get('white_value'))
self.assertEqual((0.323, 0.329), state.attributes.get('xy_color'))
fire_mqtt_message(self.hass, 'test_light_rgb/status', '0')
self.hass.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
fire_mqtt_message(self.hass, 'test_light_rgb/status', '1')
self.hass.block_till_done()
fire_mqtt_message(self.hass, 'test_light_rgb/brightness/status', '100')
self.hass.block_till_done()
light_state = self.hass.states.get('light.test')
self.hass.block_till_done()
self.assertEqual(100,
light_state.attributes['brightness'])
fire_mqtt_message(self.hass, 'test_light_rgb/color_temp/status', '300')
self.hass.block_till_done()
light_state = self.hass.states.get('light.test')
self.hass.block_till_done()
self.assertEqual(300, light_state.attributes['color_temp'])
fire_mqtt_message(self.hass, 'test_light_rgb/effect/status', 'rainbow')
self.hass.block_till_done()
light_state = self.hass.states.get('light.test')
self.hass.block_till_done()
self.assertEqual('rainbow', light_state.attributes['effect'])
fire_mqtt_message(self.hass, 'test_light_rgb/white_value/status',
'100')
self.hass.block_till_done()
light_state = self.hass.states.get('light.test')
self.hass.block_till_done()
self.assertEqual(100,
light_state.attributes['white_value'])
fire_mqtt_message(self.hass, 'test_light_rgb/status', '1')
self.hass.block_till_done()
fire_mqtt_message(self.hass, 'test_light_rgb/rgb/status',
'125,125,125')
self.hass.block_till_done()
light_state = self.hass.states.get('light.test')
self.assertEqual((255, 255, 255),
light_state.attributes.get('rgb_color'))
fire_mqtt_message(self.hass, 'test_light_rgb/xy/status',
'0.675,0.322')
self.hass.block_till_done()
light_state = self.hass.states.get('light.test')
self.assertEqual((0.672, 0.324),
light_state.attributes.get('xy_color'))
def test_brightness_controlling_scale(self):
"""Test the brightness controlling scale."""
with assert_setup_component(1, light.DOMAIN):
assert setup_component(self.hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'test_scale/status',
'command_topic': 'test_scale/set',
'brightness_state_topic': 'test_scale/brightness/status',
'brightness_command_topic': 'test_scale/brightness/set',
'brightness_scale': '99',
'qos': 0,
'payload_on': 'on',
'payload_off': 'off'
}
})
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
self.assertIsNone(state.attributes.get('brightness'))
self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE))
fire_mqtt_message(self.hass, 'test_scale/status', 'on')
self.hass.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state)
self.assertEqual(255, state.attributes.get('brightness'))
fire_mqtt_message(self.hass, 'test_scale/status', 'off')
self.hass.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
fire_mqtt_message(self.hass, 'test_scale/status', 'on')
self.hass.block_till_done()
fire_mqtt_message(self.hass, 'test_scale/brightness/status', '99')
self.hass.block_till_done()
light_state = self.hass.states.get('light.test')
self.hass.block_till_done()
self.assertEqual(255,
light_state.attributes['brightness'])
def test_white_value_controlling_scale(self):
"""Test the white_value controlling scale."""
with assert_setup_component(1, light.DOMAIN):
assert setup_component(self.hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'test_scale/status',
'command_topic': 'test_scale/set',
'white_value_state_topic': 'test_scale/white_value/status',
'white_value_command_topic': 'test_scale/white_value/set',
'white_value_scale': '99',
'qos': 0,
'payload_on': 'on',
'payload_off': 'off'
}
})
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
self.assertIsNone(state.attributes.get('white_value'))
self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE))
fire_mqtt_message(self.hass, 'test_scale/status', 'on')
self.hass.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state)
self.assertEqual(255, state.attributes.get('white_value'))
fire_mqtt_message(self.hass, 'test_scale/status', 'off')
self.hass.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
fire_mqtt_message(self.hass, 'test_scale/status', 'on')
self.hass.block_till_done()
fire_mqtt_message(self.hass, 'test_scale/white_value/status', '99')
self.hass.block_till_done()
light_state = self.hass.states.get('light.test')
self.hass.block_till_done()
self.assertEqual(255,
light_state.attributes['white_value'])
def test_controlling_state_via_topic_with_templates(self):
"""Test the setting og the state with a template."""
config = {light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'test_light_rgb/status',
'command_topic': 'test_light_rgb/set',
'brightness_command_topic': 'test_light_rgb/brightness/set',
'rgb_command_topic': 'test_light_rgb/rgb/set',
'color_temp_command_topic': 'test_light_rgb/color_temp/set',
'effect_command_topic': 'test_light_rgb/effect/set',
'white_value_command_topic': 'test_light_rgb/white_value/set',
'xy_command_topic': 'test_light_rgb/xy/set',
'brightness_state_topic': 'test_light_rgb/brightness/status',
'color_temp_state_topic': 'test_light_rgb/color_temp/status',
'effect_state_topic': 'test_light_rgb/effect/status',
'rgb_state_topic': 'test_light_rgb/rgb/status',
'white_value_state_topic': 'test_light_rgb/white_value/status',
'xy_state_topic': 'test_light_rgb/xy/status',
'state_value_template': '{{ value_json.hello }}',
'brightness_value_template': '{{ value_json.hello }}',
'color_temp_value_template': '{{ value_json.hello }}',
'effect_value_template': '{{ value_json.hello }}',
'rgb_value_template': '{{ value_json.hello | join(",") }}',
'white_value_template': '{{ value_json.hello }}',
'xy_value_template': '{{ value_json.hello | join(",") }}',
}}
with assert_setup_component(1, light.DOMAIN):
assert setup_component(self.hass, light.DOMAIN, config)
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
self.assertIsNone(state.attributes.get('brightness'))
self.assertIsNone(state.attributes.get('rgb_color'))
fire_mqtt_message(self.hass, 'test_light_rgb/rgb/status',
'{"hello": [1, 2, 3]}')
fire_mqtt_message(self.hass, 'test_light_rgb/status',
'{"hello": "ON"}')
fire_mqtt_message(self.hass, 'test_light_rgb/brightness/status',
'{"hello": "50"}')
fire_mqtt_message(self.hass, 'test_light_rgb/color_temp/status',
'{"hello": "300"}')
fire_mqtt_message(self.hass, 'test_light_rgb/effect/status',
'{"hello": "rainbow"}')
fire_mqtt_message(self.hass, 'test_light_rgb/white_value/status',
'{"hello": "75"}')
fire_mqtt_message(self.hass, 'test_light_rgb/xy/status',
'{"hello": [0.123,0.123]}')
self.hass.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state)
self.assertEqual(50, state.attributes.get('brightness'))
self.assertEqual((0, 123, 255), state.attributes.get('rgb_color'))
self.assertEqual(300, state.attributes.get('color_temp'))
self.assertEqual('rainbow', state.attributes.get('effect'))
self.assertEqual(75, state.attributes.get('white_value'))
self.assertEqual((0.14, 0.131), state.attributes.get('xy_color'))
def test_sending_mqtt_commands_and_optimistic(self):
"""Test the sending of command in optimistic mode."""
config = {light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'command_topic': 'test_light_rgb/set',
'brightness_command_topic': 'test_light_rgb/brightness/set',
'rgb_command_topic': 'test_light_rgb/rgb/set',
'color_temp_command_topic': 'test_light_rgb/color_temp/set',
'effect_command_topic': 'test_light_rgb/effect/set',
'white_value_command_topic': 'test_light_rgb/white_value/set',
'xy_command_topic': 'test_light_rgb/xy/set',
'effect_list': ['colorloop', 'random'],
'qos': 2,
'payload_on': 'on',
'payload_off': 'off'
}}
fake_state = ha.State('light.test', 'on', {'brightness': 95,
'hs_color': [100, 100],
'effect': 'random',
'color_temp': 100,
'white_value': 50})
with patch('homeassistant.components.light.mqtt.async_get_last_state',
return_value=mock_coro(fake_state)):
with assert_setup_component(1, light.DOMAIN):
assert setup_component(self.hass, light.DOMAIN, config)
state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state)
self.assertEqual(95, state.attributes.get('brightness'))
self.assertEqual((100, 100), state.attributes.get('hs_color'))
self.assertEqual('random', state.attributes.get('effect'))
self.assertEqual(100, state.attributes.get('color_temp'))
self.assertEqual(50, state.attributes.get('white_value'))
self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE))
light.turn_on(self.hass, 'light.test')
self.hass.block_till_done()
self.mock_publish.async_publish.assert_called_once_with(
'test_light_rgb/set', 'on', 2, False)
self.mock_publish.async_publish.reset_mock()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state)
light.turn_off(self.hass, 'light.test')
self.hass.block_till_done()
self.mock_publish.async_publish.assert_called_once_with(
'test_light_rgb/set', 'off', 2, False)
self.mock_publish.async_publish.reset_mock()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
self.mock_publish.reset_mock()
light.turn_on(self.hass, 'light.test',
brightness=50, xy_color=[0.123, 0.123])
light.turn_on(self.hass, 'light.test', rgb_color=[255, 128, 0],
white_value=80)
self.hass.block_till_done()
self.mock_publish.async_publish.assert_has_calls([
mock.call('test_light_rgb/set', 'on', 2, False),
mock.call('test_light_rgb/rgb/set', '255,128,0', 2, False),
mock.call('test_light_rgb/brightness/set', 50, 2, False),
mock.call('test_light_rgb/white_value/set', 80, 2, False),
mock.call('test_light_rgb/xy/set', '0.14,0.131', 2, False),
], any_order=True)
state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state)
self.assertEqual((255, 128, 0), state.attributes['rgb_color'])
self.assertEqual(50, state.attributes['brightness'])
self.assertEqual(80, state.attributes['white_value'])
self.assertEqual((0.611, 0.375), state.attributes['xy_color'])
def test_sending_mqtt_rgb_command_with_template(self):
"""Test the sending of RGB command with template."""
config = {light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'command_topic': 'test_light_rgb/set',
'rgb_command_topic': 'test_light_rgb/rgb/set',
'rgb_command_template': '{{ "#%02x%02x%02x" | '
'format(red, green, blue)}}',
'payload_on': 'on',
'payload_off': 'off',
'qos': 0
}}
with assert_setup_component(1, light.DOMAIN):
assert setup_component(self.hass, light.DOMAIN, config)
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
light.turn_on(self.hass, 'light.test', rgb_color=[255, 128, 64])
self.hass.block_till_done()
self.mock_publish.async_publish.assert_has_calls([
mock.call('test_light_rgb/set', 'on', 0, False),
mock.call('test_light_rgb/rgb/set', '#ff803f', 0, False),
], any_order=True)
state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state)
self.assertEqual((255, 128, 63), state.attributes['rgb_color'])
def test_show_brightness_if_only_command_topic(self):
"""Test the brightness if only a command topic is present."""
config = {light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'brightness_command_topic': 'test_light_rgb/brightness/set',
'command_topic': 'test_light_rgb/set',
'state_topic': 'test_light_rgb/status',
}}
with assert_setup_component(1, light.DOMAIN):
assert setup_component(self.hass, light.DOMAIN, config)
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
self.assertIsNone(state.attributes.get('brightness'))
fire_mqtt_message(self.hass, 'test_light_rgb/status', 'ON')
self.hass.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state)
self.assertEqual(255, state.attributes.get('brightness'))
def test_show_color_temp_only_if_command_topic(self):
"""Test the color temp only if a command topic is present."""
config = {light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'color_temp_command_topic': 'test_light_rgb/brightness/set',
'command_topic': 'test_light_rgb/set',
'state_topic': 'test_light_rgb/status'
}}
with assert_setup_component(1, light.DOMAIN):
assert setup_component(self.hass, light.DOMAIN, config)
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
self.assertIsNone(state.attributes.get('color_temp'))
fire_mqtt_message(self.hass, 'test_light_rgb/status', 'ON')
self.hass.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state)
self.assertEqual(150, state.attributes.get('color_temp'))
def test_show_effect_only_if_command_topic(self):
"""Test the color temp only if a command topic is present."""
config = {light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'effect_command_topic': 'test_light_rgb/effect/set',
'command_topic': 'test_light_rgb/set',
'state_topic': 'test_light_rgb/status'
}}
with assert_setup_component(1, light.DOMAIN):
assert setup_component(self.hass, light.DOMAIN, config)
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
self.assertIsNone(state.attributes.get('effect'))
fire_mqtt_message(self.hass, 'test_light_rgb/status', 'ON')
self.hass.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state)
self.assertEqual('none', state.attributes.get('effect'))
def test_show_white_value_if_only_command_topic(self):
"""Test the white_value if only a command topic is present."""
config = {light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'white_value_command_topic': 'test_light_rgb/white_value/set',
'command_topic': 'test_light_rgb/set',
'state_topic': 'test_light_rgb/status',
}}
with assert_setup_component(1, light.DOMAIN):
assert setup_component(self.hass, light.DOMAIN, config)
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
self.assertIsNone(state.attributes.get('white_value'))
fire_mqtt_message(self.hass, 'test_light_rgb/status', 'ON')
self.hass.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state)
self.assertEqual(255, state.attributes.get('white_value'))
def test_show_xy_if_only_command_topic(self):
"""Test the xy if only a command topic is present."""
config = {light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'xy_command_topic': 'test_light_rgb/xy/set',
'command_topic': 'test_light_rgb/set',
'state_topic': 'test_light_rgb/status',
}}
with assert_setup_component(1, light.DOMAIN):
assert setup_component(self.hass, light.DOMAIN, config)
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
self.assertIsNone(state.attributes.get('xy_color'))
fire_mqtt_message(self.hass, 'test_light_rgb/status', 'ON')
self.hass.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state)
self.assertEqual((0.323, 0.329), state.attributes.get('xy_color'))
def test_on_command_first(self):
"""Test on command being sent before brightness."""
config = {light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'command_topic': 'test_light/set',
'brightness_command_topic': 'test_light/bright',
'on_command_type': 'first',
}}
with assert_setup_component(1, light.DOMAIN):
assert setup_component(self.hass, light.DOMAIN, config)
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
light.turn_on(self.hass, 'light.test', brightness=50)
self.hass.block_till_done()
# Should get the following MQTT messages.
# test_light/set: 'ON'
# test_light/bright: 50
self.mock_publish.async_publish.assert_has_calls([
mock.call('test_light/set', 'ON', 0, False),
mock.call('test_light/bright', 50, 0, False),
], any_order=True)
self.mock_publish.async_publish.reset_mock()
light.turn_off(self.hass, 'light.test')
self.hass.block_till_done()
self.mock_publish.async_publish.assert_called_once_with(
'test_light/set', 'OFF', 0, False)
def test_on_command_last(self):
"""Test on command being sent after brightness."""
config = {light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'command_topic': 'test_light/set',
'brightness_command_topic': 'test_light/bright',
}}
with assert_setup_component(1, light.DOMAIN):
assert setup_component(self.hass, light.DOMAIN, config)
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
light.turn_on(self.hass, 'light.test', brightness=50)
self.hass.block_till_done()
# Should get the following MQTT messages.
# test_light/bright: 50
# test_light/set: 'ON'
self.mock_publish.async_publish.assert_has_calls([
mock.call('test_light/bright', 50, 0, False),
mock.call('test_light/set', 'ON', 0, False),
], any_order=True)
self.mock_publish.async_publish.reset_mock()
light.turn_off(self.hass, 'light.test')
self.hass.block_till_done()
self.mock_publish.async_publish.assert_called_once_with(
'test_light/set', 'OFF', 0, False)
def test_on_command_brightness(self):
"""Test on command being sent as only brightness."""
config = {light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'command_topic': 'test_light/set',
'brightness_command_topic': 'test_light/bright',
'rgb_command_topic': "test_light/rgb",
'on_command_type': 'brightness',
}}
with assert_setup_component(1, light.DOMAIN):
assert setup_component(self.hass, light.DOMAIN, config)
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
# Turn on w/ no brightness - should set to max
light.turn_on(self.hass, 'light.test')
self.hass.block_till_done()
# Should get the following MQTT messages.
# test_light/bright: 255
self.mock_publish.async_publish.assert_called_once_with(
'test_light/bright', 255, 0, False)
self.mock_publish.async_publish.reset_mock()
light.turn_off(self.hass, 'light.test')
self.hass.block_till_done()
self.mock_publish.async_publish.assert_called_once_with(
'test_light/set', 'OFF', 0, False)
self.mock_publish.async_publish.reset_mock()
# Turn on w/ brightness
light.turn_on(self.hass, 'light.test', brightness=50)
self.hass.block_till_done()
self.mock_publish.async_publish.assert_called_once_with(
'test_light/bright', 50, 0, False)
self.mock_publish.async_publish.reset_mock()
light.turn_off(self.hass, 'light.test')
self.hass.block_till_done()
# Turn on w/ just a color to insure brightness gets
# added and sent.
light.turn_on(self.hass, 'light.test', rgb_color=[255, 128, 0])
self.hass.block_till_done()
self.mock_publish.async_publish.assert_has_calls([
mock.call('test_light/rgb', '255,128,0', 0, False),
mock.call('test_light/bright', 50, 0, False)
], any_order=True)
def test_default_availability_payload(self):
"""Test availability by default payload with defined topic."""
self.assertTrue(setup_component(self.hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'command_topic': 'test_light/set',
'brightness_command_topic': 'test_light/bright',
'rgb_command_topic': "test_light/rgb",
'availability_topic': 'availability-topic'
}
}))
state = self.hass.states.get('light.test')
self.assertEqual(STATE_UNAVAILABLE, state.state)
fire_mqtt_message(self.hass, 'availability-topic', 'online')
self.hass.block_till_done()
state = self.hass.states.get('light.test')
self.assertNotEqual(STATE_UNAVAILABLE, state.state)
fire_mqtt_message(self.hass, 'availability-topic', 'offline')
self.hass.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_UNAVAILABLE, state.state)
def test_custom_availability_payload(self):
"""Test availability by custom payload with defined topic."""
self.assertTrue(setup_component(self.hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'command_topic': 'test_light/set',
'brightness_command_topic': 'test_light/bright',
'rgb_command_topic': "test_light/rgb",
'availability_topic': 'availability-topic',
'payload_available': 'good',
'payload_not_available': 'nogood'
}
}))
state = self.hass.states.get('light.test')
self.assertEqual(STATE_UNAVAILABLE, state.state)
fire_mqtt_message(self.hass, 'availability-topic', 'good')
self.hass.block_till_done()
state = self.hass.states.get('light.test')
self.assertNotEqual(STATE_UNAVAILABLE, state.state)
fire_mqtt_message(self.hass, 'availability-topic', 'nogood')
self.hass.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_UNAVAILABLE, state.state)
| {
"content_hash": "dfcc9fe03003dc1b579822a6b53c0f9b",
"timestamp": "",
"source": "github",
"line_count": 878,
"max_line_length": 79,
"avg_line_length": 39.77904328018223,
"alnum_prop": 0.5986371184790701,
"repo_name": "persandstrom/home-assistant",
"id": "1245411dcc4fe5c774314393794f390a93f5fd33",
"size": "34926",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/components/light/test_mqtt.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1067"
},
{
"name": "Python",
"bytes": "11745210"
},
{
"name": "Ruby",
"bytes": "518"
},
{
"name": "Shell",
"bytes": "16652"
}
],
"symlink_target": ""
} |
'''Example WordCountStreamletTopology'''
import sys
from heronpy.streamlet.builder import Builder
from heronpy.streamlet.runner import Runner
from heronpy.streamlet.config import Config
from heronpy.streamlet.windowconfig import WindowConfig
from heronpy.connectors.mock.arraylooper import ArrayLooper
# pylint: disable=superfluous-parens
if __name__ == '__main__':
if len(sys.argv) != 2:
print("Topology's name is not specified")
sys.exit(1)
builder = Builder()
builder.new_source(ArrayLooper(["Mary Had a little lamb", "I Love You"])) \
.flat_map(lambda line: line.split()) \
.map(lambda word: (word, 1)) \
.reduce_by_key_and_window(WindowConfig.create_sliding_window(10, 2), lambda x, y: x + y) \
.log()
runner = Runner()
config = Config()
runner.run(sys.argv[1], config, builder)
| {
"content_hash": "802ea02b7b7e850b45e0531eb262d37f",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 99,
"avg_line_length": 35.125,
"alnum_prop": 0.6951364175563464,
"repo_name": "twitter/heron",
"id": "4f2ecd6d850f2b94f7fcd6e1cac6be386b23bc93",
"size": "1693",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "examples/src/python/word_count_streamlet.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "11709"
},
{
"name": "C++",
"bytes": "1623082"
},
{
"name": "CSS",
"bytes": "109554"
},
{
"name": "HCL",
"bytes": "2115"
},
{
"name": "HTML",
"bytes": "156820"
},
{
"name": "Java",
"bytes": "4466689"
},
{
"name": "JavaScript",
"bytes": "1111202"
},
{
"name": "M4",
"bytes": "17941"
},
{
"name": "Makefile",
"bytes": "781"
},
{
"name": "Objective-C",
"bytes": "1929"
},
{
"name": "Python",
"bytes": "1537910"
},
{
"name": "Ruby",
"bytes": "1930"
},
{
"name": "Scala",
"bytes": "72781"
},
{
"name": "Shell",
"bytes": "166876"
},
{
"name": "Smarty",
"bytes": "528"
},
{
"name": "Thrift",
"bytes": "915"
}
],
"symlink_target": ""
} |
from openerp.tests.common import TransactionCase
class TestCreateInvoice(TransactionCase):
def setUp(self):
super(TestCreateInvoice, self).setUp()
self.Wizard = self.env['stock.invoice.onshipping']
self.customer = self.env.ref('base.res_partner_3')
product = self.env.ref('product.product_product_36')
dropship_route = self.env.ref('stock_dropshipping.route_drop_shipping')
self.so = self.env['sale.order'].create({
'partner_id': self.customer.id,
})
self.sol = self.env['sale.order.line'].create({
'name': '/',
'order_id': self.so.id,
'product_id': product.id,
'route_id': dropship_route.id,
})
def test_po_on_delivery_creates_correct_invoice(self):
self.so.action_button_confirm()
po = self.so.procurement_group_id.procurement_ids.purchase_id
self.assertTrue(po)
po.invoice_method = 'picking'
po.signal_workflow('purchase_confirm')
picking = po.picking_ids
self.assertEqual(1, len(picking))
picking.action_done()
wizard = self.Wizard.with_context({
'active_id': picking.id,
'active_ids': [picking.id],
}).create({})
invoice_ids = wizard.create_invoice()
invoices = self.env['account.invoice'].browse(invoice_ids)
self.assertEqual(1, len(invoices))
self.assertEqual(invoices.type, 'in_invoice')
self.assertEqual(invoices, po.invoice_ids)
| {
"content_hash": "81033ed1819c471b9f5c47e740e98ee1",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 79,
"avg_line_length": 34.81818181818182,
"alnum_prop": 0.606396866840731,
"repo_name": "cristianquaglio/odoo",
"id": "c1588b0af130678eca39e04bb683ecba245faa85",
"size": "2284",
"binary": false,
"copies": "251",
"ref": "refs/heads/master",
"path": "addons/stock_dropshipping/tests/test_invoicing.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "9611"
},
{
"name": "C++",
"bytes": "108790"
},
{
"name": "CSS",
"bytes": "671328"
},
{
"name": "HTML",
"bytes": "212829"
},
{
"name": "JavaScript",
"bytes": "5984109"
},
{
"name": "Makefile",
"bytes": "12332"
},
{
"name": "Mako",
"bytes": "561"
},
{
"name": "PHP",
"bytes": "14033"
},
{
"name": "Python",
"bytes": "8366254"
},
{
"name": "Ruby",
"bytes": "220"
},
{
"name": "Shell",
"bytes": "19163"
},
{
"name": "Vim script",
"bytes": "406"
},
{
"name": "XSLT",
"bytes": "92945"
}
],
"symlink_target": ""
} |
import requests
import json
from django.conf import settings
from django.core import serializers
from django.core.urlresolvers import reverse
if getattr(settings, 'HOOK_THREADING', True):
from .client import Client
client = Client()
else:
client = requests
def get_module(path):
"""
A modified duplicate from Django's built in backend
retriever.
slugify = get_module('django.template.defaultfilters.slugify')
"""
from importlib import import_module
try:
mod_name, func_name = path.rsplit('.', 1)
mod = import_module(mod_name)
except ImportError, e:
raise ImportError(
'Error importing alert function {0}: "{1}"'.format(mod_name, e))
try:
func = getattr(mod, func_name)
except AttributeError:
raise ImportError(
('Module "{0}" does not define a "{1}" function'
).format(mod_name, func_name))
return func
def serialize_hook(instance):
"""
Serialize the object down to Python primitives.
By default it uses Django's built in serializer.
"""
if getattr(instance, 'serialize_hook', None) and callable(instance.serialize_hook):
return instance.serialize_hook(hook=instance)
if getattr(settings, 'HOOK_SERIALIZER', None):
serializer = get_module(settings.HOOK_SERIALIZER)
return serializer(instance, hook=instance)
# if no user defined serializers, fallback to the django builtin!
return {
'hook': instance.dict(),
'data': serializers.serialize('python', [instance])[0]
}
def deliver_hook(instance, target, payload_override=None):
"""
Deliver the payload to the target URL.
By default it serializes to JSON and POSTs.
"""
payload = payload_override or serialize_hook(instance)
if hasattr(settings, 'HOOK_DELIVERER'):
deliverer = get_module(settings.HOOK_DELIVERER)
deliverer(target, payload, instance=instance)
else:
client.post(
url=target,
data=json.dumps(payload, cls=serializers.json.DjangoJSONEncoder),
headers={'Content-Type': 'application/json'}
)
return None
def get_payload(deployment):
return {
"event_name": "deployment_create",
"id": deployment.pk,
"url": reverse('projects_deployment_detail', args=(deployment.stage.project_id, deployment.stage_id, deployment.pk,)),
"status": deployment.status,
"task": {
"name": deployment.task.name
},
"date_deleted": '',
"date_update": '',
"comments": deployment.comments,
"user": {
"id": deployment.user.pk,
"name": '{} {}'.format(deployment.user.first_name, deployment.user.last_name),
"email": deployment.user.email
},
"output": deployment.output,
"date_created": '',
"configuration": '',
"stage": {
"id": deployment.stage.pk,
"name": deployment.stage.name,
"url": reverse('projects_stage_view', args=(deployment.stage.project.pk, deployment.stage.pk))
}
}
if hasattr(settings, 'DEPLOYMENT_FINISHED_PAYLOAD_GENERATOR'):
payload_generator = settings.DEPLOYMENT_FINISHED_PAYLOAD_GENERATOR
else:
payload_generator = get_payload | {
"content_hash": "90821d2e3b87296e1f45fa9c2471c0fe",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 126,
"avg_line_length": 29.883928571428573,
"alnum_prop": 0.6232446967433523,
"repo_name": "fabric-bolt/fabric-bolt",
"id": "690969e8c3a5f8b4016d7b147813a166e657a117",
"size": "4095",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "fabric_bolt/web_hooks/utils.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3076"
},
{
"name": "HTML",
"bytes": "68887"
},
{
"name": "JavaScript",
"bytes": "102382"
},
{
"name": "Python",
"bytes": "223229"
}
],
"symlink_target": ""
} |
# Copyright ClusterHQ Limited. See LICENSE file for details.
"""
Tests that verify that Docker behaviour is unchanged when running through
Powerstrip.
Run these tests as so. Ensure Docker is running on /var/run/docker.sock.
$ TEST_PASSTHRU=1 trial powerstrip.test.test_passthru
"""
import os
from twisted.internet import defer
from twisted.trial.unittest import TestCase
from ..testtools import GenerallyUsefulPowerstripTestMixin
def CompareDockerAndPowerstrip(test_case, cmd, usePTY=False,
expectDifferentResults=False):
"""
Compare the output of a real Docker server against a Powerstrip passthu.
There will be environment variables set which determine whether any
``docker`` execs will talk to Docker or Powerstrip.
:param test_case: The current ``TestCase`` context.
:param cmd: A shell command. E.g. ``echo ls | docker run -i ubuntu bash``.
This command should include at least one call to Docker.
:param usePTY: Execute the given command with a pseudo-terminal, to
encourage Docker to feel comfortable writing out streaming responses (like
`docker pull` output) that are supposed to be consumed by a human.
:param expectDifferentResults: If True, then don't make an assertion in
here. Whether this is true or not, the raw responses from docker and
powerstrip are passed back to the caller as a tuple for further inspection
if they wish to make any additional assertions about the contents of the
results.
:return: A ``Deferred`` which fires when the test has been completed.
"""
DOCKER = b"unix:///var/run/docker.sock"
POWERSTRIP = b"tcp://localhost:%(proxyPort)d"
d = getProcessOutputPTY(b"/bin/bash", ["-c", cmd], { b"DOCKER_HOST": DOCKER },
errortoo=True, usePTY=usePTY)
def got_result(docker_result):
if not docker_result:
raise ValueError("Command did not produce any output when sent to "
"Docker daemon.")
d = getProcessOutputPTY(b"/bin/bash", ["-c", cmd],
{ b"DOCKER_HOST": POWERSTRIP % dict(proxyPort=test_case.proxyPort) },
errortoo=True, usePTY=usePTY)
def compare_result(powerstrip_result, docker_result):
if not expectDifferentResults:
test_case.assertEquals(docker_result, powerstrip_result)
return powerstrip_result, docker_result
d.addCallback(compare_result, docker_result)
return d
d.addCallback(got_result)
return d
class BasicTests(TestCase, GenerallyUsefulPowerstripTestMixin):
"""
Tests for basic Docker functionality.
"""
if "TEST_PASSTHRU" not in os.environ:
skip = "Skipping passthru tests."
def tearDown(self):
shutdowns = [
self.proxyServer.stopListening()]
if hasattr(self, "nullServer"):
shutdowns.append(self.nullServer.stopListening())
return defer.gatherResults(shutdowns)
def test_run(self):
"""
Test basic ``docker run`` functionality.
"""
# XXX this will need to prime the Docker instance in most cases, e.g.
# docker pull
# Actually run the current (local) version of powerstrip on
# localhost:something.
self._configure("endpoints: {}\nadapters: {}", dockerOnSocket=True,
realDockerSocket="/var/run/docker.sock")
self.config.read_and_parse()
d = CompareDockerAndPowerstrip(self,
"docker run ubuntu echo hello")
def assertions((powerstrip, docker)):
self.assertNotIn("fatal", docker)
self.assertNotIn("fatal", powerstrip)
self.assertIn("hello", docker)
self.assertIn("hello", powerstrip)
d.addCallback(assertions)
return d
def test_run_post_hook(self):
"""
Test basic ``docker run`` functionality when there's a post-hook (the
post-hook should get skipped).
Post-hooks are skipped on attach commands because they have streaming
(aka "hijacked") responses.
Note that http://devnull/ should never be attempted because one
should always skip a post-hook when Docker responds with a hijacked
response type (`application/vnd.docker.raw-stream` as an example, such
as the TCP-stream hijacking that `docker attach` does). If the
implementation *does* attempt to connect to `devnull`, the test will
fail with a DNS lookup error. This could be made better.
"""
self._configure("""
endpoints:
"POST /*/containers/*/attach":
post: [nothing]
adapters:
nothing: http://devnull/
""",
dockerOnSocket=True,
realDockerSocket="/var/run/docker.sock")
self.config.read_and_parse()
d = CompareDockerAndPowerstrip(self,
"docker run ubuntu echo hello")
def assertions((powerstrip, docker)):
self.assertNotIn("fatal", docker)
self.assertNotIn("fatal", powerstrip)
self.assertIn("hello", docker)
self.assertIn("hello", powerstrip)
d.addCallback(assertions)
return d
def test_run_post_hook_tty(self):
"""
Test basic ``docker run`` functionality with -ti when there's a
post-hook (the post-hook should get skipped).
"""
self._configure("""
endpoints:
"POST /*/containers/*/attach":
post: [nothing]
adapters:
nothing: http://devnull/
""",
dockerOnSocket=True,
realDockerSocket="/var/run/docker.sock")
self.config.read_and_parse()
d = CompareDockerAndPowerstrip(self,
"docker run -ti ubuntu echo hello", usePTY=True)
def assertions((powerstrip, docker)):
self.assertNotIn("fatal", docker)
self.assertNotIn("fatal", powerstrip)
self.assertIn("hello", docker)
self.assertIn("hello", powerstrip)
d.addCallback(assertions)
return d
def test_run_tty(self):
"""
Test basic ``docker run`` functionality with -ti args. (terminal;
interactive).
"""
self._configure("endpoints: {}\nadapters: {}", dockerOnSocket=True,
realDockerSocket="/var/run/docker.sock")
self.config.read_and_parse()
d = CompareDockerAndPowerstrip(self,
"docker run -ti ubuntu echo hello", usePTY=True)
def assertions((powerstrip, docker)):
self.assertNotIn("fatal", docker)
self.assertNotIn("fatal", powerstrip)
self.assertIn("hello", docker)
self.assertIn("hello", powerstrip)
d.addCallback(assertions)
return d
def test_logs(self):
"""
Run a container and then get the logs from it.
"""
self._configure("""endpoints: {}\nadapters: {}""",
dockerOnSocket=True,
realDockerSocket="/var/run/docker.sock")
self.config.read_and_parse()
d = CompareDockerAndPowerstrip(self,
"""
id=$(docker run -d ubuntu bash -c \\
"for X in range {1..10000}; do echo \\$X; done");
docker wait $id >/dev/null; echo $id
""",
expectDifferentResults=True)
def extractDockerPS((powerstrip, docker)):
# Doesn't actually matter which one we use here.
containerID = docker.split("\n")[0]
return CompareDockerAndPowerstrip(self,
"docker logs %s" % (containerID,))
d.addCallback(extractDockerPS)
return d
NULL_CONFIG = """
endpoints:
"* *":
pre: [nothing]
post: [nothing]
adapters:
nothing: http://localhost:%d/null-adapter
"""
NULL_TWICE_CONFIG = """
endpoints:
"* *":
pre: [nothing, nothing2]
post: [nothing, nothing2]
adapters:
nothing: http://localhost:%d/null-adapter
nothing2: http://localhost:%d/null-adapter
"""
def test_run_null_adapter(self):
"""
Test basic ``docker run`` functionality with null adapter matching all
possible API requests to exercise as much codepath as possible.
"""
self._getNullAdapter()
self._configure(self.NULL_CONFIG % (self.nullPort,),
dockerOnSocket=True,
realDockerSocket="/var/run/docker.sock")
self.config.read_and_parse()
d = CompareDockerAndPowerstrip(self,
"docker run -ti ubuntu echo hello", usePTY=True)
def assertions((powerstrip, docker)):
self.assertNotIn("fatal", docker)
self.assertNotIn("fatal", powerstrip)
self.assertIn("hello", docker)
self.assertIn("hello", powerstrip)
d.addCallback(assertions)
return d
def test_run_null_twice_adapter(self):
"""
Test basic ``docker run`` functionality with null adapter matching all
possible API requests to exercise as much codepath as possible. Twice.
"""
self._getNullAdapter()
self._configure(self.NULL_TWICE_CONFIG % (self.nullPort, self.nullPort),
dockerOnSocket=True,
realDockerSocket="/var/run/docker.sock")
self.config.read_and_parse()
d = CompareDockerAndPowerstrip(self,
"docker run -ti ubuntu echo hello", usePTY=True)
def assertions((powerstrip, docker)):
self.assertNotIn("fatal", docker)
self.assertNotIn("fatal", powerstrip)
self.assertIn("hello", docker)
self.assertIn("hello", powerstrip)
d.addCallback(assertions)
return d
def test_run_docker_pull(self):
"""
Test basic ``docker pull`` functionality.
"""
self._getNullAdapter()
self._configure(self.NULL_CONFIG % (self.nullPort,),
dockerOnSocket=True,
realDockerSocket="/var/run/docker.sock")
self.config.read_and_parse()
d = CompareDockerAndPowerstrip(self,
"docker rmi busybox; docker pull busybox", usePTY=True,
expectDifferentResults=True)
def assertions((powerstrip, docker)):
self.assertNotIn("fatal", docker)
# The outputs vary per test run due to e.g. download speed, but
# there should be some common themes...
text = ["Downloaded newer image for busybox",
"Untagged",
"Deleted",
"Downloading",
"Extracting"]
for textLine in text:
self.assertIn(textLine, powerstrip)
self.assertIn(textLine, docker)
d.addCallback(assertions)
return d
def test_run_docker_build(self):
"""
Test basic ``docker build`` functionality.
"""
self._getNullAdapter()
self._configure(self.NULL_CONFIG % (self.nullPort,),
dockerOnSocket=True,
realDockerSocket="/var/run/docker.sock")
self.config.read_and_parse()
d = CompareDockerAndPowerstrip(self,
"cd ../fixtures/free-dockerfile; docker build .", usePTY=True)
def assertions((powerstrip, docker)):
self.assertNotIn("fatal", docker)
d.addCallback(assertions)
return d
def test_run_stdin(self):
"""
Test basic ``docker run`` functionality when piped stdin.
"""
self._configure("endpoints: {}\nadapters: {}", dockerOnSocket=True,
realDockerSocket="/var/run/docker.sock")
self.config.read_and_parse()
return CompareDockerAndPowerstrip(self,
"echo hello |docker run -i ubuntu cat")
# XXX Ripped from twisted.internet.utils.getProcessOutput (to add PTY support
# to getProcessOutput):
from twisted.internet.utils import _BackRelay
def getProcessOutputPTY(executable, args=(), env={}, path=None, reactor=None,
errortoo=0, usePTY=False):
"""
A version of getProcessOutput with a usePTY arg.
"""
return _callProtocolWithDeferredPTY(lambda d:
_BackRelay(d, errortoo=errortoo),
executable, args, env, path,
reactor, usePTY=usePTY)
def _callProtocolWithDeferredPTY(protocol, executable, args, env, path,
reactor=None, usePTY=False):
if reactor is None:
from twisted.internet import reactor
d = defer.Deferred()
p = protocol(d)
reactor.spawnProcess(p, executable, (executable,)+tuple(args), env, path,
usePTY=usePTY)
return d
# End ripping.
| {
"content_hash": "c0806de0b8ecb5467acadcc6ffd06783",
"timestamp": "",
"source": "github",
"line_count": 345,
"max_line_length": 85,
"avg_line_length": 36.88405797101449,
"alnum_prop": 0.6090373280943026,
"repo_name": "ClusterHQ/powerstrip",
"id": "c94e60958fa2877fb466129b1df9ca7e83a824a7",
"size": "12725",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "powerstrip/test/test_passthru.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "78972"
},
{
"name": "Shell",
"bytes": "524"
}
],
"symlink_target": ""
} |
import atexit
import contextlib
import copy
import functools
import os
import attr
import packaging.markers
import packaging.version
import pip_shims.shims
import requests
from packaging.utils import canonicalize_name
from vistir.compat import JSONDecodeError, fs_str
from vistir.contextmanagers import cd, temp_environ
from vistir.path import create_tracked_tempdir
from ..environment import MYPY_RUNNING
from ..utils import _ensure_dir, prepare_pip_source_args
from .cache import CACHE_DIR, DependencyCache
from .setup_info import SetupInfo
from .utils import (
clean_requires_python,
fix_requires_python_marker,
format_requirement,
full_groupby,
is_pinned_requirement,
key_from_ireq,
make_install_requirement,
name_from_req,
version_from_ireq,
)
try:
from contextlib import ExitStack
except ImportError:
from contextlib2 import ExitStack
if MYPY_RUNNING:
from typing import (
Any,
Dict,
List,
Generator,
Optional,
Union,
Tuple,
TypeVar,
Text,
Set,
)
from pip_shims.shims import (
InstallRequirement,
InstallationCandidate,
PackageFinder,
Command,
)
from packaging.requirements import Requirement as PackagingRequirement
from packaging.markers import Marker
TRequirement = TypeVar("TRequirement")
RequirementType = TypeVar(
"RequirementType", covariant=True, bound=PackagingRequirement
)
MarkerType = TypeVar("MarkerType", covariant=True, bound=Marker)
STRING_TYPE = Union[str, bytes, Text]
S = TypeVar("S", bytes, str, Text)
PKGS_DOWNLOAD_DIR = fs_str(os.path.join(CACHE_DIR, "pkgs"))
WHEEL_DOWNLOAD_DIR = fs_str(os.path.join(CACHE_DIR, "wheels"))
DEPENDENCY_CACHE = DependencyCache()
@contextlib.contextmanager
def _get_wheel_cache():
with pip_shims.shims.global_tempdir_manager():
yield pip_shims.shims.WheelCache(
CACHE_DIR, pip_shims.shims.FormatControl(set(), set())
)
def _get_filtered_versions(ireq, versions, prereleases):
return set(ireq.specifier.filter(versions, prereleases=prereleases))
def find_all_matches(finder, ireq, pre=False):
# type: (PackageFinder, InstallRequirement, bool) -> List[InstallationCandidate]
"""Find all matching dependencies using the supplied finder and the
given ireq.
:param finder: A package finder for discovering matching candidates.
:type finder: :class:`~pip._internal.index.PackageFinder`
:param ireq: An install requirement.
:type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A list of matching candidates.
:rtype: list[:class:`~pip._internal.index.InstallationCandidate`]
"""
candidates = clean_requires_python(finder.find_all_candidates(ireq.name))
versions = {candidate.version for candidate in candidates}
allowed_versions = _get_filtered_versions(ireq, versions, pre)
if not pre and not allowed_versions:
allowed_versions = _get_filtered_versions(ireq, versions, True)
candidates = {c for c in candidates if c.version in allowed_versions}
return candidates
def get_pip_command():
# type: () -> Command
# Use pip's parser for pip.conf management and defaults.
# General options (find_links, index_url, extra_index_url, trusted_host,
# and pre) are defered to pip.
pip_command = pip_shims.shims.InstallCommand()
return pip_command
@attr.s
class AbstractDependency(object):
name = attr.ib() # type: STRING_TYPE
specifiers = attr.ib()
markers = attr.ib()
candidates = attr.ib()
requirement = attr.ib()
parent = attr.ib()
finder = attr.ib()
dep_dict = attr.ib(default=attr.Factory(dict))
@property
def version_set(self):
"""Return the set of versions for the candidates in this abstract dependency.
:return: A set of matching versions
:rtype: set(str)
"""
if len(self.candidates) == 1:
return set()
return set(packaging.version.parse(version_from_ireq(c)) for c in self.candidates)
def compatible_versions(self, other):
"""Find compatible version numbers between this abstract
dependency and another one.
:param other: An abstract dependency to compare with.
:type other: :class:`~requirementslib.models.dependency.AbstractDependency`
:return: A set of compatible version strings
:rtype: set(str)
"""
if len(self.candidates) == 1 and next(iter(self.candidates)).editable:
return self
elif len(other.candidates) == 1 and next(iter(other.candidates)).editable:
return other
return self.version_set & other.version_set
def compatible_abstract_dep(self, other):
"""Merge this abstract dependency with another one.
Return the result of the merge as a new abstract dependency.
:param other: An abstract dependency to merge with
:type other: :class:`~requirementslib.models.dependency.AbstractDependency`
:return: A new, combined abstract dependency
:rtype: :class:`~requirementslib.models.dependency.AbstractDependency`
"""
from .requirements import Requirement
if len(self.candidates) == 1 and next(iter(self.candidates)).editable:
return self
elif len(other.candidates) == 1 and next(iter(other.candidates)).editable:
return other
new_specifiers = self.specifiers & other.specifiers
markers = set(self.markers) if self.markers else set()
if other.markers:
markers.add(other.markers)
new_markers = None
if markers:
new_markers = packaging.markers.Marker(
" or ".join(str(m) for m in sorted(markers))
)
new_ireq = copy.deepcopy(self.requirement.ireq)
new_ireq.req.specifier = new_specifiers
new_ireq.req.marker = new_markers
new_requirement = Requirement.from_line(format_requirement(new_ireq))
compatible_versions = self.compatible_versions(other)
if isinstance(compatible_versions, AbstractDependency):
return compatible_versions
candidates = [
c
for c in self.candidates
if packaging.version.parse(version_from_ireq(c)) in compatible_versions
]
dep_dict = {}
candidate_strings = [format_requirement(c) for c in candidates]
for c in candidate_strings:
if c in self.dep_dict:
dep_dict[c] = self.dep_dict.get(c)
return AbstractDependency(
name=self.name,
specifiers=new_specifiers,
markers=new_markers,
candidates=candidates,
requirement=new_requirement,
parent=self.parent,
dep_dict=dep_dict,
finder=self.finder,
)
def get_deps(self, candidate):
"""Get the dependencies of the supplied candidate.
:param candidate: An installrequirement
:type candidate: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A list of abstract dependencies
:rtype: list[:class:`~requirementslib.models.dependency.AbstractDependency`]
"""
key = format_requirement(candidate)
if key not in self.dep_dict:
from .requirements import Requirement
req = Requirement.from_line(key)
req = req.merge_markers(self.markers)
self.dep_dict[key] = req.get_abstract_dependencies()
return self.dep_dict[key]
@classmethod
def from_requirement(cls, requirement, parent=None):
"""Creates a new :class:`~requirementslib.models.dependency.AbstractDependency`
from a :class:`~requirementslib.models.requirements.Requirement` object.
This class is used to find all candidates matching a given set of specifiers
and a given requirement.
:param requirement: A requirement for resolution
:type requirement: :class:`~requirementslib.models.requirements.Requirement` object.
"""
name = requirement.normalized_name
specifiers = requirement.ireq.specifier if not requirement.editable else ""
markers = requirement.ireq.markers
extras = requirement.ireq.extras
is_pinned = is_pinned_requirement(requirement.ireq)
is_constraint = bool(parent)
_, finder = get_finder(sources=None)
candidates = []
if not is_pinned and not requirement.editable:
for r in requirement.find_all_matches(finder=finder):
req = make_install_requirement(
name,
r.version,
extras=extras,
markers=markers,
constraint=is_constraint,
)
req.req.link = getattr(r, "location", getattr(r, "link", None))
req.parent = parent
candidates.append(req)
candidates = sorted(
set(candidates),
key=lambda k: packaging.version.parse(version_from_ireq(k)),
)
else:
candidates = [requirement.ireq]
return cls(
name=name,
specifiers=specifiers,
markers=markers,
candidates=candidates,
requirement=requirement,
parent=parent,
finder=finder,
)
@classmethod
def from_string(cls, line, parent=None):
from .requirements import Requirement
req = Requirement.from_line(line)
abstract_dep = cls.from_requirement(req, parent=parent)
return abstract_dep
def get_abstract_dependencies(reqs, sources=None, parent=None):
"""Get all abstract dependencies for a given list of requirements.
Given a set of requirements, convert each requirement to an Abstract Dependency.
:param reqs: A list of Requirements
:type reqs: list[:class:`~requirementslib.models.requirements.Requirement`]
:param sources: Pipfile-formatted sources, defaults to None
:param sources: list[dict], optional
:param parent: The parent of this list of dependencies, defaults to None
:param parent: :class:`~requirementslib.models.requirements.Requirement`, optional
:return: A list of Abstract Dependencies
:rtype: list[:class:`~requirementslib.models.dependency.AbstractDependency`]
"""
deps = []
from .requirements import Requirement
for req in reqs:
if isinstance(req, pip_shims.shims.InstallRequirement):
requirement = Requirement.from_line("{0}{1}".format(req.name, req.specifier))
if req.link:
requirement.req.link = req.link
requirement.markers = req.markers
requirement.req.markers = req.markers
requirement.extras = req.extras
requirement.req.extras = req.extras
elif isinstance(req, Requirement):
requirement = copy.deepcopy(req)
else:
requirement = Requirement.from_line(req)
dep = AbstractDependency.from_requirement(requirement, parent=parent)
deps.append(dep)
return deps
def get_dependencies(ireq, sources=None, parent=None):
# type: (Union[InstallRequirement, InstallationCandidate], Optional[List[Dict[S, Union[S, bool]]]], Optional[AbstractDependency]) -> Set[S, ...]
"""Get all dependencies for a given install requirement.
:param ireq: A single InstallRequirement
:type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`
:param sources: Pipfile-formatted sources, defaults to None
:type sources: list[dict], optional
:param parent: The parent of this list of dependencies, defaults to None
:type parent: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A set of dependency lines for generating new InstallRequirements.
:rtype: set(str)
"""
if not isinstance(ireq, pip_shims.shims.InstallRequirement):
name = getattr(ireq, "project_name", getattr(ireq, "project", ireq.name))
version = getattr(ireq, "version", None)
if not version:
ireq = pip_shims.shims.InstallRequirement.from_line("{0}".format(name))
else:
ireq = pip_shims.shims.InstallRequirement.from_line(
"{0}=={1}".format(name, version)
)
pip_options = get_pip_options(sources=sources)
getters = [
get_dependencies_from_cache,
get_dependencies_from_wheel_cache,
get_dependencies_from_json,
functools.partial(get_dependencies_from_index, pip_options=pip_options),
]
for getter in getters:
deps = getter(ireq)
if deps is not None:
return deps
raise RuntimeError("failed to get dependencies for {}".format(ireq))
def get_dependencies_from_wheel_cache(ireq):
# type: (pip_shims.shims.InstallRequirement) -> Optional[Set[pip_shims.shims.InstallRequirement]]
"""Retrieves dependencies for the given install requirement from the wheel cache.
:param ireq: A single InstallRequirement
:type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A set of dependency lines for generating new InstallRequirements.
:rtype: set(str) or None
"""
if ireq.editable or not is_pinned_requirement(ireq):
return
with _get_wheel_cache() as wheel_cache:
matches = wheel_cache.get(ireq.link, name_from_req(ireq.req))
if matches:
matches = set(matches)
if not DEPENDENCY_CACHE.get(ireq):
DEPENDENCY_CACHE[ireq] = [format_requirement(m) for m in matches]
return matches
return None
def _marker_contains_extra(ireq):
# TODO: Implement better parsing logic avoid false-positives.
return "extra" in repr(ireq.markers)
def get_dependencies_from_json(ireq):
"""Retrieves dependencies for the given install requirement from the json api.
:param ireq: A single InstallRequirement
:type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A set of dependency lines for generating new InstallRequirements.
:rtype: set(str) or None
"""
if ireq.editable or not is_pinned_requirement(ireq):
return
# It is technically possible to parse extras out of the JSON API's
# requirement format, but it is such a chore let's just use the simple API.
if ireq.extras:
return
session = requests.session()
atexit.register(session.close)
version = str(ireq.req.specifier).lstrip("=")
def gen(ireq):
info = None
try:
info = session.get(
"https://pypi.org/pypi/{0}/{1}/json".format(ireq.req.name, version)
).json()["info"]
finally:
session.close()
requires_dist = info.get("requires_dist", info.get("requires"))
if not requires_dist: # The API can return None for this.
return
for requires in requires_dist:
i = pip_shims.shims.InstallRequirement.from_line(requires)
# See above, we don't handle requirements with extras.
if not _marker_contains_extra(i):
yield format_requirement(i)
if ireq not in DEPENDENCY_CACHE:
try:
reqs = DEPENDENCY_CACHE[ireq] = list(gen(ireq))
except JSONDecodeError:
return
req_iter = iter(reqs)
else:
req_iter = gen(ireq)
return set(req_iter)
def get_dependencies_from_cache(ireq):
"""Retrieves dependencies for the given install requirement from the dependency cache.
:param ireq: A single InstallRequirement
:type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A set of dependency lines for generating new InstallRequirements.
:rtype: set(str) or None
"""
if ireq.editable or not is_pinned_requirement(ireq):
return
if ireq not in DEPENDENCY_CACHE:
return
cached = set(DEPENDENCY_CACHE[ireq])
# Preserving sanity: Run through the cache and make sure every entry if
# valid. If this fails, something is wrong with the cache. Drop it.
try:
broken = False
for line in cached:
dep_ireq = pip_shims.shims.InstallRequirement.from_line(line)
name = canonicalize_name(dep_ireq.name)
if _marker_contains_extra(dep_ireq):
broken = True # The "extra =" marker breaks everything.
elif name == canonicalize_name(ireq.name):
broken = True # A package cannot depend on itself.
if broken:
break
except Exception:
broken = True
if broken:
del DEPENDENCY_CACHE[ireq]
return
return cached
def is_python(section):
return section.startswith("[") and ":" in section
def get_dependencies_from_index(dep, sources=None, pip_options=None, wheel_cache=None):
"""Retrieves dependencies for the given install requirement from the pip resolver.
:param dep: A single InstallRequirement
:type dep: :class:`~pip._internal.req.req_install.InstallRequirement`
:param sources: Pipfile-formatted sources, defaults to None
:type sources: list[dict], optional
:return: A set of dependency lines for generating new InstallRequirements.
:rtype: set(str) or None
"""
session, finder = get_finder(sources=sources, pip_options=pip_options)
dep.is_direct = True
requirements = None
setup_requires = {}
with temp_environ(), ExitStack() as stack:
if not wheel_cache:
wheel_cache = stack.enter_context(_get_wheel_cache())
os.environ["PIP_EXISTS_ACTION"] = "i"
if dep.editable and not dep.prepared and not dep.req:
setup_info = SetupInfo.from_ireq(dep)
results = setup_info.get_info()
setup_requires.update(results["setup_requires"])
requirements = set(results["requires"].values())
else:
results = pip_shims.shims.resolve(dep)
requirements = [v for v in results.values() if v.name != dep.name]
requirements = set([format_requirement(r) for r in requirements])
if not dep.editable and is_pinned_requirement(dep) and requirements is not None:
DEPENDENCY_CACHE[dep] = list(requirements)
return requirements
def get_pip_options(args=[], sources=None, pip_command=None):
"""Build a pip command from a list of sources
:param args: positional arguments passed through to the pip parser
:param sources: A list of pipfile-formatted sources, defaults to None
:param sources: list[dict], optional
:param pip_command: A pre-built pip command instance
:type pip_command: :class:`~pip._internal.cli.base_command.Command`
:return: An instance of pip_options using the supplied arguments plus sane defaults
:rtype: :class:`~pip._internal.cli.cmdoptions`
"""
if not pip_command:
pip_command = get_pip_command()
if not sources:
sources = [{"url": "https://pypi.org/simple", "name": "pypi", "verify_ssl": True}]
_ensure_dir(CACHE_DIR)
pip_args = args
pip_args = prepare_pip_source_args(sources, pip_args)
pip_options, _ = pip_command.parser.parse_args(pip_args)
pip_options.cache_dir = CACHE_DIR
return pip_options
def get_finder(sources=None, pip_command=None, pip_options=None):
# type: (List[Dict[S, Union[S, bool]]], Optional[Command], Any) -> PackageFinder
"""Get a package finder for looking up candidates to install
:param sources: A list of pipfile-formatted sources, defaults to None
:param sources: list[dict], optional
:param pip_command: A pip command instance, defaults to None
:type pip_command: :class:`~pip._internal.cli.base_command.Command`
:param pip_options: A pip options, defaults to None
:type pip_options: :class:`~pip._internal.cli.cmdoptions`
:return: A package finder
:rtype: :class:`~pip._internal.index.PackageFinder`
"""
if not pip_command:
pip_command = pip_shims.shims.InstallCommand()
if not sources:
sources = [{"url": "https://pypi.org/simple", "name": "pypi", "verify_ssl": True}]
if not pip_options:
pip_options = get_pip_options(sources=sources, pip_command=pip_command)
session = pip_command._build_session(pip_options)
atexit.register(session.close)
finder = pip_shims.shims.get_package_finder(
pip_shims.shims.InstallCommand(), options=pip_options, session=session
)
return session, finder
@contextlib.contextmanager
def start_resolver(finder=None, session=None, wheel_cache=None):
"""Context manager to produce a resolver.
:param finder: A package finder to use for searching the index
:type finder: :class:`~pip._internal.index.PackageFinder`
:param :class:`~requests.Session` session: A session instance
:param :class:`~pip._internal.cache.WheelCache` wheel_cache: A pip WheelCache instance
:return: A 3-tuple of finder, preparer, resolver
:rtype: (:class:`~pip._internal.operations.prepare.RequirementPreparer`, :class:`~pip._internal.resolve.Resolver`)
"""
pip_command = get_pip_command()
pip_options = get_pip_options(pip_command=pip_command)
session = None
if not finder:
session, finder = get_finder(pip_command=pip_command, pip_options=pip_options)
if not session:
session = pip_command._build_session(pip_options)
download_dir = PKGS_DOWNLOAD_DIR
_ensure_dir(download_dir)
_build_dir = create_tracked_tempdir(fs_str("build"))
_source_dir = create_tracked_tempdir(fs_str("source"))
try:
with ExitStack() as ctx:
ctx.enter_context(pip_shims.shims.global_tempdir_manager())
if not wheel_cache:
wheel_cache = ctx.enter_context(_get_wheel_cache())
_ensure_dir(fs_str(os.path.join(wheel_cache.cache_dir, "wheels")))
preparer = ctx.enter_context(
pip_shims.shims.make_preparer(
options=pip_options,
finder=finder,
session=session,
build_dir=_build_dir,
src_dir=_source_dir,
download_dir=download_dir,
wheel_download_dir=WHEEL_DOWNLOAD_DIR,
progress_bar="off",
build_isolation=False,
install_cmd=pip_command,
)
)
resolver = pip_shims.shims.get_resolver(
finder=finder,
ignore_dependencies=False,
ignore_requires_python=True,
preparer=preparer,
session=session,
options=pip_options,
install_cmd=pip_command,
wheel_cache=wheel_cache,
force_reinstall=True,
ignore_installed=True,
upgrade_strategy="to-satisfy-only",
isolated=False,
use_user_site=False,
)
yield resolver
finally:
session.close()
def get_grouped_dependencies(constraints):
# We need to track what contributed a specifierset
# as well as which specifiers were required by the root node
# in order to resolve any conflicts when we are deciding which thing to backtrack on
# then we take the loose match (which _is_ flexible) and start moving backwards in
# versions by popping them off of a stack and checking for the conflicting package
for _, ireqs in full_groupby(constraints, key=key_from_ireq):
ireqs = sorted(ireqs, key=lambda ireq: ireq.editable)
editable_ireq = next(iter(ireq for ireq in ireqs if ireq.editable), None)
if editable_ireq:
yield editable_ireq # only the editable match mattters, ignore all others
continue
ireqs = iter(ireqs)
# deepcopy the accumulator so as to not modify the self.our_constraints invariant
combined_ireq = copy.deepcopy(next(ireqs))
for ireq in ireqs:
# NOTE we may be losing some info on dropped reqs here
try:
combined_ireq.req.specifier &= ireq.req.specifier
except TypeError:
if ireq.req.specifier._specs and not combined_ireq.req.specifier._specs:
combined_ireq.req.specifier._specs = ireq.req.specifier._specs
combined_ireq.constraint &= ireq.constraint
if not combined_ireq.markers:
combined_ireq.markers = ireq.markers
else:
_markers = combined_ireq.markers._markers
if not isinstance(_markers[0], (tuple, list)):
combined_ireq.markers._markers = [
_markers,
"and",
ireq.markers._markers,
]
# Return a sorted, de-duped tuple of extras
combined_ireq.extras = tuple(
sorted(set(tuple(combined_ireq.extras) + tuple(ireq.extras)))
)
yield combined_ireq
| {
"content_hash": "2d8b13ada7a56d0a784ace0fcf364da1",
"timestamp": "",
"source": "github",
"line_count": 661,
"max_line_length": 148,
"avg_line_length": 38.33131618759455,
"alnum_prop": 0.6408414571575167,
"repo_name": "kennethreitz/pipenv",
"id": "2608479a6eb2e36b3c87b6e120b434ff8ab96a52",
"size": "25361",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pipenv/vendor/requirementslib/models/dependencies.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "202"
},
{
"name": "PowerShell",
"bytes": "7195"
},
{
"name": "Python",
"bytes": "2588085"
},
{
"name": "Roff",
"bytes": "40754"
}
],
"symlink_target": ""
} |
from django_mptt_admin.admin import DjangoMpttAdmin
from django.contrib import admin
from tabbed_admin import TabbedModelAdmin
from grappelli_autocomplete_fk_edit_link import AutocompleteEditLinkAdminMixin
from reversion.admin import VersionAdmin
from billingapp.models import FinancialAccountCategory, FinancialAccounts, FinancialTransactions, FinancialHeader, \
FinancialHeaderType
# @admin.register(FinancialAccounts)
# class FinancialAccountsAdmin(DjangoMpttAdmin):
# pass
class FinancialTransactionsInline(admin.TabularInline):
model = FinancialTransactions
extra = 0
show_change_link = True
raw_id_fields = ("financial_account",)
classes = ('grp-collapse grp-open',)
# quantity amount balance
# fields = (('idx', 'name', 'financial_account', 'quantity', 'amount', 'balance'),)
fields = (('name', 'financial_account', 'quantity', 'amount', 'balance'),)
@admin.register(FinancialAccountCategory)
class FinancialAccountCategoryAdmin(admin.ModelAdmin):
pass
class FinancialAccountsAdmin(DjangoMpttAdmin):
tree_auto_open = True
admin.site.register(FinancialAccounts, FinancialAccountsAdmin)
@admin.register(FinancialHeader)
class FinancialHeaderAdmin(admin.ModelAdmin):
inlines = [FinancialTransactionsInline,]
list_display = ['header_number', 'header_date', 'header_type']
@admin.register(FinancialHeaderType)
class FinancialHeaderTypeAdmin(admin.ModelAdmin):
pass
@admin.register(FinancialTransactions)
class FinancialTransactionsAdmin(admin.ModelAdmin):
pass
| {
"content_hash": "61698d646b043b23eab90a6ba6bc0a40",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 116,
"avg_line_length": 31.448979591836736,
"alnum_prop": 0.7774172615184944,
"repo_name": "bittssystem/version3",
"id": "64f25f3ca48ceeadce0c3c50c3fff99632967c9d",
"size": "1541",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "billingapp/admin.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "84857"
},
{
"name": "HTML",
"bytes": "87148"
},
{
"name": "JavaScript",
"bytes": "224908"
},
{
"name": "Python",
"bytes": "174137"
},
{
"name": "Shell",
"bytes": "4232"
}
],
"symlink_target": ""
} |
"""
Define the base classes for the Sumatra version control abstraction layer.
:copyright: Copyright 2006-2015 by the Sumatra team, see doc/authors.txt
:license: BSD 2-clause, see LICENSE for details.
"""
from __future__ import unicode_literals
from builtins import object
import os.path
from sumatra.core import component_type
class VersionControlError(Exception):
pass
class UncommittedModificationsError(Exception):
pass
@component_type
class Repository(object):
"""
Represents, and enables limited interaction with, the version control system
repository located at *url*.
If *upstream* is not provided, this information will be obtained, if
possible, from the version control system.
"""
required_attributes = ("exists", "checkout", "get_working_copy")
def __init__(self, url, upstream=None):
if url == ".":
url = os.path.abspath(url)
self.url = url
self.upstream = upstream
def __str__(self):
s = "%s at %s" % (self.__class__.__name__, self.url)
if self.upstream:
s += " (upstream: %s)" % self.upstream
return s
def __eq__(self, other):
return self.__class__ == other.__class__ and self.url == other.url
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash(self.url) ^ hash(self.upstream) ^ hash(self.__class__.__name__)
def __getstate__(self):
"""For pickling"""
return {'url': self.url, 'upstream': self.upstream}
def __setstate__(self, state):
"""For unpickling"""
self.__init__(state['url'])
self.upstream = state['upstream']
@property
def vcs_type(self):
return self.__class__.__name__[:-10] # strip off "Repository"
@property
def exists(self):
"""Does the repository represented by this object actually exist?"""
raise NotImplementedError
def checkout(self, path="."):
"""
Clone a repository ("checkout" in Subversion) from *self.url* to
the local filesystem at *path*.
"""
raise NotImplementedError
def get_working_copy(self, path=None):
"""
Return a :class:`WorkingCopy` object corresponding to a checkout of this repository.
"""
raise NotImplementedError
@component_type
class WorkingCopy(object):
"""
Represents, and enables limited interaction with, the version control system
working copy located in the *path* directory.
If *path* is not specified, the current working directory is assumed.
For each version control system supported by Sumatra, there is a specific
subclass of the abstract :class:`WorkingCopy` base class.
"""
required_attributes = ("contains", "current_version", "use_version",
"use_latest_version", "status", "has_changed",
"diff", "get_username")
def __init__(self, path=None):
self.path = path or os.getcwd()
def __eq__(self, other):
return (self.repository == other.repository) and (self.path == other.path) \
and (self.current_version() == other.current_version()) #and (self.diff() == other.diff())
def __ne__(self, other):
return not self.__eq__(other)
@property
def exists(self):
"""Does the working copy represented by this object actually exist?"""
raise NotImplementedError
def contains(self, path):
"""
Does the repository contain the file with the given path?
where `path` is relative to the working copy root.
"""
status = self.status()
return (path in status['modified']) or (path in status['clean'])
def current_version(self):
"""Return the version of the current state of the working copy."""
raise NotImplementedError
def use_version(self, version):
"""
Switch the working copy to *version*.
If the working copy has uncommitted changes, raises an
:class:`UncommittedModificationsError`.
"""
raise NotImplementedError
def use_latest_version(self):
"""
Switch the working copy to the most recent version.
Any uncommitted changes are retained/merged in.
"""
raise NotImplementedError
def status(self):
"""
Return a dict containing the sets of files that have been modified,
added, removed, are missing, not under version control ('unknown'),
are being ignored, or are unchanged ('clean').
"""
raise NotImplementedError
def has_changed(self):
"""Are there any uncommitted changes to the working copy?"""
raise NotImplementedError
def diff(self):
"""Return the difference between working copy and repository."""
raise NotImplementedError
def reset(self):
"""Resets all uncommitted changes since the commit. Destructive, be
careful with use"""
raise NotImplementedError
def patch(self, diff):
"""Applies the diff patch onto the repository files. Only works on a
clean working copy"""
raise NotImplementedError
def get_username(self):
"""
Return the username and e-mail of the current user, as understood by the
version control system, in the format 'username <e-mail>'.
"""
raise NotImplementedError
| {
"content_hash": "4df7da21af1b07d2029952f353bb2083",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 105,
"avg_line_length": 30.54189944134078,
"alnum_prop": 0.6200841412109018,
"repo_name": "open-research/sumatra",
"id": "e39551fcaa8d149bdfee74fc6ba8cf38078d5cca",
"size": "5467",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "sumatra/versioncontrol/base.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "8168"
},
{
"name": "HTML",
"bytes": "104980"
},
{
"name": "JavaScript",
"bytes": "4287"
},
{
"name": "Python",
"bytes": "581902"
},
{
"name": "R",
"bytes": "3325"
},
{
"name": "Shell",
"bytes": "35759"
},
{
"name": "TeX",
"bytes": "7153"
}
],
"symlink_target": ""
} |
__ALL__ = ['correctors', 'evaluators']
from music21.omr import correctors
from music21.omr import evaluators
| {
"content_hash": "9e500237ae85ca096325fe79bbd416e2",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 38,
"avg_line_length": 27.5,
"alnum_prop": 0.7545454545454545,
"repo_name": "arnavd96/Cinemiezer",
"id": "0afcb59a2ed456a8f77cc6f13e43f13ab66d6eb7",
"size": "624",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "myvenv/lib/python3.4/site-packages/music21/omr/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "300501"
},
{
"name": "C++",
"bytes": "14430"
},
{
"name": "CSS",
"bytes": "105126"
},
{
"name": "FORTRAN",
"bytes": "3200"
},
{
"name": "HTML",
"bytes": "290903"
},
{
"name": "JavaScript",
"bytes": "154747"
},
{
"name": "Jupyter Notebook",
"bytes": "558334"
},
{
"name": "Objective-C",
"bytes": "567"
},
{
"name": "Python",
"bytes": "37092739"
},
{
"name": "Shell",
"bytes": "3668"
},
{
"name": "TeX",
"bytes": "1527"
}
],
"symlink_target": ""
} |
class OVSCookieBridge(object):
'''Bridge restricting flow operations to its own distinct cookie
This class creates a bridge derived from a bridge passed at init (which
has to inherit from OVSBridgeCookieMixin), but that has its own cookie,
registered to the underlying bridge, and that will use this cookie in all
flow operations.
'''
def __new__(cls, bridge):
cookie_bridge = bridge.clone()
cookie_bridge.set_agent_uuid_stamp(bridge.request_cookie())
return cookie_bridge
def __init__(self, bridge):
pass
class OVSAgentExtensionAPI(object):
'''Implements the Agent API for Open vSwitch agent.
Extensions can gain access to this API by overriding the consume_api
method which has been added to the AgentExtension class.
'''
def __init__(self, int_br, tun_br, phys_brs=None,
plugin_rpc=None):
super(OVSAgentExtensionAPI, self).__init__()
self.br_int = int_br
self.br_tun = tun_br
self.br_phys = phys_brs or {}
self.plugin_rpc = plugin_rpc
def request_int_br(self):
"""Allows extensions to request an integration bridge to use for
extension specific flows.
"""
return OVSCookieBridge(self.br_int)
def request_tun_br(self):
"""Allows extensions to request a tunnel bridge to use for
extension specific flows.
If tunneling is not enabled, this method will return None.
"""
if not self.br_tun:
return None
return OVSCookieBridge(self.br_tun)
def request_phy_brs(self):
"""Allows extensions to request all physical bridges to use for
extension specific flows.
This a generator function which returns all existing physical bridges
in the switch.
"""
for phy_br in self.br_phys.values():
yield OVSCookieBridge(phy_br)
| {
"content_hash": "86d42a3842d341b82c576a202228aa38",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 77,
"avg_line_length": 32.15,
"alnum_prop": 0.6438569206842923,
"repo_name": "openstack/neutron",
"id": "c6ec265a0b2b9e74dbeb396517ea9e028952b808",
"size": "2564",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "neutron/plugins/ml2/drivers/openvswitch/agent/ovs_agent_extension_api.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Jinja",
"bytes": "2773"
},
{
"name": "Mako",
"bytes": "1047"
},
{
"name": "Python",
"bytes": "15932611"
},
{
"name": "Ruby",
"bytes": "1257"
},
{
"name": "Shell",
"bytes": "83270"
}
],
"symlink_target": ""
} |
from django import template
from bibbutler_web.models.entry import entry_types
register = template.Library()
@register.simple_tag
def lb():
return '{'
@register.simple_tag
def rb():
return '}'
@register.simple_tag
def get_class_verbose_name(object):
return object._meta.verbose_name
@register.simple_tag
def get_fields(object):
return object._meta.get_fields()
@register.filter(name='cut')
def cut(value, arg):
return value.replace(arg, '')
# @register.simple_tag
# def get_fields_without_id_and_relations(object):
# blacklist = ('id', 'polymorphic_ctype_id', 'bibliography_id', 'entry_ptr_id')
# fields = get_fields(object)
# return [field for field in fields if field.attname not in blacklist]
@register.inclusion_tag('bibbutler_web/modal_entry_type.html')
def load_modal_entry_type(bib_id):
return {'entry_types': entry_types,
'bib_id': bib_id}
@register.inclusion_tag('bibbutler_web/modal_delete_entry.html')
def load_modal_delete_entry(entry_id):
return {'entry_id': entry_id} | {
"content_hash": "b74f4a86834b1c9fbee9385f97755ba5",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 83,
"avg_line_length": 22.340425531914892,
"alnum_prop": 0.6980952380952381,
"repo_name": "dolonnen/bibbutler",
"id": "ae32d3a0ed6e8931968a8355e9c0935ae6a1fd3d",
"size": "1050",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bibbutler_web/templatetags/my_helpers.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "12923"
},
{
"name": "Python",
"bytes": "39038"
}
],
"symlink_target": ""
} |
import kfp
import kfp.dsl as dsl
from kfp.dsl import component, graph_component
from kfp.dsl.types import Integer, GCSPath, InconsistentTypeException
from kfp.dsl import ContainerOp, Pipeline, PipelineParam
from kfp.components.structures import ComponentSpec, InputSpec, OutputSpec
import unittest
class TestPythonComponent(unittest.TestCase):
def test_component_metadata(self):
"""Test component decorator metadata."""
class MockContainerOp:
def _set_metadata(self, component_meta):
self._metadata = component_meta
@component
def componentA(a: {'ArtifactA': {'file_type': 'csv'}}, b: Integer() = 12, c: {'ArtifactB': {'path_type': 'file', 'file_type':'tsv'}} = 'gs://hello/world') -> {'model': Integer()}:
return MockContainerOp()
containerOp = componentA(1,2,c=3)
golden_meta = ComponentSpec(name='ComponentA', inputs=[], outputs=[])
golden_meta.inputs.append(InputSpec(name='a', type={'ArtifactA': {'file_type': 'csv'}}))
golden_meta.inputs.append(InputSpec(name='b', type={'Integer': {'openapi_schema_validator': {"type": "integer"}}}, default="12", optional=True))
golden_meta.inputs.append(InputSpec(name='c', type={'ArtifactB': {'path_type':'file', 'file_type': 'tsv'}}, default='gs://hello/world', optional=True))
golden_meta.outputs.append(OutputSpec(name='model', type={'Integer': {'openapi_schema_validator': {"type": "integer"}}}))
self.assertEqual(containerOp._metadata, golden_meta)
def test_python_component_decorator(self):
# Deprecated
from kfp.dsl import python_component
from kfp.components import create_component_from_func
expected_name = 'Sum component name'
expected_description = 'Sum component description'
expected_image = 'org/image'
@python_component(
name=expected_name,
description=expected_description,
base_image=expected_image
)
def add_two_numbers_decorated(
a: float,
b: float,
) -> float:
'''Returns sum of two arguments'''
return a + b
op = create_component_from_func(add_two_numbers_decorated)
component_spec = op.component_spec
self.assertEqual(component_spec.name, expected_name)
self.assertEqual(component_spec.description.strip(), expected_description.strip())
self.assertEqual(component_spec.implementation.container.image, expected_image)
def test_type_check_with_same_representation(self):
"""Test type check at the decorator."""
kfp.TYPE_CHECK = True
@component
def a_op(field_l: Integer()) -> {'field_m': GCSPath(), 'field_n': {'customized_type': {'property_a': 'value_a', 'property_b': 'value_b'}}, 'field_o': 'GcsUri'}:
return ContainerOp(
name = 'operator a',
image = 'gcr.io/ml-pipeline/component-a',
arguments = [
'--field-l', field_l,
],
file_outputs = {
'field_m': '/schema.txt',
'field_n': '/feature.txt',
'field_o': '/output.txt'
}
)
@component
def b_op(field_x: {'customized_type': {'property_a': 'value_a', 'property_b': 'value_b'}},
field_y: 'GcsUri', # noqa: F821 TODO
field_z: GCSPath()) -> {'output_model_uri': 'GcsUri'}:
return ContainerOp(
name = 'operator b',
image = 'gcr.io/ml-pipeline/component-b',
command = [
'python3',
field_x,
],
arguments = [
'--field-y', field_y,
'--field-z', field_z,
],
file_outputs = {
'output_model_uri': '/schema.txt',
}
)
a = a_op(field_l=12)
b = b_op(field_x=a.outputs['field_n'], field_y=a.outputs['field_o'], field_z=a.outputs['field_m'])
def test_type_check_with_different_represenation(self):
"""Test type check at the decorator."""
kfp.TYPE_CHECK = True
@component
def a_op(field_l: Integer()) -> {'field_m': 'GCSPath', 'field_n': {'customized_type': {'property_a': 'value_a', 'property_b': 'value_b'}}, 'field_o': 'Integer'}:
return ContainerOp(
name = 'operator a',
image = 'gcr.io/ml-pipeline/component-b',
arguments = [
'--field-l', field_l,
],
file_outputs = {
'field_m': '/schema.txt',
'field_n': '/feature.txt',
'field_o': '/output.txt'
}
)
@component
def b_op(field_x: {'customized_type': {'property_a': 'value_a', 'property_b': 'value_b'}},
field_y: Integer(),
field_z: GCSPath()) -> {'output_model_uri': 'GcsUri'}:
return ContainerOp(
name = 'operator b',
image = 'gcr.io/ml-pipeline/component-a',
command = [
'python3',
field_x,
],
arguments = [
'--field-y', field_y,
'--field-z', field_z,
],
file_outputs = {
'output_model_uri': '/schema.txt',
}
)
a = a_op(field_l=12)
b = b_op(field_x=a.outputs['field_n'], field_y=a.outputs['field_o'], field_z=a.outputs['field_m'])
def test_type_check_with_inconsistent_types_property_value(self):
"""Test type check at the decorator."""
kfp.TYPE_CHECK = True
@component
def a_op(field_l: Integer()) -> {'field_m': {'ArtifactB': {'path_type': 'file', 'file_type':'tsv'}}, 'field_n': {'customized_type': {'property_a': 'value_a', 'property_b': 'value_b'}}, 'field_o': 'Integer'}:
return ContainerOp(
name = 'operator a',
image = 'gcr.io/ml-pipeline/component-b',
arguments = [
'--field-l', field_l,
],
file_outputs = {
'field_m': '/schema.txt',
'field_n': '/feature.txt',
'field_o': '/output.txt'
}
)
@component
def b_op(field_x: {'customized_type': {'property_a': 'value_a', 'property_b': 'value_b'}},
field_y: Integer(),
field_z: {'ArtifactB': {'path_type': 'file', 'file_type':'csv'}}) -> {'output_model_uri': 'GcsUri'}:
return ContainerOp(
name = 'operator b',
image = 'gcr.io/ml-pipeline/component-a',
command = [
'python3',
field_x,
],
arguments = [
'--field-y', field_y,
'--field-z', field_z,
],
file_outputs = {
'output_model_uri': '/schema.txt',
}
)
with self.assertRaises(InconsistentTypeException):
a = a_op(field_l=12)
b = b_op(field_x=a.outputs['field_n'], field_y=a.outputs['field_o'], field_z=a.outputs['field_m'])
def test_type_check_with_inconsistent_types_type_name(self):
"""Test type check at the decorator."""
kfp.TYPE_CHECK = True
@component
def a_op(field_l: Integer()) -> {'field_m': {'ArtifactB': {'path_type': 'file', 'file_type':'tsv'}}, 'field_n': {'customized_type': {'property_a': 'value_a', 'property_b': 'value_b'}}, 'field_o': 'Integer'}:
return ContainerOp(
name = 'operator a',
image = 'gcr.io/ml-pipeline/component-b',
arguments = [
'--field-l', field_l,
],
file_outputs = {
'field_m': '/schema.txt',
'field_n': '/feature.txt',
'field_o': '/output.txt'
}
)
@component
def b_op(field_x: {'customized_type_a': {'property_a': 'value_a', 'property_b': 'value_b'}},
field_y: Integer(),
field_z: {'ArtifactB': {'path_type': 'file', 'file_type':'tsv'}}) -> {'output_model_uri': 'GcsUri'}:
return ContainerOp(
name = 'operator b',
image = 'gcr.io/ml-pipeline/component-a',
command = [
'python3',
field_x,
],
arguments = [
'--field-y', field_y,
'--field-z', field_z,
],
file_outputs = {
'output_model_uri': '/schema.txt',
}
)
with self.assertRaises(InconsistentTypeException):
a = a_op(field_l=12)
b = b_op(field_x=a.outputs['field_n'], field_y=a.outputs['field_o'], field_z=a.outputs['field_m'])
def test_type_check_without_types(self):
"""Test type check at the decorator."""
kfp.TYPE_CHECK = True
@component
def a_op(field_l: Integer()) -> {'field_m': {'ArtifactB': {'path_type': 'file', 'file_type':'tsv'}}, 'field_n': {'customized_type': {'property_a': 'value_a', 'property_b': 'value_b'}}}:
return ContainerOp(
name = 'operator a',
image = 'gcr.io/ml-pipeline/component-b',
arguments = [
'--field-l', field_l,
],
file_outputs = {
'field_m': '/schema.txt',
'field_n': '/feature.txt',
'field_o': '/output.txt'
}
)
@component
def b_op(field_x,
field_y: Integer(),
field_z: {'ArtifactB': {'path_type': 'file', 'file_type':'tsv'}}) -> {'output_model_uri': 'GcsUri'}:
return ContainerOp(
name = 'operator b',
image = 'gcr.io/ml-pipeline/component-a',
command = [
'python3',
field_x,
],
arguments = [
'--field-y', field_y,
'--field-z', field_z,
],
file_outputs = {
'output_model_uri': '/schema.txt',
}
)
a = a_op(field_l=12)
b = b_op(field_x=a.outputs['field_n'], field_y=a.outputs['field_o'], field_z=a.outputs['field_m'])
def test_type_check_nonnamed_inputs(self):
"""Test type check at the decorator."""
kfp.TYPE_CHECK = True
@component
def a_op(field_l: Integer()) -> {'field_m': {'ArtifactB': {'path_type': 'file', 'file_type':'tsv'}}, 'field_n': {'customized_type': {'property_a': 'value_a', 'property_b': 'value_b'}}}:
return ContainerOp(
name = 'operator a',
image = 'gcr.io/ml-pipeline/component-b',
arguments = [
'--field-l', field_l,
],
file_outputs = {
'field_m': '/schema.txt',
'field_n': '/feature.txt',
'field_o': '/output.txt'
}
)
@component
def b_op(field_x,
field_y: Integer(),
field_z: {'ArtifactB': {'path_type': 'file', 'file_type':'tsv'}}) -> {'output_model_uri': 'GcsUri'}:
return ContainerOp(
name = 'operator b',
image = 'gcr.io/ml-pipeline/component-a',
command = [
'python3',
field_x,
],
arguments = [
'--field-y', field_y,
'--field-z', field_z,
],
file_outputs = {
'output_model_uri': '/schema.txt',
}
)
a = a_op(field_l=12)
b = b_op(a.outputs['field_n'], field_z=a.outputs['field_m'], field_y=a.outputs['field_o'])
def test_type_check_with_inconsistent_types_disabled(self):
"""Test type check at the decorator."""
kfp.TYPE_CHECK = False
@component
def a_op(field_l: Integer()) -> {'field_m': {'ArtifactB': {'path_type': 'file', 'file_type':'tsv'}}, 'field_n': {'customized_type': {'property_a': 'value_a', 'property_b': 'value_b'}}, 'field_o': 'Integer'}:
return ContainerOp(
name = 'operator a',
image = 'gcr.io/ml-pipeline/component-b',
arguments = [
'--field-l', field_l,
],
file_outputs = {
'field_m': '/schema.txt',
'field_n': '/feature.txt',
'field_o': '/output.txt'
}
)
@component
def b_op(field_x: {'customized_type_a': {'property_a': 'value_a', 'property_b': 'value_b'}},
field_y: Integer(),
field_z: {'ArtifactB': {'path_type': 'file', 'file_type':'tsv'}}) -> {'output_model_uri': 'GcsUri'}:
return ContainerOp(
name = 'operator b',
image = 'gcr.io/ml-pipeline/component-a',
command = [
'python3',
field_x,
],
arguments = [
'--field-y', field_y,
'--field-z', field_z,
],
file_outputs = {
'output_model_uri': '/schema.txt',
}
)
a = a_op(field_l=12)
b = b_op(field_x=a.outputs['field_n'], field_y=a.outputs['field_o'], field_z=a.outputs['field_m'])
def test_type_check_with_openapi_schema(self):
"""Test type check at the decorator."""
kfp.TYPE_CHECK = True
@component
def a_op(field_l: Integer()) -> {'field_m': 'GCSPath', 'field_n': {'customized_type': {'openapi_schema_validator': '{"type": "string", "pattern": "^gs://.*$"}'}}, 'field_o': 'Integer'}:
return ContainerOp(
name = 'operator a',
image = 'gcr.io/ml-pipeline/component-b',
arguments = [
'--field-l', field_l,
],
file_outputs = {
'field_m': '/schema.txt',
'field_n': '/feature.txt',
'field_o': '/output.txt'
}
)
@component
def b_op(field_x: {'customized_type': {'openapi_schema_validator': '{"type": "string", "pattern": "^gs://.*$"}'}},
field_y: Integer(),
field_z: GCSPath()) -> {'output_model_uri': 'GcsUri'}:
return ContainerOp(
name = 'operator b',
image = 'gcr.io/ml-pipeline/component-a',
command = [
'python3',
field_x,
],
arguments = [
'--field-y', field_y,
'--field-z', field_z,
],
file_outputs = {
'output_model_uri': '/schema.txt',
}
)
a = a_op(field_l=12)
b = b_op(field_x=a.outputs['field_n'], field_y=a.outputs['field_o'], field_z=a.outputs['field_m'])
def test_type_check_with_ignore_type(self):
"""Test type check at the decorator."""
kfp.TYPE_CHECK = True
@component
def a_op(field_l: Integer()) -> {'field_m': 'GCSPath', 'field_n': {'customized_type': {'openapi_schema_validator': '{"type": "string", "pattern": "^gs://.*$"}'}}, 'field_o': 'Integer'}:
return ContainerOp(
name = 'operator a',
image = 'gcr.io/ml-pipeline/component-b',
arguments = [
'--field-l', field_l,
],
file_outputs = {
'field_m': '/schema.txt',
'field_n': '/feature.txt',
'field_o': '/output.txt'
}
)
@component
def b_op(field_x: {'customized_type': {'openapi_schema_validator': '{"type": "string", "pattern": "^gcs://.*$"}'}},
field_y: Integer(),
field_z: GCSPath()) -> {'output_model_uri': 'GcsUri'}:
return ContainerOp(
name = 'operator b',
image = 'gcr.io/ml-pipeline/component-a',
command = [
'python3',
field_x,
],
arguments = [
'--field-y', field_y,
'--field-z', field_z,
],
file_outputs = {
'output_model_uri': '/schema.txt',
}
)
a = a_op(field_l=12)
with self.assertRaises(InconsistentTypeException):
b = b_op(field_x=a.outputs['field_n'], field_y=a.outputs['field_o'], field_z=a.outputs['field_m'])
b = b_op(field_x=a.outputs['field_n'].ignore_type(), field_y=a.outputs['field_o'], field_z=a.outputs['field_m'])
class TestGraphComponent(unittest.TestCase):
def test_graphcomponent_basic(self):
"""Test graph_component decorator metadata."""
@graph_component
def flip_component(flip_result):
with dsl.Condition(flip_result == 'heads'):
flip_component(flip_result)
with Pipeline('pipeline') as p:
param = PipelineParam(name='param')
flip_component(param)
self.assertEqual(1, len(p.groups))
self.assertEqual(1, len(p.groups[0].groups)) # pipeline
self.assertEqual(1, len(p.groups[0].groups[0].groups)) # flip_component
self.assertEqual(1, len(p.groups[0].groups[0].groups[0].groups)) # condition
self.assertEqual(0, len(p.groups[0].groups[0].groups[0].groups[0].groups)) # recursive flip_component
recursive_group = p.groups[0].groups[0].groups[0].groups[0]
self.assertTrue(recursive_group.recursive_ref is not None)
self.assertEqual(1, len(recursive_group.inputs))
self.assertEqual('param', recursive_group.inputs[0].name)
| {
"content_hash": "ae02fd4f594d9a17f8855002332ddf69",
"timestamp": "",
"source": "github",
"line_count": 453,
"max_line_length": 211,
"avg_line_length": 36.40397350993378,
"alnum_prop": 0.5270147353101692,
"repo_name": "kubeflow/kfp-tekton-backend",
"id": "ffd482945c1e8b77dde7c53f05cbb26975ba32d5",
"size": "17067",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sdk/python/tests/dsl/component_tests.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "47293"
},
{
"name": "Go",
"bytes": "1269081"
},
{
"name": "HTML",
"bytes": "3584"
},
{
"name": "JavaScript",
"bytes": "24828"
},
{
"name": "Jupyter Notebook",
"bytes": "177616"
},
{
"name": "Makefile",
"bytes": "9694"
},
{
"name": "PowerShell",
"bytes": "3194"
},
{
"name": "Python",
"bytes": "1628570"
},
{
"name": "Scala",
"bytes": "13000"
},
{
"name": "Shell",
"bytes": "180020"
},
{
"name": "Smarty",
"bytes": "7694"
},
{
"name": "Starlark",
"bytes": "76037"
},
{
"name": "TypeScript",
"bytes": "1641150"
}
],
"symlink_target": ""
} |
""" QuerySet for PolymorphicModel
Please see README.rst or DOCS.rst or http://bserve.webhop.org/wiki/django_polymorphic
"""
from compatibility_tools import defaultdict
from django.db.models.query import QuerySet
from django.contrib.contenttypes.models import ContentType
from query_translate import translate_polymorphic_filter_definitions_in_kwargs, translate_polymorphic_filter_definitions_in_args
from query_translate import translate_polymorphic_field_path
# chunk-size: maximum number of objects requested per db-request
# by the polymorphic queryset.iterator() implementation; we use the same chunk size as Django
from django.db.models.query import CHUNK_SIZE # this is 100 for Django 1.1/1.2
Polymorphic_QuerySet_objects_per_request = CHUNK_SIZE
###################################################################################
### PolymorphicQuerySet
class PolymorphicQuerySet(QuerySet):
"""
QuerySet for PolymorphicModel
Contains the core functionality for PolymorphicModel
Usually not explicitly needed, except if a custom queryset class
is to be used.
"""
def __init__(self, *args, **kwargs):
"init our queryset object member variables"
self.polymorphic_disabled = False
super(PolymorphicQuerySet, self).__init__(*args, **kwargs)
def _clone(self, *args, **kwargs):
"Django's _clone only copies its own variables, so we need to copy ours here"
new = super(PolymorphicQuerySet, self)._clone(*args, **kwargs)
new.polymorphic_disabled = self.polymorphic_disabled
return new
def non_polymorphic(self, *args, **kwargs):
"""switch off polymorphic behaviour for this query.
When the queryset is evaluated, only objects of the type of the
base class used for this query are returned."""
self.polymorphic_disabled = True
return self
def instance_of(self, *args):
"""Filter the queryset to only include the classes in args (and their subclasses).
Implementation in _translate_polymorphic_filter_defnition."""
return self.filter(instance_of=args)
def not_instance_of(self, *args):
"""Filter the queryset to exclude the classes in args (and their subclasses).
Implementation in _translate_polymorphic_filter_defnition."""
return self.filter(not_instance_of=args)
def _filter_or_exclude(self, negate, *args, **kwargs):
"We override this internal Django functon as it is used for all filter member functions."
translate_polymorphic_filter_definitions_in_args(self.model, args) # the Q objects
additional_args = translate_polymorphic_filter_definitions_in_kwargs(self.model, kwargs) # filter_field='data'
return super(PolymorphicQuerySet, self)._filter_or_exclude(negate, *(list(args) + additional_args), **kwargs)
def order_by(self, *args, **kwargs):
"""translate the field paths in the args, then call vanilla order_by."""
new_args = [translate_polymorphic_field_path(self.model, a) for a in args]
return super(PolymorphicQuerySet, self).order_by(*new_args, **kwargs)
def _process_aggregate_args(self, args, kwargs):
"""for aggregate and annotate kwargs: allow ModelX___field syntax for kwargs, forbid it for args.
Modifies kwargs if needed (these are Aggregate objects, we translate the lookup member variable)"""
for a in args:
assert not '___' in a.lookup, 'PolymorphicModel: annotate()/aggregate(): ___ model lookup supported for keyword arguments only'
for a in kwargs.values():
a.lookup = translate_polymorphic_field_path(self.model, a.lookup)
def annotate(self, *args, **kwargs):
"""translate the polymorphic field paths in the kwargs, then call vanilla annotate.
_get_real_instances will do the rest of the job after executing the query."""
self._process_aggregate_args(args, kwargs)
return super(PolymorphicQuerySet, self).annotate(*args, **kwargs)
def aggregate(self, *args, **kwargs):
"""translate the polymorphic field paths in the kwargs, then call vanilla aggregate.
We need no polymorphic object retrieval for aggregate => switch it off."""
self._process_aggregate_args(args, kwargs)
self.polymorphic_disabled = True
return super(PolymorphicQuerySet, self).aggregate(*args, **kwargs)
# Since django_polymorphic 'V1.0 beta2', extra() always returns polymorphic results.^
# The resulting objects are required to have a unique primary key within the result set
# (otherwise an error is thrown).
# The "polymorphic" keyword argument is not supported anymore.
#def extra(self, *args, **kwargs):
def _get_real_instances(self, base_result_objects):
"""
Polymorphic object loader
Does the same as:
return [ o.get_real_instance() for o in base_result_objects ]
but more efficiently.
The list base_result_objects contains the objects from the executed
base class query. The class of all of them is self.model (our base model).
Some, many or all of these objects were not created and stored as
class self.model, but as a class derived from self.model. We want to re-fetch
these objects from the db as their original class so we can return them
just as they were created/saved.
We identify these objects by looking at o.polymorphic_ctype, which specifies
the real class of these objects (the class at the time they were saved).
First, we sort the result objects in base_result_objects for their
subclass (from o.polymorphic_ctype), and then we execute one db query per
subclass of objects. Here, we handle any annotations from annotate().
Finally we re-sort the resulting objects into the correct order and
return them as a list.
"""
ordered_id_list = [] # list of ids of result-objects in correct order
results = {} # polymorphic dict of result-objects, keyed with their id (no order)
# dict contains one entry per unique model type occurring in result,
# in the format idlist_per_model[modelclass]=[list-of-object-ids]
idlist_per_model = defaultdict(list)
# - sort base_result_object ids into idlist_per_model lists, depending on their real class;
# - also record the correct result order in "ordered_id_list"
# - store objects that already have the correct class into "results"
base_result_objects_by_id = {}
self_model_content_type_id = ContentType.objects.get_for_model(self.model).pk
for base_object in base_result_objects:
ordered_id_list.append(base_object.pk)
# check if id of the result object occeres more than once - this can happen e.g. with base_objects.extra(tables=...)
assert not base_object.pk in base_result_objects_by_id, (
"django_polymorphic: result objects do not have unique primary keys - model " + unicode(self.model)
)
base_result_objects_by_id[base_object.pk] = base_object
# this object is not a derived object and already the real instance => store it right away
if (base_object.polymorphic_ctype_id == self_model_content_type_id):
results[base_object.pk] = base_object
# this object is derived and its real instance needs to be retrieved
# => store it's id into the bin for this model type
else:
idlist_per_model[base_object.get_real_instance_class()].append(base_object.pk)
# django's automatic ".pk" field does not always work correctly for
# custom fields in derived objects (unclear yet who to put the blame on).
# We get different type(o.pk) in this case.
# We work around this by using the real name of the field directly
# for accessing the primary key of the the derived objects.
# We might assume that self.model._meta.pk.name gives us the name of the primary key field,
# but it doesn't. Therefore we use polymorphic_primary_key_name, which we set up in base.py.
pk_name = self.model.polymorphic_primary_key_name
# For each model in "idlist_per_model" request its objects (the real model)
# from the db and store them in results[].
# Then we copy the annotate fields from the base objects to the real objects.
# Then we copy the extra() select fields from the base objects to the real objects.
# TODO: defer(), only(): support for these would be around here
for modelclass, idlist in idlist_per_model.items():
qs = modelclass.base_objects.filter(pk__in=idlist) # use pk__in instead ####
qs.dup_select_related(self) # copy select related configuration to new qs
for o in qs:
o_pk = getattr(o, pk_name)
if self.query.aggregates:
for anno_field_name in self.query.aggregates.keys():
attr = getattr(base_result_objects_by_id[o_pk], anno_field_name)
setattr(o, anno_field_name, attr)
if self.query.extra_select:
for select_field_name in self.query.extra_select.keys():
attr = getattr(base_result_objects_by_id[o_pk], select_field_name)
setattr(o, select_field_name, attr)
results[o_pk] = o
# re-create correct order and return result list
resultlist = [results[ordered_id] for ordered_id in ordered_id_list if ordered_id in results]
# set polymorphic_annotate_names in all objects (currently just used for debugging/printing)
if self.query.aggregates:
annotate_names = self.query.aggregates.keys() # get annotate field list
for o in resultlist:
o.polymorphic_annotate_names = annotate_names
# set polymorphic_extra_select_names in all objects (currently just used for debugging/printing)
if self.query.extra_select:
extra_select_names = self.query.extra_select.keys() # get extra select field list
for o in resultlist:
o.polymorphic_extra_select_names = extra_select_names
return resultlist
def iterator(self):
"""
This function is used by Django for all object retrieval.
By overriding it, we modify the objects that this queryset returns
when it is evaluated (or its get method or other object-returning methods are called).
Here we do the same as:
base_result_objects=list(super(PolymorphicQuerySet, self).iterator())
real_results=self._get_real_instances(base_result_objects)
for o in real_results: yield o
but it requests the objects in chunks from the database,
with Polymorphic_QuerySet_objects_per_request per chunk
"""
base_iter = super(PolymorphicQuerySet, self).iterator()
# disabled => work just like a normal queryset
if self.polymorphic_disabled:
for o in base_iter:
yield o
raise StopIteration
while True:
base_result_objects = []
reached_end = False
for i in range(Polymorphic_QuerySet_objects_per_request):
try:
o = base_iter.next()
base_result_objects.append(o)
except StopIteration:
reached_end = True
break
real_results = self._get_real_instances(base_result_objects)
for o in real_results:
yield o
if reached_end:
raise StopIteration
def __repr__(self, *args, **kwargs):
if self.model.polymorphic_query_multiline_output:
result = [repr(o) for o in self.all()]
return '[ ' + ',\n '.join(result) + ' ]'
else:
return super(PolymorphicQuerySet, self).__repr__(*args, **kwargs)
class _p_list_class(list):
def __repr__(self, *args, **kwargs):
result = [repr(o) for o in self]
return '[ ' + ',\n '.join(result) + ' ]'
def get_real_instances(self, base_result_objects=None):
"same as _get_real_instances, but make sure that __repr__ for ShowField... creates correct output"
if not base_result_objects:
base_result_objects = self
olist = self._get_real_instances(base_result_objects)
if not self.model.polymorphic_query_multiline_output:
return olist
clist = PolymorphicQuerySet._p_list_class(olist)
return clist
| {
"content_hash": "38b15a0729d261e7b86d71e8201feb3a",
"timestamp": "",
"source": "github",
"line_count": 270,
"max_line_length": 139,
"avg_line_length": 47.53703703703704,
"alnum_prop": 0.6457343202181535,
"repo_name": "sdelements/django_polymorphic",
"id": "6e397f7636f6e4d9de074b52d90d2bb9acc5540a",
"size": "12859",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "polymorphic/query.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Perl",
"bytes": "478"
},
{
"name": "Python",
"bytes": "123384"
},
{
"name": "Shell",
"bytes": "2581"
}
],
"symlink_target": ""
} |
"""
This module defines the events signaled by abinit during the execution. It also
provides a parser to extract these events form the main output file and the log file.
"""
from __future__ import unicode_literals, division, print_function
import os.path
import collections
import yaml
from monty.fnmatch import WildCard
from monty.termcolor import colored
from pymatgen.core import Structure
from pymatgen.serializers.json_coders import PMGSONable, pmg_serialize
from .abiinspect import YamlTokenizer
__all__ = [
"EventsParser",
]
def indent(lines, amount, ch=' '):
"""indent the lines in a string by padding each one with proper number of pad characters"""
padding = amount * ch
return padding + ('\n'+padding).join(lines.split('\n'))
def straceback():
"""Returns a string with the traceback."""
import traceback
return traceback.format_exc()
class AbinitEvent(yaml.YAMLObject): #, PMGSONable):
"""
Example (YAML syntax)::
Normal warning without any handler:
--- !Warning
message: |
This is a normal warning that won't
trigger any handler in the python code!
src_file: routine_name
src_line: 112
...
Critical warning that will trigger some action in the python code.
--- !ScfConvergeWarning
message: |
The human-readable message goes here!
src_file: foo.F90
src_line: 112
tolname: tolwfr
actual_tol: 1.0e-8
required_tol: 1.0e-10
nstep: 50
...
The algorithm to extract the YAML sections is very simple.
1) We use YamlTokenizer to extract the documents from the output file
2) If we have a tag that ends with "Warning", "Error", "Bug", "Comment
we know we have encountered a new ABINIT event
3) We parse the document with yaml.load(doc.text) and we get the object
Note that:
# --- and ... become reserved words (whey they are placed at
the begining of a line) since they are used to mark the beginning and
the end of YAML documents.
# All the possible events should subclass `AbinitEvent` and define
the class attribute yaml_tag so that yaml.load will know how to
build the instance.
"""
#color = None
def __init__(self, message, src_file, src_line):
"""
Basic constructor for :class:`AbinitEvent`.
Args:
message: String with human-readable message providing info on the event.
src_file: String with the name of the Fortran file where the event is raised.
src_line Integer giving the line number in src_file.
"""
self.message = message
self._src_file = src_file
self._src_line = src_line
@pmg_serialize
def as_dict(self):
return dict(message=self.message, src_file=self.src_file, src_line=self.src_line)
@classmethod
def from_dict(cls, d):
d = d.copy()
d.pop('@module', None)
d.pop('@class', None)
return cls(**d)
@property
def header(self):
return "%s at %s:%s" % (self.name, self.src_file, self.src_line)
def __str__(self):
return "\n".join((self.header, self.message))
@property
def src_file(self):
"""String with the name of the Fortran file where the event is raised."""
try:
return self._src_file
except AttributeError:
return "Unknown"
@property
def src_line(self):
"""Integer giving the line number in src_file."""
try:
return self._src_line
except AttributeError:
return "Unknown"
@property
def name(self):
"""Name of the event (class name)"""
return self.__class__.__name__
@property
def baseclass(self):
"""The baseclass of self."""
for cls in _BASE_CLASSES:
if isinstance(self, cls):
return cls
raise ValueError("Cannot determine the base class of %s" % self.__class__.__name__)
def log_correction(self, task, message):
"""
This method should be called once we have fixed the problem associated to this event.
It adds a new entry in the correction history of the task.
Args:
message (str): Human-readable string with info on the action perfomed to solve the problem.
"""
task._corrections.append(dict(
event=self.as_dict(),
message=message,
))
def correct(self, task):
"""
This method is called when an error is detected in a :class:`Task`
It should perform any corrective measures relating to the detected error.
The idea is similar to the one used in custodian but the handler receives
a :class:`Task` object so that we have access to its methods.
Returns:
(dict) JSON serializable dict that describes the errors and actions taken. E.g.
{"errors": list_of_errors, "actions": list_of_actions_taken}.
If this is an unfixable error, actions should be set to None.
"""
return 0
class AbinitComment(AbinitEvent):
"""Base class for Comment events"""
yaml_tag = '!COMMENT'
color = "blue"
class AbinitError(AbinitEvent):
"""Base class for Error events"""
yaml_tag = '!ERROR'
color = "red"
class AbinitYamlError(AbinitError):
"""Raised if the YAML parser cannot parse the document and the doc tag is an Error."""
class AbinitBug(AbinitEvent):
"""Base class for Bug events"""
yaml_tag = '!BUG'
color = "red"
class AbinitWarning(AbinitEvent):
"""
Base class for Warning events (the most important class).
Developers should subclass this class to define the different exceptions
raised by the code and the possible actions that can be performed.
"""
yaml_tag = '!WARNING'
color = None
class AbinitCriticalWarning(AbinitWarning):
color = "red"
class AbinitYamlWarning(AbinitCriticalWarning):
"""
Raised if the YAML parser cannot parse the document and the doc tas is a Warning.
"""
# Warnings that trigger restart.
class ScfConvergenceWarning(AbinitCriticalWarning):
"""Warning raised when the GS SCF cycle did not converge."""
yaml_tag = '!ScfConvergenceWarning'
class NscfConvergenceWarning(AbinitCriticalWarning):
"""Warning raised when the GS NSCF cycle did not converge."""
yaml_tag = '!NscfConvergenceWarning'
class RelaxConvergenceWarning(AbinitCriticalWarning):
"""Warning raised when the structural relaxation did not converge."""
yaml_tag = '!RelaxConvergenceWarning'
# TODO: for the time being we don't discern between GS and PhononCalculations.
#class PhononConvergenceWarning(AbinitCriticalWarning):
# """Warning raised when the phonon calculation did not converge."""
# yaml_tag = u'!PhononConvergenceWarning'
class QPSConvergenceWarning(AbinitCriticalWarning):
"""Warning raised when the QPS iteration (GW) did not converge."""
yaml_tag = '!QPSConvergenceWarning'
class HaydockConvergenceWarning(AbinitCriticalWarning):
"""Warning raised when the Haydock method (BSE) did not converge."""
yaml_tag = '!HaydockConvergenceWarning'
# Error classes providing a correct method.
class DilatmxError(AbinitError):
yaml_tag = '!DilatmxError'
def correct(self, task):
#Idea: decrease dilatxm and restart from the last structure.
#We would like to end up with a structures optimized with dilatmx 1.01
#that will be used for phonon calculations.
# Read the last structure dumped by ABINIT before aborting.
print("in dilatmx")
filepath = task.outdir.has_abiext("DILATMX_STRUCT.nc")
last_structure = Structure.from_file(filepath)
task._change_structure(last_structure)
#changes = task._modify_vars(dilatmx=1.05)
task.history.append("Take last structure from DILATMX_STRUCT.nc, will try to restart")
return 1
# Register the concrete base classes.
_BASE_CLASSES = [
AbinitComment,
AbinitError,
AbinitBug,
AbinitWarning,
]
class EventReport(collections.Iterable):
"""
Iterable storing the events raised by an ABINIT calculation.
Attributes::
stat: information about a file as returned by os.stat
"""
def __init__(self, filename, events=None):
"""
List of ABINIT events.
Args:
filename: Name of the file
events: List of Event objects
"""
self.filename = os.path.abspath(filename)
self.stat = os.stat(self.filename)
self._events = []
self._events_by_baseclass = collections.defaultdict(list)
if events is not None:
for ev in events:
self.append(ev)
def __len__(self):
return len(self._events)
def __iter__(self):
return self._events.__iter__()
def __str__(self):
#has_colours = stream_has_colours(stream)
has_colours = True
lines = []
app = lines.append
app("Events for: %s" % self.filename)
for i, event in enumerate(self):
if has_colours:
app("[%d] %s" % (i+1, colored(event.header, color=event.color)))
app(indent(event.message, 4))
else:
app("[%d] %s" % (i+1, str(event)))
app("num_errors: %s, num_warnings: %s, num_comments: %s, completed: %s" % (
self.num_errors, self.num_warnings, self.num_comments, self.run_completed))
return "\n".join(lines)
def append(self, event):
"""Add an event to the list."""
self._events.append(event)
self._events_by_baseclass[event.baseclass].append(event)
def set_run_completed(self, bool_value):
"""Set the value of _run_completed."""
self._run_completed = bool_value
@property
def run_completed(self):
"""True if the calculation terminated."""
try:
return self._run_completed
except AttributeError:
return False
@property
def comments(self):
"""List of comments found."""
return self.select(AbinitComment)
@property
def errors(self):
"""List of errors found."""
return self.select(AbinitError)
@property
def bugs(self):
"""List of bugs found."""
return self.select(AbinitBug)
@property
def warnings(self):
"""List of warnings found."""
return self.select(AbinitWarning)
@property
def num_warnings(self):
"""Number of warnings reported."""
return len(self.warnings)
@property
def num_errors(self):
"""Number of errors reported."""
return len(self.errors)
@property
def num_comments(self):
"""Number of comments reported."""
return len(self.comments)
def select(self, base_class):
"""
Return the list of events that inherits from class base_class
Args:
only_critical: if True, only critical events are returned.
"""
return self._events_by_baseclass[base_class][:]
def filter_types(self, event_types):
events = []
for ev in self:
if type(ev) in event_types: events.append(ev)
return self.__class__(filename=self.filename, events=events)
class EventsParserError(Exception):
"""Base class for the exceptions raised by :class:`EventsParser`."""
class EventsParser(object):
"""
Parses the output or the log file produced by abinit and extract the list of events.
"""
Error = EventsParserError
# Internal flag used for debugging
DEBUG_LEVEL = 0
def parse(self, filename):
"""
Parse the given file. Return :class:`EventReport`.
"""
run_completed = False
filename = os.path.abspath(filename)
report = EventReport(filename)
# TODO Use CamelCase for the Fortran messages.
# Bug is still an error of class SoftwareError
w = WildCard("*Error|*Warning|*Comment|*Bug|*ERROR|*WARNING|*COMMENT|*BUG")
with YamlTokenizer(filename) as tokens:
for doc in tokens:
#print(80*"*")
#print("doc.tag", doc.tag)
#print("doc", doc)
#print(80*"*")
if w.match(doc.tag):
#print("got doc.tag", doc.tag,"--")
try:
event = yaml.load(doc.text)
except:
# Wrong YAML doc. Check tha doc tag and instantiate the proper event.
message = "Malformatted YAML document at line: %d\n" % doc.lineno
message += doc.text
# This call is very expensive when we have many exceptions due to malformatted YAML docs.
if self.DEBUG_LEVEL:
message += "Traceback:\n %s" % straceback()
if "error" in doc.tag.lower():
print("It seems an error", doc.tag)
event = AbinitYamlError(message=message, src_file=__file__, src_line=0)
else:
event = AbinitYamlWarning(message=message, src_file=__file__, src_line=0)
event.lineno = doc.lineno
report.append(event)
# Check whether the calculation completed.
if doc.tag == "!FinalSummary":
run_completed = True
report.set_run_completed(run_completed)
return report
def report_exception(self, filename, exc):
"""
This method is used when self.parser raises an Exception so that
we can report a customized :class:`EventReport` object with info the exception.
"""
return EventReport(filename, events=[AbinitError(str(exc))])
| {
"content_hash": "66de4d2df2f47e17e8fb438c86cf2ec9",
"timestamp": "",
"source": "github",
"line_count": 458,
"max_line_length": 113,
"avg_line_length": 30.716157205240176,
"alnum_prop": 0.6091839636053454,
"repo_name": "ctoher/pymatgen",
"id": "ca50568ff945389e6b8b31e251cc3f16ea281e3c",
"size": "14084",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "pymatgen/io/abinitio/events.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Common Lisp",
"bytes": "3029065"
},
{
"name": "Groff",
"bytes": "868"
},
{
"name": "Perl",
"bytes": "229104"
},
{
"name": "Propeller Spin",
"bytes": "4026362"
},
{
"name": "Python",
"bytes": "3688213"
}
],
"symlink_target": ""
} |
"""Render the category pages and feeds."""
from __future__ import unicode_literals
from nikola.plugin_categories import Taxonomy
from nikola import utils
class ClassifyCategories(Taxonomy):
"""Classify the posts by categories."""
name = "classify_categories"
classification_name = "category"
overview_page_variable_name = "categories"
overview_page_items_variable_name = "cat_items"
overview_page_hierarchy_variable_name = "cat_hierarchy"
more_than_one_classifications_per_post = False
has_hierarchy = True
include_posts_from_subhierarchies = True
include_posts_into_hierarchy_root = False
show_list_as_subcategories_list = False
generate_atom_feeds_for_post_lists = True
template_for_classification_overview = "tags.tmpl"
always_disable_rss = False
apply_to_posts = True
apply_to_pages = False
minimum_post_count_per_classification_in_overview = 1
omit_empty_classifications = True
also_create_classifications_from_other_languages = True
path_handler_docstrings = {
'category_index': """A link to the category index.
Example:
link://category_index => /categories/index.html""",
'category': """A link to a category. Takes page number as optional keyword argument.
Example:
link://category/dogs => /categories/dogs.html""",
'category_atom': """A link to a category's Atom feed.
Example:
link://category_atom/dogs => /categories/dogs.atom""",
'category_rss': """A link to a category's RSS feed.
Example:
link://category_rss/dogs => /categories/dogs.xml""",
}
def set_site(self, site):
"""Set site, which is a Nikola instance."""
super(ClassifyCategories, self).set_site(site)
self.show_list_as_index = self.site.config['CATEGORY_PAGES_ARE_INDEXES']
self.template_for_single_list = "tagindex.tmpl" if self.show_list_as_index else "tag.tmpl"
def is_enabled(self, lang=None):
"""Return True if this taxonomy is enabled, or False otherwise."""
return True
def classify(self, post, lang):
"""Classify the given post for the given language."""
cat = post.meta('category', lang=lang).strip()
return [cat] if cat else []
def get_classification_friendly_name(self, classification, lang, only_last_component=False):
"""Extract a friendly name from the classification."""
classification = self.extract_hierarchy(classification)
return classification[-1] if classification else ''
def get_overview_path(self, lang, dest_type='page'):
"""A path handler for the list of all classifications."""
if self.site.config['CATEGORIES_INDEX_PATH'](lang):
return [_f for _f in [self.site.config['CATEGORIES_INDEX_PATH'](lang)] if _f], 'never'
else:
return [_f for _f in [self.site.config['CATEGORY_PATH'](lang)] if _f], 'always'
def slugify_tag_name(self, name, lang):
"""Slugify a tag name."""
if self.site.config['SLUG_TAG_PATH']:
name = utils.slugify(name, lang)
return name
def slugify_category_name(self, path, lang):
"""Slugify a category name."""
if lang is None: # TODO: remove in v8
utils.LOGGER.warn("ClassifyCategories.slugify_category_name() called without language!")
lang = ''
if self.site.config['CATEGORY_OUTPUT_FLAT_HIERARCHY']:
path = path[-1:] # only the leaf
result = [self.slugify_tag_name(part, lang) for part in path]
result[0] = self.site.config['CATEGORY_PREFIX'] + result[0]
if not self.site.config['PRETTY_URLS']:
result = ['-'.join(result)]
return result
def get_path(self, classification, lang, dest_type='page'):
"""A path handler for the given classification."""
return [_f for _f in [self.site.config['CATEGORY_PATH'](lang)] if _f] + self.slugify_category_name(classification, lang), 'auto'
def extract_hierarchy(self, classification):
"""Given a classification, return a list of parts in the hierarchy."""
return utils.parse_escaped_hierarchical_category_name(classification)
def recombine_classification_from_hierarchy(self, hierarchy):
"""Given a list of parts in the hierarchy, return the classification string."""
return utils.join_hierarchical_category_path(hierarchy)
def provide_overview_context_and_uptodate(self, lang):
"""Provide data for the context and the uptodate list for the list of all classifiations."""
kw = {
'category_path': self.site.config['CATEGORY_PATH'],
'category_prefix': self.site.config['CATEGORY_PREFIX'],
"category_pages_are_indexes": self.site.config['CATEGORY_PAGES_ARE_INDEXES'],
"tzinfo": self.site.tzinfo,
"category_pages_descriptions": self.site.config['CATEGORY_PAGES_DESCRIPTIONS'],
"category_pages_titles": self.site.config['CATEGORY_PAGES_TITLES'],
}
context = {
"title": self.site.MESSAGES[lang]["Categories"],
"description": self.site.MESSAGES[lang]["Categories"],
"pagekind": ["list", "tags_page"],
}
kw.update(context)
return context, kw
def provide_context_and_uptodate(self, cat, lang, node=None):
"""Provide data for the context and the uptodate list for the list of the given classifiation."""
cat_path = self.extract_hierarchy(cat)
kw = {
'category_path': self.site.config['CATEGORY_PATH'],
'category_prefix': self.site.config['CATEGORY_PREFIX'],
"category_pages_are_indexes": self.site.config['CATEGORY_PAGES_ARE_INDEXES'],
"tzinfo": self.site.tzinfo,
"category_pages_descriptions": self.site.config['CATEGORY_PAGES_DESCRIPTIONS'],
"category_pages_titles": self.site.config['CATEGORY_PAGES_TITLES'],
}
posts = self.site.posts_per_classification[self.classification_name][lang]
children = [child for child in node.children if len([post for post in posts.get(child.classification_name, []) if self.site.config['SHOW_UNTRANSLATED_POSTS'] or post.is_translation_available(lang)]) > 0]
subcats = [(child.name, self.site.link(self.classification_name, child.classification_name, lang), child.classification_name, child.classification_path) for child in children]
friendly_name = self.get_classification_friendly_name(cat, lang)
context = {
"title": self.site.config['CATEGORY_PAGES_TITLES'].get(lang, {}).get(cat, self.site.MESSAGES[lang]["Posts about %s"] % friendly_name),
"description": self.site.config['CATEGORY_PAGES_DESCRIPTIONS'].get(lang, {}).get(cat),
"kind": "category",
"pagekind": ["tag_page", "index" if self.show_list_as_index else "list"],
"tag": friendly_name,
"category": cat,
"category_path": cat_path,
"subcategories": subcats,
}
if self.show_list_as_index:
context["rss_link"] = """<link rel="alternate" type="application/rss+xml" type="application/rss+xml" title="RSS for tag {0} ({1})" href="{2}">""".format(friendly_name, lang, self.site.link("category_rss", cat, lang))
kw.update(context)
return context, kw
| {
"content_hash": "c7cfc45060bf2dd6aab2a6c00b712ee0",
"timestamp": "",
"source": "github",
"line_count": 158,
"max_line_length": 228,
"avg_line_length": 46.56962025316456,
"alnum_prop": 0.646371296547975,
"repo_name": "knowsuchagency/nikola",
"id": "2f157cafce32684074c732daf8479d838971b83e",
"size": "8500",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nikola/plugins/task/categories.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "18794"
},
{
"name": "JavaScript",
"bytes": "24667"
},
{
"name": "Python",
"bytes": "1169446"
},
{
"name": "Shell",
"bytes": "11217"
},
{
"name": "XSLT",
"bytes": "3619"
}
],
"symlink_target": ""
} |
from abc import ABCMeta, abstractmethod
import os, math,sys, random
import numpy as np
import theano
import theano.tensor as T
from config import dataset_params
from printing import print_section, print_error
from augmenter.aerial import Creator
class DataLoader:
'''
Loads a class based on value in config.
'''
@staticmethod
def create():
'''
Factory method create object by a string argument found in the
config file. The config must specify the correct class name of the loader class that should be initialized.
'''
loader = dataset_params.loader
return getattr(sys.modules[__name__], loader)()
class AbstractDataset(object):
'''
All dataloader should inherit from this class. Implements chunking of the dataset. For instance, subsets of examples
are loaded onto GPU iteratively during an epoch. This also includes a chunk switching method.
'''
__metaclass__ = ABCMeta
def __init__(self):
self.set = {
'train': None,
'validation': None,
'test': None,
}
self.all_training = []
self.active = []
self.all_shared_hooks = [] #WHen casted, cannot set_value on them
self.nr_examples = {}
@abstractmethod
def load(self, dataset_path):
"""Loading and transforming logic for dataset"""
return
def destroy(self):
#Remove contents from GPU
#TODO: symbolic cast operation, makes set_value not possible.
for key in self.set:
self.set[key][0].set_value([[]])
#self.set[key][1].set_value([[]])
for hook in self.all_shared_hooks:
hook.set_value([[]])
del self.all_training
del self.active
def get_chunk_number(self):
return len(self.all_training)
def get_elements(self, idx):
return len(self.all_training[idx][0])
def get_total_number_of_batches(self, batch_size):
s = sum(len(c[0]) for c in self.all_training)
return math.ceil(s/batch_size)
def _chunkify(self, dataset, nr_of_chunks, batch_size):
#Round items per chunk down until there is an exact number of minibatches. Multiple of batch_size
items_per_chunk = len(dataset[0])/ nr_of_chunks
if(items_per_chunk < batch_size):
print_error('Chunk limit in config set to small, or batch size to large. \n'
'Each chunk must include at least one batch.')
raise Exception('Fix chunk_size and batch_size')
temp = int(items_per_chunk / batch_size)
items_per_chunk = batch_size * temp
data, labels = dataset
#TODO:do floatX operation twice.
chunks = [[AbstractDataset._floatX(data[x:x+items_per_chunk]), AbstractDataset._floatX(labels[x:x+items_per_chunk])]
for x in xrange(0, len(dataset[0]), items_per_chunk)]
#If the last chunk is less than batch size, it is cut. No reason for an unnecessary swap.
last_chunk_size = len(chunks[-1][0])
#TODO: Quick fix
if(last_chunk_size < batch_size*15):
chunks.pop(-1)
print('---- Removed last chunk. '
'{} elements not enough for at least one minibatch of {}'.format(last_chunk_size, batch_size))
return chunks
def set_nr_examples(self, train, valid, test):
self.nr_examples['train'] = train[0].shape[0]
self.nr_examples['valid'] = valid[0].shape[0]
self.nr_examples['test'] = test[0].shape[0]
def get_report(self):
return self.nr_examples
def switch_active_training_set(self, idx):
'''
Each epoch a large number of examples will be seen by model. Often all examples will not fit on the GPU at
the same time. This method, switches the data that are currently reciding in the gpu. Will be called
nr_of_chunks times per epoch.
'''
#print('---- Changing active chunk') #This works very well so no need to print it all the time
new_chunk_x, new_chunk_y = self.all_training[idx]
self.active[0].set_value(new_chunk_x)
self.active[1].set_value(new_chunk_y)
def shared_dataset(self, data_xy, borrow=True, cast_to_int=True):
#Stored in theano shared variable to allow Theano to copy it into GPU memory
data_x, data_y = data_xy
print(data_x.shape)
print(data_y.shape)
shared_x = theano.shared(AbstractDataset._floatX(data_x), borrow=borrow)
shared_y = theano.shared(AbstractDataset._floatX(data_y), borrow=borrow)
self.all_shared_hooks.append(shared_y)
if cast_to_int:
print("---- Casted to int")
#Since labels are index integers they have to be treated as such during computations.
#Shared_y is therefore cast to int.
return shared_x, T.cast(shared_y, 'int32')
else:
return shared_x, shared_y
@staticmethod
def _floatX(d):
#Creates a data representation suitable for GPU
return np.asarray(d, dtype=theano.config.floatX)
@staticmethod
def _get_file_path(dataset):
data_dir, data_file = os.path.split(dataset)
#TODO: Add some robustness, like checking if file is folder and correct that
assert os.path.isfile(dataset)
return dataset
@staticmethod
def dataset_check(name, dataset, batch_size):
#If there are are to few examples for at least one batch, the dataset is invalid.
if len(dataset[0]) < batch_size:
print_error('Insufficent examples in {}. '
'{} examples not enough for at least one minibatch'.format(name, len(dataset[0])))
raise Exception('Decrease batch_size or increase samples_per_image')
@staticmethod
def dataset_sizes(train, valid, test, chunks):
mb = 1000000.0
train_size = sum(data.nbytes for data in train) / mb
valid_size = sum(data.nbytes for data in valid) / mb
test_size = sum(data.nbytes for data in test) / mb
nr_of_chunks = math.ceil(train_size/chunks)
print('---- Minimum number of training chunks: {}'.format(nr_of_chunks))
print('---- Dataset at least:')
print('---- Training: \t {}mb'.format(train_size))
print('---- Validation: {}mb'.format(valid_size))
print('---- Testing: \t {}mb'.format(test_size))
return nr_of_chunks
@staticmethod
def dataset_shared_stats(image_shape, label_shape, chunks):
print('')
print('Preparing shared variables for datasets')
print('---- Image data shape: {}, label data shape: {}'.format(image_shape, label_shape))
print('---- Max chunk size of {}mb'.format(chunks))
@staticmethod
def dataset_chunk_stats(nr_training_chunks, elements_pr_chunk, elements_last_chunk):
print('---- Actual number of training chunks: {}'.format(nr_training_chunks))
print('---- Elements per chunk: {}'.format(elements_pr_chunk))
print('---- Last chunk size: {}'.format(elements_last_chunk))
class AerialCurriculumDataset(AbstractDataset):
'''
Data loader for pre-generated dataset. IE, curriculum learning and datasets too big to fit in main memory.
The class includes a method for stage switching and mixing. this method switches the training set and
control the behavior of the switch.
'''
def load_set(self, path, set, stage=None):
base_path = ""
if stage != None:
base_path = os.path.join(path, set, stage)
else:
base_path = os.path.join(path, set)
labels = np.load(os.path.join(base_path, "labels", "examples.npy"))
data = np.load(os.path.join(base_path, "data", "examples.npy"))
return data, labels
def mix_in_next_stage(self):
self.stage += 1
if self.nr_of_stages <= self.stage:
#print("temporary looping through stages")
#self.stage = 1
print("No more stages available")
return
current_stage = "stage{}".format(self.stage)
labels = np.load(os.path.join(self.stage_path, current_stage, "labels", "examples.npy"))
data = np.load(os.path.join(self.stage_path, current_stage, "data", "examples.npy"))
print("---- Mixing in {} with {} examples".format(current_stage, data.shape[0]))
if not dataset_params.with_replacement:
elements = data.shape[0]
shuffle_counter = 0
shuffled_index = range(elements)
random.shuffle(shuffled_index)
#print (len(shuffled_index))
for c in range(len(self.all_training)):
nr_chunk_examples = self.all_training[c][0].shape[0]
for x in range(nr_chunk_examples ):
if shuffle_counter < elements:
i = shuffled_index.pop()
#print(c, x, i)
self.all_training[c][0][x] = data[i]
self.all_training[c][1][x] = labels[i]
else:
break
shuffle_counter += 1
else:
nr_chunks = len(self.all_training)
for i in range(data.shape[0]):
c = random.randint(0,nr_chunks-1)
nr_chunk_examples = self.all_training[c][0].shape[0]
x = random.randint(0, nr_chunk_examples-1)
self.all_training[c][0][x] = data[i]
self.all_training[c][1][x] = labels[i]
def load(self, dataset_path, params, batch_size=1):
print_section('Loading aerial curriculum dataset')
chunks = params.chunk_size
self.std = params.dataset_std #Need for debug
#For later stage loading
self.stage = 0
self.stage_path = os.path.join(dataset_path, "train")
self.nr_of_stages = len(os.listdir(os.path.join(dataset_path, "train")))
train = self.load_set(dataset_path, "train", stage="stage{}".format(self.stage))
valid = self.load_set(dataset_path, "valid")
test = self.load_set(dataset_path, "test")
#Testing dataset size requirements
AerialCurriculumDataset.dataset_check('train', train, batch_size)
AerialCurriculumDataset.dataset_check('valid', valid, batch_size)
AerialCurriculumDataset.dataset_check('test', test, batch_size)
AerialCurriculumDataset.dataset_shared_stats(train[0].shape, train[1].shape, chunks)
self.set_nr_examples(train, valid, test)
nr_of_chunks = AerialCurriculumDataset.dataset_sizes(train, valid, test, chunks)
training_chunks = self._chunkify(train, nr_of_chunks, batch_size)
AerialCurriculumDataset.dataset_chunk_stats(len(training_chunks), len(training_chunks[0][0]), len(training_chunks[-1][0]))
self.active = self.shared_dataset(training_chunks[0], cast_to_int=False)
self.set['train'] = self.active[0], T.cast(self.active[1], 'int32')
self.set['validation'] = self.shared_dataset(valid, cast_to_int=True )
self.set['test'] = self.shared_dataset(test, cast_to_int=True)
#Not stored on the GPU, unlike the shared variables defined above.
self.all_training = training_chunks
return True
class AerialDataset(AbstractDataset):
'''
Dataset loader. This class does not load a pre-generated patch dataset. Instead, it creates patch datasets from
the aerial image dataset via the Creator class. This class samples a certain number of patches from each aerial
image.
'''
def load(self, dataset_path, params, batch_size=1):
print_section('Creating aerial image dataset')
self.std = params.dataset_std
chunks = params.chunk_size
#TODO: ensure that the dataset is as expected.
creator = Creator(dataset_path,
dim=(params.input_dim, params.output_dim),
rotation=params.use_rotation,
preproccessing=params.use_preprocessing,
std=self.std,
only_mixed=params.only_mixed_labels,
reduce_testing=params.reduce_testing,
reduce_training=params.reduce_training,
reduce_validation=params.reduce_validation)
train, valid, test = creator.dynamically_create(
params.samples_per_image,
enable_label_noise=params.use_label_noise,
label_noise=params.label_noise,
only_mixed=params.only_mixed_labels
)
#Testing dataset size requirements
AerialDataset.dataset_check('train', train, batch_size)
AerialDataset.dataset_check('valid', valid, batch_size)
AerialDataset.dataset_check('test', test, batch_size)
AerialDataset.dataset_shared_stats(train[0].shape, train[1].shape, chunks)
self.set_nr_examples(train, valid, test)
nr_of_chunks = AerialDataset.dataset_sizes(train, valid, test, chunks)
training_chunks = self._chunkify(train, nr_of_chunks, batch_size)
AerialDataset.dataset_chunk_stats(len(training_chunks), len(training_chunks[0][0]), len(training_chunks[-1][0]))
self.active = self.shared_dataset(training_chunks[0], cast_to_int=False)
self.set['train'] = self.active[0], T.cast(self.active[1], 'int32')
self.set['validation'] = self.shared_dataset(valid, cast_to_int=True )
self.set['test'] = self.shared_dataset(test, cast_to_int=True)
#Not stored on the GPU, unlike the shared variables defined above.
self.all_training = training_chunks
return True
| {
"content_hash": "42ff2afbfe52d9572712bf4eac7b34f0",
"timestamp": "",
"source": "github",
"line_count": 342,
"max_line_length": 130,
"avg_line_length": 40.32163742690059,
"alnum_prop": 0.6128353879622915,
"repo_name": "olavvatne/CNN",
"id": "db1c25cc2086786747375b95ed98b3d40c13e5ce",
"size": "13790",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "data.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "88387"
},
{
"name": "Shell",
"bytes": "822"
}
],
"symlink_target": ""
} |
'''Unit tests for models and their factories.'''
import mock
import unittest
from nose.tools import * # noqa (PEP8 asserts)
import pytz
import datetime
import urlparse
import itsdangerous
import random
import string
from dateutil import parser
from modularodm import Q
from modularodm.exceptions import ValidationError, ValidationValueError, ValidationTypeError
from framework.analytics import get_total_activity_count
from framework.exceptions import PermissionsError
from framework.auth import User, Auth
from framework.auth import cas
from framework.sessions.model import Session
from framework.auth import exceptions as auth_exc
from framework.auth.exceptions import ChangePasswordError, ExpiredTokenError
from framework.auth.utils import impute_names_model
from framework.auth.signals import user_merged
from framework.tasks import handlers
from framework.bcrypt import check_password_hash
from website import filters, language, settings, mailchimp_utils
from website.exceptions import NodeStateError
from website.profile.utils import serialize_user
from website.project.signals import contributor_added
from website.project.model import (
Node, NodeLog, Pointer, ensure_schemas, has_anonymous_link,
get_pointer_parent, Embargo, MetaSchema, DraftRegistration
)
from website.util.permissions import (
CREATOR_PERMISSIONS,
ADMIN,
READ,
WRITE,
DEFAULT_CONTRIBUTOR_PERMISSIONS,
expand_permissions,
)
from website.util import web_url_for, api_url_for
from website.addons.wiki.exceptions import (
NameEmptyError,
NameInvalidError,
NameMaximumLengthError,
PageCannotRenameError,
PageConflictError,
PageNotFoundError,
)
from tests.base import OsfTestCase, Guid, fake, capture_signals, get_default_metaschema
from tests.factories import (
UserFactory, ApiOAuth2ApplicationFactory, NodeFactory, PointerFactory,
ProjectFactory, NodeLogFactory, WatchConfigFactory,
NodeWikiFactory, RegistrationFactory, UnregUserFactory,
ProjectWithAddonFactory, UnconfirmedUserFactory, PrivateLinkFactory,
AuthUserFactory, DashboardFactory, FolderFactory,
NodeLicenseRecordFactory, InstitutionFactory
)
from tests.test_features import requires_piwik
from tests.utils import mock_archive
GUID_FACTORIES = UserFactory, NodeFactory, ProjectFactory
class TestUserValidation(OsfTestCase):
def setUp(self):
super(TestUserValidation, self).setUp()
self.user = AuthUserFactory()
def test_validate_fullname_none(self):
self.user.fullname = None
with assert_raises(ValidationError):
self.user.save()
def test_validate_fullname_empty(self):
self.user.fullname = ''
with assert_raises(ValidationValueError):
self.user.save()
def test_validate_social_profile_websites_empty(self):
self.user.social = {'profileWebsites': []}
self.user.save()
assert_equal(self.user.social['profileWebsites'], [])
def test_validate_social_valid(self):
self.user.social = {'profileWebsites': ['http://cos.io/']}
self.user.save()
assert_equal(self.user.social['profileWebsites'], ['http://cos.io/'])
def test_validate_multiple_profile_websites_valid(self):
self.user.social = {'profileWebsites': ['http://cos.io/', 'http://thebuckstopshere.com', 'http://dinosaurs.com']}
self.user.save()
assert_equal(self.user.social['profileWebsites'], ['http://cos.io/', 'http://thebuckstopshere.com', 'http://dinosaurs.com'])
def test_validate_social_profile_websites_invalid(self):
self.user.social = {'profileWebsites': ['help computer']}
with assert_raises(ValidationError):
self.user.save()
def test_validate_multiple_profile_social_profile_websites_invalid(self):
self.user.social = {'profileWebsites': ['http://cos.io/', 'help computer', 'http://dinosaurs.com']}
with assert_raises(ValidationError):
self.user.save()
def test_empty_social_links(self):
assert_equal(self.user.social_links, {})
assert_equal(len(self.user.social_links), 0)
def test_profile_website_unchanged(self):
self.user.social = {'profileWebsites': ['http://cos.io/']}
self.user.save()
assert_equal(self.user.social_links['profileWebsites'], ['http://cos.io/'])
assert_equal(len(self.user.social_links), 1)
def test_various_social_handles(self):
self.user.social = {
'profileWebsites': ['http://cos.io/'],
'twitter': 'OSFramework',
'github': 'CenterForOpenScience'
}
self.user.save()
assert_equal(self.user.social_links, {
'profileWebsites': ['http://cos.io/'],
'twitter': 'http://twitter.com/OSFramework',
'github': 'http://github.com/CenterForOpenScience'
})
def test_multiple_profile_websites(self):
self.user.social = {
'profileWebsites': ['http://cos.io/', 'http://thebuckstopshere.com', 'http://dinosaurs.com'],
'twitter': 'OSFramework',
'github': 'CenterForOpenScience'
}
self.user.save()
assert_equal(self.user.social_links, {
'profileWebsites': ['http://cos.io/', 'http://thebuckstopshere.com', 'http://dinosaurs.com'],
'twitter': 'http://twitter.com/OSFramework',
'github': 'http://github.com/CenterForOpenScience'
})
def test_nonsocial_ignored(self):
self.user.social = {
'foo': 'bar',
}
self.user.save()
assert_equal(self.user.social_links, {})
def test_validate_jobs_valid(self):
self.user.jobs = [{
'institution': 'School of Lover Boys',
'department': 'Fancy Patter',
'title': 'Lover Boy',
'startMonth': 1,
'startYear': '1970',
'endMonth': 1,
'endYear': '1980',
}]
self.user.save()
def test_validate_jobs_institution_empty(self):
self.user.jobs = [{'institution': ''}]
with assert_raises(ValidationError):
self.user.save()
def test_validate_jobs_bad_end_date(self):
# end year is < start year
self.user.jobs = [{
'institution': fake.company(),
'department': fake.bs(),
'position': fake.catch_phrase(),
'startMonth': 1,
'startYear': '1970',
'endMonth': 1,
'endYear': '1960',
}]
with assert_raises(ValidationValueError):
self.user.save()
def test_validate_schools_bad_end_date(self):
# end year is < start year
self.user.schools = [{
'degree': fake.catch_phrase(),
'institution': fake.company(),
'department': fake.bs(),
'startMonth': 1,
'startYear': '1970',
'endMonth': 1,
'endYear': '1960',
}]
with assert_raises(ValidationValueError):
self.user.save()
def test_validate_jobs_bad_year(self):
start_year = ['hi', '20507', '99', '67.34']
for year in start_year:
self.user.jobs = [{
'institution': fake.company(),
'department': fake.bs(),
'position': fake.catch_phrase(),
'startMonth': 1,
'startYear': year,
'endMonth': 1,
'endYear': '1960',
}]
with assert_raises(ValidationValueError):
self.user.save()
def test_validate_schools_bad_year(self):
start_year = ['hi', '20507', '99', '67.34']
for year in start_year:
self.user.schools = [{
'degree': fake.catch_phrase(),
'institution': fake.company(),
'department': fake.bs(),
'startMonth': 1,
'startYear': year,
'endMonth': 1,
'endYear': '1960',
}]
with assert_raises(ValidationValueError):
self.user.save()
class TestUser(OsfTestCase):
def setUp(self):
super(TestUser, self).setUp()
self.user = UserFactory()
self.auth = Auth(user=self.user)
def test_repr(self):
assert_in(self.user.username, repr(self.user))
assert_in(self.user._id, repr(self.user))
def test_update_guessed_names(self):
name = fake.name()
u = User(fullname=name)
u.update_guessed_names()
u.save()
parsed = impute_names_model(name)
assert_equal(u.fullname, name)
assert_equal(u.given_name, parsed['given_name'])
assert_equal(u.middle_names, parsed['middle_names'])
assert_equal(u.family_name, parsed['family_name'])
assert_equal(u.suffix, parsed['suffix'])
def test_non_registered_user_is_not_active(self):
u = User(username=fake.email(),
fullname='Freddie Mercury',
is_registered=False)
u.set_password('killerqueen')
u.save()
assert_false(u.is_active)
def test_create_unregistered(self):
name, email = fake.name(), fake.email()
u = User.create_unregistered(email=email,
fullname=name)
u.save()
assert_equal(u.username, email)
assert_false(u.is_registered)
assert_false(u.is_claimed)
assert_true(u.is_invited)
assert_false(email in u.emails)
parsed = impute_names_model(name)
assert_equal(u.given_name, parsed['given_name'])
@mock.patch('framework.auth.core.User.update_search')
def test_search_not_updated_for_unreg_users(self, update_search):
u = User.create_unregistered(fullname=fake.name(), email=fake.email())
u.save()
assert not update_search.called
@mock.patch('framework.auth.core.User.update_search')
def test_search_updated_for_registered_users(self, update_search):
UserFactory(is_registered=True)
assert_true(update_search.called)
def test_create_unregistered_raises_error_if_already_in_db(self):
u = UnregUserFactory()
dupe = User.create_unregistered(fullname=fake.name(), email=u.username)
with assert_raises(ValidationValueError):
dupe.save()
def test_user_with_no_password_is_not_active(self):
u = User(
username=fake.email(),
fullname='Freddie Mercury',
is_registered=True,
)
u.save()
assert_false(u.is_active)
def test_merged_user_is_not_active(self):
master = UserFactory()
dupe = UserFactory(merged_by=master)
assert_false(dupe.is_active)
def test_merged_user_with_two_account_on_same_project_with_different_visibility_and_permissions(self):
user2 = UserFactory.build()
user2.save()
project = ProjectFactory(is_public=True)
# Both the master and dupe are contributors
project.add_contributor(user2, log=False)
project.add_contributor(self.user, log=False)
project.set_permissions(user=self.user, permissions=['read'])
project.set_permissions(user=user2, permissions=['read', 'write', 'admin'])
project.set_visible(user=self.user, visible=False)
project.set_visible(user=user2, visible=True)
project.save()
self.user.merge_user(user2)
self.user.save()
project.reload()
assert_true('admin' in project.permissions[self.user._id])
assert_true(self.user._id in project.visible_contributor_ids)
assert_false(project.is_contributor(user2))
def test_cant_create_user_without_username(self):
u = User() # No username given
with assert_raises(ValidationError):
u.save()
def test_date_registered_upon_saving(self):
u = User(username=fake.email(), fullname='Foo bar')
u.save()
assert_true(u.date_registered)
def test_create(self):
name, email = fake.name(), fake.email()
user = User.create(
username=email, password='foobar', fullname=name
)
user.save()
assert_true(user.check_password('foobar'))
assert_true(user._id)
assert_equal(user.given_name, impute_names_model(name)['given_name'])
def test_create_unconfirmed(self):
name, email = fake.name(), fake.email()
user = User.create_unconfirmed(
username=email, password='foobar', fullname=name
)
user.save()
assert_false(user.is_registered)
assert_equal(len(user.email_verifications.keys()), 1)
assert_equal(
len(user.emails),
0,
'primary email has not been added to emails list'
)
def test_create_confirmed(self):
name, email = fake.name(), fake.email()
user = User.create_confirmed(
username=email, password='foobar', fullname=name
)
user.save()
assert_true(user.is_registered)
assert_true(user.is_claimed)
assert_equal(user.date_registered, user.date_confirmed)
def test_cant_create_user_without_full_name(self):
u = User(username=fake.email())
with assert_raises(ValidationError):
u.save()
@mock.patch('website.security.random_string')
def test_add_unconfirmed_email(self, random_string):
token = fake.lexify('???????')
random_string.return_value = token
u = UserFactory()
assert_equal(len(u.email_verifications.keys()), 0)
u.add_unconfirmed_email('foo@bar.com')
assert_equal(len(u.email_verifications.keys()), 1)
assert_equal(u.email_verifications[token]['email'], 'foo@bar.com')
@mock.patch('website.security.random_string')
def test_add_unconfirmed_email_adds_expiration_date(self, random_string):
token = fake.lexify('???????')
random_string.return_value = token
u = UserFactory()
u.add_unconfirmed_email("test@osf.io")
assert_is_instance(u.email_verifications[token]['expiration'], datetime.datetime)
def test_add_blank_unconfirmed_email(self):
with assert_raises(ValidationError) as exc_info:
self.user.add_unconfirmed_email('')
assert_equal(exc_info.exception.message, "Invalid Email")
@mock.patch('website.security.random_string')
def test_get_confirmation_token(self, random_string):
random_string.return_value = '12345'
u = UserFactory()
u.add_unconfirmed_email('foo@bar.com')
assert_equal(u.get_confirmation_token('foo@bar.com'), '12345')
assert_equal(u.get_confirmation_token('fOo@bar.com'), '12345')
def test_get_confirmation_token_when_token_is_expired_raises_error(self):
u = UserFactory()
# Make sure token is already expired
expiration = datetime.datetime.utcnow() - datetime.timedelta(seconds=1)
u.add_unconfirmed_email('foo@bar.com', expiration=expiration)
with assert_raises(ExpiredTokenError):
u.get_confirmation_token('foo@bar.com')
@mock.patch('website.security.random_string')
def test_get_confirmation_token_when_token_is_expired_force(self, random_string):
random_string.return_value = '12345'
u = UserFactory()
# Make sure token is already expired
expiration = datetime.datetime.utcnow() - datetime.timedelta(seconds=1)
u.add_unconfirmed_email('foo@bar.com', expiration=expiration)
# sanity check
with assert_raises(ExpiredTokenError):
u.get_confirmation_token('foo@bar.com')
random_string.return_value = '54321'
token = u.get_confirmation_token('foo@bar.com', force=True)
assert_equal(token, '54321')
# Some old users will not have an 'expired' key in their email_verifications.
# Assume the token in expired
def test_get_confirmation_token_if_email_verification_doesnt_have_expiration(self):
u = UserFactory()
email = fake.email()
u.add_unconfirmed_email(email)
# manually remove 'expiration' key
token = u.get_confirmation_token(email)
del u.email_verifications[token]['expiration']
u.save()
with assert_raises(ExpiredTokenError):
u.get_confirmation_token(email)
@mock.patch('website.security.random_string')
def test_get_confirmation_url(self, random_string):
random_string.return_value = 'abcde'
u = UserFactory()
u.add_unconfirmed_email('foo@bar.com')
assert_equal(u.get_confirmation_url('foo@bar.com'),
'{0}confirm/{1}/{2}/'.format(settings.DOMAIN, u._primary_key, 'abcde'))
def test_get_confirmation_url_when_token_is_expired_raises_error(self):
u = UserFactory()
# Make sure token is already expired
expiration = datetime.datetime.utcnow() - datetime.timedelta(seconds=1)
u.add_unconfirmed_email('foo@bar.com', expiration=expiration)
with assert_raises(ExpiredTokenError):
u.get_confirmation_url('foo@bar.com')
@mock.patch('website.security.random_string')
def test_get_confirmation_url_when_token_is_expired_force(self, random_string):
random_string.return_value = '12345'
u = UserFactory()
# Make sure token is already expired
expiration = datetime.datetime.utcnow() - datetime.timedelta(seconds=1)
u.add_unconfirmed_email('foo@bar.com', expiration=expiration)
# sanity check
with assert_raises(ExpiredTokenError):
u.get_confirmation_token('foo@bar.com')
random_string.return_value = '54321'
url = u.get_confirmation_url('foo@bar.com', force=True)
expected = '{0}confirm/{1}/{2}/'.format(settings.DOMAIN, u._primary_key, '54321')
assert_equal(url, expected)
def test_confirm_primary_email(self):
u = UnconfirmedUserFactory()
token = u.get_confirmation_token(u.username)
confirmed = u.confirm_email(token)
u.save()
assert_true(confirmed)
assert_equal(len(u.email_verifications.keys()), 0)
assert_in(u.username, u.emails)
assert_true(u.is_registered)
assert_true(u.is_claimed)
def test_verify_confirmation_token(self):
u = UserFactory.build()
u.add_unconfirmed_email('foo@bar.com')
u.save()
with assert_raises(auth_exc.InvalidTokenError):
u._get_unconfirmed_email_for_token('badtoken')
valid_token = u.get_confirmation_token('foo@bar.com')
assert_true(u._get_unconfirmed_email_for_token(valid_token))
manual_expiration = datetime.datetime.utcnow() - datetime.timedelta(0, 10)
u._set_email_token_expiration(valid_token, expiration=manual_expiration)
with assert_raises(auth_exc.ExpiredTokenError):
u._get_unconfirmed_email_for_token(valid_token)
def test_verify_confirmation_token_when_token_has_no_expiration(self):
# A user verification token may not have an expiration
email = fake.email()
u = UserFactory.build()
u.add_unconfirmed_email(email)
token = u.get_confirmation_token(email)
# manually remove expiration to simulate legacy user
del u.email_verifications[token]['expiration']
u.save()
assert_true(u._get_unconfirmed_email_for_token(token))
def test_factory(self):
# Clear users
Node.remove()
User.remove()
user = UserFactory()
assert_equal(User.find().count(), 1)
assert_true(user.username)
another_user = UserFactory(username='joe@example.com')
assert_equal(another_user.username, 'joe@example.com')
assert_equal(User.find().count(), 2)
assert_true(user.date_registered)
def test_format_surname(self):
user = UserFactory(fullname='Duane Johnson')
summary = user.get_summary(formatter='surname')
assert_equal(
summary['user_display_name'],
'Johnson'
)
def test_format_surname_one_name(self):
user = UserFactory(fullname='Rock')
summary = user.get_summary(formatter='surname')
assert_equal(
summary['user_display_name'],
'Rock'
)
def test_is_watching(self):
# User watches a node
watched_node = NodeFactory()
unwatched_node = NodeFactory()
config = WatchConfigFactory(node=watched_node)
self.user.watched.append(config)
self.user.save()
assert_true(self.user.is_watching(watched_node))
assert_false(self.user.is_watching(unwatched_node))
def test_serialize(self):
d = self.user.serialize()
assert_equal(d['id'], str(self.user._primary_key))
assert_equal(d['fullname'], self.user.fullname)
assert_equal(d['registered'], self.user.is_registered)
assert_equal(d['url'], self.user.url)
def test_set_password(self):
user = User(username=fake.email(), fullname='Nick Cage')
user.set_password('ghostrider')
user.save()
assert_true(check_password_hash(user.password, 'ghostrider'))
def test_check_password(self):
user = User(username=fake.email(), fullname='Nick Cage')
user.set_password('ghostrider')
user.save()
assert_true(user.check_password('ghostrider'))
assert_false(user.check_password('ghostride'))
def test_change_password(self):
old_password = 'password'
new_password = 'new password'
confirm_password = new_password
self.user.set_password(old_password)
self.user.save()
self.user.change_password(old_password, new_password, confirm_password)
assert_true(self.user.check_password(new_password))
def test_change_password_invalid(self, old_password=None, new_password=None, confirm_password=None,
error_message='Old password is invalid'):
self.user.set_password('password')
self.user.save()
with assert_raises(ChangePasswordError) as error:
self.user.change_password(old_password, new_password, confirm_password)
self.user.save()
assert_in(error_message, error.exception.message)
assert_false(self.user.check_password(new_password))
def test_change_password_invalid_old_password(self):
self.test_change_password_invalid(
'invalid old password',
'new password',
'new password',
'Old password is invalid',
)
def test_change_password_invalid_new_password_length(self):
self.test_change_password_invalid(
'password',
'12345',
'12345',
'Password should be at least six characters',
)
def test_change_password_invalid_confirm_password(self):
self.test_change_password_invalid(
'password',
'new password',
'invalid confirm password',
'Password does not match the confirmation',
)
def test_change_password_invalid_blank_password(self, old_password='', new_password='', confirm_password=''):
self.test_change_password_invalid(
old_password,
new_password,
confirm_password,
'Passwords cannot be blank',
)
def test_change_password_invalid_blank_new_password(self):
for password in (None, '', ' '):
self.test_change_password_invalid_blank_password('password', password, 'new password')
def test_change_password_invalid_blank_confirm_password(self):
for password in (None, '', ' '):
self.test_change_password_invalid_blank_password('password', 'new password', password)
def test_url(self):
assert_equal(
self.user.url,
'/{0}/'.format(self.user._primary_key)
)
def test_absolute_url(self):
assert_equal(
self.user.absolute_url,
urlparse.urljoin(settings.DOMAIN, '/{0}/'.format(self.user._primary_key))
)
def test_profile_image_url(self):
expected = filters.gravatar(
self.user,
use_ssl=True,
size=settings.PROFILE_IMAGE_MEDIUM
)
assert_equal(self.user.profile_image_url(settings.PROFILE_IMAGE_MEDIUM), expected)
def test_profile_image_url_has_no_default_size(self):
expected = filters.gravatar(
self.user,
use_ssl=True,
)
assert_equal(self.user.profile_image_url(), expected)
size = urlparse.parse_qs(urlparse.urlparse(self.user.profile_image_url()).query).get('size')
assert_equal(size, None)
def test_activity_points(self):
assert_equal(self.user.get_activity_points(db=self.db),
get_total_activity_count(self.user._primary_key))
def test_serialize_user(self):
master = UserFactory()
user = UserFactory.build()
master.merge_user(user)
d = serialize_user(user)
assert_equal(d['id'], user._primary_key)
assert_equal(d['url'], user.url)
assert_equal(d.get('username', None), None)
assert_equal(d['fullname'], user.fullname)
assert_equal(d['registered'], user.is_registered)
assert_equal(d['absolute_url'], user.absolute_url)
assert_equal(d['date_registered'], user.date_registered.strftime('%Y-%m-%d'))
assert_equal(d['active'], user.is_active)
def test_serialize_user_full(self):
master = UserFactory()
user = UserFactory.build()
master.merge_user(user)
d = serialize_user(user, full=True)
gravatar = filters.gravatar(
user,
use_ssl=True,
size=settings.PROFILE_IMAGE_LARGE
)
assert_equal(d['id'], user._primary_key)
assert_equal(d['url'], user.url)
assert_equal(d.get('username'), None)
assert_equal(d['fullname'], user.fullname)
assert_equal(d['registered'], user.is_registered)
assert_equal(d['gravatar_url'], gravatar)
assert_equal(d['absolute_url'], user.absolute_url)
assert_equal(d['date_registered'], user.date_registered.strftime('%Y-%m-%d'))
assert_equal(d['is_merged'], user.is_merged)
assert_equal(d['merged_by']['url'], user.merged_by.url)
assert_equal(d['merged_by']['absolute_url'], user.merged_by.absolute_url)
projects = [
node
for node in user.contributed
if node.category == 'project'
and not node.is_registration
and not node.is_deleted
]
public_projects = [p for p in projects if p.is_public]
assert_equal(d['number_projects'], len(projects))
assert_equal(d['number_public_projects'], len(public_projects))
def test_recently_added(self):
# Project created
project = ProjectFactory()
assert_true(hasattr(self.user, 'recently_added'))
# Two users added as contributors
user2 = UserFactory()
user3 = UserFactory()
project.add_contributor(contributor=user2, auth=self.auth)
project.add_contributor(contributor=user3, auth=self.auth)
assert_equal(user3, self.user.recently_added[0])
assert_equal(user2, self.user.recently_added[1])
assert_equal(len(self.user.recently_added), 2)
def test_recently_added_multi_project(self):
# Three users are created
user2 = UserFactory()
user3 = UserFactory()
user4 = UserFactory()
# 2 projects created
project = ProjectFactory()
project2 = ProjectFactory()
# Users 2 and 3 are added to original project
project.add_contributor(contributor=user2, auth=self.auth)
project.add_contributor(contributor=user3, auth=self.auth)
# Users 2 and 3 are added to original project
project2.add_contributor(contributor=user2, auth=self.auth)
project2.add_contributor(contributor=user4, auth=self.auth)
assert_equal(user4, self.user.recently_added[0])
assert_equal(user2, self.user.recently_added[1])
assert_equal(user3, self.user.recently_added[2])
assert_equal(len(self.user.recently_added), 3)
def test_recently_added_length(self):
# Project created
project = ProjectFactory()
assert_equal(len(self.user.recently_added), 0)
# Add 17 users
for _ in range(17):
project.add_contributor(
contributor=UserFactory(),
auth=self.auth
)
assert_equal(len(self.user.recently_added), 15)
def test_display_full_name_registered(self):
u = UserFactory()
assert_equal(u.display_full_name(), u.fullname)
def test_display_full_name_unregistered(self):
name = fake.name()
u = UnregUserFactory()
project = ProjectFactory()
project.add_unregistered_contributor(fullname=name, email=u.username,
auth=Auth(project.creator))
project.save()
assert_equal(u.display_full_name(node=project), name)
def test_get_projects_in_common(self):
user2 = UserFactory()
project = ProjectFactory(creator=self.user)
project.add_contributor(contributor=user2, auth=self.auth)
project.save()
project_keys = set([node._id for node in self.user.contributed])
projects = set(self.user.contributed)
user2_project_keys = set([node._id for node in user2.contributed])
assert_equal(self.user.get_projects_in_common(user2, primary_keys=True),
project_keys.intersection(user2_project_keys))
assert_equal(self.user.get_projects_in_common(user2, primary_keys=False),
projects.intersection(user2.contributed))
def test_n_projects_in_common(self):
user2 = UserFactory()
user3 = UserFactory()
project = ProjectFactory(creator=self.user)
project.add_contributor(contributor=user2, auth=self.auth)
project.save()
assert_equal(self.user.n_projects_in_common(user2), 1)
assert_equal(self.user.n_projects_in_common(user3), 0)
def test_user_get_cookie(self):
user = UserFactory()
super_secret_key = 'children need maps'
signer = itsdangerous.Signer(super_secret_key)
session = Session(data={
'auth_user_id': user._id,
'auth_user_username': user.username,
'auth_user_fullname': user.fullname,
})
session.save()
assert_equal(signer.unsign(user.get_or_create_cookie(super_secret_key)), session._id)
def test_user_get_cookie_no_session(self):
user = UserFactory()
super_secret_key = 'children need maps'
signer = itsdangerous.Signer(super_secret_key)
assert_equal(
0,
Session.find(Q('data.auth_user_id', 'eq', user._id)).count()
)
cookie = user.get_or_create_cookie(super_secret_key)
session = Session.find(Q('data.auth_user_id', 'eq', user._id))[0]
assert_equal(session._id, signer.unsign(cookie))
assert_equal(session.data['auth_user_id'], user._id)
assert_equal(session.data['auth_user_username'], user.username)
assert_equal(session.data['auth_user_fullname'], user.fullname)
def test_get_user_by_cookie(self):
user = UserFactory()
cookie = user.get_or_create_cookie()
assert_equal(user, User.from_cookie(cookie))
def test_get_user_by_cookie_returns_none(self):
assert_equal(None, User.from_cookie(''))
def test_get_user_by_cookie_bad_cookie(self):
assert_equal(None, User.from_cookie('foobar'))
def test_get_user_by_cookie_no_user_id(self):
user = UserFactory()
cookie = user.get_or_create_cookie()
session = Session.find_one(Q('data.auth_user_id', 'eq', user._id))
del session.data['auth_user_id']
assert_in('data', session.save())
assert_equal(None, User.from_cookie(cookie))
def test_get_user_by_cookie_no_session(self):
user = UserFactory()
cookie = user.get_or_create_cookie()
Session.remove()
assert_equal(
0,
Session.find(Q('data.auth_user_id', 'eq', user._id)).count()
)
assert_equal(None, User.from_cookie(cookie))
class TestUserParse(unittest.TestCase):
def test_parse_first_last(self):
parsed = impute_names_model('John Darnielle')
assert_equal(parsed['given_name'], 'John')
assert_equal(parsed['family_name'], 'Darnielle')
def test_parse_first_last_particles(self):
parsed = impute_names_model('John van der Slice')
assert_equal(parsed['given_name'], 'John')
assert_equal(parsed['family_name'], 'van der Slice')
class TestDisablingUsers(OsfTestCase):
def setUp(self):
super(TestDisablingUsers, self).setUp()
self.user = UserFactory()
def test_user_enabled_by_default(self):
assert_false(self.user.is_disabled)
def test_disabled_user(self):
"""Ensure disabling a user sets date_disabled"""
self.user.is_disabled = True
self.user.save()
assert_true(isinstance(self.user.date_disabled, datetime.datetime))
assert_true(self.user.is_disabled)
assert_false(self.user.is_active)
def test_reenabled_user(self):
"""Ensure restoring a disabled user unsets date_disabled"""
self.user.is_disabled = True
self.user.save()
self.user.is_disabled = False
self.user.save()
assert_is_none(self.user.date_disabled)
assert_false(self.user.is_disabled)
assert_true(self.user.is_active)
def test_is_disabled_idempotency(self):
self.user.is_disabled = True
self.user.save()
old_date_disabled = self.user.date_disabled
self.user.is_disabled = True
self.user.save()
new_date_disabled = self.user.date_disabled
assert_equal(new_date_disabled, old_date_disabled)
@mock.patch('website.mailchimp_utils.get_mailchimp_api')
def test_disable_account(self, mock_mail):
self.user.mailchimp_mailing_lists[settings.MAILCHIMP_GENERAL_LIST] = True
self.user.save()
self.user.disable_account()
assert_true(self.user.is_disabled)
assert_true(isinstance(self.user.date_disabled, datetime.datetime))
assert_false(self.user.mailchimp_mailing_lists[settings.MAILCHIMP_GENERAL_LIST])
class TestMergingUsers(OsfTestCase):
def setUp(self):
super(TestMergingUsers, self).setUp()
with self.context:
handlers.celery_before_request()
self.master = UserFactory(
fullname='Joe Shmo',
is_registered=True,
emails=['joe@example.com'],
)
self.dupe = UserFactory(
fullname='Joseph Shmo',
emails=['joseph123@hotmail.com']
)
def _merge_dupe(self):
'''Do the actual merge.'''
self.master.merge_user(self.dupe)
self.master.save()
def test_dashboard_nodes_arent_merged(self):
dashnode = ProjectFactory(creator=self.dupe, is_dashboard=True)
self._merge_dupe()
assert_not_in(dashnode, self.master. contributed)
def test_dupe_is_merged(self):
self._merge_dupe()
assert_true(self.dupe.is_merged)
assert_equal(self.dupe.merged_by, self.master)
def test_dupe_email_is_appended(self):
self._merge_dupe()
assert_in('joseph123@hotmail.com', self.master.emails)
def test_send_user_merged_signal(self):
self.dupe.mailchimp_mailing_lists['foo'] = True
self.dupe.save()
with capture_signals() as mock_signals:
self._merge_dupe()
assert_equal(mock_signals.signals_sent(), set([user_merged]))
@mock.patch('website.mailchimp_utils.get_mailchimp_api')
def test_merged_user_unsubscribed_from_mailing_lists(self, mock_get_mailchimp_api):
list_name = 'foo'
username = self.dupe.username
self.dupe.mailchimp_mailing_lists[list_name] = True
self.dupe.save()
mock_client = mock.MagicMock()
mock_get_mailchimp_api.return_value = mock_client
mock_client.lists.list.return_value = {'data': [{'id': 2, 'list_name': list_name}]}
list_id = mailchimp_utils.get_list_id_from_name(list_name)
self._merge_dupe()
handlers.celery_teardown_request()
mock_client.lists.unsubscribe.assert_called_with(id=list_id, email={'email': username}, send_goodbye=False)
assert_false(self.dupe.mailchimp_mailing_lists[list_name])
def test_inherits_projects_contributed_by_dupe(self):
project = ProjectFactory()
project.add_contributor(self.dupe)
project.save()
self._merge_dupe()
project.reload()
assert_true(project.is_contributor(self.master))
assert_false(project.is_contributor(self.dupe))
def test_inherits_projects_created_by_dupe(self):
project = ProjectFactory(creator=self.dupe)
self._merge_dupe()
project.reload()
assert_equal(project.creator, self.master)
def test_adding_merged_user_as_contributor_adds_master(self):
project = ProjectFactory(creator=UserFactory())
self._merge_dupe()
project.add_contributor(contributor=self.dupe)
assert_true(project.is_contributor(self.master))
assert_false(project.is_contributor(self.dupe))
def test_merging_dupe_who_is_contributor_on_same_projects(self):
# Both master and dupe are contributors on the same project
project = ProjectFactory()
project.add_contributor(contributor=self.master)
project.add_contributor(contributor=self.dupe)
project.save()
self._merge_dupe() # perform the merge
project.reload()
assert_true(project.is_contributor(self.master))
assert_false(project.is_contributor(self.dupe))
assert_equal(len(project.contributors), 2) # creator and master
# are the only contribs
class TestGUID(OsfTestCase):
def setUp(self):
super(TestGUID, self).setUp()
self.records = {}
for factory in GUID_FACTORIES:
record = factory()
self.records[record._name] = record
def test_guid(self):
for record in self.records.values():
record_guid = Guid.load(record._primary_key)
# GUID must exist
assert_false(record_guid is None)
# Primary keys of GUID and record must be the same
assert_equal(
record_guid._primary_key,
record._primary_key
)
# GUID must refer to record
assert_equal(
record_guid.referent,
record
)
class TestApiOAuth2Application(OsfTestCase):
def setUp(self):
super(TestApiOAuth2Application, self).setUp()
self.api_app = ApiOAuth2ApplicationFactory()
def test_must_have_owner(self):
with assert_raises(ValidationError):
api_app = ApiOAuth2ApplicationFactory(owner=None)
api_app.save()
def test_client_id_auto_populates(self):
assert_greater(len(self.api_app.client_id), 0)
def test_client_secret_auto_populates(self):
assert_greater(len(self.api_app.client_secret), 0)
def test_new_app_is_not_flagged_as_deleted(self):
assert_true(self.api_app.is_active)
def test_cant_edit_creation_date(self):
with assert_raises(AttributeError):
self.api_app.date_created = datetime.datetime.utcnow()
def test_invalid_home_url_raises_exception(self):
with assert_raises(ValidationError):
api_app = ApiOAuth2ApplicationFactory(home_url="Totally not a URL")
api_app.save()
def test_invalid_callback_url_raises_exception(self):
with assert_raises(ValidationError):
api_app = ApiOAuth2ApplicationFactory(callback_url="itms://itunes.apple.com/us/app/apple-store/id375380948?mt=8")
api_app.save()
def test_name_cannot_be_blank(self):
with assert_raises(ValidationError):
api_app = ApiOAuth2ApplicationFactory(name='')
api_app.save()
def test_long_name_raises_exception(self):
long_name = ('JohnJacobJingelheimerSchmidtHisNameIsMyN' * 5) + 'a'
with assert_raises(ValidationError):
api_app = ApiOAuth2ApplicationFactory(name=long_name)
api_app.save()
def test_long_description_raises_exception(self):
long_desc = ('JohnJacobJingelheimerSchmidtHisNameIsMyN' * 25) + 'a'
with assert_raises(ValidationError):
api_app = ApiOAuth2ApplicationFactory(description=long_desc)
api_app.save()
@mock.patch('framework.auth.cas.CasClient.revoke_application_tokens')
def test_active_set_to_false_upon_successful_deletion(self, mock_method):
mock_method.return_value(True)
self.api_app.deactivate(save=True)
self.api_app.reload()
assert_false(self.api_app.is_active)
@mock.patch('framework.auth.cas.CasClient.revoke_application_tokens')
def test_active_remains_true_when_cas_token_deletion_fails(self, mock_method):
mock_method.side_effect = cas.CasHTTPError("CAS can't revoke tokens", 400, 'blank', 'blank')
with assert_raises(cas.CasHTTPError):
self.api_app.deactivate(save=True)
self.api_app.reload()
assert_true(self.api_app.is_active)
class TestNodeWikiPage(OsfTestCase):
def setUp(self):
super(TestNodeWikiPage, self).setUp()
self.user = UserFactory()
self.project = ProjectFactory(creator=self.user)
self.wiki = NodeWikiFactory(user=self.user, node=self.project)
def test_factory(self):
wiki = NodeWikiFactory()
assert_equal(wiki.page_name, 'home')
assert_equal(wiki.version, 1)
assert_true(hasattr(wiki, 'is_current'))
assert_equal(wiki.content, 'Some content')
assert_true(wiki.user)
assert_true(wiki.node)
def test_url(self):
assert_equal(self.wiki.url, '{project_url}wiki/home/'
.format(project_url=self.project.url))
class TestUpdateNodeWiki(OsfTestCase):
def setUp(self):
super(TestUpdateNodeWiki, self).setUp()
# Create project with component
self.user = UserFactory()
self.auth = Auth(user=self.user)
self.project = ProjectFactory()
self.node = NodeFactory(creator=self.user, parent=self.project)
# user updates the wiki
self.project.update_node_wiki('home', 'Hello world', self.auth)
self.versions = self.project.wiki_pages_versions
def test_default_wiki(self):
# There is no default wiki
project1 = ProjectFactory()
assert_equal(project1.get_wiki_page('home'), None)
def test_default_is_current(self):
assert_true(self.project.get_wiki_page('home').is_current)
self.project.update_node_wiki('home', 'Hello world 2', self.auth)
assert_true(self.project.get_wiki_page('home').is_current)
self.project.update_node_wiki('home', 'Hello world 3', self.auth)
def test_wiki_content(self):
# Wiki has correct content
assert_equal(self.project.get_wiki_page('home').content, 'Hello world')
# user updates the wiki a second time
self.project.update_node_wiki('home', 'Hola mundo', self.auth)
# Both versions have the expected content
assert_equal(self.project.get_wiki_page('home', 2).content, 'Hola mundo')
assert_equal(self.project.get_wiki_page('home', 1).content, 'Hello world')
def test_current(self):
# Wiki is current
assert_true(self.project.get_wiki_page('home', 1).is_current)
# user updates the wiki a second time
self.project.update_node_wiki('home', 'Hola mundo', self.auth)
# New version is current, old version is not
assert_true(self.project.get_wiki_page('home', 2).is_current)
assert_false(self.project.get_wiki_page('home', 1).is_current)
def test_update_log(self):
# Updates are logged
assert_equal(self.project.logs[-1].action, 'wiki_updated')
# user updates the wiki a second time
self.project.update_node_wiki('home', 'Hola mundo', self.auth)
# There are two update logs
assert_equal([log.action for log in self.project.logs].count('wiki_updated'), 2)
def test_update_log_specifics(self):
page = self.project.get_wiki_page('home')
log = self.project.logs[-1]
assert_equal('wiki_updated', log.action)
assert_equal(page._primary_key, log.params['page_id'])
def test_wiki_versions(self):
# Number of versions is correct
assert_equal(len(self.versions['home']), 1)
# Update wiki
self.project.update_node_wiki('home', 'Hello world', self.auth)
# Number of versions is correct
assert_equal(len(self.versions['home']), 2)
# Versions are different
assert_not_equal(self.versions['home'][0], self.versions['home'][1])
def test_update_two_node_wikis(self):
# user updates a second wiki for the same node
self.project.update_node_wiki('second', 'Hola mundo', self.auth)
# each wiki only has one version
assert_equal(len(self.versions['home']), 1)
assert_equal(len(self.versions['second']), 1)
# There are 2 logs saved
assert_equal([log.action for log in self.project.logs].count('wiki_updated'), 2)
# Each wiki has the expected content
assert_equal(self.project.get_wiki_page('home').content, 'Hello world')
assert_equal(self.project.get_wiki_page('second').content, 'Hola mundo')
def test_update_name_invalid(self):
# forward slashes are not allowed
invalid_name = 'invalid/name'
with assert_raises(NameInvalidError):
self.project.update_node_wiki(invalid_name, 'more valid content', self.auth)
class TestRenameNodeWiki(OsfTestCase):
def setUp(self):
super(TestRenameNodeWiki, self).setUp()
# Create project with component
self.user = UserFactory()
self.auth = Auth(user=self.user)
self.project = ProjectFactory()
self.node = NodeFactory(creator=self.user, parent=self.project)
# user updates the wiki
self.project.update_node_wiki('home', 'Hello world', self.auth)
self.versions = self.project.wiki_pages_versions
def test_rename_name_not_found(self):
for invalid_name in [None, '', ' ', 'Unknown Name']:
with assert_raises(PageNotFoundError):
self.project.rename_node_wiki(invalid_name, None, auth=self.auth)
def test_rename_new_name_invalid_none_or_blank(self):
name = 'New Page'
self.project.update_node_wiki(name, 'new content', self.auth)
for invalid_name in [None, '', ' ']:
with assert_raises(NameEmptyError):
self.project.rename_node_wiki(name, invalid_name, auth=self.auth)
def test_rename_new_name_invalid_special_characters(self):
old_name = 'old name'
# forward slashes are not allowed
invalid_name = 'invalid/name'
self.project.update_node_wiki(old_name, 'some content', self.auth)
with assert_raises(NameInvalidError):
self.project.rename_node_wiki(old_name, invalid_name, self.auth)
def test_rename_name_maximum_length(self):
old_name = 'short name'
new_name = 'a' * 101
self.project.update_node_wiki(old_name, 'some content', self.auth)
with assert_raises(NameMaximumLengthError):
self.project.rename_node_wiki(old_name, new_name, self.auth)
def test_rename_cannot_rename(self):
for args in [('home', 'New Home'), ('HOME', 'New Home')]:
with assert_raises(PageCannotRenameError):
self.project.rename_node_wiki(*args, auth=self.auth)
def test_rename_page_not_found(self):
for args in [('abc123', 'New Home'), (u'ˆ•¶£˙˙®¬™∆˙', 'New Home')]:
with assert_raises(PageNotFoundError):
self.project.rename_node_wiki(*args, auth=self.auth)
def test_rename_page(self):
old_name = 'new page'
new_name = 'New pAGE'
self.project.update_node_wiki(old_name, 'new content', self.auth)
self.project.rename_node_wiki(old_name, new_name, self.auth)
page = self.project.get_wiki_page(new_name)
assert_not_equal(old_name, page.page_name)
assert_equal(new_name, page.page_name)
assert_equal(self.project.logs[-1].action, NodeLog.WIKI_RENAMED)
def test_rename_page_case_sensitive(self):
old_name = 'new page'
new_name = 'New pAGE'
self.project.update_node_wiki(old_name, 'new content', self.auth)
self.project.rename_node_wiki(old_name, new_name, self.auth)
new_page = self.project.get_wiki_page(new_name)
assert_equal(new_name, new_page.page_name)
assert_equal(self.project.logs[-1].action, NodeLog.WIKI_RENAMED)
def test_rename_existing_deleted_page(self):
old_name = 'old page'
new_name = 'new page'
old_content = 'old content'
new_content = 'new content'
# create the old page and delete it
self.project.update_node_wiki(old_name, old_content, self.auth)
assert_in(old_name, self.project.wiki_pages_current)
self.project.delete_node_wiki(old_name, self.auth)
assert_not_in(old_name, self.project.wiki_pages_current)
# create the new page and rename it
self.project.update_node_wiki(new_name, new_content, self.auth)
self.project.rename_node_wiki(new_name, old_name, self.auth)
new_page = self.project.get_wiki_page(old_name)
old_page = self.project.get_wiki_page(old_name, version=1)
# renaming over an existing deleted page replaces it.
assert_equal(new_content, old_page.content)
assert_equal(new_content, new_page.content)
assert_equal(self.project.logs[-1].action, NodeLog.WIKI_RENAMED)
def test_rename_page_conflict(self):
existing_name = 'existing page'
new_name = 'new page'
self.project.update_node_wiki(existing_name, 'old content', self.auth)
assert_in(existing_name, self.project.wiki_pages_current)
self.project.update_node_wiki(new_name, 'new content', self.auth)
assert_in(new_name, self.project.wiki_pages_current)
with assert_raises(PageConflictError):
self.project.rename_node_wiki(new_name, existing_name, self.auth)
def test_rename_log(self):
# Rename wiki
self.project.update_node_wiki('wiki', 'content', self.auth)
self.project.rename_node_wiki('wiki', 'renamed wiki', self.auth)
# Rename is logged
assert_equal(self.project.logs[-1].action, 'wiki_renamed')
def test_rename_log_specifics(self):
self.project.update_node_wiki('wiki', 'content', self.auth)
self.project.rename_node_wiki('wiki', 'renamed wiki', self.auth)
page = self.project.get_wiki_page('renamed wiki')
log = self.project.logs[-1]
assert_equal('wiki_renamed', log.action)
assert_equal(page._primary_key, log.params['page_id'])
class TestDeleteNodeWiki(OsfTestCase):
def setUp(self):
super(TestDeleteNodeWiki, self).setUp()
# Create project with component
self.user = UserFactory()
self.auth = Auth(user=self.user)
self.project = ProjectFactory()
self.node = NodeFactory(creator=self.user, parent=self.project)
# user updates the wiki
self.project.update_node_wiki('home', 'Hello world', self.auth)
self.versions = self.project.wiki_pages_versions
def test_delete_log(self):
# Delete wiki
self.project.delete_node_wiki('home', self.auth)
# Deletion is logged
assert_equal(self.project.logs[-1].action, 'wiki_deleted')
def test_delete_log_specifics(self):
page = self.project.get_wiki_page('home')
self.project.delete_node_wiki('home', self.auth)
log = self.project.logs[-1]
assert_equal('wiki_deleted', log.action)
assert_equal(page._primary_key, log.params['page_id'])
def test_wiki_versions(self):
# Number of versions is correct
assert_equal(len(self.versions['home']), 1)
# Delete wiki
self.project.delete_node_wiki('home', self.auth)
# Number of versions is still correct
assert_equal(len(self.versions['home']), 1)
def test_wiki_delete(self):
page = self.project.get_wiki_page('home')
self.project.delete_node_wiki('home', self.auth)
# page was deleted
assert_false(self.project.get_wiki_page('home'))
log = self.project.logs[-1]
# deletion was logged
assert_equal(
NodeLog.WIKI_DELETED,
log.action,
)
# log date is not set to the page's creation date
assert_true(log.date > page.date)
def test_deleted_versions(self):
# Update wiki a second time
self.project.update_node_wiki('home', 'Hola mundo', self.auth)
assert_equal(self.project.get_wiki_page('home', 2).content, 'Hola mundo')
# Delete wiki
self.project.delete_node_wiki('home', self.auth)
# Check versions
assert_equal(self.project.get_wiki_page('home',2).content, 'Hola mundo')
assert_equal(self.project.get_wiki_page('home', 1).content, 'Hello world')
class TestNode(OsfTestCase):
def setUp(self):
super(TestNode, self).setUp()
# Create project with component
self.user = UserFactory()
self.auth = Auth(user=self.user)
self.parent = ProjectFactory(creator=self.user)
self.node = NodeFactory(creator=self.user, parent=self.parent)
def test_set_privacy_checks_admin_permissions(self):
non_contrib = UserFactory()
project = ProjectFactory(creator=self.user, is_public=False)
# Non-contrib can't make project public
with assert_raises(PermissionsError):
project.set_privacy('public', Auth(non_contrib))
project.set_privacy('public', Auth(project.creator))
project.save()
# Non-contrib can't make project private
with assert_raises(PermissionsError):
project.set_privacy('private', Auth(non_contrib))
def test_set_privacy_pending_embargo(self):
project = ProjectFactory(creator=self.user, is_public=False)
with mock_archive(project, embargo=True, autocomplete=True) as registration:
assert_true(registration.embargo.is_pending_approval)
assert_true(registration.is_pending_embargo)
with assert_raises(NodeStateError):
registration.set_privacy('public', Auth(project.creator))
def test_set_privacy_pending_registration(self):
project = ProjectFactory(creator=self.user, is_public=False)
with mock_archive(project, embargo=False, autocomplete=True) as registration:
assert_true(registration.registration_approval.is_pending_approval)
assert_true(registration.is_pending_registration)
with assert_raises(NodeStateError):
registration.set_privacy('public', Auth(project.creator))
def test_get_aggregate_logs_queryset_doesnt_return_hidden_logs(self):
n_orig_logs = len(self.parent.get_aggregate_logs_queryset(Auth(self.user)))
log = self.parent.logs[-1]
log.should_hide = True
log.save()
n_new_logs = len(self.parent.get_aggregate_logs_queryset(Auth(self.user)))
# Hidden log is not returned
assert_equal(n_new_logs, n_orig_logs - 1)
def test_validate_categories(self):
with assert_raises(ValidationError):
Node(category='invalid').save() # an invalid category
def test_web_url_for(self):
result = self.parent.web_url_for('view_project')
assert_equal(
result,
web_url_for(
'view_project',
pid=self.parent._id,
)
)
result2 = self.node.web_url_for('view_project')
assert_equal(
result2,
web_url_for(
'view_project',
pid=self.node._primary_key
)
)
def test_web_url_for_absolute(self):
result = self.parent.web_url_for('view_project', _absolute=True)
assert_in(settings.DOMAIN, result)
def test_category_display(self):
node = NodeFactory(category='hypothesis')
assert_equal(node.category_display, 'Hypothesis')
node2 = NodeFactory(category='methods and measures')
assert_equal(node2.category_display, 'Methods and Measures')
def test_api_url_for(self):
result = self.parent.api_url_for('view_project')
assert_equal(
result,
api_url_for(
'view_project',
pid=self.parent._id
)
)
result2 = self.node.api_url_for('view_project')
assert_equal(
result2,
api_url_for(
'view_project',
pid=self.node._id,
)
)
def test_api_url_for_absolute(self):
result = self.parent.api_url_for('view_project', _absolute=True)
assert_in(settings.DOMAIN, result)
def test_get_absolute_url(self):
assert_equal(self.node.get_absolute_url(),
'{}v2/nodes/{}/'
.format(settings.API_DOMAIN, self.node._id)
)
def test_node_factory(self):
node = NodeFactory()
assert_equal(node.category, 'hypothesis')
assert_true(node.node__parent)
assert_equal(node.logs[0].action, 'project_created')
assert_equal(
set(node.get_addon_names()),
set([
addon_config.short_name
for addon_config in settings.ADDONS_AVAILABLE
if 'node' in addon_config.added_default
])
)
for addon_config in settings.ADDONS_AVAILABLE:
if 'node' in addon_config.added_default:
assert_in(
addon_config.short_name,
node.get_addon_names()
)
assert_true(
len([
addon
for addon in node.addons
if addon.config.short_name == addon_config.short_name
]),
1
)
def test_add_addon(self):
addon_count = len(self.node.get_addon_names())
addon_record_count = len(self.node.addons)
added = self.node.add_addon('github', self.auth)
assert_true(added)
self.node.reload()
assert_equal(
len(self.node.get_addon_names()),
addon_count + 1
)
assert_equal(
len(self.node.addons),
addon_record_count + 1
)
assert_equal(
self.node.logs[-1].action,
NodeLog.ADDON_ADDED
)
def test_add_existing_addon(self):
addon_count = len(self.node.get_addon_names())
addon_record_count = len(self.node.addons)
added = self.node.add_addon('osffiles', self.auth)
assert_false(added)
assert_equal(
len(self.node.get_addon_names()),
addon_count
)
assert_equal(
len(self.node.addons),
addon_record_count
)
def test_delete_addon(self):
addon_count = len(self.node.get_addon_names())
deleted = self.node.delete_addon('wiki', self.auth)
assert_true(deleted)
assert_equal(
len(self.node.get_addon_names()),
addon_count - 1
)
assert_equal(
self.node.logs[-1].action,
NodeLog.ADDON_REMOVED
)
@mock.patch('website.addons.github.model.AddonGitHubNodeSettings.config')
def test_delete_mandatory_addon(self, mock_config):
mock_config.added_mandatory = ['node']
self.node.add_addon('github', self.auth)
with assert_raises(ValueError):
self.node.delete_addon('github', self.auth)
def test_delete_nonexistent_addon(self):
addon_count = len(self.node.get_addon_names())
deleted = self.node.delete_addon('github', self.auth)
assert_false(deleted)
assert_equal(
len(self.node.get_addon_names()),
addon_count
)
def test_url(self):
assert_equal(
self.node.url,
'/{0}/'.format(self.node._primary_key)
)
def test_watch_url(self):
url = self.node.watch_url
assert_equal(url, '/api/v1/project/{0}/watch/'
.format(self.node._primary_key))
def test_parent_id(self):
assert_equal(self.node.parent_id, self.parent._id)
def test_parent(self):
assert_equal(self.node.parent_node, self.parent)
def test_in_parent_nodes(self):
assert_in(self.node, self.parent.nodes)
def test_log(self):
latest_log = self.node.logs[-1]
assert_equal(latest_log.action, 'project_created')
assert_equal(latest_log.params, {
'node': self.node._primary_key,
'parent_node': self.parent._primary_key,
})
assert_equal(latest_log.user, self.user)
def test_add_pointer(self):
node2 = NodeFactory(creator=self.user)
pointer = self.node.add_pointer(node2, auth=self.auth)
assert_equal(pointer, self.node.nodes[0])
assert_equal(len(self.node.nodes), 1)
assert_false(self.node.nodes[0].primary)
assert_equal(self.node.nodes[0].node, node2)
assert_equal(len(node2.get_points()), 1)
assert_equal(
self.node.logs[-1].action, NodeLog.POINTER_CREATED
)
assert_equal(
self.node.logs[-1].params, {
'parent_node': self.node.parent_id,
'node': self.node._primary_key,
'pointer': {
'id': pointer.node._id,
'url': pointer.node.url,
'title': pointer.node.title,
'category': pointer.node.category,
},
}
)
def test_add_pointer_fails_for_registrations(self):
node = ProjectFactory()
registration = RegistrationFactory(creator=self.user)
with assert_raises(NodeStateError):
registration.add_pointer(node, auth=self.auth)
def test_get_points_exclude_folders(self):
user = UserFactory()
pointer_project = ProjectFactory(is_public=True) # project that points to another project
pointed_project = ProjectFactory(creator=user) # project that other project points to
pointer_project.add_pointer(pointed_project, Auth(pointer_project.creator), save=True)
# Project is in a dashboard folder
folder = FolderFactory(creator=pointed_project.creator)
folder.add_pointer(pointed_project, Auth(pointed_project.creator), save=True)
assert_in(pointer_project, pointed_project.get_points(folders=False))
assert_not_in(folder, pointed_project.get_points(folders=False))
assert_in(folder, pointed_project.get_points(folders=True))
def test_get_points_exclude_deleted(self):
user = UserFactory()
pointer_project = ProjectFactory(is_public=True, is_deleted=True) # project that points to another project
pointed_project = ProjectFactory(creator=user) # project that other project points to
pointer_project.add_pointer(pointed_project, Auth(pointer_project.creator), save=True)
assert_not_in(pointer_project, pointed_project.get_points(deleted=False))
assert_in(pointer_project, pointed_project.get_points(deleted=True))
def test_add_pointer_already_present(self):
node2 = NodeFactory(creator=self.user)
self.node.add_pointer(node2, auth=self.auth)
with assert_raises(ValueError):
self.node.add_pointer(node2, auth=self.auth)
def test_rm_pointer(self):
node2 = NodeFactory(creator=self.user)
pointer = self.node.add_pointer(node2, auth=self.auth)
self.node.rm_pointer(pointer, auth=self.auth)
assert_is(Pointer.load(pointer._id), None)
assert_equal(len(self.node.nodes), 0)
assert_equal(len(node2.get_points()), 0)
assert_equal(
self.node.logs[-1].action, NodeLog.POINTER_REMOVED
)
assert_equal(
self.node.logs[-1].params, {
'parent_node': self.node.parent_id,
'node': self.node._primary_key,
'pointer': {
'id': pointer.node._id,
'url': pointer.node.url,
'title': pointer.node.title,
'category': pointer.node.category,
},
}
)
def test_rm_pointer_not_present(self):
node2 = NodeFactory(creator=self.user)
pointer = Pointer(node=node2)
with assert_raises(ValueError):
self.node.rm_pointer(pointer, auth=self.auth)
def test_fork_pointer_not_present(self):
pointer = PointerFactory()
with assert_raises(ValueError):
self.node.fork_pointer(pointer, auth=self.auth)
def test_cannot_fork_deleted_node(self):
self.node.is_deleted = True
self.node.save()
fork = self.parent.fork_node(auth=self.auth)
assert_false(fork.nodes)
def _fork_pointer(self, content):
pointer = self.node.add_pointer(content, auth=self.auth)
forked = self.node.fork_pointer(pointer, auth=self.auth)
assert_true(forked.is_fork)
assert_equal(forked.forked_from, content)
assert_true(self.node.nodes[-1].primary)
assert_equal(self.node.nodes[-1], forked)
assert_equal(
self.node.logs[-1].action, NodeLog.POINTER_FORKED
)
assert_equal(
self.node.logs[-1].params, {
'parent_node': self.node.parent_id,
'node': self.node._primary_key,
'pointer': {
'id': pointer.node._id,
'url': pointer.node.url,
'title': pointer.node.title,
'category': pointer.node.category,
},
}
)
def test_fork_pointer_project(self):
project = ProjectFactory(creator=self.user)
self._fork_pointer(project)
def test_fork_pointer_component(self):
component = NodeFactory(creator=self.user)
self._fork_pointer(component)
def test_add_file(self):
#todo Add file series of tests
pass
def test_not_a_folder(self):
assert_equal(self.node.is_folder, False)
def test_not_a_dashboard(self):
assert_equal(self.node.is_dashboard, False)
def test_cannot_link_to_folder_more_than_once(self):
folder = FolderFactory(creator=self.user)
node_two = ProjectFactory(creator=self.user)
self.node.add_pointer(folder, auth=self.auth)
with assert_raises(ValueError):
node_two.add_pointer(folder, auth=self.auth)
def test_is_expanded_default_false_with_user(self):
assert_equal(self.node.is_expanded(user=self.user), False)
def test_expand_sets_true_with_user(self):
self.node.expand(user=self.user)
assert_equal(self.node.is_expanded(user=self.user), True)
def test_collapse_sets_false_with_user(self):
self.node.expand(user=self.user)
self.node.collapse(user=self.user)
assert_equal(self.node.is_expanded(user=self.user), False)
def test_cannot_register_deleted_node(self):
self.node.is_deleted = True
self.node.save()
with assert_raises(NodeStateError) as err:
self.node.register_node(
schema=None,
auth=self.auth,
data=None
)
assert_equal(err.exception.message, 'Cannot register deleted node.')
def test_set_visible_contributor_with_only_one_contributor(self):
with assert_raises(ValueError) as e:
self.node.set_visible(user=self.user, visible=False, auth=None)
assert_equal(e.exception.message, 'Must have at least one visible contributor')
def test_update_contributor(self):
new_contrib = AuthUserFactory()
self.node.add_contributor(new_contrib, permissions=DEFAULT_CONTRIBUTOR_PERMISSIONS, auth=self.auth)
assert_equal(self.node.get_permissions(new_contrib), DEFAULT_CONTRIBUTOR_PERMISSIONS)
assert_true(self.node.get_visible(new_contrib))
self.node.update_contributor(
new_contrib,
READ,
False,
auth=self.auth
)
assert_equal(self.node.get_permissions(new_contrib), [READ])
assert_false(self.node.get_visible(new_contrib))
def test_update_contributor_non_admin_raises_error(self):
non_admin = AuthUserFactory()
self.node.add_contributor(
non_admin,
permissions=DEFAULT_CONTRIBUTOR_PERMISSIONS,
auth=self.auth
)
with assert_raises(PermissionsError):
self.node.update_contributor(
non_admin,
None,
False,
auth=Auth(non_admin)
)
def test_update_contributor_only_admin_raises_error(self):
with assert_raises(NodeStateError):
self.node.update_contributor(
self.user,
WRITE,
True,
auth=self.auth
)
def test_update_contributor_non_contrib_raises_error(self):
non_contrib = AuthUserFactory()
with assert_raises(ValueError):
self.node.update_contributor(
non_contrib,
ADMIN,
True,
auth=self.auth
)
def test_contributor_manage_visibility(self):
reg_user1 = UserFactory()
#This makes sure manage_contributors uses set_visible so visibility for contributors is added before visibility
#for other contributors is removed ensuring there is always at least one visible contributor
self.node.add_contributor(contributor=self.user, permissions=['read', 'write', 'admin'], auth=self.auth)
self.node.add_contributor(contributor=reg_user1, permissions=['read', 'write', 'admin'], auth=self.auth)
self.node.manage_contributors(
user_dicts=[
{'id': self.user._id, 'permission': 'admin', 'visible': True},
{'id': reg_user1._id, 'permission': 'admin', 'visible': False},
],
auth=self.auth,
save=True
)
self.node.manage_contributors(
user_dicts=[
{'id': self.user._id, 'permission': 'admin', 'visible': False},
{'id': reg_user1._id, 'permission': 'admin', 'visible': True},
],
auth=self.auth,
save=True
)
assert_equal(len(self.node.visible_contributor_ids), 1)
def test_contributor_set_visibility_validation(self):
reg_user1, reg_user2 = UserFactory(), UserFactory()
self.node.add_contributors(
[
{'user': reg_user1, 'permissions': [
'read', 'write', 'admin'], 'visible': True},
{'user': reg_user2, 'permissions': [
'read', 'write', 'admin'], 'visible': False},
]
)
print(self.node.visible_contributor_ids)
with assert_raises(ValueError) as e:
self.node.set_visible(user=reg_user1, visible=False, auth=None)
self.node.set_visible(user=self.user, visible=False, auth=None)
assert_equal(e.exception.message, 'Must have at least one visible contributor')
def test_active_child_nodes(self):
self.node.is_deleted = True
self.node.save()
self.node.reload()
assert_false(self.parent.nodes_active)
def test_register_node_makes_private_registration(self):
user = UserFactory()
node = NodeFactory(creator=user)
node.is_public = True
node.save()
registration = node.register_node(get_default_metaschema(), Auth(user), '', None)
assert_false(registration.is_public)
def test_register_node_makes_private_child_registrations(self):
user = UserFactory()
node = NodeFactory(creator=user)
node.is_public = True
node.save()
child = NodeFactory(parent=node)
child.is_public = True
child.save()
childchild = NodeFactory(parent=child)
childchild.is_public = True
childchild.save()
registration = node.register_node(get_default_metaschema(), Auth(user), '', None)
for node in registration.node_and_primary_descendants():
assert_false(node.is_public)
@mock.patch('website.project.signals.after_create_registration')
def test_register_node_propagates_schema_and_data_to_children(self, mock_signal):
root = ProjectFactory(creator=self.user)
c1 = ProjectFactory(creator=self.user, parent=root)
ProjectFactory(creator=self.user, parent=c1)
ensure_schemas()
meta_schema = MetaSchema.find_one(
Q('name', 'eq', 'Open-Ended Registration') &
Q('schema_version', 'eq', 1)
)
data = {'some': 'data'}
reg = root.register_node(
schema=meta_schema,
auth=self.auth,
data=data,
)
r1 = reg.nodes[0]
r1a = r1.nodes[0]
for r in [reg, r1, r1a]:
assert_equal(r.registered_meta[meta_schema._id], data)
assert_equal(r.registered_schema[0], meta_schema)
class TestNodeUpdate(OsfTestCase):
def setUp(self):
super(TestNodeUpdate, self).setUp()
self.user = UserFactory()
self.node = ProjectFactory(creator=self.user, category='project', is_public=False)
def test_update_title(self):
# Creator (admin) can update
new_title = fake.catch_phrase()
self.node.update({'title': new_title}, auth=Auth(self.user), save=True)
assert_equal(self.node.title, new_title)
last_log = self.node.logs[-1]
assert_equal(last_log.action, NodeLog.EDITED_TITLE)
# Write contrib can update
new_title2 = fake.catch_phrase()
write_contrib = UserFactory()
self.node.add_contributor(write_contrib, auth=Auth(self.user), permissions=(READ, WRITE))
self.node.save()
self.node.update({'title': new_title2}, auth=Auth(write_contrib))
assert_equal(self.node.title, new_title2)
def test_update_description(self):
new_title = fake.bs()
self.node.update({'title': new_title}, auth=Auth(self.user))
assert_equal(self.node.title, new_title)
last_log = self.node.logs[-1]
assert_equal(last_log.action, NodeLog.EDITED_TITLE)
def test_update_title_and_category(self):
new_title = fake.bs()
new_category = 'data'
self.node.update({'title': new_title, 'category': new_category}, auth=Auth(self.user), save=True)
assert_equal(self.node.title, new_title)
assert_equal(self.node.category, 'data')
penultimate_log, last_log = self.node.logs[-2], self.node.logs[-1]
assert_equal(penultimate_log.action, NodeLog.EDITED_TITLE)
assert_equal(last_log.action, NodeLog.UPDATED_FIELDS)
def test_update_is_public(self):
self.node.update({'is_public': True}, auth=Auth(self.user), save=True)
assert_true(self.node.is_public)
last_log = self.node.logs[-1]
assert_equal(last_log.action, NodeLog.MADE_PUBLIC)
self.node.update({'is_public': False}, auth=Auth(self.user), save=True)
last_log = self.node.logs[-1]
assert_equal(last_log.action, NodeLog.MADE_PRIVATE)
def test_updating_title_twice_with_same_title(self):
original_n_logs = len(self.node.logs)
new_title = fake.bs()
self.node.update({'title': new_title}, auth=Auth(self.user), save=True)
assert_equal(len(self.node.logs), original_n_logs + 1) # sanity check
# Call update with same title
self.node.update({'title': new_title}, auth=Auth(self.user), save=True)
# A new log is not created
assert_equal(len(self.node.logs), original_n_logs + 1)
def test_updating_description_twice_with_same_content(self):
original_n_logs = len(self.node.logs)
new_desc = fake.bs()
self.node.update({'description': new_desc}, auth=Auth(self.user), save=True)
assert_equal(len(self.node.logs), original_n_logs + 1) # sanity check
# Call update with same description
self.node.update({'description': new_desc}, auth=Auth(self.user), save=True)
# A new log is not created
assert_equal(len(self.node.logs), original_n_logs + 1)
# Regression test for https://openscience.atlassian.net/browse/OSF-4664
def test_updating_category_twice_with_same_content_generates_one_log(self):
self.node.category = 'project'
self.node.save()
original_n_logs = len(self.node.logs)
new_category = 'data'
self.node.update({'category': new_category}, auth=Auth(self.user), save=True)
assert_equal(len(self.node.logs), original_n_logs + 1) # sanity check
assert_equal(self.node.category, new_category)
# Call update with same category
self.node.update({'category': new_category}, auth=Auth(self.user), save=True)
# Only one new log is created
assert_equal(len(self.node.logs), original_n_logs + 1)
assert_equal(self.node.category, new_category)
# TODO: test permissions, non-writable fields
class TestNodeTraversals(OsfTestCase):
def setUp(self):
super(TestNodeTraversals, self).setUp()
self.viewer = AuthUserFactory()
self.user = UserFactory()
self.auth = Auth(user=self.user)
self.root = ProjectFactory(creator=self.user)
def test_next_descendants(self):
comp1 = ProjectFactory(creator=self.user, parent=self.root)
comp1a = ProjectFactory(creator=self.user, parent=comp1)
comp1a.add_contributor(self.viewer, auth=self.auth, permissions='read')
ProjectFactory(creator=self.user, parent=comp1)
comp2 = ProjectFactory(creator=self.user, parent=self.root)
comp2.add_contributor(self.viewer, auth=self.auth, permissions='read')
comp2a = ProjectFactory(creator=self.user, parent=comp2)
comp2a.add_contributor(self.viewer, auth=self.auth, permissions='read')
ProjectFactory(creator=self.user, parent=comp2)
descendants = self.root.next_descendants(
Auth(self.viewer),
condition=lambda auth, node: node.is_contributor(auth.user)
)
assert_equal(len(descendants), 2) # two immediate children
assert_equal(len(descendants[0][1]), 1) # only one visible child of comp1
assert_equal(len(descendants[1][1]), 0) # don't auto-include comp2's children
def test_delete_registration_tree(self):
proj = NodeFactory()
NodeFactory(parent=proj)
comp2 = NodeFactory(parent=proj)
NodeFactory(parent=comp2)
reg = RegistrationFactory(project=proj)
reg_ids = [reg._id] + [r._id for r in reg.get_descendants_recursive()]
reg.delete_registration_tree(save=True)
assert_false(Node.find(Q('_id', 'in', reg_ids) & Q('is_deleted', 'eq', False)).count())
def test_delete_registration_tree_deletes_backrefs(self):
proj = NodeFactory()
NodeFactory(parent=proj)
comp2 = NodeFactory(parent=proj)
NodeFactory(parent=comp2)
reg = RegistrationFactory(project=proj)
reg.delete_registration_tree(save=True)
assert_false(proj.node__registrations)
def test_get_active_contributors_recursive_with_duplicate_users(self):
parent = ProjectFactory(creator=self.user)
child = ProjectFactory(creator=self.viewer, parent=parent)
child_non_admin = UserFactory()
child.add_contributor(child_non_admin,
auth=self.auth,
permissions=expand_permissions(WRITE))
grandchild = ProjectFactory(creator=self.user, parent=child)
contributors = list(parent.get_active_contributors_recursive())
assert_equal(len(contributors), 4)
user_ids = [user._id for user, node in contributors]
assert_in(self.user._id, user_ids)
assert_in(self.viewer._id, user_ids)
assert_in(child_non_admin._id, user_ids)
node_ids = [node._id for user, node in contributors]
assert_in(parent._id, node_ids)
assert_in(grandchild._id, node_ids)
def test_get_active_contributors_recursive_with_no_duplicate_users(self):
parent = ProjectFactory(creator=self.user)
child = ProjectFactory(creator=self.viewer, parent=parent)
child_non_admin = UserFactory()
child.add_contributor(child_non_admin,
auth=self.auth,
permissions=expand_permissions(WRITE))
grandchild = ProjectFactory(creator=self.user, parent=child) # noqa
contributors = list(parent.get_active_contributors_recursive(unique_users=True))
assert_equal(len(contributors), 3)
user_ids = [user._id for user, node in contributors]
assert_in(self.user._id, user_ids)
assert_in(self.viewer._id, user_ids)
assert_in(child_non_admin._id, user_ids)
node_ids = [node._id for user, node in contributors]
assert_in(parent._id, node_ids)
def test_get_admin_contributors_recursive_with_duplicate_users(self):
parent = ProjectFactory(creator=self.user)
child = ProjectFactory(creator=self.viewer, parent=parent)
child_non_admin = UserFactory()
child.add_contributor(child_non_admin,
auth=self.auth,
permissions=expand_permissions(WRITE))
child.save()
grandchild = ProjectFactory(creator=self.user, parent=child) # noqa
admins = list(parent.get_admin_contributors_recursive())
assert_equal(len(admins), 3)
admin_ids = [user._id for user, node in admins]
assert_in(self.user._id, admin_ids)
assert_in(self.viewer._id, admin_ids)
node_ids = [node._id for user, node in admins]
assert_in(parent._id, node_ids)
def test_get_admin_contributors_recursive_no_duplicates(self):
parent = ProjectFactory(creator=self.user)
child = ProjectFactory(creator=self.viewer, parent=parent)
child_non_admin = UserFactory()
child.add_contributor(child_non_admin,
auth=self.auth,
permissions=expand_permissions(WRITE))
child.save()
grandchild = ProjectFactory(creator=self.user, parent=child) # noqa
admins = list(parent.get_admin_contributors_recursive(unique_users=True))
assert_equal(len(admins), 2)
admin_ids = [user._id for user, node in admins]
assert_in(self.user._id, admin_ids)
assert_in(self.viewer._id, admin_ids)
def test_get_descendants_recursive(self):
comp1 = ProjectFactory(creator=self.user, parent=self.root)
comp1a = ProjectFactory(creator=self.user, parent=comp1)
comp1a.add_contributor(self.viewer, auth=self.auth, permissions='read')
comp1b = ProjectFactory(creator=self.user, parent=comp1)
comp2 = ProjectFactory(creator=self.user, parent=self.root)
comp2.add_contributor(self.viewer, auth=self.auth, permissions='read')
comp2a = ProjectFactory(creator=self.user, parent=comp2)
comp2a.add_contributor(self.viewer, auth=self.auth, permissions='read')
comp2b = ProjectFactory(creator=self.user, parent=comp2)
descendants = self.root.get_descendants_recursive()
ids = {d._id for d in descendants}
assert_false({node._id for node in [comp1, comp1a, comp1b, comp2, comp2a, comp2b]}.difference(ids))
def test_get_descendants_recursive_filtered(self):
comp1 = ProjectFactory(creator=self.user, parent=self.root)
comp1a = ProjectFactory(creator=self.user, parent=comp1)
comp1a.add_contributor(self.viewer, auth=self.auth, permissions='read')
ProjectFactory(creator=self.user, parent=comp1)
comp2 = ProjectFactory(creator=self.user, parent=self.root)
comp2.add_contributor(self.viewer, auth=self.auth, permissions='read')
comp2a = ProjectFactory(creator=self.user, parent=comp2)
comp2a.add_contributor(self.viewer, auth=self.auth, permissions='read')
ProjectFactory(creator=self.user, parent=comp2)
descendants = self.root.get_descendants_recursive(
lambda n: n.is_contributor(self.viewer)
)
ids = {d._id for d in descendants}
nids = {node._id for node in [comp1a, comp2, comp2a]}
assert_false(ids.difference(nids))
def test_get_descendants_recursive_cyclic(self):
point1 = ProjectFactory(creator=self.user, parent=self.root)
point2 = ProjectFactory(creator=self.user, parent=self.root)
point1.add_pointer(point2, auth=self.auth)
point2.add_pointer(point1, auth=self.auth)
descendants = list(point1.get_descendants_recursive())
assert_equal(len(descendants), 1)
class TestRemoveNode(OsfTestCase):
def setUp(self):
super(TestRemoveNode, self).setUp()
# Create project with component
self.user = UserFactory()
self.auth = Auth(user=self.user)
self.parent_project = ProjectFactory(creator=self.user)
self.project = ProjectFactory(creator=self.user,
parent=self.parent_project)
def test_remove_project_without_children(self):
self.project.remove_node(auth=self.auth)
assert_true(self.project.is_deleted)
# parent node should have a log of the event
assert_equal(
self.parent_project.get_aggregate_logs_queryset(self.auth)[0].action,
'node_removed'
)
def test_delete_project_log_present(self):
self.project.remove_node(auth=self.auth)
self.parent_project.remove_node(auth=self.auth)
assert_true(self.parent_project.is_deleted)
# parent node should have a log of the event
assert_equal(self.parent_project.logs[-1].action, 'project_deleted')
def test_remove_project_with_project_child_fails(self):
with assert_raises(NodeStateError):
self.parent_project.remove_node(self.auth)
def test_remove_project_with_component_child_fails(self):
NodeFactory(creator=self.user, parent=self.project)
with assert_raises(NodeStateError):
self.parent_project.remove_node(self.auth)
def test_remove_project_with_pointer_child(self):
target = ProjectFactory(creator=self.user)
self.project.add_pointer(node=target, auth=self.auth)
assert_equal(len(self.project.nodes), 1)
self.project.remove_node(auth=self.auth)
assert_true(self.project.is_deleted)
# parent node should have a log of the event
assert_equal(self.parent_project.logs[-1].action, 'node_removed')
# target node shouldn't be deleted
assert_false(target.is_deleted)
class TestDashboard(OsfTestCase):
def setUp(self):
super(TestDashboard, self).setUp()
# Create project with component
self.user = UserFactory()
self.auth = Auth(user=self.user)
self.project = DashboardFactory(creator=self.user)
def test_dashboard_is_dashboard(self):
assert_equal(self.project.is_dashboard, True)
def test_dashboard_is_folder(self):
assert_equal(self.project.is_folder, True)
def test_cannot_remove_dashboard(self):
with assert_raises(NodeStateError):
self.project.remove_node(self.auth)
def test_cannot_have_two_dashboards(self):
with assert_raises(NodeStateError):
DashboardFactory(creator=self.user)
def test_cannot_link_to_dashboard(self):
new_node = ProjectFactory(creator=self.user)
with assert_raises(ValueError):
new_node.add_pointer(self.project, auth=self.auth)
def test_can_remove_empty_folder(self):
new_folder = FolderFactory(creator=self.user)
assert_equal(new_folder.is_folder, True)
new_folder.remove_node(auth=self.auth)
assert_true(new_folder.is_deleted)
def test_can_remove_folder_structure(self):
outer_folder = FolderFactory(creator=self.user)
assert_equal(outer_folder.is_folder, True)
inner_folder = FolderFactory(creator=self.user)
assert_equal(inner_folder.is_folder, True)
outer_folder.add_pointer(inner_folder, self.auth)
outer_folder.remove_node(auth=self.auth)
assert_true(outer_folder.is_deleted)
assert_true(inner_folder.is_deleted)
class TestAddonCallbacks(OsfTestCase):
"""Verify that callback functions are called at the right times, with the
right arguments.
"""
callbacks = {
'after_remove_contributor': None,
'after_set_privacy': None,
'after_fork': (None, None),
'after_register': (None, None),
}
def setUp(self):
super(TestAddonCallbacks, self).setUp()
# Create project with component
self.user = UserFactory()
self.auth = Auth(user=self.user)
self.parent = ProjectFactory()
self.node = NodeFactory(creator=self.user, project=self.parent)
# Mock addon callbacks
for addon in self.node.addons:
mock_settings = mock.create_autospec(addon.__class__)
for callback, return_value in self.callbacks.iteritems():
mock_callback = getattr(mock_settings, callback)
mock_callback.return_value = return_value
setattr(
addon,
callback,
getattr(mock_settings, callback)
)
def test_remove_contributor_callback(self):
user2 = UserFactory()
self.node.add_contributor(contributor=user2, auth=self.auth)
self.node.remove_contributor(contributor=user2, auth=self.auth)
for addon in self.node.addons:
callback = addon.after_remove_contributor
callback.assert_called_once_with(
self.node, user2, self.auth
)
def test_set_privacy_callback(self):
self.node.set_privacy('public', self.auth)
for addon in self.node.addons:
callback = addon.after_set_privacy
callback.assert_called_with(
self.node, 'public',
)
self.node.set_privacy('private', self.auth)
for addon in self.node.addons:
callback = addon.after_set_privacy
callback.assert_called_with(
self.node, 'private'
)
def test_fork_callback(self):
fork = self.node.fork_node(auth=self.auth)
for addon in self.node.addons:
callback = addon.after_fork
callback.assert_called_once_with(
self.node, fork, self.user
)
def test_register_callback(self):
with mock_archive(self.node) as registration:
for addon in self.node.addons:
callback = addon.after_register
callback.assert_called_once_with(
self.node, registration, self.user
)
class TestProject(OsfTestCase):
def setUp(self):
super(TestProject, self).setUp()
# Create project
self.user = UserFactory()
self.auth = Auth(user=self.user)
self.project = ProjectFactory(creator=self.user, description='foobar')
def test_repr(self):
assert_in(self.project.title, repr(self.project))
assert_in(self.project._id, repr(self.project))
def test_project_factory(self):
node = ProjectFactory()
assert_equal(node.category, 'project')
assert_true(node._id)
assert_almost_equal(
node.date_created, datetime.datetime.utcnow(),
delta=datetime.timedelta(seconds=5),
)
assert_false(node.is_public)
assert_false(node.is_deleted)
assert_true(hasattr(node, 'deleted_date'))
assert_false(node.is_registration)
assert_true(hasattr(node, 'registered_date'))
assert_false(node.is_fork)
assert_true(hasattr(node, 'forked_date'))
assert_true(node.title)
assert_true(hasattr(node, 'description'))
assert_true(hasattr(node, 'registered_meta'))
assert_true(hasattr(node, 'registered_user'))
assert_true(hasattr(node, 'registered_schema'))
assert_true(node.creator)
assert_true(node.contributors)
assert_equal(len(node.logs), 1)
assert_true(hasattr(node, 'tags'))
assert_true(hasattr(node, 'nodes'))
assert_true(hasattr(node, 'forked_from'))
assert_true(hasattr(node, 'registered_from'))
assert_equal(node.logs[-1].action, 'project_created')
def test_log(self):
latest_log = self.project.logs[-1]
assert_equal(latest_log.action, 'project_created')
assert_equal(latest_log.params['node'], self.project._primary_key)
assert_equal(latest_log.user, self.user)
def test_url(self):
assert_equal(
self.project.url,
'/{0}/'.format(self.project._primary_key)
)
def test_api_url(self):
api_url = self.project.api_url
assert_equal(api_url, '/api/v1/project/{0}/'.format(self.project._primary_key))
def test_watch_url(self):
watch_url = self.project.watch_url
assert_equal(
watch_url,
'/api/v1/project/{0}/watch/'.format(self.project._primary_key)
)
def test_parent_id(self):
assert_false(self.project.parent_id)
def test_watching(self):
# A user watched a node
user = UserFactory()
config1 = WatchConfigFactory(node=self.project)
user.watched.append(config1)
user.save()
assert_in(config1._id, self.project.watchconfig__watched)
def test_add_contributor(self):
# A user is added as a contributor
user2 = UserFactory()
self.project.add_contributor(contributor=user2, auth=self.auth)
self.project.save()
assert_in(user2, self.project.contributors)
assert_equal(self.project.logs[-1].action, 'contributor_added')
def test_add_contributor_sends_contributor_added_signal(self):
user = UserFactory()
contributors = [{
'user': user,
'visible': True,
'permissions': ['read', 'write']
}]
with capture_signals() as mock_signals:
self.project.add_contributors(contributors=contributors, auth=self.auth)
self.project.save()
assert_in(user, self.project.contributors)
assert_equal(mock_signals.signals_sent(), set([contributor_added]))
def test_add_unregistered_contributor(self):
self.project.add_unregistered_contributor(
email='foo@bar.com',
fullname='Weezy F. Baby',
auth=self.auth
)
self.project.save()
latest_contributor = self.project.contributors[-1]
assert_true(isinstance(latest_contributor, User))
assert_equal(latest_contributor.username, 'foo@bar.com')
assert_equal(latest_contributor.fullname, 'Weezy F. Baby')
assert_false(latest_contributor.is_registered)
# A log event was added
assert_equal(self.project.logs[-1].action, 'contributor_added')
assert_in(self.project._primary_key, latest_contributor.unclaimed_records,
'unclaimed record was added')
unclaimed_data = latest_contributor.get_unclaimed_record(self.project._primary_key)
assert_equal(unclaimed_data['referrer_id'],
self.auth.user._primary_key)
assert_true(self.project.is_contributor(latest_contributor))
assert_equal(unclaimed_data['email'], 'foo@bar.com')
def test_add_unregistered_adds_new_unclaimed_record_if_user_already_in_db(self):
user = UnregUserFactory()
given_name = fake.name()
new_user = self.project.add_unregistered_contributor(
email=user.username,
fullname=given_name,
auth=self.auth
)
self.project.save()
# new unclaimed record was added
assert_in(self.project._primary_key, new_user.unclaimed_records)
unclaimed_data = new_user.get_unclaimed_record(self.project._primary_key)
assert_equal(unclaimed_data['name'], given_name)
def test_add_unregistered_raises_error_if_user_is_registered(self):
user = UserFactory(is_registered=True) # A registered user
with assert_raises(ValidationValueError):
self.project.add_unregistered_contributor(
email=user.username,
fullname=user.fullname,
auth=self.auth
)
def test_remove_contributor(self):
# A user is added as a contributor
user2 = UserFactory()
self.project.add_contributor(contributor=user2, auth=self.auth)
self.project.save()
# The user is removed
self.project.remove_contributor(
auth=self.auth,
contributor=user2
)
self.project.reload()
assert_not_in(user2, self.project.contributors)
assert_not_in(user2._id, self.project.permissions)
assert_equal(self.project.logs[-1].action, 'contributor_removed')
assert_equal(self.project.logs[-1].params['contributors'], [user2._id])
def test_manage_contributors_cannot_remove_last_admin_contributor(self):
user2 = UserFactory()
self.project.add_contributor(contributor=user2, permissions=['read', 'write'], auth=self.auth)
self.project.save()
with assert_raises(ValueError):
self.project.manage_contributors(
user_dicts=[{'id': user2._id,
'permission': 'write',
'visible': True}],
auth=self.auth,
save=True
)
def test_manage_contributors_logs_when_users_reorder(self):
user2 = UserFactory()
self.project.add_contributor(contributor=user2, permissions=['read', 'write'], auth=self.auth)
self.project.save()
self.project.manage_contributors(
user_dicts=[
{
'id': user2._id,
'permission': 'write',
'visible': True,
},
{
'id': self.user._id,
'permission': 'admin',
'visible': True,
},
],
auth=self.auth,
save=True
)
latest_log = self.project.logs[-1]
assert_equal(latest_log.action, NodeLog.CONTRIB_REORDERED)
assert_equal(latest_log.user, self.user)
assert_in(self.user._id, latest_log.params['contributors'])
assert_in(user2._id, latest_log.params['contributors'])
def test_add_private_link(self):
link = PrivateLinkFactory()
link.nodes.append(self.project)
link.save()
assert_in(link, self.project.private_links)
@mock.patch('framework.auth.core.Auth.private_link')
def test_has_anonymous_link(self, mock_property):
mock_property.return_value(mock.MagicMock())
mock_property.anonymous = True
link1 = PrivateLinkFactory(key="link1")
link1.nodes.append(self.project)
link1.save()
user2 = UserFactory()
auth2 = Auth(user=user2, private_key="link1")
assert_true(has_anonymous_link(self.project, auth2))
@mock.patch('framework.auth.core.Auth.private_link')
def test_has_no_anonymous_link(self, mock_property):
mock_property.return_value(mock.MagicMock())
mock_property.anonymous = False
link2 = PrivateLinkFactory(key="link2")
link2.nodes.append(self.project)
link2.save()
user3 = UserFactory()
auth3 = Auth(user=user3, private_key="link2")
assert_false(has_anonymous_link(self.project, auth3))
def test_remove_unregistered_conributor_removes_unclaimed_record(self):
new_user = self.project.add_unregistered_contributor(fullname=fake.name(),
email=fake.email(), auth=Auth(self.project.creator))
self.project.save()
assert_true(self.project.is_contributor(new_user)) # sanity check
assert_in(self.project._primary_key, new_user.unclaimed_records)
self.project.remove_contributor(
auth=self.auth,
contributor=new_user
)
self.project.save()
assert_not_in(self.project._primary_key, new_user.unclaimed_records)
def test_manage_contributors_new_contributor(self):
user = UserFactory()
users = [
{'id': self.project.creator._id, 'permission': 'read', 'visible': True},
{'id': user._id, 'permission': 'read', 'visible': True},
]
with assert_raises(ValueError):
self.project.manage_contributors(
users, auth=self.auth, save=True
)
def test_manage_contributors_no_contributors(self):
with assert_raises(ValueError):
self.project.manage_contributors(
[], auth=self.auth, save=True,
)
def test_manage_contributors_no_admins(self):
user = UserFactory()
self.project.add_contributor(
user,
permissions=['read', 'write', 'admin'],
save=True
)
users = [
{'id': self.project.creator._id, 'permission': 'read', 'visible': True},
{'id': user._id, 'permission': 'read', 'visible': True},
]
with assert_raises(ValueError):
self.project.manage_contributors(
users, auth=self.auth, save=True,
)
def test_manage_contributors_no_registered_admins(self):
unregistered = UnregUserFactory()
self.project.add_contributor(
unregistered,
permissions=['read', 'write', 'admin'],
save=True
)
users = [
{'id': self.project.creator._id, 'permission': 'read', 'visible': True},
{'id': unregistered._id, 'permission': 'admin', 'visible': True},
]
with assert_raises(ValueError):
self.project.manage_contributors(
users, auth=self.auth, save=True,
)
def test_set_title_works_with_valid_title(self):
proj = ProjectFactory(title='That Was Then', creator=self.user)
proj.set_title('This is now', auth=self.auth)
proj.save()
# Title was changed
assert_equal(proj.title, 'This is now')
# A log event was saved
latest_log = proj.logs[-1]
assert_equal(latest_log.action, 'edit_title')
assert_equal(latest_log.params['title_original'], 'That Was Then')
def test_set_title_fails_if_empty_or_whitespace(self):
proj = ProjectFactory(title='That Was Then', creator=self.user)
with assert_raises(ValidationValueError):
proj.set_title(' ', auth=self.auth)
with assert_raises(ValidationValueError):
proj.set_title('', auth=self.auth)
#assert_equal(proj.title, 'That Was Then')
def test_set_title_fails_if_too_long(self):
proj = ProjectFactory(title='That Was Then', creator=self.user)
long_title = ''.join(random.choice(string.ascii_letters + string.digits)
for _ in range(201))
with assert_raises(ValidationValueError):
proj.set_title(long_title, auth=self.auth)
def test_title_cant_be_empty(self):
with assert_raises(ValidationValueError):
proj = ProjectFactory(title='', creator=self.user)
with assert_raises(ValidationValueError):
proj = ProjectFactory(title=' ', creator=self.user)
def test_title_cant_be_too_long(self):
long_title = ''.join(random.choice(string.ascii_letters + string.digits)
for _ in range(201))
with assert_raises(ValidationValueError):
proj = ProjectFactory(title=long_title, creator=self.user)
def test_contributor_can_edit(self):
contributor = UserFactory()
contributor_auth = Auth(user=contributor)
other_guy = UserFactory()
other_guy_auth = Auth(user=other_guy)
self.project.add_contributor(
contributor=contributor, auth=self.auth)
self.project.save()
assert_true(self.project.can_edit(contributor_auth))
assert_false(self.project.can_edit(other_guy_auth))
def test_can_edit_can_be_passed_a_user(self):
assert_true(self.project.can_edit(user=self.user))
def test_creator_can_edit(self):
assert_true(self.project.can_edit(self.auth))
def test_noncontributor_cant_edit_public(self):
user1 = UserFactory()
user1_auth = Auth(user=user1)
# Change project to public
self.project.set_privacy('public')
self.project.save()
# Noncontributor can't edit
assert_false(self.project.can_edit(user1_auth))
def test_can_view_private(self):
# Create contributor and noncontributor
link = PrivateLinkFactory()
link.nodes.append(self.project)
link.save()
contributor = UserFactory()
contributor_auth = Auth(user=contributor)
other_guy = UserFactory()
other_guy_auth = Auth(user=other_guy)
self.project.add_contributor(
contributor=contributor, auth=self.auth)
self.project.save()
# Only creator and contributor can view
assert_true(self.project.can_view(self.auth))
assert_true(self.project.can_view(contributor_auth))
assert_false(self.project.can_view(other_guy_auth))
other_guy_auth.private_key = link.key
assert_true(self.project.can_view(other_guy_auth))
def test_is_admin_parent_target_admin(self):
assert_true(self.project.is_admin_parent(self.project.creator))
def test_is_admin_parent_parent_admin(self):
user = UserFactory()
node = NodeFactory(parent=self.project, creator=user)
assert_true(node.is_admin_parent(self.project.creator))
def test_is_admin_parent_grandparent_admin(self):
user = UserFactory()
parent_node = NodeFactory(
parent=self.project,
category='project',
creator=user
)
child_node = NodeFactory(parent=parent_node, creator=user)
assert_true(child_node.is_admin_parent(self.project.creator))
assert_true(parent_node.is_admin_parent(self.project.creator))
def test_is_admin_parent_parent_write(self):
user = UserFactory()
node = NodeFactory(parent=self.project, creator=user)
self.project.set_permissions(self.project.creator, ['read', 'write'])
assert_false(node.is_admin_parent(self.project.creator))
def test_has_permission_read_parent_admin(self):
user = UserFactory()
node = NodeFactory(parent=self.project, creator=user)
assert_true(node.has_permission(self.project.creator, 'read'))
assert_false(node.has_permission(self.project.creator, 'admin'))
def test_has_permission_read_grandparent_admin(self):
user = UserFactory()
parent_node = NodeFactory(
parent=self.project,
category='project',
creator=user
)
child_node = NodeFactory(
parent=parent_node,
creator=user
)
assert_true(child_node.has_permission(self.project.creator, 'read'))
assert_false(child_node.has_permission(self.project.creator, 'admin'))
assert_true(parent_node.has_permission(self.project.creator, 'read'))
assert_false(parent_node.has_permission(self.project.creator, 'admin'))
def test_can_view_parent_admin(self):
user = UserFactory()
node = NodeFactory(parent=self.project, creator=user)
assert_true(node.can_view(Auth(user=self.project.creator)))
assert_false(node.can_edit(Auth(user=self.project.creator)))
def test_can_view_grandparent_admin(self):
user = UserFactory()
parent_node = NodeFactory(
parent=self.project,
creator=user,
category='project'
)
child_node = NodeFactory(
parent=parent_node,
creator=user
)
assert_true(parent_node.can_view(Auth(user=self.project.creator)))
assert_false(parent_node.can_edit(Auth(user=self.project.creator)))
assert_true(child_node.can_view(Auth(user=self.project.creator)))
assert_false(child_node.can_edit(Auth(user=self.project.creator)))
def test_can_view_parent_write(self):
user = UserFactory()
node = NodeFactory(parent=self.project, creator=user)
self.project.set_permissions(self.project.creator, ['read', 'write'])
assert_false(node.can_view(Auth(user=self.project.creator)))
assert_false(node.can_edit(Auth(user=self.project.creator)))
def test_creator_cannot_edit_project_if_they_are_removed(self):
creator = UserFactory()
project = ProjectFactory(creator=creator)
contrib = UserFactory()
project.add_contributor(contrib, permissions=['read', 'write', 'admin'], auth=Auth(user=creator))
project.save()
assert_in(creator, project.contributors)
# Creator is removed from project
project.remove_contributor(creator, auth=Auth(user=contrib))
assert_false(project.can_view(Auth(user=creator)))
assert_false(project.can_edit(Auth(user=creator)))
assert_false(project.is_contributor(creator))
def test_can_view_public(self):
# Create contributor and noncontributor
contributor = UserFactory()
contributor_auth = Auth(user=contributor)
other_guy = UserFactory()
other_guy_auth = Auth(user=other_guy)
self.project.add_contributor(
contributor=contributor, auth=self.auth)
# Change project to public
self.project.set_privacy('public')
self.project.save()
# Creator, contributor, and noncontributor can view
assert_true(self.project.can_view(self.auth))
assert_true(self.project.can_view(contributor_auth))
assert_true(self.project.can_view(other_guy_auth))
def test_parents(self):
child1 = ProjectFactory(parent=self.project)
child2 = ProjectFactory(parent=child1)
assert_equal(self.project.parents, [])
assert_equal(child1.parents, [self.project])
assert_equal(child2.parents, [child1, self.project])
def test_admin_contributor_ids(self):
assert_equal(self.project.admin_contributor_ids, set())
child1 = ProjectFactory(parent=self.project)
child2 = ProjectFactory(parent=child1)
assert_equal(child1.admin_contributor_ids, {self.project.creator._id})
assert_equal(child2.admin_contributor_ids, {self.project.creator._id, child1.creator._id})
self.project.set_permissions(self.project.creator, ['read', 'write'])
self.project.save()
assert_equal(child1.admin_contributor_ids, set())
assert_equal(child2.admin_contributor_ids, {child1.creator._id})
def test_admin_contributors(self):
assert_equal(self.project.admin_contributors, [])
child1 = ProjectFactory(parent=self.project)
child2 = ProjectFactory(parent=child1)
assert_equal(child1.admin_contributors, [self.project.creator])
assert_equal(
child2.admin_contributors,
sorted([self.project.creator, child1.creator], key=lambda user: user.family_name)
)
self.project.set_permissions(self.project.creator, ['read', 'write'])
self.project.save()
assert_equal(child1.admin_contributors, [])
assert_equal(child2.admin_contributors, [child1.creator])
def test_is_contributor(self):
contributor = UserFactory()
other_guy = UserFactory()
self.project.add_contributor(
contributor=contributor, auth=self.auth)
self.project.save()
assert_true(self.project.is_contributor(contributor))
assert_false(self.project.is_contributor(other_guy))
assert_false(self.project.is_contributor(None))
def test_is_fork_of(self):
project = ProjectFactory()
fork1 = project.fork_node(auth=Auth(user=project.creator))
fork2 = fork1.fork_node(auth=Auth(user=project.creator))
assert_true(fork1.is_fork_of(project))
assert_true(fork2.is_fork_of(project))
def test_is_fork_of_false(self):
project = ProjectFactory()
to_fork = ProjectFactory()
fork = to_fork.fork_node(auth=Auth(user=to_fork.creator))
assert_false(fork.is_fork_of(project))
def test_is_fork_of_no_forked_from(self):
project = ProjectFactory()
assert_false(project.is_fork_of(self.project))
def test_is_registration_of(self):
project = ProjectFactory()
with mock_archive(project) as reg1:
with mock_archive(reg1) as reg2:
assert_true(reg1.is_registration_of(project))
assert_true(reg2.is_registration_of(project))
def test_is_registration_of_false(self):
project = ProjectFactory()
to_reg = ProjectFactory()
with mock_archive(to_reg) as reg:
assert_false(reg.is_registration_of(project))
def test_raises_permissions_error_if_not_a_contributor(self):
project = ProjectFactory()
user = UserFactory()
with assert_raises(PermissionsError):
project.register_node(None, Auth(user=user), '', None)
def test_admin_can_register_private_children(self):
user = UserFactory()
project = ProjectFactory(creator=user)
project.set_permissions(user, ['admin', 'write', 'read'])
child = NodeFactory(parent=project, is_public=False)
assert_false(child.can_edit(auth=Auth(user=user))) # sanity check
with mock_archive(project, None, Auth(user=user), '', None) as registration:
# child was registered
child_registration = registration.nodes[0]
assert_equal(child_registration.registered_from, child)
def test_is_registration_of_no_registered_from(self):
project = ProjectFactory()
assert_false(project.is_registration_of(self.project))
def test_registration_preserves_license(self):
license = NodeLicenseRecordFactory()
self.project.node_license = license
self.project.save()
with mock_archive(self.project, autocomplete=True) as registration:
assert_equal(registration.node_license.id, license.id)
def test_is_contributor_unregistered(self):
unreg = UnregUserFactory()
self.project.add_unregistered_contributor(
fullname=fake.name(),
email=unreg.username,
auth=self.auth
)
self.project.save()
assert_true(self.project.is_contributor(unreg))
def test_creator_is_contributor(self):
assert_true(self.project.is_contributor(self.user))
assert_in(self.user, self.project.contributors)
def test_cant_add_creator_as_contributor_twice(self):
self.project.add_contributor(contributor=self.user)
self.project.save()
assert_equal(len(self.project.contributors), 1)
def test_cant_add_same_contributor_twice(self):
contrib = UserFactory()
self.project.add_contributor(contributor=contrib)
self.project.save()
self.project.add_contributor(contributor=contrib)
self.project.save()
assert_equal(len(self.project.contributors), 2)
def test_add_contributors(self):
user1 = UserFactory()
user2 = UserFactory()
self.project.add_contributors(
[
{'user': user1, 'permissions': ['read', 'write', 'admin'], 'visible': True},
{'user': user2, 'permissions': ['read', 'write'], 'visible': False}
],
auth=self.auth
)
self.project.save()
assert_equal(len(self.project.contributors), 3)
assert_equal(
self.project.logs[-1].params['contributors'],
[user1._id, user2._id]
)
assert_in(user1._id, self.project.permissions)
assert_in(user2._id, self.project.permissions)
assert_in(user1._id, self.project.visible_contributor_ids)
assert_not_in(user2._id, self.project.visible_contributor_ids)
assert_equal(self.project.permissions[user1._id], ['read', 'write', 'admin'])
assert_equal(self.project.permissions[user2._id], ['read', 'write'])
assert_equal(
self.project.logs[-1].params['contributors'],
[user1._id, user2._id]
)
def test_set_privacy(self):
self.project.set_privacy('public', auth=self.auth)
self.project.save()
assert_true(self.project.is_public)
assert_equal(self.project.logs[-1].action, 'made_public')
self.project.set_privacy('private', auth=self.auth)
self.project.save()
assert_false(self.project.is_public)
assert_equal(self.project.logs[-1].action, NodeLog.MADE_PRIVATE)
@mock.patch('website.project.model.mails.queue_mail')
def test_set_privacy_sends_mail_default(self, mock_queue):
self.project.set_privacy('private', auth=self.auth)
self.project.set_privacy('public', auth=self.auth)
assert_true(mock_queue.called_once())
@mock.patch('website.project.model.mails.queue_mail')
def test_set_privacy_sends_mail(self, mock_queue):
self.project.set_privacy('private', auth=self.auth)
self.project.set_privacy('public', auth=self.auth, meeting_creation=False)
assert_true(mock_queue.called_once())
@mock.patch('website.project.model.mails.queue_mail')
def test_set_privacy_skips_mail(self, mock_queue):
self.project.set_privacy('private', auth=self.auth)
self.project.set_privacy('public', auth=self.auth, meeting_creation=True)
assert_false(mock_queue.called)
def test_set_privacy_can_not_cancel_pending_embargo_for_registration(self):
registration = RegistrationFactory(project=self.project)
registration.embargo_registration(
self.user,
datetime.datetime.utcnow() + datetime.timedelta(days=10)
)
assert_true(registration.is_pending_embargo)
with assert_raises(NodeStateError):
registration.set_privacy('public', auth=self.auth)
assert_false(registration.is_public)
def test_set_privacy_can_not_cancel_active_embargo_for_registration(self):
registration = RegistrationFactory(project=self.project)
registration.embargo_registration(
self.user,
datetime.datetime.utcnow() + datetime.timedelta(days=10)
)
registration.save()
assert_true(registration.is_pending_embargo)
approval_token = registration.embargo.approval_state[self.user._id]['approval_token']
registration.embargo.approve_embargo(self.user, approval_token)
assert_false(registration.is_pending_embargo)
with assert_raises(NodeStateError):
registration.set_privacy('public', auth=self.auth)
def test_set_description(self):
old_desc = self.project.description
self.project.set_description(
'new description', auth=self.auth)
self.project.save()
assert_equal(self.project.description, 'new description')
latest_log = self.project.logs[-1]
assert_equal(latest_log.action, NodeLog.EDITED_DESCRIPTION)
assert_equal(latest_log.params['description_original'], old_desc)
assert_equal(latest_log.params['description_new'], 'new description')
def test_set_description_on_node(self):
node = NodeFactory(project=self.project)
old_desc = node.description
node.set_description(
'new description', auth=self.auth)
node.save()
assert_equal(node.description, 'new description')
latest_log = node.logs[-1]
assert_equal(latest_log.action, NodeLog.EDITED_DESCRIPTION)
assert_equal(latest_log.params['description_original'], old_desc)
assert_equal(latest_log.params['description_new'], 'new description')
def test_no_parent(self):
assert_equal(self.project.parent_node, None)
def test_get_recent_logs(self):
# Add some logs
for _ in range(5):
self.project.logs.append(NodeLogFactory())
# Expected logs appears
assert_equal(
self.project.get_recent_logs(3),
list(reversed(self.project.logs)[:3])
)
assert_equal(
self.project.get_recent_logs(),
list(reversed(self.project.logs))
)
def test_date_modified(self):
contrib = UserFactory()
self.project.add_contributor(contrib, auth=Auth(self.project.creator))
self.project.save()
assert_equal(self.project.date_modified, self.project.logs[-1].date)
assert_not_equal(self.project.date_modified, self.project.date_created)
def test_date_modified_create_registration(self):
registration = RegistrationFactory(project=self.project)
self.project.save()
assert_equal(self.project.date_modified, self.project.logs[-1].date)
assert_not_equal(self.project.date_modified, self.project.date_created)
def test_date_modified_create_component(self):
self.component = NodeFactory(creator=self.user, parent=self.project)
self.project.save()
assert_equal(self.project.date_modified, self.project.date_created)
def test_replace_contributor(self):
contrib = UserFactory()
self.project.add_contributor(contrib, auth=Auth(self.project.creator))
self.project.save()
assert_in(contrib, self.project.contributors) # sanity check
replacer = UserFactory()
old_length = len(self.project.contributors)
self.project.replace_contributor(contrib, replacer)
self.project.save()
new_length = len(self.project.contributors)
assert_not_in(contrib, self.project.contributors)
assert_in(replacer, self.project.contributors)
assert_equal(old_length, new_length)
# test unclaimed_records is removed
assert_not_in(
self.project._primary_key,
contrib.unclaimed_records.keys()
)
def test_permission_override_on_readded_contributor(self):
# A child node created
self.child_node = NodeFactory(parent=self.project, creator=self.auth)
# A user is added as with read permission
user = UserFactory()
self.child_node.add_contributor(user, permissions=['read'])
# user is readded with permission admin
self.child_node.add_contributor(user, permissions=['read','write','admin'])
self.child_node.save()
assert(self.child_node.has_permission(user, 'admin'))
class TestParentNode(OsfTestCase):
def setUp(self):
super(TestParentNode, self).setUp()
# Create project
self.user = UserFactory()
self.auth = Auth(user=self.user)
self.project = ProjectFactory(creator=self.user, description='The Dudleys strike again')
self.child = NodeFactory(parent=self.project, creator=self.user, description="Devon.")
self.registration = RegistrationFactory(project=self.project)
self.template = self.project.use_as_template(auth=self.auth)
def test_top_level_project_has_no_parent(self):
assert_equal(self.project.parent_node, None)
def test_child_project_has_correct_parent(self):
assert_equal(self.child.parent_node._id, self.project._id)
def test_grandchild_has_parent_of_child(self):
grandchild = NodeFactory(parent=self.child, description="Spike")
assert_equal(grandchild.parent_node._id, self.child._id)
def test_registration_has_no_parent(self):
assert_equal(self.registration.parent_node, None)
def test_registration_child_has_correct_parent(self):
registration_child = NodeFactory(parent=self.registration)
assert_equal(self.registration._id, registration_child.parent_node._id)
def test_registration_grandchild_has_correct_parent(self):
registration_child = NodeFactory(parent=self.registration)
registration_grandchild = NodeFactory(parent=registration_child)
assert_equal(registration_grandchild.parent_node._id, registration_child._id)
def test_fork_has_no_parent(self):
fork = self.project.fork_node(auth=self.auth)
assert_equal(fork.parent_node, None)
def test_fork_child_has_parent(self):
fork = self.project.fork_node(auth=self.auth)
fork_child = NodeFactory(parent=fork)
assert_equal(fork_child.parent_node._id, fork._id)
def test_fork_grandchild_has_child_id(self):
fork = self.project.fork_node(auth=self.auth)
fork_child = NodeFactory(parent=fork)
fork_grandchild = NodeFactory(parent=fork_child)
assert_equal(fork_grandchild.parent_node._id, fork_child._id)
def test_template_has_no_parent(self):
new_project = self.project.use_as_template(auth=self.auth)
assert_equal(new_project.parent_node, None)
def test_teplate_project_child_has_correct_parent(self):
template_child = NodeFactory(parent=self.template)
assert_equal(template_child.parent_node._id, self.template._id)
def test_template_project_grandchild_has_correct_root(self):
template_child = NodeFactory(parent=self.template)
new_project_grandchild = NodeFactory(parent=template_child)
assert_equal(new_project_grandchild.parent_node._id, template_child._id)
class TestRoot(OsfTestCase):
def setUp(self):
super(TestRoot, self).setUp()
# Create project
self.user = UserFactory()
self.auth = Auth(user=self.user)
self.project = ProjectFactory(creator=self.user, description='foobar')
self.registration = RegistrationFactory(project=self.project)
def test_top_level_project_has_own_root(self):
assert(self.project.root._id, self.project._id)
def test_child_project_has_root_of_parent(self):
child = NodeFactory(parent=self.project)
assert_equal(child.root._id, self.project._id)
assert_equal(child.root._id, self.project.root._id)
def test_grandchild_root_relationships(self):
child_node_one = NodeFactory(parent=self.project)
child_node_two = NodeFactory(parent=self.project)
grandchild_from_one = NodeFactory(parent=child_node_one)
grandchild_from_two = NodeFactory(parent=child_node_two)
assert_equal(child_node_one.root._id, child_node_two.root._id)
assert_equal(grandchild_from_one.root._id, grandchild_from_two.root._id)
assert_equal(grandchild_from_two.root._id, self.project.root._id)
def test_grandchild_has_root_of_immediate_parent(self):
child_node = NodeFactory(parent=self.project)
grandchild_node = NodeFactory(parent=child_node)
assert_equal(child_node.root._id, grandchild_node.root._id)
def test_registration_has_own_root(self):
assert_equal(self.registration.root._id, self.registration._id)
def test_registration_children_have_correct_root(self):
registration_child = NodeFactory(parent=self.registration)
assert_equal(registration_child.root._id, self.registration._id)
def test_registration_grandchildren_have_correct_root(self):
registration_child = NodeFactory(parent=self.registration)
registration_grandchild = NodeFactory(parent=registration_child)
assert_equal(registration_grandchild.root._id, self.registration._id)
def test_fork_has_own_root(self):
fork = self.project.fork_node(auth=self.auth)
assert_equal(fork.root._id, fork._id)
def test_fork_children_have_correct_root(self):
fork = self.project.fork_node(auth=self.auth)
fork_child = NodeFactory(parent=fork)
assert_equal(fork_child.root._id, fork._id)
def test_fork_grandchildren_have_correct_root(self):
fork = self.project.fork_node(auth=self.auth)
fork_child = NodeFactory(parent=fork)
fork_grandchild = NodeFactory(parent=fork_child)
assert_equal(fork_grandchild.root._id, fork._id)
def test_template_project_has_own_root(self):
new_project = self.project.use_as_template(auth=self.auth)
assert_equal(new_project.root._id, new_project._id)
def test_template_project_child_has_correct_root(self):
new_project = self.project.use_as_template(auth=self.auth)
new_project_child = NodeFactory(parent=new_project)
assert_equal(new_project_child.root._id, new_project._id)
def test_template_project_grandchild_has_correct_root(self):
new_project = self.project.use_as_template(auth=self.auth)
new_project_child = NodeFactory(parent=new_project)
new_project_grandchild = NodeFactory(parent=new_project_child)
assert_equal(new_project_grandchild.root._id, new_project._id)
def test_node_find_returns_correct_nodes(self):
# Build up a family of nodes
child_node_one = NodeFactory(parent=self.project)
child_node_two = NodeFactory(parent=self.project)
NodeFactory(parent=child_node_one)
NodeFactory(parent=child_node_two)
# Create a rogue node that's not related at all
NodeFactory()
family_ids = [self.project._id] + [r._id for r in self.project.get_descendants_recursive()]
family_nodes = Node.find(Q('root', 'eq', self.project._id))
number_of_nodes = family_nodes.count()
assert_equal(number_of_nodes, 5)
found_ids = []
for node in family_nodes:
assert_in(node._id, family_ids)
found_ids.append(node._id)
for node_id in family_ids:
assert_in(node_id, found_ids)
def test_get_descendants_recursive_returns_in_depth_order(self):
"""Test the get_descendants_recursive function to make sure its
not returning any new nodes that we're not expecting
"""
child_node_one = NodeFactory(parent=self.project)
child_node_two = NodeFactory(parent=self.project)
NodeFactory(parent=child_node_one)
NodeFactory(parent=child_node_two)
parent_list = [self.project._id]
# Verifies, for every node in the list, that parent, we've seen before, in order.
for project in self.project.get_descendants_recursive():
parent_list.append(project._id)
if project.parent:
assert_in(project.parent._id, parent_list)
class TestTemplateNode(OsfTestCase):
def setUp(self):
super(TestTemplateNode, self).setUp()
self.user = UserFactory()
self.auth = Auth(user=self.user)
self.project = ProjectFactory(creator=self.user)
def _verify_log(self, node):
"""Tests to see that the "created from" log event is present (alone).
:param node: A node having been created from a template just prior
"""
assert_equal(len(node.logs), 1)
assert_equal(node.logs[0].action, NodeLog.CREATED_FROM)
def test_simple_template(self):
"""Create a templated node, with no changes"""
# created templated node
new = self.project.use_as_template(
auth=self.auth
)
assert_equal(new.title, self._default_title(self.project))
assert_not_equal(new.date_created, self.project.date_created)
self._verify_log(new)
def test_simple_template_title_changed(self):
"""Create a templated node, with the title changed"""
changed_title = 'Made from template'
# create templated node
new = self.project.use_as_template(
auth=self.auth,
changes={
self.project._primary_key: {
'title': changed_title,
}
}
)
assert_equal(new.title, changed_title)
assert_not_equal(new.date_created, self.project.date_created)
self._verify_log(new)
def test_use_as_template_preserves_license(self):
license = NodeLicenseRecordFactory()
self.project.node_license = license
self.project.save()
new = self.project.use_as_template(
auth=self.auth
)
assert_equal(new.license.node_license._id, license.node_license._id)
self._verify_log(new)
def _create_complex(self):
# create project connected via Pointer
self.pointee = ProjectFactory(creator=self.user)
self.project.add_pointer(self.pointee, auth=self.auth)
# create direct children
self.component = NodeFactory(creator=self.user, parent=self.project)
self.subproject = ProjectFactory(creator=self.user, parent=self.project)
@staticmethod
def _default_title(x):
if isinstance(x, Node):
return str(language.TEMPLATED_FROM_PREFIX + x.title)
return str(x.title)
def test_complex_template(self):
"""Create a templated node from a node with children"""
self._create_complex()
# create templated node
new = self.project.use_as_template(auth=self.auth)
assert_equal(new.title, self._default_title(self.project))
assert_equal(len(new.nodes), len(self.project.nodes))
# check that all children were copied
assert_equal(
[x.title for x in new.nodes],
[x.title for x in self.project.nodes],
)
# ensure all child nodes were actually copied, instead of moved
assert {x._primary_key for x in new.nodes}.isdisjoint(
{x._primary_key for x in self.project.nodes}
)
def test_complex_template_titles_changed(self):
self._create_complex()
# build changes dict to change each node's title
changes = {
x._primary_key: {
'title': 'New Title ' + str(idx)
} for idx, x in enumerate(self.project.nodes)
}
# create templated node
new = self.project.use_as_template(
auth=self.auth,
changes=changes
)
for old_node, new_node in zip(self.project.nodes, new.nodes):
if isinstance(old_node, Node):
assert_equal(
changes[old_node._primary_key]['title'],
new_node.title,
)
else:
assert_equal(
old_node.title,
new_node.title,
)
@requires_piwik
def test_template_piwik_site_id_not_copied(self):
new = self.project.use_as_template(
auth=self.auth
)
assert_not_equal(new.piwik_site_id, self.project.piwik_site_id)
assert_true(new.piwik_site_id is not None)
def test_template_wiki_pages_not_copied(self):
self.project.update_node_wiki(
'template', 'lol',
auth=self.auth
)
new = self.project.use_as_template(
auth=self.auth
)
assert_in('template', self.project.wiki_pages_current)
assert_in('template', self.project.wiki_pages_versions)
assert_equal(new.wiki_pages_current, {})
assert_equal(new.wiki_pages_versions, {})
def test_user_who_makes_node_from_template_has_creator_permission(self):
project = ProjectFactory(is_public=True)
user = UserFactory()
auth = Auth(user)
templated = project.use_as_template(auth)
assert_equal(templated.get_permissions(user), ['read', 'write', 'admin'])
def test_template_security(self):
"""Create a templated node from a node with public and private children
Children for which the user has no access should not be copied
"""
other_user = UserFactory()
other_user_auth = Auth(user=other_user)
self._create_complex()
# set two projects to public - leaving self.component as private
self.project.is_public = True
self.project.save()
self.subproject.is_public = True
self.subproject.save()
# add new children, for which the user has each level of access
self.read = NodeFactory(creator=self.user, parent=self.project)
self.read.add_contributor(other_user, permissions=['read', ])
self.read.save()
self.write = NodeFactory(creator=self.user, parent=self.project)
self.write.add_contributor(other_user, permissions=['read', 'write'])
self.write.save()
self.admin = NodeFactory(creator=self.user, parent=self.project)
self.admin.add_contributor(other_user)
self.admin.save()
# filter down self.nodes to only include projects the user can see
visible_nodes = filter(
lambda x: x.can_view(other_user_auth),
self.project.nodes
)
# create templated node
new = self.project.use_as_template(auth=other_user_auth)
assert_equal(new.title, self._default_title(self.project))
# check that all children were copied
assert_equal(
set(x.template_node._id for x in new.nodes),
set(x._id for x in visible_nodes),
)
# ensure all child nodes were actually copied, instead of moved
assert_true({x._primary_key for x in new.nodes}.isdisjoint(
{x._primary_key for x in self.project.nodes}
))
# ensure that the creator is admin for each node copied
for node in new.nodes:
assert_equal(
node.permissions.get(other_user._id),
['read', 'write', 'admin'],
)
class TestForkNode(OsfTestCase):
def setUp(self):
super(TestForkNode, self).setUp()
self.user = UserFactory()
self.auth = Auth(user=self.user)
self.project = ProjectFactory(creator=self.user)
def _cmp_fork_original(self, fork_user, fork_date, fork, original,
title_prepend='Fork of '):
"""Compare forked node with original node. Verify copied fields,
modified fields, and files; recursively compare child nodes.
:param fork_user: User who forked the original nodes
:param fork_date: Datetime (UTC) at which the original node was forked
:param fork: Forked node
:param original: Original node
:param title_prepend: String prepended to fork title
"""
# Test copied fields
assert_equal(title_prepend + original.title, fork.title)
assert_equal(original.category, fork.category)
assert_equal(original.description, fork.description)
assert_equal(original.logs, fork.logs[:-1])
assert_true(len(fork.logs) == len(original.logs) + 1)
assert_equal(fork.logs[-1].action, NodeLog.NODE_FORKED)
assert_equal(original.tags, fork.tags)
assert_equal(original.parent_node is None, fork.parent_node is None)
# Test modified fields
assert_true(fork.is_fork)
assert_equal(len(fork.private_links), 0)
assert_equal(fork.forked_from, original)
assert_in(fork._id, original.node__forked)
# Note: Must cast ForeignList to list for comparison
assert_equal(list(fork.contributors), [fork_user])
assert_true((fork_date - fork.date_created) < datetime.timedelta(seconds=30))
assert_not_equal(fork.forked_date, original.date_created)
# Test that pointers were copied correctly
assert_equal(
[pointer.node for pointer in original.nodes_pointer],
[pointer.node for pointer in fork.nodes_pointer],
)
# Test that add-ons were copied correctly
assert_equal(
original.get_addon_names(),
fork.get_addon_names()
)
assert_equal(
[addon.config.short_name for addon in original.get_addons()],
[addon.config.short_name for addon in fork.get_addons()]
)
fork_user_auth = Auth(user=fork_user)
# Recursively compare children
for idx, child in enumerate(original.nodes):
if child.can_view(fork_user_auth):
self._cmp_fork_original(fork_user, fork_date, fork.nodes[idx],
child, title_prepend='')
@mock.patch('framework.status.push_status_message')
def test_fork_recursion(self, mock_push_status_message):
"""Omnibus test for forking.
"""
# Make some children
self.component = NodeFactory(creator=self.user, parent=self.project)
self.subproject = ProjectFactory(creator=self.user, parent=self.project)
# Add pointers to test copying
pointee = ProjectFactory()
self.project.add_pointer(pointee, auth=self.auth)
self.component.add_pointer(pointee, auth=self.auth)
self.subproject.add_pointer(pointee, auth=self.auth)
# Add add-on to test copying
self.project.add_addon('github', self.auth)
self.component.add_addon('github', self.auth)
self.subproject.add_addon('github', self.auth)
# Log time
fork_date = datetime.datetime.utcnow()
# Fork node
with mock.patch.object(Node, 'bulk_update_search'):
fork = self.project.fork_node(auth=self.auth)
# Compare fork to original
self._cmp_fork_original(self.user, fork_date, fork, self.project)
def test_fork_private_children(self):
"""Tests that only public components are created
"""
# Make project public
self.project.set_privacy('public')
# Make some children
self.public_component = NodeFactory(
creator=self.user,
parent=self.project,
title='Forked',
is_public=True,
)
self.public_subproject = ProjectFactory(
creator=self.user,
parent=self.project,
title='Forked',
is_public=True,
)
self.private_component = NodeFactory(
creator=self.user,
parent=self.project,
title='Not Forked',
)
self.private_subproject = ProjectFactory(
creator=self.user,
parent=self.project,
title='Not Forked',
)
self.private_subproject_public_component = NodeFactory(
creator=self.user,
parent=self.private_subproject,
title='Not Forked',
)
self.public_subproject_public_component = NodeFactory(
creator=self.user,
parent=self.private_subproject,
title='Forked',
)
user2 = UserFactory()
user2_auth = Auth(user=user2)
fork = None
# New user forks the project
fork = self.project.fork_node(user2_auth)
# fork correct children
assert_equal(len(fork.nodes), 2)
assert_not_in('Not Forked', [node.title for node in fork.nodes])
def test_fork_not_public(self):
self.project.set_privacy('public')
fork = self.project.fork_node(self.auth)
assert_false(fork.is_public)
def test_not_fork_private_link(self):
link = PrivateLinkFactory()
link.nodes.append(self.project)
link.save()
fork = self.project.fork_node(self.auth)
assert_not_in(link, fork.private_links)
def test_cannot_fork_private_node(self):
user2 = UserFactory()
user2_auth = Auth(user=user2)
with assert_raises(PermissionsError):
self.project.fork_node(user2_auth)
def test_can_fork_public_node(self):
self.project.set_privacy('public')
user2 = UserFactory()
user2_auth = Auth(user=user2)
fork = self.project.fork_node(user2_auth)
assert_true(fork)
def test_contributor_can_fork(self):
user2 = UserFactory()
self.project.add_contributor(user2)
user2_auth = Auth(user=user2)
fork = self.project.fork_node(user2_auth)
assert_true(fork)
# Forker has admin permissions
assert_equal(len(fork.contributors), 1)
assert_equal(fork.get_permissions(user2), ['read', 'write', 'admin'])
def test_fork_preserves_license(self):
license = NodeLicenseRecordFactory()
self.project.node_license = license
self.project.save()
fork = self.project.fork_node(self.auth)
assert_equal(fork.node_license.id, license.id)
def test_fork_registration(self):
self.registration = RegistrationFactory(project=self.project)
fork = self.registration.fork_node(self.auth)
# fork should not be a registration
assert_false(fork.is_registration)
# Compare fork to original
self._cmp_fork_original(
self.user,
datetime.datetime.utcnow(),
fork,
self.registration,
)
class TestRegisterNode(OsfTestCase):
def setUp(self):
super(TestRegisterNode, self).setUp()
ensure_schemas()
self.user = UserFactory()
self.auth = Auth(user=self.user)
self.project = ProjectFactory(creator=self.user)
self.link = PrivateLinkFactory()
self.link.nodes.append(self.project)
self.link.save()
self.registration = RegistrationFactory(project=self.project)
def test_factory(self):
# Create a registration with kwargs
registration1 = RegistrationFactory(
title='t1', description='d1', creator=self.user,
)
assert_equal(registration1.title, 't1')
assert_equal(registration1.description, 'd1')
assert_equal(len(registration1.contributors), 1)
assert_in(self.user, registration1.contributors)
assert_equal(registration1.registered_user, self.user)
assert_equal(len(registration1.private_links), 0)
# Create a registration from a project
user2 = UserFactory()
self.project.add_contributor(user2)
registration2 = RegistrationFactory(
project=self.project,
user=user2,
data={'some': 'data'},
)
assert_equal(registration2.registered_from, self.project)
assert_equal(registration2.registered_user, user2)
assert_equal(
registration2.registered_meta[get_default_metaschema()._id],
{'some': 'data'}
)
# Test default user
assert_equal(self.registration.registered_user, self.user)
def test_title(self):
assert_equal(self.registration.title, self.project.title)
def test_description(self):
assert_equal(self.registration.description, self.project.description)
def test_category(self):
assert_equal(self.registration.category, self.project.category)
def test_permissions(self):
assert_false(self.registration.is_public)
self.project.set_privacy('public')
registration = RegistrationFactory(project=self.project)
assert_false(registration.is_public)
def test_contributors(self):
assert_equal(self.registration.contributors, self.project.contributors)
def test_forked_from(self):
# A a node that is not a fork
assert_equal(self.registration.forked_from, None)
# A node that is a fork
fork = self.project.fork_node(self.auth)
registration = RegistrationFactory(project=fork)
assert_equal(registration.forked_from, self.project)
def test_private_links(self):
assert_not_equal(
self.registration.private_links,
self.project.private_links
)
def test_creator(self):
user2 = UserFactory()
self.project.add_contributor(user2)
registration = RegistrationFactory(project=self.project)
assert_equal(registration.creator, self.user)
def test_logs(self):
# Registered node has all logs except for registration approval initiated
assert_equal(self.registration.logs, self.project.logs[:-1])
def test_tags(self):
assert_equal(self.registration.tags, self.project.tags)
def test_nodes(self):
# Create some nodes
self.component = NodeFactory(
creator=self.user,
parent=self.project,
title='Title1',
)
self.subproject = ProjectFactory(
creator=self.user,
parent=self.project,
title='Title2',
)
self.subproject_component = NodeFactory(
creator=self.user,
parent=self.subproject,
title='Title3',
)
# Make a registration
registration = RegistrationFactory(project=self.project)
# Reload the registration; else test won't catch failures to save
registration.reload()
# Registration has the nodes
assert_equal(len(registration.nodes), 2)
assert_equal(
[node.title for node in registration.nodes],
[node.title for node in self.project.nodes],
)
# Nodes are copies and not the original versions
for node in registration.nodes:
assert_not_in(node, self.project.nodes)
assert_true(node.is_registration)
def test_private_contributor_registration(self):
# Create some nodes
self.component = NodeFactory(
creator=self.user,
parent=self.project,
)
self.subproject = ProjectFactory(
creator=self.user,
parent=self.project,
)
# Create some nodes to share
self.shared_component = NodeFactory(
creator=self.user,
parent=self.project,
)
self.shared_subproject = ProjectFactory(
creator=self.user,
parent=self.project,
)
# Share the project and some nodes
user2 = UserFactory()
self.project.add_contributor(user2, permissions=('read', 'write', 'admin'))
self.shared_component.add_contributor(user2, permissions=('read', 'write', 'admin'))
self.shared_subproject.add_contributor(user2, permissions=('read', 'write', 'admin'))
# Partial contributor registers the node
registration = RegistrationFactory(project=self.project, user=user2)
# The correct subprojects were registered
assert_equal(len(registration.nodes), len(self.project.nodes))
for idx in range(len(registration.nodes)):
assert_true(registration.nodes[idx].is_registration_of(self.project.nodes[idx]))
def test_is_registration(self):
assert_true(self.registration.is_registration)
def test_registered_date(self):
assert_almost_equal(
self.registration.registered_date,
datetime.datetime.utcnow(),
delta=datetime.timedelta(seconds=30),
)
def test_registered_addons(self):
assert_equal(
[addon.config.short_name for addon in self.registration.get_addons()],
[addon.config.short_name for addon in self.registration.registered_from.get_addons()],
)
def test_registered_user(self):
# Add a second contributor
user2 = UserFactory()
self.project.add_contributor(user2, permissions=('read', 'write', 'admin'))
# Second contributor registers project
registration = RegistrationFactory(parent=self.project, user=user2)
assert_equal(registration.registered_user, user2)
def test_registered_from(self):
assert_equal(self.registration.registered_from, self.project)
def test_registered_get_absolute_url(self):
assert_equal(self.registration.get_absolute_url(),
'{}v2/registrations/{}/'
.format(settings.API_DOMAIN, self.registration._id)
)
def test_registration_list(self):
assert_in(self.registration._id, self.project.node__registrations)
def test_registration_gets_institution_affiliation(self):
node = NodeFactory()
institution = InstitutionFactory()
node.primary_institution = institution
node.save()
registration = RegistrationFactory(project=node)
assert_equal(registration.primary_institution._id, node.primary_institution._id)
assert_equal(set(registration.affiliated_institutions), set(node.affiliated_institutions))
class TestNodeLog(OsfTestCase):
def setUp(self):
super(TestNodeLog, self).setUp()
self.log = NodeLogFactory()
def test_repr(self):
rep = repr(self.log)
assert_in(self.log.action, rep)
assert_in(self.log._id, rep)
def test_node_log_factory(self):
log = NodeLogFactory()
assert_true(log.action)
def test_render_log_contributor_unregistered(self):
node = NodeFactory()
name, email = fake.name(), fake.email()
unreg = node.add_unregistered_contributor(fullname=name, email=email,
auth=Auth(node.creator))
node.save()
log = NodeLogFactory(params={'node': node._primary_key})
ret = log._render_log_contributor(unreg._primary_key)
assert_false(ret['registered'])
record = unreg.get_unclaimed_record(node._primary_key)
assert_equal(ret['fullname'], record['name'])
def test_render_log_contributor_none(self):
log = NodeLogFactory()
assert_equal(log._render_log_contributor(None), None)
def test_tz_date(self):
assert_equal(self.log.tz_date.tzinfo, pytz.UTC)
def test_formatted_date(self):
iso_formatted = self.log.formatted_date # The string version in iso format
# Reparse the date
parsed = parser.parse(iso_formatted)
unparsed = self.log.tz_date
assert_equal(parsed, unparsed)
def test_resolve_node_same_as_self_node(self):
project = ProjectFactory()
assert_equal(
project.logs[-1].resolve_node(project),
project,
)
def test_resolve_node_in_nodes_list(self):
component = NodeFactory()
assert_equal(
component.logs[-1].resolve_node(component.parent_node),
component,
)
def test_resolve_node_fork_of_self_node(self):
project = ProjectFactory()
fork = project.fork_node(auth=Auth(project.creator))
assert_equal(
fork.logs[-1].resolve_node(fork),
fork,
)
def test_resolve_node_fork_of_self_in_nodes_list(self):
user = UserFactory()
component = ProjectFactory(creator=user)
project = ProjectFactory(creator=user)
project.nodes.append(component)
project.save()
forked_project = project.fork_node(auth=Auth(user=user))
assert_equal(
forked_project.nodes[0].logs[-1].resolve_node(forked_project),
forked_project.nodes[0],
)
def test_can_view(self):
project = ProjectFactory(is_public=False)
non_contrib = UserFactory()
created_log = project.logs[0]
assert_false(created_log.can_view(project, Auth(user=non_contrib)))
assert_true(created_log.can_view(project, Auth(user=project.creator)))
def test_can_view_with_non_related_project_arg(self):
project = ProjectFactory()
unrelated = ProjectFactory()
created_log = project.logs[0]
assert_false(created_log.can_view(unrelated, Auth(user=project.creator)))
class TestPermissions(OsfTestCase):
def setUp(self):
super(TestPermissions, self).setUp()
self.project = ProjectFactory()
def test_default_creator_permissions(self):
assert_equal(
set(CREATOR_PERMISSIONS),
set(self.project.permissions[self.project.creator._id])
)
def test_default_contributor_permissions(self):
user = UserFactory()
self.project.add_contributor(user, permissions=['read'], auth=Auth(user=self.project.creator))
self.project.save()
assert_equal(
set(['read']),
set(self.project.get_permissions(user))
)
def test_adjust_permissions(self):
self.project.permissions[42] = ['dance']
self.project.save()
assert_not_in(42, self.project.permissions)
def test_add_permission(self):
self.project.add_permission(self.project.creator, 'dance')
assert_in(self.project.creator._id, self.project.permissions)
assert_in('dance', self.project.permissions[self.project.creator._id])
def test_add_permission_already_granted(self):
self.project.add_permission(self.project.creator, 'dance')
with assert_raises(ValueError):
self.project.add_permission(self.project.creator, 'dance')
def test_remove_permission(self):
self.project.add_permission(self.project.creator, 'dance')
self.project.remove_permission(self.project.creator, 'dance')
assert_not_in('dance', self.project.permissions[self.project.creator._id])
def test_remove_permission_not_granted(self):
with assert_raises(ValueError):
self.project.remove_permission(self.project.creator, 'dance')
def test_has_permission_true(self):
self.project.add_permission(self.project.creator, 'dance')
assert_true(self.project.has_permission(self.project.creator, 'dance'))
def test_has_permission_false(self):
self.project.add_permission(self.project.creator, 'dance')
assert_false(self.project.has_permission(self.project.creator, 'sing'))
def test_has_permission_not_in_dict(self):
assert_false(self.project.has_permission(self.project.creator, 'dance'))
class TestPointer(OsfTestCase):
def setUp(self):
super(TestPointer, self).setUp()
self.pointer = PointerFactory()
def test_title(self):
assert_equal(
self.pointer.title,
self.pointer.node.title
)
def test_contributors(self):
assert_equal(
self.pointer.contributors,
self.pointer.node.contributors
)
def _assert_clone(self, pointer, cloned):
assert_not_equal(
pointer._id,
cloned._id
)
assert_equal(
pointer.node,
cloned.node
)
def test_get_pointer_parent(self):
parent = ProjectFactory()
pointed = ProjectFactory()
parent.add_pointer(pointed, Auth(parent.creator))
parent.save()
assert_equal(get_pointer_parent(parent.nodes[0]), parent)
def test_clone(self):
cloned = self.pointer._clone()
self._assert_clone(self.pointer, cloned)
def test_clone_no_node(self):
pointer = Pointer()
cloned = pointer._clone()
assert_equal(cloned, None)
def test_fork(self):
forked = self.pointer.fork_node()
self._assert_clone(self.pointer, forked)
def test_register(self):
registered = self.pointer.fork_node()
self._assert_clone(self.pointer, registered)
def test_register_with_pointer_to_registration(self):
pointee = RegistrationFactory()
project = ProjectFactory()
auth = Auth(user=project.creator)
project.add_pointer(pointee, auth=auth)
with mock_archive(project) as registration:
assert_equal(registration.nodes[0].node, pointee)
def test_has_pointers_recursive_false(self):
project = ProjectFactory()
node = NodeFactory(project=project)
assert_false(project.has_pointers_recursive)
assert_false(node.has_pointers_recursive)
def test_has_pointers_recursive_true(self):
project = ProjectFactory()
node = NodeFactory(parent=project)
node.nodes.append(self.pointer)
assert_true(node.has_pointers_recursive)
assert_true(project.has_pointers_recursive)
class TestWatchConfig(OsfTestCase):
def test_factory(self):
config = WatchConfigFactory(digest=True, immediate=False)
assert_true(config.digest)
assert_false(config.immediate)
assert_true(config.node._id)
class TestUnregisteredUser(OsfTestCase):
def setUp(self):
super(TestUnregisteredUser, self).setUp()
self.referrer = UserFactory()
self.project = ProjectFactory(creator=self.referrer)
self.user = UnregUserFactory()
def add_unclaimed_record(self):
given_name = 'Fredd Merkury'
email = fake.email()
self.user.add_unclaimed_record(node=self.project,
given_name=given_name, referrer=self.referrer,
email=email)
self.user.save()
data = self.user.unclaimed_records[self.project._primary_key]
return email, data
def test_unregistered_factory(self):
u1 = UnregUserFactory()
assert_false(u1.is_registered)
assert_true(u1.password is None)
assert_true(u1.fullname)
def test_unconfirmed_factory(self):
u = UnconfirmedUserFactory()
assert_false(u.is_registered)
assert_true(u.username)
assert_true(u.fullname)
assert_true(u.password)
assert_equal(len(u.email_verifications.keys()), 1)
def test_add_unclaimed_record(self):
email, data = self.add_unclaimed_record()
assert_equal(data['name'], 'Fredd Merkury')
assert_equal(data['referrer_id'], self.referrer._primary_key)
assert_in('token', data)
assert_equal(data['email'], email)
assert_equal(data, self.user.get_unclaimed_record(self.project._primary_key))
def test_get_claim_url(self):
self.add_unclaimed_record()
uid = self.user._primary_key
pid = self.project._primary_key
token = self.user.get_unclaimed_record(pid)['token']
domain = settings.DOMAIN
assert_equal(self.user.get_claim_url(pid, external=True),
'{domain}user/{uid}/{pid}/claim/?token={token}'.format(**locals()))
def test_get_claim_url_raises_value_error_if_not_valid_pid(self):
with assert_raises(ValueError):
self.user.get_claim_url('invalidinput')
def test_cant_add_unclaimed_record_if_referrer_isnt_contributor(self):
project = ProjectFactory() # referrer isn't a contributor to this project
with assert_raises(PermissionsError):
self.user.add_unclaimed_record(node=project,
given_name='fred m', referrer=self.referrer)
def test_register(self):
assert_false(self.user.is_registered) # sanity check
assert_false(self.user.is_claimed)
email = fake.email()
self.user.register(username=email, password='killerqueen')
self.user.save()
assert_true(self.user.is_claimed)
assert_true(self.user.is_registered)
assert_true(self.user.check_password('killerqueen'))
assert_equal(self.user.username, email)
def test_registering_with_a_different_email_adds_to_emails_list(self):
user = UnregUserFactory()
assert_equal(user.password, None) # sanity check
user.register(username=fake.email(), password='killerqueen')
def test_verify_claim_token(self):
self.add_unclaimed_record()
valid = self.user.get_unclaimed_record(self.project._primary_key)['token']
assert_true(self.user.verify_claim_token(valid, project_id=self.project._primary_key))
assert_false(self.user.verify_claim_token('invalidtoken', project_id=self.project._primary_key))
def test_claim_contributor(self):
self.add_unclaimed_record()
# sanity cheque
assert_false(self.user.is_registered)
assert_true(self.project)
class TestTags(OsfTestCase):
def setUp(self):
super(TestTags, self).setUp()
self.project = ProjectFactory()
self.auth = Auth(self.project.creator)
def test_add_tag(self):
self.project.add_tag('scientific', auth=self.auth)
assert_in('scientific', self.project.tags)
assert_equal(
self.project.logs[-1].action,
NodeLog.TAG_ADDED
)
def test_add_tag_too_long(self):
with assert_raises(ValidationError):
self.project.add_tag('q' * 129, auth=self.auth)
def test_remove_tag(self):
self.project.add_tag('scientific', auth=self.auth)
self.project.remove_tag('scientific', auth=self.auth)
assert_not_in('scientific', self.project.tags)
assert_equal(
self.project.logs[-1].action,
NodeLog.TAG_REMOVED
)
def test_remove_tag_not_present(self):
self.project.remove_tag('scientific', auth=self.auth)
assert_equal(
self.project.logs[-1].action,
NodeLog.PROJECT_CREATED
)
class TestContributorVisibility(OsfTestCase):
def setUp(self):
super(TestContributorVisibility, self).setUp()
self.project = ProjectFactory()
self.user2 = UserFactory()
self.project.add_contributor(self.user2)
def test_get_visible_true(self):
assert_true(self.project.get_visible(self.project.creator))
def test_get_visible_false(self):
self.project.set_visible(self.project.creator, False)
assert_false(self.project.get_visible(self.project.creator))
def test_make_invisible(self):
self.project.set_visible(self.project.creator, False, save=True)
self.project.reload()
assert_not_in(
self.project.creator._id,
self.project.visible_contributor_ids
)
assert_not_in(
self.project.creator,
self.project.visible_contributors
)
assert_equal(
self.project.logs[-1].action,
NodeLog.MADE_CONTRIBUTOR_INVISIBLE
)
def test_make_visible(self):
self.project.set_visible(self.project.creator, False, save=True)
self.project.set_visible(self.project.creator, True, save=True)
self.project.reload()
assert_in(
self.project.creator._id,
self.project.visible_contributor_ids
)
assert_in(
self.project.creator,
self.project.visible_contributors
)
assert_equal(
self.project.logs[-1].action,
NodeLog.MADE_CONTRIBUTOR_VISIBLE
)
# Regression test: Ensure that hiding and showing the first contributor
# does not change the visible contributor order
assert_equal(
self.project.visible_contributors,
[self.project.creator, self.user2]
)
def test_set_visible_missing(self):
with assert_raises(ValueError):
self.project.set_visible(UserFactory(), True)
class TestProjectWithAddons(OsfTestCase):
def test_factory(self):
p = ProjectWithAddonFactory(addon='s3')
assert_true(p.get_addon('s3'))
assert_true(p.creator.get_addon('s3'))
class TestPrivateLink(OsfTestCase):
def test_node_scale(self):
link = PrivateLinkFactory()
project = ProjectFactory()
comp = NodeFactory(parent=project)
link.nodes.append(project)
link.save()
assert_equal(link.node_scale(project), -40)
assert_equal(link.node_scale(comp), -20)
# Regression test for https://sentry.osf.io/osf/production/group/1119/
def test_to_json_nodes_with_deleted_parent(self):
link = PrivateLinkFactory()
project = ProjectFactory(is_deleted=True)
node = NodeFactory(project=project)
link.nodes.extend([project, node])
link.save()
result = link.to_json()
# result doesn't include deleted parent
assert_equal(len(result['nodes']), 1)
# Regression test for https://sentry.osf.io/osf/production/group/1119/
def test_node_scale_with_deleted_parent(self):
link = PrivateLinkFactory()
project = ProjectFactory(is_deleted=True)
node = NodeFactory(project=project)
link.nodes.extend([project, node])
link.save()
assert_equal(link.node_scale(node), -40)
def test_create_from_node(self):
ensure_schemas()
proj = ProjectFactory()
user = proj.creator
schema = MetaSchema.find()[0]
data = {'some': 'data'}
draft = DraftRegistration.create_from_node(
proj,
user=user,
schema=schema,
data=data,
)
assert_equal(user, draft.initiator)
assert_equal(schema, draft.registration_schema)
assert_equal(data, draft.registration_metadata)
assert_equal(proj, draft.branched_from)
if __name__ == '__main__':
unittest.main()
| {
"content_hash": "fd7e4b1d15b0ff3446d303ba18263825",
"timestamp": "",
"source": "github",
"line_count": 4470,
"max_line_length": 132,
"avg_line_length": 38.295525727069354,
"alnum_prop": 0.6255133455231597,
"repo_name": "GageGaskins/osf.io",
"id": "38bb41cfdd7d1207a00b7ecee6ca3871957bd95d",
"size": "171219",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "tests/test_models.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "133911"
},
{
"name": "HTML",
"bytes": "58475"
},
{
"name": "JavaScript",
"bytes": "1393750"
},
{
"name": "Mako",
"bytes": "635929"
},
{
"name": "Perl",
"bytes": "13885"
},
{
"name": "Python",
"bytes": "4889695"
},
{
"name": "Shell",
"bytes": "2118"
}
],
"symlink_target": ""
} |
COMMTRACK_REPORT_XMLNS = 'http://commcarehq.org/ledger/v1'
SECTION_TYPE_STOCK = 'stock'
REPORT_TYPE_BALANCE = 'balance'
REPORT_TYPE_TRANSFER = 'transfer'
VALID_REPORT_TYPES = (REPORT_TYPE_BALANCE, REPORT_TYPE_TRANSFER)
TRANSACTION_TYPE_STOCKONHAND = 'stockonhand'
TRANSACTION_TYPE_STOCKOUT = 'stockout'
TRANSACTION_TYPE_RECEIPTS = 'receipts'
TRANSACTION_TYPE_CONSUMPTION = 'consumption'
TRANSACTION_SUBTYPE_INFERRED = '_inferred' | {
"content_hash": "42aa7f5243fbfb149654d7addbb18f5c",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 64,
"avg_line_length": 30.928571428571427,
"alnum_prop": 0.7782909930715936,
"repo_name": "SEL-Columbia/commcare-hq",
"id": "84a02405b727336cc8b63baba850eb452f55dbbe",
"size": "433",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "corehq/ex-submodules/casexml/apps/stock/const.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ActionScript",
"bytes": "15950"
},
{
"name": "CSS",
"bytes": "768322"
},
{
"name": "JavaScript",
"bytes": "2647080"
},
{
"name": "Python",
"bytes": "7806659"
},
{
"name": "Shell",
"bytes": "28569"
}
],
"symlink_target": ""
} |
from __future__ import absolute_import
import operator
import six
from sentry.api.serializers import serialize
from sentry.models import (Release, ReleaseCommit, Commit, CommitFileChange, Event, Group)
from sentry.api.serializers.models.commit import CommitSerializer, get_users_for_commits
from sentry.utils import metrics
from django.db.models import Q
from itertools import izip
from collections import defaultdict
from six.moves import reduce
PATH_SEPERATORS = frozenset(['/', '\\'])
def tokenize_path(path):
for sep in PATH_SEPERATORS:
if sep in path:
return reversed(path.split(sep))
else:
return iter([path])
def score_path_match_length(path_a, path_b):
score = 0
for a, b in izip(tokenize_path(path_a), tokenize_path(path_b)):
if a != b:
break
score += 1
return score
def _get_frame_paths(event):
data = event.data
try:
frames = data['sentry.interfaces.Stacktrace']['frames']
except KeyError:
try:
frames = data['sentry.interfaces.Exception']['values'][0]['stacktrace']['frames']
except (KeyError, TypeError):
return [] # can't find stacktrace information
return frames
def _get_commits(releases):
return list(Commit.objects.filter(
releasecommit=ReleaseCommit.objects.filter(
release__in=releases,
)
).select_related('author'))
def _get_commit_file_changes(commits, path_name_set):
# build a single query to get all of the commit file that might match the first n frames
path_query = reduce(
operator.or_,
(Q(filename__endswith=next(tokenize_path(path))) for path in path_name_set)
)
commit_file_change_matches = CommitFileChange.objects.filter(
path_query,
commit__in=commits,
)
return list(commit_file_change_matches)
def _match_commits_path(commit_file_changes, path):
# find commits that match the run time path the best.
matching_commits = {}
best_score = 1
for file_change in commit_file_changes:
score = score_path_match_length(file_change.filename, path)
if score > best_score:
# reset matches for better match.
best_score = score
matching_commits = {}
if score == best_score:
# skip 1-score matches when file change is longer than 1 token
if score == 1 and len(list(tokenize_path(file_change.filename))) > 1:
continue
# we want a list of unique commits that tie for longest match
matching_commits[file_change.commit.id] = (file_change.commit, score)
return matching_commits.values()
def _get_commits_committer(commits, author_id):
result = serialize([
commit for commit, score in commits if commit.author.id == author_id
], serializer=CommitSerializer(exclude=['author']))
for idx, row in enumerate(result):
row['score'] = commits[idx][1]
return result
def _get_committers(annotated_frames, commits):
# extract the unique committers and return their serialized sentry accounts
committers = defaultdict(int)
limit = 5
for annotated_frame in annotated_frames:
if limit == 0:
break
for commit, score in annotated_frame['commits']:
committers[commit.author.id] += limit
limit -= 1
if limit == 0:
break
# organize them by this heuristic (first frame is worth 5 points, second is worth 4, etc.)
sorted_committers = sorted(committers, key=committers.get)
users_by_author = get_users_for_commits([c for c, _ in commits])
user_dicts = [
{
'author': users_by_author.get(six.text_type(author_id)),
'commits': _get_commits_committer(
commits,
author_id,
)
} for author_id in sorted_committers
]
return user_dicts
def get_previous_releases(project, start_version, limit=5):
# given a release version + project, return the previous
# `limit` releases (includes the release specified by `version`)
try:
release_dates = Release.objects.filter(
organization_id=project.organization_id,
version=start_version,
projects=project,
).values('date_released', 'date_added').get()
except Release.DoesNotExist:
return []
start_date = release_dates['date_released'] or release_dates['date_added']
return list(Release.objects.filter(
projects=project,
organization_id=project.organization_id,
).extra(
select={
'date': 'COALESCE(date_released, date_added)',
},
where=["COALESCE(date_released, date_added) <= %s"],
params=[start_date]
).extra(
order_by=['-date']
)[:limit])
def get_event_file_committers(project, event, frame_limit=25):
# populate event data
Event.objects.bind_nodes([event], 'data')
group = Group.objects.get(id=event.group_id)
first_release_version = group.get_first_release()
if not first_release_version:
raise Release.DoesNotExist
releases = get_previous_releases(project, first_release_version)
if not releases:
raise Release.DoesNotExist
commits = _get_commits(releases)
if not commits:
raise Commit.DoesNotExist
frames = _get_frame_paths(event)
app_frames = [frame for frame in frames if frame['in_app']][-frame_limit:]
if not app_frames:
app_frames = [frame for frame in frames][-frame_limit:]
# TODO(maxbittker) return this set instead of annotated frames
# XXX(dcramer): frames may not define a filepath. For example, in Java its common
# to only have a module name/path
path_set = {f for f in (frame.get('filename') or frame.get('abs_path')
for frame in app_frames) if f}
file_changes = []
if path_set:
file_changes = _get_commit_file_changes(commits, path_set)
commit_path_matches = {
path: _match_commits_path(file_changes, path) for path in path_set
}
annotated_frames = [
{
'frame': frame,
'commits': commit_path_matches.get(frame.get('filename') or frame.get('abs_path')) or []
} for frame in app_frames
]
relevant_commits = list(
{match for match in commit_path_matches for match in commit_path_matches[match]}
)
committers = _get_committers(annotated_frames, relevant_commits)
metrics.incr('feature.owners.has-committers', instance='hit' if committers else 'miss')
return committers
| {
"content_hash": "d84e6cb3c7f4f3919e461cdfdfdab547",
"timestamp": "",
"source": "github",
"line_count": 213,
"max_line_length": 100,
"avg_line_length": 31.295774647887324,
"alnum_prop": 0.6360636063606361,
"repo_name": "ifduyue/sentry",
"id": "15c305075a6affcdfb7f256728c5331057bf99a0",
"size": "6666",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/sentry/utils/committers.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "301292"
},
{
"name": "HTML",
"bytes": "241298"
},
{
"name": "JavaScript",
"bytes": "3295572"
},
{
"name": "Lua",
"bytes": "65795"
},
{
"name": "Makefile",
"bytes": "6892"
},
{
"name": "Python",
"bytes": "36910084"
},
{
"name": "Ruby",
"bytes": "217"
},
{
"name": "Shell",
"bytes": "5701"
}
],
"symlink_target": ""
} |
"""functools.py - Tools for working with functions and callable objects
"""
# Python module wrapper for _functools C module
# to allow utilities written in Python to be added
# to the functools module.
# Written by Nick Coghlan <ncoghlan at gmail.com>
# and Raymond Hettinger <python at rcn.com>
# Copyright (C) 2006-2010 Python Software Foundation.
# See C source code for _functools credits/copyright
__all__ = ['update_wrapper', 'wraps', 'WRAPPER_ASSIGNMENTS', 'WRAPPER_UPDATES',
'total_ordering', 'cmp_to_key', 'lru_cache', 'reduce', 'partial']
from _functools import partial, reduce
from collections import MutableMapping, namedtuple
from .reprlib32 import recursive_repr as _recursive_repr
from weakref import proxy as _proxy
import sys as _sys
try:
from _thread import allocate_lock as Lock
except:
from ._dummy_thread32 import allocate_lock as Lock
################################################################################
### OrderedDict
################################################################################
class _Link(object):
__slots__ = 'prev', 'next', 'key', '__weakref__'
class OrderedDict(dict):
'Dictionary that remembers insertion order'
# An inherited dict maps keys to values.
# The inherited dict provides __getitem__, __len__, __contains__, and get.
# The remaining methods are order-aware.
# Big-O running times for all methods are the same as regular dictionaries.
# The internal self.__map dict maps keys to links in a doubly linked list.
# The circular doubly linked list starts and ends with a sentinel element.
# The sentinel element never gets deleted (this simplifies the algorithm).
# The sentinel is in self.__hardroot with a weakref proxy in self.__root.
# The prev links are weakref proxies (to prevent circular references).
# Individual links are kept alive by the hard reference in self.__map.
# Those hard references disappear when a key is deleted from an OrderedDict.
def __init__(self, *args, **kwds):
'''Initialize an ordered dictionary. The signature is the same as
regular dictionaries, but keyword arguments are not recommended because
their insertion order is arbitrary.
'''
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__root
except AttributeError:
self.__hardroot = _Link()
self.__root = root = _proxy(self.__hardroot)
root.prev = root.next = root
self.__map = {}
self.__update(*args, **kwds)
def __setitem__(self, key, value,
dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link):
'od.__setitem__(i, y) <==> od[i]=y'
# Setting a new item creates a new link at the end of the linked list,
# and the inherited dictionary is updated with the new key/value pair.
if key not in self:
self.__map[key] = link = Link()
root = self.__root
last = root.prev
link.prev, link.next, link.key = last, root, key
last.next = link
root.prev = proxy(link)
dict_setitem(self, key, value)
def __delitem__(self, key, dict_delitem=dict.__delitem__):
'od.__delitem__(y) <==> del od[y]'
# Deleting an existing item uses self.__map to find the link which gets
# removed by updating the links in the predecessor and successor nodes.
dict_delitem(self, key)
link = self.__map.pop(key)
link_prev = link.prev
link_next = link.next
link_prev.next = link_next
link_next.prev = link_prev
def __iter__(self):
'od.__iter__() <==> iter(od)'
# Traverse the linked list in order.
root = self.__root
curr = root.next
while curr is not root:
yield curr.key
curr = curr.next
def __reversed__(self):
'od.__reversed__() <==> reversed(od)'
# Traverse the linked list in reverse order.
root = self.__root
curr = root.prev
while curr is not root:
yield curr.key
curr = curr.prev
def clear(self):
'od.clear() -> None. Remove all items from od.'
root = self.__root
root.prev = root.next = root
self.__map.clear()
dict.clear(self)
def popitem(self, last=True):
'''od.popitem() -> (k, v), return and remove a (key, value) pair.
Pairs are returned in LIFO order if last is true or FIFO order if false.
'''
if not self:
raise KeyError('dictionary is empty')
root = self.__root
if last:
link = root.prev
link_prev = link.prev
link_prev.next = root
root.prev = link_prev
else:
link = root.next
link_next = link.next
root.next = link_next
link_next.prev = root
key = link.key
del self.__map[key]
value = dict.pop(self, key)
return key, value
def move_to_end(self, key, last=True):
'''Move an existing element to the end (or beginning if last==False).
Raises KeyError if the element does not exist.
When last=True, acts like a fast version of self[key]=self.pop(key).
'''
link = self.__map[key]
link_prev = link.prev
link_next = link.next
link_prev.next = link_next
link_next.prev = link_prev
root = self.__root
if last:
last = root.prev
link.prev = last
link.next = root
last.next = root.prev = link
else:
first = root.next
link.prev = root
link.next = first
root.next = first.prev = link
def __sizeof__(self):
sizeof = _sys.getsizeof
n = len(self) + 1 # number of links including root
size = sizeof(self.__dict__) # instance dictionary
size += sizeof(self.__map) * 2 # internal dict and inherited dict
size += sizeof(self.__hardroot) * n # link objects
size += sizeof(self.__root) * n # proxy objects
return size
update = __update = MutableMapping.update
keys = MutableMapping.keys
values = MutableMapping.values
items = MutableMapping.items
__ne__ = MutableMapping.__ne__
__marker = object()
def pop(self, key, default=__marker):
'''od.pop(k[,d]) -> v, remove specified key and return the corresponding
value. If key is not found, d is returned if given, otherwise KeyError
is raised.
'''
if key in self:
result = self[key]
del self[key]
return result
if default is self.__marker:
raise KeyError(key)
return default
def setdefault(self, key, default=None):
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
if key in self:
return self[key]
self[key] = default
return default
@_recursive_repr()
def __repr__(self):
'od.__repr__() <==> repr(od)'
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, list(self.items()))
def __reduce__(self):
'Return state information for pickling'
items = [[k, self[k]] for k in self]
inst_dict = vars(self).copy()
for k in vars(OrderedDict()):
inst_dict.pop(k, None)
if inst_dict:
return (self.__class__, (items,), inst_dict)
return self.__class__, (items,)
def copy(self):
'od.copy() -> a shallow copy of od'
return self.__class__(self)
@classmethod
def fromkeys(cls, iterable, value=None):
'''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.
If not specified, the value defaults to None.
'''
self = cls()
for key in iterable:
self[key] = value
return self
def __eq__(self, other):
'''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
while comparison to a regular mapping is order-insensitive.
'''
if isinstance(other, OrderedDict):
return len(self)==len(other) and \
all(p==q for p, q in zip(self.items(), other.items()))
return dict.__eq__(self, other)
# update_wrapper() and wraps() are tools to help write
# wrapper functions that can handle naive introspection
WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')
WRAPPER_UPDATES = ('__dict__',)
def update_wrapper(wrapper,
wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Update a wrapper function to look like the wrapped function
wrapper is the function to be updated
wrapped is the original function
assigned is a tuple naming the attributes assigned directly
from the wrapped function to the wrapper function (defaults to
functools.WRAPPER_ASSIGNMENTS)
updated is a tuple naming the attributes of the wrapper that
are updated with the corresponding attribute from the wrapped
function (defaults to functools.WRAPPER_UPDATES)
"""
wrapper.__wrapped__ = wrapped
for attr in assigned:
try:
value = getattr(wrapped, attr)
except AttributeError:
pass
else:
setattr(wrapper, attr, value)
for attr in updated:
getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
# Return the wrapper so this can be used as a decorator via partial()
return wrapper
def wraps(wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Decorator factory to apply update_wrapper() to a wrapper function
Returns a decorator that invokes update_wrapper() with the decorated
function as the wrapper argument and the arguments to wraps() as the
remaining arguments. Default arguments are as for update_wrapper().
This is a convenience function to simplify applying partial() to
update_wrapper().
"""
return partial(update_wrapper, wrapped=wrapped,
assigned=assigned, updated=updated)
def total_ordering(cls):
"""Class decorator that fills in missing ordering methods"""
convert = {
'__lt__': [('__gt__', lambda self, other: not (self < other or self == other)),
('__le__', lambda self, other: self < other or self == other),
('__ge__', lambda self, other: not self < other)],
'__le__': [('__ge__', lambda self, other: not self <= other or self == other),
('__lt__', lambda self, other: self <= other and not self == other),
('__gt__', lambda self, other: not self <= other)],
'__gt__': [('__lt__', lambda self, other: not (self > other or self == other)),
('__ge__', lambda self, other: self > other or self == other),
('__le__', lambda self, other: not self > other)],
'__ge__': [('__le__', lambda self, other: (not self >= other) or self == other),
('__gt__', lambda self, other: self >= other and not self == other),
('__lt__', lambda self, other: not self >= other)]
}
roots = set(dir(cls)) & set(convert)
if not roots:
raise ValueError('must define at least one ordering operation: < > <= >=')
root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__
for opname, opfunc in convert[root]:
if opname not in roots:
opfunc.__name__ = opname
opfunc.__doc__ = getattr(int, opname).__doc__
setattr(cls, opname, opfunc)
return cls
def cmp_to_key(mycmp):
"""Convert a cmp= function into a key= function"""
class K(object):
__slots__ = ['obj']
def __init__(self, obj):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
def __le__(self, other):
return mycmp(self.obj, other.obj) <= 0
def __ge__(self, other):
return mycmp(self.obj, other.obj) >= 0
def __ne__(self, other):
return mycmp(self.obj, other.obj) != 0
__hash__ = None
return K
_CacheInfo = namedtuple("CacheInfo", "hits misses maxsize currsize")
def lru_cache(maxsize=100):
"""Least-recently-used cache decorator.
If *maxsize* is set to None, the LRU features are disabled and the cache
can grow without bound.
Arguments to the cached function must be hashable.
View the cache statistics named tuple (hits, misses, maxsize, currsize) with
f.cache_info(). Clear the cache and statistics with f.cache_clear().
Access the underlying function with f.__wrapped__.
See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
"""
# Users should only access the lru_cache through its public API:
# cache_info, cache_clear, and f.__wrapped__
# The internals of the lru_cache are encapsulated for thread safety and
# to allow the implementation to change (including a possible C version).
def decorating_function(user_function,
tuple=tuple, sorted=sorted, len=len, KeyError=KeyError):
hits, misses = [0], [0]
kwd_mark = (object(),) # separates positional and keyword args
lock = Lock() # needed because OrderedDict isn't threadsafe
if maxsize is None:
cache = dict() # simple cache without ordering or size limit
@wraps(user_function)
def wrapper(*args, **kwds):
key = args
if kwds:
key += kwd_mark + tuple(sorted(kwds.items()))
try:
result = cache[key]
hits[0] += 1
return result
except KeyError:
pass
result = user_function(*args, **kwds)
cache[key] = result
misses[0] += 1
return result
else:
cache = OrderedDict() # ordered least recent to most recent
cache_popitem = cache.popitem
cache_renew = cache.move_to_end
@wraps(user_function)
def wrapper(*args, **kwds):
key = args
if kwds:
key += kwd_mark + tuple(sorted(kwds.items()))
with lock:
try:
result = cache[key]
cache_renew(key) # record recent use of this key
hits[0] += 1
return result
except KeyError:
pass
result = user_function(*args, **kwds)
with lock:
cache[key] = result # record recent use of this key
misses[0] += 1
if len(cache) > maxsize:
cache_popitem(0) # purge least recently used cache entry
return result
def cache_info():
"""Report cache statistics"""
with lock:
return _CacheInfo(hits[0], misses[0], maxsize, len(cache))
def cache_clear():
"""Clear the cache and cache statistics"""
with lock:
cache.clear()
hits[0] = misses[0] = 0
wrapper.cache_info = cache_info
wrapper.cache_clear = cache_clear
return wrapper
return decorating_function
| {
"content_hash": "bbb0fe6573638e389a578e8c1beec03a",
"timestamp": "",
"source": "github",
"line_count": 423,
"max_line_length": 88,
"avg_line_length": 38.03782505910166,
"alnum_prop": 0.5537600994406464,
"repo_name": "TheWardoctor/Wardoctors-repo",
"id": "e472c22d616daef2e2c1ac391abf9269d3d8e505",
"size": "16090",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "script.extendedinfo/resources/lib/functools32/functools32.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "3208"
},
{
"name": "JavaScript",
"bytes": "115722"
},
{
"name": "Python",
"bytes": "34405207"
},
{
"name": "Shell",
"bytes": "914"
}
],
"symlink_target": ""
} |
from __future__ import absolute_import
from .graph import Graph
class BarGraph(Graph):
pass
# def new_series(self,*args,**kw):
# ============= EOF ====================================
| {
"content_hash": "b2cf894fc1b3ec8cd0ba855de093af6a",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 56,
"avg_line_length": 21.666666666666668,
"alnum_prop": 0.49743589743589745,
"repo_name": "UManPychron/pychron",
"id": "df6af6d26a9c0021a6b504313654b4e1d0aa4ff2",
"size": "1133",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "pychron/graph/bar_graph.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "131"
},
{
"name": "C++",
"bytes": "3706"
},
{
"name": "CSS",
"bytes": "279"
},
{
"name": "Fortran",
"bytes": "455875"
},
{
"name": "HTML",
"bytes": "40346"
},
{
"name": "Mako",
"bytes": "412"
},
{
"name": "Processing",
"bytes": "11421"
},
{
"name": "Python",
"bytes": "10234954"
},
{
"name": "Shell",
"bytes": "10753"
}
],
"symlink_target": ""
} |
import flask
from xmltodict import parse
from flask import current_app
from .cas_urls import create_cas_login_url
from .cas_urls import create_cas_logout_url
from .cas_urls import create_cas_validate_url
try:
from urllib import urlopen
except ImportError:
from urllib.request import urlopen
blueprint = flask.Blueprint('cas', __name__)
@blueprint.route('/login/')
def login():
"""
This route has two purposes. First, it is used by the user
to login. Second, it is used by the CAS to respond with the
`ticket` after the user logs in successfully.
When the user accesses this url, they are redirected to the CAS
to login. If the login was successful, the CAS will respond to this
route with the ticket in the url. The ticket is then validated.
If validation was successful the logged in username is saved in
the user's session under the key `CAS_USERNAME_SESSION_KEY` and
the user's attributes are saved under the key
'CAS_USERNAME_ATTRIBUTE_KEY'
"""
cas_token_session_key = current_app.config['CAS_TOKEN_SESSION_KEY']
redirect_url = create_cas_login_url(
current_app.config['CAS_SERVER'],
current_app.config['CAS_LOGIN_ROUTE'],
flask.url_for('.login', _external=True))
if 'ticket' in flask.request.args:
flask.session[cas_token_session_key] = flask.request.args['ticket']
if cas_token_session_key in flask.session:
if validate(flask.session[cas_token_session_key]):
if 'CAS_AFTER_LOGIN_SESSION_URL' in flask.session:
redirect_url = flask.session.pop('CAS_AFTER_LOGIN_SESSION_URL')
else:
redirect_url = flask.url_for(
current_app.config['CAS_AFTER_LOGIN'])
else:
del flask.session[cas_token_session_key]
current_app.logger.debug('Redirecting to: {0}'.format(redirect_url))
return flask.redirect(redirect_url)
@blueprint.route('/logout/')
def logout():
"""
When the user accesses this route they are logged out.
"""
cas_username_session_key = current_app.config['CAS_USERNAME_SESSION_KEY']
cas_attributes_session_key = current_app.config['CAS_ATTRIBUTES_SESSION_KEY']
if cas_username_session_key in flask.session:
del flask.session[cas_username_session_key]
if cas_attributes_session_key in flask.session:
del flask.session[cas_attributes_session_key]
if(current_app.config['CAS_AFTER_LOGOUT'] != None):
redirect_url = create_cas_logout_url(
current_app.config['CAS_SERVER'],
current_app.config['CAS_LOGOUT_ROUTE'],
current_app.config['CAS_AFTER_LOGOUT'])
else:
redirect_url = create_cas_logout_url(
current_app.config['CAS_SERVER'],
current_app.config['CAS_LOGOUT_ROUTE'])
current_app.logger.debug('Redirecting to: {0}'.format(redirect_url))
return flask.redirect(redirect_url)
def validate(ticket):
"""
Will attempt to validate the ticket. If validation fails, then False
is returned. If validation is successful, then True is returned
and the validated username is saved in the session under the
key `CAS_USERNAME_SESSION_KEY` while tha validated attributes dictionary
is saved under the key 'CAS_ATTRIBUTES_SESSION_KEY'.
"""
cas_username_session_key = current_app.config['CAS_USERNAME_SESSION_KEY']
cas_attributes_session_key = current_app.config['CAS_ATTRIBUTES_SESSION_KEY']
current_app.logger.debug("validating token {0}".format(ticket))
cas_validate_url = create_cas_validate_url(
current_app.config['CAS_SERVER'],
current_app.config['CAS_VALIDATE_ROUTE'],
flask.url_for('.login', _external=True),
ticket)
current_app.logger.debug("Making GET request to {0}".format(
cas_validate_url))
xml_from_dict = {}
isValid = False
try:
xmldump = urlopen(cas_validate_url).read().strip().decode('utf8', 'ignore')
xml_from_dict = parse(xmldump)
isValid = True if "cas:authenticationSuccess" in xml_from_dict["cas:serviceResponse"] else False
except ValueError:
current_app.logger.error("CAS returned unexpected result")
if isValid:
current_app.logger.debug("valid")
xml_from_dict = xml_from_dict["cas:serviceResponse"]["cas:authenticationSuccess"]
username = xml_from_dict["cas:user"]
attributes = xml_from_dict["cas:attributes"]
if attributes and "cas:memberOf" in attributes:
if isinstance(attributes["cas:memberOf"],list):
groups=attributes["cas:memberOf"]
else:
groups = attributes["cas:memberOf"].lstrip('[').rstrip(']').split(',')
for group_number,group in enumerate(groups):
attributes['cas:memberOf'][group_number] = group.lstrip(' ').rstrip(' ')
flask.session[cas_username_session_key] = username
flask.session[cas_attributes_session_key] = attributes
else:
current_app.logger.debug("invalid")
return isValid
| {
"content_hash": "58188a345ae4a6ac258d2dbb22423d97",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 104,
"avg_line_length": 36.364285714285714,
"alnum_prop": 0.6633274405814182,
"repo_name": "campenberger/Flask-CAS",
"id": "fe52af31b13baa1b67709d03bf2f87883f80255e",
"size": "5091",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "flask_cas/routing.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "30672"
}
],
"symlink_target": ""
} |
from __future__ import absolute_import
from __future__ import division
import os
import logging
import psutil
from guild import var
from guild import util
DEFAULT_LOG_MAX_SIZE = 102400
DEFAULT_LOG_BACKUPS = 1
class ServiceError(Exception):
pass
class Running(ServiceError):
def __init__(self, name, pidfile):
super(Running, self).__init__(name, pidfile)
self.name = name
self.pidfile = pidfile
class NotRunning(ServiceError):
def __init__(self, name):
super(NotRunning, self).__init__(name)
self.name = name
class PidfileError(ServiceError):
def __init__(self, pidfile, error):
super(PidfileError, self).__init__(pidfile, error)
self.pidfile = pidfile
self.error = error
class OrphanedProcess(ServiceError):
def __init__(self, pid, pidfile):
super(OrphanedProcess, self).__init__(pid, pidfile)
self.pid = pid
self.pidfile = pidfile
class Status(object):
def __init__(self, running, pid=None):
self.running = running
self.pid = pid
def start(
name,
f,
foreground,
log_max_size=DEFAULT_LOG_MAX_SIZE,
log_backups=DEFAULT_LOG_BACKUPS,
):
log = _init_log(name, log_max_size, log_backups, foreground)
if foreground:
_run(f, log)
else:
_start(name, f, log)
def _init_log(name, max_size, backups, foreground):
if foreground:
handler = logging.StreamHandler()
else:
logfile = var.logfile(name)
util.ensure_dir(os.path.dirname(logfile))
handler = logging.handlers.RotatingFileHandler(
logfile, maxBytes=max_size, backupCount=backups
)
handler.setFormatter(
logging.Formatter("%(asctime)s %(message)s", "%Y-%m-%d %H:%M:%S")
)
log = logging.getLogger("guild." + name)
log.propagate = False
log.addHandler(handler)
return log
def _run(f, log, log_level=None):
# When daemonized, log.level is 10 for some reason - reset to
# log_level if provided.
if log_level is not None:
log.setLevel(log_level)
try:
f(log)
except:
log.exception("service callback")
def _start(name, f, log):
import daemonize
pidfile = var.pidfile(name)
if os.path.exists(pidfile):
raise Running(name, pidfile)
util.ensure_dir(os.path.dirname(pidfile))
# Save original log level to workaround issue with daemonization
# (see note in _run).
log_level = log.getEffectiveLevel()
daemon = daemonize.Daemonize(
app=name,
action=lambda: _run(f, log, log_level),
pid=pidfile,
keep_fds=_log_fds(log),
)
daemon.start()
def _log_fds(log):
return [h.stream.fileno() for h in log.handlers if hasattr(h, "stream")]
def stop(name, title=None):
log = logging.getLogger("guild")
title = title or name
pidfile = var.pidfile(name)
if not os.path.exists(pidfile):
raise NotRunning(name)
try:
pid = _read_pid(pidfile)
except Exception:
if log.getEffectiveLevel() <= logging.DEBUG:
log.exception("reading %s", pidfile)
log.info("%s has an invalid pidfile (%s) - deleting", title, pidfile)
util.ensure_deleted(pidfile)
else:
try:
proc = psutil.Process(pid)
except psutil.NoSuchProcess:
log.info("%s did not shut down cleanly - cleaning up", title)
util.ensure_deleted(pidfile)
else:
log.info("Stopping %s (pid %i)", title, proc.pid)
proc.terminate()
def status(name):
pidfile = var.pidfile(name)
if os.path.exists(pidfile):
try:
pid = _read_pid(pidfile)
except Exception as e:
raise PidfileError(pidfile, e)
else:
try:
proc = psutil.Process(pid)
except psutil.NoSuchProcess:
raise OrphanedProcess(pid, pidfile)
else:
return Status(proc.is_running(), pid)
else:
return Status(False)
def _read_pid(pidfile):
raw = open(pidfile, "r").read()
return int(raw.strip())
| {
"content_hash": "caf18044c033286d43280d4db918efb5",
"timestamp": "",
"source": "github",
"line_count": 163,
"max_line_length": 77,
"avg_line_length": 25.447852760736197,
"alnum_prop": 0.6051108968177434,
"repo_name": "guildai/guild",
"id": "a478e96cbd4f755b4bde892c1548fc1177918282",
"size": "4729",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "guild/service.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "416"
},
{
"name": "JavaScript",
"bytes": "29682"
},
{
"name": "Makefile",
"bytes": "2621"
},
{
"name": "Python",
"bytes": "736181"
},
{
"name": "Shell",
"bytes": "1074"
},
{
"name": "Vue",
"bytes": "48469"
}
],
"symlink_target": ""
} |
from os.path import join, dirname, realpath
ROOT_PATH = dirname(realpath(__file__))
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': join(ROOT_PATH, "testtinymce.sqlite"),
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
USE_L10N = True
MEDIA_ROOT = join(ROOT_PATH, "media")
MEDIA_URL = '/media/'
ADMIN_MEDIA_PREFIX = '/static/admin/'
STATIC_ROOT = join(ROOT_PATH, "static")
STATIC_URL = "/static/"
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
SECRET_KEY = 'w4o4x^&b4h4zne9&3b1m-_p-=+&n_i_sdf@oz=gd+6h6v1$sd9'
ROOT_URLCONF = 'testtinymce.urls'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.flatpages',
'tinymce',
'testtinymce.testapp',
)
TINYMCE_SPELLCHECKER = True
TINYMCE_COMPRESSOR = True
TINYMCE_DEFAULT_CONFIG = {
'theme': "advanced",
'plugins': "spellchecker",
'theme_advanced_buttons3_add': "|,spellchecker",
}
| {
"content_hash": "76e578783680967bbca9d6b4e98336a5",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 65,
"avg_line_length": 25.59016393442623,
"alnum_prop": 0.6675208199871877,
"repo_name": "agushuley/gu-django-tinymce",
"id": "c84a5f0288f6b8e9bdb2736621e9cfa3e98a02ca",
"size": "1605",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "testtinymce/settings.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "675"
},
{
"name": "JavaScript",
"bytes": "1898"
},
{
"name": "Makefile",
"bytes": "1130"
},
{
"name": "Python",
"bytes": "35305"
},
{
"name": "Shell",
"bytes": "530"
}
],
"symlink_target": ""
} |
from django import template
from django.conf import settings
from django.template import defaultfilters
from django.utils.translation import pgettext, ugettext as _, ungettext
register = template.Library()
# A tuple of standard large number to their converters
intword_converters = (
(3, lambda number: (
ungettext('%(value).fk', '%(value).1fk', number),
ungettext('%(value)sk', '%(value)sk', number),
)),
(6, lambda number: (
ungettext('%(value).1fm', '%(value).1fm', number),
ungettext('%(value)sm', '%(value)sm', number),
)),
(9, lambda number: (
ungettext('%(value).1fb', '%(value).1fb', number),
ungettext('%(value)sb', '%(value)sb', number),
)),
(12, lambda number: (
ungettext('%(value).1ft', '%(value).1ft', number),
ungettext('%(value)s trillion', '%(value)s trillion', number),
)),
(15, lambda number: (
ungettext('%(value).1fq', '%(value).1fq', number),
ungettext('%(value)s quadrillion', '%(value)s quadrillion', number),
)),
)
@register.filter(is_safe=False)
def abbreviatedintword(value):
"""
Converts a large integer to a friendly text representation. Works best
for numbers over 1 million. For example, 1000000 becomes '1.0 million',
1200000 becomes '1.2 million' and '1200000000' becomes '1.2 billion'.
"""
try:
value = int(value)
except (TypeError, ValueError):
return value
def _check_for_i18n(value, float_formatted, string_formatted):
"""
Use the i18n enabled defaultfilters.floatformat if possible
"""
if settings.USE_L10N:
value = defaultfilters.floatformat(value, 1)
template = string_formatted
else:
template = float_formatted
template = template % {'value': value}
return template.replace('.0', '')
for exponent, converters in intword_converters:
large_number = 10 ** exponent
if value < large_number * 1000:
new_value = value / float(large_number)
return _check_for_i18n(new_value, *converters(new_value))
return value
@register.simple_tag
def url_replace(request, field, value):
"""
Replaces or creates a GET parameter in a URL.
"""
dict_ = request.GET.copy()
dict_[field] = value
return dict_.urlencode()
@register.filter(is_safe=False)
def risk_level(value):
"""
Returns a string based risk level from a number.
1: Low
2: Medium
3: Medium
4: High
"""
if value == 1:
return 'low'
if value == 2 or value == 3:
return 'medium'
if value == 4:
return 'high'
@register.filter(is_safe=False)
def grade(value):
"""
Returns a string based grade from a number.
1: God
2: Fair
3: Fair
4: Poor
"""
if value == 1:
return 'good'
if value == 2 or value == 3:
return 'fair'
if value == 4:
return 'poor'
@register.filter(is_safe=False)
def quartile_text(value):
"""
Replaces or creates a GET parameter in a URL.
"""
return dict(zip(range(1, 5), ['lowest', 'second lowest', 'second highest', 'highest'])).get(value)
| {
"content_hash": "d7f55bde9a258216200281b08a5d2941",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 102,
"avg_line_length": 26.65289256198347,
"alnum_prop": 0.595968992248062,
"repo_name": "meilinger/firecares",
"id": "01b39b38c42f3bfb9420518675c8d41648973bba",
"size": "3225",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "firecares/firestation/templatetags/firecares.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "831772"
},
{
"name": "HTML",
"bytes": "252037"
},
{
"name": "JavaScript",
"bytes": "1118121"
},
{
"name": "PHP",
"bytes": "17935"
},
{
"name": "Python",
"bytes": "491069"
}
],
"symlink_target": ""
} |
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import paramiko
import paramiko.py3compat
import os
import os.path
import sys
import errno
from stat import S_ISDIR, S_ISLNK, S_ISREG, S_IMODE, S_IFMT
import argparse
import logging
from getpass import getuser, getpass
import glob
import socket
"""SFTPClone: sync local and remote directories."""
logger = None
try:
# Not available in Python 2.x
FileNotFoundError
except NameError:
FileNotFoundError = IOError
def configure_logging(level=logging.DEBUG):
"""Configure the module logging engine."""
if level == logging.DEBUG:
# For debugging purposes, log from everyone!
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s'
)
return logging
logger = logging.getLogger(__name__)
logger.setLevel(level)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
ch = logging.StreamHandler()
ch.setLevel(level)
ch.setFormatter(formatter)
logger.addHandler(ch)
return logger
def path_join(*args):
"""
Wrapper around `os.path.join`.
Makes sure to join paths of the same type (bytes).
"""
args = (paramiko.py3compat.u(arg) for arg in args)
return os.path.join(*args)
def parse_username_password_hostname(remote_url):
"""
Parse a command line string and return username, password, remote hostname and remote path.
:param remote_url: A command line string.
:return: A tuple, containing username, password, remote hostname and remote path.
"""
assert remote_url
assert ':' in remote_url
if '@' in remote_url:
username, hostname = remote_url.rsplit('@', 1)
else:
username, hostname = None, remote_url
hostname, remote_path = hostname.split(':', 1)
password = None
if username and ':' in username:
username, password = username.split(':', 1)
assert hostname
assert remote_path
return username, password, hostname, remote_path
def get_ssh_agent_keys(logger):
"""
Ask the SSH agent for a list of keys, and return it.
:return: A reference to the SSH agent and a list of keys.
"""
agent, agent_keys = None, None
try:
agent = paramiko.agent.Agent()
_agent_keys = agent.get_keys()
if not _agent_keys:
agent.close()
logger.error(
"SSH agent didn't provide any valid key. Trying to continue..."
)
else:
agent_keys = tuple(k for k in _agent_keys)
except paramiko.SSHException:
if agent:
agent.close()
agent = None
logger.error("SSH agent speaks a non-compatible protocol. Ignoring it.")
finally:
return agent, agent_keys
class SFTPClone(object):
"""The SFTPClone class."""
def __init__(self, local_path, remote_url,
identity_files=None, port=None, fix_symlinks=False,
ssh_config_path=None, ssh_agent=False,
exclude_file=None, known_hosts_path=None,
delete=True, allow_unknown=False,
create_remote_directory=False,
):
"""Init the needed parameters and the SFTPClient."""
self.local_path = os.path.realpath(os.path.expanduser(local_path))
self.logger = logger or configure_logging()
self.create_remote_directory = create_remote_directory
if not os.path.exists(self.local_path):
self.logger.error("Local path MUST exist. Exiting.")
sys.exit(1)
if exclude_file:
with open(exclude_file) as f:
# As in rsync's exclude from, ignore lines with leading ; and #
# and treat each path as relative (thus by removing the leading
# /)
exclude_list = [
line.rstrip().lstrip("/")
for line in f
if not line.startswith((";", "#"))
]
# actually, is a set of excluded files
self.exclude_list = {
g
for pattern in exclude_list
for g in glob.glob(path_join(self.local_path, pattern))
}
else:
self.exclude_list = set()
username, password, hostname, self.remote_path = parse_username_password_hostname(remote_url)
identity_files = identity_files or []
proxy_command = None
if ssh_config_path:
try:
with open(os.path.expanduser(ssh_config_path)) as c_file:
ssh_config = paramiko.SSHConfig()
ssh_config.parse(c_file)
c = ssh_config.lookup(hostname)
hostname = c.get("hostname", hostname)
username = c.get("user", username)
port = int(c.get("port", port))
identity_files = c.get("identityfile", identity_files)
proxy_command = c.get("proxycommand")
except Exception as e:
# it could be safe to continue anyway,
# because parameters could have been manually specified
self.logger.error(
"Error while parsing ssh_config file: %s. Trying to continue anyway...", e
)
# Set default values
if not username:
username = getuser() # defaults to current user
port = port or 22
allow_unknown = allow_unknown or False
self.chown = False
self.fix_symlinks = fix_symlinks or False
self.delete = delete if delete is not None else True
if ssh_agent:
agent, agent_keys = get_ssh_agent_keys(self.logger)
else:
agent, agent_keys = None, None
if not identity_files and not password and not agent_keys:
self.logger.error(
"You need to specify either a password, an identity or to enable the ssh-agent support."
)
sys.exit(1)
# only root can change file owner
if username == 'root':
self.chown = True
sock = (hostname, port)
if proxy_command is not None:
sock = paramiko.proxy.ProxyCommand(proxy_command)
try:
transport = paramiko.Transport(sock)
except socket.gaierror:
self.logger.error(
"Hostname not known. Are you sure you inserted it correctly?")
sys.exit(1)
try:
ssh_host = hostname if port == 22 else "[{}]:{}".format(hostname, port)
known_hosts = None
"""
Before starting the transport session, we have to configure it.
Specifically, we need to configure the preferred PK algorithm.
If the system already knows a public key of a specific kind for
a remote host, we have to peek its type as the preferred one.
"""
if known_hosts_path:
known_hosts = paramiko.HostKeys()
known_hosts_path = os.path.realpath(
os.path.expanduser(known_hosts_path))
try:
known_hosts.load(known_hosts_path)
except IOError:
self.logger.error(
"Error while loading known hosts file at {}. Exiting...".format(
known_hosts_path)
)
sys.exit(1)
known_keys = known_hosts.lookup(ssh_host)
if known_keys is not None:
# one or more keys are already known
# set their type as preferred
transport.get_security_options().key_types = \
tuple(known_keys.keys())
transport.start_client()
if not known_hosts:
self.logger.warning("Security warning: skipping known hosts check...")
else:
pubk = transport.get_remote_server_key()
if ssh_host in known_hosts.keys():
if not known_hosts.check(ssh_host, pubk):
self.logger.error(
"Security warning: "
"remote key fingerprint {} for hostname "
"{} didn't match the one in known_hosts {}. "
"Exiting...".format(
pubk.get_base64(),
ssh_host,
known_hosts.lookup(hostname),
)
)
sys.exit(1)
elif not allow_unknown:
prompt = ("The authenticity of host '{}' can't be established.\n"
"{} key is {}.\n"
"Are you sure you want to continue connecting? [y/n] ").format(
ssh_host, pubk.get_name(), pubk.get_base64())
try:
# Renamed to `input` in Python 3.x
response = raw_input(prompt)
except NameError:
response = input(prompt)
# Note: we do not modify the user's known_hosts file
if not (response == "y" or response == "yes"):
self.logger.error(
"Host authentication failed."
)
sys.exit(1)
def perform_key_auth(pkey):
try:
transport.auth_publickey(
username=username,
key=pkey
)
return True
except paramiko.SSHException:
self.logger.warning(
"Authentication with identity {}... failed".format(pkey.get_base64()[:10])
)
return False
if password: # Password auth, if specified.
transport.auth_password(
username=username,
password=password
)
elif agent_keys: # SSH agent keys have higher priority
for pkey in agent_keys:
if perform_key_auth(pkey):
break # Authentication worked.
else: # None of the keys worked.
raise paramiko.SSHException
elif identity_files: # Then follow identity file (specified from CL or ssh_config)
# Try identity files one by one, until one works
for key_path in identity_files:
key_path = os.path.expanduser(key_path)
try:
key = paramiko.RSAKey.from_private_key_file(key_path)
except paramiko.PasswordRequiredException:
pk_password = getpass(
"It seems that your identity from '{}' is encrypted. "
"Please enter your password: ".format(key_path)
)
try:
key = paramiko.RSAKey.from_private_key_file(key_path, pk_password)
except paramiko.SSHException:
self.logger.error(
"Incorrect passphrase. Cannot decode private key from '{}'.".format(key_path)
)
continue
except IOError or paramiko.SSHException:
self.logger.error(
"Something went wrong while opening '{}'. Skipping it.".format(key_path)
)
continue
if perform_key_auth(key):
break # Authentication worked.
else: # None of the keys worked.
raise paramiko.SSHException
else: # No authentication method specified, we shouldn't arrive here.
assert False
except paramiko.SSHException:
self.logger.error(
"None of the provided authentication methods worked. Exiting."
)
transport.close()
sys.exit(1)
finally:
if agent:
agent.close()
self.sftp = paramiko.SFTPClient.from_transport(transport)
if self.remote_path.startswith("~"):
# nasty hack to let getcwd work without changing dir!
self.sftp.chdir('.')
self.remote_path = self.remote_path.replace(
"~", self.sftp.getcwd()) # home is the initial sftp dir
@staticmethod
def _file_need_upload(l_st, r_st):
return True if \
l_st.st_size != r_st.st_size or int(l_st.st_mtime) != r_st.st_mtime \
else False
@staticmethod
def _must_be_deleted(local_path, r_st):
"""Return True if the remote correspondent of local_path has to be deleted.
i.e. if it doesn't exists locally or if it has a different type from the remote one."""
# if the file doesn't exists
if not os.path.lexists(local_path):
return True
# or if the file type is different
l_st = os.lstat(local_path)
if S_IFMT(r_st.st_mode) != S_IFMT(l_st.st_mode):
return True
return False
def _match_modes(self, remote_path, l_st):
"""Match mod, utime and uid/gid with locals one."""
self.sftp.chmod(remote_path, S_IMODE(l_st.st_mode))
self.sftp.utime(remote_path, (l_st.st_atime, l_st.st_mtime))
if self.chown:
self.sftp.chown(remote_path, l_st.st_uid, l_st.st_gid)
def file_upload(self, local_path, remote_path, l_st):
"""Upload local_path to remote_path and set permission and mtime."""
self.sftp.put(local_path, remote_path)
self._match_modes(remote_path, l_st)
def remote_delete(self, remote_path, r_st):
"""Remove the remote directory node."""
# If it's a directory, then delete content and directory
if S_ISDIR(r_st.st_mode):
for item in self.sftp.listdir_attr(remote_path):
full_path = path_join(remote_path, item.filename)
self.remote_delete(full_path, item)
self.sftp.rmdir(remote_path)
# Or simply delete files
else:
try:
self.sftp.remove(remote_path)
except FileNotFoundError as e:
self.logger.error(
"error while removing {}. trace: {}".format(remote_path, e)
)
def check_for_deletion(self, relative_path=None):
"""Traverse the entire remote_path tree.
Find files/directories that need to be deleted,
not being present in the local folder.
"""
if not relative_path:
relative_path = str() # root of shared directory tree
remote_path = path_join(self.remote_path, relative_path)
local_path = path_join(self.local_path, relative_path)
for remote_st in self.sftp.listdir_attr(remote_path):
r_lstat = self.sftp.lstat(path_join(remote_path, remote_st.filename))
inner_remote_path = path_join(remote_path, remote_st.filename)
inner_local_path = path_join(local_path, remote_st.filename)
# check if remote_st is a symlink
# otherwise could delete file outside shared directory
if S_ISLNK(r_lstat.st_mode):
if self._must_be_deleted(inner_local_path, r_lstat):
self.remote_delete(inner_remote_path, r_lstat)
continue
if self._must_be_deleted(inner_local_path, remote_st):
self.remote_delete(inner_remote_path, remote_st)
elif S_ISDIR(remote_st.st_mode):
self.check_for_deletion(
path_join(relative_path, remote_st.filename)
)
def create_update_symlink(self, link_destination, remote_path):
"""Create a new link pointing to link_destination in remote_path position."""
try: # if there's anything, delete it
self.sftp.remove(remote_path)
except IOError: # that's fine, nothing exists there!
pass
finally: # and recreate the link
try:
self.sftp.symlink(link_destination, remote_path)
except OSError as e:
# Sometimes, if links are "too" different, symlink fails.
# Sadly, nothing we can do about it.
self.logger.error("error while symlinking {} to {}: {}".format(
remote_path, link_destination, e))
def node_check_for_upload_create(self, relative_path, f):
"""Check if the given directory tree node has to be uploaded/created on the remote folder."""
if not relative_path:
# we're at the root of the shared directory tree
relative_path = str()
# the (absolute) local address of f.
local_path = path_join(self.local_path, relative_path, f)
try:
l_st = os.lstat(local_path)
except OSError as e:
"""A little background here.
Sometimes, in big clusters configurations (mail, etc.),
files could disappear or be moved, suddenly.
There's nothing to do about it,
system should be stopped before doing backups.
Anyway, we log it, and skip it.
"""
self.logger.error("error while checking {}: {}".format(relative_path, e))
return
if local_path in self.exclude_list:
self.logger.info("Skipping excluded file %s.", local_path)
return
# the (absolute) remote address of f.
remote_path = path_join(self.remote_path, relative_path, f)
# First case: f is a directory
if S_ISDIR(l_st.st_mode):
# we check if the folder exists on the remote side
# it has to be a folder, otherwise it would have already been
# deleted
try:
self.sftp.stat(remote_path)
except IOError: # it doesn't exist yet on remote side
self.sftp.mkdir(remote_path)
self._match_modes(remote_path, l_st)
# now, we should traverse f too (recursion magic!)
self.check_for_upload_create(path_join(relative_path, f))
# Second case: f is a symbolic link
elif S_ISLNK(l_st.st_mode):
# read the local link
local_link = os.readlink(local_path)
absolute_local_link = os.path.realpath(local_link)
# is it absolute?
is_absolute = local_link.startswith("/")
# and does it point inside the shared directory?
# add trailing slash (security)
trailing_local_path = path_join(self.local_path, '')
relpath = os.path.commonprefix(
[absolute_local_link,
trailing_local_path]
) == trailing_local_path
if relpath:
relative_link = absolute_local_link[len(trailing_local_path):]
else:
relative_link = None
"""
# Refactor them all, be efficient!
# Case A: absolute link pointing outside shared directory
# (we can only update the remote part)
if is_absolute and not relpath:
self.create_update_symlink(local_link, remote_path)
# Case B: absolute link pointing inside shared directory
# (we can leave it as it is or fix the prefix to match the one of the remote server)
elif is_absolute and relpath:
if self.fix_symlinks:
self.create_update_symlink(
join(
self.remote_path,
relative_link,
),
remote_path
)
else:
self.create_update_symlink(local_link, remote_path)
# Case C: relative link pointing outside shared directory
# (all we can do is try to make the link anyway)
elif not is_absolute and not relpath:
self.create_update_symlink(local_link, remote_path)
# Case D: relative link pointing inside shared directory
# (we preserve the relativity and link it!)
elif not is_absolute and relpath:
self.create_update_symlink(local_link, remote_path)
"""
if is_absolute and relpath:
if self.fix_symlinks:
self.create_update_symlink(
path_join(
self.remote_path,
relative_link,
),
remote_path
)
else:
self.create_update_symlink(local_link, remote_path)
# Third case: regular file
elif S_ISREG(l_st.st_mode):
try:
r_st = self.sftp.lstat(remote_path)
if self._file_need_upload(l_st, r_st):
self.file_upload(local_path, remote_path, l_st)
except IOError as e:
if e.errno == errno.ENOENT:
self.file_upload(local_path, remote_path, l_st)
# Anything else.
else:
self.logger.warning("Skipping unsupported file %s.", local_path)
def check_for_upload_create(self, relative_path=None):
"""Traverse the relative_path tree and check for files that need to be uploaded/created.
Relativity here refers to the shared directory tree."""
for f in os.listdir(
path_join(
self.local_path, relative_path) if relative_path else self.local_path
):
self.node_check_for_upload_create(relative_path, f)
def run(self):
"""Run the sync.
Confront the local and the remote directories and perform the needed changes."""
# Check if remote path is present
try:
self.sftp.stat(self.remote_path)
except FileNotFoundError as e:
if self.create_remote_directory:
self.sftp.mkdir(self.remote_path)
self.logger.info(
"Created missing remote dir: '" + self.remote_path + "'")
else:
self.logger.error(
"Remote folder does not exists. "
"Add '-r' to create it if missing.")
sys.exit(1)
try:
if self.delete:
# First check for items to be removed
self.check_for_deletion()
# Now scan local for items to upload/create
self.check_for_upload_create()
except FileNotFoundError:
# If this happens, probably the remote folder doesn't exist.
self.logger.error(
"Error while opening remote folder. Are you sure it does exist?")
sys.exit(1)
def create_parser():
"""Create the CLI argument parser."""
parser = argparse.ArgumentParser(
description='Sync a local and a remote folder through SFTP.'
)
parser.add_argument(
"path",
type=str,
metavar="local-path",
help="the path of the local folder",
)
parser.add_argument(
"remote",
type=str,
metavar="user[:password]@hostname:remote-path",
help="the ssh-url ([user[:password]@]hostname:remote-path) of the remote folder. "
"The hostname can be specified as a ssh_config's hostname too. "
"Every missing information will be gathered from there",
)
parser.add_argument(
"-k",
"--key",
metavar="identity-path",
action="append",
help="private key identity path (defaults to ~/.ssh/id_rsa)"
)
parser.add_argument(
"-l",
"--logging",
choices=['CRITICAL',
'ERROR',
'WARNING',
'INFO',
'DEBUG',
'NOTSET'],
default='ERROR',
help="set logging level"
)
parser.add_argument(
"-p",
"--port",
default=22,
type=int,
help="SSH remote port (defaults to 22)"
)
parser.add_argument(
"-f",
"--fix-symlinks",
action="store_true",
help="fix symbolic links on remote side"
)
parser.add_argument(
"-a",
"--ssh-agent",
action="store_true",
help="enable ssh-agent support"
)
parser.add_argument(
"-c",
"--ssh-config",
metavar="ssh_config path",
default="~/.ssh/config",
type=str,
help="path to the ssh-configuration file (default to ~/.ssh/config)"
)
parser.add_argument(
"-n",
"--known-hosts",
metavar="known_hosts path",
default="~/.ssh/known_hosts",
type=str,
help="path to the openSSH known_hosts file"
)
parser.add_argument(
"-d",
"--disable-known-hosts",
action="store_true",
help="disable known_hosts fingerprint checking (security warning!)"
)
parser.add_argument(
"-e",
"--exclude-from",
metavar="exclude-from-file-path",
type=str,
help="exclude files matching pattern in exclude-from-file-path"
)
parser.add_argument(
"-t",
"--do-not-delete",
action="store_true",
help="do not delete remote files missing from local folder"
)
parser.add_argument(
"-o",
"--allow-unknown",
action="store_true",
help="allow connection to unknown hosts"
)
parser.add_argument(
"-r",
"--create-remote-directory",
action="store_true",
help="Create remote base directory if missing on remote"
)
return parser
def main(args=None):
"""The main."""
parser = create_parser()
args = vars(parser.parse_args(args))
log_mapping = {
'CRITICAL': logging.CRITICAL,
'ERROR': logging.ERROR,
'WARNING': logging.WARNING,
'INFO': logging.INFO,
'DEBUG': logging.DEBUG,
'NOTSET': logging.NOTSET,
}
log_level = log_mapping[args['logging']]
del(args['logging'])
global logger
logger = configure_logging(log_level)
args_mapping = {
"path": "local_path",
"remote": "remote_url",
"ssh_config": "ssh_config_path",
"exclude_from": "exclude_file",
"known_hosts": "known_hosts_path",
"do_not_delete": "delete",
"key": "identity_files",
}
kwargs = { # convert the argument names to class constructor parameters
args_mapping[k]: v
for k, v in args.items()
if v and k in args_mapping
}
kwargs.update({
k: v
for k, v in args.items()
if v and k not in args_mapping
})
# Special case: disable known_hosts check
if args['disable_known_hosts']:
kwargs['known_hosts_path'] = None
del(kwargs['disable_known_hosts'])
# Toggle `do_not_delete` flag
if "delete" in kwargs:
kwargs["delete"] = not kwargs["delete"]
# Manually set the default identity file.
kwargs["identity_files"] = kwargs.get("identity_files", None) or ["~/.ssh/id_rsa"]
sync = SFTPClone(
**kwargs
)
sync.run()
if __name__ == '__main__':
main()
| {
"content_hash": "ea8713ec0a1d518fb6221f4a0e0fd51f",
"timestamp": "",
"source": "github",
"line_count": 806,
"max_line_length": 109,
"avg_line_length": 34.839950372208435,
"alnum_prop": 0.533528008261814,
"repo_name": "unbit/sftpclone",
"id": "c48142ce43a766eb0a02798a5f4c343e1c50f082",
"size": "28155",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sftpclone/sftpclone.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "61291"
}
],
"symlink_target": ""
} |
import frappe
def execute():
frappe.reload_doc("core", "doctype", "system_settings", force=1)
frappe.db.set_value('System Settings', None, "password_reset_limit", 3)
| {
"content_hash": "3072366fe978957fdf71f451b8da2f16",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 72,
"avg_line_length": 28.333333333333332,
"alnum_prop": 0.711764705882353,
"repo_name": "adityahase/frappe",
"id": "188f2383e70eb0672629e53bc1daf27a60463c8a",
"size": "271",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "frappe/patches/v12_0/set_default_password_reset_limit.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "288806"
},
{
"name": "HTML",
"bytes": "209164"
},
{
"name": "JavaScript",
"bytes": "2350450"
},
{
"name": "Less",
"bytes": "160693"
},
{
"name": "Makefile",
"bytes": "99"
},
{
"name": "Python",
"bytes": "3035663"
},
{
"name": "SCSS",
"bytes": "45340"
},
{
"name": "Shell",
"bytes": "517"
},
{
"name": "Vue",
"bytes": "73943"
}
],
"symlink_target": ""
} |
from jsonrpc.proxy import JSONRPCProxy
import sys
import string
# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======
if rpcpass == "":
access = JSONRPCProxy.from_url("http://127.0.0.1:46502")
else:
access = JSONRPCProxy.from_url("http://"+rpcuser+":"+rpcpass+"@127.0.0.1:46502")
cmd = sys.argv[1].lower()
if cmd == "backupwallet":
try:
path = raw_input("Enter destination path/filename: ")
print access.backupwallet(path)
except:
print "\n---An error occurred---\n"
elif cmd == "getaccount":
try:
addr = raw_input("Enter a Bitcoin address: ")
print access.getaccount(addr)
except:
print "\n---An error occurred---\n"
elif cmd == "getaccountaddress":
try:
acct = raw_input("Enter an account name: ")
print access.getaccountaddress(acct)
except:
print "\n---An error occurred---\n"
elif cmd == "getaddressesbyaccount":
try:
acct = raw_input("Enter an account name: ")
print access.getaddressesbyaccount(acct)
except:
print "\n---An error occurred---\n"
elif cmd == "getbalance":
try:
acct = raw_input("Enter an account (optional): ")
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.getbalance(acct, mc)
except:
print access.getbalance()
except:
print "\n---An error occurred---\n"
elif cmd == "getblockbycount":
try:
height = raw_input("Height: ")
print access.getblockbycount(height)
except:
print "\n---An error occurred---\n"
elif cmd == "getblockcount":
try:
print access.getblockcount()
except:
print "\n---An error occurred---\n"
elif cmd == "getblocknumber":
try:
print access.getblocknumber()
except:
print "\n---An error occurred---\n"
elif cmd == "getconnectioncount":
try:
print access.getconnectioncount()
except:
print "\n---An error occurred---\n"
elif cmd == "getdifficulty":
try:
print access.getdifficulty()
except:
print "\n---An error occurred---\n"
elif cmd == "getgenerate":
try:
print access.getgenerate()
except:
print "\n---An error occurred---\n"
elif cmd == "gethashespersec":
try:
print access.gethashespersec()
except:
print "\n---An error occurred---\n"
elif cmd == "getinfo":
try:
print access.getinfo()
except:
print "\n---An error occurred---\n"
elif cmd == "getnewaddress":
try:
acct = raw_input("Enter an account name: ")
try:
print access.getnewaddress(acct)
except:
print access.getnewaddress()
except:
print "\n---An error occurred---\n"
elif cmd == "getreceivedbyaccount":
try:
acct = raw_input("Enter an account (optional): ")
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.getreceivedbyaccount(acct, mc)
except:
print access.getreceivedbyaccount()
except:
print "\n---An error occurred---\n"
elif cmd == "getreceivedbyaddress":
try:
addr = raw_input("Enter a Bitcoin address (optional): ")
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.getreceivedbyaddress(addr, mc)
except:
print access.getreceivedbyaddress()
except:
print "\n---An error occurred---\n"
elif cmd == "gettransaction":
try:
txid = raw_input("Enter a transaction ID: ")
print access.gettransaction(txid)
except:
print "\n---An error occurred---\n"
elif cmd == "getwork":
try:
data = raw_input("Data (optional): ")
try:
print access.gettransaction(data)
except:
print access.gettransaction()
except:
print "\n---An error occurred---\n"
elif cmd == "help":
try:
cmd = raw_input("Command (optional): ")
try:
print access.help(cmd)
except:
print access.help()
except:
print "\n---An error occurred---\n"
elif cmd == "listaccounts":
try:
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.listaccounts(mc)
except:
print access.listaccounts()
except:
print "\n---An error occurred---\n"
elif cmd == "listreceivedbyaccount":
try:
mc = raw_input("Minimum confirmations (optional): ")
incemp = raw_input("Include empty? (true/false, optional): ")
try:
print access.listreceivedbyaccount(mc, incemp)
except:
print access.listreceivedbyaccount()
except:
print "\n---An error occurred---\n"
elif cmd == "listreceivedbyaddress":
try:
mc = raw_input("Minimum confirmations (optional): ")
incemp = raw_input("Include empty? (true/false, optional): ")
try:
print access.listreceivedbyaddress(mc, incemp)
except:
print access.listreceivedbyaddress()
except:
print "\n---An error occurred---\n"
elif cmd == "listtransactions":
try:
acct = raw_input("Account (optional): ")
count = raw_input("Number of transactions (optional): ")
frm = raw_input("Skip (optional):")
try:
print access.listtransactions(acct, count, frm)
except:
print access.listtransactions()
except:
print "\n---An error occurred---\n"
elif cmd == "move":
try:
frm = raw_input("From: ")
to = raw_input("To: ")
amt = raw_input("Amount:")
mc = raw_input("Minimum confirmations (optional): ")
comment = raw_input("Comment (optional): ")
try:
print access.move(frm, to, amt, mc, comment)
except:
print access.move(frm, to, amt)
except:
print "\n---An error occurred---\n"
elif cmd == "sendfrom":
try:
frm = raw_input("From: ")
to = raw_input("To: ")
amt = raw_input("Amount:")
mc = raw_input("Minimum confirmations (optional): ")
comment = raw_input("Comment (optional): ")
commentto = raw_input("Comment-to (optional): ")
try:
print access.sendfrom(frm, to, amt, mc, comment, commentto)
except:
print access.sendfrom(frm, to, amt)
except:
print "\n---An error occurred---\n"
elif cmd == "sendmany":
try:
frm = raw_input("From: ")
to = raw_input("To (in format address1:amount1,address2:amount2,...): ")
mc = raw_input("Minimum confirmations (optional): ")
comment = raw_input("Comment (optional): ")
try:
print access.sendmany(frm,to,mc,comment)
except:
print access.sendmany(frm,to)
except:
print "\n---An error occurred---\n"
elif cmd == "sendtoaddress":
try:
to = raw_input("To (in format address1:amount1,address2:amount2,...): ")
amt = raw_input("Amount:")
comment = raw_input("Comment (optional): ")
commentto = raw_input("Comment-to (optional): ")
try:
print access.sendtoaddress(to,amt,comment,commentto)
except:
print access.sendtoaddress(to,amt)
except:
print "\n---An error occurred---\n"
elif cmd == "setaccount":
try:
addr = raw_input("Address: ")
acct = raw_input("Account:")
print access.setaccount(addr,acct)
except:
print "\n---An error occurred---\n"
elif cmd == "setgenerate":
try:
gen= raw_input("Generate? (true/false): ")
cpus = raw_input("Max processors/cores (-1 for unlimited, optional):")
try:
print access.setgenerate(gen, cpus)
except:
print access.setgenerate(gen)
except:
print "\n---An error occurred---\n"
elif cmd == "settxfee":
try:
amt = raw_input("Amount:")
print access.settxfee(amt)
except:
print "\n---An error occurred---\n"
elif cmd == "stop":
try:
print access.stop()
except:
print "\n---An error occurred---\n"
elif cmd == "validateaddress":
try:
addr = raw_input("Address: ")
print access.validateaddress(addr)
except:
print "\n---An error occurred---\n"
elif cmd == "walletpassphrase":
try:
pwd = raw_input("Enter wallet passphrase: ")
access.walletpassphrase(pwd, 60)
print "\n---Wallet unlocked---\n"
except:
print "\n---An error occurred---\n"
elif cmd == "walletpassphrasechange":
try:
pwd = raw_input("Enter old wallet passphrase: ")
pwd2 = raw_input("Enter new wallet passphrase: ")
access.walletpassphrasechange(pwd, pwd2)
print
print "\n---Passphrase changed---\n"
except:
print
print "\n---An error occurred---\n"
print
else:
print "Command not found or not supported"
| {
"content_hash": "7743039ecbcb626bff231ee059051f95",
"timestamp": "",
"source": "github",
"line_count": 324,
"max_line_length": 81,
"avg_line_length": 24.265432098765434,
"alnum_prop": 0.6621724751971508,
"repo_name": "Atlascoinproject/atlascoin",
"id": "ed1c6bce5706f833c9637dc04d1aeabbd7fc984a",
"size": "7862",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "contrib/bitrpc/bitrpc.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "61563"
},
{
"name": "C",
"bytes": "8299554"
},
{
"name": "C++",
"bytes": "2804543"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "HTML",
"bytes": "50620"
},
{
"name": "Makefile",
"bytes": "17338"
},
{
"name": "NSIS",
"bytes": "6041"
},
{
"name": "Objective-C",
"bytes": "1052"
},
{
"name": "Objective-C++",
"bytes": "3736"
},
{
"name": "Python",
"bytes": "54460"
},
{
"name": "QMake",
"bytes": "23735"
},
{
"name": "Shell",
"bytes": "8513"
}
],
"symlink_target": ""
} |
"""Image utilities
Some general image utilities using PIL.
"""
import Queue
import collections
import io
import mimetypes
import os
import struct
import threading
from gi.repository import (
GLib,
GObject,
GdkPixbuf,
Gtk,
Gdk,
)
from PIL import Image, ImageFilter
mimetypes.init()
# Generating a drop shadow is an expensive operation. Keep a cache
# of already generated drop shadows so they can be reutilized
_drop_shadows_cache = {}
_icon_theme = Gtk.IconTheme.get_default()
_icon_filename_cache = {}
def get_icon_filename(choose_list, size):
"""Get a theme icon filename.
:param list choose_list: the list of icon names to choose from.
The first existing icon will be returned.
:param int size: size of the icon, to be passed to
:class:`Gtk.IconTheme.choose_icon`
:return: the path to the icon
:rtype: str
"""
icon = _icon_theme.choose_icon(choose_list, size,
Gtk.IconLookupFlags.NO_SVG)
return icon and icon.get_filename()
def get_icon_for_file(filename, size):
"""Get icon for filename mimetype.
Analyze filename to get its mimetype and return the path of an
icon representing it.
:param str filename: path of the file to be alalyzed
:param int size: size of the icon, to be passed to
:class:`Gtk.IconTheme.choose_icon`
:return: the path to the icon
:rtype: str
"""
if os.path.isdir(filename):
# mimetypes.guess_type doesn't work for folders
guessed_mime = 'folder/folder'
else:
# Fallback to unknown if mimetypes wasn't able to guess it
guessed_mime = mimetypes.guess_type(filename)[0] or 'unknown/unknown'
if guessed_mime in _icon_filename_cache:
return _icon_filename_cache[guessed_mime]
# Is there any value returned by guess_type that would have no /?
mimetype, details = guessed_mime.split('/')
# FIXME: guess_type mimetype is formatted differently from what
# Gtk.IconTheme expects. We are trying to improve matching here.
# Is there a better way for doing this?
icon_list = ['%s-%s' % (mimetype, details), details, mimetype]
if mimetype == 'application':
icon_list.append('application-x-%s' % (details, ))
icon_list.append('%s-x-generic' % (mimetype, ))
icon_list.append('unknown')
icon_filename = get_icon_filename(icon_list, size)
_icon_filename_cache[guessed_mime] = icon_filename
return icon_filename
def image2pixbuf(image):
"""Convert a PIL image to a pixbuf.
:param image: the image to convert
:type image: `PIL.Image`
:returns: the newly created pixbuf
:rtype: `GdkPixbuf.Pixbuf`
"""
with io.BytesIO() as f:
image.save(f, 'png')
loader = GdkPixbuf.PixbufLoader.new_with_type('png')
loader.write(f.getvalue())
pixbuf = loader.get_pixbuf()
loader.close()
return pixbuf
def add_border(image, border_size=5,
background_color=(0xff, 0xff, 0xff, 0xff)):
"""Add a border on the image.
:param image: the image to add the border
:type image: `PIL.Image`
:param int border_size: the size of the border
:param tuple background_color: the color of the border as a
tuple containing (r, g, b, a) information
:returns: the new image with the border
:rtype: `PIL.Image`
"""
width = image.size[0] + border_size * 2
height = image.size[1] + border_size * 2
try:
image.convert("RGBA")
image_parts = image.split()
mask = image_parts[3] if len(image_parts) == 4 else None
except IOError:
mask = None
border = Image.new("RGBA", (width, height), background_color)
border.paste(image, (border_size, border_size), mask=mask)
return border
def add_drop_shadow(image, iterations=3, border_size=2, offset=(2, 2),
shadow_color=(0x00, 0x00, 0x00, 0xff)):
"""Add a border on the image.
Based on this receipe::
http://en.wikibooks.org/wiki/Python_Imaging_Library/Drop_Shadows
:param image: the image to add the drop shadow
:type image: `PIL.Image`
:param int iterations: number of times to apply the blur filter
:param int border_size: the size of the border to add to leave
space for the shadow
:param tuple offset: the offset of the shadow as (x, y)
:param tuple shadow_color: the color of the shadow as a
tuple containing (r, g, b, a) information
:returns: the new image with the drop shadow
:rtype: `PIL.Image`
"""
width = image.size[0] + abs(offset[0]) + 2 * border_size
height = image.size[1] + abs(offset[1]) + 2 * border_size
key = (width, height, iterations, border_size, offset, shadow_color)
existing_shadow = _drop_shadows_cache.get(key)
if existing_shadow:
shadow = existing_shadow.copy()
else:
shadow = Image.new('RGBA', (width, height),
(0xff, 0xff, 0xff, 0x00))
# Place the shadow, with the required offset
# if < 0, push the rest of the image right
shadow_lft = border_size + max(offset[0], 0)
# if < 0, push the rest of the image down
shadow_top = border_size + max(offset[1], 0)
shadow.paste(shadow_color,
[shadow_lft, shadow_top,
shadow_lft + image.size[0],
shadow_top + image.size[1]])
# Apply the BLUR filter repeatedly
for i in range(iterations):
shadow = shadow.filter(ImageFilter.BLUR)
_drop_shadows_cache[key] = shadow.copy()
# Paste the original image on top of the shadow
# if the shadow offset was < 0, push right
img_lft = border_size - min(offset[0], 0)
# if the shadow offset was < 0, push down
img_top = border_size - min(offset[1], 0)
shadow.paste(image, (img_lft, img_top))
return shadow
class ImageCacheManager(GObject.GObject):
"""Helper to cache image transformations.
Image transformations can be expensive and datagrid views will
ask for them a lot. This will help by:
* Caching the mru images so the pixbuf is ready to be used,
without having to load and transform it again
* Do the transformations on another thread so larger images
transformation will not disturb the main one.
"""
__gsignals__ = {
'image-loaded': (GObject.SignalFlags.RUN_LAST, None, ()),
}
_instance = None
MAX_CACHE_SIZE = 200
IMAGE_BORDER_SIZE = 6
IMAGE_SHADOW_SIZE = 6
IMAGE_SHADOW_OFFSET = 2
def __init__(self):
"""Initialize the image cache manager object."""
super(ImageCacheManager, self).__init__()
self._lock = threading.Lock()
self._cache = {}
self._placeholders = {}
self._mru = collections.deque([], self.MAX_CACHE_SIZE)
self._waiting = set()
# We are using a LifoQueue instead of a Queue to load the most recently
# used image. For example, when scrolling the treeview, you will want
# the visible rows to be loaded before the ones that were put in the
# queue during the process.
self._queue = Queue.LifoQueue()
self._task = threading.Thread(target=self._transform_task)
self._task.daemon = True
self._task.start()
###
# Public
###
@classmethod
def get_default(cls):
"""Get the singleton default cache manager.
:return: the cache manager
:rtype: :class:`ImageCacheManager`
"""
if cls._instance is None:
cls._instance = cls()
return cls._instance
def get_image(self, path, size=24, fill_image=True, draw_border=False,
draft=False, load_on_thread=False):
"""Render path into a pixbuf.
:param str path: the image path or `None` to use a fallback image
:param int size: the size to resize the image. It will be resized
to fit a square of (size, size)
:param bool fill_image: if we should fill the image with a transparent
background to make a smaller image be at least a square of
(size, size), with the real image at the center.
:param bool draw_border: if we should add a border on the image
:param bool draft: if we should load the image as a draft. This
trades a little quality for a much higher performance.
:param bool load_on_thread: if we should load the image on another
thread. This will make a placeholder be returned the first
time this method is called.
:returns: the resized pixbuf
:rtype: :class:`GdkPixbuf.Pixbuf`
"""
params = (path, size, fill_image, draw_border, draft)
with self._lock:
# We want this params to be the last element on the deque (meaning
# it will be the most recently used item). Since we will append it
# bellow, if it were already in the deque, make sure to remove it
if params in self._mru:
self._mru.remove(params)
# When self._mru reaches its maxlen, the least recently used
#element (the position 0 in case of an append) will be removed
self._mru.append(params)
pixbuf = self._cache.get(params, None)
# The pixbuf is on cache
if pixbuf is not None:
return pixbuf
# The pixbuf is not on cache, but we don't want to
# load it on a thread
if not load_on_thread:
pixbuf = self._transform_image(*params)
# If no pixbuf, let the fallback image be returned
if pixbuf:
self._cache_pixbuf(params, pixbuf)
return pixbuf
elif params not in self._waiting:
self._waiting.add(params)
self._queue.put(params)
# Size will always be rounded to the next value. After 48, the
# next is 256 and we don't want something that big here.
fallback_size = min(size, 48)
fallback = get_icon_for_file(path or '', fallback_size)
placeholder_key = (fallback, ) + tuple(params[1:])
placeholder = self._placeholders.get(placeholder_key, None)
if placeholder is None:
# If the image is damaged for some reason, use fallback for
# its mimetype. Maybe the image is not really an image
# (it could be a video, a plain text file, etc)
placeholder = self._transform_image(
fallback, fallback_size, *params[2:])
self._placeholders[placeholder_key] = placeholder
# Make the placeholder the initial value for the image. If the
# loading fails, it will be used as the pixbuf for the image.
self._cache[params] = placeholder
return placeholder
###
# Private
###
def _cache_pixbuf(self, params, pixbuf):
"""Cache the pixbuf.
Cache the pixbuf generated by the given params.
This will also free any item any item that is not needed
anymore (the least recently used items after the
cache > :attr:`.MAX_CACHE_SIZE`) from the cache.
:param tuple params: the params used to do the image
transformation. Will be used as the key for the cache dict
:param pixbuf: the pixbuf to be cached.
:type pixbuf: :class:`GdkPixbuf.Pixbuf`
"""
self._cache[params] = pixbuf
self._waiting.discard(params)
# Free anything that is not needed anymore from the memory
for params in set(self._cache) - set(self._mru):
del self._cache[params]
def _transform_task(self):
"""Task responsible for doing image transformations.
This will run on another thread, checking the queue for any
new images, transforming and caching them after.
After loading any image here, 'image-loaded' signal
will be emitted.
"""
while True:
params = self._queue.get()
# It probably isn't needed anymore
if params not in self._mru:
continue
pixbuf = self._transform_image(*params)
if pixbuf is None:
continue
with self._lock:
self._cache_pixbuf(params, pixbuf)
GObject.idle_add(self.emit, 'image-loaded')
def _transform_image(self, path, size, fill_image, draw_border, draft):
"""Render path into a pixbuf.
:param str path: the image path or `None` to use a fallback image
:param int size: the size to resize the image. It will be resized
to fit a square of (size, size)
:param bool fill_image: if we should fill the image with a transparent
background to make a smaller image be at least a square of
(size, size), with the real image at the center.
:param bool draw_border: if we should add a border on the image
:param bool draft: if we should load the image as a draft. This
trades a little quality for a much higher performance.
:returns: the resized pixbuf
:rtype: :class:`GdkPixbuf.Pixbuf`
"""
path = path or ''
image = self._open_image(path, size, draft)
if image is None:
return None
if draw_border:
image = add_border(image, border_size=self.IMAGE_BORDER_SIZE)
image = add_drop_shadow(
image, border_size=self.IMAGE_SHADOW_SIZE,
offset=(self.IMAGE_SHADOW_OFFSET, self.IMAGE_SHADOW_OFFSET))
size += self.IMAGE_BORDER_SIZE * 2
size += self.IMAGE_SHADOW_SIZE * 2
size += self.IMAGE_SHADOW_OFFSET
else:
# FIXME: There's a bug on PIL where image.thumbnail modifications
# will be lost for some images when saving it the way we do on
# image2pixbuf (even image.copy().size != image.size when it was
# resized). Adding a border of size 0 will make it at least be
# pasted to a new image (which didn't have its thumbnail method
# called), working around this issue.
image = add_border(image, 0)
pixbuf = image2pixbuf(image)
width = pixbuf.get_width()
height = pixbuf.get_height()
if not fill_image:
return pixbuf
# Make sure the image is on the center of the image_max_size
square_pic = GdkPixbuf.Pixbuf.new(
GdkPixbuf.Colorspace.RGB, True, pixbuf.get_bits_per_sample(),
size, size)
# Fill with transparent white
square_pic.fill(0xffffff00)
dest_x = (size - width) / 2
dest_y = (size - height) / 2
pixbuf.copy_area(0, 0, width, height, square_pic, dest_x, dest_y)
return square_pic
def _open_image(self, path, size, draft):
"""Open the image on the given path.
:param str path: the image path
:param int size: the size to resize the image. It will be resized
to fit a square of (size, size)
:param bool draft: if we should load the image as a draft. This
trades a little quality for a much higher performance.
:returns: the opened image
:rtype: :class:`PIL.Image`
"""
# When trying to open the brokensuit images
# (https://code.google.com/p/javapng/wiki/BrokenSuite), PIL failed to
# open 27 of them, while Pixbuf failed to open 32. But trying PIL first
# and Pixbuf if it failed reduced that number to 20.
# In general, most of the images (specially if they are not broken,
# which is something more uncommon) will be opened directly by PIL.
try:
image = Image.open(path)
if draft:
image.draft('P', (size, size))
image.load()
except (IOError, SyntaxError, OverflowError, struct.error) as e:
try:
pixbuf = GdkPixbuf.Pixbuf.new_from_file(path)
except GLib.GError:
return None
else:
image = Image.fromstring(
"RGB", (pixbuf.get_width(), pixbuf.get_height()),
pixbuf.get_pixels())
image.thumbnail((size, size), Image.BICUBIC)
return image
| {
"content_hash": "bb85228535510422120281b2c71457ba",
"timestamp": "",
"source": "github",
"line_count": 455,
"max_line_length": 79,
"avg_line_length": 36.23516483516484,
"alnum_prop": 0.6077515618365985,
"repo_name": "jcollado/datagrid-gtk3",
"id": "4d55bff59bbf05d8d1a2c0f9f466a08d5eb2d278",
"size": "16487",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "datagrid_gtk3/utils/imageutils.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "2312"
},
{
"name": "Python",
"bytes": "213841"
}
],
"symlink_target": ""
} |
import os
# django imports
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
# settings for django-tinymce
try:
import tinymce.settings
DEFAULT_URL_TINYMCE = tinymce.settings.JS_BASE_URL + '/'
DEFAULT_PATH_TINYMCE = tinymce.settings.JS_ROOT + '/'
except ImportError:
import posixpath
DEFAULT_URL_TINYMCE = getattr(settings, 'ADMIN_MEDIA_PREFIX',
posixpath.join(settings.STATIC_URL, 'admin/')) + "tinymce/jscripts/tiny_mce/"
DEFAULT_PATH_TINYMCE = os.path.join(settings.MEDIA_ROOT, 'admin/tinymce/jscripts/tiny_mce/')
# Set to True in order to see the FileObject when Browsing.
DEBUG = getattr(settings, "FILEBROWSER_DEBUG", False)
# Main Media Settings
MEDIA_ROOT = getattr(settings, "FILEBROWSER_MEDIA_ROOT", settings.MEDIA_ROOT)
MEDIA_URL = getattr(settings, "FILEBROWSER_MEDIA_URL", settings.MEDIA_URL)
# Main FileBrowser Directory. This has to be a directory within MEDIA_ROOT.
# Leave empty in order to browse all files under MEDIA_ROOT.
# DO NOT USE A SLASH AT THE BEGINNING, DO NOT FORGET THE TRAILING SLASH AT THE END.
DIRECTORY = getattr(settings, "FILEBROWSER_DIRECTORY", 'uploads/')
# The URL/PATH to your filebrowser media-files.
URL_FILEBROWSER_MEDIA = getattr(settings, "FILEBROWSER_URL_FILEBROWSER_MEDIA", os.path.join(settings.STATIC_URL, 'filebrowser/'))
PATH_FILEBROWSER_MEDIA = getattr(settings, "FILEBROWSER_PATH_FILEBROWSER_MEDIA", os.path.join(settings.STATIC_ROOT, 'filebrowser/'))
# The URL/PATH to your TinyMCE Installation.
URL_TINYMCE = getattr(settings, "FILEBROWSER_URL_TINYMCE", DEFAULT_URL_TINYMCE)
PATH_TINYMCE = getattr(settings, "FILEBROWSER_PATH_TINYMCE", DEFAULT_PATH_TINYMCE)
# Allowed Extensions for File Upload. Lower case is important.
# Please be aware that there are Icons for the default extension settings.
# Therefore, if you add a category (e.g. "Misc"), you won't get an icon.
EXTENSIONS = getattr(settings, "FILEBROWSER_EXTENSIONS", {
'Folder': [''],
'Image': ['.jpg', '.jpeg', '.gif', '.png', '.tif', '.tiff'],
'Video': ['.mov', '.wmv', '.mpeg', '.mpg', '.avi', '.rm'],
'Document': ['.pdf', '.doc', '.rtf', '.txt', '.xls', '.csv'],
'Audio': ['.mp3', '.mp4', '.wav', '.aiff', '.midi', '.m4p'],
'Code': ['.html', '.py', '.js', '.css']
})
# Define different formats for allowed selections.
# This has to be a subset of EXTENSIONS.
SELECT_FORMATS = getattr(settings, "FILEBROWSER_SELECT_FORMATS", {
'File': ['Folder', 'Document', ],
'Image': ['Image'],
'Media': ['Video', 'Sound'],
'Document': ['Document'],
# for TinyMCE we can also define lower-case items
'image': ['Image'],
'file': ['Folder', 'Image', 'Document', ],
'media': ['Video', 'Sound'],
})
# Directory to Save Image Versions (and Thumbnails). Relative to MEDIA_ROOT.
# If no directory is given, versions are stored within the Image directory.
# VERSION URL: VERSIONS_BASEDIR/original_path/originalfilename_versionsuffix.extension
VERSIONS_BASEDIR = getattr(settings, 'FILEBROWSER_VERSIONS_BASEDIR', '')
# Versions Format. Available Attributes: verbose_name, width, height, opts
VERSIONS = getattr(settings, "FILEBROWSER_VERSIONS", {
'fb_thumb': {'verbose_name': 'Admin Thumbnail', 'width': 60, 'height': 60, 'opts': 'crop upscale'},
'thumbnail': {'verbose_name': 'Thumbnail (140px)', 'width': 140, 'height': '', 'opts': ''},
'small': {'verbose_name': 'Small (300px)', 'width': 300, 'height': '', 'opts': ''},
'product_page': {'verbose_name': 'Medium (500px * 250px)', 'width': 500, 'height': 250, 'opts': 'upscale'},
'medium': {'verbose_name': 'Medium (460px)', 'width': 460, 'height': '', 'opts': ''},
'big': {'verbose_name': 'Big (620px)', 'width': 620, 'height': '', 'opts': ''},
'big_banner': {'verbose_name': 'Big Banner (790px * 298px)', 'width': 790, 'height': 298, 'opts': 'upscale'},
'cropped': {'verbose_name': 'Cropped (60x60px)', 'width': 60, 'height': 60, 'opts': 'crop'},
'croppedthumbnail': {'verbose_name': 'Cropped Thumbnail (140x140px)', 'width': 140, 'height': 140, 'opts': 'crop'},
})
# Versions available within the Admin-Interface.
ADMIN_VERSIONS = getattr(settings, 'FILEBROWSER_ADMIN_VERSIONS', ['thumbnail', 'small', 'medium', 'big'])
# Which Version should be used as Admin-thumbnail.
ADMIN_THUMBNAIL = getattr(settings, 'FILEBROWSER_ADMIN_THUMBNAIL', 'fb_thumb')
# Preview Version
PREVIEW_VERSION = getattr(settings, 'FILEBROWSER_PREVIEW_VERSION', 'small')
# EXTRA SETTINGS
# True to save the URL including MEDIA_URL to your model fields
# or False (default) to save path relative to MEDIA_URL.
# Note: Full URL does not necessarily means absolute URL.
SAVE_FULL_URL = getattr(settings, "FILEBROWSER_SAVE_FULL_URL", True)
# If set to True, the FileBrowser will not try to import a mis-installed PIL.
STRICT_PIL = getattr(settings, 'FILEBROWSER_STRICT_PIL', False)
# PIL's Error "Suspension not allowed here" work around:
# s. http://mail.python.org/pipermail/image-sig/1999-August/000816.html
IMAGE_MAXBLOCK = getattr(settings, 'FILEBROWSER_IMAGE_MAXBLOCK', 1024 * 1024)
# Exclude files matching any of the following regular expressions
# Default is to exclude 'thumbnail' style naming of image-thumbnails.
EXTENSION_LIST = []
for exts in EXTENSIONS.values():
EXTENSION_LIST += exts
EXCLUDE = getattr(settings, 'FILEBROWSER_EXCLUDE', (r'_(%(exts)s)_.*_q\d{1,3}\.(%(exts)s)' % {'exts': ('|'.join(EXTENSION_LIST))},))
# Max. Upload Size in Bytes.
MAX_UPLOAD_SIZE = getattr(settings, "FILEBROWSER_MAX_UPLOAD_SIZE", 10485760)
# Convert Filename (replace spaces and convert to lowercase)
CONVERT_FILENAME = getattr(settings, "FILEBROWSER_CONVERT_FILENAME", True)
# Max. Entries per Page
# Loading a Sever-Directory with lots of files might take a while
# Use this setting to limit the items shown
LIST_PER_PAGE = getattr(settings, "FILEBROWSER_LIST_PER_PAGE", 50)
# Default Sorting
# Options: date, filesize, filename_lower, filetype_checked
DEFAULT_SORTING_BY = getattr(settings, "FILEBROWSER_DEFAULT_SORTING_BY", "date")
# Sorting Order: asc, desc
DEFAULT_SORTING_ORDER = getattr(settings, "FILEBROWSER_DEFAULT_SORTING_ORDER", "desc")
# regex to clean dir names before creation (no use!)
# SECURITY re for test name new dirs or file name
# FILE_AND_DIRS_NAME_REGEXP
FOLDER_REGEX = getattr(settings, "FILEBROWSER_FOLDER_REGEX", r'^[ \w-][ \w.-]*$')
# EXTRA TRANSLATION STRINGS
# The following strings are not availabe within views or templates
_('Folder')
_('Image')
_('Video')
_('Document')
_('Audio')
_('Code')
| {
"content_hash": "900c6784856eca72c007ded5f0b1c2b8",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 132,
"avg_line_length": 49.65151515151515,
"alnum_prop": 0.6940799511748551,
"repo_name": "buremba/django-filebrowser-admintools",
"id": "ef4175e42f6882a9280f037ec68b3362da823b3d",
"size": "6581",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "filebrowser/settings.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ActionScript",
"bytes": "341030"
},
{
"name": "CSS",
"bytes": "9210"
},
{
"name": "JavaScript",
"bytes": "92292"
},
{
"name": "PHP",
"bytes": "7767"
},
{
"name": "Python",
"bytes": "71543"
}
],
"symlink_target": ""
} |
import sys
try:
Set = set
except:
import sets
Set = sets.Set
try:
from cStringIO import StringIO
except:
from StringIO import StringIO
import codecs, re, weakref, os, time
try:
import threading
import thread
except ImportError:
import dummy_threading as threading
import dummy_thread as thread
if sys.platform.startswith('win') or sys.platform.startswith('java'):
time_func = time.clock
else:
time_func = time.time
def verify_directory(dir):
"""create and/or verify a filesystem directory."""
tries = 0
while not os.path.exists(dir):
try:
tries += 1
os.makedirs(dir, 0775)
except:
if tries > 5:
raise
def to_list(x, default=None):
if x is None:
return default
if not isinstance(x, (list, tuple)):
return [x]
else:
return x
class SetLikeDict(dict):
"""a dictionary that has some setlike methods on it"""
def union(self, other):
"""produce a 'union' of this dict and another (at the key level).
values in the second dict take precedence over that of the first"""
x = SetLikeDict(**self)
x.update(other)
return x
class FastEncodingBuffer(object):
"""a very rudimentary buffer that is faster than StringIO, but doesnt crash on unicode data like cStringIO."""
def __init__(self, encoding=None, errors='strict', unicode=False):
self.data = []
self.encoding = encoding
if unicode:
self.delim = u''
else:
self.delim = ''
self.unicode = unicode
self.errors = errors
self.write = self.data.append
def getvalue(self):
if self.encoding:
return self.delim.join(self.data).encode(self.encoding, self.errors)
else:
return self.delim.join(self.data)
class LRUCache(dict):
"""A dictionary-like object that stores a limited number of items, discarding
lesser used items periodically.
this is a rewrite of LRUCache from Myghty to use a periodic timestamp-based
paradigm so that synchronization is not really needed. the size management
is inexact.
"""
class _Item(object):
def __init__(self, key, value):
self.key = key
self.value = value
self.timestamp = time_func()
def __repr__(self):
return repr(self.value)
def __init__(self, capacity, threshold=.5):
self.capacity = capacity
self.threshold = threshold
def __getitem__(self, key):
item = dict.__getitem__(self, key)
item.timestamp = time_func()
return item.value
def values(self):
return [i.value for i in dict.values(self)]
def setdefault(self, key, value):
if key in self:
return self[key]
else:
self[key] = value
return value
def __setitem__(self, key, value):
item = dict.get(self, key)
if item is None:
item = self._Item(key, value)
dict.__setitem__(self, key, item)
else:
item.value = value
self._manage_size()
def _manage_size(self):
while len(self) > self.capacity + self.capacity * self.threshold:
bytime = dict.values(self)
bytime.sort(lambda a, b: cmp(b.timestamp, a.timestamp))
for item in bytime[self.capacity:]:
try:
del self[item.key]
except KeyError:
# if we couldnt find a key, most likely some other thread broke in
# on us. loop around and try again
break
# Regexp to match python magic encoding line
_PYTHON_MAGIC_COMMENT_re = re.compile(
r'[ \t\f]* \# .* coding[=:][ \t]*([-\w.]+)',
re.VERBOSE)
def parse_encoding(fp):
"""Deduce the encoding of a source file from magic comment.
It does this in the same way as the `Python interpreter`__
.. __: http://docs.python.org/ref/encodings.html
The ``fp`` argument should be a seekable file object.
"""
pos = fp.tell()
fp.seek(0)
try:
line1 = fp.readline()
has_bom = line1.startswith(codecs.BOM_UTF8)
if has_bom:
line1 = line1[len(codecs.BOM_UTF8):]
m = _PYTHON_MAGIC_COMMENT_re.match(line1)
if not m:
try:
import parser
parser.suite(line1)
except (ImportError, SyntaxError):
# Either it's a real syntax error, in which case the source
# is not valid python source, or line2 is a continuation of
# line1, in which case we don't want to scan line2 for a magic
# comment.
pass
else:
line2 = fp.readline()
m = _PYTHON_MAGIC_COMMENT_re.match(line2)
if has_bom:
if m:
raise SyntaxError, \
"python refuses to compile code with both a UTF8" \
" byte-order-mark and a magic encoding comment"
return 'utf_8'
elif m:
return m.group(1)
else:
return None
finally:
fp.seek(pos)
def sorted_dict_repr(d):
"""repr() a dictionary with the keys in order.
Used by the lexer unit test to compare parse trees based on strings.
"""
keys = d.keys()
keys.sort()
return "{" + ", ".join(["%r: %r" % (k, d[k]) for k in keys]) + "}"
def restore__ast(_ast):
"""Attempt to restore the required classes to the _ast module if it
appears to be missing them
"""
if hasattr(_ast, 'AST'):
return
_ast.PyCF_ONLY_AST = 2 << 9
m = compile("""\
def foo(): pass
class Bar(object): pass
if False: pass
baz = 'mako'
1 + 2 - 3 * 4 / 5
6 // 7 % 8 << 9 >> 10
11 & 12 ^ 13 | 14
15 and 16 or 17
-baz + (not +18) - ~17
baz and 'foo' or 'bar'
(mako is baz == baz) is not baz != mako
mako > baz < mako >= baz <= mako
mako in baz not in mako""", '<unknown>', 'exec', _ast.PyCF_ONLY_AST)
_ast.Module = type(m)
for cls in _ast.Module.__mro__:
if cls.__name__ == 'mod':
_ast.mod = cls
elif cls.__name__ == 'AST':
_ast.AST = cls
_ast.FunctionDef = type(m.body[0])
_ast.ClassDef = type(m.body[1])
_ast.If = type(m.body[2])
_ast.Name = type(m.body[3].targets[0])
_ast.Store = type(m.body[3].targets[0].ctx)
_ast.Str = type(m.body[3].value)
_ast.Sub = type(m.body[4].value.op)
_ast.Add = type(m.body[4].value.left.op)
_ast.Div = type(m.body[4].value.right.op)
_ast.Mult = type(m.body[4].value.right.left.op)
_ast.RShift = type(m.body[5].value.op)
_ast.LShift = type(m.body[5].value.left.op)
_ast.Mod = type(m.body[5].value.left.left.op)
_ast.FloorDiv = type(m.body[5].value.left.left.left.op)
_ast.BitOr = type(m.body[6].value.op)
_ast.BitXor = type(m.body[6].value.left.op)
_ast.BitAnd = type(m.body[6].value.left.left.op)
_ast.Or = type(m.body[7].value.op)
_ast.And = type(m.body[7].value.values[0].op)
_ast.Invert = type(m.body[8].value.right.op)
_ast.Not = type(m.body[8].value.left.right.op)
_ast.UAdd = type(m.body[8].value.left.right.operand.op)
_ast.USub = type(m.body[8].value.left.left.op)
_ast.Or = type(m.body[9].value.op)
_ast.And = type(m.body[9].value.values[0].op)
_ast.IsNot = type(m.body[10].value.ops[0])
_ast.NotEq = type(m.body[10].value.ops[1])
_ast.Is = type(m.body[10].value.left.ops[0])
_ast.Eq = type(m.body[10].value.left.ops[1])
_ast.Gt = type(m.body[11].value.ops[0])
_ast.Lt = type(m.body[11].value.ops[1])
_ast.GtE = type(m.body[11].value.ops[2])
_ast.LtE = type(m.body[11].value.ops[3])
_ast.In = type(m.body[12].value.ops[0])
_ast.NotIn = type(m.body[12].value.ops[1])
| {
"content_hash": "fff6e1995c178e9d7e55994d03f04cab",
"timestamp": "",
"source": "github",
"line_count": 268,
"max_line_length": 114,
"avg_line_length": 29.87313432835821,
"alnum_prop": 0.5615788158880839,
"repo_name": "bdoms/mako",
"id": "1f9f3d42637d5106460079aa76d6ec8e97a84023",
"size": "8225",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "util.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "195587"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('method', '0109_method_container'),
]
operations = [
migrations.RemoveField(
model_name='dockerimage',
name='groups_allowed',
),
migrations.RemoveField(
model_name='dockerimage',
name='user',
),
migrations.RemoveField(
model_name='dockerimage',
name='users_allowed',
),
migrations.RemoveField(
model_name='method',
name='docker_image',
),
migrations.DeleteModel(
name='DockerImage',
),
]
| {
"content_hash": "7c58ccfd02fa79b62f4396731782d924",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 44,
"avg_line_length": 22.96875,
"alnum_prop": 0.5306122448979592,
"repo_name": "cfe-lab/Kive",
"id": "2b3df14b924834322dd66032f98ad9a9d948699a",
"size": "809",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kive/method/migrations/0110_drop_dockerimage.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "26511"
},
{
"name": "HTML",
"bytes": "81400"
},
{
"name": "JavaScript",
"bytes": "121951"
},
{
"name": "Jinja",
"bytes": "15965"
},
{
"name": "Makefile",
"bytes": "1957"
},
{
"name": "Python",
"bytes": "1453355"
},
{
"name": "Sass",
"bytes": "15929"
},
{
"name": "Shell",
"bytes": "37562"
},
{
"name": "Singularity",
"bytes": "2941"
},
{
"name": "TypeScript",
"bytes": "356365"
}
],
"symlink_target": ""
} |
from datetime import date, timedelta
from random import uniform
from numpy import ndarray
def _generator(x):
return uniform(0, 1)
class gdata(object):
def __init__(self, data):
self.data = data
def __iter__(self):
return (v for v in self.data)
def datepopulate(size = 10, start=None, delta=1):
dt = start or date.today() - timedelta(days=delta*(size-1))
td = timedelta(days=delta)
return [dt+s*td for s in range(size)]
def populate(size=100, cols=1, generator=None):
generator = generator or _generator
data = ndarray([size,cols])
for c in range(0, cols):
data[:, c] = [generator(i) for i in range(0, size)]
return data
def polygen(*coefficients):
'''Polynomial generating function'''
if not coefficients:
return lambda i: 0
else:
c0 = coefficients[0]
coefficients = coefficients[1:]
def _(i):
v = c0
for c in coefficients:
v += c*i
i *= i
return v
return _
| {
"content_hash": "7dc8bb048960452398f3a1b5832fca3a",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 63,
"avg_line_length": 22.571428571428573,
"alnum_prop": 0.5524412296564195,
"repo_name": "quantmind/dynts",
"id": "d4c92148b0ac4e28242be712fafb2a11f6a3d5a4",
"size": "1106",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dynts/utils/populate.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "202792"
},
{
"name": "Visual Basic",
"bytes": "11474"
}
],
"symlink_target": ""
} |
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib
# 格式化工具
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
from_addr = input('From: ')
password = input('Password: ')
to_addr = input('To: ')
smtp_server = input('SMTP server: ')
# 邮件主题及内容
msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')
msg['from'] = _format_addr('Python发送邮件 <%s>' % from_addr)
msg['to'] = _format_addr('管理员 <%s>' % to_addr)
msg['subject'] = '这是来自SMTP的问候...'
# content='''
# 你好,
# 这是来自SMTP的问候。
# '''
# txt=email.mime.text.MIMEText(content)
# msg.attach(txt)
smtp=smtplib
smtp=smtplib.SMTP()
smtp.connect(smtp_server,'25') #默认端口为25
smtp.login(from_addr, password)
smtp.sendmail(from_addr, to_addr, str(msg))
smtp.quit()
| {
"content_hash": "1f8ddcbe60593ea24daa233517620cdd",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 61,
"avg_line_length": 25.4,
"alnum_prop": 0.6704161979752531,
"repo_name": "KrisCheng/HackerPractice",
"id": "f029f47ce29c61f3993bfd449051315d78918f3c",
"size": "1041",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Python/mail/SMTP.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "305"
},
{
"name": "HTML",
"bytes": "57696"
},
{
"name": "JavaScript",
"bytes": "83921"
},
{
"name": "Python",
"bytes": "18233"
}
],
"symlink_target": ""
} |
from google.cloud.billing import budgets_v1beta1
def sample_create_budget():
# Create a client
client = budgets_v1beta1.BudgetServiceClient()
# Initialize request argument(s)
request = budgets_v1beta1.CreateBudgetRequest(
parent="parent_value",
)
# Make the request
response = client.create_budget(request=request)
# Handle the response
print(response)
# [END billingbudgets_v1beta1_generated_BudgetService_CreateBudget_sync]
| {
"content_hash": "c7704b72433adf89196fc1a83169e465",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 72,
"avg_line_length": 25.05263157894737,
"alnum_prop": 0.7226890756302521,
"repo_name": "googleapis/python-billingbudgets",
"id": "aa3fcd233178871d1da42a33fcc001d8406a9aab",
"size": "1879",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "samples/generated_samples/billingbudgets_v1beta1_generated_budget_service_create_budget_sync.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2050"
},
{
"name": "Python",
"bytes": "520005"
},
{
"name": "Shell",
"bytes": "30684"
}
],
"symlink_target": ""
} |
from geopy.distance import vincenty
def get_hot_points(data, threshold, distance):
"""get hot point"""
hot_points = []
for each in data:
count = 0
p1 = (each[-2], each[-1]) # lat, lng
for item in data:
p2 = (item[-2], item[-1])
p_dis = vincenty(p1, p2).meters
if p_dis < distance:
count += 1
if count > threshold:
tmp = each.copy()
tmp.append(count)
hot_points.append(tmp)
break
return hot_points
| {
"content_hash": "bcb026d6eb3891baf08aa3e493c36054",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 46,
"avg_line_length": 30.842105263157894,
"alnum_prop": 0.46075085324232085,
"repo_name": "TaiwanStat/real.taiwanstat.com",
"id": "076a5c27f3dd1ac3be48e6b847ef0eebc4059475",
"size": "586",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "river/lib/geo.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "187"
},
{
"name": "CSS",
"bytes": "111100"
},
{
"name": "HTML",
"bytes": "521597"
},
{
"name": "Handlebars",
"bytes": "150100"
},
{
"name": "JavaScript",
"bytes": "3646635"
},
{
"name": "Pug",
"bytes": "3179"
},
{
"name": "Python",
"bytes": "133753"
},
{
"name": "SCSS",
"bytes": "3064"
},
{
"name": "Shell",
"bytes": "1318"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.