commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 0
2.94k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
444
| message
stringlengths 16
3.45k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 5
43.2k
| prompt
stringlengths 17
4.58k
| response
stringlengths 1
4.43k
| prompt_tagged
stringlengths 58
4.62k
| response_tagged
stringlengths 1
4.43k
| text
stringlengths 132
7.29k
| text_tagged
stringlengths 173
7.33k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1ea2ca47070ab58a8df9e308d2bcb4bd4debe088
|
tests/test_script.py
|
tests/test_script.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
""" A script to test CKAN Utils functionality """
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
from sys import exit, stderr
from scripttest import TestFileEnvironment
def main():
try:
env = TestFileEnvironment('.scripttest')
result = env.run('ckanutils --help')
print('%s' % result.stdout)
except Exception as err:
stderr.write('ERROR: %s\n' % str(err))
exit(0)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
""" A script to test CKAN Utils functionality """
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
from sys import exit, stderr
from os import path as p
from scripttest import TestFileEnvironment
from ckanutils import __version__ as version
parent_dir = p.abspath(p.dirname(p.dirname(__file__)))
script = p.join(parent_dir, 'bin', 'ckanny')
def main(verbose=False):
env = TestFileEnvironment('.scripttest')
test_num = 1
# Test main usage
result = env.run('%s --help' % script)
if verbose:
print(result.stdout)
assert result.stdout.split('\n')[0] == 'usage: ckanny <command> [<args>]'
print('\nScripttest: #%i ... ok' % test_num)
test_num += 1
# Test dsdelete usage
result = env.run('%s dsdelete --help' % script)
if verbose:
print(result.stdout)
assert ' '.join(result.stdout.split(' ')[:3]) == 'usage: ckanny [-h]'
print('Scripttest: #%i ... ok' % test_num)
test_num += 1
# Test dsupdate usage
result = env.run('%s dsupdate --help' % script)
if verbose:
print(result.stdout)
assert ' '.join(result.stdout.split(' ')[:3]) == 'usage: ckanny [-h]'
print('Scripttest: #%i ... ok' % test_num)
test_num += 1
# Test version
result = env.run('%s ver' % script)
if verbose:
print(result.stdout)
assert result.stdout.split('\n')[0] == 'v%s' % version
print('Scripttest: #%i ... ok' % test_num)
print('-----------------------------')
print('Ran %i tests\n\nOK' % test_num)
exit(0)
if __name__ == '__main__':
main()
|
Fix and update script test
|
Fix and update script test
|
Python
|
mit
|
luiscape/ckanutils,reubano/ckanutils,reubano/ckanny,reubano/ckanutils,reubano/ckanny,luiscape/ckanutils
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
""" A script to test CKAN Utils functionality """
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
from sys import exit, stderr
from scripttest import TestFileEnvironment
def main():
try:
env = TestFileEnvironment('.scripttest')
result = env.run('ckanutils --help')
print('%s' % result.stdout)
except Exception as err:
stderr.write('ERROR: %s\n' % str(err))
exit(0)
if __name__ == '__main__':
main()
Fix and update script test
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
""" A script to test CKAN Utils functionality """
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
from sys import exit, stderr
from os import path as p
from scripttest import TestFileEnvironment
from ckanutils import __version__ as version
parent_dir = p.abspath(p.dirname(p.dirname(__file__)))
script = p.join(parent_dir, 'bin', 'ckanny')
def main(verbose=False):
env = TestFileEnvironment('.scripttest')
test_num = 1
# Test main usage
result = env.run('%s --help' % script)
if verbose:
print(result.stdout)
assert result.stdout.split('\n')[0] == 'usage: ckanny <command> [<args>]'
print('\nScripttest: #%i ... ok' % test_num)
test_num += 1
# Test dsdelete usage
result = env.run('%s dsdelete --help' % script)
if verbose:
print(result.stdout)
assert ' '.join(result.stdout.split(' ')[:3]) == 'usage: ckanny [-h]'
print('Scripttest: #%i ... ok' % test_num)
test_num += 1
# Test dsupdate usage
result = env.run('%s dsupdate --help' % script)
if verbose:
print(result.stdout)
assert ' '.join(result.stdout.split(' ')[:3]) == 'usage: ckanny [-h]'
print('Scripttest: #%i ... ok' % test_num)
test_num += 1
# Test version
result = env.run('%s ver' % script)
if verbose:
print(result.stdout)
assert result.stdout.split('\n')[0] == 'v%s' % version
print('Scripttest: #%i ... ok' % test_num)
print('-----------------------------')
print('Ran %i tests\n\nOK' % test_num)
exit(0)
if __name__ == '__main__':
main()
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
""" A script to test CKAN Utils functionality """
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
from sys import exit, stderr
from scripttest import TestFileEnvironment
def main():
try:
env = TestFileEnvironment('.scripttest')
result = env.run('ckanutils --help')
print('%s' % result.stdout)
except Exception as err:
stderr.write('ERROR: %s\n' % str(err))
exit(0)
if __name__ == '__main__':
main()
<commit_msg>Fix and update script test<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
""" A script to test CKAN Utils functionality """
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
from sys import exit, stderr
from os import path as p
from scripttest import TestFileEnvironment
from ckanutils import __version__ as version
parent_dir = p.abspath(p.dirname(p.dirname(__file__)))
script = p.join(parent_dir, 'bin', 'ckanny')
def main(verbose=False):
env = TestFileEnvironment('.scripttest')
test_num = 1
# Test main usage
result = env.run('%s --help' % script)
if verbose:
print(result.stdout)
assert result.stdout.split('\n')[0] == 'usage: ckanny <command> [<args>]'
print('\nScripttest: #%i ... ok' % test_num)
test_num += 1
# Test dsdelete usage
result = env.run('%s dsdelete --help' % script)
if verbose:
print(result.stdout)
assert ' '.join(result.stdout.split(' ')[:3]) == 'usage: ckanny [-h]'
print('Scripttest: #%i ... ok' % test_num)
test_num += 1
# Test dsupdate usage
result = env.run('%s dsupdate --help' % script)
if verbose:
print(result.stdout)
assert ' '.join(result.stdout.split(' ')[:3]) == 'usage: ckanny [-h]'
print('Scripttest: #%i ... ok' % test_num)
test_num += 1
# Test version
result = env.run('%s ver' % script)
if verbose:
print(result.stdout)
assert result.stdout.split('\n')[0] == 'v%s' % version
print('Scripttest: #%i ... ok' % test_num)
print('-----------------------------')
print('Ran %i tests\n\nOK' % test_num)
exit(0)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
""" A script to test CKAN Utils functionality """
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
from sys import exit, stderr
from scripttest import TestFileEnvironment
def main():
try:
env = TestFileEnvironment('.scripttest')
result = env.run('ckanutils --help')
print('%s' % result.stdout)
except Exception as err:
stderr.write('ERROR: %s\n' % str(err))
exit(0)
if __name__ == '__main__':
main()
Fix and update script test#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
""" A script to test CKAN Utils functionality """
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
from sys import exit, stderr
from os import path as p
from scripttest import TestFileEnvironment
from ckanutils import __version__ as version
parent_dir = p.abspath(p.dirname(p.dirname(__file__)))
script = p.join(parent_dir, 'bin', 'ckanny')
def main(verbose=False):
env = TestFileEnvironment('.scripttest')
test_num = 1
# Test main usage
result = env.run('%s --help' % script)
if verbose:
print(result.stdout)
assert result.stdout.split('\n')[0] == 'usage: ckanny <command> [<args>]'
print('\nScripttest: #%i ... ok' % test_num)
test_num += 1
# Test dsdelete usage
result = env.run('%s dsdelete --help' % script)
if verbose:
print(result.stdout)
assert ' '.join(result.stdout.split(' ')[:3]) == 'usage: ckanny [-h]'
print('Scripttest: #%i ... ok' % test_num)
test_num += 1
# Test dsupdate usage
result = env.run('%s dsupdate --help' % script)
if verbose:
print(result.stdout)
assert ' '.join(result.stdout.split(' ')[:3]) == 'usage: ckanny [-h]'
print('Scripttest: #%i ... ok' % test_num)
test_num += 1
# Test version
result = env.run('%s ver' % script)
if verbose:
print(result.stdout)
assert result.stdout.split('\n')[0] == 'v%s' % version
print('Scripttest: #%i ... ok' % test_num)
print('-----------------------------')
print('Ran %i tests\n\nOK' % test_num)
exit(0)
if __name__ == '__main__':
main()
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
""" A script to test CKAN Utils functionality """
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
from sys import exit, stderr
from scripttest import TestFileEnvironment
def main():
try:
env = TestFileEnvironment('.scripttest')
result = env.run('ckanutils --help')
print('%s' % result.stdout)
except Exception as err:
stderr.write('ERROR: %s\n' % str(err))
exit(0)
if __name__ == '__main__':
main()
<commit_msg>Fix and update script test<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
""" A script to test CKAN Utils functionality """
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
from sys import exit, stderr
from os import path as p
from scripttest import TestFileEnvironment
from ckanutils import __version__ as version
parent_dir = p.abspath(p.dirname(p.dirname(__file__)))
script = p.join(parent_dir, 'bin', 'ckanny')
def main(verbose=False):
env = TestFileEnvironment('.scripttest')
test_num = 1
# Test main usage
result = env.run('%s --help' % script)
if verbose:
print(result.stdout)
assert result.stdout.split('\n')[0] == 'usage: ckanny <command> [<args>]'
print('\nScripttest: #%i ... ok' % test_num)
test_num += 1
# Test dsdelete usage
result = env.run('%s dsdelete --help' % script)
if verbose:
print(result.stdout)
assert ' '.join(result.stdout.split(' ')[:3]) == 'usage: ckanny [-h]'
print('Scripttest: #%i ... ok' % test_num)
test_num += 1
# Test dsupdate usage
result = env.run('%s dsupdate --help' % script)
if verbose:
print(result.stdout)
assert ' '.join(result.stdout.split(' ')[:3]) == 'usage: ckanny [-h]'
print('Scripttest: #%i ... ok' % test_num)
test_num += 1
# Test version
result = env.run('%s ver' % script)
if verbose:
print(result.stdout)
assert result.stdout.split('\n')[0] == 'v%s' % version
print('Scripttest: #%i ... ok' % test_num)
print('-----------------------------')
print('Ran %i tests\n\nOK' % test_num)
exit(0)
if __name__ == '__main__':
main()
|
2a893314a6f20092379298cfb53910c15154243c
|
tests/test_trivia.py
|
tests/test_trivia.py
|
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
def test_large_number(self):
self.assertFalse(
check_answer(
"33 1/3",
"128347192834719283561293847129384719238471234"
)
)
def test_parentheses_with_article_prefix(self):
self.assertTrue(
check_answer(
"the ISS (the International Space Station)",
"International Space Station"
)
)
self.assertTrue(
check_answer("Holland (The Netherlands)", "Netherlands")
)
def test_wrong_encoding(self):
self.assertTrue(check_answer("a résumé", "resume"))
self.assertTrue(check_answer("Tenochtitlán", "Tenochtitlan"))
if __name__ == "__main__":
unittest.main()
|
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
def test_correct_encoding(self):
self.assertTrue(
check_answer("Brontë Sisters (The Brontës)", "Brontes")
)
def test_incorrect_encoding(self):
self.assertTrue(check_answer("a résumé", "resume"))
self.assertTrue(check_answer("Tenochtitlán", "Tenochtitlan"))
def test_large_number(self):
self.assertFalse(
check_answer(
"33 1/3",
"128347192834719283561293847129384719238471234"
)
)
def test_parentheses_with_article_prefix(self):
self.assertTrue(
check_answer(
"the ISS (the International Space Station)",
"International Space Station"
)
)
self.assertTrue(
check_answer("Holland (The Netherlands)", "Netherlands")
)
if __name__ == "__main__":
unittest.main()
|
Test correct encoding for trivia answer
|
[Tests] Test correct encoding for trivia answer
Rename test_wrong_encoding to test_incorrect_encoding
|
Python
|
mit
|
Harmon758/Harmonbot,Harmon758/Harmonbot
|
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
def test_large_number(self):
self.assertFalse(
check_answer(
"33 1/3",
"128347192834719283561293847129384719238471234"
)
)
def test_parentheses_with_article_prefix(self):
self.assertTrue(
check_answer(
"the ISS (the International Space Station)",
"International Space Station"
)
)
self.assertTrue(
check_answer("Holland (The Netherlands)", "Netherlands")
)
def test_wrong_encoding(self):
self.assertTrue(check_answer("a résumé", "resume"))
self.assertTrue(check_answer("Tenochtitlán", "Tenochtitlan"))
if __name__ == "__main__":
unittest.main()
[Tests] Test correct encoding for trivia answer
Rename test_wrong_encoding to test_incorrect_encoding
|
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
def test_correct_encoding(self):
self.assertTrue(
check_answer("Brontë Sisters (The Brontës)", "Brontes")
)
def test_incorrect_encoding(self):
self.assertTrue(check_answer("a résumé", "resume"))
self.assertTrue(check_answer("Tenochtitlán", "Tenochtitlan"))
def test_large_number(self):
self.assertFalse(
check_answer(
"33 1/3",
"128347192834719283561293847129384719238471234"
)
)
def test_parentheses_with_article_prefix(self):
self.assertTrue(
check_answer(
"the ISS (the International Space Station)",
"International Space Station"
)
)
self.assertTrue(
check_answer("Holland (The Netherlands)", "Netherlands")
)
if __name__ == "__main__":
unittest.main()
|
<commit_before>
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
def test_large_number(self):
self.assertFalse(
check_answer(
"33 1/3",
"128347192834719283561293847129384719238471234"
)
)
def test_parentheses_with_article_prefix(self):
self.assertTrue(
check_answer(
"the ISS (the International Space Station)",
"International Space Station"
)
)
self.assertTrue(
check_answer("Holland (The Netherlands)", "Netherlands")
)
def test_wrong_encoding(self):
self.assertTrue(check_answer("a résumé", "resume"))
self.assertTrue(check_answer("Tenochtitlán", "Tenochtitlan"))
if __name__ == "__main__":
unittest.main()
<commit_msg>[Tests] Test correct encoding for trivia answer
Rename test_wrong_encoding to test_incorrect_encoding<commit_after>
|
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
def test_correct_encoding(self):
self.assertTrue(
check_answer("Brontë Sisters (The Brontës)", "Brontes")
)
def test_incorrect_encoding(self):
self.assertTrue(check_answer("a résumé", "resume"))
self.assertTrue(check_answer("Tenochtitlán", "Tenochtitlan"))
def test_large_number(self):
self.assertFalse(
check_answer(
"33 1/3",
"128347192834719283561293847129384719238471234"
)
)
def test_parentheses_with_article_prefix(self):
self.assertTrue(
check_answer(
"the ISS (the International Space Station)",
"International Space Station"
)
)
self.assertTrue(
check_answer("Holland (The Netherlands)", "Netherlands")
)
if __name__ == "__main__":
unittest.main()
|
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
def test_large_number(self):
self.assertFalse(
check_answer(
"33 1/3",
"128347192834719283561293847129384719238471234"
)
)
def test_parentheses_with_article_prefix(self):
self.assertTrue(
check_answer(
"the ISS (the International Space Station)",
"International Space Station"
)
)
self.assertTrue(
check_answer("Holland (The Netherlands)", "Netherlands")
)
def test_wrong_encoding(self):
self.assertTrue(check_answer("a résumé", "resume"))
self.assertTrue(check_answer("Tenochtitlán", "Tenochtitlan"))
if __name__ == "__main__":
unittest.main()
[Tests] Test correct encoding for trivia answer
Rename test_wrong_encoding to test_incorrect_encoding
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
def test_correct_encoding(self):
self.assertTrue(
check_answer("Brontë Sisters (The Brontës)", "Brontes")
)
def test_incorrect_encoding(self):
self.assertTrue(check_answer("a résumé", "resume"))
self.assertTrue(check_answer("Tenochtitlán", "Tenochtitlan"))
def test_large_number(self):
self.assertFalse(
check_answer(
"33 1/3",
"128347192834719283561293847129384719238471234"
)
)
def test_parentheses_with_article_prefix(self):
self.assertTrue(
check_answer(
"the ISS (the International Space Station)",
"International Space Station"
)
)
self.assertTrue(
check_answer("Holland (The Netherlands)", "Netherlands")
)
if __name__ == "__main__":
unittest.main()
|
<commit_before>
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
def test_large_number(self):
self.assertFalse(
check_answer(
"33 1/3",
"128347192834719283561293847129384719238471234"
)
)
def test_parentheses_with_article_prefix(self):
self.assertTrue(
check_answer(
"the ISS (the International Space Station)",
"International Space Station"
)
)
self.assertTrue(
check_answer("Holland (The Netherlands)", "Netherlands")
)
def test_wrong_encoding(self):
self.assertTrue(check_answer("a résumé", "resume"))
self.assertTrue(check_answer("Tenochtitlán", "Tenochtitlan"))
if __name__ == "__main__":
unittest.main()
<commit_msg>[Tests] Test correct encoding for trivia answer
Rename test_wrong_encoding to test_incorrect_encoding<commit_after>
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
def test_correct_encoding(self):
self.assertTrue(
check_answer("Brontë Sisters (The Brontës)", "Brontes")
)
def test_incorrect_encoding(self):
self.assertTrue(check_answer("a résumé", "resume"))
self.assertTrue(check_answer("Tenochtitlán", "Tenochtitlan"))
def test_large_number(self):
self.assertFalse(
check_answer(
"33 1/3",
"128347192834719283561293847129384719238471234"
)
)
def test_parentheses_with_article_prefix(self):
self.assertTrue(
check_answer(
"the ISS (the International Space Station)",
"International Space Station"
)
)
self.assertTrue(
check_answer("Holland (The Netherlands)", "Netherlands")
)
if __name__ == "__main__":
unittest.main()
|
b4f8e0ca25b27047cc3bf556a15cb603688ba905
|
respite/serializers/jsonserializer.py
|
respite/serializers/jsonserializer.py
|
try:
import json
except ImportError:
from django.utils import simplejson as json
from base import Serializer
class JSONSerializer(Serializer):
def serialize(self):
data = self.preprocess()
return json.dumps(data)
|
try:
import json
except ImportError:
from django.utils import simplejson as json
from base import Serializer
class JSONSerializer(Serializer):
def serialize(self):
data = self.preprocess()
return json.dumps(data, ensure_ascii=False)
|
Fix a bug that caused JSON to be serialized as a byte stream with unicode code points
|
Fix a bug that caused JSON to be serialized as a byte stream with unicode code points
|
Python
|
mit
|
jgorset/django-respite,jgorset/django-respite,jgorset/django-respite
|
try:
import json
except ImportError:
from django.utils import simplejson as json
from base import Serializer
class JSONSerializer(Serializer):
def serialize(self):
data = self.preprocess()
return json.dumps(data)
Fix a bug that caused JSON to be serialized as a byte stream with unicode code points
|
try:
import json
except ImportError:
from django.utils import simplejson as json
from base import Serializer
class JSONSerializer(Serializer):
def serialize(self):
data = self.preprocess()
return json.dumps(data, ensure_ascii=False)
|
<commit_before>try:
import json
except ImportError:
from django.utils import simplejson as json
from base import Serializer
class JSONSerializer(Serializer):
def serialize(self):
data = self.preprocess()
return json.dumps(data)
<commit_msg>Fix a bug that caused JSON to be serialized as a byte stream with unicode code points<commit_after>
|
try:
import json
except ImportError:
from django.utils import simplejson as json
from base import Serializer
class JSONSerializer(Serializer):
def serialize(self):
data = self.preprocess()
return json.dumps(data, ensure_ascii=False)
|
try:
import json
except ImportError:
from django.utils import simplejson as json
from base import Serializer
class JSONSerializer(Serializer):
def serialize(self):
data = self.preprocess()
return json.dumps(data)
Fix a bug that caused JSON to be serialized as a byte stream with unicode code pointstry:
import json
except ImportError:
from django.utils import simplejson as json
from base import Serializer
class JSONSerializer(Serializer):
def serialize(self):
data = self.preprocess()
return json.dumps(data, ensure_ascii=False)
|
<commit_before>try:
import json
except ImportError:
from django.utils import simplejson as json
from base import Serializer
class JSONSerializer(Serializer):
def serialize(self):
data = self.preprocess()
return json.dumps(data)
<commit_msg>Fix a bug that caused JSON to be serialized as a byte stream with unicode code points<commit_after>try:
import json
except ImportError:
from django.utils import simplejson as json
from base import Serializer
class JSONSerializer(Serializer):
def serialize(self):
data = self.preprocess()
return json.dumps(data, ensure_ascii=False)
|
2c64a9e0bd1a19cc766035d80b72ec8c4baec99f
|
project/submission/forms.py
|
project/submission/forms.py
|
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import FileSubmission, VideoSubmission
class VideoSubmissionForm(forms.ModelForm):
class Meta:
model = VideoSubmission
fields = ['video_url']
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(VideoSubmissionForm, self).__init__(*args, **kwargs)
class FileSubmissionForm(forms.ModelForm):
class Meta:
model = FileSubmission
fields = ['submission', 'comments']
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(FileSubmissionForm, self).__init__(*args, **kwargs)
def clean_submission(self):
submission = self.cleaned_data.get('submission', False)
if submission:
if submission._size > 1024**3:
raise forms.ValidationError("Submission file too large ( > 1 GB )")
return submission
else:
raise forms.ValidationError("Couldn't read uploaded zip.")
|
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import FileSubmission, VideoSubmission
class VideoSubmissionForm(forms.ModelForm):
class Meta:
model = VideoSubmission
fields = ['video_url']
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(VideoSubmissionForm, self).__init__(*args, **kwargs)
class FileSubmissionForm(forms.ModelForm):
class Meta:
model = FileSubmission
fields = ['submission', 'comments']
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(FileSubmissionForm, self).__init__(*args, **kwargs)
def clean_submission(self):
submission = self.cleaned_data.get('submission', False)
if submission:
if submission._size > 129 * 1024**2:
raise forms.ValidationError("Submission file too large ( > 128 MB )")
return submission
else:
raise forms.ValidationError("Couldn't read uploaded zip.")
|
Decrease accepted file size to 128MB
|
Decrease accepted file size to 128MB
|
Python
|
mit
|
compsci-hfh/app,compsci-hfh/app
|
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import FileSubmission, VideoSubmission
class VideoSubmissionForm(forms.ModelForm):
class Meta:
model = VideoSubmission
fields = ['video_url']
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(VideoSubmissionForm, self).__init__(*args, **kwargs)
class FileSubmissionForm(forms.ModelForm):
class Meta:
model = FileSubmission
fields = ['submission', 'comments']
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(FileSubmissionForm, self).__init__(*args, **kwargs)
def clean_submission(self):
submission = self.cleaned_data.get('submission', False)
if submission:
if submission._size > 1024**3:
raise forms.ValidationError("Submission file too large ( > 1 GB )")
return submission
else:
raise forms.ValidationError("Couldn't read uploaded zip.")
Decrease accepted file size to 128MB
|
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import FileSubmission, VideoSubmission
class VideoSubmissionForm(forms.ModelForm):
class Meta:
model = VideoSubmission
fields = ['video_url']
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(VideoSubmissionForm, self).__init__(*args, **kwargs)
class FileSubmissionForm(forms.ModelForm):
class Meta:
model = FileSubmission
fields = ['submission', 'comments']
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(FileSubmissionForm, self).__init__(*args, **kwargs)
def clean_submission(self):
submission = self.cleaned_data.get('submission', False)
if submission:
if submission._size > 129 * 1024**2:
raise forms.ValidationError("Submission file too large ( > 128 MB )")
return submission
else:
raise forms.ValidationError("Couldn't read uploaded zip.")
|
<commit_before>from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import FileSubmission, VideoSubmission
class VideoSubmissionForm(forms.ModelForm):
class Meta:
model = VideoSubmission
fields = ['video_url']
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(VideoSubmissionForm, self).__init__(*args, **kwargs)
class FileSubmissionForm(forms.ModelForm):
class Meta:
model = FileSubmission
fields = ['submission', 'comments']
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(FileSubmissionForm, self).__init__(*args, **kwargs)
def clean_submission(self):
submission = self.cleaned_data.get('submission', False)
if submission:
if submission._size > 1024**3:
raise forms.ValidationError("Submission file too large ( > 1 GB )")
return submission
else:
raise forms.ValidationError("Couldn't read uploaded zip.")
<commit_msg>Decrease accepted file size to 128MB<commit_after>
|
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import FileSubmission, VideoSubmission
class VideoSubmissionForm(forms.ModelForm):
class Meta:
model = VideoSubmission
fields = ['video_url']
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(VideoSubmissionForm, self).__init__(*args, **kwargs)
class FileSubmissionForm(forms.ModelForm):
class Meta:
model = FileSubmission
fields = ['submission', 'comments']
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(FileSubmissionForm, self).__init__(*args, **kwargs)
def clean_submission(self):
submission = self.cleaned_data.get('submission', False)
if submission:
if submission._size > 129 * 1024**2:
raise forms.ValidationError("Submission file too large ( > 128 MB )")
return submission
else:
raise forms.ValidationError("Couldn't read uploaded zip.")
|
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import FileSubmission, VideoSubmission
class VideoSubmissionForm(forms.ModelForm):
class Meta:
model = VideoSubmission
fields = ['video_url']
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(VideoSubmissionForm, self).__init__(*args, **kwargs)
class FileSubmissionForm(forms.ModelForm):
class Meta:
model = FileSubmission
fields = ['submission', 'comments']
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(FileSubmissionForm, self).__init__(*args, **kwargs)
def clean_submission(self):
submission = self.cleaned_data.get('submission', False)
if submission:
if submission._size > 1024**3:
raise forms.ValidationError("Submission file too large ( > 1 GB )")
return submission
else:
raise forms.ValidationError("Couldn't read uploaded zip.")
Decrease accepted file size to 128MBfrom django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import FileSubmission, VideoSubmission
class VideoSubmissionForm(forms.ModelForm):
class Meta:
model = VideoSubmission
fields = ['video_url']
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(VideoSubmissionForm, self).__init__(*args, **kwargs)
class FileSubmissionForm(forms.ModelForm):
class Meta:
model = FileSubmission
fields = ['submission', 'comments']
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(FileSubmissionForm, self).__init__(*args, **kwargs)
def clean_submission(self):
submission = self.cleaned_data.get('submission', False)
if submission:
if submission._size > 129 * 1024**2:
raise forms.ValidationError("Submission file too large ( > 128 MB )")
return submission
else:
raise forms.ValidationError("Couldn't read uploaded zip.")
|
<commit_before>from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import FileSubmission, VideoSubmission
class VideoSubmissionForm(forms.ModelForm):
class Meta:
model = VideoSubmission
fields = ['video_url']
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(VideoSubmissionForm, self).__init__(*args, **kwargs)
class FileSubmissionForm(forms.ModelForm):
class Meta:
model = FileSubmission
fields = ['submission', 'comments']
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(FileSubmissionForm, self).__init__(*args, **kwargs)
def clean_submission(self):
submission = self.cleaned_data.get('submission', False)
if submission:
if submission._size > 1024**3:
raise forms.ValidationError("Submission file too large ( > 1 GB )")
return submission
else:
raise forms.ValidationError("Couldn't read uploaded zip.")
<commit_msg>Decrease accepted file size to 128MB<commit_after>from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import FileSubmission, VideoSubmission
class VideoSubmissionForm(forms.ModelForm):
class Meta:
model = VideoSubmission
fields = ['video_url']
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(VideoSubmissionForm, self).__init__(*args, **kwargs)
class FileSubmissionForm(forms.ModelForm):
class Meta:
model = FileSubmission
fields = ['submission', 'comments']
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(FileSubmissionForm, self).__init__(*args, **kwargs)
def clean_submission(self):
submission = self.cleaned_data.get('submission', False)
if submission:
if submission._size > 129 * 1024**2:
raise forms.ValidationError("Submission file too large ( > 128 MB )")
return submission
else:
raise forms.ValidationError("Couldn't read uploaded zip.")
|
81d9558c5d75671349228b8cde84d7049289d3df
|
troposphere/settings/__init__.py
|
troposphere/settings/__init__.py
|
from troposphere.settings.default import *
from troposphere.settings.local import *
|
from troposphere.settings.default import *
try:
from troposphere.settings.local import *
except ImportError:
raise Exception("No local settings module found. Refer to README.md")
|
Add exception for people who dont read the docs
|
Add exception for people who dont read the docs
|
Python
|
apache-2.0
|
CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend
|
from troposphere.settings.default import *
from troposphere.settings.local import *
Add exception for people who dont read the docs
|
from troposphere.settings.default import *
try:
from troposphere.settings.local import *
except ImportError:
raise Exception("No local settings module found. Refer to README.md")
|
<commit_before>from troposphere.settings.default import *
from troposphere.settings.local import *
<commit_msg>Add exception for people who dont read the docs<commit_after>
|
from troposphere.settings.default import *
try:
from troposphere.settings.local import *
except ImportError:
raise Exception("No local settings module found. Refer to README.md")
|
from troposphere.settings.default import *
from troposphere.settings.local import *
Add exception for people who dont read the docsfrom troposphere.settings.default import *
try:
from troposphere.settings.local import *
except ImportError:
raise Exception("No local settings module found. Refer to README.md")
|
<commit_before>from troposphere.settings.default import *
from troposphere.settings.local import *
<commit_msg>Add exception for people who dont read the docs<commit_after>from troposphere.settings.default import *
try:
from troposphere.settings.local import *
except ImportError:
raise Exception("No local settings module found. Refer to README.md")
|
011a285ce247286879e4c063e7c5917f1125732f
|
numba/postpasses.py
|
numba/postpasses.py
|
# -*- coding: utf-8 -*-
"""
Postpasses over the LLVM IR.
The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc
"""
from __future__ import print_function, division, absolute_import
from numba.support.math_support import math_support
default_postpasses = {}
def register_default(name):
def dec(f):
default_postpasses[name] = f
return f
return dec
# ______________________________________________________________________
# Postpasses
@register_default('math')
def postpass_link_math(env, ee, lmod, lfunc):
"numba.math.* -> mathcode.*"
math_support.link_llvm_math_intrinsics(ee, lmod, math_support.llvm_library)
return lfunc
|
# -*- coding: utf-8 -*-
"""
Postpasses over the LLVM IR.
The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc
"""
from __future__ import print_function, division, absolute_import
from numba.support.math_support import math_support
default_postpasses = {}
def register_default(name):
def dec(f):
default_postpasses[name] = f
return f
return dec
# ______________________________________________________________________
# Postpasses
@register_default('math')
def postpass_link_math(env, ee, lmod, lfunc):
"numba.math.* -> mathcode.*"
math_support.link_llvm_math_intrinsics(ee, lmod, math_support.math_library,
math_support.link_llvm_asm)
return lfunc
|
Resolve math functions from LLVM math library
|
Resolve math functions from LLVM math library
|
Python
|
bsd-2-clause
|
pombredanne/numba,stonebig/numba,pitrou/numba,gmarkall/numba,cpcloud/numba,ssarangi/numba,stonebig/numba,sklam/numba,ssarangi/numba,pombredanne/numba,stefanseefeld/numba,IntelLabs/numba,numba/numba,cpcloud/numba,stefanseefeld/numba,stonebig/numba,seibert/numba,pombredanne/numba,gdementen/numba,seibert/numba,cpcloud/numba,pitrou/numba,gdementen/numba,stuartarchibald/numba,stuartarchibald/numba,jriehl/numba,gdementen/numba,sklam/numba,numba/numba,IntelLabs/numba,GaZ3ll3/numba,gdementen/numba,gdementen/numba,jriehl/numba,ssarangi/numba,IntelLabs/numba,GaZ3ll3/numba,pombredanne/numba,gmarkall/numba,gmarkall/numba,jriehl/numba,cpcloud/numba,jriehl/numba,pitrou/numba,numba/numba,jriehl/numba,sklam/numba,gmarkall/numba,seibert/numba,IntelLabs/numba,GaZ3ll3/numba,numba/numba,GaZ3ll3/numba,stefanseefeld/numba,seibert/numba,stefanseefeld/numba,stonebig/numba,stuartarchibald/numba,ssarangi/numba,cpcloud/numba,sklam/numba,seibert/numba,IntelLabs/numba,pitrou/numba,sklam/numba,stuartarchibald/numba,stuartarchibald/numba,pitrou/numba,numba/numba,ssarangi/numba,stonebig/numba,stefanseefeld/numba,pombredanne/numba,gmarkall/numba,GaZ3ll3/numba
|
# -*- coding: utf-8 -*-
"""
Postpasses over the LLVM IR.
The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc
"""
from __future__ import print_function, division, absolute_import
from numba.support.math_support import math_support
default_postpasses = {}
def register_default(name):
def dec(f):
default_postpasses[name] = f
return f
return dec
# ______________________________________________________________________
# Postpasses
@register_default('math')
def postpass_link_math(env, ee, lmod, lfunc):
"numba.math.* -> mathcode.*"
math_support.link_llvm_math_intrinsics(ee, lmod, math_support.llvm_library)
return lfunc
Resolve math functions from LLVM math library
|
# -*- coding: utf-8 -*-
"""
Postpasses over the LLVM IR.
The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc
"""
from __future__ import print_function, division, absolute_import
from numba.support.math_support import math_support
default_postpasses = {}
def register_default(name):
def dec(f):
default_postpasses[name] = f
return f
return dec
# ______________________________________________________________________
# Postpasses
@register_default('math')
def postpass_link_math(env, ee, lmod, lfunc):
"numba.math.* -> mathcode.*"
math_support.link_llvm_math_intrinsics(ee, lmod, math_support.math_library,
math_support.link_llvm_asm)
return lfunc
|
<commit_before># -*- coding: utf-8 -*-
"""
Postpasses over the LLVM IR.
The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc
"""
from __future__ import print_function, division, absolute_import
from numba.support.math_support import math_support
default_postpasses = {}
def register_default(name):
def dec(f):
default_postpasses[name] = f
return f
return dec
# ______________________________________________________________________
# Postpasses
@register_default('math')
def postpass_link_math(env, ee, lmod, lfunc):
"numba.math.* -> mathcode.*"
math_support.link_llvm_math_intrinsics(ee, lmod, math_support.llvm_library)
return lfunc
<commit_msg>Resolve math functions from LLVM math library<commit_after>
|
# -*- coding: utf-8 -*-
"""
Postpasses over the LLVM IR.
The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc
"""
from __future__ import print_function, division, absolute_import
from numba.support.math_support import math_support
default_postpasses = {}
def register_default(name):
def dec(f):
default_postpasses[name] = f
return f
return dec
# ______________________________________________________________________
# Postpasses
@register_default('math')
def postpass_link_math(env, ee, lmod, lfunc):
"numba.math.* -> mathcode.*"
math_support.link_llvm_math_intrinsics(ee, lmod, math_support.math_library,
math_support.link_llvm_asm)
return lfunc
|
# -*- coding: utf-8 -*-
"""
Postpasses over the LLVM IR.
The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc
"""
from __future__ import print_function, division, absolute_import
from numba.support.math_support import math_support
default_postpasses = {}
def register_default(name):
def dec(f):
default_postpasses[name] = f
return f
return dec
# ______________________________________________________________________
# Postpasses
@register_default('math')
def postpass_link_math(env, ee, lmod, lfunc):
"numba.math.* -> mathcode.*"
math_support.link_llvm_math_intrinsics(ee, lmod, math_support.llvm_library)
return lfunc
Resolve math functions from LLVM math library# -*- coding: utf-8 -*-
"""
Postpasses over the LLVM IR.
The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc
"""
from __future__ import print_function, division, absolute_import
from numba.support.math_support import math_support
default_postpasses = {}
def register_default(name):
def dec(f):
default_postpasses[name] = f
return f
return dec
# ______________________________________________________________________
# Postpasses
@register_default('math')
def postpass_link_math(env, ee, lmod, lfunc):
"numba.math.* -> mathcode.*"
math_support.link_llvm_math_intrinsics(ee, lmod, math_support.math_library,
math_support.link_llvm_asm)
return lfunc
|
<commit_before># -*- coding: utf-8 -*-
"""
Postpasses over the LLVM IR.
The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc
"""
from __future__ import print_function, division, absolute_import
from numba.support.math_support import math_support
default_postpasses = {}
def register_default(name):
def dec(f):
default_postpasses[name] = f
return f
return dec
# ______________________________________________________________________
# Postpasses
@register_default('math')
def postpass_link_math(env, ee, lmod, lfunc):
"numba.math.* -> mathcode.*"
math_support.link_llvm_math_intrinsics(ee, lmod, math_support.llvm_library)
return lfunc
<commit_msg>Resolve math functions from LLVM math library<commit_after># -*- coding: utf-8 -*-
"""
Postpasses over the LLVM IR.
The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc
"""
from __future__ import print_function, division, absolute_import
from numba.support.math_support import math_support
default_postpasses = {}
def register_default(name):
def dec(f):
default_postpasses[name] = f
return f
return dec
# ______________________________________________________________________
# Postpasses
@register_default('math')
def postpass_link_math(env, ee, lmod, lfunc):
"numba.math.* -> mathcode.*"
math_support.link_llvm_math_intrinsics(ee, lmod, math_support.math_library,
math_support.link_llvm_asm)
return lfunc
|
3de28fe8be76662654386f5b628eed87dca675db
|
abusehelper/bots/archivebot/tests/test_archivebot.py
|
abusehelper/bots/archivebot/tests/test_archivebot.py
|
import unittest
import os
from tempfile import NamedTemporaryFile
from .. import archivebot
class TestRename(unittest.TestCase):
def test_valid_rename(self):
try:
tmp = NamedTemporaryFile()
new_tmp = archivebot._rename(tmp.name)
self.assertFalse(os.path.isfile(tmp.name))
self.assertTrue(os.path.isfile(new_tmp))
self.assertTrue(new_tmp.find(".compress") > 1)
finally:
if os.path.isfile(tmp.name):
os.remove(tmp.name)
if os.path.isfile(new_tmp):
os.remove(new_tmp)
class TestCompress(unittest.TestCase):
def test_dotcompress(self):
with NamedTemporaryFile(prefix="roomname.compress@example") as tmp:
self.assertRaises(ValueError, archivebot.compress, tmp.name)
def test_valid_compress(self):
try:
tmp = NamedTemporaryFile(suffix=".compress")
tmp.write("test")
gz_file = archivebot.compress(tmp.name)
self.assertEqual(gz_file, tmp.name.replace(".compress", ".gz"))
finally:
if os.path.isfile(tmp.name):
os.remove(tmp.name)
|
import unittest
import os
from tempfile import NamedTemporaryFile
from .. import archivebot
class TestRename(unittest.TestCase):
def test_valid_rename(self):
try:
tmp = NamedTemporaryFile()
new_tmp = archivebot._rename(tmp.name)
self.assertFalse(os.path.isfile(tmp.name))
self.assertTrue(os.path.isfile(new_tmp))
self.assertTrue(new_tmp.find(".compress") > 1)
finally:
for file in [tmp.name, new_tmp]:
if os.path.isfile(file):
os.remove(file)
class TestCompress(unittest.TestCase):
def test_dotcompress(self):
with NamedTemporaryFile(prefix="roomname.compress@example") as tmp:
self.assertRaises(ValueError, archivebot.compress, tmp.name)
def test_valid_compress(self):
try:
tmp = NamedTemporaryFile(suffix=".compress")
tmp.write("test")
gz_file = archivebot.compress(tmp.name)
self.assertEqual(gz_file, tmp.name.replace(".compress", ".gz"))
finally:
for file in [tmp.name, gz_file]:
if os.path.isfile(file):
os.remove(file)
|
Remove all temporary files from disk
|
Remove all temporary files from disk
|
Python
|
mit
|
abusesa/abusehelper
|
import unittest
import os
from tempfile import NamedTemporaryFile
from .. import archivebot
class TestRename(unittest.TestCase):
def test_valid_rename(self):
try:
tmp = NamedTemporaryFile()
new_tmp = archivebot._rename(tmp.name)
self.assertFalse(os.path.isfile(tmp.name))
self.assertTrue(os.path.isfile(new_tmp))
self.assertTrue(new_tmp.find(".compress") > 1)
finally:
if os.path.isfile(tmp.name):
os.remove(tmp.name)
if os.path.isfile(new_tmp):
os.remove(new_tmp)
class TestCompress(unittest.TestCase):
def test_dotcompress(self):
with NamedTemporaryFile(prefix="roomname.compress@example") as tmp:
self.assertRaises(ValueError, archivebot.compress, tmp.name)
def test_valid_compress(self):
try:
tmp = NamedTemporaryFile(suffix=".compress")
tmp.write("test")
gz_file = archivebot.compress(tmp.name)
self.assertEqual(gz_file, tmp.name.replace(".compress", ".gz"))
finally:
if os.path.isfile(tmp.name):
os.remove(tmp.name)
Remove all temporary files from disk
|
import unittest
import os
from tempfile import NamedTemporaryFile
from .. import archivebot
class TestRename(unittest.TestCase):
def test_valid_rename(self):
try:
tmp = NamedTemporaryFile()
new_tmp = archivebot._rename(tmp.name)
self.assertFalse(os.path.isfile(tmp.name))
self.assertTrue(os.path.isfile(new_tmp))
self.assertTrue(new_tmp.find(".compress") > 1)
finally:
for file in [tmp.name, new_tmp]:
if os.path.isfile(file):
os.remove(file)
class TestCompress(unittest.TestCase):
def test_dotcompress(self):
with NamedTemporaryFile(prefix="roomname.compress@example") as tmp:
self.assertRaises(ValueError, archivebot.compress, tmp.name)
def test_valid_compress(self):
try:
tmp = NamedTemporaryFile(suffix=".compress")
tmp.write("test")
gz_file = archivebot.compress(tmp.name)
self.assertEqual(gz_file, tmp.name.replace(".compress", ".gz"))
finally:
for file in [tmp.name, gz_file]:
if os.path.isfile(file):
os.remove(file)
|
<commit_before>import unittest
import os
from tempfile import NamedTemporaryFile
from .. import archivebot
class TestRename(unittest.TestCase):
def test_valid_rename(self):
try:
tmp = NamedTemporaryFile()
new_tmp = archivebot._rename(tmp.name)
self.assertFalse(os.path.isfile(tmp.name))
self.assertTrue(os.path.isfile(new_tmp))
self.assertTrue(new_tmp.find(".compress") > 1)
finally:
if os.path.isfile(tmp.name):
os.remove(tmp.name)
if os.path.isfile(new_tmp):
os.remove(new_tmp)
class TestCompress(unittest.TestCase):
def test_dotcompress(self):
with NamedTemporaryFile(prefix="roomname.compress@example") as tmp:
self.assertRaises(ValueError, archivebot.compress, tmp.name)
def test_valid_compress(self):
try:
tmp = NamedTemporaryFile(suffix=".compress")
tmp.write("test")
gz_file = archivebot.compress(tmp.name)
self.assertEqual(gz_file, tmp.name.replace(".compress", ".gz"))
finally:
if os.path.isfile(tmp.name):
os.remove(tmp.name)
<commit_msg>Remove all temporary files from disk<commit_after>
|
import unittest
import os
from tempfile import NamedTemporaryFile
from .. import archivebot
class TestRename(unittest.TestCase):
def test_valid_rename(self):
try:
tmp = NamedTemporaryFile()
new_tmp = archivebot._rename(tmp.name)
self.assertFalse(os.path.isfile(tmp.name))
self.assertTrue(os.path.isfile(new_tmp))
self.assertTrue(new_tmp.find(".compress") > 1)
finally:
for file in [tmp.name, new_tmp]:
if os.path.isfile(file):
os.remove(file)
class TestCompress(unittest.TestCase):
def test_dotcompress(self):
with NamedTemporaryFile(prefix="roomname.compress@example") as tmp:
self.assertRaises(ValueError, archivebot.compress, tmp.name)
def test_valid_compress(self):
try:
tmp = NamedTemporaryFile(suffix=".compress")
tmp.write("test")
gz_file = archivebot.compress(tmp.name)
self.assertEqual(gz_file, tmp.name.replace(".compress", ".gz"))
finally:
for file in [tmp.name, gz_file]:
if os.path.isfile(file):
os.remove(file)
|
import unittest
import os
from tempfile import NamedTemporaryFile
from .. import archivebot
class TestRename(unittest.TestCase):
def test_valid_rename(self):
try:
tmp = NamedTemporaryFile()
new_tmp = archivebot._rename(tmp.name)
self.assertFalse(os.path.isfile(tmp.name))
self.assertTrue(os.path.isfile(new_tmp))
self.assertTrue(new_tmp.find(".compress") > 1)
finally:
if os.path.isfile(tmp.name):
os.remove(tmp.name)
if os.path.isfile(new_tmp):
os.remove(new_tmp)
class TestCompress(unittest.TestCase):
def test_dotcompress(self):
with NamedTemporaryFile(prefix="roomname.compress@example") as tmp:
self.assertRaises(ValueError, archivebot.compress, tmp.name)
def test_valid_compress(self):
try:
tmp = NamedTemporaryFile(suffix=".compress")
tmp.write("test")
gz_file = archivebot.compress(tmp.name)
self.assertEqual(gz_file, tmp.name.replace(".compress", ".gz"))
finally:
if os.path.isfile(tmp.name):
os.remove(tmp.name)
Remove all temporary files from diskimport unittest
import os
from tempfile import NamedTemporaryFile
from .. import archivebot
class TestRename(unittest.TestCase):
def test_valid_rename(self):
try:
tmp = NamedTemporaryFile()
new_tmp = archivebot._rename(tmp.name)
self.assertFalse(os.path.isfile(tmp.name))
self.assertTrue(os.path.isfile(new_tmp))
self.assertTrue(new_tmp.find(".compress") > 1)
finally:
for file in [tmp.name, new_tmp]:
if os.path.isfile(file):
os.remove(file)
class TestCompress(unittest.TestCase):
def test_dotcompress(self):
with NamedTemporaryFile(prefix="roomname.compress@example") as tmp:
self.assertRaises(ValueError, archivebot.compress, tmp.name)
def test_valid_compress(self):
try:
tmp = NamedTemporaryFile(suffix=".compress")
tmp.write("test")
gz_file = archivebot.compress(tmp.name)
self.assertEqual(gz_file, tmp.name.replace(".compress", ".gz"))
finally:
for file in [tmp.name, gz_file]:
if os.path.isfile(file):
os.remove(file)
|
<commit_before>import unittest
import os
from tempfile import NamedTemporaryFile
from .. import archivebot
class TestRename(unittest.TestCase):
def test_valid_rename(self):
try:
tmp = NamedTemporaryFile()
new_tmp = archivebot._rename(tmp.name)
self.assertFalse(os.path.isfile(tmp.name))
self.assertTrue(os.path.isfile(new_tmp))
self.assertTrue(new_tmp.find(".compress") > 1)
finally:
if os.path.isfile(tmp.name):
os.remove(tmp.name)
if os.path.isfile(new_tmp):
os.remove(new_tmp)
class TestCompress(unittest.TestCase):
def test_dotcompress(self):
with NamedTemporaryFile(prefix="roomname.compress@example") as tmp:
self.assertRaises(ValueError, archivebot.compress, tmp.name)
def test_valid_compress(self):
try:
tmp = NamedTemporaryFile(suffix=".compress")
tmp.write("test")
gz_file = archivebot.compress(tmp.name)
self.assertEqual(gz_file, tmp.name.replace(".compress", ".gz"))
finally:
if os.path.isfile(tmp.name):
os.remove(tmp.name)
<commit_msg>Remove all temporary files from disk<commit_after>import unittest
import os
from tempfile import NamedTemporaryFile
from .. import archivebot
class TestRename(unittest.TestCase):
def test_valid_rename(self):
try:
tmp = NamedTemporaryFile()
new_tmp = archivebot._rename(tmp.name)
self.assertFalse(os.path.isfile(tmp.name))
self.assertTrue(os.path.isfile(new_tmp))
self.assertTrue(new_tmp.find(".compress") > 1)
finally:
for file in [tmp.name, new_tmp]:
if os.path.isfile(file):
os.remove(file)
class TestCompress(unittest.TestCase):
def test_dotcompress(self):
with NamedTemporaryFile(prefix="roomname.compress@example") as tmp:
self.assertRaises(ValueError, archivebot.compress, tmp.name)
def test_valid_compress(self):
try:
tmp = NamedTemporaryFile(suffix=".compress")
tmp.write("test")
gz_file = archivebot.compress(tmp.name)
self.assertEqual(gz_file, tmp.name.replace(".compress", ".gz"))
finally:
for file in [tmp.name, gz_file]:
if os.path.isfile(file):
os.remove(file)
|
24b6c8650fe99791a4091cbdc2c24686e86aa67c
|
pythran/tests/test_cases.py
|
pythran/tests/test_cases.py
|
""" Tests for test cases directory. """
# TODO: check http://code.google.com/p/unladen-swallow/wiki/Benchmarks
import os
from distutils.version import LooseVersion
import numpy
import unittest
from pythran.tests import TestFromDir
class TestCases(TestFromDir):
""" Class to check all tests in the cases directory. """
path = os.path.join(os.path.dirname(__file__), "cases")
TestCases.populate(TestCases)
if LooseVersion(numpy.__version__) >= '1.20':
del TestCases.test_train_equalizer_norun0
del TestCases.test_train_eq_run0
del TestCases.test_train_eq_run1
if __name__ == '__main__':
unittest.main()
|
""" Tests for test cases directory. """
# TODO: check http://code.google.com/p/unladen-swallow/wiki/Benchmarks
import os
from distutils.version import LooseVersion
import numpy
import unittest
from pythran.tests import TestFromDir
class TestCases(TestFromDir):
""" Class to check all tests in the cases directory. """
path = os.path.join(os.path.dirname(__file__), "cases")
TestCases.populate(TestCases)
if LooseVersion(numpy.__version__) >= '1.20':
del TestCases.test_train_equalizer_norun0
del TestCases.test_train_eq_run0
del TestCases.test_train_eq_run1
# too template intensive for old g++
if os.environ.get('CXX', None) == 'g++-5':
del TestCases.test_loopy_jacob_run0
if __name__ == '__main__':
unittest.main()
|
Disable loopy-jacob test on old gcc version
|
Disable loopy-jacob test on old gcc version
This one consumes too much memory and fails the validation, but it compiles fine
with a modern gcc or clang, so let's just blacklist it.
|
Python
|
bsd-3-clause
|
serge-sans-paille/pythran,pombredanne/pythran,pombredanne/pythran,pombredanne/pythran,serge-sans-paille/pythran
|
""" Tests for test cases directory. """
# TODO: check http://code.google.com/p/unladen-swallow/wiki/Benchmarks
import os
from distutils.version import LooseVersion
import numpy
import unittest
from pythran.tests import TestFromDir
class TestCases(TestFromDir):
""" Class to check all tests in the cases directory. """
path = os.path.join(os.path.dirname(__file__), "cases")
TestCases.populate(TestCases)
if LooseVersion(numpy.__version__) >= '1.20':
del TestCases.test_train_equalizer_norun0
del TestCases.test_train_eq_run0
del TestCases.test_train_eq_run1
if __name__ == '__main__':
unittest.main()
Disable loopy-jacob test on old gcc version
This one consumes too much memory and fails the validation, but it compiles fine
with a modern gcc or clang, so let's just blacklist it.
|
""" Tests for test cases directory. """
# TODO: check http://code.google.com/p/unladen-swallow/wiki/Benchmarks
import os
from distutils.version import LooseVersion
import numpy
import unittest
from pythran.tests import TestFromDir
class TestCases(TestFromDir):
""" Class to check all tests in the cases directory. """
path = os.path.join(os.path.dirname(__file__), "cases")
TestCases.populate(TestCases)
if LooseVersion(numpy.__version__) >= '1.20':
del TestCases.test_train_equalizer_norun0
del TestCases.test_train_eq_run0
del TestCases.test_train_eq_run1
# too template intensive for old g++
if os.environ.get('CXX', None) == 'g++-5':
del TestCases.test_loopy_jacob_run0
if __name__ == '__main__':
unittest.main()
|
<commit_before>""" Tests for test cases directory. """
# TODO: check http://code.google.com/p/unladen-swallow/wiki/Benchmarks
import os
from distutils.version import LooseVersion
import numpy
import unittest
from pythran.tests import TestFromDir
class TestCases(TestFromDir):
""" Class to check all tests in the cases directory. """
path = os.path.join(os.path.dirname(__file__), "cases")
TestCases.populate(TestCases)
if LooseVersion(numpy.__version__) >= '1.20':
del TestCases.test_train_equalizer_norun0
del TestCases.test_train_eq_run0
del TestCases.test_train_eq_run1
if __name__ == '__main__':
unittest.main()
<commit_msg>Disable loopy-jacob test on old gcc version
This one consumes too much memory and fails the validation, but it compiles fine
with a modern gcc or clang, so let's just blacklist it.<commit_after>
|
""" Tests for test cases directory. """
# TODO: check http://code.google.com/p/unladen-swallow/wiki/Benchmarks
import os
from distutils.version import LooseVersion
import numpy
import unittest
from pythran.tests import TestFromDir
class TestCases(TestFromDir):
""" Class to check all tests in the cases directory. """
path = os.path.join(os.path.dirname(__file__), "cases")
TestCases.populate(TestCases)
if LooseVersion(numpy.__version__) >= '1.20':
del TestCases.test_train_equalizer_norun0
del TestCases.test_train_eq_run0
del TestCases.test_train_eq_run1
# too template intensive for old g++
if os.environ.get('CXX', None) == 'g++-5':
del TestCases.test_loopy_jacob_run0
if __name__ == '__main__':
unittest.main()
|
""" Tests for test cases directory. """
# TODO: check http://code.google.com/p/unladen-swallow/wiki/Benchmarks
import os
from distutils.version import LooseVersion
import numpy
import unittest
from pythran.tests import TestFromDir
class TestCases(TestFromDir):
""" Class to check all tests in the cases directory. """
path = os.path.join(os.path.dirname(__file__), "cases")
TestCases.populate(TestCases)
if LooseVersion(numpy.__version__) >= '1.20':
del TestCases.test_train_equalizer_norun0
del TestCases.test_train_eq_run0
del TestCases.test_train_eq_run1
if __name__ == '__main__':
unittest.main()
Disable loopy-jacob test on old gcc version
This one consumes too much memory and fails the validation, but it compiles fine
with a modern gcc or clang, so let's just blacklist it.""" Tests for test cases directory. """
# TODO: check http://code.google.com/p/unladen-swallow/wiki/Benchmarks
import os
from distutils.version import LooseVersion
import numpy
import unittest
from pythran.tests import TestFromDir
class TestCases(TestFromDir):
""" Class to check all tests in the cases directory. """
path = os.path.join(os.path.dirname(__file__), "cases")
TestCases.populate(TestCases)
if LooseVersion(numpy.__version__) >= '1.20':
del TestCases.test_train_equalizer_norun0
del TestCases.test_train_eq_run0
del TestCases.test_train_eq_run1
# too template intensive for old g++
if os.environ.get('CXX', None) == 'g++-5':
del TestCases.test_loopy_jacob_run0
if __name__ == '__main__':
unittest.main()
|
<commit_before>""" Tests for test cases directory. """
# TODO: check http://code.google.com/p/unladen-swallow/wiki/Benchmarks
import os
from distutils.version import LooseVersion
import numpy
import unittest
from pythran.tests import TestFromDir
class TestCases(TestFromDir):
""" Class to check all tests in the cases directory. """
path = os.path.join(os.path.dirname(__file__), "cases")
TestCases.populate(TestCases)
if LooseVersion(numpy.__version__) >= '1.20':
del TestCases.test_train_equalizer_norun0
del TestCases.test_train_eq_run0
del TestCases.test_train_eq_run1
if __name__ == '__main__':
unittest.main()
<commit_msg>Disable loopy-jacob test on old gcc version
This one consumes too much memory and fails the validation, but it compiles fine
with a modern gcc or clang, so let's just blacklist it.<commit_after>""" Tests for test cases directory. """
# TODO: check http://code.google.com/p/unladen-swallow/wiki/Benchmarks
import os
from distutils.version import LooseVersion
import numpy
import unittest
from pythran.tests import TestFromDir
class TestCases(TestFromDir):
""" Class to check all tests in the cases directory. """
path = os.path.join(os.path.dirname(__file__), "cases")
TestCases.populate(TestCases)
if LooseVersion(numpy.__version__) >= '1.20':
del TestCases.test_train_equalizer_norun0
del TestCases.test_train_eq_run0
del TestCases.test_train_eq_run1
# too template intensive for old g++
if os.environ.get('CXX', None) == 'g++-5':
del TestCases.test_loopy_jacob_run0
if __name__ == '__main__':
unittest.main()
|
bb19c79ebc976bfa390f3c6ecc59ec6e0d03dd7e
|
speed_spider.py
|
speed_spider.py
|
#!/usr/bin/env python
# coding: utf-8
from grab.spider import Spider, Task
from grab.tools.logs import default_logging
import time
import logging
from random import randint
from grab.util.py3k_support import *
URL_28K = 'http://load.local/grab.html'
def timer(func):
"""
Display time taken to execute the decorated function.
"""
def inner(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
total = time.time() - start
print('Time: %.2f sec.' % total)
return result
return inner
class SpeedSpider(Spider):
def task_generator(self):
url_template = 'http://load.local/grab%d.html'
#fast_url = 'http://load.local/grab0.html'
slow_url = 'http://load.local/slow.html'
#yield Task('load', url=slow_url, disable_cache=True)
#yield Task('load', url=fast_url, disable_cache=False)
for x in xrange(500):
disable_flag = True#not (x % 2)
yield Task('load', url=url_template % x, disable_cache=disable_flag)
#if randint(0, 10) == 10:
#yield Task('load', url=slow_url, disable_cache=True)
def task_load(self, grab, task):
assert 'grab' in grab.response.body
print('ok', task.url)
@timer
def main():
default_logging()
bot = SpeedSpider(thread_number=30)
bot.setup_cache(database='speed_spider', use_compression=True)
bot.run()
print(bot.render_stats())
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# coding: utf-8
from grab.spider import Spider, Task
from grab.tools.logs import default_logging
import time
import logging
from random import randint
from grab.util.py3k_support import *
URL_28K = 'http://load.local/grab.html'
def timer(func):
"""
Display time taken to execute the decorated function.
"""
def inner(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
total = time.time() - start
print('Time: %.2f sec.' % total)
return result
return inner
class SpeedSpider(Spider):
def task_generator(self):
url = 'http://load.local/grab.html'
for x in xrange(500):
yield Task('load', url=url)
def task_load(self, grab, task):
assert 'grab' in grab.response.body
print('ok', task.url)
@timer
def main():
default_logging()
bot = SpeedSpider(thread_number=30)
bot.run()
print(bot.render_stats())
if __name__ == '__main__':
main()
|
Change code of speed test
|
Change code of speed test
|
Python
|
mit
|
shaunstanislaus/grab,alihalabyah/grab,pombredanne/grab-1,alihalabyah/grab,lorien/grab,DDShadoww/grab,maurobaraldi/grab,maurobaraldi/grab,codevlabs/grab,istinspring/grab,DDShadoww/grab,codevlabs/grab,huiyi1990/grab,lorien/grab,kevinlondon/grab,giserh/grab,liorvh/grab,pombredanne/grab-1,shaunstanislaus/grab,raybuhr/grab,huiyi1990/grab,liorvh/grab,kevinlondon/grab,giserh/grab,istinspring/grab,SpaceAppsXploration/grab,raybuhr/grab,SpaceAppsXploration/grab
|
#!/usr/bin/env python
# coding: utf-8
from grab.spider import Spider, Task
from grab.tools.logs import default_logging
import time
import logging
from random import randint
from grab.util.py3k_support import *
URL_28K = 'http://load.local/grab.html'
def timer(func):
"""
Display time taken to execute the decorated function.
"""
def inner(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
total = time.time() - start
print('Time: %.2f sec.' % total)
return result
return inner
class SpeedSpider(Spider):
def task_generator(self):
url_template = 'http://load.local/grab%d.html'
#fast_url = 'http://load.local/grab0.html'
slow_url = 'http://load.local/slow.html'
#yield Task('load', url=slow_url, disable_cache=True)
#yield Task('load', url=fast_url, disable_cache=False)
for x in xrange(500):
disable_flag = True#not (x % 2)
yield Task('load', url=url_template % x, disable_cache=disable_flag)
#if randint(0, 10) == 10:
#yield Task('load', url=slow_url, disable_cache=True)
def task_load(self, grab, task):
assert 'grab' in grab.response.body
print('ok', task.url)
@timer
def main():
default_logging()
bot = SpeedSpider(thread_number=30)
bot.setup_cache(database='speed_spider', use_compression=True)
bot.run()
print(bot.render_stats())
if __name__ == '__main__':
main()
Change code of speed test
|
#!/usr/bin/env python
# coding: utf-8
from grab.spider import Spider, Task
from grab.tools.logs import default_logging
import time
import logging
from random import randint
from grab.util.py3k_support import *
URL_28K = 'http://load.local/grab.html'
def timer(func):
"""
Display time taken to execute the decorated function.
"""
def inner(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
total = time.time() - start
print('Time: %.2f sec.' % total)
return result
return inner
class SpeedSpider(Spider):
def task_generator(self):
url = 'http://load.local/grab.html'
for x in xrange(500):
yield Task('load', url=url)
def task_load(self, grab, task):
assert 'grab' in grab.response.body
print('ok', task.url)
@timer
def main():
default_logging()
bot = SpeedSpider(thread_number=30)
bot.run()
print(bot.render_stats())
if __name__ == '__main__':
main()
|
<commit_before>#!/usr/bin/env python
# coding: utf-8
from grab.spider import Spider, Task
from grab.tools.logs import default_logging
import time
import logging
from random import randint
from grab.util.py3k_support import *
URL_28K = 'http://load.local/grab.html'
def timer(func):
"""
Display time taken to execute the decorated function.
"""
def inner(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
total = time.time() - start
print('Time: %.2f sec.' % total)
return result
return inner
class SpeedSpider(Spider):
def task_generator(self):
url_template = 'http://load.local/grab%d.html'
#fast_url = 'http://load.local/grab0.html'
slow_url = 'http://load.local/slow.html'
#yield Task('load', url=slow_url, disable_cache=True)
#yield Task('load', url=fast_url, disable_cache=False)
for x in xrange(500):
disable_flag = True#not (x % 2)
yield Task('load', url=url_template % x, disable_cache=disable_flag)
#if randint(0, 10) == 10:
#yield Task('load', url=slow_url, disable_cache=True)
def task_load(self, grab, task):
assert 'grab' in grab.response.body
print('ok', task.url)
@timer
def main():
default_logging()
bot = SpeedSpider(thread_number=30)
bot.setup_cache(database='speed_spider', use_compression=True)
bot.run()
print(bot.render_stats())
if __name__ == '__main__':
main()
<commit_msg>Change code of speed test<commit_after>
|
#!/usr/bin/env python
# coding: utf-8
from grab.spider import Spider, Task
from grab.tools.logs import default_logging
import time
import logging
from random import randint
from grab.util.py3k_support import *
URL_28K = 'http://load.local/grab.html'
def timer(func):
"""
Display time taken to execute the decorated function.
"""
def inner(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
total = time.time() - start
print('Time: %.2f sec.' % total)
return result
return inner
class SpeedSpider(Spider):
def task_generator(self):
url = 'http://load.local/grab.html'
for x in xrange(500):
yield Task('load', url=url)
def task_load(self, grab, task):
assert 'grab' in grab.response.body
print('ok', task.url)
@timer
def main():
default_logging()
bot = SpeedSpider(thread_number=30)
bot.run()
print(bot.render_stats())
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# coding: utf-8
from grab.spider import Spider, Task
from grab.tools.logs import default_logging
import time
import logging
from random import randint
from grab.util.py3k_support import *
URL_28K = 'http://load.local/grab.html'
def timer(func):
"""
Display time taken to execute the decorated function.
"""
def inner(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
total = time.time() - start
print('Time: %.2f sec.' % total)
return result
return inner
class SpeedSpider(Spider):
def task_generator(self):
url_template = 'http://load.local/grab%d.html'
#fast_url = 'http://load.local/grab0.html'
slow_url = 'http://load.local/slow.html'
#yield Task('load', url=slow_url, disable_cache=True)
#yield Task('load', url=fast_url, disable_cache=False)
for x in xrange(500):
disable_flag = True#not (x % 2)
yield Task('load', url=url_template % x, disable_cache=disable_flag)
#if randint(0, 10) == 10:
#yield Task('load', url=slow_url, disable_cache=True)
def task_load(self, grab, task):
assert 'grab' in grab.response.body
print('ok', task.url)
@timer
def main():
default_logging()
bot = SpeedSpider(thread_number=30)
bot.setup_cache(database='speed_spider', use_compression=True)
bot.run()
print(bot.render_stats())
if __name__ == '__main__':
main()
Change code of speed test#!/usr/bin/env python
# coding: utf-8
from grab.spider import Spider, Task
from grab.tools.logs import default_logging
import time
import logging
from random import randint
from grab.util.py3k_support import *
URL_28K = 'http://load.local/grab.html'
def timer(func):
"""
Display time taken to execute the decorated function.
"""
def inner(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
total = time.time() - start
print('Time: %.2f sec.' % total)
return result
return inner
class SpeedSpider(Spider):
def task_generator(self):
url = 'http://load.local/grab.html'
for x in xrange(500):
yield Task('load', url=url)
def task_load(self, grab, task):
assert 'grab' in grab.response.body
print('ok', task.url)
@timer
def main():
default_logging()
bot = SpeedSpider(thread_number=30)
bot.run()
print(bot.render_stats())
if __name__ == '__main__':
main()
|
<commit_before>#!/usr/bin/env python
# coding: utf-8
from grab.spider import Spider, Task
from grab.tools.logs import default_logging
import time
import logging
from random import randint
from grab.util.py3k_support import *
URL_28K = 'http://load.local/grab.html'
def timer(func):
"""
Display time taken to execute the decorated function.
"""
def inner(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
total = time.time() - start
print('Time: %.2f sec.' % total)
return result
return inner
class SpeedSpider(Spider):
def task_generator(self):
url_template = 'http://load.local/grab%d.html'
#fast_url = 'http://load.local/grab0.html'
slow_url = 'http://load.local/slow.html'
#yield Task('load', url=slow_url, disable_cache=True)
#yield Task('load', url=fast_url, disable_cache=False)
for x in xrange(500):
disable_flag = True#not (x % 2)
yield Task('load', url=url_template % x, disable_cache=disable_flag)
#if randint(0, 10) == 10:
#yield Task('load', url=slow_url, disable_cache=True)
def task_load(self, grab, task):
assert 'grab' in grab.response.body
print('ok', task.url)
@timer
def main():
default_logging()
bot = SpeedSpider(thread_number=30)
bot.setup_cache(database='speed_spider', use_compression=True)
bot.run()
print(bot.render_stats())
if __name__ == '__main__':
main()
<commit_msg>Change code of speed test<commit_after>#!/usr/bin/env python
# coding: utf-8
from grab.spider import Spider, Task
from grab.tools.logs import default_logging
import time
import logging
from random import randint
from grab.util.py3k_support import *
URL_28K = 'http://load.local/grab.html'
def timer(func):
"""
Display time taken to execute the decorated function.
"""
def inner(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
total = time.time() - start
print('Time: %.2f sec.' % total)
return result
return inner
class SpeedSpider(Spider):
def task_generator(self):
url = 'http://load.local/grab.html'
for x in xrange(500):
yield Task('load', url=url)
def task_load(self, grab, task):
assert 'grab' in grab.response.body
print('ok', task.url)
@timer
def main():
default_logging()
bot = SpeedSpider(thread_number=30)
bot.run()
print(bot.render_stats())
if __name__ == '__main__':
main()
|
7f1f001802ffdf4a53e17b120e65af3ef9d1d2da
|
openfisca_france/conf/cache_blacklist.py
|
openfisca_france/conf/cache_blacklist.py
|
# When using openfisca for a large population, having too many variables in cache make openfisca performances drop.
# The following variables are intermadiate results and do not need to be cached in those usecases.
cache_blacklist = set([
'aide_logement_loyer_retenu',
'aide_logement_charges',
'aide_logement_R0',
'aide_logement_taux_famille',
'aide_logement_taux_loyer',
'aide_logement_participation_personnelle',
'aide_logement_loyer_seuil_degressivite',
'aide_logement_loyer_seuil_suppression',
'aide_logement_montant_brut_avant_degressivite',
])
|
# When using openfisca for a large population, having too many variables in cache make openfisca performances drop.
# The following variables are intermediate results and do not need to be cached in those usecases.
cache_blacklist = set([
'aide_logement_loyer_retenu',
'aide_logement_charges',
'aide_logement_R0',
'aide_logement_taux_famille',
'aide_logement_taux_loyer',
'aide_logement_participation_personnelle',
'aide_logement_loyer_seuil_degressivite',
'aide_logement_loyer_seuil_suppression',
'aide_logement_montant_brut_avant_degressivite',
'aides_logement_primo_accedant',
'aides_logement_primo_accedant_k',
'aides_logement_primo_accedant_nb_part',
'aides_logement_primo_accedant_loyer_minimal',
'aides_logement_primo_accedant_plafond_mensualite',
'aides_logement_primo_accedant_ressources',
])
|
Add new variable to cache blacklist
|
Add new variable to cache blacklist
|
Python
|
agpl-3.0
|
sgmap/openfisca-france,antoinearnoud/openfisca-france,antoinearnoud/openfisca-france,sgmap/openfisca-france
|
# When using openfisca for a large population, having too many variables in cache make openfisca performances drop.
# The following variables are intermadiate results and do not need to be cached in those usecases.
cache_blacklist = set([
'aide_logement_loyer_retenu',
'aide_logement_charges',
'aide_logement_R0',
'aide_logement_taux_famille',
'aide_logement_taux_loyer',
'aide_logement_participation_personnelle',
'aide_logement_loyer_seuil_degressivite',
'aide_logement_loyer_seuil_suppression',
'aide_logement_montant_brut_avant_degressivite',
])
Add new variable to cache blacklist
|
# When using openfisca for a large population, having too many variables in cache make openfisca performances drop.
# The following variables are intermediate results and do not need to be cached in those usecases.
cache_blacklist = set([
'aide_logement_loyer_retenu',
'aide_logement_charges',
'aide_logement_R0',
'aide_logement_taux_famille',
'aide_logement_taux_loyer',
'aide_logement_participation_personnelle',
'aide_logement_loyer_seuil_degressivite',
'aide_logement_loyer_seuil_suppression',
'aide_logement_montant_brut_avant_degressivite',
'aides_logement_primo_accedant',
'aides_logement_primo_accedant_k',
'aides_logement_primo_accedant_nb_part',
'aides_logement_primo_accedant_loyer_minimal',
'aides_logement_primo_accedant_plafond_mensualite',
'aides_logement_primo_accedant_ressources',
])
|
<commit_before># When using openfisca for a large population, having too many variables in cache make openfisca performances drop.
# The following variables are intermadiate results and do not need to be cached in those usecases.
cache_blacklist = set([
'aide_logement_loyer_retenu',
'aide_logement_charges',
'aide_logement_R0',
'aide_logement_taux_famille',
'aide_logement_taux_loyer',
'aide_logement_participation_personnelle',
'aide_logement_loyer_seuil_degressivite',
'aide_logement_loyer_seuil_suppression',
'aide_logement_montant_brut_avant_degressivite',
])
<commit_msg>Add new variable to cache blacklist<commit_after>
|
# When using openfisca for a large population, having too many variables in cache make openfisca performances drop.
# The following variables are intermediate results and do not need to be cached in those usecases.
cache_blacklist = set([
'aide_logement_loyer_retenu',
'aide_logement_charges',
'aide_logement_R0',
'aide_logement_taux_famille',
'aide_logement_taux_loyer',
'aide_logement_participation_personnelle',
'aide_logement_loyer_seuil_degressivite',
'aide_logement_loyer_seuil_suppression',
'aide_logement_montant_brut_avant_degressivite',
'aides_logement_primo_accedant',
'aides_logement_primo_accedant_k',
'aides_logement_primo_accedant_nb_part',
'aides_logement_primo_accedant_loyer_minimal',
'aides_logement_primo_accedant_plafond_mensualite',
'aides_logement_primo_accedant_ressources',
])
|
# When using openfisca for a large population, having too many variables in cache make openfisca performances drop.
# The following variables are intermadiate results and do not need to be cached in those usecases.
cache_blacklist = set([
'aide_logement_loyer_retenu',
'aide_logement_charges',
'aide_logement_R0',
'aide_logement_taux_famille',
'aide_logement_taux_loyer',
'aide_logement_participation_personnelle',
'aide_logement_loyer_seuil_degressivite',
'aide_logement_loyer_seuil_suppression',
'aide_logement_montant_brut_avant_degressivite',
])
Add new variable to cache blacklist# When using openfisca for a large population, having too many variables in cache make openfisca performances drop.
# The following variables are intermediate results and do not need to be cached in those usecases.
cache_blacklist = set([
'aide_logement_loyer_retenu',
'aide_logement_charges',
'aide_logement_R0',
'aide_logement_taux_famille',
'aide_logement_taux_loyer',
'aide_logement_participation_personnelle',
'aide_logement_loyer_seuil_degressivite',
'aide_logement_loyer_seuil_suppression',
'aide_logement_montant_brut_avant_degressivite',
'aides_logement_primo_accedant',
'aides_logement_primo_accedant_k',
'aides_logement_primo_accedant_nb_part',
'aides_logement_primo_accedant_loyer_minimal',
'aides_logement_primo_accedant_plafond_mensualite',
'aides_logement_primo_accedant_ressources',
])
|
<commit_before># When using openfisca for a large population, having too many variables in cache make openfisca performances drop.
# The following variables are intermadiate results and do not need to be cached in those usecases.
cache_blacklist = set([
'aide_logement_loyer_retenu',
'aide_logement_charges',
'aide_logement_R0',
'aide_logement_taux_famille',
'aide_logement_taux_loyer',
'aide_logement_participation_personnelle',
'aide_logement_loyer_seuil_degressivite',
'aide_logement_loyer_seuil_suppression',
'aide_logement_montant_brut_avant_degressivite',
])
<commit_msg>Add new variable to cache blacklist<commit_after># When using openfisca for a large population, having too many variables in cache make openfisca performances drop.
# The following variables are intermediate results and do not need to be cached in those usecases.
cache_blacklist = set([
'aide_logement_loyer_retenu',
'aide_logement_charges',
'aide_logement_R0',
'aide_logement_taux_famille',
'aide_logement_taux_loyer',
'aide_logement_participation_personnelle',
'aide_logement_loyer_seuil_degressivite',
'aide_logement_loyer_seuil_suppression',
'aide_logement_montant_brut_avant_degressivite',
'aides_logement_primo_accedant',
'aides_logement_primo_accedant_k',
'aides_logement_primo_accedant_nb_part',
'aides_logement_primo_accedant_loyer_minimal',
'aides_logement_primo_accedant_plafond_mensualite',
'aides_logement_primo_accedant_ressources',
])
|
f98ab4eb86d1753b6eeff2b78251de0c14ef0f0f
|
enabled/_50_admin_add_monitoring_panel.py
|
enabled/_50_admin_add_monitoring_panel.py
|
# The name of the panel to be added to HORIZON_CONFIG. Required.
PANEL = 'monitoring'
# The name of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'overcloud'
# The name of the panel group the PANEL is associated with.
#PANEL_GROUP = 'admin'
DEFAULT_PANEL = 'monitoring'
# Python panel class of the PANEL to be added.
ADD_PANEL = \
'monitoring.panel.Monitoring'
# A list of applications to be added to INSTALLED_APPS.
ADD_INSTALLED_APPS = ['monitoring']
# A list of angular modules to be added as dependencies to horizon app.
#ADD_ANGULAR_MODULE = ['monitoringApp']
|
# The name of the panel to be added to HORIZON_CONFIG. Required.
PANEL = 'monitoring'
# The name of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'overcloud'
# The name of the panel group the PANEL is associated with.
PANEL_GROUP = 'default'
DEFAULT_PANEL = 'monitoring'
# Python panel class of the PANEL to be added.
ADD_PANEL = \
'monitoring.panel.Monitoring'
# A list of applications to be added to INSTALLED_APPS.
ADD_INSTALLED_APPS = ['monitoring']
# A list of angular modules to be added as dependencies to horizon app.
#ADD_ANGULAR_MODULE = ['monitoringApp']
|
Remove panel group Other in dashboard
|
Remove panel group Other in dashboard
|
Python
|
apache-2.0
|
openstack/monasca-ui,stackforge/monasca-ui,stackforge/monasca-ui,openstack/monasca-ui,stackforge/monasca-ui,stackforge/monasca-ui,openstack/monasca-ui,openstack/monasca-ui
|
# The name of the panel to be added to HORIZON_CONFIG. Required.
PANEL = 'monitoring'
# The name of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'overcloud'
# The name of the panel group the PANEL is associated with.
#PANEL_GROUP = 'admin'
DEFAULT_PANEL = 'monitoring'
# Python panel class of the PANEL to be added.
ADD_PANEL = \
'monitoring.panel.Monitoring'
# A list of applications to be added to INSTALLED_APPS.
ADD_INSTALLED_APPS = ['monitoring']
# A list of angular modules to be added as dependencies to horizon app.
#ADD_ANGULAR_MODULE = ['monitoringApp']
Remove panel group Other in dashboard
|
# The name of the panel to be added to HORIZON_CONFIG. Required.
PANEL = 'monitoring'
# The name of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'overcloud'
# The name of the panel group the PANEL is associated with.
PANEL_GROUP = 'default'
DEFAULT_PANEL = 'monitoring'
# Python panel class of the PANEL to be added.
ADD_PANEL = \
'monitoring.panel.Monitoring'
# A list of applications to be added to INSTALLED_APPS.
ADD_INSTALLED_APPS = ['monitoring']
# A list of angular modules to be added as dependencies to horizon app.
#ADD_ANGULAR_MODULE = ['monitoringApp']
|
<commit_before># The name of the panel to be added to HORIZON_CONFIG. Required.
PANEL = 'monitoring'
# The name of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'overcloud'
# The name of the panel group the PANEL is associated with.
#PANEL_GROUP = 'admin'
DEFAULT_PANEL = 'monitoring'
# Python panel class of the PANEL to be added.
ADD_PANEL = \
'monitoring.panel.Monitoring'
# A list of applications to be added to INSTALLED_APPS.
ADD_INSTALLED_APPS = ['monitoring']
# A list of angular modules to be added as dependencies to horizon app.
#ADD_ANGULAR_MODULE = ['monitoringApp']
<commit_msg>Remove panel group Other in dashboard<commit_after>
|
# The name of the panel to be added to HORIZON_CONFIG. Required.
PANEL = 'monitoring'
# The name of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'overcloud'
# The name of the panel group the PANEL is associated with.
PANEL_GROUP = 'default'
DEFAULT_PANEL = 'monitoring'
# Python panel class of the PANEL to be added.
ADD_PANEL = \
'monitoring.panel.Monitoring'
# A list of applications to be added to INSTALLED_APPS.
ADD_INSTALLED_APPS = ['monitoring']
# A list of angular modules to be added as dependencies to horizon app.
#ADD_ANGULAR_MODULE = ['monitoringApp']
|
# The name of the panel to be added to HORIZON_CONFIG. Required.
PANEL = 'monitoring'
# The name of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'overcloud'
# The name of the panel group the PANEL is associated with.
#PANEL_GROUP = 'admin'
DEFAULT_PANEL = 'monitoring'
# Python panel class of the PANEL to be added.
ADD_PANEL = \
'monitoring.panel.Monitoring'
# A list of applications to be added to INSTALLED_APPS.
ADD_INSTALLED_APPS = ['monitoring']
# A list of angular modules to be added as dependencies to horizon app.
#ADD_ANGULAR_MODULE = ['monitoringApp']
Remove panel group Other in dashboard# The name of the panel to be added to HORIZON_CONFIG. Required.
PANEL = 'monitoring'
# The name of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'overcloud'
# The name of the panel group the PANEL is associated with.
PANEL_GROUP = 'default'
DEFAULT_PANEL = 'monitoring'
# Python panel class of the PANEL to be added.
ADD_PANEL = \
'monitoring.panel.Monitoring'
# A list of applications to be added to INSTALLED_APPS.
ADD_INSTALLED_APPS = ['monitoring']
# A list of angular modules to be added as dependencies to horizon app.
#ADD_ANGULAR_MODULE = ['monitoringApp']
|
<commit_before># The name of the panel to be added to HORIZON_CONFIG. Required.
PANEL = 'monitoring'
# The name of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'overcloud'
# The name of the panel group the PANEL is associated with.
#PANEL_GROUP = 'admin'
DEFAULT_PANEL = 'monitoring'
# Python panel class of the PANEL to be added.
ADD_PANEL = \
'monitoring.panel.Monitoring'
# A list of applications to be added to INSTALLED_APPS.
ADD_INSTALLED_APPS = ['monitoring']
# A list of angular modules to be added as dependencies to horizon app.
#ADD_ANGULAR_MODULE = ['monitoringApp']
<commit_msg>Remove panel group Other in dashboard<commit_after># The name of the panel to be added to HORIZON_CONFIG. Required.
PANEL = 'monitoring'
# The name of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'overcloud'
# The name of the panel group the PANEL is associated with.
PANEL_GROUP = 'default'
DEFAULT_PANEL = 'monitoring'
# Python panel class of the PANEL to be added.
ADD_PANEL = \
'monitoring.panel.Monitoring'
# A list of applications to be added to INSTALLED_APPS.
ADD_INSTALLED_APPS = ['monitoring']
# A list of angular modules to be added as dependencies to horizon app.
#ADD_ANGULAR_MODULE = ['monitoringApp']
|
6e12974b1099044dff95fb632307cd6c5500c411
|
corehq/apps/builds/utils.py
|
corehq/apps/builds/utils.py
|
import re
from .models import CommCareBuild, CommCareBuildConfig
def get_all_versions(versions=None):
"""
Returns a list of all versions found in the database,
plus those in the optional list parameter.
"""
versions = versions or []
db = CommCareBuild.get_db()
results = db.view('builds/all', group_level=1).all()
versions += [result['key'][0] for result in results]
return sorted(list(set(versions)))
def get_default_build_spec():
return CommCareBuildConfig.fetch().get_default()
def extract_build_info_from_filename(content_disposition):
"""
>>> extract_build_info_from_filename(
... 'attachment; filename=CommCare_CommCare_2.13_32703_artifacts.zip'
... )
('2.13', 32703)
>>> try:
... extract_build_info_from_filename('foo')
... except ValueError as e:
... print e
Could not find filename like 'CommCare_CommCare_([\\\\d\\\\.]+)_(\\\\d+)_artifacts.zip' in 'foo'
"""
pattern = r'CommCare_CommCare_([\d\.]+)_(\d+)_artifacts.zip'
match = re.search(pattern, content_disposition)
if match:
version, number = match.groups()
return version, int(number)
else:
raise ValueError('Could not find filename like {!r} in {!r}'.format(
pattern, content_disposition))
|
import re
from .models import CommCareBuild, CommCareBuildConfig
def get_all_versions(versions):
"""
Returns a list of all versions found in the database,
plus those in the optional list parameter.
"""
db = CommCareBuild.get_db()
results = db.view('builds/all', group_level=1).all()
versions += [result['key'][0] for result in results]
return sorted(list(set(versions)))
def get_default_build_spec():
return CommCareBuildConfig.fetch().get_default()
def extract_build_info_from_filename(content_disposition):
"""
>>> extract_build_info_from_filename(
... 'attachment; filename=CommCare_CommCare_2.13_32703_artifacts.zip'
... )
('2.13', 32703)
>>> try:
... extract_build_info_from_filename('foo')
... except ValueError as e:
... print e
Could not find filename like 'CommCare_CommCare_([\\\\d\\\\.]+)_(\\\\d+)_artifacts.zip' in 'foo'
"""
pattern = r'CommCare_CommCare_([\d\.]+)_(\d+)_artifacts.zip'
match = re.search(pattern, content_disposition)
if match:
version, number = match.groups()
return version, int(number)
else:
raise ValueError('Could not find filename like {!r} in {!r}'.format(
pattern, content_disposition))
|
Remove optional arg that's now always used
|
Remove optional arg that's now always used
|
Python
|
bsd-3-clause
|
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
|
import re
from .models import CommCareBuild, CommCareBuildConfig
def get_all_versions(versions=None):
"""
Returns a list of all versions found in the database,
plus those in the optional list parameter.
"""
versions = versions or []
db = CommCareBuild.get_db()
results = db.view('builds/all', group_level=1).all()
versions += [result['key'][0] for result in results]
return sorted(list(set(versions)))
def get_default_build_spec():
return CommCareBuildConfig.fetch().get_default()
def extract_build_info_from_filename(content_disposition):
"""
>>> extract_build_info_from_filename(
... 'attachment; filename=CommCare_CommCare_2.13_32703_artifacts.zip'
... )
('2.13', 32703)
>>> try:
... extract_build_info_from_filename('foo')
... except ValueError as e:
... print e
Could not find filename like 'CommCare_CommCare_([\\\\d\\\\.]+)_(\\\\d+)_artifacts.zip' in 'foo'
"""
pattern = r'CommCare_CommCare_([\d\.]+)_(\d+)_artifacts.zip'
match = re.search(pattern, content_disposition)
if match:
version, number = match.groups()
return version, int(number)
else:
raise ValueError('Could not find filename like {!r} in {!r}'.format(
pattern, content_disposition))
Remove optional arg that's now always used
|
import re
from .models import CommCareBuild, CommCareBuildConfig
def get_all_versions(versions):
"""
Returns a list of all versions found in the database,
plus those in the optional list parameter.
"""
db = CommCareBuild.get_db()
results = db.view('builds/all', group_level=1).all()
versions += [result['key'][0] for result in results]
return sorted(list(set(versions)))
def get_default_build_spec():
return CommCareBuildConfig.fetch().get_default()
def extract_build_info_from_filename(content_disposition):
"""
>>> extract_build_info_from_filename(
... 'attachment; filename=CommCare_CommCare_2.13_32703_artifacts.zip'
... )
('2.13', 32703)
>>> try:
... extract_build_info_from_filename('foo')
... except ValueError as e:
... print e
Could not find filename like 'CommCare_CommCare_([\\\\d\\\\.]+)_(\\\\d+)_artifacts.zip' in 'foo'
"""
pattern = r'CommCare_CommCare_([\d\.]+)_(\d+)_artifacts.zip'
match = re.search(pattern, content_disposition)
if match:
version, number = match.groups()
return version, int(number)
else:
raise ValueError('Could not find filename like {!r} in {!r}'.format(
pattern, content_disposition))
|
<commit_before>import re
from .models import CommCareBuild, CommCareBuildConfig
def get_all_versions(versions=None):
"""
Returns a list of all versions found in the database,
plus those in the optional list parameter.
"""
versions = versions or []
db = CommCareBuild.get_db()
results = db.view('builds/all', group_level=1).all()
versions += [result['key'][0] for result in results]
return sorted(list(set(versions)))
def get_default_build_spec():
return CommCareBuildConfig.fetch().get_default()
def extract_build_info_from_filename(content_disposition):
"""
>>> extract_build_info_from_filename(
... 'attachment; filename=CommCare_CommCare_2.13_32703_artifacts.zip'
... )
('2.13', 32703)
>>> try:
... extract_build_info_from_filename('foo')
... except ValueError as e:
... print e
Could not find filename like 'CommCare_CommCare_([\\\\d\\\\.]+)_(\\\\d+)_artifacts.zip' in 'foo'
"""
pattern = r'CommCare_CommCare_([\d\.]+)_(\d+)_artifacts.zip'
match = re.search(pattern, content_disposition)
if match:
version, number = match.groups()
return version, int(number)
else:
raise ValueError('Could not find filename like {!r} in {!r}'.format(
pattern, content_disposition))
<commit_msg>Remove optional arg that's now always used<commit_after>
|
import re
from .models import CommCareBuild, CommCareBuildConfig
def get_all_versions(versions):
"""
Returns a list of all versions found in the database,
plus those in the optional list parameter.
"""
db = CommCareBuild.get_db()
results = db.view('builds/all', group_level=1).all()
versions += [result['key'][0] for result in results]
return sorted(list(set(versions)))
def get_default_build_spec():
return CommCareBuildConfig.fetch().get_default()
def extract_build_info_from_filename(content_disposition):
"""
>>> extract_build_info_from_filename(
... 'attachment; filename=CommCare_CommCare_2.13_32703_artifacts.zip'
... )
('2.13', 32703)
>>> try:
... extract_build_info_from_filename('foo')
... except ValueError as e:
... print e
Could not find filename like 'CommCare_CommCare_([\\\\d\\\\.]+)_(\\\\d+)_artifacts.zip' in 'foo'
"""
pattern = r'CommCare_CommCare_([\d\.]+)_(\d+)_artifacts.zip'
match = re.search(pattern, content_disposition)
if match:
version, number = match.groups()
return version, int(number)
else:
raise ValueError('Could not find filename like {!r} in {!r}'.format(
pattern, content_disposition))
|
import re
from .models import CommCareBuild, CommCareBuildConfig
def get_all_versions(versions=None):
"""
Returns a list of all versions found in the database,
plus those in the optional list parameter.
"""
versions = versions or []
db = CommCareBuild.get_db()
results = db.view('builds/all', group_level=1).all()
versions += [result['key'][0] for result in results]
return sorted(list(set(versions)))
def get_default_build_spec():
return CommCareBuildConfig.fetch().get_default()
def extract_build_info_from_filename(content_disposition):
"""
>>> extract_build_info_from_filename(
... 'attachment; filename=CommCare_CommCare_2.13_32703_artifacts.zip'
... )
('2.13', 32703)
>>> try:
... extract_build_info_from_filename('foo')
... except ValueError as e:
... print e
Could not find filename like 'CommCare_CommCare_([\\\\d\\\\.]+)_(\\\\d+)_artifacts.zip' in 'foo'
"""
pattern = r'CommCare_CommCare_([\d\.]+)_(\d+)_artifacts.zip'
match = re.search(pattern, content_disposition)
if match:
version, number = match.groups()
return version, int(number)
else:
raise ValueError('Could not find filename like {!r} in {!r}'.format(
pattern, content_disposition))
Remove optional arg that's now always usedimport re
from .models import CommCareBuild, CommCareBuildConfig
def get_all_versions(versions):
"""
Returns a list of all versions found in the database,
plus those in the optional list parameter.
"""
db = CommCareBuild.get_db()
results = db.view('builds/all', group_level=1).all()
versions += [result['key'][0] for result in results]
return sorted(list(set(versions)))
def get_default_build_spec():
return CommCareBuildConfig.fetch().get_default()
def extract_build_info_from_filename(content_disposition):
"""
>>> extract_build_info_from_filename(
... 'attachment; filename=CommCare_CommCare_2.13_32703_artifacts.zip'
... )
('2.13', 32703)
>>> try:
... extract_build_info_from_filename('foo')
... except ValueError as e:
... print e
Could not find filename like 'CommCare_CommCare_([\\\\d\\\\.]+)_(\\\\d+)_artifacts.zip' in 'foo'
"""
pattern = r'CommCare_CommCare_([\d\.]+)_(\d+)_artifacts.zip'
match = re.search(pattern, content_disposition)
if match:
version, number = match.groups()
return version, int(number)
else:
raise ValueError('Could not find filename like {!r} in {!r}'.format(
pattern, content_disposition))
|
<commit_before>import re
from .models import CommCareBuild, CommCareBuildConfig
def get_all_versions(versions=None):
"""
Returns a list of all versions found in the database,
plus those in the optional list parameter.
"""
versions = versions or []
db = CommCareBuild.get_db()
results = db.view('builds/all', group_level=1).all()
versions += [result['key'][0] for result in results]
return sorted(list(set(versions)))
def get_default_build_spec():
return CommCareBuildConfig.fetch().get_default()
def extract_build_info_from_filename(content_disposition):
"""
>>> extract_build_info_from_filename(
... 'attachment; filename=CommCare_CommCare_2.13_32703_artifacts.zip'
... )
('2.13', 32703)
>>> try:
... extract_build_info_from_filename('foo')
... except ValueError as e:
... print e
Could not find filename like 'CommCare_CommCare_([\\\\d\\\\.]+)_(\\\\d+)_artifacts.zip' in 'foo'
"""
pattern = r'CommCare_CommCare_([\d\.]+)_(\d+)_artifacts.zip'
match = re.search(pattern, content_disposition)
if match:
version, number = match.groups()
return version, int(number)
else:
raise ValueError('Could not find filename like {!r} in {!r}'.format(
pattern, content_disposition))
<commit_msg>Remove optional arg that's now always used<commit_after>import re
from .models import CommCareBuild, CommCareBuildConfig
def get_all_versions(versions):
"""
Returns a list of all versions found in the database,
plus those in the optional list parameter.
"""
db = CommCareBuild.get_db()
results = db.view('builds/all', group_level=1).all()
versions += [result['key'][0] for result in results]
return sorted(list(set(versions)))
def get_default_build_spec():
return CommCareBuildConfig.fetch().get_default()
def extract_build_info_from_filename(content_disposition):
"""
>>> extract_build_info_from_filename(
... 'attachment; filename=CommCare_CommCare_2.13_32703_artifacts.zip'
... )
('2.13', 32703)
>>> try:
... extract_build_info_from_filename('foo')
... except ValueError as e:
... print e
Could not find filename like 'CommCare_CommCare_([\\\\d\\\\.]+)_(\\\\d+)_artifacts.zip' in 'foo'
"""
pattern = r'CommCare_CommCare_([\d\.]+)_(\d+)_artifacts.zip'
match = re.search(pattern, content_disposition)
if match:
version, number = match.groups()
return version, int(number)
else:
raise ValueError('Could not find filename like {!r} in {!r}'.format(
pattern, content_disposition))
|
ce1395db9340ee694ef7a7c35d7d185e4319cf4e
|
plugins/spotify.py
|
plugins/spotify.py
|
from plugins.util import command, get_url
import json
import re
SPOTIFY_URI_REGEX = r"(?<=spotify:)(?:track|album|artist):[a-zA-Z0-9]{22}"
ENDPOINT = "https://api.spotify.com/v1/{0}s/{1}"
@command()
def spotify(m):
spotify_uris = re.findall(SPOTIFY_URI_REGEX, m.body)
for spotify_uri in spotify_uris:
try:
type, id = _parse_spotify_uri(spotify_uri)
req = get_url(m, ENDPOINT.format(type, id))
if req:
blob = json.loads(req)
if type == "track" or type == "album":
m.bot.private_message(m.location,
blob["artists"][0]["name"] + " - " + blob["name"])
else:
m.bot.private_message(m.location, blob["name"])
except ValueError:
m.bot.logger.error("Invalid Spotify URI: " + spotify_uri)
def _parse_spotify_uri(s):
[type, id] = s.split(':')
return type, id
|
from plugins.util import command, get_url
import json
import re
SPOTIFY_URI_REGEX = r"(?<=spotify:)(?:track|album|artist):[a-zA-Z0-9]{22}"
ENDPOINT = "https://api.spotify.com/v1/{0}s/{1}"
@command()
def spotify(m):
spotify_uris = re.findall(SPOTIFY_URI_REGEX, m.body)
for spotify_uri in spotify_uris:
try:
type, id = _parse_spotify_uri(spotify_uri)
except ValueError:
m.bot.logger.error("Invalid Spotify URI: " + spotify_uri)
else:
req = get_url(m, ENDPOINT.format(type, id))
if req:
blob = json.loads(req)
if type == "track" or type == "album":
m.bot.private_message(m.location, '"{0}" by {1} - {2}'
.format(blob["name"], blob["artists"][0]["name"],
blob["external_urls"]["spotify"]))
else:
m.bot.private_message(m.location, "{0} - {1}"
.format(blob["name"], blob["external_urls"]["spotify"]))
def _parse_spotify_uri(s):
[type, id] = s.split(':')
return type, id
|
Change formatting of response, add URL
|
Change formatting of response, add URL
|
Python
|
mit
|
quanticle/GorillaBot,quanticle/GorillaBot,molly/GorillaBot,molly/GorillaBot
|
from plugins.util import command, get_url
import json
import re
SPOTIFY_URI_REGEX = r"(?<=spotify:)(?:track|album|artist):[a-zA-Z0-9]{22}"
ENDPOINT = "https://api.spotify.com/v1/{0}s/{1}"
@command()
def spotify(m):
spotify_uris = re.findall(SPOTIFY_URI_REGEX, m.body)
for spotify_uri in spotify_uris:
try:
type, id = _parse_spotify_uri(spotify_uri)
req = get_url(m, ENDPOINT.format(type, id))
if req:
blob = json.loads(req)
if type == "track" or type == "album":
m.bot.private_message(m.location,
blob["artists"][0]["name"] + " - " + blob["name"])
else:
m.bot.private_message(m.location, blob["name"])
except ValueError:
m.bot.logger.error("Invalid Spotify URI: " + spotify_uri)
def _parse_spotify_uri(s):
[type, id] = s.split(':')
return type, id
Change formatting of response, add URL
|
from plugins.util import command, get_url
import json
import re
SPOTIFY_URI_REGEX = r"(?<=spotify:)(?:track|album|artist):[a-zA-Z0-9]{22}"
ENDPOINT = "https://api.spotify.com/v1/{0}s/{1}"
@command()
def spotify(m):
spotify_uris = re.findall(SPOTIFY_URI_REGEX, m.body)
for spotify_uri in spotify_uris:
try:
type, id = _parse_spotify_uri(spotify_uri)
except ValueError:
m.bot.logger.error("Invalid Spotify URI: " + spotify_uri)
else:
req = get_url(m, ENDPOINT.format(type, id))
if req:
blob = json.loads(req)
if type == "track" or type == "album":
m.bot.private_message(m.location, '"{0}" by {1} - {2}'
.format(blob["name"], blob["artists"][0]["name"],
blob["external_urls"]["spotify"]))
else:
m.bot.private_message(m.location, "{0} - {1}"
.format(blob["name"], blob["external_urls"]["spotify"]))
def _parse_spotify_uri(s):
[type, id] = s.split(':')
return type, id
|
<commit_before>from plugins.util import command, get_url
import json
import re
SPOTIFY_URI_REGEX = r"(?<=spotify:)(?:track|album|artist):[a-zA-Z0-9]{22}"
ENDPOINT = "https://api.spotify.com/v1/{0}s/{1}"
@command()
def spotify(m):
spotify_uris = re.findall(SPOTIFY_URI_REGEX, m.body)
for spotify_uri in spotify_uris:
try:
type, id = _parse_spotify_uri(spotify_uri)
req = get_url(m, ENDPOINT.format(type, id))
if req:
blob = json.loads(req)
if type == "track" or type == "album":
m.bot.private_message(m.location,
blob["artists"][0]["name"] + " - " + blob["name"])
else:
m.bot.private_message(m.location, blob["name"])
except ValueError:
m.bot.logger.error("Invalid Spotify URI: " + spotify_uri)
def _parse_spotify_uri(s):
[type, id] = s.split(':')
return type, id
<commit_msg>Change formatting of response, add URL<commit_after>
|
from plugins.util import command, get_url
import json
import re
SPOTIFY_URI_REGEX = r"(?<=spotify:)(?:track|album|artist):[a-zA-Z0-9]{22}"
ENDPOINT = "https://api.spotify.com/v1/{0}s/{1}"
@command()
def spotify(m):
spotify_uris = re.findall(SPOTIFY_URI_REGEX, m.body)
for spotify_uri in spotify_uris:
try:
type, id = _parse_spotify_uri(spotify_uri)
except ValueError:
m.bot.logger.error("Invalid Spotify URI: " + spotify_uri)
else:
req = get_url(m, ENDPOINT.format(type, id))
if req:
blob = json.loads(req)
if type == "track" or type == "album":
m.bot.private_message(m.location, '"{0}" by {1} - {2}'
.format(blob["name"], blob["artists"][0]["name"],
blob["external_urls"]["spotify"]))
else:
m.bot.private_message(m.location, "{0} - {1}"
.format(blob["name"], blob["external_urls"]["spotify"]))
def _parse_spotify_uri(s):
[type, id] = s.split(':')
return type, id
|
from plugins.util import command, get_url
import json
import re
SPOTIFY_URI_REGEX = r"(?<=spotify:)(?:track|album|artist):[a-zA-Z0-9]{22}"
ENDPOINT = "https://api.spotify.com/v1/{0}s/{1}"
@command()
def spotify(m):
spotify_uris = re.findall(SPOTIFY_URI_REGEX, m.body)
for spotify_uri in spotify_uris:
try:
type, id = _parse_spotify_uri(spotify_uri)
req = get_url(m, ENDPOINT.format(type, id))
if req:
blob = json.loads(req)
if type == "track" or type == "album":
m.bot.private_message(m.location,
blob["artists"][0]["name"] + " - " + blob["name"])
else:
m.bot.private_message(m.location, blob["name"])
except ValueError:
m.bot.logger.error("Invalid Spotify URI: " + spotify_uri)
def _parse_spotify_uri(s):
[type, id] = s.split(':')
return type, id
Change formatting of response, add URLfrom plugins.util import command, get_url
import json
import re
SPOTIFY_URI_REGEX = r"(?<=spotify:)(?:track|album|artist):[a-zA-Z0-9]{22}"
ENDPOINT = "https://api.spotify.com/v1/{0}s/{1}"
@command()
def spotify(m):
spotify_uris = re.findall(SPOTIFY_URI_REGEX, m.body)
for spotify_uri in spotify_uris:
try:
type, id = _parse_spotify_uri(spotify_uri)
except ValueError:
m.bot.logger.error("Invalid Spotify URI: " + spotify_uri)
else:
req = get_url(m, ENDPOINT.format(type, id))
if req:
blob = json.loads(req)
if type == "track" or type == "album":
m.bot.private_message(m.location, '"{0}" by {1} - {2}'
.format(blob["name"], blob["artists"][0]["name"],
blob["external_urls"]["spotify"]))
else:
m.bot.private_message(m.location, "{0} - {1}"
.format(blob["name"], blob["external_urls"]["spotify"]))
def _parse_spotify_uri(s):
[type, id] = s.split(':')
return type, id
|
<commit_before>from plugins.util import command, get_url
import json
import re
SPOTIFY_URI_REGEX = r"(?<=spotify:)(?:track|album|artist):[a-zA-Z0-9]{22}"
ENDPOINT = "https://api.spotify.com/v1/{0}s/{1}"
@command()
def spotify(m):
spotify_uris = re.findall(SPOTIFY_URI_REGEX, m.body)
for spotify_uri in spotify_uris:
try:
type, id = _parse_spotify_uri(spotify_uri)
req = get_url(m, ENDPOINT.format(type, id))
if req:
blob = json.loads(req)
if type == "track" or type == "album":
m.bot.private_message(m.location,
blob["artists"][0]["name"] + " - " + blob["name"])
else:
m.bot.private_message(m.location, blob["name"])
except ValueError:
m.bot.logger.error("Invalid Spotify URI: " + spotify_uri)
def _parse_spotify_uri(s):
[type, id] = s.split(':')
return type, id
<commit_msg>Change formatting of response, add URL<commit_after>from plugins.util import command, get_url
import json
import re
SPOTIFY_URI_REGEX = r"(?<=spotify:)(?:track|album|artist):[a-zA-Z0-9]{22}"
ENDPOINT = "https://api.spotify.com/v1/{0}s/{1}"
@command()
def spotify(m):
spotify_uris = re.findall(SPOTIFY_URI_REGEX, m.body)
for spotify_uri in spotify_uris:
try:
type, id = _parse_spotify_uri(spotify_uri)
except ValueError:
m.bot.logger.error("Invalid Spotify URI: " + spotify_uri)
else:
req = get_url(m, ENDPOINT.format(type, id))
if req:
blob = json.loads(req)
if type == "track" or type == "album":
m.bot.private_message(m.location, '"{0}" by {1} - {2}'
.format(blob["name"], blob["artists"][0]["name"],
blob["external_urls"]["spotify"]))
else:
m.bot.private_message(m.location, "{0} - {1}"
.format(blob["name"], blob["external_urls"]["spotify"]))
def _parse_spotify_uri(s):
[type, id] = s.split(':')
return type, id
|
8052577164ba144263c7f45e4c823ba396f19d65
|
badgekit_webhooks/views.py
|
badgekit_webhooks/views.py
|
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.http import require_POST
import json
def hello(request):
return HttpResponse("Hello, world. Badges!!!")
@require_POST
def badge_issued_hook(request):
try:
data = json.loads(request.body)
except ValueError:
return HttpResponseBadRequest("Bad JSON")
return HttpResponse("Hello, world. Badges!!!")
|
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
import json
def hello(request):
return HttpResponse("Hello, world. Badges!!!")
@require_POST
@csrf_exempt
def badge_issued_hook(request):
try:
data = json.loads(request.body)
except ValueError:
return HttpResponseBadRequest("Bad JSON")
return HttpResponse("Hello, world. Badges!!!")
|
Make webhook exempt from CSRF protection
|
Make webhook exempt from CSRF protection
Soon, we will add JWT verification, to replace it.
|
Python
|
mit
|
tgs/django-badgekit-webhooks
|
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.http import require_POST
import json
def hello(request):
return HttpResponse("Hello, world. Badges!!!")
@require_POST
def badge_issued_hook(request):
try:
data = json.loads(request.body)
except ValueError:
return HttpResponseBadRequest("Bad JSON")
return HttpResponse("Hello, world. Badges!!!")
Make webhook exempt from CSRF protection
Soon, we will add JWT verification, to replace it.
|
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
import json
def hello(request):
return HttpResponse("Hello, world. Badges!!!")
@require_POST
@csrf_exempt
def badge_issued_hook(request):
try:
data = json.loads(request.body)
except ValueError:
return HttpResponseBadRequest("Bad JSON")
return HttpResponse("Hello, world. Badges!!!")
|
<commit_before>from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.http import require_POST
import json
def hello(request):
return HttpResponse("Hello, world. Badges!!!")
@require_POST
def badge_issued_hook(request):
try:
data = json.loads(request.body)
except ValueError:
return HttpResponseBadRequest("Bad JSON")
return HttpResponse("Hello, world. Badges!!!")
<commit_msg>Make webhook exempt from CSRF protection
Soon, we will add JWT verification, to replace it.<commit_after>
|
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
import json
def hello(request):
return HttpResponse("Hello, world. Badges!!!")
@require_POST
@csrf_exempt
def badge_issued_hook(request):
try:
data = json.loads(request.body)
except ValueError:
return HttpResponseBadRequest("Bad JSON")
return HttpResponse("Hello, world. Badges!!!")
|
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.http import require_POST
import json
def hello(request):
return HttpResponse("Hello, world. Badges!!!")
@require_POST
def badge_issued_hook(request):
try:
data = json.loads(request.body)
except ValueError:
return HttpResponseBadRequest("Bad JSON")
return HttpResponse("Hello, world. Badges!!!")
Make webhook exempt from CSRF protection
Soon, we will add JWT verification, to replace it.from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
import json
def hello(request):
return HttpResponse("Hello, world. Badges!!!")
@require_POST
@csrf_exempt
def badge_issued_hook(request):
try:
data = json.loads(request.body)
except ValueError:
return HttpResponseBadRequest("Bad JSON")
return HttpResponse("Hello, world. Badges!!!")
|
<commit_before>from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.http import require_POST
import json
def hello(request):
return HttpResponse("Hello, world. Badges!!!")
@require_POST
def badge_issued_hook(request):
try:
data = json.loads(request.body)
except ValueError:
return HttpResponseBadRequest("Bad JSON")
return HttpResponse("Hello, world. Badges!!!")
<commit_msg>Make webhook exempt from CSRF protection
Soon, we will add JWT verification, to replace it.<commit_after>from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
import json
def hello(request):
return HttpResponse("Hello, world. Badges!!!")
@require_POST
@csrf_exempt
def badge_issued_hook(request):
try:
data = json.loads(request.body)
except ValueError:
return HttpResponseBadRequest("Bad JSON")
return HttpResponse("Hello, world. Badges!!!")
|
ea026eeeaae0ee30a5f3a4cb9f8cc2a9d1c37e6c
|
jackrabbit/utils.py
|
jackrabbit/utils.py
|
import collections
def is_callable(o):
return isinstance(o, collections.Callable)
|
import collections
import sys
if sys.platform == 'win32':
from time import clock as time
else:
from time import time
def is_callable(o):
return isinstance(o, collections.Callable)
|
Add platform dependent time import for best resolution.
|
Add platform dependent time import for best resolution.
|
Python
|
mit
|
cbigler/jackrabbit
|
import collections
def is_callable(o):
return isinstance(o, collections.Callable)
Add platform dependent time import for best resolution.
|
import collections
import sys
if sys.platform == 'win32':
from time import clock as time
else:
from time import time
def is_callable(o):
return isinstance(o, collections.Callable)
|
<commit_before>import collections
def is_callable(o):
return isinstance(o, collections.Callable)
<commit_msg>Add platform dependent time import for best resolution.<commit_after>
|
import collections
import sys
if sys.platform == 'win32':
from time import clock as time
else:
from time import time
def is_callable(o):
return isinstance(o, collections.Callable)
|
import collections
def is_callable(o):
return isinstance(o, collections.Callable)
Add platform dependent time import for best resolution.import collections
import sys
if sys.platform == 'win32':
from time import clock as time
else:
from time import time
def is_callable(o):
return isinstance(o, collections.Callable)
|
<commit_before>import collections
def is_callable(o):
return isinstance(o, collections.Callable)
<commit_msg>Add platform dependent time import for best resolution.<commit_after>import collections
import sys
if sys.platform == 'win32':
from time import clock as time
else:
from time import time
def is_callable(o):
return isinstance(o, collections.Callable)
|
a24bf76cd3d50b1370e5e63077e1f4ae1023b086
|
lib/euehelpers.py
|
lib/euehelpers.py
|
"""
helpers functions for various aspect of eue-ng project
"""
def check_mail(self, email):
"""
Verify that the provided email is valid
"""
regex = r"^[_.0-9A-Za-z-]+@([0-9A-Za-z][0-9A-Za-z-]+.)+[A-Za-z]{2,4}$"
if not re.match(regex, email):
return False
else:
return True
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
"""
helpers functions for various aspect of eue-ng project
"""
def check_mail(email):
"""
Verify that the provided email is valid
"""
regex = r"^[_.0-9A-Za-z-]+@([0-9A-Za-z][0-9A-Za-z-]+.)+[A-Za-z]{2,4}$"
if not re.match(regex, email):
return False
else:
return True
|
Fix check_mail helpers extracted from a class
|
Fix check_mail helpers extracted from a class
|
Python
|
agpl-3.0
|
david-guenault/eue-ng,david-guenault/eue-ng,david-guenault/eue-ng,david-guenault/eue-ng,david-guenault/eue-ng,david-guenault/eue-ng
|
"""
helpers functions for various aspect of eue-ng project
"""
def check_mail(self, email):
"""
Verify that the provided email is valid
"""
regex = r"^[_.0-9A-Za-z-]+@([0-9A-Za-z][0-9A-Za-z-]+.)+[A-Za-z]{2,4}$"
if not re.match(regex, email):
return False
else:
return True
Fix check_mail helpers extracted from a class
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
"""
helpers functions for various aspect of eue-ng project
"""
def check_mail(email):
"""
Verify that the provided email is valid
"""
regex = r"^[_.0-9A-Za-z-]+@([0-9A-Za-z][0-9A-Za-z-]+.)+[A-Za-z]{2,4}$"
if not re.match(regex, email):
return False
else:
return True
|
<commit_before>"""
helpers functions for various aspect of eue-ng project
"""
def check_mail(self, email):
"""
Verify that the provided email is valid
"""
regex = r"^[_.0-9A-Za-z-]+@([0-9A-Za-z][0-9A-Za-z-]+.)+[A-Za-z]{2,4}$"
if not re.match(regex, email):
return False
else:
return True
<commit_msg>Fix check_mail helpers extracted from a class<commit_after>
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
"""
helpers functions for various aspect of eue-ng project
"""
def check_mail(email):
"""
Verify that the provided email is valid
"""
regex = r"^[_.0-9A-Za-z-]+@([0-9A-Za-z][0-9A-Za-z-]+.)+[A-Za-z]{2,4}$"
if not re.match(regex, email):
return False
else:
return True
|
"""
helpers functions for various aspect of eue-ng project
"""
def check_mail(self, email):
"""
Verify that the provided email is valid
"""
regex = r"^[_.0-9A-Za-z-]+@([0-9A-Za-z][0-9A-Za-z-]+.)+[A-Za-z]{2,4}$"
if not re.match(regex, email):
return False
else:
return True
Fix check_mail helpers extracted from a class#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
"""
helpers functions for various aspect of eue-ng project
"""
def check_mail(email):
"""
Verify that the provided email is valid
"""
regex = r"^[_.0-9A-Za-z-]+@([0-9A-Za-z][0-9A-Za-z-]+.)+[A-Za-z]{2,4}$"
if not re.match(regex, email):
return False
else:
return True
|
<commit_before>"""
helpers functions for various aspect of eue-ng project
"""
def check_mail(self, email):
"""
Verify that the provided email is valid
"""
regex = r"^[_.0-9A-Za-z-]+@([0-9A-Za-z][0-9A-Za-z-]+.)+[A-Za-z]{2,4}$"
if not re.match(regex, email):
return False
else:
return True
<commit_msg>Fix check_mail helpers extracted from a class<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
"""
helpers functions for various aspect of eue-ng project
"""
def check_mail(email):
"""
Verify that the provided email is valid
"""
regex = r"^[_.0-9A-Za-z-]+@([0-9A-Za-z][0-9A-Za-z-]+.)+[A-Za-z]{2,4}$"
if not re.match(regex, email):
return False
else:
return True
|
500664fb110ebf198fa634a44bbabf2fe26f83af
|
wafer/talks/forms.py
|
wafer/talks/forms.py
|
from django import forms
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, HTML
from wafer.talks.models import Talk
class TalkForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TalkForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
submit_button = Submit('submit', _('Submit'))
instance = kwargs['instance']
if instance:
self.helper.layout.append(
FormActions(
submit_button,
HTML('<a href="%s" class="btn btn-danger">%s</a>'
% (reverse('wafer_talk_delete', args=(instance.pk,)),
_('Delete')))))
else:
self.helper.add_input(submit_button)
class Meta:
model = Talk
fields = ('title', 'abstract', 'authors', 'notes')
widgets = {
'abstract': forms.Textarea(attrs={'class': 'input-xxlarge',
'rows': 20}),
'notes': forms.Textarea(attrs={'class': 'input-xxlarge'}),
}
# TODO: authors widget is ugly
|
from django import forms
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, HTML
from markitup.widgets import MarkItUpWidget
from wafer.talks.models import Talk
class TalkForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TalkForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
submit_button = Submit('submit', _('Submit'))
instance = kwargs['instance']
if instance:
self.helper.layout.append(
FormActions(
submit_button,
HTML('<a href="%s" class="btn btn-danger">%s</a>'
% (reverse('wafer_talk_delete', args=(instance.pk,)),
_('Delete')))))
else:
self.helper.add_input(submit_button)
class Meta:
model = Talk
fields = ('title', 'abstract', 'authors', 'notes')
widgets = {
'abstract': MarkItUpWidget(),
'notes': forms.Textarea(attrs={'class': 'input-xxlarge'}),
}
# TODO: authors widget is ugly
|
Use markitup widget in talk form
|
Use markitup widget in talk form
|
Python
|
isc
|
CarlFK/wafer,CarlFK/wafer,CTPUG/wafer,CarlFK/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CarlFK/wafer
|
from django import forms
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, HTML
from wafer.talks.models import Talk
class TalkForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TalkForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
submit_button = Submit('submit', _('Submit'))
instance = kwargs['instance']
if instance:
self.helper.layout.append(
FormActions(
submit_button,
HTML('<a href="%s" class="btn btn-danger">%s</a>'
% (reverse('wafer_talk_delete', args=(instance.pk,)),
_('Delete')))))
else:
self.helper.add_input(submit_button)
class Meta:
model = Talk
fields = ('title', 'abstract', 'authors', 'notes')
widgets = {
'abstract': forms.Textarea(attrs={'class': 'input-xxlarge',
'rows': 20}),
'notes': forms.Textarea(attrs={'class': 'input-xxlarge'}),
}
# TODO: authors widget is ugly
Use markitup widget in talk form
|
from django import forms
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, HTML
from markitup.widgets import MarkItUpWidget
from wafer.talks.models import Talk
class TalkForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TalkForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
submit_button = Submit('submit', _('Submit'))
instance = kwargs['instance']
if instance:
self.helper.layout.append(
FormActions(
submit_button,
HTML('<a href="%s" class="btn btn-danger">%s</a>'
% (reverse('wafer_talk_delete', args=(instance.pk,)),
_('Delete')))))
else:
self.helper.add_input(submit_button)
class Meta:
model = Talk
fields = ('title', 'abstract', 'authors', 'notes')
widgets = {
'abstract': MarkItUpWidget(),
'notes': forms.Textarea(attrs={'class': 'input-xxlarge'}),
}
# TODO: authors widget is ugly
|
<commit_before>from django import forms
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, HTML
from wafer.talks.models import Talk
class TalkForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TalkForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
submit_button = Submit('submit', _('Submit'))
instance = kwargs['instance']
if instance:
self.helper.layout.append(
FormActions(
submit_button,
HTML('<a href="%s" class="btn btn-danger">%s</a>'
% (reverse('wafer_talk_delete', args=(instance.pk,)),
_('Delete')))))
else:
self.helper.add_input(submit_button)
class Meta:
model = Talk
fields = ('title', 'abstract', 'authors', 'notes')
widgets = {
'abstract': forms.Textarea(attrs={'class': 'input-xxlarge',
'rows': 20}),
'notes': forms.Textarea(attrs={'class': 'input-xxlarge'}),
}
# TODO: authors widget is ugly
<commit_msg>Use markitup widget in talk form<commit_after>
|
from django import forms
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, HTML
from markitup.widgets import MarkItUpWidget
from wafer.talks.models import Talk
class TalkForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TalkForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
submit_button = Submit('submit', _('Submit'))
instance = kwargs['instance']
if instance:
self.helper.layout.append(
FormActions(
submit_button,
HTML('<a href="%s" class="btn btn-danger">%s</a>'
% (reverse('wafer_talk_delete', args=(instance.pk,)),
_('Delete')))))
else:
self.helper.add_input(submit_button)
class Meta:
model = Talk
fields = ('title', 'abstract', 'authors', 'notes')
widgets = {
'abstract': MarkItUpWidget(),
'notes': forms.Textarea(attrs={'class': 'input-xxlarge'}),
}
# TODO: authors widget is ugly
|
from django import forms
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, HTML
from wafer.talks.models import Talk
class TalkForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TalkForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
submit_button = Submit('submit', _('Submit'))
instance = kwargs['instance']
if instance:
self.helper.layout.append(
FormActions(
submit_button,
HTML('<a href="%s" class="btn btn-danger">%s</a>'
% (reverse('wafer_talk_delete', args=(instance.pk,)),
_('Delete')))))
else:
self.helper.add_input(submit_button)
class Meta:
model = Talk
fields = ('title', 'abstract', 'authors', 'notes')
widgets = {
'abstract': forms.Textarea(attrs={'class': 'input-xxlarge',
'rows': 20}),
'notes': forms.Textarea(attrs={'class': 'input-xxlarge'}),
}
# TODO: authors widget is ugly
Use markitup widget in talk formfrom django import forms
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, HTML
from markitup.widgets import MarkItUpWidget
from wafer.talks.models import Talk
class TalkForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TalkForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
submit_button = Submit('submit', _('Submit'))
instance = kwargs['instance']
if instance:
self.helper.layout.append(
FormActions(
submit_button,
HTML('<a href="%s" class="btn btn-danger">%s</a>'
% (reverse('wafer_talk_delete', args=(instance.pk,)),
_('Delete')))))
else:
self.helper.add_input(submit_button)
class Meta:
model = Talk
fields = ('title', 'abstract', 'authors', 'notes')
widgets = {
'abstract': MarkItUpWidget(),
'notes': forms.Textarea(attrs={'class': 'input-xxlarge'}),
}
# TODO: authors widget is ugly
|
<commit_before>from django import forms
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, HTML
from wafer.talks.models import Talk
class TalkForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TalkForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
submit_button = Submit('submit', _('Submit'))
instance = kwargs['instance']
if instance:
self.helper.layout.append(
FormActions(
submit_button,
HTML('<a href="%s" class="btn btn-danger">%s</a>'
% (reverse('wafer_talk_delete', args=(instance.pk,)),
_('Delete')))))
else:
self.helper.add_input(submit_button)
class Meta:
model = Talk
fields = ('title', 'abstract', 'authors', 'notes')
widgets = {
'abstract': forms.Textarea(attrs={'class': 'input-xxlarge',
'rows': 20}),
'notes': forms.Textarea(attrs={'class': 'input-xxlarge'}),
}
# TODO: authors widget is ugly
<commit_msg>Use markitup widget in talk form<commit_after>from django import forms
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, HTML
from markitup.widgets import MarkItUpWidget
from wafer.talks.models import Talk
class TalkForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TalkForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
submit_button = Submit('submit', _('Submit'))
instance = kwargs['instance']
if instance:
self.helper.layout.append(
FormActions(
submit_button,
HTML('<a href="%s" class="btn btn-danger">%s</a>'
% (reverse('wafer_talk_delete', args=(instance.pk,)),
_('Delete')))))
else:
self.helper.add_input(submit_button)
class Meta:
model = Talk
fields = ('title', 'abstract', 'authors', 'notes')
widgets = {
'abstract': MarkItUpWidget(),
'notes': forms.Textarea(attrs={'class': 'input-xxlarge'}),
}
# TODO: authors widget is ugly
|
857015c55819a35d177cd1804a3d86ac790a15c6
|
journal/__init__.py
|
journal/__init__.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
journal
Copyright (c) 2011 Matt Behrens <askedrelic@gmail.com>
http://asktherelic.com
A CLI tool to help with keeping a datetime organized journal
Licensing included in LICENSE.txt
"""
__author__ = "Matt Behrens <askedrelic@gmail.com>"
__version__ = "0.2.0"
__all__ = ["main", "parse"]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
journal
Copyright (c) 2011 Matt Behrens <askedrelic@gmail.com>
http://asktherelic.com
A CLI tool to help with keeping a datetime organized journal
Licensing included in LICENSE.txt
"""
__author__ = "Matt Behrens <askedrelic@gmail.com>"
__version__ = "0.3.0dev"
__all__ = ["main", "parse"]
|
Set correct current working version
|
Set correct current working version
|
Python
|
mit
|
askedrelic/journal
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
journal
Copyright (c) 2011 Matt Behrens <askedrelic@gmail.com>
http://asktherelic.com
A CLI tool to help with keeping a datetime organized journal
Licensing included in LICENSE.txt
"""
__author__ = "Matt Behrens <askedrelic@gmail.com>"
__version__ = "0.2.0"
__all__ = ["main", "parse"]
Set correct current working version
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
journal
Copyright (c) 2011 Matt Behrens <askedrelic@gmail.com>
http://asktherelic.com
A CLI tool to help with keeping a datetime organized journal
Licensing included in LICENSE.txt
"""
__author__ = "Matt Behrens <askedrelic@gmail.com>"
__version__ = "0.3.0dev"
__all__ = ["main", "parse"]
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
journal
Copyright (c) 2011 Matt Behrens <askedrelic@gmail.com>
http://asktherelic.com
A CLI tool to help with keeping a datetime organized journal
Licensing included in LICENSE.txt
"""
__author__ = "Matt Behrens <askedrelic@gmail.com>"
__version__ = "0.2.0"
__all__ = ["main", "parse"]
<commit_msg>Set correct current working version<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
journal
Copyright (c) 2011 Matt Behrens <askedrelic@gmail.com>
http://asktherelic.com
A CLI tool to help with keeping a datetime organized journal
Licensing included in LICENSE.txt
"""
__author__ = "Matt Behrens <askedrelic@gmail.com>"
__version__ = "0.3.0dev"
__all__ = ["main", "parse"]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
journal
Copyright (c) 2011 Matt Behrens <askedrelic@gmail.com>
http://asktherelic.com
A CLI tool to help with keeping a datetime organized journal
Licensing included in LICENSE.txt
"""
__author__ = "Matt Behrens <askedrelic@gmail.com>"
__version__ = "0.2.0"
__all__ = ["main", "parse"]
Set correct current working version#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
journal
Copyright (c) 2011 Matt Behrens <askedrelic@gmail.com>
http://asktherelic.com
A CLI tool to help with keeping a datetime organized journal
Licensing included in LICENSE.txt
"""
__author__ = "Matt Behrens <askedrelic@gmail.com>"
__version__ = "0.3.0dev"
__all__ = ["main", "parse"]
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
journal
Copyright (c) 2011 Matt Behrens <askedrelic@gmail.com>
http://asktherelic.com
A CLI tool to help with keeping a datetime organized journal
Licensing included in LICENSE.txt
"""
__author__ = "Matt Behrens <askedrelic@gmail.com>"
__version__ = "0.2.0"
__all__ = ["main", "parse"]
<commit_msg>Set correct current working version<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
journal
Copyright (c) 2011 Matt Behrens <askedrelic@gmail.com>
http://asktherelic.com
A CLI tool to help with keeping a datetime organized journal
Licensing included in LICENSE.txt
"""
__author__ = "Matt Behrens <askedrelic@gmail.com>"
__version__ = "0.3.0dev"
__all__ = ["main", "parse"]
|
ddf3e604cee09d82ea8741d2ed08f600ba2f70c0
|
scaffolder/commands/list.py
|
scaffolder/commands/list.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import make_option
from optparse import OptionParser
from scaffolder.core.commands import BaseCommand
from scaffolder.core.template import TemplateManager
class ListCommand(BaseCommand):
def __init__(self, name, help='', aliases=(), stdout=None, stderr=None):
help = 'Template command help entry'
parser = OptionParser(
version=self.get_version(),
option_list=self.get_option_list(),
usage='\n %prog {0} [OPTIONS]'.format(name)
)
aliases = ('tmp',)
BaseCommand.__init__(self, name, parser=parser, help=help, aliases=aliases)
def run(self, *args, **options):
manger = TemplateManager()
manger.list()
def get_default_option(self):
return []
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import make_option
from optparse import OptionParser
from scaffolder.core.commands import BaseCommand
from scaffolder.core.template import TemplateManager
class ListCommand(BaseCommand):
help = 'Template command help entry'
def run(self, *args, **options):
manger = TemplateManager()
manger.list()
def get_default_option(self):
return []
|
Remove __init__ method, not needed.
|
ListCommand: Remove __init__ method, not needed.
|
Python
|
mit
|
goliatone/minions
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import make_option
from optparse import OptionParser
from scaffolder.core.commands import BaseCommand
from scaffolder.core.template import TemplateManager
class ListCommand(BaseCommand):
def __init__(self, name, help='', aliases=(), stdout=None, stderr=None):
help = 'Template command help entry'
parser = OptionParser(
version=self.get_version(),
option_list=self.get_option_list(),
usage='\n %prog {0} [OPTIONS]'.format(name)
)
aliases = ('tmp',)
BaseCommand.__init__(self, name, parser=parser, help=help, aliases=aliases)
def run(self, *args, **options):
manger = TemplateManager()
manger.list()
def get_default_option(self):
return []
ListCommand: Remove __init__ method, not needed.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import make_option
from optparse import OptionParser
from scaffolder.core.commands import BaseCommand
from scaffolder.core.template import TemplateManager
class ListCommand(BaseCommand):
help = 'Template command help entry'
def run(self, *args, **options):
manger = TemplateManager()
manger.list()
def get_default_option(self):
return []
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import make_option
from optparse import OptionParser
from scaffolder.core.commands import BaseCommand
from scaffolder.core.template import TemplateManager
class ListCommand(BaseCommand):
def __init__(self, name, help='', aliases=(), stdout=None, stderr=None):
help = 'Template command help entry'
parser = OptionParser(
version=self.get_version(),
option_list=self.get_option_list(),
usage='\n %prog {0} [OPTIONS]'.format(name)
)
aliases = ('tmp',)
BaseCommand.__init__(self, name, parser=parser, help=help, aliases=aliases)
def run(self, *args, **options):
manger = TemplateManager()
manger.list()
def get_default_option(self):
return []
<commit_msg>ListCommand: Remove __init__ method, not needed.<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import make_option
from optparse import OptionParser
from scaffolder.core.commands import BaseCommand
from scaffolder.core.template import TemplateManager
class ListCommand(BaseCommand):
help = 'Template command help entry'
def run(self, *args, **options):
manger = TemplateManager()
manger.list()
def get_default_option(self):
return []
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import make_option
from optparse import OptionParser
from scaffolder.core.commands import BaseCommand
from scaffolder.core.template import TemplateManager
class ListCommand(BaseCommand):
def __init__(self, name, help='', aliases=(), stdout=None, stderr=None):
help = 'Template command help entry'
parser = OptionParser(
version=self.get_version(),
option_list=self.get_option_list(),
usage='\n %prog {0} [OPTIONS]'.format(name)
)
aliases = ('tmp',)
BaseCommand.__init__(self, name, parser=parser, help=help, aliases=aliases)
def run(self, *args, **options):
manger = TemplateManager()
manger.list()
def get_default_option(self):
return []
ListCommand: Remove __init__ method, not needed.#!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import make_option
from optparse import OptionParser
from scaffolder.core.commands import BaseCommand
from scaffolder.core.template import TemplateManager
class ListCommand(BaseCommand):
help = 'Template command help entry'
def run(self, *args, **options):
manger = TemplateManager()
manger.list()
def get_default_option(self):
return []
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import make_option
from optparse import OptionParser
from scaffolder.core.commands import BaseCommand
from scaffolder.core.template import TemplateManager
class ListCommand(BaseCommand):
def __init__(self, name, help='', aliases=(), stdout=None, stderr=None):
help = 'Template command help entry'
parser = OptionParser(
version=self.get_version(),
option_list=self.get_option_list(),
usage='\n %prog {0} [OPTIONS]'.format(name)
)
aliases = ('tmp',)
BaseCommand.__init__(self, name, parser=parser, help=help, aliases=aliases)
def run(self, *args, **options):
manger = TemplateManager()
manger.list()
def get_default_option(self):
return []
<commit_msg>ListCommand: Remove __init__ method, not needed.<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import make_option
from optparse import OptionParser
from scaffolder.core.commands import BaseCommand
from scaffolder.core.template import TemplateManager
class ListCommand(BaseCommand):
help = 'Template command help entry'
def run(self, *args, **options):
manger = TemplateManager()
manger.list()
def get_default_option(self):
return []
|
2d31f6b842f26b5c33d2650f0f7672ba09230bfd
|
ratechecker/migrations/0002_remove_fee_loader.py
|
ratechecker/migrations/0002_remove_fee_loader.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals
from django.db import migrations, OperationalError, ProgrammingError
class Migration(migrations.Migration):
dependencies = [
('ratechecker', '0001_initial'),
]
operations = [
migrations.AlterUniqueTogether(
name='fee',
unique_together=set([]),
),
migrations.RemoveField(
model_name='fee',
name='plan',
),
migrations.DeleteModel(
name='Fee',
),
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ratechecker', '0001_initial'),
]
operations = [
migrations.AlterUniqueTogether(
name='fee',
unique_together=set([]),
),
migrations.RemoveField(
model_name='fee',
name='plan',
),
migrations.DeleteModel(
name='Fee',
),
]
|
Remove OperationalError and ProgrammingError imports
|
Remove OperationalError and ProgrammingError imports
|
Python
|
cc0-1.0
|
cfpb/owning-a-home-api
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals
from django.db import migrations, OperationalError, ProgrammingError
class Migration(migrations.Migration):
dependencies = [
('ratechecker', '0001_initial'),
]
operations = [
migrations.AlterUniqueTogether(
name='fee',
unique_together=set([]),
),
migrations.RemoveField(
model_name='fee',
name='plan',
),
migrations.DeleteModel(
name='Fee',
),
]
Remove OperationalError and ProgrammingError imports
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ratechecker', '0001_initial'),
]
operations = [
migrations.AlterUniqueTogether(
name='fee',
unique_together=set([]),
),
migrations.RemoveField(
model_name='fee',
name='plan',
),
migrations.DeleteModel(
name='Fee',
),
]
|
<commit_before># -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals
from django.db import migrations, OperationalError, ProgrammingError
class Migration(migrations.Migration):
dependencies = [
('ratechecker', '0001_initial'),
]
operations = [
migrations.AlterUniqueTogether(
name='fee',
unique_together=set([]),
),
migrations.RemoveField(
model_name='fee',
name='plan',
),
migrations.DeleteModel(
name='Fee',
),
]
<commit_msg>Remove OperationalError and ProgrammingError imports<commit_after>
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ratechecker', '0001_initial'),
]
operations = [
migrations.AlterUniqueTogether(
name='fee',
unique_together=set([]),
),
migrations.RemoveField(
model_name='fee',
name='plan',
),
migrations.DeleteModel(
name='Fee',
),
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals
from django.db import migrations, OperationalError, ProgrammingError
class Migration(migrations.Migration):
dependencies = [
('ratechecker', '0001_initial'),
]
operations = [
migrations.AlterUniqueTogether(
name='fee',
unique_together=set([]),
),
migrations.RemoveField(
model_name='fee',
name='plan',
),
migrations.DeleteModel(
name='Fee',
),
]
Remove OperationalError and ProgrammingError imports# -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ratechecker', '0001_initial'),
]
operations = [
migrations.AlterUniqueTogether(
name='fee',
unique_together=set([]),
),
migrations.RemoveField(
model_name='fee',
name='plan',
),
migrations.DeleteModel(
name='Fee',
),
]
|
<commit_before># -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals
from django.db import migrations, OperationalError, ProgrammingError
class Migration(migrations.Migration):
dependencies = [
('ratechecker', '0001_initial'),
]
operations = [
migrations.AlterUniqueTogether(
name='fee',
unique_together=set([]),
),
migrations.RemoveField(
model_name='fee',
name='plan',
),
migrations.DeleteModel(
name='Fee',
),
]
<commit_msg>Remove OperationalError and ProgrammingError imports<commit_after># -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ratechecker', '0001_initial'),
]
operations = [
migrations.AlterUniqueTogether(
name='fee',
unique_together=set([]),
),
migrations.RemoveField(
model_name='fee',
name='plan',
),
migrations.DeleteModel(
name='Fee',
),
]
|
337ab254305d30d6cbe99ac4b6abe396966042b9
|
mrequests/tests/connect-wiznet.py
|
mrequests/tests/connect-wiznet.py
|
"""Sets up network on MicroPython board with Wiznet 5500 ethernet adapter attached via SPI.
This uses the netconfig_ module from my ``micropythonstm-lib``.
To compile the MicroPython ``stm32`` port with support for the Wiznet 5500 adapter,
add the following to ``mpconfigboard.mk`` in your board definition::
MICROPY_PY_WIZNET5K = 5500
MICROPY_PY_LWIP ?= 1
MICROPY_PY_USSL ?= 1
MICROPY_SSL_MBEDTLS ?= 1
and re-compile & upload the firmware::
cd mpy-cross
make
cd ../ports/stm32
make submodules
make BOARD=MYBOARD
# do whatever it takes connect your board in DFU mode
make BOARD=MYBOARD deploy
.. _netconfig: https://github.com/SpotlightKid/micropython-stm-lib/tree/master/netconfig
"""
from netconfig import connect
nic = connect('paddyland-wiznet.json', True)
print(nic.ifconfig())
|
"""Sets up network on MicroPython board with Wiznet 5500 ethernet adapter attached via SPI.
This uses the netconfig_ module from my ``micropython-stm-lib``.
To compile the MicroPython ``stm32`` port with support for the Wiznet 5500 adapter,
add the following to ``mpconfigboard.mk`` in your board definition::
MICROPY_PY_WIZNET5K = 5500
MICROPY_PY_LWIP ?= 1
MICROPY_PY_USSL ?= 1
MICROPY_SSL_MBEDTLS ?= 1
and re-compile & upload the firmware::
cd mpy-cross
make
cd ../ports/stm32
make submodules
make BOARD=MYBOARD
# do whatever it takes connect your board in DFU mode
make BOARD=MYBOARD deploy
.. _netconfig: https://github.com/SpotlightKid/micropython-stm-lib/tree/master/netconfig
"""
from netconfig import connect
nic = connect('paddyland-wiznet.json', True)
print(nic.ifconfig())
|
Fix minor typo in doc string in test support mopule
|
Fix minor typo in doc string in test support mopule
Signed-off-by: Christopher Arndt <711c73f64afdce07b7e38039a96d2224209e9a6c@chrisarndt.de>
|
Python
|
mit
|
SpotlightKid/micropython-stm-lib
|
"""Sets up network on MicroPython board with Wiznet 5500 ethernet adapter attached via SPI.
This uses the netconfig_ module from my ``micropythonstm-lib``.
To compile the MicroPython ``stm32`` port with support for the Wiznet 5500 adapter,
add the following to ``mpconfigboard.mk`` in your board definition::
MICROPY_PY_WIZNET5K = 5500
MICROPY_PY_LWIP ?= 1
MICROPY_PY_USSL ?= 1
MICROPY_SSL_MBEDTLS ?= 1
and re-compile & upload the firmware::
cd mpy-cross
make
cd ../ports/stm32
make submodules
make BOARD=MYBOARD
# do whatever it takes connect your board in DFU mode
make BOARD=MYBOARD deploy
.. _netconfig: https://github.com/SpotlightKid/micropython-stm-lib/tree/master/netconfig
"""
from netconfig import connect
nic = connect('paddyland-wiznet.json', True)
print(nic.ifconfig())
Fix minor typo in doc string in test support mopule
Signed-off-by: Christopher Arndt <711c73f64afdce07b7e38039a96d2224209e9a6c@chrisarndt.de>
|
"""Sets up network on MicroPython board with Wiznet 5500 ethernet adapter attached via SPI.
This uses the netconfig_ module from my ``micropython-stm-lib``.
To compile the MicroPython ``stm32`` port with support for the Wiznet 5500 adapter,
add the following to ``mpconfigboard.mk`` in your board definition::
MICROPY_PY_WIZNET5K = 5500
MICROPY_PY_LWIP ?= 1
MICROPY_PY_USSL ?= 1
MICROPY_SSL_MBEDTLS ?= 1
and re-compile & upload the firmware::
cd mpy-cross
make
cd ../ports/stm32
make submodules
make BOARD=MYBOARD
# do whatever it takes connect your board in DFU mode
make BOARD=MYBOARD deploy
.. _netconfig: https://github.com/SpotlightKid/micropython-stm-lib/tree/master/netconfig
"""
from netconfig import connect
nic = connect('paddyland-wiznet.json', True)
print(nic.ifconfig())
|
<commit_before>"""Sets up network on MicroPython board with Wiznet 5500 ethernet adapter attached via SPI.
This uses the netconfig_ module from my ``micropythonstm-lib``.
To compile the MicroPython ``stm32`` port with support for the Wiznet 5500 adapter,
add the following to ``mpconfigboard.mk`` in your board definition::
MICROPY_PY_WIZNET5K = 5500
MICROPY_PY_LWIP ?= 1
MICROPY_PY_USSL ?= 1
MICROPY_SSL_MBEDTLS ?= 1
and re-compile & upload the firmware::
cd mpy-cross
make
cd ../ports/stm32
make submodules
make BOARD=MYBOARD
# do whatever it takes connect your board in DFU mode
make BOARD=MYBOARD deploy
.. _netconfig: https://github.com/SpotlightKid/micropython-stm-lib/tree/master/netconfig
"""
from netconfig import connect
nic = connect('paddyland-wiznet.json', True)
print(nic.ifconfig())
<commit_msg>Fix minor typo in doc string in test support mopule
Signed-off-by: Christopher Arndt <711c73f64afdce07b7e38039a96d2224209e9a6c@chrisarndt.de><commit_after>
|
"""Sets up network on MicroPython board with Wiznet 5500 ethernet adapter attached via SPI.
This uses the netconfig_ module from my ``micropython-stm-lib``.
To compile the MicroPython ``stm32`` port with support for the Wiznet 5500 adapter,
add the following to ``mpconfigboard.mk`` in your board definition::
MICROPY_PY_WIZNET5K = 5500
MICROPY_PY_LWIP ?= 1
MICROPY_PY_USSL ?= 1
MICROPY_SSL_MBEDTLS ?= 1
and re-compile & upload the firmware::
cd mpy-cross
make
cd ../ports/stm32
make submodules
make BOARD=MYBOARD
# do whatever it takes connect your board in DFU mode
make BOARD=MYBOARD deploy
.. _netconfig: https://github.com/SpotlightKid/micropython-stm-lib/tree/master/netconfig
"""
from netconfig import connect
nic = connect('paddyland-wiznet.json', True)
print(nic.ifconfig())
|
"""Sets up network on MicroPython board with Wiznet 5500 ethernet adapter attached via SPI.
This uses the netconfig_ module from my ``micropythonstm-lib``.
To compile the MicroPython ``stm32`` port with support for the Wiznet 5500 adapter,
add the following to ``mpconfigboard.mk`` in your board definition::
MICROPY_PY_WIZNET5K = 5500
MICROPY_PY_LWIP ?= 1
MICROPY_PY_USSL ?= 1
MICROPY_SSL_MBEDTLS ?= 1
and re-compile & upload the firmware::
cd mpy-cross
make
cd ../ports/stm32
make submodules
make BOARD=MYBOARD
# do whatever it takes connect your board in DFU mode
make BOARD=MYBOARD deploy
.. _netconfig: https://github.com/SpotlightKid/micropython-stm-lib/tree/master/netconfig
"""
from netconfig import connect
nic = connect('paddyland-wiznet.json', True)
print(nic.ifconfig())
Fix minor typo in doc string in test support mopule
Signed-off-by: Christopher Arndt <711c73f64afdce07b7e38039a96d2224209e9a6c@chrisarndt.de>"""Sets up network on MicroPython board with Wiznet 5500 ethernet adapter attached via SPI.
This uses the netconfig_ module from my ``micropython-stm-lib``.
To compile the MicroPython ``stm32`` port with support for the Wiznet 5500 adapter,
add the following to ``mpconfigboard.mk`` in your board definition::
MICROPY_PY_WIZNET5K = 5500
MICROPY_PY_LWIP ?= 1
MICROPY_PY_USSL ?= 1
MICROPY_SSL_MBEDTLS ?= 1
and re-compile & upload the firmware::
cd mpy-cross
make
cd ../ports/stm32
make submodules
make BOARD=MYBOARD
# do whatever it takes connect your board in DFU mode
make BOARD=MYBOARD deploy
.. _netconfig: https://github.com/SpotlightKid/micropython-stm-lib/tree/master/netconfig
"""
from netconfig import connect
nic = connect('paddyland-wiznet.json', True)
print(nic.ifconfig())
|
<commit_before>"""Sets up network on MicroPython board with Wiznet 5500 ethernet adapter attached via SPI.
This uses the netconfig_ module from my ``micropythonstm-lib``.
To compile the MicroPython ``stm32`` port with support for the Wiznet 5500 adapter,
add the following to ``mpconfigboard.mk`` in your board definition::
MICROPY_PY_WIZNET5K = 5500
MICROPY_PY_LWIP ?= 1
MICROPY_PY_USSL ?= 1
MICROPY_SSL_MBEDTLS ?= 1
and re-compile & upload the firmware::
cd mpy-cross
make
cd ../ports/stm32
make submodules
make BOARD=MYBOARD
# do whatever it takes connect your board in DFU mode
make BOARD=MYBOARD deploy
.. _netconfig: https://github.com/SpotlightKid/micropython-stm-lib/tree/master/netconfig
"""
from netconfig import connect
nic = connect('paddyland-wiznet.json', True)
print(nic.ifconfig())
<commit_msg>Fix minor typo in doc string in test support mopule
Signed-off-by: Christopher Arndt <711c73f64afdce07b7e38039a96d2224209e9a6c@chrisarndt.de><commit_after>"""Sets up network on MicroPython board with Wiznet 5500 ethernet adapter attached via SPI.
This uses the netconfig_ module from my ``micropython-stm-lib``.
To compile the MicroPython ``stm32`` port with support for the Wiznet 5500 adapter,
add the following to ``mpconfigboard.mk`` in your board definition::
MICROPY_PY_WIZNET5K = 5500
MICROPY_PY_LWIP ?= 1
MICROPY_PY_USSL ?= 1
MICROPY_SSL_MBEDTLS ?= 1
and re-compile & upload the firmware::
cd mpy-cross
make
cd ../ports/stm32
make submodules
make BOARD=MYBOARD
# do whatever it takes connect your board in DFU mode
make BOARD=MYBOARD deploy
.. _netconfig: https://github.com/SpotlightKid/micropython-stm-lib/tree/master/netconfig
"""
from netconfig import connect
nic = connect('paddyland-wiznet.json', True)
print(nic.ifconfig())
|
ffc0b75d33264baea876898092bbd65247f564e6
|
generate_input.py
|
generate_input.py
|
import sys
from random import randint
f = open('input', 'w')
if (len(sys.argv) < 2):
print('python3 generate_input.py <n>')
sys.exit()
n = int(sys.argv[1])
f.write(str(n)+'\n')
for x in range(0, n):
for y in range(0, n):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
for x in range(0, n):
for y in range(0, n):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
f.close()
|
import sys
from random import randint
f = open('input', 'w')
if (len(sys.argv) < 2):
print('python3 generate_input.py <nlines> <ncolums>')
sys.exit()
nl = int(sys.argv[1])
nc = int(sys.argv[2])
f.write(str(nl)+'\n')
f.write(str(nc)+'\n')
for x in range(0, nl):
for y in range(0, nc):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
for x in range(0, nl):
for y in range(0, nc):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
f.close()
|
Add variable lines and columns
|
Add variable lines and columns
|
Python
|
mit
|
alepmaros/cuda_matrix_multiplication,alepmaros/cuda_matrix_multiplication,alepmaros/cuda_matrix_multiplication
|
import sys
from random import randint
f = open('input', 'w')
if (len(sys.argv) < 2):
print('python3 generate_input.py <n>')
sys.exit()
n = int(sys.argv[1])
f.write(str(n)+'\n')
for x in range(0, n):
for y in range(0, n):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
for x in range(0, n):
for y in range(0, n):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
f.close()
Add variable lines and columns
|
import sys
from random import randint
f = open('input', 'w')
if (len(sys.argv) < 2):
print('python3 generate_input.py <nlines> <ncolums>')
sys.exit()
nl = int(sys.argv[1])
nc = int(sys.argv[2])
f.write(str(nl)+'\n')
f.write(str(nc)+'\n')
for x in range(0, nl):
for y in range(0, nc):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
for x in range(0, nl):
for y in range(0, nc):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
f.close()
|
<commit_before>import sys
from random import randint
f = open('input', 'w')
if (len(sys.argv) < 2):
print('python3 generate_input.py <n>')
sys.exit()
n = int(sys.argv[1])
f.write(str(n)+'\n')
for x in range(0, n):
for y in range(0, n):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
for x in range(0, n):
for y in range(0, n):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
f.close()
<commit_msg>Add variable lines and columns<commit_after>
|
import sys
from random import randint
f = open('input', 'w')
if (len(sys.argv) < 2):
print('python3 generate_input.py <nlines> <ncolums>')
sys.exit()
nl = int(sys.argv[1])
nc = int(sys.argv[2])
f.write(str(nl)+'\n')
f.write(str(nc)+'\n')
for x in range(0, nl):
for y in range(0, nc):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
for x in range(0, nl):
for y in range(0, nc):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
f.close()
|
import sys
from random import randint
f = open('input', 'w')
if (len(sys.argv) < 2):
print('python3 generate_input.py <n>')
sys.exit()
n = int(sys.argv[1])
f.write(str(n)+'\n')
for x in range(0, n):
for y in range(0, n):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
for x in range(0, n):
for y in range(0, n):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
f.close()
Add variable lines and columnsimport sys
from random import randint
f = open('input', 'w')
if (len(sys.argv) < 2):
print('python3 generate_input.py <nlines> <ncolums>')
sys.exit()
nl = int(sys.argv[1])
nc = int(sys.argv[2])
f.write(str(nl)+'\n')
f.write(str(nc)+'\n')
for x in range(0, nl):
for y in range(0, nc):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
for x in range(0, nl):
for y in range(0, nc):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
f.close()
|
<commit_before>import sys
from random import randint
f = open('input', 'w')
if (len(sys.argv) < 2):
print('python3 generate_input.py <n>')
sys.exit()
n = int(sys.argv[1])
f.write(str(n)+'\n')
for x in range(0, n):
for y in range(0, n):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
for x in range(0, n):
for y in range(0, n):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
f.close()
<commit_msg>Add variable lines and columns<commit_after>import sys
from random import randint
f = open('input', 'w')
if (len(sys.argv) < 2):
print('python3 generate_input.py <nlines> <ncolums>')
sys.exit()
nl = int(sys.argv[1])
nc = int(sys.argv[2])
f.write(str(nl)+'\n')
f.write(str(nc)+'\n')
for x in range(0, nl):
for y in range(0, nc):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
for x in range(0, nl):
for y in range(0, nc):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
f.close()
|
143224fe0a8ca17378a2b37dd050df27c000f772
|
lbrynet/__init__.py
|
lbrynet/__init__.py
|
import logging
__version__ = "0.17.2rc11"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
import logging
__version__ = "0.18.0rc1"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
Bump version 0.17.2rc11 --> 0.18.0rc1
|
Bump version 0.17.2rc11 --> 0.18.0rc1
Signed-off-by: Jack Robison <40884020c67726395ea162083a125620dc32cdab@lbry.io>
|
Python
|
mit
|
lbryio/lbry,lbryio/lbry,lbryio/lbry
|
import logging
__version__ = "0.17.2rc11"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
Bump version 0.17.2rc11 --> 0.18.0rc1
Signed-off-by: Jack Robison <40884020c67726395ea162083a125620dc32cdab@lbry.io>
|
import logging
__version__ = "0.18.0rc1"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
<commit_before>import logging
__version__ = "0.17.2rc11"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
<commit_msg>Bump version 0.17.2rc11 --> 0.18.0rc1
Signed-off-by: Jack Robison <40884020c67726395ea162083a125620dc32cdab@lbry.io><commit_after>
|
import logging
__version__ = "0.18.0rc1"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
import logging
__version__ = "0.17.2rc11"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
Bump version 0.17.2rc11 --> 0.18.0rc1
Signed-off-by: Jack Robison <40884020c67726395ea162083a125620dc32cdab@lbry.io>import logging
__version__ = "0.18.0rc1"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
<commit_before>import logging
__version__ = "0.17.2rc11"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
<commit_msg>Bump version 0.17.2rc11 --> 0.18.0rc1
Signed-off-by: Jack Robison <40884020c67726395ea162083a125620dc32cdab@lbry.io><commit_after>import logging
__version__ = "0.18.0rc1"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
d020aeccc44d6de29724750355c341375739a6a9
|
project_template/dataset_score_lookup.py
|
project_template/dataset_score_lookup.py
|
import json
""" Input: the path of the dataset file, a list of song and line indices
Output: List of tuples of words with highest tf-idf scores
Given a list of song-line tuple (song_index, line_index),
returns a list of a word-score tuple, with the word with highest score
at the head of the list.
"""
def score_lookup(data_filename, songs_lst):
fo = open(data_filename, 'r')
lyrics = json.loads(fo.read())
fo.close()
tfidf_sum = {}
tfidf_count = {}
tfidf_scores = []
for song, line in songs_lst:
for word_idx in range(len(lyrics[song]['lyrics'][line])):
word = lyrics[song]['lyrics'][line][word_idx]
score = lyrics[song]['tfidf_scores'][line][word_idx]
if word.isalpha():
if tfidf_sum.has_key(word.lower()):
tfidf_sum[word.lower()] += score
tfidf_count[word.lower()] += 1
else:
tfidf_sum[word.lower()] = score
tfidf_count[word.lower()] = 1
for word, sum in tfidf_sum.items():
tfidf_scores.append((word, sum / tfidf_count[word]))
return sorted(tfidf_scores, key=lambda x: x[1], reverse=True)
|
import json
""" Input: Loaded dataset, a list of song and line indices
Output: List of tuples of words with highest tf-idf scores
Given a list of song-line tuple (song_index, line_index),
returns a list of a word-score tuple, with the word with highest score
at the head of the list.
"""
def score_lookup(dataset, songs_lst):
tfidf_sum = {}
tfidf_count = {}
tfidf_scores = []
for song, line in songs_lst:
for word_idx in range(len(dataset[song]['lyrics'][line])):
word = dataset[song]['lyrics'][line][word_idx]
score = dataset[song]['tfidf_scores'][line][word_idx]
if word.isalpha():
if tfidf_sum.has_key(word.lower()):
tfidf_sum[word.lower()] += score
tfidf_count[word.lower()] += 1
else:
tfidf_sum[word.lower()] = score
tfidf_count[word.lower()] = 1
for word, sum in tfidf_sum.items():
tfidf_scores.append((word, sum / tfidf_count[word]))
return sorted(tfidf_scores, key=lambda x: x[1], reverse=True)
|
Update score lookup to not load dataset file
|
Update score lookup to not load dataset file
|
Python
|
mit
|
warrencrowell/cs4300sp2016-TweetBeat,warrencrowell/cs4300sp2016-TweetBeat
|
import json
""" Input: the path of the dataset file, a list of song and line indices
Output: List of tuples of words with highest tf-idf scores
Given a list of song-line tuple (song_index, line_index),
returns a list of a word-score tuple, with the word with highest score
at the head of the list.
"""
def score_lookup(data_filename, songs_lst):
fo = open(data_filename, 'r')
lyrics = json.loads(fo.read())
fo.close()
tfidf_sum = {}
tfidf_count = {}
tfidf_scores = []
for song, line in songs_lst:
for word_idx in range(len(lyrics[song]['lyrics'][line])):
word = lyrics[song]['lyrics'][line][word_idx]
score = lyrics[song]['tfidf_scores'][line][word_idx]
if word.isalpha():
if tfidf_sum.has_key(word.lower()):
tfidf_sum[word.lower()] += score
tfidf_count[word.lower()] += 1
else:
tfidf_sum[word.lower()] = score
tfidf_count[word.lower()] = 1
for word, sum in tfidf_sum.items():
tfidf_scores.append((word, sum / tfidf_count[word]))
return sorted(tfidf_scores, key=lambda x: x[1], reverse=True)
Update score lookup to not load dataset file
|
import json
""" Input: Loaded dataset, a list of song and line indices
Output: List of tuples of words with highest tf-idf scores
Given a list of song-line tuple (song_index, line_index),
returns a list of a word-score tuple, with the word with highest score
at the head of the list.
"""
def score_lookup(dataset, songs_lst):
tfidf_sum = {}
tfidf_count = {}
tfidf_scores = []
for song, line in songs_lst:
for word_idx in range(len(dataset[song]['lyrics'][line])):
word = dataset[song]['lyrics'][line][word_idx]
score = dataset[song]['tfidf_scores'][line][word_idx]
if word.isalpha():
if tfidf_sum.has_key(word.lower()):
tfidf_sum[word.lower()] += score
tfidf_count[word.lower()] += 1
else:
tfidf_sum[word.lower()] = score
tfidf_count[word.lower()] = 1
for word, sum in tfidf_sum.items():
tfidf_scores.append((word, sum / tfidf_count[word]))
return sorted(tfidf_scores, key=lambda x: x[1], reverse=True)
|
<commit_before>import json
""" Input: the path of the dataset file, a list of song and line indices
Output: List of tuples of words with highest tf-idf scores
Given a list of song-line tuple (song_index, line_index),
returns a list of a word-score tuple, with the word with highest score
at the head of the list.
"""
def score_lookup(data_filename, songs_lst):
fo = open(data_filename, 'r')
lyrics = json.loads(fo.read())
fo.close()
tfidf_sum = {}
tfidf_count = {}
tfidf_scores = []
for song, line in songs_lst:
for word_idx in range(len(lyrics[song]['lyrics'][line])):
word = lyrics[song]['lyrics'][line][word_idx]
score = lyrics[song]['tfidf_scores'][line][word_idx]
if word.isalpha():
if tfidf_sum.has_key(word.lower()):
tfidf_sum[word.lower()] += score
tfidf_count[word.lower()] += 1
else:
tfidf_sum[word.lower()] = score
tfidf_count[word.lower()] = 1
for word, sum in tfidf_sum.items():
tfidf_scores.append((word, sum / tfidf_count[word]))
return sorted(tfidf_scores, key=lambda x: x[1], reverse=True)
<commit_msg>Update score lookup to not load dataset file<commit_after>
|
import json
""" Input: Loaded dataset, a list of song and line indices
Output: List of tuples of words with highest tf-idf scores
Given a list of song-line tuple (song_index, line_index),
returns a list of a word-score tuple, with the word with highest score
at the head of the list.
"""
def score_lookup(dataset, songs_lst):
tfidf_sum = {}
tfidf_count = {}
tfidf_scores = []
for song, line in songs_lst:
for word_idx in range(len(dataset[song]['lyrics'][line])):
word = dataset[song]['lyrics'][line][word_idx]
score = dataset[song]['tfidf_scores'][line][word_idx]
if word.isalpha():
if tfidf_sum.has_key(word.lower()):
tfidf_sum[word.lower()] += score
tfidf_count[word.lower()] += 1
else:
tfidf_sum[word.lower()] = score
tfidf_count[word.lower()] = 1
for word, sum in tfidf_sum.items():
tfidf_scores.append((word, sum / tfidf_count[word]))
return sorted(tfidf_scores, key=lambda x: x[1], reverse=True)
|
import json
""" Input: the path of the dataset file, a list of song and line indices
Output: List of tuples of words with highest tf-idf scores
Given a list of song-line tuple (song_index, line_index),
returns a list of a word-score tuple, with the word with highest score
at the head of the list.
"""
def score_lookup(data_filename, songs_lst):
fo = open(data_filename, 'r')
lyrics = json.loads(fo.read())
fo.close()
tfidf_sum = {}
tfidf_count = {}
tfidf_scores = []
for song, line in songs_lst:
for word_idx in range(len(lyrics[song]['lyrics'][line])):
word = lyrics[song]['lyrics'][line][word_idx]
score = lyrics[song]['tfidf_scores'][line][word_idx]
if word.isalpha():
if tfidf_sum.has_key(word.lower()):
tfidf_sum[word.lower()] += score
tfidf_count[word.lower()] += 1
else:
tfidf_sum[word.lower()] = score
tfidf_count[word.lower()] = 1
for word, sum in tfidf_sum.items():
tfidf_scores.append((word, sum / tfidf_count[word]))
return sorted(tfidf_scores, key=lambda x: x[1], reverse=True)
Update score lookup to not load dataset fileimport json
""" Input: Loaded dataset, a list of song and line indices
Output: List of tuples of words with highest tf-idf scores
Given a list of song-line tuple (song_index, line_index),
returns a list of a word-score tuple, with the word with highest score
at the head of the list.
"""
def score_lookup(dataset, songs_lst):
tfidf_sum = {}
tfidf_count = {}
tfidf_scores = []
for song, line in songs_lst:
for word_idx in range(len(dataset[song]['lyrics'][line])):
word = dataset[song]['lyrics'][line][word_idx]
score = dataset[song]['tfidf_scores'][line][word_idx]
if word.isalpha():
if tfidf_sum.has_key(word.lower()):
tfidf_sum[word.lower()] += score
tfidf_count[word.lower()] += 1
else:
tfidf_sum[word.lower()] = score
tfidf_count[word.lower()] = 1
for word, sum in tfidf_sum.items():
tfidf_scores.append((word, sum / tfidf_count[word]))
return sorted(tfidf_scores, key=lambda x: x[1], reverse=True)
|
<commit_before>import json
""" Input: the path of the dataset file, a list of song and line indices
Output: List of tuples of words with highest tf-idf scores
Given a list of song-line tuple (song_index, line_index),
returns a list of a word-score tuple, with the word with highest score
at the head of the list.
"""
def score_lookup(data_filename, songs_lst):
fo = open(data_filename, 'r')
lyrics = json.loads(fo.read())
fo.close()
tfidf_sum = {}
tfidf_count = {}
tfidf_scores = []
for song, line in songs_lst:
for word_idx in range(len(lyrics[song]['lyrics'][line])):
word = lyrics[song]['lyrics'][line][word_idx]
score = lyrics[song]['tfidf_scores'][line][word_idx]
if word.isalpha():
if tfidf_sum.has_key(word.lower()):
tfidf_sum[word.lower()] += score
tfidf_count[word.lower()] += 1
else:
tfidf_sum[word.lower()] = score
tfidf_count[word.lower()] = 1
for word, sum in tfidf_sum.items():
tfidf_scores.append((word, sum / tfidf_count[word]))
return sorted(tfidf_scores, key=lambda x: x[1], reverse=True)
<commit_msg>Update score lookup to not load dataset file<commit_after>import json
""" Input: Loaded dataset, a list of song and line indices
Output: List of tuples of words with highest tf-idf scores
Given a list of song-line tuple (song_index, line_index),
returns a list of a word-score tuple, with the word with highest score
at the head of the list.
"""
def score_lookup(dataset, songs_lst):
tfidf_sum = {}
tfidf_count = {}
tfidf_scores = []
for song, line in songs_lst:
for word_idx in range(len(dataset[song]['lyrics'][line])):
word = dataset[song]['lyrics'][line][word_idx]
score = dataset[song]['tfidf_scores'][line][word_idx]
if word.isalpha():
if tfidf_sum.has_key(word.lower()):
tfidf_sum[word.lower()] += score
tfidf_count[word.lower()] += 1
else:
tfidf_sum[word.lower()] = score
tfidf_count[word.lower()] = 1
for word, sum in tfidf_sum.items():
tfidf_scores.append((word, sum / tfidf_count[word]))
return sorted(tfidf_scores, key=lambda x: x[1], reverse=True)
|
49721933b824e321db9e848c85647bb3d05a2388
|
lib/feeds/errors.py
|
lib/feeds/errors.py
|
# Copyright 2009-2010 by Ka-Ping Yee
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common exception classes."""
import logging
class ErrorMessage(Exception):
"""Raise this exception to show an error message to the user."""
def __init__(self, status, message):
self.status = status
self.message = message
class Redirect(Exception):
"""Raise this exception to redirect to another page."""
def __init__(self, url):
self.url = url
|
# Copyright 2009-2010 by Ka-Ping Yee
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common exception classes."""
class ErrorMessage(Exception):
"""Raise this exception to show an error message to the user."""
def __init__(self, status, message):
self.status = status
self.message = message
class Redirect(Exception):
"""Raise this exception to redirect to another page."""
def __init__(self, url):
self.url = url
|
Remove import logging. This file is now identical to the branch point.
|
Remove import logging. This file is now identical to the branch point.
|
Python
|
apache-2.0
|
Princessgladys/googleresourcefinder,Princessgladys/googleresourcefinder,Princessgladys/googleresourcefinder
|
# Copyright 2009-2010 by Ka-Ping Yee
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common exception classes."""
import logging
class ErrorMessage(Exception):
"""Raise this exception to show an error message to the user."""
def __init__(self, status, message):
self.status = status
self.message = message
class Redirect(Exception):
"""Raise this exception to redirect to another page."""
def __init__(self, url):
self.url = url
Remove import logging. This file is now identical to the branch point.
|
# Copyright 2009-2010 by Ka-Ping Yee
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common exception classes."""
class ErrorMessage(Exception):
"""Raise this exception to show an error message to the user."""
def __init__(self, status, message):
self.status = status
self.message = message
class Redirect(Exception):
"""Raise this exception to redirect to another page."""
def __init__(self, url):
self.url = url
|
<commit_before># Copyright 2009-2010 by Ka-Ping Yee
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common exception classes."""
import logging
class ErrorMessage(Exception):
"""Raise this exception to show an error message to the user."""
def __init__(self, status, message):
self.status = status
self.message = message
class Redirect(Exception):
"""Raise this exception to redirect to another page."""
def __init__(self, url):
self.url = url
<commit_msg>Remove import logging. This file is now identical to the branch point.<commit_after>
|
# Copyright 2009-2010 by Ka-Ping Yee
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common exception classes."""
class ErrorMessage(Exception):
"""Raise this exception to show an error message to the user."""
def __init__(self, status, message):
self.status = status
self.message = message
class Redirect(Exception):
"""Raise this exception to redirect to another page."""
def __init__(self, url):
self.url = url
|
# Copyright 2009-2010 by Ka-Ping Yee
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common exception classes."""
import logging
class ErrorMessage(Exception):
"""Raise this exception to show an error message to the user."""
def __init__(self, status, message):
self.status = status
self.message = message
class Redirect(Exception):
"""Raise this exception to redirect to another page."""
def __init__(self, url):
self.url = url
Remove import logging. This file is now identical to the branch point.# Copyright 2009-2010 by Ka-Ping Yee
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common exception classes."""
class ErrorMessage(Exception):
"""Raise this exception to show an error message to the user."""
def __init__(self, status, message):
self.status = status
self.message = message
class Redirect(Exception):
"""Raise this exception to redirect to another page."""
def __init__(self, url):
self.url = url
|
<commit_before># Copyright 2009-2010 by Ka-Ping Yee
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common exception classes."""
import logging
class ErrorMessage(Exception):
"""Raise this exception to show an error message to the user."""
def __init__(self, status, message):
self.status = status
self.message = message
class Redirect(Exception):
"""Raise this exception to redirect to another page."""
def __init__(self, url):
self.url = url
<commit_msg>Remove import logging. This file is now identical to the branch point.<commit_after># Copyright 2009-2010 by Ka-Ping Yee
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common exception classes."""
class ErrorMessage(Exception):
"""Raise this exception to show an error message to the user."""
def __init__(self, status, message):
self.status = status
self.message = message
class Redirect(Exception):
"""Raise this exception to redirect to another page."""
def __init__(self, url):
self.url = url
|
fe692f0a3cdec2b3351c4e7742b115280a82343c
|
tests/unit/dashboard/voucher_form_tests.py
|
tests/unit/dashboard/voucher_form_tests.py
|
from django import test
from oscar.apps.dashboard.vouchers import forms
class TestVoucherForm(test.TestCase):
def test_handles_empty_date_fields(self):
data = {'code': '',
'name': '',
'start_date': '',
'end_date': '',
'benefit_range': '',
'benefit_type': 'Percentage',
'usage': 'Single use'}
form = forms.VoucherForm(data=data)
try:
form.is_valid()
except Exception as e:
import traceback
self.fail("Validating form failed: %s\n\n%s" % (
e.message, traceback.format_exc()))
|
from django import test
from oscar.apps.dashboard.vouchers import forms
class TestVoucherForm(test.TestCase):
def test_doesnt_crash_on_empty_date_fields(self):
"""
There was a bug fixed in 02b3644 where the voucher form would raise an
exception (instead of just failing validation) when being called with
empty fields. This tests exists to prevent a regression.
"""
data = {
'code': '',
'name': '',
'start_date': '',
'end_date': '',
'benefit_range': '',
'benefit_type': 'Percentage',
'usage': 'Single use',
}
form = forms.VoucherForm(data=data)
try:
form.is_valid()
except Exception as e:
import traceback
self.fail(
"Exception raised while validating voucher form: %s\n\n%s" % (
e.message, traceback.format_exc()))
|
Change wording for voucher form test
|
Change wording for voucher form test
I was confused by what the test does, and had to ask @codeinthehole to
explain. Hopefully made it's intention a bit clearer now.
|
Python
|
bsd-3-clause
|
rocopartners/django-oscar,sasha0/django-oscar,rocopartners/django-oscar,solarissmoke/django-oscar,dongguangming/django-oscar,itbabu/django-oscar,solarissmoke/django-oscar,bnprk/django-oscar,rocopartners/django-oscar,WillisXChen/django-oscar,lijoantony/django-oscar,bschuon/django-oscar,jlmadurga/django-oscar,machtfit/django-oscar,mexeniz/django-oscar,jinnykoo/wuyisj,bschuon/django-oscar,mexeniz/django-oscar,saadatqadri/django-oscar,anentropic/django-oscar,Bogh/django-oscar,taedori81/django-oscar,nickpack/django-oscar,pdonadeo/django-oscar,ademuk/django-oscar,dongguangming/django-oscar,jinnykoo/christmas,solarissmoke/django-oscar,thechampanurag/django-oscar,spartonia/django-oscar,kapari/django-oscar,michaelkuty/django-oscar,kapari/django-oscar,WillisXChen/django-oscar,solarissmoke/django-oscar,binarydud/django-oscar,eddiep1101/django-oscar,john-parton/django-oscar,jinnykoo/wuyisj.com,binarydud/django-oscar,faratro/django-oscar,jmt4/django-oscar,adamend/django-oscar,spartonia/django-oscar,Jannes123/django-oscar,taedori81/django-oscar,manevant/django-oscar,jinnykoo/christmas,spartonia/django-oscar,amirrpp/django-oscar,faratro/django-oscar,jinnykoo/christmas,MatthewWilkes/django-oscar,monikasulik/django-oscar,ka7eh/django-oscar,bnprk/django-oscar,monikasulik/django-oscar,nfletton/django-oscar,lijoantony/django-oscar,ahmetdaglarbas/e-commerce,QLGu/django-oscar,QLGu/django-oscar,MatthewWilkes/django-oscar,machtfit/django-oscar,jmt4/django-oscar,machtfit/django-oscar,pasqualguerrero/django-oscar,monikasulik/django-oscar,Bogh/django-oscar,okfish/django-oscar,pdonadeo/django-oscar,ademuk/django-oscar,pasqualguerrero/django-oscar,binarydud/django-oscar,kapt/django-oscar,WadeYuChen/django-oscar,faratro/django-oscar,QLGu/django-oscar,nfletton/django-oscar,bnprk/django-oscar,ahmetdaglarbas/e-commerce,nickpack/django-oscar,jlmadurga/django-oscar,john-parton/django-oscar,binarydud/django-oscar,Bogh/django-oscar,ahmetdaglarbas/e-commerce,anentropic/django-oscar,monikasulik/django-oscar,jinnykoo/wuyisj.com,itbabu/django-oscar,bschuon/django-oscar,WillisXChen/django-oscar,manevant/django-oscar,django-oscar/django-oscar,Jannes123/django-oscar,vovanbo/django-oscar,kapari/django-oscar,sasha0/django-oscar,saadatqadri/django-oscar,ka7eh/django-oscar,josesanch/django-oscar,adamend/django-oscar,WillisXChen/django-oscar,itbabu/django-oscar,nickpack/django-oscar,thechampanurag/django-oscar,sonofatailor/django-oscar,anentropic/django-oscar,taedori81/django-oscar,jinnykoo/wuyisj,vovanbo/django-oscar,anentropic/django-oscar,eddiep1101/django-oscar,okfish/django-oscar,MatthewWilkes/django-oscar,jinnykoo/wuyisj.com,ka7eh/django-oscar,pdonadeo/django-oscar,faratro/django-oscar,django-oscar/django-oscar,lijoantony/django-oscar,pdonadeo/django-oscar,sasha0/django-oscar,jmt4/django-oscar,sonofatailor/django-oscar,jlmadurga/django-oscar,adamend/django-oscar,mexeniz/django-oscar,dongguangming/django-oscar,Bogh/django-oscar,ademuk/django-oscar,ahmetdaglarbas/e-commerce,michaelkuty/django-oscar,john-parton/django-oscar,sonofatailor/django-oscar,amirrpp/django-oscar,ka7eh/django-oscar,jinnykoo/wuyisj,itbabu/django-oscar,lijoantony/django-oscar,jinnykoo/wuyisj.com,nfletton/django-oscar,bnprk/django-oscar,kapt/django-oscar,michaelkuty/django-oscar,WadeYuChen/django-oscar,WillisXChen/django-oscar,WadeYuChen/django-oscar,jinnykoo/wuyisj,pasqualguerrero/django-oscar,sonofatailor/django-oscar,amirrpp/django-oscar,josesanch/django-oscar,vovanbo/django-oscar,kapt/django-oscar,saadatqadri/django-oscar,dongguangming/django-oscar,WillisXChen/django-oscar,michaelkuty/django-oscar,mexeniz/django-oscar,bschuon/django-oscar,nfletton/django-oscar,amirrpp/django-oscar,Jannes123/django-oscar,manevant/django-oscar,eddiep1101/django-oscar,django-oscar/django-oscar,thechampanurag/django-oscar,okfish/django-oscar,nickpack/django-oscar,sasha0/django-oscar,jlmadurga/django-oscar,thechampanurag/django-oscar,saadatqadri/django-oscar,vovanbo/django-oscar,ademuk/django-oscar,Jannes123/django-oscar,jmt4/django-oscar,adamend/django-oscar,rocopartners/django-oscar,spartonia/django-oscar,WadeYuChen/django-oscar,MatthewWilkes/django-oscar,pasqualguerrero/django-oscar,okfish/django-oscar,josesanch/django-oscar,manevant/django-oscar,django-oscar/django-oscar,taedori81/django-oscar,kapari/django-oscar,eddiep1101/django-oscar,QLGu/django-oscar,john-parton/django-oscar
|
from django import test
from oscar.apps.dashboard.vouchers import forms
class TestVoucherForm(test.TestCase):
def test_handles_empty_date_fields(self):
data = {'code': '',
'name': '',
'start_date': '',
'end_date': '',
'benefit_range': '',
'benefit_type': 'Percentage',
'usage': 'Single use'}
form = forms.VoucherForm(data=data)
try:
form.is_valid()
except Exception as e:
import traceback
self.fail("Validating form failed: %s\n\n%s" % (
e.message, traceback.format_exc()))
Change wording for voucher form test
I was confused by what the test does, and had to ask @codeinthehole to
explain. Hopefully made it's intention a bit clearer now.
|
from django import test
from oscar.apps.dashboard.vouchers import forms
class TestVoucherForm(test.TestCase):
def test_doesnt_crash_on_empty_date_fields(self):
"""
There was a bug fixed in 02b3644 where the voucher form would raise an
exception (instead of just failing validation) when being called with
empty fields. This tests exists to prevent a regression.
"""
data = {
'code': '',
'name': '',
'start_date': '',
'end_date': '',
'benefit_range': '',
'benefit_type': 'Percentage',
'usage': 'Single use',
}
form = forms.VoucherForm(data=data)
try:
form.is_valid()
except Exception as e:
import traceback
self.fail(
"Exception raised while validating voucher form: %s\n\n%s" % (
e.message, traceback.format_exc()))
|
<commit_before>from django import test
from oscar.apps.dashboard.vouchers import forms
class TestVoucherForm(test.TestCase):
def test_handles_empty_date_fields(self):
data = {'code': '',
'name': '',
'start_date': '',
'end_date': '',
'benefit_range': '',
'benefit_type': 'Percentage',
'usage': 'Single use'}
form = forms.VoucherForm(data=data)
try:
form.is_valid()
except Exception as e:
import traceback
self.fail("Validating form failed: %s\n\n%s" % (
e.message, traceback.format_exc()))
<commit_msg>Change wording for voucher form test
I was confused by what the test does, and had to ask @codeinthehole to
explain. Hopefully made it's intention a bit clearer now.<commit_after>
|
from django import test
from oscar.apps.dashboard.vouchers import forms
class TestVoucherForm(test.TestCase):
def test_doesnt_crash_on_empty_date_fields(self):
"""
There was a bug fixed in 02b3644 where the voucher form would raise an
exception (instead of just failing validation) when being called with
empty fields. This tests exists to prevent a regression.
"""
data = {
'code': '',
'name': '',
'start_date': '',
'end_date': '',
'benefit_range': '',
'benefit_type': 'Percentage',
'usage': 'Single use',
}
form = forms.VoucherForm(data=data)
try:
form.is_valid()
except Exception as e:
import traceback
self.fail(
"Exception raised while validating voucher form: %s\n\n%s" % (
e.message, traceback.format_exc()))
|
from django import test
from oscar.apps.dashboard.vouchers import forms
class TestVoucherForm(test.TestCase):
def test_handles_empty_date_fields(self):
data = {'code': '',
'name': '',
'start_date': '',
'end_date': '',
'benefit_range': '',
'benefit_type': 'Percentage',
'usage': 'Single use'}
form = forms.VoucherForm(data=data)
try:
form.is_valid()
except Exception as e:
import traceback
self.fail("Validating form failed: %s\n\n%s" % (
e.message, traceback.format_exc()))
Change wording for voucher form test
I was confused by what the test does, and had to ask @codeinthehole to
explain. Hopefully made it's intention a bit clearer now.from django import test
from oscar.apps.dashboard.vouchers import forms
class TestVoucherForm(test.TestCase):
def test_doesnt_crash_on_empty_date_fields(self):
"""
There was a bug fixed in 02b3644 where the voucher form would raise an
exception (instead of just failing validation) when being called with
empty fields. This tests exists to prevent a regression.
"""
data = {
'code': '',
'name': '',
'start_date': '',
'end_date': '',
'benefit_range': '',
'benefit_type': 'Percentage',
'usage': 'Single use',
}
form = forms.VoucherForm(data=data)
try:
form.is_valid()
except Exception as e:
import traceback
self.fail(
"Exception raised while validating voucher form: %s\n\n%s" % (
e.message, traceback.format_exc()))
|
<commit_before>from django import test
from oscar.apps.dashboard.vouchers import forms
class TestVoucherForm(test.TestCase):
def test_handles_empty_date_fields(self):
data = {'code': '',
'name': '',
'start_date': '',
'end_date': '',
'benefit_range': '',
'benefit_type': 'Percentage',
'usage': 'Single use'}
form = forms.VoucherForm(data=data)
try:
form.is_valid()
except Exception as e:
import traceback
self.fail("Validating form failed: %s\n\n%s" % (
e.message, traceback.format_exc()))
<commit_msg>Change wording for voucher form test
I was confused by what the test does, and had to ask @codeinthehole to
explain. Hopefully made it's intention a bit clearer now.<commit_after>from django import test
from oscar.apps.dashboard.vouchers import forms
class TestVoucherForm(test.TestCase):
def test_doesnt_crash_on_empty_date_fields(self):
"""
There was a bug fixed in 02b3644 where the voucher form would raise an
exception (instead of just failing validation) when being called with
empty fields. This tests exists to prevent a regression.
"""
data = {
'code': '',
'name': '',
'start_date': '',
'end_date': '',
'benefit_range': '',
'benefit_type': 'Percentage',
'usage': 'Single use',
}
form = forms.VoucherForm(data=data)
try:
form.is_valid()
except Exception as e:
import traceback
self.fail(
"Exception raised while validating voucher form: %s\n\n%s" % (
e.message, traceback.format_exc()))
|
0eac6cb99624b5404824a5fbbfddc7e520cdb535
|
pyconde/search/search_indexes.py
|
pyconde/search/search_indexes.py
|
import re
from django.test.client import RequestFactory
from django.template import RequestContext
from haystack import indexes
from cms import models as cmsmodels
rf = RequestFactory()
HTML_TAG_RE = re.compile(r'<[^>]+>')
def cleanup_content(s):
"""
Removes HTML tags from data and replaces them with spaces.
"""
return HTML_TAG_RE.subn('', s)[0]
class PageIndex(indexes.SearchIndex, indexes.Indexable):
"""
Since for now we only offer this site in one language, we can get around
by not doing any language model hacks.
"""
text = indexes.CharField(document=True)
title = indexes.CharField()
url = indexes.CharField()
def get_model(self):
return cmsmodels.Page
def index_queryset(self, using=None):
return self.get_model().objects.filter(published=True)
def prepare(self, obj):
self.prepared_data = super(PageIndex, self).prepare(obj)
request = rf.get('/')
request.session = {}
text = u""
# Let's extract the title
context = RequestContext(request)
for title in obj.title_set.all():
self.prepared_data['title'] = title.title
for placeholder in obj.placeholders.all():
text += placeholder.render(context, None)
self.prepared_data['text'] = cleanup_content(
self.prepared_data['title'] + text)
self.prepared_data['url'] = obj.get_absolute_url()
return self.prepared_data
|
import re
from django.test.client import RequestFactory
from django.template import RequestContext
from haystack import indexes
from cms import models as cmsmodels
rf = RequestFactory()
HTML_TAG_RE = re.compile(r'<[^>]+>')
def cleanup_content(s):
"""
Removes HTML tags from data and replaces them with spaces.
"""
return HTML_TAG_RE.subn('', s)[0]
class PageIndex(indexes.SearchIndex, indexes.Indexable):
"""
Since for now we only offer this site in one language, we can get around
by not doing any language model hacks.
"""
text = indexes.CharField(document=True)
title = indexes.CharField()
url = indexes.CharField()
def get_model(self):
return cmsmodels.Page
def index_queryset(self, using=None):
return self.get_model().objects.filter(published=True)
def prepare(self, obj):
self.prepared_data = super(PageIndex, self).prepare(obj)
request = rf.get('/')
request.session = {}
text = u""
# Let's extract the title
context = RequestContext(request)
for title in obj.title_set.all():
self.prepared_data['title'] = title.title
for placeholder in obj.placeholders.all():
text += placeholder.render(context, None)
self.prepared_data['text'] = cleanup_content(
self.prepared_data['title'] + u' ' + text)
self.prepared_data['url'] = obj.get_absolute_url()
return self.prepared_data
|
Add whitespace between title and text for search index.
|
Add whitespace between title and text for search index.
|
Python
|
bsd-3-clause
|
pysv/djep,pysv/djep,EuroPython/djep,zerok/pyconde-website-mirror,zerok/pyconde-website-mirror,zerok/pyconde-website-mirror,EuroPython/djep,pysv/djep,EuroPython/djep,EuroPython/djep,pysv/djep,pysv/djep
|
import re
from django.test.client import RequestFactory
from django.template import RequestContext
from haystack import indexes
from cms import models as cmsmodels
rf = RequestFactory()
HTML_TAG_RE = re.compile(r'<[^>]+>')
def cleanup_content(s):
"""
Removes HTML tags from data and replaces them with spaces.
"""
return HTML_TAG_RE.subn('', s)[0]
class PageIndex(indexes.SearchIndex, indexes.Indexable):
"""
Since for now we only offer this site in one language, we can get around
by not doing any language model hacks.
"""
text = indexes.CharField(document=True)
title = indexes.CharField()
url = indexes.CharField()
def get_model(self):
return cmsmodels.Page
def index_queryset(self, using=None):
return self.get_model().objects.filter(published=True)
def prepare(self, obj):
self.prepared_data = super(PageIndex, self).prepare(obj)
request = rf.get('/')
request.session = {}
text = u""
# Let's extract the title
context = RequestContext(request)
for title in obj.title_set.all():
self.prepared_data['title'] = title.title
for placeholder in obj.placeholders.all():
text += placeholder.render(context, None)
self.prepared_data['text'] = cleanup_content(
self.prepared_data['title'] + text)
self.prepared_data['url'] = obj.get_absolute_url()
return self.prepared_data
Add whitespace between title and text for search index.
|
import re
from django.test.client import RequestFactory
from django.template import RequestContext
from haystack import indexes
from cms import models as cmsmodels
rf = RequestFactory()
HTML_TAG_RE = re.compile(r'<[^>]+>')
def cleanup_content(s):
"""
Removes HTML tags from data and replaces them with spaces.
"""
return HTML_TAG_RE.subn('', s)[0]
class PageIndex(indexes.SearchIndex, indexes.Indexable):
"""
Since for now we only offer this site in one language, we can get around
by not doing any language model hacks.
"""
text = indexes.CharField(document=True)
title = indexes.CharField()
url = indexes.CharField()
def get_model(self):
return cmsmodels.Page
def index_queryset(self, using=None):
return self.get_model().objects.filter(published=True)
def prepare(self, obj):
self.prepared_data = super(PageIndex, self).prepare(obj)
request = rf.get('/')
request.session = {}
text = u""
# Let's extract the title
context = RequestContext(request)
for title in obj.title_set.all():
self.prepared_data['title'] = title.title
for placeholder in obj.placeholders.all():
text += placeholder.render(context, None)
self.prepared_data['text'] = cleanup_content(
self.prepared_data['title'] + u' ' + text)
self.prepared_data['url'] = obj.get_absolute_url()
return self.prepared_data
|
<commit_before>import re
from django.test.client import RequestFactory
from django.template import RequestContext
from haystack import indexes
from cms import models as cmsmodels
rf = RequestFactory()
HTML_TAG_RE = re.compile(r'<[^>]+>')
def cleanup_content(s):
"""
Removes HTML tags from data and replaces them with spaces.
"""
return HTML_TAG_RE.subn('', s)[0]
class PageIndex(indexes.SearchIndex, indexes.Indexable):
"""
Since for now we only offer this site in one language, we can get around
by not doing any language model hacks.
"""
text = indexes.CharField(document=True)
title = indexes.CharField()
url = indexes.CharField()
def get_model(self):
return cmsmodels.Page
def index_queryset(self, using=None):
return self.get_model().objects.filter(published=True)
def prepare(self, obj):
self.prepared_data = super(PageIndex, self).prepare(obj)
request = rf.get('/')
request.session = {}
text = u""
# Let's extract the title
context = RequestContext(request)
for title in obj.title_set.all():
self.prepared_data['title'] = title.title
for placeholder in obj.placeholders.all():
text += placeholder.render(context, None)
self.prepared_data['text'] = cleanup_content(
self.prepared_data['title'] + text)
self.prepared_data['url'] = obj.get_absolute_url()
return self.prepared_data
<commit_msg>Add whitespace between title and text for search index.<commit_after>
|
import re
from django.test.client import RequestFactory
from django.template import RequestContext
from haystack import indexes
from cms import models as cmsmodels
rf = RequestFactory()
HTML_TAG_RE = re.compile(r'<[^>]+>')
def cleanup_content(s):
"""
Removes HTML tags from data and replaces them with spaces.
"""
return HTML_TAG_RE.subn('', s)[0]
class PageIndex(indexes.SearchIndex, indexes.Indexable):
"""
Since for now we only offer this site in one language, we can get around
by not doing any language model hacks.
"""
text = indexes.CharField(document=True)
title = indexes.CharField()
url = indexes.CharField()
def get_model(self):
return cmsmodels.Page
def index_queryset(self, using=None):
return self.get_model().objects.filter(published=True)
def prepare(self, obj):
self.prepared_data = super(PageIndex, self).prepare(obj)
request = rf.get('/')
request.session = {}
text = u""
# Let's extract the title
context = RequestContext(request)
for title in obj.title_set.all():
self.prepared_data['title'] = title.title
for placeholder in obj.placeholders.all():
text += placeholder.render(context, None)
self.prepared_data['text'] = cleanup_content(
self.prepared_data['title'] + u' ' + text)
self.prepared_data['url'] = obj.get_absolute_url()
return self.prepared_data
|
import re
from django.test.client import RequestFactory
from django.template import RequestContext
from haystack import indexes
from cms import models as cmsmodels
rf = RequestFactory()
HTML_TAG_RE = re.compile(r'<[^>]+>')
def cleanup_content(s):
"""
Removes HTML tags from data and replaces them with spaces.
"""
return HTML_TAG_RE.subn('', s)[0]
class PageIndex(indexes.SearchIndex, indexes.Indexable):
"""
Since for now we only offer this site in one language, we can get around
by not doing any language model hacks.
"""
text = indexes.CharField(document=True)
title = indexes.CharField()
url = indexes.CharField()
def get_model(self):
return cmsmodels.Page
def index_queryset(self, using=None):
return self.get_model().objects.filter(published=True)
def prepare(self, obj):
self.prepared_data = super(PageIndex, self).prepare(obj)
request = rf.get('/')
request.session = {}
text = u""
# Let's extract the title
context = RequestContext(request)
for title in obj.title_set.all():
self.prepared_data['title'] = title.title
for placeholder in obj.placeholders.all():
text += placeholder.render(context, None)
self.prepared_data['text'] = cleanup_content(
self.prepared_data['title'] + text)
self.prepared_data['url'] = obj.get_absolute_url()
return self.prepared_data
Add whitespace between title and text for search index.import re
from django.test.client import RequestFactory
from django.template import RequestContext
from haystack import indexes
from cms import models as cmsmodels
rf = RequestFactory()
HTML_TAG_RE = re.compile(r'<[^>]+>')
def cleanup_content(s):
"""
Removes HTML tags from data and replaces them with spaces.
"""
return HTML_TAG_RE.subn('', s)[0]
class PageIndex(indexes.SearchIndex, indexes.Indexable):
"""
Since for now we only offer this site in one language, we can get around
by not doing any language model hacks.
"""
text = indexes.CharField(document=True)
title = indexes.CharField()
url = indexes.CharField()
def get_model(self):
return cmsmodels.Page
def index_queryset(self, using=None):
return self.get_model().objects.filter(published=True)
def prepare(self, obj):
self.prepared_data = super(PageIndex, self).prepare(obj)
request = rf.get('/')
request.session = {}
text = u""
# Let's extract the title
context = RequestContext(request)
for title in obj.title_set.all():
self.prepared_data['title'] = title.title
for placeholder in obj.placeholders.all():
text += placeholder.render(context, None)
self.prepared_data['text'] = cleanup_content(
self.prepared_data['title'] + u' ' + text)
self.prepared_data['url'] = obj.get_absolute_url()
return self.prepared_data
|
<commit_before>import re
from django.test.client import RequestFactory
from django.template import RequestContext
from haystack import indexes
from cms import models as cmsmodels
rf = RequestFactory()
HTML_TAG_RE = re.compile(r'<[^>]+>')
def cleanup_content(s):
"""
Removes HTML tags from data and replaces them with spaces.
"""
return HTML_TAG_RE.subn('', s)[0]
class PageIndex(indexes.SearchIndex, indexes.Indexable):
"""
Since for now we only offer this site in one language, we can get around
by not doing any language model hacks.
"""
text = indexes.CharField(document=True)
title = indexes.CharField()
url = indexes.CharField()
def get_model(self):
return cmsmodels.Page
def index_queryset(self, using=None):
return self.get_model().objects.filter(published=True)
def prepare(self, obj):
self.prepared_data = super(PageIndex, self).prepare(obj)
request = rf.get('/')
request.session = {}
text = u""
# Let's extract the title
context = RequestContext(request)
for title in obj.title_set.all():
self.prepared_data['title'] = title.title
for placeholder in obj.placeholders.all():
text += placeholder.render(context, None)
self.prepared_data['text'] = cleanup_content(
self.prepared_data['title'] + text)
self.prepared_data['url'] = obj.get_absolute_url()
return self.prepared_data
<commit_msg>Add whitespace between title and text for search index.<commit_after>import re
from django.test.client import RequestFactory
from django.template import RequestContext
from haystack import indexes
from cms import models as cmsmodels
rf = RequestFactory()
HTML_TAG_RE = re.compile(r'<[^>]+>')
def cleanup_content(s):
"""
Removes HTML tags from data and replaces them with spaces.
"""
return HTML_TAG_RE.subn('', s)[0]
class PageIndex(indexes.SearchIndex, indexes.Indexable):
"""
Since for now we only offer this site in one language, we can get around
by not doing any language model hacks.
"""
text = indexes.CharField(document=True)
title = indexes.CharField()
url = indexes.CharField()
def get_model(self):
return cmsmodels.Page
def index_queryset(self, using=None):
return self.get_model().objects.filter(published=True)
def prepare(self, obj):
self.prepared_data = super(PageIndex, self).prepare(obj)
request = rf.get('/')
request.session = {}
text = u""
# Let's extract the title
context = RequestContext(request)
for title in obj.title_set.all():
self.prepared_data['title'] = title.title
for placeholder in obj.placeholders.all():
text += placeholder.render(context, None)
self.prepared_data['text'] = cleanup_content(
self.prepared_data['title'] + u' ' + text)
self.prepared_data['url'] = obj.get_absolute_url()
return self.prepared_data
|
8ab7e02668f60c67534bc0f9e986347c9b84ed50
|
climlab/__init__.py
|
climlab/__init__.py
|
__version__ = '0.3.0a'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convadj"]
#from climlab import radiation
# this should ensure that we can still import constants.py as climlab.constants
from climlab.utils import constants
from climlab.utils import thermo, legendre
# some more useful shorcuts
#from climlab.model import ebm, column
from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel
from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal
from climlab.domain import domain
from climlab.domain.field import Field, global_mean
from climlab.domain.axis import Axis
from climlab.domain.initial import column_state, surface_state
from climlab.process.process import Process, process_like, get_axes
from climlab.process.time_dependent_process import TimeDependentProcess
from climlab.process.implicit import ImplicitProcess
from climlab.process.diagnostic import DiagnosticProcess
from climlab.process.energy_budget import EnergyBudget
|
__version__ = '0.3.0.1'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convadj"]
#from climlab import radiation
# this should ensure that we can still import constants.py as climlab.constants
from climlab.utils import constants
from climlab.utils import thermo, legendre
# some more useful shorcuts
#from climlab.model import ebm, column
from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel
from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal
from climlab.domain import domain
from climlab.domain.field import Field, global_mean
from climlab.domain.axis import Axis
from climlab.domain.initial import column_state, surface_state
from climlab.process.process import Process, process_like, get_axes
from climlab.process.time_dependent_process import TimeDependentProcess
from climlab.process.implicit import ImplicitProcess
from climlab.process.diagnostic import DiagnosticProcess
from climlab.process.energy_budget import EnergyBudget
|
Change version number to 0.3.0.1
|
Change version number to 0.3.0.1
|
Python
|
mit
|
brian-rose/climlab,cjcardinale/climlab,brian-rose/climlab,cjcardinale/climlab,cjcardinale/climlab
|
__version__ = '0.3.0a'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convadj"]
#from climlab import radiation
# this should ensure that we can still import constants.py as climlab.constants
from climlab.utils import constants
from climlab.utils import thermo, legendre
# some more useful shorcuts
#from climlab.model import ebm, column
from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel
from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal
from climlab.domain import domain
from climlab.domain.field import Field, global_mean
from climlab.domain.axis import Axis
from climlab.domain.initial import column_state, surface_state
from climlab.process.process import Process, process_like, get_axes
from climlab.process.time_dependent_process import TimeDependentProcess
from climlab.process.implicit import ImplicitProcess
from climlab.process.diagnostic import DiagnosticProcess
from climlab.process.energy_budget import EnergyBudget
Change version number to 0.3.0.1
|
__version__ = '0.3.0.1'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convadj"]
#from climlab import radiation
# this should ensure that we can still import constants.py as climlab.constants
from climlab.utils import constants
from climlab.utils import thermo, legendre
# some more useful shorcuts
#from climlab.model import ebm, column
from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel
from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal
from climlab.domain import domain
from climlab.domain.field import Field, global_mean
from climlab.domain.axis import Axis
from climlab.domain.initial import column_state, surface_state
from climlab.process.process import Process, process_like, get_axes
from climlab.process.time_dependent_process import TimeDependentProcess
from climlab.process.implicit import ImplicitProcess
from climlab.process.diagnostic import DiagnosticProcess
from climlab.process.energy_budget import EnergyBudget
|
<commit_before>__version__ = '0.3.0a'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convadj"]
#from climlab import radiation
# this should ensure that we can still import constants.py as climlab.constants
from climlab.utils import constants
from climlab.utils import thermo, legendre
# some more useful shorcuts
#from climlab.model import ebm, column
from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel
from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal
from climlab.domain import domain
from climlab.domain.field import Field, global_mean
from climlab.domain.axis import Axis
from climlab.domain.initial import column_state, surface_state
from climlab.process.process import Process, process_like, get_axes
from climlab.process.time_dependent_process import TimeDependentProcess
from climlab.process.implicit import ImplicitProcess
from climlab.process.diagnostic import DiagnosticProcess
from climlab.process.energy_budget import EnergyBudget
<commit_msg>Change version number to 0.3.0.1<commit_after>
|
__version__ = '0.3.0.1'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convadj"]
#from climlab import radiation
# this should ensure that we can still import constants.py as climlab.constants
from climlab.utils import constants
from climlab.utils import thermo, legendre
# some more useful shorcuts
#from climlab.model import ebm, column
from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel
from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal
from climlab.domain import domain
from climlab.domain.field import Field, global_mean
from climlab.domain.axis import Axis
from climlab.domain.initial import column_state, surface_state
from climlab.process.process import Process, process_like, get_axes
from climlab.process.time_dependent_process import TimeDependentProcess
from climlab.process.implicit import ImplicitProcess
from climlab.process.diagnostic import DiagnosticProcess
from climlab.process.energy_budget import EnergyBudget
|
__version__ = '0.3.0a'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convadj"]
#from climlab import radiation
# this should ensure that we can still import constants.py as climlab.constants
from climlab.utils import constants
from climlab.utils import thermo, legendre
# some more useful shorcuts
#from climlab.model import ebm, column
from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel
from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal
from climlab.domain import domain
from climlab.domain.field import Field, global_mean
from climlab.domain.axis import Axis
from climlab.domain.initial import column_state, surface_state
from climlab.process.process import Process, process_like, get_axes
from climlab.process.time_dependent_process import TimeDependentProcess
from climlab.process.implicit import ImplicitProcess
from climlab.process.diagnostic import DiagnosticProcess
from climlab.process.energy_budget import EnergyBudget
Change version number to 0.3.0.1__version__ = '0.3.0.1'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convadj"]
#from climlab import radiation
# this should ensure that we can still import constants.py as climlab.constants
from climlab.utils import constants
from climlab.utils import thermo, legendre
# some more useful shorcuts
#from climlab.model import ebm, column
from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel
from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal
from climlab.domain import domain
from climlab.domain.field import Field, global_mean
from climlab.domain.axis import Axis
from climlab.domain.initial import column_state, surface_state
from climlab.process.process import Process, process_like, get_axes
from climlab.process.time_dependent_process import TimeDependentProcess
from climlab.process.implicit import ImplicitProcess
from climlab.process.diagnostic import DiagnosticProcess
from climlab.process.energy_budget import EnergyBudget
|
<commit_before>__version__ = '0.3.0a'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convadj"]
#from climlab import radiation
# this should ensure that we can still import constants.py as climlab.constants
from climlab.utils import constants
from climlab.utils import thermo, legendre
# some more useful shorcuts
#from climlab.model import ebm, column
from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel
from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal
from climlab.domain import domain
from climlab.domain.field import Field, global_mean
from climlab.domain.axis import Axis
from climlab.domain.initial import column_state, surface_state
from climlab.process.process import Process, process_like, get_axes
from climlab.process.time_dependent_process import TimeDependentProcess
from climlab.process.implicit import ImplicitProcess
from climlab.process.diagnostic import DiagnosticProcess
from climlab.process.energy_budget import EnergyBudget
<commit_msg>Change version number to 0.3.0.1<commit_after>__version__ = '0.3.0.1'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convadj"]
#from climlab import radiation
# this should ensure that we can still import constants.py as climlab.constants
from climlab.utils import constants
from climlab.utils import thermo, legendre
# some more useful shorcuts
#from climlab.model import ebm, column
from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel
from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal
from climlab.domain import domain
from climlab.domain.field import Field, global_mean
from climlab.domain.axis import Axis
from climlab.domain.initial import column_state, surface_state
from climlab.process.process import Process, process_like, get_axes
from climlab.process.time_dependent_process import TimeDependentProcess
from climlab.process.implicit import ImplicitProcess
from climlab.process.diagnostic import DiagnosticProcess
from climlab.process.energy_budget import EnergyBudget
|
6a1846c91a5829d0b41ca3f81f797e9f4aa26d6e
|
misura/canon/plugin/__init__.py
|
misura/canon/plugin/__init__.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Plugin utilities"""
from domains import NavigatorDomain, navigator_domains, node, nodes
from dataimport import Converter, create_tree, create_dataset, search_registry, get_converter, convert_file, data_importers
# List of functions which will be executed to update confdb and extend its options
clientconf_update_functions = []
# Mapping of instrument:DefaultPlotPlugin names
default_plot_plugins = {}
# Mapping of instrument: plotting rule generating function
default_plot_rules = {}
load_rules = []
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Plugin utilities"""
from domains import NavigatorDomain, navigator_domains, node, nodes
from dataimport import Converter, create_tree, create_dataset, search_registry, get_converter, convert_file, data_importers
# List of functions which will be executed to update confdb and extend its options
clientconf_update_functions = []
# Mapping of instrument:DefaultPlotPlugin names
default_plot_plugins = {}
# Mapping of instrument: plotting rule generating function
default_plot_rules = {}
|
Remove obsolete load_rules definition, FLTD-196
|
Remove obsolete load_rules definition, FLTD-196
|
Python
|
mit
|
tainstr/misura.canon,tainstr/misura.canon
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Plugin utilities"""
from domains import NavigatorDomain, navigator_domains, node, nodes
from dataimport import Converter, create_tree, create_dataset, search_registry, get_converter, convert_file, data_importers
# List of functions which will be executed to update confdb and extend its options
clientconf_update_functions = []
# Mapping of instrument:DefaultPlotPlugin names
default_plot_plugins = {}
# Mapping of instrument: plotting rule generating function
default_plot_rules = {}
load_rules = []Remove obsolete load_rules definition, FLTD-196
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Plugin utilities"""
from domains import NavigatorDomain, navigator_domains, node, nodes
from dataimport import Converter, create_tree, create_dataset, search_registry, get_converter, convert_file, data_importers
# List of functions which will be executed to update confdb and extend its options
clientconf_update_functions = []
# Mapping of instrument:DefaultPlotPlugin names
default_plot_plugins = {}
# Mapping of instrument: plotting rule generating function
default_plot_rules = {}
|
<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Plugin utilities"""
from domains import NavigatorDomain, navigator_domains, node, nodes
from dataimport import Converter, create_tree, create_dataset, search_registry, get_converter, convert_file, data_importers
# List of functions which will be executed to update confdb and extend its options
clientconf_update_functions = []
# Mapping of instrument:DefaultPlotPlugin names
default_plot_plugins = {}
# Mapping of instrument: plotting rule generating function
default_plot_rules = {}
load_rules = []<commit_msg>Remove obsolete load_rules definition, FLTD-196<commit_after>
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Plugin utilities"""
from domains import NavigatorDomain, navigator_domains, node, nodes
from dataimport import Converter, create_tree, create_dataset, search_registry, get_converter, convert_file, data_importers
# List of functions which will be executed to update confdb and extend its options
clientconf_update_functions = []
# Mapping of instrument:DefaultPlotPlugin names
default_plot_plugins = {}
# Mapping of instrument: plotting rule generating function
default_plot_rules = {}
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Plugin utilities"""
from domains import NavigatorDomain, navigator_domains, node, nodes
from dataimport import Converter, create_tree, create_dataset, search_registry, get_converter, convert_file, data_importers
# List of functions which will be executed to update confdb and extend its options
clientconf_update_functions = []
# Mapping of instrument:DefaultPlotPlugin names
default_plot_plugins = {}
# Mapping of instrument: plotting rule generating function
default_plot_rules = {}
load_rules = []Remove obsolete load_rules definition, FLTD-196#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Plugin utilities"""
from domains import NavigatorDomain, navigator_domains, node, nodes
from dataimport import Converter, create_tree, create_dataset, search_registry, get_converter, convert_file, data_importers
# List of functions which will be executed to update confdb and extend its options
clientconf_update_functions = []
# Mapping of instrument:DefaultPlotPlugin names
default_plot_plugins = {}
# Mapping of instrument: plotting rule generating function
default_plot_rules = {}
|
<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Plugin utilities"""
from domains import NavigatorDomain, navigator_domains, node, nodes
from dataimport import Converter, create_tree, create_dataset, search_registry, get_converter, convert_file, data_importers
# List of functions which will be executed to update confdb and extend its options
clientconf_update_functions = []
# Mapping of instrument:DefaultPlotPlugin names
default_plot_plugins = {}
# Mapping of instrument: plotting rule generating function
default_plot_rules = {}
load_rules = []<commit_msg>Remove obsolete load_rules definition, FLTD-196<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Plugin utilities"""
from domains import NavigatorDomain, navigator_domains, node, nodes
from dataimport import Converter, create_tree, create_dataset, search_registry, get_converter, convert_file, data_importers
# List of functions which will be executed to update confdb and extend its options
clientconf_update_functions = []
# Mapping of instrument:DefaultPlotPlugin names
default_plot_plugins = {}
# Mapping of instrument: plotting rule generating function
default_plot_rules = {}
|
2c6bda335b48ca290070a629c5582b19751c524a
|
salt/modules/ftp.py
|
salt/modules/ftp.py
|
'''
Minion side functions for salt-ftp
'''
import os
def recv(files, dest):
'''
Used with salt-ftp, pass the files dict, and the destination
'''
if not os.path.isdir(dest) or not os.path.isdir(os.path.dirname(dest)):
return 'Destination not available'
ret = {}
for path, data in files.items():
final = ''
if os.path.basename(path) == os.path.basename(dest)\
and not os.path.isdir(dest):
final = dest
elif os.path.isdir(dest):
final = os.path.join(dest, os.path.basename(path))
else:
return 'Destination not available'
try:
open(final, 'w+').write(data)
ret[final] = True
except IOError:
ret[final] = False
return ret
|
'''
Minion side functions for salt-ftp
'''
import os
def recv(files, dest):
'''
Used with salt-ftp, pass the files dict, and the destination
'''
if not os.path.isdir(dest) or not os.path.isdir(os.path.dirname(dest)):
return 'Destination not available'
ret = {}
for path, data in files.items():
final = ''
if os.path.basename(path) == os.path.basename(dest)\
and not os.path.isdir(dest):
final = dest
elif os.path.isdir(dest):
final = os.path.join(dest, os.path.basename(path))
elif os.path.isdir(os.path.dirname(dest)):
final = dest
else:
return 'Destination not available'
try:
open(final, 'w+').write(data)
ret[final] = True
except IOError:
ret[final] = False
return ret
|
Make naming the destination file work
|
Make naming the destination file work
|
Python
|
apache-2.0
|
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
|
'''
Minion side functions for salt-ftp
'''
import os
def recv(files, dest):
'''
Used with salt-ftp, pass the files dict, and the destination
'''
if not os.path.isdir(dest) or not os.path.isdir(os.path.dirname(dest)):
return 'Destination not available'
ret = {}
for path, data in files.items():
final = ''
if os.path.basename(path) == os.path.basename(dest)\
and not os.path.isdir(dest):
final = dest
elif os.path.isdir(dest):
final = os.path.join(dest, os.path.basename(path))
else:
return 'Destination not available'
try:
open(final, 'w+').write(data)
ret[final] = True
except IOError:
ret[final] = False
return ret
Make naming the destination file work
|
'''
Minion side functions for salt-ftp
'''
import os
def recv(files, dest):
'''
Used with salt-ftp, pass the files dict, and the destination
'''
if not os.path.isdir(dest) or not os.path.isdir(os.path.dirname(dest)):
return 'Destination not available'
ret = {}
for path, data in files.items():
final = ''
if os.path.basename(path) == os.path.basename(dest)\
and not os.path.isdir(dest):
final = dest
elif os.path.isdir(dest):
final = os.path.join(dest, os.path.basename(path))
elif os.path.isdir(os.path.dirname(dest)):
final = dest
else:
return 'Destination not available'
try:
open(final, 'w+').write(data)
ret[final] = True
except IOError:
ret[final] = False
return ret
|
<commit_before>'''
Minion side functions for salt-ftp
'''
import os
def recv(files, dest):
'''
Used with salt-ftp, pass the files dict, and the destination
'''
if not os.path.isdir(dest) or not os.path.isdir(os.path.dirname(dest)):
return 'Destination not available'
ret = {}
for path, data in files.items():
final = ''
if os.path.basename(path) == os.path.basename(dest)\
and not os.path.isdir(dest):
final = dest
elif os.path.isdir(dest):
final = os.path.join(dest, os.path.basename(path))
else:
return 'Destination not available'
try:
open(final, 'w+').write(data)
ret[final] = True
except IOError:
ret[final] = False
return ret
<commit_msg>Make naming the destination file work<commit_after>
|
'''
Minion side functions for salt-ftp
'''
import os
def recv(files, dest):
'''
Used with salt-ftp, pass the files dict, and the destination
'''
if not os.path.isdir(dest) or not os.path.isdir(os.path.dirname(dest)):
return 'Destination not available'
ret = {}
for path, data in files.items():
final = ''
if os.path.basename(path) == os.path.basename(dest)\
and not os.path.isdir(dest):
final = dest
elif os.path.isdir(dest):
final = os.path.join(dest, os.path.basename(path))
elif os.path.isdir(os.path.dirname(dest)):
final = dest
else:
return 'Destination not available'
try:
open(final, 'w+').write(data)
ret[final] = True
except IOError:
ret[final] = False
return ret
|
'''
Minion side functions for salt-ftp
'''
import os
def recv(files, dest):
'''
Used with salt-ftp, pass the files dict, and the destination
'''
if not os.path.isdir(dest) or not os.path.isdir(os.path.dirname(dest)):
return 'Destination not available'
ret = {}
for path, data in files.items():
final = ''
if os.path.basename(path) == os.path.basename(dest)\
and not os.path.isdir(dest):
final = dest
elif os.path.isdir(dest):
final = os.path.join(dest, os.path.basename(path))
else:
return 'Destination not available'
try:
open(final, 'w+').write(data)
ret[final] = True
except IOError:
ret[final] = False
return ret
Make naming the destination file work'''
Minion side functions for salt-ftp
'''
import os
def recv(files, dest):
'''
Used with salt-ftp, pass the files dict, and the destination
'''
if not os.path.isdir(dest) or not os.path.isdir(os.path.dirname(dest)):
return 'Destination not available'
ret = {}
for path, data in files.items():
final = ''
if os.path.basename(path) == os.path.basename(dest)\
and not os.path.isdir(dest):
final = dest
elif os.path.isdir(dest):
final = os.path.join(dest, os.path.basename(path))
elif os.path.isdir(os.path.dirname(dest)):
final = dest
else:
return 'Destination not available'
try:
open(final, 'w+').write(data)
ret[final] = True
except IOError:
ret[final] = False
return ret
|
<commit_before>'''
Minion side functions for salt-ftp
'''
import os
def recv(files, dest):
'''
Used with salt-ftp, pass the files dict, and the destination
'''
if not os.path.isdir(dest) or not os.path.isdir(os.path.dirname(dest)):
return 'Destination not available'
ret = {}
for path, data in files.items():
final = ''
if os.path.basename(path) == os.path.basename(dest)\
and not os.path.isdir(dest):
final = dest
elif os.path.isdir(dest):
final = os.path.join(dest, os.path.basename(path))
else:
return 'Destination not available'
try:
open(final, 'w+').write(data)
ret[final] = True
except IOError:
ret[final] = False
return ret
<commit_msg>Make naming the destination file work<commit_after>'''
Minion side functions for salt-ftp
'''
import os
def recv(files, dest):
'''
Used with salt-ftp, pass the files dict, and the destination
'''
if not os.path.isdir(dest) or not os.path.isdir(os.path.dirname(dest)):
return 'Destination not available'
ret = {}
for path, data in files.items():
final = ''
if os.path.basename(path) == os.path.basename(dest)\
and not os.path.isdir(dest):
final = dest
elif os.path.isdir(dest):
final = os.path.join(dest, os.path.basename(path))
elif os.path.isdir(os.path.dirname(dest)):
final = dest
else:
return 'Destination not available'
try:
open(final, 'w+').write(data)
ret[final] = True
except IOError:
ret[final] = False
return ret
|
33154ad8decc2848ce30444ec51615397a4d8d37
|
src/clusto/test/testbase.py
|
src/clusto/test/testbase.py
|
import sys
import os
sys.path.insert(0, os.curdir)
import unittest
import clusto
import ConfigParser
DB='sqlite:///:memory:'
ECHO=False
class ClustoTestResult(unittest.TestResult):
def addError(self, test, err):
"""Called when an error has occurred. 'err' is a tuple of values as
returned by sys.exc_info().
"""
print >>sys.stderr, "ERROR HERE!"
clusto.rollback_transaction()
self.errors.append((test, self._exc_info_to_string(err, test)))
class ClustoTestBase(unittest.TestCase):
def data(self):
pass
def setUp(self):
conf = ConfigParser.ConfigParser()
conf.add_section('clusto')
conf.set('clusto', 'dsn', DB)
clusto.connect(conf,echo=ECHO)
clusto.clear()
clusto.SESSION.close()
clusto.init_clusto()
self.data()
def tearDown(self):
if clusto.SESSION.is_active:
raise Exception("SESSION IS STILL ACTIVE in %s" % str(self.__class__))
clusto.clear()
clusto.disconnect()
clusto.METADATA.drop_all(clusto.SESSION.bind)
def defaultTestResult(self):
if not hasattr(self._testresult):
self._testresult = ClustoTestResult()
return self._testresult
|
import sys
import os
sys.path.insert(0, os.curdir)
import unittest
import clusto
import ConfigParser
DB='sqlite:///:memory:'
ECHO=False
class ClustoTestResult(unittest.TestResult):
def addError(self, test, err):
"""Called when an error has occurred. 'err' is a tuple of values as
returned by sys.exc_info().
"""
print >>sys.stderr, "ERROR HERE!"
clusto.rollback_transaction()
self.errors.append((test, self._exc_info_to_string(err, test)))
class ClustoTestBase(unittest.TestCase):
def data(self):
pass
def setUp(self):
conf = ConfigParser.ConfigParser()
conf.add_section('clusto')
conf.set('clusto', 'dsn', DB)
conf.set('clusto', 'versioning', '1')
clusto.connect(conf,echo=ECHO)
clusto.clear()
clusto.SESSION.close()
clusto.init_clusto()
self.data()
def tearDown(self):
if clusto.SESSION.is_active:
raise Exception("SESSION IS STILL ACTIVE in %s" % str(self.__class__))
clusto.clear()
clusto.disconnect()
clusto.METADATA.drop_all(clusto.SESSION.bind)
def defaultTestResult(self):
if not hasattr(self._testresult):
self._testresult = ClustoTestResult()
return self._testresult
|
Enable versioning during unit tests
|
Enable versioning during unit tests
|
Python
|
bsd-3-clause
|
clusto/clusto,thekad/clusto,sloppyfocus/clusto,sloppyfocus/clusto,motivator/clusto,JTCunning/clusto,motivator/clusto,clusto/clusto,thekad/clusto,JTCunning/clusto
|
import sys
import os
sys.path.insert(0, os.curdir)
import unittest
import clusto
import ConfigParser
DB='sqlite:///:memory:'
ECHO=False
class ClustoTestResult(unittest.TestResult):
def addError(self, test, err):
"""Called when an error has occurred. 'err' is a tuple of values as
returned by sys.exc_info().
"""
print >>sys.stderr, "ERROR HERE!"
clusto.rollback_transaction()
self.errors.append((test, self._exc_info_to_string(err, test)))
class ClustoTestBase(unittest.TestCase):
def data(self):
pass
def setUp(self):
conf = ConfigParser.ConfigParser()
conf.add_section('clusto')
conf.set('clusto', 'dsn', DB)
clusto.connect(conf,echo=ECHO)
clusto.clear()
clusto.SESSION.close()
clusto.init_clusto()
self.data()
def tearDown(self):
if clusto.SESSION.is_active:
raise Exception("SESSION IS STILL ACTIVE in %s" % str(self.__class__))
clusto.clear()
clusto.disconnect()
clusto.METADATA.drop_all(clusto.SESSION.bind)
def defaultTestResult(self):
if not hasattr(self._testresult):
self._testresult = ClustoTestResult()
return self._testresult
Enable versioning during unit tests
|
import sys
import os
sys.path.insert(0, os.curdir)
import unittest
import clusto
import ConfigParser
DB='sqlite:///:memory:'
ECHO=False
class ClustoTestResult(unittest.TestResult):
def addError(self, test, err):
"""Called when an error has occurred. 'err' is a tuple of values as
returned by sys.exc_info().
"""
print >>sys.stderr, "ERROR HERE!"
clusto.rollback_transaction()
self.errors.append((test, self._exc_info_to_string(err, test)))
class ClustoTestBase(unittest.TestCase):
def data(self):
pass
def setUp(self):
conf = ConfigParser.ConfigParser()
conf.add_section('clusto')
conf.set('clusto', 'dsn', DB)
conf.set('clusto', 'versioning', '1')
clusto.connect(conf,echo=ECHO)
clusto.clear()
clusto.SESSION.close()
clusto.init_clusto()
self.data()
def tearDown(self):
if clusto.SESSION.is_active:
raise Exception("SESSION IS STILL ACTIVE in %s" % str(self.__class__))
clusto.clear()
clusto.disconnect()
clusto.METADATA.drop_all(clusto.SESSION.bind)
def defaultTestResult(self):
if not hasattr(self._testresult):
self._testresult = ClustoTestResult()
return self._testresult
|
<commit_before>import sys
import os
sys.path.insert(0, os.curdir)
import unittest
import clusto
import ConfigParser
DB='sqlite:///:memory:'
ECHO=False
class ClustoTestResult(unittest.TestResult):
def addError(self, test, err):
"""Called when an error has occurred. 'err' is a tuple of values as
returned by sys.exc_info().
"""
print >>sys.stderr, "ERROR HERE!"
clusto.rollback_transaction()
self.errors.append((test, self._exc_info_to_string(err, test)))
class ClustoTestBase(unittest.TestCase):
def data(self):
pass
def setUp(self):
conf = ConfigParser.ConfigParser()
conf.add_section('clusto')
conf.set('clusto', 'dsn', DB)
clusto.connect(conf,echo=ECHO)
clusto.clear()
clusto.SESSION.close()
clusto.init_clusto()
self.data()
def tearDown(self):
if clusto.SESSION.is_active:
raise Exception("SESSION IS STILL ACTIVE in %s" % str(self.__class__))
clusto.clear()
clusto.disconnect()
clusto.METADATA.drop_all(clusto.SESSION.bind)
def defaultTestResult(self):
if not hasattr(self._testresult):
self._testresult = ClustoTestResult()
return self._testresult
<commit_msg>Enable versioning during unit tests<commit_after>
|
import sys
import os
sys.path.insert(0, os.curdir)
import unittest
import clusto
import ConfigParser
DB='sqlite:///:memory:'
ECHO=False
class ClustoTestResult(unittest.TestResult):
def addError(self, test, err):
"""Called when an error has occurred. 'err' is a tuple of values as
returned by sys.exc_info().
"""
print >>sys.stderr, "ERROR HERE!"
clusto.rollback_transaction()
self.errors.append((test, self._exc_info_to_string(err, test)))
class ClustoTestBase(unittest.TestCase):
def data(self):
pass
def setUp(self):
conf = ConfigParser.ConfigParser()
conf.add_section('clusto')
conf.set('clusto', 'dsn', DB)
conf.set('clusto', 'versioning', '1')
clusto.connect(conf,echo=ECHO)
clusto.clear()
clusto.SESSION.close()
clusto.init_clusto()
self.data()
def tearDown(self):
if clusto.SESSION.is_active:
raise Exception("SESSION IS STILL ACTIVE in %s" % str(self.__class__))
clusto.clear()
clusto.disconnect()
clusto.METADATA.drop_all(clusto.SESSION.bind)
def defaultTestResult(self):
if not hasattr(self._testresult):
self._testresult = ClustoTestResult()
return self._testresult
|
import sys
import os
sys.path.insert(0, os.curdir)
import unittest
import clusto
import ConfigParser
DB='sqlite:///:memory:'
ECHO=False
class ClustoTestResult(unittest.TestResult):
def addError(self, test, err):
"""Called when an error has occurred. 'err' is a tuple of values as
returned by sys.exc_info().
"""
print >>sys.stderr, "ERROR HERE!"
clusto.rollback_transaction()
self.errors.append((test, self._exc_info_to_string(err, test)))
class ClustoTestBase(unittest.TestCase):
def data(self):
pass
def setUp(self):
conf = ConfigParser.ConfigParser()
conf.add_section('clusto')
conf.set('clusto', 'dsn', DB)
clusto.connect(conf,echo=ECHO)
clusto.clear()
clusto.SESSION.close()
clusto.init_clusto()
self.data()
def tearDown(self):
if clusto.SESSION.is_active:
raise Exception("SESSION IS STILL ACTIVE in %s" % str(self.__class__))
clusto.clear()
clusto.disconnect()
clusto.METADATA.drop_all(clusto.SESSION.bind)
def defaultTestResult(self):
if not hasattr(self._testresult):
self._testresult = ClustoTestResult()
return self._testresult
Enable versioning during unit testsimport sys
import os
sys.path.insert(0, os.curdir)
import unittest
import clusto
import ConfigParser
DB='sqlite:///:memory:'
ECHO=False
class ClustoTestResult(unittest.TestResult):
def addError(self, test, err):
"""Called when an error has occurred. 'err' is a tuple of values as
returned by sys.exc_info().
"""
print >>sys.stderr, "ERROR HERE!"
clusto.rollback_transaction()
self.errors.append((test, self._exc_info_to_string(err, test)))
class ClustoTestBase(unittest.TestCase):
def data(self):
pass
def setUp(self):
conf = ConfigParser.ConfigParser()
conf.add_section('clusto')
conf.set('clusto', 'dsn', DB)
conf.set('clusto', 'versioning', '1')
clusto.connect(conf,echo=ECHO)
clusto.clear()
clusto.SESSION.close()
clusto.init_clusto()
self.data()
def tearDown(self):
if clusto.SESSION.is_active:
raise Exception("SESSION IS STILL ACTIVE in %s" % str(self.__class__))
clusto.clear()
clusto.disconnect()
clusto.METADATA.drop_all(clusto.SESSION.bind)
def defaultTestResult(self):
if not hasattr(self._testresult):
self._testresult = ClustoTestResult()
return self._testresult
|
<commit_before>import sys
import os
sys.path.insert(0, os.curdir)
import unittest
import clusto
import ConfigParser
DB='sqlite:///:memory:'
ECHO=False
class ClustoTestResult(unittest.TestResult):
def addError(self, test, err):
"""Called when an error has occurred. 'err' is a tuple of values as
returned by sys.exc_info().
"""
print >>sys.stderr, "ERROR HERE!"
clusto.rollback_transaction()
self.errors.append((test, self._exc_info_to_string(err, test)))
class ClustoTestBase(unittest.TestCase):
def data(self):
pass
def setUp(self):
conf = ConfigParser.ConfigParser()
conf.add_section('clusto')
conf.set('clusto', 'dsn', DB)
clusto.connect(conf,echo=ECHO)
clusto.clear()
clusto.SESSION.close()
clusto.init_clusto()
self.data()
def tearDown(self):
if clusto.SESSION.is_active:
raise Exception("SESSION IS STILL ACTIVE in %s" % str(self.__class__))
clusto.clear()
clusto.disconnect()
clusto.METADATA.drop_all(clusto.SESSION.bind)
def defaultTestResult(self):
if not hasattr(self._testresult):
self._testresult = ClustoTestResult()
return self._testresult
<commit_msg>Enable versioning during unit tests<commit_after>import sys
import os
sys.path.insert(0, os.curdir)
import unittest
import clusto
import ConfigParser
DB='sqlite:///:memory:'
ECHO=False
class ClustoTestResult(unittest.TestResult):
def addError(self, test, err):
"""Called when an error has occurred. 'err' is a tuple of values as
returned by sys.exc_info().
"""
print >>sys.stderr, "ERROR HERE!"
clusto.rollback_transaction()
self.errors.append((test, self._exc_info_to_string(err, test)))
class ClustoTestBase(unittest.TestCase):
def data(self):
pass
def setUp(self):
conf = ConfigParser.ConfigParser()
conf.add_section('clusto')
conf.set('clusto', 'dsn', DB)
conf.set('clusto', 'versioning', '1')
clusto.connect(conf,echo=ECHO)
clusto.clear()
clusto.SESSION.close()
clusto.init_clusto()
self.data()
def tearDown(self):
if clusto.SESSION.is_active:
raise Exception("SESSION IS STILL ACTIVE in %s" % str(self.__class__))
clusto.clear()
clusto.disconnect()
clusto.METADATA.drop_all(clusto.SESSION.bind)
def defaultTestResult(self):
if not hasattr(self._testresult):
self._testresult = ClustoTestResult()
return self._testresult
|
c08e6a22e589880d97b92048cfaec994c41a23d4
|
pylama/lint/pylama_pydocstyle.py
|
pylama/lint/pylama_pydocstyle.py
|
"""pydocstyle support."""
from pydocstyle import PEP257Checker
from pylama.lint import Linter as Abstract
class Linter(Abstract):
"""Check pydocstyle errors."""
@staticmethod
def run(path, code=None, **meta):
"""pydocstyle code checking.
:return list: List of errors.
"""
return [{
'lnum': e.line,
# Remove colon after error code ("D403: ..." => "D403 ...").
'text': (e.message[0:4] + e.message[5:]
if e.message[4] == ':' else e.message),
'type': 'D',
'number': e.code
} for e in PEP257Checker().check_source(code, path)]
|
"""pydocstyle support."""
THIRD_ARG = True
try:
#: Import for pydocstyle 2.0.0 and newer
from pydocstyle import ConventionChecker as PyDocChecker
except ImportError:
#: Backward compatibility for pydocstyle prior to 2.0.0
from pydocstyle import PEP257Checker as PyDocChecker
THIRD_ARG = False
from pylama.lint import Linter as Abstract
class Linter(Abstract):
"""Check pydocstyle errors."""
@staticmethod
def run(path, code=None, **meta):
"""pydocstyle code checking.
:return list: List of errors.
"""
check_source_args = (code, path, None) if THIRD_ARG else (code, path)
return [{
'lnum': e.line,
# Remove colon after error code ("D403: ..." => "D403 ...").
'text': (e.message[0:4] + e.message[5:]
if e.message[4] == ':' else e.message),
'type': 'D',
'number': e.code
} for e in PyDocChecker().check_source(*check_source_args)]
|
Update for pydocstyle 2.0.0 compatibility
|
Update for pydocstyle 2.0.0 compatibility
Fix klen/pylama#96
Adding the newer ignore_decorators argument. Thanks to @not-raspberry for the tip!
|
Python
|
mit
|
klen/pylama
|
"""pydocstyle support."""
from pydocstyle import PEP257Checker
from pylama.lint import Linter as Abstract
class Linter(Abstract):
"""Check pydocstyle errors."""
@staticmethod
def run(path, code=None, **meta):
"""pydocstyle code checking.
:return list: List of errors.
"""
return [{
'lnum': e.line,
# Remove colon after error code ("D403: ..." => "D403 ...").
'text': (e.message[0:4] + e.message[5:]
if e.message[4] == ':' else e.message),
'type': 'D',
'number': e.code
} for e in PEP257Checker().check_source(code, path)]
Update for pydocstyle 2.0.0 compatibility
Fix klen/pylama#96
Adding the newer ignore_decorators argument. Thanks to @not-raspberry for the tip!
|
"""pydocstyle support."""
THIRD_ARG = True
try:
#: Import for pydocstyle 2.0.0 and newer
from pydocstyle import ConventionChecker as PyDocChecker
except ImportError:
#: Backward compatibility for pydocstyle prior to 2.0.0
from pydocstyle import PEP257Checker as PyDocChecker
THIRD_ARG = False
from pylama.lint import Linter as Abstract
class Linter(Abstract):
"""Check pydocstyle errors."""
@staticmethod
def run(path, code=None, **meta):
"""pydocstyle code checking.
:return list: List of errors.
"""
check_source_args = (code, path, None) if THIRD_ARG else (code, path)
return [{
'lnum': e.line,
# Remove colon after error code ("D403: ..." => "D403 ...").
'text': (e.message[0:4] + e.message[5:]
if e.message[4] == ':' else e.message),
'type': 'D',
'number': e.code
} for e in PyDocChecker().check_source(*check_source_args)]
|
<commit_before>"""pydocstyle support."""
from pydocstyle import PEP257Checker
from pylama.lint import Linter as Abstract
class Linter(Abstract):
"""Check pydocstyle errors."""
@staticmethod
def run(path, code=None, **meta):
"""pydocstyle code checking.
:return list: List of errors.
"""
return [{
'lnum': e.line,
# Remove colon after error code ("D403: ..." => "D403 ...").
'text': (e.message[0:4] + e.message[5:]
if e.message[4] == ':' else e.message),
'type': 'D',
'number': e.code
} for e in PEP257Checker().check_source(code, path)]
<commit_msg>Update for pydocstyle 2.0.0 compatibility
Fix klen/pylama#96
Adding the newer ignore_decorators argument. Thanks to @not-raspberry for the tip!<commit_after>
|
"""pydocstyle support."""
THIRD_ARG = True
try:
#: Import for pydocstyle 2.0.0 and newer
from pydocstyle import ConventionChecker as PyDocChecker
except ImportError:
#: Backward compatibility for pydocstyle prior to 2.0.0
from pydocstyle import PEP257Checker as PyDocChecker
THIRD_ARG = False
from pylama.lint import Linter as Abstract
class Linter(Abstract):
"""Check pydocstyle errors."""
@staticmethod
def run(path, code=None, **meta):
"""pydocstyle code checking.
:return list: List of errors.
"""
check_source_args = (code, path, None) if THIRD_ARG else (code, path)
return [{
'lnum': e.line,
# Remove colon after error code ("D403: ..." => "D403 ...").
'text': (e.message[0:4] + e.message[5:]
if e.message[4] == ':' else e.message),
'type': 'D',
'number': e.code
} for e in PyDocChecker().check_source(*check_source_args)]
|
"""pydocstyle support."""
from pydocstyle import PEP257Checker
from pylama.lint import Linter as Abstract
class Linter(Abstract):
"""Check pydocstyle errors."""
@staticmethod
def run(path, code=None, **meta):
"""pydocstyle code checking.
:return list: List of errors.
"""
return [{
'lnum': e.line,
# Remove colon after error code ("D403: ..." => "D403 ...").
'text': (e.message[0:4] + e.message[5:]
if e.message[4] == ':' else e.message),
'type': 'D',
'number': e.code
} for e in PEP257Checker().check_source(code, path)]
Update for pydocstyle 2.0.0 compatibility
Fix klen/pylama#96
Adding the newer ignore_decorators argument. Thanks to @not-raspberry for the tip!"""pydocstyle support."""
THIRD_ARG = True
try:
#: Import for pydocstyle 2.0.0 and newer
from pydocstyle import ConventionChecker as PyDocChecker
except ImportError:
#: Backward compatibility for pydocstyle prior to 2.0.0
from pydocstyle import PEP257Checker as PyDocChecker
THIRD_ARG = False
from pylama.lint import Linter as Abstract
class Linter(Abstract):
"""Check pydocstyle errors."""
@staticmethod
def run(path, code=None, **meta):
"""pydocstyle code checking.
:return list: List of errors.
"""
check_source_args = (code, path, None) if THIRD_ARG else (code, path)
return [{
'lnum': e.line,
# Remove colon after error code ("D403: ..." => "D403 ...").
'text': (e.message[0:4] + e.message[5:]
if e.message[4] == ':' else e.message),
'type': 'D',
'number': e.code
} for e in PyDocChecker().check_source(*check_source_args)]
|
<commit_before>"""pydocstyle support."""
from pydocstyle import PEP257Checker
from pylama.lint import Linter as Abstract
class Linter(Abstract):
"""Check pydocstyle errors."""
@staticmethod
def run(path, code=None, **meta):
"""pydocstyle code checking.
:return list: List of errors.
"""
return [{
'lnum': e.line,
# Remove colon after error code ("D403: ..." => "D403 ...").
'text': (e.message[0:4] + e.message[5:]
if e.message[4] == ':' else e.message),
'type': 'D',
'number': e.code
} for e in PEP257Checker().check_source(code, path)]
<commit_msg>Update for pydocstyle 2.0.0 compatibility
Fix klen/pylama#96
Adding the newer ignore_decorators argument. Thanks to @not-raspberry for the tip!<commit_after>"""pydocstyle support."""
THIRD_ARG = True
try:
#: Import for pydocstyle 2.0.0 and newer
from pydocstyle import ConventionChecker as PyDocChecker
except ImportError:
#: Backward compatibility for pydocstyle prior to 2.0.0
from pydocstyle import PEP257Checker as PyDocChecker
THIRD_ARG = False
from pylama.lint import Linter as Abstract
class Linter(Abstract):
"""Check pydocstyle errors."""
@staticmethod
def run(path, code=None, **meta):
"""pydocstyle code checking.
:return list: List of errors.
"""
check_source_args = (code, path, None) if THIRD_ARG else (code, path)
return [{
'lnum': e.line,
# Remove colon after error code ("D403: ..." => "D403 ...").
'text': (e.message[0:4] + e.message[5:]
if e.message[4] == ':' else e.message),
'type': 'D',
'number': e.code
} for e in PyDocChecker().check_source(*check_source_args)]
|
95807cb007c9ea51a3594adca33b7fab809afc3e
|
tests/zeus/api/test_authentication.py
|
tests/zeus/api/test_authentication.py
|
import pytest
from zeus import factories
from zeus.auth import AuthenticationFailed
from zeus.api.authentication import ApiTokenAuthentication
def test_no_header(app):
with app.test_request_context('/'):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_authentication_type(app):
with app.test_request_context('/', headers={'Authentication': 'foobar'}):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_token(app):
with app.test_request_context('/', headers={'Authentication': 'Bearer: foobar'}):
with pytest.raises(AuthenticationFailed):
ApiTokenAuthentication().authenticate()
def test_expired_token(app):
api_token = factories.ApiTokenFactory(expired=True)
with app.test_request_context(
'/', headers={'Authentication': 'Bearer: {}'.format(api_token.access_token)}
):
with pytest.raises(AuthenticationFailed):
ApiTokenAuthentication().authenticate()
def test_valid_token(app, default_api_token):
with app.test_request_context(
'/', headers={'Authentication': 'Bearer: {}'.format(default_api_token.access_token)}
):
tenant = ApiTokenAuthentication().authenticate()
assert tenant.token_id == default_api_token.id
|
import pytest
from zeus import factories
from zeus.auth import AuthenticationFailed
from zeus.api.authentication import ApiTokenAuthentication
def test_no_header(app):
with app.test_request_context('/'):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_authentication_type(app):
with app.test_request_context('/', headers={'Authorization': 'foobar'}):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_token(app):
with app.test_request_context('/', headers={'Authorization': 'Bearer: foobar'}):
with pytest.raises(AuthenticationFailed):
ApiTokenAuthentication().authenticate()
def test_expired_token(app):
api_token = factories.ApiTokenFactory(expired=True)
with app.test_request_context(
'/', headers={'Authorization': 'Bearer: {}'.format(api_token.access_token)}
):
with pytest.raises(AuthenticationFailed):
ApiTokenAuthentication().authenticate()
def test_valid_token(app, default_api_token):
with app.test_request_context(
'/', headers={'Authorization': 'Bearer: {}'.format(default_api_token.access_token)}
):
tenant = ApiTokenAuthentication().authenticate()
assert tenant.token_id == default_api_token.id
|
Fix tests for new header
|
test(auth): Fix tests for new header
|
Python
|
apache-2.0
|
getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus
|
import pytest
from zeus import factories
from zeus.auth import AuthenticationFailed
from zeus.api.authentication import ApiTokenAuthentication
def test_no_header(app):
with app.test_request_context('/'):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_authentication_type(app):
with app.test_request_context('/', headers={'Authentication': 'foobar'}):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_token(app):
with app.test_request_context('/', headers={'Authentication': 'Bearer: foobar'}):
with pytest.raises(AuthenticationFailed):
ApiTokenAuthentication().authenticate()
def test_expired_token(app):
api_token = factories.ApiTokenFactory(expired=True)
with app.test_request_context(
'/', headers={'Authentication': 'Bearer: {}'.format(api_token.access_token)}
):
with pytest.raises(AuthenticationFailed):
ApiTokenAuthentication().authenticate()
def test_valid_token(app, default_api_token):
with app.test_request_context(
'/', headers={'Authentication': 'Bearer: {}'.format(default_api_token.access_token)}
):
tenant = ApiTokenAuthentication().authenticate()
assert tenant.token_id == default_api_token.id
test(auth): Fix tests for new header
|
import pytest
from zeus import factories
from zeus.auth import AuthenticationFailed
from zeus.api.authentication import ApiTokenAuthentication
def test_no_header(app):
with app.test_request_context('/'):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_authentication_type(app):
with app.test_request_context('/', headers={'Authorization': 'foobar'}):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_token(app):
with app.test_request_context('/', headers={'Authorization': 'Bearer: foobar'}):
with pytest.raises(AuthenticationFailed):
ApiTokenAuthentication().authenticate()
def test_expired_token(app):
api_token = factories.ApiTokenFactory(expired=True)
with app.test_request_context(
'/', headers={'Authorization': 'Bearer: {}'.format(api_token.access_token)}
):
with pytest.raises(AuthenticationFailed):
ApiTokenAuthentication().authenticate()
def test_valid_token(app, default_api_token):
with app.test_request_context(
'/', headers={'Authorization': 'Bearer: {}'.format(default_api_token.access_token)}
):
tenant = ApiTokenAuthentication().authenticate()
assert tenant.token_id == default_api_token.id
|
<commit_before>import pytest
from zeus import factories
from zeus.auth import AuthenticationFailed
from zeus.api.authentication import ApiTokenAuthentication
def test_no_header(app):
with app.test_request_context('/'):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_authentication_type(app):
with app.test_request_context('/', headers={'Authentication': 'foobar'}):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_token(app):
with app.test_request_context('/', headers={'Authentication': 'Bearer: foobar'}):
with pytest.raises(AuthenticationFailed):
ApiTokenAuthentication().authenticate()
def test_expired_token(app):
api_token = factories.ApiTokenFactory(expired=True)
with app.test_request_context(
'/', headers={'Authentication': 'Bearer: {}'.format(api_token.access_token)}
):
with pytest.raises(AuthenticationFailed):
ApiTokenAuthentication().authenticate()
def test_valid_token(app, default_api_token):
with app.test_request_context(
'/', headers={'Authentication': 'Bearer: {}'.format(default_api_token.access_token)}
):
tenant = ApiTokenAuthentication().authenticate()
assert tenant.token_id == default_api_token.id
<commit_msg>test(auth): Fix tests for new header<commit_after>
|
import pytest
from zeus import factories
from zeus.auth import AuthenticationFailed
from zeus.api.authentication import ApiTokenAuthentication
def test_no_header(app):
with app.test_request_context('/'):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_authentication_type(app):
with app.test_request_context('/', headers={'Authorization': 'foobar'}):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_token(app):
with app.test_request_context('/', headers={'Authorization': 'Bearer: foobar'}):
with pytest.raises(AuthenticationFailed):
ApiTokenAuthentication().authenticate()
def test_expired_token(app):
api_token = factories.ApiTokenFactory(expired=True)
with app.test_request_context(
'/', headers={'Authorization': 'Bearer: {}'.format(api_token.access_token)}
):
with pytest.raises(AuthenticationFailed):
ApiTokenAuthentication().authenticate()
def test_valid_token(app, default_api_token):
with app.test_request_context(
'/', headers={'Authorization': 'Bearer: {}'.format(default_api_token.access_token)}
):
tenant = ApiTokenAuthentication().authenticate()
assert tenant.token_id == default_api_token.id
|
import pytest
from zeus import factories
from zeus.auth import AuthenticationFailed
from zeus.api.authentication import ApiTokenAuthentication
def test_no_header(app):
with app.test_request_context('/'):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_authentication_type(app):
with app.test_request_context('/', headers={'Authentication': 'foobar'}):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_token(app):
with app.test_request_context('/', headers={'Authentication': 'Bearer: foobar'}):
with pytest.raises(AuthenticationFailed):
ApiTokenAuthentication().authenticate()
def test_expired_token(app):
api_token = factories.ApiTokenFactory(expired=True)
with app.test_request_context(
'/', headers={'Authentication': 'Bearer: {}'.format(api_token.access_token)}
):
with pytest.raises(AuthenticationFailed):
ApiTokenAuthentication().authenticate()
def test_valid_token(app, default_api_token):
with app.test_request_context(
'/', headers={'Authentication': 'Bearer: {}'.format(default_api_token.access_token)}
):
tenant = ApiTokenAuthentication().authenticate()
assert tenant.token_id == default_api_token.id
test(auth): Fix tests for new headerimport pytest
from zeus import factories
from zeus.auth import AuthenticationFailed
from zeus.api.authentication import ApiTokenAuthentication
def test_no_header(app):
with app.test_request_context('/'):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_authentication_type(app):
with app.test_request_context('/', headers={'Authorization': 'foobar'}):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_token(app):
with app.test_request_context('/', headers={'Authorization': 'Bearer: foobar'}):
with pytest.raises(AuthenticationFailed):
ApiTokenAuthentication().authenticate()
def test_expired_token(app):
api_token = factories.ApiTokenFactory(expired=True)
with app.test_request_context(
'/', headers={'Authorization': 'Bearer: {}'.format(api_token.access_token)}
):
with pytest.raises(AuthenticationFailed):
ApiTokenAuthentication().authenticate()
def test_valid_token(app, default_api_token):
with app.test_request_context(
'/', headers={'Authorization': 'Bearer: {}'.format(default_api_token.access_token)}
):
tenant = ApiTokenAuthentication().authenticate()
assert tenant.token_id == default_api_token.id
|
<commit_before>import pytest
from zeus import factories
from zeus.auth import AuthenticationFailed
from zeus.api.authentication import ApiTokenAuthentication
def test_no_header(app):
with app.test_request_context('/'):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_authentication_type(app):
with app.test_request_context('/', headers={'Authentication': 'foobar'}):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_token(app):
with app.test_request_context('/', headers={'Authentication': 'Bearer: foobar'}):
with pytest.raises(AuthenticationFailed):
ApiTokenAuthentication().authenticate()
def test_expired_token(app):
api_token = factories.ApiTokenFactory(expired=True)
with app.test_request_context(
'/', headers={'Authentication': 'Bearer: {}'.format(api_token.access_token)}
):
with pytest.raises(AuthenticationFailed):
ApiTokenAuthentication().authenticate()
def test_valid_token(app, default_api_token):
with app.test_request_context(
'/', headers={'Authentication': 'Bearer: {}'.format(default_api_token.access_token)}
):
tenant = ApiTokenAuthentication().authenticate()
assert tenant.token_id == default_api_token.id
<commit_msg>test(auth): Fix tests for new header<commit_after>import pytest
from zeus import factories
from zeus.auth import AuthenticationFailed
from zeus.api.authentication import ApiTokenAuthentication
def test_no_header(app):
with app.test_request_context('/'):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_authentication_type(app):
with app.test_request_context('/', headers={'Authorization': 'foobar'}):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_token(app):
with app.test_request_context('/', headers={'Authorization': 'Bearer: foobar'}):
with pytest.raises(AuthenticationFailed):
ApiTokenAuthentication().authenticate()
def test_expired_token(app):
api_token = factories.ApiTokenFactory(expired=True)
with app.test_request_context(
'/', headers={'Authorization': 'Bearer: {}'.format(api_token.access_token)}
):
with pytest.raises(AuthenticationFailed):
ApiTokenAuthentication().authenticate()
def test_valid_token(app, default_api_token):
with app.test_request_context(
'/', headers={'Authorization': 'Bearer: {}'.format(default_api_token.access_token)}
):
tenant = ApiTokenAuthentication().authenticate()
assert tenant.token_id == default_api_token.id
|
79d2a78c0043aea7232933735654169ac05a70c3
|
ofxclient/util.py
|
ofxclient/util.py
|
from ofxclient.client import Client
from StringIO import StringIO
def combined_download(accounts, days=60):
"""Download OFX files and combine them into one
It expects an 'accounts' list of ofxclient.Account objects
as well as an optional 'days' specifier which defaults to 60
"""
client = Client(institution=None)
out_file = StringIO()
out_file.write(client.header())
for a in accounts:
ofx = a.download(days=days).read()
stripped = ofx.partition('<OFX>')[2].partition('</OFX>')[0]
out_file.write(stripped)
out_file.write("<OFX>")
out_file.seek(0)
return out_file
|
from ofxclient.client import Client
from StringIO import StringIO
def combined_download(accounts, days=60):
"""Download OFX files and combine them into one
It expects an 'accounts' list of ofxclient.Account objects
as well as an optional 'days' specifier which defaults to 60
"""
client = Client(institution=None)
out_file = StringIO()
out_file.write(client.header())
out_file.write('<OFX>')
for a in accounts:
ofx = a.download(days=days).read()
stripped = ofx.partition('<OFX>')[2].partition('</OFX>')[0]
out_file.write(stripped)
out_file.write("</OFX>")
out_file.seek(0)
return out_file
|
Fix bug with document merger
|
Fix bug with document merger
|
Python
|
mit
|
captin411/ofxclient,jbms/ofxclient
|
from ofxclient.client import Client
from StringIO import StringIO
def combined_download(accounts, days=60):
"""Download OFX files and combine them into one
It expects an 'accounts' list of ofxclient.Account objects
as well as an optional 'days' specifier which defaults to 60
"""
client = Client(institution=None)
out_file = StringIO()
out_file.write(client.header())
for a in accounts:
ofx = a.download(days=days).read()
stripped = ofx.partition('<OFX>')[2].partition('</OFX>')[0]
out_file.write(stripped)
out_file.write("<OFX>")
out_file.seek(0)
return out_file
Fix bug with document merger
|
from ofxclient.client import Client
from StringIO import StringIO
def combined_download(accounts, days=60):
"""Download OFX files and combine them into one
It expects an 'accounts' list of ofxclient.Account objects
as well as an optional 'days' specifier which defaults to 60
"""
client = Client(institution=None)
out_file = StringIO()
out_file.write(client.header())
out_file.write('<OFX>')
for a in accounts:
ofx = a.download(days=days).read()
stripped = ofx.partition('<OFX>')[2].partition('</OFX>')[0]
out_file.write(stripped)
out_file.write("</OFX>")
out_file.seek(0)
return out_file
|
<commit_before>from ofxclient.client import Client
from StringIO import StringIO
def combined_download(accounts, days=60):
"""Download OFX files and combine them into one
It expects an 'accounts' list of ofxclient.Account objects
as well as an optional 'days' specifier which defaults to 60
"""
client = Client(institution=None)
out_file = StringIO()
out_file.write(client.header())
for a in accounts:
ofx = a.download(days=days).read()
stripped = ofx.partition('<OFX>')[2].partition('</OFX>')[0]
out_file.write(stripped)
out_file.write("<OFX>")
out_file.seek(0)
return out_file
<commit_msg>Fix bug with document merger<commit_after>
|
from ofxclient.client import Client
from StringIO import StringIO
def combined_download(accounts, days=60):
"""Download OFX files and combine them into one
It expects an 'accounts' list of ofxclient.Account objects
as well as an optional 'days' specifier which defaults to 60
"""
client = Client(institution=None)
out_file = StringIO()
out_file.write(client.header())
out_file.write('<OFX>')
for a in accounts:
ofx = a.download(days=days).read()
stripped = ofx.partition('<OFX>')[2].partition('</OFX>')[0]
out_file.write(stripped)
out_file.write("</OFX>")
out_file.seek(0)
return out_file
|
from ofxclient.client import Client
from StringIO import StringIO
def combined_download(accounts, days=60):
"""Download OFX files and combine them into one
It expects an 'accounts' list of ofxclient.Account objects
as well as an optional 'days' specifier which defaults to 60
"""
client = Client(institution=None)
out_file = StringIO()
out_file.write(client.header())
for a in accounts:
ofx = a.download(days=days).read()
stripped = ofx.partition('<OFX>')[2].partition('</OFX>')[0]
out_file.write(stripped)
out_file.write("<OFX>")
out_file.seek(0)
return out_file
Fix bug with document mergerfrom ofxclient.client import Client
from StringIO import StringIO
def combined_download(accounts, days=60):
"""Download OFX files and combine them into one
It expects an 'accounts' list of ofxclient.Account objects
as well as an optional 'days' specifier which defaults to 60
"""
client = Client(institution=None)
out_file = StringIO()
out_file.write(client.header())
out_file.write('<OFX>')
for a in accounts:
ofx = a.download(days=days).read()
stripped = ofx.partition('<OFX>')[2].partition('</OFX>')[0]
out_file.write(stripped)
out_file.write("</OFX>")
out_file.seek(0)
return out_file
|
<commit_before>from ofxclient.client import Client
from StringIO import StringIO
def combined_download(accounts, days=60):
"""Download OFX files and combine them into one
It expects an 'accounts' list of ofxclient.Account objects
as well as an optional 'days' specifier which defaults to 60
"""
client = Client(institution=None)
out_file = StringIO()
out_file.write(client.header())
for a in accounts:
ofx = a.download(days=days).read()
stripped = ofx.partition('<OFX>')[2].partition('</OFX>')[0]
out_file.write(stripped)
out_file.write("<OFX>")
out_file.seek(0)
return out_file
<commit_msg>Fix bug with document merger<commit_after>from ofxclient.client import Client
from StringIO import StringIO
def combined_download(accounts, days=60):
"""Download OFX files and combine them into one
It expects an 'accounts' list of ofxclient.Account objects
as well as an optional 'days' specifier which defaults to 60
"""
client = Client(institution=None)
out_file = StringIO()
out_file.write(client.header())
out_file.write('<OFX>')
for a in accounts:
ofx = a.download(days=days).read()
stripped = ofx.partition('<OFX>')[2].partition('</OFX>')[0]
out_file.write(stripped)
out_file.write("</OFX>")
out_file.seek(0)
return out_file
|
bc5fa08e84cd11349dc44c3065b7b5380d60ebd9
|
raven/contrib/django/handlers.py
|
raven/contrib/django/handlers.py
|
"""
raven.contrib.django.handlers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import logging
from raven.handlers.logging import SentryHandler as BaseSentryHandler
class SentryHandler(BaseSentryHandler):
def __init__(self):
logging.Handler.__init__(self)
def _get_client(self):
from raven.contrib.django.models import client
return client
client = property(_get_client)
def _emit(self, record):
request = getattr(record, 'request', None)
return super(SentryHandler, self)._emit(record, request=request)
|
"""
raven.contrib.django.handlers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import logging
from raven.handlers.logging import SentryHandler as BaseSentryHandler
class SentryHandler(BaseSentryHandler):
def __init__(self, level=logging.NOTSET):
logging.Handler.__init__(self, level=level)
def _get_client(self):
from raven.contrib.django.models import client
return client
client = property(_get_client)
def _emit(self, record):
request = getattr(record, 'request', None)
return super(SentryHandler, self)._emit(record, request=request)
|
Allow level param in Django SentryHandler.__init__
|
Allow level param in Django SentryHandler.__init__
For consistency with superclass and with logging.Handler
|
Python
|
bsd-3-clause
|
arthurlogilab/raven-python,inspirehep/raven-python,ewdurbin/raven-python,jbarbuto/raven-python,getsentry/raven-python,dbravender/raven-python,jbarbuto/raven-python,Photonomie/raven-python,percipient/raven-python,akheron/raven-python,icereval/raven-python,nikolas/raven-python,akalipetis/raven-python,someonehan/raven-python,nikolas/raven-python,ewdurbin/raven-python,inspirehep/raven-python,icereval/raven-python,danriti/raven-python,danriti/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,someonehan/raven-python,danriti/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,akheron/raven-python,akheron/raven-python,arthurlogilab/raven-python,hzy/raven-python,nikolas/raven-python,arthurlogilab/raven-python,jbarbuto/raven-python,inspirehep/raven-python,smarkets/raven-python,arthurlogilab/raven-python,smarkets/raven-python,johansteffner/raven-python,akalipetis/raven-python,lepture/raven-python,getsentry/raven-python,akalipetis/raven-python,ronaldevers/raven-python,johansteffner/raven-python,percipient/raven-python,icereval/raven-python,jmp0xf/raven-python,jmagnusson/raven-python,lepture/raven-python,smarkets/raven-python,johansteffner/raven-python,Photonomie/raven-python,someonehan/raven-python,ronaldevers/raven-python,dbravender/raven-python,ronaldevers/raven-python,lepture/raven-python,percipient/raven-python,jbarbuto/raven-python,jmagnusson/raven-python,jmp0xf/raven-python,smarkets/raven-python,recht/raven-python,jmp0xf/raven-python,icereval/raven-python,jmagnusson/raven-python,Photonomie/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,dbravender/raven-python,recht/raven-python,nikolas/raven-python,getsentry/raven-python,hzy/raven-python,inspirehep/raven-python,recht/raven-python,ewdurbin/raven-python,hzy/raven-python
|
"""
raven.contrib.django.handlers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import logging
from raven.handlers.logging import SentryHandler as BaseSentryHandler
class SentryHandler(BaseSentryHandler):
def __init__(self):
logging.Handler.__init__(self)
def _get_client(self):
from raven.contrib.django.models import client
return client
client = property(_get_client)
def _emit(self, record):
request = getattr(record, 'request', None)
return super(SentryHandler, self)._emit(record, request=request)
Allow level param in Django SentryHandler.__init__
For consistency with superclass and with logging.Handler
|
"""
raven.contrib.django.handlers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import logging
from raven.handlers.logging import SentryHandler as BaseSentryHandler
class SentryHandler(BaseSentryHandler):
def __init__(self, level=logging.NOTSET):
logging.Handler.__init__(self, level=level)
def _get_client(self):
from raven.contrib.django.models import client
return client
client = property(_get_client)
def _emit(self, record):
request = getattr(record, 'request', None)
return super(SentryHandler, self)._emit(record, request=request)
|
<commit_before>"""
raven.contrib.django.handlers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import logging
from raven.handlers.logging import SentryHandler as BaseSentryHandler
class SentryHandler(BaseSentryHandler):
def __init__(self):
logging.Handler.__init__(self)
def _get_client(self):
from raven.contrib.django.models import client
return client
client = property(_get_client)
def _emit(self, record):
request = getattr(record, 'request', None)
return super(SentryHandler, self)._emit(record, request=request)
<commit_msg>Allow level param in Django SentryHandler.__init__
For consistency with superclass and with logging.Handler<commit_after>
|
"""
raven.contrib.django.handlers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import logging
from raven.handlers.logging import SentryHandler as BaseSentryHandler
class SentryHandler(BaseSentryHandler):
def __init__(self, level=logging.NOTSET):
logging.Handler.__init__(self, level=level)
def _get_client(self):
from raven.contrib.django.models import client
return client
client = property(_get_client)
def _emit(self, record):
request = getattr(record, 'request', None)
return super(SentryHandler, self)._emit(record, request=request)
|
"""
raven.contrib.django.handlers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import logging
from raven.handlers.logging import SentryHandler as BaseSentryHandler
class SentryHandler(BaseSentryHandler):
def __init__(self):
logging.Handler.__init__(self)
def _get_client(self):
from raven.contrib.django.models import client
return client
client = property(_get_client)
def _emit(self, record):
request = getattr(record, 'request', None)
return super(SentryHandler, self)._emit(record, request=request)
Allow level param in Django SentryHandler.__init__
For consistency with superclass and with logging.Handler"""
raven.contrib.django.handlers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import logging
from raven.handlers.logging import SentryHandler as BaseSentryHandler
class SentryHandler(BaseSentryHandler):
def __init__(self, level=logging.NOTSET):
logging.Handler.__init__(self, level=level)
def _get_client(self):
from raven.contrib.django.models import client
return client
client = property(_get_client)
def _emit(self, record):
request = getattr(record, 'request', None)
return super(SentryHandler, self)._emit(record, request=request)
|
<commit_before>"""
raven.contrib.django.handlers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import logging
from raven.handlers.logging import SentryHandler as BaseSentryHandler
class SentryHandler(BaseSentryHandler):
def __init__(self):
logging.Handler.__init__(self)
def _get_client(self):
from raven.contrib.django.models import client
return client
client = property(_get_client)
def _emit(self, record):
request = getattr(record, 'request', None)
return super(SentryHandler, self)._emit(record, request=request)
<commit_msg>Allow level param in Django SentryHandler.__init__
For consistency with superclass and with logging.Handler<commit_after>"""
raven.contrib.django.handlers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import logging
from raven.handlers.logging import SentryHandler as BaseSentryHandler
class SentryHandler(BaseSentryHandler):
def __init__(self, level=logging.NOTSET):
logging.Handler.__init__(self, level=level)
def _get_client(self):
from raven.contrib.django.models import client
return client
client = property(_get_client)
def _emit(self, record):
request = getattr(record, 'request', None)
return super(SentryHandler, self)._emit(record, request=request)
|
486633791bea00c6a846b88124860efbc7532433
|
fancypages/assets/fields.py
|
fancypages/assets/fields.py
|
from django.db.models.fields.related import ForeignKey
from .forms import AssetField
class AssetKey(ForeignKey):
def formfield(self, **kwargs):
kwargs['form_class'] = AssetField
return super(AssetKey, self).formfield(**kwargs)
def value_from_object(self, obj):
asset_obj = getattr(obj, self.name, None)
if not asset_obj:
return None
return [asset_obj.id, asset_obj._meta.module_name]
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^fancypages\.assets\.fields\.AssetKey"])
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
import django
from django.db.models.fields.related import ForeignKey
from .forms import AssetField
class AssetKey(ForeignKey):
def formfield(self, **kwargs):
kwargs['form_class'] = AssetField
return super(AssetKey, self).formfield(**kwargs)
def value_from_object(self, obj):
asset_obj = getattr(obj, self.name, None)
if not asset_obj:
return None
return [asset_obj.id, asset_obj._meta.module_name]
# This is only required for Django version < 1.7 suing South for migrations
if django.VERSION[:2] < (1, 7):
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^fancypages\.assets\.fields\.AssetKey"])
|
Fix south introspection rule for custom AssetField
|
Fix south introspection rule for custom AssetField
|
Python
|
bsd-3-clause
|
tangentlabs/django-fancypages,tangentlabs/django-fancypages,tangentlabs/django-fancypages
|
from django.db.models.fields.related import ForeignKey
from .forms import AssetField
class AssetKey(ForeignKey):
def formfield(self, **kwargs):
kwargs['form_class'] = AssetField
return super(AssetKey, self).formfield(**kwargs)
def value_from_object(self, obj):
asset_obj = getattr(obj, self.name, None)
if not asset_obj:
return None
return [asset_obj.id, asset_obj._meta.module_name]
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^fancypages\.assets\.fields\.AssetKey"])
Fix south introspection rule for custom AssetField
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
import django
from django.db.models.fields.related import ForeignKey
from .forms import AssetField
class AssetKey(ForeignKey):
def formfield(self, **kwargs):
kwargs['form_class'] = AssetField
return super(AssetKey, self).formfield(**kwargs)
def value_from_object(self, obj):
asset_obj = getattr(obj, self.name, None)
if not asset_obj:
return None
return [asset_obj.id, asset_obj._meta.module_name]
# This is only required for Django version < 1.7 suing South for migrations
if django.VERSION[:2] < (1, 7):
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^fancypages\.assets\.fields\.AssetKey"])
|
<commit_before>from django.db.models.fields.related import ForeignKey
from .forms import AssetField
class AssetKey(ForeignKey):
def formfield(self, **kwargs):
kwargs['form_class'] = AssetField
return super(AssetKey, self).formfield(**kwargs)
def value_from_object(self, obj):
asset_obj = getattr(obj, self.name, None)
if not asset_obj:
return None
return [asset_obj.id, asset_obj._meta.module_name]
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^fancypages\.assets\.fields\.AssetKey"])
<commit_msg>Fix south introspection rule for custom AssetField<commit_after>
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
import django
from django.db.models.fields.related import ForeignKey
from .forms import AssetField
class AssetKey(ForeignKey):
def formfield(self, **kwargs):
kwargs['form_class'] = AssetField
return super(AssetKey, self).formfield(**kwargs)
def value_from_object(self, obj):
asset_obj = getattr(obj, self.name, None)
if not asset_obj:
return None
return [asset_obj.id, asset_obj._meta.module_name]
# This is only required for Django version < 1.7 suing South for migrations
if django.VERSION[:2] < (1, 7):
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^fancypages\.assets\.fields\.AssetKey"])
|
from django.db.models.fields.related import ForeignKey
from .forms import AssetField
class AssetKey(ForeignKey):
def formfield(self, **kwargs):
kwargs['form_class'] = AssetField
return super(AssetKey, self).formfield(**kwargs)
def value_from_object(self, obj):
asset_obj = getattr(obj, self.name, None)
if not asset_obj:
return None
return [asset_obj.id, asset_obj._meta.module_name]
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^fancypages\.assets\.fields\.AssetKey"])
Fix south introspection rule for custom AssetField# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
import django
from django.db.models.fields.related import ForeignKey
from .forms import AssetField
class AssetKey(ForeignKey):
def formfield(self, **kwargs):
kwargs['form_class'] = AssetField
return super(AssetKey, self).formfield(**kwargs)
def value_from_object(self, obj):
asset_obj = getattr(obj, self.name, None)
if not asset_obj:
return None
return [asset_obj.id, asset_obj._meta.module_name]
# This is only required for Django version < 1.7 suing South for migrations
if django.VERSION[:2] < (1, 7):
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^fancypages\.assets\.fields\.AssetKey"])
|
<commit_before>from django.db.models.fields.related import ForeignKey
from .forms import AssetField
class AssetKey(ForeignKey):
def formfield(self, **kwargs):
kwargs['form_class'] = AssetField
return super(AssetKey, self).formfield(**kwargs)
def value_from_object(self, obj):
asset_obj = getattr(obj, self.name, None)
if not asset_obj:
return None
return [asset_obj.id, asset_obj._meta.module_name]
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^fancypages\.assets\.fields\.AssetKey"])
<commit_msg>Fix south introspection rule for custom AssetField<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
import django
from django.db.models.fields.related import ForeignKey
from .forms import AssetField
class AssetKey(ForeignKey):
def formfield(self, **kwargs):
kwargs['form_class'] = AssetField
return super(AssetKey, self).formfield(**kwargs)
def value_from_object(self, obj):
asset_obj = getattr(obj, self.name, None)
if not asset_obj:
return None
return [asset_obj.id, asset_obj._meta.module_name]
# This is only required for Django version < 1.7 suing South for migrations
if django.VERSION[:2] < (1, 7):
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^fancypages\.assets\.fields\.AssetKey"])
|
5c858e20eca77a2175178deacdbbc8005232879a
|
fireplace/cards/gvg/mage.py
|
fireplace/cards/gvg/mage.py
|
from ..utils import *
##
# Minions
# Snowchugger
class GVG_002:
events = Damage().on(
lambda self, target, amount, source: source is self and Freeze(target)
)
# Goblin Blastmage
class GVG_004:
play = Find(FRIENDLY_MINIONS + MECH) & Hit(RANDOM_ENEMY_CHARACTER, 1) * 4
# Flame Leviathan
class GVG_007:
in_hand = Draw(CONTROLLER, SELF).on(Hit(ALL_CHARACTERS, 2))
# Illuminator
class GVG_089:
events = OWN_TURN_END.on(Find(FRIENDLY_SECRETS) & Heal(FRIENDLY_HERO, 4))
##
# Spells
# Flamecannon
class GVG_001:
play = Hit(RANDOM_ENEMY_MINION, 4)
# Unstable Portal
class GVG_003:
play = Buff(Give(CONTROLLER, RandomMinion()), "GVG_003e")
# Echo of Medivh
class GVG_005:
play = Give(CONTROLLER, Copy(FRIENDLY_MINIONS))
|
from ..utils import *
##
# Minions
# Snowchugger
class GVG_002:
events = Damage().on(
lambda self, target, amount, source: source is self and Freeze(target)
)
# Goblin Blastmage
class GVG_004:
play = Find(FRIENDLY_MINIONS + MECH) & Hit(RANDOM_ENEMY_CHARACTER, 1) * 4
# Flame Leviathan
class GVG_007:
draw = Hit(ALL_CHARACTERS, 2)
# Illuminator
class GVG_089:
events = OWN_TURN_END.on(Find(FRIENDLY_SECRETS) & Heal(FRIENDLY_HERO, 4))
##
# Spells
# Flamecannon
class GVG_001:
play = Hit(RANDOM_ENEMY_MINION, 4)
# Unstable Portal
class GVG_003:
play = Buff(Give(CONTROLLER, RandomMinion()), "GVG_003e")
# Echo of Medivh
class GVG_005:
play = Give(CONTROLLER, Copy(FRIENDLY_MINIONS))
|
Update Flame Leviathan to use draw script
|
Update Flame Leviathan to use draw script
|
Python
|
agpl-3.0
|
smallnamespace/fireplace,oftc-ftw/fireplace,amw2104/fireplace,Ragowit/fireplace,smallnamespace/fireplace,liujimj/fireplace,NightKev/fireplace,oftc-ftw/fireplace,Meerkov/fireplace,Meerkov/fireplace,Ragowit/fireplace,amw2104/fireplace,liujimj/fireplace,jleclanche/fireplace,beheh/fireplace
|
from ..utils import *
##
# Minions
# Snowchugger
class GVG_002:
events = Damage().on(
lambda self, target, amount, source: source is self and Freeze(target)
)
# Goblin Blastmage
class GVG_004:
play = Find(FRIENDLY_MINIONS + MECH) & Hit(RANDOM_ENEMY_CHARACTER, 1) * 4
# Flame Leviathan
class GVG_007:
in_hand = Draw(CONTROLLER, SELF).on(Hit(ALL_CHARACTERS, 2))
# Illuminator
class GVG_089:
events = OWN_TURN_END.on(Find(FRIENDLY_SECRETS) & Heal(FRIENDLY_HERO, 4))
##
# Spells
# Flamecannon
class GVG_001:
play = Hit(RANDOM_ENEMY_MINION, 4)
# Unstable Portal
class GVG_003:
play = Buff(Give(CONTROLLER, RandomMinion()), "GVG_003e")
# Echo of Medivh
class GVG_005:
play = Give(CONTROLLER, Copy(FRIENDLY_MINIONS))
Update Flame Leviathan to use draw script
|
from ..utils import *
##
# Minions
# Snowchugger
class GVG_002:
events = Damage().on(
lambda self, target, amount, source: source is self and Freeze(target)
)
# Goblin Blastmage
class GVG_004:
play = Find(FRIENDLY_MINIONS + MECH) & Hit(RANDOM_ENEMY_CHARACTER, 1) * 4
# Flame Leviathan
class GVG_007:
draw = Hit(ALL_CHARACTERS, 2)
# Illuminator
class GVG_089:
events = OWN_TURN_END.on(Find(FRIENDLY_SECRETS) & Heal(FRIENDLY_HERO, 4))
##
# Spells
# Flamecannon
class GVG_001:
play = Hit(RANDOM_ENEMY_MINION, 4)
# Unstable Portal
class GVG_003:
play = Buff(Give(CONTROLLER, RandomMinion()), "GVG_003e")
# Echo of Medivh
class GVG_005:
play = Give(CONTROLLER, Copy(FRIENDLY_MINIONS))
|
<commit_before>from ..utils import *
##
# Minions
# Snowchugger
class GVG_002:
events = Damage().on(
lambda self, target, amount, source: source is self and Freeze(target)
)
# Goblin Blastmage
class GVG_004:
play = Find(FRIENDLY_MINIONS + MECH) & Hit(RANDOM_ENEMY_CHARACTER, 1) * 4
# Flame Leviathan
class GVG_007:
in_hand = Draw(CONTROLLER, SELF).on(Hit(ALL_CHARACTERS, 2))
# Illuminator
class GVG_089:
events = OWN_TURN_END.on(Find(FRIENDLY_SECRETS) & Heal(FRIENDLY_HERO, 4))
##
# Spells
# Flamecannon
class GVG_001:
play = Hit(RANDOM_ENEMY_MINION, 4)
# Unstable Portal
class GVG_003:
play = Buff(Give(CONTROLLER, RandomMinion()), "GVG_003e")
# Echo of Medivh
class GVG_005:
play = Give(CONTROLLER, Copy(FRIENDLY_MINIONS))
<commit_msg>Update Flame Leviathan to use draw script<commit_after>
|
from ..utils import *
##
# Minions
# Snowchugger
class GVG_002:
events = Damage().on(
lambda self, target, amount, source: source is self and Freeze(target)
)
# Goblin Blastmage
class GVG_004:
play = Find(FRIENDLY_MINIONS + MECH) & Hit(RANDOM_ENEMY_CHARACTER, 1) * 4
# Flame Leviathan
class GVG_007:
draw = Hit(ALL_CHARACTERS, 2)
# Illuminator
class GVG_089:
events = OWN_TURN_END.on(Find(FRIENDLY_SECRETS) & Heal(FRIENDLY_HERO, 4))
##
# Spells
# Flamecannon
class GVG_001:
play = Hit(RANDOM_ENEMY_MINION, 4)
# Unstable Portal
class GVG_003:
play = Buff(Give(CONTROLLER, RandomMinion()), "GVG_003e")
# Echo of Medivh
class GVG_005:
play = Give(CONTROLLER, Copy(FRIENDLY_MINIONS))
|
from ..utils import *
##
# Minions
# Snowchugger
class GVG_002:
events = Damage().on(
lambda self, target, amount, source: source is self and Freeze(target)
)
# Goblin Blastmage
class GVG_004:
play = Find(FRIENDLY_MINIONS + MECH) & Hit(RANDOM_ENEMY_CHARACTER, 1) * 4
# Flame Leviathan
class GVG_007:
in_hand = Draw(CONTROLLER, SELF).on(Hit(ALL_CHARACTERS, 2))
# Illuminator
class GVG_089:
events = OWN_TURN_END.on(Find(FRIENDLY_SECRETS) & Heal(FRIENDLY_HERO, 4))
##
# Spells
# Flamecannon
class GVG_001:
play = Hit(RANDOM_ENEMY_MINION, 4)
# Unstable Portal
class GVG_003:
play = Buff(Give(CONTROLLER, RandomMinion()), "GVG_003e")
# Echo of Medivh
class GVG_005:
play = Give(CONTROLLER, Copy(FRIENDLY_MINIONS))
Update Flame Leviathan to use draw scriptfrom ..utils import *
##
# Minions
# Snowchugger
class GVG_002:
events = Damage().on(
lambda self, target, amount, source: source is self and Freeze(target)
)
# Goblin Blastmage
class GVG_004:
play = Find(FRIENDLY_MINIONS + MECH) & Hit(RANDOM_ENEMY_CHARACTER, 1) * 4
# Flame Leviathan
class GVG_007:
draw = Hit(ALL_CHARACTERS, 2)
# Illuminator
class GVG_089:
events = OWN_TURN_END.on(Find(FRIENDLY_SECRETS) & Heal(FRIENDLY_HERO, 4))
##
# Spells
# Flamecannon
class GVG_001:
play = Hit(RANDOM_ENEMY_MINION, 4)
# Unstable Portal
class GVG_003:
play = Buff(Give(CONTROLLER, RandomMinion()), "GVG_003e")
# Echo of Medivh
class GVG_005:
play = Give(CONTROLLER, Copy(FRIENDLY_MINIONS))
|
<commit_before>from ..utils import *
##
# Minions
# Snowchugger
class GVG_002:
events = Damage().on(
lambda self, target, amount, source: source is self and Freeze(target)
)
# Goblin Blastmage
class GVG_004:
play = Find(FRIENDLY_MINIONS + MECH) & Hit(RANDOM_ENEMY_CHARACTER, 1) * 4
# Flame Leviathan
class GVG_007:
in_hand = Draw(CONTROLLER, SELF).on(Hit(ALL_CHARACTERS, 2))
# Illuminator
class GVG_089:
events = OWN_TURN_END.on(Find(FRIENDLY_SECRETS) & Heal(FRIENDLY_HERO, 4))
##
# Spells
# Flamecannon
class GVG_001:
play = Hit(RANDOM_ENEMY_MINION, 4)
# Unstable Portal
class GVG_003:
play = Buff(Give(CONTROLLER, RandomMinion()), "GVG_003e")
# Echo of Medivh
class GVG_005:
play = Give(CONTROLLER, Copy(FRIENDLY_MINIONS))
<commit_msg>Update Flame Leviathan to use draw script<commit_after>from ..utils import *
##
# Minions
# Snowchugger
class GVG_002:
events = Damage().on(
lambda self, target, amount, source: source is self and Freeze(target)
)
# Goblin Blastmage
class GVG_004:
play = Find(FRIENDLY_MINIONS + MECH) & Hit(RANDOM_ENEMY_CHARACTER, 1) * 4
# Flame Leviathan
class GVG_007:
draw = Hit(ALL_CHARACTERS, 2)
# Illuminator
class GVG_089:
events = OWN_TURN_END.on(Find(FRIENDLY_SECRETS) & Heal(FRIENDLY_HERO, 4))
##
# Spells
# Flamecannon
class GVG_001:
play = Hit(RANDOM_ENEMY_MINION, 4)
# Unstable Portal
class GVG_003:
play = Buff(Give(CONTROLLER, RandomMinion()), "GVG_003e")
# Echo of Medivh
class GVG_005:
play = Give(CONTROLLER, Copy(FRIENDLY_MINIONS))
|
2814d7b8060d1f468bb6fb34d1460cdad1811031
|
tools/android/emulator/reporting.py
|
tools/android/emulator/reporting.py
|
"""An interface to report the status of emulator launches."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import logging
import os
import uuid
class NoOpReporter(object):
"""Captures all device and failure data and throws it away."""
def __init__(self):
pass
def ReportDeviceProperties(self, unused_emu_type, unused_props):
pass
def ReportFailure(self, unused_component, unused_details):
pass
def ReportToolsUsage(self, unused_namespace, unused_tool_name,
unused_runtime_ms, unused_success):
pass
def Emit(self):
pass
def MakeReporter():
"""Creates a reporter instance."""
return NoOpReporter()
|
"""An interface to report the status of emulator launches."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import logging
import os
import uuid
class NoOpReporter(object):
"""Captures all device and failure data and throws it away."""
def __init__(self):
pass
def ReportDeviceProperties(self, unused_emu_type, unused_props):
pass
def ReportFailure(self, unused_component, unused_details):
pass
def ReportToolsUsage(self, unused_namespace, unused_tool_name,
unused_runtime_ms, unused_success,
unused_total_runtime):
pass
def Emit(self):
pass
def MakeReporter():
"""Creates a reporter instance."""
return NoOpReporter()
|
Update the reporter interface to even track the total runtime
|
Update the reporter interface to even track the total runtime
PiperOrigin-RevId: 160982468
|
Python
|
apache-2.0
|
android/android-test,android/android-test,android/android-test,android/android-test,android/android-test
|
"""An interface to report the status of emulator launches."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import logging
import os
import uuid
class NoOpReporter(object):
"""Captures all device and failure data and throws it away."""
def __init__(self):
pass
def ReportDeviceProperties(self, unused_emu_type, unused_props):
pass
def ReportFailure(self, unused_component, unused_details):
pass
def ReportToolsUsage(self, unused_namespace, unused_tool_name,
unused_runtime_ms, unused_success):
pass
def Emit(self):
pass
def MakeReporter():
"""Creates a reporter instance."""
return NoOpReporter()
Update the reporter interface to even track the total runtime
PiperOrigin-RevId: 160982468
|
"""An interface to report the status of emulator launches."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import logging
import os
import uuid
class NoOpReporter(object):
"""Captures all device and failure data and throws it away."""
def __init__(self):
pass
def ReportDeviceProperties(self, unused_emu_type, unused_props):
pass
def ReportFailure(self, unused_component, unused_details):
pass
def ReportToolsUsage(self, unused_namespace, unused_tool_name,
unused_runtime_ms, unused_success,
unused_total_runtime):
pass
def Emit(self):
pass
def MakeReporter():
"""Creates a reporter instance."""
return NoOpReporter()
|
<commit_before>"""An interface to report the status of emulator launches."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import logging
import os
import uuid
class NoOpReporter(object):
"""Captures all device and failure data and throws it away."""
def __init__(self):
pass
def ReportDeviceProperties(self, unused_emu_type, unused_props):
pass
def ReportFailure(self, unused_component, unused_details):
pass
def ReportToolsUsage(self, unused_namespace, unused_tool_name,
unused_runtime_ms, unused_success):
pass
def Emit(self):
pass
def MakeReporter():
"""Creates a reporter instance."""
return NoOpReporter()
<commit_msg>Update the reporter interface to even track the total runtime
PiperOrigin-RevId: 160982468<commit_after>
|
"""An interface to report the status of emulator launches."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import logging
import os
import uuid
class NoOpReporter(object):
"""Captures all device and failure data and throws it away."""
def __init__(self):
pass
def ReportDeviceProperties(self, unused_emu_type, unused_props):
pass
def ReportFailure(self, unused_component, unused_details):
pass
def ReportToolsUsage(self, unused_namespace, unused_tool_name,
unused_runtime_ms, unused_success,
unused_total_runtime):
pass
def Emit(self):
pass
def MakeReporter():
"""Creates a reporter instance."""
return NoOpReporter()
|
"""An interface to report the status of emulator launches."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import logging
import os
import uuid
class NoOpReporter(object):
"""Captures all device and failure data and throws it away."""
def __init__(self):
pass
def ReportDeviceProperties(self, unused_emu_type, unused_props):
pass
def ReportFailure(self, unused_component, unused_details):
pass
def ReportToolsUsage(self, unused_namespace, unused_tool_name,
unused_runtime_ms, unused_success):
pass
def Emit(self):
pass
def MakeReporter():
"""Creates a reporter instance."""
return NoOpReporter()
Update the reporter interface to even track the total runtime
PiperOrigin-RevId: 160982468"""An interface to report the status of emulator launches."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import logging
import os
import uuid
class NoOpReporter(object):
"""Captures all device and failure data and throws it away."""
def __init__(self):
pass
def ReportDeviceProperties(self, unused_emu_type, unused_props):
pass
def ReportFailure(self, unused_component, unused_details):
pass
def ReportToolsUsage(self, unused_namespace, unused_tool_name,
unused_runtime_ms, unused_success,
unused_total_runtime):
pass
def Emit(self):
pass
def MakeReporter():
"""Creates a reporter instance."""
return NoOpReporter()
|
<commit_before>"""An interface to report the status of emulator launches."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import logging
import os
import uuid
class NoOpReporter(object):
"""Captures all device and failure data and throws it away."""
def __init__(self):
pass
def ReportDeviceProperties(self, unused_emu_type, unused_props):
pass
def ReportFailure(self, unused_component, unused_details):
pass
def ReportToolsUsage(self, unused_namespace, unused_tool_name,
unused_runtime_ms, unused_success):
pass
def Emit(self):
pass
def MakeReporter():
"""Creates a reporter instance."""
return NoOpReporter()
<commit_msg>Update the reporter interface to even track the total runtime
PiperOrigin-RevId: 160982468<commit_after>"""An interface to report the status of emulator launches."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import logging
import os
import uuid
class NoOpReporter(object):
"""Captures all device and failure data and throws it away."""
def __init__(self):
pass
def ReportDeviceProperties(self, unused_emu_type, unused_props):
pass
def ReportFailure(self, unused_component, unused_details):
pass
def ReportToolsUsage(self, unused_namespace, unused_tool_name,
unused_runtime_ms, unused_success,
unused_total_runtime):
pass
def Emit(self):
pass
def MakeReporter():
"""Creates a reporter instance."""
return NoOpReporter()
|
16ed5ff024a8ee04809cf9192727e1e7adcf565d
|
frigg/builds/serializers.py
|
frigg/builds/serializers.py
|
from rest_framework import serializers
from frigg.projects.models import Project
from .models import Build, BuildResult
class ProjectInlineSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'private',
'approved',
)
class BuildResultSerializer(serializers.ModelSerializer):
class Meta:
model = BuildResult
fields = (
'id',
'coverage',
'succeeded',
'tasks',
)
class BuildInlineSerializer(serializers.ModelSerializer):
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'build_number',
'branch',
'sha',
'pull_request_id',
'start_time',
'end_time',
'result'
)
class BuildSerializer(serializers.ModelSerializer):
project = ProjectInlineSerializer(read_only=True)
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'project',
'result',
'build_number',
'branch',
'pull_request_id',
'sha',
'start_time',
'end_time',
)
|
from rest_framework import serializers
from frigg.projects.models import Project
from .models import Build, BuildResult
class ProjectInlineSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'private',
'approved',
)
class BuildResultSerializer(serializers.ModelSerializer):
class Meta:
model = BuildResult
fields = (
'id',
'coverage',
'succeeded',
'tasks',
'setup_tasks',
)
class BuildInlineSerializer(serializers.ModelSerializer):
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'build_number',
'branch',
'sha',
'pull_request_id',
'start_time',
'end_time',
'result',
'short_message',
'message',
'color',
'pull_request_url',
'commit_url',
)
class BuildSerializer(serializers.ModelSerializer):
project = ProjectInlineSerializer(read_only=True)
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'project',
'result',
'build_number',
'branch',
'pull_request_id',
'sha',
'start_time',
'end_time',
'short_message',
'message',
'color',
'pull_request_url',
'commit_url',
)
|
Add more data to the api
|
Add more data to the api
|
Python
|
mit
|
frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq
|
from rest_framework import serializers
from frigg.projects.models import Project
from .models import Build, BuildResult
class ProjectInlineSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'private',
'approved',
)
class BuildResultSerializer(serializers.ModelSerializer):
class Meta:
model = BuildResult
fields = (
'id',
'coverage',
'succeeded',
'tasks',
)
class BuildInlineSerializer(serializers.ModelSerializer):
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'build_number',
'branch',
'sha',
'pull_request_id',
'start_time',
'end_time',
'result'
)
class BuildSerializer(serializers.ModelSerializer):
project = ProjectInlineSerializer(read_only=True)
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'project',
'result',
'build_number',
'branch',
'pull_request_id',
'sha',
'start_time',
'end_time',
)
Add more data to the api
|
from rest_framework import serializers
from frigg.projects.models import Project
from .models import Build, BuildResult
class ProjectInlineSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'private',
'approved',
)
class BuildResultSerializer(serializers.ModelSerializer):
class Meta:
model = BuildResult
fields = (
'id',
'coverage',
'succeeded',
'tasks',
'setup_tasks',
)
class BuildInlineSerializer(serializers.ModelSerializer):
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'build_number',
'branch',
'sha',
'pull_request_id',
'start_time',
'end_time',
'result',
'short_message',
'message',
'color',
'pull_request_url',
'commit_url',
)
class BuildSerializer(serializers.ModelSerializer):
project = ProjectInlineSerializer(read_only=True)
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'project',
'result',
'build_number',
'branch',
'pull_request_id',
'sha',
'start_time',
'end_time',
'short_message',
'message',
'color',
'pull_request_url',
'commit_url',
)
|
<commit_before>from rest_framework import serializers
from frigg.projects.models import Project
from .models import Build, BuildResult
class ProjectInlineSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'private',
'approved',
)
class BuildResultSerializer(serializers.ModelSerializer):
class Meta:
model = BuildResult
fields = (
'id',
'coverage',
'succeeded',
'tasks',
)
class BuildInlineSerializer(serializers.ModelSerializer):
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'build_number',
'branch',
'sha',
'pull_request_id',
'start_time',
'end_time',
'result'
)
class BuildSerializer(serializers.ModelSerializer):
project = ProjectInlineSerializer(read_only=True)
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'project',
'result',
'build_number',
'branch',
'pull_request_id',
'sha',
'start_time',
'end_time',
)
<commit_msg>Add more data to the api<commit_after>
|
from rest_framework import serializers
from frigg.projects.models import Project
from .models import Build, BuildResult
class ProjectInlineSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'private',
'approved',
)
class BuildResultSerializer(serializers.ModelSerializer):
class Meta:
model = BuildResult
fields = (
'id',
'coverage',
'succeeded',
'tasks',
'setup_tasks',
)
class BuildInlineSerializer(serializers.ModelSerializer):
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'build_number',
'branch',
'sha',
'pull_request_id',
'start_time',
'end_time',
'result',
'short_message',
'message',
'color',
'pull_request_url',
'commit_url',
)
class BuildSerializer(serializers.ModelSerializer):
project = ProjectInlineSerializer(read_only=True)
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'project',
'result',
'build_number',
'branch',
'pull_request_id',
'sha',
'start_time',
'end_time',
'short_message',
'message',
'color',
'pull_request_url',
'commit_url',
)
|
from rest_framework import serializers
from frigg.projects.models import Project
from .models import Build, BuildResult
class ProjectInlineSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'private',
'approved',
)
class BuildResultSerializer(serializers.ModelSerializer):
class Meta:
model = BuildResult
fields = (
'id',
'coverage',
'succeeded',
'tasks',
)
class BuildInlineSerializer(serializers.ModelSerializer):
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'build_number',
'branch',
'sha',
'pull_request_id',
'start_time',
'end_time',
'result'
)
class BuildSerializer(serializers.ModelSerializer):
project = ProjectInlineSerializer(read_only=True)
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'project',
'result',
'build_number',
'branch',
'pull_request_id',
'sha',
'start_time',
'end_time',
)
Add more data to the apifrom rest_framework import serializers
from frigg.projects.models import Project
from .models import Build, BuildResult
class ProjectInlineSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'private',
'approved',
)
class BuildResultSerializer(serializers.ModelSerializer):
class Meta:
model = BuildResult
fields = (
'id',
'coverage',
'succeeded',
'tasks',
'setup_tasks',
)
class BuildInlineSerializer(serializers.ModelSerializer):
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'build_number',
'branch',
'sha',
'pull_request_id',
'start_time',
'end_time',
'result',
'short_message',
'message',
'color',
'pull_request_url',
'commit_url',
)
class BuildSerializer(serializers.ModelSerializer):
project = ProjectInlineSerializer(read_only=True)
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'project',
'result',
'build_number',
'branch',
'pull_request_id',
'sha',
'start_time',
'end_time',
'short_message',
'message',
'color',
'pull_request_url',
'commit_url',
)
|
<commit_before>from rest_framework import serializers
from frigg.projects.models import Project
from .models import Build, BuildResult
class ProjectInlineSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'private',
'approved',
)
class BuildResultSerializer(serializers.ModelSerializer):
class Meta:
model = BuildResult
fields = (
'id',
'coverage',
'succeeded',
'tasks',
)
class BuildInlineSerializer(serializers.ModelSerializer):
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'build_number',
'branch',
'sha',
'pull_request_id',
'start_time',
'end_time',
'result'
)
class BuildSerializer(serializers.ModelSerializer):
project = ProjectInlineSerializer(read_only=True)
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'project',
'result',
'build_number',
'branch',
'pull_request_id',
'sha',
'start_time',
'end_time',
)
<commit_msg>Add more data to the api<commit_after>from rest_framework import serializers
from frigg.projects.models import Project
from .models import Build, BuildResult
class ProjectInlineSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'private',
'approved',
)
class BuildResultSerializer(serializers.ModelSerializer):
class Meta:
model = BuildResult
fields = (
'id',
'coverage',
'succeeded',
'tasks',
'setup_tasks',
)
class BuildInlineSerializer(serializers.ModelSerializer):
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'build_number',
'branch',
'sha',
'pull_request_id',
'start_time',
'end_time',
'result',
'short_message',
'message',
'color',
'pull_request_url',
'commit_url',
)
class BuildSerializer(serializers.ModelSerializer):
project = ProjectInlineSerializer(read_only=True)
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'project',
'result',
'build_number',
'branch',
'pull_request_id',
'sha',
'start_time',
'end_time',
'short_message',
'message',
'color',
'pull_request_url',
'commit_url',
)
|
8ed7fff1b7ec0d069e9a4545785bf99768afe761
|
flask_jsonapiview/fields.py
|
flask_jsonapiview/fields.py
|
from marshmallow import fields, ValidationError
from .exceptions import IncorrectTypeError
__all__ = ('StubObject',)
# -----------------------------------------------------------------------------
class Type(fields.Field):
_CHECK_ATTRIBUTE = False
def _add_to_schema(self, field_name, schema):
super(Type, self)._add_to_schema(field_name, schema)
self._type = schema.opts.type
def _serialize(self, value, attr, obj):
return self._type
def _deserialize(self, value, attr, data):
if value != self._type:
raise IncorrectTypeError(value, self._type)
# -----------------------------------------------------------------------------
class StubObject(fields.Field):
def __init__(self, type, **kwargs):
super(StubObject, self).__init__(**kwargs)
self._type = type
def _serialize(self, value, attr, obj):
return {'type': self._type, 'id': value}
def _deserialize(self, value, attr, data):
try:
if value['type'] != self._type:
raise IncorrectTypeError(value['type'], self._type)
if not isinstance(value['id'], basestring):
raise ValidationError("incorrect id type")
except (TypeError, KeyError):
raise ValidationError("incorrect input shape")
return value['id']
|
from marshmallow import fields, ValidationError
from marshmallow.compat import basestring
from .exceptions import IncorrectTypeError
__all__ = ('StubObject',)
# -----------------------------------------------------------------------------
class Type(fields.Field):
_CHECK_ATTRIBUTE = False
def _add_to_schema(self, field_name, schema):
super(Type, self)._add_to_schema(field_name, schema)
self._type = schema.opts.type
def _serialize(self, value, attr, obj):
return self._type
def _deserialize(self, value, attr, data):
if value != self._type:
raise IncorrectTypeError(value, self._type)
# -----------------------------------------------------------------------------
class StubObject(fields.Field):
def __init__(self, type, **kwargs):
super(StubObject, self).__init__(**kwargs)
self._type = type
def _serialize(self, value, attr, obj):
return {'type': self._type, 'id': value}
def _deserialize(self, value, attr, data):
try:
if value['type'] != self._type:
raise IncorrectTypeError(value['type'], self._type)
if not isinstance(value['id'], basestring):
raise ValidationError("incorrect id type")
except (TypeError, KeyError):
raise ValidationError("incorrect input shape")
return value['id']
|
Use compat basestring for id validation
|
Use compat basestring for id validation
|
Python
|
mit
|
taion/flask-jsonapiview,4Catalyzer/flask-resty,4Catalyzer/flask-jsonapiview
|
from marshmallow import fields, ValidationError
from .exceptions import IncorrectTypeError
__all__ = ('StubObject',)
# -----------------------------------------------------------------------------
class Type(fields.Field):
_CHECK_ATTRIBUTE = False
def _add_to_schema(self, field_name, schema):
super(Type, self)._add_to_schema(field_name, schema)
self._type = schema.opts.type
def _serialize(self, value, attr, obj):
return self._type
def _deserialize(self, value, attr, data):
if value != self._type:
raise IncorrectTypeError(value, self._type)
# -----------------------------------------------------------------------------
class StubObject(fields.Field):
def __init__(self, type, **kwargs):
super(StubObject, self).__init__(**kwargs)
self._type = type
def _serialize(self, value, attr, obj):
return {'type': self._type, 'id': value}
def _deserialize(self, value, attr, data):
try:
if value['type'] != self._type:
raise IncorrectTypeError(value['type'], self._type)
if not isinstance(value['id'], basestring):
raise ValidationError("incorrect id type")
except (TypeError, KeyError):
raise ValidationError("incorrect input shape")
return value['id']
Use compat basestring for id validation
|
from marshmallow import fields, ValidationError
from marshmallow.compat import basestring
from .exceptions import IncorrectTypeError
__all__ = ('StubObject',)
# -----------------------------------------------------------------------------
class Type(fields.Field):
_CHECK_ATTRIBUTE = False
def _add_to_schema(self, field_name, schema):
super(Type, self)._add_to_schema(field_name, schema)
self._type = schema.opts.type
def _serialize(self, value, attr, obj):
return self._type
def _deserialize(self, value, attr, data):
if value != self._type:
raise IncorrectTypeError(value, self._type)
# -----------------------------------------------------------------------------
class StubObject(fields.Field):
def __init__(self, type, **kwargs):
super(StubObject, self).__init__(**kwargs)
self._type = type
def _serialize(self, value, attr, obj):
return {'type': self._type, 'id': value}
def _deserialize(self, value, attr, data):
try:
if value['type'] != self._type:
raise IncorrectTypeError(value['type'], self._type)
if not isinstance(value['id'], basestring):
raise ValidationError("incorrect id type")
except (TypeError, KeyError):
raise ValidationError("incorrect input shape")
return value['id']
|
<commit_before>from marshmallow import fields, ValidationError
from .exceptions import IncorrectTypeError
__all__ = ('StubObject',)
# -----------------------------------------------------------------------------
class Type(fields.Field):
_CHECK_ATTRIBUTE = False
def _add_to_schema(self, field_name, schema):
super(Type, self)._add_to_schema(field_name, schema)
self._type = schema.opts.type
def _serialize(self, value, attr, obj):
return self._type
def _deserialize(self, value, attr, data):
if value != self._type:
raise IncorrectTypeError(value, self._type)
# -----------------------------------------------------------------------------
class StubObject(fields.Field):
def __init__(self, type, **kwargs):
super(StubObject, self).__init__(**kwargs)
self._type = type
def _serialize(self, value, attr, obj):
return {'type': self._type, 'id': value}
def _deserialize(self, value, attr, data):
try:
if value['type'] != self._type:
raise IncorrectTypeError(value['type'], self._type)
if not isinstance(value['id'], basestring):
raise ValidationError("incorrect id type")
except (TypeError, KeyError):
raise ValidationError("incorrect input shape")
return value['id']
<commit_msg>Use compat basestring for id validation<commit_after>
|
from marshmallow import fields, ValidationError
from marshmallow.compat import basestring
from .exceptions import IncorrectTypeError
__all__ = ('StubObject',)
# -----------------------------------------------------------------------------
class Type(fields.Field):
_CHECK_ATTRIBUTE = False
def _add_to_schema(self, field_name, schema):
super(Type, self)._add_to_schema(field_name, schema)
self._type = schema.opts.type
def _serialize(self, value, attr, obj):
return self._type
def _deserialize(self, value, attr, data):
if value != self._type:
raise IncorrectTypeError(value, self._type)
# -----------------------------------------------------------------------------
class StubObject(fields.Field):
def __init__(self, type, **kwargs):
super(StubObject, self).__init__(**kwargs)
self._type = type
def _serialize(self, value, attr, obj):
return {'type': self._type, 'id': value}
def _deserialize(self, value, attr, data):
try:
if value['type'] != self._type:
raise IncorrectTypeError(value['type'], self._type)
if not isinstance(value['id'], basestring):
raise ValidationError("incorrect id type")
except (TypeError, KeyError):
raise ValidationError("incorrect input shape")
return value['id']
|
from marshmallow import fields, ValidationError
from .exceptions import IncorrectTypeError
__all__ = ('StubObject',)
# -----------------------------------------------------------------------------
class Type(fields.Field):
_CHECK_ATTRIBUTE = False
def _add_to_schema(self, field_name, schema):
super(Type, self)._add_to_schema(field_name, schema)
self._type = schema.opts.type
def _serialize(self, value, attr, obj):
return self._type
def _deserialize(self, value, attr, data):
if value != self._type:
raise IncorrectTypeError(value, self._type)
# -----------------------------------------------------------------------------
class StubObject(fields.Field):
def __init__(self, type, **kwargs):
super(StubObject, self).__init__(**kwargs)
self._type = type
def _serialize(self, value, attr, obj):
return {'type': self._type, 'id': value}
def _deserialize(self, value, attr, data):
try:
if value['type'] != self._type:
raise IncorrectTypeError(value['type'], self._type)
if not isinstance(value['id'], basestring):
raise ValidationError("incorrect id type")
except (TypeError, KeyError):
raise ValidationError("incorrect input shape")
return value['id']
Use compat basestring for id validationfrom marshmallow import fields, ValidationError
from marshmallow.compat import basestring
from .exceptions import IncorrectTypeError
__all__ = ('StubObject',)
# -----------------------------------------------------------------------------
class Type(fields.Field):
_CHECK_ATTRIBUTE = False
def _add_to_schema(self, field_name, schema):
super(Type, self)._add_to_schema(field_name, schema)
self._type = schema.opts.type
def _serialize(self, value, attr, obj):
return self._type
def _deserialize(self, value, attr, data):
if value != self._type:
raise IncorrectTypeError(value, self._type)
# -----------------------------------------------------------------------------
class StubObject(fields.Field):
def __init__(self, type, **kwargs):
super(StubObject, self).__init__(**kwargs)
self._type = type
def _serialize(self, value, attr, obj):
return {'type': self._type, 'id': value}
def _deserialize(self, value, attr, data):
try:
if value['type'] != self._type:
raise IncorrectTypeError(value['type'], self._type)
if not isinstance(value['id'], basestring):
raise ValidationError("incorrect id type")
except (TypeError, KeyError):
raise ValidationError("incorrect input shape")
return value['id']
|
<commit_before>from marshmallow import fields, ValidationError
from .exceptions import IncorrectTypeError
__all__ = ('StubObject',)
# -----------------------------------------------------------------------------
class Type(fields.Field):
_CHECK_ATTRIBUTE = False
def _add_to_schema(self, field_name, schema):
super(Type, self)._add_to_schema(field_name, schema)
self._type = schema.opts.type
def _serialize(self, value, attr, obj):
return self._type
def _deserialize(self, value, attr, data):
if value != self._type:
raise IncorrectTypeError(value, self._type)
# -----------------------------------------------------------------------------
class StubObject(fields.Field):
def __init__(self, type, **kwargs):
super(StubObject, self).__init__(**kwargs)
self._type = type
def _serialize(self, value, attr, obj):
return {'type': self._type, 'id': value}
def _deserialize(self, value, attr, data):
try:
if value['type'] != self._type:
raise IncorrectTypeError(value['type'], self._type)
if not isinstance(value['id'], basestring):
raise ValidationError("incorrect id type")
except (TypeError, KeyError):
raise ValidationError("incorrect input shape")
return value['id']
<commit_msg>Use compat basestring for id validation<commit_after>from marshmallow import fields, ValidationError
from marshmallow.compat import basestring
from .exceptions import IncorrectTypeError
__all__ = ('StubObject',)
# -----------------------------------------------------------------------------
class Type(fields.Field):
_CHECK_ATTRIBUTE = False
def _add_to_schema(self, field_name, schema):
super(Type, self)._add_to_schema(field_name, schema)
self._type = schema.opts.type
def _serialize(self, value, attr, obj):
return self._type
def _deserialize(self, value, attr, data):
if value != self._type:
raise IncorrectTypeError(value, self._type)
# -----------------------------------------------------------------------------
class StubObject(fields.Field):
def __init__(self, type, **kwargs):
super(StubObject, self).__init__(**kwargs)
self._type = type
def _serialize(self, value, attr, obj):
return {'type': self._type, 'id': value}
def _deserialize(self, value, attr, data):
try:
if value['type'] != self._type:
raise IncorrectTypeError(value['type'], self._type)
if not isinstance(value['id'], basestring):
raise ValidationError("incorrect id type")
except (TypeError, KeyError):
raise ValidationError("incorrect input shape")
return value['id']
|
555536b93609ab3b1c29475d51408aaf7eda4675
|
cray_test.py
|
cray_test.py
|
# -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest
from yatest import testpost, testpage, testutility, testconfig
if __name__ == '__main__':
all_test_suites = []
all_test_suites.append(testpost.get_test_suites())
all_test_suites.append(testpage.get_test_suites())
all_test_suites.append(testutility.get_test_suites())
all_test_suites.append(testconfig.get_test_suites())
alltests = unittest.TestSuite(all_test_suites)
status = not unittest.TextTestRunner(verbosity=2).run(alltests).wasSuccessful()
sys.exit(status)
|
# -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest
from yatest import testpost, testpage, testutility, testconfig, testgenerator, testpostmanager
if __name__ == '__main__':
all_test_suites = []
all_test_suites.append(testpost.get_test_suites())
all_test_suites.append(testpage.get_test_suites())
all_test_suites.append(testutility.get_test_suites())
all_test_suites.append(testconfig.get_test_suites())
all_test_suites.append(testgenerator.get_test_suites())
all_test_suites.append(testpostmanager.get_test_suites())
alltests = unittest.TestSuite(all_test_suites)
status = not unittest.TextTestRunner(verbosity=2).run(alltests).wasSuccessful()
sys.exit(status)
|
Add new added test cases to travis.
|
Add new added test cases to travis.
|
Python
|
mit
|
boluny/cray,boluny/cray
|
# -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest
from yatest import testpost, testpage, testutility, testconfig
if __name__ == '__main__':
all_test_suites = []
all_test_suites.append(testpost.get_test_suites())
all_test_suites.append(testpage.get_test_suites())
all_test_suites.append(testutility.get_test_suites())
all_test_suites.append(testconfig.get_test_suites())
alltests = unittest.TestSuite(all_test_suites)
status = not unittest.TextTestRunner(verbosity=2).run(alltests).wasSuccessful()
sys.exit(status)
Add new added test cases to travis.
|
# -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest
from yatest import testpost, testpage, testutility, testconfig, testgenerator, testpostmanager
if __name__ == '__main__':
all_test_suites = []
all_test_suites.append(testpost.get_test_suites())
all_test_suites.append(testpage.get_test_suites())
all_test_suites.append(testutility.get_test_suites())
all_test_suites.append(testconfig.get_test_suites())
all_test_suites.append(testgenerator.get_test_suites())
all_test_suites.append(testpostmanager.get_test_suites())
alltests = unittest.TestSuite(all_test_suites)
status = not unittest.TextTestRunner(verbosity=2).run(alltests).wasSuccessful()
sys.exit(status)
|
<commit_before># -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest
from yatest import testpost, testpage, testutility, testconfig
if __name__ == '__main__':
all_test_suites = []
all_test_suites.append(testpost.get_test_suites())
all_test_suites.append(testpage.get_test_suites())
all_test_suites.append(testutility.get_test_suites())
all_test_suites.append(testconfig.get_test_suites())
alltests = unittest.TestSuite(all_test_suites)
status = not unittest.TextTestRunner(verbosity=2).run(alltests).wasSuccessful()
sys.exit(status)
<commit_msg>Add new added test cases to travis.<commit_after>
|
# -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest
from yatest import testpost, testpage, testutility, testconfig, testgenerator, testpostmanager
if __name__ == '__main__':
all_test_suites = []
all_test_suites.append(testpost.get_test_suites())
all_test_suites.append(testpage.get_test_suites())
all_test_suites.append(testutility.get_test_suites())
all_test_suites.append(testconfig.get_test_suites())
all_test_suites.append(testgenerator.get_test_suites())
all_test_suites.append(testpostmanager.get_test_suites())
alltests = unittest.TestSuite(all_test_suites)
status = not unittest.TextTestRunner(verbosity=2).run(alltests).wasSuccessful()
sys.exit(status)
|
# -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest
from yatest import testpost, testpage, testutility, testconfig
if __name__ == '__main__':
all_test_suites = []
all_test_suites.append(testpost.get_test_suites())
all_test_suites.append(testpage.get_test_suites())
all_test_suites.append(testutility.get_test_suites())
all_test_suites.append(testconfig.get_test_suites())
alltests = unittest.TestSuite(all_test_suites)
status = not unittest.TextTestRunner(verbosity=2).run(alltests).wasSuccessful()
sys.exit(status)
Add new added test cases to travis.# -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest
from yatest import testpost, testpage, testutility, testconfig, testgenerator, testpostmanager
if __name__ == '__main__':
all_test_suites = []
all_test_suites.append(testpost.get_test_suites())
all_test_suites.append(testpage.get_test_suites())
all_test_suites.append(testutility.get_test_suites())
all_test_suites.append(testconfig.get_test_suites())
all_test_suites.append(testgenerator.get_test_suites())
all_test_suites.append(testpostmanager.get_test_suites())
alltests = unittest.TestSuite(all_test_suites)
status = not unittest.TextTestRunner(verbosity=2).run(alltests).wasSuccessful()
sys.exit(status)
|
<commit_before># -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest
from yatest import testpost, testpage, testutility, testconfig
if __name__ == '__main__':
all_test_suites = []
all_test_suites.append(testpost.get_test_suites())
all_test_suites.append(testpage.get_test_suites())
all_test_suites.append(testutility.get_test_suites())
all_test_suites.append(testconfig.get_test_suites())
alltests = unittest.TestSuite(all_test_suites)
status = not unittest.TextTestRunner(verbosity=2).run(alltests).wasSuccessful()
sys.exit(status)
<commit_msg>Add new added test cases to travis.<commit_after># -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest
from yatest import testpost, testpage, testutility, testconfig, testgenerator, testpostmanager
if __name__ == '__main__':
all_test_suites = []
all_test_suites.append(testpost.get_test_suites())
all_test_suites.append(testpage.get_test_suites())
all_test_suites.append(testutility.get_test_suites())
all_test_suites.append(testconfig.get_test_suites())
all_test_suites.append(testgenerator.get_test_suites())
all_test_suites.append(testpostmanager.get_test_suites())
alltests = unittest.TestSuite(all_test_suites)
status = not unittest.TextTestRunner(verbosity=2).run(alltests).wasSuccessful()
sys.exit(status)
|
e56e85b56fe68112c40f4d76ce103d5c10d6dea7
|
kyokai/asphalt.py
|
kyokai/asphalt.py
|
"""
Asphalt framework mixin for Kyokai.
"""
import logging
import asyncio
from functools import partial
from typing import Union
from asphalt.core import Component, resolve_reference, Context
from typeguard import check_argument_types
from kyokai.app import Kyokai
from kyokai.protocol import KyokaiProtocol
logger = logging.getLogger("Kyokai")
class KyoukaiComponent(Component):
def __init__(self, app: Union[str, Kyokai], ip: str = '0.0.0.0', port: int = 4444):
assert check_argument_types()
self.app = resolve_reference(app)
self.ip = ip
self.port = port
async def start(self, ctx: Context):
"""
Starts a Kyokai server.
"""
protocol_factory = partial(KyokaiProtocol, self.app, ctx)
server = await asyncio.get_event_loop().create_server(protocol_factory)
logger.info("Kyokai serving on {}:{}.".format(self.ip, self.port))
|
"""
Asphalt framework mixin for Kyokai.
"""
import logging
import asyncio
from functools import partial
from typing import Union
from asphalt.core import Component, resolve_reference, Context
from typeguard import check_argument_types
from kyokai.app import Kyokai
from kyokai.protocol import KyokaiProtocol
logger = logging.getLogger("Kyokai")
class KyoukaiComponent(Component):
def __init__(self, app: Union[str, Kyokai], ip: str = '0.0.0.0', port: int = 4444):
assert check_argument_types()
self.app = resolve_reference(app)
self.ip = ip
self.port = port
async def start(self, ctx: Context):
"""
Starts a Kyokai server.
"""
protocol_factory = partial(KyokaiProtocol, self.app, ctx)
server = await asyncio.get_event_loop().create_server(protocol_factory, self.ip, self.port)
logger.info("Kyokai serving on {}:{}.".format(self.ip, self.port))
|
Fix server not being created properly.
|
Fix server not being created properly.
|
Python
|
mit
|
SunDwarf/Kyoukai
|
"""
Asphalt framework mixin for Kyokai.
"""
import logging
import asyncio
from functools import partial
from typing import Union
from asphalt.core import Component, resolve_reference, Context
from typeguard import check_argument_types
from kyokai.app import Kyokai
from kyokai.protocol import KyokaiProtocol
logger = logging.getLogger("Kyokai")
class KyoukaiComponent(Component):
def __init__(self, app: Union[str, Kyokai], ip: str = '0.0.0.0', port: int = 4444):
assert check_argument_types()
self.app = resolve_reference(app)
self.ip = ip
self.port = port
async def start(self, ctx: Context):
"""
Starts a Kyokai server.
"""
protocol_factory = partial(KyokaiProtocol, self.app, ctx)
server = await asyncio.get_event_loop().create_server(protocol_factory)
logger.info("Kyokai serving on {}:{}.".format(self.ip, self.port))
Fix server not being created properly.
|
"""
Asphalt framework mixin for Kyokai.
"""
import logging
import asyncio
from functools import partial
from typing import Union
from asphalt.core import Component, resolve_reference, Context
from typeguard import check_argument_types
from kyokai.app import Kyokai
from kyokai.protocol import KyokaiProtocol
logger = logging.getLogger("Kyokai")
class KyoukaiComponent(Component):
def __init__(self, app: Union[str, Kyokai], ip: str = '0.0.0.0', port: int = 4444):
assert check_argument_types()
self.app = resolve_reference(app)
self.ip = ip
self.port = port
async def start(self, ctx: Context):
"""
Starts a Kyokai server.
"""
protocol_factory = partial(KyokaiProtocol, self.app, ctx)
server = await asyncio.get_event_loop().create_server(protocol_factory, self.ip, self.port)
logger.info("Kyokai serving on {}:{}.".format(self.ip, self.port))
|
<commit_before>"""
Asphalt framework mixin for Kyokai.
"""
import logging
import asyncio
from functools import partial
from typing import Union
from asphalt.core import Component, resolve_reference, Context
from typeguard import check_argument_types
from kyokai.app import Kyokai
from kyokai.protocol import KyokaiProtocol
logger = logging.getLogger("Kyokai")
class KyoukaiComponent(Component):
def __init__(self, app: Union[str, Kyokai], ip: str = '0.0.0.0', port: int = 4444):
assert check_argument_types()
self.app = resolve_reference(app)
self.ip = ip
self.port = port
async def start(self, ctx: Context):
"""
Starts a Kyokai server.
"""
protocol_factory = partial(KyokaiProtocol, self.app, ctx)
server = await asyncio.get_event_loop().create_server(protocol_factory)
logger.info("Kyokai serving on {}:{}.".format(self.ip, self.port))
<commit_msg>Fix server not being created properly.<commit_after>
|
"""
Asphalt framework mixin for Kyokai.
"""
import logging
import asyncio
from functools import partial
from typing import Union
from asphalt.core import Component, resolve_reference, Context
from typeguard import check_argument_types
from kyokai.app import Kyokai
from kyokai.protocol import KyokaiProtocol
logger = logging.getLogger("Kyokai")
class KyoukaiComponent(Component):
def __init__(self, app: Union[str, Kyokai], ip: str = '0.0.0.0', port: int = 4444):
assert check_argument_types()
self.app = resolve_reference(app)
self.ip = ip
self.port = port
async def start(self, ctx: Context):
"""
Starts a Kyokai server.
"""
protocol_factory = partial(KyokaiProtocol, self.app, ctx)
server = await asyncio.get_event_loop().create_server(protocol_factory, self.ip, self.port)
logger.info("Kyokai serving on {}:{}.".format(self.ip, self.port))
|
"""
Asphalt framework mixin for Kyokai.
"""
import logging
import asyncio
from functools import partial
from typing import Union
from asphalt.core import Component, resolve_reference, Context
from typeguard import check_argument_types
from kyokai.app import Kyokai
from kyokai.protocol import KyokaiProtocol
logger = logging.getLogger("Kyokai")
class KyoukaiComponent(Component):
def __init__(self, app: Union[str, Kyokai], ip: str = '0.0.0.0', port: int = 4444):
assert check_argument_types()
self.app = resolve_reference(app)
self.ip = ip
self.port = port
async def start(self, ctx: Context):
"""
Starts a Kyokai server.
"""
protocol_factory = partial(KyokaiProtocol, self.app, ctx)
server = await asyncio.get_event_loop().create_server(protocol_factory)
logger.info("Kyokai serving on {}:{}.".format(self.ip, self.port))
Fix server not being created properly."""
Asphalt framework mixin for Kyokai.
"""
import logging
import asyncio
from functools import partial
from typing import Union
from asphalt.core import Component, resolve_reference, Context
from typeguard import check_argument_types
from kyokai.app import Kyokai
from kyokai.protocol import KyokaiProtocol
logger = logging.getLogger("Kyokai")
class KyoukaiComponent(Component):
def __init__(self, app: Union[str, Kyokai], ip: str = '0.0.0.0', port: int = 4444):
assert check_argument_types()
self.app = resolve_reference(app)
self.ip = ip
self.port = port
async def start(self, ctx: Context):
"""
Starts a Kyokai server.
"""
protocol_factory = partial(KyokaiProtocol, self.app, ctx)
server = await asyncio.get_event_loop().create_server(protocol_factory, self.ip, self.port)
logger.info("Kyokai serving on {}:{}.".format(self.ip, self.port))
|
<commit_before>"""
Asphalt framework mixin for Kyokai.
"""
import logging
import asyncio
from functools import partial
from typing import Union
from asphalt.core import Component, resolve_reference, Context
from typeguard import check_argument_types
from kyokai.app import Kyokai
from kyokai.protocol import KyokaiProtocol
logger = logging.getLogger("Kyokai")
class KyoukaiComponent(Component):
def __init__(self, app: Union[str, Kyokai], ip: str = '0.0.0.0', port: int = 4444):
assert check_argument_types()
self.app = resolve_reference(app)
self.ip = ip
self.port = port
async def start(self, ctx: Context):
"""
Starts a Kyokai server.
"""
protocol_factory = partial(KyokaiProtocol, self.app, ctx)
server = await asyncio.get_event_loop().create_server(protocol_factory)
logger.info("Kyokai serving on {}:{}.".format(self.ip, self.port))
<commit_msg>Fix server not being created properly.<commit_after>"""
Asphalt framework mixin for Kyokai.
"""
import logging
import asyncio
from functools import partial
from typing import Union
from asphalt.core import Component, resolve_reference, Context
from typeguard import check_argument_types
from kyokai.app import Kyokai
from kyokai.protocol import KyokaiProtocol
logger = logging.getLogger("Kyokai")
class KyoukaiComponent(Component):
def __init__(self, app: Union[str, Kyokai], ip: str = '0.0.0.0', port: int = 4444):
assert check_argument_types()
self.app = resolve_reference(app)
self.ip = ip
self.port = port
async def start(self, ctx: Context):
"""
Starts a Kyokai server.
"""
protocol_factory = partial(KyokaiProtocol, self.app, ctx)
server = await asyncio.get_event_loop().create_server(protocol_factory, self.ip, self.port)
logger.info("Kyokai serving on {}:{}.".format(self.ip, self.port))
|
52bca1129cfe21669b5f7faf2e99e148a559bd32
|
src/utils/build_dependencies.py
|
src/utils/build_dependencies.py
|
#!/usr/bin/env python
import glob
dependencies = {}
for src in glob.iglob('*.F90'):
module = src.strip('.F90')
d = set()
for line in open(src, 'r'):
words = line.split()
if words and words[0].lower() == 'use':
name = words[1].strip(',')
if name in ['mpi','hdf5','h5lt']:
continue
if name.startswith('xml_data_'):
name = name.replace('xml_data_', 'templates/')
d.add(name)
if d:
d = list(d)
d.sort()
dependencies[module] = d
keys = dependencies.keys()
keys.sort()
for module in keys:
for dep in dependencies[module]:
print("{0}.o: {1}.o".format(module, dep))
print('')
|
#!/usr/bin/env python
import glob
import re
dependencies = {}
for src in glob.iglob('*.F90'):
module = src.strip('.F90')
deps = set()
d = re.findall(r'\n\s*use\s+(\w+)',
open(src,'r').read())
for name in d:
if name in ['mpi','hdf5','h5lt']:
continue
if name.startswith('xml_data_'):
name = name.replace('xml_data_', 'templates/')
deps.add(name)
if deps:
dependencies[module] = sorted(list(deps))
keys = dependencies.keys()
keys.sort()
for module in keys:
for dep in dependencies[module]:
print("{0}.o: {1}.o".format(module, dep))
print('')
|
Fix potential bug in build dependencies script. If you gave it ' use module,only: ...' before it would not work.
|
Fix potential bug in build dependencies script. If you gave it ' use module,only: ...' before it would not work.
|
Python
|
mit
|
mjlong/openmc,wbinventor/openmc,kellyrowland/openmc,lilulu/openmc,liangjg/openmc,mit-crpg/openmc,johnnyliu27/openmc,smharper/openmc,keadyk/openmc_mg_prepush,smharper/openmc,paulromano/openmc,johnnyliu27/openmc,smharper/openmc,liangjg/openmc,mit-crpg/openmc,smharper/openmc,walshjon/openmc,lilulu/openmc,sxds/opemmc,paulromano/openmc,mjlong/openmc,amandalund/openmc,wbinventor/openmc,bhermanmit/openmc,samuelshaner/openmc,johnnyliu27/openmc,johnnyliu27/openmc,shenqicang/openmc,shikhar413/openmc,walshjon/openmc,bhermanmit/cdash,walshjon/openmc,samuelshaner/openmc,lilulu/openmc,shikhar413/openmc,samuelshaner/openmc,amandalund/openmc,amandalund/openmc,wbinventor/openmc,shenqicang/openmc,amandalund/openmc,shikhar413/openmc,shikhar413/openmc,keadyk/openmc_mg_prepush,paulromano/openmc,kellyrowland/openmc,samuelshaner/openmc,liangjg/openmc,mit-crpg/openmc,nhorelik/openmc,walshjon/openmc,mit-crpg/openmc,sxds/opemmc,keadyk/openmc_mg_prepush,nhorelik/openmc,liangjg/openmc,bhermanmit/openmc,paulromano/openmc,wbinventor/openmc
|
#!/usr/bin/env python
import glob
dependencies = {}
for src in glob.iglob('*.F90'):
module = src.strip('.F90')
d = set()
for line in open(src, 'r'):
words = line.split()
if words and words[0].lower() == 'use':
name = words[1].strip(',')
if name in ['mpi','hdf5','h5lt']:
continue
if name.startswith('xml_data_'):
name = name.replace('xml_data_', 'templates/')
d.add(name)
if d:
d = list(d)
d.sort()
dependencies[module] = d
keys = dependencies.keys()
keys.sort()
for module in keys:
for dep in dependencies[module]:
print("{0}.o: {1}.o".format(module, dep))
print('')
Fix potential bug in build dependencies script. If you gave it ' use module,only: ...' before it would not work.
|
#!/usr/bin/env python
import glob
import re
dependencies = {}
for src in glob.iglob('*.F90'):
module = src.strip('.F90')
deps = set()
d = re.findall(r'\n\s*use\s+(\w+)',
open(src,'r').read())
for name in d:
if name in ['mpi','hdf5','h5lt']:
continue
if name.startswith('xml_data_'):
name = name.replace('xml_data_', 'templates/')
deps.add(name)
if deps:
dependencies[module] = sorted(list(deps))
keys = dependencies.keys()
keys.sort()
for module in keys:
for dep in dependencies[module]:
print("{0}.o: {1}.o".format(module, dep))
print('')
|
<commit_before>#!/usr/bin/env python
import glob
dependencies = {}
for src in glob.iglob('*.F90'):
module = src.strip('.F90')
d = set()
for line in open(src, 'r'):
words = line.split()
if words and words[0].lower() == 'use':
name = words[1].strip(',')
if name in ['mpi','hdf5','h5lt']:
continue
if name.startswith('xml_data_'):
name = name.replace('xml_data_', 'templates/')
d.add(name)
if d:
d = list(d)
d.sort()
dependencies[module] = d
keys = dependencies.keys()
keys.sort()
for module in keys:
for dep in dependencies[module]:
print("{0}.o: {1}.o".format(module, dep))
print('')
<commit_msg>Fix potential bug in build dependencies script. If you gave it ' use module,only: ...' before it would not work.<commit_after>
|
#!/usr/bin/env python
import glob
import re
dependencies = {}
for src in glob.iglob('*.F90'):
module = src.strip('.F90')
deps = set()
d = re.findall(r'\n\s*use\s+(\w+)',
open(src,'r').read())
for name in d:
if name in ['mpi','hdf5','h5lt']:
continue
if name.startswith('xml_data_'):
name = name.replace('xml_data_', 'templates/')
deps.add(name)
if deps:
dependencies[module] = sorted(list(deps))
keys = dependencies.keys()
keys.sort()
for module in keys:
for dep in dependencies[module]:
print("{0}.o: {1}.o".format(module, dep))
print('')
|
#!/usr/bin/env python
import glob
dependencies = {}
for src in glob.iglob('*.F90'):
module = src.strip('.F90')
d = set()
for line in open(src, 'r'):
words = line.split()
if words and words[0].lower() == 'use':
name = words[1].strip(',')
if name in ['mpi','hdf5','h5lt']:
continue
if name.startswith('xml_data_'):
name = name.replace('xml_data_', 'templates/')
d.add(name)
if d:
d = list(d)
d.sort()
dependencies[module] = d
keys = dependencies.keys()
keys.sort()
for module in keys:
for dep in dependencies[module]:
print("{0}.o: {1}.o".format(module, dep))
print('')
Fix potential bug in build dependencies script. If you gave it ' use module,only: ...' before it would not work.#!/usr/bin/env python
import glob
import re
dependencies = {}
for src in glob.iglob('*.F90'):
module = src.strip('.F90')
deps = set()
d = re.findall(r'\n\s*use\s+(\w+)',
open(src,'r').read())
for name in d:
if name in ['mpi','hdf5','h5lt']:
continue
if name.startswith('xml_data_'):
name = name.replace('xml_data_', 'templates/')
deps.add(name)
if deps:
dependencies[module] = sorted(list(deps))
keys = dependencies.keys()
keys.sort()
for module in keys:
for dep in dependencies[module]:
print("{0}.o: {1}.o".format(module, dep))
print('')
|
<commit_before>#!/usr/bin/env python
import glob
dependencies = {}
for src in glob.iglob('*.F90'):
module = src.strip('.F90')
d = set()
for line in open(src, 'r'):
words = line.split()
if words and words[0].lower() == 'use':
name = words[1].strip(',')
if name in ['mpi','hdf5','h5lt']:
continue
if name.startswith('xml_data_'):
name = name.replace('xml_data_', 'templates/')
d.add(name)
if d:
d = list(d)
d.sort()
dependencies[module] = d
keys = dependencies.keys()
keys.sort()
for module in keys:
for dep in dependencies[module]:
print("{0}.o: {1}.o".format(module, dep))
print('')
<commit_msg>Fix potential bug in build dependencies script. If you gave it ' use module,only: ...' before it would not work.<commit_after>#!/usr/bin/env python
import glob
import re
dependencies = {}
for src in glob.iglob('*.F90'):
module = src.strip('.F90')
deps = set()
d = re.findall(r'\n\s*use\s+(\w+)',
open(src,'r').read())
for name in d:
if name in ['mpi','hdf5','h5lt']:
continue
if name.startswith('xml_data_'):
name = name.replace('xml_data_', 'templates/')
deps.add(name)
if deps:
dependencies[module] = sorted(list(deps))
keys = dependencies.keys()
keys.sort()
for module in keys:
for dep in dependencies[module]:
print("{0}.o: {1}.o".format(module, dep))
print('')
|
005890de77432c1e97e834483b8c477ef92be187
|
src/cli/_errors.py
|
src/cli/_errors.py
|
"""
Error heirarchy for stratis cli.
"""
class StratisCliError(Exception):
"""
Top-level stratis cli error.
"""
pass
class StratisCliValueError(StratisCliError):
""" Raised when a parameter has an unacceptable value.
May also be raised when the parameter has an unacceptable type.
"""
_FMT_STR = "value '%s' for parameter %s is unacceptable"
def __init__(self, value, param, msg=None):
""" Initializer.
:param object value: the value
:param str param: the parameter
:param str msg: an explanatory message
"""
# pylint: disable=super-init-not-called
self._value = value
self._param = param
self._msg = msg
def __str__(self): # pragma: no cover
if self._msg:
fmt_str = self._FMT_STR + ": %s"
return fmt_str % (self._value, self._param, self._msg)
else:
return self._FMT_STR % (self._value, self._param)
class StratisCliValueUnimplementedError(StratisCliValueError):
"""
Raised if a parameter is not intrinsically bad but functionality
is unimplemented for this value.
"""
pass
class StratisCliUnimplementedError(StratisCliError):
"""
Raised if a method is temporarily unimplemented.
"""
pass
|
"""
Error heirarchy for stratis cli.
"""
class StratisCliError(Exception):
"""
Top-level stratis cli error.
"""
pass
class StratisCliValueError(StratisCliError):
""" Raised when a parameter has an unacceptable value.
May also be raised when the parameter has an unacceptable type.
"""
_FMT_STR = "value '%s' for parameter %s is unacceptable"
def __init__(self, value, param, msg=None):
""" Initializer.
:param object value: the value
:param str param: the parameter
:param str msg: an explanatory message
"""
# pylint: disable=super-init-not-called
self._value = value
self._param = param
self._msg = msg
def __str__(self): # pragma: no cover
if self._msg:
fmt_str = self._FMT_STR + ": %s"
return fmt_str % (self._value, self._param, self._msg)
else:
return self._FMT_STR % (self._value, self._param)
class StratisCliValueUnimplementedError(StratisCliValueError):
"""
Raised if a parameter is not intrinsically bad but functionality
is unimplemented for this value.
"""
pass
class StratisCliUnimplementedError(StratisCliError):
"""
Raised if a method is temporarily unimplemented.
"""
pass
class StratisCliKnownBugError(StratisCliError):
"""
Raised if a method is unimplemented due to a bug.
"""
pass
|
Add a class for a known error that prevents implementation.
|
Add a class for a known error that prevents implementation.
Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>
|
Python
|
apache-2.0
|
stratis-storage/stratis-cli,stratis-storage/stratis-cli
|
"""
Error heirarchy for stratis cli.
"""
class StratisCliError(Exception):
"""
Top-level stratis cli error.
"""
pass
class StratisCliValueError(StratisCliError):
""" Raised when a parameter has an unacceptable value.
May also be raised when the parameter has an unacceptable type.
"""
_FMT_STR = "value '%s' for parameter %s is unacceptable"
def __init__(self, value, param, msg=None):
""" Initializer.
:param object value: the value
:param str param: the parameter
:param str msg: an explanatory message
"""
# pylint: disable=super-init-not-called
self._value = value
self._param = param
self._msg = msg
def __str__(self): # pragma: no cover
if self._msg:
fmt_str = self._FMT_STR + ": %s"
return fmt_str % (self._value, self._param, self._msg)
else:
return self._FMT_STR % (self._value, self._param)
class StratisCliValueUnimplementedError(StratisCliValueError):
"""
Raised if a parameter is not intrinsically bad but functionality
is unimplemented for this value.
"""
pass
class StratisCliUnimplementedError(StratisCliError):
"""
Raised if a method is temporarily unimplemented.
"""
pass
Add a class for a known error that prevents implementation.
Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>
|
"""
Error heirarchy for stratis cli.
"""
class StratisCliError(Exception):
"""
Top-level stratis cli error.
"""
pass
class StratisCliValueError(StratisCliError):
""" Raised when a parameter has an unacceptable value.
May also be raised when the parameter has an unacceptable type.
"""
_FMT_STR = "value '%s' for parameter %s is unacceptable"
def __init__(self, value, param, msg=None):
""" Initializer.
:param object value: the value
:param str param: the parameter
:param str msg: an explanatory message
"""
# pylint: disable=super-init-not-called
self._value = value
self._param = param
self._msg = msg
def __str__(self): # pragma: no cover
if self._msg:
fmt_str = self._FMT_STR + ": %s"
return fmt_str % (self._value, self._param, self._msg)
else:
return self._FMT_STR % (self._value, self._param)
class StratisCliValueUnimplementedError(StratisCliValueError):
"""
Raised if a parameter is not intrinsically bad but functionality
is unimplemented for this value.
"""
pass
class StratisCliUnimplementedError(StratisCliError):
"""
Raised if a method is temporarily unimplemented.
"""
pass
class StratisCliKnownBugError(StratisCliError):
"""
Raised if a method is unimplemented due to a bug.
"""
pass
|
<commit_before>"""
Error heirarchy for stratis cli.
"""
class StratisCliError(Exception):
"""
Top-level stratis cli error.
"""
pass
class StratisCliValueError(StratisCliError):
""" Raised when a parameter has an unacceptable value.
May also be raised when the parameter has an unacceptable type.
"""
_FMT_STR = "value '%s' for parameter %s is unacceptable"
def __init__(self, value, param, msg=None):
""" Initializer.
:param object value: the value
:param str param: the parameter
:param str msg: an explanatory message
"""
# pylint: disable=super-init-not-called
self._value = value
self._param = param
self._msg = msg
def __str__(self): # pragma: no cover
if self._msg:
fmt_str = self._FMT_STR + ": %s"
return fmt_str % (self._value, self._param, self._msg)
else:
return self._FMT_STR % (self._value, self._param)
class StratisCliValueUnimplementedError(StratisCliValueError):
"""
Raised if a parameter is not intrinsically bad but functionality
is unimplemented for this value.
"""
pass
class StratisCliUnimplementedError(StratisCliError):
"""
Raised if a method is temporarily unimplemented.
"""
pass
<commit_msg>Add a class for a known error that prevents implementation.
Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com><commit_after>
|
"""
Error heirarchy for stratis cli.
"""
class StratisCliError(Exception):
"""
Top-level stratis cli error.
"""
pass
class StratisCliValueError(StratisCliError):
""" Raised when a parameter has an unacceptable value.
May also be raised when the parameter has an unacceptable type.
"""
_FMT_STR = "value '%s' for parameter %s is unacceptable"
def __init__(self, value, param, msg=None):
""" Initializer.
:param object value: the value
:param str param: the parameter
:param str msg: an explanatory message
"""
# pylint: disable=super-init-not-called
self._value = value
self._param = param
self._msg = msg
def __str__(self): # pragma: no cover
if self._msg:
fmt_str = self._FMT_STR + ": %s"
return fmt_str % (self._value, self._param, self._msg)
else:
return self._FMT_STR % (self._value, self._param)
class StratisCliValueUnimplementedError(StratisCliValueError):
"""
Raised if a parameter is not intrinsically bad but functionality
is unimplemented for this value.
"""
pass
class StratisCliUnimplementedError(StratisCliError):
"""
Raised if a method is temporarily unimplemented.
"""
pass
class StratisCliKnownBugError(StratisCliError):
"""
Raised if a method is unimplemented due to a bug.
"""
pass
|
"""
Error heirarchy for stratis cli.
"""
class StratisCliError(Exception):
"""
Top-level stratis cli error.
"""
pass
class StratisCliValueError(StratisCliError):
""" Raised when a parameter has an unacceptable value.
May also be raised when the parameter has an unacceptable type.
"""
_FMT_STR = "value '%s' for parameter %s is unacceptable"
def __init__(self, value, param, msg=None):
""" Initializer.
:param object value: the value
:param str param: the parameter
:param str msg: an explanatory message
"""
# pylint: disable=super-init-not-called
self._value = value
self._param = param
self._msg = msg
def __str__(self): # pragma: no cover
if self._msg:
fmt_str = self._FMT_STR + ": %s"
return fmt_str % (self._value, self._param, self._msg)
else:
return self._FMT_STR % (self._value, self._param)
class StratisCliValueUnimplementedError(StratisCliValueError):
"""
Raised if a parameter is not intrinsically bad but functionality
is unimplemented for this value.
"""
pass
class StratisCliUnimplementedError(StratisCliError):
"""
Raised if a method is temporarily unimplemented.
"""
pass
Add a class for a known error that prevents implementation.
Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>"""
Error heirarchy for stratis cli.
"""
class StratisCliError(Exception):
"""
Top-level stratis cli error.
"""
pass
class StratisCliValueError(StratisCliError):
""" Raised when a parameter has an unacceptable value.
May also be raised when the parameter has an unacceptable type.
"""
_FMT_STR = "value '%s' for parameter %s is unacceptable"
def __init__(self, value, param, msg=None):
""" Initializer.
:param object value: the value
:param str param: the parameter
:param str msg: an explanatory message
"""
# pylint: disable=super-init-not-called
self._value = value
self._param = param
self._msg = msg
def __str__(self): # pragma: no cover
if self._msg:
fmt_str = self._FMT_STR + ": %s"
return fmt_str % (self._value, self._param, self._msg)
else:
return self._FMT_STR % (self._value, self._param)
class StratisCliValueUnimplementedError(StratisCliValueError):
"""
Raised if a parameter is not intrinsically bad but functionality
is unimplemented for this value.
"""
pass
class StratisCliUnimplementedError(StratisCliError):
"""
Raised if a method is temporarily unimplemented.
"""
pass
class StratisCliKnownBugError(StratisCliError):
"""
Raised if a method is unimplemented due to a bug.
"""
pass
|
<commit_before>"""
Error heirarchy for stratis cli.
"""
class StratisCliError(Exception):
"""
Top-level stratis cli error.
"""
pass
class StratisCliValueError(StratisCliError):
""" Raised when a parameter has an unacceptable value.
May also be raised when the parameter has an unacceptable type.
"""
_FMT_STR = "value '%s' for parameter %s is unacceptable"
def __init__(self, value, param, msg=None):
""" Initializer.
:param object value: the value
:param str param: the parameter
:param str msg: an explanatory message
"""
# pylint: disable=super-init-not-called
self._value = value
self._param = param
self._msg = msg
def __str__(self): # pragma: no cover
if self._msg:
fmt_str = self._FMT_STR + ": %s"
return fmt_str % (self._value, self._param, self._msg)
else:
return self._FMT_STR % (self._value, self._param)
class StratisCliValueUnimplementedError(StratisCliValueError):
"""
Raised if a parameter is not intrinsically bad but functionality
is unimplemented for this value.
"""
pass
class StratisCliUnimplementedError(StratisCliError):
"""
Raised if a method is temporarily unimplemented.
"""
pass
<commit_msg>Add a class for a known error that prevents implementation.
Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com><commit_after>"""
Error heirarchy for stratis cli.
"""
class StratisCliError(Exception):
"""
Top-level stratis cli error.
"""
pass
class StratisCliValueError(StratisCliError):
""" Raised when a parameter has an unacceptable value.
May also be raised when the parameter has an unacceptable type.
"""
_FMT_STR = "value '%s' for parameter %s is unacceptable"
def __init__(self, value, param, msg=None):
""" Initializer.
:param object value: the value
:param str param: the parameter
:param str msg: an explanatory message
"""
# pylint: disable=super-init-not-called
self._value = value
self._param = param
self._msg = msg
def __str__(self): # pragma: no cover
if self._msg:
fmt_str = self._FMT_STR + ": %s"
return fmt_str % (self._value, self._param, self._msg)
else:
return self._FMT_STR % (self._value, self._param)
class StratisCliValueUnimplementedError(StratisCliValueError):
"""
Raised if a parameter is not intrinsically bad but functionality
is unimplemented for this value.
"""
pass
class StratisCliUnimplementedError(StratisCliError):
"""
Raised if a method is temporarily unimplemented.
"""
pass
class StratisCliKnownBugError(StratisCliError):
"""
Raised if a method is unimplemented due to a bug.
"""
pass
|
2084ac35a66067046db98e6b6d76d589952f1953
|
chipy8.py
|
chipy8.py
|
class Memory(object):
def __init__(self):
self._stream = [0x00] * 4096
def __len__(self):
return len(self._stream)
def read_byte(self, address):
return self._stream[address]
def write_byte(self, address, data):
self._stream[address] = data
def load(self, address, data):
for offset, datum in enumerate(data):
self._stream[address + offset] = datum
class Chip8(object):
def __init__(self):
self.registers = [0x00] * 16
self.index_register = 0
self.program_counter = 0x200
self.memory = [0x00] * 4096
# 0x000-0x1FF - Chip 8 interpreter (contains font set in emu)
# 0x050-0x0A0 - Used for the built in 4x5 pixel font set (0-F)
# 0x200-0xFFF - Program ROM and work RAM
self.screen = [0x00] * 32 * 64
self.keyboard = [0x00] * 16
self.stack = []
self.delay_timer = 0
self.sound_timer = 0
|
class Memory(object):
def __init__(self):
self._stream = [0x00] * 4096
def __len__(self):
return len(self._stream)
def read_byte(self, address):
return self._stream[address]
def write_byte(self, address, data):
self._stream[address] = data
def load(self, address, data):
for offset, datum in enumerate(data):
self._stream[address + offset] = datum
class Chip8(object):
def __init__(self):
self.registers = [0x00] * 16
self.index_register = 0
self.program_counter = 0x200
self.memory = Memory()
# 0x000-0x1FF - Chip 8 interpreter (contains font set in emu)
# 0x050-0x0A0 - Used for the built in 4x5 pixel font set (0-F)
# 0x200-0xFFF - Program ROM and work RAM
self.screen = [0x00] * 32 * 64
self.keyboard = [0x00] * 16
self.stack = []
self.delay_timer = 0
self.sound_timer = 0
|
Refactor Chip8 to use a Memory instance.
|
Refactor Chip8 to use a Memory instance.
|
Python
|
bsd-3-clause
|
gutomaia/chipy8
|
class Memory(object):
def __init__(self):
self._stream = [0x00] * 4096
def __len__(self):
return len(self._stream)
def read_byte(self, address):
return self._stream[address]
def write_byte(self, address, data):
self._stream[address] = data
def load(self, address, data):
for offset, datum in enumerate(data):
self._stream[address + offset] = datum
class Chip8(object):
def __init__(self):
self.registers = [0x00] * 16
self.index_register = 0
self.program_counter = 0x200
self.memory = [0x00] * 4096
# 0x000-0x1FF - Chip 8 interpreter (contains font set in emu)
# 0x050-0x0A0 - Used for the built in 4x5 pixel font set (0-F)
# 0x200-0xFFF - Program ROM and work RAM
self.screen = [0x00] * 32 * 64
self.keyboard = [0x00] * 16
self.stack = []
self.delay_timer = 0
self.sound_timer = 0
Refactor Chip8 to use a Memory instance.
|
class Memory(object):
def __init__(self):
self._stream = [0x00] * 4096
def __len__(self):
return len(self._stream)
def read_byte(self, address):
return self._stream[address]
def write_byte(self, address, data):
self._stream[address] = data
def load(self, address, data):
for offset, datum in enumerate(data):
self._stream[address + offset] = datum
class Chip8(object):
def __init__(self):
self.registers = [0x00] * 16
self.index_register = 0
self.program_counter = 0x200
self.memory = Memory()
# 0x000-0x1FF - Chip 8 interpreter (contains font set in emu)
# 0x050-0x0A0 - Used for the built in 4x5 pixel font set (0-F)
# 0x200-0xFFF - Program ROM and work RAM
self.screen = [0x00] * 32 * 64
self.keyboard = [0x00] * 16
self.stack = []
self.delay_timer = 0
self.sound_timer = 0
|
<commit_before>
class Memory(object):
def __init__(self):
self._stream = [0x00] * 4096
def __len__(self):
return len(self._stream)
def read_byte(self, address):
return self._stream[address]
def write_byte(self, address, data):
self._stream[address] = data
def load(self, address, data):
for offset, datum in enumerate(data):
self._stream[address + offset] = datum
class Chip8(object):
def __init__(self):
self.registers = [0x00] * 16
self.index_register = 0
self.program_counter = 0x200
self.memory = [0x00] * 4096
# 0x000-0x1FF - Chip 8 interpreter (contains font set in emu)
# 0x050-0x0A0 - Used for the built in 4x5 pixel font set (0-F)
# 0x200-0xFFF - Program ROM and work RAM
self.screen = [0x00] * 32 * 64
self.keyboard = [0x00] * 16
self.stack = []
self.delay_timer = 0
self.sound_timer = 0
<commit_msg>Refactor Chip8 to use a Memory instance.<commit_after>
|
class Memory(object):
def __init__(self):
self._stream = [0x00] * 4096
def __len__(self):
return len(self._stream)
def read_byte(self, address):
return self._stream[address]
def write_byte(self, address, data):
self._stream[address] = data
def load(self, address, data):
for offset, datum in enumerate(data):
self._stream[address + offset] = datum
class Chip8(object):
def __init__(self):
self.registers = [0x00] * 16
self.index_register = 0
self.program_counter = 0x200
self.memory = Memory()
# 0x000-0x1FF - Chip 8 interpreter (contains font set in emu)
# 0x050-0x0A0 - Used for the built in 4x5 pixel font set (0-F)
# 0x200-0xFFF - Program ROM and work RAM
self.screen = [0x00] * 32 * 64
self.keyboard = [0x00] * 16
self.stack = []
self.delay_timer = 0
self.sound_timer = 0
|
class Memory(object):
def __init__(self):
self._stream = [0x00] * 4096
def __len__(self):
return len(self._stream)
def read_byte(self, address):
return self._stream[address]
def write_byte(self, address, data):
self._stream[address] = data
def load(self, address, data):
for offset, datum in enumerate(data):
self._stream[address + offset] = datum
class Chip8(object):
def __init__(self):
self.registers = [0x00] * 16
self.index_register = 0
self.program_counter = 0x200
self.memory = [0x00] * 4096
# 0x000-0x1FF - Chip 8 interpreter (contains font set in emu)
# 0x050-0x0A0 - Used for the built in 4x5 pixel font set (0-F)
# 0x200-0xFFF - Program ROM and work RAM
self.screen = [0x00] * 32 * 64
self.keyboard = [0x00] * 16
self.stack = []
self.delay_timer = 0
self.sound_timer = 0
Refactor Chip8 to use a Memory instance.
class Memory(object):
def __init__(self):
self._stream = [0x00] * 4096
def __len__(self):
return len(self._stream)
def read_byte(self, address):
return self._stream[address]
def write_byte(self, address, data):
self._stream[address] = data
def load(self, address, data):
for offset, datum in enumerate(data):
self._stream[address + offset] = datum
class Chip8(object):
def __init__(self):
self.registers = [0x00] * 16
self.index_register = 0
self.program_counter = 0x200
self.memory = Memory()
# 0x000-0x1FF - Chip 8 interpreter (contains font set in emu)
# 0x050-0x0A0 - Used for the built in 4x5 pixel font set (0-F)
# 0x200-0xFFF - Program ROM and work RAM
self.screen = [0x00] * 32 * 64
self.keyboard = [0x00] * 16
self.stack = []
self.delay_timer = 0
self.sound_timer = 0
|
<commit_before>
class Memory(object):
def __init__(self):
self._stream = [0x00] * 4096
def __len__(self):
return len(self._stream)
def read_byte(self, address):
return self._stream[address]
def write_byte(self, address, data):
self._stream[address] = data
def load(self, address, data):
for offset, datum in enumerate(data):
self._stream[address + offset] = datum
class Chip8(object):
def __init__(self):
self.registers = [0x00] * 16
self.index_register = 0
self.program_counter = 0x200
self.memory = [0x00] * 4096
# 0x000-0x1FF - Chip 8 interpreter (contains font set in emu)
# 0x050-0x0A0 - Used for the built in 4x5 pixel font set (0-F)
# 0x200-0xFFF - Program ROM and work RAM
self.screen = [0x00] * 32 * 64
self.keyboard = [0x00] * 16
self.stack = []
self.delay_timer = 0
self.sound_timer = 0
<commit_msg>Refactor Chip8 to use a Memory instance.<commit_after>
class Memory(object):
def __init__(self):
self._stream = [0x00] * 4096
def __len__(self):
return len(self._stream)
def read_byte(self, address):
return self._stream[address]
def write_byte(self, address, data):
self._stream[address] = data
def load(self, address, data):
for offset, datum in enumerate(data):
self._stream[address + offset] = datum
class Chip8(object):
def __init__(self):
self.registers = [0x00] * 16
self.index_register = 0
self.program_counter = 0x200
self.memory = Memory()
# 0x000-0x1FF - Chip 8 interpreter (contains font set in emu)
# 0x050-0x0A0 - Used for the built in 4x5 pixel font set (0-F)
# 0x200-0xFFF - Program ROM and work RAM
self.screen = [0x00] * 32 * 64
self.keyboard = [0x00] * 16
self.stack = []
self.delay_timer = 0
self.sound_timer = 0
|
e6b24f6e8bfca6f8e22bd63c893a228cc2a694f1
|
starter_project/normalize_breton_test.py
|
starter_project/normalize_breton_test.py
|
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
if __name__ == '__main__':
unittest.main()
|
import unittest
import normalize_breton_lib
class TestStringMethods(unittest.TestCase):
def test_normalize_breton(self):
'Test the output of NormalizeBreton.'
test_cases = [(('a--bc', 'a-bc'), ('ccb--a', 'ccb-a'), ('ba--aa', 'ba-aa'))]
for test in test_cases:
for test_case, expected in test:
test_fst = normalize_breton_lib.NormalizeBreton(test_case)
self.assertEqual(test_fst, expected)
if __name__ == '__main__':
unittest.main()
|
Add basic test for example Pynini FST.
|
Add basic test for example Pynini FST.
|
Python
|
apache-2.0
|
googleinterns/text-norm-for-low-resource-languages,googleinterns/text-norm-for-low-resource-languages
|
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
if __name__ == '__main__':
unittest.main()
Add basic test for example Pynini FST.
|
import unittest
import normalize_breton_lib
class TestStringMethods(unittest.TestCase):
def test_normalize_breton(self):
'Test the output of NormalizeBreton.'
test_cases = [(('a--bc', 'a-bc'), ('ccb--a', 'ccb-a'), ('ba--aa', 'ba-aa'))]
for test in test_cases:
for test_case, expected in test:
test_fst = normalize_breton_lib.NormalizeBreton(test_case)
self.assertEqual(test_fst, expected)
if __name__ == '__main__':
unittest.main()
|
<commit_before>import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
if __name__ == '__main__':
unittest.main()
<commit_msg>Add basic test for example Pynini FST.<commit_after>
|
import unittest
import normalize_breton_lib
class TestStringMethods(unittest.TestCase):
def test_normalize_breton(self):
'Test the output of NormalizeBreton.'
test_cases = [(('a--bc', 'a-bc'), ('ccb--a', 'ccb-a'), ('ba--aa', 'ba-aa'))]
for test in test_cases:
for test_case, expected in test:
test_fst = normalize_breton_lib.NormalizeBreton(test_case)
self.assertEqual(test_fst, expected)
if __name__ == '__main__':
unittest.main()
|
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
if __name__ == '__main__':
unittest.main()
Add basic test for example Pynini FST.import unittest
import normalize_breton_lib
class TestStringMethods(unittest.TestCase):
def test_normalize_breton(self):
'Test the output of NormalizeBreton.'
test_cases = [(('a--bc', 'a-bc'), ('ccb--a', 'ccb-a'), ('ba--aa', 'ba-aa'))]
for test in test_cases:
for test_case, expected in test:
test_fst = normalize_breton_lib.NormalizeBreton(test_case)
self.assertEqual(test_fst, expected)
if __name__ == '__main__':
unittest.main()
|
<commit_before>import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
if __name__ == '__main__':
unittest.main()
<commit_msg>Add basic test for example Pynini FST.<commit_after>import unittest
import normalize_breton_lib
class TestStringMethods(unittest.TestCase):
def test_normalize_breton(self):
'Test the output of NormalizeBreton.'
test_cases = [(('a--bc', 'a-bc'), ('ccb--a', 'ccb-a'), ('ba--aa', 'ba-aa'))]
for test in test_cases:
for test_case, expected in test:
test_fst = normalize_breton_lib.NormalizeBreton(test_case)
self.assertEqual(test_fst, expected)
if __name__ == '__main__':
unittest.main()
|
c2f30f7c192b8a282c44727b2afc71b90e98cd3a
|
django_project/core/settings/prod_docker.py
|
django_project/core/settings/prod_docker.py
|
from .project import *
import os
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'gis',
'USER': os.environ['DATABASE_USERNAME'],
'PASSWORD': os.environ['DATABASE_PASSWORD'],
'HOST': os.environ['DATABASE_HOST'],
'PORT': 5432,
'TEST_NAME': 'unittests',
}
}
PIPELINE_YUGLIFY_BINARY = '/usr/local/bin/yuglify'
|
from .project import *
import os
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'gis',
'USER': os.environ['DATABASE_USERNAME'],
'PASSWORD': os.environ['DATABASE_PASSWORD'],
'HOST': os.environ['DATABASE_HOST'],
'PORT': 5432,
'TEST_NAME': 'unittests',
}
}
#PIPELINE_YUGLIFY_BINARY = '/usr/local/bin/yuglify'
|
Comment out yuglify search path
|
Comment out yuglify search path
|
Python
|
bsd-2-clause
|
ismailsunni/healthsites,ismailsunni/healthsites,ismailsunni/healthsites,ismailsunni/healthsites
|
from .project import *
import os
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'gis',
'USER': os.environ['DATABASE_USERNAME'],
'PASSWORD': os.environ['DATABASE_PASSWORD'],
'HOST': os.environ['DATABASE_HOST'],
'PORT': 5432,
'TEST_NAME': 'unittests',
}
}
PIPELINE_YUGLIFY_BINARY = '/usr/local/bin/yuglify'
Comment out yuglify search path
|
from .project import *
import os
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'gis',
'USER': os.environ['DATABASE_USERNAME'],
'PASSWORD': os.environ['DATABASE_PASSWORD'],
'HOST': os.environ['DATABASE_HOST'],
'PORT': 5432,
'TEST_NAME': 'unittests',
}
}
#PIPELINE_YUGLIFY_BINARY = '/usr/local/bin/yuglify'
|
<commit_before>from .project import *
import os
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'gis',
'USER': os.environ['DATABASE_USERNAME'],
'PASSWORD': os.environ['DATABASE_PASSWORD'],
'HOST': os.environ['DATABASE_HOST'],
'PORT': 5432,
'TEST_NAME': 'unittests',
}
}
PIPELINE_YUGLIFY_BINARY = '/usr/local/bin/yuglify'
<commit_msg>Comment out yuglify search path<commit_after>
|
from .project import *
import os
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'gis',
'USER': os.environ['DATABASE_USERNAME'],
'PASSWORD': os.environ['DATABASE_PASSWORD'],
'HOST': os.environ['DATABASE_HOST'],
'PORT': 5432,
'TEST_NAME': 'unittests',
}
}
#PIPELINE_YUGLIFY_BINARY = '/usr/local/bin/yuglify'
|
from .project import *
import os
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'gis',
'USER': os.environ['DATABASE_USERNAME'],
'PASSWORD': os.environ['DATABASE_PASSWORD'],
'HOST': os.environ['DATABASE_HOST'],
'PORT': 5432,
'TEST_NAME': 'unittests',
}
}
PIPELINE_YUGLIFY_BINARY = '/usr/local/bin/yuglify'
Comment out yuglify search pathfrom .project import *
import os
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'gis',
'USER': os.environ['DATABASE_USERNAME'],
'PASSWORD': os.environ['DATABASE_PASSWORD'],
'HOST': os.environ['DATABASE_HOST'],
'PORT': 5432,
'TEST_NAME': 'unittests',
}
}
#PIPELINE_YUGLIFY_BINARY = '/usr/local/bin/yuglify'
|
<commit_before>from .project import *
import os
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'gis',
'USER': os.environ['DATABASE_USERNAME'],
'PASSWORD': os.environ['DATABASE_PASSWORD'],
'HOST': os.environ['DATABASE_HOST'],
'PORT': 5432,
'TEST_NAME': 'unittests',
}
}
PIPELINE_YUGLIFY_BINARY = '/usr/local/bin/yuglify'
<commit_msg>Comment out yuglify search path<commit_after>from .project import *
import os
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'gis',
'USER': os.environ['DATABASE_USERNAME'],
'PASSWORD': os.environ['DATABASE_PASSWORD'],
'HOST': os.environ['DATABASE_HOST'],
'PORT': 5432,
'TEST_NAME': 'unittests',
}
}
#PIPELINE_YUGLIFY_BINARY = '/usr/local/bin/yuglify'
|
da3995150d6eacf7695c4606e83c24c82a17546d
|
autogenerate_config_docs/hooks.py
|
autogenerate_config_docs/hooks.py
|
#
# A collection of shared functions for managing help flag mapping files.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
"""Hooks to handle configuration options not handled on module import or with a
call to _register_runtime_opts(). The HOOKS dict associate hook functions with
a module path."""
def keystone_config():
from keystone.common import config
config.configure()
def glance_store_config():
try:
import glance_store
from oslo.config import cfg
glance_store.backend.register_opts(cfg.CONF)
except ImportError:
# glance_store is not available before Juno
pass
HOOKS = {'keystone.common.config': keystone_config,
'glance.common.config': glance_store_config}
|
#
# A collection of shared functions for managing help flag mapping files.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
"""Hooks to handle configuration options not handled on module import or with a
call to _register_runtime_opts(). The HOOKS dict associate hook functions with
a module path."""
def keystone_config():
from keystone.common import config
config.configure()
def glance_store_config():
try:
import glance_store
from oslo.config import cfg
glance_store.backend.register_opts(cfg.CONF)
except ImportError:
# glance_store is not available before Juno
pass
def nova_spice():
import nova.cmd.spicehtml5proxy # noqa
HOOKS = {'keystone.common.config': keystone_config,
'glance.common.config': glance_store_config,
'nova.spice': nova_spice}
|
Add a hook for nova.cmd.spicehtml5proxy
|
Add a hook for nova.cmd.spicehtml5proxy
The cmd/ folders are excluded from the autohelp imports to avoid ending
up with a bunch of CLI options. nova/cmd/spicehtml5proxy.py holds real
configuration options and needs to be imported.
Change-Id: Ic0f8066332a45cae253ad3e03f4717f1887e16ee
Partial-Bug: #1394595
|
Python
|
apache-2.0
|
openstack/openstack-doc-tools,savinash47/openstack-doc-tools,savinash47/openstack-doc-tools,savinash47/openstack-doc-tools,openstack/openstack-doc-tools
|
#
# A collection of shared functions for managing help flag mapping files.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
"""Hooks to handle configuration options not handled on module import or with a
call to _register_runtime_opts(). The HOOKS dict associate hook functions with
a module path."""
def keystone_config():
from keystone.common import config
config.configure()
def glance_store_config():
try:
import glance_store
from oslo.config import cfg
glance_store.backend.register_opts(cfg.CONF)
except ImportError:
# glance_store is not available before Juno
pass
HOOKS = {'keystone.common.config': keystone_config,
'glance.common.config': glance_store_config}
Add a hook for nova.cmd.spicehtml5proxy
The cmd/ folders are excluded from the autohelp imports to avoid ending
up with a bunch of CLI options. nova/cmd/spicehtml5proxy.py holds real
configuration options and needs to be imported.
Change-Id: Ic0f8066332a45cae253ad3e03f4717f1887e16ee
Partial-Bug: #1394595
|
#
# A collection of shared functions for managing help flag mapping files.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
"""Hooks to handle configuration options not handled on module import or with a
call to _register_runtime_opts(). The HOOKS dict associate hook functions with
a module path."""
def keystone_config():
from keystone.common import config
config.configure()
def glance_store_config():
try:
import glance_store
from oslo.config import cfg
glance_store.backend.register_opts(cfg.CONF)
except ImportError:
# glance_store is not available before Juno
pass
def nova_spice():
import nova.cmd.spicehtml5proxy # noqa
HOOKS = {'keystone.common.config': keystone_config,
'glance.common.config': glance_store_config,
'nova.spice': nova_spice}
|
<commit_before>#
# A collection of shared functions for managing help flag mapping files.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
"""Hooks to handle configuration options not handled on module import or with a
call to _register_runtime_opts(). The HOOKS dict associate hook functions with
a module path."""
def keystone_config():
from keystone.common import config
config.configure()
def glance_store_config():
try:
import glance_store
from oslo.config import cfg
glance_store.backend.register_opts(cfg.CONF)
except ImportError:
# glance_store is not available before Juno
pass
HOOKS = {'keystone.common.config': keystone_config,
'glance.common.config': glance_store_config}
<commit_msg>Add a hook for nova.cmd.spicehtml5proxy
The cmd/ folders are excluded from the autohelp imports to avoid ending
up with a bunch of CLI options. nova/cmd/spicehtml5proxy.py holds real
configuration options and needs to be imported.
Change-Id: Ic0f8066332a45cae253ad3e03f4717f1887e16ee
Partial-Bug: #1394595<commit_after>
|
#
# A collection of shared functions for managing help flag mapping files.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
"""Hooks to handle configuration options not handled on module import or with a
call to _register_runtime_opts(). The HOOKS dict associate hook functions with
a module path."""
def keystone_config():
from keystone.common import config
config.configure()
def glance_store_config():
try:
import glance_store
from oslo.config import cfg
glance_store.backend.register_opts(cfg.CONF)
except ImportError:
# glance_store is not available before Juno
pass
def nova_spice():
import nova.cmd.spicehtml5proxy # noqa
HOOKS = {'keystone.common.config': keystone_config,
'glance.common.config': glance_store_config,
'nova.spice': nova_spice}
|
#
# A collection of shared functions for managing help flag mapping files.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
"""Hooks to handle configuration options not handled on module import or with a
call to _register_runtime_opts(). The HOOKS dict associate hook functions with
a module path."""
def keystone_config():
from keystone.common import config
config.configure()
def glance_store_config():
try:
import glance_store
from oslo.config import cfg
glance_store.backend.register_opts(cfg.CONF)
except ImportError:
# glance_store is not available before Juno
pass
HOOKS = {'keystone.common.config': keystone_config,
'glance.common.config': glance_store_config}
Add a hook for nova.cmd.spicehtml5proxy
The cmd/ folders are excluded from the autohelp imports to avoid ending
up with a bunch of CLI options. nova/cmd/spicehtml5proxy.py holds real
configuration options and needs to be imported.
Change-Id: Ic0f8066332a45cae253ad3e03f4717f1887e16ee
Partial-Bug: #1394595#
# A collection of shared functions for managing help flag mapping files.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
"""Hooks to handle configuration options not handled on module import or with a
call to _register_runtime_opts(). The HOOKS dict associate hook functions with
a module path."""
def keystone_config():
from keystone.common import config
config.configure()
def glance_store_config():
try:
import glance_store
from oslo.config import cfg
glance_store.backend.register_opts(cfg.CONF)
except ImportError:
# glance_store is not available before Juno
pass
def nova_spice():
import nova.cmd.spicehtml5proxy # noqa
HOOKS = {'keystone.common.config': keystone_config,
'glance.common.config': glance_store_config,
'nova.spice': nova_spice}
|
<commit_before>#
# A collection of shared functions for managing help flag mapping files.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
"""Hooks to handle configuration options not handled on module import or with a
call to _register_runtime_opts(). The HOOKS dict associate hook functions with
a module path."""
def keystone_config():
from keystone.common import config
config.configure()
def glance_store_config():
try:
import glance_store
from oslo.config import cfg
glance_store.backend.register_opts(cfg.CONF)
except ImportError:
# glance_store is not available before Juno
pass
HOOKS = {'keystone.common.config': keystone_config,
'glance.common.config': glance_store_config}
<commit_msg>Add a hook for nova.cmd.spicehtml5proxy
The cmd/ folders are excluded from the autohelp imports to avoid ending
up with a bunch of CLI options. nova/cmd/spicehtml5proxy.py holds real
configuration options and needs to be imported.
Change-Id: Ic0f8066332a45cae253ad3e03f4717f1887e16ee
Partial-Bug: #1394595<commit_after>#
# A collection of shared functions for managing help flag mapping files.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
"""Hooks to handle configuration options not handled on module import or with a
call to _register_runtime_opts(). The HOOKS dict associate hook functions with
a module path."""
def keystone_config():
from keystone.common import config
config.configure()
def glance_store_config():
try:
import glance_store
from oslo.config import cfg
glance_store.backend.register_opts(cfg.CONF)
except ImportError:
# glance_store is not available before Juno
pass
def nova_spice():
import nova.cmd.spicehtml5proxy # noqa
HOOKS = {'keystone.common.config': keystone_config,
'glance.common.config': glance_store_config,
'nova.spice': nova_spice}
|
09468a6411a5c0816ecb2f79037b0a79b3ceb9c5
|
lib/carbon/hashing.py
|
lib/carbon/hashing.py
|
import hashlib
import bisect
serverRing = None
class ConsistentHashRing:
def __init__(self, nodes, replica_count=100):
self.ring = []
self.replica_count = replica_count
for node in nodes:
self.add_node(node)
def compute_ring_position(self, key):
big_hash = hashlib.md5( str(key) ).hexdigest()
small_hash = int(big_hash[:4], 16)
return small_hash
def add_node(self, key):
for i in range(self.replica_count):
replica_key = "%s:%d" % (key, i)
position = self.compute_ring_position(replica_key)
entry = (position, key)
bisect.insort(self.ring, entry)
def remove_node(self, key):
self.ring = [entry for entry in self.ring if entry[1] != key]
def get_node(self, key):
assert self.ring
position = self.compute_ring_position(key)
search_entry = (position, None)
index = bisect.bisect_left(self.ring, search_entry)
index %= len(self.ring)
entry = self.ring[index]
return entry[1]
def setDestinationServers(servers):
global serverRing
serverRing = ConsistentHashRing(servers)
def getDestinations(metric):
return [ serverRing.get_node(metric) ]
|
try:
from hashlib import md5
except ImportError:
from md5 import md5
import bisect
serverRing = None
class ConsistentHashRing:
def __init__(self, nodes, replica_count=100):
self.ring = []
self.replica_count = replica_count
for node in nodes:
self.add_node(node)
def compute_ring_position(self, key):
big_hash = md5( str(key) ).hexdigest()
small_hash = int(big_hash[:4], 16)
return small_hash
def add_node(self, key):
for i in range(self.replica_count):
replica_key = "%s:%d" % (key, i)
position = self.compute_ring_position(replica_key)
entry = (position, key)
bisect.insort(self.ring, entry)
def remove_node(self, key):
self.ring = [entry for entry in self.ring if entry[1] != key]
def get_node(self, key):
assert self.ring
position = self.compute_ring_position(key)
search_entry = (position, None)
index = bisect.bisect_left(self.ring, search_entry)
index %= len(self.ring)
entry = self.ring[index]
return entry[1]
def setDestinationServers(servers):
global serverRing
serverRing = ConsistentHashRing(servers)
def getDestinations(metric):
return [ serverRing.get_node(metric) ]
|
Make compatible with python 2.4 hashlib was added in python 2.5, but just using the md5() method so fall back to md5.md5() if we can't import hashlib
|
Make compatible with python 2.4
hashlib was added in python 2.5, but just using the md5() method so fall back
to md5.md5() if we can't import hashlib
|
Python
|
apache-2.0
|
kharandziuk/carbon,criteo-forks/carbon,krux/carbon,graphite-project/carbon,pratX/carbon,johnseekins/carbon,graphite-server/carbon,JeanFred/carbon,mleinart/carbon,benburry/carbon,graphite-server/carbon,iain-buclaw-sociomantic/carbon,obfuscurity/carbon,xadjmerripen/carbon,cbowman0/carbon,deniszh/carbon,obfuscurity/carbon,lyft/carbon,deniszh/carbon,pratX/carbon,johnseekins/carbon,cbowman0/carbon,criteo-forks/carbon,benburry/carbon,kharandziuk/carbon,protochron/carbon,lyft/carbon,protochron/carbon,piotr1212/carbon,graphite-project/carbon,krux/carbon,JeanFred/carbon,pu239ppy/carbon,mleinart/carbon,pu239ppy/carbon,piotr1212/carbon,iain-buclaw-sociomantic/carbon,xadjmerripen/carbon
|
import hashlib
import bisect
serverRing = None
class ConsistentHashRing:
def __init__(self, nodes, replica_count=100):
self.ring = []
self.replica_count = replica_count
for node in nodes:
self.add_node(node)
def compute_ring_position(self, key):
big_hash = hashlib.md5( str(key) ).hexdigest()
small_hash = int(big_hash[:4], 16)
return small_hash
def add_node(self, key):
for i in range(self.replica_count):
replica_key = "%s:%d" % (key, i)
position = self.compute_ring_position(replica_key)
entry = (position, key)
bisect.insort(self.ring, entry)
def remove_node(self, key):
self.ring = [entry for entry in self.ring if entry[1] != key]
def get_node(self, key):
assert self.ring
position = self.compute_ring_position(key)
search_entry = (position, None)
index = bisect.bisect_left(self.ring, search_entry)
index %= len(self.ring)
entry = self.ring[index]
return entry[1]
def setDestinationServers(servers):
global serverRing
serverRing = ConsistentHashRing(servers)
def getDestinations(metric):
return [ serverRing.get_node(metric) ]
Make compatible with python 2.4
hashlib was added in python 2.5, but just using the md5() method so fall back
to md5.md5() if we can't import hashlib
|
try:
from hashlib import md5
except ImportError:
from md5 import md5
import bisect
serverRing = None
class ConsistentHashRing:
def __init__(self, nodes, replica_count=100):
self.ring = []
self.replica_count = replica_count
for node in nodes:
self.add_node(node)
def compute_ring_position(self, key):
big_hash = md5( str(key) ).hexdigest()
small_hash = int(big_hash[:4], 16)
return small_hash
def add_node(self, key):
for i in range(self.replica_count):
replica_key = "%s:%d" % (key, i)
position = self.compute_ring_position(replica_key)
entry = (position, key)
bisect.insort(self.ring, entry)
def remove_node(self, key):
self.ring = [entry for entry in self.ring if entry[1] != key]
def get_node(self, key):
assert self.ring
position = self.compute_ring_position(key)
search_entry = (position, None)
index = bisect.bisect_left(self.ring, search_entry)
index %= len(self.ring)
entry = self.ring[index]
return entry[1]
def setDestinationServers(servers):
global serverRing
serverRing = ConsistentHashRing(servers)
def getDestinations(metric):
return [ serverRing.get_node(metric) ]
|
<commit_before>import hashlib
import bisect
serverRing = None
class ConsistentHashRing:
def __init__(self, nodes, replica_count=100):
self.ring = []
self.replica_count = replica_count
for node in nodes:
self.add_node(node)
def compute_ring_position(self, key):
big_hash = hashlib.md5( str(key) ).hexdigest()
small_hash = int(big_hash[:4], 16)
return small_hash
def add_node(self, key):
for i in range(self.replica_count):
replica_key = "%s:%d" % (key, i)
position = self.compute_ring_position(replica_key)
entry = (position, key)
bisect.insort(self.ring, entry)
def remove_node(self, key):
self.ring = [entry for entry in self.ring if entry[1] != key]
def get_node(self, key):
assert self.ring
position = self.compute_ring_position(key)
search_entry = (position, None)
index = bisect.bisect_left(self.ring, search_entry)
index %= len(self.ring)
entry = self.ring[index]
return entry[1]
def setDestinationServers(servers):
global serverRing
serverRing = ConsistentHashRing(servers)
def getDestinations(metric):
return [ serverRing.get_node(metric) ]
<commit_msg>Make compatible with python 2.4
hashlib was added in python 2.5, but just using the md5() method so fall back
to md5.md5() if we can't import hashlib<commit_after>
|
try:
from hashlib import md5
except ImportError:
from md5 import md5
import bisect
serverRing = None
class ConsistentHashRing:
def __init__(self, nodes, replica_count=100):
self.ring = []
self.replica_count = replica_count
for node in nodes:
self.add_node(node)
def compute_ring_position(self, key):
big_hash = md5( str(key) ).hexdigest()
small_hash = int(big_hash[:4], 16)
return small_hash
def add_node(self, key):
for i in range(self.replica_count):
replica_key = "%s:%d" % (key, i)
position = self.compute_ring_position(replica_key)
entry = (position, key)
bisect.insort(self.ring, entry)
def remove_node(self, key):
self.ring = [entry for entry in self.ring if entry[1] != key]
def get_node(self, key):
assert self.ring
position = self.compute_ring_position(key)
search_entry = (position, None)
index = bisect.bisect_left(self.ring, search_entry)
index %= len(self.ring)
entry = self.ring[index]
return entry[1]
def setDestinationServers(servers):
global serverRing
serverRing = ConsistentHashRing(servers)
def getDestinations(metric):
return [ serverRing.get_node(metric) ]
|
import hashlib
import bisect
serverRing = None
class ConsistentHashRing:
def __init__(self, nodes, replica_count=100):
self.ring = []
self.replica_count = replica_count
for node in nodes:
self.add_node(node)
def compute_ring_position(self, key):
big_hash = hashlib.md5( str(key) ).hexdigest()
small_hash = int(big_hash[:4], 16)
return small_hash
def add_node(self, key):
for i in range(self.replica_count):
replica_key = "%s:%d" % (key, i)
position = self.compute_ring_position(replica_key)
entry = (position, key)
bisect.insort(self.ring, entry)
def remove_node(self, key):
self.ring = [entry for entry in self.ring if entry[1] != key]
def get_node(self, key):
assert self.ring
position = self.compute_ring_position(key)
search_entry = (position, None)
index = bisect.bisect_left(self.ring, search_entry)
index %= len(self.ring)
entry = self.ring[index]
return entry[1]
def setDestinationServers(servers):
global serverRing
serverRing = ConsistentHashRing(servers)
def getDestinations(metric):
return [ serverRing.get_node(metric) ]
Make compatible with python 2.4
hashlib was added in python 2.5, but just using the md5() method so fall back
to md5.md5() if we can't import hashlibtry:
from hashlib import md5
except ImportError:
from md5 import md5
import bisect
serverRing = None
class ConsistentHashRing:
def __init__(self, nodes, replica_count=100):
self.ring = []
self.replica_count = replica_count
for node in nodes:
self.add_node(node)
def compute_ring_position(self, key):
big_hash = md5( str(key) ).hexdigest()
small_hash = int(big_hash[:4], 16)
return small_hash
def add_node(self, key):
for i in range(self.replica_count):
replica_key = "%s:%d" % (key, i)
position = self.compute_ring_position(replica_key)
entry = (position, key)
bisect.insort(self.ring, entry)
def remove_node(self, key):
self.ring = [entry for entry in self.ring if entry[1] != key]
def get_node(self, key):
assert self.ring
position = self.compute_ring_position(key)
search_entry = (position, None)
index = bisect.bisect_left(self.ring, search_entry)
index %= len(self.ring)
entry = self.ring[index]
return entry[1]
def setDestinationServers(servers):
global serverRing
serverRing = ConsistentHashRing(servers)
def getDestinations(metric):
return [ serverRing.get_node(metric) ]
|
<commit_before>import hashlib
import bisect
serverRing = None
class ConsistentHashRing:
def __init__(self, nodes, replica_count=100):
self.ring = []
self.replica_count = replica_count
for node in nodes:
self.add_node(node)
def compute_ring_position(self, key):
big_hash = hashlib.md5( str(key) ).hexdigest()
small_hash = int(big_hash[:4], 16)
return small_hash
def add_node(self, key):
for i in range(self.replica_count):
replica_key = "%s:%d" % (key, i)
position = self.compute_ring_position(replica_key)
entry = (position, key)
bisect.insort(self.ring, entry)
def remove_node(self, key):
self.ring = [entry for entry in self.ring if entry[1] != key]
def get_node(self, key):
assert self.ring
position = self.compute_ring_position(key)
search_entry = (position, None)
index = bisect.bisect_left(self.ring, search_entry)
index %= len(self.ring)
entry = self.ring[index]
return entry[1]
def setDestinationServers(servers):
global serverRing
serverRing = ConsistentHashRing(servers)
def getDestinations(metric):
return [ serverRing.get_node(metric) ]
<commit_msg>Make compatible with python 2.4
hashlib was added in python 2.5, but just using the md5() method so fall back
to md5.md5() if we can't import hashlib<commit_after>try:
from hashlib import md5
except ImportError:
from md5 import md5
import bisect
serverRing = None
class ConsistentHashRing:
def __init__(self, nodes, replica_count=100):
self.ring = []
self.replica_count = replica_count
for node in nodes:
self.add_node(node)
def compute_ring_position(self, key):
big_hash = md5( str(key) ).hexdigest()
small_hash = int(big_hash[:4], 16)
return small_hash
def add_node(self, key):
for i in range(self.replica_count):
replica_key = "%s:%d" % (key, i)
position = self.compute_ring_position(replica_key)
entry = (position, key)
bisect.insort(self.ring, entry)
def remove_node(self, key):
self.ring = [entry for entry in self.ring if entry[1] != key]
def get_node(self, key):
assert self.ring
position = self.compute_ring_position(key)
search_entry = (position, None)
index = bisect.bisect_left(self.ring, search_entry)
index %= len(self.ring)
entry = self.ring[index]
return entry[1]
def setDestinationServers(servers):
global serverRing
serverRing = ConsistentHashRing(servers)
def getDestinations(metric):
return [ serverRing.get_node(metric) ]
|
dde6e366fb61d6f4e16fb1f810f3eb4ffb582f0f
|
config.py
|
config.py
|
import os
BASEDIR = os.path.abspath(os.path.dirname(__file__))
SECRET_KEY = 'secret'
class Config(object):
DEBUG = False
TESTING = False
SECRET_KEY = 'secret'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'bucketlist.sqlite')
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'bucketlist-database.sqlite')
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'tests/bucketlist_test.sqlite')
|
import os
BASEDIR = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
TESTING = False
SECRET_KEY = 'secret'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'bucketlist.sqlite')
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'bucketlist-database.sqlite')
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'tests/bucketlist_test.sqlite')
|
Remove repetition for secret key setting
|
Remove repetition for secret key setting
|
Python
|
mit
|
andela-hoyeboade/bucketlist-api
|
import os
BASEDIR = os.path.abspath(os.path.dirname(__file__))
SECRET_KEY = 'secret'
class Config(object):
DEBUG = False
TESTING = False
SECRET_KEY = 'secret'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'bucketlist.sqlite')
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'bucketlist-database.sqlite')
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'tests/bucketlist_test.sqlite')
Remove repetition for secret key setting
|
import os
BASEDIR = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
TESTING = False
SECRET_KEY = 'secret'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'bucketlist.sqlite')
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'bucketlist-database.sqlite')
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'tests/bucketlist_test.sqlite')
|
<commit_before>import os
BASEDIR = os.path.abspath(os.path.dirname(__file__))
SECRET_KEY = 'secret'
class Config(object):
DEBUG = False
TESTING = False
SECRET_KEY = 'secret'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'bucketlist.sqlite')
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'bucketlist-database.sqlite')
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'tests/bucketlist_test.sqlite')
<commit_msg>Remove repetition for secret key setting<commit_after>
|
import os
BASEDIR = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
TESTING = False
SECRET_KEY = 'secret'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'bucketlist.sqlite')
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'bucketlist-database.sqlite')
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'tests/bucketlist_test.sqlite')
|
import os
BASEDIR = os.path.abspath(os.path.dirname(__file__))
SECRET_KEY = 'secret'
class Config(object):
DEBUG = False
TESTING = False
SECRET_KEY = 'secret'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'bucketlist.sqlite')
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'bucketlist-database.sqlite')
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'tests/bucketlist_test.sqlite')
Remove repetition for secret key settingimport os
BASEDIR = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
TESTING = False
SECRET_KEY = 'secret'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'bucketlist.sqlite')
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'bucketlist-database.sqlite')
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'tests/bucketlist_test.sqlite')
|
<commit_before>import os
BASEDIR = os.path.abspath(os.path.dirname(__file__))
SECRET_KEY = 'secret'
class Config(object):
DEBUG = False
TESTING = False
SECRET_KEY = 'secret'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'bucketlist.sqlite')
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'bucketlist-database.sqlite')
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'tests/bucketlist_test.sqlite')
<commit_msg>Remove repetition for secret key setting<commit_after>import os
BASEDIR = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
TESTING = False
SECRET_KEY = 'secret'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'bucketlist.sqlite')
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'bucketlist-database.sqlite')
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASEDIR, 'tests/bucketlist_test.sqlite')
|
93835ce92dd04ada1c073888a61bd2edd4dc17d2
|
links/folder/serializers.py
|
links/folder/serializers.py
|
from rest_framework import serializers
from folder.models import Folder
from link.serializers import LinkSerializer
class FolderSerializer(serializers.ModelSerializer):
class Meta:
model = Folder
fields = ('id', 'name', 'description', 'is_public', 'created',)
read_only_fields = ('created',)
class FolderExtendedSerializer(serializers.ModelSerializer):
links = LinkSerializer(many=True)
class Meta:
model = Folder
fields = ('id', 'name', 'description', 'is_public', 'created',)
read_only_fields = ('created',)
|
from rest_framework import serializers
from folder.models import Folder
from link.serializers import LinkSerializer
class FolderSerializer(serializers.ModelSerializer):
class Meta:
model = Folder
fields = ('id', 'name', 'description', 'is_public', 'created',)
read_only_fields = ('created',)
class FolderExtendedSerializer(serializers.ModelSerializer):
links = LinkSerializer(many=True)
class Meta:
model = Folder
fields = ('id', 'name', 'description', 'links', 'is_public', 'created',)
read_only_fields = ('created',)
|
Add links list to response serializer
|
Add links list to response serializer
|
Python
|
mit
|
projectweekend/Links-API,projectweekend/Links-API
|
from rest_framework import serializers
from folder.models import Folder
from link.serializers import LinkSerializer
class FolderSerializer(serializers.ModelSerializer):
class Meta:
model = Folder
fields = ('id', 'name', 'description', 'is_public', 'created',)
read_only_fields = ('created',)
class FolderExtendedSerializer(serializers.ModelSerializer):
links = LinkSerializer(many=True)
class Meta:
model = Folder
fields = ('id', 'name', 'description', 'is_public', 'created',)
read_only_fields = ('created',)
Add links list to response serializer
|
from rest_framework import serializers
from folder.models import Folder
from link.serializers import LinkSerializer
class FolderSerializer(serializers.ModelSerializer):
class Meta:
model = Folder
fields = ('id', 'name', 'description', 'is_public', 'created',)
read_only_fields = ('created',)
class FolderExtendedSerializer(serializers.ModelSerializer):
links = LinkSerializer(many=True)
class Meta:
model = Folder
fields = ('id', 'name', 'description', 'links', 'is_public', 'created',)
read_only_fields = ('created',)
|
<commit_before>from rest_framework import serializers
from folder.models import Folder
from link.serializers import LinkSerializer
class FolderSerializer(serializers.ModelSerializer):
class Meta:
model = Folder
fields = ('id', 'name', 'description', 'is_public', 'created',)
read_only_fields = ('created',)
class FolderExtendedSerializer(serializers.ModelSerializer):
links = LinkSerializer(many=True)
class Meta:
model = Folder
fields = ('id', 'name', 'description', 'is_public', 'created',)
read_only_fields = ('created',)
<commit_msg>Add links list to response serializer<commit_after>
|
from rest_framework import serializers
from folder.models import Folder
from link.serializers import LinkSerializer
class FolderSerializer(serializers.ModelSerializer):
class Meta:
model = Folder
fields = ('id', 'name', 'description', 'is_public', 'created',)
read_only_fields = ('created',)
class FolderExtendedSerializer(serializers.ModelSerializer):
links = LinkSerializer(many=True)
class Meta:
model = Folder
fields = ('id', 'name', 'description', 'links', 'is_public', 'created',)
read_only_fields = ('created',)
|
from rest_framework import serializers
from folder.models import Folder
from link.serializers import LinkSerializer
class FolderSerializer(serializers.ModelSerializer):
class Meta:
model = Folder
fields = ('id', 'name', 'description', 'is_public', 'created',)
read_only_fields = ('created',)
class FolderExtendedSerializer(serializers.ModelSerializer):
links = LinkSerializer(many=True)
class Meta:
model = Folder
fields = ('id', 'name', 'description', 'is_public', 'created',)
read_only_fields = ('created',)
Add links list to response serializerfrom rest_framework import serializers
from folder.models import Folder
from link.serializers import LinkSerializer
class FolderSerializer(serializers.ModelSerializer):
class Meta:
model = Folder
fields = ('id', 'name', 'description', 'is_public', 'created',)
read_only_fields = ('created',)
class FolderExtendedSerializer(serializers.ModelSerializer):
links = LinkSerializer(many=True)
class Meta:
model = Folder
fields = ('id', 'name', 'description', 'links', 'is_public', 'created',)
read_only_fields = ('created',)
|
<commit_before>from rest_framework import serializers
from folder.models import Folder
from link.serializers import LinkSerializer
class FolderSerializer(serializers.ModelSerializer):
class Meta:
model = Folder
fields = ('id', 'name', 'description', 'is_public', 'created',)
read_only_fields = ('created',)
class FolderExtendedSerializer(serializers.ModelSerializer):
links = LinkSerializer(many=True)
class Meta:
model = Folder
fields = ('id', 'name', 'description', 'is_public', 'created',)
read_only_fields = ('created',)
<commit_msg>Add links list to response serializer<commit_after>from rest_framework import serializers
from folder.models import Folder
from link.serializers import LinkSerializer
class FolderSerializer(serializers.ModelSerializer):
class Meta:
model = Folder
fields = ('id', 'name', 'description', 'is_public', 'created',)
read_only_fields = ('created',)
class FolderExtendedSerializer(serializers.ModelSerializer):
links = LinkSerializer(many=True)
class Meta:
model = Folder
fields = ('id', 'name', 'description', 'links', 'is_public', 'created',)
read_only_fields = ('created',)
|
60c28f155a605508e2b1c481c7380ebbd09f0b42
|
examples/firewallpolicy.py
|
examples/firewallpolicy.py
|
#!env python
#License upload using FORTIOSAPI from Github
import sys
from fortiosapi import FortiOSAPI
import json
def main():
# Parse for command line argument for fgt ip
if len(sys.argv) < 2:
# Requires fgt ip and vdom
print "Please specify fgt ip address"
exit()
# Initilize fgt connection
ip = sys.argv[1]
#fgt = FGT(ip)
# Hard coded vdom value for all requests
vdom = "root"
# Login to the FGT ip
fgt = FortiOSAPI()
fgt.login(ip,'admin','')
parameters = { 'global':'1' }
upload_data={'source':'upload',
'scope':'global'}
files={'file': ('license',open("license.lic", 'r'), 'text/plain')}
fgt.upload('system/vmlicense','upload',
data=upload_data,
parameters=parameters,
files=files)
fgt.logout()
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
#License upload using FORTIOSAPI from Github
import logging
import sys
from fortiosapi import FortiOSAPI
formatter = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
logger = logging.getLogger('fortiosapi')
hdlr = logging.FileHandler('testfortiosapi.log')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
def main():
# Parse for command line argument for fgt ip
if len(sys.argv) < 2:
# Requires fgt ip and password
print "Please specify fgt ip address"
exit()
# Initilize fgt connection
ip = sys.argv[1]
try:
passwd = sys.argv[2]
except:
passwd = ''
#fgt = FGT(ip)
# Hard coded vdom value for all requests
vdom = "root"
# Login to the FGT ip
fgt = FortiOSAPI()
fgt.login(ip, 'admin', passwd)
data = {
'policyid': "66",
'name': "Testfortiosapi",
'action': "accept",
'srcintf': [{"name": "port1"}],
'dstintf': [{"name": "port2"}],
'srcaddr': [{"name": "all"}],
'dstaddr': [{"name": "all"}],
'schedule': "always",
'service': [{"name": "HTTPS"}],
"utm-status": "enable",
"profile-type": "single",
'av-profile': "default",
'profile-protocol-options': "default",
'ssl-ssh-profile': "certificate-inspection",
'logtraffic': "all",
}
fgt.set('firewall', 'policy', vdom="root", data=data)
fgt.logout()
if __name__ == '__main__':
main()
|
Create an example firewall rule push with the antivirus enablement.
|
Create an example firewall rule push with the antivirus enablement.
|
Python
|
apache-2.0
|
thomnico/fortigateconf,thomnico/fortiosapi,thomnico/fortiosapi
|
#!env python
#License upload using FORTIOSAPI from Github
import sys
from fortiosapi import FortiOSAPI
import json
def main():
# Parse for command line argument for fgt ip
if len(sys.argv) < 2:
# Requires fgt ip and vdom
print "Please specify fgt ip address"
exit()
# Initilize fgt connection
ip = sys.argv[1]
#fgt = FGT(ip)
# Hard coded vdom value for all requests
vdom = "root"
# Login to the FGT ip
fgt = FortiOSAPI()
fgt.login(ip,'admin','')
parameters = { 'global':'1' }
upload_data={'source':'upload',
'scope':'global'}
files={'file': ('license',open("license.lic", 'r'), 'text/plain')}
fgt.upload('system/vmlicense','upload',
data=upload_data,
parameters=parameters,
files=files)
fgt.logout()
if __name__ == '__main__':
main()Create an example firewall rule push with the antivirus enablement.
|
#!/usr/bin/env python
#License upload using FORTIOSAPI from Github
import logging
import sys
from fortiosapi import FortiOSAPI
formatter = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
logger = logging.getLogger('fortiosapi')
hdlr = logging.FileHandler('testfortiosapi.log')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
def main():
# Parse for command line argument for fgt ip
if len(sys.argv) < 2:
# Requires fgt ip and password
print "Please specify fgt ip address"
exit()
# Initilize fgt connection
ip = sys.argv[1]
try:
passwd = sys.argv[2]
except:
passwd = ''
#fgt = FGT(ip)
# Hard coded vdom value for all requests
vdom = "root"
# Login to the FGT ip
fgt = FortiOSAPI()
fgt.login(ip, 'admin', passwd)
data = {
'policyid': "66",
'name': "Testfortiosapi",
'action': "accept",
'srcintf': [{"name": "port1"}],
'dstintf': [{"name": "port2"}],
'srcaddr': [{"name": "all"}],
'dstaddr': [{"name": "all"}],
'schedule': "always",
'service': [{"name": "HTTPS"}],
"utm-status": "enable",
"profile-type": "single",
'av-profile': "default",
'profile-protocol-options': "default",
'ssl-ssh-profile': "certificate-inspection",
'logtraffic': "all",
}
fgt.set('firewall', 'policy', vdom="root", data=data)
fgt.logout()
if __name__ == '__main__':
main()
|
<commit_before>#!env python
#License upload using FORTIOSAPI from Github
import sys
from fortiosapi import FortiOSAPI
import json
def main():
# Parse for command line argument for fgt ip
if len(sys.argv) < 2:
# Requires fgt ip and vdom
print "Please specify fgt ip address"
exit()
# Initilize fgt connection
ip = sys.argv[1]
#fgt = FGT(ip)
# Hard coded vdom value for all requests
vdom = "root"
# Login to the FGT ip
fgt = FortiOSAPI()
fgt.login(ip,'admin','')
parameters = { 'global':'1' }
upload_data={'source':'upload',
'scope':'global'}
files={'file': ('license',open("license.lic", 'r'), 'text/plain')}
fgt.upload('system/vmlicense','upload',
data=upload_data,
parameters=parameters,
files=files)
fgt.logout()
if __name__ == '__main__':
main()<commit_msg>Create an example firewall rule push with the antivirus enablement.<commit_after>
|
#!/usr/bin/env python
#License upload using FORTIOSAPI from Github
import logging
import sys
from fortiosapi import FortiOSAPI
formatter = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
logger = logging.getLogger('fortiosapi')
hdlr = logging.FileHandler('testfortiosapi.log')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
def main():
# Parse for command line argument for fgt ip
if len(sys.argv) < 2:
# Requires fgt ip and password
print "Please specify fgt ip address"
exit()
# Initilize fgt connection
ip = sys.argv[1]
try:
passwd = sys.argv[2]
except:
passwd = ''
#fgt = FGT(ip)
# Hard coded vdom value for all requests
vdom = "root"
# Login to the FGT ip
fgt = FortiOSAPI()
fgt.login(ip, 'admin', passwd)
data = {
'policyid': "66",
'name': "Testfortiosapi",
'action': "accept",
'srcintf': [{"name": "port1"}],
'dstintf': [{"name": "port2"}],
'srcaddr': [{"name": "all"}],
'dstaddr': [{"name": "all"}],
'schedule': "always",
'service': [{"name": "HTTPS"}],
"utm-status": "enable",
"profile-type": "single",
'av-profile': "default",
'profile-protocol-options': "default",
'ssl-ssh-profile': "certificate-inspection",
'logtraffic': "all",
}
fgt.set('firewall', 'policy', vdom="root", data=data)
fgt.logout()
if __name__ == '__main__':
main()
|
#!env python
#License upload using FORTIOSAPI from Github
import sys
from fortiosapi import FortiOSAPI
import json
def main():
# Parse for command line argument for fgt ip
if len(sys.argv) < 2:
# Requires fgt ip and vdom
print "Please specify fgt ip address"
exit()
# Initilize fgt connection
ip = sys.argv[1]
#fgt = FGT(ip)
# Hard coded vdom value for all requests
vdom = "root"
# Login to the FGT ip
fgt = FortiOSAPI()
fgt.login(ip,'admin','')
parameters = { 'global':'1' }
upload_data={'source':'upload',
'scope':'global'}
files={'file': ('license',open("license.lic", 'r'), 'text/plain')}
fgt.upload('system/vmlicense','upload',
data=upload_data,
parameters=parameters,
files=files)
fgt.logout()
if __name__ == '__main__':
main()Create an example firewall rule push with the antivirus enablement.#!/usr/bin/env python
#License upload using FORTIOSAPI from Github
import logging
import sys
from fortiosapi import FortiOSAPI
formatter = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
logger = logging.getLogger('fortiosapi')
hdlr = logging.FileHandler('testfortiosapi.log')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
def main():
# Parse for command line argument for fgt ip
if len(sys.argv) < 2:
# Requires fgt ip and password
print "Please specify fgt ip address"
exit()
# Initilize fgt connection
ip = sys.argv[1]
try:
passwd = sys.argv[2]
except:
passwd = ''
#fgt = FGT(ip)
# Hard coded vdom value for all requests
vdom = "root"
# Login to the FGT ip
fgt = FortiOSAPI()
fgt.login(ip, 'admin', passwd)
data = {
'policyid': "66",
'name': "Testfortiosapi",
'action': "accept",
'srcintf': [{"name": "port1"}],
'dstintf': [{"name": "port2"}],
'srcaddr': [{"name": "all"}],
'dstaddr': [{"name": "all"}],
'schedule': "always",
'service': [{"name": "HTTPS"}],
"utm-status": "enable",
"profile-type": "single",
'av-profile': "default",
'profile-protocol-options': "default",
'ssl-ssh-profile': "certificate-inspection",
'logtraffic': "all",
}
fgt.set('firewall', 'policy', vdom="root", data=data)
fgt.logout()
if __name__ == '__main__':
main()
|
<commit_before>#!env python
#License upload using FORTIOSAPI from Github
import sys
from fortiosapi import FortiOSAPI
import json
def main():
# Parse for command line argument for fgt ip
if len(sys.argv) < 2:
# Requires fgt ip and vdom
print "Please specify fgt ip address"
exit()
# Initilize fgt connection
ip = sys.argv[1]
#fgt = FGT(ip)
# Hard coded vdom value for all requests
vdom = "root"
# Login to the FGT ip
fgt = FortiOSAPI()
fgt.login(ip,'admin','')
parameters = { 'global':'1' }
upload_data={'source':'upload',
'scope':'global'}
files={'file': ('license',open("license.lic", 'r'), 'text/plain')}
fgt.upload('system/vmlicense','upload',
data=upload_data,
parameters=parameters,
files=files)
fgt.logout()
if __name__ == '__main__':
main()<commit_msg>Create an example firewall rule push with the antivirus enablement.<commit_after>#!/usr/bin/env python
#License upload using FORTIOSAPI from Github
import logging
import sys
from fortiosapi import FortiOSAPI
formatter = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
logger = logging.getLogger('fortiosapi')
hdlr = logging.FileHandler('testfortiosapi.log')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
def main():
# Parse for command line argument for fgt ip
if len(sys.argv) < 2:
# Requires fgt ip and password
print "Please specify fgt ip address"
exit()
# Initilize fgt connection
ip = sys.argv[1]
try:
passwd = sys.argv[2]
except:
passwd = ''
#fgt = FGT(ip)
# Hard coded vdom value for all requests
vdom = "root"
# Login to the FGT ip
fgt = FortiOSAPI()
fgt.login(ip, 'admin', passwd)
data = {
'policyid': "66",
'name': "Testfortiosapi",
'action': "accept",
'srcintf': [{"name": "port1"}],
'dstintf': [{"name": "port2"}],
'srcaddr': [{"name": "all"}],
'dstaddr': [{"name": "all"}],
'schedule': "always",
'service': [{"name": "HTTPS"}],
"utm-status": "enable",
"profile-type": "single",
'av-profile': "default",
'profile-protocol-options': "default",
'ssl-ssh-profile': "certificate-inspection",
'logtraffic': "all",
}
fgt.set('firewall', 'policy', vdom="root", data=data)
fgt.logout()
if __name__ == '__main__':
main()
|
f2aecf968edc95fdab3ff47218e279c487464684
|
django_sites/templatetags/_sities_resolve.py
|
django_sites/templatetags/_sities_resolve.py
|
# -*- coding: utf-8 -*-
from .. import utils
try:
from django_jinja.base import Library
jinja_register = Library()
jinja_register.global_function("sites_resolve", utils.resolve)
except ImportError:
pass
|
# -*- coding: utf-8 -*-
from .. import utils
try:
from django_jinja.base import Library
jinja_register = Library()
jinja_register.global_function("sites_reverse", utils.reverse)
except ImportError:
pass
|
Fix invalid templatetag function register.
|
Fix invalid templatetag function register.
|
Python
|
bsd-3-clause
|
niwinz/django-sites,niwinz/django-sites
|
# -*- coding: utf-8 -*-
from .. import utils
try:
from django_jinja.base import Library
jinja_register = Library()
jinja_register.global_function("sites_resolve", utils.resolve)
except ImportError:
pass
Fix invalid templatetag function register.
|
# -*- coding: utf-8 -*-
from .. import utils
try:
from django_jinja.base import Library
jinja_register = Library()
jinja_register.global_function("sites_reverse", utils.reverse)
except ImportError:
pass
|
<commit_before># -*- coding: utf-8 -*-
from .. import utils
try:
from django_jinja.base import Library
jinja_register = Library()
jinja_register.global_function("sites_resolve", utils.resolve)
except ImportError:
pass
<commit_msg>Fix invalid templatetag function register.<commit_after>
|
# -*- coding: utf-8 -*-
from .. import utils
try:
from django_jinja.base import Library
jinja_register = Library()
jinja_register.global_function("sites_reverse", utils.reverse)
except ImportError:
pass
|
# -*- coding: utf-8 -*-
from .. import utils
try:
from django_jinja.base import Library
jinja_register = Library()
jinja_register.global_function("sites_resolve", utils.resolve)
except ImportError:
pass
Fix invalid templatetag function register.# -*- coding: utf-8 -*-
from .. import utils
try:
from django_jinja.base import Library
jinja_register = Library()
jinja_register.global_function("sites_reverse", utils.reverse)
except ImportError:
pass
|
<commit_before># -*- coding: utf-8 -*-
from .. import utils
try:
from django_jinja.base import Library
jinja_register = Library()
jinja_register.global_function("sites_resolve", utils.resolve)
except ImportError:
pass
<commit_msg>Fix invalid templatetag function register.<commit_after># -*- coding: utf-8 -*-
from .. import utils
try:
from django_jinja.base import Library
jinja_register = Library()
jinja_register.global_function("sites_reverse", utils.reverse)
except ImportError:
pass
|
81a35c396834667ba322456bac5abebe748e04f9
|
tests/test_django_prometheus.py
|
tests/test_django_prometheus.py
|
#!/usr/bin/env python
import django_prometheus
import unittest
# TODO(korfuri): Add real tests. For now, this is just a placeholder
# to set up a testing system.
class DjangoPrometheusTest(unittest.TestCase):
def testNothing(self):
self.assertTrue(True)
if __name__ == 'main':
unittest.main()
|
#!/usr/bin/env python
import django_prometheus
from django_prometheus.utils import PowersOf, _INF
import unittest
class DjangoPrometheusTest(unittest.TestCase):
def testPowersOf(self):
"""Tests utils.PowersOf."""
self.assertEqual(
[0, 1, 2, 4, 8, _INF],
PowersOf(2, 4))
self.assertEqual(
[0, 3, 9, 27, 81, 243, _INF],
PowersOf(3, 5, lower=1))
self.assertEqual(
[1, 2, 4, 8, _INF],
PowersOf(2, 4, include_zero=False))
self.assertEqual(
[4, 8, 16, 32, 64, 128, _INF],
PowersOf(2, 6, lower=2, include_zero=False))
if __name__ == 'main':
unittest.main()
|
Add a test for PowersOf.
|
Add a test for PowersOf.
|
Python
|
apache-2.0
|
obytes/django-prometheus,wangwanzhong/django-prometheus,wangwanzhong/django-prometheus,korfuri/django-prometheus,DingaGa/django-prometheus,DingaGa/django-prometheus,obytes/django-prometheus,korfuri/django-prometheus
|
#!/usr/bin/env python
import django_prometheus
import unittest
# TODO(korfuri): Add real tests. For now, this is just a placeholder
# to set up a testing system.
class DjangoPrometheusTest(unittest.TestCase):
def testNothing(self):
self.assertTrue(True)
if __name__ == 'main':
unittest.main()
Add a test for PowersOf.
|
#!/usr/bin/env python
import django_prometheus
from django_prometheus.utils import PowersOf, _INF
import unittest
class DjangoPrometheusTest(unittest.TestCase):
def testPowersOf(self):
"""Tests utils.PowersOf."""
self.assertEqual(
[0, 1, 2, 4, 8, _INF],
PowersOf(2, 4))
self.assertEqual(
[0, 3, 9, 27, 81, 243, _INF],
PowersOf(3, 5, lower=1))
self.assertEqual(
[1, 2, 4, 8, _INF],
PowersOf(2, 4, include_zero=False))
self.assertEqual(
[4, 8, 16, 32, 64, 128, _INF],
PowersOf(2, 6, lower=2, include_zero=False))
if __name__ == 'main':
unittest.main()
|
<commit_before>#!/usr/bin/env python
import django_prometheus
import unittest
# TODO(korfuri): Add real tests. For now, this is just a placeholder
# to set up a testing system.
class DjangoPrometheusTest(unittest.TestCase):
def testNothing(self):
self.assertTrue(True)
if __name__ == 'main':
unittest.main()
<commit_msg>Add a test for PowersOf.<commit_after>
|
#!/usr/bin/env python
import django_prometheus
from django_prometheus.utils import PowersOf, _INF
import unittest
class DjangoPrometheusTest(unittest.TestCase):
def testPowersOf(self):
"""Tests utils.PowersOf."""
self.assertEqual(
[0, 1, 2, 4, 8, _INF],
PowersOf(2, 4))
self.assertEqual(
[0, 3, 9, 27, 81, 243, _INF],
PowersOf(3, 5, lower=1))
self.assertEqual(
[1, 2, 4, 8, _INF],
PowersOf(2, 4, include_zero=False))
self.assertEqual(
[4, 8, 16, 32, 64, 128, _INF],
PowersOf(2, 6, lower=2, include_zero=False))
if __name__ == 'main':
unittest.main()
|
#!/usr/bin/env python
import django_prometheus
import unittest
# TODO(korfuri): Add real tests. For now, this is just a placeholder
# to set up a testing system.
class DjangoPrometheusTest(unittest.TestCase):
def testNothing(self):
self.assertTrue(True)
if __name__ == 'main':
unittest.main()
Add a test for PowersOf.#!/usr/bin/env python
import django_prometheus
from django_prometheus.utils import PowersOf, _INF
import unittest
class DjangoPrometheusTest(unittest.TestCase):
def testPowersOf(self):
"""Tests utils.PowersOf."""
self.assertEqual(
[0, 1, 2, 4, 8, _INF],
PowersOf(2, 4))
self.assertEqual(
[0, 3, 9, 27, 81, 243, _INF],
PowersOf(3, 5, lower=1))
self.assertEqual(
[1, 2, 4, 8, _INF],
PowersOf(2, 4, include_zero=False))
self.assertEqual(
[4, 8, 16, 32, 64, 128, _INF],
PowersOf(2, 6, lower=2, include_zero=False))
if __name__ == 'main':
unittest.main()
|
<commit_before>#!/usr/bin/env python
import django_prometheus
import unittest
# TODO(korfuri): Add real tests. For now, this is just a placeholder
# to set up a testing system.
class DjangoPrometheusTest(unittest.TestCase):
def testNothing(self):
self.assertTrue(True)
if __name__ == 'main':
unittest.main()
<commit_msg>Add a test for PowersOf.<commit_after>#!/usr/bin/env python
import django_prometheus
from django_prometheus.utils import PowersOf, _INF
import unittest
class DjangoPrometheusTest(unittest.TestCase):
def testPowersOf(self):
"""Tests utils.PowersOf."""
self.assertEqual(
[0, 1, 2, 4, 8, _INF],
PowersOf(2, 4))
self.assertEqual(
[0, 3, 9, 27, 81, 243, _INF],
PowersOf(3, 5, lower=1))
self.assertEqual(
[1, 2, 4, 8, _INF],
PowersOf(2, 4, include_zero=False))
self.assertEqual(
[4, 8, 16, 32, 64, 128, _INF],
PowersOf(2, 6, lower=2, include_zero=False))
if __name__ == 'main':
unittest.main()
|
02e41cb74be0c346f43453daad43353a2ee5ca0f
|
src/mercury/inventory/options.py
|
src/mercury/inventory/options.py
|
from mercury.common.configuration import MercuryConfiguration
DEFAULT_CONFIG_FILE = 'mercury-inventory.yaml'
def parse_options():
configuration = MercuryConfiguration(
'mercury-inventory',
DEFAULT_CONFIG_FILE,
description='The mercury inventory service'
)
configuration.add_option('inventory.bind_address',
default='tcp://127.0.0.1:9000',
help_string='Mercury Inventory bind address'
)
configuration.add_option('asyncio_debug',
'--asyncio-debug',
'ASYNCIO_DEBUG',
'logging.debug_asyncio',
default=False,
special_type=bool,
help_string='Enable asyncio debugging'
)
configuration.add_option('inventory.database.name',
default='test',
help_string='The inventory database')
configuration.add_option('inventory.database.collection',
default='inventory',
help_string='The collection for inventory '
'documents')
configuration.add_option('inventory.database.servers',
default='localhost:27017',
special_type=list,
help_string='Server or coma separated list of '
'servers to connect to')
configuration.add_option('inventory.database.replica_name',
help_string='An optional replica name')
configuration.add_option('inventory.database.user',
help_string='The database user')
configuration.add_option('inventory.database.password',
help_string='The database user\'s password')
return configuration.scan_options()
|
from mercury.common.configuration import MercuryConfiguration
DEFAULT_CONFIG_FILE = 'mercury-inventory.yaml'
def parse_options():
configuration = MercuryConfiguration(
'mercury-inventory',
DEFAULT_CONFIG_FILE,
description='The mercury inventory service'
)
configuration.add_option('inventory.bind_address',
default='tcp://127.0.0.1:9000',
help_string='Mercury Inventory bind address'
)
configuration.add_option('asyncio_debug',
'--asyncio-debug',
'ASYNCIO_DEBUG',
'logging.debug_asyncio',
default=False,
special_type=bool,
help_string='Enable asyncio debugging'
)
configuration.add_option('inventory.database.name',
default='test',
help_string='The inventory database')
configuration.add_option('inventory.database.collection',
default='inventory',
help_string='The collection for inventory '
'documents')
configuration.add_option('inventory.database.servers',
default='localhost:27017',
special_type=list,
help_string='Server or coma separated list of '
'servers to connect to')
configuration.add_option('inventory.database.replica_name',
help_string='An optional replica name')
configuration.add_option('inventory.database.username',
help_string='The database user')
configuration.add_option('inventory.database.password',
help_string='The database user\'s password')
return configuration.scan_options()
|
Use the correct option name
|
Use the correct option name
|
Python
|
apache-2.0
|
jr0d/mercury,jr0d/mercury
|
from mercury.common.configuration import MercuryConfiguration
DEFAULT_CONFIG_FILE = 'mercury-inventory.yaml'
def parse_options():
configuration = MercuryConfiguration(
'mercury-inventory',
DEFAULT_CONFIG_FILE,
description='The mercury inventory service'
)
configuration.add_option('inventory.bind_address',
default='tcp://127.0.0.1:9000',
help_string='Mercury Inventory bind address'
)
configuration.add_option('asyncio_debug',
'--asyncio-debug',
'ASYNCIO_DEBUG',
'logging.debug_asyncio',
default=False,
special_type=bool,
help_string='Enable asyncio debugging'
)
configuration.add_option('inventory.database.name',
default='test',
help_string='The inventory database')
configuration.add_option('inventory.database.collection',
default='inventory',
help_string='The collection for inventory '
'documents')
configuration.add_option('inventory.database.servers',
default='localhost:27017',
special_type=list,
help_string='Server or coma separated list of '
'servers to connect to')
configuration.add_option('inventory.database.replica_name',
help_string='An optional replica name')
configuration.add_option('inventory.database.user',
help_string='The database user')
configuration.add_option('inventory.database.password',
help_string='The database user\'s password')
return configuration.scan_options()
Use the correct option name
|
from mercury.common.configuration import MercuryConfiguration
DEFAULT_CONFIG_FILE = 'mercury-inventory.yaml'
def parse_options():
configuration = MercuryConfiguration(
'mercury-inventory',
DEFAULT_CONFIG_FILE,
description='The mercury inventory service'
)
configuration.add_option('inventory.bind_address',
default='tcp://127.0.0.1:9000',
help_string='Mercury Inventory bind address'
)
configuration.add_option('asyncio_debug',
'--asyncio-debug',
'ASYNCIO_DEBUG',
'logging.debug_asyncio',
default=False,
special_type=bool,
help_string='Enable asyncio debugging'
)
configuration.add_option('inventory.database.name',
default='test',
help_string='The inventory database')
configuration.add_option('inventory.database.collection',
default='inventory',
help_string='The collection for inventory '
'documents')
configuration.add_option('inventory.database.servers',
default='localhost:27017',
special_type=list,
help_string='Server or coma separated list of '
'servers to connect to')
configuration.add_option('inventory.database.replica_name',
help_string='An optional replica name')
configuration.add_option('inventory.database.username',
help_string='The database user')
configuration.add_option('inventory.database.password',
help_string='The database user\'s password')
return configuration.scan_options()
|
<commit_before>from mercury.common.configuration import MercuryConfiguration
DEFAULT_CONFIG_FILE = 'mercury-inventory.yaml'
def parse_options():
configuration = MercuryConfiguration(
'mercury-inventory',
DEFAULT_CONFIG_FILE,
description='The mercury inventory service'
)
configuration.add_option('inventory.bind_address',
default='tcp://127.0.0.1:9000',
help_string='Mercury Inventory bind address'
)
configuration.add_option('asyncio_debug',
'--asyncio-debug',
'ASYNCIO_DEBUG',
'logging.debug_asyncio',
default=False,
special_type=bool,
help_string='Enable asyncio debugging'
)
configuration.add_option('inventory.database.name',
default='test',
help_string='The inventory database')
configuration.add_option('inventory.database.collection',
default='inventory',
help_string='The collection for inventory '
'documents')
configuration.add_option('inventory.database.servers',
default='localhost:27017',
special_type=list,
help_string='Server or coma separated list of '
'servers to connect to')
configuration.add_option('inventory.database.replica_name',
help_string='An optional replica name')
configuration.add_option('inventory.database.user',
help_string='The database user')
configuration.add_option('inventory.database.password',
help_string='The database user\'s password')
return configuration.scan_options()
<commit_msg>Use the correct option name<commit_after>
|
from mercury.common.configuration import MercuryConfiguration
DEFAULT_CONFIG_FILE = 'mercury-inventory.yaml'
def parse_options():
configuration = MercuryConfiguration(
'mercury-inventory',
DEFAULT_CONFIG_FILE,
description='The mercury inventory service'
)
configuration.add_option('inventory.bind_address',
default='tcp://127.0.0.1:9000',
help_string='Mercury Inventory bind address'
)
configuration.add_option('asyncio_debug',
'--asyncio-debug',
'ASYNCIO_DEBUG',
'logging.debug_asyncio',
default=False,
special_type=bool,
help_string='Enable asyncio debugging'
)
configuration.add_option('inventory.database.name',
default='test',
help_string='The inventory database')
configuration.add_option('inventory.database.collection',
default='inventory',
help_string='The collection for inventory '
'documents')
configuration.add_option('inventory.database.servers',
default='localhost:27017',
special_type=list,
help_string='Server or coma separated list of '
'servers to connect to')
configuration.add_option('inventory.database.replica_name',
help_string='An optional replica name')
configuration.add_option('inventory.database.username',
help_string='The database user')
configuration.add_option('inventory.database.password',
help_string='The database user\'s password')
return configuration.scan_options()
|
from mercury.common.configuration import MercuryConfiguration
DEFAULT_CONFIG_FILE = 'mercury-inventory.yaml'
def parse_options():
configuration = MercuryConfiguration(
'mercury-inventory',
DEFAULT_CONFIG_FILE,
description='The mercury inventory service'
)
configuration.add_option('inventory.bind_address',
default='tcp://127.0.0.1:9000',
help_string='Mercury Inventory bind address'
)
configuration.add_option('asyncio_debug',
'--asyncio-debug',
'ASYNCIO_DEBUG',
'logging.debug_asyncio',
default=False,
special_type=bool,
help_string='Enable asyncio debugging'
)
configuration.add_option('inventory.database.name',
default='test',
help_string='The inventory database')
configuration.add_option('inventory.database.collection',
default='inventory',
help_string='The collection for inventory '
'documents')
configuration.add_option('inventory.database.servers',
default='localhost:27017',
special_type=list,
help_string='Server or coma separated list of '
'servers to connect to')
configuration.add_option('inventory.database.replica_name',
help_string='An optional replica name')
configuration.add_option('inventory.database.user',
help_string='The database user')
configuration.add_option('inventory.database.password',
help_string='The database user\'s password')
return configuration.scan_options()
Use the correct option namefrom mercury.common.configuration import MercuryConfiguration
DEFAULT_CONFIG_FILE = 'mercury-inventory.yaml'
def parse_options():
configuration = MercuryConfiguration(
'mercury-inventory',
DEFAULT_CONFIG_FILE,
description='The mercury inventory service'
)
configuration.add_option('inventory.bind_address',
default='tcp://127.0.0.1:9000',
help_string='Mercury Inventory bind address'
)
configuration.add_option('asyncio_debug',
'--asyncio-debug',
'ASYNCIO_DEBUG',
'logging.debug_asyncio',
default=False,
special_type=bool,
help_string='Enable asyncio debugging'
)
configuration.add_option('inventory.database.name',
default='test',
help_string='The inventory database')
configuration.add_option('inventory.database.collection',
default='inventory',
help_string='The collection for inventory '
'documents')
configuration.add_option('inventory.database.servers',
default='localhost:27017',
special_type=list,
help_string='Server or coma separated list of '
'servers to connect to')
configuration.add_option('inventory.database.replica_name',
help_string='An optional replica name')
configuration.add_option('inventory.database.username',
help_string='The database user')
configuration.add_option('inventory.database.password',
help_string='The database user\'s password')
return configuration.scan_options()
|
<commit_before>from mercury.common.configuration import MercuryConfiguration
DEFAULT_CONFIG_FILE = 'mercury-inventory.yaml'
def parse_options():
configuration = MercuryConfiguration(
'mercury-inventory',
DEFAULT_CONFIG_FILE,
description='The mercury inventory service'
)
configuration.add_option('inventory.bind_address',
default='tcp://127.0.0.1:9000',
help_string='Mercury Inventory bind address'
)
configuration.add_option('asyncio_debug',
'--asyncio-debug',
'ASYNCIO_DEBUG',
'logging.debug_asyncio',
default=False,
special_type=bool,
help_string='Enable asyncio debugging'
)
configuration.add_option('inventory.database.name',
default='test',
help_string='The inventory database')
configuration.add_option('inventory.database.collection',
default='inventory',
help_string='The collection for inventory '
'documents')
configuration.add_option('inventory.database.servers',
default='localhost:27017',
special_type=list,
help_string='Server or coma separated list of '
'servers to connect to')
configuration.add_option('inventory.database.replica_name',
help_string='An optional replica name')
configuration.add_option('inventory.database.user',
help_string='The database user')
configuration.add_option('inventory.database.password',
help_string='The database user\'s password')
return configuration.scan_options()
<commit_msg>Use the correct option name<commit_after>from mercury.common.configuration import MercuryConfiguration
DEFAULT_CONFIG_FILE = 'mercury-inventory.yaml'
def parse_options():
configuration = MercuryConfiguration(
'mercury-inventory',
DEFAULT_CONFIG_FILE,
description='The mercury inventory service'
)
configuration.add_option('inventory.bind_address',
default='tcp://127.0.0.1:9000',
help_string='Mercury Inventory bind address'
)
configuration.add_option('asyncio_debug',
'--asyncio-debug',
'ASYNCIO_DEBUG',
'logging.debug_asyncio',
default=False,
special_type=bool,
help_string='Enable asyncio debugging'
)
configuration.add_option('inventory.database.name',
default='test',
help_string='The inventory database')
configuration.add_option('inventory.database.collection',
default='inventory',
help_string='The collection for inventory '
'documents')
configuration.add_option('inventory.database.servers',
default='localhost:27017',
special_type=list,
help_string='Server or coma separated list of '
'servers to connect to')
configuration.add_option('inventory.database.replica_name',
help_string='An optional replica name')
configuration.add_option('inventory.database.username',
help_string='The database user')
configuration.add_option('inventory.database.password',
help_string='The database user\'s password')
return configuration.scan_options()
|
f701ee5a8c1ee707fedcb9e20c86161f537b9013
|
thinc/neural/_classes/resnet.py
|
thinc/neural/_classes/resnet.py
|
from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
return X + self._layers[0](X)
def begin_update(self, X, drop=0.):
y, bp_y = self._layers[0].begin_update(X, drop=drop)
output = X+y
def residual_bwd(d_output, sgd=None):
return d_output + bp_y(d_output, sgd)
return output, residual_bwd
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
if hasattr(layer, 'W'):
layer.W.fill(0)
|
from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
Y = self._layers[0](X)
if isinstance(X, list) or isinstance(X, tuple):
return [X[i]+Y[i] for i in range(len(X))]
else:
return X + Y
def begin_update(self, X, drop=0.):
y, bp_y = self._layers[0].begin_update(X, drop=drop)
if isinstance(X, list) or isinstance(X, tuple):
output = [X[i]+y[i] for i in range(len(X))]
else:
output = X+y
def residual_bwd(d_output, sgd=None):
dX = bp_y(d_output, sgd)
if isinstance(d_output, list) or isinstance(d_output, tuple):
return [d_output[i]+dX[i] for i in range(len(d_output))]
else:
return d_output + dX
return output, residual_bwd
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
if hasattr(layer, 'W'):
layer.W.fill(0)
|
Make residual connections work for list-valued inputs
|
Make residual connections work for list-valued inputs
|
Python
|
mit
|
spacy-io/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc
|
from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
return X + self._layers[0](X)
def begin_update(self, X, drop=0.):
y, bp_y = self._layers[0].begin_update(X, drop=drop)
output = X+y
def residual_bwd(d_output, sgd=None):
return d_output + bp_y(d_output, sgd)
return output, residual_bwd
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
if hasattr(layer, 'W'):
layer.W.fill(0)
Make residual connections work for list-valued inputs
|
from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
Y = self._layers[0](X)
if isinstance(X, list) or isinstance(X, tuple):
return [X[i]+Y[i] for i in range(len(X))]
else:
return X + Y
def begin_update(self, X, drop=0.):
y, bp_y = self._layers[0].begin_update(X, drop=drop)
if isinstance(X, list) or isinstance(X, tuple):
output = [X[i]+y[i] for i in range(len(X))]
else:
output = X+y
def residual_bwd(d_output, sgd=None):
dX = bp_y(d_output, sgd)
if isinstance(d_output, list) or isinstance(d_output, tuple):
return [d_output[i]+dX[i] for i in range(len(d_output))]
else:
return d_output + dX
return output, residual_bwd
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
if hasattr(layer, 'W'):
layer.W.fill(0)
|
<commit_before>from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
return X + self._layers[0](X)
def begin_update(self, X, drop=0.):
y, bp_y = self._layers[0].begin_update(X, drop=drop)
output = X+y
def residual_bwd(d_output, sgd=None):
return d_output + bp_y(d_output, sgd)
return output, residual_bwd
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
if hasattr(layer, 'W'):
layer.W.fill(0)
<commit_msg>Make residual connections work for list-valued inputs<commit_after>
|
from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
Y = self._layers[0](X)
if isinstance(X, list) or isinstance(X, tuple):
return [X[i]+Y[i] for i in range(len(X))]
else:
return X + Y
def begin_update(self, X, drop=0.):
y, bp_y = self._layers[0].begin_update(X, drop=drop)
if isinstance(X, list) or isinstance(X, tuple):
output = [X[i]+y[i] for i in range(len(X))]
else:
output = X+y
def residual_bwd(d_output, sgd=None):
dX = bp_y(d_output, sgd)
if isinstance(d_output, list) or isinstance(d_output, tuple):
return [d_output[i]+dX[i] for i in range(len(d_output))]
else:
return d_output + dX
return output, residual_bwd
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
if hasattr(layer, 'W'):
layer.W.fill(0)
|
from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
return X + self._layers[0](X)
def begin_update(self, X, drop=0.):
y, bp_y = self._layers[0].begin_update(X, drop=drop)
output = X+y
def residual_bwd(d_output, sgd=None):
return d_output + bp_y(d_output, sgd)
return output, residual_bwd
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
if hasattr(layer, 'W'):
layer.W.fill(0)
Make residual connections work for list-valued inputsfrom .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
Y = self._layers[0](X)
if isinstance(X, list) or isinstance(X, tuple):
return [X[i]+Y[i] for i in range(len(X))]
else:
return X + Y
def begin_update(self, X, drop=0.):
y, bp_y = self._layers[0].begin_update(X, drop=drop)
if isinstance(X, list) or isinstance(X, tuple):
output = [X[i]+y[i] for i in range(len(X))]
else:
output = X+y
def residual_bwd(d_output, sgd=None):
dX = bp_y(d_output, sgd)
if isinstance(d_output, list) or isinstance(d_output, tuple):
return [d_output[i]+dX[i] for i in range(len(d_output))]
else:
return d_output + dX
return output, residual_bwd
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
if hasattr(layer, 'W'):
layer.W.fill(0)
|
<commit_before>from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
return X + self._layers[0](X)
def begin_update(self, X, drop=0.):
y, bp_y = self._layers[0].begin_update(X, drop=drop)
output = X+y
def residual_bwd(d_output, sgd=None):
return d_output + bp_y(d_output, sgd)
return output, residual_bwd
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
if hasattr(layer, 'W'):
layer.W.fill(0)
<commit_msg>Make residual connections work for list-valued inputs<commit_after>from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
Y = self._layers[0](X)
if isinstance(X, list) or isinstance(X, tuple):
return [X[i]+Y[i] for i in range(len(X))]
else:
return X + Y
def begin_update(self, X, drop=0.):
y, bp_y = self._layers[0].begin_update(X, drop=drop)
if isinstance(X, list) or isinstance(X, tuple):
output = [X[i]+y[i] for i in range(len(X))]
else:
output = X+y
def residual_bwd(d_output, sgd=None):
dX = bp_y(d_output, sgd)
if isinstance(d_output, list) or isinstance(d_output, tuple):
return [d_output[i]+dX[i] for i in range(len(d_output))]
else:
return d_output + dX
return output, residual_bwd
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
if hasattr(layer, 'W'):
layer.W.fill(0)
|
5ab5d583aa056fb15b3b375768665aea8e9ab4be
|
pyhomer/__init__.py
|
pyhomer/__init__.py
|
# -*- coding: utf-8 -*-
__author__ = 'Olga Botvinnik'
__email__ = 'olga.botvinnik@gmail.com'
__version__ = '0.1.0'
from .pyhomer import ForegroundBackgroundPair
|
# -*- coding: utf-8 -*-
__author__ = 'Olga Botvinnik'
__email__ = 'olga.botvinnik@gmail.com'
__version__ = '0.1.0'
from .pyhomer import ForegroundBackgroundPair, construct_homer_command
|
Add constructing homer command to module level functions
|
Add constructing homer command to module level functions
|
Python
|
bsd-3-clause
|
olgabot/pyhomer
|
# -*- coding: utf-8 -*-
__author__ = 'Olga Botvinnik'
__email__ = 'olga.botvinnik@gmail.com'
__version__ = '0.1.0'
from .pyhomer import ForegroundBackgroundPairAdd constructing homer command to module level functions
|
# -*- coding: utf-8 -*-
__author__ = 'Olga Botvinnik'
__email__ = 'olga.botvinnik@gmail.com'
__version__ = '0.1.0'
from .pyhomer import ForegroundBackgroundPair, construct_homer_command
|
<commit_before># -*- coding: utf-8 -*-
__author__ = 'Olga Botvinnik'
__email__ = 'olga.botvinnik@gmail.com'
__version__ = '0.1.0'
from .pyhomer import ForegroundBackgroundPair<commit_msg>Add constructing homer command to module level functions<commit_after>
|
# -*- coding: utf-8 -*-
__author__ = 'Olga Botvinnik'
__email__ = 'olga.botvinnik@gmail.com'
__version__ = '0.1.0'
from .pyhomer import ForegroundBackgroundPair, construct_homer_command
|
# -*- coding: utf-8 -*-
__author__ = 'Olga Botvinnik'
__email__ = 'olga.botvinnik@gmail.com'
__version__ = '0.1.0'
from .pyhomer import ForegroundBackgroundPairAdd constructing homer command to module level functions# -*- coding: utf-8 -*-
__author__ = 'Olga Botvinnik'
__email__ = 'olga.botvinnik@gmail.com'
__version__ = '0.1.0'
from .pyhomer import ForegroundBackgroundPair, construct_homer_command
|
<commit_before># -*- coding: utf-8 -*-
__author__ = 'Olga Botvinnik'
__email__ = 'olga.botvinnik@gmail.com'
__version__ = '0.1.0'
from .pyhomer import ForegroundBackgroundPair<commit_msg>Add constructing homer command to module level functions<commit_after># -*- coding: utf-8 -*-
__author__ = 'Olga Botvinnik'
__email__ = 'olga.botvinnik@gmail.com'
__version__ = '0.1.0'
from .pyhomer import ForegroundBackgroundPair, construct_homer_command
|
c56cc755044e223c3ac641ba4bbcb38a6780bd4d
|
apps/polls/templatetags/react_polls.py
|
apps/polls/templatetags/react_polls.py
|
import json
from django import template
from django.utils.html import format_html
from rest_framework.renderers import JSONRenderer
from .. import serializers
register = template.Library()
@register.simple_tag(takes_context=True)
def react_polls(context, question):
user = context['request'].user
user_choices = question.user_choices_list(user)
# TODO: use serializer
data = {
'label': question.label,
'choices': [{
'label': choice.label,
'count': choice.vote_count,
'ownChoice': (choice.pk in user_choices)
} for choice in question.choices.annotate_with_vote_count()]
}
return format_html(
(
'<div id="{id}" data-question="{question}"></div>'
'<script>window.adhocracy4.renderPolls("{id}")</script>'
),
id='question-%s' % (question.pk,),
question=json.dumps(data)
)
@register.simple_tag
def react_poll_form(poll):
serializer = serializers.PollSerializer(poll)
data_poll = JSONRenderer().render(serializer.data)
return format_html(
(
'<div id="{id}" data-poll="{poll}"></div>'
'<script>window.adhocracy4.renderPollManagement("{id}")</script>'
),
id='question-%s' % (poll.pk,),
poll=data_poll
)
|
import json
from django import template
from django.utils.html import format_html
from rest_framework.renderers import JSONRenderer
from .. import serializers
register = template.Library()
@register.simple_tag(takes_context=True)
def react_polls(context, question):
user = context['request'].user
user_choices = question.user_choices_list(user)
# TODO: use serializer
data = {
'label': question.label,
'choices': [{
'label': choice.label,
'count': choice.vote_count,
'ownChoice': (choice.pk in user_choices)
} for choice in question.choices.annotate_vote_count()]
}
return format_html(
(
'<div id="{id}" data-question="{question}"></div>'
'<script>window.adhocracy4.renderPolls("{id}")</script>'
),
id='question-%s' % (question.pk,),
question=json.dumps(data)
)
@register.simple_tag
def react_poll_form(poll):
serializer = serializers.PollSerializer(poll)
data_poll = JSONRenderer().render(serializer.data)
return format_html(
(
'<div id="{id}" data-poll="{poll}"></div>'
'<script>window.adhocracy4.renderPollManagement("{id}")</script>'
),
id='question-%s' % (poll.pk,),
poll=data_poll
)
|
Use Manager to annotate vote count
|
Fix: Use Manager to annotate vote count
|
Python
|
agpl-3.0
|
liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin
|
import json
from django import template
from django.utils.html import format_html
from rest_framework.renderers import JSONRenderer
from .. import serializers
register = template.Library()
@register.simple_tag(takes_context=True)
def react_polls(context, question):
user = context['request'].user
user_choices = question.user_choices_list(user)
# TODO: use serializer
data = {
'label': question.label,
'choices': [{
'label': choice.label,
'count': choice.vote_count,
'ownChoice': (choice.pk in user_choices)
} for choice in question.choices.annotate_with_vote_count()]
}
return format_html(
(
'<div id="{id}" data-question="{question}"></div>'
'<script>window.adhocracy4.renderPolls("{id}")</script>'
),
id='question-%s' % (question.pk,),
question=json.dumps(data)
)
@register.simple_tag
def react_poll_form(poll):
serializer = serializers.PollSerializer(poll)
data_poll = JSONRenderer().render(serializer.data)
return format_html(
(
'<div id="{id}" data-poll="{poll}"></div>'
'<script>window.adhocracy4.renderPollManagement("{id}")</script>'
),
id='question-%s' % (poll.pk,),
poll=data_poll
)
Fix: Use Manager to annotate vote count
|
import json
from django import template
from django.utils.html import format_html
from rest_framework.renderers import JSONRenderer
from .. import serializers
register = template.Library()
@register.simple_tag(takes_context=True)
def react_polls(context, question):
user = context['request'].user
user_choices = question.user_choices_list(user)
# TODO: use serializer
data = {
'label': question.label,
'choices': [{
'label': choice.label,
'count': choice.vote_count,
'ownChoice': (choice.pk in user_choices)
} for choice in question.choices.annotate_vote_count()]
}
return format_html(
(
'<div id="{id}" data-question="{question}"></div>'
'<script>window.adhocracy4.renderPolls("{id}")</script>'
),
id='question-%s' % (question.pk,),
question=json.dumps(data)
)
@register.simple_tag
def react_poll_form(poll):
serializer = serializers.PollSerializer(poll)
data_poll = JSONRenderer().render(serializer.data)
return format_html(
(
'<div id="{id}" data-poll="{poll}"></div>'
'<script>window.adhocracy4.renderPollManagement("{id}")</script>'
),
id='question-%s' % (poll.pk,),
poll=data_poll
)
|
<commit_before>import json
from django import template
from django.utils.html import format_html
from rest_framework.renderers import JSONRenderer
from .. import serializers
register = template.Library()
@register.simple_tag(takes_context=True)
def react_polls(context, question):
user = context['request'].user
user_choices = question.user_choices_list(user)
# TODO: use serializer
data = {
'label': question.label,
'choices': [{
'label': choice.label,
'count': choice.vote_count,
'ownChoice': (choice.pk in user_choices)
} for choice in question.choices.annotate_with_vote_count()]
}
return format_html(
(
'<div id="{id}" data-question="{question}"></div>'
'<script>window.adhocracy4.renderPolls("{id}")</script>'
),
id='question-%s' % (question.pk,),
question=json.dumps(data)
)
@register.simple_tag
def react_poll_form(poll):
serializer = serializers.PollSerializer(poll)
data_poll = JSONRenderer().render(serializer.data)
return format_html(
(
'<div id="{id}" data-poll="{poll}"></div>'
'<script>window.adhocracy4.renderPollManagement("{id}")</script>'
),
id='question-%s' % (poll.pk,),
poll=data_poll
)
<commit_msg>Fix: Use Manager to annotate vote count<commit_after>
|
import json
from django import template
from django.utils.html import format_html
from rest_framework.renderers import JSONRenderer
from .. import serializers
register = template.Library()
@register.simple_tag(takes_context=True)
def react_polls(context, question):
user = context['request'].user
user_choices = question.user_choices_list(user)
# TODO: use serializer
data = {
'label': question.label,
'choices': [{
'label': choice.label,
'count': choice.vote_count,
'ownChoice': (choice.pk in user_choices)
} for choice in question.choices.annotate_vote_count()]
}
return format_html(
(
'<div id="{id}" data-question="{question}"></div>'
'<script>window.adhocracy4.renderPolls("{id}")</script>'
),
id='question-%s' % (question.pk,),
question=json.dumps(data)
)
@register.simple_tag
def react_poll_form(poll):
serializer = serializers.PollSerializer(poll)
data_poll = JSONRenderer().render(serializer.data)
return format_html(
(
'<div id="{id}" data-poll="{poll}"></div>'
'<script>window.adhocracy4.renderPollManagement("{id}")</script>'
),
id='question-%s' % (poll.pk,),
poll=data_poll
)
|
import json
from django import template
from django.utils.html import format_html
from rest_framework.renderers import JSONRenderer
from .. import serializers
register = template.Library()
@register.simple_tag(takes_context=True)
def react_polls(context, question):
user = context['request'].user
user_choices = question.user_choices_list(user)
# TODO: use serializer
data = {
'label': question.label,
'choices': [{
'label': choice.label,
'count': choice.vote_count,
'ownChoice': (choice.pk in user_choices)
} for choice in question.choices.annotate_with_vote_count()]
}
return format_html(
(
'<div id="{id}" data-question="{question}"></div>'
'<script>window.adhocracy4.renderPolls("{id}")</script>'
),
id='question-%s' % (question.pk,),
question=json.dumps(data)
)
@register.simple_tag
def react_poll_form(poll):
serializer = serializers.PollSerializer(poll)
data_poll = JSONRenderer().render(serializer.data)
return format_html(
(
'<div id="{id}" data-poll="{poll}"></div>'
'<script>window.adhocracy4.renderPollManagement("{id}")</script>'
),
id='question-%s' % (poll.pk,),
poll=data_poll
)
Fix: Use Manager to annotate vote countimport json
from django import template
from django.utils.html import format_html
from rest_framework.renderers import JSONRenderer
from .. import serializers
register = template.Library()
@register.simple_tag(takes_context=True)
def react_polls(context, question):
user = context['request'].user
user_choices = question.user_choices_list(user)
# TODO: use serializer
data = {
'label': question.label,
'choices': [{
'label': choice.label,
'count': choice.vote_count,
'ownChoice': (choice.pk in user_choices)
} for choice in question.choices.annotate_vote_count()]
}
return format_html(
(
'<div id="{id}" data-question="{question}"></div>'
'<script>window.adhocracy4.renderPolls("{id}")</script>'
),
id='question-%s' % (question.pk,),
question=json.dumps(data)
)
@register.simple_tag
def react_poll_form(poll):
serializer = serializers.PollSerializer(poll)
data_poll = JSONRenderer().render(serializer.data)
return format_html(
(
'<div id="{id}" data-poll="{poll}"></div>'
'<script>window.adhocracy4.renderPollManagement("{id}")</script>'
),
id='question-%s' % (poll.pk,),
poll=data_poll
)
|
<commit_before>import json
from django import template
from django.utils.html import format_html
from rest_framework.renderers import JSONRenderer
from .. import serializers
register = template.Library()
@register.simple_tag(takes_context=True)
def react_polls(context, question):
user = context['request'].user
user_choices = question.user_choices_list(user)
# TODO: use serializer
data = {
'label': question.label,
'choices': [{
'label': choice.label,
'count': choice.vote_count,
'ownChoice': (choice.pk in user_choices)
} for choice in question.choices.annotate_with_vote_count()]
}
return format_html(
(
'<div id="{id}" data-question="{question}"></div>'
'<script>window.adhocracy4.renderPolls("{id}")</script>'
),
id='question-%s' % (question.pk,),
question=json.dumps(data)
)
@register.simple_tag
def react_poll_form(poll):
serializer = serializers.PollSerializer(poll)
data_poll = JSONRenderer().render(serializer.data)
return format_html(
(
'<div id="{id}" data-poll="{poll}"></div>'
'<script>window.adhocracy4.renderPollManagement("{id}")</script>'
),
id='question-%s' % (poll.pk,),
poll=data_poll
)
<commit_msg>Fix: Use Manager to annotate vote count<commit_after>import json
from django import template
from django.utils.html import format_html
from rest_framework.renderers import JSONRenderer
from .. import serializers
register = template.Library()
@register.simple_tag(takes_context=True)
def react_polls(context, question):
user = context['request'].user
user_choices = question.user_choices_list(user)
# TODO: use serializer
data = {
'label': question.label,
'choices': [{
'label': choice.label,
'count': choice.vote_count,
'ownChoice': (choice.pk in user_choices)
} for choice in question.choices.annotate_vote_count()]
}
return format_html(
(
'<div id="{id}" data-question="{question}"></div>'
'<script>window.adhocracy4.renderPolls("{id}")</script>'
),
id='question-%s' % (question.pk,),
question=json.dumps(data)
)
@register.simple_tag
def react_poll_form(poll):
serializer = serializers.PollSerializer(poll)
data_poll = JSONRenderer().render(serializer.data)
return format_html(
(
'<div id="{id}" data-poll="{poll}"></div>'
'<script>window.adhocracy4.renderPollManagement("{id}")</script>'
),
id='question-%s' % (poll.pk,),
poll=data_poll
)
|
e08c2b053ab99de5a77b49b43524f5fab816b19e
|
fluent_blogs/templatetags/fluent_blogs_comments_tags.py
|
fluent_blogs/templatetags/fluent_blogs_comments_tags.py
|
"""
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
from django.template import Library
from fluent_utils.django_compat import is_installed
# Expose the tag library in the site.
# If `django.contrib.comments` is not used, this library can provide stubs instead.
# Currently, the real tags are exposed as the template already checks for `object.comments_are_open`.
# When a custom template is used, authors likely choose the desired commenting library instead.
if is_installed('django.contrib.comments'):
from django.contrib.comments.templatetags.comments import register
elif is_installed('django_comments'):
from django_comments.templatetags.comments import register
else:
register = Library()
|
"""
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
import warnings
from django.template import Library
from django.utils.safestring import mark_safe
from fluent_utils.django_compat import is_installed
# Expose the tag library in the site.
# If `django.contrib.comments` is not used, this library can provide stubs instead.
# Currently, the real tags are exposed as the template already checks for `object.comments_are_open`.
# When a custom template is used, authors likely choose the desired commenting library instead.
if is_installed('django.contrib.comments'):
from django.contrib.comments.templatetags.comments import register
elif is_installed('django_comments'):
from django_comments.templatetags.comments import register
else:
register = Library()
@register.simple_tag
def render_comment_list(for_, object):
warnings.warn(
"Can't render comments list: no comment app installed!\n"
"Make sure either 'django.contrib.comments' or 'django_comments' is in INSTALLED_APPS"
)
return mark_safe("<!-- Can't render comments list: no comment plugin installed! -->")
@register.simple_tag
def render_comment_form(for_, object):
warnings.warn(
"Can't render comments form: no comment app installed!\n"
"Make sure either 'django.contrib.comments' or 'django_comments' is in INSTALLED_APPS"
)
return mark_safe("<!-- no comment plugin installed! -->")
|
Add render_comment_list / render_comment_form stub tags for Django
|
Add render_comment_list / render_comment_form stub tags for Django
|
Python
|
apache-2.0
|
edoburu/django-fluent-blogs,edoburu/django-fluent-blogs
|
"""
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
from django.template import Library
from fluent_utils.django_compat import is_installed
# Expose the tag library in the site.
# If `django.contrib.comments` is not used, this library can provide stubs instead.
# Currently, the real tags are exposed as the template already checks for `object.comments_are_open`.
# When a custom template is used, authors likely choose the desired commenting library instead.
if is_installed('django.contrib.comments'):
from django.contrib.comments.templatetags.comments import register
elif is_installed('django_comments'):
from django_comments.templatetags.comments import register
else:
register = Library()
Add render_comment_list / render_comment_form stub tags for Django
|
"""
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
import warnings
from django.template import Library
from django.utils.safestring import mark_safe
from fluent_utils.django_compat import is_installed
# Expose the tag library in the site.
# If `django.contrib.comments` is not used, this library can provide stubs instead.
# Currently, the real tags are exposed as the template already checks for `object.comments_are_open`.
# When a custom template is used, authors likely choose the desired commenting library instead.
if is_installed('django.contrib.comments'):
from django.contrib.comments.templatetags.comments import register
elif is_installed('django_comments'):
from django_comments.templatetags.comments import register
else:
register = Library()
@register.simple_tag
def render_comment_list(for_, object):
warnings.warn(
"Can't render comments list: no comment app installed!\n"
"Make sure either 'django.contrib.comments' or 'django_comments' is in INSTALLED_APPS"
)
return mark_safe("<!-- Can't render comments list: no comment plugin installed! -->")
@register.simple_tag
def render_comment_form(for_, object):
warnings.warn(
"Can't render comments form: no comment app installed!\n"
"Make sure either 'django.contrib.comments' or 'django_comments' is in INSTALLED_APPS"
)
return mark_safe("<!-- no comment plugin installed! -->")
|
<commit_before>"""
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
from django.template import Library
from fluent_utils.django_compat import is_installed
# Expose the tag library in the site.
# If `django.contrib.comments` is not used, this library can provide stubs instead.
# Currently, the real tags are exposed as the template already checks for `object.comments_are_open`.
# When a custom template is used, authors likely choose the desired commenting library instead.
if is_installed('django.contrib.comments'):
from django.contrib.comments.templatetags.comments import register
elif is_installed('django_comments'):
from django_comments.templatetags.comments import register
else:
register = Library()
<commit_msg>Add render_comment_list / render_comment_form stub tags for Django<commit_after>
|
"""
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
import warnings
from django.template import Library
from django.utils.safestring import mark_safe
from fluent_utils.django_compat import is_installed
# Expose the tag library in the site.
# If `django.contrib.comments` is not used, this library can provide stubs instead.
# Currently, the real tags are exposed as the template already checks for `object.comments_are_open`.
# When a custom template is used, authors likely choose the desired commenting library instead.
if is_installed('django.contrib.comments'):
from django.contrib.comments.templatetags.comments import register
elif is_installed('django_comments'):
from django_comments.templatetags.comments import register
else:
register = Library()
@register.simple_tag
def render_comment_list(for_, object):
warnings.warn(
"Can't render comments list: no comment app installed!\n"
"Make sure either 'django.contrib.comments' or 'django_comments' is in INSTALLED_APPS"
)
return mark_safe("<!-- Can't render comments list: no comment plugin installed! -->")
@register.simple_tag
def render_comment_form(for_, object):
warnings.warn(
"Can't render comments form: no comment app installed!\n"
"Make sure either 'django.contrib.comments' or 'django_comments' is in INSTALLED_APPS"
)
return mark_safe("<!-- no comment plugin installed! -->")
|
"""
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
from django.template import Library
from fluent_utils.django_compat import is_installed
# Expose the tag library in the site.
# If `django.contrib.comments` is not used, this library can provide stubs instead.
# Currently, the real tags are exposed as the template already checks for `object.comments_are_open`.
# When a custom template is used, authors likely choose the desired commenting library instead.
if is_installed('django.contrib.comments'):
from django.contrib.comments.templatetags.comments import register
elif is_installed('django_comments'):
from django_comments.templatetags.comments import register
else:
register = Library()
Add render_comment_list / render_comment_form stub tags for Django"""
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
import warnings
from django.template import Library
from django.utils.safestring import mark_safe
from fluent_utils.django_compat import is_installed
# Expose the tag library in the site.
# If `django.contrib.comments` is not used, this library can provide stubs instead.
# Currently, the real tags are exposed as the template already checks for `object.comments_are_open`.
# When a custom template is used, authors likely choose the desired commenting library instead.
if is_installed('django.contrib.comments'):
from django.contrib.comments.templatetags.comments import register
elif is_installed('django_comments'):
from django_comments.templatetags.comments import register
else:
register = Library()
@register.simple_tag
def render_comment_list(for_, object):
warnings.warn(
"Can't render comments list: no comment app installed!\n"
"Make sure either 'django.contrib.comments' or 'django_comments' is in INSTALLED_APPS"
)
return mark_safe("<!-- Can't render comments list: no comment plugin installed! -->")
@register.simple_tag
def render_comment_form(for_, object):
warnings.warn(
"Can't render comments form: no comment app installed!\n"
"Make sure either 'django.contrib.comments' or 'django_comments' is in INSTALLED_APPS"
)
return mark_safe("<!-- no comment plugin installed! -->")
|
<commit_before>"""
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
from django.template import Library
from fluent_utils.django_compat import is_installed
# Expose the tag library in the site.
# If `django.contrib.comments` is not used, this library can provide stubs instead.
# Currently, the real tags are exposed as the template already checks for `object.comments_are_open`.
# When a custom template is used, authors likely choose the desired commenting library instead.
if is_installed('django.contrib.comments'):
from django.contrib.comments.templatetags.comments import register
elif is_installed('django_comments'):
from django_comments.templatetags.comments import register
else:
register = Library()
<commit_msg>Add render_comment_list / render_comment_form stub tags for Django<commit_after>"""
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
import warnings
from django.template import Library
from django.utils.safestring import mark_safe
from fluent_utils.django_compat import is_installed
# Expose the tag library in the site.
# If `django.contrib.comments` is not used, this library can provide stubs instead.
# Currently, the real tags are exposed as the template already checks for `object.comments_are_open`.
# When a custom template is used, authors likely choose the desired commenting library instead.
if is_installed('django.contrib.comments'):
from django.contrib.comments.templatetags.comments import register
elif is_installed('django_comments'):
from django_comments.templatetags.comments import register
else:
register = Library()
@register.simple_tag
def render_comment_list(for_, object):
warnings.warn(
"Can't render comments list: no comment app installed!\n"
"Make sure either 'django.contrib.comments' or 'django_comments' is in INSTALLED_APPS"
)
return mark_safe("<!-- Can't render comments list: no comment plugin installed! -->")
@register.simple_tag
def render_comment_form(for_, object):
warnings.warn(
"Can't render comments form: no comment app installed!\n"
"Make sure either 'django.contrib.comments' or 'django_comments' is in INSTALLED_APPS"
)
return mark_safe("<!-- no comment plugin installed! -->")
|
514be833dd759c51a2b3f8ca0ae2df4499d63b83
|
tests/test_video_conferences.py
|
tests/test_video_conferences.py
|
import pytest
@pytest.mark.skip(
reason="Broken in 5.0. https://github.com/RocketChat/Rocket.Chat/issues/26520"
)
def test_update_jitsi_timeout(logged_rocket):
update_jitsi_timeout = logged_rocket.update_jitsi_timeout(room_id="GENERAL").json()
assert update_jitsi_timeout.get("success")
|
import pytest
# TODO: Go back to this test once the ticket has being answered
@pytest.mark.skip(
reason="Broken in 5.0. https://github.com/RocketChat/Rocket.Chat/issues/26520"
)
def test_update_jitsi_timeout(logged_rocket):
update_jitsi_timeout = logged_rocket.update_jitsi_timeout(room_id="GENERAL").json()
assert update_jitsi_timeout.get("success")
|
Add todo in the test_update_jitsi_timeout so it's easier to find in the future
|
Add todo in the test_update_jitsi_timeout so it's easier to find in the future
|
Python
|
mit
|
jadolg/rocketchat_API
|
import pytest
@pytest.mark.skip(
reason="Broken in 5.0. https://github.com/RocketChat/Rocket.Chat/issues/26520"
)
def test_update_jitsi_timeout(logged_rocket):
update_jitsi_timeout = logged_rocket.update_jitsi_timeout(room_id="GENERAL").json()
assert update_jitsi_timeout.get("success")
Add todo in the test_update_jitsi_timeout so it's easier to find in the future
|
import pytest
# TODO: Go back to this test once the ticket has being answered
@pytest.mark.skip(
reason="Broken in 5.0. https://github.com/RocketChat/Rocket.Chat/issues/26520"
)
def test_update_jitsi_timeout(logged_rocket):
update_jitsi_timeout = logged_rocket.update_jitsi_timeout(room_id="GENERAL").json()
assert update_jitsi_timeout.get("success")
|
<commit_before>import pytest
@pytest.mark.skip(
reason="Broken in 5.0. https://github.com/RocketChat/Rocket.Chat/issues/26520"
)
def test_update_jitsi_timeout(logged_rocket):
update_jitsi_timeout = logged_rocket.update_jitsi_timeout(room_id="GENERAL").json()
assert update_jitsi_timeout.get("success")
<commit_msg>Add todo in the test_update_jitsi_timeout so it's easier to find in the future<commit_after>
|
import pytest
# TODO: Go back to this test once the ticket has being answered
@pytest.mark.skip(
reason="Broken in 5.0. https://github.com/RocketChat/Rocket.Chat/issues/26520"
)
def test_update_jitsi_timeout(logged_rocket):
update_jitsi_timeout = logged_rocket.update_jitsi_timeout(room_id="GENERAL").json()
assert update_jitsi_timeout.get("success")
|
import pytest
@pytest.mark.skip(
reason="Broken in 5.0. https://github.com/RocketChat/Rocket.Chat/issues/26520"
)
def test_update_jitsi_timeout(logged_rocket):
update_jitsi_timeout = logged_rocket.update_jitsi_timeout(room_id="GENERAL").json()
assert update_jitsi_timeout.get("success")
Add todo in the test_update_jitsi_timeout so it's easier to find in the futureimport pytest
# TODO: Go back to this test once the ticket has being answered
@pytest.mark.skip(
reason="Broken in 5.0. https://github.com/RocketChat/Rocket.Chat/issues/26520"
)
def test_update_jitsi_timeout(logged_rocket):
update_jitsi_timeout = logged_rocket.update_jitsi_timeout(room_id="GENERAL").json()
assert update_jitsi_timeout.get("success")
|
<commit_before>import pytest
@pytest.mark.skip(
reason="Broken in 5.0. https://github.com/RocketChat/Rocket.Chat/issues/26520"
)
def test_update_jitsi_timeout(logged_rocket):
update_jitsi_timeout = logged_rocket.update_jitsi_timeout(room_id="GENERAL").json()
assert update_jitsi_timeout.get("success")
<commit_msg>Add todo in the test_update_jitsi_timeout so it's easier to find in the future<commit_after>import pytest
# TODO: Go back to this test once the ticket has being answered
@pytest.mark.skip(
reason="Broken in 5.0. https://github.com/RocketChat/Rocket.Chat/issues/26520"
)
def test_update_jitsi_timeout(logged_rocket):
update_jitsi_timeout = logged_rocket.update_jitsi_timeout(room_id="GENERAL").json()
assert update_jitsi_timeout.get("success")
|
bc70937c953bae8d25478a71652a57c27f0940f2
|
blanc_basic_events/events/listeners.py
|
blanc_basic_events/events/listeners.py
|
from django.db.models.signals import post_save, post_delete
from .models import RecurringEvent, RecurringEventExclusion
def update_event(sender, instance, raw=False, **kwargs):
if not raw:
instance.event.save()
post_save.connect(update_event, sender=RecurringEvent)
post_save.connect(update_event, sender=RecurringEventExclusion)
post_delete.connect(update_event, sender=RecurringEvent)
post_delete.connect(update_event, sender=RecurringEventExclusion)
|
from django.db.models.signals import post_save, post_delete
from .models import Event, RecurringEvent, RecurringEventExclusion
def update_event(sender, instance, raw=False, **kwargs):
if not raw:
try:
instance.event.save()
except Event.DoesNotExist:
pass
post_save.connect(update_event, sender=RecurringEvent)
post_save.connect(update_event, sender=RecurringEventExclusion)
post_delete.connect(update_event, sender=RecurringEvent)
post_delete.connect(update_event, sender=RecurringEventExclusion)
|
Fix for when the event gets deleted before the recurring event or recurring event exclusion
|
Fix for when the event gets deleted before the recurring event or recurring event exclusion
|
Python
|
bsd-3-clause
|
blancltd/blanc-basic-events
|
from django.db.models.signals import post_save, post_delete
from .models import RecurringEvent, RecurringEventExclusion
def update_event(sender, instance, raw=False, **kwargs):
if not raw:
instance.event.save()
post_save.connect(update_event, sender=RecurringEvent)
post_save.connect(update_event, sender=RecurringEventExclusion)
post_delete.connect(update_event, sender=RecurringEvent)
post_delete.connect(update_event, sender=RecurringEventExclusion)
Fix for when the event gets deleted before the recurring event or recurring event exclusion
|
from django.db.models.signals import post_save, post_delete
from .models import Event, RecurringEvent, RecurringEventExclusion
def update_event(sender, instance, raw=False, **kwargs):
if not raw:
try:
instance.event.save()
except Event.DoesNotExist:
pass
post_save.connect(update_event, sender=RecurringEvent)
post_save.connect(update_event, sender=RecurringEventExclusion)
post_delete.connect(update_event, sender=RecurringEvent)
post_delete.connect(update_event, sender=RecurringEventExclusion)
|
<commit_before>from django.db.models.signals import post_save, post_delete
from .models import RecurringEvent, RecurringEventExclusion
def update_event(sender, instance, raw=False, **kwargs):
if not raw:
instance.event.save()
post_save.connect(update_event, sender=RecurringEvent)
post_save.connect(update_event, sender=RecurringEventExclusion)
post_delete.connect(update_event, sender=RecurringEvent)
post_delete.connect(update_event, sender=RecurringEventExclusion)
<commit_msg>Fix for when the event gets deleted before the recurring event or recurring event exclusion<commit_after>
|
from django.db.models.signals import post_save, post_delete
from .models import Event, RecurringEvent, RecurringEventExclusion
def update_event(sender, instance, raw=False, **kwargs):
if not raw:
try:
instance.event.save()
except Event.DoesNotExist:
pass
post_save.connect(update_event, sender=RecurringEvent)
post_save.connect(update_event, sender=RecurringEventExclusion)
post_delete.connect(update_event, sender=RecurringEvent)
post_delete.connect(update_event, sender=RecurringEventExclusion)
|
from django.db.models.signals import post_save, post_delete
from .models import RecurringEvent, RecurringEventExclusion
def update_event(sender, instance, raw=False, **kwargs):
if not raw:
instance.event.save()
post_save.connect(update_event, sender=RecurringEvent)
post_save.connect(update_event, sender=RecurringEventExclusion)
post_delete.connect(update_event, sender=RecurringEvent)
post_delete.connect(update_event, sender=RecurringEventExclusion)
Fix for when the event gets deleted before the recurring event or recurring event exclusionfrom django.db.models.signals import post_save, post_delete
from .models import Event, RecurringEvent, RecurringEventExclusion
def update_event(sender, instance, raw=False, **kwargs):
if not raw:
try:
instance.event.save()
except Event.DoesNotExist:
pass
post_save.connect(update_event, sender=RecurringEvent)
post_save.connect(update_event, sender=RecurringEventExclusion)
post_delete.connect(update_event, sender=RecurringEvent)
post_delete.connect(update_event, sender=RecurringEventExclusion)
|
<commit_before>from django.db.models.signals import post_save, post_delete
from .models import RecurringEvent, RecurringEventExclusion
def update_event(sender, instance, raw=False, **kwargs):
if not raw:
instance.event.save()
post_save.connect(update_event, sender=RecurringEvent)
post_save.connect(update_event, sender=RecurringEventExclusion)
post_delete.connect(update_event, sender=RecurringEvent)
post_delete.connect(update_event, sender=RecurringEventExclusion)
<commit_msg>Fix for when the event gets deleted before the recurring event or recurring event exclusion<commit_after>from django.db.models.signals import post_save, post_delete
from .models import Event, RecurringEvent, RecurringEventExclusion
def update_event(sender, instance, raw=False, **kwargs):
if not raw:
try:
instance.event.save()
except Event.DoesNotExist:
pass
post_save.connect(update_event, sender=RecurringEvent)
post_save.connect(update_event, sender=RecurringEventExclusion)
post_delete.connect(update_event, sender=RecurringEvent)
post_delete.connect(update_event, sender=RecurringEventExclusion)
|
147d545b7118d7d8974cfe2ee95648d62fc0d1e9
|
microcms/admin.py
|
microcms/admin.py
|
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
from django.contrib.flatpages.admin import FlatPageAdmin as StockFlatPageAdmin
from django.contrib.sites.models import Site
from microcms.conf import settings
from microcms.models import Meta
class MetaAdmin(admin.ModelAdmin):
list_display = ('flatpage',)
list_filter = ('flatpage',)
ordering = ('flatpage',)
search_fields = ('flatpage',)
admin.site.register(Meta, MetaAdmin)
class MetaInline(admin.StackedInline):
model = Meta
class FlatPageAdmin(StockFlatPageAdmin):
inlines = [MetaInline]
class Media:
js = [settings.TINYMCE_URL, settings.TINYMCE_SETUP_URL]
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, FlatPageAdmin)
|
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
from django.contrib.flatpages.admin import FlatPageAdmin as StockFlatPageAdmin
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from microcms.conf import settings
from microcms.models import Meta
class MetaAdmin(admin.ModelAdmin):
list_display = ('flatpage',)
list_filter = ('flatpage',)
ordering = ('flatpage',)
search_fields = ('flatpage',)
admin.site.register(Meta, MetaAdmin)
class MetaInline(admin.StackedInline):
model = Meta
class FlatPageAdmin(StockFlatPageAdmin):
fieldsets = (
(None, {'fields': ('url', 'title', 'content')}),
(_('Advanced options'),
{'classes': ('collapse closed',),
'fields': ('enable_comments',
'registration_required',
'template_name')
}
),
)
inlines = [MetaInline]
class Media:
js = [settings.TINYMCE_URL, settings.TINYMCE_SETUP_URL]
def save_model(self, request, obj, form, change):
# Get the site with the lower id
site = Site.objects.order_by('id')[0]
obj.save()
obj.sites.add(site)
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, FlatPageAdmin)
|
Insert automatically flatpage default site
|
Insert automatically flatpage default site
|
Python
|
bsd-3-clause
|
eriol/django-microcms,eriol/django-microcms
|
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
from django.contrib.flatpages.admin import FlatPageAdmin as StockFlatPageAdmin
from django.contrib.sites.models import Site
from microcms.conf import settings
from microcms.models import Meta
class MetaAdmin(admin.ModelAdmin):
list_display = ('flatpage',)
list_filter = ('flatpage',)
ordering = ('flatpage',)
search_fields = ('flatpage',)
admin.site.register(Meta, MetaAdmin)
class MetaInline(admin.StackedInline):
model = Meta
class FlatPageAdmin(StockFlatPageAdmin):
inlines = [MetaInline]
class Media:
js = [settings.TINYMCE_URL, settings.TINYMCE_SETUP_URL]
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, FlatPageAdmin)
Insert automatically flatpage default site
|
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
from django.contrib.flatpages.admin import FlatPageAdmin as StockFlatPageAdmin
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from microcms.conf import settings
from microcms.models import Meta
class MetaAdmin(admin.ModelAdmin):
list_display = ('flatpage',)
list_filter = ('flatpage',)
ordering = ('flatpage',)
search_fields = ('flatpage',)
admin.site.register(Meta, MetaAdmin)
class MetaInline(admin.StackedInline):
model = Meta
class FlatPageAdmin(StockFlatPageAdmin):
fieldsets = (
(None, {'fields': ('url', 'title', 'content')}),
(_('Advanced options'),
{'classes': ('collapse closed',),
'fields': ('enable_comments',
'registration_required',
'template_name')
}
),
)
inlines = [MetaInline]
class Media:
js = [settings.TINYMCE_URL, settings.TINYMCE_SETUP_URL]
def save_model(self, request, obj, form, change):
# Get the site with the lower id
site = Site.objects.order_by('id')[0]
obj.save()
obj.sites.add(site)
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, FlatPageAdmin)
|
<commit_before># -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
from django.contrib.flatpages.admin import FlatPageAdmin as StockFlatPageAdmin
from django.contrib.sites.models import Site
from microcms.conf import settings
from microcms.models import Meta
class MetaAdmin(admin.ModelAdmin):
list_display = ('flatpage',)
list_filter = ('flatpage',)
ordering = ('flatpage',)
search_fields = ('flatpage',)
admin.site.register(Meta, MetaAdmin)
class MetaInline(admin.StackedInline):
model = Meta
class FlatPageAdmin(StockFlatPageAdmin):
inlines = [MetaInline]
class Media:
js = [settings.TINYMCE_URL, settings.TINYMCE_SETUP_URL]
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, FlatPageAdmin)
<commit_msg>Insert automatically flatpage default site<commit_after>
|
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
from django.contrib.flatpages.admin import FlatPageAdmin as StockFlatPageAdmin
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from microcms.conf import settings
from microcms.models import Meta
class MetaAdmin(admin.ModelAdmin):
list_display = ('flatpage',)
list_filter = ('flatpage',)
ordering = ('flatpage',)
search_fields = ('flatpage',)
admin.site.register(Meta, MetaAdmin)
class MetaInline(admin.StackedInline):
model = Meta
class FlatPageAdmin(StockFlatPageAdmin):
fieldsets = (
(None, {'fields': ('url', 'title', 'content')}),
(_('Advanced options'),
{'classes': ('collapse closed',),
'fields': ('enable_comments',
'registration_required',
'template_name')
}
),
)
inlines = [MetaInline]
class Media:
js = [settings.TINYMCE_URL, settings.TINYMCE_SETUP_URL]
def save_model(self, request, obj, form, change):
# Get the site with the lower id
site = Site.objects.order_by('id')[0]
obj.save()
obj.sites.add(site)
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, FlatPageAdmin)
|
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
from django.contrib.flatpages.admin import FlatPageAdmin as StockFlatPageAdmin
from django.contrib.sites.models import Site
from microcms.conf import settings
from microcms.models import Meta
class MetaAdmin(admin.ModelAdmin):
list_display = ('flatpage',)
list_filter = ('flatpage',)
ordering = ('flatpage',)
search_fields = ('flatpage',)
admin.site.register(Meta, MetaAdmin)
class MetaInline(admin.StackedInline):
model = Meta
class FlatPageAdmin(StockFlatPageAdmin):
inlines = [MetaInline]
class Media:
js = [settings.TINYMCE_URL, settings.TINYMCE_SETUP_URL]
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, FlatPageAdmin)
Insert automatically flatpage default site# -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
from django.contrib.flatpages.admin import FlatPageAdmin as StockFlatPageAdmin
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from microcms.conf import settings
from microcms.models import Meta
class MetaAdmin(admin.ModelAdmin):
list_display = ('flatpage',)
list_filter = ('flatpage',)
ordering = ('flatpage',)
search_fields = ('flatpage',)
admin.site.register(Meta, MetaAdmin)
class MetaInline(admin.StackedInline):
model = Meta
class FlatPageAdmin(StockFlatPageAdmin):
fieldsets = (
(None, {'fields': ('url', 'title', 'content')}),
(_('Advanced options'),
{'classes': ('collapse closed',),
'fields': ('enable_comments',
'registration_required',
'template_name')
}
),
)
inlines = [MetaInline]
class Media:
js = [settings.TINYMCE_URL, settings.TINYMCE_SETUP_URL]
def save_model(self, request, obj, form, change):
# Get the site with the lower id
site = Site.objects.order_by('id')[0]
obj.save()
obj.sites.add(site)
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, FlatPageAdmin)
|
<commit_before># -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
from django.contrib.flatpages.admin import FlatPageAdmin as StockFlatPageAdmin
from django.contrib.sites.models import Site
from microcms.conf import settings
from microcms.models import Meta
class MetaAdmin(admin.ModelAdmin):
list_display = ('flatpage',)
list_filter = ('flatpage',)
ordering = ('flatpage',)
search_fields = ('flatpage',)
admin.site.register(Meta, MetaAdmin)
class MetaInline(admin.StackedInline):
model = Meta
class FlatPageAdmin(StockFlatPageAdmin):
inlines = [MetaInline]
class Media:
js = [settings.TINYMCE_URL, settings.TINYMCE_SETUP_URL]
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, FlatPageAdmin)
<commit_msg>Insert automatically flatpage default site<commit_after># -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
from django.contrib.flatpages.admin import FlatPageAdmin as StockFlatPageAdmin
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from microcms.conf import settings
from microcms.models import Meta
class MetaAdmin(admin.ModelAdmin):
list_display = ('flatpage',)
list_filter = ('flatpage',)
ordering = ('flatpage',)
search_fields = ('flatpage',)
admin.site.register(Meta, MetaAdmin)
class MetaInline(admin.StackedInline):
model = Meta
class FlatPageAdmin(StockFlatPageAdmin):
fieldsets = (
(None, {'fields': ('url', 'title', 'content')}),
(_('Advanced options'),
{'classes': ('collapse closed',),
'fields': ('enable_comments',
'registration_required',
'template_name')
}
),
)
inlines = [MetaInline]
class Media:
js = [settings.TINYMCE_URL, settings.TINYMCE_SETUP_URL]
def save_model(self, request, obj, form, change):
# Get the site with the lower id
site = Site.objects.order_by('id')[0]
obj.save()
obj.sites.add(site)
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, FlatPageAdmin)
|
60de17292159deb590de6e5c9c2a45f1b95b0094
|
girder/app/app/__init__.py
|
girder/app/app/__init__.py
|
from .configuration import Configuration
from girder.utility import setting_utilities
from .constants import Features, Branding, Deployment
from .launch_taskflow import launch_taskflow
from .user import get_orcid, set_orcid, get_twitter, set_twitter
from girder.plugin import GirderPlugin
@setting_utilities.validator({
Features.NOTEBOOKS,
Deployment.SITE,
Branding.PRIVACY,
Branding.LICENSE,
Branding.HEADER_LOGO_ID,
Branding.FOOTER_LOGO_ID,
Branding.FOOTER_LOGO_URL,
Branding.FAVICON_ID
})
def validateSettings(event):
pass
class AppPlugin(GirderPlugin):
DISPLAY_NAME = 'OpenChemistry App'
def load(self, info):
info['apiRoot'].configuration = Configuration()
# Twitter and orcid stuff
info['apiRoot'].user.route('GET', (':id', 'orcid'), get_orcid)
info['apiRoot'].user.route('POST', (':id', 'orcid'), set_orcid)
info['apiRoot'].user.route('GET', (':id', 'twitter'), get_twitter)
info['apiRoot'].user.route('POST', (':id', 'twitter'), set_twitter)
# Launch a taskflow with a single endpoint
info['apiRoot'].queues.route('POST', ('launchtaskflow',), launch_taskflow)
|
from .configuration import Configuration
from girder.api.rest import Resource
from girder.utility import setting_utilities
from .constants import Features, Branding, Deployment
from .launch_taskflow import launch_taskflow
from .user import get_orcid, set_orcid, get_twitter, set_twitter
from girder.plugin import GirderPlugin
@setting_utilities.validator({
Features.NOTEBOOKS,
Deployment.SITE,
Branding.PRIVACY,
Branding.LICENSE,
Branding.HEADER_LOGO_ID,
Branding.FOOTER_LOGO_ID,
Branding.FOOTER_LOGO_URL,
Branding.FAVICON_ID
})
def validateSettings(event):
pass
class AppPlugin(GirderPlugin):
DISPLAY_NAME = 'OpenChemistry App'
def load(self, info):
info['apiRoot'].configuration = Configuration()
# Twitter and orcid stuff
info['apiRoot'].user.route('GET', (':id', 'orcid'), get_orcid)
info['apiRoot'].user.route('POST', (':id', 'orcid'), set_orcid)
info['apiRoot'].user.route('GET', (':id', 'twitter'), get_twitter)
info['apiRoot'].user.route('POST', (':id', 'twitter'), set_twitter)
# Launch a taskflow with a single endpoint
info['apiRoot'].launch_taskflow = Resource()
info['apiRoot'].launch_taskflow.route('POST', ('launch',), launch_taskflow)
|
Put the endpoint at /launch_taskflow/launch
|
Put the endpoint at /launch_taskflow/launch
Put it here instead of under "queues"
Signed-off-by: Patrick Avery <743342299f279e7a8c3ff5eb40671fce3e95f13a@kitware.com>
|
Python
|
bsd-3-clause
|
OpenChemistry/mongochemserver
|
from .configuration import Configuration
from girder.utility import setting_utilities
from .constants import Features, Branding, Deployment
from .launch_taskflow import launch_taskflow
from .user import get_orcid, set_orcid, get_twitter, set_twitter
from girder.plugin import GirderPlugin
@setting_utilities.validator({
Features.NOTEBOOKS,
Deployment.SITE,
Branding.PRIVACY,
Branding.LICENSE,
Branding.HEADER_LOGO_ID,
Branding.FOOTER_LOGO_ID,
Branding.FOOTER_LOGO_URL,
Branding.FAVICON_ID
})
def validateSettings(event):
pass
class AppPlugin(GirderPlugin):
DISPLAY_NAME = 'OpenChemistry App'
def load(self, info):
info['apiRoot'].configuration = Configuration()
# Twitter and orcid stuff
info['apiRoot'].user.route('GET', (':id', 'orcid'), get_orcid)
info['apiRoot'].user.route('POST', (':id', 'orcid'), set_orcid)
info['apiRoot'].user.route('GET', (':id', 'twitter'), get_twitter)
info['apiRoot'].user.route('POST', (':id', 'twitter'), set_twitter)
# Launch a taskflow with a single endpoint
info['apiRoot'].queues.route('POST', ('launchtaskflow',), launch_taskflow)
Put the endpoint at /launch_taskflow/launch
Put it here instead of under "queues"
Signed-off-by: Patrick Avery <743342299f279e7a8c3ff5eb40671fce3e95f13a@kitware.com>
|
from .configuration import Configuration
from girder.api.rest import Resource
from girder.utility import setting_utilities
from .constants import Features, Branding, Deployment
from .launch_taskflow import launch_taskflow
from .user import get_orcid, set_orcid, get_twitter, set_twitter
from girder.plugin import GirderPlugin
@setting_utilities.validator({
Features.NOTEBOOKS,
Deployment.SITE,
Branding.PRIVACY,
Branding.LICENSE,
Branding.HEADER_LOGO_ID,
Branding.FOOTER_LOGO_ID,
Branding.FOOTER_LOGO_URL,
Branding.FAVICON_ID
})
def validateSettings(event):
pass
class AppPlugin(GirderPlugin):
DISPLAY_NAME = 'OpenChemistry App'
def load(self, info):
info['apiRoot'].configuration = Configuration()
# Twitter and orcid stuff
info['apiRoot'].user.route('GET', (':id', 'orcid'), get_orcid)
info['apiRoot'].user.route('POST', (':id', 'orcid'), set_orcid)
info['apiRoot'].user.route('GET', (':id', 'twitter'), get_twitter)
info['apiRoot'].user.route('POST', (':id', 'twitter'), set_twitter)
# Launch a taskflow with a single endpoint
info['apiRoot'].launch_taskflow = Resource()
info['apiRoot'].launch_taskflow.route('POST', ('launch',), launch_taskflow)
|
<commit_before>from .configuration import Configuration
from girder.utility import setting_utilities
from .constants import Features, Branding, Deployment
from .launch_taskflow import launch_taskflow
from .user import get_orcid, set_orcid, get_twitter, set_twitter
from girder.plugin import GirderPlugin
@setting_utilities.validator({
Features.NOTEBOOKS,
Deployment.SITE,
Branding.PRIVACY,
Branding.LICENSE,
Branding.HEADER_LOGO_ID,
Branding.FOOTER_LOGO_ID,
Branding.FOOTER_LOGO_URL,
Branding.FAVICON_ID
})
def validateSettings(event):
pass
class AppPlugin(GirderPlugin):
DISPLAY_NAME = 'OpenChemistry App'
def load(self, info):
info['apiRoot'].configuration = Configuration()
# Twitter and orcid stuff
info['apiRoot'].user.route('GET', (':id', 'orcid'), get_orcid)
info['apiRoot'].user.route('POST', (':id', 'orcid'), set_orcid)
info['apiRoot'].user.route('GET', (':id', 'twitter'), get_twitter)
info['apiRoot'].user.route('POST', (':id', 'twitter'), set_twitter)
# Launch a taskflow with a single endpoint
info['apiRoot'].queues.route('POST', ('launchtaskflow',), launch_taskflow)
<commit_msg>Put the endpoint at /launch_taskflow/launch
Put it here instead of under "queues"
Signed-off-by: Patrick Avery <743342299f279e7a8c3ff5eb40671fce3e95f13a@kitware.com><commit_after>
|
from .configuration import Configuration
from girder.api.rest import Resource
from girder.utility import setting_utilities
from .constants import Features, Branding, Deployment
from .launch_taskflow import launch_taskflow
from .user import get_orcid, set_orcid, get_twitter, set_twitter
from girder.plugin import GirderPlugin
@setting_utilities.validator({
Features.NOTEBOOKS,
Deployment.SITE,
Branding.PRIVACY,
Branding.LICENSE,
Branding.HEADER_LOGO_ID,
Branding.FOOTER_LOGO_ID,
Branding.FOOTER_LOGO_URL,
Branding.FAVICON_ID
})
def validateSettings(event):
pass
class AppPlugin(GirderPlugin):
DISPLAY_NAME = 'OpenChemistry App'
def load(self, info):
info['apiRoot'].configuration = Configuration()
# Twitter and orcid stuff
info['apiRoot'].user.route('GET', (':id', 'orcid'), get_orcid)
info['apiRoot'].user.route('POST', (':id', 'orcid'), set_orcid)
info['apiRoot'].user.route('GET', (':id', 'twitter'), get_twitter)
info['apiRoot'].user.route('POST', (':id', 'twitter'), set_twitter)
# Launch a taskflow with a single endpoint
info['apiRoot'].launch_taskflow = Resource()
info['apiRoot'].launch_taskflow.route('POST', ('launch',), launch_taskflow)
|
from .configuration import Configuration
from girder.utility import setting_utilities
from .constants import Features, Branding, Deployment
from .launch_taskflow import launch_taskflow
from .user import get_orcid, set_orcid, get_twitter, set_twitter
from girder.plugin import GirderPlugin
@setting_utilities.validator({
Features.NOTEBOOKS,
Deployment.SITE,
Branding.PRIVACY,
Branding.LICENSE,
Branding.HEADER_LOGO_ID,
Branding.FOOTER_LOGO_ID,
Branding.FOOTER_LOGO_URL,
Branding.FAVICON_ID
})
def validateSettings(event):
pass
class AppPlugin(GirderPlugin):
DISPLAY_NAME = 'OpenChemistry App'
def load(self, info):
info['apiRoot'].configuration = Configuration()
# Twitter and orcid stuff
info['apiRoot'].user.route('GET', (':id', 'orcid'), get_orcid)
info['apiRoot'].user.route('POST', (':id', 'orcid'), set_orcid)
info['apiRoot'].user.route('GET', (':id', 'twitter'), get_twitter)
info['apiRoot'].user.route('POST', (':id', 'twitter'), set_twitter)
# Launch a taskflow with a single endpoint
info['apiRoot'].queues.route('POST', ('launchtaskflow',), launch_taskflow)
Put the endpoint at /launch_taskflow/launch
Put it here instead of under "queues"
Signed-off-by: Patrick Avery <743342299f279e7a8c3ff5eb40671fce3e95f13a@kitware.com>from .configuration import Configuration
from girder.api.rest import Resource
from girder.utility import setting_utilities
from .constants import Features, Branding, Deployment
from .launch_taskflow import launch_taskflow
from .user import get_orcid, set_orcid, get_twitter, set_twitter
from girder.plugin import GirderPlugin
@setting_utilities.validator({
Features.NOTEBOOKS,
Deployment.SITE,
Branding.PRIVACY,
Branding.LICENSE,
Branding.HEADER_LOGO_ID,
Branding.FOOTER_LOGO_ID,
Branding.FOOTER_LOGO_URL,
Branding.FAVICON_ID
})
def validateSettings(event):
pass
class AppPlugin(GirderPlugin):
DISPLAY_NAME = 'OpenChemistry App'
def load(self, info):
info['apiRoot'].configuration = Configuration()
# Twitter and orcid stuff
info['apiRoot'].user.route('GET', (':id', 'orcid'), get_orcid)
info['apiRoot'].user.route('POST', (':id', 'orcid'), set_orcid)
info['apiRoot'].user.route('GET', (':id', 'twitter'), get_twitter)
info['apiRoot'].user.route('POST', (':id', 'twitter'), set_twitter)
# Launch a taskflow with a single endpoint
info['apiRoot'].launch_taskflow = Resource()
info['apiRoot'].launch_taskflow.route('POST', ('launch',), launch_taskflow)
|
<commit_before>from .configuration import Configuration
from girder.utility import setting_utilities
from .constants import Features, Branding, Deployment
from .launch_taskflow import launch_taskflow
from .user import get_orcid, set_orcid, get_twitter, set_twitter
from girder.plugin import GirderPlugin
@setting_utilities.validator({
Features.NOTEBOOKS,
Deployment.SITE,
Branding.PRIVACY,
Branding.LICENSE,
Branding.HEADER_LOGO_ID,
Branding.FOOTER_LOGO_ID,
Branding.FOOTER_LOGO_URL,
Branding.FAVICON_ID
})
def validateSettings(event):
pass
class AppPlugin(GirderPlugin):
DISPLAY_NAME = 'OpenChemistry App'
def load(self, info):
info['apiRoot'].configuration = Configuration()
# Twitter and orcid stuff
info['apiRoot'].user.route('GET', (':id', 'orcid'), get_orcid)
info['apiRoot'].user.route('POST', (':id', 'orcid'), set_orcid)
info['apiRoot'].user.route('GET', (':id', 'twitter'), get_twitter)
info['apiRoot'].user.route('POST', (':id', 'twitter'), set_twitter)
# Launch a taskflow with a single endpoint
info['apiRoot'].queues.route('POST', ('launchtaskflow',), launch_taskflow)
<commit_msg>Put the endpoint at /launch_taskflow/launch
Put it here instead of under "queues"
Signed-off-by: Patrick Avery <743342299f279e7a8c3ff5eb40671fce3e95f13a@kitware.com><commit_after>from .configuration import Configuration
from girder.api.rest import Resource
from girder.utility import setting_utilities
from .constants import Features, Branding, Deployment
from .launch_taskflow import launch_taskflow
from .user import get_orcid, set_orcid, get_twitter, set_twitter
from girder.plugin import GirderPlugin
@setting_utilities.validator({
Features.NOTEBOOKS,
Deployment.SITE,
Branding.PRIVACY,
Branding.LICENSE,
Branding.HEADER_LOGO_ID,
Branding.FOOTER_LOGO_ID,
Branding.FOOTER_LOGO_URL,
Branding.FAVICON_ID
})
def validateSettings(event):
pass
class AppPlugin(GirderPlugin):
DISPLAY_NAME = 'OpenChemistry App'
def load(self, info):
info['apiRoot'].configuration = Configuration()
# Twitter and orcid stuff
info['apiRoot'].user.route('GET', (':id', 'orcid'), get_orcid)
info['apiRoot'].user.route('POST', (':id', 'orcid'), set_orcid)
info['apiRoot'].user.route('GET', (':id', 'twitter'), get_twitter)
info['apiRoot'].user.route('POST', (':id', 'twitter'), set_twitter)
# Launch a taskflow with a single endpoint
info['apiRoot'].launch_taskflow = Resource()
info['apiRoot'].launch_taskflow.route('POST', ('launch',), launch_taskflow)
|
61d20995b7bc291796299055751099204180bf28
|
UM/Operations/AddSceneNodeOperation.py
|
UM/Operations/AddSceneNodeOperation.py
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.SceneNode import SceneNode
class AddSceneNodeOperation(Operation.Operation):
def __init__(self, node, parent):
super().__init__()
self._node = node
self._parent = parent
def undo(self):
self._node.setParent(None)
def redo(self):
self._node.setParent(self._parent)
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.Selection import Selection
from UM.Scene.SceneNode import SceneNode
class AddSceneNodeOperation(Operation.Operation):
def __init__(self, node, parent):
super().__init__()
self._node = node
self._parent = parent
self._selected = False
def undo(self):
self._node.setParent(None)
self._selected = Selection.isSelected(self._node)
if self._selected:
Selection.remove(self._node)
def redo(self):
self._node.setParent(self._parent)
if self._selected:
Selection.add(self._node)
|
Undo & redo of add SceneNode now correctly set the previous selection state.
|
Undo & redo of add SceneNode now correctly set the previous selection state.
CURA-640
|
Python
|
agpl-3.0
|
onitake/Uranium,onitake/Uranium
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.SceneNode import SceneNode
class AddSceneNodeOperation(Operation.Operation):
def __init__(self, node, parent):
super().__init__()
self._node = node
self._parent = parent
def undo(self):
self._node.setParent(None)
def redo(self):
self._node.setParent(self._parent)
Undo & redo of add SceneNode now correctly set the previous selection state.
CURA-640
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.Selection import Selection
from UM.Scene.SceneNode import SceneNode
class AddSceneNodeOperation(Operation.Operation):
def __init__(self, node, parent):
super().__init__()
self._node = node
self._parent = parent
self._selected = False
def undo(self):
self._node.setParent(None)
self._selected = Selection.isSelected(self._node)
if self._selected:
Selection.remove(self._node)
def redo(self):
self._node.setParent(self._parent)
if self._selected:
Selection.add(self._node)
|
<commit_before># Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.SceneNode import SceneNode
class AddSceneNodeOperation(Operation.Operation):
def __init__(self, node, parent):
super().__init__()
self._node = node
self._parent = parent
def undo(self):
self._node.setParent(None)
def redo(self):
self._node.setParent(self._parent)
<commit_msg>Undo & redo of add SceneNode now correctly set the previous selection state.
CURA-640<commit_after>
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.Selection import Selection
from UM.Scene.SceneNode import SceneNode
class AddSceneNodeOperation(Operation.Operation):
def __init__(self, node, parent):
super().__init__()
self._node = node
self._parent = parent
self._selected = False
def undo(self):
self._node.setParent(None)
self._selected = Selection.isSelected(self._node)
if self._selected:
Selection.remove(self._node)
def redo(self):
self._node.setParent(self._parent)
if self._selected:
Selection.add(self._node)
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.SceneNode import SceneNode
class AddSceneNodeOperation(Operation.Operation):
def __init__(self, node, parent):
super().__init__()
self._node = node
self._parent = parent
def undo(self):
self._node.setParent(None)
def redo(self):
self._node.setParent(self._parent)
Undo & redo of add SceneNode now correctly set the previous selection state.
CURA-640# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.Selection import Selection
from UM.Scene.SceneNode import SceneNode
class AddSceneNodeOperation(Operation.Operation):
def __init__(self, node, parent):
super().__init__()
self._node = node
self._parent = parent
self._selected = False
def undo(self):
self._node.setParent(None)
self._selected = Selection.isSelected(self._node)
if self._selected:
Selection.remove(self._node)
def redo(self):
self._node.setParent(self._parent)
if self._selected:
Selection.add(self._node)
|
<commit_before># Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.SceneNode import SceneNode
class AddSceneNodeOperation(Operation.Operation):
def __init__(self, node, parent):
super().__init__()
self._node = node
self._parent = parent
def undo(self):
self._node.setParent(None)
def redo(self):
self._node.setParent(self._parent)
<commit_msg>Undo & redo of add SceneNode now correctly set the previous selection state.
CURA-640<commit_after># Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.Selection import Selection
from UM.Scene.SceneNode import SceneNode
class AddSceneNodeOperation(Operation.Operation):
def __init__(self, node, parent):
super().__init__()
self._node = node
self._parent = parent
self._selected = False
def undo(self):
self._node.setParent(None)
self._selected = Selection.isSelected(self._node)
if self._selected:
Selection.remove(self._node)
def redo(self):
self._node.setParent(self._parent)
if self._selected:
Selection.add(self._node)
|
59789bae7df5de6d7568a1b372b95a891fd5c3a2
|
confluent_server/confluent/userutil.py
|
confluent_server/confluent/userutil.py
|
from ctypes import *
from ctypes.util import find_library
import grp
import pwd
import os
libc = cdll.LoadLibrary(find_library('libc'))
_getgrouplist = libc.getgrouplist
_getgrouplist.restype = c_int32
class TooSmallException(Exception):
def __init__(self, count):
self.count = count
super(TooSmallException, self).__init__()
def getgrouplist(name, gid, ng=32):
_getgrouplist.argtypes = [c_char_p, c_uint, POINTER(c_uint * ng), POINTER(c_int)]
glist = (c_uint * ng)()
nglist = c_int(ng)
count = _getgrouplist(name, gid, byref(glist), byref(nglist))
if count < 0:
raise TooSmallException(nglist.value)
for gidx in range(count):
gent = glist[gidx]
yield grp.getgrgid(gent).gr_name
def grouplist(username):
pent = pwd.getpwnam(username)
try:
groups = getgrouplist(pent.pw_name, pent.pw_gid)
except TooSmallException as e:
groups = getgrouplist(pent.pw_name, pent.pw_gid, e.count)
return list(groups)
if __name__ == '__main__':
import sys
print(repr(grouplist(sys.argv[1])))
|
from ctypes import *
from ctypes.util import find_library
import grp
import pwd
import os
libc = cdll.LoadLibrary(find_library('libc'))
_getgrouplist = libc.getgrouplist
_getgrouplist.restype = c_int32
class TooSmallException(Exception):
def __init__(self, count):
self.count = count
super(TooSmallException, self).__init__()
def getgrouplist(name, gid, ng=32):
_getgrouplist.argtypes = [c_char_p, c_uint, POINTER(c_uint * ng), POINTER(c_int)]
glist = (c_uint * ng)()
nglist = c_int(ng)
if not isinstance(name, bytes):
name = name.encode('utf-8')
count = _getgrouplist(name, gid, byref(glist), byref(nglist))
if count < 0:
raise TooSmallException(nglist.value)
for gidx in range(count):
gent = glist[gidx]
yield grp.getgrgid(gent).gr_name
def grouplist(username):
pent = pwd.getpwnam(username)
try:
groups = getgrouplist(pent.pw_name, pent.pw_gid)
except TooSmallException as e:
groups = getgrouplist(pent.pw_name, pent.pw_gid, e.count)
return list(groups)
if __name__ == '__main__':
import sys
print(repr(grouplist(sys.argv[1])))
|
Fix python3 ctypes str usage
|
Fix python3 ctypes str usage
In python3, the string is likely to be unicode and incompatible
with the libc function. If it isn't bytes, force it to be bytes.
|
Python
|
apache-2.0
|
xcat2/confluent,xcat2/confluent,jjohnson42/confluent,xcat2/confluent,jjohnson42/confluent,jjohnson42/confluent,xcat2/confluent,xcat2/confluent,jjohnson42/confluent,jjohnson42/confluent
|
from ctypes import *
from ctypes.util import find_library
import grp
import pwd
import os
libc = cdll.LoadLibrary(find_library('libc'))
_getgrouplist = libc.getgrouplist
_getgrouplist.restype = c_int32
class TooSmallException(Exception):
def __init__(self, count):
self.count = count
super(TooSmallException, self).__init__()
def getgrouplist(name, gid, ng=32):
_getgrouplist.argtypes = [c_char_p, c_uint, POINTER(c_uint * ng), POINTER(c_int)]
glist = (c_uint * ng)()
nglist = c_int(ng)
count = _getgrouplist(name, gid, byref(glist), byref(nglist))
if count < 0:
raise TooSmallException(nglist.value)
for gidx in range(count):
gent = glist[gidx]
yield grp.getgrgid(gent).gr_name
def grouplist(username):
pent = pwd.getpwnam(username)
try:
groups = getgrouplist(pent.pw_name, pent.pw_gid)
except TooSmallException as e:
groups = getgrouplist(pent.pw_name, pent.pw_gid, e.count)
return list(groups)
if __name__ == '__main__':
import sys
print(repr(grouplist(sys.argv[1])))
Fix python3 ctypes str usage
In python3, the string is likely to be unicode and incompatible
with the libc function. If it isn't bytes, force it to be bytes.
|
from ctypes import *
from ctypes.util import find_library
import grp
import pwd
import os
libc = cdll.LoadLibrary(find_library('libc'))
_getgrouplist = libc.getgrouplist
_getgrouplist.restype = c_int32
class TooSmallException(Exception):
def __init__(self, count):
self.count = count
super(TooSmallException, self).__init__()
def getgrouplist(name, gid, ng=32):
_getgrouplist.argtypes = [c_char_p, c_uint, POINTER(c_uint * ng), POINTER(c_int)]
glist = (c_uint * ng)()
nglist = c_int(ng)
if not isinstance(name, bytes):
name = name.encode('utf-8')
count = _getgrouplist(name, gid, byref(glist), byref(nglist))
if count < 0:
raise TooSmallException(nglist.value)
for gidx in range(count):
gent = glist[gidx]
yield grp.getgrgid(gent).gr_name
def grouplist(username):
pent = pwd.getpwnam(username)
try:
groups = getgrouplist(pent.pw_name, pent.pw_gid)
except TooSmallException as e:
groups = getgrouplist(pent.pw_name, pent.pw_gid, e.count)
return list(groups)
if __name__ == '__main__':
import sys
print(repr(grouplist(sys.argv[1])))
|
<commit_before>from ctypes import *
from ctypes.util import find_library
import grp
import pwd
import os
libc = cdll.LoadLibrary(find_library('libc'))
_getgrouplist = libc.getgrouplist
_getgrouplist.restype = c_int32
class TooSmallException(Exception):
def __init__(self, count):
self.count = count
super(TooSmallException, self).__init__()
def getgrouplist(name, gid, ng=32):
_getgrouplist.argtypes = [c_char_p, c_uint, POINTER(c_uint * ng), POINTER(c_int)]
glist = (c_uint * ng)()
nglist = c_int(ng)
count = _getgrouplist(name, gid, byref(glist), byref(nglist))
if count < 0:
raise TooSmallException(nglist.value)
for gidx in range(count):
gent = glist[gidx]
yield grp.getgrgid(gent).gr_name
def grouplist(username):
pent = pwd.getpwnam(username)
try:
groups = getgrouplist(pent.pw_name, pent.pw_gid)
except TooSmallException as e:
groups = getgrouplist(pent.pw_name, pent.pw_gid, e.count)
return list(groups)
if __name__ == '__main__':
import sys
print(repr(grouplist(sys.argv[1])))
<commit_msg>Fix python3 ctypes str usage
In python3, the string is likely to be unicode and incompatible
with the libc function. If it isn't bytes, force it to be bytes.<commit_after>
|
from ctypes import *
from ctypes.util import find_library
import grp
import pwd
import os
libc = cdll.LoadLibrary(find_library('libc'))
_getgrouplist = libc.getgrouplist
_getgrouplist.restype = c_int32
class TooSmallException(Exception):
def __init__(self, count):
self.count = count
super(TooSmallException, self).__init__()
def getgrouplist(name, gid, ng=32):
_getgrouplist.argtypes = [c_char_p, c_uint, POINTER(c_uint * ng), POINTER(c_int)]
glist = (c_uint * ng)()
nglist = c_int(ng)
if not isinstance(name, bytes):
name = name.encode('utf-8')
count = _getgrouplist(name, gid, byref(glist), byref(nglist))
if count < 0:
raise TooSmallException(nglist.value)
for gidx in range(count):
gent = glist[gidx]
yield grp.getgrgid(gent).gr_name
def grouplist(username):
pent = pwd.getpwnam(username)
try:
groups = getgrouplist(pent.pw_name, pent.pw_gid)
except TooSmallException as e:
groups = getgrouplist(pent.pw_name, pent.pw_gid, e.count)
return list(groups)
if __name__ == '__main__':
import sys
print(repr(grouplist(sys.argv[1])))
|
from ctypes import *
from ctypes.util import find_library
import grp
import pwd
import os
libc = cdll.LoadLibrary(find_library('libc'))
_getgrouplist = libc.getgrouplist
_getgrouplist.restype = c_int32
class TooSmallException(Exception):
def __init__(self, count):
self.count = count
super(TooSmallException, self).__init__()
def getgrouplist(name, gid, ng=32):
_getgrouplist.argtypes = [c_char_p, c_uint, POINTER(c_uint * ng), POINTER(c_int)]
glist = (c_uint * ng)()
nglist = c_int(ng)
count = _getgrouplist(name, gid, byref(glist), byref(nglist))
if count < 0:
raise TooSmallException(nglist.value)
for gidx in range(count):
gent = glist[gidx]
yield grp.getgrgid(gent).gr_name
def grouplist(username):
pent = pwd.getpwnam(username)
try:
groups = getgrouplist(pent.pw_name, pent.pw_gid)
except TooSmallException as e:
groups = getgrouplist(pent.pw_name, pent.pw_gid, e.count)
return list(groups)
if __name__ == '__main__':
import sys
print(repr(grouplist(sys.argv[1])))
Fix python3 ctypes str usage
In python3, the string is likely to be unicode and incompatible
with the libc function. If it isn't bytes, force it to be bytes.from ctypes import *
from ctypes.util import find_library
import grp
import pwd
import os
libc = cdll.LoadLibrary(find_library('libc'))
_getgrouplist = libc.getgrouplist
_getgrouplist.restype = c_int32
class TooSmallException(Exception):
def __init__(self, count):
self.count = count
super(TooSmallException, self).__init__()
def getgrouplist(name, gid, ng=32):
_getgrouplist.argtypes = [c_char_p, c_uint, POINTER(c_uint * ng), POINTER(c_int)]
glist = (c_uint * ng)()
nglist = c_int(ng)
if not isinstance(name, bytes):
name = name.encode('utf-8')
count = _getgrouplist(name, gid, byref(glist), byref(nglist))
if count < 0:
raise TooSmallException(nglist.value)
for gidx in range(count):
gent = glist[gidx]
yield grp.getgrgid(gent).gr_name
def grouplist(username):
pent = pwd.getpwnam(username)
try:
groups = getgrouplist(pent.pw_name, pent.pw_gid)
except TooSmallException as e:
groups = getgrouplist(pent.pw_name, pent.pw_gid, e.count)
return list(groups)
if __name__ == '__main__':
import sys
print(repr(grouplist(sys.argv[1])))
|
<commit_before>from ctypes import *
from ctypes.util import find_library
import grp
import pwd
import os
libc = cdll.LoadLibrary(find_library('libc'))
_getgrouplist = libc.getgrouplist
_getgrouplist.restype = c_int32
class TooSmallException(Exception):
def __init__(self, count):
self.count = count
super(TooSmallException, self).__init__()
def getgrouplist(name, gid, ng=32):
_getgrouplist.argtypes = [c_char_p, c_uint, POINTER(c_uint * ng), POINTER(c_int)]
glist = (c_uint * ng)()
nglist = c_int(ng)
count = _getgrouplist(name, gid, byref(glist), byref(nglist))
if count < 0:
raise TooSmallException(nglist.value)
for gidx in range(count):
gent = glist[gidx]
yield grp.getgrgid(gent).gr_name
def grouplist(username):
pent = pwd.getpwnam(username)
try:
groups = getgrouplist(pent.pw_name, pent.pw_gid)
except TooSmallException as e:
groups = getgrouplist(pent.pw_name, pent.pw_gid, e.count)
return list(groups)
if __name__ == '__main__':
import sys
print(repr(grouplist(sys.argv[1])))
<commit_msg>Fix python3 ctypes str usage
In python3, the string is likely to be unicode and incompatible
with the libc function. If it isn't bytes, force it to be bytes.<commit_after>from ctypes import *
from ctypes.util import find_library
import grp
import pwd
import os
libc = cdll.LoadLibrary(find_library('libc'))
_getgrouplist = libc.getgrouplist
_getgrouplist.restype = c_int32
class TooSmallException(Exception):
def __init__(self, count):
self.count = count
super(TooSmallException, self).__init__()
def getgrouplist(name, gid, ng=32):
_getgrouplist.argtypes = [c_char_p, c_uint, POINTER(c_uint * ng), POINTER(c_int)]
glist = (c_uint * ng)()
nglist = c_int(ng)
if not isinstance(name, bytes):
name = name.encode('utf-8')
count = _getgrouplist(name, gid, byref(glist), byref(nglist))
if count < 0:
raise TooSmallException(nglist.value)
for gidx in range(count):
gent = glist[gidx]
yield grp.getgrgid(gent).gr_name
def grouplist(username):
pent = pwd.getpwnam(username)
try:
groups = getgrouplist(pent.pw_name, pent.pw_gid)
except TooSmallException as e:
groups = getgrouplist(pent.pw_name, pent.pw_gid, e.count)
return list(groups)
if __name__ == '__main__':
import sys
print(repr(grouplist(sys.argv[1])))
|
d12be22b5427a1433dd2ff7b1d2f97951d2b9c0f
|
pycon/migrations/0002_remove_old_google_openid_auths.py
|
pycon/migrations/0002_remove_old_google_openid_auths.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Google OpenID auth has been turned off, so any associations that
users had to their Google accounts via Google OpenID are now useless.
Just remove them.
"""
from django.db import migrations
def no_op(apps, schema_editor):
pass
def remove_old_google_openid_auths(apps, schema_editor):
UserSocialAuth = apps.get_model('social_auth', 'UserSocialAuth')
db_alias = schema_editor.connection.alias
UserSocialAuth.objects.using(db_alias).filter(provider='google').delete()
class Migration(migrations.Migration):
dependencies = [
('pycon', '0001_initial'),
('social_auth', '0001_initial'),
]
operations = [
migrations.RunPython(remove_old_google_openid_auths, no_op),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Google OpenID auth has been turned off, so any associations that
users had to their Google accounts via Google OpenID are now useless.
Just remove them.
"""
from django.db import migrations
def no_op(apps, schema_editor):
pass
def remove_old_google_openid_auths(apps, schema_editor):
UserSocialAuth = apps.get_model('social_auth', 'UserSocialAuth')
db_alias = schema_editor.connection.alias
UserSocialAuth.objects.using(db_alias).filter(provider='google').delete()
class Migration(migrations.Migration):
dependencies = [
('pycon', '0001_initial'),
]
operations = [
migrations.RunPython(remove_old_google_openid_auths, no_op),
]
|
Undo premature fix for dependency
|
Undo premature fix for dependency
|
Python
|
bsd-3-clause
|
Diwahars/pycon,PyCon/pycon,njl/pycon,njl/pycon,njl/pycon,PyCon/pycon,Diwahars/pycon,Diwahars/pycon,PyCon/pycon,PyCon/pycon,Diwahars/pycon,njl/pycon
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Google OpenID auth has been turned off, so any associations that
users had to their Google accounts via Google OpenID are now useless.
Just remove them.
"""
from django.db import migrations
def no_op(apps, schema_editor):
pass
def remove_old_google_openid_auths(apps, schema_editor):
UserSocialAuth = apps.get_model('social_auth', 'UserSocialAuth')
db_alias = schema_editor.connection.alias
UserSocialAuth.objects.using(db_alias).filter(provider='google').delete()
class Migration(migrations.Migration):
dependencies = [
('pycon', '0001_initial'),
('social_auth', '0001_initial'),
]
operations = [
migrations.RunPython(remove_old_google_openid_auths, no_op),
]
Undo premature fix for dependency
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Google OpenID auth has been turned off, so any associations that
users had to their Google accounts via Google OpenID are now useless.
Just remove them.
"""
from django.db import migrations
def no_op(apps, schema_editor):
pass
def remove_old_google_openid_auths(apps, schema_editor):
UserSocialAuth = apps.get_model('social_auth', 'UserSocialAuth')
db_alias = schema_editor.connection.alias
UserSocialAuth.objects.using(db_alias).filter(provider='google').delete()
class Migration(migrations.Migration):
dependencies = [
('pycon', '0001_initial'),
]
operations = [
migrations.RunPython(remove_old_google_openid_auths, no_op),
]
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Google OpenID auth has been turned off, so any associations that
users had to their Google accounts via Google OpenID are now useless.
Just remove them.
"""
from django.db import migrations
def no_op(apps, schema_editor):
pass
def remove_old_google_openid_auths(apps, schema_editor):
UserSocialAuth = apps.get_model('social_auth', 'UserSocialAuth')
db_alias = schema_editor.connection.alias
UserSocialAuth.objects.using(db_alias).filter(provider='google').delete()
class Migration(migrations.Migration):
dependencies = [
('pycon', '0001_initial'),
('social_auth', '0001_initial'),
]
operations = [
migrations.RunPython(remove_old_google_openid_auths, no_op),
]
<commit_msg>Undo premature fix for dependency<commit_after>
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Google OpenID auth has been turned off, so any associations that
users had to their Google accounts via Google OpenID are now useless.
Just remove them.
"""
from django.db import migrations
def no_op(apps, schema_editor):
pass
def remove_old_google_openid_auths(apps, schema_editor):
UserSocialAuth = apps.get_model('social_auth', 'UserSocialAuth')
db_alias = schema_editor.connection.alias
UserSocialAuth.objects.using(db_alias).filter(provider='google').delete()
class Migration(migrations.Migration):
dependencies = [
('pycon', '0001_initial'),
]
operations = [
migrations.RunPython(remove_old_google_openid_auths, no_op),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Google OpenID auth has been turned off, so any associations that
users had to their Google accounts via Google OpenID are now useless.
Just remove them.
"""
from django.db import migrations
def no_op(apps, schema_editor):
pass
def remove_old_google_openid_auths(apps, schema_editor):
UserSocialAuth = apps.get_model('social_auth', 'UserSocialAuth')
db_alias = schema_editor.connection.alias
UserSocialAuth.objects.using(db_alias).filter(provider='google').delete()
class Migration(migrations.Migration):
dependencies = [
('pycon', '0001_initial'),
('social_auth', '0001_initial'),
]
operations = [
migrations.RunPython(remove_old_google_openid_auths, no_op),
]
Undo premature fix for dependency# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Google OpenID auth has been turned off, so any associations that
users had to their Google accounts via Google OpenID are now useless.
Just remove them.
"""
from django.db import migrations
def no_op(apps, schema_editor):
pass
def remove_old_google_openid_auths(apps, schema_editor):
UserSocialAuth = apps.get_model('social_auth', 'UserSocialAuth')
db_alias = schema_editor.connection.alias
UserSocialAuth.objects.using(db_alias).filter(provider='google').delete()
class Migration(migrations.Migration):
dependencies = [
('pycon', '0001_initial'),
]
operations = [
migrations.RunPython(remove_old_google_openid_auths, no_op),
]
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Google OpenID auth has been turned off, so any associations that
users had to their Google accounts via Google OpenID are now useless.
Just remove them.
"""
from django.db import migrations
def no_op(apps, schema_editor):
pass
def remove_old_google_openid_auths(apps, schema_editor):
UserSocialAuth = apps.get_model('social_auth', 'UserSocialAuth')
db_alias = schema_editor.connection.alias
UserSocialAuth.objects.using(db_alias).filter(provider='google').delete()
class Migration(migrations.Migration):
dependencies = [
('pycon', '0001_initial'),
('social_auth', '0001_initial'),
]
operations = [
migrations.RunPython(remove_old_google_openid_auths, no_op),
]
<commit_msg>Undo premature fix for dependency<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Google OpenID auth has been turned off, so any associations that
users had to their Google accounts via Google OpenID are now useless.
Just remove them.
"""
from django.db import migrations
def no_op(apps, schema_editor):
pass
def remove_old_google_openid_auths(apps, schema_editor):
UserSocialAuth = apps.get_model('social_auth', 'UserSocialAuth')
db_alias = schema_editor.connection.alias
UserSocialAuth.objects.using(db_alias).filter(provider='google').delete()
class Migration(migrations.Migration):
dependencies = [
('pycon', '0001_initial'),
]
operations = [
migrations.RunPython(remove_old_google_openid_auths, no_op),
]
|
7a5d5f8c495870222955dbf24f9680903f9e90b4
|
recommends/management/commands/recommends_precompute.py
|
recommends/management/commands/recommends_precompute.py
|
from django.core.management.base import BaseCommand
from recommends.tasks import recommends_precompute
from datetime import datetime
import dateutil.relativedelta
from optparse import make_option
import warnings
class Command(BaseCommand):
help = 'Calculate recommendations and similarities based on ratings'
option_list = BaseCommand.option_list + (
make_option('--verbose',
action='store_true',
dest='verbose',
default=False,
help='verbose mode'
),
)
def handle(self, *args, **options):
verbosity = int(options.get('verbosity', 0))
if options['verbose']:
warnings.warn('The `--verbose` option is being deprecated and it will be removed in the next release. Use `--verbosity` instead.', PendingDeprecationWarning)
verbosity = 1
if verbosity == 0:
# avoids allocating the results
recommends_precompute()
else:
self.stdout.write("\nCalculation Started.\n")
start_time = datetime.now()
results = recommends_precompute()
end_time = datetime.now()
if verbosity > 1:
for r in results:
self.stdout.write(
"%d similarities and %d recommendations saved.\n"
% (r['similar_count'], r['recommend_count']))
rd = dateutil.relativedelta.relativedelta(end_time, start_time)
self.stdout.write(
"Calculation finished in %d years, %d months, %d days, %d hours, %d minutes and %d seconds\n"
% (rd.years, rd.months, rd.days, rd.hours, rd.minutes, rd.seconds))
|
from django.core.management.base import BaseCommand
from recommends.tasks import recommends_precompute
from datetime import datetime
import dateutil.relativedelta
import warnings
class Command(BaseCommand):
help = 'Calculate recommendations and similarities based on ratings'
def add_arguments(self, parser):
parser.add_argument('--verbose',
action='store_true',
dest='verbose',
default=False,
help='verbose mode')
def handle(self, *args, **options):
verbosity = int(options.get('verbosity', 0))
if options['verbose']:
warnings.warn('The `--verbose` option is being deprecated and it will be removed in the next release. Use `--verbosity` instead.', PendingDeprecationWarning)
verbosity = 1
if verbosity == 0:
# avoids allocating the results
recommends_precompute()
else:
self.stdout.write("\nCalculation Started.\n")
start_time = datetime.now()
results = recommends_precompute()
end_time = datetime.now()
if verbosity > 1:
for r in results:
self.stdout.write(
"%d similarities and %d recommendations saved.\n"
% (r['similar_count'], r['recommend_count']))
rd = dateutil.relativedelta.relativedelta(end_time, start_time)
self.stdout.write(
"Calculation finished in %d years, %d months, %d days, %d hours, %d minutes and %d seconds\n"
% (rd.years, rd.months, rd.days, rd.hours, rd.minutes, rd.seconds))
|
Change deprecated options_list to add_arguments
|
Change deprecated options_list to add_arguments
|
Python
|
mit
|
fcurella/django-recommends,fcurella/django-recommends
|
from django.core.management.base import BaseCommand
from recommends.tasks import recommends_precompute
from datetime import datetime
import dateutil.relativedelta
from optparse import make_option
import warnings
class Command(BaseCommand):
help = 'Calculate recommendations and similarities based on ratings'
option_list = BaseCommand.option_list + (
make_option('--verbose',
action='store_true',
dest='verbose',
default=False,
help='verbose mode'
),
)
def handle(self, *args, **options):
verbosity = int(options.get('verbosity', 0))
if options['verbose']:
warnings.warn('The `--verbose` option is being deprecated and it will be removed in the next release. Use `--verbosity` instead.', PendingDeprecationWarning)
verbosity = 1
if verbosity == 0:
# avoids allocating the results
recommends_precompute()
else:
self.stdout.write("\nCalculation Started.\n")
start_time = datetime.now()
results = recommends_precompute()
end_time = datetime.now()
if verbosity > 1:
for r in results:
self.stdout.write(
"%d similarities and %d recommendations saved.\n"
% (r['similar_count'], r['recommend_count']))
rd = dateutil.relativedelta.relativedelta(end_time, start_time)
self.stdout.write(
"Calculation finished in %d years, %d months, %d days, %d hours, %d minutes and %d seconds\n"
% (rd.years, rd.months, rd.days, rd.hours, rd.minutes, rd.seconds))
Change deprecated options_list to add_arguments
|
from django.core.management.base import BaseCommand
from recommends.tasks import recommends_precompute
from datetime import datetime
import dateutil.relativedelta
import warnings
class Command(BaseCommand):
help = 'Calculate recommendations and similarities based on ratings'
def add_arguments(self, parser):
parser.add_argument('--verbose',
action='store_true',
dest='verbose',
default=False,
help='verbose mode')
def handle(self, *args, **options):
verbosity = int(options.get('verbosity', 0))
if options['verbose']:
warnings.warn('The `--verbose` option is being deprecated and it will be removed in the next release. Use `--verbosity` instead.', PendingDeprecationWarning)
verbosity = 1
if verbosity == 0:
# avoids allocating the results
recommends_precompute()
else:
self.stdout.write("\nCalculation Started.\n")
start_time = datetime.now()
results = recommends_precompute()
end_time = datetime.now()
if verbosity > 1:
for r in results:
self.stdout.write(
"%d similarities and %d recommendations saved.\n"
% (r['similar_count'], r['recommend_count']))
rd = dateutil.relativedelta.relativedelta(end_time, start_time)
self.stdout.write(
"Calculation finished in %d years, %d months, %d days, %d hours, %d minutes and %d seconds\n"
% (rd.years, rd.months, rd.days, rd.hours, rd.minutes, rd.seconds))
|
<commit_before>from django.core.management.base import BaseCommand
from recommends.tasks import recommends_precompute
from datetime import datetime
import dateutil.relativedelta
from optparse import make_option
import warnings
class Command(BaseCommand):
help = 'Calculate recommendations and similarities based on ratings'
option_list = BaseCommand.option_list + (
make_option('--verbose',
action='store_true',
dest='verbose',
default=False,
help='verbose mode'
),
)
def handle(self, *args, **options):
verbosity = int(options.get('verbosity', 0))
if options['verbose']:
warnings.warn('The `--verbose` option is being deprecated and it will be removed in the next release. Use `--verbosity` instead.', PendingDeprecationWarning)
verbosity = 1
if verbosity == 0:
# avoids allocating the results
recommends_precompute()
else:
self.stdout.write("\nCalculation Started.\n")
start_time = datetime.now()
results = recommends_precompute()
end_time = datetime.now()
if verbosity > 1:
for r in results:
self.stdout.write(
"%d similarities and %d recommendations saved.\n"
% (r['similar_count'], r['recommend_count']))
rd = dateutil.relativedelta.relativedelta(end_time, start_time)
self.stdout.write(
"Calculation finished in %d years, %d months, %d days, %d hours, %d minutes and %d seconds\n"
% (rd.years, rd.months, rd.days, rd.hours, rd.minutes, rd.seconds))
<commit_msg>Change deprecated options_list to add_arguments<commit_after>
|
from django.core.management.base import BaseCommand
from recommends.tasks import recommends_precompute
from datetime import datetime
import dateutil.relativedelta
import warnings
class Command(BaseCommand):
help = 'Calculate recommendations and similarities based on ratings'
def add_arguments(self, parser):
parser.add_argument('--verbose',
action='store_true',
dest='verbose',
default=False,
help='verbose mode')
def handle(self, *args, **options):
verbosity = int(options.get('verbosity', 0))
if options['verbose']:
warnings.warn('The `--verbose` option is being deprecated and it will be removed in the next release. Use `--verbosity` instead.', PendingDeprecationWarning)
verbosity = 1
if verbosity == 0:
# avoids allocating the results
recommends_precompute()
else:
self.stdout.write("\nCalculation Started.\n")
start_time = datetime.now()
results = recommends_precompute()
end_time = datetime.now()
if verbosity > 1:
for r in results:
self.stdout.write(
"%d similarities and %d recommendations saved.\n"
% (r['similar_count'], r['recommend_count']))
rd = dateutil.relativedelta.relativedelta(end_time, start_time)
self.stdout.write(
"Calculation finished in %d years, %d months, %d days, %d hours, %d minutes and %d seconds\n"
% (rd.years, rd.months, rd.days, rd.hours, rd.minutes, rd.seconds))
|
from django.core.management.base import BaseCommand
from recommends.tasks import recommends_precompute
from datetime import datetime
import dateutil.relativedelta
from optparse import make_option
import warnings
class Command(BaseCommand):
help = 'Calculate recommendations and similarities based on ratings'
option_list = BaseCommand.option_list + (
make_option('--verbose',
action='store_true',
dest='verbose',
default=False,
help='verbose mode'
),
)
def handle(self, *args, **options):
verbosity = int(options.get('verbosity', 0))
if options['verbose']:
warnings.warn('The `--verbose` option is being deprecated and it will be removed in the next release. Use `--verbosity` instead.', PendingDeprecationWarning)
verbosity = 1
if verbosity == 0:
# avoids allocating the results
recommends_precompute()
else:
self.stdout.write("\nCalculation Started.\n")
start_time = datetime.now()
results = recommends_precompute()
end_time = datetime.now()
if verbosity > 1:
for r in results:
self.stdout.write(
"%d similarities and %d recommendations saved.\n"
% (r['similar_count'], r['recommend_count']))
rd = dateutil.relativedelta.relativedelta(end_time, start_time)
self.stdout.write(
"Calculation finished in %d years, %d months, %d days, %d hours, %d minutes and %d seconds\n"
% (rd.years, rd.months, rd.days, rd.hours, rd.minutes, rd.seconds))
Change deprecated options_list to add_argumentsfrom django.core.management.base import BaseCommand
from recommends.tasks import recommends_precompute
from datetime import datetime
import dateutil.relativedelta
import warnings
class Command(BaseCommand):
help = 'Calculate recommendations and similarities based on ratings'
def add_arguments(self, parser):
parser.add_argument('--verbose',
action='store_true',
dest='verbose',
default=False,
help='verbose mode')
def handle(self, *args, **options):
verbosity = int(options.get('verbosity', 0))
if options['verbose']:
warnings.warn('The `--verbose` option is being deprecated and it will be removed in the next release. Use `--verbosity` instead.', PendingDeprecationWarning)
verbosity = 1
if verbosity == 0:
# avoids allocating the results
recommends_precompute()
else:
self.stdout.write("\nCalculation Started.\n")
start_time = datetime.now()
results = recommends_precompute()
end_time = datetime.now()
if verbosity > 1:
for r in results:
self.stdout.write(
"%d similarities and %d recommendations saved.\n"
% (r['similar_count'], r['recommend_count']))
rd = dateutil.relativedelta.relativedelta(end_time, start_time)
self.stdout.write(
"Calculation finished in %d years, %d months, %d days, %d hours, %d minutes and %d seconds\n"
% (rd.years, rd.months, rd.days, rd.hours, rd.minutes, rd.seconds))
|
<commit_before>from django.core.management.base import BaseCommand
from recommends.tasks import recommends_precompute
from datetime import datetime
import dateutil.relativedelta
from optparse import make_option
import warnings
class Command(BaseCommand):
help = 'Calculate recommendations and similarities based on ratings'
option_list = BaseCommand.option_list + (
make_option('--verbose',
action='store_true',
dest='verbose',
default=False,
help='verbose mode'
),
)
def handle(self, *args, **options):
verbosity = int(options.get('verbosity', 0))
if options['verbose']:
warnings.warn('The `--verbose` option is being deprecated and it will be removed in the next release. Use `--verbosity` instead.', PendingDeprecationWarning)
verbosity = 1
if verbosity == 0:
# avoids allocating the results
recommends_precompute()
else:
self.stdout.write("\nCalculation Started.\n")
start_time = datetime.now()
results = recommends_precompute()
end_time = datetime.now()
if verbosity > 1:
for r in results:
self.stdout.write(
"%d similarities and %d recommendations saved.\n"
% (r['similar_count'], r['recommend_count']))
rd = dateutil.relativedelta.relativedelta(end_time, start_time)
self.stdout.write(
"Calculation finished in %d years, %d months, %d days, %d hours, %d minutes and %d seconds\n"
% (rd.years, rd.months, rd.days, rd.hours, rd.minutes, rd.seconds))
<commit_msg>Change deprecated options_list to add_arguments<commit_after>from django.core.management.base import BaseCommand
from recommends.tasks import recommends_precompute
from datetime import datetime
import dateutil.relativedelta
import warnings
class Command(BaseCommand):
help = 'Calculate recommendations and similarities based on ratings'
def add_arguments(self, parser):
parser.add_argument('--verbose',
action='store_true',
dest='verbose',
default=False,
help='verbose mode')
def handle(self, *args, **options):
verbosity = int(options.get('verbosity', 0))
if options['verbose']:
warnings.warn('The `--verbose` option is being deprecated and it will be removed in the next release. Use `--verbosity` instead.', PendingDeprecationWarning)
verbosity = 1
if verbosity == 0:
# avoids allocating the results
recommends_precompute()
else:
self.stdout.write("\nCalculation Started.\n")
start_time = datetime.now()
results = recommends_precompute()
end_time = datetime.now()
if verbosity > 1:
for r in results:
self.stdout.write(
"%d similarities and %d recommendations saved.\n"
% (r['similar_count'], r['recommend_count']))
rd = dateutil.relativedelta.relativedelta(end_time, start_time)
self.stdout.write(
"Calculation finished in %d years, %d months, %d days, %d hours, %d minutes and %d seconds\n"
% (rd.years, rd.months, rd.days, rd.hours, rd.minutes, rd.seconds))
|
69167ea402872e49a6c6dcb3d384af2912fd13d1
|
anyway/parsers/news_flash/scrap_flash_news.py
|
anyway/parsers/news_flash/scrap_flash_news.py
|
import os
import sys
from .new_news_check import is_new_flash_news
from .news_flash_crawl import news_flash_crawl
from ..mda_twitter.mda_twitter import mda_twitter
# from sys import exit
# import time
def scrap_flash_news(site_name, maps_key):
"""
init scraping for a site
:param site_name: name of the site to scrap
:param maps_key: google maps key path
"""
if site_name == 'ynet':
rss_link = 'https://www.ynet.co.il/Integration/StoryRss1854.xml'
if is_new_flash_news(rss_link):
news_flash_crawl(rss_link, site_name, maps_key)
if site_name == 'twitter':
mda_twitter()
def main(google_maps_key_path):
"""
main function for beginning of the news flash process
:param google_maps_key_path: path to google maps key
"""
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
scrap_flash_news('ynet',google_maps_key_path)
#scrap_flash_news('twitter',google_maps_key_path)
|
import os
import sys
from .new_news_check import is_new_flash_news
from .news_flash_crawl import news_flash_crawl
from ..mda_twitter.mda_twitter import mda_twitter
# from sys import exit
# import time
def scrap_flash_news(site_name, maps_key):
"""
init scraping for a site
:param site_name: name of the site to scrap
:param maps_key: google maps key path
"""
if site_name == 'ynet':
rss_link = 'https://www.ynet.co.il/Integration/StoryRss1854.xml'
if is_new_flash_news(rss_link):
news_flash_crawl(rss_link, site_name, maps_key)
if site_name == 'twitter':
mda_twitter()
def main(google_maps_key_path):
"""
main function for beginning of the news flash process
:param google_maps_key_path: path to google maps key
"""
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
scrap_flash_news('ynet',google_maps_key_path)
scrap_flash_news('twitter',google_maps_key_path)
|
Revert "temp stop twitter scraping"
|
Revert "temp stop twitter scraping"
This reverts commit 21db824f3b2a544fa38547bb1fd6c6271f861354.
|
Python
|
mit
|
hasadna/anyway,hasadna/anyway,hasadna/anyway,hasadna/anyway
|
import os
import sys
from .new_news_check import is_new_flash_news
from .news_flash_crawl import news_flash_crawl
from ..mda_twitter.mda_twitter import mda_twitter
# from sys import exit
# import time
def scrap_flash_news(site_name, maps_key):
"""
init scraping for a site
:param site_name: name of the site to scrap
:param maps_key: google maps key path
"""
if site_name == 'ynet':
rss_link = 'https://www.ynet.co.il/Integration/StoryRss1854.xml'
if is_new_flash_news(rss_link):
news_flash_crawl(rss_link, site_name, maps_key)
if site_name == 'twitter':
mda_twitter()
def main(google_maps_key_path):
"""
main function for beginning of the news flash process
:param google_maps_key_path: path to google maps key
"""
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
scrap_flash_news('ynet',google_maps_key_path)
#scrap_flash_news('twitter',google_maps_key_path)
Revert "temp stop twitter scraping"
This reverts commit 21db824f3b2a544fa38547bb1fd6c6271f861354.
|
import os
import sys
from .new_news_check import is_new_flash_news
from .news_flash_crawl import news_flash_crawl
from ..mda_twitter.mda_twitter import mda_twitter
# from sys import exit
# import time
def scrap_flash_news(site_name, maps_key):
"""
init scraping for a site
:param site_name: name of the site to scrap
:param maps_key: google maps key path
"""
if site_name == 'ynet':
rss_link = 'https://www.ynet.co.il/Integration/StoryRss1854.xml'
if is_new_flash_news(rss_link):
news_flash_crawl(rss_link, site_name, maps_key)
if site_name == 'twitter':
mda_twitter()
def main(google_maps_key_path):
"""
main function for beginning of the news flash process
:param google_maps_key_path: path to google maps key
"""
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
scrap_flash_news('ynet',google_maps_key_path)
scrap_flash_news('twitter',google_maps_key_path)
|
<commit_before>import os
import sys
from .new_news_check import is_new_flash_news
from .news_flash_crawl import news_flash_crawl
from ..mda_twitter.mda_twitter import mda_twitter
# from sys import exit
# import time
def scrap_flash_news(site_name, maps_key):
"""
init scraping for a site
:param site_name: name of the site to scrap
:param maps_key: google maps key path
"""
if site_name == 'ynet':
rss_link = 'https://www.ynet.co.il/Integration/StoryRss1854.xml'
if is_new_flash_news(rss_link):
news_flash_crawl(rss_link, site_name, maps_key)
if site_name == 'twitter':
mda_twitter()
def main(google_maps_key_path):
"""
main function for beginning of the news flash process
:param google_maps_key_path: path to google maps key
"""
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
scrap_flash_news('ynet',google_maps_key_path)
#scrap_flash_news('twitter',google_maps_key_path)
<commit_msg>Revert "temp stop twitter scraping"
This reverts commit 21db824f3b2a544fa38547bb1fd6c6271f861354.<commit_after>
|
import os
import sys
from .new_news_check import is_new_flash_news
from .news_flash_crawl import news_flash_crawl
from ..mda_twitter.mda_twitter import mda_twitter
# from sys import exit
# import time
def scrap_flash_news(site_name, maps_key):
"""
init scraping for a site
:param site_name: name of the site to scrap
:param maps_key: google maps key path
"""
if site_name == 'ynet':
rss_link = 'https://www.ynet.co.il/Integration/StoryRss1854.xml'
if is_new_flash_news(rss_link):
news_flash_crawl(rss_link, site_name, maps_key)
if site_name == 'twitter':
mda_twitter()
def main(google_maps_key_path):
"""
main function for beginning of the news flash process
:param google_maps_key_path: path to google maps key
"""
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
scrap_flash_news('ynet',google_maps_key_path)
scrap_flash_news('twitter',google_maps_key_path)
|
import os
import sys
from .new_news_check import is_new_flash_news
from .news_flash_crawl import news_flash_crawl
from ..mda_twitter.mda_twitter import mda_twitter
# from sys import exit
# import time
def scrap_flash_news(site_name, maps_key):
"""
init scraping for a site
:param site_name: name of the site to scrap
:param maps_key: google maps key path
"""
if site_name == 'ynet':
rss_link = 'https://www.ynet.co.il/Integration/StoryRss1854.xml'
if is_new_flash_news(rss_link):
news_flash_crawl(rss_link, site_name, maps_key)
if site_name == 'twitter':
mda_twitter()
def main(google_maps_key_path):
"""
main function for beginning of the news flash process
:param google_maps_key_path: path to google maps key
"""
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
scrap_flash_news('ynet',google_maps_key_path)
#scrap_flash_news('twitter',google_maps_key_path)
Revert "temp stop twitter scraping"
This reverts commit 21db824f3b2a544fa38547bb1fd6c6271f861354.import os
import sys
from .new_news_check import is_new_flash_news
from .news_flash_crawl import news_flash_crawl
from ..mda_twitter.mda_twitter import mda_twitter
# from sys import exit
# import time
def scrap_flash_news(site_name, maps_key):
"""
init scraping for a site
:param site_name: name of the site to scrap
:param maps_key: google maps key path
"""
if site_name == 'ynet':
rss_link = 'https://www.ynet.co.il/Integration/StoryRss1854.xml'
if is_new_flash_news(rss_link):
news_flash_crawl(rss_link, site_name, maps_key)
if site_name == 'twitter':
mda_twitter()
def main(google_maps_key_path):
"""
main function for beginning of the news flash process
:param google_maps_key_path: path to google maps key
"""
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
scrap_flash_news('ynet',google_maps_key_path)
scrap_flash_news('twitter',google_maps_key_path)
|
<commit_before>import os
import sys
from .new_news_check import is_new_flash_news
from .news_flash_crawl import news_flash_crawl
from ..mda_twitter.mda_twitter import mda_twitter
# from sys import exit
# import time
def scrap_flash_news(site_name, maps_key):
"""
init scraping for a site
:param site_name: name of the site to scrap
:param maps_key: google maps key path
"""
if site_name == 'ynet':
rss_link = 'https://www.ynet.co.il/Integration/StoryRss1854.xml'
if is_new_flash_news(rss_link):
news_flash_crawl(rss_link, site_name, maps_key)
if site_name == 'twitter':
mda_twitter()
def main(google_maps_key_path):
"""
main function for beginning of the news flash process
:param google_maps_key_path: path to google maps key
"""
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
scrap_flash_news('ynet',google_maps_key_path)
#scrap_flash_news('twitter',google_maps_key_path)
<commit_msg>Revert "temp stop twitter scraping"
This reverts commit 21db824f3b2a544fa38547bb1fd6c6271f861354.<commit_after>import os
import sys
from .new_news_check import is_new_flash_news
from .news_flash_crawl import news_flash_crawl
from ..mda_twitter.mda_twitter import mda_twitter
# from sys import exit
# import time
def scrap_flash_news(site_name, maps_key):
"""
init scraping for a site
:param site_name: name of the site to scrap
:param maps_key: google maps key path
"""
if site_name == 'ynet':
rss_link = 'https://www.ynet.co.il/Integration/StoryRss1854.xml'
if is_new_flash_news(rss_link):
news_flash_crawl(rss_link, site_name, maps_key)
if site_name == 'twitter':
mda_twitter()
def main(google_maps_key_path):
"""
main function for beginning of the news flash process
:param google_maps_key_path: path to google maps key
"""
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
scrap_flash_news('ynet',google_maps_key_path)
scrap_flash_news('twitter',google_maps_key_path)
|
d426351e86ab52f0c77f9a2b97d5bcdb35ee719f
|
tests/dojo_test.py
|
tests/dojo_test.py
|
import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("Blue", "office")
self.assertTrue(blue_office)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)
|
import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("office", "Blue")
self.assertTrue(blue_office)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)
def test_create_rooms_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
offices = my_class_instance.create_room("office", "Blue", "Black", "Brown")
self.assertTrue(offices)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 3)
|
Add test for creation of multiple rooms
|
Add test for creation of multiple rooms
|
Python
|
mit
|
EdwinKato/Space-Allocator,EdwinKato/Space-Allocator
|
import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("Blue", "office")
self.assertTrue(blue_office)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)Add test for creation of multiple rooms
|
import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("office", "Blue")
self.assertTrue(blue_office)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)
def test_create_rooms_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
offices = my_class_instance.create_room("office", "Blue", "Black", "Brown")
self.assertTrue(offices)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 3)
|
<commit_before>import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("Blue", "office")
self.assertTrue(blue_office)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)<commit_msg>Add test for creation of multiple rooms<commit_after>
|
import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("office", "Blue")
self.assertTrue(blue_office)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)
def test_create_rooms_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
offices = my_class_instance.create_room("office", "Blue", "Black", "Brown")
self.assertTrue(offices)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 3)
|
import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("Blue", "office")
self.assertTrue(blue_office)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)Add test for creation of multiple roomsimport unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("office", "Blue")
self.assertTrue(blue_office)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)
def test_create_rooms_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
offices = my_class_instance.create_room("office", "Blue", "Black", "Brown")
self.assertTrue(offices)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 3)
|
<commit_before>import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("Blue", "office")
self.assertTrue(blue_office)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)<commit_msg>Add test for creation of multiple rooms<commit_after>import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("office", "Blue")
self.assertTrue(blue_office)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)
def test_create_rooms_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
offices = my_class_instance.create_room("office", "Blue", "Black", "Brown")
self.assertTrue(offices)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 3)
|
da74f8963ffbe80c2ae3c99e3b17bc30ea2e6728
|
user_management/utils/sentry.py
|
user_management/utils/sentry.py
|
from django.views.debug import SafeExceptionReporterFilter
from raven.contrib.django.client import DjangoClient
class SensitiveDjangoClient(DjangoClient):
"""
Hide sensitive request data from being logged by Sentry.
Borrowed from http://stackoverflow.com/a/23966581/240995
"""
def get_data_from_request(self, request):
request.POST = SafeExceptionReporterFilter().get_post_parameters(request)
result = super().get_data_from_request(request)
# override the request.data with POST data
# POST data contains no sensitive info in it
result['request']['data'] = request.POST
# remove the whole cookie as it contains DRF auth token and session id
if 'cookies' in result['request']:
del result['request']['cookies']
if 'Cookie' in result['request']['headers']:
del result['request']['headers']['Cookie']
return result
|
from django.views.debug import SafeExceptionReporterFilter
from raven.contrib.django.client import DjangoClient
class SensitiveDjangoClient(DjangoClient):
"""
Hide sensitive request data from being logged by Sentry.
Borrowed from http://stackoverflow.com/a/23966581/240995
"""
def get_data_from_request(self, request):
request.POST = SafeExceptionReporterFilter().get_post_parameters(request)
result = super(SensitiveDjangoClient, self).get_data_from_request(request)
# override the request.data with POST data
# POST data contains no sensitive info in it
result['request']['data'] = request.POST
# remove the whole cookie as it contains DRF auth token and session id
if 'cookies' in result['request']:
del result['request']['cookies']
if 'Cookie' in result['request']['headers']:
del result['request']['headers']['Cookie']
return result
|
Fix call to super for py2.7
|
Fix call to super for py2.7
|
Python
|
bsd-2-clause
|
incuna/django-user-management,incuna/django-user-management
|
from django.views.debug import SafeExceptionReporterFilter
from raven.contrib.django.client import DjangoClient
class SensitiveDjangoClient(DjangoClient):
"""
Hide sensitive request data from being logged by Sentry.
Borrowed from http://stackoverflow.com/a/23966581/240995
"""
def get_data_from_request(self, request):
request.POST = SafeExceptionReporterFilter().get_post_parameters(request)
result = super().get_data_from_request(request)
# override the request.data with POST data
# POST data contains no sensitive info in it
result['request']['data'] = request.POST
# remove the whole cookie as it contains DRF auth token and session id
if 'cookies' in result['request']:
del result['request']['cookies']
if 'Cookie' in result['request']['headers']:
del result['request']['headers']['Cookie']
return result
Fix call to super for py2.7
|
from django.views.debug import SafeExceptionReporterFilter
from raven.contrib.django.client import DjangoClient
class SensitiveDjangoClient(DjangoClient):
"""
Hide sensitive request data from being logged by Sentry.
Borrowed from http://stackoverflow.com/a/23966581/240995
"""
def get_data_from_request(self, request):
request.POST = SafeExceptionReporterFilter().get_post_parameters(request)
result = super(SensitiveDjangoClient, self).get_data_from_request(request)
# override the request.data with POST data
# POST data contains no sensitive info in it
result['request']['data'] = request.POST
# remove the whole cookie as it contains DRF auth token and session id
if 'cookies' in result['request']:
del result['request']['cookies']
if 'Cookie' in result['request']['headers']:
del result['request']['headers']['Cookie']
return result
|
<commit_before>from django.views.debug import SafeExceptionReporterFilter
from raven.contrib.django.client import DjangoClient
class SensitiveDjangoClient(DjangoClient):
"""
Hide sensitive request data from being logged by Sentry.
Borrowed from http://stackoverflow.com/a/23966581/240995
"""
def get_data_from_request(self, request):
request.POST = SafeExceptionReporterFilter().get_post_parameters(request)
result = super().get_data_from_request(request)
# override the request.data with POST data
# POST data contains no sensitive info in it
result['request']['data'] = request.POST
# remove the whole cookie as it contains DRF auth token and session id
if 'cookies' in result['request']:
del result['request']['cookies']
if 'Cookie' in result['request']['headers']:
del result['request']['headers']['Cookie']
return result
<commit_msg>Fix call to super for py2.7<commit_after>
|
from django.views.debug import SafeExceptionReporterFilter
from raven.contrib.django.client import DjangoClient
class SensitiveDjangoClient(DjangoClient):
"""
Hide sensitive request data from being logged by Sentry.
Borrowed from http://stackoverflow.com/a/23966581/240995
"""
def get_data_from_request(self, request):
request.POST = SafeExceptionReporterFilter().get_post_parameters(request)
result = super(SensitiveDjangoClient, self).get_data_from_request(request)
# override the request.data with POST data
# POST data contains no sensitive info in it
result['request']['data'] = request.POST
# remove the whole cookie as it contains DRF auth token and session id
if 'cookies' in result['request']:
del result['request']['cookies']
if 'Cookie' in result['request']['headers']:
del result['request']['headers']['Cookie']
return result
|
from django.views.debug import SafeExceptionReporterFilter
from raven.contrib.django.client import DjangoClient
class SensitiveDjangoClient(DjangoClient):
"""
Hide sensitive request data from being logged by Sentry.
Borrowed from http://stackoverflow.com/a/23966581/240995
"""
def get_data_from_request(self, request):
request.POST = SafeExceptionReporterFilter().get_post_parameters(request)
result = super().get_data_from_request(request)
# override the request.data with POST data
# POST data contains no sensitive info in it
result['request']['data'] = request.POST
# remove the whole cookie as it contains DRF auth token and session id
if 'cookies' in result['request']:
del result['request']['cookies']
if 'Cookie' in result['request']['headers']:
del result['request']['headers']['Cookie']
return result
Fix call to super for py2.7from django.views.debug import SafeExceptionReporterFilter
from raven.contrib.django.client import DjangoClient
class SensitiveDjangoClient(DjangoClient):
"""
Hide sensitive request data from being logged by Sentry.
Borrowed from http://stackoverflow.com/a/23966581/240995
"""
def get_data_from_request(self, request):
request.POST = SafeExceptionReporterFilter().get_post_parameters(request)
result = super(SensitiveDjangoClient, self).get_data_from_request(request)
# override the request.data with POST data
# POST data contains no sensitive info in it
result['request']['data'] = request.POST
# remove the whole cookie as it contains DRF auth token and session id
if 'cookies' in result['request']:
del result['request']['cookies']
if 'Cookie' in result['request']['headers']:
del result['request']['headers']['Cookie']
return result
|
<commit_before>from django.views.debug import SafeExceptionReporterFilter
from raven.contrib.django.client import DjangoClient
class SensitiveDjangoClient(DjangoClient):
"""
Hide sensitive request data from being logged by Sentry.
Borrowed from http://stackoverflow.com/a/23966581/240995
"""
def get_data_from_request(self, request):
request.POST = SafeExceptionReporterFilter().get_post_parameters(request)
result = super().get_data_from_request(request)
# override the request.data with POST data
# POST data contains no sensitive info in it
result['request']['data'] = request.POST
# remove the whole cookie as it contains DRF auth token and session id
if 'cookies' in result['request']:
del result['request']['cookies']
if 'Cookie' in result['request']['headers']:
del result['request']['headers']['Cookie']
return result
<commit_msg>Fix call to super for py2.7<commit_after>from django.views.debug import SafeExceptionReporterFilter
from raven.contrib.django.client import DjangoClient
class SensitiveDjangoClient(DjangoClient):
"""
Hide sensitive request data from being logged by Sentry.
Borrowed from http://stackoverflow.com/a/23966581/240995
"""
def get_data_from_request(self, request):
request.POST = SafeExceptionReporterFilter().get_post_parameters(request)
result = super(SensitiveDjangoClient, self).get_data_from_request(request)
# override the request.data with POST data
# POST data contains no sensitive info in it
result['request']['data'] = request.POST
# remove the whole cookie as it contains DRF auth token and session id
if 'cookies' in result['request']:
del result['request']['cookies']
if 'Cookie' in result['request']['headers']:
del result['request']['headers']['Cookie']
return result
|
a4d538d84fdfd8e20b58ada8a4435ed48ed64ab8
|
spreadflow_delta/test/matchers.py
|
spreadflow_delta/test/matchers.py
|
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from testtools import matchers
from spreadflow_core.test.matchers import MatchesInvocation
class MatchesDeltaItem(matchers.MatchesDict):
def __init__(self, item):
spec = {
'data': matchers.Equals(item['data']),
'inserts': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['inserts']]),
'deletes': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['deletes']])
}
if 'parent' in item:
spec['parent'] = MatchesDeltaItem(item['parent'])
super(MatchesDeltaItem, self).__init__(spec)
class MatchesSendDeltaItemInvocation(MatchesInvocation):
def __init__(self, expected_item, expected_port):
super(MatchesSendDeltaItemInvocation, self).__init__(
MatchesDeltaItem(expected_item),
matchers.Equals(expected_port)
)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from testtools import matchers
from spreadflow_core.test.matchers import MatchesInvocation
class MatchesDeltaItem(matchers.MatchesDict):
def __init__(self, item):
spec = {
'data': matchers.Equals(item['data']),
'inserts': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['inserts']]),
'deletes': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['deletes']])
}
if 'parent' in item:
spec['parent'] = MatchesDeltaItem(item['parent'])
# Use equal matcher for remaining keys.
for key in set(item.keys()) - set(spec.keys()):
spec[key] = matchers.Equals(item[key])
super(MatchesDeltaItem, self).__init__(spec)
class MatchesSendDeltaItemInvocation(MatchesInvocation):
def __init__(self, expected_item, expected_port):
super(MatchesSendDeltaItemInvocation, self).__init__(
MatchesDeltaItem(expected_item),
matchers.Equals(expected_port)
)
|
Use equal matcher for remaining keys
|
Use equal matcher for remaining keys
|
Python
|
mit
|
znerol/spreadflow-delta
|
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from testtools import matchers
from spreadflow_core.test.matchers import MatchesInvocation
class MatchesDeltaItem(matchers.MatchesDict):
def __init__(self, item):
spec = {
'data': matchers.Equals(item['data']),
'inserts': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['inserts']]),
'deletes': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['deletes']])
}
if 'parent' in item:
spec['parent'] = MatchesDeltaItem(item['parent'])
super(MatchesDeltaItem, self).__init__(spec)
class MatchesSendDeltaItemInvocation(MatchesInvocation):
def __init__(self, expected_item, expected_port):
super(MatchesSendDeltaItemInvocation, self).__init__(
MatchesDeltaItem(expected_item),
matchers.Equals(expected_port)
)
Use equal matcher for remaining keys
|
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from testtools import matchers
from spreadflow_core.test.matchers import MatchesInvocation
class MatchesDeltaItem(matchers.MatchesDict):
def __init__(self, item):
spec = {
'data': matchers.Equals(item['data']),
'inserts': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['inserts']]),
'deletes': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['deletes']])
}
if 'parent' in item:
spec['parent'] = MatchesDeltaItem(item['parent'])
# Use equal matcher for remaining keys.
for key in set(item.keys()) - set(spec.keys()):
spec[key] = matchers.Equals(item[key])
super(MatchesDeltaItem, self).__init__(spec)
class MatchesSendDeltaItemInvocation(MatchesInvocation):
def __init__(self, expected_item, expected_port):
super(MatchesSendDeltaItemInvocation, self).__init__(
MatchesDeltaItem(expected_item),
matchers.Equals(expected_port)
)
|
<commit_before>from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from testtools import matchers
from spreadflow_core.test.matchers import MatchesInvocation
class MatchesDeltaItem(matchers.MatchesDict):
def __init__(self, item):
spec = {
'data': matchers.Equals(item['data']),
'inserts': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['inserts']]),
'deletes': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['deletes']])
}
if 'parent' in item:
spec['parent'] = MatchesDeltaItem(item['parent'])
super(MatchesDeltaItem, self).__init__(spec)
class MatchesSendDeltaItemInvocation(MatchesInvocation):
def __init__(self, expected_item, expected_port):
super(MatchesSendDeltaItemInvocation, self).__init__(
MatchesDeltaItem(expected_item),
matchers.Equals(expected_port)
)
<commit_msg>Use equal matcher for remaining keys<commit_after>
|
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from testtools import matchers
from spreadflow_core.test.matchers import MatchesInvocation
class MatchesDeltaItem(matchers.MatchesDict):
def __init__(self, item):
spec = {
'data': matchers.Equals(item['data']),
'inserts': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['inserts']]),
'deletes': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['deletes']])
}
if 'parent' in item:
spec['parent'] = MatchesDeltaItem(item['parent'])
# Use equal matcher for remaining keys.
for key in set(item.keys()) - set(spec.keys()):
spec[key] = matchers.Equals(item[key])
super(MatchesDeltaItem, self).__init__(spec)
class MatchesSendDeltaItemInvocation(MatchesInvocation):
def __init__(self, expected_item, expected_port):
super(MatchesSendDeltaItemInvocation, self).__init__(
MatchesDeltaItem(expected_item),
matchers.Equals(expected_port)
)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from testtools import matchers
from spreadflow_core.test.matchers import MatchesInvocation
class MatchesDeltaItem(matchers.MatchesDict):
def __init__(self, item):
spec = {
'data': matchers.Equals(item['data']),
'inserts': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['inserts']]),
'deletes': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['deletes']])
}
if 'parent' in item:
spec['parent'] = MatchesDeltaItem(item['parent'])
super(MatchesDeltaItem, self).__init__(spec)
class MatchesSendDeltaItemInvocation(MatchesInvocation):
def __init__(self, expected_item, expected_port):
super(MatchesSendDeltaItemInvocation, self).__init__(
MatchesDeltaItem(expected_item),
matchers.Equals(expected_port)
)
Use equal matcher for remaining keysfrom __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from testtools import matchers
from spreadflow_core.test.matchers import MatchesInvocation
class MatchesDeltaItem(matchers.MatchesDict):
def __init__(self, item):
spec = {
'data': matchers.Equals(item['data']),
'inserts': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['inserts']]),
'deletes': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['deletes']])
}
if 'parent' in item:
spec['parent'] = MatchesDeltaItem(item['parent'])
# Use equal matcher for remaining keys.
for key in set(item.keys()) - set(spec.keys()):
spec[key] = matchers.Equals(item[key])
super(MatchesDeltaItem, self).__init__(spec)
class MatchesSendDeltaItemInvocation(MatchesInvocation):
def __init__(self, expected_item, expected_port):
super(MatchesSendDeltaItemInvocation, self).__init__(
MatchesDeltaItem(expected_item),
matchers.Equals(expected_port)
)
|
<commit_before>from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from testtools import matchers
from spreadflow_core.test.matchers import MatchesInvocation
class MatchesDeltaItem(matchers.MatchesDict):
def __init__(self, item):
spec = {
'data': matchers.Equals(item['data']),
'inserts': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['inserts']]),
'deletes': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['deletes']])
}
if 'parent' in item:
spec['parent'] = MatchesDeltaItem(item['parent'])
super(MatchesDeltaItem, self).__init__(spec)
class MatchesSendDeltaItemInvocation(MatchesInvocation):
def __init__(self, expected_item, expected_port):
super(MatchesSendDeltaItemInvocation, self).__init__(
MatchesDeltaItem(expected_item),
matchers.Equals(expected_port)
)
<commit_msg>Use equal matcher for remaining keys<commit_after>from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from testtools import matchers
from spreadflow_core.test.matchers import MatchesInvocation
class MatchesDeltaItem(matchers.MatchesDict):
def __init__(self, item):
spec = {
'data': matchers.Equals(item['data']),
'inserts': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['inserts']]),
'deletes': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['deletes']])
}
if 'parent' in item:
spec['parent'] = MatchesDeltaItem(item['parent'])
# Use equal matcher for remaining keys.
for key in set(item.keys()) - set(spec.keys()):
spec[key] = matchers.Equals(item[key])
super(MatchesDeltaItem, self).__init__(spec)
class MatchesSendDeltaItemInvocation(MatchesInvocation):
def __init__(self, expected_item, expected_port):
super(MatchesSendDeltaItemInvocation, self).__init__(
MatchesDeltaItem(expected_item),
matchers.Equals(expected_port)
)
|
22e1bc81b7aa456c8211f3fc83c1fd4fc69f514b
|
web_scraper/core/prettifiers.py
|
web_scraper/core/prettifiers.py
|
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import re
def simple_prettifier(scraped_data):
"""Return more presentable data (in a list) provided by scrape_target_elements()
:param bs4.element.ResultSet scraped_data: all of the data scraped by scrape_target_elements()
:return: list of presentable data
:rtype: list
"""
data_list = []
for data in scraped_data:
data_list.append(data.text)
return data_list
def regex_prettifier(scraped_data, regex):
"""Return regex modified data (in a list).
:param list scraped_data: all the scraped data
:param str regex: the regular expression you want to use to prettify the
data
:return: list of regex modified data
:rtype: list
"""
data_list = []
for data in scraped_data:
data_list.append(re.sub(regex, '', data))
return data_list
|
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import re
def remove_html_tags(scraped_data):
"""Return more presentable data (in a list) provided by scrape_target_elements()
:param bs4.element.ResultSet scraped_data: all of the data scraped by scrape_target_elements()
:return: list of presentable data
:rtype: list
"""
data_list = []
for data in scraped_data:
data_list.append(data.text)
return data_list
def regex_prettifier(scraped_data, regex):
"""Return regex modified data (in a list).
:param list scraped_data: all the scraped data
:param str regex: the regular expression you want to use to prettify the
data
:return: list of regex modified data
:rtype: list
"""
data_list = []
for data in scraped_data:
data_list.append(re.sub(regex, '', data))
return data_list
|
Change function name to be more accurate
|
Change function name to be more accurate
|
Python
|
mit
|
Samuel-L/cli-ws,Samuel-L/cli-ws
|
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import re
def simple_prettifier(scraped_data):
"""Return more presentable data (in a list) provided by scrape_target_elements()
:param bs4.element.ResultSet scraped_data: all of the data scraped by scrape_target_elements()
:return: list of presentable data
:rtype: list
"""
data_list = []
for data in scraped_data:
data_list.append(data.text)
return data_list
def regex_prettifier(scraped_data, regex):
"""Return regex modified data (in a list).
:param list scraped_data: all the scraped data
:param str regex: the regular expression you want to use to prettify the
data
:return: list of regex modified data
:rtype: list
"""
data_list = []
for data in scraped_data:
data_list.append(re.sub(regex, '', data))
return data_list
Change function name to be more accurate
|
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import re
def remove_html_tags(scraped_data):
"""Return more presentable data (in a list) provided by scrape_target_elements()
:param bs4.element.ResultSet scraped_data: all of the data scraped by scrape_target_elements()
:return: list of presentable data
:rtype: list
"""
data_list = []
for data in scraped_data:
data_list.append(data.text)
return data_list
def regex_prettifier(scraped_data, regex):
"""Return regex modified data (in a list).
:param list scraped_data: all the scraped data
:param str regex: the regular expression you want to use to prettify the
data
:return: list of regex modified data
:rtype: list
"""
data_list = []
for data in scraped_data:
data_list.append(re.sub(regex, '', data))
return data_list
|
<commit_before>import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import re
def simple_prettifier(scraped_data):
"""Return more presentable data (in a list) provided by scrape_target_elements()
:param bs4.element.ResultSet scraped_data: all of the data scraped by scrape_target_elements()
:return: list of presentable data
:rtype: list
"""
data_list = []
for data in scraped_data:
data_list.append(data.text)
return data_list
def regex_prettifier(scraped_data, regex):
"""Return regex modified data (in a list).
:param list scraped_data: all the scraped data
:param str regex: the regular expression you want to use to prettify the
data
:return: list of regex modified data
:rtype: list
"""
data_list = []
for data in scraped_data:
data_list.append(re.sub(regex, '', data))
return data_list
<commit_msg>Change function name to be more accurate<commit_after>
|
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import re
def remove_html_tags(scraped_data):
"""Return more presentable data (in a list) provided by scrape_target_elements()
:param bs4.element.ResultSet scraped_data: all of the data scraped by scrape_target_elements()
:return: list of presentable data
:rtype: list
"""
data_list = []
for data in scraped_data:
data_list.append(data.text)
return data_list
def regex_prettifier(scraped_data, regex):
"""Return regex modified data (in a list).
:param list scraped_data: all the scraped data
:param str regex: the regular expression you want to use to prettify the
data
:return: list of regex modified data
:rtype: list
"""
data_list = []
for data in scraped_data:
data_list.append(re.sub(regex, '', data))
return data_list
|
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import re
def simple_prettifier(scraped_data):
"""Return more presentable data (in a list) provided by scrape_target_elements()
:param bs4.element.ResultSet scraped_data: all of the data scraped by scrape_target_elements()
:return: list of presentable data
:rtype: list
"""
data_list = []
for data in scraped_data:
data_list.append(data.text)
return data_list
def regex_prettifier(scraped_data, regex):
"""Return regex modified data (in a list).
:param list scraped_data: all the scraped data
:param str regex: the regular expression you want to use to prettify the
data
:return: list of regex modified data
:rtype: list
"""
data_list = []
for data in scraped_data:
data_list.append(re.sub(regex, '', data))
return data_list
Change function name to be more accurateimport os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import re
def remove_html_tags(scraped_data):
"""Return more presentable data (in a list) provided by scrape_target_elements()
:param bs4.element.ResultSet scraped_data: all of the data scraped by scrape_target_elements()
:return: list of presentable data
:rtype: list
"""
data_list = []
for data in scraped_data:
data_list.append(data.text)
return data_list
def regex_prettifier(scraped_data, regex):
"""Return regex modified data (in a list).
:param list scraped_data: all the scraped data
:param str regex: the regular expression you want to use to prettify the
data
:return: list of regex modified data
:rtype: list
"""
data_list = []
for data in scraped_data:
data_list.append(re.sub(regex, '', data))
return data_list
|
<commit_before>import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import re
def simple_prettifier(scraped_data):
"""Return more presentable data (in a list) provided by scrape_target_elements()
:param bs4.element.ResultSet scraped_data: all of the data scraped by scrape_target_elements()
:return: list of presentable data
:rtype: list
"""
data_list = []
for data in scraped_data:
data_list.append(data.text)
return data_list
def regex_prettifier(scraped_data, regex):
"""Return regex modified data (in a list).
:param list scraped_data: all the scraped data
:param str regex: the regular expression you want to use to prettify the
data
:return: list of regex modified data
:rtype: list
"""
data_list = []
for data in scraped_data:
data_list.append(re.sub(regex, '', data))
return data_list
<commit_msg>Change function name to be more accurate<commit_after>import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import re
def remove_html_tags(scraped_data):
"""Return more presentable data (in a list) provided by scrape_target_elements()
:param bs4.element.ResultSet scraped_data: all of the data scraped by scrape_target_elements()
:return: list of presentable data
:rtype: list
"""
data_list = []
for data in scraped_data:
data_list.append(data.text)
return data_list
def regex_prettifier(scraped_data, regex):
"""Return regex modified data (in a list).
:param list scraped_data: all the scraped data
:param str regex: the regular expression you want to use to prettify the
data
:return: list of regex modified data
:rtype: list
"""
data_list = []
for data in scraped_data:
data_list.append(re.sub(regex, '', data))
return data_list
|
a268f6c74806d5996d469dd84ab365b0cf830f96
|
OpenSSL/_util.py
|
OpenSSL/_util.py
|
from six import PY3, binary_type, text_type
from cryptography.hazmat.bindings.openssl.binding import Binding
binding = Binding()
ffi = binding.ffi
lib = binding.lib
def exception_from_error_queue(exceptionType):
def text(charp):
return native(ffi.string(charp))
errors = []
while True:
error = lib.ERR_get_error()
if error == 0:
break
errors.append((
text(lib.ERR_lib_error_string(error)),
text(lib.ERR_func_error_string(error)),
text(lib.ERR_reason_error_string(error))))
raise exceptionType(errors)
def native(s):
"""
Convert :py:class:`bytes` or :py:class:`unicode` to the native
:py:class:`str` type, using UTF-8 encoding if conversion is necessary.
:raise UnicodeError: The input string is not UTF-8 decodeable.
:raise TypeError: The input is neither :py:class:`bytes` nor
:py:class:`unicode`.
"""
if not isinstance(s, (binary_type, text_type)):
raise TypeError("%r is neither bytes nor unicode" % s)
if PY3:
if isinstance(s, binary_type):
return s.decode("utf-8")
else:
if isinstance(s, text_type):
return s.encode("utf-8")
return s
if PY3:
def byte_string(s):
return s.encode("charmap")
else:
def byte_string(s):
return s
|
from six import PY3, binary_type, text_type
from cryptography.hazmat.bindings.openssl.binding import Binding
binding = Binding()
ffi = binding.ffi
lib = binding.lib
def exception_from_error_queue(exceptionType):
def text(charp):
if not charp:
return ""
return native(ffi.string(charp))
errors = []
while True:
error = lib.ERR_get_error()
if error == 0:
break
errors.append((
text(lib.ERR_lib_error_string(error)),
text(lib.ERR_func_error_string(error)),
text(lib.ERR_reason_error_string(error))))
raise exceptionType(errors)
def native(s):
"""
Convert :py:class:`bytes` or :py:class:`unicode` to the native
:py:class:`str` type, using UTF-8 encoding if conversion is necessary.
:raise UnicodeError: The input string is not UTF-8 decodeable.
:raise TypeError: The input is neither :py:class:`bytes` nor
:py:class:`unicode`.
"""
if not isinstance(s, (binary_type, text_type)):
raise TypeError("%r is neither bytes nor unicode" % s)
if PY3:
if isinstance(s, binary_type):
return s.decode("utf-8")
else:
if isinstance(s, text_type):
return s.encode("utf-8")
return s
if PY3:
def byte_string(s):
return s.encode("charmap")
else:
def byte_string(s):
return s
|
Handle when an OpenSSL error doesn't contain a reason
|
Handle when an OpenSSL error doesn't contain a reason
(Or any other field)
You can reproduce the error by running:
```
treq.get('https://nile.ghdonline.org')
```
from within a twisted program (and doing the approrpiate deferred stuff).
I'm unsure how to craft a unit test for this
|
Python
|
apache-2.0
|
mschmo/pyopenssl,daodaoliang/pyopenssl,mhils/pyopenssl,mhils/pyopenssl,pyca/pyopenssl,sorenh/pyopenssl,adamwolf/pyopenssl,reaperhulk/pyopenssl,aalba6675/pyopenssl,mitghi/pyopenssl,samv/pyopenssl,elitest/pyopenssl,r0ro/pyopenssl,r0ro/pyopenssl,reaperhulk/pyopenssl,kjav/pyopenssl,mitghi/pyopenssl,aalba6675/pyopenssl,hynek/pyopenssl,sholsapp/pyopenssl,hynek/pyopenssl
|
from six import PY3, binary_type, text_type
from cryptography.hazmat.bindings.openssl.binding import Binding
binding = Binding()
ffi = binding.ffi
lib = binding.lib
def exception_from_error_queue(exceptionType):
def text(charp):
return native(ffi.string(charp))
errors = []
while True:
error = lib.ERR_get_error()
if error == 0:
break
errors.append((
text(lib.ERR_lib_error_string(error)),
text(lib.ERR_func_error_string(error)),
text(lib.ERR_reason_error_string(error))))
raise exceptionType(errors)
def native(s):
"""
Convert :py:class:`bytes` or :py:class:`unicode` to the native
:py:class:`str` type, using UTF-8 encoding if conversion is necessary.
:raise UnicodeError: The input string is not UTF-8 decodeable.
:raise TypeError: The input is neither :py:class:`bytes` nor
:py:class:`unicode`.
"""
if not isinstance(s, (binary_type, text_type)):
raise TypeError("%r is neither bytes nor unicode" % s)
if PY3:
if isinstance(s, binary_type):
return s.decode("utf-8")
else:
if isinstance(s, text_type):
return s.encode("utf-8")
return s
if PY3:
def byte_string(s):
return s.encode("charmap")
else:
def byte_string(s):
return s
Handle when an OpenSSL error doesn't contain a reason
(Or any other field)
You can reproduce the error by running:
```
treq.get('https://nile.ghdonline.org')
```
from within a twisted program (and doing the approrpiate deferred stuff).
I'm unsure how to craft a unit test for this
|
from six import PY3, binary_type, text_type
from cryptography.hazmat.bindings.openssl.binding import Binding
binding = Binding()
ffi = binding.ffi
lib = binding.lib
def exception_from_error_queue(exceptionType):
def text(charp):
if not charp:
return ""
return native(ffi.string(charp))
errors = []
while True:
error = lib.ERR_get_error()
if error == 0:
break
errors.append((
text(lib.ERR_lib_error_string(error)),
text(lib.ERR_func_error_string(error)),
text(lib.ERR_reason_error_string(error))))
raise exceptionType(errors)
def native(s):
"""
Convert :py:class:`bytes` or :py:class:`unicode` to the native
:py:class:`str` type, using UTF-8 encoding if conversion is necessary.
:raise UnicodeError: The input string is not UTF-8 decodeable.
:raise TypeError: The input is neither :py:class:`bytes` nor
:py:class:`unicode`.
"""
if not isinstance(s, (binary_type, text_type)):
raise TypeError("%r is neither bytes nor unicode" % s)
if PY3:
if isinstance(s, binary_type):
return s.decode("utf-8")
else:
if isinstance(s, text_type):
return s.encode("utf-8")
return s
if PY3:
def byte_string(s):
return s.encode("charmap")
else:
def byte_string(s):
return s
|
<commit_before>from six import PY3, binary_type, text_type
from cryptography.hazmat.bindings.openssl.binding import Binding
binding = Binding()
ffi = binding.ffi
lib = binding.lib
def exception_from_error_queue(exceptionType):
def text(charp):
return native(ffi.string(charp))
errors = []
while True:
error = lib.ERR_get_error()
if error == 0:
break
errors.append((
text(lib.ERR_lib_error_string(error)),
text(lib.ERR_func_error_string(error)),
text(lib.ERR_reason_error_string(error))))
raise exceptionType(errors)
def native(s):
"""
Convert :py:class:`bytes` or :py:class:`unicode` to the native
:py:class:`str` type, using UTF-8 encoding if conversion is necessary.
:raise UnicodeError: The input string is not UTF-8 decodeable.
:raise TypeError: The input is neither :py:class:`bytes` nor
:py:class:`unicode`.
"""
if not isinstance(s, (binary_type, text_type)):
raise TypeError("%r is neither bytes nor unicode" % s)
if PY3:
if isinstance(s, binary_type):
return s.decode("utf-8")
else:
if isinstance(s, text_type):
return s.encode("utf-8")
return s
if PY3:
def byte_string(s):
return s.encode("charmap")
else:
def byte_string(s):
return s
<commit_msg>Handle when an OpenSSL error doesn't contain a reason
(Or any other field)
You can reproduce the error by running:
```
treq.get('https://nile.ghdonline.org')
```
from within a twisted program (and doing the approrpiate deferred stuff).
I'm unsure how to craft a unit test for this<commit_after>
|
from six import PY3, binary_type, text_type
from cryptography.hazmat.bindings.openssl.binding import Binding
binding = Binding()
ffi = binding.ffi
lib = binding.lib
def exception_from_error_queue(exceptionType):
def text(charp):
if not charp:
return ""
return native(ffi.string(charp))
errors = []
while True:
error = lib.ERR_get_error()
if error == 0:
break
errors.append((
text(lib.ERR_lib_error_string(error)),
text(lib.ERR_func_error_string(error)),
text(lib.ERR_reason_error_string(error))))
raise exceptionType(errors)
def native(s):
"""
Convert :py:class:`bytes` or :py:class:`unicode` to the native
:py:class:`str` type, using UTF-8 encoding if conversion is necessary.
:raise UnicodeError: The input string is not UTF-8 decodeable.
:raise TypeError: The input is neither :py:class:`bytes` nor
:py:class:`unicode`.
"""
if not isinstance(s, (binary_type, text_type)):
raise TypeError("%r is neither bytes nor unicode" % s)
if PY3:
if isinstance(s, binary_type):
return s.decode("utf-8")
else:
if isinstance(s, text_type):
return s.encode("utf-8")
return s
if PY3:
def byte_string(s):
return s.encode("charmap")
else:
def byte_string(s):
return s
|
from six import PY3, binary_type, text_type
from cryptography.hazmat.bindings.openssl.binding import Binding
binding = Binding()
ffi = binding.ffi
lib = binding.lib
def exception_from_error_queue(exceptionType):
def text(charp):
return native(ffi.string(charp))
errors = []
while True:
error = lib.ERR_get_error()
if error == 0:
break
errors.append((
text(lib.ERR_lib_error_string(error)),
text(lib.ERR_func_error_string(error)),
text(lib.ERR_reason_error_string(error))))
raise exceptionType(errors)
def native(s):
"""
Convert :py:class:`bytes` or :py:class:`unicode` to the native
:py:class:`str` type, using UTF-8 encoding if conversion is necessary.
:raise UnicodeError: The input string is not UTF-8 decodeable.
:raise TypeError: The input is neither :py:class:`bytes` nor
:py:class:`unicode`.
"""
if not isinstance(s, (binary_type, text_type)):
raise TypeError("%r is neither bytes nor unicode" % s)
if PY3:
if isinstance(s, binary_type):
return s.decode("utf-8")
else:
if isinstance(s, text_type):
return s.encode("utf-8")
return s
if PY3:
def byte_string(s):
return s.encode("charmap")
else:
def byte_string(s):
return s
Handle when an OpenSSL error doesn't contain a reason
(Or any other field)
You can reproduce the error by running:
```
treq.get('https://nile.ghdonline.org')
```
from within a twisted program (and doing the approrpiate deferred stuff).
I'm unsure how to craft a unit test for thisfrom six import PY3, binary_type, text_type
from cryptography.hazmat.bindings.openssl.binding import Binding
binding = Binding()
ffi = binding.ffi
lib = binding.lib
def exception_from_error_queue(exceptionType):
def text(charp):
if not charp:
return ""
return native(ffi.string(charp))
errors = []
while True:
error = lib.ERR_get_error()
if error == 0:
break
errors.append((
text(lib.ERR_lib_error_string(error)),
text(lib.ERR_func_error_string(error)),
text(lib.ERR_reason_error_string(error))))
raise exceptionType(errors)
def native(s):
"""
Convert :py:class:`bytes` or :py:class:`unicode` to the native
:py:class:`str` type, using UTF-8 encoding if conversion is necessary.
:raise UnicodeError: The input string is not UTF-8 decodeable.
:raise TypeError: The input is neither :py:class:`bytes` nor
:py:class:`unicode`.
"""
if not isinstance(s, (binary_type, text_type)):
raise TypeError("%r is neither bytes nor unicode" % s)
if PY3:
if isinstance(s, binary_type):
return s.decode("utf-8")
else:
if isinstance(s, text_type):
return s.encode("utf-8")
return s
if PY3:
def byte_string(s):
return s.encode("charmap")
else:
def byte_string(s):
return s
|
<commit_before>from six import PY3, binary_type, text_type
from cryptography.hazmat.bindings.openssl.binding import Binding
binding = Binding()
ffi = binding.ffi
lib = binding.lib
def exception_from_error_queue(exceptionType):
def text(charp):
return native(ffi.string(charp))
errors = []
while True:
error = lib.ERR_get_error()
if error == 0:
break
errors.append((
text(lib.ERR_lib_error_string(error)),
text(lib.ERR_func_error_string(error)),
text(lib.ERR_reason_error_string(error))))
raise exceptionType(errors)
def native(s):
"""
Convert :py:class:`bytes` or :py:class:`unicode` to the native
:py:class:`str` type, using UTF-8 encoding if conversion is necessary.
:raise UnicodeError: The input string is not UTF-8 decodeable.
:raise TypeError: The input is neither :py:class:`bytes` nor
:py:class:`unicode`.
"""
if not isinstance(s, (binary_type, text_type)):
raise TypeError("%r is neither bytes nor unicode" % s)
if PY3:
if isinstance(s, binary_type):
return s.decode("utf-8")
else:
if isinstance(s, text_type):
return s.encode("utf-8")
return s
if PY3:
def byte_string(s):
return s.encode("charmap")
else:
def byte_string(s):
return s
<commit_msg>Handle when an OpenSSL error doesn't contain a reason
(Or any other field)
You can reproduce the error by running:
```
treq.get('https://nile.ghdonline.org')
```
from within a twisted program (and doing the approrpiate deferred stuff).
I'm unsure how to craft a unit test for this<commit_after>from six import PY3, binary_type, text_type
from cryptography.hazmat.bindings.openssl.binding import Binding
binding = Binding()
ffi = binding.ffi
lib = binding.lib
def exception_from_error_queue(exceptionType):
def text(charp):
if not charp:
return ""
return native(ffi.string(charp))
errors = []
while True:
error = lib.ERR_get_error()
if error == 0:
break
errors.append((
text(lib.ERR_lib_error_string(error)),
text(lib.ERR_func_error_string(error)),
text(lib.ERR_reason_error_string(error))))
raise exceptionType(errors)
def native(s):
"""
Convert :py:class:`bytes` or :py:class:`unicode` to the native
:py:class:`str` type, using UTF-8 encoding if conversion is necessary.
:raise UnicodeError: The input string is not UTF-8 decodeable.
:raise TypeError: The input is neither :py:class:`bytes` nor
:py:class:`unicode`.
"""
if not isinstance(s, (binary_type, text_type)):
raise TypeError("%r is neither bytes nor unicode" % s)
if PY3:
if isinstance(s, binary_type):
return s.decode("utf-8")
else:
if isinstance(s, text_type):
return s.encode("utf-8")
return s
if PY3:
def byte_string(s):
return s.encode("charmap")
else:
def byte_string(s):
return s
|
49adcb1053022ec0ee3c3e5591161969f33245b8
|
collectionkit/contrib/work_creator/admin_utils.py
|
collectionkit/contrib/work_creator/admin_utils.py
|
from django.core.urlresolvers import reverse
from generic.admin.mixins import ThumbnailAdminMixin
import settings
def admin_link(obj):
return "<a href='%s'>%s</a>" % (admin_url(obj), obj)
def admin_url(obj):
return reverse(
'admin:%s_%s_change' % (obj._meta.app_label, obj._meta.module_name),
args=[obj.id]
)
class WorkThumbnailMixin(ThumbnailAdminMixin):
thumbnail_options = settings.WORK_THUMBNAIL_OPTIONS
|
from django.core.urlresolvers import reverse
from generic.admin.mixins import ThumbnailAdminMixin
import settings
def admin_link(obj):
return "<a href='%s'>%s</a>" % (admin_url(obj), obj)
def admin_url(obj):
return reverse(
'admin:%s_%s_change' % (obj._meta.app_label, obj._meta.model_name),
args=[obj.id]
)
class WorkThumbnailMixin(ThumbnailAdminMixin):
thumbnail_options = settings.WORK_THUMBNAIL_OPTIONS
|
Update to 1.8 way of getting model name.
|
Update to 1.8 way of getting model name.
|
Python
|
mit
|
ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/glamkit-collections,ic-labs/glamkit-collections
|
from django.core.urlresolvers import reverse
from generic.admin.mixins import ThumbnailAdminMixin
import settings
def admin_link(obj):
return "<a href='%s'>%s</a>" % (admin_url(obj), obj)
def admin_url(obj):
return reverse(
'admin:%s_%s_change' % (obj._meta.app_label, obj._meta.module_name),
args=[obj.id]
)
class WorkThumbnailMixin(ThumbnailAdminMixin):
thumbnail_options = settings.WORK_THUMBNAIL_OPTIONS
Update to 1.8 way of getting model name.
|
from django.core.urlresolvers import reverse
from generic.admin.mixins import ThumbnailAdminMixin
import settings
def admin_link(obj):
return "<a href='%s'>%s</a>" % (admin_url(obj), obj)
def admin_url(obj):
return reverse(
'admin:%s_%s_change' % (obj._meta.app_label, obj._meta.model_name),
args=[obj.id]
)
class WorkThumbnailMixin(ThumbnailAdminMixin):
thumbnail_options = settings.WORK_THUMBNAIL_OPTIONS
|
<commit_before>from django.core.urlresolvers import reverse
from generic.admin.mixins import ThumbnailAdminMixin
import settings
def admin_link(obj):
return "<a href='%s'>%s</a>" % (admin_url(obj), obj)
def admin_url(obj):
return reverse(
'admin:%s_%s_change' % (obj._meta.app_label, obj._meta.module_name),
args=[obj.id]
)
class WorkThumbnailMixin(ThumbnailAdminMixin):
thumbnail_options = settings.WORK_THUMBNAIL_OPTIONS
<commit_msg>Update to 1.8 way of getting model name.<commit_after>
|
from django.core.urlresolvers import reverse
from generic.admin.mixins import ThumbnailAdminMixin
import settings
def admin_link(obj):
return "<a href='%s'>%s</a>" % (admin_url(obj), obj)
def admin_url(obj):
return reverse(
'admin:%s_%s_change' % (obj._meta.app_label, obj._meta.model_name),
args=[obj.id]
)
class WorkThumbnailMixin(ThumbnailAdminMixin):
thumbnail_options = settings.WORK_THUMBNAIL_OPTIONS
|
from django.core.urlresolvers import reverse
from generic.admin.mixins import ThumbnailAdminMixin
import settings
def admin_link(obj):
return "<a href='%s'>%s</a>" % (admin_url(obj), obj)
def admin_url(obj):
return reverse(
'admin:%s_%s_change' % (obj._meta.app_label, obj._meta.module_name),
args=[obj.id]
)
class WorkThumbnailMixin(ThumbnailAdminMixin):
thumbnail_options = settings.WORK_THUMBNAIL_OPTIONS
Update to 1.8 way of getting model name.from django.core.urlresolvers import reverse
from generic.admin.mixins import ThumbnailAdminMixin
import settings
def admin_link(obj):
return "<a href='%s'>%s</a>" % (admin_url(obj), obj)
def admin_url(obj):
return reverse(
'admin:%s_%s_change' % (obj._meta.app_label, obj._meta.model_name),
args=[obj.id]
)
class WorkThumbnailMixin(ThumbnailAdminMixin):
thumbnail_options = settings.WORK_THUMBNAIL_OPTIONS
|
<commit_before>from django.core.urlresolvers import reverse
from generic.admin.mixins import ThumbnailAdminMixin
import settings
def admin_link(obj):
return "<a href='%s'>%s</a>" % (admin_url(obj), obj)
def admin_url(obj):
return reverse(
'admin:%s_%s_change' % (obj._meta.app_label, obj._meta.module_name),
args=[obj.id]
)
class WorkThumbnailMixin(ThumbnailAdminMixin):
thumbnail_options = settings.WORK_THUMBNAIL_OPTIONS
<commit_msg>Update to 1.8 way of getting model name.<commit_after>from django.core.urlresolvers import reverse
from generic.admin.mixins import ThumbnailAdminMixin
import settings
def admin_link(obj):
return "<a href='%s'>%s</a>" % (admin_url(obj), obj)
def admin_url(obj):
return reverse(
'admin:%s_%s_change' % (obj._meta.app_label, obj._meta.model_name),
args=[obj.id]
)
class WorkThumbnailMixin(ThumbnailAdminMixin):
thumbnail_options = settings.WORK_THUMBNAIL_OPTIONS
|
9f7b105b0ff84123df72cf3d14577eb82e15f699
|
community_mailbot/scripts/discourse_categories.py
|
community_mailbot/scripts/discourse_categories.py
|
# encoding: utf-8
"""
List categories and their IDs in a Discourse forum.
"""
import os
from argparse import ArgumentParser
from urllib.parse import urljoin
import requests
def main():
args = parse_args()
params = {}
if args.key is not None:
params['api_key'] = args.key
if args.user is not None:
params['api_username'] = args.user
url = urljoin(args.url, 'site.json')
r = requests.get(url, params=params)
r.raise_for_status()
site_feed = r.json()
for c in site_feed['categories']:
print(c['id'], c['name'])
def parse_args():
parser = ArgumentParser(description=__doc__)
parser.add_argument(
'--key',
default=os.getenv('DISCOURSE_KEY', None),
help='Discourse API key')
parser.add_argument(
'--user',
default=os.getenv('DISCOURSE_KEY', None),
help='Discourse API user')
parser.add_argument(
'--url',
default='http://community.lsst.org',
help='Base URL of the discourse forum')
return parser.parse_args()
if __name__ == '__main__':
main()
|
# encoding: utf-8
"""
List categories and their IDs in a Discourse forum.
"""
import os
from argparse import ArgumentParser
from community_mailbot.discourse import SiteFeed
def main():
args = parse_args()
site_feed = SiteFeed(args.url, user=args.user, key=args.key)
for c_id, name in site_feed.category_names.items():
print(c_id, name)
def parse_args():
parser = ArgumentParser(description=__doc__)
parser.add_argument(
'--key',
default=os.getenv('DISCOURSE_KEY', None),
help='Discourse API key')
parser.add_argument(
'--user',
default=os.getenv('DISCOURSE_USER', None),
help='Discourse API user')
parser.add_argument(
'--url',
default='http://community.lsst.org',
help='Base URL of the discourse forum')
return parser.parse_args()
if __name__ == '__main__':
main()
|
Use SiteFeed to get a category listing
|
Use SiteFeed to get a category listing
|
Python
|
mit
|
lsst-sqre/community_mailbot
|
# encoding: utf-8
"""
List categories and their IDs in a Discourse forum.
"""
import os
from argparse import ArgumentParser
from urllib.parse import urljoin
import requests
def main():
args = parse_args()
params = {}
if args.key is not None:
params['api_key'] = args.key
if args.user is not None:
params['api_username'] = args.user
url = urljoin(args.url, 'site.json')
r = requests.get(url, params=params)
r.raise_for_status()
site_feed = r.json()
for c in site_feed['categories']:
print(c['id'], c['name'])
def parse_args():
parser = ArgumentParser(description=__doc__)
parser.add_argument(
'--key',
default=os.getenv('DISCOURSE_KEY', None),
help='Discourse API key')
parser.add_argument(
'--user',
default=os.getenv('DISCOURSE_KEY', None),
help='Discourse API user')
parser.add_argument(
'--url',
default='http://community.lsst.org',
help='Base URL of the discourse forum')
return parser.parse_args()
if __name__ == '__main__':
main()
Use SiteFeed to get a category listing
|
# encoding: utf-8
"""
List categories and their IDs in a Discourse forum.
"""
import os
from argparse import ArgumentParser
from community_mailbot.discourse import SiteFeed
def main():
args = parse_args()
site_feed = SiteFeed(args.url, user=args.user, key=args.key)
for c_id, name in site_feed.category_names.items():
print(c_id, name)
def parse_args():
parser = ArgumentParser(description=__doc__)
parser.add_argument(
'--key',
default=os.getenv('DISCOURSE_KEY', None),
help='Discourse API key')
parser.add_argument(
'--user',
default=os.getenv('DISCOURSE_USER', None),
help='Discourse API user')
parser.add_argument(
'--url',
default='http://community.lsst.org',
help='Base URL of the discourse forum')
return parser.parse_args()
if __name__ == '__main__':
main()
|
<commit_before># encoding: utf-8
"""
List categories and their IDs in a Discourse forum.
"""
import os
from argparse import ArgumentParser
from urllib.parse import urljoin
import requests
def main():
args = parse_args()
params = {}
if args.key is not None:
params['api_key'] = args.key
if args.user is not None:
params['api_username'] = args.user
url = urljoin(args.url, 'site.json')
r = requests.get(url, params=params)
r.raise_for_status()
site_feed = r.json()
for c in site_feed['categories']:
print(c['id'], c['name'])
def parse_args():
parser = ArgumentParser(description=__doc__)
parser.add_argument(
'--key',
default=os.getenv('DISCOURSE_KEY', None),
help='Discourse API key')
parser.add_argument(
'--user',
default=os.getenv('DISCOURSE_KEY', None),
help='Discourse API user')
parser.add_argument(
'--url',
default='http://community.lsst.org',
help='Base URL of the discourse forum')
return parser.parse_args()
if __name__ == '__main__':
main()
<commit_msg>Use SiteFeed to get a category listing<commit_after>
|
# encoding: utf-8
"""
List categories and their IDs in a Discourse forum.
"""
import os
from argparse import ArgumentParser
from community_mailbot.discourse import SiteFeed
def main():
args = parse_args()
site_feed = SiteFeed(args.url, user=args.user, key=args.key)
for c_id, name in site_feed.category_names.items():
print(c_id, name)
def parse_args():
parser = ArgumentParser(description=__doc__)
parser.add_argument(
'--key',
default=os.getenv('DISCOURSE_KEY', None),
help='Discourse API key')
parser.add_argument(
'--user',
default=os.getenv('DISCOURSE_USER', None),
help='Discourse API user')
parser.add_argument(
'--url',
default='http://community.lsst.org',
help='Base URL of the discourse forum')
return parser.parse_args()
if __name__ == '__main__':
main()
|
# encoding: utf-8
"""
List categories and their IDs in a Discourse forum.
"""
import os
from argparse import ArgumentParser
from urllib.parse import urljoin
import requests
def main():
args = parse_args()
params = {}
if args.key is not None:
params['api_key'] = args.key
if args.user is not None:
params['api_username'] = args.user
url = urljoin(args.url, 'site.json')
r = requests.get(url, params=params)
r.raise_for_status()
site_feed = r.json()
for c in site_feed['categories']:
print(c['id'], c['name'])
def parse_args():
parser = ArgumentParser(description=__doc__)
parser.add_argument(
'--key',
default=os.getenv('DISCOURSE_KEY', None),
help='Discourse API key')
parser.add_argument(
'--user',
default=os.getenv('DISCOURSE_KEY', None),
help='Discourse API user')
parser.add_argument(
'--url',
default='http://community.lsst.org',
help='Base URL of the discourse forum')
return parser.parse_args()
if __name__ == '__main__':
main()
Use SiteFeed to get a category listing# encoding: utf-8
"""
List categories and their IDs in a Discourse forum.
"""
import os
from argparse import ArgumentParser
from community_mailbot.discourse import SiteFeed
def main():
args = parse_args()
site_feed = SiteFeed(args.url, user=args.user, key=args.key)
for c_id, name in site_feed.category_names.items():
print(c_id, name)
def parse_args():
parser = ArgumentParser(description=__doc__)
parser.add_argument(
'--key',
default=os.getenv('DISCOURSE_KEY', None),
help='Discourse API key')
parser.add_argument(
'--user',
default=os.getenv('DISCOURSE_USER', None),
help='Discourse API user')
parser.add_argument(
'--url',
default='http://community.lsst.org',
help='Base URL of the discourse forum')
return parser.parse_args()
if __name__ == '__main__':
main()
|
<commit_before># encoding: utf-8
"""
List categories and their IDs in a Discourse forum.
"""
import os
from argparse import ArgumentParser
from urllib.parse import urljoin
import requests
def main():
args = parse_args()
params = {}
if args.key is not None:
params['api_key'] = args.key
if args.user is not None:
params['api_username'] = args.user
url = urljoin(args.url, 'site.json')
r = requests.get(url, params=params)
r.raise_for_status()
site_feed = r.json()
for c in site_feed['categories']:
print(c['id'], c['name'])
def parse_args():
parser = ArgumentParser(description=__doc__)
parser.add_argument(
'--key',
default=os.getenv('DISCOURSE_KEY', None),
help='Discourse API key')
parser.add_argument(
'--user',
default=os.getenv('DISCOURSE_KEY', None),
help='Discourse API user')
parser.add_argument(
'--url',
default='http://community.lsst.org',
help='Base URL of the discourse forum')
return parser.parse_args()
if __name__ == '__main__':
main()
<commit_msg>Use SiteFeed to get a category listing<commit_after># encoding: utf-8
"""
List categories and their IDs in a Discourse forum.
"""
import os
from argparse import ArgumentParser
from community_mailbot.discourse import SiteFeed
def main():
args = parse_args()
site_feed = SiteFeed(args.url, user=args.user, key=args.key)
for c_id, name in site_feed.category_names.items():
print(c_id, name)
def parse_args():
parser = ArgumentParser(description=__doc__)
parser.add_argument(
'--key',
default=os.getenv('DISCOURSE_KEY', None),
help='Discourse API key')
parser.add_argument(
'--user',
default=os.getenv('DISCOURSE_USER', None),
help='Discourse API user')
parser.add_argument(
'--url',
default='http://community.lsst.org',
help='Base URL of the discourse forum')
return parser.parse_args()
if __name__ == '__main__':
main()
|
0668b59d8ec73e80976928706f96922605fe4f67
|
tsserver/models.py
|
tsserver/models.py
|
from tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime)
temperature = db.Column(db.Float)
pressure = db.Column(db.Float)
def __init__(self, timestamp, temperature, pressure):
self.timestamp = timestamp
self.temperature = temperature
self.pressure = pressure
def as_dict(self):
return {'timestamp': datetime_to_str(self.timestamp),
'temperature': self.temperature,
'pressure': self.pressure}
|
from tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
timestamp = db.Column(db.DateTime, primary_key=True)
temperature = db.Column(db.Float)
pressure = db.Column(db.Float)
def __init__(self, timestamp, temperature, pressure):
self.timestamp = timestamp
self.temperature = temperature
self.pressure = pressure
def as_dict(self):
return {'timestamp': datetime_to_str(self.timestamp),
'temperature': self.temperature,
'pressure': self.pressure}
|
Remove integer ID in Telemetry model
|
Remove integer ID in Telemetry model
|
Python
|
mit
|
m4tx/techswarm-server
|
from tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime)
temperature = db.Column(db.Float)
pressure = db.Column(db.Float)
def __init__(self, timestamp, temperature, pressure):
self.timestamp = timestamp
self.temperature = temperature
self.pressure = pressure
def as_dict(self):
return {'timestamp': datetime_to_str(self.timestamp),
'temperature': self.temperature,
'pressure': self.pressure}
Remove integer ID in Telemetry model
|
from tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
timestamp = db.Column(db.DateTime, primary_key=True)
temperature = db.Column(db.Float)
pressure = db.Column(db.Float)
def __init__(self, timestamp, temperature, pressure):
self.timestamp = timestamp
self.temperature = temperature
self.pressure = pressure
def as_dict(self):
return {'timestamp': datetime_to_str(self.timestamp),
'temperature': self.temperature,
'pressure': self.pressure}
|
<commit_before>from tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime)
temperature = db.Column(db.Float)
pressure = db.Column(db.Float)
def __init__(self, timestamp, temperature, pressure):
self.timestamp = timestamp
self.temperature = temperature
self.pressure = pressure
def as_dict(self):
return {'timestamp': datetime_to_str(self.timestamp),
'temperature': self.temperature,
'pressure': self.pressure}
<commit_msg>Remove integer ID in Telemetry model<commit_after>
|
from tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
timestamp = db.Column(db.DateTime, primary_key=True)
temperature = db.Column(db.Float)
pressure = db.Column(db.Float)
def __init__(self, timestamp, temperature, pressure):
self.timestamp = timestamp
self.temperature = temperature
self.pressure = pressure
def as_dict(self):
return {'timestamp': datetime_to_str(self.timestamp),
'temperature': self.temperature,
'pressure': self.pressure}
|
from tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime)
temperature = db.Column(db.Float)
pressure = db.Column(db.Float)
def __init__(self, timestamp, temperature, pressure):
self.timestamp = timestamp
self.temperature = temperature
self.pressure = pressure
def as_dict(self):
return {'timestamp': datetime_to_str(self.timestamp),
'temperature': self.temperature,
'pressure': self.pressure}
Remove integer ID in Telemetry modelfrom tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
timestamp = db.Column(db.DateTime, primary_key=True)
temperature = db.Column(db.Float)
pressure = db.Column(db.Float)
def __init__(self, timestamp, temperature, pressure):
self.timestamp = timestamp
self.temperature = temperature
self.pressure = pressure
def as_dict(self):
return {'timestamp': datetime_to_str(self.timestamp),
'temperature': self.temperature,
'pressure': self.pressure}
|
<commit_before>from tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime)
temperature = db.Column(db.Float)
pressure = db.Column(db.Float)
def __init__(self, timestamp, temperature, pressure):
self.timestamp = timestamp
self.temperature = temperature
self.pressure = pressure
def as_dict(self):
return {'timestamp': datetime_to_str(self.timestamp),
'temperature': self.temperature,
'pressure': self.pressure}
<commit_msg>Remove integer ID in Telemetry model<commit_after>from tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
timestamp = db.Column(db.DateTime, primary_key=True)
temperature = db.Column(db.Float)
pressure = db.Column(db.Float)
def __init__(self, timestamp, temperature, pressure):
self.timestamp = timestamp
self.temperature = temperature
self.pressure = pressure
def as_dict(self):
return {'timestamp': datetime_to_str(self.timestamp),
'temperature': self.temperature,
'pressure': self.pressure}
|
ea180a007c1a5bfaeb56e6b223610876b0619e63
|
webmaster_verification/views.py
|
webmaster_verification/views.py
|
import logging
logger = logging.getLogger(__name__)
from django.http import Http404
from django.views.generic import TemplateView
import settings
class VerificationView(TemplateView):
"""
This simply adds the verification key to the view context and makes sure
we return a 404 if the key wasn't set for the provider
"""
def get_context_data(self, **kwargs):
context = super(VerificationView, self).get_context_data(**kwargs)
try:
context['%s_verification' % self.provider] = settings.WEBMASTER_VERIFICATION[self.provider]
except KeyError:
raise Http404
except AttributeError:
logger.info("WEBMASTER_VERIFICATION not defined in settings")
raise Http404
return context
class GoogleVerificationView(VerificationView):
template_name = 'webmaster_verification/google_verify_template.html'
provider = 'google'
class BingVerificationView(VerificationView):
template_name = 'webmaster_verification/bing_verify_template.xml'
provider = 'bing'
class MajesticVerificationView(VerificationView):
template_name = 'webmaster_verification/majestic_verify_template.txt'
provider = 'majestic'
|
import logging
logger = logging.getLogger(__name__)
from django.http import Http404
from django.views.generic import TemplateView
import settings
class VerificationView(TemplateView):
"""
This simply adds the verification key to the view context and makes sure
we return a 404 if the key wasn't set for the provider
"""
def get_context_data(self, **kwargs):
context = super(VerificationView, self).get_context_data(**kwargs)
try:
context['%s_verification' % self.provider] = settings.WEBMASTER_VERIFICATION[self.provider]
except KeyError:
raise Http404
except AttributeError:
logger.info("WEBMASTER_VERIFICATION not defined in settings")
raise Http404
return context
class VerificationTextView(VerificationView):
"""
Return proper content type
"""
def render_to_response(self, context, **kwargs):
return super(VerificationTextView, self).render_to_response(
context,
content_type='text/plain',
**kwargs
)
class VerificationXMLView(VerificationView):
"""
Return proper content type
"""
def render_to_response(self, context, **kwargs):
return super(VerificationXMLView, self).render_to_response(
context,
content_type='text/xml',
**kwargs
)
class GoogleVerificationView(VerificationView):
template_name = 'webmaster_verification/google_verify_template.html'
provider = 'google'
class BingVerificationView(VerificationXMLView):
template_name = 'webmaster_verification/bing_verify_template.xml'
provider = 'bing'
class MajesticVerificationView(VerificationTextView):
template_name = 'webmaster_verification/majestic_verify_template.txt'
provider = 'majestic'
|
Use proper content-type for all files
|
Use proper content-type for all files
|
Python
|
bsd-3-clause
|
nkuttler/django-webmaster-verification,nkuttler/django-webmaster-verification
|
import logging
logger = logging.getLogger(__name__)
from django.http import Http404
from django.views.generic import TemplateView
import settings
class VerificationView(TemplateView):
"""
This simply adds the verification key to the view context and makes sure
we return a 404 if the key wasn't set for the provider
"""
def get_context_data(self, **kwargs):
context = super(VerificationView, self).get_context_data(**kwargs)
try:
context['%s_verification' % self.provider] = settings.WEBMASTER_VERIFICATION[self.provider]
except KeyError:
raise Http404
except AttributeError:
logger.info("WEBMASTER_VERIFICATION not defined in settings")
raise Http404
return context
class GoogleVerificationView(VerificationView):
template_name = 'webmaster_verification/google_verify_template.html'
provider = 'google'
class BingVerificationView(VerificationView):
template_name = 'webmaster_verification/bing_verify_template.xml'
provider = 'bing'
class MajesticVerificationView(VerificationView):
template_name = 'webmaster_verification/majestic_verify_template.txt'
provider = 'majestic'
Use proper content-type for all files
|
import logging
logger = logging.getLogger(__name__)
from django.http import Http404
from django.views.generic import TemplateView
import settings
class VerificationView(TemplateView):
"""
This simply adds the verification key to the view context and makes sure
we return a 404 if the key wasn't set for the provider
"""
def get_context_data(self, **kwargs):
context = super(VerificationView, self).get_context_data(**kwargs)
try:
context['%s_verification' % self.provider] = settings.WEBMASTER_VERIFICATION[self.provider]
except KeyError:
raise Http404
except AttributeError:
logger.info("WEBMASTER_VERIFICATION not defined in settings")
raise Http404
return context
class VerificationTextView(VerificationView):
"""
Return proper content type
"""
def render_to_response(self, context, **kwargs):
return super(VerificationTextView, self).render_to_response(
context,
content_type='text/plain',
**kwargs
)
class VerificationXMLView(VerificationView):
"""
Return proper content type
"""
def render_to_response(self, context, **kwargs):
return super(VerificationXMLView, self).render_to_response(
context,
content_type='text/xml',
**kwargs
)
class GoogleVerificationView(VerificationView):
template_name = 'webmaster_verification/google_verify_template.html'
provider = 'google'
class BingVerificationView(VerificationXMLView):
template_name = 'webmaster_verification/bing_verify_template.xml'
provider = 'bing'
class MajesticVerificationView(VerificationTextView):
template_name = 'webmaster_verification/majestic_verify_template.txt'
provider = 'majestic'
|
<commit_before>import logging
logger = logging.getLogger(__name__)
from django.http import Http404
from django.views.generic import TemplateView
import settings
class VerificationView(TemplateView):
"""
This simply adds the verification key to the view context and makes sure
we return a 404 if the key wasn't set for the provider
"""
def get_context_data(self, **kwargs):
context = super(VerificationView, self).get_context_data(**kwargs)
try:
context['%s_verification' % self.provider] = settings.WEBMASTER_VERIFICATION[self.provider]
except KeyError:
raise Http404
except AttributeError:
logger.info("WEBMASTER_VERIFICATION not defined in settings")
raise Http404
return context
class GoogleVerificationView(VerificationView):
template_name = 'webmaster_verification/google_verify_template.html'
provider = 'google'
class BingVerificationView(VerificationView):
template_name = 'webmaster_verification/bing_verify_template.xml'
provider = 'bing'
class MajesticVerificationView(VerificationView):
template_name = 'webmaster_verification/majestic_verify_template.txt'
provider = 'majestic'
<commit_msg>Use proper content-type for all files<commit_after>
|
import logging
logger = logging.getLogger(__name__)
from django.http import Http404
from django.views.generic import TemplateView
import settings
class VerificationView(TemplateView):
"""
This simply adds the verification key to the view context and makes sure
we return a 404 if the key wasn't set for the provider
"""
def get_context_data(self, **kwargs):
context = super(VerificationView, self).get_context_data(**kwargs)
try:
context['%s_verification' % self.provider] = settings.WEBMASTER_VERIFICATION[self.provider]
except KeyError:
raise Http404
except AttributeError:
logger.info("WEBMASTER_VERIFICATION not defined in settings")
raise Http404
return context
class VerificationTextView(VerificationView):
"""
Return proper content type
"""
def render_to_response(self, context, **kwargs):
return super(VerificationTextView, self).render_to_response(
context,
content_type='text/plain',
**kwargs
)
class VerificationXMLView(VerificationView):
"""
Return proper content type
"""
def render_to_response(self, context, **kwargs):
return super(VerificationXMLView, self).render_to_response(
context,
content_type='text/xml',
**kwargs
)
class GoogleVerificationView(VerificationView):
template_name = 'webmaster_verification/google_verify_template.html'
provider = 'google'
class BingVerificationView(VerificationXMLView):
template_name = 'webmaster_verification/bing_verify_template.xml'
provider = 'bing'
class MajesticVerificationView(VerificationTextView):
template_name = 'webmaster_verification/majestic_verify_template.txt'
provider = 'majestic'
|
import logging
logger = logging.getLogger(__name__)
from django.http import Http404
from django.views.generic import TemplateView
import settings
class VerificationView(TemplateView):
"""
This simply adds the verification key to the view context and makes sure
we return a 404 if the key wasn't set for the provider
"""
def get_context_data(self, **kwargs):
context = super(VerificationView, self).get_context_data(**kwargs)
try:
context['%s_verification' % self.provider] = settings.WEBMASTER_VERIFICATION[self.provider]
except KeyError:
raise Http404
except AttributeError:
logger.info("WEBMASTER_VERIFICATION not defined in settings")
raise Http404
return context
class GoogleVerificationView(VerificationView):
template_name = 'webmaster_verification/google_verify_template.html'
provider = 'google'
class BingVerificationView(VerificationView):
template_name = 'webmaster_verification/bing_verify_template.xml'
provider = 'bing'
class MajesticVerificationView(VerificationView):
template_name = 'webmaster_verification/majestic_verify_template.txt'
provider = 'majestic'
Use proper content-type for all filesimport logging
logger = logging.getLogger(__name__)
from django.http import Http404
from django.views.generic import TemplateView
import settings
class VerificationView(TemplateView):
"""
This simply adds the verification key to the view context and makes sure
we return a 404 if the key wasn't set for the provider
"""
def get_context_data(self, **kwargs):
context = super(VerificationView, self).get_context_data(**kwargs)
try:
context['%s_verification' % self.provider] = settings.WEBMASTER_VERIFICATION[self.provider]
except KeyError:
raise Http404
except AttributeError:
logger.info("WEBMASTER_VERIFICATION not defined in settings")
raise Http404
return context
class VerificationTextView(VerificationView):
"""
Return proper content type
"""
def render_to_response(self, context, **kwargs):
return super(VerificationTextView, self).render_to_response(
context,
content_type='text/plain',
**kwargs
)
class VerificationXMLView(VerificationView):
"""
Return proper content type
"""
def render_to_response(self, context, **kwargs):
return super(VerificationXMLView, self).render_to_response(
context,
content_type='text/xml',
**kwargs
)
class GoogleVerificationView(VerificationView):
template_name = 'webmaster_verification/google_verify_template.html'
provider = 'google'
class BingVerificationView(VerificationXMLView):
template_name = 'webmaster_verification/bing_verify_template.xml'
provider = 'bing'
class MajesticVerificationView(VerificationTextView):
template_name = 'webmaster_verification/majestic_verify_template.txt'
provider = 'majestic'
|
<commit_before>import logging
logger = logging.getLogger(__name__)
from django.http import Http404
from django.views.generic import TemplateView
import settings
class VerificationView(TemplateView):
"""
This simply adds the verification key to the view context and makes sure
we return a 404 if the key wasn't set for the provider
"""
def get_context_data(self, **kwargs):
context = super(VerificationView, self).get_context_data(**kwargs)
try:
context['%s_verification' % self.provider] = settings.WEBMASTER_VERIFICATION[self.provider]
except KeyError:
raise Http404
except AttributeError:
logger.info("WEBMASTER_VERIFICATION not defined in settings")
raise Http404
return context
class GoogleVerificationView(VerificationView):
template_name = 'webmaster_verification/google_verify_template.html'
provider = 'google'
class BingVerificationView(VerificationView):
template_name = 'webmaster_verification/bing_verify_template.xml'
provider = 'bing'
class MajesticVerificationView(VerificationView):
template_name = 'webmaster_verification/majestic_verify_template.txt'
provider = 'majestic'
<commit_msg>Use proper content-type for all files<commit_after>import logging
logger = logging.getLogger(__name__)
from django.http import Http404
from django.views.generic import TemplateView
import settings
class VerificationView(TemplateView):
"""
This simply adds the verification key to the view context and makes sure
we return a 404 if the key wasn't set for the provider
"""
def get_context_data(self, **kwargs):
context = super(VerificationView, self).get_context_data(**kwargs)
try:
context['%s_verification' % self.provider] = settings.WEBMASTER_VERIFICATION[self.provider]
except KeyError:
raise Http404
except AttributeError:
logger.info("WEBMASTER_VERIFICATION not defined in settings")
raise Http404
return context
class VerificationTextView(VerificationView):
"""
Return proper content type
"""
def render_to_response(self, context, **kwargs):
return super(VerificationTextView, self).render_to_response(
context,
content_type='text/plain',
**kwargs
)
class VerificationXMLView(VerificationView):
"""
Return proper content type
"""
def render_to_response(self, context, **kwargs):
return super(VerificationXMLView, self).render_to_response(
context,
content_type='text/xml',
**kwargs
)
class GoogleVerificationView(VerificationView):
template_name = 'webmaster_verification/google_verify_template.html'
provider = 'google'
class BingVerificationView(VerificationXMLView):
template_name = 'webmaster_verification/bing_verify_template.xml'
provider = 'bing'
class MajesticVerificationView(VerificationTextView):
template_name = 'webmaster_verification/majestic_verify_template.txt'
provider = 'majestic'
|
d84e8b60b0c619feaf529d4ab1eb53ef9e21aae5
|
lingcod/bookmarks/forms.py
|
lingcod/bookmarks/forms.py
|
from lingcod.features.forms import FeatureForm
from lingcod.bookmarks.models import Bookmark
from django import forms
class BookmarkForm(FeatureForm):
name = forms.CharField(label='Bookmark Name')
latitude = forms.FloatField(widget=forms.HiddenInput())
longitude = forms.FloatField(widget=forms.HiddenInput())
altitude = forms.FloatField(widget=forms.HiddenInput())
heading = forms.FloatField(widget=forms.HiddenInput())
tilt = forms.FloatField(widget=forms.HiddenInput())
roll = forms.FloatField(widget=forms.HiddenInput())
altitudeMode = forms.FloatField(widget=forms.HiddenInput())
publicstate = forms.CharField(widget=forms.HiddenInput())
ip = forms.CharField(widget=forms.HiddenInput())
class Meta(FeatureForm.Meta):
model = Bookmark
|
from lingcod.features.forms import FeatureForm
from lingcod.bookmarks.models import Bookmark
from django import forms
class BookmarkForm(FeatureForm):
name = forms.CharField(label='Bookmark Name')
latitude = forms.FloatField(widget=forms.HiddenInput())
longitude = forms.FloatField(widget=forms.HiddenInput())
altitude = forms.FloatField(widget=forms.HiddenInput())
heading = forms.FloatField(widget=forms.HiddenInput())
tilt = forms.FloatField(widget=forms.HiddenInput())
roll = forms.FloatField(widget=forms.HiddenInput())
altitudeMode = forms.FloatField(widget=forms.HiddenInput())
publicstate = forms.CharField(widget=forms.HiddenInput())
ip = forms.CharField(widget=forms.HiddenInput(), required=False)
class Meta(FeatureForm.Meta):
model = Bookmark
|
Allow IP to be blank in form
|
Allow IP to be blank in form
|
Python
|
bsd-3-clause
|
Ecotrust/madrona_addons,Ecotrust/madrona_addons
|
from lingcod.features.forms import FeatureForm
from lingcod.bookmarks.models import Bookmark
from django import forms
class BookmarkForm(FeatureForm):
name = forms.CharField(label='Bookmark Name')
latitude = forms.FloatField(widget=forms.HiddenInput())
longitude = forms.FloatField(widget=forms.HiddenInput())
altitude = forms.FloatField(widget=forms.HiddenInput())
heading = forms.FloatField(widget=forms.HiddenInput())
tilt = forms.FloatField(widget=forms.HiddenInput())
roll = forms.FloatField(widget=forms.HiddenInput())
altitudeMode = forms.FloatField(widget=forms.HiddenInput())
publicstate = forms.CharField(widget=forms.HiddenInput())
ip = forms.CharField(widget=forms.HiddenInput())
class Meta(FeatureForm.Meta):
model = Bookmark
Allow IP to be blank in form
|
from lingcod.features.forms import FeatureForm
from lingcod.bookmarks.models import Bookmark
from django import forms
class BookmarkForm(FeatureForm):
name = forms.CharField(label='Bookmark Name')
latitude = forms.FloatField(widget=forms.HiddenInput())
longitude = forms.FloatField(widget=forms.HiddenInput())
altitude = forms.FloatField(widget=forms.HiddenInput())
heading = forms.FloatField(widget=forms.HiddenInput())
tilt = forms.FloatField(widget=forms.HiddenInput())
roll = forms.FloatField(widget=forms.HiddenInput())
altitudeMode = forms.FloatField(widget=forms.HiddenInput())
publicstate = forms.CharField(widget=forms.HiddenInput())
ip = forms.CharField(widget=forms.HiddenInput(), required=False)
class Meta(FeatureForm.Meta):
model = Bookmark
|
<commit_before>from lingcod.features.forms import FeatureForm
from lingcod.bookmarks.models import Bookmark
from django import forms
class BookmarkForm(FeatureForm):
name = forms.CharField(label='Bookmark Name')
latitude = forms.FloatField(widget=forms.HiddenInput())
longitude = forms.FloatField(widget=forms.HiddenInput())
altitude = forms.FloatField(widget=forms.HiddenInput())
heading = forms.FloatField(widget=forms.HiddenInput())
tilt = forms.FloatField(widget=forms.HiddenInput())
roll = forms.FloatField(widget=forms.HiddenInput())
altitudeMode = forms.FloatField(widget=forms.HiddenInput())
publicstate = forms.CharField(widget=forms.HiddenInput())
ip = forms.CharField(widget=forms.HiddenInput())
class Meta(FeatureForm.Meta):
model = Bookmark
<commit_msg>Allow IP to be blank in form<commit_after>
|
from lingcod.features.forms import FeatureForm
from lingcod.bookmarks.models import Bookmark
from django import forms
class BookmarkForm(FeatureForm):
name = forms.CharField(label='Bookmark Name')
latitude = forms.FloatField(widget=forms.HiddenInput())
longitude = forms.FloatField(widget=forms.HiddenInput())
altitude = forms.FloatField(widget=forms.HiddenInput())
heading = forms.FloatField(widget=forms.HiddenInput())
tilt = forms.FloatField(widget=forms.HiddenInput())
roll = forms.FloatField(widget=forms.HiddenInput())
altitudeMode = forms.FloatField(widget=forms.HiddenInput())
publicstate = forms.CharField(widget=forms.HiddenInput())
ip = forms.CharField(widget=forms.HiddenInput(), required=False)
class Meta(FeatureForm.Meta):
model = Bookmark
|
from lingcod.features.forms import FeatureForm
from lingcod.bookmarks.models import Bookmark
from django import forms
class BookmarkForm(FeatureForm):
name = forms.CharField(label='Bookmark Name')
latitude = forms.FloatField(widget=forms.HiddenInput())
longitude = forms.FloatField(widget=forms.HiddenInput())
altitude = forms.FloatField(widget=forms.HiddenInput())
heading = forms.FloatField(widget=forms.HiddenInput())
tilt = forms.FloatField(widget=forms.HiddenInput())
roll = forms.FloatField(widget=forms.HiddenInput())
altitudeMode = forms.FloatField(widget=forms.HiddenInput())
publicstate = forms.CharField(widget=forms.HiddenInput())
ip = forms.CharField(widget=forms.HiddenInput())
class Meta(FeatureForm.Meta):
model = Bookmark
Allow IP to be blank in formfrom lingcod.features.forms import FeatureForm
from lingcod.bookmarks.models import Bookmark
from django import forms
class BookmarkForm(FeatureForm):
name = forms.CharField(label='Bookmark Name')
latitude = forms.FloatField(widget=forms.HiddenInput())
longitude = forms.FloatField(widget=forms.HiddenInput())
altitude = forms.FloatField(widget=forms.HiddenInput())
heading = forms.FloatField(widget=forms.HiddenInput())
tilt = forms.FloatField(widget=forms.HiddenInput())
roll = forms.FloatField(widget=forms.HiddenInput())
altitudeMode = forms.FloatField(widget=forms.HiddenInput())
publicstate = forms.CharField(widget=forms.HiddenInput())
ip = forms.CharField(widget=forms.HiddenInput(), required=False)
class Meta(FeatureForm.Meta):
model = Bookmark
|
<commit_before>from lingcod.features.forms import FeatureForm
from lingcod.bookmarks.models import Bookmark
from django import forms
class BookmarkForm(FeatureForm):
name = forms.CharField(label='Bookmark Name')
latitude = forms.FloatField(widget=forms.HiddenInput())
longitude = forms.FloatField(widget=forms.HiddenInput())
altitude = forms.FloatField(widget=forms.HiddenInput())
heading = forms.FloatField(widget=forms.HiddenInput())
tilt = forms.FloatField(widget=forms.HiddenInput())
roll = forms.FloatField(widget=forms.HiddenInput())
altitudeMode = forms.FloatField(widget=forms.HiddenInput())
publicstate = forms.CharField(widget=forms.HiddenInput())
ip = forms.CharField(widget=forms.HiddenInput())
class Meta(FeatureForm.Meta):
model = Bookmark
<commit_msg>Allow IP to be blank in form<commit_after>from lingcod.features.forms import FeatureForm
from lingcod.bookmarks.models import Bookmark
from django import forms
class BookmarkForm(FeatureForm):
name = forms.CharField(label='Bookmark Name')
latitude = forms.FloatField(widget=forms.HiddenInput())
longitude = forms.FloatField(widget=forms.HiddenInput())
altitude = forms.FloatField(widget=forms.HiddenInput())
heading = forms.FloatField(widget=forms.HiddenInput())
tilt = forms.FloatField(widget=forms.HiddenInput())
roll = forms.FloatField(widget=forms.HiddenInput())
altitudeMode = forms.FloatField(widget=forms.HiddenInput())
publicstate = forms.CharField(widget=forms.HiddenInput())
ip = forms.CharField(widget=forms.HiddenInput(), required=False)
class Meta(FeatureForm.Meta):
model = Bookmark
|
97f81ddfdd78d062e5019793101926fb52b0db38
|
sum.py
|
sum.py
|
import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
new_view = self.view.window().new_file()
new_view.set_name('Sum')
new_view.insert(edit, 0, '42')
new_view.set_scratch(True)
|
import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
new_view = self.view.window().new_file()
new_view.set_name('Sum')
new_view.insert(edit, 0, '42')
new_view.set_read_only(True)
new_view.set_scratch(True)
|
Set new file to read-only
|
Set new file to read-only
Since the new file does not prompt about file changes when closed, if
the user were to edit the new file and close without saving, their
changes would be lost forever. By setting the new file to be read-only,
the user will not be able to make changes to it that may be lost.
|
Python
|
mit
|
jbrudvik/sublime-sum,jbrudvik/sublime-sum
|
import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
new_view = self.view.window().new_file()
new_view.set_name('Sum')
new_view.insert(edit, 0, '42')
new_view.set_scratch(True)
Set new file to read-only
Since the new file does not prompt about file changes when closed, if
the user were to edit the new file and close without saving, their
changes would be lost forever. By setting the new file to be read-only,
the user will not be able to make changes to it that may be lost.
|
import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
new_view = self.view.window().new_file()
new_view.set_name('Sum')
new_view.insert(edit, 0, '42')
new_view.set_read_only(True)
new_view.set_scratch(True)
|
<commit_before>import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
new_view = self.view.window().new_file()
new_view.set_name('Sum')
new_view.insert(edit, 0, '42')
new_view.set_scratch(True)
<commit_msg>Set new file to read-only
Since the new file does not prompt about file changes when closed, if
the user were to edit the new file and close without saving, their
changes would be lost forever. By setting the new file to be read-only,
the user will not be able to make changes to it that may be lost.<commit_after>
|
import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
new_view = self.view.window().new_file()
new_view.set_name('Sum')
new_view.insert(edit, 0, '42')
new_view.set_read_only(True)
new_view.set_scratch(True)
|
import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
new_view = self.view.window().new_file()
new_view.set_name('Sum')
new_view.insert(edit, 0, '42')
new_view.set_scratch(True)
Set new file to read-only
Since the new file does not prompt about file changes when closed, if
the user were to edit the new file and close without saving, their
changes would be lost forever. By setting the new file to be read-only,
the user will not be able to make changes to it that may be lost.import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
new_view = self.view.window().new_file()
new_view.set_name('Sum')
new_view.insert(edit, 0, '42')
new_view.set_read_only(True)
new_view.set_scratch(True)
|
<commit_before>import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
new_view = self.view.window().new_file()
new_view.set_name('Sum')
new_view.insert(edit, 0, '42')
new_view.set_scratch(True)
<commit_msg>Set new file to read-only
Since the new file does not prompt about file changes when closed, if
the user were to edit the new file and close without saving, their
changes would be lost forever. By setting the new file to be read-only,
the user will not be able to make changes to it that may be lost.<commit_after>import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
new_view = self.view.window().new_file()
new_view.set_name('Sum')
new_view.insert(edit, 0, '42')
new_view.set_read_only(True)
new_view.set_scratch(True)
|
767471a5067198b810d8477abcf11da891930581
|
polemarch/__init__.py
|
polemarch/__init__.py
|
'''
### Polemarch is ansible based service for orchestration infrastructure.
* [Documentation](http://polemarch.readthedocs.io/)
* [Issue Tracker](https://gitlab.com/vstconsulting/polemarch/issues)
* [Source Code](https://gitlab.com/vstconsulting/polemarch)
'''
import os
import warnings
try:
from vstutils.environment import prepare_environment, cmd_execution
except ImportError:
warnings.warn('"vstutils" was not installed', ImportWarning)
prepare_environment = lambda *args, **kwargs: ()
cmd_execution = prepare_environment
default_settings = {
# ansible specific environment variables
"ANSIBLE_HOST_KEY_CHECKING": 'False',
"ANSIBLE_FORCE_COLOR": "true",
# celery specific
"C_FORCE_ROOT": "true",
# django settings module
"DJANGO_SETTINGS_MODULE": os.getenv(
"DJANGO_SETTINGS_MODULE", 'polemarch.main.settings'
),
# VSTUTILS settings
"VST_PROJECT": os.getenv("VST_PROJECT", 'polemarch'),
"VST_ROOT_URLCONF": os.getenv("VST_ROOT_URLCONF", 'vstutils.urls'),
}
__version__ = "1.4.4"
prepare_environment(**default_settings)
|
'''
### Polemarch is ansible based service for orchestration infrastructure.
* [Documentation](http://polemarch.readthedocs.io/)
* [Issue Tracker](https://gitlab.com/vstconsulting/polemarch/issues)
* [Source Code](https://gitlab.com/vstconsulting/polemarch)
'''
import os
import warnings
try:
from vstutils.environment import prepare_environment, cmd_execution
except ImportError:
warnings.warn('"vstutils" was not installed', ImportWarning)
prepare_environment = lambda *args, **kwargs: ()
cmd_execution = prepare_environment
default_settings = {
# ansible specific environment variables
"ANSIBLE_HOST_KEY_CHECKING": 'False',
"ANSIBLE_FORCE_COLOR": "true",
# celery specific
"C_FORCE_ROOT": "true",
# django settings module
"DJANGO_SETTINGS_MODULE": os.getenv(
"DJANGO_SETTINGS_MODULE", 'polemarch.main.settings'
),
# VSTUTILS settings
"VST_PROJECT": os.getenv("VST_PROJECT", 'polemarch'),
"VST_ROOT_URLCONF": os.getenv("VST_ROOT_URLCONF", 'vstutils.urls'),
}
__version__ = "1.4.5"
prepare_environment(**default_settings)
|
Update PM version to 1.4.5
|
Update PM version to 1.4.5
|
Python
|
agpl-3.0
|
vstconsulting/polemarch,vstconsulting/polemarch,vstconsulting/polemarch,vstconsulting/polemarch
|
'''
### Polemarch is ansible based service for orchestration infrastructure.
* [Documentation](http://polemarch.readthedocs.io/)
* [Issue Tracker](https://gitlab.com/vstconsulting/polemarch/issues)
* [Source Code](https://gitlab.com/vstconsulting/polemarch)
'''
import os
import warnings
try:
from vstutils.environment import prepare_environment, cmd_execution
except ImportError:
warnings.warn('"vstutils" was not installed', ImportWarning)
prepare_environment = lambda *args, **kwargs: ()
cmd_execution = prepare_environment
default_settings = {
# ansible specific environment variables
"ANSIBLE_HOST_KEY_CHECKING": 'False',
"ANSIBLE_FORCE_COLOR": "true",
# celery specific
"C_FORCE_ROOT": "true",
# django settings module
"DJANGO_SETTINGS_MODULE": os.getenv(
"DJANGO_SETTINGS_MODULE", 'polemarch.main.settings'
),
# VSTUTILS settings
"VST_PROJECT": os.getenv("VST_PROJECT", 'polemarch'),
"VST_ROOT_URLCONF": os.getenv("VST_ROOT_URLCONF", 'vstutils.urls'),
}
__version__ = "1.4.4"
prepare_environment(**default_settings)
Update PM version to 1.4.5
|
'''
### Polemarch is ansible based service for orchestration infrastructure.
* [Documentation](http://polemarch.readthedocs.io/)
* [Issue Tracker](https://gitlab.com/vstconsulting/polemarch/issues)
* [Source Code](https://gitlab.com/vstconsulting/polemarch)
'''
import os
import warnings
try:
from vstutils.environment import prepare_environment, cmd_execution
except ImportError:
warnings.warn('"vstutils" was not installed', ImportWarning)
prepare_environment = lambda *args, **kwargs: ()
cmd_execution = prepare_environment
default_settings = {
# ansible specific environment variables
"ANSIBLE_HOST_KEY_CHECKING": 'False',
"ANSIBLE_FORCE_COLOR": "true",
# celery specific
"C_FORCE_ROOT": "true",
# django settings module
"DJANGO_SETTINGS_MODULE": os.getenv(
"DJANGO_SETTINGS_MODULE", 'polemarch.main.settings'
),
# VSTUTILS settings
"VST_PROJECT": os.getenv("VST_PROJECT", 'polemarch'),
"VST_ROOT_URLCONF": os.getenv("VST_ROOT_URLCONF", 'vstutils.urls'),
}
__version__ = "1.4.5"
prepare_environment(**default_settings)
|
<commit_before>'''
### Polemarch is ansible based service for orchestration infrastructure.
* [Documentation](http://polemarch.readthedocs.io/)
* [Issue Tracker](https://gitlab.com/vstconsulting/polemarch/issues)
* [Source Code](https://gitlab.com/vstconsulting/polemarch)
'''
import os
import warnings
try:
from vstutils.environment import prepare_environment, cmd_execution
except ImportError:
warnings.warn('"vstutils" was not installed', ImportWarning)
prepare_environment = lambda *args, **kwargs: ()
cmd_execution = prepare_environment
default_settings = {
# ansible specific environment variables
"ANSIBLE_HOST_KEY_CHECKING": 'False',
"ANSIBLE_FORCE_COLOR": "true",
# celery specific
"C_FORCE_ROOT": "true",
# django settings module
"DJANGO_SETTINGS_MODULE": os.getenv(
"DJANGO_SETTINGS_MODULE", 'polemarch.main.settings'
),
# VSTUTILS settings
"VST_PROJECT": os.getenv("VST_PROJECT", 'polemarch'),
"VST_ROOT_URLCONF": os.getenv("VST_ROOT_URLCONF", 'vstutils.urls'),
}
__version__ = "1.4.4"
prepare_environment(**default_settings)
<commit_msg>Update PM version to 1.4.5<commit_after>
|
'''
### Polemarch is ansible based service for orchestration infrastructure.
* [Documentation](http://polemarch.readthedocs.io/)
* [Issue Tracker](https://gitlab.com/vstconsulting/polemarch/issues)
* [Source Code](https://gitlab.com/vstconsulting/polemarch)
'''
import os
import warnings
try:
from vstutils.environment import prepare_environment, cmd_execution
except ImportError:
warnings.warn('"vstutils" was not installed', ImportWarning)
prepare_environment = lambda *args, **kwargs: ()
cmd_execution = prepare_environment
default_settings = {
# ansible specific environment variables
"ANSIBLE_HOST_KEY_CHECKING": 'False',
"ANSIBLE_FORCE_COLOR": "true",
# celery specific
"C_FORCE_ROOT": "true",
# django settings module
"DJANGO_SETTINGS_MODULE": os.getenv(
"DJANGO_SETTINGS_MODULE", 'polemarch.main.settings'
),
# VSTUTILS settings
"VST_PROJECT": os.getenv("VST_PROJECT", 'polemarch'),
"VST_ROOT_URLCONF": os.getenv("VST_ROOT_URLCONF", 'vstutils.urls'),
}
__version__ = "1.4.5"
prepare_environment(**default_settings)
|
'''
### Polemarch is ansible based service for orchestration infrastructure.
* [Documentation](http://polemarch.readthedocs.io/)
* [Issue Tracker](https://gitlab.com/vstconsulting/polemarch/issues)
* [Source Code](https://gitlab.com/vstconsulting/polemarch)
'''
import os
import warnings
try:
from vstutils.environment import prepare_environment, cmd_execution
except ImportError:
warnings.warn('"vstutils" was not installed', ImportWarning)
prepare_environment = lambda *args, **kwargs: ()
cmd_execution = prepare_environment
default_settings = {
# ansible specific environment variables
"ANSIBLE_HOST_KEY_CHECKING": 'False',
"ANSIBLE_FORCE_COLOR": "true",
# celery specific
"C_FORCE_ROOT": "true",
# django settings module
"DJANGO_SETTINGS_MODULE": os.getenv(
"DJANGO_SETTINGS_MODULE", 'polemarch.main.settings'
),
# VSTUTILS settings
"VST_PROJECT": os.getenv("VST_PROJECT", 'polemarch'),
"VST_ROOT_URLCONF": os.getenv("VST_ROOT_URLCONF", 'vstutils.urls'),
}
__version__ = "1.4.4"
prepare_environment(**default_settings)
Update PM version to 1.4.5'''
### Polemarch is ansible based service for orchestration infrastructure.
* [Documentation](http://polemarch.readthedocs.io/)
* [Issue Tracker](https://gitlab.com/vstconsulting/polemarch/issues)
* [Source Code](https://gitlab.com/vstconsulting/polemarch)
'''
import os
import warnings
try:
from vstutils.environment import prepare_environment, cmd_execution
except ImportError:
warnings.warn('"vstutils" was not installed', ImportWarning)
prepare_environment = lambda *args, **kwargs: ()
cmd_execution = prepare_environment
default_settings = {
# ansible specific environment variables
"ANSIBLE_HOST_KEY_CHECKING": 'False',
"ANSIBLE_FORCE_COLOR": "true",
# celery specific
"C_FORCE_ROOT": "true",
# django settings module
"DJANGO_SETTINGS_MODULE": os.getenv(
"DJANGO_SETTINGS_MODULE", 'polemarch.main.settings'
),
# VSTUTILS settings
"VST_PROJECT": os.getenv("VST_PROJECT", 'polemarch'),
"VST_ROOT_URLCONF": os.getenv("VST_ROOT_URLCONF", 'vstutils.urls'),
}
__version__ = "1.4.5"
prepare_environment(**default_settings)
|
<commit_before>'''
### Polemarch is ansible based service for orchestration infrastructure.
* [Documentation](http://polemarch.readthedocs.io/)
* [Issue Tracker](https://gitlab.com/vstconsulting/polemarch/issues)
* [Source Code](https://gitlab.com/vstconsulting/polemarch)
'''
import os
import warnings
try:
from vstutils.environment import prepare_environment, cmd_execution
except ImportError:
warnings.warn('"vstutils" was not installed', ImportWarning)
prepare_environment = lambda *args, **kwargs: ()
cmd_execution = prepare_environment
default_settings = {
# ansible specific environment variables
"ANSIBLE_HOST_KEY_CHECKING": 'False',
"ANSIBLE_FORCE_COLOR": "true",
# celery specific
"C_FORCE_ROOT": "true",
# django settings module
"DJANGO_SETTINGS_MODULE": os.getenv(
"DJANGO_SETTINGS_MODULE", 'polemarch.main.settings'
),
# VSTUTILS settings
"VST_PROJECT": os.getenv("VST_PROJECT", 'polemarch'),
"VST_ROOT_URLCONF": os.getenv("VST_ROOT_URLCONF", 'vstutils.urls'),
}
__version__ = "1.4.4"
prepare_environment(**default_settings)
<commit_msg>Update PM version to 1.4.5<commit_after>'''
### Polemarch is ansible based service for orchestration infrastructure.
* [Documentation](http://polemarch.readthedocs.io/)
* [Issue Tracker](https://gitlab.com/vstconsulting/polemarch/issues)
* [Source Code](https://gitlab.com/vstconsulting/polemarch)
'''
import os
import warnings
try:
from vstutils.environment import prepare_environment, cmd_execution
except ImportError:
warnings.warn('"vstutils" was not installed', ImportWarning)
prepare_environment = lambda *args, **kwargs: ()
cmd_execution = prepare_environment
default_settings = {
# ansible specific environment variables
"ANSIBLE_HOST_KEY_CHECKING": 'False',
"ANSIBLE_FORCE_COLOR": "true",
# celery specific
"C_FORCE_ROOT": "true",
# django settings module
"DJANGO_SETTINGS_MODULE": os.getenv(
"DJANGO_SETTINGS_MODULE", 'polemarch.main.settings'
),
# VSTUTILS settings
"VST_PROJECT": os.getenv("VST_PROJECT", 'polemarch'),
"VST_ROOT_URLCONF": os.getenv("VST_ROOT_URLCONF", 'vstutils.urls'),
}
__version__ = "1.4.5"
prepare_environment(**default_settings)
|
c36718dfb0ec25427a5c5c1c42945da1b757924d
|
topaz/modules/ffi/function.py
|
topaz/modules/ffi/function.py
|
from topaz.objects.objectobject import W_Object
from topaz.module import ClassDef
from topaz.modules.ffi.type import W_TypeObject
from topaz.error import RubyError
from topaz.coerce import Coerce
class W_FunctionObject(W_Object):
classdef = ClassDef('Function', W_Object.classdef)
@classdef.singleton_method('allocate')
def singleton_method_allocate(self, space, args_w):
return W_FunctionObject(space)
@classdef.method('initialize')
def method_initialize(self, space, w_ret_type, w_arg_types, w_function, w_options):
if not space.is_kind_of(w_ret_type, space.getclassfor(W_TypeObject)):
try:
sym = Coerce.symbol(space, w_ret_type)
if sym.upper() in W_TypeObject.basics:
# code for string object
pass
else:
raise space.error(space.w_TypeError,
"can't convert Symbol into Type")
except RubyError:
tp = w_ret_type.getclass(space).name
raise space.error(space.w_TypeError,
"can't convert %s into Type" % tp)
# code for type object
|
from topaz.objects.objectobject import W_Object
from topaz.module import ClassDef
from topaz.modules.ffi.type import W_TypeObject
from topaz.error import RubyError
from topaz.coerce import Coerce
class W_FunctionObject(W_Object):
classdef = ClassDef('Function', W_Object.classdef)
@classdef.singleton_method('allocate')
def singleton_method_allocate(self, space, args_w):
return W_FunctionObject(space)
@classdef.method('initialize')
def method_initialize(self, space, w_ret_type, w_arg_types, w_function, w_options):
ret_type = self.type_unwrap(space, w_ret_type)
arg_types = [self.type_unwrap(space, w_type)
for w_type in space.listview(w_arg_types)]
# code for type object
def type_unwrap(self, space, w_type):
if space.is_kind_of(w_type, space.getclassfor(W_TypeObject)):
return self
try:
sym = Coerce.symbol(space, w_type)
key = sym.upper()
if key in W_TypeObject.basics:
return W_TypeObject.basics[key]
else:
raise space.error(space.w_TypeError,
"can't convert Symbol into Type")
except RubyError:
tp = w_type.getclass(space).name
raise space.error(space.w_TypeError,
"can't convert %s into Type" % tp)
|
Put the type unwrapping into a separat method
|
Put the type unwrapping into a separat method
|
Python
|
bsd-3-clause
|
babelsberg/babelsberg-r,topazproject/topaz,babelsberg/babelsberg-r,topazproject/topaz,babelsberg/babelsberg-r,babelsberg/babelsberg-r,babelsberg/babelsberg-r,topazproject/topaz,topazproject/topaz
|
from topaz.objects.objectobject import W_Object
from topaz.module import ClassDef
from topaz.modules.ffi.type import W_TypeObject
from topaz.error import RubyError
from topaz.coerce import Coerce
class W_FunctionObject(W_Object):
classdef = ClassDef('Function', W_Object.classdef)
@classdef.singleton_method('allocate')
def singleton_method_allocate(self, space, args_w):
return W_FunctionObject(space)
@classdef.method('initialize')
def method_initialize(self, space, w_ret_type, w_arg_types, w_function, w_options):
if not space.is_kind_of(w_ret_type, space.getclassfor(W_TypeObject)):
try:
sym = Coerce.symbol(space, w_ret_type)
if sym.upper() in W_TypeObject.basics:
# code for string object
pass
else:
raise space.error(space.w_TypeError,
"can't convert Symbol into Type")
except RubyError:
tp = w_ret_type.getclass(space).name
raise space.error(space.w_TypeError,
"can't convert %s into Type" % tp)
# code for type object
Put the type unwrapping into a separat method
|
from topaz.objects.objectobject import W_Object
from topaz.module import ClassDef
from topaz.modules.ffi.type import W_TypeObject
from topaz.error import RubyError
from topaz.coerce import Coerce
class W_FunctionObject(W_Object):
classdef = ClassDef('Function', W_Object.classdef)
@classdef.singleton_method('allocate')
def singleton_method_allocate(self, space, args_w):
return W_FunctionObject(space)
@classdef.method('initialize')
def method_initialize(self, space, w_ret_type, w_arg_types, w_function, w_options):
ret_type = self.type_unwrap(space, w_ret_type)
arg_types = [self.type_unwrap(space, w_type)
for w_type in space.listview(w_arg_types)]
# code for type object
def type_unwrap(self, space, w_type):
if space.is_kind_of(w_type, space.getclassfor(W_TypeObject)):
return self
try:
sym = Coerce.symbol(space, w_type)
key = sym.upper()
if key in W_TypeObject.basics:
return W_TypeObject.basics[key]
else:
raise space.error(space.w_TypeError,
"can't convert Symbol into Type")
except RubyError:
tp = w_type.getclass(space).name
raise space.error(space.w_TypeError,
"can't convert %s into Type" % tp)
|
<commit_before>from topaz.objects.objectobject import W_Object
from topaz.module import ClassDef
from topaz.modules.ffi.type import W_TypeObject
from topaz.error import RubyError
from topaz.coerce import Coerce
class W_FunctionObject(W_Object):
classdef = ClassDef('Function', W_Object.classdef)
@classdef.singleton_method('allocate')
def singleton_method_allocate(self, space, args_w):
return W_FunctionObject(space)
@classdef.method('initialize')
def method_initialize(self, space, w_ret_type, w_arg_types, w_function, w_options):
if not space.is_kind_of(w_ret_type, space.getclassfor(W_TypeObject)):
try:
sym = Coerce.symbol(space, w_ret_type)
if sym.upper() in W_TypeObject.basics:
# code for string object
pass
else:
raise space.error(space.w_TypeError,
"can't convert Symbol into Type")
except RubyError:
tp = w_ret_type.getclass(space).name
raise space.error(space.w_TypeError,
"can't convert %s into Type" % tp)
# code for type object
<commit_msg>Put the type unwrapping into a separat method<commit_after>
|
from topaz.objects.objectobject import W_Object
from topaz.module import ClassDef
from topaz.modules.ffi.type import W_TypeObject
from topaz.error import RubyError
from topaz.coerce import Coerce
class W_FunctionObject(W_Object):
classdef = ClassDef('Function', W_Object.classdef)
@classdef.singleton_method('allocate')
def singleton_method_allocate(self, space, args_w):
return W_FunctionObject(space)
@classdef.method('initialize')
def method_initialize(self, space, w_ret_type, w_arg_types, w_function, w_options):
ret_type = self.type_unwrap(space, w_ret_type)
arg_types = [self.type_unwrap(space, w_type)
for w_type in space.listview(w_arg_types)]
# code for type object
def type_unwrap(self, space, w_type):
if space.is_kind_of(w_type, space.getclassfor(W_TypeObject)):
return self
try:
sym = Coerce.symbol(space, w_type)
key = sym.upper()
if key in W_TypeObject.basics:
return W_TypeObject.basics[key]
else:
raise space.error(space.w_TypeError,
"can't convert Symbol into Type")
except RubyError:
tp = w_type.getclass(space).name
raise space.error(space.w_TypeError,
"can't convert %s into Type" % tp)
|
from topaz.objects.objectobject import W_Object
from topaz.module import ClassDef
from topaz.modules.ffi.type import W_TypeObject
from topaz.error import RubyError
from topaz.coerce import Coerce
class W_FunctionObject(W_Object):
classdef = ClassDef('Function', W_Object.classdef)
@classdef.singleton_method('allocate')
def singleton_method_allocate(self, space, args_w):
return W_FunctionObject(space)
@classdef.method('initialize')
def method_initialize(self, space, w_ret_type, w_arg_types, w_function, w_options):
if not space.is_kind_of(w_ret_type, space.getclassfor(W_TypeObject)):
try:
sym = Coerce.symbol(space, w_ret_type)
if sym.upper() in W_TypeObject.basics:
# code for string object
pass
else:
raise space.error(space.w_TypeError,
"can't convert Symbol into Type")
except RubyError:
tp = w_ret_type.getclass(space).name
raise space.error(space.w_TypeError,
"can't convert %s into Type" % tp)
# code for type object
Put the type unwrapping into a separat methodfrom topaz.objects.objectobject import W_Object
from topaz.module import ClassDef
from topaz.modules.ffi.type import W_TypeObject
from topaz.error import RubyError
from topaz.coerce import Coerce
class W_FunctionObject(W_Object):
classdef = ClassDef('Function', W_Object.classdef)
@classdef.singleton_method('allocate')
def singleton_method_allocate(self, space, args_w):
return W_FunctionObject(space)
@classdef.method('initialize')
def method_initialize(self, space, w_ret_type, w_arg_types, w_function, w_options):
ret_type = self.type_unwrap(space, w_ret_type)
arg_types = [self.type_unwrap(space, w_type)
for w_type in space.listview(w_arg_types)]
# code for type object
def type_unwrap(self, space, w_type):
if space.is_kind_of(w_type, space.getclassfor(W_TypeObject)):
return self
try:
sym = Coerce.symbol(space, w_type)
key = sym.upper()
if key in W_TypeObject.basics:
return W_TypeObject.basics[key]
else:
raise space.error(space.w_TypeError,
"can't convert Symbol into Type")
except RubyError:
tp = w_type.getclass(space).name
raise space.error(space.w_TypeError,
"can't convert %s into Type" % tp)
|
<commit_before>from topaz.objects.objectobject import W_Object
from topaz.module import ClassDef
from topaz.modules.ffi.type import W_TypeObject
from topaz.error import RubyError
from topaz.coerce import Coerce
class W_FunctionObject(W_Object):
classdef = ClassDef('Function', W_Object.classdef)
@classdef.singleton_method('allocate')
def singleton_method_allocate(self, space, args_w):
return W_FunctionObject(space)
@classdef.method('initialize')
def method_initialize(self, space, w_ret_type, w_arg_types, w_function, w_options):
if not space.is_kind_of(w_ret_type, space.getclassfor(W_TypeObject)):
try:
sym = Coerce.symbol(space, w_ret_type)
if sym.upper() in W_TypeObject.basics:
# code for string object
pass
else:
raise space.error(space.w_TypeError,
"can't convert Symbol into Type")
except RubyError:
tp = w_ret_type.getclass(space).name
raise space.error(space.w_TypeError,
"can't convert %s into Type" % tp)
# code for type object
<commit_msg>Put the type unwrapping into a separat method<commit_after>from topaz.objects.objectobject import W_Object
from topaz.module import ClassDef
from topaz.modules.ffi.type import W_TypeObject
from topaz.error import RubyError
from topaz.coerce import Coerce
class W_FunctionObject(W_Object):
classdef = ClassDef('Function', W_Object.classdef)
@classdef.singleton_method('allocate')
def singleton_method_allocate(self, space, args_w):
return W_FunctionObject(space)
@classdef.method('initialize')
def method_initialize(self, space, w_ret_type, w_arg_types, w_function, w_options):
ret_type = self.type_unwrap(space, w_ret_type)
arg_types = [self.type_unwrap(space, w_type)
for w_type in space.listview(w_arg_types)]
# code for type object
def type_unwrap(self, space, w_type):
if space.is_kind_of(w_type, space.getclassfor(W_TypeObject)):
return self
try:
sym = Coerce.symbol(space, w_type)
key = sym.upper()
if key in W_TypeObject.basics:
return W_TypeObject.basics[key]
else:
raise space.error(space.w_TypeError,
"can't convert Symbol into Type")
except RubyError:
tp = w_type.getclass(space).name
raise space.error(space.w_TypeError,
"can't convert %s into Type" % tp)
|
d01a13f498e01efe613bace4c140d6901752475b
|
multilingual_model/admin.py
|
multilingual_model/admin.py
|
from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationInline(admin.StackedInline):
def __init__(self, *args, **kwargs):
super(TranslationInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
|
from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationStackedInline(admin.StackedInline):
def __init__(self, *args, **kwargs):
super(TranslationStackedInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = MAX_LANGUAGES
class TranslationTabularInline(admin.TabularInline):
def __init__(self, *args, **kwargs):
super(TranslationTabularInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
|
Rename TranslationInline to TranslationStackedInline, add TranslationTabularInline.
|
Rename TranslationInline to TranslationStackedInline, add TranslationTabularInline.
|
Python
|
agpl-3.0
|
dokterbob/django-multilingual-model
|
from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationInline(admin.StackedInline):
def __init__(self, *args, **kwargs):
super(TranslationInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
Rename TranslationInline to TranslationStackedInline, add TranslationTabularInline.
|
from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationStackedInline(admin.StackedInline):
def __init__(self, *args, **kwargs):
super(TranslationStackedInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = MAX_LANGUAGES
class TranslationTabularInline(admin.TabularInline):
def __init__(self, *args, **kwargs):
super(TranslationTabularInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
|
<commit_before>from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationInline(admin.StackedInline):
def __init__(self, *args, **kwargs):
super(TranslationInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
<commit_msg>Rename TranslationInline to TranslationStackedInline, add TranslationTabularInline.<commit_after>
|
from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationStackedInline(admin.StackedInline):
def __init__(self, *args, **kwargs):
super(TranslationStackedInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = MAX_LANGUAGES
class TranslationTabularInline(admin.TabularInline):
def __init__(self, *args, **kwargs):
super(TranslationTabularInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
|
from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationInline(admin.StackedInline):
def __init__(self, *args, **kwargs):
super(TranslationInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
Rename TranslationInline to TranslationStackedInline, add TranslationTabularInline.from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationStackedInline(admin.StackedInline):
def __init__(self, *args, **kwargs):
super(TranslationStackedInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = MAX_LANGUAGES
class TranslationTabularInline(admin.TabularInline):
def __init__(self, *args, **kwargs):
super(TranslationTabularInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
|
<commit_before>from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationInline(admin.StackedInline):
def __init__(self, *args, **kwargs):
super(TranslationInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
<commit_msg>Rename TranslationInline to TranslationStackedInline, add TranslationTabularInline.<commit_after>from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationStackedInline(admin.StackedInline):
def __init__(self, *args, **kwargs):
super(TranslationStackedInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = MAX_LANGUAGES
class TranslationTabularInline(admin.TabularInline):
def __init__(self, *args, **kwargs):
super(TranslationTabularInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
|
1aa98285f1d51e36f9091542dd0323168a443a28
|
wiblog/formatting.py
|
wiblog/formatting.py
|
from django.utils.safestring import mark_safe
import CommonMark
# Convert a markdown string into HTML5, and prevent Django from escaping it
def mdToHTML(value):
parser = CommonMark.DocParser()
renderer = CommonMark.HTMLRenderer()
ast = parser.parse(value)
return mark_safe(renderer.render(ast))
# Get a summary of a post
def summarize(fullBody):
firstNewline = fullBody.find("\n")
if firstNewline > 0:
return unicode(fullBody)[:firstNewline]
return fullBody
|
from django.utils.safestring import mark_safe
import CommonMark
# Convert a markdown string into HTML5, and prevent Django from escaping it
def mdToHTML(value):
parser = CommonMark.Parser()
renderer = CommonMark.HTMLRenderer()
ast = parser.parse(value)
return mark_safe(renderer.render(ast))
# Get a summary of a post
def summarize(fullBody):
firstNewline = fullBody.find("\n")
if firstNewline > 0:
return fullBody[:firstNewline]
return fullBody
|
Fix changed CommonMark syntax (?)
|
Fix changed CommonMark syntax (?)
|
Python
|
agpl-3.0
|
lo-windigo/fragdev,lo-windigo/fragdev
|
from django.utils.safestring import mark_safe
import CommonMark
# Convert a markdown string into HTML5, and prevent Django from escaping it
def mdToHTML(value):
parser = CommonMark.DocParser()
renderer = CommonMark.HTMLRenderer()
ast = parser.parse(value)
return mark_safe(renderer.render(ast))
# Get a summary of a post
def summarize(fullBody):
firstNewline = fullBody.find("\n")
if firstNewline > 0:
return unicode(fullBody)[:firstNewline]
return fullBody
Fix changed CommonMark syntax (?)
|
from django.utils.safestring import mark_safe
import CommonMark
# Convert a markdown string into HTML5, and prevent Django from escaping it
def mdToHTML(value):
parser = CommonMark.Parser()
renderer = CommonMark.HTMLRenderer()
ast = parser.parse(value)
return mark_safe(renderer.render(ast))
# Get a summary of a post
def summarize(fullBody):
firstNewline = fullBody.find("\n")
if firstNewline > 0:
return fullBody[:firstNewline]
return fullBody
|
<commit_before>from django.utils.safestring import mark_safe
import CommonMark
# Convert a markdown string into HTML5, and prevent Django from escaping it
def mdToHTML(value):
parser = CommonMark.DocParser()
renderer = CommonMark.HTMLRenderer()
ast = parser.parse(value)
return mark_safe(renderer.render(ast))
# Get a summary of a post
def summarize(fullBody):
firstNewline = fullBody.find("\n")
if firstNewline > 0:
return unicode(fullBody)[:firstNewline]
return fullBody
<commit_msg>Fix changed CommonMark syntax (?)<commit_after>
|
from django.utils.safestring import mark_safe
import CommonMark
# Convert a markdown string into HTML5, and prevent Django from escaping it
def mdToHTML(value):
parser = CommonMark.Parser()
renderer = CommonMark.HTMLRenderer()
ast = parser.parse(value)
return mark_safe(renderer.render(ast))
# Get a summary of a post
def summarize(fullBody):
firstNewline = fullBody.find("\n")
if firstNewline > 0:
return fullBody[:firstNewline]
return fullBody
|
from django.utils.safestring import mark_safe
import CommonMark
# Convert a markdown string into HTML5, and prevent Django from escaping it
def mdToHTML(value):
parser = CommonMark.DocParser()
renderer = CommonMark.HTMLRenderer()
ast = parser.parse(value)
return mark_safe(renderer.render(ast))
# Get a summary of a post
def summarize(fullBody):
firstNewline = fullBody.find("\n")
if firstNewline > 0:
return unicode(fullBody)[:firstNewline]
return fullBody
Fix changed CommonMark syntax (?)from django.utils.safestring import mark_safe
import CommonMark
# Convert a markdown string into HTML5, and prevent Django from escaping it
def mdToHTML(value):
parser = CommonMark.Parser()
renderer = CommonMark.HTMLRenderer()
ast = parser.parse(value)
return mark_safe(renderer.render(ast))
# Get a summary of a post
def summarize(fullBody):
firstNewline = fullBody.find("\n")
if firstNewline > 0:
return fullBody[:firstNewline]
return fullBody
|
<commit_before>from django.utils.safestring import mark_safe
import CommonMark
# Convert a markdown string into HTML5, and prevent Django from escaping it
def mdToHTML(value):
parser = CommonMark.DocParser()
renderer = CommonMark.HTMLRenderer()
ast = parser.parse(value)
return mark_safe(renderer.render(ast))
# Get a summary of a post
def summarize(fullBody):
firstNewline = fullBody.find("\n")
if firstNewline > 0:
return unicode(fullBody)[:firstNewline]
return fullBody
<commit_msg>Fix changed CommonMark syntax (?)<commit_after>from django.utils.safestring import mark_safe
import CommonMark
# Convert a markdown string into HTML5, and prevent Django from escaping it
def mdToHTML(value):
parser = CommonMark.Parser()
renderer = CommonMark.HTMLRenderer()
ast = parser.parse(value)
return mark_safe(renderer.render(ast))
# Get a summary of a post
def summarize(fullBody):
firstNewline = fullBody.find("\n")
if firstNewline > 0:
return fullBody[:firstNewline]
return fullBody
|
273127e89bd714502d2f57e1220e7e0f1811d7fb
|
django_git/utils.py
|
django_git/utils.py
|
import os
from git import *
from django.conf import settings
def get_repos():
repos = [get_repo(dir) for dir in os.listdir(settings.REPOS_ROOT)]
return [r for r in repos if not (r is None)]
def get_repo(name):
repo_path = os.path.join(settings.REPOS_ROOT, name)
if os.path.isdir(repo_path):
try:
return Repo(repo_path)
except Exception:
pass
return None
def get_commit(name, commit):
repo = get_repo(name)
commit = repo.commit(commit)
return commit
def get_blob(repo, commit, file):
repo = get_repo(repo)
commit = repo.commit(commit)
tree = commit.tree
for path_seg in file.split('/'):
t = tree.get(path_seg)
if isinstance(t, Tree):
tree = t
else:
blob = t
return blob
|
import os
from git import *
from django.conf import settings
def get_repos():
repos = [get_repo(dir) for dir in os.listdir(settings.REPOS_ROOT)]
return [r for r in repos if not (r is None)]
def get_repo(name):
repo_path = os.path.join(settings.REPOS_ROOT, name)
if os.path.isdir(repo_path):
try:
return Repo(repo_path)
except Exception:
pass
return None
def get_commit(name, commit):
repo = get_repo(name)
commit = repo.commit(commit)
return commit
def get_blob(repo, commit, file):
repo = get_repo(repo)
commit = repo.commit(commit)
tree = commit.tree
for path_seg in file.split(os.sep):
t = tree.get(path_seg)
if isinstance(t, Tree):
tree = t
else:
blob = t
return blob
|
Use os.sep for splitting directories
|
Use os.sep for splitting directories
Signed-off-by: Seth Buntin <7fa3258757ee476d85f026594ec3f1563305da2c@gmail.com>
|
Python
|
bsd-3-clause
|
sethtrain/django-git,sethtrain/django-git
|
import os
from git import *
from django.conf import settings
def get_repos():
repos = [get_repo(dir) for dir in os.listdir(settings.REPOS_ROOT)]
return [r for r in repos if not (r is None)]
def get_repo(name):
repo_path = os.path.join(settings.REPOS_ROOT, name)
if os.path.isdir(repo_path):
try:
return Repo(repo_path)
except Exception:
pass
return None
def get_commit(name, commit):
repo = get_repo(name)
commit = repo.commit(commit)
return commit
def get_blob(repo, commit, file):
repo = get_repo(repo)
commit = repo.commit(commit)
tree = commit.tree
for path_seg in file.split('/'):
t = tree.get(path_seg)
if isinstance(t, Tree):
tree = t
else:
blob = t
return blob
Use os.sep for splitting directories
Signed-off-by: Seth Buntin <7fa3258757ee476d85f026594ec3f1563305da2c@gmail.com>
|
import os
from git import *
from django.conf import settings
def get_repos():
repos = [get_repo(dir) for dir in os.listdir(settings.REPOS_ROOT)]
return [r for r in repos if not (r is None)]
def get_repo(name):
repo_path = os.path.join(settings.REPOS_ROOT, name)
if os.path.isdir(repo_path):
try:
return Repo(repo_path)
except Exception:
pass
return None
def get_commit(name, commit):
repo = get_repo(name)
commit = repo.commit(commit)
return commit
def get_blob(repo, commit, file):
repo = get_repo(repo)
commit = repo.commit(commit)
tree = commit.tree
for path_seg in file.split(os.sep):
t = tree.get(path_seg)
if isinstance(t, Tree):
tree = t
else:
blob = t
return blob
|
<commit_before>import os
from git import *
from django.conf import settings
def get_repos():
repos = [get_repo(dir) for dir in os.listdir(settings.REPOS_ROOT)]
return [r for r in repos if not (r is None)]
def get_repo(name):
repo_path = os.path.join(settings.REPOS_ROOT, name)
if os.path.isdir(repo_path):
try:
return Repo(repo_path)
except Exception:
pass
return None
def get_commit(name, commit):
repo = get_repo(name)
commit = repo.commit(commit)
return commit
def get_blob(repo, commit, file):
repo = get_repo(repo)
commit = repo.commit(commit)
tree = commit.tree
for path_seg in file.split('/'):
t = tree.get(path_seg)
if isinstance(t, Tree):
tree = t
else:
blob = t
return blob
<commit_msg>Use os.sep for splitting directories
Signed-off-by: Seth Buntin <7fa3258757ee476d85f026594ec3f1563305da2c@gmail.com><commit_after>
|
import os
from git import *
from django.conf import settings
def get_repos():
repos = [get_repo(dir) for dir in os.listdir(settings.REPOS_ROOT)]
return [r for r in repos if not (r is None)]
def get_repo(name):
repo_path = os.path.join(settings.REPOS_ROOT, name)
if os.path.isdir(repo_path):
try:
return Repo(repo_path)
except Exception:
pass
return None
def get_commit(name, commit):
repo = get_repo(name)
commit = repo.commit(commit)
return commit
def get_blob(repo, commit, file):
repo = get_repo(repo)
commit = repo.commit(commit)
tree = commit.tree
for path_seg in file.split(os.sep):
t = tree.get(path_seg)
if isinstance(t, Tree):
tree = t
else:
blob = t
return blob
|
import os
from git import *
from django.conf import settings
def get_repos():
repos = [get_repo(dir) for dir in os.listdir(settings.REPOS_ROOT)]
return [r for r in repos if not (r is None)]
def get_repo(name):
repo_path = os.path.join(settings.REPOS_ROOT, name)
if os.path.isdir(repo_path):
try:
return Repo(repo_path)
except Exception:
pass
return None
def get_commit(name, commit):
repo = get_repo(name)
commit = repo.commit(commit)
return commit
def get_blob(repo, commit, file):
repo = get_repo(repo)
commit = repo.commit(commit)
tree = commit.tree
for path_seg in file.split('/'):
t = tree.get(path_seg)
if isinstance(t, Tree):
tree = t
else:
blob = t
return blob
Use os.sep for splitting directories
Signed-off-by: Seth Buntin <7fa3258757ee476d85f026594ec3f1563305da2c@gmail.com>import os
from git import *
from django.conf import settings
def get_repos():
repos = [get_repo(dir) for dir in os.listdir(settings.REPOS_ROOT)]
return [r for r in repos if not (r is None)]
def get_repo(name):
repo_path = os.path.join(settings.REPOS_ROOT, name)
if os.path.isdir(repo_path):
try:
return Repo(repo_path)
except Exception:
pass
return None
def get_commit(name, commit):
repo = get_repo(name)
commit = repo.commit(commit)
return commit
def get_blob(repo, commit, file):
repo = get_repo(repo)
commit = repo.commit(commit)
tree = commit.tree
for path_seg in file.split(os.sep):
t = tree.get(path_seg)
if isinstance(t, Tree):
tree = t
else:
blob = t
return blob
|
<commit_before>import os
from git import *
from django.conf import settings
def get_repos():
repos = [get_repo(dir) for dir in os.listdir(settings.REPOS_ROOT)]
return [r for r in repos if not (r is None)]
def get_repo(name):
repo_path = os.path.join(settings.REPOS_ROOT, name)
if os.path.isdir(repo_path):
try:
return Repo(repo_path)
except Exception:
pass
return None
def get_commit(name, commit):
repo = get_repo(name)
commit = repo.commit(commit)
return commit
def get_blob(repo, commit, file):
repo = get_repo(repo)
commit = repo.commit(commit)
tree = commit.tree
for path_seg in file.split('/'):
t = tree.get(path_seg)
if isinstance(t, Tree):
tree = t
else:
blob = t
return blob
<commit_msg>Use os.sep for splitting directories
Signed-off-by: Seth Buntin <7fa3258757ee476d85f026594ec3f1563305da2c@gmail.com><commit_after>import os
from git import *
from django.conf import settings
def get_repos():
repos = [get_repo(dir) for dir in os.listdir(settings.REPOS_ROOT)]
return [r for r in repos if not (r is None)]
def get_repo(name):
repo_path = os.path.join(settings.REPOS_ROOT, name)
if os.path.isdir(repo_path):
try:
return Repo(repo_path)
except Exception:
pass
return None
def get_commit(name, commit):
repo = get_repo(name)
commit = repo.commit(commit)
return commit
def get_blob(repo, commit, file):
repo = get_repo(repo)
commit = repo.commit(commit)
tree = commit.tree
for path_seg in file.split(os.sep):
t = tree.get(path_seg)
if isinstance(t, Tree):
tree = t
else:
blob = t
return blob
|
5e50f8127a48a08d66bdc9d8aec28064b33ad864
|
game.py
|
game.py
|
import datetime
import map_loader
class Game(object):
def __init__(self, name=name, players=players, map=None):
""" Initialize a new game. """
self.name = name,
self.players = players, # List of player usernames
self.status = 'Waiting',
self.raw_state = self.generate_clean_state(), # JSON object
self.created = datetime.datetime.now(),
map = 'default' if map is None else map
self.map = map.read_map_file(map)
def generate_clean_state(self):
""" Generates a blank game state JSON object. """
return '{}'
def load_from_state(self):
""" Load game attributes from raw game state. """
pass
def serialize(self):
""" Turn game into a serialized game state for storage. """
pass
def update(self):
""" Execute a round. """
pass
|
import datetime
import json
import map_loader
class GAME_STATUS(object):
""" Game status constants. """
lobby = 'waiting for players'
waiting = 'waiting for moves'
playing = 'playing'
cancelled = 'cancelled'
complete = 'complete'
class Game(object):
def __init__(self, name=name, players=players, map='default'):
""" Initialize a new game. """
self.name = name,
self.players = players, # List of player usernames
self.status = GAME_STATUS.lobby,
self.created = datetime.datetime.now(),
# These attributes are persisted in the raw_state, not DB properties
self.map = map.read_map_file(map)
self.current_turn = 0
self.max_turns = 0
self.raw_state = self.serialize(), # JSON state (a DB property)
def load_state_from_json(self):
""" Load game attributes from raw game state. """
state = json.loads(self.raw_state)
self.map = state['map']
self.current_turn, self.max_turns = state['turn']
def serialize_state(self):
""" Turn game state into a serialized game state for storage. """
state = {
'map': self.map,
'turn': [self.current_turn, self.max_turns],
}
return json.dumps(state)
def update(self):
""" Execute a round. """
self.current_turn += 1
if self.current_turn == self.max_turns:
self.status = GAME_STATUS.complete
|
Add some state related methods to Game
|
Add some state related methods to Game
|
Python
|
mit
|
supermitch/mech-ai,supermitch/mech-ai,supermitch/mech-ai
|
import datetime
import map_loader
class Game(object):
def __init__(self, name=name, players=players, map=None):
""" Initialize a new game. """
self.name = name,
self.players = players, # List of player usernames
self.status = 'Waiting',
self.raw_state = self.generate_clean_state(), # JSON object
self.created = datetime.datetime.now(),
map = 'default' if map is None else map
self.map = map.read_map_file(map)
def generate_clean_state(self):
""" Generates a blank game state JSON object. """
return '{}'
def load_from_state(self):
""" Load game attributes from raw game state. """
pass
def serialize(self):
""" Turn game into a serialized game state for storage. """
pass
def update(self):
""" Execute a round. """
pass
Add some state related methods to Game
|
import datetime
import json
import map_loader
class GAME_STATUS(object):
""" Game status constants. """
lobby = 'waiting for players'
waiting = 'waiting for moves'
playing = 'playing'
cancelled = 'cancelled'
complete = 'complete'
class Game(object):
def __init__(self, name=name, players=players, map='default'):
""" Initialize a new game. """
self.name = name,
self.players = players, # List of player usernames
self.status = GAME_STATUS.lobby,
self.created = datetime.datetime.now(),
# These attributes are persisted in the raw_state, not DB properties
self.map = map.read_map_file(map)
self.current_turn = 0
self.max_turns = 0
self.raw_state = self.serialize(), # JSON state (a DB property)
def load_state_from_json(self):
""" Load game attributes from raw game state. """
state = json.loads(self.raw_state)
self.map = state['map']
self.current_turn, self.max_turns = state['turn']
def serialize_state(self):
""" Turn game state into a serialized game state for storage. """
state = {
'map': self.map,
'turn': [self.current_turn, self.max_turns],
}
return json.dumps(state)
def update(self):
""" Execute a round. """
self.current_turn += 1
if self.current_turn == self.max_turns:
self.status = GAME_STATUS.complete
|
<commit_before>import datetime
import map_loader
class Game(object):
def __init__(self, name=name, players=players, map=None):
""" Initialize a new game. """
self.name = name,
self.players = players, # List of player usernames
self.status = 'Waiting',
self.raw_state = self.generate_clean_state(), # JSON object
self.created = datetime.datetime.now(),
map = 'default' if map is None else map
self.map = map.read_map_file(map)
def generate_clean_state(self):
""" Generates a blank game state JSON object. """
return '{}'
def load_from_state(self):
""" Load game attributes from raw game state. """
pass
def serialize(self):
""" Turn game into a serialized game state for storage. """
pass
def update(self):
""" Execute a round. """
pass
<commit_msg>Add some state related methods to Game<commit_after>
|
import datetime
import json
import map_loader
class GAME_STATUS(object):
""" Game status constants. """
lobby = 'waiting for players'
waiting = 'waiting for moves'
playing = 'playing'
cancelled = 'cancelled'
complete = 'complete'
class Game(object):
def __init__(self, name=name, players=players, map='default'):
""" Initialize a new game. """
self.name = name,
self.players = players, # List of player usernames
self.status = GAME_STATUS.lobby,
self.created = datetime.datetime.now(),
# These attributes are persisted in the raw_state, not DB properties
self.map = map.read_map_file(map)
self.current_turn = 0
self.max_turns = 0
self.raw_state = self.serialize(), # JSON state (a DB property)
def load_state_from_json(self):
""" Load game attributes from raw game state. """
state = json.loads(self.raw_state)
self.map = state['map']
self.current_turn, self.max_turns = state['turn']
def serialize_state(self):
""" Turn game state into a serialized game state for storage. """
state = {
'map': self.map,
'turn': [self.current_turn, self.max_turns],
}
return json.dumps(state)
def update(self):
""" Execute a round. """
self.current_turn += 1
if self.current_turn == self.max_turns:
self.status = GAME_STATUS.complete
|
import datetime
import map_loader
class Game(object):
def __init__(self, name=name, players=players, map=None):
""" Initialize a new game. """
self.name = name,
self.players = players, # List of player usernames
self.status = 'Waiting',
self.raw_state = self.generate_clean_state(), # JSON object
self.created = datetime.datetime.now(),
map = 'default' if map is None else map
self.map = map.read_map_file(map)
def generate_clean_state(self):
""" Generates a blank game state JSON object. """
return '{}'
def load_from_state(self):
""" Load game attributes from raw game state. """
pass
def serialize(self):
""" Turn game into a serialized game state for storage. """
pass
def update(self):
""" Execute a round. """
pass
Add some state related methods to Gameimport datetime
import json
import map_loader
class GAME_STATUS(object):
""" Game status constants. """
lobby = 'waiting for players'
waiting = 'waiting for moves'
playing = 'playing'
cancelled = 'cancelled'
complete = 'complete'
class Game(object):
def __init__(self, name=name, players=players, map='default'):
""" Initialize a new game. """
self.name = name,
self.players = players, # List of player usernames
self.status = GAME_STATUS.lobby,
self.created = datetime.datetime.now(),
# These attributes are persisted in the raw_state, not DB properties
self.map = map.read_map_file(map)
self.current_turn = 0
self.max_turns = 0
self.raw_state = self.serialize(), # JSON state (a DB property)
def load_state_from_json(self):
""" Load game attributes from raw game state. """
state = json.loads(self.raw_state)
self.map = state['map']
self.current_turn, self.max_turns = state['turn']
def serialize_state(self):
""" Turn game state into a serialized game state for storage. """
state = {
'map': self.map,
'turn': [self.current_turn, self.max_turns],
}
return json.dumps(state)
def update(self):
""" Execute a round. """
self.current_turn += 1
if self.current_turn == self.max_turns:
self.status = GAME_STATUS.complete
|
<commit_before>import datetime
import map_loader
class Game(object):
def __init__(self, name=name, players=players, map=None):
""" Initialize a new game. """
self.name = name,
self.players = players, # List of player usernames
self.status = 'Waiting',
self.raw_state = self.generate_clean_state(), # JSON object
self.created = datetime.datetime.now(),
map = 'default' if map is None else map
self.map = map.read_map_file(map)
def generate_clean_state(self):
""" Generates a blank game state JSON object. """
return '{}'
def load_from_state(self):
""" Load game attributes from raw game state. """
pass
def serialize(self):
""" Turn game into a serialized game state for storage. """
pass
def update(self):
""" Execute a round. """
pass
<commit_msg>Add some state related methods to Game<commit_after>import datetime
import json
import map_loader
class GAME_STATUS(object):
""" Game status constants. """
lobby = 'waiting for players'
waiting = 'waiting for moves'
playing = 'playing'
cancelled = 'cancelled'
complete = 'complete'
class Game(object):
def __init__(self, name=name, players=players, map='default'):
""" Initialize a new game. """
self.name = name,
self.players = players, # List of player usernames
self.status = GAME_STATUS.lobby,
self.created = datetime.datetime.now(),
# These attributes are persisted in the raw_state, not DB properties
self.map = map.read_map_file(map)
self.current_turn = 0
self.max_turns = 0
self.raw_state = self.serialize(), # JSON state (a DB property)
def load_state_from_json(self):
""" Load game attributes from raw game state. """
state = json.loads(self.raw_state)
self.map = state['map']
self.current_turn, self.max_turns = state['turn']
def serialize_state(self):
""" Turn game state into a serialized game state for storage. """
state = {
'map': self.map,
'turn': [self.current_turn, self.max_turns],
}
return json.dumps(state)
def update(self):
""" Execute a round. """
self.current_turn += 1
if self.current_turn == self.max_turns:
self.status = GAME_STATUS.complete
|
067036e927fde0a97708162323ba13d4a239bb5b
|
grammpy/exceptions/NotNonterminalException.py
|
grammpy/exceptions/NotNonterminalException.py
|
#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from .GrammpyException import GrammpyException
class NotNonterminalException(GrammpyException):
pass
|
#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from typing import Any
from .GrammpyException import GrammpyException
class NotNonterminalException(GrammpyException):
def __init__(self, parameter, *args: Any) -> None:
super().__init__(*args)
self.object = parameter
|
Implement NotNonterminalEception __init__ method and pass object
|
Implement NotNonterminalEception __init__ method and pass object
|
Python
|
mit
|
PatrikValkovic/grammpy
|
#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from .GrammpyException import GrammpyException
class NotNonterminalException(GrammpyException):
pass
Implement NotNonterminalEception __init__ method and pass object
|
#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from typing import Any
from .GrammpyException import GrammpyException
class NotNonterminalException(GrammpyException):
def __init__(self, parameter, *args: Any) -> None:
super().__init__(*args)
self.object = parameter
|
<commit_before>#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from .GrammpyException import GrammpyException
class NotNonterminalException(GrammpyException):
pass
<commit_msg>Implement NotNonterminalEception __init__ method and pass object<commit_after>
|
#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from typing import Any
from .GrammpyException import GrammpyException
class NotNonterminalException(GrammpyException):
def __init__(self, parameter, *args: Any) -> None:
super().__init__(*args)
self.object = parameter
|
#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from .GrammpyException import GrammpyException
class NotNonterminalException(GrammpyException):
pass
Implement NotNonterminalEception __init__ method and pass object#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from typing import Any
from .GrammpyException import GrammpyException
class NotNonterminalException(GrammpyException):
def __init__(self, parameter, *args: Any) -> None:
super().__init__(*args)
self.object = parameter
|
<commit_before>#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from .GrammpyException import GrammpyException
class NotNonterminalException(GrammpyException):
pass
<commit_msg>Implement NotNonterminalEception __init__ method and pass object<commit_after>#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from typing import Any
from .GrammpyException import GrammpyException
class NotNonterminalException(GrammpyException):
def __init__(self, parameter, *args: Any) -> None:
super().__init__(*args)
self.object = parameter
|
0d24acf08ec81f2b84609ce417cc314a4e76c570
|
testproject/tablib_test/tests.py
|
testproject/tablib_test/tests.py
|
from django.test import TestCase
from django_tablib import ModelDataset, Field
from .models import TestModel
class DjangoTablibTestCase(TestCase):
def setUp(self):
TestModel.objects.create(field1='value')
def test_declarative_fields(self):
class TestModelDataset(ModelDataset):
field1 = Field(header='Field 1')
field2 = Field(attribute='field1')
class Meta:
model = TestModel
data = TestModelDataset()
self.assertEqual(len(data.headers), 2)
self.assertTrue('id' not in data.headers)
self.assertFalse('field1' in data.headers)
self.assertTrue('field2' in data.headers)
self.assertTrue('Field 1' in data.headers)
self.assertEqual(data[0][0], data[0][1])
|
from django.test import TestCase
from django_tablib import ModelDataset, Field
from .models import TestModel
class DjangoTablibTestCase(TestCase):
def setUp(self):
TestModel.objects.create(field1='value')
def test_declarative_fields(self):
class TestModelDataset(ModelDataset):
field1 = Field(header='Field 1')
field2 = Field(attribute='field1')
class Meta:
model = TestModel
data = TestModelDataset()
self.assertEqual(len(data.headers), 3)
self.assertTrue('id' in data.headers)
self.assertFalse('field1' in data.headers)
self.assertTrue('field2' in data.headers)
self.assertTrue('Field 1' in data.headers)
self.assertEqual(data[0][0], data[0][1])
|
Adjust test for new functionality.
|
Adjust test for new functionality.
|
Python
|
mit
|
ebrelsford/django-tablib,joshourisman/django-tablib,joshourisman/django-tablib,ebrelsford/django-tablib
|
from django.test import TestCase
from django_tablib import ModelDataset, Field
from .models import TestModel
class DjangoTablibTestCase(TestCase):
def setUp(self):
TestModel.objects.create(field1='value')
def test_declarative_fields(self):
class TestModelDataset(ModelDataset):
field1 = Field(header='Field 1')
field2 = Field(attribute='field1')
class Meta:
model = TestModel
data = TestModelDataset()
self.assertEqual(len(data.headers), 2)
self.assertTrue('id' not in data.headers)
self.assertFalse('field1' in data.headers)
self.assertTrue('field2' in data.headers)
self.assertTrue('Field 1' in data.headers)
self.assertEqual(data[0][0], data[0][1])
Adjust test for new functionality.
|
from django.test import TestCase
from django_tablib import ModelDataset, Field
from .models import TestModel
class DjangoTablibTestCase(TestCase):
def setUp(self):
TestModel.objects.create(field1='value')
def test_declarative_fields(self):
class TestModelDataset(ModelDataset):
field1 = Field(header='Field 1')
field2 = Field(attribute='field1')
class Meta:
model = TestModel
data = TestModelDataset()
self.assertEqual(len(data.headers), 3)
self.assertTrue('id' in data.headers)
self.assertFalse('field1' in data.headers)
self.assertTrue('field2' in data.headers)
self.assertTrue('Field 1' in data.headers)
self.assertEqual(data[0][0], data[0][1])
|
<commit_before>from django.test import TestCase
from django_tablib import ModelDataset, Field
from .models import TestModel
class DjangoTablibTestCase(TestCase):
def setUp(self):
TestModel.objects.create(field1='value')
def test_declarative_fields(self):
class TestModelDataset(ModelDataset):
field1 = Field(header='Field 1')
field2 = Field(attribute='field1')
class Meta:
model = TestModel
data = TestModelDataset()
self.assertEqual(len(data.headers), 2)
self.assertTrue('id' not in data.headers)
self.assertFalse('field1' in data.headers)
self.assertTrue('field2' in data.headers)
self.assertTrue('Field 1' in data.headers)
self.assertEqual(data[0][0], data[0][1])
<commit_msg>Adjust test for new functionality.<commit_after>
|
from django.test import TestCase
from django_tablib import ModelDataset, Field
from .models import TestModel
class DjangoTablibTestCase(TestCase):
def setUp(self):
TestModel.objects.create(field1='value')
def test_declarative_fields(self):
class TestModelDataset(ModelDataset):
field1 = Field(header='Field 1')
field2 = Field(attribute='field1')
class Meta:
model = TestModel
data = TestModelDataset()
self.assertEqual(len(data.headers), 3)
self.assertTrue('id' in data.headers)
self.assertFalse('field1' in data.headers)
self.assertTrue('field2' in data.headers)
self.assertTrue('Field 1' in data.headers)
self.assertEqual(data[0][0], data[0][1])
|
from django.test import TestCase
from django_tablib import ModelDataset, Field
from .models import TestModel
class DjangoTablibTestCase(TestCase):
def setUp(self):
TestModel.objects.create(field1='value')
def test_declarative_fields(self):
class TestModelDataset(ModelDataset):
field1 = Field(header='Field 1')
field2 = Field(attribute='field1')
class Meta:
model = TestModel
data = TestModelDataset()
self.assertEqual(len(data.headers), 2)
self.assertTrue('id' not in data.headers)
self.assertFalse('field1' in data.headers)
self.assertTrue('field2' in data.headers)
self.assertTrue('Field 1' in data.headers)
self.assertEqual(data[0][0], data[0][1])
Adjust test for new functionality.from django.test import TestCase
from django_tablib import ModelDataset, Field
from .models import TestModel
class DjangoTablibTestCase(TestCase):
def setUp(self):
TestModel.objects.create(field1='value')
def test_declarative_fields(self):
class TestModelDataset(ModelDataset):
field1 = Field(header='Field 1')
field2 = Field(attribute='field1')
class Meta:
model = TestModel
data = TestModelDataset()
self.assertEqual(len(data.headers), 3)
self.assertTrue('id' in data.headers)
self.assertFalse('field1' in data.headers)
self.assertTrue('field2' in data.headers)
self.assertTrue('Field 1' in data.headers)
self.assertEqual(data[0][0], data[0][1])
|
<commit_before>from django.test import TestCase
from django_tablib import ModelDataset, Field
from .models import TestModel
class DjangoTablibTestCase(TestCase):
def setUp(self):
TestModel.objects.create(field1='value')
def test_declarative_fields(self):
class TestModelDataset(ModelDataset):
field1 = Field(header='Field 1')
field2 = Field(attribute='field1')
class Meta:
model = TestModel
data = TestModelDataset()
self.assertEqual(len(data.headers), 2)
self.assertTrue('id' not in data.headers)
self.assertFalse('field1' in data.headers)
self.assertTrue('field2' in data.headers)
self.assertTrue('Field 1' in data.headers)
self.assertEqual(data[0][0], data[0][1])
<commit_msg>Adjust test for new functionality.<commit_after>from django.test import TestCase
from django_tablib import ModelDataset, Field
from .models import TestModel
class DjangoTablibTestCase(TestCase):
def setUp(self):
TestModel.objects.create(field1='value')
def test_declarative_fields(self):
class TestModelDataset(ModelDataset):
field1 = Field(header='Field 1')
field2 = Field(attribute='field1')
class Meta:
model = TestModel
data = TestModelDataset()
self.assertEqual(len(data.headers), 3)
self.assertTrue('id' in data.headers)
self.assertFalse('field1' in data.headers)
self.assertTrue('field2' in data.headers)
self.assertTrue('Field 1' in data.headers)
self.assertEqual(data[0][0], data[0][1])
|
9cc9f7db5c230460e4e181c1aed2ec2270d18449
|
tests/test_preferred_encoding.py
|
tests/test_preferred_encoding.py
|
# -*- coding: utf-8 -*-
import locale
import codecs
import pytest
from cookiecutter.compat import PY3
@pytest.mark.skipif(not PY3, reason='Only necessary on Python3')
def test_not_ascii():
"""Make sure that the systems preferred encoding is not `ascii`.
Otherwise `click` is raising a RuntimeError for Python3. For a detailed
description of this very problem please consult the following gist:
https://gist.github.com/hackebrot/937245251887197ef542
This test also checks that `tox.ini` explicitly copies the according
system environment variables to the test environments.
"""
try:
preferred_encoding = locale.getpreferredencoding()
fs_enc = codecs.lookup(preferred_encoding).name
except Exception:
fs_enc = 'ascii'
assert fs_enc != 'ascii'
|
# -*- coding: utf-8 -*-
import locale
import codecs
import pytest
from cookiecutter.compat import PY3
@pytest.mark.skipif(not PY3, reason='Only necessary on Python3')
def test_not_ascii():
"""Make sure that the systems preferred encoding is not `ascii`.
Otherwise `click` is raising a RuntimeError for Python3. For a detailed
description of this very problem please consult the following gist:
https://gist.github.com/hackebrot/937245251887197ef542
This test also checks that `tox.ini` explicitly copies the according
system environment variables to the test environments.
"""
try:
preferred_encoding = locale.getpreferredencoding()
fs_enc = codecs.lookup(preferred_encoding).name
except Exception:
fs_enc = 'ascii'
assert fs_enc != 'ascii'
|
Add another blank line to fix flake8 check
|
Add another blank line to fix flake8 check
|
Python
|
bsd-3-clause
|
cguardia/cookiecutter,moi65/cookiecutter,pjbull/cookiecutter,kkujawinski/cookiecutter,dajose/cookiecutter,Vauxoo/cookiecutter,venumech/cookiecutter,lgp171188/cookiecutter,lucius-feng/cookiecutter,atlassian/cookiecutter,foodszhang/cookiecutter,Vauxoo/cookiecutter,venumech/cookiecutter,hackebrot/cookiecutter,moi65/cookiecutter,willingc/cookiecutter,agconti/cookiecutter,michaeljoseph/cookiecutter,Springerle/cookiecutter,lgp171188/cookiecutter,foodszhang/cookiecutter,janusnic/cookiecutter,terryjbates/cookiecutter,vintasoftware/cookiecutter,ionelmc/cookiecutter,hackebrot/cookiecutter,drgarcia1986/cookiecutter,takeflight/cookiecutter,benthomasson/cookiecutter,stevepiercy/cookiecutter,christabor/cookiecutter,sp1rs/cookiecutter,kkujawinski/cookiecutter,cguardia/cookiecutter,tylerdave/cookiecutter,atlassian/cookiecutter,stevepiercy/cookiecutter,tylerdave/cookiecutter,benthomasson/cookiecutter,ionelmc/cookiecutter,luzfcb/cookiecutter,willingc/cookiecutter,lucius-feng/cookiecutter,janusnic/cookiecutter,drgarcia1986/cookiecutter,luzfcb/cookiecutter,pjbull/cookiecutter,christabor/cookiecutter,nhomar/cookiecutter,vintasoftware/cookiecutter,takeflight/cookiecutter,audreyr/cookiecutter,ramiroluz/cookiecutter,ramiroluz/cookiecutter,michaeljoseph/cookiecutter,terryjbates/cookiecutter,sp1rs/cookiecutter,agconti/cookiecutter,audreyr/cookiecutter,Springerle/cookiecutter,nhomar/cookiecutter,dajose/cookiecutter
|
# -*- coding: utf-8 -*-
import locale
import codecs
import pytest
from cookiecutter.compat import PY3
@pytest.mark.skipif(not PY3, reason='Only necessary on Python3')
def test_not_ascii():
"""Make sure that the systems preferred encoding is not `ascii`.
Otherwise `click` is raising a RuntimeError for Python3. For a detailed
description of this very problem please consult the following gist:
https://gist.github.com/hackebrot/937245251887197ef542
This test also checks that `tox.ini` explicitly copies the according
system environment variables to the test environments.
"""
try:
preferred_encoding = locale.getpreferredencoding()
fs_enc = codecs.lookup(preferred_encoding).name
except Exception:
fs_enc = 'ascii'
assert fs_enc != 'ascii'
Add another blank line to fix flake8 check
|
# -*- coding: utf-8 -*-
import locale
import codecs
import pytest
from cookiecutter.compat import PY3
@pytest.mark.skipif(not PY3, reason='Only necessary on Python3')
def test_not_ascii():
"""Make sure that the systems preferred encoding is not `ascii`.
Otherwise `click` is raising a RuntimeError for Python3. For a detailed
description of this very problem please consult the following gist:
https://gist.github.com/hackebrot/937245251887197ef542
This test also checks that `tox.ini` explicitly copies the according
system environment variables to the test environments.
"""
try:
preferred_encoding = locale.getpreferredencoding()
fs_enc = codecs.lookup(preferred_encoding).name
except Exception:
fs_enc = 'ascii'
assert fs_enc != 'ascii'
|
<commit_before># -*- coding: utf-8 -*-
import locale
import codecs
import pytest
from cookiecutter.compat import PY3
@pytest.mark.skipif(not PY3, reason='Only necessary on Python3')
def test_not_ascii():
"""Make sure that the systems preferred encoding is not `ascii`.
Otherwise `click` is raising a RuntimeError for Python3. For a detailed
description of this very problem please consult the following gist:
https://gist.github.com/hackebrot/937245251887197ef542
This test also checks that `tox.ini` explicitly copies the according
system environment variables to the test environments.
"""
try:
preferred_encoding = locale.getpreferredencoding()
fs_enc = codecs.lookup(preferred_encoding).name
except Exception:
fs_enc = 'ascii'
assert fs_enc != 'ascii'
<commit_msg>Add another blank line to fix flake8 check<commit_after>
|
# -*- coding: utf-8 -*-
import locale
import codecs
import pytest
from cookiecutter.compat import PY3
@pytest.mark.skipif(not PY3, reason='Only necessary on Python3')
def test_not_ascii():
"""Make sure that the systems preferred encoding is not `ascii`.
Otherwise `click` is raising a RuntimeError for Python3. For a detailed
description of this very problem please consult the following gist:
https://gist.github.com/hackebrot/937245251887197ef542
This test also checks that `tox.ini` explicitly copies the according
system environment variables to the test environments.
"""
try:
preferred_encoding = locale.getpreferredencoding()
fs_enc = codecs.lookup(preferred_encoding).name
except Exception:
fs_enc = 'ascii'
assert fs_enc != 'ascii'
|
# -*- coding: utf-8 -*-
import locale
import codecs
import pytest
from cookiecutter.compat import PY3
@pytest.mark.skipif(not PY3, reason='Only necessary on Python3')
def test_not_ascii():
"""Make sure that the systems preferred encoding is not `ascii`.
Otherwise `click` is raising a RuntimeError for Python3. For a detailed
description of this very problem please consult the following gist:
https://gist.github.com/hackebrot/937245251887197ef542
This test also checks that `tox.ini` explicitly copies the according
system environment variables to the test environments.
"""
try:
preferred_encoding = locale.getpreferredencoding()
fs_enc = codecs.lookup(preferred_encoding).name
except Exception:
fs_enc = 'ascii'
assert fs_enc != 'ascii'
Add another blank line to fix flake8 check# -*- coding: utf-8 -*-
import locale
import codecs
import pytest
from cookiecutter.compat import PY3
@pytest.mark.skipif(not PY3, reason='Only necessary on Python3')
def test_not_ascii():
"""Make sure that the systems preferred encoding is not `ascii`.
Otherwise `click` is raising a RuntimeError for Python3. For a detailed
description of this very problem please consult the following gist:
https://gist.github.com/hackebrot/937245251887197ef542
This test also checks that `tox.ini` explicitly copies the according
system environment variables to the test environments.
"""
try:
preferred_encoding = locale.getpreferredencoding()
fs_enc = codecs.lookup(preferred_encoding).name
except Exception:
fs_enc = 'ascii'
assert fs_enc != 'ascii'
|
<commit_before># -*- coding: utf-8 -*-
import locale
import codecs
import pytest
from cookiecutter.compat import PY3
@pytest.mark.skipif(not PY3, reason='Only necessary on Python3')
def test_not_ascii():
"""Make sure that the systems preferred encoding is not `ascii`.
Otherwise `click` is raising a RuntimeError for Python3. For a detailed
description of this very problem please consult the following gist:
https://gist.github.com/hackebrot/937245251887197ef542
This test also checks that `tox.ini` explicitly copies the according
system environment variables to the test environments.
"""
try:
preferred_encoding = locale.getpreferredencoding()
fs_enc = codecs.lookup(preferred_encoding).name
except Exception:
fs_enc = 'ascii'
assert fs_enc != 'ascii'
<commit_msg>Add another blank line to fix flake8 check<commit_after># -*- coding: utf-8 -*-
import locale
import codecs
import pytest
from cookiecutter.compat import PY3
@pytest.mark.skipif(not PY3, reason='Only necessary on Python3')
def test_not_ascii():
"""Make sure that the systems preferred encoding is not `ascii`.
Otherwise `click` is raising a RuntimeError for Python3. For a detailed
description of this very problem please consult the following gist:
https://gist.github.com/hackebrot/937245251887197ef542
This test also checks that `tox.ini` explicitly copies the according
system environment variables to the test environments.
"""
try:
preferred_encoding = locale.getpreferredencoding()
fs_enc = codecs.lookup(preferred_encoding).name
except Exception:
fs_enc = 'ascii'
assert fs_enc != 'ascii'
|
3f51ab2ada60e78c9821cef557cb06194a24226a
|
tests/optvis/test_integration.py
|
tests/optvis/test_integration.py
|
from __future__ import absolute_import, division, print_function
import pytest
import tensorflow as tf
from lucid.modelzoo.vision_models import InceptionV1
from lucid.optvis import objectives, param, render, transform
model = InceptionV1()
model.load_graphdef()
@pytest.mark.parametrize("decorrelate", [True, False])
@pytest.mark.parametrize("fft", [True, False])
def test_integration(decorrelate, fft):
obj = objectives.neuron("mixed3a_pre_relu", 0)
param_f = lambda: param.image(16, decorrelate=decorrelate, fft=fft)
rendering = render.render_vis(model, obj, param_f=param_f, thresholds=(1,2),
verbose=False, transforms=[])
start_image = rendering[0]
end_image = rendering[-1]
objective_f = objectives.neuron("mixed3a", 177)
param_f = lambda: param.image(64, decorrelate=decorrelate, fft=fft)
rendering = render.render_vis(model, objective_f, param_f, verbose=False, thresholds=(0,64), use_fixed_seed=True)
start_image, end_image = rendering
assert (start_image != end_image).any()
|
from __future__ import absolute_import, division, print_function
import pytest
import tensorflow as tf
from lucid.modelzoo.vision_models import InceptionV1
from lucid.optvis import objectives, param, render, transform
@pytest.fixture
def inceptionv1():
model = InceptionV1()
model.load_graphdef()
return model
@pytest.mark.parametrize("decorrelate", [True, False])
@pytest.mark.parametrize("fft", [True, False])
def test_integration(decorrelate, fft, inceptionv1):
obj = objectives.neuron("mixed3a_pre_relu", 0)
param_f = lambda: param.image(16, decorrelate=decorrelate, fft=fft)
rendering = render.render_vis(inceptionv1, obj, param_f=param_f, thresholds=(1,2),
verbose=False, transforms=[])
start_image = rendering[0]
end_image = rendering[-1]
objective_f = objectives.neuron("mixed3a", 177)
param_f = lambda: param.image(64, decorrelate=decorrelate, fft=fft)
rendering = render.render_vis(inceptionv1, objective_f, param_f, verbose=False, thresholds=(0,64), use_fixed_seed=True)
start_image, end_image = rendering
assert (start_image != end_image).any()
|
Move model init into pytest fixture to avoid loading model and downloading graph just by importing the test module
|
Move model init into pytest fixture to avoid loading model and downloading graph just by importing the test module
|
Python
|
apache-2.0
|
tensorflow/lucid,tensorflow/lucid,tensorflow/lucid,tensorflow/lucid
|
from __future__ import absolute_import, division, print_function
import pytest
import tensorflow as tf
from lucid.modelzoo.vision_models import InceptionV1
from lucid.optvis import objectives, param, render, transform
model = InceptionV1()
model.load_graphdef()
@pytest.mark.parametrize("decorrelate", [True, False])
@pytest.mark.parametrize("fft", [True, False])
def test_integration(decorrelate, fft):
obj = objectives.neuron("mixed3a_pre_relu", 0)
param_f = lambda: param.image(16, decorrelate=decorrelate, fft=fft)
rendering = render.render_vis(model, obj, param_f=param_f, thresholds=(1,2),
verbose=False, transforms=[])
start_image = rendering[0]
end_image = rendering[-1]
objective_f = objectives.neuron("mixed3a", 177)
param_f = lambda: param.image(64, decorrelate=decorrelate, fft=fft)
rendering = render.render_vis(model, objective_f, param_f, verbose=False, thresholds=(0,64), use_fixed_seed=True)
start_image, end_image = rendering
assert (start_image != end_image).any()
Move model init into pytest fixture to avoid loading model and downloading graph just by importing the test module
|
from __future__ import absolute_import, division, print_function
import pytest
import tensorflow as tf
from lucid.modelzoo.vision_models import InceptionV1
from lucid.optvis import objectives, param, render, transform
@pytest.fixture
def inceptionv1():
model = InceptionV1()
model.load_graphdef()
return model
@pytest.mark.parametrize("decorrelate", [True, False])
@pytest.mark.parametrize("fft", [True, False])
def test_integration(decorrelate, fft, inceptionv1):
obj = objectives.neuron("mixed3a_pre_relu", 0)
param_f = lambda: param.image(16, decorrelate=decorrelate, fft=fft)
rendering = render.render_vis(inceptionv1, obj, param_f=param_f, thresholds=(1,2),
verbose=False, transforms=[])
start_image = rendering[0]
end_image = rendering[-1]
objective_f = objectives.neuron("mixed3a", 177)
param_f = lambda: param.image(64, decorrelate=decorrelate, fft=fft)
rendering = render.render_vis(inceptionv1, objective_f, param_f, verbose=False, thresholds=(0,64), use_fixed_seed=True)
start_image, end_image = rendering
assert (start_image != end_image).any()
|
<commit_before>from __future__ import absolute_import, division, print_function
import pytest
import tensorflow as tf
from lucid.modelzoo.vision_models import InceptionV1
from lucid.optvis import objectives, param, render, transform
model = InceptionV1()
model.load_graphdef()
@pytest.mark.parametrize("decorrelate", [True, False])
@pytest.mark.parametrize("fft", [True, False])
def test_integration(decorrelate, fft):
obj = objectives.neuron("mixed3a_pre_relu", 0)
param_f = lambda: param.image(16, decorrelate=decorrelate, fft=fft)
rendering = render.render_vis(model, obj, param_f=param_f, thresholds=(1,2),
verbose=False, transforms=[])
start_image = rendering[0]
end_image = rendering[-1]
objective_f = objectives.neuron("mixed3a", 177)
param_f = lambda: param.image(64, decorrelate=decorrelate, fft=fft)
rendering = render.render_vis(model, objective_f, param_f, verbose=False, thresholds=(0,64), use_fixed_seed=True)
start_image, end_image = rendering
assert (start_image != end_image).any()
<commit_msg>Move model init into pytest fixture to avoid loading model and downloading graph just by importing the test module<commit_after>
|
from __future__ import absolute_import, division, print_function
import pytest
import tensorflow as tf
from lucid.modelzoo.vision_models import InceptionV1
from lucid.optvis import objectives, param, render, transform
@pytest.fixture
def inceptionv1():
model = InceptionV1()
model.load_graphdef()
return model
@pytest.mark.parametrize("decorrelate", [True, False])
@pytest.mark.parametrize("fft", [True, False])
def test_integration(decorrelate, fft, inceptionv1):
obj = objectives.neuron("mixed3a_pre_relu", 0)
param_f = lambda: param.image(16, decorrelate=decorrelate, fft=fft)
rendering = render.render_vis(inceptionv1, obj, param_f=param_f, thresholds=(1,2),
verbose=False, transforms=[])
start_image = rendering[0]
end_image = rendering[-1]
objective_f = objectives.neuron("mixed3a", 177)
param_f = lambda: param.image(64, decorrelate=decorrelate, fft=fft)
rendering = render.render_vis(inceptionv1, objective_f, param_f, verbose=False, thresholds=(0,64), use_fixed_seed=True)
start_image, end_image = rendering
assert (start_image != end_image).any()
|
from __future__ import absolute_import, division, print_function
import pytest
import tensorflow as tf
from lucid.modelzoo.vision_models import InceptionV1
from lucid.optvis import objectives, param, render, transform
model = InceptionV1()
model.load_graphdef()
@pytest.mark.parametrize("decorrelate", [True, False])
@pytest.mark.parametrize("fft", [True, False])
def test_integration(decorrelate, fft):
obj = objectives.neuron("mixed3a_pre_relu", 0)
param_f = lambda: param.image(16, decorrelate=decorrelate, fft=fft)
rendering = render.render_vis(model, obj, param_f=param_f, thresholds=(1,2),
verbose=False, transforms=[])
start_image = rendering[0]
end_image = rendering[-1]
objective_f = objectives.neuron("mixed3a", 177)
param_f = lambda: param.image(64, decorrelate=decorrelate, fft=fft)
rendering = render.render_vis(model, objective_f, param_f, verbose=False, thresholds=(0,64), use_fixed_seed=True)
start_image, end_image = rendering
assert (start_image != end_image).any()
Move model init into pytest fixture to avoid loading model and downloading graph just by importing the test modulefrom __future__ import absolute_import, division, print_function
import pytest
import tensorflow as tf
from lucid.modelzoo.vision_models import InceptionV1
from lucid.optvis import objectives, param, render, transform
@pytest.fixture
def inceptionv1():
model = InceptionV1()
model.load_graphdef()
return model
@pytest.mark.parametrize("decorrelate", [True, False])
@pytest.mark.parametrize("fft", [True, False])
def test_integration(decorrelate, fft, inceptionv1):
obj = objectives.neuron("mixed3a_pre_relu", 0)
param_f = lambda: param.image(16, decorrelate=decorrelate, fft=fft)
rendering = render.render_vis(inceptionv1, obj, param_f=param_f, thresholds=(1,2),
verbose=False, transforms=[])
start_image = rendering[0]
end_image = rendering[-1]
objective_f = objectives.neuron("mixed3a", 177)
param_f = lambda: param.image(64, decorrelate=decorrelate, fft=fft)
rendering = render.render_vis(inceptionv1, objective_f, param_f, verbose=False, thresholds=(0,64), use_fixed_seed=True)
start_image, end_image = rendering
assert (start_image != end_image).any()
|
<commit_before>from __future__ import absolute_import, division, print_function
import pytest
import tensorflow as tf
from lucid.modelzoo.vision_models import InceptionV1
from lucid.optvis import objectives, param, render, transform
model = InceptionV1()
model.load_graphdef()
@pytest.mark.parametrize("decorrelate", [True, False])
@pytest.mark.parametrize("fft", [True, False])
def test_integration(decorrelate, fft):
obj = objectives.neuron("mixed3a_pre_relu", 0)
param_f = lambda: param.image(16, decorrelate=decorrelate, fft=fft)
rendering = render.render_vis(model, obj, param_f=param_f, thresholds=(1,2),
verbose=False, transforms=[])
start_image = rendering[0]
end_image = rendering[-1]
objective_f = objectives.neuron("mixed3a", 177)
param_f = lambda: param.image(64, decorrelate=decorrelate, fft=fft)
rendering = render.render_vis(model, objective_f, param_f, verbose=False, thresholds=(0,64), use_fixed_seed=True)
start_image, end_image = rendering
assert (start_image != end_image).any()
<commit_msg>Move model init into pytest fixture to avoid loading model and downloading graph just by importing the test module<commit_after>from __future__ import absolute_import, division, print_function
import pytest
import tensorflow as tf
from lucid.modelzoo.vision_models import InceptionV1
from lucid.optvis import objectives, param, render, transform
@pytest.fixture
def inceptionv1():
model = InceptionV1()
model.load_graphdef()
return model
@pytest.mark.parametrize("decorrelate", [True, False])
@pytest.mark.parametrize("fft", [True, False])
def test_integration(decorrelate, fft, inceptionv1):
obj = objectives.neuron("mixed3a_pre_relu", 0)
param_f = lambda: param.image(16, decorrelate=decorrelate, fft=fft)
rendering = render.render_vis(inceptionv1, obj, param_f=param_f, thresholds=(1,2),
verbose=False, transforms=[])
start_image = rendering[0]
end_image = rendering[-1]
objective_f = objectives.neuron("mixed3a", 177)
param_f = lambda: param.image(64, decorrelate=decorrelate, fft=fft)
rendering = render.render_vis(inceptionv1, objective_f, param_f, verbose=False, thresholds=(0,64), use_fixed_seed=True)
start_image, end_image = rendering
assert (start_image != end_image).any()
|
b14ec035f6a4890ce85504f449402aec857227fe
|
cla_backend/apps/status/tests/smoketests.py
|
cla_backend/apps/status/tests/smoketests.py
|
import unittest
from celery import Celery
from django.conf import settings
from django.db import connection
class SmokeTests(unittest.TestCase):
def setUp(self):
pass
def test_can_access_db(self):
"access the database"
cursor = connection.cursor()
cursor.execute('SELECT 1')
row = cursor.fetchone()
self.assertEqual(1, row[0])
def test_can_access_celery(self):
"connect to SQS"
if not getattr(settings, 'CELERY_ALWAYS_EAGER', False):
conn = Celery('cla_backend').connection()
conn.config_from_object('django.conf:settings')
conn.connect()
conn.release()
|
import unittest
from celery import Celery
from django.conf import settings
from django.db import connection
class SmokeTests(unittest.TestCase):
def setUp(self):
pass
def test_can_access_db(self):
"access the database"
cursor = connection.cursor()
cursor.execute('SELECT 1')
row = cursor.fetchone()
self.assertEqual(1, row[0])
def test_can_access_celery(self):
"connect to SQS"
if not getattr(settings, 'CELERY_ALWAYS_EAGER', False):
app = Celery('cla_backend')
app.config_from_object('django.conf:settings')
app.connection().connect()
conn.connect()
conn.release()
|
Configure Celery correctly in smoketest
|
Configure Celery correctly in smoketest
|
Python
|
mit
|
ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend
|
import unittest
from celery import Celery
from django.conf import settings
from django.db import connection
class SmokeTests(unittest.TestCase):
def setUp(self):
pass
def test_can_access_db(self):
"access the database"
cursor = connection.cursor()
cursor.execute('SELECT 1')
row = cursor.fetchone()
self.assertEqual(1, row[0])
def test_can_access_celery(self):
"connect to SQS"
if not getattr(settings, 'CELERY_ALWAYS_EAGER', False):
conn = Celery('cla_backend').connection()
conn.config_from_object('django.conf:settings')
conn.connect()
conn.release()
Configure Celery correctly in smoketest
|
import unittest
from celery import Celery
from django.conf import settings
from django.db import connection
class SmokeTests(unittest.TestCase):
def setUp(self):
pass
def test_can_access_db(self):
"access the database"
cursor = connection.cursor()
cursor.execute('SELECT 1')
row = cursor.fetchone()
self.assertEqual(1, row[0])
def test_can_access_celery(self):
"connect to SQS"
if not getattr(settings, 'CELERY_ALWAYS_EAGER', False):
app = Celery('cla_backend')
app.config_from_object('django.conf:settings')
app.connection().connect()
conn.connect()
conn.release()
|
<commit_before>import unittest
from celery import Celery
from django.conf import settings
from django.db import connection
class SmokeTests(unittest.TestCase):
def setUp(self):
pass
def test_can_access_db(self):
"access the database"
cursor = connection.cursor()
cursor.execute('SELECT 1')
row = cursor.fetchone()
self.assertEqual(1, row[0])
def test_can_access_celery(self):
"connect to SQS"
if not getattr(settings, 'CELERY_ALWAYS_EAGER', False):
conn = Celery('cla_backend').connection()
conn.config_from_object('django.conf:settings')
conn.connect()
conn.release()
<commit_msg>Configure Celery correctly in smoketest<commit_after>
|
import unittest
from celery import Celery
from django.conf import settings
from django.db import connection
class SmokeTests(unittest.TestCase):
def setUp(self):
pass
def test_can_access_db(self):
"access the database"
cursor = connection.cursor()
cursor.execute('SELECT 1')
row = cursor.fetchone()
self.assertEqual(1, row[0])
def test_can_access_celery(self):
"connect to SQS"
if not getattr(settings, 'CELERY_ALWAYS_EAGER', False):
app = Celery('cla_backend')
app.config_from_object('django.conf:settings')
app.connection().connect()
conn.connect()
conn.release()
|
import unittest
from celery import Celery
from django.conf import settings
from django.db import connection
class SmokeTests(unittest.TestCase):
def setUp(self):
pass
def test_can_access_db(self):
"access the database"
cursor = connection.cursor()
cursor.execute('SELECT 1')
row = cursor.fetchone()
self.assertEqual(1, row[0])
def test_can_access_celery(self):
"connect to SQS"
if not getattr(settings, 'CELERY_ALWAYS_EAGER', False):
conn = Celery('cla_backend').connection()
conn.config_from_object('django.conf:settings')
conn.connect()
conn.release()
Configure Celery correctly in smoketestimport unittest
from celery import Celery
from django.conf import settings
from django.db import connection
class SmokeTests(unittest.TestCase):
def setUp(self):
pass
def test_can_access_db(self):
"access the database"
cursor = connection.cursor()
cursor.execute('SELECT 1')
row = cursor.fetchone()
self.assertEqual(1, row[0])
def test_can_access_celery(self):
"connect to SQS"
if not getattr(settings, 'CELERY_ALWAYS_EAGER', False):
app = Celery('cla_backend')
app.config_from_object('django.conf:settings')
app.connection().connect()
conn.connect()
conn.release()
|
<commit_before>import unittest
from celery import Celery
from django.conf import settings
from django.db import connection
class SmokeTests(unittest.TestCase):
def setUp(self):
pass
def test_can_access_db(self):
"access the database"
cursor = connection.cursor()
cursor.execute('SELECT 1')
row = cursor.fetchone()
self.assertEqual(1, row[0])
def test_can_access_celery(self):
"connect to SQS"
if not getattr(settings, 'CELERY_ALWAYS_EAGER', False):
conn = Celery('cla_backend').connection()
conn.config_from_object('django.conf:settings')
conn.connect()
conn.release()
<commit_msg>Configure Celery correctly in smoketest<commit_after>import unittest
from celery import Celery
from django.conf import settings
from django.db import connection
class SmokeTests(unittest.TestCase):
def setUp(self):
pass
def test_can_access_db(self):
"access the database"
cursor = connection.cursor()
cursor.execute('SELECT 1')
row = cursor.fetchone()
self.assertEqual(1, row[0])
def test_can_access_celery(self):
"connect to SQS"
if not getattr(settings, 'CELERY_ALWAYS_EAGER', False):
app = Celery('cla_backend')
app.config_from_object('django.conf:settings')
app.connection().connect()
conn.connect()
conn.release()
|
4158e2b5d2d7524f4d8e66b9ee021c1f63e11b25
|
blanc_basic_events/events/templatetags/events_tags.py
|
blanc_basic_events/events/templatetags/events_tags.py
|
from django import template
from blanc_basic_events.events.models import Event
register = template.Library()
@register.assignment_tag
def get_events():
return Event.objects.all().prefetch_related('recurringevent_set', 'recurringeventexclusion_set')
|
from django import template
from blanc_basic_events.events.models import Category, Event
register = template.Library()
@register.assignment_tag
def get_events_categories():
return Category.objects.all()
@register.assignment_tag
def get_events():
return Event.objects.all().prefetch_related('recurringevent_set', 'recurringeventexclusion_set')
|
Tag to get all categories
|
Tag to get all categories
|
Python
|
bsd-3-clause
|
blancltd/blanc-basic-events
|
from django import template
from blanc_basic_events.events.models import Event
register = template.Library()
@register.assignment_tag
def get_events():
return Event.objects.all().prefetch_related('recurringevent_set', 'recurringeventexclusion_set')
Tag to get all categories
|
from django import template
from blanc_basic_events.events.models import Category, Event
register = template.Library()
@register.assignment_tag
def get_events_categories():
return Category.objects.all()
@register.assignment_tag
def get_events():
return Event.objects.all().prefetch_related('recurringevent_set', 'recurringeventexclusion_set')
|
<commit_before>from django import template
from blanc_basic_events.events.models import Event
register = template.Library()
@register.assignment_tag
def get_events():
return Event.objects.all().prefetch_related('recurringevent_set', 'recurringeventexclusion_set')
<commit_msg>Tag to get all categories<commit_after>
|
from django import template
from blanc_basic_events.events.models import Category, Event
register = template.Library()
@register.assignment_tag
def get_events_categories():
return Category.objects.all()
@register.assignment_tag
def get_events():
return Event.objects.all().prefetch_related('recurringevent_set', 'recurringeventexclusion_set')
|
from django import template
from blanc_basic_events.events.models import Event
register = template.Library()
@register.assignment_tag
def get_events():
return Event.objects.all().prefetch_related('recurringevent_set', 'recurringeventexclusion_set')
Tag to get all categoriesfrom django import template
from blanc_basic_events.events.models import Category, Event
register = template.Library()
@register.assignment_tag
def get_events_categories():
return Category.objects.all()
@register.assignment_tag
def get_events():
return Event.objects.all().prefetch_related('recurringevent_set', 'recurringeventexclusion_set')
|
<commit_before>from django import template
from blanc_basic_events.events.models import Event
register = template.Library()
@register.assignment_tag
def get_events():
return Event.objects.all().prefetch_related('recurringevent_set', 'recurringeventexclusion_set')
<commit_msg>Tag to get all categories<commit_after>from django import template
from blanc_basic_events.events.models import Category, Event
register = template.Library()
@register.assignment_tag
def get_events_categories():
return Category.objects.all()
@register.assignment_tag
def get_events():
return Event.objects.all().prefetch_related('recurringevent_set', 'recurringeventexclusion_set')
|
1344b1e521afd83494f99930260c00f679e883d1
|
cms/djangoapps/contentstore/views/session_kv_store.py
|
cms/djangoapps/contentstore/views/session_kv_store.py
|
from xblock.runtime import KeyValueStore, InvalidScopeError
class SessionKeyValueStore(KeyValueStore):
def __init__(self, request, model_data):
self._model_data = model_data
self._session = request.session
def get(self, key):
try:
return self._model_data[key.field_name]
except (KeyError, InvalidScopeError):
return self._session[tuple(key)]
def set(self, key, value):
try:
self._model_data[key.field_name] = value
except (KeyError, InvalidScopeError):
self._session[tuple(key)] = value
def delete(self, key):
try:
del self._model_data[key.field_name]
except (KeyError, InvalidScopeError):
del self._session[tuple(key)]
def has(self, key):
return key in self._model_data or key in self._session
|
from xblock.runtime import KeyValueStore, InvalidScopeError
class SessionKeyValueStore(KeyValueStore):
def __init__(self, request, descriptor_model_data):
self._descriptor_model_data = descriptor_model_data
self._session = request.session
def get(self, key):
try:
return self._descriptor_model_data[key.field_name]
except (KeyError, InvalidScopeError):
return self._session[tuple(key)]
def set(self, key, value):
try:
self._descriptor_model_data[key.field_name] = value
except (KeyError, InvalidScopeError):
self._session[tuple(key)] = value
def delete(self, key):
try:
del self._descriptor_model_data[key.field_name]
except (KeyError, InvalidScopeError):
del self._session[tuple(key)]
def has(self, key):
return key in self._descriptor_model_data or key in self._session
|
Make SessionKeyValueStore variable names clearer
|
Make SessionKeyValueStore variable names clearer
|
Python
|
agpl-3.0
|
TsinghuaX/edx-platform,cognitiveclass/edx-platform,shashank971/edx-platform,J861449197/edx-platform,kursitet/edx-platform,LearnEra/LearnEraPlaftform,chauhanhardik/populo_2,philanthropy-u/edx-platform,analyseuc3m/ANALYSE-v1,amir-qayyum-khan/edx-platform,10clouds/edx-platform,abdoosh00/edraak,Semi-global/edx-platform,sameetb-cuelogic/edx-platform-test,waheedahmed/edx-platform,chauhanhardik/populo,shubhdev/edx-platform,DNFcode/edx-platform,hkawasaki/kawasaki-aio8-1,vismartltd/edx-platform,waheedahmed/edx-platform,fintech-circle/edx-platform,jamiefolsom/edx-platform,xingyepei/edx-platform,ovnicraft/edx-platform,nanolearningllc/edx-platform-cypress-2,longmen21/edx-platform,MSOpenTech/edx-platform,pdehaye/theming-edx-platform,zerobatu/edx-platform,bitifirefly/edx-platform,mushtaqak/edx-platform,ahmadiga/min_edx,RPI-OPENEDX/edx-platform,mbareta/edx-platform-ft,arbrandes/edx-platform,hmcmooc/muddx-platform,appliedx/edx-platform,mahendra-r/edx-platform,UOMx/edx-platform,bitifirefly/edx-platform,pabloborrego93/edx-platform,kmoocdev/edx-platform,zadgroup/edx-platform,cecep-edu/edx-platform,ampax/edx-platform,Lektorium-LLC/edx-platform,andyzsf/edx,MSOpenTech/edx-platform,synergeticsedx/deployment-wipro,appsembler/edx-platform,ovnicraft/edx-platform,jonathan-beard/edx-platform,naresh21/synergetics-edx-platform,mjirayu/sit_academy,devs1991/test_edx_docmode,praveen-pal/edx-platform,nanolearningllc/edx-platform-cypress-2,eduNEXT/edx-platform,nttks/edx-platform,bdero/edx-platform,peterm-itr/edx-platform,chudaol/edx-platform,dsajkl/reqiop,praveen-pal/edx-platform,kmoocdev2/edx-platform,auferack08/edx-platform,EduPepperPD/pepper2013,teltek/edx-platform,msegado/edx-platform,Edraak/edx-platform,ZLLab-Mooc/edx-platform,shurihell/testasia,caesar2164/edx-platform,naresh21/synergetics-edx-platform,raccoongang/edx-platform,fintech-circle/edx-platform,Endika/edx-platform,mbareta/edx-platform-ft,stvstnfrd/edx-platform,chand3040/cloud_that,morpheby/levelup-by,antonve/s4-project-mooc,edry/edx-platform,DNFcode/edx-platform,nttks/jenkins-test,gsehub/edx-platform,andyzsf/edx,chrisndodge/edx-platform,wwj718/edx-platform,ubc/edx-platform,PepperPD/edx-pepper-platform,beni55/edx-platform,nanolearningllc/edx-platform-cypress,rationalAgent/edx-platform-custom,eduNEXT/edunext-platform,tiagochiavericosta/edx-platform,philanthropy-u/edx-platform,motion2015/a3,mjg2203/edx-platform-seas,kmoocdev/edx-platform,jonathan-beard/edx-platform,zerobatu/edx-platform,CourseTalk/edx-platform,Softmotions/edx-platform,utecuy/edx-platform,dcosentino/edx-platform,stvstnfrd/edx-platform,jazztpt/edx-platform,ESOedX/edx-platform,beacloudgenius/edx-platform,hastexo/edx-platform,jzoldak/edx-platform,nanolearning/edx-platform,WatanabeYasumasa/edx-platform,ahmadiga/min_edx,Stanford-Online/edx-platform,wwj718/edx-platform,ubc/edx-platform,morpheby/levelup-by,mjirayu/sit_academy,cyanna/edx-platform,motion2015/edx-platform,dcosentino/edx-platform,LearnEra/LearnEraPlaftform,dcosentino/edx-platform,pku9104038/edx-platform,olexiim/edx-platform,mahendra-r/edx-platform,xingyepei/edx-platform,atsolakid/edx-platform,miptliot/edx-platform,eestay/edx-platform,zerobatu/edx-platform,Stanford-Online/edx-platform,nagyistoce/edx-platform,UOMx/edx-platform,mjirayu/sit_academy,peterm-itr/edx-platform,Softmotions/edx-platform,openfun/edx-platform,kmoocdev2/edx-platform,J861449197/edx-platform,gymnasium/edx-platform,rhndg/openedx,chauhanhardik/populo,appliedx/edx-platform,polimediaupv/edx-platform,Shrhawk/edx-platform,mcgachey/edx-platform,nanolearningllc/edx-platform-cypress-2,torchingloom/edx-platform,TsinghuaX/edx-platform,ahmedaljazzar/edx-platform,rhndg/openedx,procangroup/edx-platform,kxliugang/edx-platform,EduPepperPD/pepper2013,halvertoluke/edx-platform,jbzdak/edx-platform,benpatterson/edx-platform,longmen21/edx-platform,nagyistoce/edx-platform,cselis86/edx-platform,jjmiranda/edx-platform,CredoReference/edx-platform,DNFcode/edx-platform,martynovp/edx-platform,RPI-OPENEDX/edx-platform,JCBarahona/edX,WatanabeYasumasa/edx-platform,OmarIthawi/edx-platform,pelikanchik/edx-platform,cognitiveclass/edx-platform,unicri/edx-platform,Edraak/edraak-platform,BehavioralInsightsTeam/edx-platform,nagyistoce/edx-platform,fly19890211/edx-platform,nanolearningllc/edx-platform-cypress,iivic/BoiseStateX,wwj718/edx-platform,procangroup/edx-platform,shurihell/testasia,halvertoluke/edx-platform,jazkarta/edx-platform-for-isc,andyzsf/edx,hkawasaki/kawasaki-aio8-2,eestay/edx-platform,vikas1885/test1,bitifirefly/edx-platform,Ayub-Khan/edx-platform,a-parhom/edx-platform,LICEF/edx-platform,arifsetiawan/edx-platform,jjmiranda/edx-platform,ampax/edx-platform-backup,pelikanchik/edx-platform,yokose-ks/edx-platform,appsembler/edx-platform,angelapper/edx-platform,waheedahmed/edx-platform,nttks/jenkins-test,bitifirefly/edx-platform,rue89-tech/edx-platform,zerobatu/edx-platform,jswope00/GAI,ahmedaljazzar/edx-platform,longmen21/edx-platform,antonve/s4-project-mooc,LearnEra/LearnEraPlaftform,antoviaque/edx-platform,msegado/edx-platform,leansoft/edx-platform,SivilTaram/edx-platform,franosincic/edx-platform,ampax/edx-platform,Endika/edx-platform,devs1991/test_edx_docmode,SivilTaram/edx-platform,JioEducation/edx-platform,kamalx/edx-platform,Edraak/circleci-edx-platform,Shrhawk/edx-platform,inares/edx-platform,synergeticsedx/deployment-wipro,polimediaupv/edx-platform,zhenzhai/edx-platform,jazkarta/edx-platform,EDUlib/edx-platform,etzhou/edx-platform,beacloudgenius/edx-platform,raccoongang/edx-platform,jbassen/edx-platform,J861449197/edx-platform,dsajkl/123,IndonesiaX/edx-platform,JioEducation/edx-platform,solashirai/edx-platform,jswope00/griffinx,TeachAtTUM/edx-platform,Edraak/circleci-edx-platform,halvertoluke/edx-platform,pabloborrego93/edx-platform,jswope00/GAI,pelikanchik/edx-platform,bdero/edx-platform,fly19890211/edx-platform,Semi-global/edx-platform,jruiperezv/ANALYSE,louyihua/edx-platform,rationalAgent/edx-platform-custom,hkawasaki/kawasaki-aio8-1,sudheerchintala/LearnEraPlatForm,syjeon/new_edx,arifsetiawan/edx-platform,dsajkl/123,valtech-mooc/edx-platform,shabab12/edx-platform,adoosii/edx-platform,edx-solutions/edx-platform,ahmedaljazzar/edx-platform,shurihell/testasia,leansoft/edx-platform,solashirai/edx-platform,wwj718/edx-platform,jbassen/edx-platform,10clouds/edx-platform,ESOedX/edx-platform,xuxiao19910803/edx-platform,EduPepperPDTesting/pepper2013-testing,UXE/local-edx,MakeHer/edx-platform,jbassen/edx-platform,playm2mboy/edx-platform,LICEF/edx-platform,edry/edx-platform,lduarte1991/edx-platform,chrisndodge/edx-platform,playm2mboy/edx-platform,tiagochiavericosta/edx-platform,simbs/edx-platform,jazkarta/edx-platform,jswope00/GAI,EduPepperPD/pepper2013,EDUlib/edx-platform,tiagochiavericosta/edx-platform,zubair-arbi/edx-platform,shabab12/edx-platform,jswope00/griffinx,hastexo/edx-platform,atsolakid/edx-platform,PepperPD/edx-pepper-platform,BehavioralInsightsTeam/edx-platform,miptliot/edx-platform,nttks/jenkins-test,doganov/edx-platform,hastexo/edx-platform,chauhanhardik/populo,JCBarahona/edX,jolyonb/edx-platform,abdoosh00/edraak,lduarte1991/edx-platform,ahmadio/edx-platform,apigee/edx-platform,ahmadiga/min_edx,msegado/edx-platform,IITBinterns13/edx-platform-dev,Livit/Livit.Learn.EdX,Unow/edx-platform,IONISx/edx-platform,zofuthan/edx-platform,cecep-edu/edx-platform,SravanthiSinha/edx-platform,caesar2164/edx-platform,dcosentino/edx-platform,shubhdev/edxOnBaadal,eemirtekin/edx-platform,ahmadiga/min_edx,vikas1885/test1,Kalyzee/edx-platform,mjirayu/sit_academy,pomegranited/edx-platform,appliedx/edx-platform,kamalx/edx-platform,morenopc/edx-platform,Livit/Livit.Learn.EdX,knehez/edx-platform,louyihua/edx-platform,Ayub-Khan/edx-platform,LICEF/edx-platform,rationalAgent/edx-platform-custom,Endika/edx-platform,ferabra/edx-platform,openfun/edx-platform,solashirai/edx-platform,UXE/local-edx,caesar2164/edx-platform,kamalx/edx-platform,defance/edx-platform,beacloudgenius/edx-platform,marcore/edx-platform,beacloudgenius/edx-platform,hkawasaki/kawasaki-aio8-0,bdero/edx-platform,gymnasium/edx-platform,etzhou/edx-platform,ak2703/edx-platform,hkawasaki/kawasaki-aio8-0,kursitet/edx-platform,zadgroup/edx-platform,SravanthiSinha/edx-platform,simbs/edx-platform,jswope00/GAI,angelapper/edx-platform,B-MOOC/edx-platform,jswope00/griffinx,praveen-pal/edx-platform,AkA84/edx-platform,carsongee/edx-platform,abdoosh00/edx-rtl-final,xingyepei/edx-platform,miptliot/edx-platform,zadgroup/edx-platform,ZLLab-Mooc/edx-platform,fintech-circle/edx-platform,devs1991/test_edx_docmode,zhenzhai/edx-platform,cognitiveclass/edx-platform,DefyVentures/edx-platform,sameetb-cuelogic/edx-platform-test,ak2703/edx-platform,nanolearning/edx-platform,y12uc231/edx-platform,utecuy/edx-platform,hmcmooc/muddx-platform,CourseTalk/edx-platform,WatanabeYasumasa/edx-platform,ampax/edx-platform-backup,shubhdev/openedx,MakeHer/edx-platform,fly19890211/edx-platform,jolyonb/edx-platform,kursitet/edx-platform,IndonesiaX/edx-platform,edx/edx-platform,appliedx/edx-platform,mushtaqak/edx-platform,shurihell/testasia,franosincic/edx-platform,pepeportela/edx-platform,alexthered/kienhoc-platform,shubhdev/edxOnBaadal,deepsrijit1105/edx-platform,wwj718/ANALYSE,mcgachey/edx-platform,beni55/edx-platform,shabab12/edx-platform,jelugbo/tundex,MSOpenTech/edx-platform,Endika/edx-platform,ubc/edx-platform,jjmiranda/edx-platform,kalebhartje/schoolboost,romain-li/edx-platform,TeachAtTUM/edx-platform,xingyepei/edx-platform,SravanthiSinha/edx-platform,jazkarta/edx-platform-for-isc,Edraak/circleci-edx-platform,ZLLab-Mooc/edx-platform,Softmotions/edx-platform,rationalAgent/edx-platform-custom,polimediaupv/edx-platform,hastexo/edx-platform,devs1991/test_edx_docmode,auferack08/edx-platform,10clouds/edx-platform,amir-qayyum-khan/edx-platform,PepperPD/edx-pepper-platform,doismellburning/edx-platform,ahmadio/edx-platform,jbzdak/edx-platform,jazkarta/edx-platform,mahendra-r/edx-platform,Edraak/circleci-edx-platform,JioEducation/edx-platform,cpennington/edx-platform,kmoocdev/edx-platform,bitifirefly/edx-platform,naresh21/synergetics-edx-platform,4eek/edx-platform,ESOedX/edx-platform,ovnicraft/edx-platform,edx-solutions/edx-platform,adoosii/edx-platform,IndonesiaX/edx-platform,chauhanhardik/populo,EduPepperPDTesting/pepper2013-testing,shubhdev/edx-platform,antoviaque/edx-platform,Unow/edx-platform,RPI-OPENEDX/edx-platform,raccoongang/edx-platform,sameetb-cuelogic/edx-platform-test,wwj718/ANALYSE,xuxiao19910803/edx-platform,MakeHer/edx-platform,ampax/edx-platform-backup,TsinghuaX/edx-platform,naresh21/synergetics-edx-platform,louyihua/edx-platform,ampax/edx-platform,simbs/edx-platform,xinjiguaike/edx-platform,proversity-org/edx-platform,knehez/edx-platform,chudaol/edx-platform,vikas1885/test1,carsongee/edx-platform,IndonesiaX/edx-platform,MakeHer/edx-platform,Kalyzee/edx-platform,shashank971/edx-platform,Kalyzee/edx-platform,B-MOOC/edx-platform,dsajkl/123,jswope00/griffinx,sudheerchintala/LearnEraPlatForm,kmoocdev2/edx-platform,rue89-tech/edx-platform,shurihell/testasia,Shrhawk/edx-platform,Semi-global/edx-platform,arbrandes/edx-platform,vasyarv/edx-platform,nanolearningllc/edx-platform-cypress-2,pomegranited/edx-platform,hkawasaki/kawasaki-aio8-2,xuxiao19910803/edx-platform,mitocw/edx-platform,xuxiao19910803/edx,nanolearning/edx-platform,nikolas/edx-platform,jamesblunt/edx-platform,motion2015/a3,IITBinterns13/edx-platform-dev,kalebhartje/schoolboost,tanmaykm/edx-platform,jelugbo/tundex,beni55/edx-platform,pepeportela/edx-platform,nttks/edx-platform,caesar2164/edx-platform,abdoosh00/edraak,cpennington/edx-platform,kxliugang/edx-platform,hkawasaki/kawasaki-aio8-1,kursitet/edx-platform,rue89-tech/edx-platform,appliedx/edx-platform,morpheby/levelup-by,adoosii/edx-platform,alexthered/kienhoc-platform,eduNEXT/edunext-platform,nanolearning/edx-platform,IndonesiaX/edx-platform,knehez/edx-platform,nikolas/edx-platform,msegado/edx-platform,olexiim/edx-platform,pdehaye/theming-edx-platform,longmen21/edx-platform,hamzehd/edx-platform,mitocw/edx-platform,ovnicraft/edx-platform,bigdatauniversity/edx-platform,mahendra-r/edx-platform,kmoocdev/edx-platform,jazkarta/edx-platform,nanolearningllc/edx-platform-cypress,ahmadio/edx-platform,eestay/edx-platform,waheedahmed/edx-platform,mbareta/edx-platform-ft,kursitet/edx-platform,lduarte1991/edx-platform,wwj718/ANALYSE,EDUlib/edx-platform,motion2015/edx-platform,TsinghuaX/edx-platform,doganov/edx-platform,alu042/edx-platform,zofuthan/edx-platform,prarthitm/edxplatform,shashank971/edx-platform,deepsrijit1105/edx-platform,y12uc231/edx-platform,nanolearningllc/edx-platform-cypress,utecuy/edx-platform,pepeportela/edx-platform,EDUlib/edx-platform,romain-li/edx-platform,iivic/BoiseStateX,Shrhawk/edx-platform,DefyVentures/edx-platform,Edraak/edraak-platform,BehavioralInsightsTeam/edx-platform,arifsetiawan/edx-platform,sudheerchintala/LearnEraPlatForm,jonathan-beard/edx-platform,cpennington/edx-platform,nikolas/edx-platform,utecuy/edx-platform,nikolas/edx-platform,torchingloom/edx-platform,pepeportela/edx-platform,Softmotions/edx-platform,gsehub/edx-platform,RPI-OPENEDX/edx-platform,Livit/Livit.Learn.EdX,vasyarv/edx-platform,arifsetiawan/edx-platform,longmen21/edx-platform,cyanna/edx-platform,bigdatauniversity/edx-platform,dsajkl/123,yokose-ks/edx-platform,hamzehd/edx-platform,DNFcode/edx-platform,zubair-arbi/edx-platform,eduNEXT/edx-platform,don-github/edx-platform,syjeon/new_edx,synergeticsedx/deployment-wipro,knehez/edx-platform,inares/edx-platform,chrisndodge/edx-platform,cyanna/edx-platform,TeachAtTUM/edx-platform,xuxiao19910803/edx,jamiefolsom/edx-platform,IONISx/edx-platform,nttks/edx-platform,motion2015/edx-platform,doismellburning/edx-platform,pabloborrego93/edx-platform,eestay/edx-platform,nttks/jenkins-test,SravanthiSinha/edx-platform,chauhanhardik/populo_2,motion2015/edx-platform,unicri/edx-platform,shashank971/edx-platform,iivic/BoiseStateX,shubhdev/openedx,mtlchun/edx,chand3040/cloud_that,eduNEXT/edunext-platform,olexiim/edx-platform,tanmaykm/edx-platform,teltek/edx-platform,dkarakats/edx-platform,doganov/edx-platform,praveen-pal/edx-platform,apigee/edx-platform,dsajkl/reqiop,wwj718/edx-platform,ahmadiga/min_edx,cyanna/edx-platform,torchingloom/edx-platform,CourseTalk/edx-platform,syjeon/new_edx,nanolearningllc/edx-platform-cypress,defance/edx-platform,Lektorium-LLC/edx-platform,yokose-ks/edx-platform,LICEF/edx-platform,angelapper/edx-platform,mbareta/edx-platform-ft,antonve/s4-project-mooc,chudaol/edx-platform,hkawasaki/kawasaki-aio8-0,B-MOOC/edx-platform,rismalrv/edx-platform,ak2703/edx-platform,mcgachey/edx-platform,rhndg/openedx,teltek/edx-platform,devs1991/test_edx_docmode,edx-solutions/edx-platform,shubhdev/openedx,xinjiguaike/edx-platform,mjg2203/edx-platform-seas,halvertoluke/edx-platform,Edraak/edx-platform,jbzdak/edx-platform,mtlchun/edx,rue89-tech/edx-platform,romain-li/edx-platform,SivilTaram/edx-platform,raccoongang/edx-platform,carsongee/edx-platform,eemirtekin/edx-platform,Ayub-Khan/edx-platform,playm2mboy/edx-platform,prarthitm/edxplatform,mushtaqak/edx-platform,jruiperezv/ANALYSE,DefyVentures/edx-platform,kalebhartje/schoolboost,a-parhom/edx-platform,synergeticsedx/deployment-wipro,DNFcode/edx-platform,xinjiguaike/edx-platform,sameetb-cuelogic/edx-platform-test,olexiim/edx-platform,pdehaye/theming-edx-platform,jamesblunt/edx-platform,Stanford-Online/edx-platform,chauhanhardik/populo_2,franosincic/edx-platform,OmarIthawi/edx-platform,abdoosh00/edraak,cselis86/edx-platform,IONISx/edx-platform,ubc/edx-platform,jbassen/edx-platform,ferabra/edx-platform,pku9104038/edx-platform,philanthropy-u/edx-platform,mcgachey/edx-platform,shubhdev/edx-platform,JioEducation/edx-platform,eduNEXT/edunext-platform,jelugbo/tundex,UXE/local-edx,valtech-mooc/edx-platform,nttks/jenkins-test,PepperPD/edx-pepper-platform,openfun/edx-platform,eemirtekin/edx-platform,zofuthan/edx-platform,Softmotions/edx-platform,jbzdak/edx-platform,tanmaykm/edx-platform,unicri/edx-platform,olexiim/edx-platform,alexthered/kienhoc-platform,pdehaye/theming-edx-platform,cselis86/edx-platform,Unow/edx-platform,devs1991/test_edx_docmode,nanolearning/edx-platform,Edraak/circleci-edx-platform,zadgroup/edx-platform,jbzdak/edx-platform,fintech-circle/edx-platform,y12uc231/edx-platform,romain-li/edx-platform,dkarakats/edx-platform,wwj718/ANALYSE,shashank971/edx-platform,don-github/edx-platform,torchingloom/edx-platform,TeachAtTUM/edx-platform,jonathan-beard/edx-platform,martynovp/edx-platform,fly19890211/edx-platform,vasyarv/edx-platform,motion2015/a3,nagyistoce/edx-platform,morpheby/levelup-by,hamzehd/edx-platform,EduPepperPDTesting/pepper2013-testing,UOMx/edx-platform,doganov/edx-platform,jelugbo/tundex,inares/edx-platform,cselis86/edx-platform,eduNEXT/edx-platform,jazztpt/edx-platform,shubhdev/edx-platform,MakeHer/edx-platform,chudaol/edx-platform,jazkarta/edx-platform-for-isc,BehavioralInsightsTeam/edx-platform,don-github/edx-platform,hkawasaki/kawasaki-aio8-2,shubhdev/openedx,vasyarv/edx-platform,dkarakats/edx-platform,apigee/edx-platform,mcgachey/edx-platform,AkA84/edx-platform,xinjiguaike/edx-platform,marcore/edx-platform,alu042/edx-platform,edx-solutions/edx-platform,Livit/Livit.Learn.EdX,IONISx/edx-platform,hmcmooc/muddx-platform,edx/edx-platform,rationalAgent/edx-platform-custom,edry/edx-platform,bdero/edx-platform,JCBarahona/edX,zerobatu/edx-platform,procangroup/edx-platform,bigdatauniversity/edx-platform,rismalrv/edx-platform,zofuthan/edx-platform,pelikanchik/edx-platform,gsehub/edx-platform,fly19890211/edx-platform,zubair-arbi/edx-platform,arbrandes/edx-platform,jzoldak/edx-platform,openfun/edx-platform,AkA84/edx-platform,valtech-mooc/edx-platform,appsembler/edx-platform,adoosii/edx-platform,auferack08/edx-platform,wwj718/ANALYSE,ESOedX/edx-platform,Kalyzee/edx-platform,Ayub-Khan/edx-platform,mahendra-r/edx-platform,apigee/edx-platform,SivilTaram/edx-platform,chand3040/cloud_that,miptliot/edx-platform,xuxiao19910803/edx,tanmaykm/edx-platform,appsembler/edx-platform,rismalrv/edx-platform,tiagochiavericosta/edx-platform,chrisndodge/edx-platform,hamzehd/edx-platform,itsjeyd/edx-platform,Stanford-Online/edx-platform,pomegranited/edx-platform,dsajkl/123,JCBarahona/edX,doismellburning/edx-platform,jswope00/griffinx,cselis86/edx-platform,edx/edx-platform,procangroup/edx-platform,jelugbo/tundex,itsjeyd/edx-platform,philanthropy-u/edx-platform,gymnasium/edx-platform,EduPepperPDTesting/pepper2013-testing,torchingloom/edx-platform,shubhdev/edxOnBaadal,jamesblunt/edx-platform,EduPepperPDTesting/pepper2013-testing,benpatterson/edx-platform,jruiperezv/ANALYSE,playm2mboy/edx-platform,jzoldak/edx-platform,cognitiveclass/edx-platform,iivic/BoiseStateX,DefyVentures/edx-platform,dkarakats/edx-platform,ak2703/edx-platform,rhndg/openedx,kamalx/edx-platform,motion2015/a3,mtlchun/edx,edry/edx-platform,jazztpt/edx-platform,dsajkl/reqiop,Semi-global/edx-platform,sudheerchintala/LearnEraPlatForm,ampax/edx-platform,zofuthan/edx-platform,cecep-edu/edx-platform,shubhdev/openedx,jamiefolsom/edx-platform,zubair-arbi/edx-platform,shubhdev/edx-platform,simbs/edx-platform,polimediaupv/edx-platform,etzhou/edx-platform,gsehub/edx-platform,UOMx/edx-platform,J861449197/edx-platform,LearnEra/LearnEraPlaftform,vismartltd/edx-platform,DefyVentures/edx-platform,vismartltd/edx-platform,CredoReference/edx-platform,carsongee/edx-platform,don-github/edx-platform,EduPepperPD/pepper2013,Edraak/edx-platform,CredoReference/edx-platform,ampax/edx-platform-backup,mtlchun/edx,ampax/edx-platform-backup,rhndg/openedx,nagyistoce/edx-platform,adoosii/edx-platform,angelapper/edx-platform,PepperPD/edx-pepper-platform,devs1991/test_edx_docmode,kalebhartje/schoolboost,bigdatauniversity/edx-platform,kmoocdev2/edx-platform,UXE/local-edx,benpatterson/edx-platform,chauhanhardik/populo_2,utecuy/edx-platform,proversity-org/edx-platform,morenopc/edx-platform,franosincic/edx-platform,martynovp/edx-platform,cecep-edu/edx-platform,OmarIthawi/edx-platform,SivilTaram/edx-platform,LICEF/edx-platform,analyseuc3m/ANALYSE-v1,xuxiao19910803/edx-platform,jamesblunt/edx-platform,4eek/edx-platform,iivic/BoiseStateX,AkA84/edx-platform,shubhdev/edxOnBaadal,xuxiao19910803/edx,beni55/edx-platform,yokose-ks/edx-platform,jazztpt/edx-platform,AkA84/edx-platform,jamiefolsom/edx-platform,chudaol/edx-platform,cyanna/edx-platform,a-parhom/edx-platform,IONISx/edx-platform,ferabra/edx-platform,openfun/edx-platform,mitocw/edx-platform,antoviaque/edx-platform,cecep-edu/edx-platform,beacloudgenius/edx-platform,Edraak/edraak-platform,motion2015/edx-platform,hkawasaki/kawasaki-aio8-1,playm2mboy/edx-platform,romain-li/edx-platform,leansoft/edx-platform,vismartltd/edx-platform,kalebhartje/schoolboost,hkawasaki/kawasaki-aio8-2,halvertoluke/edx-platform,zubair-arbi/edx-platform,J861449197/edx-platform,devs1991/test_edx_docmode,stvstnfrd/edx-platform,Unow/edx-platform,morenopc/edx-platform,mjirayu/sit_academy,analyseuc3m/ANALYSE-v1,jjmiranda/edx-platform,y12uc231/edx-platform,jazztpt/edx-platform,4eek/edx-platform,edx/edx-platform,doganov/edx-platform,vikas1885/test1,zhenzhai/edx-platform,ferabra/edx-platform,arifsetiawan/edx-platform,inares/edx-platform,mtlchun/edx,ZLLab-Mooc/edx-platform,deepsrijit1105/edx-platform,jonathan-beard/edx-platform,peterm-itr/edx-platform,teltek/edx-platform,antonve/s4-project-mooc,morenopc/edx-platform,vismartltd/edx-platform,jruiperezv/ANALYSE,arbrandes/edx-platform,bigdatauniversity/edx-platform,rismalrv/edx-platform,jazkarta/edx-platform,chauhanhardik/populo,unicri/edx-platform,itsjeyd/edx-platform,benpatterson/edx-platform,benpatterson/edx-platform,xingyepei/edx-platform,chauhanhardik/populo_2,Edraak/edx-platform,eestay/edx-platform,Lektorium-LLC/edx-platform,eemirtekin/edx-platform,kxliugang/edx-platform,Edraak/edraak-platform,proversity-org/edx-platform,pomegranited/edx-platform,lduarte1991/edx-platform,inares/edx-platform,syjeon/new_edx,solashirai/edx-platform,pomegranited/edx-platform,msegado/edx-platform,RPI-OPENEDX/edx-platform,polimediaupv/edx-platform,zhenzhai/edx-platform,eemirtekin/edx-platform,atsolakid/edx-platform,louyihua/edx-platform,jzoldak/edx-platform,abdoosh00/edx-rtl-final,hmcmooc/muddx-platform,valtech-mooc/edx-platform,jbassen/edx-platform,marcore/edx-platform,ahmedaljazzar/edx-platform,valtech-mooc/edx-platform,hkawasaki/kawasaki-aio8-0,zadgroup/edx-platform,mjg2203/edx-platform-seas,IITBinterns13/edx-platform-dev,motion2015/a3,nttks/edx-platform,MSOpenTech/edx-platform,edry/edx-platform,vikas1885/test1,ak2703/edx-platform,analyseuc3m/ANALYSE-v1,alu042/edx-platform,nttks/edx-platform,gymnasium/edx-platform,defance/edx-platform,andyzsf/edx,zhenzhai/edx-platform,EduPepperPDTesting/pepper2013-testing,pabloborrego93/edx-platform,stvstnfrd/edx-platform,dcosentino/edx-platform,tiagochiavericosta/edx-platform,Semi-global/edx-platform,atsolakid/edx-platform,chand3040/cloud_that,mjg2203/edx-platform-seas,kxliugang/edx-platform,jazkarta/edx-platform-for-isc,4eek/edx-platform,doismellburning/edx-platform,cognitiveclass/edx-platform,alexthered/kienhoc-platform,yokose-ks/edx-platform,ZLLab-Mooc/edx-platform,rue89-tech/edx-platform,4eek/edx-platform,a-parhom/edx-platform,nikolas/edx-platform,jazkarta/edx-platform-for-isc,itsjeyd/edx-platform,Edraak/edx-platform,martynovp/edx-platform,kmoocdev/edx-platform,dsajkl/reqiop,amir-qayyum-khan/edx-platform,kxliugang/edx-platform,xuxiao19910803/edx,hamzehd/edx-platform,don-github/edx-platform,solashirai/edx-platform,pku9104038/edx-platform,WatanabeYasumasa/edx-platform,pku9104038/edx-platform,antonve/s4-project-mooc,B-MOOC/edx-platform,defance/edx-platform,SravanthiSinha/edx-platform,eduNEXT/edx-platform,jolyonb/edx-platform,JCBarahona/edX,mitocw/edx-platform,doismellburning/edx-platform,etzhou/edx-platform,proversity-org/edx-platform,waheedahmed/edx-platform,unicri/edx-platform,etzhou/edx-platform,peterm-itr/edx-platform,jruiperezv/ANALYSE,Shrhawk/edx-platform,deepsrijit1105/edx-platform,CredoReference/edx-platform,mushtaqak/edx-platform,sameetb-cuelogic/edx-platform-test,y12uc231/edx-platform,ferabra/edx-platform,ahmadio/edx-platform,shubhdev/edxOnBaadal,marcore/edx-platform,ahmadio/edx-platform,10clouds/edx-platform,chand3040/cloud_that,amir-qayyum-khan/edx-platform,IITBinterns13/edx-platform-dev,kmoocdev2/edx-platform,beni55/edx-platform,atsolakid/edx-platform,prarthitm/edxplatform,leansoft/edx-platform,shabab12/edx-platform,leansoft/edx-platform,xinjiguaike/edx-platform,cpennington/edx-platform,alu042/edx-platform,morenopc/edx-platform,abdoosh00/edx-rtl-final,ovnicraft/edx-platform,kamalx/edx-platform,B-MOOC/edx-platform,jamiefolsom/edx-platform,prarthitm/edxplatform,auferack08/edx-platform,jolyonb/edx-platform,jamesblunt/edx-platform,nanolearningllc/edx-platform-cypress-2,antoviaque/edx-platform,Lektorium-LLC/edx-platform,simbs/edx-platform,ubc/edx-platform,rismalrv/edx-platform,Ayub-Khan/edx-platform,xuxiao19910803/edx-platform,franosincic/edx-platform,EduPepperPD/pepper2013,mushtaqak/edx-platform,OmarIthawi/edx-platform,Kalyzee/edx-platform,vasyarv/edx-platform,dkarakats/edx-platform,MSOpenTech/edx-platform,martynovp/edx-platform,CourseTalk/edx-platform,abdoosh00/edx-rtl-final,knehez/edx-platform,alexthered/kienhoc-platform
|
from xblock.runtime import KeyValueStore, InvalidScopeError
class SessionKeyValueStore(KeyValueStore):
def __init__(self, request, model_data):
self._model_data = model_data
self._session = request.session
def get(self, key):
try:
return self._model_data[key.field_name]
except (KeyError, InvalidScopeError):
return self._session[tuple(key)]
def set(self, key, value):
try:
self._model_data[key.field_name] = value
except (KeyError, InvalidScopeError):
self._session[tuple(key)] = value
def delete(self, key):
try:
del self._model_data[key.field_name]
except (KeyError, InvalidScopeError):
del self._session[tuple(key)]
def has(self, key):
return key in self._model_data or key in self._session
Make SessionKeyValueStore variable names clearer
|
from xblock.runtime import KeyValueStore, InvalidScopeError
class SessionKeyValueStore(KeyValueStore):
def __init__(self, request, descriptor_model_data):
self._descriptor_model_data = descriptor_model_data
self._session = request.session
def get(self, key):
try:
return self._descriptor_model_data[key.field_name]
except (KeyError, InvalidScopeError):
return self._session[tuple(key)]
def set(self, key, value):
try:
self._descriptor_model_data[key.field_name] = value
except (KeyError, InvalidScopeError):
self._session[tuple(key)] = value
def delete(self, key):
try:
del self._descriptor_model_data[key.field_name]
except (KeyError, InvalidScopeError):
del self._session[tuple(key)]
def has(self, key):
return key in self._descriptor_model_data or key in self._session
|
<commit_before>from xblock.runtime import KeyValueStore, InvalidScopeError
class SessionKeyValueStore(KeyValueStore):
def __init__(self, request, model_data):
self._model_data = model_data
self._session = request.session
def get(self, key):
try:
return self._model_data[key.field_name]
except (KeyError, InvalidScopeError):
return self._session[tuple(key)]
def set(self, key, value):
try:
self._model_data[key.field_name] = value
except (KeyError, InvalidScopeError):
self._session[tuple(key)] = value
def delete(self, key):
try:
del self._model_data[key.field_name]
except (KeyError, InvalidScopeError):
del self._session[tuple(key)]
def has(self, key):
return key in self._model_data or key in self._session
<commit_msg>Make SessionKeyValueStore variable names clearer<commit_after>
|
from xblock.runtime import KeyValueStore, InvalidScopeError
class SessionKeyValueStore(KeyValueStore):
def __init__(self, request, descriptor_model_data):
self._descriptor_model_data = descriptor_model_data
self._session = request.session
def get(self, key):
try:
return self._descriptor_model_data[key.field_name]
except (KeyError, InvalidScopeError):
return self._session[tuple(key)]
def set(self, key, value):
try:
self._descriptor_model_data[key.field_name] = value
except (KeyError, InvalidScopeError):
self._session[tuple(key)] = value
def delete(self, key):
try:
del self._descriptor_model_data[key.field_name]
except (KeyError, InvalidScopeError):
del self._session[tuple(key)]
def has(self, key):
return key in self._descriptor_model_data or key in self._session
|
from xblock.runtime import KeyValueStore, InvalidScopeError
class SessionKeyValueStore(KeyValueStore):
def __init__(self, request, model_data):
self._model_data = model_data
self._session = request.session
def get(self, key):
try:
return self._model_data[key.field_name]
except (KeyError, InvalidScopeError):
return self._session[tuple(key)]
def set(self, key, value):
try:
self._model_data[key.field_name] = value
except (KeyError, InvalidScopeError):
self._session[tuple(key)] = value
def delete(self, key):
try:
del self._model_data[key.field_name]
except (KeyError, InvalidScopeError):
del self._session[tuple(key)]
def has(self, key):
return key in self._model_data or key in self._session
Make SessionKeyValueStore variable names clearerfrom xblock.runtime import KeyValueStore, InvalidScopeError
class SessionKeyValueStore(KeyValueStore):
def __init__(self, request, descriptor_model_data):
self._descriptor_model_data = descriptor_model_data
self._session = request.session
def get(self, key):
try:
return self._descriptor_model_data[key.field_name]
except (KeyError, InvalidScopeError):
return self._session[tuple(key)]
def set(self, key, value):
try:
self._descriptor_model_data[key.field_name] = value
except (KeyError, InvalidScopeError):
self._session[tuple(key)] = value
def delete(self, key):
try:
del self._descriptor_model_data[key.field_name]
except (KeyError, InvalidScopeError):
del self._session[tuple(key)]
def has(self, key):
return key in self._descriptor_model_data or key in self._session
|
<commit_before>from xblock.runtime import KeyValueStore, InvalidScopeError
class SessionKeyValueStore(KeyValueStore):
def __init__(self, request, model_data):
self._model_data = model_data
self._session = request.session
def get(self, key):
try:
return self._model_data[key.field_name]
except (KeyError, InvalidScopeError):
return self._session[tuple(key)]
def set(self, key, value):
try:
self._model_data[key.field_name] = value
except (KeyError, InvalidScopeError):
self._session[tuple(key)] = value
def delete(self, key):
try:
del self._model_data[key.field_name]
except (KeyError, InvalidScopeError):
del self._session[tuple(key)]
def has(self, key):
return key in self._model_data or key in self._session
<commit_msg>Make SessionKeyValueStore variable names clearer<commit_after>from xblock.runtime import KeyValueStore, InvalidScopeError
class SessionKeyValueStore(KeyValueStore):
def __init__(self, request, descriptor_model_data):
self._descriptor_model_data = descriptor_model_data
self._session = request.session
def get(self, key):
try:
return self._descriptor_model_data[key.field_name]
except (KeyError, InvalidScopeError):
return self._session[tuple(key)]
def set(self, key, value):
try:
self._descriptor_model_data[key.field_name] = value
except (KeyError, InvalidScopeError):
self._session[tuple(key)] = value
def delete(self, key):
try:
del self._descriptor_model_data[key.field_name]
except (KeyError, InvalidScopeError):
del self._session[tuple(key)]
def has(self, key):
return key in self._descriptor_model_data or key in self._session
|
03bca9051114a936b584632a72242ca023cbde3e
|
openslides/utils/csv_ext.py
|
openslides/utils/csv_ext.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.utils.csv_ext
~~~~~~~~~~~~~~~~~~~~~~~~
Additional dialect definitions for pythons CSV module.
:copyright: 2011 by the OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
from csv import Dialect, excel, register_dialect
class excel_semikolon(Dialect):
delimiter = ';'
doublequote = True
lineterminator = '\r\n'
quotechar = '"'
quoting = 0
skipinitialspace = False
def patchup(dialect):
if dialect:
if dialect.delimiter == excel_semikolon.delimiter and \
dialect.quotechar == excel_semikolon.quotechar:
# walks like a duck and talks like a duck.. must be one
dialect.doublequote = True
return dialect
register_dialect("excel_semikolon", excel_semikolon)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.utils.csv_ext
~~~~~~~~~~~~~~~~~~~~~~~~
Additional dialect definitions for pythons CSV module.
:copyright: 2011 by the OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
from csv import Dialect, excel, register_dialect
class excel_semikolon(Dialect):
delimiter = ';'
doublequote = True
lineterminator = '\r\n'
quotechar = '"'
quoting = 0
skipinitialspace = False
def patchup(dialect):
if dialect:
if dialect.delimiter in [excel_semikolon.delimiter, excel.delimiter] and \
dialect.quotechar == excel_semikolon.quotechar:
# walks like a duck and talks like a duck.. must be one
dialect.doublequote = True
return dialect
register_dialect("excel_semikolon", excel_semikolon)
|
Extend patchup for builtin excel dialect
|
Extend patchup for builtin excel dialect
|
Python
|
mit
|
ostcar/OpenSlides,normanjaeckel/OpenSlides,tsiegleauq/OpenSlides,jwinzer/OpenSlides,normanjaeckel/OpenSlides,OpenSlides/OpenSlides,emanuelschuetze/OpenSlides,CatoTH/OpenSlides,jwinzer/OpenSlides,rolandgeider/OpenSlides,emanuelschuetze/OpenSlides,OpenSlides/OpenSlides,jwinzer/OpenSlides,ostcar/OpenSlides,FinnStutzenstein/OpenSlides,boehlke/OpenSlides,boehlke/OpenSlides,tsiegleauq/OpenSlides,FinnStutzenstein/OpenSlides,rolandgeider/OpenSlides,rolandgeider/OpenSlides,emanuelschuetze/OpenSlides,boehlke/OpenSlides,normanjaeckel/OpenSlides,jwinzer/OpenSlides,normanjaeckel/OpenSlides,CatoTH/OpenSlides,FinnStutzenstein/OpenSlides,jwinzer/OpenSlides,ostcar/OpenSlides,CatoTH/OpenSlides,tsiegleauq/OpenSlides,FinnStutzenstein/OpenSlides,CatoTH/OpenSlides,boehlke/OpenSlides,emanuelschuetze/OpenSlides
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.utils.csv_ext
~~~~~~~~~~~~~~~~~~~~~~~~
Additional dialect definitions for pythons CSV module.
:copyright: 2011 by the OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
from csv import Dialect, excel, register_dialect
class excel_semikolon(Dialect):
delimiter = ';'
doublequote = True
lineterminator = '\r\n'
quotechar = '"'
quoting = 0
skipinitialspace = False
def patchup(dialect):
if dialect:
if dialect.delimiter == excel_semikolon.delimiter and \
dialect.quotechar == excel_semikolon.quotechar:
# walks like a duck and talks like a duck.. must be one
dialect.doublequote = True
return dialect
register_dialect("excel_semikolon", excel_semikolon)
Extend patchup for builtin excel dialect
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.utils.csv_ext
~~~~~~~~~~~~~~~~~~~~~~~~
Additional dialect definitions for pythons CSV module.
:copyright: 2011 by the OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
from csv import Dialect, excel, register_dialect
class excel_semikolon(Dialect):
delimiter = ';'
doublequote = True
lineterminator = '\r\n'
quotechar = '"'
quoting = 0
skipinitialspace = False
def patchup(dialect):
if dialect:
if dialect.delimiter in [excel_semikolon.delimiter, excel.delimiter] and \
dialect.quotechar == excel_semikolon.quotechar:
# walks like a duck and talks like a duck.. must be one
dialect.doublequote = True
return dialect
register_dialect("excel_semikolon", excel_semikolon)
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.utils.csv_ext
~~~~~~~~~~~~~~~~~~~~~~~~
Additional dialect definitions for pythons CSV module.
:copyright: 2011 by the OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
from csv import Dialect, excel, register_dialect
class excel_semikolon(Dialect):
delimiter = ';'
doublequote = True
lineterminator = '\r\n'
quotechar = '"'
quoting = 0
skipinitialspace = False
def patchup(dialect):
if dialect:
if dialect.delimiter == excel_semikolon.delimiter and \
dialect.quotechar == excel_semikolon.quotechar:
# walks like a duck and talks like a duck.. must be one
dialect.doublequote = True
return dialect
register_dialect("excel_semikolon", excel_semikolon)
<commit_msg>Extend patchup for builtin excel dialect<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.utils.csv_ext
~~~~~~~~~~~~~~~~~~~~~~~~
Additional dialect definitions for pythons CSV module.
:copyright: 2011 by the OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
from csv import Dialect, excel, register_dialect
class excel_semikolon(Dialect):
delimiter = ';'
doublequote = True
lineterminator = '\r\n'
quotechar = '"'
quoting = 0
skipinitialspace = False
def patchup(dialect):
if dialect:
if dialect.delimiter in [excel_semikolon.delimiter, excel.delimiter] and \
dialect.quotechar == excel_semikolon.quotechar:
# walks like a duck and talks like a duck.. must be one
dialect.doublequote = True
return dialect
register_dialect("excel_semikolon", excel_semikolon)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.utils.csv_ext
~~~~~~~~~~~~~~~~~~~~~~~~
Additional dialect definitions for pythons CSV module.
:copyright: 2011 by the OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
from csv import Dialect, excel, register_dialect
class excel_semikolon(Dialect):
delimiter = ';'
doublequote = True
lineterminator = '\r\n'
quotechar = '"'
quoting = 0
skipinitialspace = False
def patchup(dialect):
if dialect:
if dialect.delimiter == excel_semikolon.delimiter and \
dialect.quotechar == excel_semikolon.quotechar:
# walks like a duck and talks like a duck.. must be one
dialect.doublequote = True
return dialect
register_dialect("excel_semikolon", excel_semikolon)
Extend patchup for builtin excel dialect#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.utils.csv_ext
~~~~~~~~~~~~~~~~~~~~~~~~
Additional dialect definitions for pythons CSV module.
:copyright: 2011 by the OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
from csv import Dialect, excel, register_dialect
class excel_semikolon(Dialect):
delimiter = ';'
doublequote = True
lineterminator = '\r\n'
quotechar = '"'
quoting = 0
skipinitialspace = False
def patchup(dialect):
if dialect:
if dialect.delimiter in [excel_semikolon.delimiter, excel.delimiter] and \
dialect.quotechar == excel_semikolon.quotechar:
# walks like a duck and talks like a duck.. must be one
dialect.doublequote = True
return dialect
register_dialect("excel_semikolon", excel_semikolon)
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.utils.csv_ext
~~~~~~~~~~~~~~~~~~~~~~~~
Additional dialect definitions for pythons CSV module.
:copyright: 2011 by the OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
from csv import Dialect, excel, register_dialect
class excel_semikolon(Dialect):
delimiter = ';'
doublequote = True
lineterminator = '\r\n'
quotechar = '"'
quoting = 0
skipinitialspace = False
def patchup(dialect):
if dialect:
if dialect.delimiter == excel_semikolon.delimiter and \
dialect.quotechar == excel_semikolon.quotechar:
# walks like a duck and talks like a duck.. must be one
dialect.doublequote = True
return dialect
register_dialect("excel_semikolon", excel_semikolon)
<commit_msg>Extend patchup for builtin excel dialect<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.utils.csv_ext
~~~~~~~~~~~~~~~~~~~~~~~~
Additional dialect definitions for pythons CSV module.
:copyright: 2011 by the OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
from csv import Dialect, excel, register_dialect
class excel_semikolon(Dialect):
delimiter = ';'
doublequote = True
lineterminator = '\r\n'
quotechar = '"'
quoting = 0
skipinitialspace = False
def patchup(dialect):
if dialect:
if dialect.delimiter in [excel_semikolon.delimiter, excel.delimiter] and \
dialect.quotechar == excel_semikolon.quotechar:
# walks like a duck and talks like a duck.. must be one
dialect.doublequote = True
return dialect
register_dialect("excel_semikolon", excel_semikolon)
|
921ec4fce301dd98fc18d81fc7c78347486ea4f0
|
counterpartylib/test/config_context_test.py
|
counterpartylib/test/config_context_test.py
|
#! /usr/bin/python3
import pprint
import tempfile
from counterpartylib.test import conftest # this is require near the top to do setup of the test suite
from counterpartylib.test.fixtures.params import DEFAULT_PARAMS as DP
from counterpartylib.test import util_test
from counterpartylib.test.util_test import CURR_DIR
from counterpartylib.lib import (blocks, config, util)
FIXTURE_SQL_FILE = CURR_DIR + '/fixtures/scenarios/parseblock_unittest_fixture.sql'
FIXTURE_DB = tempfile.gettempdir() + '/fixtures.parseblock_unittest_fixture.db'
def test_config_context(cp_server):
assert config.BTC_NAME == "Bitcoin"
with util_test.ConfigContext(BTC_NAME="Bitcoin Testing"):
assert config.BTC_NAME == "Bitcoin Testing"
with util_test.ConfigContext(BTC_NAME="Bitcoin Testing Testing"):
assert config.BTC_NAME == "Bitcoin Testing Testing"
assert config.BTC_NAME == "Bitcoin Testing"
assert config.BTC_NAME == "Bitcoin"
def test_mock_protocol_changes(cp_server):
assert util.enabled('multisig_addresses') == True
with util_test.MockProtocolChangesContext(multisig_addresses=False):
assert util.enabled('multisig_addresses') == False
with util_test.MockProtocolChangesContext(multisig_addresses=None):
assert util.enabled('multisig_addresses') == None
assert util.enabled('multisig_addresses') == False
assert util.enabled('multisig_addresses') == True
|
#! /usr/bin/python3
import pprint
import tempfile
from counterpartylib.test import conftest # this is require near the top to do setup of the test suite
from counterpartylib.test.fixtures.params import DEFAULT_PARAMS as DP
from counterpartylib.test import util_test
from counterpartylib.test.util_test import CURR_DIR
from counterpartylib.lib import (blocks, config, util)
FIXTURE_SQL_FILE = CURR_DIR + '/fixtures/scenarios/parseblock_unittest_fixture.sql'
FIXTURE_DB = tempfile.gettempdir() + '/fixtures.parseblock_unittest_fixture.db'
def test_config_context(cp_server):
assert config.BTC_NAME == "Monacoin"
with util_test.ConfigContext(BTC_NAME="Monacoin Testing"):
assert config.BTC_NAME == "Monacoin Testing"
with util_test.ConfigContext(BTC_NAME="Monacoin Testing Testing"):
assert config.BTC_NAME == "Monacoin Testing Testing"
assert config.BTC_NAME == "Monacoin Testing"
assert config.BTC_NAME == "Monacoin"
def test_mock_protocol_changes(cp_server):
assert util.enabled('multisig_addresses') == True
with util_test.MockProtocolChangesContext(multisig_addresses=False):
assert util.enabled('multisig_addresses') == False
with util_test.MockProtocolChangesContext(multisig_addresses=None):
assert util.enabled('multisig_addresses') == None
assert util.enabled('multisig_addresses') == False
assert util.enabled('multisig_addresses') == True
|
Fix test failures comparing with "Bitcoin".
|
Fix test failures comparing with "Bitcoin".
|
Python
|
mit
|
monaparty/counterparty-lib,monaparty/counterparty-lib
|
#! /usr/bin/python3
import pprint
import tempfile
from counterpartylib.test import conftest # this is require near the top to do setup of the test suite
from counterpartylib.test.fixtures.params import DEFAULT_PARAMS as DP
from counterpartylib.test import util_test
from counterpartylib.test.util_test import CURR_DIR
from counterpartylib.lib import (blocks, config, util)
FIXTURE_SQL_FILE = CURR_DIR + '/fixtures/scenarios/parseblock_unittest_fixture.sql'
FIXTURE_DB = tempfile.gettempdir() + '/fixtures.parseblock_unittest_fixture.db'
def test_config_context(cp_server):
assert config.BTC_NAME == "Bitcoin"
with util_test.ConfigContext(BTC_NAME="Bitcoin Testing"):
assert config.BTC_NAME == "Bitcoin Testing"
with util_test.ConfigContext(BTC_NAME="Bitcoin Testing Testing"):
assert config.BTC_NAME == "Bitcoin Testing Testing"
assert config.BTC_NAME == "Bitcoin Testing"
assert config.BTC_NAME == "Bitcoin"
def test_mock_protocol_changes(cp_server):
assert util.enabled('multisig_addresses') == True
with util_test.MockProtocolChangesContext(multisig_addresses=False):
assert util.enabled('multisig_addresses') == False
with util_test.MockProtocolChangesContext(multisig_addresses=None):
assert util.enabled('multisig_addresses') == None
assert util.enabled('multisig_addresses') == False
assert util.enabled('multisig_addresses') == True
Fix test failures comparing with "Bitcoin".
|
#! /usr/bin/python3
import pprint
import tempfile
from counterpartylib.test import conftest # this is require near the top to do setup of the test suite
from counterpartylib.test.fixtures.params import DEFAULT_PARAMS as DP
from counterpartylib.test import util_test
from counterpartylib.test.util_test import CURR_DIR
from counterpartylib.lib import (blocks, config, util)
FIXTURE_SQL_FILE = CURR_DIR + '/fixtures/scenarios/parseblock_unittest_fixture.sql'
FIXTURE_DB = tempfile.gettempdir() + '/fixtures.parseblock_unittest_fixture.db'
def test_config_context(cp_server):
assert config.BTC_NAME == "Monacoin"
with util_test.ConfigContext(BTC_NAME="Monacoin Testing"):
assert config.BTC_NAME == "Monacoin Testing"
with util_test.ConfigContext(BTC_NAME="Monacoin Testing Testing"):
assert config.BTC_NAME == "Monacoin Testing Testing"
assert config.BTC_NAME == "Monacoin Testing"
assert config.BTC_NAME == "Monacoin"
def test_mock_protocol_changes(cp_server):
assert util.enabled('multisig_addresses') == True
with util_test.MockProtocolChangesContext(multisig_addresses=False):
assert util.enabled('multisig_addresses') == False
with util_test.MockProtocolChangesContext(multisig_addresses=None):
assert util.enabled('multisig_addresses') == None
assert util.enabled('multisig_addresses') == False
assert util.enabled('multisig_addresses') == True
|
<commit_before>#! /usr/bin/python3
import pprint
import tempfile
from counterpartylib.test import conftest # this is require near the top to do setup of the test suite
from counterpartylib.test.fixtures.params import DEFAULT_PARAMS as DP
from counterpartylib.test import util_test
from counterpartylib.test.util_test import CURR_DIR
from counterpartylib.lib import (blocks, config, util)
FIXTURE_SQL_FILE = CURR_DIR + '/fixtures/scenarios/parseblock_unittest_fixture.sql'
FIXTURE_DB = tempfile.gettempdir() + '/fixtures.parseblock_unittest_fixture.db'
def test_config_context(cp_server):
assert config.BTC_NAME == "Bitcoin"
with util_test.ConfigContext(BTC_NAME="Bitcoin Testing"):
assert config.BTC_NAME == "Bitcoin Testing"
with util_test.ConfigContext(BTC_NAME="Bitcoin Testing Testing"):
assert config.BTC_NAME == "Bitcoin Testing Testing"
assert config.BTC_NAME == "Bitcoin Testing"
assert config.BTC_NAME == "Bitcoin"
def test_mock_protocol_changes(cp_server):
assert util.enabled('multisig_addresses') == True
with util_test.MockProtocolChangesContext(multisig_addresses=False):
assert util.enabled('multisig_addresses') == False
with util_test.MockProtocolChangesContext(multisig_addresses=None):
assert util.enabled('multisig_addresses') == None
assert util.enabled('multisig_addresses') == False
assert util.enabled('multisig_addresses') == True
<commit_msg>Fix test failures comparing with "Bitcoin".<commit_after>
|
#! /usr/bin/python3
import pprint
import tempfile
from counterpartylib.test import conftest # this is require near the top to do setup of the test suite
from counterpartylib.test.fixtures.params import DEFAULT_PARAMS as DP
from counterpartylib.test import util_test
from counterpartylib.test.util_test import CURR_DIR
from counterpartylib.lib import (blocks, config, util)
FIXTURE_SQL_FILE = CURR_DIR + '/fixtures/scenarios/parseblock_unittest_fixture.sql'
FIXTURE_DB = tempfile.gettempdir() + '/fixtures.parseblock_unittest_fixture.db'
def test_config_context(cp_server):
assert config.BTC_NAME == "Monacoin"
with util_test.ConfigContext(BTC_NAME="Monacoin Testing"):
assert config.BTC_NAME == "Monacoin Testing"
with util_test.ConfigContext(BTC_NAME="Monacoin Testing Testing"):
assert config.BTC_NAME == "Monacoin Testing Testing"
assert config.BTC_NAME == "Monacoin Testing"
assert config.BTC_NAME == "Monacoin"
def test_mock_protocol_changes(cp_server):
assert util.enabled('multisig_addresses') == True
with util_test.MockProtocolChangesContext(multisig_addresses=False):
assert util.enabled('multisig_addresses') == False
with util_test.MockProtocolChangesContext(multisig_addresses=None):
assert util.enabled('multisig_addresses') == None
assert util.enabled('multisig_addresses') == False
assert util.enabled('multisig_addresses') == True
|
#! /usr/bin/python3
import pprint
import tempfile
from counterpartylib.test import conftest # this is require near the top to do setup of the test suite
from counterpartylib.test.fixtures.params import DEFAULT_PARAMS as DP
from counterpartylib.test import util_test
from counterpartylib.test.util_test import CURR_DIR
from counterpartylib.lib import (blocks, config, util)
FIXTURE_SQL_FILE = CURR_DIR + '/fixtures/scenarios/parseblock_unittest_fixture.sql'
FIXTURE_DB = tempfile.gettempdir() + '/fixtures.parseblock_unittest_fixture.db'
def test_config_context(cp_server):
assert config.BTC_NAME == "Bitcoin"
with util_test.ConfigContext(BTC_NAME="Bitcoin Testing"):
assert config.BTC_NAME == "Bitcoin Testing"
with util_test.ConfigContext(BTC_NAME="Bitcoin Testing Testing"):
assert config.BTC_NAME == "Bitcoin Testing Testing"
assert config.BTC_NAME == "Bitcoin Testing"
assert config.BTC_NAME == "Bitcoin"
def test_mock_protocol_changes(cp_server):
assert util.enabled('multisig_addresses') == True
with util_test.MockProtocolChangesContext(multisig_addresses=False):
assert util.enabled('multisig_addresses') == False
with util_test.MockProtocolChangesContext(multisig_addresses=None):
assert util.enabled('multisig_addresses') == None
assert util.enabled('multisig_addresses') == False
assert util.enabled('multisig_addresses') == True
Fix test failures comparing with "Bitcoin".#! /usr/bin/python3
import pprint
import tempfile
from counterpartylib.test import conftest # this is require near the top to do setup of the test suite
from counterpartylib.test.fixtures.params import DEFAULT_PARAMS as DP
from counterpartylib.test import util_test
from counterpartylib.test.util_test import CURR_DIR
from counterpartylib.lib import (blocks, config, util)
FIXTURE_SQL_FILE = CURR_DIR + '/fixtures/scenarios/parseblock_unittest_fixture.sql'
FIXTURE_DB = tempfile.gettempdir() + '/fixtures.parseblock_unittest_fixture.db'
def test_config_context(cp_server):
assert config.BTC_NAME == "Monacoin"
with util_test.ConfigContext(BTC_NAME="Monacoin Testing"):
assert config.BTC_NAME == "Monacoin Testing"
with util_test.ConfigContext(BTC_NAME="Monacoin Testing Testing"):
assert config.BTC_NAME == "Monacoin Testing Testing"
assert config.BTC_NAME == "Monacoin Testing"
assert config.BTC_NAME == "Monacoin"
def test_mock_protocol_changes(cp_server):
assert util.enabled('multisig_addresses') == True
with util_test.MockProtocolChangesContext(multisig_addresses=False):
assert util.enabled('multisig_addresses') == False
with util_test.MockProtocolChangesContext(multisig_addresses=None):
assert util.enabled('multisig_addresses') == None
assert util.enabled('multisig_addresses') == False
assert util.enabled('multisig_addresses') == True
|
<commit_before>#! /usr/bin/python3
import pprint
import tempfile
from counterpartylib.test import conftest # this is require near the top to do setup of the test suite
from counterpartylib.test.fixtures.params import DEFAULT_PARAMS as DP
from counterpartylib.test import util_test
from counterpartylib.test.util_test import CURR_DIR
from counterpartylib.lib import (blocks, config, util)
FIXTURE_SQL_FILE = CURR_DIR + '/fixtures/scenarios/parseblock_unittest_fixture.sql'
FIXTURE_DB = tempfile.gettempdir() + '/fixtures.parseblock_unittest_fixture.db'
def test_config_context(cp_server):
assert config.BTC_NAME == "Bitcoin"
with util_test.ConfigContext(BTC_NAME="Bitcoin Testing"):
assert config.BTC_NAME == "Bitcoin Testing"
with util_test.ConfigContext(BTC_NAME="Bitcoin Testing Testing"):
assert config.BTC_NAME == "Bitcoin Testing Testing"
assert config.BTC_NAME == "Bitcoin Testing"
assert config.BTC_NAME == "Bitcoin"
def test_mock_protocol_changes(cp_server):
assert util.enabled('multisig_addresses') == True
with util_test.MockProtocolChangesContext(multisig_addresses=False):
assert util.enabled('multisig_addresses') == False
with util_test.MockProtocolChangesContext(multisig_addresses=None):
assert util.enabled('multisig_addresses') == None
assert util.enabled('multisig_addresses') == False
assert util.enabled('multisig_addresses') == True
<commit_msg>Fix test failures comparing with "Bitcoin".<commit_after>#! /usr/bin/python3
import pprint
import tempfile
from counterpartylib.test import conftest # this is require near the top to do setup of the test suite
from counterpartylib.test.fixtures.params import DEFAULT_PARAMS as DP
from counterpartylib.test import util_test
from counterpartylib.test.util_test import CURR_DIR
from counterpartylib.lib import (blocks, config, util)
FIXTURE_SQL_FILE = CURR_DIR + '/fixtures/scenarios/parseblock_unittest_fixture.sql'
FIXTURE_DB = tempfile.gettempdir() + '/fixtures.parseblock_unittest_fixture.db'
def test_config_context(cp_server):
assert config.BTC_NAME == "Monacoin"
with util_test.ConfigContext(BTC_NAME="Monacoin Testing"):
assert config.BTC_NAME == "Monacoin Testing"
with util_test.ConfigContext(BTC_NAME="Monacoin Testing Testing"):
assert config.BTC_NAME == "Monacoin Testing Testing"
assert config.BTC_NAME == "Monacoin Testing"
assert config.BTC_NAME == "Monacoin"
def test_mock_protocol_changes(cp_server):
assert util.enabled('multisig_addresses') == True
with util_test.MockProtocolChangesContext(multisig_addresses=False):
assert util.enabled('multisig_addresses') == False
with util_test.MockProtocolChangesContext(multisig_addresses=None):
assert util.enabled('multisig_addresses') == None
assert util.enabled('multisig_addresses') == False
assert util.enabled('multisig_addresses') == True
|
86e01016763cd96e6c623b554811a10cceb02fe3
|
rnacentral/portal/templatetags/portal_extras.py
|
rnacentral/portal/templatetags/portal_extras.py
|
"""
Copyright [2009-2015] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from django import template
from portal.config.expert_databases import expert_dbs
register = template.Library()
@register.assignment_tag
def get_expert_databases_columns():
"""
Return expert databases grouped and order for the website footer.
"""
dbs = sorted(expert_dbs, key=lambda x: x['name'].lower())
return [
dbs[:10],
dbs[10:19],
dbs[19:28],
dbs[28:],
]
@register.assignment_tag
def get_expert_databases_list():
"""
Get an alphabetically sorted list of imported expert databases.
"""
imported_dbs = [x for x in expert_dbs if x['imported']]
return sorted(imported_dbs, key=lambda x: x['name'].lower())
|
"""
Copyright [2009-2015] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from django import template
from portal.config.expert_databases import expert_dbs
register = template.Library()
@register.assignment_tag
def get_expert_databases_columns():
"""
Return expert databases grouped and order for the website footer.
"""
dbs = sorted(expert_dbs, key=lambda x: x['name'].lower())
return [
dbs[:10],
dbs[10:20],
dbs[20:30],
dbs[30:],
]
@register.assignment_tag
def get_expert_databases_list():
"""
Get an alphabetically sorted list of imported expert databases.
"""
imported_dbs = [x for x in expert_dbs if x['imported']]
return sorted(imported_dbs, key=lambda x: x['name'].lower())
|
Update Expert Databases columns in the footer
|
Update Expert Databases columns in the footer
|
Python
|
apache-2.0
|
RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode
|
"""
Copyright [2009-2015] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from django import template
from portal.config.expert_databases import expert_dbs
register = template.Library()
@register.assignment_tag
def get_expert_databases_columns():
"""
Return expert databases grouped and order for the website footer.
"""
dbs = sorted(expert_dbs, key=lambda x: x['name'].lower())
return [
dbs[:10],
dbs[10:19],
dbs[19:28],
dbs[28:],
]
@register.assignment_tag
def get_expert_databases_list():
"""
Get an alphabetically sorted list of imported expert databases.
"""
imported_dbs = [x for x in expert_dbs if x['imported']]
return sorted(imported_dbs, key=lambda x: x['name'].lower())
Update Expert Databases columns in the footer
|
"""
Copyright [2009-2015] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from django import template
from portal.config.expert_databases import expert_dbs
register = template.Library()
@register.assignment_tag
def get_expert_databases_columns():
"""
Return expert databases grouped and order for the website footer.
"""
dbs = sorted(expert_dbs, key=lambda x: x['name'].lower())
return [
dbs[:10],
dbs[10:20],
dbs[20:30],
dbs[30:],
]
@register.assignment_tag
def get_expert_databases_list():
"""
Get an alphabetically sorted list of imported expert databases.
"""
imported_dbs = [x for x in expert_dbs if x['imported']]
return sorted(imported_dbs, key=lambda x: x['name'].lower())
|
<commit_before>"""
Copyright [2009-2015] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from django import template
from portal.config.expert_databases import expert_dbs
register = template.Library()
@register.assignment_tag
def get_expert_databases_columns():
"""
Return expert databases grouped and order for the website footer.
"""
dbs = sorted(expert_dbs, key=lambda x: x['name'].lower())
return [
dbs[:10],
dbs[10:19],
dbs[19:28],
dbs[28:],
]
@register.assignment_tag
def get_expert_databases_list():
"""
Get an alphabetically sorted list of imported expert databases.
"""
imported_dbs = [x for x in expert_dbs if x['imported']]
return sorted(imported_dbs, key=lambda x: x['name'].lower())
<commit_msg>Update Expert Databases columns in the footer<commit_after>
|
"""
Copyright [2009-2015] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from django import template
from portal.config.expert_databases import expert_dbs
register = template.Library()
@register.assignment_tag
def get_expert_databases_columns():
"""
Return expert databases grouped and order for the website footer.
"""
dbs = sorted(expert_dbs, key=lambda x: x['name'].lower())
return [
dbs[:10],
dbs[10:20],
dbs[20:30],
dbs[30:],
]
@register.assignment_tag
def get_expert_databases_list():
"""
Get an alphabetically sorted list of imported expert databases.
"""
imported_dbs = [x for x in expert_dbs if x['imported']]
return sorted(imported_dbs, key=lambda x: x['name'].lower())
|
"""
Copyright [2009-2015] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from django import template
from portal.config.expert_databases import expert_dbs
register = template.Library()
@register.assignment_tag
def get_expert_databases_columns():
"""
Return expert databases grouped and order for the website footer.
"""
dbs = sorted(expert_dbs, key=lambda x: x['name'].lower())
return [
dbs[:10],
dbs[10:19],
dbs[19:28],
dbs[28:],
]
@register.assignment_tag
def get_expert_databases_list():
"""
Get an alphabetically sorted list of imported expert databases.
"""
imported_dbs = [x for x in expert_dbs if x['imported']]
return sorted(imported_dbs, key=lambda x: x['name'].lower())
Update Expert Databases columns in the footer"""
Copyright [2009-2015] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from django import template
from portal.config.expert_databases import expert_dbs
register = template.Library()
@register.assignment_tag
def get_expert_databases_columns():
"""
Return expert databases grouped and order for the website footer.
"""
dbs = sorted(expert_dbs, key=lambda x: x['name'].lower())
return [
dbs[:10],
dbs[10:20],
dbs[20:30],
dbs[30:],
]
@register.assignment_tag
def get_expert_databases_list():
"""
Get an alphabetically sorted list of imported expert databases.
"""
imported_dbs = [x for x in expert_dbs if x['imported']]
return sorted(imported_dbs, key=lambda x: x['name'].lower())
|
<commit_before>"""
Copyright [2009-2015] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from django import template
from portal.config.expert_databases import expert_dbs
register = template.Library()
@register.assignment_tag
def get_expert_databases_columns():
"""
Return expert databases grouped and order for the website footer.
"""
dbs = sorted(expert_dbs, key=lambda x: x['name'].lower())
return [
dbs[:10],
dbs[10:19],
dbs[19:28],
dbs[28:],
]
@register.assignment_tag
def get_expert_databases_list():
"""
Get an alphabetically sorted list of imported expert databases.
"""
imported_dbs = [x for x in expert_dbs if x['imported']]
return sorted(imported_dbs, key=lambda x: x['name'].lower())
<commit_msg>Update Expert Databases columns in the footer<commit_after>"""
Copyright [2009-2015] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from django import template
from portal.config.expert_databases import expert_dbs
register = template.Library()
@register.assignment_tag
def get_expert_databases_columns():
"""
Return expert databases grouped and order for the website footer.
"""
dbs = sorted(expert_dbs, key=lambda x: x['name'].lower())
return [
dbs[:10],
dbs[10:20],
dbs[20:30],
dbs[30:],
]
@register.assignment_tag
def get_expert_databases_list():
"""
Get an alphabetically sorted list of imported expert databases.
"""
imported_dbs = [x for x in expert_dbs if x['imported']]
return sorted(imported_dbs, key=lambda x: x['name'].lower())
|
4bb164688a90e2b07ff0e0c3a74ce8b27f743d4b
|
contrib/core/actions/inject_trigger.py
|
contrib/core/actions/inject_trigger.py
|
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from st2common.runners.base_action import Action
__all__ = [
'InjectTriggerAction'
]
class InjectTriggerAction(Action):
def run(self, trigger, payload=None, trace_tag=None):
payload = payload or {}
datastore_service = self.action_service.datastore_service
client = datastore_service.get_api_client()
# Dispatch the trigger using the /webhooks/st2 API endpoint
self.logger.debug('Injecting trigger "%s" with payload="%s"' % (trigger, str(payload)))
result = client.webhooks.post_generic_webhook(trigger=trigger, payload=payload,
trace_tag=trace_tag)
return result
|
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from st2common.runners.base_action import Action
__all__ = [
'InjectTriggerAction'
]
class InjectTriggerAction(Action):
def run(self, trigger, payload=None, trace_tag=None):
payload = payload or {}
datastore_service = self.action_service.datastore_service
client = datastore_service.get_api_client()
# Dispatch the trigger using the /webhooks/st2 API endpoint
# NOTE: Webhooks API endpoint is asynchronous so we don't know if the actual injection
# results in a TriggerInstanceDB database object creation or not. The object is created
# inside rulesengine service and could fail due to the user providing an invalid trigger
# reference or similar.
self.logger.debug('Injecting trigger "%s" with payload="%s"' % (trigger, str(payload)))
result = client.webhooks.post_generic_webhook(trigger=trigger, payload=payload,
trace_tag=trace_tag)
return result
|
Add a comment / clarfification.
|
Add a comment / clarfification.
|
Python
|
apache-2.0
|
Plexxi/st2,StackStorm/st2,nzlosh/st2,Plexxi/st2,Plexxi/st2,StackStorm/st2,nzlosh/st2,StackStorm/st2,nzlosh/st2,Plexxi/st2,StackStorm/st2,nzlosh/st2
|
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from st2common.runners.base_action import Action
__all__ = [
'InjectTriggerAction'
]
class InjectTriggerAction(Action):
def run(self, trigger, payload=None, trace_tag=None):
payload = payload or {}
datastore_service = self.action_service.datastore_service
client = datastore_service.get_api_client()
# Dispatch the trigger using the /webhooks/st2 API endpoint
self.logger.debug('Injecting trigger "%s" with payload="%s"' % (trigger, str(payload)))
result = client.webhooks.post_generic_webhook(trigger=trigger, payload=payload,
trace_tag=trace_tag)
return result
Add a comment / clarfification.
|
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from st2common.runners.base_action import Action
__all__ = [
'InjectTriggerAction'
]
class InjectTriggerAction(Action):
def run(self, trigger, payload=None, trace_tag=None):
payload = payload or {}
datastore_service = self.action_service.datastore_service
client = datastore_service.get_api_client()
# Dispatch the trigger using the /webhooks/st2 API endpoint
# NOTE: Webhooks API endpoint is asynchronous so we don't know if the actual injection
# results in a TriggerInstanceDB database object creation or not. The object is created
# inside rulesengine service and could fail due to the user providing an invalid trigger
# reference or similar.
self.logger.debug('Injecting trigger "%s" with payload="%s"' % (trigger, str(payload)))
result = client.webhooks.post_generic_webhook(trigger=trigger, payload=payload,
trace_tag=trace_tag)
return result
|
<commit_before># Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from st2common.runners.base_action import Action
__all__ = [
'InjectTriggerAction'
]
class InjectTriggerAction(Action):
def run(self, trigger, payload=None, trace_tag=None):
payload = payload or {}
datastore_service = self.action_service.datastore_service
client = datastore_service.get_api_client()
# Dispatch the trigger using the /webhooks/st2 API endpoint
self.logger.debug('Injecting trigger "%s" with payload="%s"' % (trigger, str(payload)))
result = client.webhooks.post_generic_webhook(trigger=trigger, payload=payload,
trace_tag=trace_tag)
return result
<commit_msg>Add a comment / clarfification.<commit_after>
|
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from st2common.runners.base_action import Action
__all__ = [
'InjectTriggerAction'
]
class InjectTriggerAction(Action):
def run(self, trigger, payload=None, trace_tag=None):
payload = payload or {}
datastore_service = self.action_service.datastore_service
client = datastore_service.get_api_client()
# Dispatch the trigger using the /webhooks/st2 API endpoint
# NOTE: Webhooks API endpoint is asynchronous so we don't know if the actual injection
# results in a TriggerInstanceDB database object creation or not. The object is created
# inside rulesengine service and could fail due to the user providing an invalid trigger
# reference or similar.
self.logger.debug('Injecting trigger "%s" with payload="%s"' % (trigger, str(payload)))
result = client.webhooks.post_generic_webhook(trigger=trigger, payload=payload,
trace_tag=trace_tag)
return result
|
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from st2common.runners.base_action import Action
__all__ = [
'InjectTriggerAction'
]
class InjectTriggerAction(Action):
def run(self, trigger, payload=None, trace_tag=None):
payload = payload or {}
datastore_service = self.action_service.datastore_service
client = datastore_service.get_api_client()
# Dispatch the trigger using the /webhooks/st2 API endpoint
self.logger.debug('Injecting trigger "%s" with payload="%s"' % (trigger, str(payload)))
result = client.webhooks.post_generic_webhook(trigger=trigger, payload=payload,
trace_tag=trace_tag)
return result
Add a comment / clarfification.# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from st2common.runners.base_action import Action
__all__ = [
'InjectTriggerAction'
]
class InjectTriggerAction(Action):
def run(self, trigger, payload=None, trace_tag=None):
payload = payload or {}
datastore_service = self.action_service.datastore_service
client = datastore_service.get_api_client()
# Dispatch the trigger using the /webhooks/st2 API endpoint
# NOTE: Webhooks API endpoint is asynchronous so we don't know if the actual injection
# results in a TriggerInstanceDB database object creation or not. The object is created
# inside rulesengine service and could fail due to the user providing an invalid trigger
# reference or similar.
self.logger.debug('Injecting trigger "%s" with payload="%s"' % (trigger, str(payload)))
result = client.webhooks.post_generic_webhook(trigger=trigger, payload=payload,
trace_tag=trace_tag)
return result
|
<commit_before># Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from st2common.runners.base_action import Action
__all__ = [
'InjectTriggerAction'
]
class InjectTriggerAction(Action):
def run(self, trigger, payload=None, trace_tag=None):
payload = payload or {}
datastore_service = self.action_service.datastore_service
client = datastore_service.get_api_client()
# Dispatch the trigger using the /webhooks/st2 API endpoint
self.logger.debug('Injecting trigger "%s" with payload="%s"' % (trigger, str(payload)))
result = client.webhooks.post_generic_webhook(trigger=trigger, payload=payload,
trace_tag=trace_tag)
return result
<commit_msg>Add a comment / clarfification.<commit_after># Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from st2common.runners.base_action import Action
__all__ = [
'InjectTriggerAction'
]
class InjectTriggerAction(Action):
def run(self, trigger, payload=None, trace_tag=None):
payload = payload or {}
datastore_service = self.action_service.datastore_service
client = datastore_service.get_api_client()
# Dispatch the trigger using the /webhooks/st2 API endpoint
# NOTE: Webhooks API endpoint is asynchronous so we don't know if the actual injection
# results in a TriggerInstanceDB database object creation or not. The object is created
# inside rulesengine service and could fail due to the user providing an invalid trigger
# reference or similar.
self.logger.debug('Injecting trigger "%s" with payload="%s"' % (trigger, str(payload)))
result = client.webhooks.post_generic_webhook(trigger=trigger, payload=payload,
trace_tag=trace_tag)
return result
|
8d0c87b21b17f0567dc4ce642437860cdf35bc6b
|
linter.py
|
linter.py
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Copyright (c) 2014 CorvisaCloud, LLC
#
# License: MIT
#
"""This module exports the Luacheck plugin class."""
from SublimeLinter.lint import Linter
class Luacheck(Linter):
"""Provides an interface to luacheck."""
syntax = 'lua'
tempfile_suffix = 'lua'
defaults = {
'--ignore:,': ['channel'],
'--only:,': [],
'--limit=': None,
'--globals:,': [],
}
comment_re = r'\s*--'
inline_settings = 'limit'
inline_overrides = ('ignore', 'only', 'globals')
config_file = ('--config', '.luacheckrc', '~')
cmd = 'luacheck @ *'
regex = r'^(?P<filename>.+):(?P<line>\d+):(?P<col>\d+): (?P<message>.*)$'
def build_args(self, settings):
"""Return args, transforming --ignore, --only, and --globals args into a format luacheck understands."""
args = super().build_args(settings)
for arg in ('--ignore', '--only', '--globals'):
try:
index = args.index(arg)
values = args[index + 1].split(',')
args[index + 1:index + 2] = values
except ValueError:
pass
return args
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Copyright (c) 2015-2017 The SublimeLinter Community
# Copyright (c) 2014 CorvisaCloud, LLC
#
# License: MIT
#
"""This module exports the Luacheck plugin class."""
from SublimeLinter.lint import Linter
class Luacheck(Linter):
"""Provides an interface to luacheck."""
syntax = 'lua'
cmd = 'luacheck - --formatter=plain --codes --ranges --filename @'
version_args = '--help'
version_re = r'[Ll]uacheck (?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 0.11.0, < 1.0.0'
regex = (
r'^.+:(?P<line>\d+):(?P<col>\d+)\-(?P<col_end>\d+): '
r'\((?:(?P<error>E)|(?P<warning>W))\d+\) '
r'(?P<message>.+)'
)
def split_match(self, match):
"""Patch regex matches to highlight token correctly."""
match, line, col, error, warning, msg, _ = super().split_match(match)
col_end = int(match.group(3))
token_len = col_end - col
return match, line, col, error, warning, msg, "." * token_len
|
Update for luacheck >= 0.11.0
|
Update for luacheck >= 0.11.0
* Remove 'channel' from default ignore list.
* Remove SublimeLinter inline options, use luacheck inline options.
* Use `--ranges` to highlight tokens correctly.
* Use `--codes` to distinguish warnings from errors.
* Use `--filename` to apply per-path config overrides correctly.
* Add version requirement.
|
Python
|
mit
|
SublimeLinter/SublimeLinter-luacheck
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Copyright (c) 2014 CorvisaCloud, LLC
#
# License: MIT
#
"""This module exports the Luacheck plugin class."""
from SublimeLinter.lint import Linter
class Luacheck(Linter):
"""Provides an interface to luacheck."""
syntax = 'lua'
tempfile_suffix = 'lua'
defaults = {
'--ignore:,': ['channel'],
'--only:,': [],
'--limit=': None,
'--globals:,': [],
}
comment_re = r'\s*--'
inline_settings = 'limit'
inline_overrides = ('ignore', 'only', 'globals')
config_file = ('--config', '.luacheckrc', '~')
cmd = 'luacheck @ *'
regex = r'^(?P<filename>.+):(?P<line>\d+):(?P<col>\d+): (?P<message>.*)$'
def build_args(self, settings):
"""Return args, transforming --ignore, --only, and --globals args into a format luacheck understands."""
args = super().build_args(settings)
for arg in ('--ignore', '--only', '--globals'):
try:
index = args.index(arg)
values = args[index + 1].split(',')
args[index + 1:index + 2] = values
except ValueError:
pass
return args
Update for luacheck >= 0.11.0
* Remove 'channel' from default ignore list.
* Remove SublimeLinter inline options, use luacheck inline options.
* Use `--ranges` to highlight tokens correctly.
* Use `--codes` to distinguish warnings from errors.
* Use `--filename` to apply per-path config overrides correctly.
* Add version requirement.
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Copyright (c) 2015-2017 The SublimeLinter Community
# Copyright (c) 2014 CorvisaCloud, LLC
#
# License: MIT
#
"""This module exports the Luacheck plugin class."""
from SublimeLinter.lint import Linter
class Luacheck(Linter):
"""Provides an interface to luacheck."""
syntax = 'lua'
cmd = 'luacheck - --formatter=plain --codes --ranges --filename @'
version_args = '--help'
version_re = r'[Ll]uacheck (?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 0.11.0, < 1.0.0'
regex = (
r'^.+:(?P<line>\d+):(?P<col>\d+)\-(?P<col_end>\d+): '
r'\((?:(?P<error>E)|(?P<warning>W))\d+\) '
r'(?P<message>.+)'
)
def split_match(self, match):
"""Patch regex matches to highlight token correctly."""
match, line, col, error, warning, msg, _ = super().split_match(match)
col_end = int(match.group(3))
token_len = col_end - col
return match, line, col, error, warning, msg, "." * token_len
|
<commit_before>#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Copyright (c) 2014 CorvisaCloud, LLC
#
# License: MIT
#
"""This module exports the Luacheck plugin class."""
from SublimeLinter.lint import Linter
class Luacheck(Linter):
"""Provides an interface to luacheck."""
syntax = 'lua'
tempfile_suffix = 'lua'
defaults = {
'--ignore:,': ['channel'],
'--only:,': [],
'--limit=': None,
'--globals:,': [],
}
comment_re = r'\s*--'
inline_settings = 'limit'
inline_overrides = ('ignore', 'only', 'globals')
config_file = ('--config', '.luacheckrc', '~')
cmd = 'luacheck @ *'
regex = r'^(?P<filename>.+):(?P<line>\d+):(?P<col>\d+): (?P<message>.*)$'
def build_args(self, settings):
"""Return args, transforming --ignore, --only, and --globals args into a format luacheck understands."""
args = super().build_args(settings)
for arg in ('--ignore', '--only', '--globals'):
try:
index = args.index(arg)
values = args[index + 1].split(',')
args[index + 1:index + 2] = values
except ValueError:
pass
return args
<commit_msg>Update for luacheck >= 0.11.0
* Remove 'channel' from default ignore list.
* Remove SublimeLinter inline options, use luacheck inline options.
* Use `--ranges` to highlight tokens correctly.
* Use `--codes` to distinguish warnings from errors.
* Use `--filename` to apply per-path config overrides correctly.
* Add version requirement.<commit_after>
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Copyright (c) 2015-2017 The SublimeLinter Community
# Copyright (c) 2014 CorvisaCloud, LLC
#
# License: MIT
#
"""This module exports the Luacheck plugin class."""
from SublimeLinter.lint import Linter
class Luacheck(Linter):
"""Provides an interface to luacheck."""
syntax = 'lua'
cmd = 'luacheck - --formatter=plain --codes --ranges --filename @'
version_args = '--help'
version_re = r'[Ll]uacheck (?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 0.11.0, < 1.0.0'
regex = (
r'^.+:(?P<line>\d+):(?P<col>\d+)\-(?P<col_end>\d+): '
r'\((?:(?P<error>E)|(?P<warning>W))\d+\) '
r'(?P<message>.+)'
)
def split_match(self, match):
"""Patch regex matches to highlight token correctly."""
match, line, col, error, warning, msg, _ = super().split_match(match)
col_end = int(match.group(3))
token_len = col_end - col
return match, line, col, error, warning, msg, "." * token_len
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Copyright (c) 2014 CorvisaCloud, LLC
#
# License: MIT
#
"""This module exports the Luacheck plugin class."""
from SublimeLinter.lint import Linter
class Luacheck(Linter):
"""Provides an interface to luacheck."""
syntax = 'lua'
tempfile_suffix = 'lua'
defaults = {
'--ignore:,': ['channel'],
'--only:,': [],
'--limit=': None,
'--globals:,': [],
}
comment_re = r'\s*--'
inline_settings = 'limit'
inline_overrides = ('ignore', 'only', 'globals')
config_file = ('--config', '.luacheckrc', '~')
cmd = 'luacheck @ *'
regex = r'^(?P<filename>.+):(?P<line>\d+):(?P<col>\d+): (?P<message>.*)$'
def build_args(self, settings):
"""Return args, transforming --ignore, --only, and --globals args into a format luacheck understands."""
args = super().build_args(settings)
for arg in ('--ignore', '--only', '--globals'):
try:
index = args.index(arg)
values = args[index + 1].split(',')
args[index + 1:index + 2] = values
except ValueError:
pass
return args
Update for luacheck >= 0.11.0
* Remove 'channel' from default ignore list.
* Remove SublimeLinter inline options, use luacheck inline options.
* Use `--ranges` to highlight tokens correctly.
* Use `--codes` to distinguish warnings from errors.
* Use `--filename` to apply per-path config overrides correctly.
* Add version requirement.#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Copyright (c) 2015-2017 The SublimeLinter Community
# Copyright (c) 2014 CorvisaCloud, LLC
#
# License: MIT
#
"""This module exports the Luacheck plugin class."""
from SublimeLinter.lint import Linter
class Luacheck(Linter):
"""Provides an interface to luacheck."""
syntax = 'lua'
cmd = 'luacheck - --formatter=plain --codes --ranges --filename @'
version_args = '--help'
version_re = r'[Ll]uacheck (?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 0.11.0, < 1.0.0'
regex = (
r'^.+:(?P<line>\d+):(?P<col>\d+)\-(?P<col_end>\d+): '
r'\((?:(?P<error>E)|(?P<warning>W))\d+\) '
r'(?P<message>.+)'
)
def split_match(self, match):
"""Patch regex matches to highlight token correctly."""
match, line, col, error, warning, msg, _ = super().split_match(match)
col_end = int(match.group(3))
token_len = col_end - col
return match, line, col, error, warning, msg, "." * token_len
|
<commit_before>#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Copyright (c) 2014 CorvisaCloud, LLC
#
# License: MIT
#
"""This module exports the Luacheck plugin class."""
from SublimeLinter.lint import Linter
class Luacheck(Linter):
"""Provides an interface to luacheck."""
syntax = 'lua'
tempfile_suffix = 'lua'
defaults = {
'--ignore:,': ['channel'],
'--only:,': [],
'--limit=': None,
'--globals:,': [],
}
comment_re = r'\s*--'
inline_settings = 'limit'
inline_overrides = ('ignore', 'only', 'globals')
config_file = ('--config', '.luacheckrc', '~')
cmd = 'luacheck @ *'
regex = r'^(?P<filename>.+):(?P<line>\d+):(?P<col>\d+): (?P<message>.*)$'
def build_args(self, settings):
"""Return args, transforming --ignore, --only, and --globals args into a format luacheck understands."""
args = super().build_args(settings)
for arg in ('--ignore', '--only', '--globals'):
try:
index = args.index(arg)
values = args[index + 1].split(',')
args[index + 1:index + 2] = values
except ValueError:
pass
return args
<commit_msg>Update for luacheck >= 0.11.0
* Remove 'channel' from default ignore list.
* Remove SublimeLinter inline options, use luacheck inline options.
* Use `--ranges` to highlight tokens correctly.
* Use `--codes` to distinguish warnings from errors.
* Use `--filename` to apply per-path config overrides correctly.
* Add version requirement.<commit_after>#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Copyright (c) 2015-2017 The SublimeLinter Community
# Copyright (c) 2014 CorvisaCloud, LLC
#
# License: MIT
#
"""This module exports the Luacheck plugin class."""
from SublimeLinter.lint import Linter
class Luacheck(Linter):
"""Provides an interface to luacheck."""
syntax = 'lua'
cmd = 'luacheck - --formatter=plain --codes --ranges --filename @'
version_args = '--help'
version_re = r'[Ll]uacheck (?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 0.11.0, < 1.0.0'
regex = (
r'^.+:(?P<line>\d+):(?P<col>\d+)\-(?P<col_end>\d+): '
r'\((?:(?P<error>E)|(?P<warning>W))\d+\) '
r'(?P<message>.+)'
)
def split_match(self, match):
"""Patch regex matches to highlight token correctly."""
match, line, col, error, warning, msg, _ = super().split_match(match)
col_end = int(match.group(3))
token_len = col_end - col
return match, line, col, error, warning, msg, "." * token_len
|
0e5dbca7b28ad12f8b285418b815d8706f494c56
|
web_scraper/core/proxy_pinger.py
|
web_scraper/core/proxy_pinger.py
|
from platform import system as system_name
from os import system as system_call
def ping_several_hosts(hosts_list):
""" Ping all hosts in hosts_list and return dict with statuses of hosts
Positional Arguments:
host_lists (list): a list of hostnames
Return:
dict: dict containing hosts that works and hosts that doesn't work
"""
WORKING = 1
NOT_WORKING = 2
hosts_dict = {WORKING: [], NOT_WORKING: []}
for host in hosts_list:
if ping(host):
hosts_dict[WORKING].append(host)
else:
hosts_dict[NOT_WORKING].append(host)
return hosts_dict
def ping(host):
""" Retrun True if host responds to a ping
:param str host: hostname
:return: True if host responds to ping, false if not
:rtype: Bool
"""
parameters = "-n 1" if system_name().lower() == "windows" else "-c 1"
return system_call(f"ping {parameters} {host}") == 0
|
from platform import system as system_name
from os import system as system_call
def ping_several_hosts(hosts_list):
"""Ping all hosts in hosts_list and return dict with statuses of hosts
Positional Arguments:
host_lists (list): a list of hostnames
Return:
dict: dict containing hosts that works and hosts that doesn't work
"""
WORKING = 1
NOT_WORKING = 2
hosts_dict = {WORKING: [], NOT_WORKING: []}
for host in hosts_list:
if ping(host):
hosts_dict[WORKING].append(host)
else:
hosts_dict[NOT_WORKING].append(host)
return hosts_dict
def ping(host):
""" Retrun True if host responds to a ping
:param str host: hostname
:return: True if host responds to ping, false if not
:rtype: Bool
"""
parameters = "-n 1" if system_name().lower() == "windows" else "-c 1"
return system_call(f"ping {parameters} {host}") == 0
|
Fix whitespace in docs in ping_several_hosts
|
Fix whitespace in docs in ping_several_hosts
|
Python
|
mit
|
Samuel-L/cli-ws,Samuel-L/cli-ws
|
from platform import system as system_name
from os import system as system_call
def ping_several_hosts(hosts_list):
""" Ping all hosts in hosts_list and return dict with statuses of hosts
Positional Arguments:
host_lists (list): a list of hostnames
Return:
dict: dict containing hosts that works and hosts that doesn't work
"""
WORKING = 1
NOT_WORKING = 2
hosts_dict = {WORKING: [], NOT_WORKING: []}
for host in hosts_list:
if ping(host):
hosts_dict[WORKING].append(host)
else:
hosts_dict[NOT_WORKING].append(host)
return hosts_dict
def ping(host):
""" Retrun True if host responds to a ping
:param str host: hostname
:return: True if host responds to ping, false if not
:rtype: Bool
"""
parameters = "-n 1" if system_name().lower() == "windows" else "-c 1"
return system_call(f"ping {parameters} {host}") == 0
Fix whitespace in docs in ping_several_hosts
|
from platform import system as system_name
from os import system as system_call
def ping_several_hosts(hosts_list):
"""Ping all hosts in hosts_list and return dict with statuses of hosts
Positional Arguments:
host_lists (list): a list of hostnames
Return:
dict: dict containing hosts that works and hosts that doesn't work
"""
WORKING = 1
NOT_WORKING = 2
hosts_dict = {WORKING: [], NOT_WORKING: []}
for host in hosts_list:
if ping(host):
hosts_dict[WORKING].append(host)
else:
hosts_dict[NOT_WORKING].append(host)
return hosts_dict
def ping(host):
""" Retrun True if host responds to a ping
:param str host: hostname
:return: True if host responds to ping, false if not
:rtype: Bool
"""
parameters = "-n 1" if system_name().lower() == "windows" else "-c 1"
return system_call(f"ping {parameters} {host}") == 0
|
<commit_before>from platform import system as system_name
from os import system as system_call
def ping_several_hosts(hosts_list):
""" Ping all hosts in hosts_list and return dict with statuses of hosts
Positional Arguments:
host_lists (list): a list of hostnames
Return:
dict: dict containing hosts that works and hosts that doesn't work
"""
WORKING = 1
NOT_WORKING = 2
hosts_dict = {WORKING: [], NOT_WORKING: []}
for host in hosts_list:
if ping(host):
hosts_dict[WORKING].append(host)
else:
hosts_dict[NOT_WORKING].append(host)
return hosts_dict
def ping(host):
""" Retrun True if host responds to a ping
:param str host: hostname
:return: True if host responds to ping, false if not
:rtype: Bool
"""
parameters = "-n 1" if system_name().lower() == "windows" else "-c 1"
return system_call(f"ping {parameters} {host}") == 0
<commit_msg>Fix whitespace in docs in ping_several_hosts<commit_after>
|
from platform import system as system_name
from os import system as system_call
def ping_several_hosts(hosts_list):
"""Ping all hosts in hosts_list and return dict with statuses of hosts
Positional Arguments:
host_lists (list): a list of hostnames
Return:
dict: dict containing hosts that works and hosts that doesn't work
"""
WORKING = 1
NOT_WORKING = 2
hosts_dict = {WORKING: [], NOT_WORKING: []}
for host in hosts_list:
if ping(host):
hosts_dict[WORKING].append(host)
else:
hosts_dict[NOT_WORKING].append(host)
return hosts_dict
def ping(host):
""" Retrun True if host responds to a ping
:param str host: hostname
:return: True if host responds to ping, false if not
:rtype: Bool
"""
parameters = "-n 1" if system_name().lower() == "windows" else "-c 1"
return system_call(f"ping {parameters} {host}") == 0
|
from platform import system as system_name
from os import system as system_call
def ping_several_hosts(hosts_list):
""" Ping all hosts in hosts_list and return dict with statuses of hosts
Positional Arguments:
host_lists (list): a list of hostnames
Return:
dict: dict containing hosts that works and hosts that doesn't work
"""
WORKING = 1
NOT_WORKING = 2
hosts_dict = {WORKING: [], NOT_WORKING: []}
for host in hosts_list:
if ping(host):
hosts_dict[WORKING].append(host)
else:
hosts_dict[NOT_WORKING].append(host)
return hosts_dict
def ping(host):
""" Retrun True if host responds to a ping
:param str host: hostname
:return: True if host responds to ping, false if not
:rtype: Bool
"""
parameters = "-n 1" if system_name().lower() == "windows" else "-c 1"
return system_call(f"ping {parameters} {host}") == 0
Fix whitespace in docs in ping_several_hostsfrom platform import system as system_name
from os import system as system_call
def ping_several_hosts(hosts_list):
"""Ping all hosts in hosts_list and return dict with statuses of hosts
Positional Arguments:
host_lists (list): a list of hostnames
Return:
dict: dict containing hosts that works and hosts that doesn't work
"""
WORKING = 1
NOT_WORKING = 2
hosts_dict = {WORKING: [], NOT_WORKING: []}
for host in hosts_list:
if ping(host):
hosts_dict[WORKING].append(host)
else:
hosts_dict[NOT_WORKING].append(host)
return hosts_dict
def ping(host):
""" Retrun True if host responds to a ping
:param str host: hostname
:return: True if host responds to ping, false if not
:rtype: Bool
"""
parameters = "-n 1" if system_name().lower() == "windows" else "-c 1"
return system_call(f"ping {parameters} {host}") == 0
|
<commit_before>from platform import system as system_name
from os import system as system_call
def ping_several_hosts(hosts_list):
""" Ping all hosts in hosts_list and return dict with statuses of hosts
Positional Arguments:
host_lists (list): a list of hostnames
Return:
dict: dict containing hosts that works and hosts that doesn't work
"""
WORKING = 1
NOT_WORKING = 2
hosts_dict = {WORKING: [], NOT_WORKING: []}
for host in hosts_list:
if ping(host):
hosts_dict[WORKING].append(host)
else:
hosts_dict[NOT_WORKING].append(host)
return hosts_dict
def ping(host):
""" Retrun True if host responds to a ping
:param str host: hostname
:return: True if host responds to ping, false if not
:rtype: Bool
"""
parameters = "-n 1" if system_name().lower() == "windows" else "-c 1"
return system_call(f"ping {parameters} {host}") == 0
<commit_msg>Fix whitespace in docs in ping_several_hosts<commit_after>from platform import system as system_name
from os import system as system_call
def ping_several_hosts(hosts_list):
"""Ping all hosts in hosts_list and return dict with statuses of hosts
Positional Arguments:
host_lists (list): a list of hostnames
Return:
dict: dict containing hosts that works and hosts that doesn't work
"""
WORKING = 1
NOT_WORKING = 2
hosts_dict = {WORKING: [], NOT_WORKING: []}
for host in hosts_list:
if ping(host):
hosts_dict[WORKING].append(host)
else:
hosts_dict[NOT_WORKING].append(host)
return hosts_dict
def ping(host):
""" Retrun True if host responds to a ping
:param str host: hostname
:return: True if host responds to ping, false if not
:rtype: Bool
"""
parameters = "-n 1" if system_name().lower() == "windows" else "-c 1"
return system_call(f"ping {parameters} {host}") == 0
|
41aa2c20a564c87fac1fd02d3bf40db84b02d49d
|
testing/test_run.py
|
testing/test_run.py
|
from regr_test import run
from subprocess import check_output
import os
def test_source():
script = 'test_env.sh'
var_name, var_value = 'TESTVAR', 'This is a test'
with open(script, 'w') as f:
f.write('export %s="%s"' % (var_name, var_value))
env = run.source(script)
cmd = ['/bin/bash', '-c', 'echo $%s' % var_name]
stdout = check_output(cmd, env=env, universal_newlines=True)
os.remove(script)
assert stdout.strip() == var_value
def test_duration():
time = 2
p = run.execute('sleep %s' % time)
(duration, data) = run.monitor(p)
assert abs(duration-time) < 1.0
def test_timeout():
p = run.execute('sleep 5')
(duration, data) = run.monitor(p, timeout=2)
assert duration is None
|
from regr_test import run
import os
from subprocess import check_output
from tempfile import NamedTemporaryFile
def test_source():
var_name, var_value = 'TESTVAR', 'This is a test'
with NamedTemporaryFile('w', delete=False) as f:
f.write('export %s="%s"' % (var_name, var_value))
script_name = f.name
env = run.source(script_name)
cmd = ['/bin/bash', '-c', 'echo $%s' % var_name]
stdout = check_output(cmd, env=env, universal_newlines=True)
os.remove(script_name)
assert stdout.strip() == var_value
def test_duration():
time = 2
p = run.execute('sleep %s' % time)
(duration, data) = run.monitor(p)
assert abs(duration-time) < 1.0
def test_timeout():
p = run.execute('sleep 5')
(duration, data) = run.monitor(p, timeout=2)
assert duration is None
|
Make a test more secure
|
Make a test more secure
Choose a random filename to avoid overwriting a file.
|
Python
|
mit
|
davidchall/nrtest
|
from regr_test import run
from subprocess import check_output
import os
def test_source():
script = 'test_env.sh'
var_name, var_value = 'TESTVAR', 'This is a test'
with open(script, 'w') as f:
f.write('export %s="%s"' % (var_name, var_value))
env = run.source(script)
cmd = ['/bin/bash', '-c', 'echo $%s' % var_name]
stdout = check_output(cmd, env=env, universal_newlines=True)
os.remove(script)
assert stdout.strip() == var_value
def test_duration():
time = 2
p = run.execute('sleep %s' % time)
(duration, data) = run.monitor(p)
assert abs(duration-time) < 1.0
def test_timeout():
p = run.execute('sleep 5')
(duration, data) = run.monitor(p, timeout=2)
assert duration is None
Make a test more secure
Choose a random filename to avoid overwriting a file.
|
from regr_test import run
import os
from subprocess import check_output
from tempfile import NamedTemporaryFile
def test_source():
var_name, var_value = 'TESTVAR', 'This is a test'
with NamedTemporaryFile('w', delete=False) as f:
f.write('export %s="%s"' % (var_name, var_value))
script_name = f.name
env = run.source(script_name)
cmd = ['/bin/bash', '-c', 'echo $%s' % var_name]
stdout = check_output(cmd, env=env, universal_newlines=True)
os.remove(script_name)
assert stdout.strip() == var_value
def test_duration():
time = 2
p = run.execute('sleep %s' % time)
(duration, data) = run.monitor(p)
assert abs(duration-time) < 1.0
def test_timeout():
p = run.execute('sleep 5')
(duration, data) = run.monitor(p, timeout=2)
assert duration is None
|
<commit_before>from regr_test import run
from subprocess import check_output
import os
def test_source():
script = 'test_env.sh'
var_name, var_value = 'TESTVAR', 'This is a test'
with open(script, 'w') as f:
f.write('export %s="%s"' % (var_name, var_value))
env = run.source(script)
cmd = ['/bin/bash', '-c', 'echo $%s' % var_name]
stdout = check_output(cmd, env=env, universal_newlines=True)
os.remove(script)
assert stdout.strip() == var_value
def test_duration():
time = 2
p = run.execute('sleep %s' % time)
(duration, data) = run.monitor(p)
assert abs(duration-time) < 1.0
def test_timeout():
p = run.execute('sleep 5')
(duration, data) = run.monitor(p, timeout=2)
assert duration is None
<commit_msg>Make a test more secure
Choose a random filename to avoid overwriting a file.<commit_after>
|
from regr_test import run
import os
from subprocess import check_output
from tempfile import NamedTemporaryFile
def test_source():
var_name, var_value = 'TESTVAR', 'This is a test'
with NamedTemporaryFile('w', delete=False) as f:
f.write('export %s="%s"' % (var_name, var_value))
script_name = f.name
env = run.source(script_name)
cmd = ['/bin/bash', '-c', 'echo $%s' % var_name]
stdout = check_output(cmd, env=env, universal_newlines=True)
os.remove(script_name)
assert stdout.strip() == var_value
def test_duration():
time = 2
p = run.execute('sleep %s' % time)
(duration, data) = run.monitor(p)
assert abs(duration-time) < 1.0
def test_timeout():
p = run.execute('sleep 5')
(duration, data) = run.monitor(p, timeout=2)
assert duration is None
|
from regr_test import run
from subprocess import check_output
import os
def test_source():
script = 'test_env.sh'
var_name, var_value = 'TESTVAR', 'This is a test'
with open(script, 'w') as f:
f.write('export %s="%s"' % (var_name, var_value))
env = run.source(script)
cmd = ['/bin/bash', '-c', 'echo $%s' % var_name]
stdout = check_output(cmd, env=env, universal_newlines=True)
os.remove(script)
assert stdout.strip() == var_value
def test_duration():
time = 2
p = run.execute('sleep %s' % time)
(duration, data) = run.monitor(p)
assert abs(duration-time) < 1.0
def test_timeout():
p = run.execute('sleep 5')
(duration, data) = run.monitor(p, timeout=2)
assert duration is None
Make a test more secure
Choose a random filename to avoid overwriting a file.from regr_test import run
import os
from subprocess import check_output
from tempfile import NamedTemporaryFile
def test_source():
var_name, var_value = 'TESTVAR', 'This is a test'
with NamedTemporaryFile('w', delete=False) as f:
f.write('export %s="%s"' % (var_name, var_value))
script_name = f.name
env = run.source(script_name)
cmd = ['/bin/bash', '-c', 'echo $%s' % var_name]
stdout = check_output(cmd, env=env, universal_newlines=True)
os.remove(script_name)
assert stdout.strip() == var_value
def test_duration():
time = 2
p = run.execute('sleep %s' % time)
(duration, data) = run.monitor(p)
assert abs(duration-time) < 1.0
def test_timeout():
p = run.execute('sleep 5')
(duration, data) = run.monitor(p, timeout=2)
assert duration is None
|
<commit_before>from regr_test import run
from subprocess import check_output
import os
def test_source():
script = 'test_env.sh'
var_name, var_value = 'TESTVAR', 'This is a test'
with open(script, 'w') as f:
f.write('export %s="%s"' % (var_name, var_value))
env = run.source(script)
cmd = ['/bin/bash', '-c', 'echo $%s' % var_name]
stdout = check_output(cmd, env=env, universal_newlines=True)
os.remove(script)
assert stdout.strip() == var_value
def test_duration():
time = 2
p = run.execute('sleep %s' % time)
(duration, data) = run.monitor(p)
assert abs(duration-time) < 1.0
def test_timeout():
p = run.execute('sleep 5')
(duration, data) = run.monitor(p, timeout=2)
assert duration is None
<commit_msg>Make a test more secure
Choose a random filename to avoid overwriting a file.<commit_after>from regr_test import run
import os
from subprocess import check_output
from tempfile import NamedTemporaryFile
def test_source():
var_name, var_value = 'TESTVAR', 'This is a test'
with NamedTemporaryFile('w', delete=False) as f:
f.write('export %s="%s"' % (var_name, var_value))
script_name = f.name
env = run.source(script_name)
cmd = ['/bin/bash', '-c', 'echo $%s' % var_name]
stdout = check_output(cmd, env=env, universal_newlines=True)
os.remove(script_name)
assert stdout.strip() == var_value
def test_duration():
time = 2
p = run.execute('sleep %s' % time)
(duration, data) = run.monitor(p)
assert abs(duration-time) < 1.0
def test_timeout():
p = run.execute('sleep 5')
(duration, data) = run.monitor(p, timeout=2)
assert duration is None
|
6f25ac61617547726ff6410f3095456b98d584eb
|
proj/proj/utils/account.py
|
proj/proj/utils/account.py
|
# coding: utf-8
from flask import session
from ..models import User
def signin_user(user, permenent):
"""Sign in user"""
session.permanent = permenent
session['user_id'] = user.id
def signout_user():
"""Sign out user"""
session.pop('user_id', None)
def get_current_user():
"""获取当前user,同时进行session有效性的检测"""
if not 'user_id' in session:
return None
user = User.query.filter(User.id == session['user_id']).first()
if not user:
signout_user()
return None
return user
|
# coding: utf-8
from flask import session
from ..models import User
def signin_user(user, permenent=True):
"""Sign in user"""
session.permanent = permenent
session['user_id'] = user.id
def signout_user():
"""Sign out user"""
session.pop('user_id', None)
def get_current_user():
"""获取当前user,同时进行session有效性的检测"""
if not 'user_id' in session:
return None
user = User.query.filter(User.id == session['user_id']).first()
if not user:
signout_user()
return None
return user
|
Set permenent to True in utils.signin_user method.
|
Set permenent to True in utils.signin_user method.
|
Python
|
mit
|
1045347128/Flask-Boost,hustlzp/Flask-Boost,hustlzp/Flask-Boost,1045347128/Flask-Boost,hustlzp/Flask-Boost,1045347128/Flask-Boost,1045347128/Flask-Boost,hustlzp/Flask-Boost
|
# coding: utf-8
from flask import session
from ..models import User
def signin_user(user, permenent):
"""Sign in user"""
session.permanent = permenent
session['user_id'] = user.id
def signout_user():
"""Sign out user"""
session.pop('user_id', None)
def get_current_user():
"""获取当前user,同时进行session有效性的检测"""
if not 'user_id' in session:
return None
user = User.query.filter(User.id == session['user_id']).first()
if not user:
signout_user()
return None
return userSet permenent to True in utils.signin_user method.
|
# coding: utf-8
from flask import session
from ..models import User
def signin_user(user, permenent=True):
"""Sign in user"""
session.permanent = permenent
session['user_id'] = user.id
def signout_user():
"""Sign out user"""
session.pop('user_id', None)
def get_current_user():
"""获取当前user,同时进行session有效性的检测"""
if not 'user_id' in session:
return None
user = User.query.filter(User.id == session['user_id']).first()
if not user:
signout_user()
return None
return user
|
<commit_before># coding: utf-8
from flask import session
from ..models import User
def signin_user(user, permenent):
"""Sign in user"""
session.permanent = permenent
session['user_id'] = user.id
def signout_user():
"""Sign out user"""
session.pop('user_id', None)
def get_current_user():
"""获取当前user,同时进行session有效性的检测"""
if not 'user_id' in session:
return None
user = User.query.filter(User.id == session['user_id']).first()
if not user:
signout_user()
return None
return user<commit_msg>Set permenent to True in utils.signin_user method.<commit_after>
|
# coding: utf-8
from flask import session
from ..models import User
def signin_user(user, permenent=True):
"""Sign in user"""
session.permanent = permenent
session['user_id'] = user.id
def signout_user():
"""Sign out user"""
session.pop('user_id', None)
def get_current_user():
"""获取当前user,同时进行session有效性的检测"""
if not 'user_id' in session:
return None
user = User.query.filter(User.id == session['user_id']).first()
if not user:
signout_user()
return None
return user
|
# coding: utf-8
from flask import session
from ..models import User
def signin_user(user, permenent):
"""Sign in user"""
session.permanent = permenent
session['user_id'] = user.id
def signout_user():
"""Sign out user"""
session.pop('user_id', None)
def get_current_user():
"""获取当前user,同时进行session有效性的检测"""
if not 'user_id' in session:
return None
user = User.query.filter(User.id == session['user_id']).first()
if not user:
signout_user()
return None
return userSet permenent to True in utils.signin_user method.# coding: utf-8
from flask import session
from ..models import User
def signin_user(user, permenent=True):
"""Sign in user"""
session.permanent = permenent
session['user_id'] = user.id
def signout_user():
"""Sign out user"""
session.pop('user_id', None)
def get_current_user():
"""获取当前user,同时进行session有效性的检测"""
if not 'user_id' in session:
return None
user = User.query.filter(User.id == session['user_id']).first()
if not user:
signout_user()
return None
return user
|
<commit_before># coding: utf-8
from flask import session
from ..models import User
def signin_user(user, permenent):
"""Sign in user"""
session.permanent = permenent
session['user_id'] = user.id
def signout_user():
"""Sign out user"""
session.pop('user_id', None)
def get_current_user():
"""获取当前user,同时进行session有效性的检测"""
if not 'user_id' in session:
return None
user = User.query.filter(User.id == session['user_id']).first()
if not user:
signout_user()
return None
return user<commit_msg>Set permenent to True in utils.signin_user method.<commit_after># coding: utf-8
from flask import session
from ..models import User
def signin_user(user, permenent=True):
"""Sign in user"""
session.permanent = permenent
session['user_id'] = user.id
def signout_user():
"""Sign out user"""
session.pop('user_id', None)
def get_current_user():
"""获取当前user,同时进行session有效性的检测"""
if not 'user_id' in session:
return None
user = User.query.filter(User.id == session['user_id']).first()
if not user:
signout_user()
return None
return user
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.