commit
stringlengths 40
40
| old_file
stringlengths 4
234
| new_file
stringlengths 4
234
| old_contents
stringlengths 10
3.01k
| new_contents
stringlengths 19
3.38k
| subject
stringlengths 16
736
| message
stringlengths 17
2.63k
| lang
stringclasses 4
values | license
stringclasses 13
values | repos
stringlengths 5
82.6k
| config
stringclasses 4
values | content
stringlengths 134
4.41k
| fuzzy_diff
stringlengths 29
3.44k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
956cb919554c8103149fa6442254bdfed0ce32d1
|
lms/djangoapps/experiments/factories.py
|
lms/djangoapps/experiments/factories.py
|
import factory
from experiments.models import ExperimentData, ExperimentKeyValue
from student.tests.factories import UserFactory
class ExperimentDataFactory(factory.DjangoModelFactory):
class Meta(object):
model = ExperimentData
user = factory.SubFactory(UserFactory)
experiment_id = factory.fuzzy.FuzzyInteger(0)
key = factory.Sequence(lambda n: n)
value = factory.Faker('word')
class ExperimentKeyValueFactory(factory.DjangoModelFactory):
class Meta(object):
model = ExperimentKeyValue
experiment_id = factory.fuzzy.FuzzyInteger(0)
key = factory.Sequence(lambda n: n)
value = factory.Faker('word')
|
import factory
import factory.fuzzy
from experiments.models import ExperimentData, ExperimentKeyValue
from student.tests.factories import UserFactory
class ExperimentDataFactory(factory.DjangoModelFactory):
class Meta(object):
model = ExperimentData
user = factory.SubFactory(UserFactory)
experiment_id = factory.fuzzy.FuzzyInteger(0)
key = factory.Sequence(lambda n: n)
value = factory.Faker('word')
class ExperimentKeyValueFactory(factory.DjangoModelFactory):
class Meta(object):
model = ExperimentKeyValue
experiment_id = factory.fuzzy.FuzzyInteger(0)
key = factory.Sequence(lambda n: n)
value = factory.Faker('word')
|
Add an import of a submodule to make pytest less complainy
|
Add an import of a submodule to make pytest less complainy
|
Python
|
agpl-3.0
|
angelapper/edx-platform,TeachAtTUM/edx-platform,a-parhom/edx-platform,CredoReference/edx-platform,gsehub/edx-platform,eduNEXT/edunext-platform,eduNEXT/edx-platform,stvstnfrd/edx-platform,eduNEXT/edx-platform,TeachAtTUM/edx-platform,Stanford-Online/edx-platform,a-parhom/edx-platform,eduNEXT/edx-platform,ahmedaljazzar/edx-platform,msegado/edx-platform,lduarte1991/edx-platform,kmoocdev2/edx-platform,edx-solutions/edx-platform,kmoocdev2/edx-platform,a-parhom/edx-platform,Edraak/edraak-platform,cpennington/edx-platform,eduNEXT/edunext-platform,msegado/edx-platform,gymnasium/edx-platform,hastexo/edx-platform,stvstnfrd/edx-platform,lduarte1991/edx-platform,hastexo/edx-platform,appsembler/edx-platform,gsehub/edx-platform,jolyonb/edx-platform,eduNEXT/edunext-platform,msegado/edx-platform,jolyonb/edx-platform,a-parhom/edx-platform,Edraak/edraak-platform,gymnasium/edx-platform,kmoocdev2/edx-platform,teltek/edx-platform,teltek/edx-platform,TeachAtTUM/edx-platform,lduarte1991/edx-platform,msegado/edx-platform,ESOedX/edx-platform,angelapper/edx-platform,edx-solutions/edx-platform,cpennington/edx-platform,teltek/edx-platform,mitocw/edx-platform,appsembler/edx-platform,arbrandes/edx-platform,jolyonb/edx-platform,edx-solutions/edx-platform,philanthropy-u/edx-platform,arbrandes/edx-platform,stvstnfrd/edx-platform,EDUlib/edx-platform,proversity-org/edx-platform,gsehub/edx-platform,eduNEXT/edx-platform,EDUlib/edx-platform,gymnasium/edx-platform,mitocw/edx-platform,edx-solutions/edx-platform,angelapper/edx-platform,kmoocdev2/edx-platform,gymnasium/edx-platform,cpennington/edx-platform,teltek/edx-platform,hastexo/edx-platform,CredoReference/edx-platform,procangroup/edx-platform,arbrandes/edx-platform,Stanford-Online/edx-platform,Edraak/edraak-platform,EDUlib/edx-platform,proversity-org/edx-platform,Stanford-Online/edx-platform,edx/edx-platform,BehavioralInsightsTeam/edx-platform,angelapper/edx-platform,procangroup/edx-platform,ahmedaljazzar/edx-platform,ahmedaljazzar/edx-platform,CredoReference/edx-platform,BehavioralInsightsTeam/edx-platform,gsehub/edx-platform,edx/edx-platform,EDUlib/edx-platform,mitocw/edx-platform,appsembler/edx-platform,Edraak/edraak-platform,mitocw/edx-platform,arbrandes/edx-platform,appsembler/edx-platform,proversity-org/edx-platform,eduNEXT/edunext-platform,philanthropy-u/edx-platform,ESOedX/edx-platform,edx/edx-platform,ESOedX/edx-platform,jolyonb/edx-platform,cpennington/edx-platform,kmoocdev2/edx-platform,ahmedaljazzar/edx-platform,procangroup/edx-platform,msegado/edx-platform,TeachAtTUM/edx-platform,philanthropy-u/edx-platform,procangroup/edx-platform,hastexo/edx-platform,Stanford-Online/edx-platform,stvstnfrd/edx-platform,proversity-org/edx-platform,ESOedX/edx-platform,BehavioralInsightsTeam/edx-platform,edx/edx-platform,BehavioralInsightsTeam/edx-platform,CredoReference/edx-platform,lduarte1991/edx-platform,philanthropy-u/edx-platform
|
python
|
## Code Before:
import factory
from experiments.models import ExperimentData, ExperimentKeyValue
from student.tests.factories import UserFactory
class ExperimentDataFactory(factory.DjangoModelFactory):
class Meta(object):
model = ExperimentData
user = factory.SubFactory(UserFactory)
experiment_id = factory.fuzzy.FuzzyInteger(0)
key = factory.Sequence(lambda n: n)
value = factory.Faker('word')
class ExperimentKeyValueFactory(factory.DjangoModelFactory):
class Meta(object):
model = ExperimentKeyValue
experiment_id = factory.fuzzy.FuzzyInteger(0)
key = factory.Sequence(lambda n: n)
value = factory.Faker('word')
## Instruction:
Add an import of a submodule to make pytest less complainy
## Code After:
import factory
import factory.fuzzy
from experiments.models import ExperimentData, ExperimentKeyValue
from student.tests.factories import UserFactory
class ExperimentDataFactory(factory.DjangoModelFactory):
class Meta(object):
model = ExperimentData
user = factory.SubFactory(UserFactory)
experiment_id = factory.fuzzy.FuzzyInteger(0)
key = factory.Sequence(lambda n: n)
value = factory.Faker('word')
class ExperimentKeyValueFactory(factory.DjangoModelFactory):
class Meta(object):
model = ExperimentKeyValue
experiment_id = factory.fuzzy.FuzzyInteger(0)
key = factory.Sequence(lambda n: n)
value = factory.Faker('word')
|
// ... existing code ...
import factory
import factory.fuzzy
from experiments.models import ExperimentData, ExperimentKeyValue
from student.tests.factories import UserFactory
// ... rest of the code ...
|
c600d1e1ad3cef69f6028afd64e14a04c747e1c6
|
tests/test_install.py
|
tests/test_install.py
|
import sys
import os
from subprocess import check_call
from pew._utils import invoke_pew as invoke
from utils import skip_windows, connection_required
import pytest
def skip_marker(f):
return skip_windows(reason='Pythonz unavailable in Windows')(
pytest.mark.skipif(
sys.platform == 'cygwin',
reason='Pythonz unavailable in Cygwin')(
pytest.mark.skipif(os.environ.get('NIX'),
reason='Pythonz unavailable in Nix')(
connection_required(f))))
@skip_marker
def test_install():
py_version = ['2.6.1', '--type', 'pypy']
assert invoke('install', *py_version).returncode == 0
py = invoke('locate_python', *py_version).out
check_call([py, '-V'])
@skip_marker
def test_uninstall():
py_version = ['2.6.1', '--type', 'pypy']
invoke('install', *py_version)
assert invoke('uninstall', *py_version).returncode == 0
assert invoke('locate_python', *py_version).returncode != 0
|
import sys
import os
from subprocess import check_call
from pew._utils import invoke_pew as invoke
from utils import skip_windows, connection_required
import pytest
def skip_marker(f):
return skip_windows(reason='Pythonz unavailable in Windows')(
pytest.mark.skipif(
sys.platform == 'cygwin',
reason='Pythonz unavailable in Cygwin')(
pytest.mark.skipif(os.environ.get('NIX'),
reason='Pythonz unavailable in Nix')(
connection_required(f))))
@skip_marker
def test_install():
py_version = ['3.5.1']
assert invoke('install', *py_version).returncode == 0
py = invoke('locate_python', *py_version).out
check_call([py, '-V'])
@skip_marker
def test_uninstall():
py_version = ['3.5.1']
invoke('install', *py_version)
assert invoke('uninstall', *py_version).returncode == 0
assert invoke('locate_python', *py_version).returncode != 0
|
Replace version of Python to install in test_{un,}install test
|
Replace version of Python to install in test_{un,}install test
PyPy 2.6.1's download link is not working anymore.
|
Python
|
mit
|
berdario/pew,berdario/pew
|
python
|
## Code Before:
import sys
import os
from subprocess import check_call
from pew._utils import invoke_pew as invoke
from utils import skip_windows, connection_required
import pytest
def skip_marker(f):
return skip_windows(reason='Pythonz unavailable in Windows')(
pytest.mark.skipif(
sys.platform == 'cygwin',
reason='Pythonz unavailable in Cygwin')(
pytest.mark.skipif(os.environ.get('NIX'),
reason='Pythonz unavailable in Nix')(
connection_required(f))))
@skip_marker
def test_install():
py_version = ['2.6.1', '--type', 'pypy']
assert invoke('install', *py_version).returncode == 0
py = invoke('locate_python', *py_version).out
check_call([py, '-V'])
@skip_marker
def test_uninstall():
py_version = ['2.6.1', '--type', 'pypy']
invoke('install', *py_version)
assert invoke('uninstall', *py_version).returncode == 0
assert invoke('locate_python', *py_version).returncode != 0
## Instruction:
Replace version of Python to install in test_{un,}install test
PyPy 2.6.1's download link is not working anymore.
## Code After:
import sys
import os
from subprocess import check_call
from pew._utils import invoke_pew as invoke
from utils import skip_windows, connection_required
import pytest
def skip_marker(f):
return skip_windows(reason='Pythonz unavailable in Windows')(
pytest.mark.skipif(
sys.platform == 'cygwin',
reason='Pythonz unavailable in Cygwin')(
pytest.mark.skipif(os.environ.get('NIX'),
reason='Pythonz unavailable in Nix')(
connection_required(f))))
@skip_marker
def test_install():
py_version = ['3.5.1']
assert invoke('install', *py_version).returncode == 0
py = invoke('locate_python', *py_version).out
check_call([py, '-V'])
@skip_marker
def test_uninstall():
py_version = ['3.5.1']
invoke('install', *py_version)
assert invoke('uninstall', *py_version).returncode == 0
assert invoke('locate_python', *py_version).returncode != 0
|
...
@skip_marker
def test_install():
py_version = ['3.5.1']
assert invoke('install', *py_version).returncode == 0
py = invoke('locate_python', *py_version).out
check_call([py, '-V'])
...
@skip_marker
def test_uninstall():
py_version = ['3.5.1']
invoke('install', *py_version)
assert invoke('uninstall', *py_version).returncode == 0
assert invoke('locate_python', *py_version).returncode != 0
...
|
1d92358eaf7731d75c9feff2a00dbae51abd6893
|
src/refract/ElementInserter.h
|
src/refract/ElementInserter.h
|
//
// refract/ElementInserter.h
// librefract
//
// Created by Jiri Kratochvil on 17/06/15.
// Copyright (c) 2015 Apiary Inc. All rights reserved.
//
#ifndef REFRACT_ELEMENTINSERTER_H
#define REFRACT_ELEMENTINSERTER_H
#include <iterator>
namespace refract
{
// Forward declarations of Elements
struct IElement;
template <typename T>
struct ElementInsertIterator : public std::iterator<std::output_iterator_tag, void, void, void, void> {
T& element;
ElementInsertIterator(T& element) : element(element) {}
ElementInsertIterator& operator=(refract::IElement* e) {
element.push_back(e);
return *this;
}
ElementInsertIterator& operator++() {
return *this;
}
ElementInsertIterator& operator*() {
return *this;
}
};
template <typename T>
ElementInsertIterator<T> ElementInserter(T& element) {
return ElementInsertIterator<T>(element);
}
}; // namespace refract
#endif // #ifndef REFRACT_ELEMENTINSERTER_H
|
//
// refract/ElementInserter.h
// librefract
//
// Created by Jiri Kratochvil on 17/06/15.
// Copyright (c) 2015 Apiary Inc. All rights reserved.
//
#ifndef REFRACT_ELEMENTINSERTER_H
#define REFRACT_ELEMENTINSERTER_H
#include <iterator>
namespace refract
{
// Forward declarations of Elements
struct IElement;
template <typename T>
struct ElementInsertIterator : public std::iterator<std::output_iterator_tag, void, void, void, void> {
T& element;
ElementInsertIterator(T& element) : element(element) {}
ElementInsertIterator(const ElementInsertIterator& other) : element(other.element) {}
ElementInsertIterator& operator=(const ElementInsertIterator& other) {
element = other.element;
return *this;
}
ElementInsertIterator& operator=(refract::IElement* e) {
element.push_back(e);
return *this;
}
ElementInsertIterator& operator=(const refract::IElement* e) {
element.push_back(e);
return *this;
}
ElementInsertIterator& operator++() {
return *this;
}
ElementInsertIterator& operator*() {
return *this;
}
};
template <typename T>
ElementInsertIterator<T> ElementInserter(T& element) {
return ElementInsertIterator<T>(element);
}
}; // namespace refract
#endif // #ifndef REFRACT_ELEMENTINSERTER_H
|
Add copy c-tor and assign operator to ElementInsertIterator
|
Add copy c-tor and assign operator to ElementInsertIterator
|
C
|
mit
|
apiaryio/drafter,apiaryio/drafter,apiaryio/drafter,apiaryio/drafter,apiaryio/drafter
|
c
|
## Code Before:
//
// refract/ElementInserter.h
// librefract
//
// Created by Jiri Kratochvil on 17/06/15.
// Copyright (c) 2015 Apiary Inc. All rights reserved.
//
#ifndef REFRACT_ELEMENTINSERTER_H
#define REFRACT_ELEMENTINSERTER_H
#include <iterator>
namespace refract
{
// Forward declarations of Elements
struct IElement;
template <typename T>
struct ElementInsertIterator : public std::iterator<std::output_iterator_tag, void, void, void, void> {
T& element;
ElementInsertIterator(T& element) : element(element) {}
ElementInsertIterator& operator=(refract::IElement* e) {
element.push_back(e);
return *this;
}
ElementInsertIterator& operator++() {
return *this;
}
ElementInsertIterator& operator*() {
return *this;
}
};
template <typename T>
ElementInsertIterator<T> ElementInserter(T& element) {
return ElementInsertIterator<T>(element);
}
}; // namespace refract
#endif // #ifndef REFRACT_ELEMENTINSERTER_H
## Instruction:
Add copy c-tor and assign operator to ElementInsertIterator
## Code After:
//
// refract/ElementInserter.h
// librefract
//
// Created by Jiri Kratochvil on 17/06/15.
// Copyright (c) 2015 Apiary Inc. All rights reserved.
//
#ifndef REFRACT_ELEMENTINSERTER_H
#define REFRACT_ELEMENTINSERTER_H
#include <iterator>
namespace refract
{
// Forward declarations of Elements
struct IElement;
template <typename T>
struct ElementInsertIterator : public std::iterator<std::output_iterator_tag, void, void, void, void> {
T& element;
ElementInsertIterator(T& element) : element(element) {}
ElementInsertIterator(const ElementInsertIterator& other) : element(other.element) {}
ElementInsertIterator& operator=(const ElementInsertIterator& other) {
element = other.element;
return *this;
}
ElementInsertIterator& operator=(refract::IElement* e) {
element.push_back(e);
return *this;
}
ElementInsertIterator& operator=(const refract::IElement* e) {
element.push_back(e);
return *this;
}
ElementInsertIterator& operator++() {
return *this;
}
ElementInsertIterator& operator*() {
return *this;
}
};
template <typename T>
ElementInsertIterator<T> ElementInserter(T& element) {
return ElementInsertIterator<T>(element);
}
}; // namespace refract
#endif // #ifndef REFRACT_ELEMENTINSERTER_H
|
...
template <typename T>
struct ElementInsertIterator : public std::iterator<std::output_iterator_tag, void, void, void, void> {
T& element;
ElementInsertIterator(T& element) : element(element) {}
ElementInsertIterator(const ElementInsertIterator& other) : element(other.element) {}
ElementInsertIterator& operator=(const ElementInsertIterator& other) {
element = other.element;
return *this;
}
ElementInsertIterator& operator=(refract::IElement* e) {
element.push_back(e);
return *this;
}
ElementInsertIterator& operator=(const refract::IElement* e) {
element.push_back(e);
return *this;
}
...
|
6d8461181a889c639cc497e35b38dee77ecb2941
|
celery/patch.py
|
celery/patch.py
|
import logging
import sys
def _check_logger_class():
"""Make sure process name is recorded when loggers are used."""
from multiprocessing.process import current_process
logging._acquireLock()
try:
OldLoggerClass = logging.getLoggerClass()
if not getattr(OldLoggerClass, '_process_aware', False):
class ProcessAwareLogger(OldLoggerClass):
_process_aware = True
def makeRecord(self, *args, **kwds):
record = OldLoggerClass.makeRecord(self, *args, **kwds)
record.processName = current_process()._name
return record
logging.setLoggerClass(ProcessAwareLogger)
finally:
logging._releaseLock()
def monkeypatch():
major, minor = sys.version_info[:2]
if major == 2 and minor < 6: # python < 2.6
_check_logger_class()
|
import logging
import sys
def _check_logger_class():
"""Make sure process name is recorded when loggers are used."""
from multiprocessing.process import current_process
logging._acquireLock()
try:
OldLoggerClass = logging.getLoggerClass()
if not getattr(OldLoggerClass, '_process_aware', False):
class ProcessAwareLogger(OldLoggerClass):
_process_aware = True
def makeRecord(self, *args, **kwds):
record = OldLoggerClass.makeRecord(self, *args, **kwds)
record.processName = current_process()._name
return record
logging.setLoggerClass(ProcessAwareLogger)
finally:
logging._releaseLock()
def monkeypatch():
_check_logger_class()
|
Make sure the logger class is process aware even when running Python >= 2.6
|
Make sure the logger class is process aware even when running Python >= 2.6
|
Python
|
bsd-3-clause
|
frac/celery,WoLpH/celery,ask/celery,ask/celery,cbrepo/celery,WoLpH/celery,cbrepo/celery,mitsuhiko/celery,frac/celery,mitsuhiko/celery
|
python
|
## Code Before:
import logging
import sys
def _check_logger_class():
"""Make sure process name is recorded when loggers are used."""
from multiprocessing.process import current_process
logging._acquireLock()
try:
OldLoggerClass = logging.getLoggerClass()
if not getattr(OldLoggerClass, '_process_aware', False):
class ProcessAwareLogger(OldLoggerClass):
_process_aware = True
def makeRecord(self, *args, **kwds):
record = OldLoggerClass.makeRecord(self, *args, **kwds)
record.processName = current_process()._name
return record
logging.setLoggerClass(ProcessAwareLogger)
finally:
logging._releaseLock()
def monkeypatch():
major, minor = sys.version_info[:2]
if major == 2 and minor < 6: # python < 2.6
_check_logger_class()
## Instruction:
Make sure the logger class is process aware even when running Python >= 2.6
## Code After:
import logging
import sys
def _check_logger_class():
"""Make sure process name is recorded when loggers are used."""
from multiprocessing.process import current_process
logging._acquireLock()
try:
OldLoggerClass = logging.getLoggerClass()
if not getattr(OldLoggerClass, '_process_aware', False):
class ProcessAwareLogger(OldLoggerClass):
_process_aware = True
def makeRecord(self, *args, **kwds):
record = OldLoggerClass.makeRecord(self, *args, **kwds)
record.processName = current_process()._name
return record
logging.setLoggerClass(ProcessAwareLogger)
finally:
logging._releaseLock()
def monkeypatch():
_check_logger_class()
|
// ... existing code ...
def monkeypatch():
_check_logger_class()
// ... rest of the code ...
|
95bde4f783a4d11627d8bc64e24b383e945bdf01
|
src/web/tags.py
|
src/web/tags.py
|
__docformat__ = "reStructuredText"
import json
import datetime
from django.template.base import Library
from django.utils.safestring import mark_safe
register = Library()
#CDN_URL = 'https://cdn.crate.io'
CDN_URL = 'http://localhost:8001'
def media(context, media_url):
"""
Get the path for a media file.
"""
if media_url.startswith('http://') or media_url.startswith('https://'):
url = media_url
elif media_url.startswith('/'):
url = u'{0}{1}'.format(CDN_URL, media_url)
else:
url = u'{0}/media/{1}'.format(CDN_URL, media_url)
return url
register.simple_tag(takes_context=True)(media)
|
__docformat__ = "reStructuredText"
import json
import datetime
from django.template.base import Library
from django.utils.safestring import mark_safe
register = Library()
CDN_URL = 'https://cdn.crate.io'
def media(context, media_url):
"""
Get the path for a media file.
"""
if media_url.startswith('http://') or media_url.startswith('https://'):
url = media_url
elif media_url.startswith('/'):
url = u'{0}{1}'.format(CDN_URL, media_url)
else:
url = u'{0}/media/{1}'.format(CDN_URL, media_url)
return url
register.simple_tag(takes_context=True)(media)
|
Revert local CDN location set by Jodok
|
Revert local CDN location set by Jodok
|
Python
|
apache-2.0
|
crate/crate-web,jomolinare/crate-web,crate/crate-web,crate/crate-web,jomolinare/crate-web,jomolinare/crate-web
|
python
|
## Code Before:
__docformat__ = "reStructuredText"
import json
import datetime
from django.template.base import Library
from django.utils.safestring import mark_safe
register = Library()
#CDN_URL = 'https://cdn.crate.io'
CDN_URL = 'http://localhost:8001'
def media(context, media_url):
"""
Get the path for a media file.
"""
if media_url.startswith('http://') or media_url.startswith('https://'):
url = media_url
elif media_url.startswith('/'):
url = u'{0}{1}'.format(CDN_URL, media_url)
else:
url = u'{0}/media/{1}'.format(CDN_URL, media_url)
return url
register.simple_tag(takes_context=True)(media)
## Instruction:
Revert local CDN location set by Jodok
## Code After:
__docformat__ = "reStructuredText"
import json
import datetime
from django.template.base import Library
from django.utils.safestring import mark_safe
register = Library()
CDN_URL = 'https://cdn.crate.io'
def media(context, media_url):
"""
Get the path for a media file.
"""
if media_url.startswith('http://') or media_url.startswith('https://'):
url = media_url
elif media_url.startswith('/'):
url = u'{0}{1}'.format(CDN_URL, media_url)
else:
url = u'{0}/media/{1}'.format(CDN_URL, media_url)
return url
register.simple_tag(takes_context=True)(media)
|
# ... existing code ...
register = Library()
CDN_URL = 'https://cdn.crate.io'
def media(context, media_url):
"""
# ... rest of the code ...
|
fcede0dca2fbda88ca938c20123ad909ee5a7302
|
src/main/java/com/thegongoliers/output/motors/LimiterMotorModule.java
|
src/main/java/com/thegongoliers/output/motors/LimiterMotorModule.java
|
package com.thegongoliers.output.motors;
import com.thegongoliers.annotations.Untested;
import java.util.function.BooleanSupplier;
@Untested
public class LimiterMotorModule implements MotorModule {
private BooleanSupplier mPositiveLimit;
private BooleanSupplier mNegativeLimit;
public LimiterMotorModule(BooleanSupplier positiveLimit, BooleanSupplier negativeLimit) {
mPositiveLimit = positiveLimit;
mNegativeLimit = negativeLimit;
if (mPositiveLimit == null) {
mPositiveLimit = () -> false;
}
if (mNegativeLimit == null) {
mNegativeLimit = () -> false;
}
}
@Override
public double run(double currentSpeed, double desiredSpeed, double deltaTime) {
if (shouldStop(desiredSpeed)) {
return 0.0;
}
return desiredSpeed;
}
public boolean isAtPositiveLimit(){
return mPositiveLimit.getAsBoolean();
}
public boolean isAtNegativeLimit(){
return mNegativeLimit.getAsBoolean();
}
private boolean shouldStop(double speed) {
if (speed > 0 && isAtPositiveLimit()) {
return true;
}
if (speed < 0 && isAtNegativeLimit()) {
return true;
}
return false;
}
}
|
package com.thegongoliers.output.motors;
import com.thegongoliers.annotations.Untested;
import java.util.function.BooleanSupplier;
@Untested
public class LimiterMotorModule implements MotorModule {
private BooleanSupplier mPositiveLimit;
private BooleanSupplier mNegativeLimit;
public LimiterMotorModule(BooleanSupplier positiveLimit, BooleanSupplier negativeLimit) {
mPositiveLimit = positiveLimit;
mNegativeLimit = negativeLimit;
if (mPositiveLimit == null) {
mPositiveLimit = () -> false;
}
if (mNegativeLimit == null) {
mNegativeLimit = () -> false;
}
}
public void setNegativeLimit(BooleanSupplier mNegativeLimit) {
this.mNegativeLimit = mNegativeLimit;
}
public void setPositiveLimit(BooleanSupplier mPositiveLimit) {
this.mPositiveLimit = mPositiveLimit;
}
@Override
public double run(double currentSpeed, double desiredSpeed, double deltaTime) {
if (shouldStop(desiredSpeed)) {
return 0.0;
}
return desiredSpeed;
}
public boolean isAtPositiveLimit(){
return mPositiveLimit.getAsBoolean();
}
public boolean isAtNegativeLimit(){
return mNegativeLimit.getAsBoolean();
}
private boolean shouldStop(double speed) {
if (speed > 0 && isAtPositiveLimit()) {
return true;
}
if (speed < 0 && isAtNegativeLimit()) {
return true;
}
return false;
}
}
|
Add setters for limited motor
|
Add setters for limited motor
|
Java
|
mit
|
Gongoliers/Library-of-Gongolierium
|
java
|
## Code Before:
package com.thegongoliers.output.motors;
import com.thegongoliers.annotations.Untested;
import java.util.function.BooleanSupplier;
@Untested
public class LimiterMotorModule implements MotorModule {
private BooleanSupplier mPositiveLimit;
private BooleanSupplier mNegativeLimit;
public LimiterMotorModule(BooleanSupplier positiveLimit, BooleanSupplier negativeLimit) {
mPositiveLimit = positiveLimit;
mNegativeLimit = negativeLimit;
if (mPositiveLimit == null) {
mPositiveLimit = () -> false;
}
if (mNegativeLimit == null) {
mNegativeLimit = () -> false;
}
}
@Override
public double run(double currentSpeed, double desiredSpeed, double deltaTime) {
if (shouldStop(desiredSpeed)) {
return 0.0;
}
return desiredSpeed;
}
public boolean isAtPositiveLimit(){
return mPositiveLimit.getAsBoolean();
}
public boolean isAtNegativeLimit(){
return mNegativeLimit.getAsBoolean();
}
private boolean shouldStop(double speed) {
if (speed > 0 && isAtPositiveLimit()) {
return true;
}
if (speed < 0 && isAtNegativeLimit()) {
return true;
}
return false;
}
}
## Instruction:
Add setters for limited motor
## Code After:
package com.thegongoliers.output.motors;
import com.thegongoliers.annotations.Untested;
import java.util.function.BooleanSupplier;
@Untested
public class LimiterMotorModule implements MotorModule {
private BooleanSupplier mPositiveLimit;
private BooleanSupplier mNegativeLimit;
public LimiterMotorModule(BooleanSupplier positiveLimit, BooleanSupplier negativeLimit) {
mPositiveLimit = positiveLimit;
mNegativeLimit = negativeLimit;
if (mPositiveLimit == null) {
mPositiveLimit = () -> false;
}
if (mNegativeLimit == null) {
mNegativeLimit = () -> false;
}
}
public void setNegativeLimit(BooleanSupplier mNegativeLimit) {
this.mNegativeLimit = mNegativeLimit;
}
public void setPositiveLimit(BooleanSupplier mPositiveLimit) {
this.mPositiveLimit = mPositiveLimit;
}
@Override
public double run(double currentSpeed, double desiredSpeed, double deltaTime) {
if (shouldStop(desiredSpeed)) {
return 0.0;
}
return desiredSpeed;
}
public boolean isAtPositiveLimit(){
return mPositiveLimit.getAsBoolean();
}
public boolean isAtNegativeLimit(){
return mNegativeLimit.getAsBoolean();
}
private boolean shouldStop(double speed) {
if (speed > 0 && isAtPositiveLimit()) {
return true;
}
if (speed < 0 && isAtNegativeLimit()) {
return true;
}
return false;
}
}
|
# ... existing code ...
if (mNegativeLimit == null) {
mNegativeLimit = () -> false;
}
}
public void setNegativeLimit(BooleanSupplier mNegativeLimit) {
this.mNegativeLimit = mNegativeLimit;
}
public void setPositiveLimit(BooleanSupplier mPositiveLimit) {
this.mPositiveLimit = mPositiveLimit;
}
@Override
# ... rest of the code ...
|
db80c8f857b0c4ff3a5ad02a59e6442629599914
|
setuptools/tests/test_upload_docs.py
|
setuptools/tests/test_upload_docs.py
|
import os
import zipfile
import pytest
from setuptools.command.upload_docs import upload_docs
from setuptools.dist import Distribution
from .textwrap import DALS
from . import contexts
SETUP_PY = DALS(
"""
from setuptools import setup
setup(name='foo')
""")
@pytest.fixture
def sample_project(tmpdir_cwd):
# setup.py
with open('setup.py', 'wt') as f:
f.write(SETUP_PY)
os.mkdir('build')
# A test document.
with open('build/index.html', 'w') as f:
f.write("Hello world.")
# An empty folder.
os.mkdir('build/empty')
@pytest.mark.usefixtures('sample_project')
@pytest.mark.usefixtures('user_override')
class TestUploadDocsTest:
def test_create_zipfile(self):
"""
Ensure zipfile creation handles common cases, including a folder
containing an empty folder.
"""
dist = Distribution()
cmd = upload_docs(dist)
cmd.target_dir = cmd.upload_dir = 'build'
with contexts.tempdir() as tmp_dir:
tmp_file = os.path.join(tmp_dir, 'foo.zip')
zip_file = cmd.create_zipfile(tmp_file)
assert zipfile.is_zipfile(tmp_file)
with zipfile.ZipFile(tmp_file) as zip_file:
assert zip_file.namelist() == ['index.html']
|
import os
import zipfile
import contextlib
import pytest
from setuptools.command.upload_docs import upload_docs
from setuptools.dist import Distribution
from .textwrap import DALS
from . import contexts
SETUP_PY = DALS(
"""
from setuptools import setup
setup(name='foo')
""")
@pytest.fixture
def sample_project(tmpdir_cwd):
# setup.py
with open('setup.py', 'wt') as f:
f.write(SETUP_PY)
os.mkdir('build')
# A test document.
with open('build/index.html', 'w') as f:
f.write("Hello world.")
# An empty folder.
os.mkdir('build/empty')
@pytest.mark.usefixtures('sample_project')
@pytest.mark.usefixtures('user_override')
class TestUploadDocsTest:
def test_create_zipfile(self):
"""
Ensure zipfile creation handles common cases, including a folder
containing an empty folder.
"""
dist = Distribution()
cmd = upload_docs(dist)
cmd.target_dir = cmd.upload_dir = 'build'
with contexts.tempdir() as tmp_dir:
tmp_file = os.path.join(tmp_dir, 'foo.zip')
zip_file = cmd.create_zipfile(tmp_file)
assert zipfile.is_zipfile(tmp_file)
with contextlib.closing(zipfile.ZipFile(tmp_file)) as zip_file:
assert zip_file.namelist() == ['index.html']
|
Use closing for Python 2.6 compatibility
|
Use closing for Python 2.6 compatibility
|
Python
|
mit
|
pypa/setuptools,pypa/setuptools,pypa/setuptools
|
python
|
## Code Before:
import os
import zipfile
import pytest
from setuptools.command.upload_docs import upload_docs
from setuptools.dist import Distribution
from .textwrap import DALS
from . import contexts
SETUP_PY = DALS(
"""
from setuptools import setup
setup(name='foo')
""")
@pytest.fixture
def sample_project(tmpdir_cwd):
# setup.py
with open('setup.py', 'wt') as f:
f.write(SETUP_PY)
os.mkdir('build')
# A test document.
with open('build/index.html', 'w') as f:
f.write("Hello world.")
# An empty folder.
os.mkdir('build/empty')
@pytest.mark.usefixtures('sample_project')
@pytest.mark.usefixtures('user_override')
class TestUploadDocsTest:
def test_create_zipfile(self):
"""
Ensure zipfile creation handles common cases, including a folder
containing an empty folder.
"""
dist = Distribution()
cmd = upload_docs(dist)
cmd.target_dir = cmd.upload_dir = 'build'
with contexts.tempdir() as tmp_dir:
tmp_file = os.path.join(tmp_dir, 'foo.zip')
zip_file = cmd.create_zipfile(tmp_file)
assert zipfile.is_zipfile(tmp_file)
with zipfile.ZipFile(tmp_file) as zip_file:
assert zip_file.namelist() == ['index.html']
## Instruction:
Use closing for Python 2.6 compatibility
## Code After:
import os
import zipfile
import contextlib
import pytest
from setuptools.command.upload_docs import upload_docs
from setuptools.dist import Distribution
from .textwrap import DALS
from . import contexts
SETUP_PY = DALS(
"""
from setuptools import setup
setup(name='foo')
""")
@pytest.fixture
def sample_project(tmpdir_cwd):
# setup.py
with open('setup.py', 'wt') as f:
f.write(SETUP_PY)
os.mkdir('build')
# A test document.
with open('build/index.html', 'w') as f:
f.write("Hello world.")
# An empty folder.
os.mkdir('build/empty')
@pytest.mark.usefixtures('sample_project')
@pytest.mark.usefixtures('user_override')
class TestUploadDocsTest:
def test_create_zipfile(self):
"""
Ensure zipfile creation handles common cases, including a folder
containing an empty folder.
"""
dist = Distribution()
cmd = upload_docs(dist)
cmd.target_dir = cmd.upload_dir = 'build'
with contexts.tempdir() as tmp_dir:
tmp_file = os.path.join(tmp_dir, 'foo.zip')
zip_file = cmd.create_zipfile(tmp_file)
assert zipfile.is_zipfile(tmp_file)
with contextlib.closing(zipfile.ZipFile(tmp_file)) as zip_file:
assert zip_file.namelist() == ['index.html']
|
# ... existing code ...
import os
import zipfile
import contextlib
import pytest
# ... modified code ...
assert zipfile.is_zipfile(tmp_file)
with contextlib.closing(zipfile.ZipFile(tmp_file)) as zip_file:
assert zip_file.namelist() == ['index.html']
# ... rest of the code ...
|
2088b3df274fd31c28baa6193c937046c04b98a6
|
scripts/generate_wiki_languages.py
|
scripts/generate_wiki_languages.py
|
from urllib2 import urlopen
import csv
import lxml.builder as lb
from lxml import etree
# Returns CSV of all wikipedias, ordered by number of 'good' articles
URL = "https://wikistats.wmflabs.org/api.php?action=dump&table=wikipedias&format=csv&s=good"
data = csv.reader(urlopen(URL))
# Column 2 is the language code
lang_keys = [row[2] for row in data]
del lang_keys[0] # Get rid of the headers
# Generate the XML
x = lb.E
keys = [x.item(k) for k in lang_keys]
resources = x.resources(
getattr(x, 'string-array')(*keys, name="preference_language_keys"),
)
open("languages_list.xml", "w").write(
etree.tostring(resources, pretty_print=True, encoding="utf-8", xml_declaration=True)
)
|
from urllib2 import urlopen
import csv
import json
import lxml.builder as lb
from lxml import etree
# Returns CSV of all wikipedias, ordered by number of 'good' articles
URL = "https://wikistats.wmflabs.org/api.php?action=dump&table=wikipedias&format=csv&s=good"
data = csv.reader(urlopen(URL))
lang_keys = []
lang_local_names = []
lang_eng_names = []
for row in data:
lang_keys.append(row[2])
lang_local_names.append(row[10])
lang_eng_names.append(row[1])
# Generate the XML, for Android
x = lb.E
keys = [x.item(k) for k in lang_keys]
# Skip the headers!
del keys[0]
resources = x.resources(
getattr(x, 'string-array')(*keys, name="preference_language_keys"),
)
open("languages_list.xml", "w").write(
etree.tostring(resources, pretty_print=True, encoding="utf-8", xml_declaration=True)
)
# Generate the JSON, for iOS
langs_json = []
# Start from 1, to skip the headers
for i in xrange(1, len(lang_keys)):
langs_json.append({
"code": lang_keys[i],
"name": lang_local_names[i],
"canonical_name": lang_eng_names[i]
})
open("languages_list.json", "w").write(json.dumps(langs_json, indent=4))
|
Modify language generation script to make JSON for iOS
|
Modify language generation script to make JSON for iOS
Change-Id: Ib5aec2f6cfcb5bd1187cf8863ecd50f1b1a2d20c
|
Python
|
apache-2.0
|
Wikinaut/wikipedia-app,carloshwa/apps-android-wikipedia,dbrant/apps-android-wikipedia,creaITve/apps-android-tbrc-works,reproio/apps-android-wikipedia,anirudh24seven/apps-android-wikipedia,reproio/apps-android-wikipedia,wikimedia/apps-android-wikipedia,BrunoMRodrigues/apps-android-tbrc-work,BrunoMRodrigues/apps-android-tbrc-work,carloshwa/apps-android-wikipedia,creaITve/apps-android-tbrc-works,BrunoMRodrigues/apps-android-tbrc-work,Wikinaut/wikipedia-app,Wikinaut/wikipedia-app,BrunoMRodrigues/apps-android-tbrc-work,wikimedia/apps-android-wikipedia,anirudh24seven/apps-android-wikipedia,anirudh24seven/apps-android-wikipedia,carloshwa/apps-android-wikipedia,wikimedia/apps-android-wikipedia,Wikinaut/wikipedia-app,parvez3019/apps-android-wikipedia,carloshwa/apps-android-wikipedia,Duct-and-rice/KrswtkhrWiki4Android,anirudh24seven/apps-android-wikipedia,SAGROUP2/apps-android-wikipedia,parvez3019/apps-android-wikipedia,dbrant/apps-android-wikipedia,SAGROUP2/apps-android-wikipedia,dbrant/apps-android-wikipedia,reproio/apps-android-wikipedia,reproio/apps-android-wikipedia,creaITve/apps-android-tbrc-works,anirudh24seven/apps-android-wikipedia,dbrant/apps-android-wikipedia,SAGROUP2/apps-android-wikipedia,Duct-and-rice/KrswtkhrWiki4Android,parvez3019/apps-android-wikipedia,parvez3019/apps-android-wikipedia,SAGROUP2/apps-android-wikipedia,creaITve/apps-android-tbrc-works,wikimedia/apps-android-wikipedia,Duct-and-rice/KrswtkhrWiki4Android,SAGROUP2/apps-android-wikipedia,parvez3019/apps-android-wikipedia,carloshwa/apps-android-wikipedia,dbrant/apps-android-wikipedia,reproio/apps-android-wikipedia,Duct-and-rice/KrswtkhrWiki4Android,Duct-and-rice/KrswtkhrWiki4Android,Wikinaut/wikipedia-app
|
python
|
## Code Before:
from urllib2 import urlopen
import csv
import lxml.builder as lb
from lxml import etree
# Returns CSV of all wikipedias, ordered by number of 'good' articles
URL = "https://wikistats.wmflabs.org/api.php?action=dump&table=wikipedias&format=csv&s=good"
data = csv.reader(urlopen(URL))
# Column 2 is the language code
lang_keys = [row[2] for row in data]
del lang_keys[0] # Get rid of the headers
# Generate the XML
x = lb.E
keys = [x.item(k) for k in lang_keys]
resources = x.resources(
getattr(x, 'string-array')(*keys, name="preference_language_keys"),
)
open("languages_list.xml", "w").write(
etree.tostring(resources, pretty_print=True, encoding="utf-8", xml_declaration=True)
)
## Instruction:
Modify language generation script to make JSON for iOS
Change-Id: Ib5aec2f6cfcb5bd1187cf8863ecd50f1b1a2d20c
## Code After:
from urllib2 import urlopen
import csv
import json
import lxml.builder as lb
from lxml import etree
# Returns CSV of all wikipedias, ordered by number of 'good' articles
URL = "https://wikistats.wmflabs.org/api.php?action=dump&table=wikipedias&format=csv&s=good"
data = csv.reader(urlopen(URL))
lang_keys = []
lang_local_names = []
lang_eng_names = []
for row in data:
lang_keys.append(row[2])
lang_local_names.append(row[10])
lang_eng_names.append(row[1])
# Generate the XML, for Android
x = lb.E
keys = [x.item(k) for k in lang_keys]
# Skip the headers!
del keys[0]
resources = x.resources(
getattr(x, 'string-array')(*keys, name="preference_language_keys"),
)
open("languages_list.xml", "w").write(
etree.tostring(resources, pretty_print=True, encoding="utf-8", xml_declaration=True)
)
# Generate the JSON, for iOS
langs_json = []
# Start from 1, to skip the headers
for i in xrange(1, len(lang_keys)):
langs_json.append({
"code": lang_keys[i],
"name": lang_local_names[i],
"canonical_name": lang_eng_names[i]
})
open("languages_list.json", "w").write(json.dumps(langs_json, indent=4))
|
...
from urllib2 import urlopen
import csv
import json
import lxml.builder as lb
from lxml import etree
...
data = csv.reader(urlopen(URL))
lang_keys = []
lang_local_names = []
lang_eng_names = []
for row in data:
lang_keys.append(row[2])
lang_local_names.append(row[10])
lang_eng_names.append(row[1])
# Generate the XML, for Android
x = lb.E
keys = [x.item(k) for k in lang_keys]
# Skip the headers!
del keys[0]
resources = x.resources(
getattr(x, 'string-array')(*keys, name="preference_language_keys"),
)
...
etree.tostring(resources, pretty_print=True, encoding="utf-8", xml_declaration=True)
)
# Generate the JSON, for iOS
langs_json = []
# Start from 1, to skip the headers
for i in xrange(1, len(lang_keys)):
langs_json.append({
"code": lang_keys[i],
"name": lang_local_names[i],
"canonical_name": lang_eng_names[i]
})
open("languages_list.json", "w").write(json.dumps(langs_json, indent=4))
...
|
95365b5e25619a5a30fe48e31ffbc62a1d77b33f
|
src/com/twitter/intellij/pants/service/project/wizard/FastpassProjectImportProvider.java
|
src/com/twitter/intellij/pants/service/project/wizard/FastpassProjectImportProvider.java
|
// Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
package com.twitter.intellij.pants.service.project.wizard;
import com.intellij.ide.util.PropertiesComponent;
import icons.PantsIcons;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.bsp.project.importing.BspProjectImportProvider;
import javax.swing.Icon;
import java.util.Optional;
public class FastpassProjectImportProvider extends BspProjectImportProvider {
static private String label() {
return Optional
.ofNullable(PropertiesComponent.getInstance().getValue("fastpass.import.provider.label"))
.orElse("Pants (Fastpass)");
}
@Override
public @Nullable Icon getIcon() {
return PantsIcons.Icon;
}
@Override
public @NotNull
@Nls(capitalization = Nls.Capitalization.Sentence) String getName() {
return label();
}
}
|
// Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
package com.twitter.intellij.pants.service.project.wizard;
import com.intellij.ide.util.PropertiesComponent;
import icons.PantsIcons;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.bsp.project.importing.BspProjectImportProvider;
import javax.swing.Icon;
import java.util.Optional;
public class FastpassProjectImportProvider extends BspProjectImportProvider {
static private String label() {
return Optional
.ofNullable(PropertiesComponent.getInstance().getValue("fastpass.import.provider.label"))
.orElse("Pants (Fastpass)");
}
@Override
public @Nullable Icon getIcon() {
return PantsIcons.Icon;
}
@NotNull
@Override
public String getId() {
return "Fastpass";
}
@Override
public @NotNull
@Nls(capitalization = Nls.Capitalization.Sentence) String getName() {
return label();
}
}
|
Set Fastpass Import provider ID to 'Fastpass'
|
Set Fastpass Import provider ID to 'Fastpass'
|
Java
|
apache-2.0
|
pantsbuild/intellij-pants-plugin,pantsbuild/intellij-pants-plugin,pantsbuild/intellij-pants-plugin,pantsbuild/intellij-pants-plugin,pantsbuild/intellij-pants-plugin
|
java
|
## Code Before:
// Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
package com.twitter.intellij.pants.service.project.wizard;
import com.intellij.ide.util.PropertiesComponent;
import icons.PantsIcons;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.bsp.project.importing.BspProjectImportProvider;
import javax.swing.Icon;
import java.util.Optional;
public class FastpassProjectImportProvider extends BspProjectImportProvider {
static private String label() {
return Optional
.ofNullable(PropertiesComponent.getInstance().getValue("fastpass.import.provider.label"))
.orElse("Pants (Fastpass)");
}
@Override
public @Nullable Icon getIcon() {
return PantsIcons.Icon;
}
@Override
public @NotNull
@Nls(capitalization = Nls.Capitalization.Sentence) String getName() {
return label();
}
}
## Instruction:
Set Fastpass Import provider ID to 'Fastpass'
## Code After:
// Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
package com.twitter.intellij.pants.service.project.wizard;
import com.intellij.ide.util.PropertiesComponent;
import icons.PantsIcons;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.bsp.project.importing.BspProjectImportProvider;
import javax.swing.Icon;
import java.util.Optional;
public class FastpassProjectImportProvider extends BspProjectImportProvider {
static private String label() {
return Optional
.ofNullable(PropertiesComponent.getInstance().getValue("fastpass.import.provider.label"))
.orElse("Pants (Fastpass)");
}
@Override
public @Nullable Icon getIcon() {
return PantsIcons.Icon;
}
@NotNull
@Override
public String getId() {
return "Fastpass";
}
@Override
public @NotNull
@Nls(capitalization = Nls.Capitalization.Sentence) String getName() {
return label();
}
}
|
# ... existing code ...
return PantsIcons.Icon;
}
@NotNull
@Override
public String getId() {
return "Fastpass";
}
@Override
public @NotNull
@Nls(capitalization = Nls.Capitalization.Sentence) String getName() {
# ... rest of the code ...
|
a882990c9d05497540efca385ebb55c200e01e76
|
MUON/mapping/AliMpStationType.h
|
MUON/mapping/AliMpStationType.h
|
/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* See cxx source for full Copyright notice */
// $Id$
// $MpId: AliMpStationType.h,v 1.5 2005/10/28 15:05:04 ivana Exp $
/// \ingroup basic
/// \enum AliMpStationType
/// Enumeration for refering to a MUON station
///
/// Authors: David Guez, Ivana Hrivnacova; IPN Orsay
#ifndef ALI_MP_STATION_TYPE_H
#define ALI_MP_STATION_TYPE_H
enum AliMpStationType
{
kStationInvalid = -1,///< invalid station
kStation1 = 0, ///< station 1 (quadrants)
kStation2, ///< station 2 (quadrants)
kStation345, ///< station 3,4,5 (slats)
kStationTrigger ///< trigger stations (slats)
};
inline
const char* StationTypeName(AliMpStationType stationType)
{
switch ( stationType )
{
case kStation1:
return "st1";
break;
case kStation2:
return "st2";
break;
case kStation345:
return "slat";
break;
case kStationTrigger:
return "trigger";
break;
case kStationInvalid:
default:
return "unknown";
break;
}
}
#endif //ALI_MP_STATION_TYPE_H
|
/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* See cxx source for full Copyright notice */
// $Id$
// $MpId: AliMpStationType.h,v 1.5 2005/10/28 15:05:04 ivana Exp $
/// \ingroup basic
/// \enum AliMpStationType
/// Enumeration for refering to a MUON station
///
/// Authors: David Guez, Ivana Hrivnacova; IPN Orsay
#ifndef ALI_MP_STATION_TYPE_H
#define ALI_MP_STATION_TYPE_H
enum AliMpStationType
{
kStationInvalid = -1,///< invalid station
kStation1 = 0, ///< station 1 (quadrants)
kStation2, ///< station 2 (quadrants)
kStation345, ///< station 3,4,5 (slats)
kStationTrigger ///< trigger stations (slats)
};
inline
const char* StationTypeName(AliMpStationType stationType)
{
switch ( stationType )
{
case kStation1:
return "st1";
break;
case kStation2:
return "st2";
break;
case kStation345:
return "slat";
break;
case kStationTrigger:
return "trigger";
break;
case kStationInvalid:
default:
return "invalid";
break;
}
return "unknown";
}
#endif //ALI_MP_STATION_TYPE_H
|
Fix warning from gcc4 (Laurent)
|
Fix warning from gcc4
(Laurent)
|
C
|
bsd-3-clause
|
ALICEHLT/AliRoot,shahor02/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,alisw/AliRoot,ecalvovi/AliRoot,mkrzewic/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,miranov25/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,ALICEHLT/AliRoot,ALICEHLT/AliRoot,mkrzewic/AliRoot,miranov25/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,jgrosseo/AliRoot,coppedis/AliRoot,coppedis/AliRoot,alisw/AliRoot,sebaleh/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,coppedis/AliRoot,mkrzewic/AliRoot,sebaleh/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,shahor02/AliRoot,shahor02/AliRoot,miranov25/AliRoot,shahor02/AliRoot,jgrosseo/AliRoot,shahor02/AliRoot,ALICEHLT/AliRoot,ecalvovi/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,shahor02/AliRoot,mkrzewic/AliRoot,miranov25/AliRoot,alisw/AliRoot,coppedis/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,alisw/AliRoot,coppedis/AliRoot,miranov25/AliRoot,jgrosseo/AliRoot,coppedis/AliRoot,shahor02/AliRoot,mkrzewic/AliRoot,jgrosseo/AliRoot,ecalvovi/AliRoot,alisw/AliRoot,jgrosseo/AliRoot
|
c
|
## Code Before:
/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* See cxx source for full Copyright notice */
// $Id$
// $MpId: AliMpStationType.h,v 1.5 2005/10/28 15:05:04 ivana Exp $
/// \ingroup basic
/// \enum AliMpStationType
/// Enumeration for refering to a MUON station
///
/// Authors: David Guez, Ivana Hrivnacova; IPN Orsay
#ifndef ALI_MP_STATION_TYPE_H
#define ALI_MP_STATION_TYPE_H
enum AliMpStationType
{
kStationInvalid = -1,///< invalid station
kStation1 = 0, ///< station 1 (quadrants)
kStation2, ///< station 2 (quadrants)
kStation345, ///< station 3,4,5 (slats)
kStationTrigger ///< trigger stations (slats)
};
inline
const char* StationTypeName(AliMpStationType stationType)
{
switch ( stationType )
{
case kStation1:
return "st1";
break;
case kStation2:
return "st2";
break;
case kStation345:
return "slat";
break;
case kStationTrigger:
return "trigger";
break;
case kStationInvalid:
default:
return "unknown";
break;
}
}
#endif //ALI_MP_STATION_TYPE_H
## Instruction:
Fix warning from gcc4
(Laurent)
## Code After:
/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* See cxx source for full Copyright notice */
// $Id$
// $MpId: AliMpStationType.h,v 1.5 2005/10/28 15:05:04 ivana Exp $
/// \ingroup basic
/// \enum AliMpStationType
/// Enumeration for refering to a MUON station
///
/// Authors: David Guez, Ivana Hrivnacova; IPN Orsay
#ifndef ALI_MP_STATION_TYPE_H
#define ALI_MP_STATION_TYPE_H
enum AliMpStationType
{
kStationInvalid = -1,///< invalid station
kStation1 = 0, ///< station 1 (quadrants)
kStation2, ///< station 2 (quadrants)
kStation345, ///< station 3,4,5 (slats)
kStationTrigger ///< trigger stations (slats)
};
inline
const char* StationTypeName(AliMpStationType stationType)
{
switch ( stationType )
{
case kStation1:
return "st1";
break;
case kStation2:
return "st2";
break;
case kStation345:
return "slat";
break;
case kStationTrigger:
return "trigger";
break;
case kStationInvalid:
default:
return "invalid";
break;
}
return "unknown";
}
#endif //ALI_MP_STATION_TYPE_H
|
# ... existing code ...
break;
case kStationInvalid:
default:
return "invalid";
break;
}
return "unknown";
}
#endif //ALI_MP_STATION_TYPE_H
# ... rest of the code ...
|
6e8efdbb31c8713eeee0105ddafbd88d6286cfc9
|
ganttcharts/cli/send_summary_emails.py
|
ganttcharts/cli/send_summary_emails.py
|
import datetime
import time
from .. import emails
from ..database import get_sql_connection
from ..models import Account, Session as SqlSession
__description__ = 'Send out summary emails.'
def send_out_emails():
session = SqlSession()
today = datetime.date.today()
accounts = session.query(Account) \
.filter(Account.receive_summary_email == True)
for account in accounts:
email = emails.Summary(account, today)
with emails.Mailer() as mailer:
mailer.send(email)
def command(args):
get_sql_connection()
if args.forever:
while True:
tomorrow = datetime.datetime.utcnow() + datetime.timedelta(days=1)
tomorrow = tomorrow.replace(hour=4, minute=0)
diff = tomorrow - datetime.datetime.utcnow()
time.sleep(diff.total_seconds())
send_out_emails()
else:
send_out_emails()
def add_subparser(subparsers):
parser = subparsers.add_parser('send-summary-emails', help=__description__)
parser.add_argument('--forever', action='store_true')
parser.set_defaults(func=command)
|
import datetime
import time
from .. import emails
from ..database import get_sql_connection
from ..models import Account, Session as SqlSession
__description__ = 'Send out summary emails.'
def send_out_emails():
session = SqlSession()
today = datetime.date.today()
accounts = session.query(Account) \
.filter(Account.receive_summary_email == True)
for account in accounts:
try:
email = emails.Summary(account, today)
except RuntimeError: # no tasks
continue
with emails.Mailer() as mailer:
mailer.send(email)
def command(args):
get_sql_connection()
if args.forever:
while True:
tomorrow = datetime.datetime.utcnow() + datetime.timedelta(days=1)
tomorrow = tomorrow.replace(hour=4, minute=0)
diff = tomorrow - datetime.datetime.utcnow()
time.sleep(diff.total_seconds())
send_out_emails()
else:
send_out_emails()
def add_subparser(subparsers):
parser = subparsers.add_parser('send-summary-emails', help=__description__)
parser.add_argument('--forever', action='store_true')
parser.set_defaults(func=command)
|
Add check for no tasks
|
Add check for no tasks
|
Python
|
mit
|
thomasleese/gantt-charts,thomasleese/gantt-charts,thomasleese/gantt-charts,thomasleese/gantt-charts,thomasleese/gantt-charts
|
python
|
## Code Before:
import datetime
import time
from .. import emails
from ..database import get_sql_connection
from ..models import Account, Session as SqlSession
__description__ = 'Send out summary emails.'
def send_out_emails():
session = SqlSession()
today = datetime.date.today()
accounts = session.query(Account) \
.filter(Account.receive_summary_email == True)
for account in accounts:
email = emails.Summary(account, today)
with emails.Mailer() as mailer:
mailer.send(email)
def command(args):
get_sql_connection()
if args.forever:
while True:
tomorrow = datetime.datetime.utcnow() + datetime.timedelta(days=1)
tomorrow = tomorrow.replace(hour=4, minute=0)
diff = tomorrow - datetime.datetime.utcnow()
time.sleep(diff.total_seconds())
send_out_emails()
else:
send_out_emails()
def add_subparser(subparsers):
parser = subparsers.add_parser('send-summary-emails', help=__description__)
parser.add_argument('--forever', action='store_true')
parser.set_defaults(func=command)
## Instruction:
Add check for no tasks
## Code After:
import datetime
import time
from .. import emails
from ..database import get_sql_connection
from ..models import Account, Session as SqlSession
__description__ = 'Send out summary emails.'
def send_out_emails():
session = SqlSession()
today = datetime.date.today()
accounts = session.query(Account) \
.filter(Account.receive_summary_email == True)
for account in accounts:
try:
email = emails.Summary(account, today)
except RuntimeError: # no tasks
continue
with emails.Mailer() as mailer:
mailer.send(email)
def command(args):
get_sql_connection()
if args.forever:
while True:
tomorrow = datetime.datetime.utcnow() + datetime.timedelta(days=1)
tomorrow = tomorrow.replace(hour=4, minute=0)
diff = tomorrow - datetime.datetime.utcnow()
time.sleep(diff.total_seconds())
send_out_emails()
else:
send_out_emails()
def add_subparser(subparsers):
parser = subparsers.add_parser('send-summary-emails', help=__description__)
parser.add_argument('--forever', action='store_true')
parser.set_defaults(func=command)
|
# ... existing code ...
accounts = session.query(Account) \
.filter(Account.receive_summary_email == True)
for account in accounts:
try:
email = emails.Summary(account, today)
except RuntimeError: # no tasks
continue
with emails.Mailer() as mailer:
mailer.send(email)
# ... rest of the code ...
|
813b81293cd2bd69982aef36ad09fc52f7bea1f6
|
relaygram/http_server.py
|
relaygram/http_server.py
|
import http.server
from threading import Thread
import os.path
class HTTPHandler:
def __init__(self, config):
self.config = config
handler = HTTPHandler.make_http_handler('C:/tmp/test/')
self.httpd = http.server.HTTPServer(('', 8000), handler)
self.thread = Thread(target=self.main_loop)
def run(self):
self.thread.start()
return self
def main_loop(self):
self.httpd.serve_forever()
@staticmethod
def make_http_handler(root_path):
class RelayGramHTTPHandler(http.server.BaseHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super(RelayGramHTTPHandler, self).__init__(*args, **kwargs)
def do_GET(self):
file_path = os.path.abspath(root_path + self.path)
if os.path.commonpath([root_path, file_path]) != os.path.abspath(root_path): # Detect path traversal attempt
self.send_error(501, "Nice try")
else:
if not os.path.exists(file_path) or not os.path.isfile(file_path):
self.send_error(404, 'File Not Found')
else:
self.send_response(200)
self.wfile.write(open(file_path, mode='rb').read())
return RelayGramHTTPHandler
|
import http.server
from threading import Thread
import os.path
class HTTPHandler:
def __init__(self, config):
self.config = config
handler = HTTPHandler.make_http_handler(self.config['media_dir'])
self.httpd = http.server.HTTPServer(('', self.config['media']['port']), handler)
self.thread = Thread(target=self.main_loop)
def run(self):
self.thread.start()
return self
def main_loop(self):
self.httpd.serve_forever()
@staticmethod
def make_http_handler(root_path):
class RelayGramHTTPHandler(http.server.BaseHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super(RelayGramHTTPHandler, self).__init__(*args, **kwargs)
def do_GET(self):
file_path = os.path.abspath(root_path + self.path)
if os.path.commonpath([root_path, file_path]) != os.path.abspath(root_path): # Detect path traversal attempt
self.send_error(501, "Nice try")
else:
if not os.path.exists(file_path) or not os.path.isfile(file_path):
self.send_error(404, 'File Not Found')
else:
self.send_response(200)
self.wfile.write(open(file_path, mode='rb').read())
return RelayGramHTTPHandler
|
Use proper settings for httpd server.
|
Use proper settings for httpd server.
|
Python
|
mit
|
Surye/relaygram
|
python
|
## Code Before:
import http.server
from threading import Thread
import os.path
class HTTPHandler:
def __init__(self, config):
self.config = config
handler = HTTPHandler.make_http_handler('C:/tmp/test/')
self.httpd = http.server.HTTPServer(('', 8000), handler)
self.thread = Thread(target=self.main_loop)
def run(self):
self.thread.start()
return self
def main_loop(self):
self.httpd.serve_forever()
@staticmethod
def make_http_handler(root_path):
class RelayGramHTTPHandler(http.server.BaseHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super(RelayGramHTTPHandler, self).__init__(*args, **kwargs)
def do_GET(self):
file_path = os.path.abspath(root_path + self.path)
if os.path.commonpath([root_path, file_path]) != os.path.abspath(root_path): # Detect path traversal attempt
self.send_error(501, "Nice try")
else:
if not os.path.exists(file_path) or not os.path.isfile(file_path):
self.send_error(404, 'File Not Found')
else:
self.send_response(200)
self.wfile.write(open(file_path, mode='rb').read())
return RelayGramHTTPHandler
## Instruction:
Use proper settings for httpd server.
## Code After:
import http.server
from threading import Thread
import os.path
class HTTPHandler:
def __init__(self, config):
self.config = config
handler = HTTPHandler.make_http_handler(self.config['media_dir'])
self.httpd = http.server.HTTPServer(('', self.config['media']['port']), handler)
self.thread = Thread(target=self.main_loop)
def run(self):
self.thread.start()
return self
def main_loop(self):
self.httpd.serve_forever()
@staticmethod
def make_http_handler(root_path):
class RelayGramHTTPHandler(http.server.BaseHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super(RelayGramHTTPHandler, self).__init__(*args, **kwargs)
def do_GET(self):
file_path = os.path.abspath(root_path + self.path)
if os.path.commonpath([root_path, file_path]) != os.path.abspath(root_path): # Detect path traversal attempt
self.send_error(501, "Nice try")
else:
if not os.path.exists(file_path) or not os.path.isfile(file_path):
self.send_error(404, 'File Not Found')
else:
self.send_response(200)
self.wfile.write(open(file_path, mode='rb').read())
return RelayGramHTTPHandler
|
// ... existing code ...
def __init__(self, config):
self.config = config
handler = HTTPHandler.make_http_handler(self.config['media_dir'])
self.httpd = http.server.HTTPServer(('', self.config['media']['port']), handler)
self.thread = Thread(target=self.main_loop)
// ... rest of the code ...
|
b13ec943c809e1edfbaf3ede7a8f0373a46db7c2
|
src/main/java/macrobase/analysis/outlier/TimeSeriesOutlierDetector.java
|
src/main/java/macrobase/analysis/outlier/TimeSeriesOutlierDetector.java
|
package macrobase.analysis.outlier;
import java.util.List;
import macrobase.conf.MacroBaseConf;
import macrobase.conf.MacroBaseDefaults;
import macrobase.datamodel.Datum;
public abstract class TimeSeriesOutlierDetector extends OutlierDetector {
protected final int tupleWindowSize;
private int currentTupleWindowSize;
public TimeSeriesOutlierDetector(MacroBaseConf conf) {
super(conf);
this.tupleWindowSize = conf.getInt(MacroBaseConf.TUPLE_WINDOW, MacroBaseDefaults.TUPLE_WINDOW);
assert tupleWindowSize > 1;
}
public abstract void addToWindow(Datum datum);
public abstract void removeLastFromWindow();
// Score current window.
public abstract double scoreWindow();
@Override
public void train(List<Datum> data) {
// Just sanity checks - we don't actually compute anything in train,
// since we train as we go while scoring.
assert data.size() >= tupleWindowSize;
assert data.get(0).getTime() != null;
}
@Override
public double score(Datum datum) {
/*
* Note: we assume score is called with data in order - this is true for
* batch analysis. Somewhat hacky but allows us to maintain
* compatibility with OutlierDetector.
*/
if (currentTupleWindowSize == tupleWindowSize) {
currentTupleWindowSize--;
removeLastFromWindow();
}
currentTupleWindowSize++;
addToWindow(datum);
return scoreWindow();
}
@Override
public double getZScoreEquivalent(double zscore) {
return 0;
}
}
|
package macrobase.analysis.outlier;
import java.util.List;
import macrobase.conf.MacroBaseConf;
import macrobase.conf.MacroBaseDefaults;
import macrobase.datamodel.Datum;
public abstract class TimeSeriesOutlierDetector extends OutlierDetector {
protected final int tupleWindowSize;
private int currentTupleWindowSize;
public TimeSeriesOutlierDetector(MacroBaseConf conf) {
super(conf);
this.tupleWindowSize = conf.getInt(MacroBaseConf.TUPLE_WINDOW, MacroBaseDefaults.TUPLE_WINDOW);
assert tupleWindowSize > 1;
}
public abstract void addToWindow(Datum datum);
public abstract void removeLastFromWindow();
/**
* Use the current window to build a model and then score the latest datum.
*/
public abstract double scoreWindow();
@Override
public void train(List<Datum> data) {
// Just sanity checks - we don't actually compute anything in train,
// since we train as we go while scoring.
assert data.size() >= tupleWindowSize;
assert data.get(0).getTime() != null;
}
@Override
public double score(Datum datum) {
/*
* Note: we assume score is called with data in order - this is true for
* batch analysis. Somewhat hacky but allows us to maintain
* compatibility with OutlierDetector.
*/
if (currentTupleWindowSize == tupleWindowSize) {
currentTupleWindowSize--;
removeLastFromWindow();
}
currentTupleWindowSize++;
addToWindow(datum);
return scoreWindow();
}
@Override
public double getZScoreEquivalent(double zscore) {
return 0;
}
}
|
Clarify current model of time series scoring
|
Clarify current model of time series scoring
|
Java
|
apache-2.0
|
kexinrong/macrobase,kexinrong/macrobase,stanford-futuredata/macrobase,stanford-futuredata/macrobase,stanford-futuredata/macrobase,kexinrong/macrobase,stanford-futuredata/macrobase,kexinrong/macrobase,kexinrong/macrobase,stanford-futuredata/macrobase,kexinrong/macrobase,kexinrong/macrobase
|
java
|
## Code Before:
package macrobase.analysis.outlier;
import java.util.List;
import macrobase.conf.MacroBaseConf;
import macrobase.conf.MacroBaseDefaults;
import macrobase.datamodel.Datum;
public abstract class TimeSeriesOutlierDetector extends OutlierDetector {
protected final int tupleWindowSize;
private int currentTupleWindowSize;
public TimeSeriesOutlierDetector(MacroBaseConf conf) {
super(conf);
this.tupleWindowSize = conf.getInt(MacroBaseConf.TUPLE_WINDOW, MacroBaseDefaults.TUPLE_WINDOW);
assert tupleWindowSize > 1;
}
public abstract void addToWindow(Datum datum);
public abstract void removeLastFromWindow();
// Score current window.
public abstract double scoreWindow();
@Override
public void train(List<Datum> data) {
// Just sanity checks - we don't actually compute anything in train,
// since we train as we go while scoring.
assert data.size() >= tupleWindowSize;
assert data.get(0).getTime() != null;
}
@Override
public double score(Datum datum) {
/*
* Note: we assume score is called with data in order - this is true for
* batch analysis. Somewhat hacky but allows us to maintain
* compatibility with OutlierDetector.
*/
if (currentTupleWindowSize == tupleWindowSize) {
currentTupleWindowSize--;
removeLastFromWindow();
}
currentTupleWindowSize++;
addToWindow(datum);
return scoreWindow();
}
@Override
public double getZScoreEquivalent(double zscore) {
return 0;
}
}
## Instruction:
Clarify current model of time series scoring
## Code After:
package macrobase.analysis.outlier;
import java.util.List;
import macrobase.conf.MacroBaseConf;
import macrobase.conf.MacroBaseDefaults;
import macrobase.datamodel.Datum;
public abstract class TimeSeriesOutlierDetector extends OutlierDetector {
protected final int tupleWindowSize;
private int currentTupleWindowSize;
public TimeSeriesOutlierDetector(MacroBaseConf conf) {
super(conf);
this.tupleWindowSize = conf.getInt(MacroBaseConf.TUPLE_WINDOW, MacroBaseDefaults.TUPLE_WINDOW);
assert tupleWindowSize > 1;
}
public abstract void addToWindow(Datum datum);
public abstract void removeLastFromWindow();
/**
* Use the current window to build a model and then score the latest datum.
*/
public abstract double scoreWindow();
@Override
public void train(List<Datum> data) {
// Just sanity checks - we don't actually compute anything in train,
// since we train as we go while scoring.
assert data.size() >= tupleWindowSize;
assert data.get(0).getTime() != null;
}
@Override
public double score(Datum datum) {
/*
* Note: we assume score is called with data in order - this is true for
* batch analysis. Somewhat hacky but allows us to maintain
* compatibility with OutlierDetector.
*/
if (currentTupleWindowSize == tupleWindowSize) {
currentTupleWindowSize--;
removeLastFromWindow();
}
currentTupleWindowSize++;
addToWindow(datum);
return scoreWindow();
}
@Override
public double getZScoreEquivalent(double zscore) {
return 0;
}
}
|
// ... existing code ...
public abstract void removeLastFromWindow();
/**
* Use the current window to build a model and then score the latest datum.
*/
public abstract double scoreWindow();
@Override
// ... rest of the code ...
|
f852cc8e84d3452d1dc6f0d49af84b434647dcdd
|
ethereumj-core/src/test/java/org/ethereum/solidity/AbiTest.java
|
ethereumj-core/src/test/java/org/ethereum/solidity/AbiTest.java
|
package org.ethereum.solidity;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertTrue;
import org.ethereum.solidity.Abi.Entry;
import org.ethereum.solidity.Abi.Entry.Type;
import org.junit.Test;
import java.io.IOException;
public class AbiTest {
@Test
public void simpleTest() throws IOException {
String contractAbi = "[{"
+ "\"name\":\"simpleFunction\","
+ "\"constant\":true,"
+ "\"payable\":true,"
+ "\"type\":\"function\","
+ "\"inputs\": [{\"name\":\"_in\", \"type\":\"bytes32\"}],"
+ "\"outputs\":[{\"name\":\"_out\",\"type\":\"bytes32\"}]}]";
Abi abi = Abi.fromJson(contractAbi);
assertEquals(abi.size(), 1);
Entry onlyFunc = abi.get(0);
assertEquals(onlyFunc.type, Type.function);
assertEquals(onlyFunc.inputs.size(), 1);
assertEquals(onlyFunc.outputs.size(), 1);
assertTrue(onlyFunc.payable);
assertTrue(onlyFunc.constant);
}
public static void main(String[] args) throws Exception {
new AbiTest().simpleTest();
}
}
|
package org.ethereum.solidity;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertTrue;
import org.ethereum.solidity.Abi.Entry;
import org.ethereum.solidity.Abi.Entry.Type;
import org.junit.Test;
import java.io.IOException;
public class AbiTest {
@Test
public void simpleTest() throws IOException {
String contractAbi = "[{"
+ "\"name\":\"simpleFunction\","
+ "\"constant\":true,"
+ "\"payable\":true,"
+ "\"type\":\"function\","
+ "\"inputs\": [{\"name\":\"_in\", \"type\":\"bytes32\"}],"
+ "\"outputs\":[{\"name\":\"_out\",\"type\":\"bytes32\"}]}]";
Abi abi = Abi.fromJson(contractAbi);
assertEquals(abi.size(), 1);
Entry onlyFunc = abi.get(0);
assertEquals(onlyFunc.type, Type.function);
assertEquals(onlyFunc.inputs.size(), 1);
assertEquals(onlyFunc.outputs.size(), 1);
assertTrue(onlyFunc.payable);
assertTrue(onlyFunc.constant);
}
@Test
public void simpleLegacyTest() throws IOException {
String contractAbi = "[{"
+ "\"name\":\"simpleFunction\","
+ "\"constant\":true,"
+ "\"type\":\"function\","
+ "\"inputs\": [{\"name\":\"_in\", \"type\":\"bytes32\"}],"
+ "\"outputs\":[{\"name\":\"_out\",\"type\":\"bytes32\"}]}]";
Abi abi = Abi.fromJson(contractAbi);
assertEquals(abi.size(), 1);
Entry onlyFunc = abi.get(0);
assertEquals(onlyFunc.type, Type.function);
assertEquals(onlyFunc.inputs.size(), 1);
assertEquals(onlyFunc.outputs.size(), 1);
assertTrue(onlyFunc.constant);
}
}
|
Add test for solc backward compatibility
|
Add test for solc backward compatibility
|
Java
|
mit
|
loxal/FreeEthereum,loxal/FreeEthereum,loxal/ethereumj,loxal/FreeEthereum
|
java
|
## Code Before:
package org.ethereum.solidity;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertTrue;
import org.ethereum.solidity.Abi.Entry;
import org.ethereum.solidity.Abi.Entry.Type;
import org.junit.Test;
import java.io.IOException;
public class AbiTest {
@Test
public void simpleTest() throws IOException {
String contractAbi = "[{"
+ "\"name\":\"simpleFunction\","
+ "\"constant\":true,"
+ "\"payable\":true,"
+ "\"type\":\"function\","
+ "\"inputs\": [{\"name\":\"_in\", \"type\":\"bytes32\"}],"
+ "\"outputs\":[{\"name\":\"_out\",\"type\":\"bytes32\"}]}]";
Abi abi = Abi.fromJson(contractAbi);
assertEquals(abi.size(), 1);
Entry onlyFunc = abi.get(0);
assertEquals(onlyFunc.type, Type.function);
assertEquals(onlyFunc.inputs.size(), 1);
assertEquals(onlyFunc.outputs.size(), 1);
assertTrue(onlyFunc.payable);
assertTrue(onlyFunc.constant);
}
public static void main(String[] args) throws Exception {
new AbiTest().simpleTest();
}
}
## Instruction:
Add test for solc backward compatibility
## Code After:
package org.ethereum.solidity;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertTrue;
import org.ethereum.solidity.Abi.Entry;
import org.ethereum.solidity.Abi.Entry.Type;
import org.junit.Test;
import java.io.IOException;
public class AbiTest {
@Test
public void simpleTest() throws IOException {
String contractAbi = "[{"
+ "\"name\":\"simpleFunction\","
+ "\"constant\":true,"
+ "\"payable\":true,"
+ "\"type\":\"function\","
+ "\"inputs\": [{\"name\":\"_in\", \"type\":\"bytes32\"}],"
+ "\"outputs\":[{\"name\":\"_out\",\"type\":\"bytes32\"}]}]";
Abi abi = Abi.fromJson(contractAbi);
assertEquals(abi.size(), 1);
Entry onlyFunc = abi.get(0);
assertEquals(onlyFunc.type, Type.function);
assertEquals(onlyFunc.inputs.size(), 1);
assertEquals(onlyFunc.outputs.size(), 1);
assertTrue(onlyFunc.payable);
assertTrue(onlyFunc.constant);
}
@Test
public void simpleLegacyTest() throws IOException {
String contractAbi = "[{"
+ "\"name\":\"simpleFunction\","
+ "\"constant\":true,"
+ "\"type\":\"function\","
+ "\"inputs\": [{\"name\":\"_in\", \"type\":\"bytes32\"}],"
+ "\"outputs\":[{\"name\":\"_out\",\"type\":\"bytes32\"}]}]";
Abi abi = Abi.fromJson(contractAbi);
assertEquals(abi.size(), 1);
Entry onlyFunc = abi.get(0);
assertEquals(onlyFunc.type, Type.function);
assertEquals(onlyFunc.inputs.size(), 1);
assertEquals(onlyFunc.outputs.size(), 1);
assertTrue(onlyFunc.constant);
}
}
|
...
assertTrue(onlyFunc.constant);
}
@Test
public void simpleLegacyTest() throws IOException {
String contractAbi = "[{"
+ "\"name\":\"simpleFunction\","
+ "\"constant\":true,"
+ "\"type\":\"function\","
+ "\"inputs\": [{\"name\":\"_in\", \"type\":\"bytes32\"}],"
+ "\"outputs\":[{\"name\":\"_out\",\"type\":\"bytes32\"}]}]";
Abi abi = Abi.fromJson(contractAbi);
assertEquals(abi.size(), 1);
Entry onlyFunc = abi.get(0);
assertEquals(onlyFunc.type, Type.function);
assertEquals(onlyFunc.inputs.size(), 1);
assertEquals(onlyFunc.outputs.size(), 1);
assertTrue(onlyFunc.constant);
}
}
...
|
4641b9a1b9a79fdeb0aaa3264de7bd1703b1d1fa
|
alexandria/web.py
|
alexandria/web.py
|
from alexandria import app, mongo
from decorators import *
from flask import render_template, request, jsonify, g, send_from_directory, redirect, url_for, session, flash
import os
import shutil
import requests
from pymongo import MongoClient
from functools import wraps
import bcrypt
from bson.objectid import ObjectId
@app.route('/', methods=['GET'])
@authenticated
def index():
return render_template('app.html')
@app.route('/portal')
def portal():
if not session.get('username'):
return render_template('portal.html')
else:
return render_template('index.html')
@app.route('/logout')
def logout():
session.pop('username', None)
session.pop('role', None)
session.pop('realname', None)
return redirect(url_for('index'))
@app.route('/download/<id>/<format>')
@authenticated
def download(id, format):
book = mongo.Books.find({'id':id})[0]
response = send_from_directory(app.config['LIB_DIR'], id+'.'+format)
response.headers.add('Content-Disposition', 'attachment; filename="' + book['title'] + '.' + format + '"')
return response
@app.route('/upload')
@authenticated
@administrator
def upload():
return render_template('upload.html')
if __name__ == "__main__":
app.run()
|
from alexandria import app, mongo
from decorators import *
from flask import render_template, request, jsonify, g, send_from_directory, redirect, url_for, session, flash
import os
import shutil
import requests
from pymongo import MongoClient
from functools import wraps
import bcrypt
from bson.objectid import ObjectId
@app.route('/', methods=['GET'])
@authenticated
def index():
return render_template('app.html')
@app.route('/portal')
def portal():
if not session.get('username'):
return render_template('portal.html')
else:
return redirect(url_for('index'))
@app.route('/logout')
def logout():
session.pop('username', None)
session.pop('role', None)
session.pop('realname', None)
return redirect(url_for('index'))
@app.route('/download/<id>/<format>')
@authenticated
def download(id, format):
book = mongo.Books.find({'id':id})[0]
response = send_from_directory(app.config['LIB_DIR'], id+'.'+format)
response.headers.add('Content-Disposition', 'attachment; filename="' + book['title'] + '.' + format + '"')
return response
@app.route('/upload')
@authenticated
@administrator
def upload():
return render_template('upload.html')
if __name__ == "__main__":
app.run()
|
Fix return on active user accessing the portal
|
Fix return on active user accessing the portal
|
Python
|
mit
|
citruspi/Alexandria,citruspi/Alexandria
|
python
|
## Code Before:
from alexandria import app, mongo
from decorators import *
from flask import render_template, request, jsonify, g, send_from_directory, redirect, url_for, session, flash
import os
import shutil
import requests
from pymongo import MongoClient
from functools import wraps
import bcrypt
from bson.objectid import ObjectId
@app.route('/', methods=['GET'])
@authenticated
def index():
return render_template('app.html')
@app.route('/portal')
def portal():
if not session.get('username'):
return render_template('portal.html')
else:
return render_template('index.html')
@app.route('/logout')
def logout():
session.pop('username', None)
session.pop('role', None)
session.pop('realname', None)
return redirect(url_for('index'))
@app.route('/download/<id>/<format>')
@authenticated
def download(id, format):
book = mongo.Books.find({'id':id})[0]
response = send_from_directory(app.config['LIB_DIR'], id+'.'+format)
response.headers.add('Content-Disposition', 'attachment; filename="' + book['title'] + '.' + format + '"')
return response
@app.route('/upload')
@authenticated
@administrator
def upload():
return render_template('upload.html')
if __name__ == "__main__":
app.run()
## Instruction:
Fix return on active user accessing the portal
## Code After:
from alexandria import app, mongo
from decorators import *
from flask import render_template, request, jsonify, g, send_from_directory, redirect, url_for, session, flash
import os
import shutil
import requests
from pymongo import MongoClient
from functools import wraps
import bcrypt
from bson.objectid import ObjectId
@app.route('/', methods=['GET'])
@authenticated
def index():
return render_template('app.html')
@app.route('/portal')
def portal():
if not session.get('username'):
return render_template('portal.html')
else:
return redirect(url_for('index'))
@app.route('/logout')
def logout():
session.pop('username', None)
session.pop('role', None)
session.pop('realname', None)
return redirect(url_for('index'))
@app.route('/download/<id>/<format>')
@authenticated
def download(id, format):
book = mongo.Books.find({'id':id})[0]
response = send_from_directory(app.config['LIB_DIR'], id+'.'+format)
response.headers.add('Content-Disposition', 'attachment; filename="' + book['title'] + '.' + format + '"')
return response
@app.route('/upload')
@authenticated
@administrator
def upload():
return render_template('upload.html')
if __name__ == "__main__":
app.run()
|
// ... existing code ...
else:
return redirect(url_for('index'))
@app.route('/logout')
// ... rest of the code ...
|
1ceae27eddb5fd399e58930974638cb1bd367955
|
mcrouter/lib/StatsReply.h
|
mcrouter/lib/StatsReply.h
|
/*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#pragma once
#include <string>
#include <vector>
#include <folly/Conv.h>
namespace facebook { namespace memcache {
class McReply;
namespace cpp2 {
class McStatsReply;
}
template <class ThriftType>
class TypedThriftReply;
class StatsReply {
public:
template <typename V>
void addStat(folly::StringPiece name, V value) {
stats_.push_back(make_pair(name.str(), folly::to<std::string>(value)));
}
McReply getMcReply();
TypedThriftReply<cpp2::McStatsReply> getReply();
private:
std::vector<std::pair<std::string, std::string>> stats_;
};
}} // facebook::memcache
|
/*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#pragma once
#include <string>
#include <vector>
#include <folly/Conv.h>
namespace facebook { namespace memcache {
class McReply;
namespace cpp2 {
class McStatsReply;
}
template <class ThriftType>
class TypedThriftReply;
class StatsReply {
public:
template <typename V>
void addStat(folly::StringPiece name, V&& value) {
stats_.emplace_back(name.str(),
folly::to<std::string>(std::forward<V>(value)));
}
McReply getMcReply();
TypedThriftReply<cpp2::McStatsReply> getReply();
private:
std::vector<std::pair<std::string, std::string>> stats_;
};
}} // facebook::memcache
|
Fix printf format, remove unused variables
|
Fix printf format, remove unused variables
Summary: title
Differential Revision: D3188505
fb-gh-sync-id: 7f544319c247b8607e058d2ae0c02c272e3c5fe1
fbshipit-source-id: 7f544319c247b8607e058d2ae0c02c272e3c5fe1
|
C
|
mit
|
yqzhang/mcrouter,facebook/mcrouter,facebook/mcrouter,yqzhang/mcrouter,yqzhang/mcrouter,facebook/mcrouter,yqzhang/mcrouter,facebook/mcrouter
|
c
|
## Code Before:
/*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#pragma once
#include <string>
#include <vector>
#include <folly/Conv.h>
namespace facebook { namespace memcache {
class McReply;
namespace cpp2 {
class McStatsReply;
}
template <class ThriftType>
class TypedThriftReply;
class StatsReply {
public:
template <typename V>
void addStat(folly::StringPiece name, V value) {
stats_.push_back(make_pair(name.str(), folly::to<std::string>(value)));
}
McReply getMcReply();
TypedThriftReply<cpp2::McStatsReply> getReply();
private:
std::vector<std::pair<std::string, std::string>> stats_;
};
}} // facebook::memcache
## Instruction:
Fix printf format, remove unused variables
Summary: title
Differential Revision: D3188505
fb-gh-sync-id: 7f544319c247b8607e058d2ae0c02c272e3c5fe1
fbshipit-source-id: 7f544319c247b8607e058d2ae0c02c272e3c5fe1
## Code After:
/*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#pragma once
#include <string>
#include <vector>
#include <folly/Conv.h>
namespace facebook { namespace memcache {
class McReply;
namespace cpp2 {
class McStatsReply;
}
template <class ThriftType>
class TypedThriftReply;
class StatsReply {
public:
template <typename V>
void addStat(folly::StringPiece name, V&& value) {
stats_.emplace_back(name.str(),
folly::to<std::string>(std::forward<V>(value)));
}
McReply getMcReply();
TypedThriftReply<cpp2::McStatsReply> getReply();
private:
std::vector<std::pair<std::string, std::string>> stats_;
};
}} // facebook::memcache
|
# ... existing code ...
class StatsReply {
public:
template <typename V>
void addStat(folly::StringPiece name, V&& value) {
stats_.emplace_back(name.str(),
folly::to<std::string>(std::forward<V>(value)));
}
McReply getMcReply();
# ... rest of the code ...
|
9bcc53dba29ec430925dc6cd9676ad46ddf72461
|
FunctionDeclaration.h
|
FunctionDeclaration.h
|
namespace liquid {
class FunctionDeclaration : public Statement
{
friend class ClassDeclaration;
Identifier* type;
Identifier* id;
VariableList* arguments;
Block* block;
YYLTYPE location;
public:
FunctionDeclaration( Identifier* type, Identifier* id, VariableList* arguments, Block* block, YYLTYPE loc )
: type( type ), id( id ), arguments( arguments ), block( block ), location( loc )
{}
FunctionDeclaration( Identifier* id, VariableList* arguments, Block* block, YYLTYPE loc )
: type( new Identifier( "var", location ) ), id( id ), arguments( arguments ), block( block ), location( loc )
{}
virtual ~FunctionDeclaration();
virtual llvm::Value* codeGen( CodeGenContext& context );
NodeType getType() { return NodeType::function; }
Identifier* getId() { return id; }
virtual std::string toString();
virtual void Accept( Visitor& v ) { v.VisitFunctionDeclaration( this ); }
virtual VariableList* getParameter() { return arguments; }
virtual Block* getBody() { return block; }
virtual Identifier* getRetType() { return type; }
YYLTYPE getlocation() { return location; }
};
}
#endif // FUNCTION_DECLARATION_H
|
namespace liquid {
class FunctionDeclaration : public Statement
{
friend class ClassDeclaration;
Identifier* type;
Identifier* id;
VariableList* arguments;
Block* block;
YYLTYPE location;
public:
FunctionDeclaration( Identifier* type, Identifier* id, VariableList* arguments, Block* block, YYLTYPE loc )
: type( type ), id( id ), arguments( arguments ), block( block ), location( loc )
{}
FunctionDeclaration( Identifier* id, VariableList* arguments, Block* block, YYLTYPE loc )
: type(new Identifier("var", loc)), id(id), arguments(arguments), block(block), location(loc)
{}
virtual ~FunctionDeclaration();
virtual llvm::Value* codeGen( CodeGenContext& context );
NodeType getType() { return NodeType::function; }
Identifier* getId() { return id; }
virtual std::string toString();
virtual void Accept( Visitor& v ) { v.VisitFunctionDeclaration( this ); }
virtual VariableList* getParameter() { return arguments; }
virtual Block* getBody() { return block; }
virtual Identifier* getRetType() { return type; }
YYLTYPE getlocation() { return location; }
};
}
#endif // FUNCTION_DECLARATION_H
|
Fix crash wrong order of member initialization.
|
Fix crash wrong order of member initialization.
|
C
|
mit
|
xkbeyer/liquid,xkbeyer/liquid
|
c
|
## Code Before:
namespace liquid {
class FunctionDeclaration : public Statement
{
friend class ClassDeclaration;
Identifier* type;
Identifier* id;
VariableList* arguments;
Block* block;
YYLTYPE location;
public:
FunctionDeclaration( Identifier* type, Identifier* id, VariableList* arguments, Block* block, YYLTYPE loc )
: type( type ), id( id ), arguments( arguments ), block( block ), location( loc )
{}
FunctionDeclaration( Identifier* id, VariableList* arguments, Block* block, YYLTYPE loc )
: type( new Identifier( "var", location ) ), id( id ), arguments( arguments ), block( block ), location( loc )
{}
virtual ~FunctionDeclaration();
virtual llvm::Value* codeGen( CodeGenContext& context );
NodeType getType() { return NodeType::function; }
Identifier* getId() { return id; }
virtual std::string toString();
virtual void Accept( Visitor& v ) { v.VisitFunctionDeclaration( this ); }
virtual VariableList* getParameter() { return arguments; }
virtual Block* getBody() { return block; }
virtual Identifier* getRetType() { return type; }
YYLTYPE getlocation() { return location; }
};
}
#endif // FUNCTION_DECLARATION_H
## Instruction:
Fix crash wrong order of member initialization.
## Code After:
namespace liquid {
class FunctionDeclaration : public Statement
{
friend class ClassDeclaration;
Identifier* type;
Identifier* id;
VariableList* arguments;
Block* block;
YYLTYPE location;
public:
FunctionDeclaration( Identifier* type, Identifier* id, VariableList* arguments, Block* block, YYLTYPE loc )
: type( type ), id( id ), arguments( arguments ), block( block ), location( loc )
{}
FunctionDeclaration( Identifier* id, VariableList* arguments, Block* block, YYLTYPE loc )
: type(new Identifier("var", loc)), id(id), arguments(arguments), block(block), location(loc)
{}
virtual ~FunctionDeclaration();
virtual llvm::Value* codeGen( CodeGenContext& context );
NodeType getType() { return NodeType::function; }
Identifier* getId() { return id; }
virtual std::string toString();
virtual void Accept( Visitor& v ) { v.VisitFunctionDeclaration( this ); }
virtual VariableList* getParameter() { return arguments; }
virtual Block* getBody() { return block; }
virtual Identifier* getRetType() { return type; }
YYLTYPE getlocation() { return location; }
};
}
#endif // FUNCTION_DECLARATION_H
|
...
: type( type ), id( id ), arguments( arguments ), block( block ), location( loc )
{}
FunctionDeclaration( Identifier* id, VariableList* arguments, Block* block, YYLTYPE loc )
: type(new Identifier("var", loc)), id(id), arguments(arguments), block(block), location(loc)
{}
virtual ~FunctionDeclaration();
virtual llvm::Value* codeGen( CodeGenContext& context );
...
|
5a0e780e4d47efebed691fe389ff01a7ee0ff1cb
|
setup.py
|
setup.py
|
from setuptools import setup
def get_version():
import re
with open('lastpass/__init__.py', 'r') as f:
for line in f:
m = re.match(r'__version__ = [\'"]([^\'"]*)[\'"]', line)
if m:
return m.group(1)
return ''
setup(
name='lastpass-python',
version=get_version(),
description='LastPass Python API (unofficial)',
long_description=open('README.rst').read(),
license='MIT',
author='konomae',
author_email='[email protected]',
url='https://github.com/konomae/lastpass-python',
packages=['lastpass'],
install_requires=[
"requests>=1.2.1,<=3.0.0",
"pycrypto>=2.6.1",
],
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation :: CPython',
],
)
|
from setuptools import setup
def get_version():
import re
with open('lastpass/__init__.py', 'r') as f:
for line in f:
m = re.match(r'__version__ = [\'"]([^\'"]*)[\'"]', line)
if m:
return m.group(1)
raise RuntimeError('Cannot find version information')
setup(
name='lastpass-python',
version=get_version(),
description='LastPass Python API (unofficial)',
long_description=open('README.rst').read(),
license='MIT',
author='konomae',
author_email='[email protected]',
url='https://github.com/konomae/lastpass-python',
packages=['lastpass'],
install_requires=[
"requests>=1.2.1,<=3.0.0",
"pycrypto>=2.6.1",
],
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation :: CPython',
],
)
|
Raise RuntimeError if __version__ is not found
|
Raise RuntimeError if __version__ is not found
|
Python
|
mit
|
dhercher/lastpass-python,konomae/lastpass-python
|
python
|
## Code Before:
from setuptools import setup
def get_version():
import re
with open('lastpass/__init__.py', 'r') as f:
for line in f:
m = re.match(r'__version__ = [\'"]([^\'"]*)[\'"]', line)
if m:
return m.group(1)
return ''
setup(
name='lastpass-python',
version=get_version(),
description='LastPass Python API (unofficial)',
long_description=open('README.rst').read(),
license='MIT',
author='konomae',
author_email='[email protected]',
url='https://github.com/konomae/lastpass-python',
packages=['lastpass'],
install_requires=[
"requests>=1.2.1,<=3.0.0",
"pycrypto>=2.6.1",
],
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation :: CPython',
],
)
## Instruction:
Raise RuntimeError if __version__ is not found
## Code After:
from setuptools import setup
def get_version():
import re
with open('lastpass/__init__.py', 'r') as f:
for line in f:
m = re.match(r'__version__ = [\'"]([^\'"]*)[\'"]', line)
if m:
return m.group(1)
raise RuntimeError('Cannot find version information')
setup(
name='lastpass-python',
version=get_version(),
description='LastPass Python API (unofficial)',
long_description=open('README.rst').read(),
license='MIT',
author='konomae',
author_email='[email protected]',
url='https://github.com/konomae/lastpass-python',
packages=['lastpass'],
install_requires=[
"requests>=1.2.1,<=3.0.0",
"pycrypto>=2.6.1",
],
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation :: CPython',
],
)
|
# ... existing code ...
m = re.match(r'__version__ = [\'"]([^\'"]*)[\'"]', line)
if m:
return m.group(1)
raise RuntimeError('Cannot find version information')
setup(
# ... rest of the code ...
|
023302715cb21971dbb51c0ac18fa80acbb33717
|
dddsample/src/main/java/se/citerus/dddsample/domain/TrackingId.java
|
dddsample/src/main/java/se/citerus/dddsample/domain/TrackingId.java
|
package se.citerus.dddsample.domain;
import org.apache.commons.lang.Validate;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* Identifies a particular cargo.
* <p/>
* Make sure to put a constraint in the database to make sure TrackingId is unique.
*/
public final class TrackingId {
private String id;
/**
* Constructor.
*
* @param id Id string.
*/
public TrackingId(final String id) {
Validate.notNull(id);
this.id = id;
}
/**
* @return String representation of this tracking id.
*/
public String idString() {
return id;
}
@Override
public boolean equals(final Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
TrackingId() {
// Needed by Hibernate
}
}
|
package se.citerus.dddsample.domain;
import org.apache.commons.lang.Validate;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* Uniquely identifies a particular cargo. Automatically generated by the application.
*
*/
public final class TrackingId implements ValueObject<TrackingId> {
private String id;
/**
* Constructor.
*
* @param id Id string.
*/
public TrackingId(final String id) {
Validate.notNull(id);
this.id = id;
}
/**
* @return String representation of this tracking id.
*/
public String idString() {
return id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TrackingId other = (TrackingId) o;
return sameValueAs(other);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
public boolean sameValueAs(TrackingId other) {
return other != null && EqualsBuilder.reflectionEquals(this, other);
}
TrackingId() {
// Needed by Hibernate
}
}
|
Implement ValueObject.sameValueAs(), and use that as delegate in equals()
|
Implement ValueObject.sameValueAs(), and use that as delegate in equals()
|
Java
|
mit
|
stefan-ka/dddsample-core,romank0/dddsample-core,loothingpogixxv/dddsample-core,gacalves/dddsample-core,citerus/dddsample-core,orende/dddsample-core,IzzyXie2010/dddsample-core,citerus/dddsample-core,gacalves/dddsample-core,IzzyXie2010/dddsample-core,romank0/dddsample-core,loothingpogixxv/dddsample-core,orende/dddsample-core,stefan-ka/dddsample-core
|
java
|
## Code Before:
package se.citerus.dddsample.domain;
import org.apache.commons.lang.Validate;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* Identifies a particular cargo.
* <p/>
* Make sure to put a constraint in the database to make sure TrackingId is unique.
*/
public final class TrackingId {
private String id;
/**
* Constructor.
*
* @param id Id string.
*/
public TrackingId(final String id) {
Validate.notNull(id);
this.id = id;
}
/**
* @return String representation of this tracking id.
*/
public String idString() {
return id;
}
@Override
public boolean equals(final Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
TrackingId() {
// Needed by Hibernate
}
}
## Instruction:
Implement ValueObject.sameValueAs(), and use that as delegate in equals()
## Code After:
package se.citerus.dddsample.domain;
import org.apache.commons.lang.Validate;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* Uniquely identifies a particular cargo. Automatically generated by the application.
*
*/
public final class TrackingId implements ValueObject<TrackingId> {
private String id;
/**
* Constructor.
*
* @param id Id string.
*/
public TrackingId(final String id) {
Validate.notNull(id);
this.id = id;
}
/**
* @return String representation of this tracking id.
*/
public String idString() {
return id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TrackingId other = (TrackingId) o;
return sameValueAs(other);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
public boolean sameValueAs(TrackingId other) {
return other != null && EqualsBuilder.reflectionEquals(this, other);
}
TrackingId() {
// Needed by Hibernate
}
}
|
...
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* Uniquely identifies a particular cargo. Automatically generated by the application.
*
*/
public final class TrackingId implements ValueObject<TrackingId> {
private String id;
...
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TrackingId other = (TrackingId) o;
return sameValueAs(other);
}
@Override
...
return HashCodeBuilder.reflectionHashCode(this);
}
public boolean sameValueAs(TrackingId other) {
return other != null && EqualsBuilder.reflectionEquals(this, other);
}
TrackingId() {
// Needed by Hibernate
}
}
...
|
b4c9b76d132668695b77d37d7db3071e629fcba7
|
makerscience_admin/models.py
|
makerscience_admin/models.py
|
from django.db import models
from solo.models import SingletonModel
class MakerScienceStaticContent (SingletonModel):
about = models.TextField(null=True, blank=True)
about_team = models.TextField(null=True, blank=True)
about_contact = models.TextField(null=True, blank=True)
about_faq = models.TextField(null=True, blank=True)
about_cgu = models.TextField(null=True, blank=True)
class PageViews(models.Model):
client = models.CharField(max_length=255)
resource_uri = models.CharField(max_length=255)
|
from django.db import models
from django.db.models.signals import post_delete
from solo.models import SingletonModel
from accounts.models import ObjectProfileLink
from makerscience_forum.models import MakerSciencePost
class MakerScienceStaticContent (SingletonModel):
about = models.TextField(null=True, blank=True)
about_team = models.TextField(null=True, blank=True)
about_contact = models.TextField(null=True, blank=True)
about_faq = models.TextField(null=True, blank=True)
about_cgu = models.TextField(null=True, blank=True)
class PageViews(models.Model):
client = models.CharField(max_length=255)
resource_uri = models.CharField(max_length=255)
def clear_makerscience(sender, instance, **kwargs):
if sender == MakerSciencePost:
ObjectProfileLink.objects.filter(content_type__model='post',
object_id=instance.parent.id).delete()
instance.parent.delete()
post_delete.connect(clear_makerscience, sender=MakerSciencePost)
|
Allow to clear useless instances
|
Allow to clear useless instances
|
Python
|
agpl-3.0
|
atiberghien/makerscience-server,atiberghien/makerscience-server
|
python
|
## Code Before:
from django.db import models
from solo.models import SingletonModel
class MakerScienceStaticContent (SingletonModel):
about = models.TextField(null=True, blank=True)
about_team = models.TextField(null=True, blank=True)
about_contact = models.TextField(null=True, blank=True)
about_faq = models.TextField(null=True, blank=True)
about_cgu = models.TextField(null=True, blank=True)
class PageViews(models.Model):
client = models.CharField(max_length=255)
resource_uri = models.CharField(max_length=255)
## Instruction:
Allow to clear useless instances
## Code After:
from django.db import models
from django.db.models.signals import post_delete
from solo.models import SingletonModel
from accounts.models import ObjectProfileLink
from makerscience_forum.models import MakerSciencePost
class MakerScienceStaticContent (SingletonModel):
about = models.TextField(null=True, blank=True)
about_team = models.TextField(null=True, blank=True)
about_contact = models.TextField(null=True, blank=True)
about_faq = models.TextField(null=True, blank=True)
about_cgu = models.TextField(null=True, blank=True)
class PageViews(models.Model):
client = models.CharField(max_length=255)
resource_uri = models.CharField(max_length=255)
def clear_makerscience(sender, instance, **kwargs):
if sender == MakerSciencePost:
ObjectProfileLink.objects.filter(content_type__model='post',
object_id=instance.parent.id).delete()
instance.parent.delete()
post_delete.connect(clear_makerscience, sender=MakerSciencePost)
|
// ... existing code ...
from django.db import models
from django.db.models.signals import post_delete
from solo.models import SingletonModel
from accounts.models import ObjectProfileLink
from makerscience_forum.models import MakerSciencePost
class MakerScienceStaticContent (SingletonModel):
about = models.TextField(null=True, blank=True)
// ... modified code ...
class PageViews(models.Model):
client = models.CharField(max_length=255)
resource_uri = models.CharField(max_length=255)
def clear_makerscience(sender, instance, **kwargs):
if sender == MakerSciencePost:
ObjectProfileLink.objects.filter(content_type__model='post',
object_id=instance.parent.id).delete()
instance.parent.delete()
post_delete.connect(clear_makerscience, sender=MakerSciencePost)
// ... rest of the code ...
|
b81e65b9c6579e02684f0b313060b17d7ba669ef
|
src/include/xmmsclient/xmmsclient++/detail/superlist.h
|
src/include/xmmsclient/xmmsclient++/detail/superlist.h
|
namespace Xmms
{
namespace Detail
{
class SuperList
{
public:
SuperList( xmmsc_result_t* result );
SuperList( const SuperList& list );
virtual SuperList& operator=( const SuperList& list );
virtual ~SuperList();
virtual void first();
virtual void operator++();
virtual bool isValid() const;
protected:
xmmsc_result_t* result_;
bool constructed_;
virtual void constructContents() = 0;
};
void dict_foreach( const void* key,
xmmsc_result_value_type_t type,
const void* value,
void* udata );
void propdict_foreach( const void* key,
xmmsc_result_value_type_t type,
const void* value,
const char* source,
void* udata );
}
}
#endif // XMMSCLIENTPP_SUPERLIST_H
|
namespace Xmms
{
namespace Detail
{
class SuperList
{
public:
SuperList( xmmsc_result_t* result );
SuperList( const SuperList& list );
virtual SuperList& operator=( const SuperList& list );
virtual ~SuperList();
virtual void first();
virtual void operator++();
virtual bool isValid() const;
protected:
xmmsc_result_t* result_;
bool constructed_;
virtual void constructContents() = 0;
};
}
}
#endif // XMMSCLIENTPP_SUPERLIST_H
|
Remove obsolete *_foreach function completely (Function declarations were still there).
|
OTHER: Remove obsolete *_foreach function completely (Function declarations were still there).
|
C
|
lgpl-2.1
|
oneman/xmms2-oneman,theefer/xmms2,krad-radio/xmms2-krad,krad-radio/xmms2-krad,oneman/xmms2-oneman-old,oneman/xmms2-oneman,krad-radio/xmms2-krad,mantaraya36/xmms2-mantaraya36,mantaraya36/xmms2-mantaraya36,chrippa/xmms2,dreamerc/xmms2,oneman/xmms2-oneman,six600110/xmms2,oneman/xmms2-oneman,xmms2/xmms2-stable,chrippa/xmms2,xmms2/xmms2-stable,theefer/xmms2,theefer/xmms2,dreamerc/xmms2,theeternalsw0rd/xmms2,theefer/xmms2,krad-radio/xmms2-krad,krad-radio/xmms2-krad,xmms2/xmms2-stable,chrippa/xmms2,theeternalsw0rd/xmms2,dreamerc/xmms2,xmms2/xmms2-stable,theefer/xmms2,theeternalsw0rd/xmms2,dreamerc/xmms2,dreamerc/xmms2,six600110/xmms2,xmms2/xmms2-stable,mantaraya36/xmms2-mantaraya36,six600110/xmms2,mantaraya36/xmms2-mantaraya36,oneman/xmms2-oneman,theeternalsw0rd/xmms2,oneman/xmms2-oneman-old,theeternalsw0rd/xmms2,xmms2/xmms2-stable,oneman/xmms2-oneman,chrippa/xmms2,mantaraya36/xmms2-mantaraya36,chrippa/xmms2,oneman/xmms2-oneman,six600110/xmms2,mantaraya36/xmms2-mantaraya36,theefer/xmms2,oneman/xmms2-oneman-old,chrippa/xmms2,oneman/xmms2-oneman-old,six600110/xmms2,krad-radio/xmms2-krad,oneman/xmms2-oneman-old,six600110/xmms2,mantaraya36/xmms2-mantaraya36,theeternalsw0rd/xmms2,theefer/xmms2
|
c
|
## Code Before:
namespace Xmms
{
namespace Detail
{
class SuperList
{
public:
SuperList( xmmsc_result_t* result );
SuperList( const SuperList& list );
virtual SuperList& operator=( const SuperList& list );
virtual ~SuperList();
virtual void first();
virtual void operator++();
virtual bool isValid() const;
protected:
xmmsc_result_t* result_;
bool constructed_;
virtual void constructContents() = 0;
};
void dict_foreach( const void* key,
xmmsc_result_value_type_t type,
const void* value,
void* udata );
void propdict_foreach( const void* key,
xmmsc_result_value_type_t type,
const void* value,
const char* source,
void* udata );
}
}
#endif // XMMSCLIENTPP_SUPERLIST_H
## Instruction:
OTHER: Remove obsolete *_foreach function completely (Function declarations were still there).
## Code After:
namespace Xmms
{
namespace Detail
{
class SuperList
{
public:
SuperList( xmmsc_result_t* result );
SuperList( const SuperList& list );
virtual SuperList& operator=( const SuperList& list );
virtual ~SuperList();
virtual void first();
virtual void operator++();
virtual bool isValid() const;
protected:
xmmsc_result_t* result_;
bool constructed_;
virtual void constructContents() = 0;
};
}
}
#endif // XMMSCLIENTPP_SUPERLIST_H
|
// ... existing code ...
};
}
}
// ... rest of the code ...
|
9540d909d0af9586b83b8bc504760e1f8b7768bb
|
vscode-extensions/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/java/DefaultJavaProjectFinder.java
|
vscode-extensions/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/java/DefaultJavaProjectFinder.java
|
package org.springframework.ide.vscode.commons.languageserver.java;
import org.springframework.ide.vscode.commons.java.IJavaProject;
import org.springframework.ide.vscode.commons.languageserver.util.IDocument;
public class DefaultJavaProjectFinder implements JavaProjectFinder {
private final IJavaProjectFinderStrategy[] STRATEGIES = new IJavaProjectFinderStrategy[] {
new JavaProjectWithClasspathFileFinderStrategy(),
new MavenProjectFinderStrategy()
};
@Override
public IJavaProject find(IDocument d) {
for (IJavaProjectFinderStrategy strategy : STRATEGIES) {
try {
return strategy.find(d);
} catch (Throwable t) {
// Log perhaps?
}
}
return null;
}
}
|
package org.springframework.ide.vscode.commons.languageserver.java;
import org.springframework.ide.vscode.commons.java.IJavaProject;
import org.springframework.ide.vscode.commons.languageserver.util.IDocument;
public class DefaultJavaProjectFinder implements JavaProjectFinder {
private final IJavaProjectFinderStrategy[] STRATEGIES = new IJavaProjectFinderStrategy[] {
new JavaProjectWithClasspathFileFinderStrategy(),
new MavenProjectFinderStrategy()
};
@Override
public IJavaProject find(IDocument d) {
for (IJavaProjectFinderStrategy strategy : STRATEGIES) {
try {
IJavaProject project = strategy.find(d);
if (project != null) {
return project;
}
} catch (Throwable t) {
// Log perhaps?
}
}
return null;
}
}
|
Handle null found project for default java project finder
|
Handle null found project for default java project finder
|
Java
|
epl-1.0
|
spring-projects/sts4,spring-projects/sts4,spring-projects/sts4,spring-projects/sts4,spring-projects/sts4,spring-projects/sts4
|
java
|
## Code Before:
package org.springframework.ide.vscode.commons.languageserver.java;
import org.springframework.ide.vscode.commons.java.IJavaProject;
import org.springframework.ide.vscode.commons.languageserver.util.IDocument;
public class DefaultJavaProjectFinder implements JavaProjectFinder {
private final IJavaProjectFinderStrategy[] STRATEGIES = new IJavaProjectFinderStrategy[] {
new JavaProjectWithClasspathFileFinderStrategy(),
new MavenProjectFinderStrategy()
};
@Override
public IJavaProject find(IDocument d) {
for (IJavaProjectFinderStrategy strategy : STRATEGIES) {
try {
return strategy.find(d);
} catch (Throwable t) {
// Log perhaps?
}
}
return null;
}
}
## Instruction:
Handle null found project for default java project finder
## Code After:
package org.springframework.ide.vscode.commons.languageserver.java;
import org.springframework.ide.vscode.commons.java.IJavaProject;
import org.springframework.ide.vscode.commons.languageserver.util.IDocument;
public class DefaultJavaProjectFinder implements JavaProjectFinder {
private final IJavaProjectFinderStrategy[] STRATEGIES = new IJavaProjectFinderStrategy[] {
new JavaProjectWithClasspathFileFinderStrategy(),
new MavenProjectFinderStrategy()
};
@Override
public IJavaProject find(IDocument d) {
for (IJavaProjectFinderStrategy strategy : STRATEGIES) {
try {
IJavaProject project = strategy.find(d);
if (project != null) {
return project;
}
} catch (Throwable t) {
// Log perhaps?
}
}
return null;
}
}
|
# ... existing code ...
public IJavaProject find(IDocument d) {
for (IJavaProjectFinderStrategy strategy : STRATEGIES) {
try {
IJavaProject project = strategy.find(d);
if (project != null) {
return project;
}
} catch (Throwable t) {
// Log perhaps?
}
# ... rest of the code ...
|
da9930326bb54aeb56dbe91355246b8dd1ec066b
|
src/main/java/com/crowdin/cli/utils/file/FileReader.java
|
src/main/java/com/crowdin/cli/utils/file/FileReader.java
|
package com.crowdin.cli.utils.file;
import com.crowdin.cli.utils.MessageSource;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Map;
import java.util.ResourceBundle;
public class FileReader {
private static final ResourceBundle RESOURCE_BUNDLE = MessageSource.RESOURCE_BUNDLE;
private static final String DEFAULT_CONFIG_FILE_NAME = "crowdin.yml";
private static final String YAML_EXTENSION = ".yaml";
private static final String YML_EXTENSION = ".yml";
public Map<String, Object> readCliConfig(File fileCfg) {
if (fileCfg == null) {
throw new NullPointerException("FileReader.readCliConfig has null args");
}
if (!(fileCfg.getName().endsWith(YAML_EXTENSION) || fileCfg.getName().endsWith(YML_EXTENSION))) {
System.out.println("WARN: file with name '" + fileCfg.getAbsolutePath() + "' has different type from YAML");
}
Yaml yaml = new Yaml();
InputStream inputStream = null;
try {
inputStream = new FileInputStream(fileCfg);
} catch (FileNotFoundException e) {
throw new RuntimeException(RESOURCE_BUNDLE.getString("error.configuration_file_not_exist"));
}
Map<String, Object> result = null;
try {
result = (Map<String, Object>) yaml.load(inputStream);
} catch (Exception e) {
throw new RuntimeException(RESOURCE_BUNDLE.getString("error.reading_configuration_file"), e);
}
return result;
}
}
|
package com.crowdin.cli.utils.file;
import com.crowdin.cli.utils.MessageSource;
import org.yaml.snakeyaml.Yaml;
import java.io.*;
import java.util.Map;
import java.util.ResourceBundle;
public class FileReader {
private static final ResourceBundle RESOURCE_BUNDLE = MessageSource.RESOURCE_BUNDLE;
private static final String DEFAULT_CONFIG_FILE_NAME = "crowdin.yml";
private static final String YAML_EXTENSION = ".yaml";
private static final String YML_EXTENSION = ".yml";
public Map<String, Object> readCliConfig(File fileCfg) {
if (fileCfg == null) {
throw new NullPointerException("FileReader.readCliConfig has null args");
}
if (!(fileCfg.getName().endsWith(YAML_EXTENSION) || fileCfg.getName().endsWith(YML_EXTENSION))) {
System.out.println("WARN: file with name '" + fileCfg.getAbsolutePath() + "' has different type from YAML");
}
Yaml yaml = new Yaml();
try (InputStream inputStream = new FileInputStream(fileCfg)){
return (Map<String, Object>) yaml.load(inputStream);
} catch (FileNotFoundException e) {
throw new RuntimeException(RESOURCE_BUNDLE.getString("error.configuration_file_not_exist"));
} catch (Exception e) {
throw new RuntimeException(RESOURCE_BUNDLE.getString("error.reading_configuration_file"), e);
}
}
}
|
Fix old bug - close stream after reading
|
Fix old bug - close stream after reading
|
Java
|
mit
|
crowdin/crowdin-cli,crowdin/crowdin-cli
|
java
|
## Code Before:
package com.crowdin.cli.utils.file;
import com.crowdin.cli.utils.MessageSource;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Map;
import java.util.ResourceBundle;
public class FileReader {
private static final ResourceBundle RESOURCE_BUNDLE = MessageSource.RESOURCE_BUNDLE;
private static final String DEFAULT_CONFIG_FILE_NAME = "crowdin.yml";
private static final String YAML_EXTENSION = ".yaml";
private static final String YML_EXTENSION = ".yml";
public Map<String, Object> readCliConfig(File fileCfg) {
if (fileCfg == null) {
throw new NullPointerException("FileReader.readCliConfig has null args");
}
if (!(fileCfg.getName().endsWith(YAML_EXTENSION) || fileCfg.getName().endsWith(YML_EXTENSION))) {
System.out.println("WARN: file with name '" + fileCfg.getAbsolutePath() + "' has different type from YAML");
}
Yaml yaml = new Yaml();
InputStream inputStream = null;
try {
inputStream = new FileInputStream(fileCfg);
} catch (FileNotFoundException e) {
throw new RuntimeException(RESOURCE_BUNDLE.getString("error.configuration_file_not_exist"));
}
Map<String, Object> result = null;
try {
result = (Map<String, Object>) yaml.load(inputStream);
} catch (Exception e) {
throw new RuntimeException(RESOURCE_BUNDLE.getString("error.reading_configuration_file"), e);
}
return result;
}
}
## Instruction:
Fix old bug - close stream after reading
## Code After:
package com.crowdin.cli.utils.file;
import com.crowdin.cli.utils.MessageSource;
import org.yaml.snakeyaml.Yaml;
import java.io.*;
import java.util.Map;
import java.util.ResourceBundle;
public class FileReader {
private static final ResourceBundle RESOURCE_BUNDLE = MessageSource.RESOURCE_BUNDLE;
private static final String DEFAULT_CONFIG_FILE_NAME = "crowdin.yml";
private static final String YAML_EXTENSION = ".yaml";
private static final String YML_EXTENSION = ".yml";
public Map<String, Object> readCliConfig(File fileCfg) {
if (fileCfg == null) {
throw new NullPointerException("FileReader.readCliConfig has null args");
}
if (!(fileCfg.getName().endsWith(YAML_EXTENSION) || fileCfg.getName().endsWith(YML_EXTENSION))) {
System.out.println("WARN: file with name '" + fileCfg.getAbsolutePath() + "' has different type from YAML");
}
Yaml yaml = new Yaml();
try (InputStream inputStream = new FileInputStream(fileCfg)){
return (Map<String, Object>) yaml.load(inputStream);
} catch (FileNotFoundException e) {
throw new RuntimeException(RESOURCE_BUNDLE.getString("error.configuration_file_not_exist"));
} catch (Exception e) {
throw new RuntimeException(RESOURCE_BUNDLE.getString("error.reading_configuration_file"), e);
}
}
}
|
// ... existing code ...
import com.crowdin.cli.utils.MessageSource;
import org.yaml.snakeyaml.Yaml;
import java.io.*;
import java.util.Map;
import java.util.ResourceBundle;
// ... modified code ...
}
Yaml yaml = new Yaml();
try (InputStream inputStream = new FileInputStream(fileCfg)){
return (Map<String, Object>) yaml.load(inputStream);
} catch (FileNotFoundException e) {
throw new RuntimeException(RESOURCE_BUNDLE.getString("error.configuration_file_not_exist"));
} catch (Exception e) {
throw new RuntimeException(RESOURCE_BUNDLE.getString("error.reading_configuration_file"), e);
}
}
}
// ... rest of the code ...
|
130df743b14cf329c09f0c514ec0d6991b21dd45
|
examples/mnist-deepautoencoder.py
|
examples/mnist-deepautoencoder.py
|
import matplotlib.pyplot as plt
import theanets
from utils import load_mnist, plot_layers, plot_images
train, valid, _ = load_mnist()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(784, 256, 64, 36, 64, 256, 784),
train_batches=100,
tied_weights=True,
)
e.train(train, valid, optimize='layerwise')
e.train(train, valid)
plot_layers([e.network.get_weights(i) for i in (1, 2, 3)], tied_weights=True)
plt.tight_layout()
plt.show()
valid = valid[:16*16]
plot_images(valid, 121, 'Sample data')
plot_images(e.network.predict(valid), 122, 'Reconstructed data')
plt.tight_layout()
plt.show()
|
import matplotlib.pyplot as plt
import theanets
from utils import load_mnist, plot_layers, plot_images
train, valid, _ = load_mnist()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(784, 256, 64, 36, 64, 256, 784),
train_batches=100,
tied_weights=True,
)
e.train(train, valid, optimize='layerwise', patience=1, min_improvement=0.1)
e.train(train, valid)
plot_layers([e.network.get_weights(i) for i in (1, 2, 3)], tied_weights=True)
plt.tight_layout()
plt.show()
valid = valid[:16*16]
plot_images(valid, 121, 'Sample data')
plot_images(e.network.predict(valid), 122, 'Reconstructed data')
plt.tight_layout()
plt.show()
|
Decrease patience for each layerwise trainer.
|
Decrease patience for each layerwise trainer.
|
Python
|
mit
|
chrinide/theanets,lmjohns3/theanets,devdoer/theanets
|
python
|
## Code Before:
import matplotlib.pyplot as plt
import theanets
from utils import load_mnist, plot_layers, plot_images
train, valid, _ = load_mnist()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(784, 256, 64, 36, 64, 256, 784),
train_batches=100,
tied_weights=True,
)
e.train(train, valid, optimize='layerwise')
e.train(train, valid)
plot_layers([e.network.get_weights(i) for i in (1, 2, 3)], tied_weights=True)
plt.tight_layout()
plt.show()
valid = valid[:16*16]
plot_images(valid, 121, 'Sample data')
plot_images(e.network.predict(valid), 122, 'Reconstructed data')
plt.tight_layout()
plt.show()
## Instruction:
Decrease patience for each layerwise trainer.
## Code After:
import matplotlib.pyplot as plt
import theanets
from utils import load_mnist, plot_layers, plot_images
train, valid, _ = load_mnist()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(784, 256, 64, 36, 64, 256, 784),
train_batches=100,
tied_weights=True,
)
e.train(train, valid, optimize='layerwise', patience=1, min_improvement=0.1)
e.train(train, valid)
plot_layers([e.network.get_weights(i) for i in (1, 2, 3)], tied_weights=True)
plt.tight_layout()
plt.show()
valid = valid[:16*16]
plot_images(valid, 121, 'Sample data')
plot_images(e.network.predict(valid), 122, 'Reconstructed data')
plt.tight_layout()
plt.show()
|
...
train_batches=100,
tied_weights=True,
)
e.train(train, valid, optimize='layerwise', patience=1, min_improvement=0.1)
e.train(train, valid)
plot_layers([e.network.get_weights(i) for i in (1, 2, 3)], tied_weights=True)
...
|
07823ae7f7368f4bc4a4e4436129319f7215150b
|
faker/utils/distribution.py
|
faker/utils/distribution.py
|
import bisect
from faker.generator import random
def random_sample():
return random.uniform(0.0, 1.0)
def cumsum(it):
total = 0
for x in it:
total += x
yield total
def choice_distribution(a, p):
assert len(a) == len(p)
cdf = list(cumsum(p))
normal = cdf[-1]
cdf2 = [float(i) / float(normal) for i in cdf]
uniform_sample = random_sample()
idx = bisect.bisect_right(cdf2, uniform_sample)
return a[idx]
|
import bisect
from sys import version_info
from faker.generator import random
def random_sample():
return random.uniform(0.0, 1.0)
def cumsum(it):
total = 0
for x in it:
total += x
yield total
def choice_distribution(a, p):
assert len(a) == len(p)
if version_info.major >= 3 and version_info.minor >= 6:
from random import choices
return choices(a, weights=p)[0]
else:
cdf = list(cumsum(p))
normal = cdf[-1]
cdf2 = [float(i) / float(normal) for i in cdf]
uniform_sample = random_sample()
idx = bisect.bisect_right(cdf2, uniform_sample)
return a[idx]
|
Use random.choices when available for better performance
|
Use random.choices when available for better performance
|
Python
|
mit
|
joke2k/faker,joke2k/faker,danhuss/faker
|
python
|
## Code Before:
import bisect
from faker.generator import random
def random_sample():
return random.uniform(0.0, 1.0)
def cumsum(it):
total = 0
for x in it:
total += x
yield total
def choice_distribution(a, p):
assert len(a) == len(p)
cdf = list(cumsum(p))
normal = cdf[-1]
cdf2 = [float(i) / float(normal) for i in cdf]
uniform_sample = random_sample()
idx = bisect.bisect_right(cdf2, uniform_sample)
return a[idx]
## Instruction:
Use random.choices when available for better performance
## Code After:
import bisect
from sys import version_info
from faker.generator import random
def random_sample():
return random.uniform(0.0, 1.0)
def cumsum(it):
total = 0
for x in it:
total += x
yield total
def choice_distribution(a, p):
assert len(a) == len(p)
if version_info.major >= 3 and version_info.minor >= 6:
from random import choices
return choices(a, weights=p)[0]
else:
cdf = list(cumsum(p))
normal = cdf[-1]
cdf2 = [float(i) / float(normal) for i in cdf]
uniform_sample = random_sample()
idx = bisect.bisect_right(cdf2, uniform_sample)
return a[idx]
|
// ... existing code ...
import bisect
from sys import version_info
from faker.generator import random
def random_sample():
// ... modified code ...
def choice_distribution(a, p):
assert len(a) == len(p)
if version_info.major >= 3 and version_info.minor >= 6:
from random import choices
return choices(a, weights=p)[0]
else:
cdf = list(cumsum(p))
normal = cdf[-1]
cdf2 = [float(i) / float(normal) for i in cdf]
uniform_sample = random_sample()
idx = bisect.bisect_right(cdf2, uniform_sample)
return a[idx]
// ... rest of the code ...
|
0bb36aebdf0766c9244c6e317df89ddda86361b0
|
polls/admin.py
|
polls/admin.py
|
from __future__ import unicode_literals
from django.contrib import admin
from .models import Question, Choice, Answer
class ChoiceInline(admin.TabularInline):
model = Choice
class QuestionAdmin(admin.ModelAdmin):
inlines = [
ChoiceInline,
]
admin.site.register(Question, QuestionAdmin)
admin.site.register(Answer)
|
from __future__ import unicode_literals
from django.contrib import admin
from .models import Question, Choice, Answer
class ChoiceInline(admin.TabularInline):
model = Choice
def copy_question(modeladmin, request, queryset):
for orig in queryset:
q = Question(question_text="Kopie van "+orig.question_text)
q.save()
for orig_choice in orig.choice_set.all():
c = Choice(question=q, choice_text=orig_choice.choice_text)
c.save()
copy_question.short_description = "Kopieer stemmingen"
class QuestionAdmin(admin.ModelAdmin):
inlines = [
ChoiceInline,
]
actions = [copy_question]
admin.site.register(Question, QuestionAdmin)
admin.site.register(Answer)
|
Allow Questions to be copied
|
Allow Questions to be copied
|
Python
|
apache-2.0
|
gerard-/votingapp,gerard-/votingapp
|
python
|
## Code Before:
from __future__ import unicode_literals
from django.contrib import admin
from .models import Question, Choice, Answer
class ChoiceInline(admin.TabularInline):
model = Choice
class QuestionAdmin(admin.ModelAdmin):
inlines = [
ChoiceInline,
]
admin.site.register(Question, QuestionAdmin)
admin.site.register(Answer)
## Instruction:
Allow Questions to be copied
## Code After:
from __future__ import unicode_literals
from django.contrib import admin
from .models import Question, Choice, Answer
class ChoiceInline(admin.TabularInline):
model = Choice
def copy_question(modeladmin, request, queryset):
for orig in queryset:
q = Question(question_text="Kopie van "+orig.question_text)
q.save()
for orig_choice in orig.choice_set.all():
c = Choice(question=q, choice_text=orig_choice.choice_text)
c.save()
copy_question.short_description = "Kopieer stemmingen"
class QuestionAdmin(admin.ModelAdmin):
inlines = [
ChoiceInline,
]
actions = [copy_question]
admin.site.register(Question, QuestionAdmin)
admin.site.register(Answer)
|
// ... existing code ...
class ChoiceInline(admin.TabularInline):
model = Choice
def copy_question(modeladmin, request, queryset):
for orig in queryset:
q = Question(question_text="Kopie van "+orig.question_text)
q.save()
for orig_choice in orig.choice_set.all():
c = Choice(question=q, choice_text=orig_choice.choice_text)
c.save()
copy_question.short_description = "Kopieer stemmingen"
class QuestionAdmin(admin.ModelAdmin):
inlines = [
ChoiceInline,
]
actions = [copy_question]
admin.site.register(Question, QuestionAdmin)
admin.site.register(Answer)
// ... rest of the code ...
|
ca9b79aee8269803e8cd74d3cf31aa97cc5191e0
|
iReactionTest/Database/DatabaseConnectorTest.java
|
iReactionTest/Database/DatabaseConnectorTest.java
|
package Database;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class DatabaseConnectorTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testConnect() throws Exception {
}
@Test
public void testDisconnect() throws Exception {
}
}
|
package Database;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.sql.Connection;
import static org.junit.Assert.*;
public class DatabaseConnectorTest {
DatabaseConnector databaseConnector;
@Before
public void setUp() throws Exception {
databaseConnector = new DatabaseConnector(Config.URL.toString(), Config.USERNAME.toString(), Config.PASSWORD.toString(), Config.DATABASE.toString());
}
@After
public void tearDown() throws Exception {
}
@Test
public void testConnect() throws Exception {
Connection connection = null;
try {
connection = databaseConnector.connect();
assertNotNull(connection);
} catch (Exception e) {
assertTrue(e.toString().contains("SQLException"));
assertNull(connection);
}
}
@Test
public void testDisconnect() throws Exception {
Connection connection = null;
try {
databaseConnector.connect();
assertTrue(databaseConnector.isActive());
databaseConnector.disconnect();
assertFalse(databaseConnector.isActive());
} catch (Exception e) {
assertTrue(e.toString().contains("SQLException"));
assertNull(connection);
}
}
}
|
Add Tests to DatabaseConnectionTest class
|
Add Tests to DatabaseConnectionTest class
|
Java
|
mit
|
andela-kogunde/iReaction
|
java
|
## Code Before:
package Database;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class DatabaseConnectorTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testConnect() throws Exception {
}
@Test
public void testDisconnect() throws Exception {
}
}
## Instruction:
Add Tests to DatabaseConnectionTest class
## Code After:
package Database;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.sql.Connection;
import static org.junit.Assert.*;
public class DatabaseConnectorTest {
DatabaseConnector databaseConnector;
@Before
public void setUp() throws Exception {
databaseConnector = new DatabaseConnector(Config.URL.toString(), Config.USERNAME.toString(), Config.PASSWORD.toString(), Config.DATABASE.toString());
}
@After
public void tearDown() throws Exception {
}
@Test
public void testConnect() throws Exception {
Connection connection = null;
try {
connection = databaseConnector.connect();
assertNotNull(connection);
} catch (Exception e) {
assertTrue(e.toString().contains("SQLException"));
assertNull(connection);
}
}
@Test
public void testDisconnect() throws Exception {
Connection connection = null;
try {
databaseConnector.connect();
assertTrue(databaseConnector.isActive());
databaseConnector.disconnect();
assertFalse(databaseConnector.isActive());
} catch (Exception e) {
assertTrue(e.toString().contains("SQLException"));
assertNull(connection);
}
}
}
|
...
import org.junit.Before;
import org.junit.Test;
import java.sql.Connection;
import static org.junit.Assert.*;
public class DatabaseConnectorTest {
DatabaseConnector databaseConnector;
@Before
public void setUp() throws Exception {
databaseConnector = new DatabaseConnector(Config.URL.toString(), Config.USERNAME.toString(), Config.PASSWORD.toString(), Config.DATABASE.toString());
}
@After
...
@Test
public void testConnect() throws Exception {
Connection connection = null;
try {
connection = databaseConnector.connect();
assertNotNull(connection);
} catch (Exception e) {
assertTrue(e.toString().contains("SQLException"));
assertNull(connection);
}
}
@Test
public void testDisconnect() throws Exception {
Connection connection = null;
try {
databaseConnector.connect();
assertTrue(databaseConnector.isActive());
databaseConnector.disconnect();
assertFalse(databaseConnector.isActive());
} catch (Exception e) {
assertTrue(e.toString().contains("SQLException"));
assertNull(connection);
}
}
}
...
|
d5fe0925c90cd6b9e634019a061d53b39e6c275c
|
src/com/twu/biblioteca/Books.java
|
src/com/twu/biblioteca/Books.java
|
package com.twu.biblioteca;
import java.util.ArrayList;
import java.util.List;
public class Books {
private List<String[]> books;
public Books() {
books = new ArrayList<>();
books.add(new String[]{"Harry Potter and The Sorcer's Stone", "JK Rowling", "1999"});
books.add(new String[]{"Harry Potter and The Chamber of Secrets", "JK Rowling", "2000"});
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (String[] bookDetails : books) {
sb.append("| ");
for(String bookDetail : bookDetails) {
sb.append(bookDetail).append(" | ");
}
sb.deleteCharAt(sb.length() - 1);
sb.append("\n");
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
}
|
package com.twu.biblioteca;
import java.util.ArrayList;
import java.util.List;
public class Books {
private List<Book> books;
public Books() {
books = new ArrayList<>();
books.add(new Book("Harry Potter and The Sorcer's Stone", "JK Rowling", 1999));
books.add(new Book("Harry Potter and The Chamber of Secrets", "JK Rowling", 2000));
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for(Book book : books) {
sb.append(book).append("\n");
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
}
|
Change List of String[] to List of Book
|
Change List of String[] to List of Book
|
Java
|
apache-2.0
|
arunvelsriram/twu-biblioteca-arunvelsriram
|
java
|
## Code Before:
package com.twu.biblioteca;
import java.util.ArrayList;
import java.util.List;
public class Books {
private List<String[]> books;
public Books() {
books = new ArrayList<>();
books.add(new String[]{"Harry Potter and The Sorcer's Stone", "JK Rowling", "1999"});
books.add(new String[]{"Harry Potter and The Chamber of Secrets", "JK Rowling", "2000"});
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (String[] bookDetails : books) {
sb.append("| ");
for(String bookDetail : bookDetails) {
sb.append(bookDetail).append(" | ");
}
sb.deleteCharAt(sb.length() - 1);
sb.append("\n");
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
}
## Instruction:
Change List of String[] to List of Book
## Code After:
package com.twu.biblioteca;
import java.util.ArrayList;
import java.util.List;
public class Books {
private List<Book> books;
public Books() {
books = new ArrayList<>();
books.add(new Book("Harry Potter and The Sorcer's Stone", "JK Rowling", 1999));
books.add(new Book("Harry Potter and The Chamber of Secrets", "JK Rowling", 2000));
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for(Book book : books) {
sb.append(book).append("\n");
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
}
|
# ... existing code ...
import java.util.List;
public class Books {
private List<Book> books;
public Books() {
books = new ArrayList<>();
books.add(new Book("Harry Potter and The Sorcer's Stone", "JK Rowling", 1999));
books.add(new Book("Harry Potter and The Chamber of Secrets", "JK Rowling", 2000));
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for(Book book : books) {
sb.append(book).append("\n");
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
# ... rest of the code ...
|
83dce279fcf157f9ca4cc2e7dbdad55db9f1f857
|
play.py
|
play.py
|
import readline
import random
import shelve
import sys
from src import parser
from src import locations
from src import classes
player = classes.Player(locations, locations.start)
previousNoun = ''
turns = 0
while True:
try:
command = parser.parseCommand(input('> '))
if command is not None:
hasNoun = True
action = command[0]
if len(command) >= 2:
noun = command[1]
else:
hasNoun = False
noun = None
if previousNoun != '' and noun == 'it':
noun = previousNoun
try:
commandResult = getattr(player, action)(action, noun,
hasNoun)
except AttributeError:
print('You can\'t do that here.')
if noun is not None:
previousNoun = noun
else:
previousNoun = ''
turns += 1
except KeyboardInterrupt:
player.die()
|
import os
import readline
import random
import shelve
import sys
os.chdir(os.path.dirname(os.path.abspath(__file__)))
from src import parser
from src import locations
from src import classes
player = classes.Player(locations, locations.start)
previousNoun = ''
turns = 0
while True:
try:
command = parser.parseCommand(input('> '))
if command is not None:
hasNoun = True
action = command[0]
if len(command) >= 2:
noun = command[1]
else:
hasNoun = False
noun = None
if previousNoun != '' and noun == 'it':
noun = previousNoun
try:
commandResult = getattr(player, action)(action, noun,
hasNoun)
except AttributeError:
print('You can\'t do that here.')
if noun is not None:
previousNoun = noun
else:
previousNoun = ''
turns += 1
except KeyboardInterrupt:
player.die()
|
Fix issue where game could be in wrong cwd
|
Fix issue where game could be in wrong cwd
|
Python
|
mit
|
disorientedperson/python-adventure-game,allanburleson/python-adventure-game
|
python
|
## Code Before:
import readline
import random
import shelve
import sys
from src import parser
from src import locations
from src import classes
player = classes.Player(locations, locations.start)
previousNoun = ''
turns = 0
while True:
try:
command = parser.parseCommand(input('> '))
if command is not None:
hasNoun = True
action = command[0]
if len(command) >= 2:
noun = command[1]
else:
hasNoun = False
noun = None
if previousNoun != '' and noun == 'it':
noun = previousNoun
try:
commandResult = getattr(player, action)(action, noun,
hasNoun)
except AttributeError:
print('You can\'t do that here.')
if noun is not None:
previousNoun = noun
else:
previousNoun = ''
turns += 1
except KeyboardInterrupt:
player.die()
## Instruction:
Fix issue where game could be in wrong cwd
## Code After:
import os
import readline
import random
import shelve
import sys
os.chdir(os.path.dirname(os.path.abspath(__file__)))
from src import parser
from src import locations
from src import classes
player = classes.Player(locations, locations.start)
previousNoun = ''
turns = 0
while True:
try:
command = parser.parseCommand(input('> '))
if command is not None:
hasNoun = True
action = command[0]
if len(command) >= 2:
noun = command[1]
else:
hasNoun = False
noun = None
if previousNoun != '' and noun == 'it':
noun = previousNoun
try:
commandResult = getattr(player, action)(action, noun,
hasNoun)
except AttributeError:
print('You can\'t do that here.')
if noun is not None:
previousNoun = noun
else:
previousNoun = ''
turns += 1
except KeyboardInterrupt:
player.die()
|
// ... existing code ...
import os
import readline
import random
import shelve
import sys
os.chdir(os.path.dirname(os.path.abspath(__file__)))
from src import parser
from src import locations
// ... rest of the code ...
|
f8b52162748ccf62db881fad101e6a91ed014bd4
|
plugins/Hitman_Codename_47.py
|
plugins/Hitman_Codename_47.py
|
import os
from lib.base_plugin import BasePlugin
from lib.paths import SteamGamesPath
class HitmanCodename47Plugin(BasePlugin):
Name = "Hitman: Codename 47"
support_os = ["Windows"]
def backup(self, _):
_.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')
def restore(self, _):
_.restore_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')
def detect(self):
if os.path.isdir(os.path.join(SteamGamesPath, 'Hitman Codename 47')):
return True
return False
|
import os
from lib.base_plugin import BasePlugin
from lib.paths import SteamGamesPath
class HitmanCodename47Plugin(BasePlugin):
Name = "Hitman: Codename 47"
support_os = ["Windows"]
def backup(self, _):
_.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')
_.add_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini'])
def restore(self, _):
_.restore_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')
_.restore_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini'])
def detect(self):
if os.path.isdir(os.path.join(SteamGamesPath, 'Hitman Codename 47')):
return True
return False
|
Add backuping config files for Hitman: Codename 47
|
Add backuping config files for Hitman: Codename 47
|
Python
|
mit
|
Pr0Ger/SGSB
|
python
|
## Code Before:
import os
from lib.base_plugin import BasePlugin
from lib.paths import SteamGamesPath
class HitmanCodename47Plugin(BasePlugin):
Name = "Hitman: Codename 47"
support_os = ["Windows"]
def backup(self, _):
_.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')
def restore(self, _):
_.restore_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')
def detect(self):
if os.path.isdir(os.path.join(SteamGamesPath, 'Hitman Codename 47')):
return True
return False
## Instruction:
Add backuping config files for Hitman: Codename 47
## Code After:
import os
from lib.base_plugin import BasePlugin
from lib.paths import SteamGamesPath
class HitmanCodename47Plugin(BasePlugin):
Name = "Hitman: Codename 47"
support_os = ["Windows"]
def backup(self, _):
_.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')
_.add_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini'])
def restore(self, _):
_.restore_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')
_.restore_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini'])
def detect(self):
if os.path.isdir(os.path.join(SteamGamesPath, 'Hitman Codename 47')):
return True
return False
|
// ... existing code ...
def backup(self, _):
_.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')
_.add_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini'])
def restore(self, _):
_.restore_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')
_.restore_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini'])
def detect(self):
if os.path.isdir(os.path.join(SteamGamesPath, 'Hitman Codename 47')):
// ... rest of the code ...
|
9516caa0c62289c89b605b9b8a34622a0bb54e2b
|
tests/70_program_libpfasst_swe_sphere_timestepper_convergence_l1/postprocessing_pickle.py
|
tests/70_program_libpfasst_swe_sphere_timestepper_convergence_l1/postprocessing_pickle.py
|
import sys
import math
import glob
from mule_local.postprocessing.pickle_SphereDataPhysicalDiff import *
from mule.exec_program import *
pickle_SphereDataPhysicalDiff()
|
import sys
import math
import glob
from mule_local.postprocessing.pickle_SphereDataSpectralDiff import *
from mule.exec_program import *
pickle_SphereDataSpectralDiff()
|
Use SphereDataSpectral instead of SphereDataPhysical
|
Use SphereDataSpectral instead of SphereDataPhysical
The script for physical data requires CSV files as default output files,
whereas the spectral script uses .sweet binary files as default.
Since libpfasst_swe_sphere's CSV output is not in the same format as
swe_sphere's CSV output, the CSV parsing does not work --> this is
the easiest way to use the (working) binary output files.
|
Python
|
mit
|
schreiberx/sweet,schreiberx/sweet,schreiberx/sweet,schreiberx/sweet
|
python
|
## Code Before:
import sys
import math
import glob
from mule_local.postprocessing.pickle_SphereDataPhysicalDiff import *
from mule.exec_program import *
pickle_SphereDataPhysicalDiff()
## Instruction:
Use SphereDataSpectral instead of SphereDataPhysical
The script for physical data requires CSV files as default output files,
whereas the spectral script uses .sweet binary files as default.
Since libpfasst_swe_sphere's CSV output is not in the same format as
swe_sphere's CSV output, the CSV parsing does not work --> this is
the easiest way to use the (working) binary output files.
## Code After:
import sys
import math
import glob
from mule_local.postprocessing.pickle_SphereDataSpectralDiff import *
from mule.exec_program import *
pickle_SphereDataSpectralDiff()
|
...
import math
import glob
from mule_local.postprocessing.pickle_SphereDataSpectralDiff import *
from mule.exec_program import *
pickle_SphereDataSpectralDiff()
...
|
fa42219c1e6763f3adfc1f6ede4080f769e476a6
|
tests/test_mongo.py
|
tests/test_mongo.py
|
from uuid import uuid4 as uuid
import pytest
pymongo = pytest.importorskip('pymongo')
from simplekv.db.mongo import MongoStore
from basic_store import BasicStore
class TestMongoDB(BasicStore):
@pytest.fixture
def db_name(self):
return '_simplekv_test_{}'.format(uuid())
@pytest.yield_fixture
def store(self, db_name):
conn = pymongo.MongoClient()
yield MongoStore(conn[db_name])
conn.drop_database(self.db_name)
|
from uuid import uuid4 as uuid
import pytest
pymongo = pytest.importorskip('pymongo')
from simplekv.db.mongo import MongoStore
from basic_store import BasicStore
class TestMongoDB(BasicStore):
@pytest.fixture
def db_name(self):
return '_simplekv_test_{}'.format(uuid())
@pytest.yield_fixture
def store(self, db_name):
conn = pymongo.MongoClient()
yield MongoStore(conn[db_name], 'simplekv-tests')
conn.drop_database(self.db_name)
|
Add database table name to MongoStore tests.
|
Add database table name to MongoStore tests.
|
Python
|
mit
|
fmarczin/simplekv,karteek/simplekv,mbr/simplekv,mbr/simplekv,fmarczin/simplekv,karteek/simplekv
|
python
|
## Code Before:
from uuid import uuid4 as uuid
import pytest
pymongo = pytest.importorskip('pymongo')
from simplekv.db.mongo import MongoStore
from basic_store import BasicStore
class TestMongoDB(BasicStore):
@pytest.fixture
def db_name(self):
return '_simplekv_test_{}'.format(uuid())
@pytest.yield_fixture
def store(self, db_name):
conn = pymongo.MongoClient()
yield MongoStore(conn[db_name])
conn.drop_database(self.db_name)
## Instruction:
Add database table name to MongoStore tests.
## Code After:
from uuid import uuid4 as uuid
import pytest
pymongo = pytest.importorskip('pymongo')
from simplekv.db.mongo import MongoStore
from basic_store import BasicStore
class TestMongoDB(BasicStore):
@pytest.fixture
def db_name(self):
return '_simplekv_test_{}'.format(uuid())
@pytest.yield_fixture
def store(self, db_name):
conn = pymongo.MongoClient()
yield MongoStore(conn[db_name], 'simplekv-tests')
conn.drop_database(self.db_name)
|
// ... existing code ...
@pytest.yield_fixture
def store(self, db_name):
conn = pymongo.MongoClient()
yield MongoStore(conn[db_name], 'simplekv-tests')
conn.drop_database(self.db_name)
// ... rest of the code ...
|
988f4655a96076acd3bfb906d240bd4601fbe535
|
getalltext.py
|
getalltext.py
|
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to analyse')
args=parser.parse_args()
filepath = args.filepath
with open(filepath, 'r') as jsonfile:
events = (loads(line) for line in jsonfile)
for event in events:
#check the event is the sort we're looking for
if "from" in event and "text" in event:
#do i need the "from" here?
print(event["text"])
if __name__ == "__main__":
main()
|
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to analyse')
parser.add_argument('-u','--usernames', help='Show usernames before messages',action='store_true')
args=parser.parse_args()
filepath = args.filepath
with open(filepath, 'r') as jsonfile:
events = (loads(line) for line in jsonfile)
for event in events:
#check the event is the sort we're looking for
if "from" in event and "text" in event:
if args.usernames:
print(event['from']['username'],end=': ')
#do i need the "from" here?
print(event["text"])
if __name__ == "__main__":
main()
|
Add argument to print usernames
|
Add argument to print usernames
|
Python
|
mit
|
expectocode/telegram-analysis,expectocode/telegramAnalysis
|
python
|
## Code Before:
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to analyse')
args=parser.parse_args()
filepath = args.filepath
with open(filepath, 'r') as jsonfile:
events = (loads(line) for line in jsonfile)
for event in events:
#check the event is the sort we're looking for
if "from" in event and "text" in event:
#do i need the "from" here?
print(event["text"])
if __name__ == "__main__":
main()
## Instruction:
Add argument to print usernames
## Code After:
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to analyse')
parser.add_argument('-u','--usernames', help='Show usernames before messages',action='store_true')
args=parser.parse_args()
filepath = args.filepath
with open(filepath, 'r') as jsonfile:
events = (loads(line) for line in jsonfile)
for event in events:
#check the event is the sort we're looking for
if "from" in event and "text" in event:
if args.usernames:
print(event['from']['username'],end=': ')
#do i need the "from" here?
print(event["text"])
if __name__ == "__main__":
main()
|
...
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to analyse')
parser.add_argument('-u','--usernames', help='Show usernames before messages',action='store_true')
args=parser.parse_args()
filepath = args.filepath
...
for event in events:
#check the event is the sort we're looking for
if "from" in event and "text" in event:
if args.usernames:
print(event['from']['username'],end=': ')
#do i need the "from" here?
print(event["text"])
...
|
00b5599e574740680e6c08884510ad605294fad2
|
tests/conftest.py
|
tests/conftest.py
|
"""Shared fixtures for :mod:`pytest`."""
from __future__ import print_function, absolute_import
import os
import pytest # noqa
import gryaml
from py2neo_compat import py2neo_ver
@pytest.fixture
def graphdb():
"""Fixture connecting to graphdb."""
if 'NEO4J_URI' not in os.environ:
pytest.skip('Need NEO4J_URI environment variable set')
graphdb = gryaml.connect(uri=os.environ['NEO4J_URI'])
graphdb.cypher.execute('MATCH (n) DETACH DELETE n')
return graphdb
@pytest.yield_fixture
def graphdb_offline():
"""Ensure the database is not connected."""
if py2neo_ver < 2:
pytest.skip('Offline not supported in py2neo < 2')
neo4j_uri_env = os.environ.get('NEO4J_URI', None)
if neo4j_uri_env:
del os.environ['NEO4J_URI']
old_graphdb = gryaml._py2neo.graphdb
gryaml._py2neo.graphdb = None
yield
gryaml._py2neo.graphdb = old_graphdb
if neo4j_uri_env:
os.environ['NEO4J_URI'] = neo4j_uri_env
|
"""Shared fixtures for :mod:`pytest`."""
from __future__ import print_function, absolute_import
import os
import pytest # noqa
import gryaml
from py2neo_compat import py2neo_ver
@pytest.fixture
def graphdb():
"""Fixture connecting to graphdb."""
if 'NEO4J_URI' not in os.environ:
pytest.skip('Need NEO4J_URI environment variable set')
graphdb = gryaml.connect(uri=os.environ['NEO4J_URI'])
graphdb.delete_all()
return graphdb
@pytest.yield_fixture
def graphdb_offline():
"""Ensure the database is not connected."""
if py2neo_ver < 2:
pytest.skip('Offline not supported in py2neo < 2')
neo4j_uri_env = os.environ.get('NEO4J_URI', None)
if neo4j_uri_env:
del os.environ['NEO4J_URI']
old_graphdb = gryaml._py2neo.graphdb
gryaml._py2neo.graphdb = None
yield
gryaml._py2neo.graphdb = old_graphdb
if neo4j_uri_env:
os.environ['NEO4J_URI'] = neo4j_uri_env
|
Use `delete_all` instead of running cypher query
|
Use `delete_all` instead of running cypher query
|
Python
|
mit
|
wcooley/python-gryaml
|
python
|
## Code Before:
"""Shared fixtures for :mod:`pytest`."""
from __future__ import print_function, absolute_import
import os
import pytest # noqa
import gryaml
from py2neo_compat import py2neo_ver
@pytest.fixture
def graphdb():
"""Fixture connecting to graphdb."""
if 'NEO4J_URI' not in os.environ:
pytest.skip('Need NEO4J_URI environment variable set')
graphdb = gryaml.connect(uri=os.environ['NEO4J_URI'])
graphdb.cypher.execute('MATCH (n) DETACH DELETE n')
return graphdb
@pytest.yield_fixture
def graphdb_offline():
"""Ensure the database is not connected."""
if py2neo_ver < 2:
pytest.skip('Offline not supported in py2neo < 2')
neo4j_uri_env = os.environ.get('NEO4J_URI', None)
if neo4j_uri_env:
del os.environ['NEO4J_URI']
old_graphdb = gryaml._py2neo.graphdb
gryaml._py2neo.graphdb = None
yield
gryaml._py2neo.graphdb = old_graphdb
if neo4j_uri_env:
os.environ['NEO4J_URI'] = neo4j_uri_env
## Instruction:
Use `delete_all` instead of running cypher query
## Code After:
"""Shared fixtures for :mod:`pytest`."""
from __future__ import print_function, absolute_import
import os
import pytest # noqa
import gryaml
from py2neo_compat import py2neo_ver
@pytest.fixture
def graphdb():
"""Fixture connecting to graphdb."""
if 'NEO4J_URI' not in os.environ:
pytest.skip('Need NEO4J_URI environment variable set')
graphdb = gryaml.connect(uri=os.environ['NEO4J_URI'])
graphdb.delete_all()
return graphdb
@pytest.yield_fixture
def graphdb_offline():
"""Ensure the database is not connected."""
if py2neo_ver < 2:
pytest.skip('Offline not supported in py2neo < 2')
neo4j_uri_env = os.environ.get('NEO4J_URI', None)
if neo4j_uri_env:
del os.environ['NEO4J_URI']
old_graphdb = gryaml._py2neo.graphdb
gryaml._py2neo.graphdb = None
yield
gryaml._py2neo.graphdb = old_graphdb
if neo4j_uri_env:
os.environ['NEO4J_URI'] = neo4j_uri_env
|
...
if 'NEO4J_URI' not in os.environ:
pytest.skip('Need NEO4J_URI environment variable set')
graphdb = gryaml.connect(uri=os.environ['NEO4J_URI'])
graphdb.delete_all()
return graphdb
@pytest.yield_fixture
...
|
80ac121a8c12324bd43d240e80a60c746ded7234
|
src/Lolifier.java
|
src/Lolifier.java
|
/**
* Lolifier.class
* Created: 16-09-2013
* @author Allek
* @since 0.0.0
**/
public class Lolifier {
}
|
/*
* Lolifier.class
* Created: 16-09-2013
*/
import javax.swing.JFrame;
/**
* @author Allek
* @since 0.0.0
**/
public class Lolifier extends JFrame {
/**
* Number of "lo"s in a loline (which will then be
* be followed by ending 'l').
* @since 0.0.1
**/
public static final int LOLINE_LOS = 100;
/**
* Default constructor... yeah.
* @since 0.0.1
**/
public Lolifier() {
super("Lolifier");
initGUI();
}
/**
* Wohoo, handle command line args if provided and
* start le lulz.
* @since 0.0.1
**/
public static void main(String args[]) {
new Lolifier().run();
}
/**
* Initialize GUI and whatnot.
* @since 0.0.1
**/
private void initGUI() {
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* Uh, run the thing.
* @since 0.0.1
**/
public void run() {
setVisible(true);
}
}
|
Set up intial JFrame stuff, ish laid out skeleton for the lulz.
|
Set up intial JFrame stuff, ish laid out skeleton for the lulz.
|
Java
|
apache-2.0
|
tchieze/lolifier,tchieze/lolifier
|
java
|
## Code Before:
/**
* Lolifier.class
* Created: 16-09-2013
* @author Allek
* @since 0.0.0
**/
public class Lolifier {
}
## Instruction:
Set up intial JFrame stuff, ish laid out skeleton for the lulz.
## Code After:
/*
* Lolifier.class
* Created: 16-09-2013
*/
import javax.swing.JFrame;
/**
* @author Allek
* @since 0.0.0
**/
public class Lolifier extends JFrame {
/**
* Number of "lo"s in a loline (which will then be
* be followed by ending 'l').
* @since 0.0.1
**/
public static final int LOLINE_LOS = 100;
/**
* Default constructor... yeah.
* @since 0.0.1
**/
public Lolifier() {
super("Lolifier");
initGUI();
}
/**
* Wohoo, handle command line args if provided and
* start le lulz.
* @since 0.0.1
**/
public static void main(String args[]) {
new Lolifier().run();
}
/**
* Initialize GUI and whatnot.
* @since 0.0.1
**/
private void initGUI() {
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* Uh, run the thing.
* @since 0.0.1
**/
public void run() {
setVisible(true);
}
}
|
...
/*
* Lolifier.class
* Created: 16-09-2013
*/
import javax.swing.JFrame;
/**
* @author Allek
* @since 0.0.0
**/
public class Lolifier extends JFrame {
/**
* Number of "lo"s in a loline (which will then be
* be followed by ending 'l').
* @since 0.0.1
**/
public static final int LOLINE_LOS = 100;
/**
* Default constructor... yeah.
* @since 0.0.1
**/
public Lolifier() {
super("Lolifier");
initGUI();
}
/**
* Wohoo, handle command line args if provided and
* start le lulz.
* @since 0.0.1
**/
public static void main(String args[]) {
new Lolifier().run();
}
/**
* Initialize GUI and whatnot.
* @since 0.0.1
**/
private void initGUI() {
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* Uh, run the thing.
* @since 0.0.1
**/
public void run() {
setVisible(true);
}
}
...
|
ffde5305a2182e566384887d51e4fde90adc9908
|
runtests.py
|
runtests.py
|
import os
import sys
import django
from django.conf import settings
from django.test.utils import get_runner
if __name__ == "__main__":
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings'
django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner()
failures = test_runner.run_tests(["tests"])
sys.exit(bool(failures))
|
import os
import sys
import django
from django.conf import settings
from django.test.utils import get_runner
if __name__ == "__main__":
tests = "tests" if len(sys.argv) == 1 else sys.argv[1]
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings'
django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner()
failures = test_runner.run_tests([tests])
sys.exit(bool(failures))
|
Make it possible to run individual tests.
|
Tests: Make it possible to run individual tests.
|
Python
|
agpl-3.0
|
etesync/journal-manager
|
python
|
## Code Before:
import os
import sys
import django
from django.conf import settings
from django.test.utils import get_runner
if __name__ == "__main__":
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings'
django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner()
failures = test_runner.run_tests(["tests"])
sys.exit(bool(failures))
## Instruction:
Tests: Make it possible to run individual tests.
## Code After:
import os
import sys
import django
from django.conf import settings
from django.test.utils import get_runner
if __name__ == "__main__":
tests = "tests" if len(sys.argv) == 1 else sys.argv[1]
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings'
django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner()
failures = test_runner.run_tests([tests])
sys.exit(bool(failures))
|
...
from django.test.utils import get_runner
if __name__ == "__main__":
tests = "tests" if len(sys.argv) == 1 else sys.argv[1]
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings'
django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner()
failures = test_runner.run_tests([tests])
sys.exit(bool(failures))
...
|
0eb4ffc80a3fed17e8ab945ebfe2c97426453548
|
src/org/netbeans/modules/web/primefaces/crudgenerator/util/StringHelper.java
|
src/org/netbeans/modules/web/primefaces/crudgenerator/util/StringHelper.java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.netbeans.modules.web.primefaces.crudgenerator.util;
/**
*
* @author kuw
*/
public class StringHelper {
public static String firstLower(String string) {
boolean makeFirstLower = string.length() < 2 || (!Character.isUpperCase(string.charAt(1)));
return makeFirstLower ? string.substring(0, 1).toLowerCase() + string.substring(1) : string;
}
public static String firstUpper(String string) {
boolean makeFirstUpper = string.length() < 2 || (!Character.isLowerCase(string.charAt(1)));
return makeFirstUpper ? string.substring(0, 1).toUpperCase() + string.substring(1) : string;
}
public static String removeBeanMethodPrefix(String methodName) {
if (methodName.startsWith("get")) { //NOI18N
methodName = methodName.replaceFirst("get", "");
}
if (methodName.startsWith("set")) { //NOI18N
methodName = methodName.replaceFirst("set", "");
}
if (methodName.startsWith("is")) { //NOI18N
methodName = methodName.replaceFirst("is", "");
}
return methodName;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.netbeans.modules.web.primefaces.crudgenerator.util;
/**
*
* @author kuw
*/
public class StringHelper {
public static String firstLower(String string) {
boolean makeFirstLower = string.length() < 2 || (!Character.isUpperCase(string.charAt(1)));
return makeFirstLower ? string.substring(0, 1).toLowerCase() + string.substring(1) : string;
}
public static String firstUpper(String string) {
return string.length() > 1 ? string.substring(0, 1).toUpperCase() + string.substring(1) : string.toUpperCase();
}
public static String removeBeanMethodPrefix(String methodName) {
if (methodName.startsWith("get")) { //NOI18N
methodName = methodName.replaceFirst("get", "");
}
if (methodName.startsWith("set")) { //NOI18N
methodName = methodName.replaceFirst("set", "");
}
if (methodName.startsWith("is")) { //NOI18N
methodName = methodName.replaceFirst("is", "");
}
return methodName;
}
}
|
Fix first upper case problem.
|
Fix first upper case problem.
|
Java
|
mit
|
hfluz/nbcrudgen,hfluz/nbcrudgen,hfluz/nbcrudgen
|
java
|
## Code Before:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.netbeans.modules.web.primefaces.crudgenerator.util;
/**
*
* @author kuw
*/
public class StringHelper {
public static String firstLower(String string) {
boolean makeFirstLower = string.length() < 2 || (!Character.isUpperCase(string.charAt(1)));
return makeFirstLower ? string.substring(0, 1).toLowerCase() + string.substring(1) : string;
}
public static String firstUpper(String string) {
boolean makeFirstUpper = string.length() < 2 || (!Character.isLowerCase(string.charAt(1)));
return makeFirstUpper ? string.substring(0, 1).toUpperCase() + string.substring(1) : string;
}
public static String removeBeanMethodPrefix(String methodName) {
if (methodName.startsWith("get")) { //NOI18N
methodName = methodName.replaceFirst("get", "");
}
if (methodName.startsWith("set")) { //NOI18N
methodName = methodName.replaceFirst("set", "");
}
if (methodName.startsWith("is")) { //NOI18N
methodName = methodName.replaceFirst("is", "");
}
return methodName;
}
}
## Instruction:
Fix first upper case problem.
## Code After:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.netbeans.modules.web.primefaces.crudgenerator.util;
/**
*
* @author kuw
*/
public class StringHelper {
public static String firstLower(String string) {
boolean makeFirstLower = string.length() < 2 || (!Character.isUpperCase(string.charAt(1)));
return makeFirstLower ? string.substring(0, 1).toLowerCase() + string.substring(1) : string;
}
public static String firstUpper(String string) {
return string.length() > 1 ? string.substring(0, 1).toUpperCase() + string.substring(1) : string.toUpperCase();
}
public static String removeBeanMethodPrefix(String methodName) {
if (methodName.startsWith("get")) { //NOI18N
methodName = methodName.replaceFirst("get", "");
}
if (methodName.startsWith("set")) { //NOI18N
methodName = methodName.replaceFirst("set", "");
}
if (methodName.startsWith("is")) { //NOI18N
methodName = methodName.replaceFirst("is", "");
}
return methodName;
}
}
|
// ... existing code ...
}
public static String firstUpper(String string) {
return string.length() > 1 ? string.substring(0, 1).toUpperCase() + string.substring(1) : string.toUpperCase();
}
public static String removeBeanMethodPrefix(String methodName) {
// ... rest of the code ...
|
876932ae5b80a2a1f82eba06dd51418f728f6491
|
src/thed/DRandom.java
|
src/thed/DRandom.java
|
package thed;
import java.util.Random;
/**
* ThreadLocal for java.util.Random instances.
*
* @author Derek Mulvihill - Sep 2, 2013
*/
public class DRandom {
private static ThreadLocal<Random> random = new ThreadLocal<Random>() {
protected Random initialValue() {
return new Random();
}
};
public static Random get() {
return random.get();
}
}
|
package thed;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
/**
* ThreadLocal for java.util.Random instances.
*
* @author Derek Mulvihill - Sep 2, 2013
*/
public class DRandom {
public static Random get() {
ThreadLocalRandom.current();
}
}
|
Use ThreadLocalRandom instead of ThreadLocal<Random>
|
Use ThreadLocalRandom instead of ThreadLocal<Random>
|
Java
|
mit
|
derekmu/Schmince-2
|
java
|
## Code Before:
package thed;
import java.util.Random;
/**
* ThreadLocal for java.util.Random instances.
*
* @author Derek Mulvihill - Sep 2, 2013
*/
public class DRandom {
private static ThreadLocal<Random> random = new ThreadLocal<Random>() {
protected Random initialValue() {
return new Random();
}
};
public static Random get() {
return random.get();
}
}
## Instruction:
Use ThreadLocalRandom instead of ThreadLocal<Random>
## Code After:
package thed;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
/**
* ThreadLocal for java.util.Random instances.
*
* @author Derek Mulvihill - Sep 2, 2013
*/
public class DRandom {
public static Random get() {
ThreadLocalRandom.current();
}
}
|
...
package thed;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
/**
* ThreadLocal for java.util.Random instances.
...
* @author Derek Mulvihill - Sep 2, 2013
*/
public class DRandom {
public static Random get() {
ThreadLocalRandom.current();
}
}
...
|
c81670e3ab8b5dcedc37def3a10803dde9b7c8b1
|
devicehive/transports/base_transport.py
|
devicehive/transports/base_transport.py
|
class BaseTransport(object):
"""Base transport class."""
def __init__(self, name, data_format_class, data_format_options,
handler_class, handler_options):
self.name = name
self._data_format = data_format_class(**data_format_options)
self._data_type = self._data_format.data_type
self._handler = handler_class(self, **handler_options)
self._connected = False
def _assert_not_connected(self):
assert not self._connected, 'transport connection already created'
def _assert_connected(self):
assert self._connected, 'transport connection has not created'
def _encode_obj(self, obj):
return self._data_format.encode(obj)
def _decode_data(self, data):
return self._data_format.decode(data)
def _call_handler_method(self, name, *args):
getattr(self._handler, name)(*args)
def is_connected(self):
return self._connected
def connect(self, url, **options):
raise NotImplementedError
def send_request(self, action, obj, **params):
raise NotImplementedError
def request(self, action, obj, **params):
raise NotImplementedError
def close(self):
raise NotImplementedError
def join(self, timeout=None):
raise NotImplementedError
|
class BaseTransport(object):
"""Base transport class."""
def __init__(self, name, data_format_class, data_format_options,
handler_class, handler_options):
self.name = name
self._data_format = data_format_class(**data_format_options)
self._data_type = self._data_format.data_type
self._handler = handler_class(self, **handler_options)
self._connected = False
def _assert_not_connected(self):
assert not self._connected, 'transport connection already created'
def _assert_connected(self):
assert self._connected, 'transport connection has not created'
def _encode_obj(self, obj):
return self._data_format.encode(obj)
def _decode_data(self, data):
return self._data_format.decode(data)
def _call_handler_method(self, name, *args):
getattr(self._handler, name)(*args)
def is_connected(self):
return self._connected
def connect(self, url, **options):
raise NotImplementedError
def send_request(self, obj, **params):
raise NotImplementedError
def request(self, obj, **params):
raise NotImplementedError
def close(self):
raise NotImplementedError
def join(self, timeout=None):
raise NotImplementedError
|
Remove action from required params
|
Remove action from required params
|
Python
|
apache-2.0
|
devicehive/devicehive-python
|
python
|
## Code Before:
class BaseTransport(object):
"""Base transport class."""
def __init__(self, name, data_format_class, data_format_options,
handler_class, handler_options):
self.name = name
self._data_format = data_format_class(**data_format_options)
self._data_type = self._data_format.data_type
self._handler = handler_class(self, **handler_options)
self._connected = False
def _assert_not_connected(self):
assert not self._connected, 'transport connection already created'
def _assert_connected(self):
assert self._connected, 'transport connection has not created'
def _encode_obj(self, obj):
return self._data_format.encode(obj)
def _decode_data(self, data):
return self._data_format.decode(data)
def _call_handler_method(self, name, *args):
getattr(self._handler, name)(*args)
def is_connected(self):
return self._connected
def connect(self, url, **options):
raise NotImplementedError
def send_request(self, action, obj, **params):
raise NotImplementedError
def request(self, action, obj, **params):
raise NotImplementedError
def close(self):
raise NotImplementedError
def join(self, timeout=None):
raise NotImplementedError
## Instruction:
Remove action from required params
## Code After:
class BaseTransport(object):
"""Base transport class."""
def __init__(self, name, data_format_class, data_format_options,
handler_class, handler_options):
self.name = name
self._data_format = data_format_class(**data_format_options)
self._data_type = self._data_format.data_type
self._handler = handler_class(self, **handler_options)
self._connected = False
def _assert_not_connected(self):
assert not self._connected, 'transport connection already created'
def _assert_connected(self):
assert self._connected, 'transport connection has not created'
def _encode_obj(self, obj):
return self._data_format.encode(obj)
def _decode_data(self, data):
return self._data_format.decode(data)
def _call_handler_method(self, name, *args):
getattr(self._handler, name)(*args)
def is_connected(self):
return self._connected
def connect(self, url, **options):
raise NotImplementedError
def send_request(self, obj, **params):
raise NotImplementedError
def request(self, obj, **params):
raise NotImplementedError
def close(self):
raise NotImplementedError
def join(self, timeout=None):
raise NotImplementedError
|
# ... existing code ...
def connect(self, url, **options):
raise NotImplementedError
def send_request(self, obj, **params):
raise NotImplementedError
def request(self, obj, **params):
raise NotImplementedError
def close(self):
# ... rest of the code ...
|
5a6c8b1c9c13078462bec7ba254c6a6f95dd3c42
|
contrib/linux/tests/test_action_dig.py
|
contrib/linux/tests/test_action_dig.py
|
from __future__ import absolute_import
from st2tests.base import BaseActionTestCase
from dig import DigAction
class DigActionTestCase(BaseActionTestCase):
action_cls = DigAction
def test_run(self):
action = self.get_action_instance()
# Use the defaults from dig.yaml
result = action.run(rand=False, count=0, nameserver=None, hostname='', queryopts='short')
self.assertIsInstance(result, list)
self.assertEqual(len(result), 0)
result = action.run(rand=False, count=0, nameserver=None, hostname='google.com',
queryopts='')
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
|
from __future__ import absolute_import
from st2tests.base import BaseActionTestCase
from dig import DigAction
class DigActionTestCase(BaseActionTestCase):
action_cls = DigAction
def test_run(self):
action = self.get_action_instance()
# Use the defaults from dig.yaml
result = action.run(rand=False, count=0, nameserver=None, hostname='', queryopts='short')
self.assertIsInstance(result, list)
self.assertEqual(len(result), 0)
result = action.run(rand=False, count=0, nameserver=None, hostname='google.com',
queryopts='')
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
first_result = result[0]
self.assertIsInstance(first_result, str)
self.assertGreater(len(first_result))
|
Test that returned result is a str instance
|
Test that returned result is a str instance
|
Python
|
apache-2.0
|
nzlosh/st2,StackStorm/st2,StackStorm/st2,Plexxi/st2,Plexxi/st2,Plexxi/st2,StackStorm/st2,StackStorm/st2,nzlosh/st2,nzlosh/st2,Plexxi/st2,nzlosh/st2
|
python
|
## Code Before:
from __future__ import absolute_import
from st2tests.base import BaseActionTestCase
from dig import DigAction
class DigActionTestCase(BaseActionTestCase):
action_cls = DigAction
def test_run(self):
action = self.get_action_instance()
# Use the defaults from dig.yaml
result = action.run(rand=False, count=0, nameserver=None, hostname='', queryopts='short')
self.assertIsInstance(result, list)
self.assertEqual(len(result), 0)
result = action.run(rand=False, count=0, nameserver=None, hostname='google.com',
queryopts='')
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
## Instruction:
Test that returned result is a str instance
## Code After:
from __future__ import absolute_import
from st2tests.base import BaseActionTestCase
from dig import DigAction
class DigActionTestCase(BaseActionTestCase):
action_cls = DigAction
def test_run(self):
action = self.get_action_instance()
# Use the defaults from dig.yaml
result = action.run(rand=False, count=0, nameserver=None, hostname='', queryopts='short')
self.assertIsInstance(result, list)
self.assertEqual(len(result), 0)
result = action.run(rand=False, count=0, nameserver=None, hostname='google.com',
queryopts='')
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
first_result = result[0]
self.assertIsInstance(first_result, str)
self.assertGreater(len(first_result))
|
// ... existing code ...
queryopts='')
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
first_result = result[0]
self.assertIsInstance(first_result, str)
self.assertGreater(len(first_result))
// ... rest of the code ...
|
c33bbe44708ccf60f4a0cf759b3f38b739b7fb5d
|
PartyUPLambda/purge.py
|
PartyUPLambda/purge.py
|
import json
import boto3
import time
import decimal
from boto3.dynamodb.conditions import Key, Attr
def purge_item(item, batch):
response = batch.delete_item(
Key={
'event' : item['event'],
'id': item['id']
}
)
def purge_handler(event, context):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Samples')
filter = Attr('time').lte(decimal.Decimal(time.time()-172800))
with table.batch_writer() as batch:
response = table.scan(
FilterExpression=filter
)
for item in response['Items']:
purge_item(item, batch)
while 'LastEvaluatedKey' in response:
response = scan(
FilterExpression=filter,
ExclusiveStartKey=response['LastEvaluatedKey']
)
for item in response['Items']:
purge_item(item, batch)
|
import logging
import json
import boto3
import time
import decimal
from boto3.dynamodb.conditions import Key, Attr
logger = logging.getLogger()
logger.setLevel(logging.ERROR)
def purge_item(item, batch):
response = batch.delete_item(
Key={
'event' : item['event'],
'id': item['id']
}
)
def purge_handler(event, context):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Samples')
filter = Attr('time').lte(decimal.Decimal(time.time()-172800))
with table.batch_writer() as batch:
response = table.scan(
FilterExpression=filter
)
for item in response['Items']:
purge_item(item, batch)
while 'LastEvaluatedKey' in response:
response = scan(
FilterExpression=filter,
ExclusiveStartKey=response['LastEvaluatedKey']
)
for item in response['Items']:
purge_item(item, batch)
|
Add error logging to aid tracking down future issues.
|
Add error logging to aid tracking down future issues.
|
Python
|
mit
|
SandcastleApps/partyup,SandcastleApps/partyup,SandcastleApps/partyup
|
python
|
## Code Before:
import json
import boto3
import time
import decimal
from boto3.dynamodb.conditions import Key, Attr
def purge_item(item, batch):
response = batch.delete_item(
Key={
'event' : item['event'],
'id': item['id']
}
)
def purge_handler(event, context):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Samples')
filter = Attr('time').lte(decimal.Decimal(time.time()-172800))
with table.batch_writer() as batch:
response = table.scan(
FilterExpression=filter
)
for item in response['Items']:
purge_item(item, batch)
while 'LastEvaluatedKey' in response:
response = scan(
FilterExpression=filter,
ExclusiveStartKey=response['LastEvaluatedKey']
)
for item in response['Items']:
purge_item(item, batch)
## Instruction:
Add error logging to aid tracking down future issues.
## Code After:
import logging
import json
import boto3
import time
import decimal
from boto3.dynamodb.conditions import Key, Attr
logger = logging.getLogger()
logger.setLevel(logging.ERROR)
def purge_item(item, batch):
response = batch.delete_item(
Key={
'event' : item['event'],
'id': item['id']
}
)
def purge_handler(event, context):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Samples')
filter = Attr('time').lte(decimal.Decimal(time.time()-172800))
with table.batch_writer() as batch:
response = table.scan(
FilterExpression=filter
)
for item in response['Items']:
purge_item(item, batch)
while 'LastEvaluatedKey' in response:
response = scan(
FilterExpression=filter,
ExclusiveStartKey=response['LastEvaluatedKey']
)
for item in response['Items']:
purge_item(item, batch)
|
...
import logging
import json
import boto3
import time
import decimal
from boto3.dynamodb.conditions import Key, Attr
logger = logging.getLogger()
logger.setLevel(logging.ERROR)
def purge_item(item, batch):
response = batch.delete_item(
...
|
923f6127eec0a6a576493f41d0f3b2fb9b6156d1
|
tests/Settings/TestContainerStack.py
|
tests/Settings/TestContainerStack.py
|
import UM.Settings
def test_container_stack():
stack = UM.Settings.ContainerStack()
|
import pytest
import uuid # For creating unique ID's for each container stack.
import UM.Settings
## Creates a brand new container stack to test with.
#
# The container stack will get a new, unique ID.
@pytest.fixture
def container_stack():
return UM.Settings.ContainerStack(uuid.uuid4().int)
def test_container_stack(container_stack):
assert container_stack != None
|
Test creating container stack with fixture
|
Test creating container stack with fixture
The fixture will automatically generate a unique ID.
Contributes to issue CURA-1278.
|
Python
|
agpl-3.0
|
onitake/Uranium,onitake/Uranium
|
python
|
## Code Before:
import UM.Settings
def test_container_stack():
stack = UM.Settings.ContainerStack()
## Instruction:
Test creating container stack with fixture
The fixture will automatically generate a unique ID.
Contributes to issue CURA-1278.
## Code After:
import pytest
import uuid # For creating unique ID's for each container stack.
import UM.Settings
## Creates a brand new container stack to test with.
#
# The container stack will get a new, unique ID.
@pytest.fixture
def container_stack():
return UM.Settings.ContainerStack(uuid.uuid4().int)
def test_container_stack(container_stack):
assert container_stack != None
|
// ... existing code ...
import pytest
import uuid # For creating unique ID's for each container stack.
import UM.Settings
## Creates a brand new container stack to test with.
#
# The container stack will get a new, unique ID.
@pytest.fixture
def container_stack():
return UM.Settings.ContainerStack(uuid.uuid4().int)
def test_container_stack(container_stack):
assert container_stack != None
// ... rest of the code ...
|
943d2648c17facb9dbfd4f26d335beef341e9c49
|
fabfile.py
|
fabfile.py
|
from fabric.api import local
__author__ = 'derek'
def deploy(version):
local('python runtests.py')
local("git tag -a %s -m %s" % (version, version))
local('python setup.py sdist upload')
|
from fabric.api import local
__author__ = 'derek'
def deploy(version):
local('python runtests.py')
local("git tag -a %s -m %s" % (version, version))
local("git push origin --tags")
local('python setup.py sdist upload')
|
Make sure to push the tags
|
Make sure to push the tags
|
Python
|
mit
|
winfieldco/django-mail-queue,Goury/django-mail-queue,Goury/django-mail-queue,dstegelman/django-mail-queue,dstegelman/django-mail-queue,styrmis/django-mail-queue
|
python
|
## Code Before:
from fabric.api import local
__author__ = 'derek'
def deploy(version):
local('python runtests.py')
local("git tag -a %s -m %s" % (version, version))
local('python setup.py sdist upload')
## Instruction:
Make sure to push the tags
## Code After:
from fabric.api import local
__author__ = 'derek'
def deploy(version):
local('python runtests.py')
local("git tag -a %s -m %s" % (version, version))
local("git push origin --tags")
local('python setup.py sdist upload')
|
...
def deploy(version):
local('python runtests.py')
local("git tag -a %s -m %s" % (version, version))
local("git push origin --tags")
local('python setup.py sdist upload')
...
|
d6fd33b1409130013d5f31148e89fb75c65aaec6
|
cloudfoundry-connector/src/main/java/org/springframework/cloud/cloudfoundry/MongoServiceInfoCreator.java
|
cloudfoundry-connector/src/main/java/org/springframework/cloud/cloudfoundry/MongoServiceInfoCreator.java
|
package org.springframework.cloud.cloudfoundry;
import java.util.Map;
import org.springframework.cloud.service.common.MongoServiceInfo;
/**
*
* @author Ramnivas Laddad
*
*/
public class MongoServiceInfoCreator extends CloudFoundryServiceInfoCreator<MongoServiceInfo> {
public MongoServiceInfoCreator() {
super("mongodb");
}
public MongoServiceInfo createServiceInfo(Map<String,Object> serviceData) {
@SuppressWarnings("unchecked")
Map<String,Object> credentials = (Map<String, Object>) serviceData.get("credentials");
String id = (String) serviceData.get("name");
String uri = (String) credentials.get("uri");
return new MongoServiceInfo(id, uri);
}
}
|
package org.springframework.cloud.cloudfoundry;
import java.util.Map;
import org.springframework.cloud.service.common.MongoServiceInfo;
/**
*
* @author Ramnivas Laddad
*
*/
public class MongoServiceInfoCreator extends CloudFoundryServiceInfoCreator<MongoServiceInfo> {
public MongoServiceInfoCreator() {
super("mongodb");
}
public MongoServiceInfo createServiceInfo(Map<String,Object> serviceData) {
@SuppressWarnings("unchecked")
Map<String,Object> credentials = (Map<String, Object>) serviceData.get("credentials");
String id = (String) serviceData.get("name");
String uri = (String) ((credentials.get("uri") == null) ? credentials.get("url") : credentials.get("uri"));
return new MongoServiceInfo(id, uri);
}
}
|
Add fix for MongoDb if url is used instead of uri
|
Add fix for MongoDb if url is used instead of uri
|
Java
|
apache-2.0
|
spring-cloud/spring-cloud-connectors,mbogoevici/spring-cloud-connectors,gorcz/spring-cloud-connectors,scottfrederick/spring-cloud-connectors,chrisjs/spring-cloud-connectors,sandhya9/spring-cloud-connectors,scottfrederick/spring-cloud-connectors,sandhya9/spring-cloud-connectors,mbogoevici/spring-cloud-connectors,spring-cloud/spring-cloud-connectors,chrisjs/spring-cloud-connectors
|
java
|
## Code Before:
package org.springframework.cloud.cloudfoundry;
import java.util.Map;
import org.springframework.cloud.service.common.MongoServiceInfo;
/**
*
* @author Ramnivas Laddad
*
*/
public class MongoServiceInfoCreator extends CloudFoundryServiceInfoCreator<MongoServiceInfo> {
public MongoServiceInfoCreator() {
super("mongodb");
}
public MongoServiceInfo createServiceInfo(Map<String,Object> serviceData) {
@SuppressWarnings("unchecked")
Map<String,Object> credentials = (Map<String, Object>) serviceData.get("credentials");
String id = (String) serviceData.get("name");
String uri = (String) credentials.get("uri");
return new MongoServiceInfo(id, uri);
}
}
## Instruction:
Add fix for MongoDb if url is used instead of uri
## Code After:
package org.springframework.cloud.cloudfoundry;
import java.util.Map;
import org.springframework.cloud.service.common.MongoServiceInfo;
/**
*
* @author Ramnivas Laddad
*
*/
public class MongoServiceInfoCreator extends CloudFoundryServiceInfoCreator<MongoServiceInfo> {
public MongoServiceInfoCreator() {
super("mongodb");
}
public MongoServiceInfo createServiceInfo(Map<String,Object> serviceData) {
@SuppressWarnings("unchecked")
Map<String,Object> credentials = (Map<String, Object>) serviceData.get("credentials");
String id = (String) serviceData.get("name");
String uri = (String) ((credentials.get("uri") == null) ? credentials.get("url") : credentials.get("uri"));
return new MongoServiceInfo(id, uri);
}
}
|
# ... existing code ...
import org.springframework.cloud.service.common.MongoServiceInfo;
/**
*
* @author Ramnivas Laddad
*
*/
# ... modified code ...
public MongoServiceInfo createServiceInfo(Map<String,Object> serviceData) {
@SuppressWarnings("unchecked")
Map<String,Object> credentials = (Map<String, Object>) serviceData.get("credentials");
String id = (String) serviceData.get("name");
String uri = (String) ((credentials.get("uri") == null) ? credentials.get("url") : credentials.get("uri"));
return new MongoServiceInfo(id, uri);
}
# ... rest of the code ...
|
c447ca3d85d9862be38034be85b2328e3d6b02a3
|
vcproj/tests/test_solution.py
|
vcproj/tests/test_solution.py
|
import vcproj.solution
import tempfile, filecmp
import pytest
@pytest.fixture(scope="session")
def test_sol():
return vcproj.solution.parse('vcproj/tests/test_solution/vc15sol/vc15sol.sln')
def test_all_projects(test_sol):
projects = test_sol.project_names()
len(list(projects)) == 59
def test_project_names(test_sol):
projects = test_sol.project_names()
assert 'Helper' in projects
assert 'MDraw' in projects
def test_project_files(test_sol):
proj_files = list(test_sol.project_files())
assert 'PrivateLib\\PrivateLib.vcxproj' in proj_files
assert 'Helper\\Helper.vcxproj' in proj_files
assert 'Resource\\Resource.vcxproj' in proj_files
def test_dependencies(test_sol):
deps = list(test_sol.dependencies('DXHHTest'))
assert deps == ['Public', 'MDraw']
def test_set_dependencies():
s = vcproj.solution.parse('vcproj/tests/test_solution/test.sln')
s.set_dependencies('lib1', ['lib2'])
assert list(s.dependencies('lib1')) == ['lib2']
def test_write():
s = vcproj.solution.parse('vcproj/tests/test_solution/test.sln')
temp = tempfile.NamedTemporaryFile()
temp.close()
s.write(temp.name)
assert filecmp.cmp('vcproj/tests/test_solution/test.sln', temp.name)
|
import vcproj.solution
import tempfile, filecmp
import pytest
@pytest.fixture(scope="session")
def test_sol():
return vcproj.solution.parse('vcproj/tests/test_solution/test.sln')
def test_project_files(test_sol):
assert list(test_sol.project_files()) == ['test\\test.vcxproj', 'lib1\\lib1.vcxproj', 'lib2\\lib2.vcxproj']
def test_dependencies(test_sol):
assert list(test_sol.dependencies('test')) == ['lib1', 'lib2']
def test_project_names(test_sol):
assert list(test_sol.project_names()) == ['test', 'lib1', 'lib2']
def test_set_dependencies(test_sol):
test_sol.set_dependencies('lib1', ['lib2'])
assert list(test_sol.dependencies('lib1')) == ['lib2']
def test_write():
s = vcproj.solution.parse('vcproj/tests/test_solution/test.sln')
temp = tempfile.NamedTemporaryFile()
temp.close()
s.write(temp.name)
assert filecmp.cmp('vcproj/tests/test_solution/test.sln', temp.name)
|
Add back in test of 2010 solution
|
Add back in test of 2010 solution
|
Python
|
unlicense
|
jhandley/pyvcproj,jhandley/pyvcproj,jhandley/pyvcproj
|
python
|
## Code Before:
import vcproj.solution
import tempfile, filecmp
import pytest
@pytest.fixture(scope="session")
def test_sol():
return vcproj.solution.parse('vcproj/tests/test_solution/vc15sol/vc15sol.sln')
def test_all_projects(test_sol):
projects = test_sol.project_names()
len(list(projects)) == 59
def test_project_names(test_sol):
projects = test_sol.project_names()
assert 'Helper' in projects
assert 'MDraw' in projects
def test_project_files(test_sol):
proj_files = list(test_sol.project_files())
assert 'PrivateLib\\PrivateLib.vcxproj' in proj_files
assert 'Helper\\Helper.vcxproj' in proj_files
assert 'Resource\\Resource.vcxproj' in proj_files
def test_dependencies(test_sol):
deps = list(test_sol.dependencies('DXHHTest'))
assert deps == ['Public', 'MDraw']
def test_set_dependencies():
s = vcproj.solution.parse('vcproj/tests/test_solution/test.sln')
s.set_dependencies('lib1', ['lib2'])
assert list(s.dependencies('lib1')) == ['lib2']
def test_write():
s = vcproj.solution.parse('vcproj/tests/test_solution/test.sln')
temp = tempfile.NamedTemporaryFile()
temp.close()
s.write(temp.name)
assert filecmp.cmp('vcproj/tests/test_solution/test.sln', temp.name)
## Instruction:
Add back in test of 2010 solution
## Code After:
import vcproj.solution
import tempfile, filecmp
import pytest
@pytest.fixture(scope="session")
def test_sol():
return vcproj.solution.parse('vcproj/tests/test_solution/test.sln')
def test_project_files(test_sol):
assert list(test_sol.project_files()) == ['test\\test.vcxproj', 'lib1\\lib1.vcxproj', 'lib2\\lib2.vcxproj']
def test_dependencies(test_sol):
assert list(test_sol.dependencies('test')) == ['lib1', 'lib2']
def test_project_names(test_sol):
assert list(test_sol.project_names()) == ['test', 'lib1', 'lib2']
def test_set_dependencies(test_sol):
test_sol.set_dependencies('lib1', ['lib2'])
assert list(test_sol.dependencies('lib1')) == ['lib2']
def test_write():
s = vcproj.solution.parse('vcproj/tests/test_solution/test.sln')
temp = tempfile.NamedTemporaryFile()
temp.close()
s.write(temp.name)
assert filecmp.cmp('vcproj/tests/test_solution/test.sln', temp.name)
|
...
@pytest.fixture(scope="session")
def test_sol():
return vcproj.solution.parse('vcproj/tests/test_solution/test.sln')
def test_project_files(test_sol):
assert list(test_sol.project_files()) == ['test\\test.vcxproj', 'lib1\\lib1.vcxproj', 'lib2\\lib2.vcxproj']
def test_dependencies(test_sol):
assert list(test_sol.dependencies('test')) == ['lib1', 'lib2']
def test_project_names(test_sol):
assert list(test_sol.project_names()) == ['test', 'lib1', 'lib2']
def test_set_dependencies(test_sol):
test_sol.set_dependencies('lib1', ['lib2'])
assert list(test_sol.dependencies('lib1')) == ['lib2']
def test_write():
s = vcproj.solution.parse('vcproj/tests/test_solution/test.sln')
...
|
fc66db188ecabbe21cea23c91a9e9b24bbf9d11e
|
bluebottle/homepage/views.py
|
bluebottle/homepage/views.py
|
from rest_framework import generics, response
from .models import HomePage
from .serializers import HomePageSerializer
# Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object
class HomePageDetail(generics.GenericAPIView):
serializer_class = HomePageSerializer
def get(self, request, language='en'):
homepage = HomePage().get(language)
serialized = HomePageSerializer().to_native(homepage)
return response.Response(serialized)
|
from django.utils import translation
from rest_framework import generics, response
from .models import HomePage
from .serializers import HomePageSerializer
# Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object
class HomePageDetail(generics.GenericAPIView):
serializer_class = HomePageSerializer
def get(self, request, language='en'):
# Force requested language
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()
homepage = HomePage().get(language)
serialized = HomePageSerializer().to_native(homepage)
return response.Response(serialized)
|
Fix translations for homepage stats
|
Fix translations for homepage stats
|
Python
|
bsd-3-clause
|
jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle
|
python
|
## Code Before:
from rest_framework import generics, response
from .models import HomePage
from .serializers import HomePageSerializer
# Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object
class HomePageDetail(generics.GenericAPIView):
serializer_class = HomePageSerializer
def get(self, request, language='en'):
homepage = HomePage().get(language)
serialized = HomePageSerializer().to_native(homepage)
return response.Response(serialized)
## Instruction:
Fix translations for homepage stats
## Code After:
from django.utils import translation
from rest_framework import generics, response
from .models import HomePage
from .serializers import HomePageSerializer
# Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object
class HomePageDetail(generics.GenericAPIView):
serializer_class = HomePageSerializer
def get(self, request, language='en'):
# Force requested language
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()
homepage = HomePage().get(language)
serialized = HomePageSerializer().to_native(homepage)
return response.Response(serialized)
|
// ... existing code ...
from django.utils import translation
from rest_framework import generics, response
from .models import HomePage
// ... modified code ...
serializer_class = HomePageSerializer
def get(self, request, language='en'):
# Force requested language
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()
homepage = HomePage().get(language)
serialized = HomePageSerializer().to_native(homepage)
return response.Response(serialized)
// ... rest of the code ...
|
0c21d60108d38f43d22aa03c882a62c93754d5da
|
tests/test_cli.py
|
tests/test_cli.py
|
from mdformat._cli import run
UNFORMATTED_MARKDOWN = "\n\n# A header\n\n"
FORMATTED_MARKDOWN = "# A header\n"
def test_no_files_passed():
assert run(()) == 0
def test_format(tmp_path):
file_path = tmp_path / "test_markdown.md"
file_path.write_text(UNFORMATTED_MARKDOWN)
assert run((str(file_path),)) == 0
assert file_path.read_text() == FORMATTED_MARKDOWN
def test_invalid_file():
assert run(("this is not a valid filepath?`=|><@{[]\\/,.%¤#'",)) == 1
def test_check(tmp_path):
file_path = tmp_path / "test_markdown.md"
file_path.write_text(FORMATTED_MARKDOWN)
assert run((str(file_path), "--check")) == 0
def test_check__fail(tmp_path):
file_path = tmp_path / "test_markdown.md"
file_path.write_text(UNFORMATTED_MARKDOWN)
assert run((str(file_path), "--check")) == 1
|
from io import StringIO
import sys
from mdformat._cli import run
UNFORMATTED_MARKDOWN = "\n\n# A header\n\n"
FORMATTED_MARKDOWN = "# A header\n"
def test_no_files_passed():
assert run(()) == 0
def test_format(tmp_path):
file_path = tmp_path / "test_markdown.md"
file_path.write_text(UNFORMATTED_MARKDOWN)
assert run((str(file_path),)) == 0
assert file_path.read_text() == FORMATTED_MARKDOWN
def test_invalid_file():
assert run(("this is not a valid filepath?`=|><@{[]\\/,.%¤#'",)) == 1
def test_check(tmp_path):
file_path = tmp_path / "test_markdown.md"
file_path.write_text(FORMATTED_MARKDOWN)
assert run((str(file_path), "--check")) == 0
def test_check__fail(tmp_path):
file_path = tmp_path / "test_markdown.md"
file_path.write_text(UNFORMATTED_MARKDOWN)
assert run((str(file_path), "--check")) == 1
def test_dash_stdin(capsys, monkeypatch):
monkeypatch.setattr(sys, "stdin", StringIO(UNFORMATTED_MARKDOWN))
run(("-",))
captured = capsys.readouterr()
assert captured.out == FORMATTED_MARKDOWN
|
Test read from stdin and write to stdout
|
Test read from stdin and write to stdout
|
Python
|
mit
|
executablebooks/mdformat
|
python
|
## Code Before:
from mdformat._cli import run
UNFORMATTED_MARKDOWN = "\n\n# A header\n\n"
FORMATTED_MARKDOWN = "# A header\n"
def test_no_files_passed():
assert run(()) == 0
def test_format(tmp_path):
file_path = tmp_path / "test_markdown.md"
file_path.write_text(UNFORMATTED_MARKDOWN)
assert run((str(file_path),)) == 0
assert file_path.read_text() == FORMATTED_MARKDOWN
def test_invalid_file():
assert run(("this is not a valid filepath?`=|><@{[]\\/,.%¤#'",)) == 1
def test_check(tmp_path):
file_path = tmp_path / "test_markdown.md"
file_path.write_text(FORMATTED_MARKDOWN)
assert run((str(file_path), "--check")) == 0
def test_check__fail(tmp_path):
file_path = tmp_path / "test_markdown.md"
file_path.write_text(UNFORMATTED_MARKDOWN)
assert run((str(file_path), "--check")) == 1
## Instruction:
Test read from stdin and write to stdout
## Code After:
from io import StringIO
import sys
from mdformat._cli import run
UNFORMATTED_MARKDOWN = "\n\n# A header\n\n"
FORMATTED_MARKDOWN = "# A header\n"
def test_no_files_passed():
assert run(()) == 0
def test_format(tmp_path):
file_path = tmp_path / "test_markdown.md"
file_path.write_text(UNFORMATTED_MARKDOWN)
assert run((str(file_path),)) == 0
assert file_path.read_text() == FORMATTED_MARKDOWN
def test_invalid_file():
assert run(("this is not a valid filepath?`=|><@{[]\\/,.%¤#'",)) == 1
def test_check(tmp_path):
file_path = tmp_path / "test_markdown.md"
file_path.write_text(FORMATTED_MARKDOWN)
assert run((str(file_path), "--check")) == 0
def test_check__fail(tmp_path):
file_path = tmp_path / "test_markdown.md"
file_path.write_text(UNFORMATTED_MARKDOWN)
assert run((str(file_path), "--check")) == 1
def test_dash_stdin(capsys, monkeypatch):
monkeypatch.setattr(sys, "stdin", StringIO(UNFORMATTED_MARKDOWN))
run(("-",))
captured = capsys.readouterr()
assert captured.out == FORMATTED_MARKDOWN
|
// ... existing code ...
from io import StringIO
import sys
from mdformat._cli import run
UNFORMATTED_MARKDOWN = "\n\n# A header\n\n"
// ... modified code ...
file_path = tmp_path / "test_markdown.md"
file_path.write_text(UNFORMATTED_MARKDOWN)
assert run((str(file_path), "--check")) == 1
def test_dash_stdin(capsys, monkeypatch):
monkeypatch.setattr(sys, "stdin", StringIO(UNFORMATTED_MARKDOWN))
run(("-",))
captured = capsys.readouterr()
assert captured.out == FORMATTED_MARKDOWN
// ... rest of the code ...
|
12d239d62c293cdb1a3fa1a69df06bf9c8e65366
|
grip/github_renderer.py
|
grip/github_renderer.py
|
from flask import abort, json
import requests
def render_content(text, gfm=False, context=None, username=None, password=None):
"""Renders the specified markup using the GitHub API."""
if gfm:
url = 'https://api.github.com/markdown'
data = {'text': text, 'mode': 'gfm', 'context': context}
if context:
data['context'] = context
data = json.dumps(data)
else:
url = 'https://api.github.com/markdown/raw'
data = text
headers = {'content-type': 'text/plain'}
auth = (username, password) if username else None
r = requests.post(url, headers=headers, data=data, auth=auth)
# Relay HTTP errors
if r.status_code != 200:
try:
message = r.json()['message']
except:
message = r.text
abort(r.status_code, message)
return r.text
|
from flask import abort, json
import requests
def render_content(text, gfm=False, context=None,
username=None, password=None):
"""Renders the specified markup using the GitHub API."""
if gfm:
url = 'https://api.github.com/markdown'
data = {'text': text, 'mode': 'gfm'}
if context:
data['context'] = context
data = json.dumps(data)
else:
url = 'https://api.github.com/markdown/raw'
data = text
headers = {'content-type': 'text/plain'}
auth = (username, password) if username else None
r = requests.post(url, headers=headers, data=data, auth=auth)
# Relay HTTP errors
if r.status_code != 200:
try:
message = r.json()['message']
except:
message = r.text
abort(r.status_code, message)
return r.text
|
Remove duplicate 'context': context in GitHub renderer.
|
Remove duplicate 'context': context in GitHub renderer.
|
Python
|
mit
|
jbarreras/grip,ssundarraj/grip,joeyespo/grip,mgoddard-pivotal/grip,mgoddard-pivotal/grip,jbarreras/grip,joeyespo/grip,ssundarraj/grip
|
python
|
## Code Before:
from flask import abort, json
import requests
def render_content(text, gfm=False, context=None, username=None, password=None):
"""Renders the specified markup using the GitHub API."""
if gfm:
url = 'https://api.github.com/markdown'
data = {'text': text, 'mode': 'gfm', 'context': context}
if context:
data['context'] = context
data = json.dumps(data)
else:
url = 'https://api.github.com/markdown/raw'
data = text
headers = {'content-type': 'text/plain'}
auth = (username, password) if username else None
r = requests.post(url, headers=headers, data=data, auth=auth)
# Relay HTTP errors
if r.status_code != 200:
try:
message = r.json()['message']
except:
message = r.text
abort(r.status_code, message)
return r.text
## Instruction:
Remove duplicate 'context': context in GitHub renderer.
## Code After:
from flask import abort, json
import requests
def render_content(text, gfm=False, context=None,
username=None, password=None):
"""Renders the specified markup using the GitHub API."""
if gfm:
url = 'https://api.github.com/markdown'
data = {'text': text, 'mode': 'gfm'}
if context:
data['context'] = context
data = json.dumps(data)
else:
url = 'https://api.github.com/markdown/raw'
data = text
headers = {'content-type': 'text/plain'}
auth = (username, password) if username else None
r = requests.post(url, headers=headers, data=data, auth=auth)
# Relay HTTP errors
if r.status_code != 200:
try:
message = r.json()['message']
except:
message = r.text
abort(r.status_code, message)
return r.text
|
// ... existing code ...
import requests
def render_content(text, gfm=False, context=None,
username=None, password=None):
"""Renders the specified markup using the GitHub API."""
if gfm:
url = 'https://api.github.com/markdown'
data = {'text': text, 'mode': 'gfm'}
if context:
data['context'] = context
data = json.dumps(data)
// ... rest of the code ...
|
641b2d07a4250a779ad6ff31f579968f69362cc0
|
numscons/numdist/__init__.py
|
numscons/numdist/__init__.py
|
from numdist_copy import default_lib_dirs, default_include_dirs, \
default_src_dirs, get_standard_file
from numdist_copy import msvc_runtime_library
from conv_template import process_file as process_c_file
from from_template import process_file as process_f_file
|
from numdist_copy import default_lib_dirs, default_include_dirs, \
default_src_dirs, get_standard_file
from numdist_copy import msvc_runtime_library
from conv_template import process_file as process_c_file, process_str as process_c_str
from from_template import process_file as process_f_file
|
Add process_c_str function to the numdist API
|
Add process_c_str function to the numdist API
|
Python
|
bsd-3-clause
|
cournape/numscons,cournape/numscons,cournape/numscons
|
python
|
## Code Before:
from numdist_copy import default_lib_dirs, default_include_dirs, \
default_src_dirs, get_standard_file
from numdist_copy import msvc_runtime_library
from conv_template import process_file as process_c_file
from from_template import process_file as process_f_file
## Instruction:
Add process_c_str function to the numdist API
## Code After:
from numdist_copy import default_lib_dirs, default_include_dirs, \
default_src_dirs, get_standard_file
from numdist_copy import msvc_runtime_library
from conv_template import process_file as process_c_file, process_str as process_c_str
from from_template import process_file as process_f_file
|
...
default_src_dirs, get_standard_file
from numdist_copy import msvc_runtime_library
from conv_template import process_file as process_c_file, process_str as process_c_str
from from_template import process_file as process_f_file
...
|
4139dafb967c61ac8d10b3b9fa8d64c8c079bfa2
|
scripts/png2raw.py
|
scripts/png2raw.py
|
import Image
import logging
import sys
def main(argv):
pngFileName = sys.argv[1]
baseFileName, _ = pngFileName.rsplit('.')
rawFileName = '%s.raw' % baseFileName
palFileName = '%s.pal' % baseFileName
image = Image.open(pngFileName)
with open(palFileName, 'w') as palFile:
pal = map(chr, image.getpalette())
palFile.write("".join(pal))
with open(rawFileName, 'w') as rawFile:
w, h = image.size
for y in range(h):
for x in range(w):
pixel = image.getpixel((x,y))
rawFile.write(chr(pixel))
if __name__ == '__main__':
FORMAT = '%(levelname)s: %(message)s'
logging.basicConfig(format=FORMAT, level=logging.DEBUG)
main(sys.argv)
|
import Image
import argparse
import os
def main():
parser = argparse.ArgumentParser(
description='Converts input image to raw image and palette data.')
parser.add_argument('-f', '--force', action='store_true',
help='If output files exist, the tool will overwrite them.')
parser.add_argument('input', metavar='INPUT', type=str,
help='Input image filename.')
parser.add_argument('output', metavar='OUTPUT', type=str,
help='Output files basename (without extension).')
args = parser.parse_args()
inputPath = os.path.abspath(args.input)
outputPath = os.path.abspath(args.output)
rawFilePath = '%s.raw' % outputPath
palFilePath = '%s.pal' % outputPath
if not os.path.isfile(inputPath):
raise SystemExit('Input file does not exists!')
if any(map(os.path.isfile, [rawFilePath, palFilePath])) and not args.force:
raise SystemExit('Will not overwrite output files!')
try:
image = Image.open(inputPath)
except IOError as ex:
raise SystemExit('Error: %s.' % ex)
else:
with open(palFilePath, 'w') as palFile:
pal = map(chr, image.getpalette())
palFile.write("".join(pal))
with open(rawFilePath, 'w') as rawFile:
w, h = image.size
for y in range(h):
for x in range(w):
pixel = image.getpixel((x,y))
rawFile.write(chr(pixel))
if __name__ == '__main__':
main()
|
Add cmdline options parser and a sanity check.
|
Add cmdline options parser and a sanity check.
|
Python
|
artistic-2.0
|
cahirwpz/demoscene,cahirwpz/demoscene,cahirwpz/demoscene,cahirwpz/demoscene
|
python
|
## Code Before:
import Image
import logging
import sys
def main(argv):
pngFileName = sys.argv[1]
baseFileName, _ = pngFileName.rsplit('.')
rawFileName = '%s.raw' % baseFileName
palFileName = '%s.pal' % baseFileName
image = Image.open(pngFileName)
with open(palFileName, 'w') as palFile:
pal = map(chr, image.getpalette())
palFile.write("".join(pal))
with open(rawFileName, 'w') as rawFile:
w, h = image.size
for y in range(h):
for x in range(w):
pixel = image.getpixel((x,y))
rawFile.write(chr(pixel))
if __name__ == '__main__':
FORMAT = '%(levelname)s: %(message)s'
logging.basicConfig(format=FORMAT, level=logging.DEBUG)
main(sys.argv)
## Instruction:
Add cmdline options parser and a sanity check.
## Code After:
import Image
import argparse
import os
def main():
parser = argparse.ArgumentParser(
description='Converts input image to raw image and palette data.')
parser.add_argument('-f', '--force', action='store_true',
help='If output files exist, the tool will overwrite them.')
parser.add_argument('input', metavar='INPUT', type=str,
help='Input image filename.')
parser.add_argument('output', metavar='OUTPUT', type=str,
help='Output files basename (without extension).')
args = parser.parse_args()
inputPath = os.path.abspath(args.input)
outputPath = os.path.abspath(args.output)
rawFilePath = '%s.raw' % outputPath
palFilePath = '%s.pal' % outputPath
if not os.path.isfile(inputPath):
raise SystemExit('Input file does not exists!')
if any(map(os.path.isfile, [rawFilePath, palFilePath])) and not args.force:
raise SystemExit('Will not overwrite output files!')
try:
image = Image.open(inputPath)
except IOError as ex:
raise SystemExit('Error: %s.' % ex)
else:
with open(palFilePath, 'w') as palFile:
pal = map(chr, image.getpalette())
palFile.write("".join(pal))
with open(rawFilePath, 'w') as rawFile:
w, h = image.size
for y in range(h):
for x in range(w):
pixel = image.getpixel((x,y))
rawFile.write(chr(pixel))
if __name__ == '__main__':
main()
|
// ... existing code ...
import Image
import argparse
import os
def main():
parser = argparse.ArgumentParser(
description='Converts input image to raw image and palette data.')
parser.add_argument('-f', '--force', action='store_true',
help='If output files exist, the tool will overwrite them.')
parser.add_argument('input', metavar='INPUT', type=str,
help='Input image filename.')
parser.add_argument('output', metavar='OUTPUT', type=str,
help='Output files basename (without extension).')
args = parser.parse_args()
inputPath = os.path.abspath(args.input)
outputPath = os.path.abspath(args.output)
rawFilePath = '%s.raw' % outputPath
palFilePath = '%s.pal' % outputPath
if not os.path.isfile(inputPath):
raise SystemExit('Input file does not exists!')
if any(map(os.path.isfile, [rawFilePath, palFilePath])) and not args.force:
raise SystemExit('Will not overwrite output files!')
try:
image = Image.open(inputPath)
except IOError as ex:
raise SystemExit('Error: %s.' % ex)
else:
with open(palFilePath, 'w') as palFile:
pal = map(chr, image.getpalette())
palFile.write("".join(pal))
with open(rawFilePath, 'w') as rawFile:
w, h = image.size
for y in range(h):
for x in range(w):
pixel = image.getpixel((x,y))
rawFile.write(chr(pixel))
if __name__ == '__main__':
main()
// ... rest of the code ...
|
b97f50bc64ae57ac60b882a9281813c701adc325
|
src/main/java/Main.java
|
src/main/java/Main.java
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
printTitle();
titleWait();
System.out.println("You wake up on a beach.");
}
private static void printTitle() {
String banner = "___________ .__ ___________ __ \n" +
"\\_ _____/_____ |__| ___\\__ ___/___ ___ ____/ |_ \n" +
" | __)_\\____ \\| |/ ___\\| |_/ __ \\\\ \\/ /\\ __\\\n" +
" | \\ |_> > \\ \\___| |\\ ___/ > < | | \n" +
"/_______ / __/|__|\\___ >____| \\___ >__/\\_ \\ |__| \n" +
" \\/|__| \\/ \\/ \\/ ";
System.out.println(banner);
}
private static void titleWait() {
System.out.println("Press \"ENTER\" to continue...");
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
clearScreen();
}
private static void clearScreen() {
}
}
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
printTitle();
titleWait();
System.out.println("You wake up on a beach.");
}
private static void printTitle() {
String banner = "___________ .__ ___________ __ \n" +
"\\_ _____/_____ |__| ___\\__ ___/___ ___ ____/ |_ \n" +
" | __)_\\____ \\| |/ ___\\| |_/ __ \\\\ \\/ /\\ __\\\n" +
" | \\ |_> > \\ \\___| |\\ ___/ > < | | \n" +
"/_______ / __/|__|\\___ >____| \\___ >__/\\_ \\ |__| \n" +
" \\/|__| \\/ \\/ \\/ ";
System.out.println(banner);
}
private static void titleWait() {
System.out.println("Press \"ENTER\" to continue...");
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
clearScreen();
}
private static void clearScreen() {
System.out.println("\n\n\n\n\n\n\n\n\n\n");
}
}
|
Add new line print to clearScreen()
|
Add new line print to clearScreen()
|
Java
|
mit
|
MarkNBroadhead/EpicText
|
java
|
## Code Before:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
printTitle();
titleWait();
System.out.println("You wake up on a beach.");
}
private static void printTitle() {
String banner = "___________ .__ ___________ __ \n" +
"\\_ _____/_____ |__| ___\\__ ___/___ ___ ____/ |_ \n" +
" | __)_\\____ \\| |/ ___\\| |_/ __ \\\\ \\/ /\\ __\\\n" +
" | \\ |_> > \\ \\___| |\\ ___/ > < | | \n" +
"/_______ / __/|__|\\___ >____| \\___ >__/\\_ \\ |__| \n" +
" \\/|__| \\/ \\/ \\/ ";
System.out.println(banner);
}
private static void titleWait() {
System.out.println("Press \"ENTER\" to continue...");
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
clearScreen();
}
private static void clearScreen() {
}
}
## Instruction:
Add new line print to clearScreen()
## Code After:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
printTitle();
titleWait();
System.out.println("You wake up on a beach.");
}
private static void printTitle() {
String banner = "___________ .__ ___________ __ \n" +
"\\_ _____/_____ |__| ___\\__ ___/___ ___ ____/ |_ \n" +
" | __)_\\____ \\| |/ ___\\| |_/ __ \\\\ \\/ /\\ __\\\n" +
" | \\ |_> > \\ \\___| |\\ ___/ > < | | \n" +
"/_______ / __/|__|\\___ >____| \\___ >__/\\_ \\ |__| \n" +
" \\/|__| \\/ \\/ \\/ ";
System.out.println(banner);
}
private static void titleWait() {
System.out.println("Press \"ENTER\" to continue...");
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
clearScreen();
}
private static void clearScreen() {
System.out.println("\n\n\n\n\n\n\n\n\n\n");
}
}
|
// ... existing code ...
}
private static void clearScreen() {
System.out.println("\n\n\n\n\n\n\n\n\n\n");
}
}
// ... rest of the code ...
|
5183ad354943e81787010e3f108b1e819b9f703d
|
quran_tafseer/serializers.py
|
quran_tafseer/serializers.py
|
from django.urls import reverse
from rest_framework import serializers
from .models import Tafseer, TafseerText
class TafseerSerializer(serializers.ModelSerializer):
class Meta:
model = Tafseer
fields = ['id', 'name']
class TafseerTextSerializer(serializers.ModelSerializer):
tafseer_id = serializers.IntegerField(source='tafseer.id')
tafseer_name = serializers.CharField(source='tafseer.name')
ayah_url = serializers.SerializerMethodField()
ayah_number = serializers.IntegerField(source='ayah.number')
def get_ayah_url(self, obj):
return reverse('ayah-detail', kwargs={'number': obj.ayah.number,
'sura_num': obj.ayah.sura.pk})
class Meta:
model = TafseerText
fields = ['tafseer_id', 'tafseer_name', 'ayah_url',
'ayah_number', 'text']
|
from django.urls import reverse
from rest_framework import serializers
from .models import Tafseer, TafseerText
class TafseerSerializer(serializers.ModelSerializer):
class Meta:
model = Tafseer
fields = ['id', 'name', 'language', 'author', 'book_name']
class TafseerTextSerializer(serializers.ModelSerializer):
tafseer_id = serializers.IntegerField(source='tafseer.id')
tafseer_name = serializers.CharField(source='tafseer.name')
ayah_url = serializers.SerializerMethodField()
ayah_number = serializers.IntegerField(source='ayah.number')
def get_ayah_url(self, obj):
return reverse('ayah-detail', kwargs={'number': obj.ayah.number,
'sura_num': obj.ayah.sura.pk})
class Meta:
model = TafseerText
fields = ['tafseer_id', 'tafseer_name', 'ayah_url',
'ayah_number', 'text']
|
Add meta data to Serializer
|
[FIX] Add meta data to Serializer
|
Python
|
mit
|
EmadMokhtar/tafseer_api
|
python
|
## Code Before:
from django.urls import reverse
from rest_framework import serializers
from .models import Tafseer, TafseerText
class TafseerSerializer(serializers.ModelSerializer):
class Meta:
model = Tafseer
fields = ['id', 'name']
class TafseerTextSerializer(serializers.ModelSerializer):
tafseer_id = serializers.IntegerField(source='tafseer.id')
tafseer_name = serializers.CharField(source='tafseer.name')
ayah_url = serializers.SerializerMethodField()
ayah_number = serializers.IntegerField(source='ayah.number')
def get_ayah_url(self, obj):
return reverse('ayah-detail', kwargs={'number': obj.ayah.number,
'sura_num': obj.ayah.sura.pk})
class Meta:
model = TafseerText
fields = ['tafseer_id', 'tafseer_name', 'ayah_url',
'ayah_number', 'text']
## Instruction:
[FIX] Add meta data to Serializer
## Code After:
from django.urls import reverse
from rest_framework import serializers
from .models import Tafseer, TafseerText
class TafseerSerializer(serializers.ModelSerializer):
class Meta:
model = Tafseer
fields = ['id', 'name', 'language', 'author', 'book_name']
class TafseerTextSerializer(serializers.ModelSerializer):
tafseer_id = serializers.IntegerField(source='tafseer.id')
tafseer_name = serializers.CharField(source='tafseer.name')
ayah_url = serializers.SerializerMethodField()
ayah_number = serializers.IntegerField(source='ayah.number')
def get_ayah_url(self, obj):
return reverse('ayah-detail', kwargs={'number': obj.ayah.number,
'sura_num': obj.ayah.sura.pk})
class Meta:
model = TafseerText
fields = ['tafseer_id', 'tafseer_name', 'ayah_url',
'ayah_number', 'text']
|
# ... existing code ...
class Meta:
model = Tafseer
fields = ['id', 'name', 'language', 'author', 'book_name']
class TafseerTextSerializer(serializers.ModelSerializer):
# ... rest of the code ...
|
e0270d78dff4b3e58726465ef464a82ce00738a3
|
utility.py
|
utility.py
|
from datetime import datetime
#our timestamping function, accurate to milliseconds
#(remove [:-3] to display microseconds)
def get_time():
return datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
def rd_print(log, *args, **kwargs):
print(get_time(), *args, **kwargs)
if log:
print(get_time(), *args, **kwargs, file=log, flush=True)
|
from datetime import datetime
#our timestamping function, accurate to milliseconds
#(remove [:-3] to display microseconds)
def get_time():
return datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
def rd_print(log, *args, **kwargs):
print(get_time(), *args, **kwargs)
if log:
print(file=log, flush=True, get_time(), *args, **kwargs)
|
Make rd_print() compatibile with Python 3.4.
|
Make rd_print() compatibile with Python 3.4.
|
Python
|
bsd-2-clause
|
tdaede/rd_tool,tdaede/rd_tool
|
python
|
## Code Before:
from datetime import datetime
#our timestamping function, accurate to milliseconds
#(remove [:-3] to display microseconds)
def get_time():
return datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
def rd_print(log, *args, **kwargs):
print(get_time(), *args, **kwargs)
if log:
print(get_time(), *args, **kwargs, file=log, flush=True)
## Instruction:
Make rd_print() compatibile with Python 3.4.
## Code After:
from datetime import datetime
#our timestamping function, accurate to milliseconds
#(remove [:-3] to display microseconds)
def get_time():
return datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
def rd_print(log, *args, **kwargs):
print(get_time(), *args, **kwargs)
if log:
print(file=log, flush=True, get_time(), *args, **kwargs)
|
...
def rd_print(log, *args, **kwargs):
print(get_time(), *args, **kwargs)
if log:
print(file=log, flush=True, get_time(), *args, **kwargs)
...
|
0128ca2edb48cb58c8a68b4b6e9a8eaeba53518c
|
python/play/dwalk.py
|
python/play/dwalk.py
|
import os
import sys
def dwalk(path, header=''):
print header + '+ ' + path
files = []
dirs = []
for e in os.listdir(path):
epath = os.path.join(path, e)
if os.path.isdir(epath):
# print header + '{} is a dir'.format(e)
dirs.append(e)
else:
# print header + '{} is a file'.format(e)
files.append(e)
# print '{} dirs: {}'.format(header, dirs)
# print '{} files: {}'.format(header, files)
for f in sorted(files):
# print header + '| > ' + os.path.join(path, f)
print header + '| > ' + f
for d in sorted(dirs):
dwalk(os.path.join(path,d), header+'| ')
|
import os
import sys
def dwalk(path, header=''):
print header + '+ ' + path
files = []
dirs = []
for e in os.listdir(path):
epath = os.path.join(path, e)
if os.path.isdir(epath):
# print header + '{} is a dir'.format(e)
dirs.append(e)
else:
# print header + '{} is a file'.format(e)
files.append(e)
# print '{} dirs: {}'.format(header, dirs)
# print '{} files: {}'.format(header, files)
for f in sorted(files):
# print header + '| > ' + os.path.join(path, f)
print header + '| > ' + f
for d in sorted(dirs):
dwalk(os.path.join(path,d), header+'| ')
|
Convert tabs to spaces, and set up vim modeline to expand tabs going forward.
|
Convert tabs to spaces, and set up vim modeline to expand tabs going forward.
|
Python
|
bsd-2-clause
|
tedzo/python_play
|
python
|
## Code Before:
import os
import sys
def dwalk(path, header=''):
print header + '+ ' + path
files = []
dirs = []
for e in os.listdir(path):
epath = os.path.join(path, e)
if os.path.isdir(epath):
# print header + '{} is a dir'.format(e)
dirs.append(e)
else:
# print header + '{} is a file'.format(e)
files.append(e)
# print '{} dirs: {}'.format(header, dirs)
# print '{} files: {}'.format(header, files)
for f in sorted(files):
# print header + '| > ' + os.path.join(path, f)
print header + '| > ' + f
for d in sorted(dirs):
dwalk(os.path.join(path,d), header+'| ')
## Instruction:
Convert tabs to spaces, and set up vim modeline to expand tabs going forward.
## Code After:
import os
import sys
def dwalk(path, header=''):
print header + '+ ' + path
files = []
dirs = []
for e in os.listdir(path):
epath = os.path.join(path, e)
if os.path.isdir(epath):
# print header + '{} is a dir'.format(e)
dirs.append(e)
else:
# print header + '{} is a file'.format(e)
files.append(e)
# print '{} dirs: {}'.format(header, dirs)
# print '{} files: {}'.format(header, files)
for f in sorted(files):
# print header + '| > ' + os.path.join(path, f)
print header + '| > ' + f
for d in sorted(dirs):
dwalk(os.path.join(path,d), header+'| ')
|
// ... existing code ...
files = []
dirs = []
for e in os.listdir(path):
epath = os.path.join(path, e)
if os.path.isdir(epath):
# print header + '{} is a dir'.format(e)
dirs.append(e)
else:
# print header + '{} is a file'.format(e)
files.append(e)
# print '{} dirs: {}'.format(header, dirs)
# print '{} files: {}'.format(header, files)
for f in sorted(files):
# print header + '| > ' + os.path.join(path, f)
print header + '| > ' + f
for d in sorted(dirs):
dwalk(os.path.join(path,d), header+'| ')
// ... rest of the code ...
|
b57be89c94d050dd1e5f4279f91170982b00cc2e
|
polyaxon/clusters/management/commands/clean_experiments.py
|
polyaxon/clusters/management/commands/clean_experiments.py
|
from django.core.management import BaseCommand
from experiments.models import Experiment
from spawner import scheduler
from spawner.utils.constants import ExperimentLifeCycle
class Command(BaseCommand):
def handle(self, *args, **options):
for experiment in Experiment.objects.filter(
experiment_status__status__in=ExperimentLifeCycle.RUNNING_STATUS):
scheduler.stop_experiment(experiment)
|
from django.core.management import BaseCommand
from experiments.models import Experiment
from spawner import scheduler
from spawner.utils.constants import ExperimentLifeCycle
class Command(BaseCommand):
def handle(self, *args, **options):
for experiment in Experiment.objects.filter(
experiment_status__status__in=ExperimentLifeCycle.RUNNING_STATUS):
scheduler.stop_experiment(experiment, update_status=True)
|
Update status when stopping experiments
|
Update status when stopping experiments
|
Python
|
apache-2.0
|
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
|
python
|
## Code Before:
from django.core.management import BaseCommand
from experiments.models import Experiment
from spawner import scheduler
from spawner.utils.constants import ExperimentLifeCycle
class Command(BaseCommand):
def handle(self, *args, **options):
for experiment in Experiment.objects.filter(
experiment_status__status__in=ExperimentLifeCycle.RUNNING_STATUS):
scheduler.stop_experiment(experiment)
## Instruction:
Update status when stopping experiments
## Code After:
from django.core.management import BaseCommand
from experiments.models import Experiment
from spawner import scheduler
from spawner.utils.constants import ExperimentLifeCycle
class Command(BaseCommand):
def handle(self, *args, **options):
for experiment in Experiment.objects.filter(
experiment_status__status__in=ExperimentLifeCycle.RUNNING_STATUS):
scheduler.stop_experiment(experiment, update_status=True)
|
// ... existing code ...
def handle(self, *args, **options):
for experiment in Experiment.objects.filter(
experiment_status__status__in=ExperimentLifeCycle.RUNNING_STATUS):
scheduler.stop_experiment(experiment, update_status=True)
// ... rest of the code ...
|
e784a4ed199001209a43c97b7b55b5aadd26be1b
|
src/main/java/de/innoaccel/wamp/server/message/CallErrorMessage.java
|
src/main/java/de/innoaccel/wamp/server/message/CallErrorMessage.java
|
package de.innoaccel.wamp.server.message;
public class CallErrorMessage implements Message
{
private String callId;
private String errorURI;
private String errorDesc;
private String errorDetails;
public CallErrorMessage(String callId, String errorURI, String errorDesc)
{
this(callId, errorURI, errorDesc, null);
}
public CallErrorMessage(String callId, String errorURI, String errorDesc, String errorDetails)
{
this.callId = callId;
this.errorURI = errorURI;
this.errorDesc = errorDesc;
this.errorDetails = errorDetails;
}
@Override
public int getMessageCode()
{
return Message.CALL_ERROR;
}
public String getCallId()
{
return this.callId;
}
public String getErrorURI()
{
return this.errorURI;
}
public String getErrorDesc()
{
return this.errorDesc;
}
public String getErrorDetails()
{
return this.errorDetails;
}
}
|
package de.innoaccel.wamp.server.message;
public class CallErrorMessage implements Message
{
private String callId;
private String errorURI;
private String errorDesc;
private Object errorDetails;
public CallErrorMessage(String callId, String errorURI, String errorDesc)
{
this(callId, errorURI, errorDesc, null);
}
public CallErrorMessage(String callId, String errorURI, String errorDesc, Object errorDetails)
{
this.callId = callId;
this.errorURI = errorURI;
this.errorDesc = errorDesc;
this.errorDetails = errorDetails;
}
@Override
public int getMessageCode()
{
return Message.CALL_ERROR;
}
public String getCallId()
{
return this.callId;
}
public String getErrorURI()
{
return this.errorURI;
}
public String getErrorDesc()
{
return this.errorDesc;
}
public Object getErrorDetails()
{
return this.errorDetails;
}
}
|
Allow error details to be any type
|
Allow error details to be any type
|
Java
|
bsd-2-clause
|
fritz-gerneth/java-wamp-server
|
java
|
## Code Before:
package de.innoaccel.wamp.server.message;
public class CallErrorMessage implements Message
{
private String callId;
private String errorURI;
private String errorDesc;
private String errorDetails;
public CallErrorMessage(String callId, String errorURI, String errorDesc)
{
this(callId, errorURI, errorDesc, null);
}
public CallErrorMessage(String callId, String errorURI, String errorDesc, String errorDetails)
{
this.callId = callId;
this.errorURI = errorURI;
this.errorDesc = errorDesc;
this.errorDetails = errorDetails;
}
@Override
public int getMessageCode()
{
return Message.CALL_ERROR;
}
public String getCallId()
{
return this.callId;
}
public String getErrorURI()
{
return this.errorURI;
}
public String getErrorDesc()
{
return this.errorDesc;
}
public String getErrorDetails()
{
return this.errorDetails;
}
}
## Instruction:
Allow error details to be any type
## Code After:
package de.innoaccel.wamp.server.message;
public class CallErrorMessage implements Message
{
private String callId;
private String errorURI;
private String errorDesc;
private Object errorDetails;
public CallErrorMessage(String callId, String errorURI, String errorDesc)
{
this(callId, errorURI, errorDesc, null);
}
public CallErrorMessage(String callId, String errorURI, String errorDesc, Object errorDetails)
{
this.callId = callId;
this.errorURI = errorURI;
this.errorDesc = errorDesc;
this.errorDetails = errorDetails;
}
@Override
public int getMessageCode()
{
return Message.CALL_ERROR;
}
public String getCallId()
{
return this.callId;
}
public String getErrorURI()
{
return this.errorURI;
}
public String getErrorDesc()
{
return this.errorDesc;
}
public Object getErrorDetails()
{
return this.errorDetails;
}
}
|
// ... existing code ...
private String errorDesc;
private Object errorDetails;
public CallErrorMessage(String callId, String errorURI, String errorDesc)
{
// ... modified code ...
this(callId, errorURI, errorDesc, null);
}
public CallErrorMessage(String callId, String errorURI, String errorDesc, Object errorDetails)
{
this.callId = callId;
this.errorURI = errorURI;
...
return this.errorDesc;
}
public Object getErrorDetails()
{
return this.errorDetails;
}
// ... rest of the code ...
|
0a2fa84285a586282d79146f85d9efba12a528dd
|
Parallel/Testing/Cxx/TestSockets.py
|
Parallel/Testing/Cxx/TestSockets.py
|
import os, sys, time
# Fork, run server in child, client in parent
pid = os.fork()
if pid == 0:
# exec the parent
os.execv(sys.argv[1], ('-D', sys.argv[3]))
else:
# wait a little to make sure that the server is ready
time.sleep(10)
# run the client
os.system('%s -D %s -V %s' % ( sys.argv[2], sys.argv[3],
sys.argv[4] ))
# in case the client fails, we need to kill the server
# or it will stay around
time.sleep(20)
os.kill(pid, 15)
|
import os, sys, time
# Fork, run server in child, client in parent
pid = os.fork()
if pid == 0:
# exec the parent
os.execv(sys.argv[1], ('-D', sys.argv[3]))
else:
# wait a little to make sure that the server is ready
time.sleep(10)
# run the client
retVal = os.system('%s -D %s -V %s' % ( sys.argv[2], sys.argv[3],
sys.argv[4] ))
# in case the client fails, we need to kill the server
# or it will stay around
time.sleep(20)
os.kill(pid, 15)
sys.exit(os.WEXITSTATUS(retVal))
|
Return code from script must reflect that of the test.
|
BUG: Return code from script must reflect that of the test.
|
Python
|
bsd-3-clause
|
mspark93/VTK,jeffbaumes/jeffbaumes-vtk,demarle/VTK,sumedhasingla/VTK,sankhesh/VTK,mspark93/VTK,keithroe/vtkoptix,daviddoria/PointGraphsPhase1,SimVascular/VTK,collects/VTK,SimVascular/VTK,sumedhasingla/VTK,mspark93/VTK,biddisco/VTK,sgh/vtk,jmerkow/VTK,aashish24/VTK-old,demarle/VTK,demarle/VTK,aashish24/VTK-old,johnkit/vtk-dev,johnkit/vtk-dev,johnkit/vtk-dev,msmolens/VTK,hendradarwin/VTK,SimVascular/VTK,johnkit/vtk-dev,hendradarwin/VTK,cjh1/VTK,demarle/VTK,ashray/VTK-EVM,daviddoria/PointGraphsPhase1,sankhesh/VTK,keithroe/vtkoptix,Wuteyan/VTK,mspark93/VTK,spthaolt/VTK,candy7393/VTK,aashish24/VTK-old,jmerkow/VTK,sgh/vtk,gram526/VTK,Wuteyan/VTK,daviddoria/PointGraphsPhase1,sgh/vtk,spthaolt/VTK,keithroe/vtkoptix,sumedhasingla/VTK,hendradarwin/VTK,berendkleinhaneveld/VTK,ashray/VTK-EVM,berendkleinhaneveld/VTK,jeffbaumes/jeffbaumes-vtk,jmerkow/VTK,sankhesh/VTK,SimVascular/VTK,ashray/VTK-EVM,keithroe/vtkoptix,ashray/VTK-EVM,arnaudgelas/VTK,biddisco/VTK,candy7393/VTK,collects/VTK,sumedhasingla/VTK,berendkleinhaneveld/VTK,jeffbaumes/jeffbaumes-vtk,naucoin/VTKSlicerWidgets,aashish24/VTK-old,Wuteyan/VTK,msmolens/VTK,jmerkow/VTK,cjh1/VTK,jeffbaumes/jeffbaumes-vtk,naucoin/VTKSlicerWidgets,jmerkow/VTK,johnkit/vtk-dev,msmolens/VTK,jmerkow/VTK,spthaolt/VTK,cjh1/VTK,spthaolt/VTK,msmolens/VTK,biddisco/VTK,cjh1/VTK,collects/VTK,arnaudgelas/VTK,Wuteyan/VTK,aashish24/VTK-old,spthaolt/VTK,hendradarwin/VTK,mspark93/VTK,naucoin/VTKSlicerWidgets,naucoin/VTKSlicerWidgets,jeffbaumes/jeffbaumes-vtk,SimVascular/VTK,Wuteyan/VTK,sankhesh/VTK,sankhesh/VTK,hendradarwin/VTK,arnaudgelas/VTK,daviddoria/PointGraphsPhase1,collects/VTK,spthaolt/VTK,Wuteyan/VTK,johnkit/vtk-dev,Wuteyan/VTK,gram526/VTK,candy7393/VTK,candy7393/VTK,candy7393/VTK,keithroe/vtkoptix,keithroe/vtkoptix,sumedhasingla/VTK,sankhesh/VTK,berendkleinhaneveld/VTK,candy7393/VTK,msmolens/VTK,demarle/VTK,sumedhasingla/VTK,berendkleinhaneveld/VTK,msmolens/VTK,ashray/VTK-EVM,daviddoria/PointGraphsPhase1,msmolens/VTK,keithroe/vtkoptix,gram526/VTK,sgh/vtk,sgh/vtk,keithroe/vtkoptix,berendkleinhaneveld/VTK,demarle/VTK,sankhesh/VTK,candy7393/VTK,daviddoria/PointGraphsPhase1,collects/VTK,cjh1/VTK,jeffbaumes/jeffbaumes-vtk,collects/VTK,johnkit/vtk-dev,gram526/VTK,sumedhasingla/VTK,biddisco/VTK,ashray/VTK-EVM,mspark93/VTK,mspark93/VTK,sgh/vtk,demarle/VTK,arnaudgelas/VTK,hendradarwin/VTK,jmerkow/VTK,gram526/VTK,candy7393/VTK,SimVascular/VTK,jmerkow/VTK,aashish24/VTK-old,gram526/VTK,biddisco/VTK,mspark93/VTK,sankhesh/VTK,hendradarwin/VTK,ashray/VTK-EVM,biddisco/VTK,SimVascular/VTK,msmolens/VTK,naucoin/VTKSlicerWidgets,biddisco/VTK,gram526/VTK,cjh1/VTK,ashray/VTK-EVM,SimVascular/VTK,naucoin/VTKSlicerWidgets,arnaudgelas/VTK,arnaudgelas/VTK,spthaolt/VTK,gram526/VTK,sumedhasingla/VTK,berendkleinhaneveld/VTK,demarle/VTK
|
python
|
## Code Before:
import os, sys, time
# Fork, run server in child, client in parent
pid = os.fork()
if pid == 0:
# exec the parent
os.execv(sys.argv[1], ('-D', sys.argv[3]))
else:
# wait a little to make sure that the server is ready
time.sleep(10)
# run the client
os.system('%s -D %s -V %s' % ( sys.argv[2], sys.argv[3],
sys.argv[4] ))
# in case the client fails, we need to kill the server
# or it will stay around
time.sleep(20)
os.kill(pid, 15)
## Instruction:
BUG: Return code from script must reflect that of the test.
## Code After:
import os, sys, time
# Fork, run server in child, client in parent
pid = os.fork()
if pid == 0:
# exec the parent
os.execv(sys.argv[1], ('-D', sys.argv[3]))
else:
# wait a little to make sure that the server is ready
time.sleep(10)
# run the client
retVal = os.system('%s -D %s -V %s' % ( sys.argv[2], sys.argv[3],
sys.argv[4] ))
# in case the client fails, we need to kill the server
# or it will stay around
time.sleep(20)
os.kill(pid, 15)
sys.exit(os.WEXITSTATUS(retVal))
|
...
# wait a little to make sure that the server is ready
time.sleep(10)
# run the client
retVal = os.system('%s -D %s -V %s' % ( sys.argv[2], sys.argv[3],
sys.argv[4] ))
# in case the client fails, we need to kill the server
# or it will stay around
time.sleep(20)
os.kill(pid, 15)
sys.exit(os.WEXITSTATUS(retVal))
...
|
30f74ac44c4ea93c84d856fc166cbbb71ef921a2
|
common/net/minecraftforge/common/ForgeInternalHandler.java
|
common/net/minecraftforge/common/ForgeInternalHandler.java
|
package net.minecraftforge.common;
import java.util.UUID;
import net.minecraft.src.*;
import net.minecraftforge.event.*;
import net.minecraftforge.event.entity.*;
import net.minecraftforge.event.world.WorldEvent;
public class ForgeInternalHandler
{
@ForgeSubscribe(priority = EventPriority.HIGHEST)
public void onEntityJoinWorld(EntityJoinWorldEvent event)
{
if (!event.world.isRemote)
{
if (event.entity.getPersistentID() == null)
{
event.entity.generatePersistentID();
}
else
{
ForgeChunkManager.loadEntity(event.entity);
}
}
Entity entity = event.entity;
if (entity instanceof EntityItem)
{
ItemStack item = ((EntityItem)entity).item;
if (item != null && item.getItem().hasCustomEntity(item))
{
Entity newEntity = item.getItem().createEntity(event.world, entity, item);
if (newEntity != null)
{
entity.setDead();
event.setCanceled(true);
event.world.spawnEntityInWorld(newEntity);
}
}
}
}
@ForgeSubscribe(priority = EventPriority.HIGHEST)
public void onDimensionLoad(WorldEvent.Load event)
{
ForgeChunkManager.loadWorld(event.world);
}
@ForgeSubscribe(priority = EventPriority.HIGHEST)
public void onDimensionSave(WorldEvent.Save event)
{
ForgeChunkManager.saveWorld(event.world);
}
}
|
package net.minecraftforge.common;
import java.util.UUID;
import net.minecraft.src.*;
import net.minecraftforge.event.*;
import net.minecraftforge.event.entity.*;
import net.minecraftforge.event.world.WorldEvent;
public class ForgeInternalHandler
{
@ForgeSubscribe(priority = EventPriority.HIGHEST)
public void onEntityJoinWorld(EntityJoinWorldEvent event)
{
if (!event.world.isRemote)
{
if (event.entity.getPersistentID() == null)
{
event.entity.generatePersistentID();
}
else
{
ForgeChunkManager.loadEntity(event.entity);
}
}
Entity entity = event.entity;
if (entity.getClass().equals(EntityItem.class))
{
ItemStack item = ((EntityItem)entity).item;
if (item != null && item.getItem().hasCustomEntity(item))
{
Entity newEntity = item.getItem().createEntity(event.world, entity, item);
if (newEntity != null)
{
entity.setDead();
event.setCanceled(true);
event.world.spawnEntityInWorld(newEntity);
}
}
}
}
@ForgeSubscribe(priority = EventPriority.HIGHEST)
public void onDimensionLoad(WorldEvent.Load event)
{
ForgeChunkManager.loadWorld(event.world);
}
@ForgeSubscribe(priority = EventPriority.HIGHEST)
public void onDimensionSave(WorldEvent.Save event)
{
ForgeChunkManager.saveWorld(event.world);
}
}
|
Make Item.createEntity only call when its specifically a EntityItem, not a subclass of it.
|
Make Item.createEntity only call when its specifically a EntityItem, not a subclass of it.
|
Java
|
lgpl-2.1
|
CrafterKina/MinecraftForge,Mathe172/MinecraftForge,simon816/MinecraftForge,Zaggy1024/MinecraftForge,Theerapak/MinecraftForge,Ghostlyr/MinecraftForge,jdpadrnos/MinecraftForge,blay09/MinecraftForge,bonii-xx/MinecraftForge,fcjailybo/MinecraftForge,karlthepagan/MinecraftForge,Vorquel/MinecraftForge,brubo1/MinecraftForge,RainWarrior/MinecraftForge,ThiagoGarciaAlves/MinecraftForge,luacs1998/MinecraftForge,dmf444/MinecraftForge,mickkay/MinecraftForge,shadekiller666/MinecraftForge
|
java
|
## Code Before:
package net.minecraftforge.common;
import java.util.UUID;
import net.minecraft.src.*;
import net.minecraftforge.event.*;
import net.minecraftforge.event.entity.*;
import net.minecraftforge.event.world.WorldEvent;
public class ForgeInternalHandler
{
@ForgeSubscribe(priority = EventPriority.HIGHEST)
public void onEntityJoinWorld(EntityJoinWorldEvent event)
{
if (!event.world.isRemote)
{
if (event.entity.getPersistentID() == null)
{
event.entity.generatePersistentID();
}
else
{
ForgeChunkManager.loadEntity(event.entity);
}
}
Entity entity = event.entity;
if (entity instanceof EntityItem)
{
ItemStack item = ((EntityItem)entity).item;
if (item != null && item.getItem().hasCustomEntity(item))
{
Entity newEntity = item.getItem().createEntity(event.world, entity, item);
if (newEntity != null)
{
entity.setDead();
event.setCanceled(true);
event.world.spawnEntityInWorld(newEntity);
}
}
}
}
@ForgeSubscribe(priority = EventPriority.HIGHEST)
public void onDimensionLoad(WorldEvent.Load event)
{
ForgeChunkManager.loadWorld(event.world);
}
@ForgeSubscribe(priority = EventPriority.HIGHEST)
public void onDimensionSave(WorldEvent.Save event)
{
ForgeChunkManager.saveWorld(event.world);
}
}
## Instruction:
Make Item.createEntity only call when its specifically a EntityItem, not a subclass of it.
## Code After:
package net.minecraftforge.common;
import java.util.UUID;
import net.minecraft.src.*;
import net.minecraftforge.event.*;
import net.minecraftforge.event.entity.*;
import net.minecraftforge.event.world.WorldEvent;
public class ForgeInternalHandler
{
@ForgeSubscribe(priority = EventPriority.HIGHEST)
public void onEntityJoinWorld(EntityJoinWorldEvent event)
{
if (!event.world.isRemote)
{
if (event.entity.getPersistentID() == null)
{
event.entity.generatePersistentID();
}
else
{
ForgeChunkManager.loadEntity(event.entity);
}
}
Entity entity = event.entity;
if (entity.getClass().equals(EntityItem.class))
{
ItemStack item = ((EntityItem)entity).item;
if (item != null && item.getItem().hasCustomEntity(item))
{
Entity newEntity = item.getItem().createEntity(event.world, entity, item);
if (newEntity != null)
{
entity.setDead();
event.setCanceled(true);
event.world.spawnEntityInWorld(newEntity);
}
}
}
}
@ForgeSubscribe(priority = EventPriority.HIGHEST)
public void onDimensionLoad(WorldEvent.Load event)
{
ForgeChunkManager.loadWorld(event.world);
}
@ForgeSubscribe(priority = EventPriority.HIGHEST)
public void onDimensionSave(WorldEvent.Save event)
{
ForgeChunkManager.saveWorld(event.world);
}
}
|
// ... existing code ...
}
}
Entity entity = event.entity;
if (entity.getClass().equals(EntityItem.class))
{
ItemStack item = ((EntityItem)entity).item;
if (item != null && item.getItem().hasCustomEntity(item))
// ... rest of the code ...
|
bd2d1869894b30eb83eb11ec6e9814e7ab2d4168
|
panda/api/activity_log.py
|
panda/api/activity_log.py
|
from tastypie import fields
from tastypie.authorization import DjangoAuthorization
from panda.api.utils import PandaApiKeyAuthentication, PandaModelResource, PandaSerializer
from panda.models import ActivityLog
class ActivityLogResource(PandaModelResource):
"""
API resource for DataUploads.
"""
from panda.api.users import UserResource
creator = fields.ForeignKey(UserResource, 'user', full=True)
class Meta:
queryset = ActivityLog.objects.all()
resource_name = 'activity_log'
allowed_methods = ['get', 'post']
authentication = PandaApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = PandaSerializer()
def obj_create(self, bundle, request=None, **kwargs):
"""
Create an activity log for the accessing user.
"""
bundle = super(ActivityLogResource, self).obj_create(bundle, request=request, user=request.user, **kwargs)
return bundle
|
from tastypie import fields
from tastypie.authorization import DjangoAuthorization
from tastypie.exceptions import ImmediateHttpResponse
from tastypie.http import HttpConflict
from panda.api.utils import PandaApiKeyAuthentication, PandaModelResource, PandaSerializer
from django.db import IntegrityError
from panda.models import ActivityLog
class ActivityLogResource(PandaModelResource):
"""
API resource for DataUploads.
"""
from panda.api.users import UserResource
creator = fields.ForeignKey(UserResource, 'user', full=True)
class Meta:
queryset = ActivityLog.objects.all()
resource_name = 'activity_log'
allowed_methods = ['get', 'post']
authentication = PandaApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = PandaSerializer()
def obj_create(self, bundle, request=None, **kwargs):
"""
Create an activity log for the accessing user.
"""
try:
bundle = super(ActivityLogResource, self).obj_create(bundle, request=request, user=request.user, **kwargs)
except IntegrityError:
raise ImmediateHttpResponse(response=HttpConflict('Activity has already been recorded.'))
return bundle
|
Return 409 for duplicate activity logging.
|
Return 409 for duplicate activity logging.
|
Python
|
mit
|
ibrahimcesar/panda,PalmBeachPost/panda,ibrahimcesar/panda,NUKnightLab/panda,pandaproject/panda,datadesk/panda,newsapps/panda,ibrahimcesar/panda,newsapps/panda,pandaproject/panda,PalmBeachPost/panda,PalmBeachPost/panda,NUKnightLab/panda,pandaproject/panda,pandaproject/panda,ibrahimcesar/panda,ibrahimcesar/panda,PalmBeachPost/panda,datadesk/panda,datadesk/panda,NUKnightLab/panda,PalmBeachPost/panda,datadesk/panda,newsapps/panda,NUKnightLab/panda,newsapps/panda,pandaproject/panda,datadesk/panda
|
python
|
## Code Before:
from tastypie import fields
from tastypie.authorization import DjangoAuthorization
from panda.api.utils import PandaApiKeyAuthentication, PandaModelResource, PandaSerializer
from panda.models import ActivityLog
class ActivityLogResource(PandaModelResource):
"""
API resource for DataUploads.
"""
from panda.api.users import UserResource
creator = fields.ForeignKey(UserResource, 'user', full=True)
class Meta:
queryset = ActivityLog.objects.all()
resource_name = 'activity_log'
allowed_methods = ['get', 'post']
authentication = PandaApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = PandaSerializer()
def obj_create(self, bundle, request=None, **kwargs):
"""
Create an activity log for the accessing user.
"""
bundle = super(ActivityLogResource, self).obj_create(bundle, request=request, user=request.user, **kwargs)
return bundle
## Instruction:
Return 409 for duplicate activity logging.
## Code After:
from tastypie import fields
from tastypie.authorization import DjangoAuthorization
from tastypie.exceptions import ImmediateHttpResponse
from tastypie.http import HttpConflict
from panda.api.utils import PandaApiKeyAuthentication, PandaModelResource, PandaSerializer
from django.db import IntegrityError
from panda.models import ActivityLog
class ActivityLogResource(PandaModelResource):
"""
API resource for DataUploads.
"""
from panda.api.users import UserResource
creator = fields.ForeignKey(UserResource, 'user', full=True)
class Meta:
queryset = ActivityLog.objects.all()
resource_name = 'activity_log'
allowed_methods = ['get', 'post']
authentication = PandaApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = PandaSerializer()
def obj_create(self, bundle, request=None, **kwargs):
"""
Create an activity log for the accessing user.
"""
try:
bundle = super(ActivityLogResource, self).obj_create(bundle, request=request, user=request.user, **kwargs)
except IntegrityError:
raise ImmediateHttpResponse(response=HttpConflict('Activity has already been recorded.'))
return bundle
|
...
from tastypie import fields
from tastypie.authorization import DjangoAuthorization
from tastypie.exceptions import ImmediateHttpResponse
from tastypie.http import HttpConflict
from panda.api.utils import PandaApiKeyAuthentication, PandaModelResource, PandaSerializer
from django.db import IntegrityError
from panda.models import ActivityLog
class ActivityLogResource(PandaModelResource):
...
"""
Create an activity log for the accessing user.
"""
try:
bundle = super(ActivityLogResource, self).obj_create(bundle, request=request, user=request.user, **kwargs)
except IntegrityError:
raise ImmediateHttpResponse(response=HttpConflict('Activity has already been recorded.'))
return bundle
...
|
2eb9db36a5a4faec2f804c8a67e2433b7160d77f
|
biz.aQute.bndlib/src/aQute/bnd/connection/settings/SettingsParser.java
|
biz.aQute.bndlib/src/aQute/bnd/connection/settings/SettingsParser.java
|
package aQute.bnd.connection.settings;
import java.io.File;
import aQute.lib.xpath.XPathParser;
public class SettingsParser extends XPathParser {
final SettingsDTO settings = new SettingsDTO();
/*
* <proxies> <proxy> <id>example-proxy</id> <active>true</active>
* <protocol>http</protocol> <host>proxy.example.com</host>
* <port>8080</port> <username>proxyuser</username>
* <password>somepassword</password>
* <nonProxyHosts>www.google.com|*.example.com</nonProxyHosts> </proxy>
* </proxies>
*/
public SettingsParser(File file) throws Exception {
super(file);
parse("/settings/proxies/proxy", ProxyDTO.class, settings.proxies);
parse("/settings/servers/server", ServerDTO.class, settings.servers);
}
public SettingsDTO getSettings() {
return settings;
}
}
|
package aQute.bnd.connection.settings;
import java.io.File;
import aQute.bnd.osgi.Macro;
import aQute.bnd.osgi.Processor;
import aQute.lib.xpath.XPathParser;
public class SettingsParser extends XPathParser {
final SettingsDTO settings = new SettingsDTO();
private final Macro replacer = new Processor().getReplacer();
/*
* <proxies> <proxy> <id>example-proxy</id> <active>true</active>
* <protocol>http</protocol> <host>proxy.example.com</host>
* <port>8080</port> <username>proxyuser</username>
* <password>somepassword</password>
* <nonProxyHosts>www.google.com|*.example.com</nonProxyHosts> </proxy>
* </proxies>
*/
public SettingsParser(File file) throws Exception {
super(file);
parse("/settings/proxies/proxy", ProxyDTO.class, settings.proxies);
parse("/settings/servers/server", ServerDTO.class, settings.servers);
}
public SettingsDTO getSettings() {
return settings;
}
@Override
protected String processValue(String value) {
return replacer.process(value);
}
}
|
Add support for macro replacement in file parsing
|
connection-settings: Add support for macro replacement in file parsing
Macro replacement is limited to system properties and environment
variables. See https://maven.apache.org/settings.html
Signed-off-by: BJ Hargrave <[email protected]>
|
Java
|
apache-2.0
|
psoreide/bnd,psoreide/bnd,psoreide/bnd
|
java
|
## Code Before:
package aQute.bnd.connection.settings;
import java.io.File;
import aQute.lib.xpath.XPathParser;
public class SettingsParser extends XPathParser {
final SettingsDTO settings = new SettingsDTO();
/*
* <proxies> <proxy> <id>example-proxy</id> <active>true</active>
* <protocol>http</protocol> <host>proxy.example.com</host>
* <port>8080</port> <username>proxyuser</username>
* <password>somepassword</password>
* <nonProxyHosts>www.google.com|*.example.com</nonProxyHosts> </proxy>
* </proxies>
*/
public SettingsParser(File file) throws Exception {
super(file);
parse("/settings/proxies/proxy", ProxyDTO.class, settings.proxies);
parse("/settings/servers/server", ServerDTO.class, settings.servers);
}
public SettingsDTO getSettings() {
return settings;
}
}
## Instruction:
connection-settings: Add support for macro replacement in file parsing
Macro replacement is limited to system properties and environment
variables. See https://maven.apache.org/settings.html
Signed-off-by: BJ Hargrave <[email protected]>
## Code After:
package aQute.bnd.connection.settings;
import java.io.File;
import aQute.bnd.osgi.Macro;
import aQute.bnd.osgi.Processor;
import aQute.lib.xpath.XPathParser;
public class SettingsParser extends XPathParser {
final SettingsDTO settings = new SettingsDTO();
private final Macro replacer = new Processor().getReplacer();
/*
* <proxies> <proxy> <id>example-proxy</id> <active>true</active>
* <protocol>http</protocol> <host>proxy.example.com</host>
* <port>8080</port> <username>proxyuser</username>
* <password>somepassword</password>
* <nonProxyHosts>www.google.com|*.example.com</nonProxyHosts> </proxy>
* </proxies>
*/
public SettingsParser(File file) throws Exception {
super(file);
parse("/settings/proxies/proxy", ProxyDTO.class, settings.proxies);
parse("/settings/servers/server", ServerDTO.class, settings.servers);
}
public SettingsDTO getSettings() {
return settings;
}
@Override
protected String processValue(String value) {
return replacer.process(value);
}
}
|
// ... existing code ...
import java.io.File;
import aQute.bnd.osgi.Macro;
import aQute.bnd.osgi.Processor;
import aQute.lib.xpath.XPathParser;
public class SettingsParser extends XPathParser {
final SettingsDTO settings = new SettingsDTO();
private final Macro replacer = new Processor().getReplacer();
/*
* <proxies> <proxy> <id>example-proxy</id> <active>true</active>
// ... modified code ...
public SettingsDTO getSettings() {
return settings;
}
@Override
protected String processValue(String value) {
return replacer.process(value);
}
}
// ... rest of the code ...
|
d0ae779c15cfa916a186dff8872e2a3f4401c2d3
|
snapshots/hacl-c/Random.h
|
snapshots/hacl-c/Random.h
|
/* This file was auto-generated by KreMLin! */
#ifndef __Random_H
#define __Random_H
#include "kremlib.h"
#include "config.h"
#include "drng.h"
#include "cpuid.h"
typedef uint8_t u8;
typedef uint32_t u32;
typedef uint64_t u64;
typedef uint8_t *bytes;
uint32_t random_uint32();
uint64_t random_uint64();
void random_bytes(uint8_t *rand, uint32_t n);
uint32_t randseed_uint32();
uint64_t randseed_uint64();
#endif
|
/* This file was auto-generated by KreMLin! */
#ifndef __Random_H
#define __Random_H
#include "kremlib.h"
#include "config.h"
#include "drng.h"
#include "cpuid.h"
typedef uint8_t u8;
typedef uint32_t u32;
typedef uint64_t u64;
uint32_t random_uint32();
uint64_t random_uint64();
void random_bytes(uint8_t *rand, uint32_t n);
uint32_t randseed_uint32();
uint64_t randseed_uint64();
#endif
|
Remove a redifinition of type 'bytes'
|
Remove a redifinition of type 'bytes'
|
C
|
apache-2.0
|
mitls/hacl-star,mitls/hacl-star,mitls/hacl-star,mitls/hacl-star,mitls/hacl-star,mitls/hacl-star,mitls/hacl-star,mitls/hacl-star,mitls/hacl-star
|
c
|
## Code Before:
/* This file was auto-generated by KreMLin! */
#ifndef __Random_H
#define __Random_H
#include "kremlib.h"
#include "config.h"
#include "drng.h"
#include "cpuid.h"
typedef uint8_t u8;
typedef uint32_t u32;
typedef uint64_t u64;
typedef uint8_t *bytes;
uint32_t random_uint32();
uint64_t random_uint64();
void random_bytes(uint8_t *rand, uint32_t n);
uint32_t randseed_uint32();
uint64_t randseed_uint64();
#endif
## Instruction:
Remove a redifinition of type 'bytes'
## Code After:
/* This file was auto-generated by KreMLin! */
#ifndef __Random_H
#define __Random_H
#include "kremlib.h"
#include "config.h"
#include "drng.h"
#include "cpuid.h"
typedef uint8_t u8;
typedef uint32_t u32;
typedef uint64_t u64;
uint32_t random_uint32();
uint64_t random_uint64();
void random_bytes(uint8_t *rand, uint32_t n);
uint32_t randseed_uint32();
uint64_t randseed_uint64();
#endif
|
// ... existing code ...
typedef uint64_t u64;
uint32_t random_uint32();
uint64_t random_uint64();
// ... rest of the code ...
|
ad60b0cd3326c0729237afbb094d22f4415fb422
|
laboratory/experiment.py
|
laboratory/experiment.py
|
import traceback
from laboratory.observation import Observation, Test
from laboratory import exceptions
class Experiment(object):
def __init__(self, name='Experiment', raise_on_mismatch=False):
self.name = name
self.raise_on_mismatch = raise_on_mismatch
self._control = None
self.observations = []
def control(self):
self._control = Observation('Control')
return Test('Control', True, self._control)
def candidate(self, name='Candidate'):
observation = Observation(name)
self.observations.append(observation)
return Test(name, False, observation)
def run(self):
control = self._control
if control is None:
raise exceptions.LaboratoryException(
'Your experiment must record a control case'
)
match = self.compare(control, *self.observations)
return control.value
def compare(self, control, *candidates):
for observation in candidates:
if observation.failure or control.value != observation.value:
return self._comparison_mismatch(control, observation)
return True
def _comparison_mismatch(self, control, observation):
if self.raise_on_mismatch:
if observation.failure:
msg = '%s raised an exception:\n%s' % (
observation.name, traceback.format_exc(observation.exception)
)
else:
msg = '%s does not match control value (%s != %s)' % (
observation.name, control.value, observation.value
)
raise exceptions.MismatchException(msg)
return False
def publish(self):
raise NotImplementedError
|
import traceback
from laboratory.observation import Observation, Test
from laboratory import exceptions
class Experiment(object):
def __init__(self, name='Experiment', raise_on_mismatch=False):
self.name = name
self.raise_on_mismatch = raise_on_mismatch
self._control = None
self.observations = []
def control(self):
self._control = Observation('Control')
return Test('Control', True, self._control)
def candidate(self, name='Candidate'):
observation = Observation(name)
self.observations.append(observation)
return Test(name, False, observation)
def run(self):
control = self._control
if control is None:
raise exceptions.LaboratoryException(
'Your experiment must record a control case'
)
match = self.compare(control, *self.observations)
self.publish(match)
return control.value
def compare(self, control, *candidates):
for observation in candidates:
if observation.failure or control.value != observation.value:
return self._comparison_mismatch(control, observation)
return True
def _comparison_mismatch(self, control, observation):
if self.raise_on_mismatch:
if observation.failure:
msg = '%s raised an exception:\n%s' % (
observation.name, traceback.format_exc(observation.exception)
)
else:
msg = '%s does not match control value (%s != %s)' % (
observation.name, control.value, observation.value
)
raise exceptions.MismatchException(msg)
return False
def publish(self, match):
return
|
Call Experiment.publish in run method
|
Call Experiment.publish in run method
|
Python
|
mit
|
joealcorn/laboratory,shaunvxc/laboratory
|
python
|
## Code Before:
import traceback
from laboratory.observation import Observation, Test
from laboratory import exceptions
class Experiment(object):
def __init__(self, name='Experiment', raise_on_mismatch=False):
self.name = name
self.raise_on_mismatch = raise_on_mismatch
self._control = None
self.observations = []
def control(self):
self._control = Observation('Control')
return Test('Control', True, self._control)
def candidate(self, name='Candidate'):
observation = Observation(name)
self.observations.append(observation)
return Test(name, False, observation)
def run(self):
control = self._control
if control is None:
raise exceptions.LaboratoryException(
'Your experiment must record a control case'
)
match = self.compare(control, *self.observations)
return control.value
def compare(self, control, *candidates):
for observation in candidates:
if observation.failure or control.value != observation.value:
return self._comparison_mismatch(control, observation)
return True
def _comparison_mismatch(self, control, observation):
if self.raise_on_mismatch:
if observation.failure:
msg = '%s raised an exception:\n%s' % (
observation.name, traceback.format_exc(observation.exception)
)
else:
msg = '%s does not match control value (%s != %s)' % (
observation.name, control.value, observation.value
)
raise exceptions.MismatchException(msg)
return False
def publish(self):
raise NotImplementedError
## Instruction:
Call Experiment.publish in run method
## Code After:
import traceback
from laboratory.observation import Observation, Test
from laboratory import exceptions
class Experiment(object):
def __init__(self, name='Experiment', raise_on_mismatch=False):
self.name = name
self.raise_on_mismatch = raise_on_mismatch
self._control = None
self.observations = []
def control(self):
self._control = Observation('Control')
return Test('Control', True, self._control)
def candidate(self, name='Candidate'):
observation = Observation(name)
self.observations.append(observation)
return Test(name, False, observation)
def run(self):
control = self._control
if control is None:
raise exceptions.LaboratoryException(
'Your experiment must record a control case'
)
match = self.compare(control, *self.observations)
self.publish(match)
return control.value
def compare(self, control, *candidates):
for observation in candidates:
if observation.failure or control.value != observation.value:
return self._comparison_mismatch(control, observation)
return True
def _comparison_mismatch(self, control, observation):
if self.raise_on_mismatch:
if observation.failure:
msg = '%s raised an exception:\n%s' % (
observation.name, traceback.format_exc(observation.exception)
)
else:
msg = '%s does not match control value (%s != %s)' % (
observation.name, control.value, observation.value
)
raise exceptions.MismatchException(msg)
return False
def publish(self, match):
return
|
# ... existing code ...
)
match = self.compare(control, *self.observations)
self.publish(match)
return control.value
def compare(self, control, *candidates):
# ... modified code ...
return False
def publish(self, match):
return
# ... rest of the code ...
|
66b20aa7fbd322a051ab7ae26ecd8c46f7605763
|
ptoolbox/tags.py
|
ptoolbox/tags.py
|
from datetime import datetime
TAG_WIDTH = 'EXIF ExifImageWidth'
TAG_HEIGHT = 'EXIF ExifImageLength'
TAG_DATETIME = 'Image DateTime'
TAG_ORIENTATION = 'Image Orientation'
# XXX: this is a terrible way to retrieve the orientations. Exifread regretfully does not
# get back raw EXIF orientations, and no other library is available on pip as of today.
ORIENTATIONS = [
'Horizontal (normal)',
'Mirrored horizontal',
'Rotated 180',
'Mirrored vertical',
'Mirrored horizontal then rotated 90 CCW',
'Rotated 90 CCW',
'Mirrored horizontal then rotated 90 CW',
'Rotated 90 CW',
]
def parse_time(tags):
tag = tags.get(TAG_DATETIME, None)
if not tag:
raise KeyError(TAG_DATETIME)
return datetime.strptime(str(tag), "%Y:%m:%d %H:%M:%S")
def parse_width(tags):
tag = tags.get(TAG_WIDTH, None)
if not tag:
raise KeyError(TAG_WIDTH)
return int(str(tag), 10)
def parse_height(tags):
tag = tags.get(TAG_HEIGHT, None)
if not tag:
raise KeyError(TAG_HEIGHT)
return int(str(tag), 10)
def parse_orientation(tags):
tag = tags.get(TAG_ORIENTATION, None)
if not tag:
raise KeyError(TAG_ORIENTATION)
return ORIENTATIONS.index(str(tag)) + 1 # XXX: convert back to original EXIF orientation
|
from datetime import datetime
TAG_WIDTH = 'EXIF ExifImageWidth'
TAG_HEIGHT = 'EXIF ExifImageLength'
TAG_DATETIME = 'Image DateTime'
def parse_time(tags):
tag = tags.get(TAG_DATETIME, None)
if not tag:
raise KeyError(TAG_DATETIME)
return datetime.strptime(str(tag), "%Y:%m:%d %H:%M:%S")
def parse_width(tags):
tag = tags.get(TAG_WIDTH, None)
if not tag:
raise KeyError(TAG_WIDTH)
return int(str(tag), 10)
def parse_height(tags):
tag = tags.get(TAG_HEIGHT, None)
if not tag:
raise KeyError(TAG_HEIGHT)
return int(str(tag), 10)
|
Remove orientation tag parsing, not needed.
|
Remove orientation tag parsing, not needed.
|
Python
|
mit
|
vperron/picasa-toolbox
|
python
|
## Code Before:
from datetime import datetime
TAG_WIDTH = 'EXIF ExifImageWidth'
TAG_HEIGHT = 'EXIF ExifImageLength'
TAG_DATETIME = 'Image DateTime'
TAG_ORIENTATION = 'Image Orientation'
# XXX: this is a terrible way to retrieve the orientations. Exifread regretfully does not
# get back raw EXIF orientations, and no other library is available on pip as of today.
ORIENTATIONS = [
'Horizontal (normal)',
'Mirrored horizontal',
'Rotated 180',
'Mirrored vertical',
'Mirrored horizontal then rotated 90 CCW',
'Rotated 90 CCW',
'Mirrored horizontal then rotated 90 CW',
'Rotated 90 CW',
]
def parse_time(tags):
tag = tags.get(TAG_DATETIME, None)
if not tag:
raise KeyError(TAG_DATETIME)
return datetime.strptime(str(tag), "%Y:%m:%d %H:%M:%S")
def parse_width(tags):
tag = tags.get(TAG_WIDTH, None)
if not tag:
raise KeyError(TAG_WIDTH)
return int(str(tag), 10)
def parse_height(tags):
tag = tags.get(TAG_HEIGHT, None)
if not tag:
raise KeyError(TAG_HEIGHT)
return int(str(tag), 10)
def parse_orientation(tags):
tag = tags.get(TAG_ORIENTATION, None)
if not tag:
raise KeyError(TAG_ORIENTATION)
return ORIENTATIONS.index(str(tag)) + 1 # XXX: convert back to original EXIF orientation
## Instruction:
Remove orientation tag parsing, not needed.
## Code After:
from datetime import datetime
TAG_WIDTH = 'EXIF ExifImageWidth'
TAG_HEIGHT = 'EXIF ExifImageLength'
TAG_DATETIME = 'Image DateTime'
def parse_time(tags):
tag = tags.get(TAG_DATETIME, None)
if not tag:
raise KeyError(TAG_DATETIME)
return datetime.strptime(str(tag), "%Y:%m:%d %H:%M:%S")
def parse_width(tags):
tag = tags.get(TAG_WIDTH, None)
if not tag:
raise KeyError(TAG_WIDTH)
return int(str(tag), 10)
def parse_height(tags):
tag = tags.get(TAG_HEIGHT, None)
if not tag:
raise KeyError(TAG_HEIGHT)
return int(str(tag), 10)
|
# ... existing code ...
TAG_WIDTH = 'EXIF ExifImageWidth'
TAG_HEIGHT = 'EXIF ExifImageLength'
TAG_DATETIME = 'Image DateTime'
def parse_time(tags):
tag = tags.get(TAG_DATETIME, None)
# ... modified code ...
if not tag:
raise KeyError(TAG_HEIGHT)
return int(str(tag), 10)
# ... rest of the code ...
|
33505f9b4dfeead0b01ee1b8cf3f8f228476e866
|
openpassword/crypt_utils.py
|
openpassword/crypt_utils.py
|
from Crypto.Cipher import AES
def decrypt(data, key_iv):
key = key_iv[0:16]
iv = key_iv[16:]
print(data)
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.decrypt(data)
def encrypt(data, key_iv):
key = key_iv[0:16]
iv = key_iv[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.encrypt(data)
|
from Crypto.Cipher import AES
def decrypt(data, key_iv):
key = key_iv[0:16]
iv = key_iv[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.decrypt(data)
def encrypt(data, key_iv):
key = key_iv[0:16]
iv = key_iv[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.encrypt(data)
|
Remove print statement from crypto utils...
|
Remove print statement from crypto utils...
|
Python
|
mit
|
openpassword/blimey,openpassword/blimey
|
python
|
## Code Before:
from Crypto.Cipher import AES
def decrypt(data, key_iv):
key = key_iv[0:16]
iv = key_iv[16:]
print(data)
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.decrypt(data)
def encrypt(data, key_iv):
key = key_iv[0:16]
iv = key_iv[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.encrypt(data)
## Instruction:
Remove print statement from crypto utils...
## Code After:
from Crypto.Cipher import AES
def decrypt(data, key_iv):
key = key_iv[0:16]
iv = key_iv[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.decrypt(data)
def encrypt(data, key_iv):
key = key_iv[0:16]
iv = key_iv[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.encrypt(data)
|
...
def decrypt(data, key_iv):
key = key_iv[0:16]
iv = key_iv[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.decrypt(data)
...
|
0315f2b47261cfabe11b2668225ec1bc19e5493c
|
vispy_volume/tests/test_vispy_widget.py
|
vispy_volume/tests/test_vispy_widget.py
|
import numpy as np
from ..vispy_widget import QtVispyWidget
from glue.qt import get_qapp
class Event(object):
def __init__(self, text):
self.text = text
def test_widget():
# Make sure QApplication is started
get_qapp()
# Create fake data
data = np.arange(1000).reshape((10,10,10))
# Set up widget
w = QtVispyWidget()
w.set_data(data)
w.set_canvas()
w.canvas.render()
# Test changing colormap
w.set_colormap()
# Test key presses
w.on_key_press(Event(text='1'))
w.on_key_press(Event(text='2'))
w.on_key_press(Event(text='3'))
#Test mouse_wheel
w.on_mouse_wheel(Event(type=mouse_wheel)
|
import numpy as np
from ..vispy_widget import QtVispyWidget
from glue.qt import get_qapp
class KeyEvent(object):
def __init__(self, text):
self.text = text
class MouseEvent(object):
def __init__(self, delta, type):
self.type = type
self.delta = delta
def test_widget():
# Make sure QApplication is started
get_qapp()
# Create fake data
data = np.arange(1000).reshape((10,10,10))
# Set up widget
w = QtVispyWidget()
w.set_data(data)
w.set_canvas()
w.canvas.render()
# Test changing colormap
w.set_colormap()
# Test key presses
w.on_key_press(KeyEvent(text='1'))
w.on_key_press(KeyEvent(text='2'))
w.on_key_press(KeyEvent(text='3'))
#Test mouse_wheel
w.on_mouse_wheel(MouseEvent(type='mouse_wheel', delta=(0, 0.5)))
w.on_mouse_wheel(MouseEvent(type='mouse_wheel', delta=(0, -0.3)))
|
Fix the mouse_wheel test unit
|
Fix the mouse_wheel test unit
|
Python
|
bsd-2-clause
|
astrofrog/glue-3d-viewer,PennyQ/astro-vispy,PennyQ/glue-3d-viewer,astrofrog/glue-vispy-viewers,glue-viz/glue-3d-viewer,glue-viz/glue-vispy-viewers
|
python
|
## Code Before:
import numpy as np
from ..vispy_widget import QtVispyWidget
from glue.qt import get_qapp
class Event(object):
def __init__(self, text):
self.text = text
def test_widget():
# Make sure QApplication is started
get_qapp()
# Create fake data
data = np.arange(1000).reshape((10,10,10))
# Set up widget
w = QtVispyWidget()
w.set_data(data)
w.set_canvas()
w.canvas.render()
# Test changing colormap
w.set_colormap()
# Test key presses
w.on_key_press(Event(text='1'))
w.on_key_press(Event(text='2'))
w.on_key_press(Event(text='3'))
#Test mouse_wheel
w.on_mouse_wheel(Event(type=mouse_wheel)
## Instruction:
Fix the mouse_wheel test unit
## Code After:
import numpy as np
from ..vispy_widget import QtVispyWidget
from glue.qt import get_qapp
class KeyEvent(object):
def __init__(self, text):
self.text = text
class MouseEvent(object):
def __init__(self, delta, type):
self.type = type
self.delta = delta
def test_widget():
# Make sure QApplication is started
get_qapp()
# Create fake data
data = np.arange(1000).reshape((10,10,10))
# Set up widget
w = QtVispyWidget()
w.set_data(data)
w.set_canvas()
w.canvas.render()
# Test changing colormap
w.set_colormap()
# Test key presses
w.on_key_press(KeyEvent(text='1'))
w.on_key_press(KeyEvent(text='2'))
w.on_key_press(KeyEvent(text='3'))
#Test mouse_wheel
w.on_mouse_wheel(MouseEvent(type='mouse_wheel', delta=(0, 0.5)))
w.on_mouse_wheel(MouseEvent(type='mouse_wheel', delta=(0, -0.3)))
|
...
from glue.qt import get_qapp
class KeyEvent(object):
def __init__(self, text):
self.text = text
class MouseEvent(object):
def __init__(self, delta, type):
self.type = type
self.delta = delta
def test_widget():
...
w.set_colormap()
# Test key presses
w.on_key_press(KeyEvent(text='1'))
w.on_key_press(KeyEvent(text='2'))
w.on_key_press(KeyEvent(text='3'))
#Test mouse_wheel
w.on_mouse_wheel(MouseEvent(type='mouse_wheel', delta=(0, 0.5)))
w.on_mouse_wheel(MouseEvent(type='mouse_wheel', delta=(0, -0.3)))
...
|
59764c6d3621423c9d4e136e99a69078a79ca6f5
|
numpy/distutils/checks/cpu_popcnt.c
|
numpy/distutils/checks/cpu_popcnt.c
|
#include <nmmintrin.h>
#else
#include <popcntintrin.h>
#endif
int main(void)
{
long long a = 0;
int b;
#ifdef _MSC_VER
#ifdef _M_X64
a = _mm_popcnt_u64(1);
#endif
b = _mm_popcnt_u32(1);
#else
#ifdef __x86_64__
a = __builtin_popcountll(1);
#endif
b = __builtin_popcount(1);
#endif
return (int)a + b;
}
|
#include <nmmintrin.h>
#else
#include <popcntintrin.h>
#endif
#include <stdlib.h>
int main(void)
{
long long a = 0;
int b;
a = random();
b = random();
#ifdef _MSC_VER
#ifdef _M_X64
a = _mm_popcnt_u64(a);
#endif
b = _mm_popcnt_u32(b);
#else
#ifdef __x86_64__
a = __builtin_popcountll(a);
#endif
b = __builtin_popcount(b);
#endif
return (int)a + b;
}
|
Fix compile-time test of POPCNT
|
Fix compile-time test of POPCNT
The compile-time test of POPCNT, cpu_popcnt.c produced code that would
execute without error even if the machine didn't support the popcnt
instruction. This patch attempts to use popcnt on random numbers so the
compiler can't substitute the answer at compile time.
|
C
|
bsd-3-clause
|
seberg/numpy,anntzer/numpy,simongibbons/numpy,charris/numpy,mattip/numpy,mattip/numpy,mhvk/numpy,jakirkham/numpy,anntzer/numpy,numpy/numpy,rgommers/numpy,mhvk/numpy,seberg/numpy,pdebuyl/numpy,pdebuyl/numpy,endolith/numpy,mhvk/numpy,rgommers/numpy,mhvk/numpy,endolith/numpy,charris/numpy,anntzer/numpy,jakirkham/numpy,rgommers/numpy,rgommers/numpy,jakirkham/numpy,charris/numpy,anntzer/numpy,endolith/numpy,mattip/numpy,numpy/numpy,charris/numpy,jakirkham/numpy,mhvk/numpy,mattip/numpy,simongibbons/numpy,pdebuyl/numpy,simongibbons/numpy,seberg/numpy,pdebuyl/numpy,simongibbons/numpy,numpy/numpy,simongibbons/numpy,seberg/numpy,numpy/numpy,endolith/numpy,jakirkham/numpy
|
c
|
## Code Before:
#include <nmmintrin.h>
#else
#include <popcntintrin.h>
#endif
int main(void)
{
long long a = 0;
int b;
#ifdef _MSC_VER
#ifdef _M_X64
a = _mm_popcnt_u64(1);
#endif
b = _mm_popcnt_u32(1);
#else
#ifdef __x86_64__
a = __builtin_popcountll(1);
#endif
b = __builtin_popcount(1);
#endif
return (int)a + b;
}
## Instruction:
Fix compile-time test of POPCNT
The compile-time test of POPCNT, cpu_popcnt.c produced code that would
execute without error even if the machine didn't support the popcnt
instruction. This patch attempts to use popcnt on random numbers so the
compiler can't substitute the answer at compile time.
## Code After:
#include <nmmintrin.h>
#else
#include <popcntintrin.h>
#endif
#include <stdlib.h>
int main(void)
{
long long a = 0;
int b;
a = random();
b = random();
#ifdef _MSC_VER
#ifdef _M_X64
a = _mm_popcnt_u64(a);
#endif
b = _mm_popcnt_u32(b);
#else
#ifdef __x86_64__
a = __builtin_popcountll(a);
#endif
b = __builtin_popcount(b);
#endif
return (int)a + b;
}
|
// ... existing code ...
#include <popcntintrin.h>
#endif
#include <stdlib.h>
int main(void)
{
long long a = 0;
int b;
a = random();
b = random();
#ifdef _MSC_VER
#ifdef _M_X64
a = _mm_popcnt_u64(a);
#endif
b = _mm_popcnt_u32(b);
#else
#ifdef __x86_64__
a = __builtin_popcountll(a);
#endif
b = __builtin_popcount(b);
#endif
return (int)a + b;
}
// ... rest of the code ...
|
182f070c69e59907eeda3c261d833a492af46967
|
rojak-database/generate_media_data.py
|
rojak-database/generate_media_data.py
|
import MySQLdb as mysql
from faker import Factory
# Open database connection
db = mysql.connect('localhost', 'root', 'rojak', 'rojak_database')
# Create new db cursor
cursor = db.cursor()
sql = '''
INSERT INTO `media`(`name`, `website_url`, `logo_url`, `facebookpage_url`,
`slogan`)
VALUES ('{}', '{}', '{}', '{}', '{}');
'''
MAX_MEDIA=100
fake = Factory.create('it_IT')
for i in xrange(MAX_MEDIA):
# Generate random data for the media
media_name = fake.name() + ' Media ' + str(i)
website_name = media_name.lower().replace(' ', '')
website_name = website_name.replace("'", '')
website_url = 'https://{}.com'.format(website_name)
cat_txt = website_name
cat_img = 'http://lorempixel.com/500/500/cats/{}'.format(cat_txt)
logo_url = cat_img
facebookpage_url = 'https://facebook.com/{}'.format(website_name)
slogan = ' '.join(fake.text().split()[:5])
# Parse the SQL command
insert_sql = sql.format(media_name, website_url, logo_url,
facebookpage_url, slogan)
# insert to the database
try:
cursor.execute(insert_sql)
db.commit()
except mysql.Error as err:
print("Something went wrong: {}".format(err))
db.rollback()
# Close the DB connection
db.close()
|
import MySQLdb as mysql
from faker import Factory
# Open database connection
db = mysql.connect('localhost', 'root', 'rojak', 'rojak_database')
# Create new db cursor
cursor = db.cursor()
sql = '''
INSERT INTO `media`(`name`, `website_url`, `logo_url`, `facebookpage_url`,
`slogan`)
VALUES ('{}', '{}', '{}', '{}', '{}');
'''
MAX_MEDIA=100
fake = Factory.create()
for i in xrange(MAX_MEDIA):
# Generate random data for the media
media_name = fake.name() + ' Media ' + str(i)
website_name = media_name.lower().replace(' ', '')
website_url = 'https://{}.com'.format(website_name)
cat_txt = website_name
cat_img = 'http://lorempixel.com/500/500/cats/{}'.format(cat_txt)
logo_url = cat_img
facebookpage_url = 'https://facebook.com/{}'.format(website_name)
slogan = ' '.join(fake.text().split()[:5])
# Parse the SQL command
insert_sql = sql.format(media_name, website_url, logo_url,
facebookpage_url, slogan)
# insert to the database
try:
cursor.execute(insert_sql)
db.commit()
except mysql.Error as err:
print("Something went wrong: {}".format(err))
db.rollback()
# Close the DB connection
db.close()
|
Update the default language for the media generator
|
Update the default language for the media generator
|
Python
|
bsd-3-clause
|
CodeRiderz/rojak,bobbypriambodo/rojak,reinarduswindy/rojak,CodeRiderz/rojak,bobbypriambodo/rojak,reinarduswindy/rojak,bobbypriambodo/rojak,reinarduswindy/rojak,CodeRiderz/rojak,pyk/rojak,pyk/rojak,bobbypriambodo/rojak,pyk/rojak,bobbypriambodo/rojak,rawgni/rojak,bobbypriambodo/rojak,CodeRiderz/rojak,pyk/rojak,pyk/rojak,CodeRiderz/rojak,rawgni/rojak,pyk/rojak,rawgni/rojak,rawgni/rojak,rawgni/rojak,pyk/rojak,reinarduswindy/rojak,reinarduswindy/rojak,CodeRiderz/rojak,CodeRiderz/rojak,rawgni/rojak,rawgni/rojak,reinarduswindy/rojak,reinarduswindy/rojak,bobbypriambodo/rojak
|
python
|
## Code Before:
import MySQLdb as mysql
from faker import Factory
# Open database connection
db = mysql.connect('localhost', 'root', 'rojak', 'rojak_database')
# Create new db cursor
cursor = db.cursor()
sql = '''
INSERT INTO `media`(`name`, `website_url`, `logo_url`, `facebookpage_url`,
`slogan`)
VALUES ('{}', '{}', '{}', '{}', '{}');
'''
MAX_MEDIA=100
fake = Factory.create('it_IT')
for i in xrange(MAX_MEDIA):
# Generate random data for the media
media_name = fake.name() + ' Media ' + str(i)
website_name = media_name.lower().replace(' ', '')
website_name = website_name.replace("'", '')
website_url = 'https://{}.com'.format(website_name)
cat_txt = website_name
cat_img = 'http://lorempixel.com/500/500/cats/{}'.format(cat_txt)
logo_url = cat_img
facebookpage_url = 'https://facebook.com/{}'.format(website_name)
slogan = ' '.join(fake.text().split()[:5])
# Parse the SQL command
insert_sql = sql.format(media_name, website_url, logo_url,
facebookpage_url, slogan)
# insert to the database
try:
cursor.execute(insert_sql)
db.commit()
except mysql.Error as err:
print("Something went wrong: {}".format(err))
db.rollback()
# Close the DB connection
db.close()
## Instruction:
Update the default language for the media generator
## Code After:
import MySQLdb as mysql
from faker import Factory
# Open database connection
db = mysql.connect('localhost', 'root', 'rojak', 'rojak_database')
# Create new db cursor
cursor = db.cursor()
sql = '''
INSERT INTO `media`(`name`, `website_url`, `logo_url`, `facebookpage_url`,
`slogan`)
VALUES ('{}', '{}', '{}', '{}', '{}');
'''
MAX_MEDIA=100
fake = Factory.create()
for i in xrange(MAX_MEDIA):
# Generate random data for the media
media_name = fake.name() + ' Media ' + str(i)
website_name = media_name.lower().replace(' ', '')
website_url = 'https://{}.com'.format(website_name)
cat_txt = website_name
cat_img = 'http://lorempixel.com/500/500/cats/{}'.format(cat_txt)
logo_url = cat_img
facebookpage_url = 'https://facebook.com/{}'.format(website_name)
slogan = ' '.join(fake.text().split()[:5])
# Parse the SQL command
insert_sql = sql.format(media_name, website_url, logo_url,
facebookpage_url, slogan)
# insert to the database
try:
cursor.execute(insert_sql)
db.commit()
except mysql.Error as err:
print("Something went wrong: {}".format(err))
db.rollback()
# Close the DB connection
db.close()
|
# ... existing code ...
'''
MAX_MEDIA=100
fake = Factory.create()
for i in xrange(MAX_MEDIA):
# Generate random data for the media
media_name = fake.name() + ' Media ' + str(i)
website_name = media_name.lower().replace(' ', '')
website_url = 'https://{}.com'.format(website_name)
cat_txt = website_name
cat_img = 'http://lorempixel.com/500/500/cats/{}'.format(cat_txt)
# ... rest of the code ...
|
33b5e210ffc32f9f7b3764e1f6f3d54e1f040783
|
changes/flow.py
|
changes/flow.py
|
import logging
from plumbum import local, CommandNotFound
from changes.changelog import generate_changelog
from changes.packaging import build_package, install_package, upload_package, install_from_pypi
from changes.vcs import tag_and_push, commit_version_change
from changes.verification import run_tests
from changes.version import increment_version
log = logging.getLogger(__name__)
def perform_release(context):
"""Executes the release process."""
try:
run_tests()
if not context.skip_changelog:
generate_changelog(context)
increment_version(context)
build_package(context)
install_package(context)
upload_package(context)
install_from_pypi(context)
commit_version_change(context)
tag_and_push(context)
except:
log.exception('Error releasing')
|
import logging
import click
from changes.changelog import generate_changelog
from changes.config import project_config, store_settings
from changes.packaging import build_distributions, install_package, upload_package, install_from_pypi
from changes.vcs import tag_and_push, commit_version_change, create_github_release, upload_release_distributions
from changes.verification import run_tests
from changes.version import increment_version
log = logging.getLogger(__name__)
def publish(context):
"""Publishes the project"""
commit_version_change(context)
if context.github:
# github token
project_settings = project_config(context.module_name)
if not project_settings['gh_token']:
click.echo('You need a GitHub token for changes to create a release.')
click.pause('Press [enter] to launch the GitHub "New personal access '
'token" page, to create a token for changes.')
click.launch('https://github.com/settings/tokens/new')
project_settings['gh_token'] = click.prompt('Enter your changes token')
store_settings(context.module_name, project_settings)
description = click.prompt('Describe this release')
upload_url = create_github_release(context, project_settings['gh_token'], description)
upload_release_distributions(
context,
project_settings['gh_token'],
build_distributions(context),
upload_url,
)
click.pause('Press [enter] to review and update your new release')
click.launch('{0}/releases/tag/{1}'.format(context.repo_url, context.new_version))
else:
tag_and_push(context)
def perform_release(context):
"""Executes the release process."""
try:
run_tests()
if not context.skip_changelog:
generate_changelog(context)
increment_version(context)
build_distributions(context)
install_package(context)
upload_package(context)
install_from_pypi(context)
publish(context)
except:
log.exception('Error releasing')
|
Add github releases to publishing
|
Add github releases to publishing
|
Python
|
mit
|
goldsborough/changes
|
python
|
## Code Before:
import logging
from plumbum import local, CommandNotFound
from changes.changelog import generate_changelog
from changes.packaging import build_package, install_package, upload_package, install_from_pypi
from changes.vcs import tag_and_push, commit_version_change
from changes.verification import run_tests
from changes.version import increment_version
log = logging.getLogger(__name__)
def perform_release(context):
"""Executes the release process."""
try:
run_tests()
if not context.skip_changelog:
generate_changelog(context)
increment_version(context)
build_package(context)
install_package(context)
upload_package(context)
install_from_pypi(context)
commit_version_change(context)
tag_and_push(context)
except:
log.exception('Error releasing')
## Instruction:
Add github releases to publishing
## Code After:
import logging
import click
from changes.changelog import generate_changelog
from changes.config import project_config, store_settings
from changes.packaging import build_distributions, install_package, upload_package, install_from_pypi
from changes.vcs import tag_and_push, commit_version_change, create_github_release, upload_release_distributions
from changes.verification import run_tests
from changes.version import increment_version
log = logging.getLogger(__name__)
def publish(context):
"""Publishes the project"""
commit_version_change(context)
if context.github:
# github token
project_settings = project_config(context.module_name)
if not project_settings['gh_token']:
click.echo('You need a GitHub token for changes to create a release.')
click.pause('Press [enter] to launch the GitHub "New personal access '
'token" page, to create a token for changes.')
click.launch('https://github.com/settings/tokens/new')
project_settings['gh_token'] = click.prompt('Enter your changes token')
store_settings(context.module_name, project_settings)
description = click.prompt('Describe this release')
upload_url = create_github_release(context, project_settings['gh_token'], description)
upload_release_distributions(
context,
project_settings['gh_token'],
build_distributions(context),
upload_url,
)
click.pause('Press [enter] to review and update your new release')
click.launch('{0}/releases/tag/{1}'.format(context.repo_url, context.new_version))
else:
tag_and_push(context)
def perform_release(context):
"""Executes the release process."""
try:
run_tests()
if not context.skip_changelog:
generate_changelog(context)
increment_version(context)
build_distributions(context)
install_package(context)
upload_package(context)
install_from_pypi(context)
publish(context)
except:
log.exception('Error releasing')
|
...
import logging
import click
from changes.changelog import generate_changelog
from changes.config import project_config, store_settings
from changes.packaging import build_distributions, install_package, upload_package, install_from_pypi
from changes.vcs import tag_and_push, commit_version_change, create_github_release, upload_release_distributions
from changes.verification import run_tests
from changes.version import increment_version
log = logging.getLogger(__name__)
def publish(context):
"""Publishes the project"""
commit_version_change(context)
if context.github:
# github token
project_settings = project_config(context.module_name)
if not project_settings['gh_token']:
click.echo('You need a GitHub token for changes to create a release.')
click.pause('Press [enter] to launch the GitHub "New personal access '
'token" page, to create a token for changes.')
click.launch('https://github.com/settings/tokens/new')
project_settings['gh_token'] = click.prompt('Enter your changes token')
store_settings(context.module_name, project_settings)
description = click.prompt('Describe this release')
upload_url = create_github_release(context, project_settings['gh_token'], description)
upload_release_distributions(
context,
project_settings['gh_token'],
build_distributions(context),
upload_url,
)
click.pause('Press [enter] to review and update your new release')
click.launch('{0}/releases/tag/{1}'.format(context.repo_url, context.new_version))
else:
tag_and_push(context)
def perform_release(context):
...
if not context.skip_changelog:
generate_changelog(context)
increment_version(context)
build_distributions(context)
install_package(context)
upload_package(context)
install_from_pypi(context)
publish(context)
except:
log.exception('Error releasing')
...
|
dd27eea0ea43447dad321b4b9ec88f24e5ada268
|
asv/__init__.py
|
asv/__init__.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
import sys
if sys.version_info >= (3, 3):
# OS X framework builds of Python 3.3 can not call other 3.3
# virtualenvs as a subprocess because `__PYENV_LAUNCHER__` is
# inherited.
if os.environ.get('__PYVENV_LAUNCHER__'):
os.unsetenv('__PYVENV_LAUNCHER__')
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
import sys
if sys.version_info >= (3, 3):
# OS X framework builds of Python 3.3 can not call other 3.3
# virtualenvs as a subprocess because `__PYENV_LAUNCHER__` is
# inherited.
if os.environ.get('__PYVENV_LAUNCHER__'):
os.unsetenv('__PYVENV_LAUNCHER__')
def check_version_compatibility():
"""
Performs a number of compatibility checks with third-party
libraries.
"""
from distutils.version import LooseVersion
if sys.version_info[0] == 3:
import virtualenv
if LooseVersion(virtualenv.__version__) == LooseVersion('1.11'):
raise RuntimeError("asv is not compatible with Python 3.x and virtualenv 1.11")
check_version_compatibility()
|
Add version check for incompatible Python 3.x/virtualenv 1.11 combination
|
Add version check for incompatible Python 3.x/virtualenv 1.11 combination
|
Python
|
bsd-3-clause
|
pv/asv,mdboom/asv,airspeed-velocity/asv,waylonflinn/asv,airspeed-velocity/asv,giltis/asv,cpcloud/asv,spacetelescope/asv,mdboom/asv,giltis/asv,edisongustavo/asv,qwhelan/asv,airspeed-velocity/asv,pv/asv,cpcloud/asv,airspeed-velocity/asv,spacetelescope/asv,mdboom/asv,ericdill/asv,ericdill/asv,pv/asv,cpcloud/asv,mdboom/asv,edisongustavo/asv,qwhelan/asv,pv/asv,qwhelan/asv,spacetelescope/asv,edisongustavo/asv,ericdill/asv,spacetelescope/asv,ericdill/asv,qwhelan/asv,waylonflinn/asv,giltis/asv,waylonflinn/asv
|
python
|
## Code Before:
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
import sys
if sys.version_info >= (3, 3):
# OS X framework builds of Python 3.3 can not call other 3.3
# virtualenvs as a subprocess because `__PYENV_LAUNCHER__` is
# inherited.
if os.environ.get('__PYVENV_LAUNCHER__'):
os.unsetenv('__PYVENV_LAUNCHER__')
## Instruction:
Add version check for incompatible Python 3.x/virtualenv 1.11 combination
## Code After:
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
import sys
if sys.version_info >= (3, 3):
# OS X framework builds of Python 3.3 can not call other 3.3
# virtualenvs as a subprocess because `__PYENV_LAUNCHER__` is
# inherited.
if os.environ.get('__PYVENV_LAUNCHER__'):
os.unsetenv('__PYVENV_LAUNCHER__')
def check_version_compatibility():
"""
Performs a number of compatibility checks with third-party
libraries.
"""
from distutils.version import LooseVersion
if sys.version_info[0] == 3:
import virtualenv
if LooseVersion(virtualenv.__version__) == LooseVersion('1.11'):
raise RuntimeError("asv is not compatible with Python 3.x and virtualenv 1.11")
check_version_compatibility()
|
// ... existing code ...
# inherited.
if os.environ.get('__PYVENV_LAUNCHER__'):
os.unsetenv('__PYVENV_LAUNCHER__')
def check_version_compatibility():
"""
Performs a number of compatibility checks with third-party
libraries.
"""
from distutils.version import LooseVersion
if sys.version_info[0] == 3:
import virtualenv
if LooseVersion(virtualenv.__version__) == LooseVersion('1.11'):
raise RuntimeError("asv is not compatible with Python 3.x and virtualenv 1.11")
check_version_compatibility()
// ... rest of the code ...
|
b280771f37b5535cee61ab636f2f3256d6c18cee
|
setup.py
|
setup.py
|
from distutils.core import setup
from platform import python_version_tuple
import re
LICENSE = open("LICENSE").read()
# strip links from the descripton on the PyPI
LONG_DESCRIPTION = open("README.rst").read().replace("`_", "`")
# strip Build Status from the PyPI package
if python_version_tuple()[:2] >= ('2', '7'):
LONG_DESCRIPTION = re.sub("^Build status\n(.*\n){7}", "", LONG_DESCRIPTION, flags=re.M)
setup(name='tabulate',
version='0.7.3',
description='Pretty-print tabular data',
long_description=LONG_DESCRIPTION,
author='Sergey Astanin',
author_email='[email protected]',
url='https://bitbucket.org/astanin/python-tabulate',
license=LICENSE,
classifiers= [ "Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Topic :: Software Development :: Libraries" ],
py_modules = ['tabulate'])
|
from distutils.core import setup
from platform import python_version_tuple
import re
LICENSE = open("LICENSE").read()
# strip links from the descripton on the PyPI
LONG_DESCRIPTION = open("README.rst").read().replace("`_", "`")
# strip Build Status from the PyPI package
if python_version_tuple()[:2] >= ('2', '7'):
LONG_DESCRIPTION = re.sub("^Build status\n(.*\n){7}", "", LONG_DESCRIPTION, flags=re.M)
setup(name='tabulate',
version='0.7.3',
description='Pretty-print tabular data',
long_description=LONG_DESCRIPTION,
author='Sergey Astanin',
author_email='[email protected]',
url='https://bitbucket.org/astanin/python-tabulate',
license=LICENSE,
classifiers= [ "Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: Software Development :: Libraries" ],
py_modules = ['tabulate'])
|
Add Python 3.4 to classifiers
|
Add Python 3.4 to classifiers
All tests passed on Python 3.4.
|
Python
|
mit
|
astanin/python-tabulate,kyokley/tabulate
|
python
|
## Code Before:
from distutils.core import setup
from platform import python_version_tuple
import re
LICENSE = open("LICENSE").read()
# strip links from the descripton on the PyPI
LONG_DESCRIPTION = open("README.rst").read().replace("`_", "`")
# strip Build Status from the PyPI package
if python_version_tuple()[:2] >= ('2', '7'):
LONG_DESCRIPTION = re.sub("^Build status\n(.*\n){7}", "", LONG_DESCRIPTION, flags=re.M)
setup(name='tabulate',
version='0.7.3',
description='Pretty-print tabular data',
long_description=LONG_DESCRIPTION,
author='Sergey Astanin',
author_email='[email protected]',
url='https://bitbucket.org/astanin/python-tabulate',
license=LICENSE,
classifiers= [ "Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Topic :: Software Development :: Libraries" ],
py_modules = ['tabulate'])
## Instruction:
Add Python 3.4 to classifiers
All tests passed on Python 3.4.
## Code After:
from distutils.core import setup
from platform import python_version_tuple
import re
LICENSE = open("LICENSE").read()
# strip links from the descripton on the PyPI
LONG_DESCRIPTION = open("README.rst").read().replace("`_", "`")
# strip Build Status from the PyPI package
if python_version_tuple()[:2] >= ('2', '7'):
LONG_DESCRIPTION = re.sub("^Build status\n(.*\n){7}", "", LONG_DESCRIPTION, flags=re.M)
setup(name='tabulate',
version='0.7.3',
description='Pretty-print tabular data',
long_description=LONG_DESCRIPTION,
author='Sergey Astanin',
author_email='[email protected]',
url='https://bitbucket.org/astanin/python-tabulate',
license=LICENSE,
classifiers= [ "Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: Software Development :: Libraries" ],
py_modules = ['tabulate'])
|
...
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: Software Development :: Libraries" ],
py_modules = ['tabulate'])
...
|
fa885b929f8323c88228dbc4d40ca286d49ee286
|
test_project/blog/api.py
|
test_project/blog/api.py
|
from tastypie.resources import ModelResource
from tastypie.api import Api
from tastypie import fields
from models import Entry, Comment
class EntryResource(ModelResource):
class Meta:
queryset = Entry.objects.all()
class CommentResource(ModelResource):
entry = fields.ForeignKey("blog.api.EntryResource", attribute="entry")
upvotes = fields.IntegerField(readonly=True)
class Meta:
queryset = Comment.objects.all()
api = Api(api_name="v1")
api.register(EntryResource())
api.register(CommentResource())
|
from tastypie.resources import ModelResource
from tastypie.api import Api
from tastypie import fields
from models import Entry, Comment, SmartTag
class EntryResource(ModelResource):
class Meta:
queryset = Entry.objects.all()
class CommentResource(ModelResource):
entry = fields.ForeignKey("blog.api.EntryResource", attribute="entry")
upvotes = fields.IntegerField(readonly=True)
class Meta:
queryset = Comment.objects.all()
class SmartTagResource(ModelResource):
entry = fields.ForeignKey("blog.api.EntryResource", attribute="entry")
class Meta:
queryset = SmartTag.objects.all()
resource_name = 'smart-tag'
api = Api(api_name="v1")
api.register(EntryResource())
api.register(CommentResource())
api.register(SmartTagResource())
|
Create corresponding SmartTag resource with explicitly defined 'resource_name' attribute that will be used for its TastyFactory key.
|
Create corresponding SmartTag resource with explicitly defined 'resource_name' attribute that will be used for its TastyFactory key.
|
Python
|
bsd-3-clause
|
juanique/django-chocolate,juanique/django-chocolate,juanique/django-chocolate
|
python
|
## Code Before:
from tastypie.resources import ModelResource
from tastypie.api import Api
from tastypie import fields
from models import Entry, Comment
class EntryResource(ModelResource):
class Meta:
queryset = Entry.objects.all()
class CommentResource(ModelResource):
entry = fields.ForeignKey("blog.api.EntryResource", attribute="entry")
upvotes = fields.IntegerField(readonly=True)
class Meta:
queryset = Comment.objects.all()
api = Api(api_name="v1")
api.register(EntryResource())
api.register(CommentResource())
## Instruction:
Create corresponding SmartTag resource with explicitly defined 'resource_name' attribute that will be used for its TastyFactory key.
## Code After:
from tastypie.resources import ModelResource
from tastypie.api import Api
from tastypie import fields
from models import Entry, Comment, SmartTag
class EntryResource(ModelResource):
class Meta:
queryset = Entry.objects.all()
class CommentResource(ModelResource):
entry = fields.ForeignKey("blog.api.EntryResource", attribute="entry")
upvotes = fields.IntegerField(readonly=True)
class Meta:
queryset = Comment.objects.all()
class SmartTagResource(ModelResource):
entry = fields.ForeignKey("blog.api.EntryResource", attribute="entry")
class Meta:
queryset = SmartTag.objects.all()
resource_name = 'smart-tag'
api = Api(api_name="v1")
api.register(EntryResource())
api.register(CommentResource())
api.register(SmartTagResource())
|
// ... existing code ...
from tastypie.resources import ModelResource
from tastypie.api import Api
from tastypie import fields
from models import Entry, Comment, SmartTag
class EntryResource(ModelResource):
// ... modified code ...
queryset = Comment.objects.all()
class SmartTagResource(ModelResource):
entry = fields.ForeignKey("blog.api.EntryResource", attribute="entry")
class Meta:
queryset = SmartTag.objects.all()
resource_name = 'smart-tag'
api = Api(api_name="v1")
api.register(EntryResource())
api.register(CommentResource())
api.register(SmartTagResource())
// ... rest of the code ...
|
181d3b06bf985d0ccec156363ecd4fe3792ddf1a
|
scripts/assignment_test.py
|
scripts/assignment_test.py
|
import unittest
dbconfig = None
try:
import dbconfig
import erppeek
except ImportError:
pass
@unittest.skipIf(not dbconfig, "depends on ERP")
class Assignment_Test(unittest.TestCase):
def setUp(self):
self.erp = erppeek.Client(**dbconfig.erppeek)
self.Assignments = self.erp.GenerationkwhAssignments
self.tearDown()
def setupProvider(self,assignments=[]):
self.Assignments.add(assignments)
def assertAssignmentsEqual(self, expectation):
result = self.Assignments.browse([])
self.assertEqual([
[r.active,
r.polissa_id.id,
r.member_id.id,
r.priority]
for r in result],
expectation)
def tearDown(self):
for a in self.Assignments.browse([]):
a.unlink()
def test_no_assignments(self):
self.setupProvider()
self.assertAssignmentsEqual([])
def test_one_assignment(self):
rp=self.erp.ResPartner.browse([])[0]
gp=self.erp.GiscedataPolissa.browse([])[0]
self.setupProvider([[True,gp.id,rp.id,1]])
self.assertAssignmentsEqual([[True,gp.id,rp.id,1]])
if __name__ == '__main__':
unittest.main()
|
import unittest
dbconfig = None
try:
import dbconfig
import erppeek
except ImportError:
pass
@unittest.skipIf(not dbconfig, "depends on ERP")
class Assignment_Test(unittest.TestCase):
def setUp(self):
self.erp = erppeek.Client(**dbconfig.erppeek)
self.Assignments = self.erp.GenerationkwhAssignments
self.tearDown()
def setupProvider(self,assignments=[]):
self.Assignments.add(assignments)
def assertAssignmentsEqual(self, expectation):
result = self.Assignments.browse([])
self.assertEqual([
[r.active,
r.polissa_id.id,
r.member_id.id,
r.priority]
for r in result],
expectation)
def tearDown(self):
for a in self.Assignments.browse([]):
a.unlink()
def test_no_assignments(self):
self.setupProvider()
self.assertAssignmentsEqual([])
def test_one_assignment(self):
rp=self.erp.ResPartner.browse([],limit=1)[0]
gp=self.erp.GiscedataPolissa.browse([], limit=1)[0]
self.setupProvider([[True,gp.id,rp.id,1]])
self.assertAssignmentsEqual([[True,gp.id,rp.id,1]])
"""def test_no_duplication(self):
rp=self.erp.ResPartner.browse([], limit=1)[0]
gp=self.erp.GiscedataPolissa.browse([],limit=1)[0]
self.setupProvider([[True,gp.id,rp.id,1]])
self.assertAssignmentsEqual([[True,gp.id,rp.id,1]])"""
if __name__ == '__main__':
unittest.main()
|
Refactor of one assignment test
|
Refactor of one assignment test
|
Python
|
agpl-3.0
|
Som-Energia/somenergia-generationkwh,Som-Energia/somenergia-generationkwh
|
python
|
## Code Before:
import unittest
dbconfig = None
try:
import dbconfig
import erppeek
except ImportError:
pass
@unittest.skipIf(not dbconfig, "depends on ERP")
class Assignment_Test(unittest.TestCase):
def setUp(self):
self.erp = erppeek.Client(**dbconfig.erppeek)
self.Assignments = self.erp.GenerationkwhAssignments
self.tearDown()
def setupProvider(self,assignments=[]):
self.Assignments.add(assignments)
def assertAssignmentsEqual(self, expectation):
result = self.Assignments.browse([])
self.assertEqual([
[r.active,
r.polissa_id.id,
r.member_id.id,
r.priority]
for r in result],
expectation)
def tearDown(self):
for a in self.Assignments.browse([]):
a.unlink()
def test_no_assignments(self):
self.setupProvider()
self.assertAssignmentsEqual([])
def test_one_assignment(self):
rp=self.erp.ResPartner.browse([])[0]
gp=self.erp.GiscedataPolissa.browse([])[0]
self.setupProvider([[True,gp.id,rp.id,1]])
self.assertAssignmentsEqual([[True,gp.id,rp.id,1]])
if __name__ == '__main__':
unittest.main()
## Instruction:
Refactor of one assignment test
## Code After:
import unittest
dbconfig = None
try:
import dbconfig
import erppeek
except ImportError:
pass
@unittest.skipIf(not dbconfig, "depends on ERP")
class Assignment_Test(unittest.TestCase):
def setUp(self):
self.erp = erppeek.Client(**dbconfig.erppeek)
self.Assignments = self.erp.GenerationkwhAssignments
self.tearDown()
def setupProvider(self,assignments=[]):
self.Assignments.add(assignments)
def assertAssignmentsEqual(self, expectation):
result = self.Assignments.browse([])
self.assertEqual([
[r.active,
r.polissa_id.id,
r.member_id.id,
r.priority]
for r in result],
expectation)
def tearDown(self):
for a in self.Assignments.browse([]):
a.unlink()
def test_no_assignments(self):
self.setupProvider()
self.assertAssignmentsEqual([])
def test_one_assignment(self):
rp=self.erp.ResPartner.browse([],limit=1)[0]
gp=self.erp.GiscedataPolissa.browse([], limit=1)[0]
self.setupProvider([[True,gp.id,rp.id,1]])
self.assertAssignmentsEqual([[True,gp.id,rp.id,1]])
"""def test_no_duplication(self):
rp=self.erp.ResPartner.browse([], limit=1)[0]
gp=self.erp.GiscedataPolissa.browse([],limit=1)[0]
self.setupProvider([[True,gp.id,rp.id,1]])
self.assertAssignmentsEqual([[True,gp.id,rp.id,1]])"""
if __name__ == '__main__':
unittest.main()
|
# ... existing code ...
pass
@unittest.skipIf(not dbconfig, "depends on ERP")
class Assignment_Test(unittest.TestCase):
def setUp(self):
self.erp = erppeek.Client(**dbconfig.erppeek)
self.Assignments = self.erp.GenerationkwhAssignments
# ... modified code ...
self.assertAssignmentsEqual([])
def test_one_assignment(self):
rp=self.erp.ResPartner.browse([],limit=1)[0]
gp=self.erp.GiscedataPolissa.browse([], limit=1)[0]
self.setupProvider([[True,gp.id,rp.id,1]])
self.assertAssignmentsEqual([[True,gp.id,rp.id,1]])
"""def test_no_duplication(self):
rp=self.erp.ResPartner.browse([], limit=1)[0]
gp=self.erp.GiscedataPolissa.browse([],limit=1)[0]
self.setupProvider([[True,gp.id,rp.id,1]])
self.assertAssignmentsEqual([[True,gp.id,rp.id,1]])"""
if __name__ == '__main__':
unittest.main()
# ... rest of the code ...
|
bef37803384b1521419559c99f0606d0616d9d4f
|
1.11.2/src/main/java/org/yggard/brokkgui/wrapper/event/SlotEvent.java
|
1.11.2/src/main/java/org/yggard/brokkgui/wrapper/event/SlotEvent.java
|
package org.yggard.brokkgui.wrapper.event;
import org.yggard.brokkgui.wrapper.container.BrokkGuiContainer;
import org.yggard.hermod.EventType;
import org.yggard.hermod.HermodEvent;
import net.minecraft.inventory.Slot;
/**
* @author Ourten 31 oct. 2016
*/
public class SlotEvent extends HermodEvent
{
public static final EventType<SlotEvent> ANY = new EventType<>("SLOT_EVENT");
public static final EventType<SlotEvent.Click> CLICK = new EventType<>(SlotEvent.ANY, "SLOT_CLICK_EVENT");
private final Slot slot;
public SlotEvent(final BrokkGuiContainer<?> source, final Slot slot)
{
super(source);
this.slot = slot;
}
public Slot getSlot()
{
return this.slot;
}
public static final class Click extends SlotEvent
{
private final int key;
public Click(final BrokkGuiContainer<?> source, final Slot slot, final int key)
{
super(source, slot);
this.key = key;
}
public int getKey()
{
return this.key;
}
}
}
|
package org.yggard.brokkgui.wrapper.event;
import org.yggard.brokkgui.wrapper.container.BrokkGuiContainer;
import org.yggard.hermod.EventType;
import org.yggard.hermod.HermodEvent;
import net.minecraft.inventory.Slot;
/**
* @author Ourten 31 oct. 2016
*/
public class SlotEvent extends HermodEvent
{
public static final EventType<SlotEvent> ANY = new EventType<>("SLOT_EVENT");
public static final EventType<SlotEvent.Click> CLICK = new EventType<>(SlotEvent.ANY, "SLOT_CLICK_EVENT");
public static final EventType<Change> CHANGE = new EventType<>(SlotEvent.ANY, "SLOT_CHANGE_EVENT");
private final Slot slot;
public SlotEvent(final BrokkGuiContainer<?> source, final Slot slot)
{
super(source);
this.slot = slot;
}
public Slot getSlot()
{
return this.slot;
}
public static final class Click extends SlotEvent
{
private final int key;
public Click(final BrokkGuiContainer<?> source, final Slot slot, final int key)
{
super(source, slot);
this.key = key;
}
public int getKey()
{
return this.key;
}
}
public static final class Change extends SlotEvent
{
public Change(final BrokkGuiContainer<?> source, final Slot slot)
{
super(source, slot);
}
}
}
|
Add a slot change event
|
Add a slot change event
|
Java
|
apache-2.0
|
Phenix246/BrokkGUI,Yggard/BrokkGUI
|
java
|
## Code Before:
package org.yggard.brokkgui.wrapper.event;
import org.yggard.brokkgui.wrapper.container.BrokkGuiContainer;
import org.yggard.hermod.EventType;
import org.yggard.hermod.HermodEvent;
import net.minecraft.inventory.Slot;
/**
* @author Ourten 31 oct. 2016
*/
public class SlotEvent extends HermodEvent
{
public static final EventType<SlotEvent> ANY = new EventType<>("SLOT_EVENT");
public static final EventType<SlotEvent.Click> CLICK = new EventType<>(SlotEvent.ANY, "SLOT_CLICK_EVENT");
private final Slot slot;
public SlotEvent(final BrokkGuiContainer<?> source, final Slot slot)
{
super(source);
this.slot = slot;
}
public Slot getSlot()
{
return this.slot;
}
public static final class Click extends SlotEvent
{
private final int key;
public Click(final BrokkGuiContainer<?> source, final Slot slot, final int key)
{
super(source, slot);
this.key = key;
}
public int getKey()
{
return this.key;
}
}
}
## Instruction:
Add a slot change event
## Code After:
package org.yggard.brokkgui.wrapper.event;
import org.yggard.brokkgui.wrapper.container.BrokkGuiContainer;
import org.yggard.hermod.EventType;
import org.yggard.hermod.HermodEvent;
import net.minecraft.inventory.Slot;
/**
* @author Ourten 31 oct. 2016
*/
public class SlotEvent extends HermodEvent
{
public static final EventType<SlotEvent> ANY = new EventType<>("SLOT_EVENT");
public static final EventType<SlotEvent.Click> CLICK = new EventType<>(SlotEvent.ANY, "SLOT_CLICK_EVENT");
public static final EventType<Change> CHANGE = new EventType<>(SlotEvent.ANY, "SLOT_CHANGE_EVENT");
private final Slot slot;
public SlotEvent(final BrokkGuiContainer<?> source, final Slot slot)
{
super(source);
this.slot = slot;
}
public Slot getSlot()
{
return this.slot;
}
public static final class Click extends SlotEvent
{
private final int key;
public Click(final BrokkGuiContainer<?> source, final Slot slot, final int key)
{
super(source, slot);
this.key = key;
}
public int getKey()
{
return this.key;
}
}
public static final class Change extends SlotEvent
{
public Change(final BrokkGuiContainer<?> source, final Slot slot)
{
super(source, slot);
}
}
}
|
...
*/
public class SlotEvent extends HermodEvent
{
public static final EventType<SlotEvent> ANY = new EventType<>("SLOT_EVENT");
public static final EventType<SlotEvent.Click> CLICK = new EventType<>(SlotEvent.ANY, "SLOT_CLICK_EVENT");
public static final EventType<Change> CHANGE = new EventType<>(SlotEvent.ANY, "SLOT_CHANGE_EVENT");
private final Slot slot;
...
return this.key;
}
}
public static final class Change extends SlotEvent
{
public Change(final BrokkGuiContainer<?> source, final Slot slot)
{
super(source, slot);
}
}
}
...
|
de02c92510a6117aad01be7666d737d2ad861fd7
|
send_sms.py
|
send_sms.py
|
import datetime
import json
import sys
import requests
import pytz
from twilio.rest import TwilioRestClient
import conf
def send(s):
client.sms.messages.create(to=conf.TO, from_=conf.FROM, body=s)
# Use the first arg as the message to send, or use the default if not specified
default_message = "You haven't committed anything today!"
message = sys.argv[1] if len(sys.argv) > 1 else default_message
# Initialise twilio stuff
client = TwilioRestClient(conf.ACCOUNT_SID, conf.AUTH_TOKEN)
# Get Github contributions activity
url = 'https://github.com/users/%s/contributions_calendar_data' % conf.USERNAME
request = requests.get(url)
if request.ok:
data = json.loads(request.text)
# Set to epoch begin just in case this is a totally new account
latest_contribution = datetime.datetime(1970, 1, 1, 0, 0)
# Get data for the latest contribution
for i in reversed(data):
if i[1] > 0:
latest_contribution = datetime.datetime.strptime(i[0], '%Y/%m/%d')
break
# Find out today's date in PST (since Github uses PST)
today = datetime.datetime.now(pytz.timezone('US/Pacific'))
# Haven't contributed anything today?
if latest_contribution.date() < today.date():
send(message)
else:
send('There was a problem accessing the Github API :(')
|
import json
import sys
import requests
from twilio.rest import TwilioRestClient
import conf
def send(s):
client.sms.messages.create(to=conf.TO, from_=conf.FROM, body=s)
# Use the first arg as the message to send, or use the default if not specified
default_message = "You haven't committed anything today!"
message = sys.argv[1] if len(sys.argv) > 1 else default_message
# Initialise twilio stuff
client = TwilioRestClient(conf.ACCOUNT_SID, conf.AUTH_TOKEN)
# Get Github contributions activity
url = 'https://github.com/users/%s/contributions_calendar_data' % conf.USERNAME
request = requests.get(url)
if request.ok:
try:
data = json.loads(request.text)
# Get the number of commits made today
commits_today = data[-1][1]
if not commits_today:
send(message)
except:
send('There was an error getting the number of commits today')
else:
send('There was a problem accessing the Github API :(')
|
Improve logic in determining latest contribution
|
Improve logic in determining latest contribution
Looks like the list will always contain data for the last 366 days, and
the last entry in the list will always contain data for the current day
(PST). Much simpler this way.
Added some generic error-handling just in case this isn't true.
|
Python
|
mit
|
dellsystem/github-streak-saver
|
python
|
## Code Before:
import datetime
import json
import sys
import requests
import pytz
from twilio.rest import TwilioRestClient
import conf
def send(s):
client.sms.messages.create(to=conf.TO, from_=conf.FROM, body=s)
# Use the first arg as the message to send, or use the default if not specified
default_message = "You haven't committed anything today!"
message = sys.argv[1] if len(sys.argv) > 1 else default_message
# Initialise twilio stuff
client = TwilioRestClient(conf.ACCOUNT_SID, conf.AUTH_TOKEN)
# Get Github contributions activity
url = 'https://github.com/users/%s/contributions_calendar_data' % conf.USERNAME
request = requests.get(url)
if request.ok:
data = json.loads(request.text)
# Set to epoch begin just in case this is a totally new account
latest_contribution = datetime.datetime(1970, 1, 1, 0, 0)
# Get data for the latest contribution
for i in reversed(data):
if i[1] > 0:
latest_contribution = datetime.datetime.strptime(i[0], '%Y/%m/%d')
break
# Find out today's date in PST (since Github uses PST)
today = datetime.datetime.now(pytz.timezone('US/Pacific'))
# Haven't contributed anything today?
if latest_contribution.date() < today.date():
send(message)
else:
send('There was a problem accessing the Github API :(')
## Instruction:
Improve logic in determining latest contribution
Looks like the list will always contain data for the last 366 days, and
the last entry in the list will always contain data for the current day
(PST). Much simpler this way.
Added some generic error-handling just in case this isn't true.
## Code After:
import json
import sys
import requests
from twilio.rest import TwilioRestClient
import conf
def send(s):
client.sms.messages.create(to=conf.TO, from_=conf.FROM, body=s)
# Use the first arg as the message to send, or use the default if not specified
default_message = "You haven't committed anything today!"
message = sys.argv[1] if len(sys.argv) > 1 else default_message
# Initialise twilio stuff
client = TwilioRestClient(conf.ACCOUNT_SID, conf.AUTH_TOKEN)
# Get Github contributions activity
url = 'https://github.com/users/%s/contributions_calendar_data' % conf.USERNAME
request = requests.get(url)
if request.ok:
try:
data = json.loads(request.text)
# Get the number of commits made today
commits_today = data[-1][1]
if not commits_today:
send(message)
except:
send('There was an error getting the number of commits today')
else:
send('There was a problem accessing the Github API :(')
|
// ... existing code ...
import json
import sys
import requests
from twilio.rest import TwilioRestClient
import conf
// ... modified code ...
url = 'https://github.com/users/%s/contributions_calendar_data' % conf.USERNAME
request = requests.get(url)
if request.ok:
try:
data = json.loads(request.text)
# Get the number of commits made today
commits_today = data[-1][1]
if not commits_today:
send(message)
except:
send('There was an error getting the number of commits today')
else:
send('There was a problem accessing the Github API :(')
// ... rest of the code ...
|
e7cba721d78860d0151cc65793e567b0da719d39
|
regserver/regulations/tests/partial_view_tests.py
|
regserver/regulations/tests/partial_view_tests.py
|
from unittest import TestCase
from mock import Mock, patch
from regulations.generator.layers.layers_applier import *
from regulations.views.partial import *
class PartialParagraphViewTests(TestCase):
@patch('regulations.views.partial.generator')
def test_get_context_data(self, generator):
generator.get_all_section_layers.return_value = (InlineLayersApplier(),
ParagraphLayersApplier(), SearchReplaceLayersApplier())
generator.get_tree_paragraph.return_value = {
'text': 'Some Text',
'children': [],
'label': {'text': '867-53-q', 'parts': ['867', '53', 'q']}
}
rpv = PartialParagraphView()
context = rpv.get_context_data(paragraph_id = '867-53-q',
reg_version = 'verver')
self.assertEqual(context['node'],
generator.get_tree_paragraph.return_value)
|
from unittest import TestCase
from mock import Mock, patch
from django.test import RequestFactory
from regulations.generator.layers.layers_applier import *
from regulations.views.partial import *
class PartialParagraphViewTests(TestCase):
@patch('regulations.views.partial.generator')
def test_get_context_data(self, generator):
generator.get_all_section_layers.return_value = (InlineLayersApplier(),
ParagraphLayersApplier(), SearchReplaceLayersApplier())
generator.get_tree_paragraph.return_value = {
'text': 'Some Text',
'children': [],
'label': {'text': '867-53-q', 'parts': ['867', '53', 'q']}
}
paragraph_id = '103-3-a'
reg_version = '2013-10607'
request = RequestFactory().get('/fake-path')
view = PartialParagraphView.as_view(template_name='tree.html')
response = view(request, paragraph_id=paragraph_id, reg_version=reg_version)
self.assertEqual(response.context_data['node'],
generator.get_tree_paragraph.return_value)
|
Change test, so that view has a request object
|
Change test, so that view has a request object
|
Python
|
cc0-1.0
|
ascott1/regulations-site,18F/regulations-site,ascott1/regulations-site,grapesmoker/regulations-site,tadhg-ohiggins/regulations-site,18F/regulations-site,adderall/regulations-site,adderall/regulations-site,ascott1/regulations-site,grapesmoker/regulations-site,EricSchles/regulations-site,EricSchles/regulations-site,willbarton/regulations-site,adderall/regulations-site,willbarton/regulations-site,willbarton/regulations-site,grapesmoker/regulations-site,tadhg-ohiggins/regulations-site,jeremiak/regulations-site,tadhg-ohiggins/regulations-site,EricSchles/regulations-site,jeremiak/regulations-site,18F/regulations-site,EricSchles/regulations-site,adderall/regulations-site,jeremiak/regulations-site,18F/regulations-site,eregs/regulations-site,ascott1/regulations-site,willbarton/regulations-site,grapesmoker/regulations-site,eregs/regulations-site,tadhg-ohiggins/regulations-site,jeremiak/regulations-site,eregs/regulations-site,eregs/regulations-site
|
python
|
## Code Before:
from unittest import TestCase
from mock import Mock, patch
from regulations.generator.layers.layers_applier import *
from regulations.views.partial import *
class PartialParagraphViewTests(TestCase):
@patch('regulations.views.partial.generator')
def test_get_context_data(self, generator):
generator.get_all_section_layers.return_value = (InlineLayersApplier(),
ParagraphLayersApplier(), SearchReplaceLayersApplier())
generator.get_tree_paragraph.return_value = {
'text': 'Some Text',
'children': [],
'label': {'text': '867-53-q', 'parts': ['867', '53', 'q']}
}
rpv = PartialParagraphView()
context = rpv.get_context_data(paragraph_id = '867-53-q',
reg_version = 'verver')
self.assertEqual(context['node'],
generator.get_tree_paragraph.return_value)
## Instruction:
Change test, so that view has a request object
## Code After:
from unittest import TestCase
from mock import Mock, patch
from django.test import RequestFactory
from regulations.generator.layers.layers_applier import *
from regulations.views.partial import *
class PartialParagraphViewTests(TestCase):
@patch('regulations.views.partial.generator')
def test_get_context_data(self, generator):
generator.get_all_section_layers.return_value = (InlineLayersApplier(),
ParagraphLayersApplier(), SearchReplaceLayersApplier())
generator.get_tree_paragraph.return_value = {
'text': 'Some Text',
'children': [],
'label': {'text': '867-53-q', 'parts': ['867', '53', 'q']}
}
paragraph_id = '103-3-a'
reg_version = '2013-10607'
request = RequestFactory().get('/fake-path')
view = PartialParagraphView.as_view(template_name='tree.html')
response = view(request, paragraph_id=paragraph_id, reg_version=reg_version)
self.assertEqual(response.context_data['node'],
generator.get_tree_paragraph.return_value)
|
# ... existing code ...
from unittest import TestCase
from mock import Mock, patch
from django.test import RequestFactory
from regulations.generator.layers.layers_applier import *
from regulations.views.partial import *
class PartialParagraphViewTests(TestCase):
@patch('regulations.views.partial.generator')
def test_get_context_data(self, generator):
generator.get_all_section_layers.return_value = (InlineLayersApplier(),
# ... modified code ...
'children': [],
'label': {'text': '867-53-q', 'parts': ['867', '53', 'q']}
}
paragraph_id = '103-3-a'
reg_version = '2013-10607'
request = RequestFactory().get('/fake-path')
view = PartialParagraphView.as_view(template_name='tree.html')
response = view(request, paragraph_id=paragraph_id, reg_version=reg_version)
self.assertEqual(response.context_data['node'],
generator.get_tree_paragraph.return_value)
# ... rest of the code ...
|
fa54689fada175aa10ee1b096e73a0cd33aa702b
|
pmxbot/buffer.py
|
pmxbot/buffer.py
|
import logging
import irc.buffer
log = logging.getLogger(__name__)
class ErrorReportingBuffer(irc.buffer.LineBuffer):
encoding = 'utf-8'
def lines(self):
lines = super().lines()
for line in lines:
try:
yield line.decode(self.encoding)
except UnicodeDecodeError:
log.error("Unable to decode line: {line!r}".format(line=line))
@classmethod
def install(cls):
irc.client.ServerConnection.buffer_class = cls
|
import logging
import irc.buffer
import irc.client
log = logging.getLogger(__name__)
class ErrorReportingBuffer(irc.buffer.LineBuffer):
encoding = 'utf-8'
def lines(self):
lines = super().lines()
for line in lines:
try:
yield line.decode(self.encoding)
except UnicodeDecodeError:
log.error("Unable to decode line: {line!r}".format(line=line))
@classmethod
def install(cls):
irc.client.ServerConnection.buffer_class = cls
|
Correct AttributeError when client isn't explicitly imported.
|
Correct AttributeError when client isn't explicitly imported.
|
Python
|
mit
|
yougov/pmxbot,yougov/pmxbot,yougov/pmxbot
|
python
|
## Code Before:
import logging
import irc.buffer
log = logging.getLogger(__name__)
class ErrorReportingBuffer(irc.buffer.LineBuffer):
encoding = 'utf-8'
def lines(self):
lines = super().lines()
for line in lines:
try:
yield line.decode(self.encoding)
except UnicodeDecodeError:
log.error("Unable to decode line: {line!r}".format(line=line))
@classmethod
def install(cls):
irc.client.ServerConnection.buffer_class = cls
## Instruction:
Correct AttributeError when client isn't explicitly imported.
## Code After:
import logging
import irc.buffer
import irc.client
log = logging.getLogger(__name__)
class ErrorReportingBuffer(irc.buffer.LineBuffer):
encoding = 'utf-8'
def lines(self):
lines = super().lines()
for line in lines:
try:
yield line.decode(self.encoding)
except UnicodeDecodeError:
log.error("Unable to decode line: {line!r}".format(line=line))
@classmethod
def install(cls):
irc.client.ServerConnection.buffer_class = cls
|
// ... existing code ...
import logging
import irc.buffer
import irc.client
log = logging.getLogger(__name__)
// ... rest of the code ...
|
9c07f8fdb9c955f49cf6ff92a25b1c0629157811
|
assembler6502.py
|
assembler6502.py
|
import sys
import assembler6502_tokenizer as tokenizer
import assembler6502_parser as parser
def output_byte(hexcode):
sys.stdout.write(hexcode)
#sys.stdout.write(chr(int(hexcode, 16)))
def main():
code = """
; sample code
beginning:
sty $44,X
"""
for line in code.split("\n"):
hexcodes = parser.parse_line(line)
for hexcode in hexcodes:
output_byte(hexcode)
print
if __name__ == "__main__":
main()
|
import sys
import assembler6502_tokenizer as tokenizer
import assembler6502_parser as parser
def output_byte(hexcode):
sys.stdout.write(hexcode + "\n")
#sys.stdout.write(chr(int(hexcode, 16)))
def main():
code = sys.stdin.read()
for line in code.split("\n"):
hexcodes = parser.parse_line(line)
for hexcode in hexcodes:
output_byte(hexcode)
if __name__ == "__main__":
main()
|
Use stdin for assembler input
|
Use stdin for assembler input
|
Python
|
mit
|
technetia/project-tdm,technetia/project-tdm,technetia/project-tdm
|
python
|
## Code Before:
import sys
import assembler6502_tokenizer as tokenizer
import assembler6502_parser as parser
def output_byte(hexcode):
sys.stdout.write(hexcode)
#sys.stdout.write(chr(int(hexcode, 16)))
def main():
code = """
; sample code
beginning:
sty $44,X
"""
for line in code.split("\n"):
hexcodes = parser.parse_line(line)
for hexcode in hexcodes:
output_byte(hexcode)
print
if __name__ == "__main__":
main()
## Instruction:
Use stdin for assembler input
## Code After:
import sys
import assembler6502_tokenizer as tokenizer
import assembler6502_parser as parser
def output_byte(hexcode):
sys.stdout.write(hexcode + "\n")
#sys.stdout.write(chr(int(hexcode, 16)))
def main():
code = sys.stdin.read()
for line in code.split("\n"):
hexcodes = parser.parse_line(line)
for hexcode in hexcodes:
output_byte(hexcode)
if __name__ == "__main__":
main()
|
# ... existing code ...
import assembler6502_parser as parser
def output_byte(hexcode):
sys.stdout.write(hexcode + "\n")
#sys.stdout.write(chr(int(hexcode, 16)))
def main():
code = sys.stdin.read()
for line in code.split("\n"):
hexcodes = parser.parse_line(line)
for hexcode in hexcodes:
output_byte(hexcode)
if __name__ == "__main__":
main()
# ... rest of the code ...
|
462efd1a2ee217b8a70d1769f2fae9265f54fc4f
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
setup(
name="adbons",
version="0.0.1",
author="Daniel Bälz",
author_email="[email protected]",
description="""A wrapper for the Android adb tool.
It's just adb on steroids""",
license="BSD",
packages=find_packages(),
include_package_data=True,
install_requires=[
"Click"
],
entry_points={
'console_scripts': ['adbons=src.adbons:cli']
},
classifiers=[
"Topic :: Utilities",
"License :: OSI Approved :: BSD License",
],
)
|
from setuptools import setup, find_packages
setup(
name="adbons",
version="0.0.1",
author="Daniel Bälz",
author_email="[email protected]",
description="""A wrapper for the Android adb tool.
It's just adb on steroids""",
license="BSD",
packages=find_packages(),
include_package_data=True,
install_requires=[
"click",
"pyyaml"
],
entry_points={
'console_scripts': ['adbons=src.adbons:cli']
},
classifiers=[
"Topic :: Utilities",
"License :: OSI Approved :: BSD License",
],
)
|
Add pyyaml and use lower case lib names
|
Add pyyaml and use lower case lib names
|
Python
|
bsd-2-clause
|
dbaelz/adbons
|
python
|
## Code Before:
from setuptools import setup, find_packages
setup(
name="adbons",
version="0.0.1",
author="Daniel Bälz",
author_email="[email protected]",
description="""A wrapper for the Android adb tool.
It's just adb on steroids""",
license="BSD",
packages=find_packages(),
include_package_data=True,
install_requires=[
"Click"
],
entry_points={
'console_scripts': ['adbons=src.adbons:cli']
},
classifiers=[
"Topic :: Utilities",
"License :: OSI Approved :: BSD License",
],
)
## Instruction:
Add pyyaml and use lower case lib names
## Code After:
from setuptools import setup, find_packages
setup(
name="adbons",
version="0.0.1",
author="Daniel Bälz",
author_email="[email protected]",
description="""A wrapper for the Android adb tool.
It's just adb on steroids""",
license="BSD",
packages=find_packages(),
include_package_data=True,
install_requires=[
"click",
"pyyaml"
],
entry_points={
'console_scripts': ['adbons=src.adbons:cli']
},
classifiers=[
"Topic :: Utilities",
"License :: OSI Approved :: BSD License",
],
)
|
...
packages=find_packages(),
include_package_data=True,
install_requires=[
"click",
"pyyaml"
],
entry_points={
'console_scripts': ['adbons=src.adbons:cli']
...
|
9138112f3abef61a96485ade7e0b484a43429b81
|
tests/unit/actions.py
|
tests/unit/actions.py
|
"""Unit tests for `pycall.actions`."""
class TestActions(TestCase):
"""Test all `pycall.actions` classes to ensure they are actual
`pycall.actions.Action` subclasses.
"""
pass
|
"""Unit tests for `pycall.actions`."""
|
Revert "Adding test case stub."
|
Revert "Adding test case stub."
This reverts commit 6c6b08a63b308690144d73f54b98000e3b1b5672.
|
Python
|
unlicense
|
rdegges/pycall
|
python
|
## Code Before:
"""Unit tests for `pycall.actions`."""
class TestActions(TestCase):
"""Test all `pycall.actions` classes to ensure they are actual
`pycall.actions.Action` subclasses.
"""
pass
## Instruction:
Revert "Adding test case stub."
This reverts commit 6c6b08a63b308690144d73f54b98000e3b1b5672.
## Code After:
"""Unit tests for `pycall.actions`."""
|
// ... existing code ...
"""Unit tests for `pycall.actions`."""
// ... rest of the code ...
|
0e9c38d2df67c0967c552034d5f43baadd00287f
|
src/main/java/com/github/solairerove/woodstock/service/impl/CategoryServiceImpl.java
|
src/main/java/com/github/solairerove/woodstock/service/impl/CategoryServiceImpl.java
|
package com.github.solairerove.woodstock.service.impl;
import com.github.solairerove.woodstock.domain.Category;
import com.github.solairerove.woodstock.dto.CategoryDTO;
import com.github.solairerove.woodstock.repository.CategoryRepository;
import com.github.solairerove.woodstock.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by krivitski-no on 10/14/16.
*/
@Service
public class CategoryServiceImpl implements CategoryService {
private final CategoryRepository repository;
@Autowired
public CategoryServiceImpl(CategoryRepository repository) {
this.repository = repository;
}
@Override
public Category create(CategoryDTO categoryDTO) {
Category category = new Category(categoryDTO.getName());
return repository.save(category);
}
@Override
public Category get(Long id) {
return repository.findOne(id);
}
}
|
package com.github.solairerove.woodstock.service.impl;
import com.github.solairerove.woodstock.domain.Category;
import com.github.solairerove.woodstock.dto.CategoryDTO;
import com.github.solairerove.woodstock.repository.CategoryRepository;
import com.github.solairerove.woodstock.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by krivitski-no on 10/14/16.
*/
@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
private final CategoryRepository repository;
@Autowired
public CategoryServiceImpl(CategoryRepository repository) {
this.repository = repository;
}
@Override
public Category create(CategoryDTO categoryDTO) {
Category category = new Category(categoryDTO.getName());
return repository.save(category);
}
@Override
public Category get(Long id) {
return repository.findOne(id);
}
}
|
Add transactional annotation: - merge new-api branch
|
Add transactional annotation:
- merge new-api branch
|
Java
|
apache-2.0
|
solairerove/woodstock,solairerove/woodstock,solairerove/woodstock
|
java
|
## Code Before:
package com.github.solairerove.woodstock.service.impl;
import com.github.solairerove.woodstock.domain.Category;
import com.github.solairerove.woodstock.dto.CategoryDTO;
import com.github.solairerove.woodstock.repository.CategoryRepository;
import com.github.solairerove.woodstock.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by krivitski-no on 10/14/16.
*/
@Service
public class CategoryServiceImpl implements CategoryService {
private final CategoryRepository repository;
@Autowired
public CategoryServiceImpl(CategoryRepository repository) {
this.repository = repository;
}
@Override
public Category create(CategoryDTO categoryDTO) {
Category category = new Category(categoryDTO.getName());
return repository.save(category);
}
@Override
public Category get(Long id) {
return repository.findOne(id);
}
}
## Instruction:
Add transactional annotation:
- merge new-api branch
## Code After:
package com.github.solairerove.woodstock.service.impl;
import com.github.solairerove.woodstock.domain.Category;
import com.github.solairerove.woodstock.dto.CategoryDTO;
import com.github.solairerove.woodstock.repository.CategoryRepository;
import com.github.solairerove.woodstock.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by krivitski-no on 10/14/16.
*/
@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
private final CategoryRepository repository;
@Autowired
public CategoryServiceImpl(CategoryRepository repository) {
this.repository = repository;
}
@Override
public Category create(CategoryDTO categoryDTO) {
Category category = new Category(categoryDTO.getName());
return repository.save(category);
}
@Override
public Category get(Long id) {
return repository.findOne(id);
}
}
|
# ... existing code ...
import com.github.solairerove.woodstock.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by krivitski-no on 10/14/16.
*/
@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
private final CategoryRepository repository;
# ... rest of the code ...
|
2f4141311af549b6d57e72534b4da0a6ce950629
|
src/waldur_mastermind/analytics/serializers.py
|
src/waldur_mastermind/analytics/serializers.py
|
from __future__ import unicode_literals
from datetime import timedelta
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from waldur_core.core.serializers import GenericRelatedField
from waldur_core.structure.models import Customer, Project
class DailyHistoryQuotaSerializer(serializers.Serializer):
scope = GenericRelatedField(related_models=(Project, Customer))
quota_names = serializers.ListField(child=serializers.CharField(), required=False)
start = serializers.DateField(format='%Y-%m-%d', required=False)
end = serializers.DateField(format='%Y-%m-%d', required=False)
def validate(self, attrs):
if attrs['start'] >= attrs['end']:
raise serializers.ValidationError(
_('Invalid period specified. `start` should be lesser than `end`.')
)
if 'quota_names' not in attrs:
attrs['quota_names'] = attrs['scope'].get_quotas_names
if 'end' not in attrs:
attrs['end'] = timezone.now().date()
if 'start' not in attrs:
attrs['start'] = timezone.now().date() - timedelta(days=30)
return attrs
|
from __future__ import unicode_literals
from datetime import timedelta
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from waldur_core.core.serializers import GenericRelatedField
from waldur_core.structure.models import Customer, Project
class DailyHistoryQuotaSerializer(serializers.Serializer):
scope = GenericRelatedField(related_models=(Project, Customer))
quota_names = serializers.ListField(child=serializers.CharField(), required=False)
start = serializers.DateField(format='%Y-%m-%d', required=False)
end = serializers.DateField(format='%Y-%m-%d', required=False)
def validate(self, attrs):
if 'quota_names' not in attrs:
attrs['quota_names'] = attrs['scope'].get_quotas_names
if 'end' not in attrs:
attrs['end'] = timezone.now().date()
if 'start' not in attrs:
attrs['start'] = timezone.now().date() - timedelta(days=30)
if attrs['start'] >= attrs['end']:
raise serializers.ValidationError(
_('Invalid period specified. `start` should be lesser than `end`.')
)
return attrs
|
Fix period validation in daily quota serializer.
|
Fix period validation in daily quota serializer.
|
Python
|
mit
|
opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind
|
python
|
## Code Before:
from __future__ import unicode_literals
from datetime import timedelta
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from waldur_core.core.serializers import GenericRelatedField
from waldur_core.structure.models import Customer, Project
class DailyHistoryQuotaSerializer(serializers.Serializer):
scope = GenericRelatedField(related_models=(Project, Customer))
quota_names = serializers.ListField(child=serializers.CharField(), required=False)
start = serializers.DateField(format='%Y-%m-%d', required=False)
end = serializers.DateField(format='%Y-%m-%d', required=False)
def validate(self, attrs):
if attrs['start'] >= attrs['end']:
raise serializers.ValidationError(
_('Invalid period specified. `start` should be lesser than `end`.')
)
if 'quota_names' not in attrs:
attrs['quota_names'] = attrs['scope'].get_quotas_names
if 'end' not in attrs:
attrs['end'] = timezone.now().date()
if 'start' not in attrs:
attrs['start'] = timezone.now().date() - timedelta(days=30)
return attrs
## Instruction:
Fix period validation in daily quota serializer.
## Code After:
from __future__ import unicode_literals
from datetime import timedelta
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from waldur_core.core.serializers import GenericRelatedField
from waldur_core.structure.models import Customer, Project
class DailyHistoryQuotaSerializer(serializers.Serializer):
scope = GenericRelatedField(related_models=(Project, Customer))
quota_names = serializers.ListField(child=serializers.CharField(), required=False)
start = serializers.DateField(format='%Y-%m-%d', required=False)
end = serializers.DateField(format='%Y-%m-%d', required=False)
def validate(self, attrs):
if 'quota_names' not in attrs:
attrs['quota_names'] = attrs['scope'].get_quotas_names
if 'end' not in attrs:
attrs['end'] = timezone.now().date()
if 'start' not in attrs:
attrs['start'] = timezone.now().date() - timedelta(days=30)
if attrs['start'] >= attrs['end']:
raise serializers.ValidationError(
_('Invalid period specified. `start` should be lesser than `end`.')
)
return attrs
|
# ... existing code ...
end = serializers.DateField(format='%Y-%m-%d', required=False)
def validate(self, attrs):
if 'quota_names' not in attrs:
attrs['quota_names'] = attrs['scope'].get_quotas_names
if 'end' not in attrs:
# ... modified code ...
attrs['end'] = timezone.now().date()
if 'start' not in attrs:
attrs['start'] = timezone.now().date() - timedelta(days=30)
if attrs['start'] >= attrs['end']:
raise serializers.ValidationError(
_('Invalid period specified. `start` should be lesser than `end`.')
)
return attrs
# ... rest of the code ...
|
73af60749ea7b031473bc5f0c3ddd60d39ec6fa6
|
docs/examples/customer_fetch/get_customer.py
|
docs/examples/customer_fetch/get_customer.py
|
from sharpy.product import CheddarProduct
# Get a product instance to work with
product = CheddarProduct(
username = CHEDDAR_USERNAME,
password = CHEDDAR_PASSWORD,
product_code = CHEDDAR_PRODUCT,
)
# Get the customer from Cheddar Getter
customer = product.get_customer(code='1BDI')
|
from sharpy.product import CheddarProduct
from sharpy import exceptions
# Get a product instance to work with
product = CheddarProduct(
username = CHEDDAR_USERNAME,
password = CHEDDAR_PASSWORD,
product_code = CHEDDAR_PRODUCT,
)
try:
# Get the customer from Cheddar Getter
customer = product.get_customer(code='1BDI')
except exceptions.NotFound, err:
print 'You do not appear to be a customer yet'
else:
# Test if the customer's subscription is canceled
if customer.subscription.canceled:
if customer.subscription.cancel_type == 'paypal-pending':
print 'Waiting for Paypal authorization'
else:
print 'Your subscription appears to have been cancelled'
else:
print 'Your subscription appears to be active'
|
Add a bit to the get customer to show handling not-found and testing for canceled status
|
Add a bit to the get customer to show handling not-found and testing for canceled status
|
Python
|
bsd-3-clause
|
SeanOC/sharpy,smartfile/sharpy
|
python
|
## Code Before:
from sharpy.product import CheddarProduct
# Get a product instance to work with
product = CheddarProduct(
username = CHEDDAR_USERNAME,
password = CHEDDAR_PASSWORD,
product_code = CHEDDAR_PRODUCT,
)
# Get the customer from Cheddar Getter
customer = product.get_customer(code='1BDI')
## Instruction:
Add a bit to the get customer to show handling not-found and testing for canceled status
## Code After:
from sharpy.product import CheddarProduct
from sharpy import exceptions
# Get a product instance to work with
product = CheddarProduct(
username = CHEDDAR_USERNAME,
password = CHEDDAR_PASSWORD,
product_code = CHEDDAR_PRODUCT,
)
try:
# Get the customer from Cheddar Getter
customer = product.get_customer(code='1BDI')
except exceptions.NotFound, err:
print 'You do not appear to be a customer yet'
else:
# Test if the customer's subscription is canceled
if customer.subscription.canceled:
if customer.subscription.cancel_type == 'paypal-pending':
print 'Waiting for Paypal authorization'
else:
print 'Your subscription appears to have been cancelled'
else:
print 'Your subscription appears to be active'
|
...
from sharpy.product import CheddarProduct
from sharpy import exceptions
# Get a product instance to work with
product = CheddarProduct(
...
product_code = CHEDDAR_PRODUCT,
)
try:
# Get the customer from Cheddar Getter
customer = product.get_customer(code='1BDI')
except exceptions.NotFound, err:
print 'You do not appear to be a customer yet'
else:
# Test if the customer's subscription is canceled
if customer.subscription.canceled:
if customer.subscription.cancel_type == 'paypal-pending':
print 'Waiting for Paypal authorization'
else:
print 'Your subscription appears to have been cancelled'
else:
print 'Your subscription appears to be active'
...
|
3eb57619a4e8a669cf879b67d96377ccb21de204
|
babel_util/scripts/wos_to_pajek.py
|
babel_util/scripts/wos_to_pajek.py
|
from parsers.wos import WOSStream
from util.PajekFactory import PajekFactory
from util.misc import open_file, Checkpoint
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Creates Pajek (.net) files from WOS XML")
parser.add_argument('outfile')
parser.add_argument('infile', nargs='+')
args = parser.parse_args()
chk = Checkpoint()
nodes = args.outfile + ".nodes"
edges = args.outfile + ".edges"
nodes_f = open_file(nodes, "w")
edges_f = open_file(edges, "w")
parsed = 1
total_files = len(args.infile)
pjk = PajekFactory(node_stream=nodes_f, edge_stream=edges_f)
for file in args.infile:
print(chk.checkpoint("Parsing {}: {}/{}: {:.2%}".format(file, parsed, total_files, parsed/float(total_files))))
f = open_file(file)
parser = WOSStream(f)
for entry in parser.parse():
if "citations" in entry:
for citation in entry["citations"]:
pjk.add_edge(entry["id"], citation)
print(chk.checkpoint(" Done: "+str(pjk)))
parsed += 1
with open_file(args.outfile, "w") as f:
f.writelines(pjk.make_header())
chk.end("Done")
|
from parsers.wos import WOSStream
from util.PajekFactory import PajekFactory
from util.misc import open_file, Checkpoint
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Creates Pajek (.net) files from WOS XML")
parser.add_argument('outfile')
parser.add_argument('--wos-only', action="store_true", help="Only include nodes/edges in WOS")
parser.add_argument('infile', nargs='+')
args = parser.parse_args()
chk = Checkpoint()
nodes = args.outfile + ".nodes"
edges = args.outfile + ".edges"
nodes_f = open_file(nodes, "w")
edges_f = open_file(edges, "w")
parsed = 1
total_files = len(args.infile)
pjk = PajekFactory(node_stream=nodes_f, edge_stream=edges_f)
for file in args.infile:
print(chk.checkpoint("Parsing {}: {}/{}: {:.2%}".format(file, parsed, total_files, parsed/float(total_files))))
f = open_file(file)
parser = WOSStream(f, args.wos_only)
for entry in parser.parse():
if "citations" in entry:
for citation in entry["citations"]:
pjk.add_edge(entry["id"], citation)
print(chk.checkpoint(" Done: "+str(pjk)))
parsed += 1
with open_file(args.outfile, "w") as f:
f.writelines(pjk.make_header())
chk.end("Done")
|
Add wos-only option to script
|
Add wos-only option to script
|
Python
|
agpl-3.0
|
jevinw/rec_utilities,jevinw/rec_utilities
|
python
|
## Code Before:
from parsers.wos import WOSStream
from util.PajekFactory import PajekFactory
from util.misc import open_file, Checkpoint
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Creates Pajek (.net) files from WOS XML")
parser.add_argument('outfile')
parser.add_argument('infile', nargs='+')
args = parser.parse_args()
chk = Checkpoint()
nodes = args.outfile + ".nodes"
edges = args.outfile + ".edges"
nodes_f = open_file(nodes, "w")
edges_f = open_file(edges, "w")
parsed = 1
total_files = len(args.infile)
pjk = PajekFactory(node_stream=nodes_f, edge_stream=edges_f)
for file in args.infile:
print(chk.checkpoint("Parsing {}: {}/{}: {:.2%}".format(file, parsed, total_files, parsed/float(total_files))))
f = open_file(file)
parser = WOSStream(f)
for entry in parser.parse():
if "citations" in entry:
for citation in entry["citations"]:
pjk.add_edge(entry["id"], citation)
print(chk.checkpoint(" Done: "+str(pjk)))
parsed += 1
with open_file(args.outfile, "w") as f:
f.writelines(pjk.make_header())
chk.end("Done")
## Instruction:
Add wos-only option to script
## Code After:
from parsers.wos import WOSStream
from util.PajekFactory import PajekFactory
from util.misc import open_file, Checkpoint
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Creates Pajek (.net) files from WOS XML")
parser.add_argument('outfile')
parser.add_argument('--wos-only', action="store_true", help="Only include nodes/edges in WOS")
parser.add_argument('infile', nargs='+')
args = parser.parse_args()
chk = Checkpoint()
nodes = args.outfile + ".nodes"
edges = args.outfile + ".edges"
nodes_f = open_file(nodes, "w")
edges_f = open_file(edges, "w")
parsed = 1
total_files = len(args.infile)
pjk = PajekFactory(node_stream=nodes_f, edge_stream=edges_f)
for file in args.infile:
print(chk.checkpoint("Parsing {}: {}/{}: {:.2%}".format(file, parsed, total_files, parsed/float(total_files))))
f = open_file(file)
parser = WOSStream(f, args.wos_only)
for entry in parser.parse():
if "citations" in entry:
for citation in entry["citations"]:
pjk.add_edge(entry["id"], citation)
print(chk.checkpoint(" Done: "+str(pjk)))
parsed += 1
with open_file(args.outfile, "w") as f:
f.writelines(pjk.make_header())
chk.end("Done")
|
...
import argparse
parser = argparse.ArgumentParser(description="Creates Pajek (.net) files from WOS XML")
parser.add_argument('outfile')
parser.add_argument('--wos-only', action="store_true", help="Only include nodes/edges in WOS")
parser.add_argument('infile', nargs='+')
args = parser.parse_args()
...
for file in args.infile:
print(chk.checkpoint("Parsing {}: {}/{}: {:.2%}".format(file, parsed, total_files, parsed/float(total_files))))
f = open_file(file)
parser = WOSStream(f, args.wos_only)
for entry in parser.parse():
if "citations" in entry:
for citation in entry["citations"]:
...
|
5886d1ba7e199ee47c80476114d442a46ca36a9c
|
src/main/kotlin/org/moe/gradle/utils/PropertiesUtil.kt
|
src/main/kotlin/org/moe/gradle/utils/PropertiesUtil.kt
|
@file:JvmName("PropertiesUtil")
package org.moe.gradle.utils
import groovy.lang.MissingPropertyException
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.internal.project.DefaultProject
import java.util.Properties
private const val LOCAL_PROPERTIES: String = "local.properties"
private fun Project.tryLocalProperty(key: String): String? {
val f = file(LOCAL_PROPERTIES)
if (f.exists()) {
val propFile = Properties()
propFile.load(f.inputStream())
return propFile.getProperty(key)
}
return null
}
fun Project.tryGetProperty(key: String): String? {
val localProp = tryLocalProperty(key)
if (localProp != null) {
return localProp
}
if (hasProperty(key)) {
val result = property(key)
if (result != null && result !is String) {
throw GradleException("Value of $key property is not a String")
}
return result as String?
}
return null
}
@Throws(MissingPropertyException::class)
fun Project.getProperty(key: String): String {
val localProp = tryLocalProperty(key)
if (localProp != null) {
return localProp
}
val result = property(key) ?: throw (this as DefaultProject).asDynamicObject.getMissingProperty(key)
if (result !is String) {
throw GradleException("Value of $key property is not a String")
}
return result
}
|
@file:JvmName("PropertiesUtil")
package org.moe.gradle.utils
import groovy.lang.MissingPropertyException
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.internal.project.DefaultProject
import java.util.Properties
private const val LOCAL_PROPERTIES: String = "local.properties"
private fun Project.tryLocalProperty(key: String): String? {
val f = file(LOCAL_PROPERTIES)
if (f.exists()) {
val propFile = Properties()
propFile.load(f.inputStream())
return propFile.getProperty(key)
}
return parent?.tryLocalProperty(key)
}
fun Project.tryGetProperty(key: String): String? {
val localProp = tryLocalProperty(key)
if (localProp != null) {
return localProp
}
if (hasProperty(key)) {
val result = property(key)
if (result != null && result !is String) {
throw GradleException("Value of $key property is not a String")
}
return result as String?
}
return null
}
@Throws(MissingPropertyException::class)
fun Project.getProperty(key: String): String {
val localProp = tryLocalProperty(key)
if (localProp != null) {
return localProp
}
val result = property(key) ?: throw (this as DefaultProject).asDynamicObject.getMissingProperty(key)
if (result !is String) {
throw GradleException("Value of $key property is not a String")
}
return result
}
|
Support local property on multi-module project
|
Support local property on multi-module project
(cherry picked from commit a3b6dabb0305860cfd36a3c76e1fcf80e3361bf0)
|
Kotlin
|
apache-2.0
|
multi-os-engine/moe-plugin-gradle,multi-os-engine/moe-plugin-gradle
|
kotlin
|
## Code Before:
@file:JvmName("PropertiesUtil")
package org.moe.gradle.utils
import groovy.lang.MissingPropertyException
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.internal.project.DefaultProject
import java.util.Properties
private const val LOCAL_PROPERTIES: String = "local.properties"
private fun Project.tryLocalProperty(key: String): String? {
val f = file(LOCAL_PROPERTIES)
if (f.exists()) {
val propFile = Properties()
propFile.load(f.inputStream())
return propFile.getProperty(key)
}
return null
}
fun Project.tryGetProperty(key: String): String? {
val localProp = tryLocalProperty(key)
if (localProp != null) {
return localProp
}
if (hasProperty(key)) {
val result = property(key)
if (result != null && result !is String) {
throw GradleException("Value of $key property is not a String")
}
return result as String?
}
return null
}
@Throws(MissingPropertyException::class)
fun Project.getProperty(key: String): String {
val localProp = tryLocalProperty(key)
if (localProp != null) {
return localProp
}
val result = property(key) ?: throw (this as DefaultProject).asDynamicObject.getMissingProperty(key)
if (result !is String) {
throw GradleException("Value of $key property is not a String")
}
return result
}
## Instruction:
Support local property on multi-module project
(cherry picked from commit a3b6dabb0305860cfd36a3c76e1fcf80e3361bf0)
## Code After:
@file:JvmName("PropertiesUtil")
package org.moe.gradle.utils
import groovy.lang.MissingPropertyException
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.internal.project.DefaultProject
import java.util.Properties
private const val LOCAL_PROPERTIES: String = "local.properties"
private fun Project.tryLocalProperty(key: String): String? {
val f = file(LOCAL_PROPERTIES)
if (f.exists()) {
val propFile = Properties()
propFile.load(f.inputStream())
return propFile.getProperty(key)
}
return parent?.tryLocalProperty(key)
}
fun Project.tryGetProperty(key: String): String? {
val localProp = tryLocalProperty(key)
if (localProp != null) {
return localProp
}
if (hasProperty(key)) {
val result = property(key)
if (result != null && result !is String) {
throw GradleException("Value of $key property is not a String")
}
return result as String?
}
return null
}
@Throws(MissingPropertyException::class)
fun Project.getProperty(key: String): String {
val localProp = tryLocalProperty(key)
if (localProp != null) {
return localProp
}
val result = property(key) ?: throw (this as DefaultProject).asDynamicObject.getMissingProperty(key)
if (result !is String) {
throw GradleException("Value of $key property is not a String")
}
return result
}
|
...
return propFile.getProperty(key)
}
return parent?.tryLocalProperty(key)
}
fun Project.tryGetProperty(key: String): String? {
...
|
f392baca8bf1982c612f090ec5b7694a1e499ccc
|
app/src/main/kotlin/de/markusfisch/android/binaryeye/app/BinaryEyeApp.kt
|
app/src/main/kotlin/de/markusfisch/android/binaryeye/app/BinaryEyeApp.kt
|
package de.markusfisch.android.binaryeye.app
import android.app.Application
import android.support.v8.renderscript.RenderScript
import de.markusfisch.android.binaryeye.data.Database
import de.markusfisch.android.binaryeye.preference.Preferences
val db = Database()
val prefs = Preferences()
class BinaryEyeApp : Application() {
override fun onCreate() {
super.onCreate()
prefs.init(this)
if (prefs.forceCompat ||
System.getProperty("os.version")?.contains(
"lineageos", true
) == true
) {
// required to make RenderScript work on Lineage 16.0
RenderScript.forceCompat()
}
db.open(this)
}
}
|
package de.markusfisch.android.binaryeye.app
import android.app.Application
import android.support.v8.renderscript.RenderScript
import de.markusfisch.android.binaryeye.data.Database
import de.markusfisch.android.binaryeye.preference.Preferences
val db = Database()
val prefs = Preferences()
class BinaryEyeApp : Application() {
override fun onCreate() {
super.onCreate()
prefs.init(this)
if (prefs.forceCompat) {
RenderScript.forceCompat()
}
db.open(this)
}
}
|
Remove special RenderScript handling for LineageOS
|
Remove special RenderScript handling for LineageOS
Always running `RenderScript.forceCompat()` interferes with the
`forceCompat` flag that is set/unset if there is a RSRuntimeException.
Now that the app is restarting automatically for a RSRuntimeException
this special handling is no longer required anyway.
|
Kotlin
|
mit
|
markusfisch/BinaryEye,markusfisch/BinaryEye
|
kotlin
|
## Code Before:
package de.markusfisch.android.binaryeye.app
import android.app.Application
import android.support.v8.renderscript.RenderScript
import de.markusfisch.android.binaryeye.data.Database
import de.markusfisch.android.binaryeye.preference.Preferences
val db = Database()
val prefs = Preferences()
class BinaryEyeApp : Application() {
override fun onCreate() {
super.onCreate()
prefs.init(this)
if (prefs.forceCompat ||
System.getProperty("os.version")?.contains(
"lineageos", true
) == true
) {
// required to make RenderScript work on Lineage 16.0
RenderScript.forceCompat()
}
db.open(this)
}
}
## Instruction:
Remove special RenderScript handling for LineageOS
Always running `RenderScript.forceCompat()` interferes with the
`forceCompat` flag that is set/unset if there is a RSRuntimeException.
Now that the app is restarting automatically for a RSRuntimeException
this special handling is no longer required anyway.
## Code After:
package de.markusfisch.android.binaryeye.app
import android.app.Application
import android.support.v8.renderscript.RenderScript
import de.markusfisch.android.binaryeye.data.Database
import de.markusfisch.android.binaryeye.preference.Preferences
val db = Database()
val prefs = Preferences()
class BinaryEyeApp : Application() {
override fun onCreate() {
super.onCreate()
prefs.init(this)
if (prefs.forceCompat) {
RenderScript.forceCompat()
}
db.open(this)
}
}
|
# ... existing code ...
super.onCreate()
prefs.init(this)
if (prefs.forceCompat) {
RenderScript.forceCompat()
}
# ... rest of the code ...
|
018e76e5aa2a7ca8652af008a3b658017b3f178d
|
thefederation/tests/factories.py
|
thefederation/tests/factories.py
|
import factory
from django.utils.timezone import utc, now
from thefederation.models import Node, Platform, Protocol, Stat
class PlatformFactory(factory.DjangoModelFactory):
name = factory.Faker('word')
class Meta:
model = Platform
class ProtocolFactory(factory.DjangoModelFactory):
name = factory.Faker('word')
class Meta:
model = Protocol
class NodeFactory(factory.DjangoModelFactory):
host = factory.Sequence(lambda n: 'node%s.local' % n)
name = factory.Faker('company')
open_signups = factory.Faker('pybool')
platform = factory.SubFactory(PlatformFactory)
class Meta:
model = Node
class Params:
active = factory.Trait(
last_success = factory.Faker('past_datetime', start_date='-1d', tzinfo=utc),
)
@factory.post_generation
def protocols(self, create, extracted, **kwargs):
if not create:
return
if extracted:
self.protocols.add(extracted)
return
self.protocols.add(ProtocolFactory())
class StatFactory(factory.DjangoModelFactory):
date = now().date()
node = factory.SubFactory(NodeFactory)
users_total = factory.Faker('pyint')
users_half_year = factory.Faker('pyint')
users_monthly = factory.Faker('pyint')
users_weekly = factory.Faker('pyint')
class Meta:
model = Stat
|
import factory
from django.utils.timezone import utc, now
from thefederation.models import Node, Platform, Protocol, Stat
class PlatformFactory(factory.DjangoModelFactory):
name = factory.Faker('pystr')
class Meta:
model = Platform
class ProtocolFactory(factory.DjangoModelFactory):
name = factory.Faker('pystr')
class Meta:
model = Protocol
class NodeFactory(factory.DjangoModelFactory):
host = factory.Sequence(lambda n: 'node%s.local' % n)
name = factory.Faker('company')
open_signups = factory.Faker('pybool')
platform = factory.SubFactory(PlatformFactory)
class Meta:
model = Node
class Params:
active = factory.Trait(
last_success = factory.Faker('past_datetime', start_date='-1d', tzinfo=utc),
)
@factory.post_generation
def protocols(self, create, extracted, **kwargs):
if not create:
return
if extracted:
self.protocols.add(extracted)
return
self.protocols.add(ProtocolFactory())
class StatFactory(factory.DjangoModelFactory):
date = now().date()
node = factory.SubFactory(NodeFactory)
users_total = factory.Faker('pyint')
users_half_year = factory.Faker('pyint')
users_monthly = factory.Faker('pyint')
users_weekly = factory.Faker('pyint')
class Meta:
model = Stat
|
Make factory random names a bit more random to avoid clashes
|
Make factory random names a bit more random to avoid clashes
|
Python
|
agpl-3.0
|
jaywink/the-federation.info,jaywink/diaspora-hub,jaywink/diaspora-hub,jaywink/diaspora-hub,jaywink/the-federation.info,jaywink/the-federation.info
|
python
|
## Code Before:
import factory
from django.utils.timezone import utc, now
from thefederation.models import Node, Platform, Protocol, Stat
class PlatformFactory(factory.DjangoModelFactory):
name = factory.Faker('word')
class Meta:
model = Platform
class ProtocolFactory(factory.DjangoModelFactory):
name = factory.Faker('word')
class Meta:
model = Protocol
class NodeFactory(factory.DjangoModelFactory):
host = factory.Sequence(lambda n: 'node%s.local' % n)
name = factory.Faker('company')
open_signups = factory.Faker('pybool')
platform = factory.SubFactory(PlatformFactory)
class Meta:
model = Node
class Params:
active = factory.Trait(
last_success = factory.Faker('past_datetime', start_date='-1d', tzinfo=utc),
)
@factory.post_generation
def protocols(self, create, extracted, **kwargs):
if not create:
return
if extracted:
self.protocols.add(extracted)
return
self.protocols.add(ProtocolFactory())
class StatFactory(factory.DjangoModelFactory):
date = now().date()
node = factory.SubFactory(NodeFactory)
users_total = factory.Faker('pyint')
users_half_year = factory.Faker('pyint')
users_monthly = factory.Faker('pyint')
users_weekly = factory.Faker('pyint')
class Meta:
model = Stat
## Instruction:
Make factory random names a bit more random to avoid clashes
## Code After:
import factory
from django.utils.timezone import utc, now
from thefederation.models import Node, Platform, Protocol, Stat
class PlatformFactory(factory.DjangoModelFactory):
name = factory.Faker('pystr')
class Meta:
model = Platform
class ProtocolFactory(factory.DjangoModelFactory):
name = factory.Faker('pystr')
class Meta:
model = Protocol
class NodeFactory(factory.DjangoModelFactory):
host = factory.Sequence(lambda n: 'node%s.local' % n)
name = factory.Faker('company')
open_signups = factory.Faker('pybool')
platform = factory.SubFactory(PlatformFactory)
class Meta:
model = Node
class Params:
active = factory.Trait(
last_success = factory.Faker('past_datetime', start_date='-1d', tzinfo=utc),
)
@factory.post_generation
def protocols(self, create, extracted, **kwargs):
if not create:
return
if extracted:
self.protocols.add(extracted)
return
self.protocols.add(ProtocolFactory())
class StatFactory(factory.DjangoModelFactory):
date = now().date()
node = factory.SubFactory(NodeFactory)
users_total = factory.Faker('pyint')
users_half_year = factory.Faker('pyint')
users_monthly = factory.Faker('pyint')
users_weekly = factory.Faker('pyint')
class Meta:
model = Stat
|
// ... existing code ...
class PlatformFactory(factory.DjangoModelFactory):
name = factory.Faker('pystr')
class Meta:
model = Platform
// ... modified code ...
class ProtocolFactory(factory.DjangoModelFactory):
name = factory.Faker('pystr')
class Meta:
model = Protocol
// ... rest of the code ...
|
c0d5a95745e15c8f215a66445cca5e05e46e0c10
|
arc/arc/Controllers/Protocols/FolderViewControllerDelegate.h
|
arc/arc/Controllers/Protocols/FolderViewControllerDelegate.h
|
//
// FolderViewControllerDelegate.h
// arc
//
// Created by Jerome Cheng on 17/4/13.
// Copyright (c) 2013 nus.cs3217. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "File.h"
#import "Folder.h"
@class FolderViewController;
@protocol FolderViewControllerDelegate <NSObject>
- (void)folderViewController:(FolderViewController *)sender selectedFile:(id<File>)file;
- (void)folderViewController:(FolderViewController *)sender selectedFolder:(id<Folder>)folder;
@end
|
//
// FolderViewControllerDelegate.h
// arc
//
// Created by Jerome Cheng on 17/4/13.
// Copyright (c) 2013 nus.cs3217. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "File.h"
#import "Folder.h"
@class FolderViewController;
@protocol FolderViewControllerDelegate <NSObject>
// Allows delegate to know which file or folder was selected in navigation mode.
- (void)folderViewController:(FolderViewController *)sender selectedFile:(id<File>)file;
- (void)folderViewController:(FolderViewController *)sender selectedFolder:(id<Folder>)folder;
// Allows the delegate to know if the controller has entered or left editing mode.
- (void)folderViewController:(FolderViewController *)folderviewController
DidEnterEditModeAnimate:(BOOL)animate;
- (void)folderViewController:(FolderViewController *)folderviewController DidExitEditModeAnimate:(BOOL)animate;
@end
|
Add methods to notify FolderView delegate when edit mode is toggled.
|
Add methods to notify FolderView delegate when edit mode is toggled.
|
C
|
mit
|
BenTobias/arc,BenTobias/arc,BenTobias/arc,BenTobias/arc,BenTobias/arc,BenTobias/arc
|
c
|
## Code Before:
//
// FolderViewControllerDelegate.h
// arc
//
// Created by Jerome Cheng on 17/4/13.
// Copyright (c) 2013 nus.cs3217. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "File.h"
#import "Folder.h"
@class FolderViewController;
@protocol FolderViewControllerDelegate <NSObject>
- (void)folderViewController:(FolderViewController *)sender selectedFile:(id<File>)file;
- (void)folderViewController:(FolderViewController *)sender selectedFolder:(id<Folder>)folder;
@end
## Instruction:
Add methods to notify FolderView delegate when edit mode is toggled.
## Code After:
//
// FolderViewControllerDelegate.h
// arc
//
// Created by Jerome Cheng on 17/4/13.
// Copyright (c) 2013 nus.cs3217. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "File.h"
#import "Folder.h"
@class FolderViewController;
@protocol FolderViewControllerDelegate <NSObject>
// Allows delegate to know which file or folder was selected in navigation mode.
- (void)folderViewController:(FolderViewController *)sender selectedFile:(id<File>)file;
- (void)folderViewController:(FolderViewController *)sender selectedFolder:(id<Folder>)folder;
// Allows the delegate to know if the controller has entered or left editing mode.
- (void)folderViewController:(FolderViewController *)folderviewController
DidEnterEditModeAnimate:(BOOL)animate;
- (void)folderViewController:(FolderViewController *)folderviewController DidExitEditModeAnimate:(BOOL)animate;
@end
|
...
@protocol FolderViewControllerDelegate <NSObject>
// Allows delegate to know which file or folder was selected in navigation mode.
- (void)folderViewController:(FolderViewController *)sender selectedFile:(id<File>)file;
- (void)folderViewController:(FolderViewController *)sender selectedFolder:(id<Folder>)folder;
// Allows the delegate to know if the controller has entered or left editing mode.
- (void)folderViewController:(FolderViewController *)folderviewController
DidEnterEditModeAnimate:(BOOL)animate;
- (void)folderViewController:(FolderViewController *)folderviewController DidExitEditModeAnimate:(BOOL)animate;
@end
...
|
905ddcef2652c53e39669d5d8e861924751fc802
|
setup.py
|
setup.py
|
from setuptools import setup
setup(name = 'OWSLib',
version = '0.1.0',
description = 'OGC Web Service utility library',
license = 'GPL',
keywords = 'gis ogc ows wfs wms capabilities metadata',
author = 'Sean Gillies',
author_email = '[email protected]',
maintainer = 'Sean Gillies',
maintainer_email = '[email protected]',
url = 'http://trac.gispython.org/projects/PCL/wiki/OwsLib',
packages = ['owslib'],
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Scientific/Engineering :: GIS',
],
)
|
from setuptools import setup
setup(name = 'OWSLib',
version = '0.2.0',
description = 'OGC Web Service utility library',
license = 'BSD',
keywords = 'gis ogc ows wfs wms capabilities metadata',
author = 'Sean Gillies',
author_email = '[email protected]',
maintainer = 'Sean Gillies',
maintainer_email = '[email protected]',
url = 'http://trac.gispython.org/projects/PCL/wiki/OwsLib',
packages = ['owslib'],
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Scientific/Engineering :: GIS',
],
)
|
Change version and license for 0.2
|
Change version and license for 0.2
|
Python
|
bsd-3-clause
|
ocefpaf/OWSLib,bird-house/OWSLib,kwilcox/OWSLib,daf/OWSLib,jaygoldfinch/OWSLib,daf/OWSLib,QuLogic/OWSLib,datagovuk/OWSLib,Jenselme/OWSLib,dblodgett-usgs/OWSLib,datagovuk/OWSLib,tomkralidis/OWSLib,b-cube/OWSLib,menegon/OWSLib,kalxas/OWSLib,mbertrand/OWSLib,robmcmullen/OWSLib,geopython/OWSLib,gfusca/OWSLib,jachym/OWSLib,daf/OWSLib,geographika/OWSLib,JuergenWeichand/OWSLib,jaygoldfinch/OWSLib,KeyproOy/OWSLib,datagovuk/OWSLib
|
python
|
## Code Before:
from setuptools import setup
setup(name = 'OWSLib',
version = '0.1.0',
description = 'OGC Web Service utility library',
license = 'GPL',
keywords = 'gis ogc ows wfs wms capabilities metadata',
author = 'Sean Gillies',
author_email = '[email protected]',
maintainer = 'Sean Gillies',
maintainer_email = '[email protected]',
url = 'http://trac.gispython.org/projects/PCL/wiki/OwsLib',
packages = ['owslib'],
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Scientific/Engineering :: GIS',
],
)
## Instruction:
Change version and license for 0.2
## Code After:
from setuptools import setup
setup(name = 'OWSLib',
version = '0.2.0',
description = 'OGC Web Service utility library',
license = 'BSD',
keywords = 'gis ogc ows wfs wms capabilities metadata',
author = 'Sean Gillies',
author_email = '[email protected]',
maintainer = 'Sean Gillies',
maintainer_email = '[email protected]',
url = 'http://trac.gispython.org/projects/PCL/wiki/OwsLib',
packages = ['owslib'],
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Scientific/Engineering :: GIS',
],
)
|
...
from setuptools import setup
setup(name = 'OWSLib',
version = '0.2.0',
description = 'OGC Web Service utility library',
license = 'BSD',
keywords = 'gis ogc ows wfs wms capabilities metadata',
author = 'Sean Gillies',
author_email = '[email protected]',
...
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Scientific/Engineering :: GIS',
...
|
5953acb8d720489d63f0bb8fe61da2180bf0926c
|
src/main/java/com/github/aureliano/verbum_domini/domain/bean/IBean.java
|
src/main/java/com/github/aureliano/verbum_domini/domain/bean/IBean.java
|
package com.github.aureliano.verbum_domini.domain.bean;
import java.io.Serializable;
public interface IBean extends Serializable {
public abstract <T extends Object> T toResource();
}
|
package com.github.aureliano.verbum_domini.domain.bean;
import java.io.Serializable;
public interface IBean extends Serializable {
public abstract Integer getId();
public abstract <T extends Object> T toResource();
}
|
Define id reader as contract method.
|
Define id reader as contract method.
|
Java
|
mit
|
aureliano/verbum-domini,aureliano/verbum-domini,aureliano/verbum-domini,aureliano/verbum-domini
|
java
|
## Code Before:
package com.github.aureliano.verbum_domini.domain.bean;
import java.io.Serializable;
public interface IBean extends Serializable {
public abstract <T extends Object> T toResource();
}
## Instruction:
Define id reader as contract method.
## Code After:
package com.github.aureliano.verbum_domini.domain.bean;
import java.io.Serializable;
public interface IBean extends Serializable {
public abstract Integer getId();
public abstract <T extends Object> T toResource();
}
|
# ... existing code ...
public interface IBean extends Serializable {
public abstract Integer getId();
public abstract <T extends Object> T toResource();
}
# ... rest of the code ...
|
10f5254d144aaa8af56eb6445cea08a491d9fcb8
|
loader/problem.h
|
loader/problem.h
|
// Explorer loader problem list
// /problem.h
#ifndef PROBLEM_H_
#define PROBLEM_H_
/**错误列表*/
#define ERR_NO_MEM_FOR_ID 1 // 没有可用于中断描述符表的内存
#define ERR_NO_MEM_FOR_SD 2 // 没有可用于储存器描述符表的内存
#define ERR_NO_MEM_FOR_SCTBUF 3 // 没有可用于扇区缓存的内存
#define ERR_NO_MEM_FOR_CONFIG 4 // 没有可以分配给引导配置文件的内存
#define ERR_NO_MEM_FOR_BUFFER 5 // 没有可以分配给缓冲系统的内存
#define ERR_NO_MEM_FOR_FS 6 // 没有可以分配给文件系统的内存
#define ERR_NO_MEM_FOR_MMU 7 // 没有可以分配给MMU的内存
/**警告列表*/
#define WARN_NO_MEM 0x80000001 // 无充足内存
#define WARN_STORAGE_NOT_SUPPORT 0x80000002 // 暂时不支持这个储存器
#endif
|
// Explorer loader problem list
// /problem.h
#ifndef PROBLEM_H_
#define PROBLEM_H_
/**错误列表*/
#define ERR_NO_MEM_FOR_ID 1 // 没有可用于中断描述符表的内存
#define ERR_NO_MEM_FOR_SD 2 // 没有可用于储存器描述符表的内存
#define ERR_NO_MEM_FOR_SCTBUF 3 // 没有可用于扇区缓存的内存
#define ERR_NO_MEM_FOR_CONFIG 4 // 没有可以分配给引导配置文件的内存
#define ERR_NO_MEM_FOR_BUFFER 5 // 没有可以分配给缓冲系统的内存
#define ERR_NO_MEM_FOR_FS 6 // 没有可以分配给文件系统的内存
#define ERR_NO_MEM_FOR_MMU 7 // 没有可以分配给MMU的内存
#define ERR_NO_FILE 8 // 没有文件
#define ERR_CONFIG_OVERSIZE 9 // CONFIG.LDR oversized
/**警告列表*/
#define WARN_NO_MEM 0x80000001 // 无充足内存
#define WARN_STORAGE_NOT_SUPPORT 0x80000002 // 暂时不支持这个储存器
#define WARN_SCRIPT_SIZE_BAD 0x80000003 // length of cript incorrect
#endif
|
Add new error and warning number
|
Add new error and warning number
|
C
|
bsd-2-clause
|
MakeOS/GhostBirdOS,MakeOS/GhostBirdOS
|
c
|
## Code Before:
// Explorer loader problem list
// /problem.h
#ifndef PROBLEM_H_
#define PROBLEM_H_
/**错误列表*/
#define ERR_NO_MEM_FOR_ID 1 // 没有可用于中断描述符表的内存
#define ERR_NO_MEM_FOR_SD 2 // 没有可用于储存器描述符表的内存
#define ERR_NO_MEM_FOR_SCTBUF 3 // 没有可用于扇区缓存的内存
#define ERR_NO_MEM_FOR_CONFIG 4 // 没有可以分配给引导配置文件的内存
#define ERR_NO_MEM_FOR_BUFFER 5 // 没有可以分配给缓冲系统的内存
#define ERR_NO_MEM_FOR_FS 6 // 没有可以分配给文件系统的内存
#define ERR_NO_MEM_FOR_MMU 7 // 没有可以分配给MMU的内存
/**警告列表*/
#define WARN_NO_MEM 0x80000001 // 无充足内存
#define WARN_STORAGE_NOT_SUPPORT 0x80000002 // 暂时不支持这个储存器
#endif
## Instruction:
Add new error and warning number
## Code After:
// Explorer loader problem list
// /problem.h
#ifndef PROBLEM_H_
#define PROBLEM_H_
/**错误列表*/
#define ERR_NO_MEM_FOR_ID 1 // 没有可用于中断描述符表的内存
#define ERR_NO_MEM_FOR_SD 2 // 没有可用于储存器描述符表的内存
#define ERR_NO_MEM_FOR_SCTBUF 3 // 没有可用于扇区缓存的内存
#define ERR_NO_MEM_FOR_CONFIG 4 // 没有可以分配给引导配置文件的内存
#define ERR_NO_MEM_FOR_BUFFER 5 // 没有可以分配给缓冲系统的内存
#define ERR_NO_MEM_FOR_FS 6 // 没有可以分配给文件系统的内存
#define ERR_NO_MEM_FOR_MMU 7 // 没有可以分配给MMU的内存
#define ERR_NO_FILE 8 // 没有文件
#define ERR_CONFIG_OVERSIZE 9 // CONFIG.LDR oversized
/**警告列表*/
#define WARN_NO_MEM 0x80000001 // 无充足内存
#define WARN_STORAGE_NOT_SUPPORT 0x80000002 // 暂时不支持这个储存器
#define WARN_SCRIPT_SIZE_BAD 0x80000003 // length of cript incorrect
#endif
|
# ... existing code ...
#define PROBLEM_H_
/**错误列表*/
#define ERR_NO_MEM_FOR_ID 1 // 没有可用于中断描述符表的内存
#define ERR_NO_MEM_FOR_SD 2 // 没有可用于储存器描述符表的内存
#define ERR_NO_MEM_FOR_SCTBUF 3 // 没有可用于扇区缓存的内存
#define ERR_NO_MEM_FOR_CONFIG 4 // 没有可以分配给引导配置文件的内存
#define ERR_NO_MEM_FOR_BUFFER 5 // 没有可以分配给缓冲系统的内存
#define ERR_NO_MEM_FOR_FS 6 // 没有可以分配给文件系统的内存
#define ERR_NO_MEM_FOR_MMU 7 // 没有可以分配给MMU的内存
#define ERR_NO_FILE 8 // 没有文件
#define ERR_CONFIG_OVERSIZE 9 // CONFIG.LDR oversized
/**警告列表*/
#define WARN_NO_MEM 0x80000001 // 无充足内存
#define WARN_STORAGE_NOT_SUPPORT 0x80000002 // 暂时不支持这个储存器
#define WARN_SCRIPT_SIZE_BAD 0x80000003 // length of cript incorrect
#endif
# ... rest of the code ...
|
c2bb7f0461599cc7624b8d844be93b6912fc0b1d
|
examples/test_filter_strings.py
|
examples/test_filter_strings.py
|
def test_filter_strings(wish):
accept_names = wish
names = ['has MARK', 'does not have']
accept_pattern = '.*MARK.*'
|
def test_filter_strings_basic(wish):
filter_strings = wish
input = ['has MARK', 'does not have']
expected_ouput = ['has MARK']
accept_pattern = '.*MARK.*'
assert list(filter_strings(input, accept_pattern)) == expected_ouput
|
Complete unfinished code committed by mistake.
|
Complete unfinished code committed by mistake.
|
Python
|
mit
|
nodev-io/pytest-nodev,alexamici/pytest-wish,alexamici/pytest-nodev
|
python
|
## Code Before:
def test_filter_strings(wish):
accept_names = wish
names = ['has MARK', 'does not have']
accept_pattern = '.*MARK.*'
## Instruction:
Complete unfinished code committed by mistake.
## Code After:
def test_filter_strings_basic(wish):
filter_strings = wish
input = ['has MARK', 'does not have']
expected_ouput = ['has MARK']
accept_pattern = '.*MARK.*'
assert list(filter_strings(input, accept_pattern)) == expected_ouput
|
// ... existing code ...
def test_filter_strings_basic(wish):
filter_strings = wish
input = ['has MARK', 'does not have']
expected_ouput = ['has MARK']
accept_pattern = '.*MARK.*'
assert list(filter_strings(input, accept_pattern)) == expected_ouput
// ... rest of the code ...
|
df8618c185108aa71e42da7d9569e16fb350b4c0
|
hackeriet/doorcontrold/__init__.py
|
hackeriet/doorcontrold/__init__.py
|
from hackeriet.mqtt import MQTT
from hackeriet.door import Doors
import threading, os, logging
logging.basicConfig(level=logging.INFO, format='%(asctime)-15s %(message)s')
piface = False
# Determine if piface is used on the Pi
if "PIFACE" in os.environ:
piface = True
logging.info('Using piface configuration')
# Be backwards compatible with old env variable name
gpio_pin = int(os.getenv("DOOR_GPIO_PIN", os.getenv("DOOR_PIN", 0)))
# How many seconds should the door lock remain open
timeout = int(os.getenv("DOOR_TIMEOUT", 2))
door = Doors(piface=piface,pin=gpio_pin,timeout=timeout)
mqtt = MQTT()
door_name = os.getenv("DOOR_NAME", 'hackeriet')
door_topic = "hackeriet/door/%s/open" % door_name
mqtt.subscribe(door_topic, 0)
def on_message(mosq, obj, msg):
door.open()
logging('Door opened: %s' % msg.payload.decode())
mqtt.on_message = on_message
# Block forever
def main():
for t in threading.enumerate():
if t us threading.currentThread():
continue
t.join()
if __name__ == "__main__":
main()
|
from hackeriet.mqtt import MQTT
from hackeriet.door import Doors
import threading, os, logging
logging.basicConfig(level=logging.INFO, format='%(asctime)-15s %(message)s')
piface = False
# Determine if piface is used on the Pi
if "PIFACE" in os.environ:
piface = True
logging.info('Using piface configuration')
# Be backwards compatible with old env variable name
gpio_pin = int(os.getenv("DOOR_GPIO_PIN", os.getenv("DOOR_PIN", 0)))
# How many seconds should the door lock remain open
timeout = int(os.getenv("DOOR_TIMEOUT", 2))
door = Doors(piface=piface,pin=gpio_pin,timeout=timeout)
def on_message(mosq, obj, msg):
door.open()
logging.info('Door opened: %s' % msg.payload
door_name = os.getenv("DOOR_NAME", 'hackeriet')
door_topic = "hackeriet/door/%s/open" % door_name
mqtt = MQTT(on_message)
mqtt.subscribe(door_topic, 0)
# Block forever
def main():
for t in threading.enumerate():
if t us threading.currentThread():
continue
t.join()
if __name__ == "__main__":
main()
|
Fix incompatibilities with latest paho lib
|
Fix incompatibilities with latest paho lib
|
Python
|
apache-2.0
|
hackeriet/pyhackeriet,hackeriet/pyhackeriet,hackeriet/nfcd,hackeriet/nfcd,hackeriet/pyhackeriet,hackeriet/nfcd
|
python
|
## Code Before:
from hackeriet.mqtt import MQTT
from hackeriet.door import Doors
import threading, os, logging
logging.basicConfig(level=logging.INFO, format='%(asctime)-15s %(message)s')
piface = False
# Determine if piface is used on the Pi
if "PIFACE" in os.environ:
piface = True
logging.info('Using piface configuration')
# Be backwards compatible with old env variable name
gpio_pin = int(os.getenv("DOOR_GPIO_PIN", os.getenv("DOOR_PIN", 0)))
# How many seconds should the door lock remain open
timeout = int(os.getenv("DOOR_TIMEOUT", 2))
door = Doors(piface=piface,pin=gpio_pin,timeout=timeout)
mqtt = MQTT()
door_name = os.getenv("DOOR_NAME", 'hackeriet')
door_topic = "hackeriet/door/%s/open" % door_name
mqtt.subscribe(door_topic, 0)
def on_message(mosq, obj, msg):
door.open()
logging('Door opened: %s' % msg.payload.decode())
mqtt.on_message = on_message
# Block forever
def main():
for t in threading.enumerate():
if t us threading.currentThread():
continue
t.join()
if __name__ == "__main__":
main()
## Instruction:
Fix incompatibilities with latest paho lib
## Code After:
from hackeriet.mqtt import MQTT
from hackeriet.door import Doors
import threading, os, logging
logging.basicConfig(level=logging.INFO, format='%(asctime)-15s %(message)s')
piface = False
# Determine if piface is used on the Pi
if "PIFACE" in os.environ:
piface = True
logging.info('Using piface configuration')
# Be backwards compatible with old env variable name
gpio_pin = int(os.getenv("DOOR_GPIO_PIN", os.getenv("DOOR_PIN", 0)))
# How many seconds should the door lock remain open
timeout = int(os.getenv("DOOR_TIMEOUT", 2))
door = Doors(piface=piface,pin=gpio_pin,timeout=timeout)
def on_message(mosq, obj, msg):
door.open()
logging.info('Door opened: %s' % msg.payload
door_name = os.getenv("DOOR_NAME", 'hackeriet')
door_topic = "hackeriet/door/%s/open" % door_name
mqtt = MQTT(on_message)
mqtt.subscribe(door_topic, 0)
# Block forever
def main():
for t in threading.enumerate():
if t us threading.currentThread():
continue
t.join()
if __name__ == "__main__":
main()
|
...
timeout = int(os.getenv("DOOR_TIMEOUT", 2))
door = Doors(piface=piface,pin=gpio_pin,timeout=timeout)
def on_message(mosq, obj, msg):
door.open()
logging.info('Door opened: %s' % msg.payload
door_name = os.getenv("DOOR_NAME", 'hackeriet')
door_topic = "hackeriet/door/%s/open" % door_name
mqtt = MQTT(on_message)
mqtt.subscribe(door_topic, 0)
# Block forever
def main():
...
|
c66756e164965158fe37ae73b9b056bd37bf71aa
|
src/com/xtremelabs/droidsugar/view/ResourceLoader.java
|
src/com/xtremelabs/droidsugar/view/ResourceLoader.java
|
package com.xtremelabs.droidsugar.view;
import java.io.File;
public class ResourceLoader {
public final ViewLoader viewLoader;
public final StringResourceLoader stringResourceLoader;
public ResourceLoader(Class rClass, File resourceDir) throws Exception {
ResourceExtractor resourceExtractor = new ResourceExtractor();
resourceExtractor.addRClass(rClass);
viewLoader = new ViewLoader(resourceExtractor);
viewLoader.addResourceXmlDir(new File(resourceDir, "layout"));
stringResourceLoader = new StringResourceLoader(resourceExtractor);
stringResourceLoader.addResourceXmlDir(new File(resourceDir, "values"));
}
}
|
package com.xtremelabs.droidsugar.view;
import java.io.File;
import java.io.FileFilter;
public class ResourceLoader {
public final ViewLoader viewLoader;
public final StringResourceLoader stringResourceLoader;
public ResourceLoader(Class rClass, File resourceDir) throws Exception {
ResourceExtractor resourceExtractor = new ResourceExtractor();
resourceExtractor.addRClass(rClass);
viewLoader = new ViewLoader(resourceExtractor);
File[] layoutDirs = resourceDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getPath().contains("/layout");
}
});
for (File layoutDir : layoutDirs) {
viewLoader.addResourceXmlDir(layoutDir);
}
stringResourceLoader = new StringResourceLoader(resourceExtractor);
stringResourceLoader.addResourceXmlDir(new File(resourceDir, "values"));
}
}
|
Load resources from all layout* directories
|
Load resources from all layout* directories
|
Java
|
mit
|
tuenti/robolectric,tuenti/robolectric,yinquan529/platform-external-robolectric,android-ia/platform_external_robolectric,paulpv/robolectric,Omegaphora/external_robolectric,ocadotechnology/robolectric,ChameleonOS/android_external_robolectric,WonderCsabo/robolectric,thiz11/platform_external_robolectric,tyronen/robolectric,karlicoss/robolectric,upsight/playhaven-robolectric,pivotal-oscar/robolectric,mag/robolectric,pivotal-oscar/robolectric,yxm4109/robolectric,ChengCorp/robolectric,spotify/robolectric,ecgreb/robolectric,tmrudick/robolectric,tjohn/robolectric,daisy1754/robolectric,spotify/robolectric,rossimo/robolectric,MIPS/external-robolectric,hgl888/robolectric,android-ia/platform_external_robolectric,kriegfrj/robolectric,cesar1000/robolectric,BCGDV/robolectric,ChameleonOS/android_external_robolectric,VikingDen/robolectric,tyronen/robolectric,lexs/robolectric,toluju/robolectric,diegotori/robolectric,1zaman/robolectric,zbsz/robolectric,geekboxzone/lollipop_external_robolectric,rossimo/robolectric,geekboxzone/lollipop_external_robolectric,geekboxzone/lollipop_external_robolectric,cc12703/robolectric,holmari/robolectric,davidsun/robolectric,palfrey/robolectric,charlesmunger/robolectric,toluju/robolectric,macklinu/robolectric,palfrey/robolectric,mag/robolectric,1zaman/robolectric,androidgilbert/robolectric,ChengCorp/robolectric,gruszczy/robolectric,MIPS/external-robolectric,lexs/robolectric,trevorrjohn/robolectric,gb112211/robolectric,yuzhong-google/robolectric,MIPS/external-robolectric,svenji/robolectric,IllusionRom-deprecated/android_platform_external_robolectric,fiower/robolectric,daisy1754/robolectric,jongerrish/robolectric,rongou/robolectric,ecgreb/robolectric,diegotori/robolectric,spotify/robolectric,tyronen/robolectric,tjohn/robolectric,erichaugh/robolectric,ChengCorp/robolectric,karlicoss/robolectric,gabrielduque/robolectric,IllusionRom-deprecated/android_platform_external_robolectric,ocadotechnology/robolectric,tuenti/robolectric,1zaman/robolectric,charlesmunger/robolectric,davidsun/robolectric,xin3liang/platform_external_robolectric,androidgilbert/robolectric,palfrey/robolectric,zbsz/robolectric,tec27/robolectric,gabrielduque/robolectric,fiower/robolectric,hgl888/robolectric,Omegaphora/external_robolectric,davidsun/robolectric,rongou/robolectric,VikingDen/robolectric,tec27/robolectric,IllusionRom-deprecated/android_platform_external_robolectric,paulpv/robolectric,hgl888/robolectric,androidgilbert/robolectric,jongerrish/robolectric,WonderCsabo/robolectric,tjohn/robolectric,gb112211/robolectric,daisy1754/robolectric,yuzhong-google/robolectric,geekboxzone/mmallow_external_robolectric,mag/robolectric,BCGDV/robolectric,tmrudick/robolectric,tmrudick/robolectric,yinquan529/platform-external-robolectric,wyvx/robolectric,svenji/robolectric,zhongyu05/robolectric,eric-kansas/robolectric,zbsz/robolectric,geekboxzone/mmallow_external_robolectric,VikingDen/robolectric,trevorrjohn/robolectric,amarts/robolectric,ecgreb/robolectric,amarts/robolectric,charlesmunger/robolectric,androidgilbert/robolectric,gruszczy/robolectric,Omegaphora/external_robolectric,macklinu/robolectric,diegotori/robolectric,jingle1267/robolectric,erichaugh/robolectric,tec27/robolectric,yinquan529/platform-external-robolectric,lexs/robolectric,fiower/robolectric,geekboxzone/mmallow_external_robolectric,karlicoss/robolectric,Omegaphora/external_robolectric,BCGDV/robolectric,cesar1000/robolectric,geekboxzone/lollipop_external_robolectric,plackemacher/robolectric,eric-kansas/robolectric,plackemacher/robolectric,xin3liang/platform_external_robolectric,xin3liang/platform_external_robolectric,gabrielduque/robolectric,android-ia/platform_external_robolectric,macklinu/robolectric,jingle1267/robolectric,yxm4109/robolectric,thiz11/platform_external_robolectric,android-ia/platform_external_robolectric,trevorrjohn/robolectric,jongerrish/robolectric,cc12703/robolectric,yxm4109/robolectric,holmari/robolectric,yinquan529/platform-external-robolectric,ChameleonOS/android_external_robolectric,rburgst/robolectric,BCGDV/robolectric,rongou/robolectric,yuzhong-google/robolectric,thiz11/platform_external_robolectric,cesar1000/robolectric,yxm4109/robolectric,ocadotechnology/robolectric,gb112211/robolectric,rburgst/robolectric,geekboxzone/mmallow_external_robolectric,eric-kansas/robolectric,zhongyu05/robolectric,pivotal-oscar/robolectric,wyvx/robolectric,kriegfrj/robolectric,rossimo/robolectric,jingle1267/robolectric,wyvx/robolectric,gruszczy/robolectric,erichaugh/robolectric,svenji/robolectric,paulpv/robolectric,rburgst/robolectric,holmari/robolectric,toluju/robolectric,plackemacher/robolectric,amarts/robolectric,WonderCsabo/robolectric,jongerrish/robolectric,kriegfrj/robolectric,cc12703/robolectric,zhongyu05/robolectric
|
java
|
## Code Before:
package com.xtremelabs.droidsugar.view;
import java.io.File;
public class ResourceLoader {
public final ViewLoader viewLoader;
public final StringResourceLoader stringResourceLoader;
public ResourceLoader(Class rClass, File resourceDir) throws Exception {
ResourceExtractor resourceExtractor = new ResourceExtractor();
resourceExtractor.addRClass(rClass);
viewLoader = new ViewLoader(resourceExtractor);
viewLoader.addResourceXmlDir(new File(resourceDir, "layout"));
stringResourceLoader = new StringResourceLoader(resourceExtractor);
stringResourceLoader.addResourceXmlDir(new File(resourceDir, "values"));
}
}
## Instruction:
Load resources from all layout* directories
## Code After:
package com.xtremelabs.droidsugar.view;
import java.io.File;
import java.io.FileFilter;
public class ResourceLoader {
public final ViewLoader viewLoader;
public final StringResourceLoader stringResourceLoader;
public ResourceLoader(Class rClass, File resourceDir) throws Exception {
ResourceExtractor resourceExtractor = new ResourceExtractor();
resourceExtractor.addRClass(rClass);
viewLoader = new ViewLoader(resourceExtractor);
File[] layoutDirs = resourceDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getPath().contains("/layout");
}
});
for (File layoutDir : layoutDirs) {
viewLoader.addResourceXmlDir(layoutDir);
}
stringResourceLoader = new StringResourceLoader(resourceExtractor);
stringResourceLoader.addResourceXmlDir(new File(resourceDir, "values"));
}
}
|
// ... existing code ...
package com.xtremelabs.droidsugar.view;
import java.io.File;
import java.io.FileFilter;
public class ResourceLoader {
public final ViewLoader viewLoader;
// ... modified code ...
resourceExtractor.addRClass(rClass);
viewLoader = new ViewLoader(resourceExtractor);
File[] layoutDirs = resourceDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getPath().contains("/layout");
}
});
for (File layoutDir : layoutDirs) {
viewLoader.addResourceXmlDir(layoutDir);
}
stringResourceLoader = new StringResourceLoader(resourceExtractor);
stringResourceLoader.addResourceXmlDir(new File(resourceDir, "values"));
// ... rest of the code ...
|
aa6df5b1ca4801cdaa85f7546c292be4f34e0107
|
test/pyrostest/test_system.py
|
test/pyrostest/test_system.py
|
import pytest
import pyrostest
class TestSpinUp(pyrostest.RosTest):
def noop(self):
pass
@pyrostest.launch_node('pyrostest', 'add_one.py')
def launches_node(self):
pass
class FailureCases(pyrostest.RosTest):
@pytest.mark.xfail(strict=True)
@pyrostest.launch_node('this_isnt_a_project', 'add_one.py')
def no_rospackage(self):
pass
@pytest.mark.xfail(strict=True)
@pyrostest.launch_node('pyrostest', 'this_isnt_a_rosnode.py')
def no_node(self):
pass
@pytest.mark.xfail(strict=True)
@pyrostest.with_launch_file('pyrostest', 'does_not_exist')
def no_launch_file(self):
pass
@pytest.mark.xfail(strict=True)
@pyrostest.with_launch_file('not_a_package', 'exists')
def no_launch_package(self):
pass
|
import pytest
import pyrostest
class TestSpinUp(pyrostest.RosTest):
def test_noop(self):
pass
@pyrostest.launch_node('pyrostest', 'add_one.py')
def test_launches_node(self):
pass
class TestFailureCases(pyrostest.RosTest):
@pytest.mark.xfail(strict=True)
@pyrostest.launch_node('this_isnt_a_project', 'add_one.py')
def test_no_rospackage(self):
pass
@pytest.mark.xfail(strict=True)
@pyrostest.launch_node('pyrostest', 'this_isnt_a_rosnode.py')
def test_no_node(self):
pass
@pytest.mark.xfail(strict=True)
@pyrostest.with_launch_file('pyrostest', 'does_not_exist')
def test_no_launch_file(self):
pass
@pytest.mark.xfail(strict=True)
@pyrostest.with_launch_file('not_a_package', 'exists')
def test_no_launch_package(self):
pass
|
Rename tests so that they run.
|
Rename tests so that they run.
|
Python
|
mit
|
gtagency/pyrostest,gtagency/pyrostest
|
python
|
## Code Before:
import pytest
import pyrostest
class TestSpinUp(pyrostest.RosTest):
def noop(self):
pass
@pyrostest.launch_node('pyrostest', 'add_one.py')
def launches_node(self):
pass
class FailureCases(pyrostest.RosTest):
@pytest.mark.xfail(strict=True)
@pyrostest.launch_node('this_isnt_a_project', 'add_one.py')
def no_rospackage(self):
pass
@pytest.mark.xfail(strict=True)
@pyrostest.launch_node('pyrostest', 'this_isnt_a_rosnode.py')
def no_node(self):
pass
@pytest.mark.xfail(strict=True)
@pyrostest.with_launch_file('pyrostest', 'does_not_exist')
def no_launch_file(self):
pass
@pytest.mark.xfail(strict=True)
@pyrostest.with_launch_file('not_a_package', 'exists')
def no_launch_package(self):
pass
## Instruction:
Rename tests so that they run.
## Code After:
import pytest
import pyrostest
class TestSpinUp(pyrostest.RosTest):
def test_noop(self):
pass
@pyrostest.launch_node('pyrostest', 'add_one.py')
def test_launches_node(self):
pass
class TestFailureCases(pyrostest.RosTest):
@pytest.mark.xfail(strict=True)
@pyrostest.launch_node('this_isnt_a_project', 'add_one.py')
def test_no_rospackage(self):
pass
@pytest.mark.xfail(strict=True)
@pyrostest.launch_node('pyrostest', 'this_isnt_a_rosnode.py')
def test_no_node(self):
pass
@pytest.mark.xfail(strict=True)
@pyrostest.with_launch_file('pyrostest', 'does_not_exist')
def test_no_launch_file(self):
pass
@pytest.mark.xfail(strict=True)
@pyrostest.with_launch_file('not_a_package', 'exists')
def test_no_launch_package(self):
pass
|
# ... existing code ...
import pyrostest
class TestSpinUp(pyrostest.RosTest):
def test_noop(self):
pass
@pyrostest.launch_node('pyrostest', 'add_one.py')
def test_launches_node(self):
pass
class TestFailureCases(pyrostest.RosTest):
@pytest.mark.xfail(strict=True)
@pyrostest.launch_node('this_isnt_a_project', 'add_one.py')
def test_no_rospackage(self):
pass
@pytest.mark.xfail(strict=True)
@pyrostest.launch_node('pyrostest', 'this_isnt_a_rosnode.py')
def test_no_node(self):
pass
@pytest.mark.xfail(strict=True)
@pyrostest.with_launch_file('pyrostest', 'does_not_exist')
def test_no_launch_file(self):
pass
@pytest.mark.xfail(strict=True)
@pyrostest.with_launch_file('not_a_package', 'exists')
def test_no_launch_package(self):
pass
# ... rest of the code ...
|
d676a1b1e7e3efbbfc72f1d7e522865b623783df
|
utils/etc.py
|
utils/etc.py
|
def reverse_insort(seq, val):
lo = 0
hi = len(seq)
while lo < hi:
mid = (lo + hi) // 2
if val > seq[mid]:
hi = mid
else:
lo = mid + 1
seq.insert(lo, val)
|
def reverse_insort(seq, val, lo=0, hi=None):
if hi is None:
hi = len(seq)
while lo < hi:
mid = (lo + hi) // 2
if val > seq[mid]:
hi = mid
else:
lo = mid + 1
seq.insert(lo, val)
|
Add optional hi and lo params to reverse_insort
|
Add optional hi and lo params to reverse_insort
|
Python
|
mit
|
BeatButton/beattie,BeatButton/beattie-bot
|
python
|
## Code Before:
def reverse_insort(seq, val):
lo = 0
hi = len(seq)
while lo < hi:
mid = (lo + hi) // 2
if val > seq[mid]:
hi = mid
else:
lo = mid + 1
seq.insert(lo, val)
## Instruction:
Add optional hi and lo params to reverse_insort
## Code After:
def reverse_insort(seq, val, lo=0, hi=None):
if hi is None:
hi = len(seq)
while lo < hi:
mid = (lo + hi) // 2
if val > seq[mid]:
hi = mid
else:
lo = mid + 1
seq.insert(lo, val)
|
// ... existing code ...
def reverse_insort(seq, val, lo=0, hi=None):
if hi is None:
hi = len(seq)
while lo < hi:
mid = (lo + hi) // 2
if val > seq[mid]:
// ... rest of the code ...
|
5883ccc3ca5ff073f571fa9cfe363d7a0be59d47
|
setup.py
|
setup.py
|
from distutils.core import setup
import request
setup(
name='django-request',
version='%s' % request.__version__,
description='django-request is a statistics module for django. It stores requests in a database for admins to see, it can also be used to get statistics on who is online etc.',
author='Kyle Fuller',
author_email='[email protected]',
url='http://kylefuller.co.uk/projects/django-request/',
download_url='http://github.com/kylef/django-request/zipball/master',
packages=['request', 'request.templatetags'],
package_data={'request': ['templates/admin/request/*.html', 'templates/admin/request/request/*.html']},
license='BSD',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
]
)
|
from distutils.core import setup
import request
setup(
name='django-request',
version='%s' % request.__version__,
description='django-request is a statistics module for django. It stores requests in a database for admins to see, it can also be used to get statistics on who is online etc.',
author='Kyle Fuller',
author_email='[email protected]',
url='http://kylefuller.co.uk/projects/django-request/',
download_url='http://github.com/kylef/django-request/zipball/%s' % request.__version__,
packages=['request', 'request.templatetags'],
package_data={'request': ['templates/admin/request/*.html', 'templates/admin/request/request/*.html']},
license='BSD',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
]
)
|
Set the download link to the current version of django-request, not latest git.
|
Set the download link to the current version of django-request, not latest git.
|
Python
|
bsd-2-clause
|
kylef/django-request,gnublade/django-request,kylef/django-request,gnublade/django-request,gnublade/django-request,kylef/django-request
|
python
|
## Code Before:
from distutils.core import setup
import request
setup(
name='django-request',
version='%s' % request.__version__,
description='django-request is a statistics module for django. It stores requests in a database for admins to see, it can also be used to get statistics on who is online etc.',
author='Kyle Fuller',
author_email='[email protected]',
url='http://kylefuller.co.uk/projects/django-request/',
download_url='http://github.com/kylef/django-request/zipball/master',
packages=['request', 'request.templatetags'],
package_data={'request': ['templates/admin/request/*.html', 'templates/admin/request/request/*.html']},
license='BSD',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
]
)
## Instruction:
Set the download link to the current version of django-request, not latest git.
## Code After:
from distutils.core import setup
import request
setup(
name='django-request',
version='%s' % request.__version__,
description='django-request is a statistics module for django. It stores requests in a database for admins to see, it can also be used to get statistics on who is online etc.',
author='Kyle Fuller',
author_email='[email protected]',
url='http://kylefuller.co.uk/projects/django-request/',
download_url='http://github.com/kylef/django-request/zipball/%s' % request.__version__,
packages=['request', 'request.templatetags'],
package_data={'request': ['templates/admin/request/*.html', 'templates/admin/request/request/*.html']},
license='BSD',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
]
)
|
# ... existing code ...
author='Kyle Fuller',
author_email='[email protected]',
url='http://kylefuller.co.uk/projects/django-request/',
download_url='http://github.com/kylef/django-request/zipball/%s' % request.__version__,
packages=['request', 'request.templatetags'],
package_data={'request': ['templates/admin/request/*.html', 'templates/admin/request/request/*.html']},
license='BSD',
# ... rest of the code ...
|
7a1056e7c929b07220fdefb45e282104ee192836
|
github3/__init__.py
|
github3/__init__.py
|
__title__ = 'github3'
__author__ = 'Ian Cordasco'
__license__ = 'Modified BSD'
__copyright__ = 'Copyright 2012 Ian Cordasco'
__version__ = '0.1a3'
from .api import *
from .github import GitHub
from .models import GitHubError
from .event import Event
from .gist import Gist, GistComment, GistFile
from .git import Blob, GitData, Commit, Reference, GitObject, Tag, Tree, Hash
from .issue import Issue, IssueComment, IssueEvent, Label, Milestone
|
__title__ = 'github3'
__author__ = 'Ian Cordasco'
__license__ = 'Modified BSD'
__copyright__ = 'Copyright 2012 Ian Cordasco'
__version__ = '0.1a3'
from .api import *
from .github import GitHub
from .models import GitHubError
from .event import Event
from .gist import Gist, GistComment, GistFile
from .git import Blob, GitData, Commit, Reference, GitObject, Tag, Tree, Hash
from .issue import Issue, IssueComment, IssueEvent, Label, Milestone
from .legacy import LegacyUser, LegacyRepo, LegacyIssue
from .org import Organization, Team
from .pulls import PullRequest
from .repo import Repository, Branch
from .user import User
|
Add more objects to the default namespace.
|
Add more objects to the default namespace.
Ease of testing, I'm not exactly a fan of polluting it though. Might rework
this later.
|
Python
|
bsd-3-clause
|
wbrefvem/github3.py,itsmemattchung/github3.py,christophelec/github3.py,sigmavirus24/github3.py,icio/github3.py,h4ck3rm1k3/github3.py,krxsky/github3.py,jim-minter/github3.py,ueg1990/github3.py,agamdua/github3.py,degustaf/github3.py,balloob/github3.py
|
python
|
## Code Before:
__title__ = 'github3'
__author__ = 'Ian Cordasco'
__license__ = 'Modified BSD'
__copyright__ = 'Copyright 2012 Ian Cordasco'
__version__ = '0.1a3'
from .api import *
from .github import GitHub
from .models import GitHubError
from .event import Event
from .gist import Gist, GistComment, GistFile
from .git import Blob, GitData, Commit, Reference, GitObject, Tag, Tree, Hash
from .issue import Issue, IssueComment, IssueEvent, Label, Milestone
## Instruction:
Add more objects to the default namespace.
Ease of testing, I'm not exactly a fan of polluting it though. Might rework
this later.
## Code After:
__title__ = 'github3'
__author__ = 'Ian Cordasco'
__license__ = 'Modified BSD'
__copyright__ = 'Copyright 2012 Ian Cordasco'
__version__ = '0.1a3'
from .api import *
from .github import GitHub
from .models import GitHubError
from .event import Event
from .gist import Gist, GistComment, GistFile
from .git import Blob, GitData, Commit, Reference, GitObject, Tag, Tree, Hash
from .issue import Issue, IssueComment, IssueEvent, Label, Milestone
from .legacy import LegacyUser, LegacyRepo, LegacyIssue
from .org import Organization, Team
from .pulls import PullRequest
from .repo import Repository, Branch
from .user import User
|
# ... existing code ...
from .api import *
from .github import GitHub
from .models import GitHubError
from .event import Event
from .gist import Gist, GistComment, GistFile
from .git import Blob, GitData, Commit, Reference, GitObject, Tag, Tree, Hash
from .issue import Issue, IssueComment, IssueEvent, Label, Milestone
from .legacy import LegacyUser, LegacyRepo, LegacyIssue
from .org import Organization, Team
from .pulls import PullRequest
from .repo import Repository, Branch
from .user import User
# ... rest of the code ...
|
2ca428e2c4e0be9c9df0aeff88025a9200d6b74a
|
Magic/src/main/java/com/elmakers/mine/bukkit/entity/EntityWolfData.java
|
Magic/src/main/java/com/elmakers/mine/bukkit/entity/EntityWolfData.java
|
package com.elmakers.mine.bukkit.entity;
import org.bukkit.DyeColor;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Wolf;
import com.elmakers.mine.bukkit.api.magic.MageController;
public class EntityWolfData extends EntityAnimalData {
private boolean isAngry;
private DyeColor collarColor;
public EntityWolfData() {
}
public EntityWolfData(ConfigurationSection parameters, MageController controller) {
super(parameters, controller);
String colorString = parameters.getString("color");
if (colorString != null) {
try {
collarColor = DyeColor.valueOf(colorString.toUpperCase());
} catch (Exception ex) {
collarColor = null;
}
}
isAngry = parameters.getBoolean("angry", false);
}
public EntityWolfData(Entity entity) {
super(entity);
if (entity instanceof Wolf) {
Wolf wolf = (Wolf)entity;
collarColor = wolf.getCollarColor();
isAngry = wolf.isAngry();
sitting = wolf.isSitting();
}
}
@Override
public void apply(Entity entity) {
super.apply(entity);
if (entity instanceof Wolf) {
Wolf wolf = (Wolf)entity;
wolf.setCollarColor(collarColor);
wolf.setAngry(isAngry);
wolf.setSitting(sitting);
}
}
}
|
package com.elmakers.mine.bukkit.entity;
import org.bukkit.DyeColor;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Wolf;
import com.elmakers.mine.bukkit.api.magic.MageController;
public class EntityWolfData extends EntityAnimalData {
private boolean isAngry;
private DyeColor collarColor;
public EntityWolfData() {
}
public EntityWolfData(ConfigurationSection parameters, MageController controller) {
super(parameters, controller);
String colorString = parameters.getString("color");
if (colorString != null) {
try {
collarColor = DyeColor.valueOf(colorString.toUpperCase());
} catch (Exception ex) {
collarColor = null;
}
}
isAngry = parameters.getBoolean("angry", false);
}
public EntityWolfData(Entity entity) {
super(entity);
if (entity instanceof Wolf) {
Wolf wolf = (Wolf)entity;
collarColor = wolf.getCollarColor();
isAngry = wolf.isAngry();
sitting = wolf.isSitting();
}
}
@Override
public void apply(Entity entity) {
super.apply(entity);
if (entity instanceof Wolf) {
Wolf wolf = (Wolf)entity;
if (collarColor != null) {
wolf.setCollarColor(collarColor);
}
wolf.setAngry(isAngry);
wolf.setSitting(sitting);
}
}
}
|
Fix NPE in applying wolf entity data from config
|
Fix NPE in applying wolf entity data from config
|
Java
|
mit
|
elBukkit/MagicPlugin,elBukkit/MagicPlugin,elBukkit/MagicPlugin
|
java
|
## Code Before:
package com.elmakers.mine.bukkit.entity;
import org.bukkit.DyeColor;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Wolf;
import com.elmakers.mine.bukkit.api.magic.MageController;
public class EntityWolfData extends EntityAnimalData {
private boolean isAngry;
private DyeColor collarColor;
public EntityWolfData() {
}
public EntityWolfData(ConfigurationSection parameters, MageController controller) {
super(parameters, controller);
String colorString = parameters.getString("color");
if (colorString != null) {
try {
collarColor = DyeColor.valueOf(colorString.toUpperCase());
} catch (Exception ex) {
collarColor = null;
}
}
isAngry = parameters.getBoolean("angry", false);
}
public EntityWolfData(Entity entity) {
super(entity);
if (entity instanceof Wolf) {
Wolf wolf = (Wolf)entity;
collarColor = wolf.getCollarColor();
isAngry = wolf.isAngry();
sitting = wolf.isSitting();
}
}
@Override
public void apply(Entity entity) {
super.apply(entity);
if (entity instanceof Wolf) {
Wolf wolf = (Wolf)entity;
wolf.setCollarColor(collarColor);
wolf.setAngry(isAngry);
wolf.setSitting(sitting);
}
}
}
## Instruction:
Fix NPE in applying wolf entity data from config
## Code After:
package com.elmakers.mine.bukkit.entity;
import org.bukkit.DyeColor;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Wolf;
import com.elmakers.mine.bukkit.api.magic.MageController;
public class EntityWolfData extends EntityAnimalData {
private boolean isAngry;
private DyeColor collarColor;
public EntityWolfData() {
}
public EntityWolfData(ConfigurationSection parameters, MageController controller) {
super(parameters, controller);
String colorString = parameters.getString("color");
if (colorString != null) {
try {
collarColor = DyeColor.valueOf(colorString.toUpperCase());
} catch (Exception ex) {
collarColor = null;
}
}
isAngry = parameters.getBoolean("angry", false);
}
public EntityWolfData(Entity entity) {
super(entity);
if (entity instanceof Wolf) {
Wolf wolf = (Wolf)entity;
collarColor = wolf.getCollarColor();
isAngry = wolf.isAngry();
sitting = wolf.isSitting();
}
}
@Override
public void apply(Entity entity) {
super.apply(entity);
if (entity instanceof Wolf) {
Wolf wolf = (Wolf)entity;
if (collarColor != null) {
wolf.setCollarColor(collarColor);
}
wolf.setAngry(isAngry);
wolf.setSitting(sitting);
}
}
}
|
// ... existing code ...
super.apply(entity);
if (entity instanceof Wolf) {
Wolf wolf = (Wolf)entity;
if (collarColor != null) {
wolf.setCollarColor(collarColor);
}
wolf.setAngry(isAngry);
wolf.setSitting(sitting);
}
// ... rest of the code ...
|
2804b6574069642c2cd86545f47bd3c332c049ed
|
src/test/java/org/yukung/tutorial/junit/DateTest.java
|
src/test/java/org/yukung/tutorial/junit/DateTest.java
|
package org.yukung.tutorial.junit;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.util.Date;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class DateTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testDate() {
assertThat(new Date(), is(IsDate.dateOf(2012, 1, 12)));
}
}
|
package org.yukung.tutorial.junit;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.yukung.tutorial.junit.IsDate.*;
import java.util.Date;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class DateTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testDate() {
assertThat(new Date(), is(dateOf(2012, 1, 12)));
}
}
|
Fix test case using static import to 'IsDate' class.
|
Fix test case using static import to 'IsDate' class.
|
Java
|
mit
|
yukung/playground,yukung/playground,yukung/playground,yukung/playground
|
java
|
## Code Before:
package org.yukung.tutorial.junit;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.util.Date;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class DateTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testDate() {
assertThat(new Date(), is(IsDate.dateOf(2012, 1, 12)));
}
}
## Instruction:
Fix test case using static import to 'IsDate' class.
## Code After:
package org.yukung.tutorial.junit;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.yukung.tutorial.junit.IsDate.*;
import java.util.Date;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class DateTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testDate() {
assertThat(new Date(), is(dateOf(2012, 1, 12)));
}
}
|
# ... existing code ...
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.yukung.tutorial.junit.IsDate.*;
import java.util.Date;
# ... modified code ...
@Test
public void testDate() {
assertThat(new Date(), is(dateOf(2012, 1, 12)));
}
}
# ... rest of the code ...
|
afc959e23f21e086f710cbc7f3bb56d0b4d93329
|
bin/set_deploy_permissions.py
|
bin/set_deploy_permissions.py
|
import os
import sys
import subprocess
server_writable_directories = [
"vendor/solr/apache-solr-4.0.0/example/solr/collection1/data/",
"vendor/solr/apache-solr-4.0.0/example/solr-webapp/",
"lib/dotstorm/assets/dotstorm/uploads/",
"lib/www/assets/group_logos/",
"lib/www/assets/user_icons/",
]
BASE = os.path.join(os.path.dirname(__file__), "..")
def set_permissions(user):
for path in server_writable_directories:
print user, path
if not os.path.exists(path):
os.makedirs(path)
subprocess.check_call(["chown", "-R", user, os.path.join(BASE, path)])
if __name__ == "__main__":
try:
target_user = sys.argv[1]
except IndexError:
print "Missing required parameter `target user`."
print "Usage: set_deploy_permissions.py [username]"
sys.exit(1)
set_permissions(target_user)
|
import os
import sys
import subprocess
server_writable_directories = [
"vendor/solr/apache-solr-4.0.0/example/solr/collection1/data/",
"vendor/solr/apache-solr-4.0.0/example/solr-webapp/",
"lib/dotstorm/assets/dotstorm/uploads/",
"lib/www/assets/group_logos/",
"lib/www/assets/user_icons/",
"builtAssets/",
]
BASE = os.path.join(os.path.dirname(__file__), "..")
def set_permissions(user):
for path in server_writable_directories:
print user, path
if not os.path.exists(path):
os.makedirs(path)
subprocess.check_call(["chown", "-R", user, os.path.join(BASE, path)])
if __name__ == "__main__":
try:
target_user = sys.argv[1]
except IndexError:
print "Missing required parameter `target user`."
print "Usage: set_deploy_permissions.py [username]"
sys.exit(1)
set_permissions(target_user)
|
Add builtAssets to webserver-writable dirs
|
Add builtAssets to webserver-writable dirs
|
Python
|
bsd-2-clause
|
yourcelf/intertwinkles,yourcelf/intertwinkles
|
python
|
## Code Before:
import os
import sys
import subprocess
server_writable_directories = [
"vendor/solr/apache-solr-4.0.0/example/solr/collection1/data/",
"vendor/solr/apache-solr-4.0.0/example/solr-webapp/",
"lib/dotstorm/assets/dotstorm/uploads/",
"lib/www/assets/group_logos/",
"lib/www/assets/user_icons/",
]
BASE = os.path.join(os.path.dirname(__file__), "..")
def set_permissions(user):
for path in server_writable_directories:
print user, path
if not os.path.exists(path):
os.makedirs(path)
subprocess.check_call(["chown", "-R", user, os.path.join(BASE, path)])
if __name__ == "__main__":
try:
target_user = sys.argv[1]
except IndexError:
print "Missing required parameter `target user`."
print "Usage: set_deploy_permissions.py [username]"
sys.exit(1)
set_permissions(target_user)
## Instruction:
Add builtAssets to webserver-writable dirs
## Code After:
import os
import sys
import subprocess
server_writable_directories = [
"vendor/solr/apache-solr-4.0.0/example/solr/collection1/data/",
"vendor/solr/apache-solr-4.0.0/example/solr-webapp/",
"lib/dotstorm/assets/dotstorm/uploads/",
"lib/www/assets/group_logos/",
"lib/www/assets/user_icons/",
"builtAssets/",
]
BASE = os.path.join(os.path.dirname(__file__), "..")
def set_permissions(user):
for path in server_writable_directories:
print user, path
if not os.path.exists(path):
os.makedirs(path)
subprocess.check_call(["chown", "-R", user, os.path.join(BASE, path)])
if __name__ == "__main__":
try:
target_user = sys.argv[1]
except IndexError:
print "Missing required parameter `target user`."
print "Usage: set_deploy_permissions.py [username]"
sys.exit(1)
set_permissions(target_user)
|
// ... existing code ...
"lib/dotstorm/assets/dotstorm/uploads/",
"lib/www/assets/group_logos/",
"lib/www/assets/user_icons/",
"builtAssets/",
]
BASE = os.path.join(os.path.dirname(__file__), "..")
// ... rest of the code ...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.