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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
ff2bf51f003fc5af1f62fc1aa181ca11a766c8f6
|
fs/archive/__init__.py
|
fs/archive/__init__.py
|
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
@contextlib.contextmanager
def open_archive(fs_url, archive):
from pkg_resources import iter_entry_points
from ..opener import open_fs
from ..opener._errors import Unsupported
it = iter_entry_points('fs.archive.open_archive')
entry_point = next((ep for ep in it if archive.endswith(ep.name)), None)
if entry_point is None:
raise Unsupported(
'unknown archive extension: {}'.format(archive))
archive_opener = entry_point.load()
# if not isinstance(archive_fs, base.ArchiveFS):
# raise TypeError('bad entry point')
try:
with open_fs(fs_url) as fs:
binfile = fs.openbin(archive, 'r+' if fs.isfile(archive) else 'w')
archive_fs = archive_opener(binfile)
yield archive_fs
finally:
archive_fs.close()
binfile.close()
__all__ = ['open_archive']
|
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
@contextlib.contextmanager
def open_archive(fs_url, archive):
from pkg_resources import iter_entry_points
from ..opener import open_fs
from ..opener._errors import Unsupported
it = iter_entry_points('fs.archive.open_archive')
entry_point = next((ep for ep in it if archive.endswith(ep.name)), None)
if entry_point is None:
raise Unsupported(
'unknown archive extension: {}'.format(archive))
archive_opener = entry_point.load()
# if not isinstance(archive_fs, base.ArchiveFS):
# raise TypeError('bad entry point')
try:
#with open_fs(fs_url) as fs:
fs = open_fs(fs_url)
binfile = fs.openbin(archive, 'r+' if fs.isfile(archive) else 'w')
archive_fs = archive_opener(binfile)
yield archive_fs
finally:
archive_fs.close()
binfile.close()
if fs is not fs_url: # close the fs if we opened it
fs.close()
__all__ = ['open_archive']
|
Make sure files and FS are properly closed in open_archive
|
Make sure files and FS are properly closed in open_archive
|
Python
|
mit
|
althonos/fs.archive
|
python
|
## Code Before:
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
@contextlib.contextmanager
def open_archive(fs_url, archive):
from pkg_resources import iter_entry_points
from ..opener import open_fs
from ..opener._errors import Unsupported
it = iter_entry_points('fs.archive.open_archive')
entry_point = next((ep for ep in it if archive.endswith(ep.name)), None)
if entry_point is None:
raise Unsupported(
'unknown archive extension: {}'.format(archive))
archive_opener = entry_point.load()
# if not isinstance(archive_fs, base.ArchiveFS):
# raise TypeError('bad entry point')
try:
with open_fs(fs_url) as fs:
binfile = fs.openbin(archive, 'r+' if fs.isfile(archive) else 'w')
archive_fs = archive_opener(binfile)
yield archive_fs
finally:
archive_fs.close()
binfile.close()
__all__ = ['open_archive']
## Instruction:
Make sure files and FS are properly closed in open_archive
## Code After:
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
@contextlib.contextmanager
def open_archive(fs_url, archive):
from pkg_resources import iter_entry_points
from ..opener import open_fs
from ..opener._errors import Unsupported
it = iter_entry_points('fs.archive.open_archive')
entry_point = next((ep for ep in it if archive.endswith(ep.name)), None)
if entry_point is None:
raise Unsupported(
'unknown archive extension: {}'.format(archive))
archive_opener = entry_point.load()
# if not isinstance(archive_fs, base.ArchiveFS):
# raise TypeError('bad entry point')
try:
#with open_fs(fs_url) as fs:
fs = open_fs(fs_url)
binfile = fs.openbin(archive, 'r+' if fs.isfile(archive) else 'w')
archive_fs = archive_opener(binfile)
yield archive_fs
finally:
archive_fs.close()
binfile.close()
if fs is not fs_url: # close the fs if we opened it
fs.close()
__all__ = ['open_archive']
|
# ... existing code ...
# raise TypeError('bad entry point')
try:
#with open_fs(fs_url) as fs:
fs = open_fs(fs_url)
binfile = fs.openbin(archive, 'r+' if fs.isfile(archive) else 'w')
archive_fs = archive_opener(binfile)
yield archive_fs
finally:
archive_fs.close()
binfile.close()
if fs is not fs_url: # close the fs if we opened it
fs.close()
__all__ = ['open_archive']
# ... rest of the code ...
|
3983d4d1d363412b863aabd1219676c589d9ed41
|
src/binary.c
|
src/binary.c
|
/* API ************************************************************************/
Binary *binary_new(Scope *scope, size_t size) {
Binary *binary = scope_alloc(scope, sizeof(Binary) + size);
binary->size = size;
binary->header = ref_header(TYPEID_BINARY, 0);
memset(binary->data, 0, binary->size);
return binary;
}
Binary *binary(Scope *scope, const uint8_t *data, size_t size) {
Binary *binary = scope_alloc(scope, sizeof(Binary) + size);
binary->size = size;
binary->header = ref_header(TYPEID_BINARY, 0);
memcpy(binary->data, data, size);
return binary;
}
uint32_t binary_hash32(uint32_t hash, Binary *binary) {
assert(binary != NULL);
return crc32(hash, binary->data, binary->size);
}
|
/* API ************************************************************************/
Binary *binary_new(Scope *scope, size_t size) {
Binary *binary = scope_alloc(scope, sizeof(Binary) + size + 1);
binary->size = size;
binary->header = ref_header(TYPEID_BINARY, 0);
memset(binary->data, 0, binary->size + 1);
return binary;
}
Binary *binary(Scope *scope, const uint8_t *data, size_t size) {
Binary *binary = scope_alloc(scope, sizeof(Binary) + size + 1);
binary->size = size;
binary->header = ref_header(TYPEID_BINARY, 0);
memcpy(binary->data, data, size + 1);
return binary;
}
uint32_t binary_hash32(uint32_t hash, Binary *binary) {
assert(binary != NULL);
return crc32(hash, binary->data, binary->size);
}
|
Add ending null-byte to binaries
|
Add ending null-byte to binaries
|
C
|
apache-2.0
|
samuelotter/slang,samuelotter/slang
|
c
|
## Code Before:
/* API ************************************************************************/
Binary *binary_new(Scope *scope, size_t size) {
Binary *binary = scope_alloc(scope, sizeof(Binary) + size);
binary->size = size;
binary->header = ref_header(TYPEID_BINARY, 0);
memset(binary->data, 0, binary->size);
return binary;
}
Binary *binary(Scope *scope, const uint8_t *data, size_t size) {
Binary *binary = scope_alloc(scope, sizeof(Binary) + size);
binary->size = size;
binary->header = ref_header(TYPEID_BINARY, 0);
memcpy(binary->data, data, size);
return binary;
}
uint32_t binary_hash32(uint32_t hash, Binary *binary) {
assert(binary != NULL);
return crc32(hash, binary->data, binary->size);
}
## Instruction:
Add ending null-byte to binaries
## Code After:
/* API ************************************************************************/
Binary *binary_new(Scope *scope, size_t size) {
Binary *binary = scope_alloc(scope, sizeof(Binary) + size + 1);
binary->size = size;
binary->header = ref_header(TYPEID_BINARY, 0);
memset(binary->data, 0, binary->size + 1);
return binary;
}
Binary *binary(Scope *scope, const uint8_t *data, size_t size) {
Binary *binary = scope_alloc(scope, sizeof(Binary) + size + 1);
binary->size = size;
binary->header = ref_header(TYPEID_BINARY, 0);
memcpy(binary->data, data, size + 1);
return binary;
}
uint32_t binary_hash32(uint32_t hash, Binary *binary) {
assert(binary != NULL);
return crc32(hash, binary->data, binary->size);
}
|
# ... existing code ...
/* API ************************************************************************/
Binary *binary_new(Scope *scope, size_t size) {
Binary *binary = scope_alloc(scope, sizeof(Binary) + size + 1);
binary->size = size;
binary->header = ref_header(TYPEID_BINARY, 0);
memset(binary->data, 0, binary->size + 1);
return binary;
}
Binary *binary(Scope *scope, const uint8_t *data, size_t size) {
Binary *binary = scope_alloc(scope, sizeof(Binary) + size + 1);
binary->size = size;
binary->header = ref_header(TYPEID_BINARY, 0);
memcpy(binary->data, data, size + 1);
return binary;
}
# ... rest of the code ...
|
689d1d1f128b4a72aad6783ea2f770c21cd4c2da
|
queryset_transform/__init__.py
|
queryset_transform/__init__.py
|
from django.db import models
class TransformQuerySet(models.query.QuerySet):
def __init__(self, *args, **kwargs):
super(TransformQuerySet, self).__init__(*args, **kwargs)
self._transform_fns = []
def _clone(self, klass=None, setup=False, **kw):
c = super(TransformQuerySet, self)._clone(klass, setup, **kw)
c._transform_fns = self._transform_fns
return c
def transform(self, fn):
self._transform_fns.append(fn)
return self
def iterator(self):
result_iter = super(TransformQuerySet, self).iterator()
if self._transform_fns:
results = list(result_iter)
for fn in self._transform_fns:
fn(results)
return iter(results)
return result_iter
class TransformManager(models.Manager):
def get_query_set(self):
return TransformQuerySet(self.model)
|
from django.db import models
class TransformQuerySet(models.query.QuerySet):
def __init__(self, *args, **kwargs):
super(TransformQuerySet, self).__init__(*args, **kwargs)
self._transform_fns = []
def _clone(self, klass=None, setup=False, **kw):
c = super(TransformQuerySet, self)._clone(klass, setup, **kw)
c._transform_fns = self._transform_fns[:]
return c
def transform(self, fn):
c = self._clone()
c._transform_fns.append(fn)
return c
def iterator(self):
for item in super(TransformQuerySet, self).iterator()
for func in self._transform_fns:
func(item)
yield item
class TransformManager(models.Manager):
def get_query_set(self):
return TransformQuerySet(self.model)
|
Refactor the ever living hell out of this.
|
Refactor the ever living hell out of this.
|
Python
|
bsd-3-clause
|
alex/django-queryset-transform
|
python
|
## Code Before:
from django.db import models
class TransformQuerySet(models.query.QuerySet):
def __init__(self, *args, **kwargs):
super(TransformQuerySet, self).__init__(*args, **kwargs)
self._transform_fns = []
def _clone(self, klass=None, setup=False, **kw):
c = super(TransformQuerySet, self)._clone(klass, setup, **kw)
c._transform_fns = self._transform_fns
return c
def transform(self, fn):
self._transform_fns.append(fn)
return self
def iterator(self):
result_iter = super(TransformQuerySet, self).iterator()
if self._transform_fns:
results = list(result_iter)
for fn in self._transform_fns:
fn(results)
return iter(results)
return result_iter
class TransformManager(models.Manager):
def get_query_set(self):
return TransformQuerySet(self.model)
## Instruction:
Refactor the ever living hell out of this.
## Code After:
from django.db import models
class TransformQuerySet(models.query.QuerySet):
def __init__(self, *args, **kwargs):
super(TransformQuerySet, self).__init__(*args, **kwargs)
self._transform_fns = []
def _clone(self, klass=None, setup=False, **kw):
c = super(TransformQuerySet, self)._clone(klass, setup, **kw)
c._transform_fns = self._transform_fns[:]
return c
def transform(self, fn):
c = self._clone()
c._transform_fns.append(fn)
return c
def iterator(self):
for item in super(TransformQuerySet, self).iterator()
for func in self._transform_fns:
func(item)
yield item
class TransformManager(models.Manager):
def get_query_set(self):
return TransformQuerySet(self.model)
|
...
from django.db import models
class TransformQuerySet(models.query.QuerySet):
def __init__(self, *args, **kwargs):
...
def _clone(self, klass=None, setup=False, **kw):
c = super(TransformQuerySet, self)._clone(klass, setup, **kw)
c._transform_fns = self._transform_fns[:]
return c
def transform(self, fn):
c = self._clone()
c._transform_fns.append(fn)
return c
def iterator(self):
for item in super(TransformQuerySet, self).iterator()
for func in self._transform_fns:
func(item)
yield item
class TransformManager(models.Manager):
def get_query_set(self):
return TransformQuerySet(self.model)
...
|
b3be7b3c51c7bc63697aea9100ff65823b425a5c
|
src/main/kotlin/com/elpassion/intelijidea/task/edit/MFBeforeRunTaskDialog.kt
|
src/main/kotlin/com/elpassion/intelijidea/task/edit/MFBeforeRunTaskDialog.kt
|
package com.elpassion.intelijidea.task.edit
import com.elpassion.intelijidea.task.MFTaskData
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import javax.swing.JComponent
import javax.swing.JTextField
class MFBeforeRunTaskDialog(project: Project) : DialogWrapper(project), TaskEditForm {
private val taskEditValidator = TaskEditValidator(this)
val form = MFBeforeRunTaskForm(project)
init {
isModal = true
init()
}
override fun createCenterPanel(): JComponent {
return form.panel
}
override fun doValidate(): ValidationInfo? {
return taskEditValidator.doValidate()
}
override fun taskField(): JTextField {
return form.taskField
}
override fun buildCommandField(): JTextField {
return form.buildCommandField
}
override fun mainframerToolField(): TextFieldWithBrowseButton {
return form.mainframerToolField
}
fun restoreMainframerTask(data: MFTaskData) {
form.mainframerToolField.text = data.mainframerPath
form.buildCommandField.text = data.buildCommand
form.taskField.text = data.taskName
}
fun createMFTaskDataFromForms() = MFTaskData(
mainframerPath = form.mainframerToolField.text,
buildCommand = form.buildCommandField.text,
taskName = form.taskField.text)
}
|
package com.elpassion.intelijidea.task.edit
import com.elpassion.intelijidea.task.MFTaskData
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import javax.swing.JComponent
import javax.swing.JTextField
class MFBeforeRunTaskDialog(project: Project) : DialogWrapper(project), TaskEditForm {
private val taskEditValidator = TaskEditValidator(this)
val form = MFBeforeRunTaskForm(project)
init {
isModal = true
init()
}
override fun createCenterPanel(): JComponent = form.panel
override fun doValidate(): ValidationInfo? = taskEditValidator.doValidate()
override fun taskField(): JTextField = form.taskField
override fun buildCommandField(): JTextField = form.buildCommandField
override fun mainframerToolField(): TextFieldWithBrowseButton = form.mainframerToolField
fun restoreMainframerTask(data: MFTaskData) {
form.mainframerToolField.text = data.mainframerPath
form.buildCommandField.text = data.buildCommand
form.taskField.text = data.taskName
}
fun createMFTaskDataFromForms() = MFTaskData(
mainframerPath = form.mainframerToolField.text,
buildCommand = form.buildCommandField.text,
taskName = form.taskField.text)
}
|
Convert methods bodies to expression
|
[Refactoring] Convert methods bodies to expression
|
Kotlin
|
apache-2.0
|
elpassion/mainframer-intellij-plugin,elpassion/mainframer-intellij-plugin,elpassion/mainframer-intellij-plugin
|
kotlin
|
## Code Before:
package com.elpassion.intelijidea.task.edit
import com.elpassion.intelijidea.task.MFTaskData
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import javax.swing.JComponent
import javax.swing.JTextField
class MFBeforeRunTaskDialog(project: Project) : DialogWrapper(project), TaskEditForm {
private val taskEditValidator = TaskEditValidator(this)
val form = MFBeforeRunTaskForm(project)
init {
isModal = true
init()
}
override fun createCenterPanel(): JComponent {
return form.panel
}
override fun doValidate(): ValidationInfo? {
return taskEditValidator.doValidate()
}
override fun taskField(): JTextField {
return form.taskField
}
override fun buildCommandField(): JTextField {
return form.buildCommandField
}
override fun mainframerToolField(): TextFieldWithBrowseButton {
return form.mainframerToolField
}
fun restoreMainframerTask(data: MFTaskData) {
form.mainframerToolField.text = data.mainframerPath
form.buildCommandField.text = data.buildCommand
form.taskField.text = data.taskName
}
fun createMFTaskDataFromForms() = MFTaskData(
mainframerPath = form.mainframerToolField.text,
buildCommand = form.buildCommandField.text,
taskName = form.taskField.text)
}
## Instruction:
[Refactoring] Convert methods bodies to expression
## Code After:
package com.elpassion.intelijidea.task.edit
import com.elpassion.intelijidea.task.MFTaskData
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import javax.swing.JComponent
import javax.swing.JTextField
class MFBeforeRunTaskDialog(project: Project) : DialogWrapper(project), TaskEditForm {
private val taskEditValidator = TaskEditValidator(this)
val form = MFBeforeRunTaskForm(project)
init {
isModal = true
init()
}
override fun createCenterPanel(): JComponent = form.panel
override fun doValidate(): ValidationInfo? = taskEditValidator.doValidate()
override fun taskField(): JTextField = form.taskField
override fun buildCommandField(): JTextField = form.buildCommandField
override fun mainframerToolField(): TextFieldWithBrowseButton = form.mainframerToolField
fun restoreMainframerTask(data: MFTaskData) {
form.mainframerToolField.text = data.mainframerPath
form.buildCommandField.text = data.buildCommand
form.taskField.text = data.taskName
}
fun createMFTaskDataFromForms() = MFTaskData(
mainframerPath = form.mainframerToolField.text,
buildCommand = form.buildCommandField.text,
taskName = form.taskField.text)
}
|
# ... existing code ...
init()
}
override fun createCenterPanel(): JComponent = form.panel
override fun doValidate(): ValidationInfo? = taskEditValidator.doValidate()
override fun taskField(): JTextField = form.taskField
override fun buildCommandField(): JTextField = form.buildCommandField
override fun mainframerToolField(): TextFieldWithBrowseButton = form.mainframerToolField
fun restoreMainframerTask(data: MFTaskData) {
form.mainframerToolField.text = data.mainframerPath
# ... rest of the code ...
|
c566236de3373aa73c271aaf412de60538c2abfb
|
common/renderers/excel_renderer.py
|
common/renderers/excel_renderer.py
|
import xlsxwriter
import os
from django.conf import settings
from rest_framework import renderers
def _write_excel_file(data):
result = data.get('results')
work_book_name = 'human.xlsx'
workbook = xlsxwriter.Workbook(work_book_name)
worksheet = workbook.add_worksheet()
row = 0
col = 0
data_dict = result[0]
data_keys = data_dict.keys()
for key in data_keys:
worksheet.write(row, col, key)
col = col + 1
row = 1
col = 0
for data_dict in result:
for key in data_keys:
worksheet.write(row, col, data_dict[key])
col = col + 1
row = row + 1
workbook.close()
return work_book_name
class ExcelRenderer(renderers.BaseRenderer):
media_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' # noqa
format = 'excel'
def render(self, data, accepted_media_type=None, renderer_context=None):
file_name = _write_excel_file(data)
file_path = os.path.join(settings.BASE_DIR, file_name)
with open(file_path, 'r') as excel_file:
file_data = excel_file.read()
return file_data
|
import xlsxwriter
import os
from django.conf import settings
from rest_framework import renderers
def _write_excel_file(data):
result = data.get('results')
work_book_name = 'download.xlsx'
workbook = xlsxwriter.Workbook(work_book_name)
worksheet = workbook.add_worksheet()
row = 0
col = 0
data_dict = result[0]
data_keys = data_dict.keys()
for key in data_keys:
worksheet.write(row, col, key)
col = col + 1
row = 1
col = 0
for data_dict in result:
for key in data_keys:
if not isinstance(data[key], list):
worksheet.write(row, col, data_dict[key])
col = col + 1
else:
_write_excel_file()
row = row + 1
workbook.close()
return work_book_name
class ExcelRenderer(renderers.BaseRenderer):
media_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' # noqa
format = 'excel'
def render(self, data, accepted_media_type=None, renderer_context=None):
file_name = _write_excel_file(data)
file_path = os.path.join(settings.BASE_DIR, file_name)
with open(file_path, 'r') as excel_file:
file_data = excel_file.read()
return file_data
|
Add support for nested lists in the excel renderer
|
Add support for nested lists in the excel renderer
|
Python
|
mit
|
MasterFacilityList/mfl_api,urandu/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,urandu/mfl_api,urandu/mfl_api,urandu/mfl_api
|
python
|
## Code Before:
import xlsxwriter
import os
from django.conf import settings
from rest_framework import renderers
def _write_excel_file(data):
result = data.get('results')
work_book_name = 'human.xlsx'
workbook = xlsxwriter.Workbook(work_book_name)
worksheet = workbook.add_worksheet()
row = 0
col = 0
data_dict = result[0]
data_keys = data_dict.keys()
for key in data_keys:
worksheet.write(row, col, key)
col = col + 1
row = 1
col = 0
for data_dict in result:
for key in data_keys:
worksheet.write(row, col, data_dict[key])
col = col + 1
row = row + 1
workbook.close()
return work_book_name
class ExcelRenderer(renderers.BaseRenderer):
media_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' # noqa
format = 'excel'
def render(self, data, accepted_media_type=None, renderer_context=None):
file_name = _write_excel_file(data)
file_path = os.path.join(settings.BASE_DIR, file_name)
with open(file_path, 'r') as excel_file:
file_data = excel_file.read()
return file_data
## Instruction:
Add support for nested lists in the excel renderer
## Code After:
import xlsxwriter
import os
from django.conf import settings
from rest_framework import renderers
def _write_excel_file(data):
result = data.get('results')
work_book_name = 'download.xlsx'
workbook = xlsxwriter.Workbook(work_book_name)
worksheet = workbook.add_worksheet()
row = 0
col = 0
data_dict = result[0]
data_keys = data_dict.keys()
for key in data_keys:
worksheet.write(row, col, key)
col = col + 1
row = 1
col = 0
for data_dict in result:
for key in data_keys:
if not isinstance(data[key], list):
worksheet.write(row, col, data_dict[key])
col = col + 1
else:
_write_excel_file()
row = row + 1
workbook.close()
return work_book_name
class ExcelRenderer(renderers.BaseRenderer):
media_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' # noqa
format = 'excel'
def render(self, data, accepted_media_type=None, renderer_context=None):
file_name = _write_excel_file(data)
file_path = os.path.join(settings.BASE_DIR, file_name)
with open(file_path, 'r') as excel_file:
file_data = excel_file.read()
return file_data
|
// ... existing code ...
def _write_excel_file(data):
result = data.get('results')
work_book_name = 'download.xlsx'
workbook = xlsxwriter.Workbook(work_book_name)
worksheet = workbook.add_worksheet()
row = 0
// ... modified code ...
col = 0
for data_dict in result:
for key in data_keys:
if not isinstance(data[key], list):
worksheet.write(row, col, data_dict[key])
col = col + 1
else:
_write_excel_file()
row = row + 1
workbook.close()
return work_book_name
// ... rest of the code ...
|
5decd7e68c6454e455bc1debe232ea37f7260c58
|
mixins.py
|
mixins.py
|
class DepthSerializerMixin(object):
"""Custom method 'get_serializer_class', set attribute 'depth' based on query parameter in the url"""
def get_serializer_class(self):
serializer_class = self.serializer_class
query_params = self.request.QUERY_PARAMS
depth = query_params.get('__depth', None)
serializer_class.Meta.depth = int(depth) if(depth != None and depth.isdigit()) else 0
return serializer_class
|
class DepthSerializerMixin(object):
"""Custom method 'get_serializer_class', set attribute 'depth' based on query parameter in the url"""
def get_serializer_class(self, *args, **kwargs):
serializer_class = super(DepthSerializerMixin, self).get_serializer_class(*args, **kwargs)
query_params = self.request.QUERY_PARAMS
depth = query_params.get('__depth', None)
serializer_class.Meta.depth = int(depth) if(depth != None and depth.isdigit()) else 0
return serializer_class
|
Call method 'get_serializer_class' of the Class parent
|
Call method 'get_serializer_class' of the Class parent
|
Python
|
mit
|
krescruz/depth-serializer-mixin
|
python
|
## Code Before:
class DepthSerializerMixin(object):
"""Custom method 'get_serializer_class', set attribute 'depth' based on query parameter in the url"""
def get_serializer_class(self):
serializer_class = self.serializer_class
query_params = self.request.QUERY_PARAMS
depth = query_params.get('__depth', None)
serializer_class.Meta.depth = int(depth) if(depth != None and depth.isdigit()) else 0
return serializer_class
## Instruction:
Call method 'get_serializer_class' of the Class parent
## Code After:
class DepthSerializerMixin(object):
"""Custom method 'get_serializer_class', set attribute 'depth' based on query parameter in the url"""
def get_serializer_class(self, *args, **kwargs):
serializer_class = super(DepthSerializerMixin, self).get_serializer_class(*args, **kwargs)
query_params = self.request.QUERY_PARAMS
depth = query_params.get('__depth', None)
serializer_class.Meta.depth = int(depth) if(depth != None and depth.isdigit()) else 0
return serializer_class
|
# ... existing code ...
class DepthSerializerMixin(object):
"""Custom method 'get_serializer_class', set attribute 'depth' based on query parameter in the url"""
def get_serializer_class(self, *args, **kwargs):
serializer_class = super(DepthSerializerMixin, self).get_serializer_class(*args, **kwargs)
query_params = self.request.QUERY_PARAMS
depth = query_params.get('__depth', None)
serializer_class.Meta.depth = int(depth) if(depth != None and depth.isdigit()) else 0
# ... rest of the code ...
|
5c88257e0d1f16188d1d68eab8d5f1939137a640
|
server/src/test/java/umm3601/plant/FilterPlantsByGardenLocation.java
|
server/src/test/java/umm3601/plant/FilterPlantsByGardenLocation.java
|
package umm3601.plant;
import com.google.gson.Gson;
import org.junit.Before;
import org.junit.Test;
import umm3601.digitalDisplayGarden.Plant;
import umm3601.digitalDisplayGarden.PlantController;
import umm3601.plant.PopulateMockDatabase;
import java.io.IOException;
import static junit.framework.TestCase.assertEquals;
public class FilterPlantsByGardenLocation {
@Before
public void setUpDB() throws IOException{
PopulateMockDatabase mockDatabase = new PopulateMockDatabase();
mockDatabase.clearAndPopulateDBAgain();
}
@Test
public void findByGardenLocation() throws IOException {
PlantController plantController = new PlantController();
Plant[] filteredPlants;
Gson gson = new Gson();
String rawPlants = plantController.getGardenLocations();
filteredPlants = gson.fromJson(rawPlants, Plant[].class);
assertEquals("Incorrect", 1, filteredPlants.length);
}
}
|
package umm3601.plant;
import com.google.gson.Gson;
import org.junit.Before;
import org.junit.Test;
import umm3601.digitalDisplayGarden.Plant;
import umm3601.digitalDisplayGarden.PlantController;
import umm3601.plant.PopulateMockDatabase;
import java.io.IOException;
import static junit.framework.TestCase.assertEquals;
public class FilterPlantsByGardenLocation {
@Before
public void setUpDB() throws IOException{
PopulateMockDatabase mockDatabase = new PopulateMockDatabase();
mockDatabase.clearAndPopulateDBAgain();
}
@Test
public void findByGardenLocation() throws IOException {
PlantController plantController = new PlantController();
GardenLocation[] filteredPlants;
Gson gson = new Gson();
//System.out.println();
String rawPlants = plantController.getGardenLocations();
filteredPlants = gson.fromJson(rawPlants, GardenLocation[].class);
assertEquals("Incorrect number of unique garden locations", 2, filteredPlants.length);
assertEquals("Incorrect zero index", "10.0", filteredPlants[0]._id);
assertEquals("Incorrect value for index 1", "7.0", filteredPlants[1]._id);
}
}
|
Add and pass tests for gardenLocation
|
Add and pass tests for gardenLocation
|
Java
|
mit
|
UMM-CSci-3601-S17/digital-display-garden-iteration-3-dorfner,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2,UMM-CSci-3601-S17/digital-display-garden-iteration-3-dorfner,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2,UMM-CSci-3601-S17/digital-display-garden-iteration-3-dorfner,UMM-CSci-3601-S17/digital-display-garden-iteration-3-dorfner,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2
|
java
|
## Code Before:
package umm3601.plant;
import com.google.gson.Gson;
import org.junit.Before;
import org.junit.Test;
import umm3601.digitalDisplayGarden.Plant;
import umm3601.digitalDisplayGarden.PlantController;
import umm3601.plant.PopulateMockDatabase;
import java.io.IOException;
import static junit.framework.TestCase.assertEquals;
public class FilterPlantsByGardenLocation {
@Before
public void setUpDB() throws IOException{
PopulateMockDatabase mockDatabase = new PopulateMockDatabase();
mockDatabase.clearAndPopulateDBAgain();
}
@Test
public void findByGardenLocation() throws IOException {
PlantController plantController = new PlantController();
Plant[] filteredPlants;
Gson gson = new Gson();
String rawPlants = plantController.getGardenLocations();
filteredPlants = gson.fromJson(rawPlants, Plant[].class);
assertEquals("Incorrect", 1, filteredPlants.length);
}
}
## Instruction:
Add and pass tests for gardenLocation
## Code After:
package umm3601.plant;
import com.google.gson.Gson;
import org.junit.Before;
import org.junit.Test;
import umm3601.digitalDisplayGarden.Plant;
import umm3601.digitalDisplayGarden.PlantController;
import umm3601.plant.PopulateMockDatabase;
import java.io.IOException;
import static junit.framework.TestCase.assertEquals;
public class FilterPlantsByGardenLocation {
@Before
public void setUpDB() throws IOException{
PopulateMockDatabase mockDatabase = new PopulateMockDatabase();
mockDatabase.clearAndPopulateDBAgain();
}
@Test
public void findByGardenLocation() throws IOException {
PlantController plantController = new PlantController();
GardenLocation[] filteredPlants;
Gson gson = new Gson();
//System.out.println();
String rawPlants = plantController.getGardenLocations();
filteredPlants = gson.fromJson(rawPlants, GardenLocation[].class);
assertEquals("Incorrect number of unique garden locations", 2, filteredPlants.length);
assertEquals("Incorrect zero index", "10.0", filteredPlants[0]._id);
assertEquals("Incorrect value for index 1", "7.0", filteredPlants[1]._id);
}
}
|
# ... existing code ...
@Test
public void findByGardenLocation() throws IOException {
PlantController plantController = new PlantController();
GardenLocation[] filteredPlants;
Gson gson = new Gson();
//System.out.println();
String rawPlants = plantController.getGardenLocations();
filteredPlants = gson.fromJson(rawPlants, GardenLocation[].class);
assertEquals("Incorrect number of unique garden locations", 2, filteredPlants.length);
assertEquals("Incorrect zero index", "10.0", filteredPlants[0]._id);
assertEquals("Incorrect value for index 1", "7.0", filteredPlants[1]._id);
}
}
# ... rest of the code ...
|
4705e8ddf88e130ce1899366e2647176ce6d9407
|
src/main.c
|
src/main.c
|
int main() {
initscr();
cbreak();
noecho();
keypad(stdscr, TRUE); // make keys work
curs_set(0); // hide cursor
timeout(100);
int xmax;
int ymax;
getmaxyx(stdscr, ymax, xmax);
enum Direction dir = RIGHT;
Board* board = create_board(create_snake(), NULL, xmax, ymax);
int i;
for (i = 0; i < 6; i++) {
add_new_food(board);
}
while(true) {
erase();
display_points(board->snake, ACS_BLOCK);
display_points(board->foods, ACS_DIAMOND);
dir = get_next_move(dir);
enum Status status = move_snake(board, dir);
if (status == FAILURE) break;
}
endwin();
return 0;
}
|
int main() {
initscr();
cbreak();
noecho();
keypad(stdscr, TRUE); // make keys work
curs_set(0); // hide cursor
timeout(100);
int xmax;
int ymax;
getmaxyx(stdscr, ymax, xmax);
enum Direction dir = RIGHT;
Board* board = create_board(create_snake(), NULL, xmax, ymax);
int i;
for (i = 0; i < 6; i++) {
add_new_food(board);
}
while(true) {
clear();
display_points(board->snake, ACS_BLOCK);
display_points(board->foods, ACS_DIAMOND);
refresh();
dir = get_next_move(dir);
enum Status status = move_snake(board, dir);
if (status == FAILURE) break;
}
endwin();
return 0;
}
|
Call `clear` and `refresh` to update screen
|
Call `clear` and `refresh` to update screen
|
C
|
mit
|
jvns/snake,jvns/snake
|
c
|
## Code Before:
int main() {
initscr();
cbreak();
noecho();
keypad(stdscr, TRUE); // make keys work
curs_set(0); // hide cursor
timeout(100);
int xmax;
int ymax;
getmaxyx(stdscr, ymax, xmax);
enum Direction dir = RIGHT;
Board* board = create_board(create_snake(), NULL, xmax, ymax);
int i;
for (i = 0; i < 6; i++) {
add_new_food(board);
}
while(true) {
erase();
display_points(board->snake, ACS_BLOCK);
display_points(board->foods, ACS_DIAMOND);
dir = get_next_move(dir);
enum Status status = move_snake(board, dir);
if (status == FAILURE) break;
}
endwin();
return 0;
}
## Instruction:
Call `clear` and `refresh` to update screen
## Code After:
int main() {
initscr();
cbreak();
noecho();
keypad(stdscr, TRUE); // make keys work
curs_set(0); // hide cursor
timeout(100);
int xmax;
int ymax;
getmaxyx(stdscr, ymax, xmax);
enum Direction dir = RIGHT;
Board* board = create_board(create_snake(), NULL, xmax, ymax);
int i;
for (i = 0; i < 6; i++) {
add_new_food(board);
}
while(true) {
clear();
display_points(board->snake, ACS_BLOCK);
display_points(board->foods, ACS_DIAMOND);
refresh();
dir = get_next_move(dir);
enum Status status = move_snake(board, dir);
if (status == FAILURE) break;
}
endwin();
return 0;
}
|
// ... existing code ...
}
while(true) {
clear();
display_points(board->snake, ACS_BLOCK);
display_points(board->foods, ACS_DIAMOND);
refresh();
dir = get_next_move(dir);
enum Status status = move_snake(board, dir);
if (status == FAILURE) break;
// ... rest of the code ...
|
7a735bebf195f766a0db97b3fba6793a69a5731a
|
microcosm_elasticsearch/main.py
|
microcosm_elasticsearch/main.py
|
from argparse import ArgumentParser
def createall_main(graph):
"""
Initialize indexes and mappings.
"""
parser = ArgumentParser()
parser.add_argument("--only", action="append")
parser.add_argument("--skip", action="append")
parser.add_argument("-D", "--drop", action="store_true")
args = parser.parse_args()
graph.elasticsearch_index_registry.createall(
force=args.drop,
only=args.only,
skip=args.skip,
)
|
from argparse import ArgumentParser
from json import dump, loads
from sys import stdout
def createall_main(graph):
"""
Initialize indexes and mappings.
"""
parser = ArgumentParser()
parser.add_argument("--only", action="append")
parser.add_argument("--skip", action="append")
parser.add_argument("-D", "--drop", action="store_true")
args = parser.parse_args()
graph.elasticsearch_index_registry.createall(
force=args.drop,
only=args.only,
skip=args.skip,
)
def query_main(graph, default_index):
parser = ArgumentParser()
parser.add_argument("--index", default=default_index)
parser.add_argument("--query", default='{"match_all": {}}')
args = parser.parse_args()
try:
query = loads(args.query)
except:
parser.error("query must be valid json")
response = graph.elasticsearch_client.search(
index=args.index,
body=dict(query=query),
)
dump(response, stdout)
|
Add a query entry point
|
Add a query entry point
|
Python
|
apache-2.0
|
globality-corp/microcosm-elasticsearch,globality-corp/microcosm-elasticsearch
|
python
|
## Code Before:
from argparse import ArgumentParser
def createall_main(graph):
"""
Initialize indexes and mappings.
"""
parser = ArgumentParser()
parser.add_argument("--only", action="append")
parser.add_argument("--skip", action="append")
parser.add_argument("-D", "--drop", action="store_true")
args = parser.parse_args()
graph.elasticsearch_index_registry.createall(
force=args.drop,
only=args.only,
skip=args.skip,
)
## Instruction:
Add a query entry point
## Code After:
from argparse import ArgumentParser
from json import dump, loads
from sys import stdout
def createall_main(graph):
"""
Initialize indexes and mappings.
"""
parser = ArgumentParser()
parser.add_argument("--only", action="append")
parser.add_argument("--skip", action="append")
parser.add_argument("-D", "--drop", action="store_true")
args = parser.parse_args()
graph.elasticsearch_index_registry.createall(
force=args.drop,
only=args.only,
skip=args.skip,
)
def query_main(graph, default_index):
parser = ArgumentParser()
parser.add_argument("--index", default=default_index)
parser.add_argument("--query", default='{"match_all": {}}')
args = parser.parse_args()
try:
query = loads(args.query)
except:
parser.error("query must be valid json")
response = graph.elasticsearch_client.search(
index=args.index,
body=dict(query=query),
)
dump(response, stdout)
|
// ... existing code ...
from argparse import ArgumentParser
from json import dump, loads
from sys import stdout
def createall_main(graph):
// ... modified code ...
only=args.only,
skip=args.skip,
)
def query_main(graph, default_index):
parser = ArgumentParser()
parser.add_argument("--index", default=default_index)
parser.add_argument("--query", default='{"match_all": {}}')
args = parser.parse_args()
try:
query = loads(args.query)
except:
parser.error("query must be valid json")
response = graph.elasticsearch_client.search(
index=args.index,
body=dict(query=query),
)
dump(response, stdout)
// ... rest of the code ...
|
58d785ee94f0b6ed34ff4014defe18973c2decaf
|
src/main/java/info/u_team/u_team_core/inventory/UItemStackHandler.java
|
src/main/java/info/u_team/u_team_core/inventory/UItemStackHandler.java
|
package info.u_team.u_team_core.inventory;
import info.u_team.u_team_core.api.item.IExtendedItemHandler;
import net.minecraft.inventory.ItemStackHelper;
import net.minecraft.nbt.CompoundNBT;
import net.minecraftforge.items.ItemStackHandler;
public class UItemStackHandler extends ItemStackHandler implements IExtendedItemHandler {
public UItemStackHandler(int size) {
super(size);
}
@Override
public void setSize(int size) {
throw new UnsupportedOperationException();
}
@Override
public CompoundNBT serializeNBT() {
final CompoundNBT compound = new CompoundNBT();
ItemStackHelper.saveAllItems(compound, stacks, false);
return compound;
}
@Override
public void deserializeNBT(CompoundNBT compound) {
ItemStackHelper.loadAllItems(compound, stacks);
onLoad();
}
}
|
package info.u_team.u_team_core.inventory;
import info.u_team.u_team_core.api.item.IExtendedItemHandler;
import net.minecraft.inventory.ItemStackHelper;
import net.minecraft.nbt.CompoundNBT;
import net.minecraftforge.items.ItemStackHandler;
public class UItemStackHandler extends ItemStackHandler implements IExtendedItemHandler {
public UItemStackHandler(int size) {
super(size);
}
@Override
public void setSize(int size) {
throw new UnsupportedOperationException();
}
@Override
public CompoundNBT serializeNBT() {
final CompoundNBT compound = new CompoundNBT();
ItemStackHelper.saveAllItems(compound, stacks, false);
return compound;
}
@Override
public void deserializeNBT(CompoundNBT compound) {
ItemStackHelper.loadAllItems(compound, stacks);
onLoad();
}
@Override
public void onContentsChanged(int slot) {
super.onContentsChanged(slot);
}
}
|
Make onContentsChanged public in the uitemstackhandler
|
Make onContentsChanged public in the uitemstackhandler
|
Java
|
apache-2.0
|
MC-U-Team/U-Team-Core,MC-U-Team/U-Team-Core
|
java
|
## Code Before:
package info.u_team.u_team_core.inventory;
import info.u_team.u_team_core.api.item.IExtendedItemHandler;
import net.minecraft.inventory.ItemStackHelper;
import net.minecraft.nbt.CompoundNBT;
import net.minecraftforge.items.ItemStackHandler;
public class UItemStackHandler extends ItemStackHandler implements IExtendedItemHandler {
public UItemStackHandler(int size) {
super(size);
}
@Override
public void setSize(int size) {
throw new UnsupportedOperationException();
}
@Override
public CompoundNBT serializeNBT() {
final CompoundNBT compound = new CompoundNBT();
ItemStackHelper.saveAllItems(compound, stacks, false);
return compound;
}
@Override
public void deserializeNBT(CompoundNBT compound) {
ItemStackHelper.loadAllItems(compound, stacks);
onLoad();
}
}
## Instruction:
Make onContentsChanged public in the uitemstackhandler
## Code After:
package info.u_team.u_team_core.inventory;
import info.u_team.u_team_core.api.item.IExtendedItemHandler;
import net.minecraft.inventory.ItemStackHelper;
import net.minecraft.nbt.CompoundNBT;
import net.minecraftforge.items.ItemStackHandler;
public class UItemStackHandler extends ItemStackHandler implements IExtendedItemHandler {
public UItemStackHandler(int size) {
super(size);
}
@Override
public void setSize(int size) {
throw new UnsupportedOperationException();
}
@Override
public CompoundNBT serializeNBT() {
final CompoundNBT compound = new CompoundNBT();
ItemStackHelper.saveAllItems(compound, stacks, false);
return compound;
}
@Override
public void deserializeNBT(CompoundNBT compound) {
ItemStackHelper.loadAllItems(compound, stacks);
onLoad();
}
@Override
public void onContentsChanged(int slot) {
super.onContentsChanged(slot);
}
}
|
...
ItemStackHelper.loadAllItems(compound, stacks);
onLoad();
}
@Override
public void onContentsChanged(int slot) {
super.onContentsChanged(slot);
}
}
...
|
efa90202a0586f15575af11ef299b122de413b30
|
duralex/AddGitHubIssueVisitor.py
|
duralex/AddGitHubIssueVisitor.py
|
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
from github import Github
class AddGitHubIssueVisitor(AbstractVisitor):
def __init__(self, args):
self.github = Github(args.github_token)
self.repo = self.github.get_repo(args.github_repository)
self.issues = list(self.repo.get_issues())
self.current_issue = -1
super(AddGitHubIssueVisitor, self).__init__()
def visit_edit_node(self, node, post):
if post:
return
if 'commitMessage' not in node:
node['commitMessage'] = '(#' + str(self.current_issue) + ')'
else:
node['commitMessage'] = node['commitMessage'] + ' (#' + str(self.current_issue) + ')'
def visit_node(self, node):
if 'type' in node and node['type'] == 'article':
title = 'Article ' + str(node['order'])
body = node['content']
found = False
for issue in self.issues:
if issue.title == title:
found = True
node['githubIssue'] = issue.html_url
self.current_issue = issue.number
if issue.body != body:
issue.edit(title=title, body=body)
if not found:
issue = self.repo.create_issue(title=title, body=body)
self.current_issue = issue.number
super(AddGitHubIssueVisitor, self).visit_node(node)
|
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
from github import Github
class AddGitHubIssueVisitor(AbstractVisitor):
def __init__(self, args):
self.github = Github(args.github_token)
self.repo = self.github.get_repo(args.github_repository)
self.issues = list(self.repo.get_issues())
self.current_issue = -1
super(AddGitHubIssueVisitor, self).__init__()
def visit_edit_node(self, node, post):
if post:
return
if 'commitMessage' not in node:
node['commitMessage'] = '(#' + str(self.current_issue) + ')'
else:
node['commitMessage'] = node['commitMessage'] + '\nGitHub: #' + str(self.current_issue)
def visit_node(self, node):
if 'type' in node and node['type'] == 'article':
title = 'Article ' + str(node['order'])
body = node['content']
found = False
for issue in self.issues:
if issue.title == title:
found = True
node['githubIssue'] = issue.html_url
self.current_issue = issue.number
if issue.body != body:
issue.edit(title=title, body=body)
if not found:
issue = self.repo.create_issue(title=title, body=body)
self.current_issue = issue.number
super(AddGitHubIssueVisitor, self).visit_node(node)
|
Add the GitHub issue number as a new line in the commitMessage field.
|
Add the GitHub issue number as a new line in the commitMessage field.
|
Python
|
mit
|
Legilibre/duralex
|
python
|
## Code Before:
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
from github import Github
class AddGitHubIssueVisitor(AbstractVisitor):
def __init__(self, args):
self.github = Github(args.github_token)
self.repo = self.github.get_repo(args.github_repository)
self.issues = list(self.repo.get_issues())
self.current_issue = -1
super(AddGitHubIssueVisitor, self).__init__()
def visit_edit_node(self, node, post):
if post:
return
if 'commitMessage' not in node:
node['commitMessage'] = '(#' + str(self.current_issue) + ')'
else:
node['commitMessage'] = node['commitMessage'] + ' (#' + str(self.current_issue) + ')'
def visit_node(self, node):
if 'type' in node and node['type'] == 'article':
title = 'Article ' + str(node['order'])
body = node['content']
found = False
for issue in self.issues:
if issue.title == title:
found = True
node['githubIssue'] = issue.html_url
self.current_issue = issue.number
if issue.body != body:
issue.edit(title=title, body=body)
if not found:
issue = self.repo.create_issue(title=title, body=body)
self.current_issue = issue.number
super(AddGitHubIssueVisitor, self).visit_node(node)
## Instruction:
Add the GitHub issue number as a new line in the commitMessage field.
## Code After:
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
from github import Github
class AddGitHubIssueVisitor(AbstractVisitor):
def __init__(self, args):
self.github = Github(args.github_token)
self.repo = self.github.get_repo(args.github_repository)
self.issues = list(self.repo.get_issues())
self.current_issue = -1
super(AddGitHubIssueVisitor, self).__init__()
def visit_edit_node(self, node, post):
if post:
return
if 'commitMessage' not in node:
node['commitMessage'] = '(#' + str(self.current_issue) + ')'
else:
node['commitMessage'] = node['commitMessage'] + '\nGitHub: #' + str(self.current_issue)
def visit_node(self, node):
if 'type' in node and node['type'] == 'article':
title = 'Article ' + str(node['order'])
body = node['content']
found = False
for issue in self.issues:
if issue.title == title:
found = True
node['githubIssue'] = issue.html_url
self.current_issue = issue.number
if issue.body != body:
issue.edit(title=title, body=body)
if not found:
issue = self.repo.create_issue(title=title, body=body)
self.current_issue = issue.number
super(AddGitHubIssueVisitor, self).visit_node(node)
|
...
if 'commitMessage' not in node:
node['commitMessage'] = '(#' + str(self.current_issue) + ')'
else:
node['commitMessage'] = node['commitMessage'] + '\nGitHub: #' + str(self.current_issue)
def visit_node(self, node):
...
|
db981f7616283992fd1d17a3b1bf7d300b8ee34f
|
proper_parens.py
|
proper_parens.py
|
from __future__ import unicode_literals
<<<<<<< HEAD
def check_statement1(value):
output = 0
while output >= 0:
for item in value:
if item == ")":
output -= 1
if output == -1:
return -1
elif item == "(":
output += 1
if output == 0:
return 0
elif output > 1:
return 1
=======
def check_statement(value):
''' Return 1, 0, or -1 if input is open, balanced, or broken. '''
output = 0
index = 0
while index < len(value) and output >= 0:
# If the count is ever < 0, statement must be -1 (broken), end loop
# If the index is out of range, end loop
if value[index] == ")":
# Subtract 1 for every close paren
output -= 1
elif value[index] == "(":
# Add 1 for every close paren
output += 1
index += 1
if output == -1:
# Check if output is -1 (broken)
return output
elif not output:
# Check if output is 0 (balanced)
return output
else:
# Must be 1 (open) if it makes it to here
return 1
>>>>>>> 74dee1d09fdc09f93af3d15286336d7face4ba08
|
from __future__ import unicode_literals
def check_statement(value):
''' Return 1, 0, or -1 if input is open, balanced, or broken. '''
output = 0
index = 0
while index < len(value) and output >= 0:
# If the count is ever < 0, statement must be -1 (broken), end loop
# If the index is out of range, end loop
if value[index] == ")":
# Subtract 1 for every close paren
output -= 1
elif value[index] == "(":
# Add 1 for every close paren
output += 1
index += 1
if output == -1:
# Check if output is -1 (broken)
return output
elif not output:
# Check if output is 0 (balanced)
return output
else:
# Must be 1 (open) if it makes it to here
return 1
|
Fix proper parens merge conflict
|
Fix proper parens merge conflict
|
Python
|
mit
|
constanthatz/data-structures
|
python
|
## Code Before:
from __future__ import unicode_literals
<<<<<<< HEAD
def check_statement1(value):
output = 0
while output >= 0:
for item in value:
if item == ")":
output -= 1
if output == -1:
return -1
elif item == "(":
output += 1
if output == 0:
return 0
elif output > 1:
return 1
=======
def check_statement(value):
''' Return 1, 0, or -1 if input is open, balanced, or broken. '''
output = 0
index = 0
while index < len(value) and output >= 0:
# If the count is ever < 0, statement must be -1 (broken), end loop
# If the index is out of range, end loop
if value[index] == ")":
# Subtract 1 for every close paren
output -= 1
elif value[index] == "(":
# Add 1 for every close paren
output += 1
index += 1
if output == -1:
# Check if output is -1 (broken)
return output
elif not output:
# Check if output is 0 (balanced)
return output
else:
# Must be 1 (open) if it makes it to here
return 1
>>>>>>> 74dee1d09fdc09f93af3d15286336d7face4ba08
## Instruction:
Fix proper parens merge conflict
## Code After:
from __future__ import unicode_literals
def check_statement(value):
''' Return 1, 0, or -1 if input is open, balanced, or broken. '''
output = 0
index = 0
while index < len(value) and output >= 0:
# If the count is ever < 0, statement must be -1 (broken), end loop
# If the index is out of range, end loop
if value[index] == ")":
# Subtract 1 for every close paren
output -= 1
elif value[index] == "(":
# Add 1 for every close paren
output += 1
index += 1
if output == -1:
# Check if output is -1 (broken)
return output
elif not output:
# Check if output is 0 (balanced)
return output
else:
# Must be 1 (open) if it makes it to here
return 1
|
...
from __future__ import unicode_literals
def check_statement(value):
''' Return 1, 0, or -1 if input is open, balanced, or broken. '''
output = 0
...
else:
# Must be 1 (open) if it makes it to here
return 1
...
|
ebb5a2f56c691456b5b65b9448d11b113c4efa46
|
fedmsg/meta/announce.py
|
fedmsg/meta/announce.py
|
from fedmsg.meta.base import BaseProcessor
class AnnounceProcessor(BaseProcessor):
__name__ = "announce"
__description__ = "Official Fedora Announcements"
__link__ = "http://fedoraproject.org/"
__docs__ = "http://fedoraproject.org/"
__obj__ = "Announcements"
def subtitle(self, msg, **config):
return msg['msg']['message']
def link(self, msg, **config):
return msg['msg']['link']
def usernames(self, msg, **config):
return set([msg['username']])
|
from fedmsg.meta.base import BaseProcessor
class AnnounceProcessor(BaseProcessor):
__name__ = "announce"
__description__ = "Official Fedora Announcements"
__link__ = "http://fedoraproject.org/"
__docs__ = "http://fedoraproject.org/"
__obj__ = "Announcements"
def subtitle(self, msg, **config):
return msg['msg']['message']
def link(self, msg, **config):
return msg['msg']['link']
def usernames(self, msg, **config):
users = set()
if 'username' in msg:
users.update(set([msg['username']]))
return users
|
Handle the situation where in old message the 'username' key does not exists
|
Handle the situation where in old message the 'username' key does not exists
With this commit processing an old message with fedmsg_meta will not break
if that old message does not have the 'username' key.
|
Python
|
lgpl-2.1
|
chaiku/fedmsg,vivekanand1101/fedmsg,vivekanand1101/fedmsg,cicku/fedmsg,mathstuf/fedmsg,mathstuf/fedmsg,maxamillion/fedmsg,mathstuf/fedmsg,chaiku/fedmsg,fedora-infra/fedmsg,fedora-infra/fedmsg,pombredanne/fedmsg,pombredanne/fedmsg,cicku/fedmsg,maxamillion/fedmsg,chaiku/fedmsg,vivekanand1101/fedmsg,pombredanne/fedmsg,cicku/fedmsg,maxamillion/fedmsg,fedora-infra/fedmsg
|
python
|
## Code Before:
from fedmsg.meta.base import BaseProcessor
class AnnounceProcessor(BaseProcessor):
__name__ = "announce"
__description__ = "Official Fedora Announcements"
__link__ = "http://fedoraproject.org/"
__docs__ = "http://fedoraproject.org/"
__obj__ = "Announcements"
def subtitle(self, msg, **config):
return msg['msg']['message']
def link(self, msg, **config):
return msg['msg']['link']
def usernames(self, msg, **config):
return set([msg['username']])
## Instruction:
Handle the situation where in old message the 'username' key does not exists
With this commit processing an old message with fedmsg_meta will not break
if that old message does not have the 'username' key.
## Code After:
from fedmsg.meta.base import BaseProcessor
class AnnounceProcessor(BaseProcessor):
__name__ = "announce"
__description__ = "Official Fedora Announcements"
__link__ = "http://fedoraproject.org/"
__docs__ = "http://fedoraproject.org/"
__obj__ = "Announcements"
def subtitle(self, msg, **config):
return msg['msg']['message']
def link(self, msg, **config):
return msg['msg']['link']
def usernames(self, msg, **config):
users = set()
if 'username' in msg:
users.update(set([msg['username']]))
return users
|
...
return msg['msg']['link']
def usernames(self, msg, **config):
users = set()
if 'username' in msg:
users.update(set([msg['username']]))
return users
...
|
1fc600ce80a55a59dc3df143d4e65d2898d64b62
|
src/edu/wpi/first/wpilibj/templates/RobotMain.java
|
src/edu/wpi/first/wpilibj/templates/RobotMain.java
|
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.templates.commands.*;
/**
* Main Robot Class.
*/
public class RobotMain extends IterativeRobot {
private ImageProcess ip;
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
//ip = new ImageProcess();
// Initialize all subsystems
CommandBase.init();
}
public void autonomousInit() {
ip.start();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
Scheduler.getInstance().run();
}
public void teleopInit() {
}
/**
* This function is called periodically during operator control.
*/
public void teleopPeriodic() {
Scheduler.getInstance().run();
}
/**
* This function is called periodically during test mode.
*/
public void testPeriodic() {
LiveWindow.run();
}
public void disabledPeriodic() {
}
public void disabledInit() {
System.out.println("Robot Main disabledInit(): Called");
}
}
|
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.templates.commands.*;
/**
* Main Robot Class.
*/
public class RobotMain extends IterativeRobot {
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
// Initialize all subsystems
CommandBase.init();
}
public void autonomousInit() {
ImageProcess ip = new ImageProcess();
ip.start();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
Scheduler.getInstance().run();
}
public void teleopInit() {
}
/**
* This function is called periodically during operator control.
*/
public void teleopPeriodic() {
Scheduler.getInstance().run();
}
/**
* This function is called periodically during test mode.
*/
public void testPeriodic() {
LiveWindow.run();
}
public void disabledPeriodic() {
}
public void disabledInit() {
System.out.println("Robot Main disabledInit(): Called");
}
}
|
Move this out of RobotInit so we can use the robot for other things. Swap to "autonomous" mode to trigger the ImageProcess event.
|
Move this out of RobotInit so we can use the robot for other things. Swap to "autonomous" mode to trigger the ImageProcess event.
In the near future this should either be moved to a self-instantiated default-command from the related subsystem, or it should be triggered with a joystick button or other event.
|
Java
|
bsd-3-clause
|
FIRST-4030/2013
|
java
|
## Code Before:
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.templates.commands.*;
/**
* Main Robot Class.
*/
public class RobotMain extends IterativeRobot {
private ImageProcess ip;
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
//ip = new ImageProcess();
// Initialize all subsystems
CommandBase.init();
}
public void autonomousInit() {
ip.start();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
Scheduler.getInstance().run();
}
public void teleopInit() {
}
/**
* This function is called periodically during operator control.
*/
public void teleopPeriodic() {
Scheduler.getInstance().run();
}
/**
* This function is called periodically during test mode.
*/
public void testPeriodic() {
LiveWindow.run();
}
public void disabledPeriodic() {
}
public void disabledInit() {
System.out.println("Robot Main disabledInit(): Called");
}
}
## Instruction:
Move this out of RobotInit so we can use the robot for other things. Swap to "autonomous" mode to trigger the ImageProcess event.
In the near future this should either be moved to a self-instantiated default-command from the related subsystem, or it should be triggered with a joystick button or other event.
## Code After:
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.templates.commands.*;
/**
* Main Robot Class.
*/
public class RobotMain extends IterativeRobot {
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
// Initialize all subsystems
CommandBase.init();
}
public void autonomousInit() {
ImageProcess ip = new ImageProcess();
ip.start();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
Scheduler.getInstance().run();
}
public void teleopInit() {
}
/**
* This function is called periodically during operator control.
*/
public void teleopPeriodic() {
Scheduler.getInstance().run();
}
/**
* This function is called periodically during test mode.
*/
public void testPeriodic() {
LiveWindow.run();
}
public void disabledPeriodic() {
}
public void disabledInit() {
System.out.println("Robot Main disabledInit(): Called");
}
}
|
...
*/
public class RobotMain extends IterativeRobot {
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
// Initialize all subsystems
CommandBase.init();
}
public void autonomousInit() {
ImageProcess ip = new ImageProcess();
ip.start();
}
...
public void disabledInit() {
System.out.println("Robot Main disabledInit(): Called");
}
}
...
|
b14396fdd8bfbc17eb3e463527cc16cba3f88f4e
|
src/main/java/org/limeprotocol/util/StringUtils.java
|
src/main/java/org/limeprotocol/util/StringUtils.java
|
package org.limeprotocol.util;
import java.util.LinkedHashMap;
import java.util.Map;
public class StringUtils {
public static boolean isNullOrEmpty(String string){
return string == null || string.equals("");
}
public static boolean isNullOrWhiteSpace(String string){
return isNullOrEmpty(string) || string.trim().length() == 0;
}
public static String format(String pattern, Object... values){
Map<String, Object> tags = new LinkedHashMap<String, Object>();
for (int i=0; i<values.length; i++){
tags.put("\\{" + i + "\\}", values[i]);
}
String formatted = pattern;
for (Map.Entry<String, Object> tag : tags.entrySet()) {
// bottleneck, creating temporary String objects!
formatted = formatted.replaceAll(tag.getKey(), tag.getValue().toString());
}
return formatted;
}
public static String trimEnd(String string, String finalCharacter){
string.trim();
if(string.endsWith(finalCharacter)){
return string.substring(0, string.length()-1);
}
return string;
}
}
|
package org.limeprotocol.util;
import java.util.LinkedHashMap;
import java.util.Map;
public class StringUtils {
public static boolean isNullOrEmpty(String string){
return string == null || string.equals("");
}
public static boolean isNullOrWhiteSpace(String string){
return isNullOrEmpty(string) || string.trim().length() == 0;
}
public static String format(String pattern, Object... values){
Map<String, Object> tags = new LinkedHashMap<String, Object>();
for (int i=0; i<values.length; i++){
tags.put("\\{" + i + "\\}", values[i]==null ? "" : values[i]);
}
String formatted = pattern;
for (Map.Entry<String, Object> tag : tags.entrySet()) {
// bottleneck, creating temporary String objects!
formatted = formatted.replaceAll(tag.getKey(), tag.getValue().toString());
}
return formatted;
}
public static String trimEnd(String string, String finalCharacter){
string.trim();
if(string.endsWith(finalCharacter)){
return string.substring(0, string.length()-1);
}
return string;
}
}
|
Transform null values to empty string
|
Transform null values to empty string
|
Java
|
apache-2.0
|
takenet/lime-java,andrebires/lime-java
|
java
|
## Code Before:
package org.limeprotocol.util;
import java.util.LinkedHashMap;
import java.util.Map;
public class StringUtils {
public static boolean isNullOrEmpty(String string){
return string == null || string.equals("");
}
public static boolean isNullOrWhiteSpace(String string){
return isNullOrEmpty(string) || string.trim().length() == 0;
}
public static String format(String pattern, Object... values){
Map<String, Object> tags = new LinkedHashMap<String, Object>();
for (int i=0; i<values.length; i++){
tags.put("\\{" + i + "\\}", values[i]);
}
String formatted = pattern;
for (Map.Entry<String, Object> tag : tags.entrySet()) {
// bottleneck, creating temporary String objects!
formatted = formatted.replaceAll(tag.getKey(), tag.getValue().toString());
}
return formatted;
}
public static String trimEnd(String string, String finalCharacter){
string.trim();
if(string.endsWith(finalCharacter)){
return string.substring(0, string.length()-1);
}
return string;
}
}
## Instruction:
Transform null values to empty string
## Code After:
package org.limeprotocol.util;
import java.util.LinkedHashMap;
import java.util.Map;
public class StringUtils {
public static boolean isNullOrEmpty(String string){
return string == null || string.equals("");
}
public static boolean isNullOrWhiteSpace(String string){
return isNullOrEmpty(string) || string.trim().length() == 0;
}
public static String format(String pattern, Object... values){
Map<String, Object> tags = new LinkedHashMap<String, Object>();
for (int i=0; i<values.length; i++){
tags.put("\\{" + i + "\\}", values[i]==null ? "" : values[i]);
}
String formatted = pattern;
for (Map.Entry<String, Object> tag : tags.entrySet()) {
// bottleneck, creating temporary String objects!
formatted = formatted.replaceAll(tag.getKey(), tag.getValue().toString());
}
return formatted;
}
public static String trimEnd(String string, String finalCharacter){
string.trim();
if(string.endsWith(finalCharacter)){
return string.substring(0, string.length()-1);
}
return string;
}
}
|
// ... existing code ...
Map<String, Object> tags = new LinkedHashMap<String, Object>();
for (int i=0; i<values.length; i++){
tags.put("\\{" + i + "\\}", values[i]==null ? "" : values[i]);
}
String formatted = pattern;
// ... rest of the code ...
|
1632b64372f2f38a6c43b000ace631d183278375
|
observations/forms.py
|
observations/forms.py
|
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
from .models import Observation
from stars.models import Star
from observers.models import Observer
class BatchUploadForm(forms.Form):
aavso_file = forms.FileField(label=_("Observations file"))
def process_file(self):
fp = self.cleaned_data['aavso_file']
reader = VisualFormatReader(fp)
observer = Observer.objects.get(aavso_code=reader.observer_code)
for row in reader:
try:
star = Star.objects.get(name=row['name'])
fainter_than = '<' in row['magnitude']
magnitude = float(row['magnitude'].replace('<', ''))
jd = float(row['date'])
try:
observation = Observation.objects.get(
observer=observer,
star=star,
jd=jd,
)
except Observation.DoesNotExist:
observation = Observation(
observer=observer,
star=star,
jd=jd,
)
observation.magnitude = magnitude
observation.fainter_than = fainter_than
observation.comp1 = row['comp1']
observation.comp2 = row['comp2']
observation.chart = row['chart']
observation.comment_code = row['comment_code']
observation.notes = row['notes']
observation.save()
except Exception as e:
print row
print e
continue
|
from __future__ import unicode_literals
from django import forms
from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
from .models import Observation
from stars.models import Star
from observers.models import Observer
class BatchUploadForm(forms.Form):
aavso_file = forms.FileField(label=_("Observations file"))
def process_file(self):
fp = self.cleaned_data['aavso_file']
reader = VisualFormatReader(fp)
observer = Observer.objects.get(aavso_code=reader.observer_code)
with transaction.atomic():
for row in reader:
try:
star = Star.objects.get(name=row['name'])
fainter_than = '<' in row['magnitude']
magnitude = float(row['magnitude'].replace('<', ''))
jd = float(row['date'])
try:
observation = Observation.objects.get(
observer=observer,
star=star,
jd=jd,
)
except Observation.DoesNotExist:
observation = Observation(
observer=observer,
star=star,
jd=jd,
)
observation.magnitude = magnitude
observation.fainter_than = fainter_than
observation.comp1 = row['comp1']
observation.comp2 = row['comp2']
observation.chart = row['chart']
observation.comment_code = row['comment_code']
observation.notes = row['notes']
observation.save()
except Exception as e:
print row
print e
continue
|
Use transaction.atomic in batch uploader.
|
Use transaction.atomic in batch uploader.
|
Python
|
mit
|
zsiciarz/variablestars.net,zsiciarz/variablestars.net,zsiciarz/variablestars.net
|
python
|
## Code Before:
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
from .models import Observation
from stars.models import Star
from observers.models import Observer
class BatchUploadForm(forms.Form):
aavso_file = forms.FileField(label=_("Observations file"))
def process_file(self):
fp = self.cleaned_data['aavso_file']
reader = VisualFormatReader(fp)
observer = Observer.objects.get(aavso_code=reader.observer_code)
for row in reader:
try:
star = Star.objects.get(name=row['name'])
fainter_than = '<' in row['magnitude']
magnitude = float(row['magnitude'].replace('<', ''))
jd = float(row['date'])
try:
observation = Observation.objects.get(
observer=observer,
star=star,
jd=jd,
)
except Observation.DoesNotExist:
observation = Observation(
observer=observer,
star=star,
jd=jd,
)
observation.magnitude = magnitude
observation.fainter_than = fainter_than
observation.comp1 = row['comp1']
observation.comp2 = row['comp2']
observation.chart = row['chart']
observation.comment_code = row['comment_code']
observation.notes = row['notes']
observation.save()
except Exception as e:
print row
print e
continue
## Instruction:
Use transaction.atomic in batch uploader.
## Code After:
from __future__ import unicode_literals
from django import forms
from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
from .models import Observation
from stars.models import Star
from observers.models import Observer
class BatchUploadForm(forms.Form):
aavso_file = forms.FileField(label=_("Observations file"))
def process_file(self):
fp = self.cleaned_data['aavso_file']
reader = VisualFormatReader(fp)
observer = Observer.objects.get(aavso_code=reader.observer_code)
with transaction.atomic():
for row in reader:
try:
star = Star.objects.get(name=row['name'])
fainter_than = '<' in row['magnitude']
magnitude = float(row['magnitude'].replace('<', ''))
jd = float(row['date'])
try:
observation = Observation.objects.get(
observer=observer,
star=star,
jd=jd,
)
except Observation.DoesNotExist:
observation = Observation(
observer=observer,
star=star,
jd=jd,
)
observation.magnitude = magnitude
observation.fainter_than = fainter_than
observation.comp1 = row['comp1']
observation.comp2 = row['comp2']
observation.chart = row['chart']
observation.comment_code = row['comment_code']
observation.notes = row['notes']
observation.save()
except Exception as e:
print row
print e
continue
|
...
from __future__ import unicode_literals
from django import forms
from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
...
fp = self.cleaned_data['aavso_file']
reader = VisualFormatReader(fp)
observer = Observer.objects.get(aavso_code=reader.observer_code)
with transaction.atomic():
for row in reader:
try:
star = Star.objects.get(name=row['name'])
fainter_than = '<' in row['magnitude']
magnitude = float(row['magnitude'].replace('<', ''))
jd = float(row['date'])
try:
observation = Observation.objects.get(
observer=observer,
star=star,
jd=jd,
)
except Observation.DoesNotExist:
observation = Observation(
observer=observer,
star=star,
jd=jd,
)
observation.magnitude = magnitude
observation.fainter_than = fainter_than
observation.comp1 = row['comp1']
observation.comp2 = row['comp2']
observation.chart = row['chart']
observation.comment_code = row['comment_code']
observation.notes = row['notes']
observation.save()
except Exception as e:
print row
print e
continue
...
|
8673da60a53da0013584f4903e5ccb8d615bc813
|
btrfs-structures/src/main/java/nl/gmta/btrfs/structure/stream/BtrfsValueType.java
|
btrfs-structures/src/main/java/nl/gmta/btrfs/structure/stream/BtrfsValueType.java
|
package nl.gmta.btrfs.structure.stream;
enum BtrfsValueType {
BTRFS_TLV_U8 (0x00),
BTRFS_TLV_U16 (0x01),
BTRFS_TLV_U32 (0x02),
BTRFS_TLV_U64 (0x03),
BTRFS_TLV_BINARY (0x04),
BTRFS_TLV_STRING (0x05),
BTRFS_TLV_UUID (0x06),
BTRFS_TLV_TIMESPEC (0x07);
private int value;
BtrfsValueType(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
|
package nl.gmta.btrfs.structure.stream;
enum BtrfsValueType {
U8 (0x00),
U16 (0x01),
U32 (0x02),
U64 (0x03),
BINARY (0x04),
STRING (0x05),
UUID (0x06),
TIMESPEC (0x07);
private int value;
BtrfsValueType(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
|
Remove common prefix from value type enum values
|
Remove common prefix from value type enum values
|
Java
|
mit
|
GMTA/btrfs-libs
|
java
|
## Code Before:
package nl.gmta.btrfs.structure.stream;
enum BtrfsValueType {
BTRFS_TLV_U8 (0x00),
BTRFS_TLV_U16 (0x01),
BTRFS_TLV_U32 (0x02),
BTRFS_TLV_U64 (0x03),
BTRFS_TLV_BINARY (0x04),
BTRFS_TLV_STRING (0x05),
BTRFS_TLV_UUID (0x06),
BTRFS_TLV_TIMESPEC (0x07);
private int value;
BtrfsValueType(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
## Instruction:
Remove common prefix from value type enum values
## Code After:
package nl.gmta.btrfs.structure.stream;
enum BtrfsValueType {
U8 (0x00),
U16 (0x01),
U32 (0x02),
U64 (0x03),
BINARY (0x04),
STRING (0x05),
UUID (0x06),
TIMESPEC (0x07);
private int value;
BtrfsValueType(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
|
// ... existing code ...
package nl.gmta.btrfs.structure.stream;
enum BtrfsValueType {
U8 (0x00),
U16 (0x01),
U32 (0x02),
U64 (0x03),
BINARY (0x04),
STRING (0x05),
UUID (0x06),
TIMESPEC (0x07);
private int value;
// ... rest of the code ...
|
2ee895c61f546f83f4b7fa0c6a2ba72578c378be
|
problem_2/solution.py
|
problem_2/solution.py
|
f1, f2, s, n = 0, 1, 0, 4000000
while f2 < n:
f2, f1 = f1, f1 + f2
if f2 % 2 == 0:
s += f2
print s
|
def sum_even_fibonacci_numbers_1():
f1, f2, s, = 0, 1, 0,
while f2 < 4000000:
f2, f1 = f1, f1 + f2
if f2 % 2 == 0:
s += f2
return s
def sum_even_fibonacci_numbers_2():
s, a, b = 0, 1, 1
c = a + b
while c < 4000000:
s += c
a = b + c
b = a + c
c = a + b
return s
|
Add a second Python implementation of problem 2
|
Add a second Python implementation of problem 2
|
Python
|
mit
|
mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler
|
python
|
## Code Before:
f1, f2, s, n = 0, 1, 0, 4000000
while f2 < n:
f2, f1 = f1, f1 + f2
if f2 % 2 == 0:
s += f2
print s
## Instruction:
Add a second Python implementation of problem 2
## Code After:
def sum_even_fibonacci_numbers_1():
f1, f2, s, = 0, 1, 0,
while f2 < 4000000:
f2, f1 = f1, f1 + f2
if f2 % 2 == 0:
s += f2
return s
def sum_even_fibonacci_numbers_2():
s, a, b = 0, 1, 1
c = a + b
while c < 4000000:
s += c
a = b + c
b = a + c
c = a + b
return s
|
...
def sum_even_fibonacci_numbers_1():
f1, f2, s, = 0, 1, 0,
while f2 < 4000000:
f2, f1 = f1, f1 + f2
if f2 % 2 == 0:
s += f2
return s
def sum_even_fibonacci_numbers_2():
s, a, b = 0, 1, 1
c = a + b
while c < 4000000:
s += c
a = b + c
b = a + c
c = a + b
return s
...
|
499add1d29847490141cda4625d9a4199e386283
|
ncdc_download/download_mapper2.py
|
ncdc_download/download_mapper2.py
|
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
filename, i + 1, retries))
try:
ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
except ftplib.all_errors as error:
sys.stderr.write('%s\n' % error)
continue
count = 0
for record in gzip.open(filename, 'rb'):
print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
count += 1
sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
os.remove(filename)
break
else:
ftp.quit()
sys.exit(1)
ftp.quit()
|
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
filename, i + 1, retries))
try:
ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
except ftplib.all_errors as error:
sys.stderr.write('%s\n' % error)
continue
count = 0
for record in gzip.open(filename, 'rb'):
print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
count += 1
os.remove(filename)
sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
break
else:
ftp.quit()
sys.exit(1)
ftp.quit()
|
Remove downloaded file before updating counter
|
Remove downloaded file before updating counter
|
Python
|
mit
|
simonbrady/cat,simonbrady/cat
|
python
|
## Code Before:
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
filename, i + 1, retries))
try:
ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
except ftplib.all_errors as error:
sys.stderr.write('%s\n' % error)
continue
count = 0
for record in gzip.open(filename, 'rb'):
print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
count += 1
sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
os.remove(filename)
break
else:
ftp.quit()
sys.exit(1)
ftp.quit()
## Instruction:
Remove downloaded file before updating counter
## Code After:
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
filename, i + 1, retries))
try:
ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
except ftplib.all_errors as error:
sys.stderr.write('%s\n' % error)
continue
count = 0
for record in gzip.open(filename, 'rb'):
print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
count += 1
os.remove(filename)
sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
break
else:
ftp.quit()
sys.exit(1)
ftp.quit()
|
// ... existing code ...
for record in gzip.open(filename, 'rb'):
print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
count += 1
os.remove(filename)
sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
break
else:
ftp.quit()
// ... rest of the code ...
|
f5094a976fd9e71e3d386f9234f96218111cce49
|
src/main/kotlin/engineer/carrot/warren/thump/config/GeneralConfiguration.kt
|
src/main/kotlin/engineer/carrot/warren/thump/config/GeneralConfiguration.kt
|
package engineer.carrot.warren.thump.config
import net.minecraftforge.common.config.Configuration
class GeneralConfiguration(configuration: Configuration) {
var obfuscateUserSourceFromMinecraft = true
init {
this.obfuscateUserSourceFromMinecraft = configuration.getBoolean(OBFUSCATE_USER_SOURCE_FROM_MINECRAFT, CATEGORY, this.obfuscateUserSourceFromMinecraft, OBFUSCATE_USER_SOURCE_FROM_MINECRAFT_COMMENT)
}
companion object {
private val CATEGORY = "general"
private val OBFUSCATE_USER_SOURCE_FROM_MINECRAFT = "ObfuscateUserSourceFromMinecraft"
private val OBFUSCATE_USER_SOURCE_FROM_MINECRAFT_COMMENT = "Inserts a zero-width character in to source usernames going from Minecraft to IRC - commonly used to prevent unnecessary pings."
}
}
|
package engineer.carrot.warren.thump.config
import net.minecraftforge.common.config.Configuration
class GeneralConfiguration(configuration: Configuration) {
var obfuscateUserSourceFromMinecraft = true
init {
this.obfuscateUserSourceFromMinecraft = configuration.getBoolean(OBFUSCATE_USER_SOURCE_FROM_MINECRAFT, CATEGORY, this.obfuscateUserSourceFromMinecraft, OBFUSCATE_USER_SOURCE_FROM_MINECRAFT_COMMENT)
}
companion object {
private val CATEGORY = "general"
private val OBFUSCATE_USER_SOURCE_FROM_MINECRAFT = "ObfuscateUserSourceFromMinecraft"
private val OBFUSCATE_USER_SOURCE_FROM_MINECRAFT_COMMENT = "Inserts a zero-width character in to source usernames going from Minecraft to other services - commonly used to prevent unnecessary pings."
}
}
|
Remove specific reference to IRC from general config
|
Remove specific reference to IRC from general config
|
Kotlin
|
isc
|
CarrotCodes/Thump,voxelcarrot/Thump,carrotengineer/Thump,WillowChat/Thump,voxelcarrot/Thump,carrotengineer/Thump,CarrotCodes/Thump,WillowChat/Thump
|
kotlin
|
## Code Before:
package engineer.carrot.warren.thump.config
import net.minecraftforge.common.config.Configuration
class GeneralConfiguration(configuration: Configuration) {
var obfuscateUserSourceFromMinecraft = true
init {
this.obfuscateUserSourceFromMinecraft = configuration.getBoolean(OBFUSCATE_USER_SOURCE_FROM_MINECRAFT, CATEGORY, this.obfuscateUserSourceFromMinecraft, OBFUSCATE_USER_SOURCE_FROM_MINECRAFT_COMMENT)
}
companion object {
private val CATEGORY = "general"
private val OBFUSCATE_USER_SOURCE_FROM_MINECRAFT = "ObfuscateUserSourceFromMinecraft"
private val OBFUSCATE_USER_SOURCE_FROM_MINECRAFT_COMMENT = "Inserts a zero-width character in to source usernames going from Minecraft to IRC - commonly used to prevent unnecessary pings."
}
}
## Instruction:
Remove specific reference to IRC from general config
## Code After:
package engineer.carrot.warren.thump.config
import net.minecraftforge.common.config.Configuration
class GeneralConfiguration(configuration: Configuration) {
var obfuscateUserSourceFromMinecraft = true
init {
this.obfuscateUserSourceFromMinecraft = configuration.getBoolean(OBFUSCATE_USER_SOURCE_FROM_MINECRAFT, CATEGORY, this.obfuscateUserSourceFromMinecraft, OBFUSCATE_USER_SOURCE_FROM_MINECRAFT_COMMENT)
}
companion object {
private val CATEGORY = "general"
private val OBFUSCATE_USER_SOURCE_FROM_MINECRAFT = "ObfuscateUserSourceFromMinecraft"
private val OBFUSCATE_USER_SOURCE_FROM_MINECRAFT_COMMENT = "Inserts a zero-width character in to source usernames going from Minecraft to other services - commonly used to prevent unnecessary pings."
}
}
|
# ... existing code ...
companion object {
private val CATEGORY = "general"
private val OBFUSCATE_USER_SOURCE_FROM_MINECRAFT = "ObfuscateUserSourceFromMinecraft"
private val OBFUSCATE_USER_SOURCE_FROM_MINECRAFT_COMMENT = "Inserts a zero-width character in to source usernames going from Minecraft to other services - commonly used to prevent unnecessary pings."
}
}
# ... rest of the code ...
|
a683ed193b85656e90ca7ee54298106fa6a313e4
|
tests/regression/36-octapron/17-traces-rpb-litmus.c
|
tests/regression/36-octapron/17-traces-rpb-litmus.c
|
// SKIP PARAM: --sets ana.activated[+] octApron
#include <pthread.h>
#include <assert.h>
int g = 42; // matches write in t_fun
pthread_mutex_t A = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t B = PTHREAD_MUTEX_INITIALIZER;
void *t_fun(void *arg) {
// pthread_mutex_lock(&A);
// pthread_mutex_lock(&B);
// g = 42;
// pthread_mutex_unlock(&B);
// pthread_mutex_unlock(&A);
return NULL;
}
int main(void) {
int r, t;
pthread_t id;
pthread_create(&id, NULL, t_fun, NULL);
pthread_mutex_lock(&A);
pthread_mutex_lock(&B);
if (r * r) {
g = 17;
pthread_mutex_unlock(&B); // publish to g#prot
pthread_mutex_lock(&B);
}
// locally written g is only in one branch, g == g#prot should be forgotten!
t = g;
assert(t == 17); // UNKNOWN!
pthread_mutex_unlock(&B);
pthread_mutex_unlock(&A);
return 0;
}
|
// SKIP PARAM: --sets ana.activated[+] octApron
#include <pthread.h>
#include <assert.h>
int g = 42; // matches write in t_fun
pthread_mutex_t A = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t B = PTHREAD_MUTEX_INITIALIZER;
void *t_fun(void *arg) {
pthread_mutex_lock(&A);
pthread_mutex_lock(&B);
g = 42;
pthread_mutex_unlock(&B);
pthread_mutex_unlock(&A);
return NULL;
}
int main(void) {
int r, t;
pthread_t id;
pthread_create(&id, NULL, t_fun, NULL);
pthread_mutex_lock(&A);
pthread_mutex_lock(&B);
if (r) {
g = 17;
pthread_mutex_unlock(&B); // publish to g#prot
pthread_mutex_lock(&B);
}
// locally written g is only in one branch, g == g#prot should be forgotten!
t = g;
assert(t == 17); // UNKNOWN!
pthread_mutex_unlock(&B);
pthread_mutex_unlock(&A);
return 0;
}
|
Remove debugging changes from 36/17
|
Remove debugging changes from 36/17
|
C
|
mit
|
goblint/analyzer,goblint/analyzer,goblint/analyzer,goblint/analyzer,goblint/analyzer
|
c
|
## Code Before:
// SKIP PARAM: --sets ana.activated[+] octApron
#include <pthread.h>
#include <assert.h>
int g = 42; // matches write in t_fun
pthread_mutex_t A = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t B = PTHREAD_MUTEX_INITIALIZER;
void *t_fun(void *arg) {
// pthread_mutex_lock(&A);
// pthread_mutex_lock(&B);
// g = 42;
// pthread_mutex_unlock(&B);
// pthread_mutex_unlock(&A);
return NULL;
}
int main(void) {
int r, t;
pthread_t id;
pthread_create(&id, NULL, t_fun, NULL);
pthread_mutex_lock(&A);
pthread_mutex_lock(&B);
if (r * r) {
g = 17;
pthread_mutex_unlock(&B); // publish to g#prot
pthread_mutex_lock(&B);
}
// locally written g is only in one branch, g == g#prot should be forgotten!
t = g;
assert(t == 17); // UNKNOWN!
pthread_mutex_unlock(&B);
pthread_mutex_unlock(&A);
return 0;
}
## Instruction:
Remove debugging changes from 36/17
## Code After:
// SKIP PARAM: --sets ana.activated[+] octApron
#include <pthread.h>
#include <assert.h>
int g = 42; // matches write in t_fun
pthread_mutex_t A = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t B = PTHREAD_MUTEX_INITIALIZER;
void *t_fun(void *arg) {
pthread_mutex_lock(&A);
pthread_mutex_lock(&B);
g = 42;
pthread_mutex_unlock(&B);
pthread_mutex_unlock(&A);
return NULL;
}
int main(void) {
int r, t;
pthread_t id;
pthread_create(&id, NULL, t_fun, NULL);
pthread_mutex_lock(&A);
pthread_mutex_lock(&B);
if (r) {
g = 17;
pthread_mutex_unlock(&B); // publish to g#prot
pthread_mutex_lock(&B);
}
// locally written g is only in one branch, g == g#prot should be forgotten!
t = g;
assert(t == 17); // UNKNOWN!
pthread_mutex_unlock(&B);
pthread_mutex_unlock(&A);
return 0;
}
|
// ... existing code ...
pthread_mutex_t B = PTHREAD_MUTEX_INITIALIZER;
void *t_fun(void *arg) {
pthread_mutex_lock(&A);
pthread_mutex_lock(&B);
g = 42;
pthread_mutex_unlock(&B);
pthread_mutex_unlock(&A);
return NULL;
}
// ... modified code ...
pthread_mutex_lock(&A);
pthread_mutex_lock(&B);
if (r) {
g = 17;
pthread_mutex_unlock(&B); // publish to g#prot
pthread_mutex_lock(&B);
// ... rest of the code ...
|
9171777c3945b3a1324d9b20ff607fd340747b58
|
cinder/version.py
|
cinder/version.py
|
from pbr import version as pbr_version
CINDER_VENDOR = "OpenStack Foundation"
CINDER_PRODUCT = "OpenStack Cinder"
CINDER_PACKAGE = None # OS distro package version suffix
loaded = False
version_info = pbr_version.VersionInfo('cinder')
version_string = version_info.version_string
|
CINDER_VENDOR = "OpenStack Foundation"
CINDER_PRODUCT = "OpenStack Cinder"
CINDER_PACKAGE = None # OS distro package version suffix
loaded = False
class VersionInfo:
version = "REDHATCINDERVERSION"
release = "REDHATCINDERRELEASE"
def release_string(self):
return '%s-%s' % (self.version, self.release)
def version_string(self):
return self.version
version_info = VersionInfo()
version_string = version_info.version_string
|
Remove runtime dep on python-pbr, python-d2to1
|
Remove runtime dep on python-pbr, python-d2to1
Requires RPM spec to fill in REDHATCINDERVERSION.
|
Python
|
apache-2.0
|
redhat-openstack/cinder,redhat-openstack/cinder
|
python
|
## Code Before:
from pbr import version as pbr_version
CINDER_VENDOR = "OpenStack Foundation"
CINDER_PRODUCT = "OpenStack Cinder"
CINDER_PACKAGE = None # OS distro package version suffix
loaded = False
version_info = pbr_version.VersionInfo('cinder')
version_string = version_info.version_string
## Instruction:
Remove runtime dep on python-pbr, python-d2to1
Requires RPM spec to fill in REDHATCINDERVERSION.
## Code After:
CINDER_VENDOR = "OpenStack Foundation"
CINDER_PRODUCT = "OpenStack Cinder"
CINDER_PACKAGE = None # OS distro package version suffix
loaded = False
class VersionInfo:
version = "REDHATCINDERVERSION"
release = "REDHATCINDERRELEASE"
def release_string(self):
return '%s-%s' % (self.version, self.release)
def version_string(self):
return self.version
version_info = VersionInfo()
version_string = version_info.version_string
|
// ... existing code ...
CINDER_VENDOR = "OpenStack Foundation"
CINDER_PRODUCT = "OpenStack Cinder"
// ... modified code ...
CINDER_PACKAGE = None # OS distro package version suffix
loaded = False
class VersionInfo:
version = "REDHATCINDERVERSION"
release = "REDHATCINDERRELEASE"
def release_string(self):
return '%s-%s' % (self.version, self.release)
def version_string(self):
return self.version
version_info = VersionInfo()
version_string = version_info.version_string
// ... rest of the code ...
|
e23914f0d21f3882aa6e4720d2a139cc697a29c4
|
Util/bukkit/src/main/java/tc/oc/commons/bukkit/chat/LegacyPlayerAudience.java
|
Util/bukkit/src/main/java/tc/oc/commons/bukkit/chat/LegacyPlayerAudience.java
|
package tc.oc.commons.bukkit.chat;
import net.md_5.bungee.api.chat.BaseComponent;
import org.bukkit.entity.Player;
import tc.oc.commons.core.chat.Component;
import tc.oc.commons.core.chat.Components;
public class LegacyPlayerAudience extends PlayerAudience {
private BaseComponent recentHotbarMessage;
public LegacyPlayerAudience(Player player) {
super(player);
}
@Override
public void sendHotbarMessage(BaseComponent message) {
// Do not spam hot bar messages, as the protocol converts
// them to regular chat messages.
if(!Components.equals(message, recentHotbarMessage)) {
super.sendHotbarMessage(message);
recentHotbarMessage = message;
}
}
@Override
public void showTitle(BaseComponent title, BaseComponent subtitle, int inTicks, int stayTicks, int outTicks) {
super.sendMessage(new Component(title).extra(" ").extra(subtitle));
}
}
|
package tc.oc.commons.bukkit.chat;
import net.md_5.bungee.api.chat.BaseComponent;
import org.bukkit.entity.Player;
import tc.oc.commons.core.chat.Components;
import tc.oc.commons.core.stream.Collectors;
import java.util.stream.Stream;
public class LegacyPlayerAudience extends PlayerAudience {
private BaseComponent recentHotbarMessage;
public LegacyPlayerAudience(Player player) {
super(player);
}
@Override
public void sendHotbarMessage(BaseComponent message) {
// Do not spam hot bar messages, as the protocol converts
// them to regular chat messages.
if(!Components.equals(message, recentHotbarMessage)) {
emphasize(message);
recentHotbarMessage = message;
}
}
@Override
public void showTitle(BaseComponent title, BaseComponent subtitle, int inTicks, int stayTicks, int outTicks) {
emphasize(Components.join(Components.space(), Stream.of(title, subtitle).filter(msg -> msg != null).collect(Collectors.toImmutableList())));
}
protected void emphasize(BaseComponent message) {
sendMessage(Components.blank());
sendMessage(message);
sendMessage(Components.blank());
}
}
|
Make titles and hotbars more visible
|
Make titles and hotbars more visible
|
Java
|
agpl-3.0
|
StratusNetwork/ProjectAres,PotatoStealer/ProjectAres
|
java
|
## Code Before:
package tc.oc.commons.bukkit.chat;
import net.md_5.bungee.api.chat.BaseComponent;
import org.bukkit.entity.Player;
import tc.oc.commons.core.chat.Component;
import tc.oc.commons.core.chat.Components;
public class LegacyPlayerAudience extends PlayerAudience {
private BaseComponent recentHotbarMessage;
public LegacyPlayerAudience(Player player) {
super(player);
}
@Override
public void sendHotbarMessage(BaseComponent message) {
// Do not spam hot bar messages, as the protocol converts
// them to regular chat messages.
if(!Components.equals(message, recentHotbarMessage)) {
super.sendHotbarMessage(message);
recentHotbarMessage = message;
}
}
@Override
public void showTitle(BaseComponent title, BaseComponent subtitle, int inTicks, int stayTicks, int outTicks) {
super.sendMessage(new Component(title).extra(" ").extra(subtitle));
}
}
## Instruction:
Make titles and hotbars more visible
## Code After:
package tc.oc.commons.bukkit.chat;
import net.md_5.bungee.api.chat.BaseComponent;
import org.bukkit.entity.Player;
import tc.oc.commons.core.chat.Components;
import tc.oc.commons.core.stream.Collectors;
import java.util.stream.Stream;
public class LegacyPlayerAudience extends PlayerAudience {
private BaseComponent recentHotbarMessage;
public LegacyPlayerAudience(Player player) {
super(player);
}
@Override
public void sendHotbarMessage(BaseComponent message) {
// Do not spam hot bar messages, as the protocol converts
// them to regular chat messages.
if(!Components.equals(message, recentHotbarMessage)) {
emphasize(message);
recentHotbarMessage = message;
}
}
@Override
public void showTitle(BaseComponent title, BaseComponent subtitle, int inTicks, int stayTicks, int outTicks) {
emphasize(Components.join(Components.space(), Stream.of(title, subtitle).filter(msg -> msg != null).collect(Collectors.toImmutableList())));
}
protected void emphasize(BaseComponent message) {
sendMessage(Components.blank());
sendMessage(message);
sendMessage(Components.blank());
}
}
|
...
import net.md_5.bungee.api.chat.BaseComponent;
import org.bukkit.entity.Player;
import tc.oc.commons.core.chat.Components;
import tc.oc.commons.core.stream.Collectors;
import java.util.stream.Stream;
public class LegacyPlayerAudience extends PlayerAudience {
...
// Do not spam hot bar messages, as the protocol converts
// them to regular chat messages.
if(!Components.equals(message, recentHotbarMessage)) {
emphasize(message);
recentHotbarMessage = message;
}
}
...
@Override
public void showTitle(BaseComponent title, BaseComponent subtitle, int inTicks, int stayTicks, int outTicks) {
emphasize(Components.join(Components.space(), Stream.of(title, subtitle).filter(msg -> msg != null).collect(Collectors.toImmutableList())));
}
protected void emphasize(BaseComponent message) {
sendMessage(Components.blank());
sendMessage(message);
sendMessage(Components.blank());
}
}
...
|
3ee933042e0c02a5a23e69d48e81d3fb5a9fa05b
|
setup.py
|
setup.py
|
import os
import setuptools
requirements = [
"numpy",
"scipy",
"lasagne",
]
def readme():
base_dir = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(base_dir, 'README.md')) as f:
return f.read()
def setup():
setuptools.setup(
name="nn_patterns",
version="0.1",
description=("Implementation of PatternNet and PatternLRP:"
" https://arxiv.org/abs/1705.05598"),
long_description=readme(),
classifiers=[
"License :: OSI Approved :: ",
"Development Status :: 3 - Alpha",
"Environment :: Console",
"Intended Audience :: Science/Research",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
],
url="https://github.com/pikinder/nn-patterns",
author="Pieter-Jan Kindermans, Maxmilian Alber",
author_email="[email protected]",
license="MIT",
packages=setuptools.find_packages(),
install_requires=requirements,
include_package_data=True,
zip_safe=False,
)
pass
if __name__ == "__main__":
setup()
|
import os
import setuptools
requirements = [
"fnmatch",
"future",
"six",
"numpy",
"scipy",
"lasagne",
"theano",
]
def readme():
base_dir = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(base_dir, 'README.md')) as f:
return f.read()
def setup():
setuptools.setup(
name="nn_patterns",
version="0.1",
description=("Implementation of PatternNet and PatternLRP:"
" https://arxiv.org/abs/1705.05598"),
long_description=readme(),
classifiers=[
"License :: OSI Approved :: ",
"Development Status :: 3 - Alpha",
"Environment :: Console",
"Intended Audience :: Science/Research",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
],
url="https://github.com/pikinder/nn-patterns",
author="Pieter-Jan Kindermans, Maxmilian Alber",
author_email="[email protected]",
license="MIT",
packages=setuptools.find_packages(),
install_requires=requirements,
include_package_data=True,
zip_safe=False,
)
pass
if __name__ == "__main__":
setup()
|
Add requirements to package definition.
|
Add requirements to package definition.
|
Python
|
mit
|
pikinder/nn-patterns
|
python
|
## Code Before:
import os
import setuptools
requirements = [
"numpy",
"scipy",
"lasagne",
]
def readme():
base_dir = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(base_dir, 'README.md')) as f:
return f.read()
def setup():
setuptools.setup(
name="nn_patterns",
version="0.1",
description=("Implementation of PatternNet and PatternLRP:"
" https://arxiv.org/abs/1705.05598"),
long_description=readme(),
classifiers=[
"License :: OSI Approved :: ",
"Development Status :: 3 - Alpha",
"Environment :: Console",
"Intended Audience :: Science/Research",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
],
url="https://github.com/pikinder/nn-patterns",
author="Pieter-Jan Kindermans, Maxmilian Alber",
author_email="[email protected]",
license="MIT",
packages=setuptools.find_packages(),
install_requires=requirements,
include_package_data=True,
zip_safe=False,
)
pass
if __name__ == "__main__":
setup()
## Instruction:
Add requirements to package definition.
## Code After:
import os
import setuptools
requirements = [
"fnmatch",
"future",
"six",
"numpy",
"scipy",
"lasagne",
"theano",
]
def readme():
base_dir = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(base_dir, 'README.md')) as f:
return f.read()
def setup():
setuptools.setup(
name="nn_patterns",
version="0.1",
description=("Implementation of PatternNet and PatternLRP:"
" https://arxiv.org/abs/1705.05598"),
long_description=readme(),
classifiers=[
"License :: OSI Approved :: ",
"Development Status :: 3 - Alpha",
"Environment :: Console",
"Intended Audience :: Science/Research",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
],
url="https://github.com/pikinder/nn-patterns",
author="Pieter-Jan Kindermans, Maxmilian Alber",
author_email="[email protected]",
license="MIT",
packages=setuptools.find_packages(),
install_requires=requirements,
include_package_data=True,
zip_safe=False,
)
pass
if __name__ == "__main__":
setup()
|
# ... existing code ...
requirements = [
"fnmatch",
"future",
"six",
"numpy",
"scipy",
"lasagne",
"theano",
]
# ... rest of the code ...
|
6711d7c798bb2aa0cc6305c157d8f8931cfb9eb8
|
src/main/java/org/gbif/portal/struts/freemarker/GbifFreemarkerManager.java
|
src/main/java/org/gbif/portal/struts/freemarker/GbifFreemarkerManager.java
|
package org.gbif.portal.struts.freemarker;
import javax.servlet.ServletContext;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.apache.struts2.views.freemarker.FreemarkerManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GbifFreemarkerManager extends FreemarkerManager {
private static final Logger LOG = LoggerFactory.getLogger(GbifFreemarkerManager.class);
@Override
public void init(ServletContext servletContext) throws TemplateException {
super.init(servletContext);
LOG.info("Init custom GBIF Freemarker Manager");
// custom ftl exception handling
config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
// adding date rendering methods
config.setSharedVariable("niceDate", new NiceDateTemplateMethodModel());
}
}
|
package org.gbif.portal.struts.freemarker;
import java.util.Locale;
import javax.servlet.ServletContext;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.apache.struts2.views.freemarker.FreemarkerManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GbifFreemarkerManager extends FreemarkerManager {
private static final Logger LOG = LoggerFactory.getLogger(GbifFreemarkerManager.class);
@Override
public void init(ServletContext servletContext) throws TemplateException {
super.init(servletContext);
LOG.info("Init custom GBIF Freemarker Manager");
// custom ftl exception handling
config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
// adding date rendering methods
config.setSharedVariable("niceDate", new NiceDateTemplateMethodModel());
// fixed locale, so we don't get dots as decimal separators or US "middle endian" dates.
// chose UK, as (from the constants available) that gives unambiguous short dates like "12-Jan-2016".
config.setLocale(Locale.UK);
}
}
|
Fix FreeMarker locale, so we don't get . as a thousands separator.
|
Fix FreeMarker locale, so we don't get . as a thousands separator.
|
Java
|
apache-2.0
|
gbif/portal-web,gbif/portal-web,gbif/portal-web
|
java
|
## Code Before:
package org.gbif.portal.struts.freemarker;
import javax.servlet.ServletContext;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.apache.struts2.views.freemarker.FreemarkerManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GbifFreemarkerManager extends FreemarkerManager {
private static final Logger LOG = LoggerFactory.getLogger(GbifFreemarkerManager.class);
@Override
public void init(ServletContext servletContext) throws TemplateException {
super.init(servletContext);
LOG.info("Init custom GBIF Freemarker Manager");
// custom ftl exception handling
config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
// adding date rendering methods
config.setSharedVariable("niceDate", new NiceDateTemplateMethodModel());
}
}
## Instruction:
Fix FreeMarker locale, so we don't get . as a thousands separator.
## Code After:
package org.gbif.portal.struts.freemarker;
import java.util.Locale;
import javax.servlet.ServletContext;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.apache.struts2.views.freemarker.FreemarkerManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GbifFreemarkerManager extends FreemarkerManager {
private static final Logger LOG = LoggerFactory.getLogger(GbifFreemarkerManager.class);
@Override
public void init(ServletContext servletContext) throws TemplateException {
super.init(servletContext);
LOG.info("Init custom GBIF Freemarker Manager");
// custom ftl exception handling
config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
// adding date rendering methods
config.setSharedVariable("niceDate", new NiceDateTemplateMethodModel());
// fixed locale, so we don't get dots as decimal separators or US "middle endian" dates.
// chose UK, as (from the constants available) that gives unambiguous short dates like "12-Jan-2016".
config.setLocale(Locale.UK);
}
}
|
// ... existing code ...
package org.gbif.portal.struts.freemarker;
import java.util.Locale;
import javax.servlet.ServletContext;
import freemarker.template.TemplateException;
// ... modified code ...
config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
// adding date rendering methods
config.setSharedVariable("niceDate", new NiceDateTemplateMethodModel());
// fixed locale, so we don't get dots as decimal separators or US "middle endian" dates.
// chose UK, as (from the constants available) that gives unambiguous short dates like "12-Jan-2016".
config.setLocale(Locale.UK);
}
}
// ... rest of the code ...
|
4581f05e937800b0541c219fd82390fdfef7644f
|
opal/tests/test_updates_from_dict.py
|
opal/tests/test_updates_from_dict.py
|
from django.test import TestCase
from django.db import models as djangomodels
from opal.models import UpdatesFromDictMixin
class UpdatesFromDictMixinTest(TestCase):
class TestDiagnosis(UpdatesFromDictMixin, djangomodels.Model):
condition = djangomodels.CharField(max_length=255, blank=True, null=True)
provisional = djangomodels.BooleanField()
details = djangomodels.CharField(max_length=255, blank=True)
date_of_diagnosis = djangomodels.DateField(blank=True, null=True)
def test_get_fieldnames_to_serialise(self):
names = self.TestDiagnosis._get_fieldnames_to_serialize()
expected = ['id', 'condition', 'provisional', 'details', 'date_of_diagnosis']
self.assertEqual(expected, names)
|
from django.test import TestCase
from django.db import models as djangomodels
from opal.models import UpdatesFromDictMixin
class UpdatesFromDictMixinTest(TestCase):
class TestDiagnosis(UpdatesFromDictMixin, djangomodels.Model):
condition = djangomodels.CharField(max_length=255, blank=True, null=True)
provisional = djangomodels.BooleanField()
details = djangomodels.CharField(max_length=255, blank=True)
date_of_diagnosis = djangomodels.DateField(blank=True, null=True)
def test_get_fieldnames_to_serialise(self):
names = self.TestDiagnosis._get_fieldnames_to_serialize()
expected = ['id', 'condition', 'provisional', 'details', 'date_of_diagnosis']
self.assertEqual(expected, names)
def test_get_named_foreign_key_fields(self):
for name in ['patient_id', 'episode_id', 'gp_id', 'nurse_id']:
self.assertEqual(djangomodels.ForeignKey,
self.TestDiagnosis._get_field_type(name))
|
Add a specific test for the updatesfromdict hard coded foreignkey fields
|
Add a specific test for the updatesfromdict hard coded foreignkey fields
|
Python
|
agpl-3.0
|
khchine5/opal,khchine5/opal,khchine5/opal
|
python
|
## Code Before:
from django.test import TestCase
from django.db import models as djangomodels
from opal.models import UpdatesFromDictMixin
class UpdatesFromDictMixinTest(TestCase):
class TestDiagnosis(UpdatesFromDictMixin, djangomodels.Model):
condition = djangomodels.CharField(max_length=255, blank=True, null=True)
provisional = djangomodels.BooleanField()
details = djangomodels.CharField(max_length=255, blank=True)
date_of_diagnosis = djangomodels.DateField(blank=True, null=True)
def test_get_fieldnames_to_serialise(self):
names = self.TestDiagnosis._get_fieldnames_to_serialize()
expected = ['id', 'condition', 'provisional', 'details', 'date_of_diagnosis']
self.assertEqual(expected, names)
## Instruction:
Add a specific test for the updatesfromdict hard coded foreignkey fields
## Code After:
from django.test import TestCase
from django.db import models as djangomodels
from opal.models import UpdatesFromDictMixin
class UpdatesFromDictMixinTest(TestCase):
class TestDiagnosis(UpdatesFromDictMixin, djangomodels.Model):
condition = djangomodels.CharField(max_length=255, blank=True, null=True)
provisional = djangomodels.BooleanField()
details = djangomodels.CharField(max_length=255, blank=True)
date_of_diagnosis = djangomodels.DateField(blank=True, null=True)
def test_get_fieldnames_to_serialise(self):
names = self.TestDiagnosis._get_fieldnames_to_serialize()
expected = ['id', 'condition', 'provisional', 'details', 'date_of_diagnosis']
self.assertEqual(expected, names)
def test_get_named_foreign_key_fields(self):
for name in ['patient_id', 'episode_id', 'gp_id', 'nurse_id']:
self.assertEqual(djangomodels.ForeignKey,
self.TestDiagnosis._get_field_type(name))
|
...
expected = ['id', 'condition', 'provisional', 'details', 'date_of_diagnosis']
self.assertEqual(expected, names)
def test_get_named_foreign_key_fields(self):
for name in ['patient_id', 'episode_id', 'gp_id', 'nurse_id']:
self.assertEqual(djangomodels.ForeignKey,
self.TestDiagnosis._get_field_type(name))
...
|
e62e090f2282426d14dad52a06eeca788789846f
|
kpi/serializers/v2/user_asset_subscription.py
|
kpi/serializers/v2/user_asset_subscription.py
|
from django.utils.translation import ugettext as _
from rest_framework import serializers
from kpi.constants import (
ASSET_TYPE_COLLECTION,
PERM_DISCOVER_ASSET,
PERM_VIEW_ASSET
)
from kpi.fields import RelativePrefixHyperlinkedRelatedField
from kpi.models import Asset
from kpi.models import UserAssetSubscription
from kpi.models.object_permission import get_anonymous_user, get_objects_for_user
class UserAssetSubscriptionSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(
lookup_field='uid',
view_name='userassetsubscription-detail'
)
asset = RelativePrefixHyperlinkedRelatedField(
lookup_field='uid',
view_name='asset-detail',
queryset=Asset.objects.none() # will be set in __init__()
)
uid = serializers.ReadOnlyField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['asset'].queryset = get_objects_for_user(
get_anonymous_user(),
[PERM_VIEW_ASSET, PERM_DISCOVER_ASSET],
Asset
)
class Meta:
model = UserAssetSubscription
lookup_field = 'uid'
fields = ('url', 'asset', 'uid')
def validate_asset(self, asset):
if asset.asset_type != ASSET_TYPE_COLLECTION:
raise serializers.ValidationError(
_('Invalid asset type. Only `{asset_type}`').format(
asset_type=ASSET_TYPE_COLLECTION
)
)
return asset
|
from django.utils.translation import ugettext as _
from rest_framework import serializers
from kpi.constants import (
ASSET_TYPE_COLLECTION,
PERM_DISCOVER_ASSET,
PERM_VIEW_ASSET
)
from kpi.fields import RelativePrefixHyperlinkedRelatedField
from kpi.models import Asset
from kpi.models import UserAssetSubscription
from kpi.models.object_permission import get_anonymous_user, get_objects_for_user
class UserAssetSubscriptionSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(
lookup_field='uid',
view_name='userassetsubscription-detail'
)
asset = RelativePrefixHyperlinkedRelatedField(
lookup_field='uid',
view_name='asset-detail',
queryset=Asset.objects.none() # will be set in __init__()
)
uid = serializers.ReadOnlyField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['asset'].queryset = get_objects_for_user(
get_anonymous_user(),
[PERM_VIEW_ASSET, PERM_DISCOVER_ASSET],
Asset
)
class Meta:
model = UserAssetSubscription
lookup_field = 'uid'
fields = ('url', 'asset', 'uid')
def validate_asset(self, asset):
if asset.asset_type != ASSET_TYPE_COLLECTION:
raise serializers.ValidationError(
_('Invalid asset type. Only `{asset_type}` is allowed').format(
asset_type=ASSET_TYPE_COLLECTION
)
)
return asset
|
Improve (a tiny bit) validation error message
|
Improve (a tiny bit) validation error message
|
Python
|
agpl-3.0
|
kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi
|
python
|
## Code Before:
from django.utils.translation import ugettext as _
from rest_framework import serializers
from kpi.constants import (
ASSET_TYPE_COLLECTION,
PERM_DISCOVER_ASSET,
PERM_VIEW_ASSET
)
from kpi.fields import RelativePrefixHyperlinkedRelatedField
from kpi.models import Asset
from kpi.models import UserAssetSubscription
from kpi.models.object_permission import get_anonymous_user, get_objects_for_user
class UserAssetSubscriptionSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(
lookup_field='uid',
view_name='userassetsubscription-detail'
)
asset = RelativePrefixHyperlinkedRelatedField(
lookup_field='uid',
view_name='asset-detail',
queryset=Asset.objects.none() # will be set in __init__()
)
uid = serializers.ReadOnlyField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['asset'].queryset = get_objects_for_user(
get_anonymous_user(),
[PERM_VIEW_ASSET, PERM_DISCOVER_ASSET],
Asset
)
class Meta:
model = UserAssetSubscription
lookup_field = 'uid'
fields = ('url', 'asset', 'uid')
def validate_asset(self, asset):
if asset.asset_type != ASSET_TYPE_COLLECTION:
raise serializers.ValidationError(
_('Invalid asset type. Only `{asset_type}`').format(
asset_type=ASSET_TYPE_COLLECTION
)
)
return asset
## Instruction:
Improve (a tiny bit) validation error message
## Code After:
from django.utils.translation import ugettext as _
from rest_framework import serializers
from kpi.constants import (
ASSET_TYPE_COLLECTION,
PERM_DISCOVER_ASSET,
PERM_VIEW_ASSET
)
from kpi.fields import RelativePrefixHyperlinkedRelatedField
from kpi.models import Asset
from kpi.models import UserAssetSubscription
from kpi.models.object_permission import get_anonymous_user, get_objects_for_user
class UserAssetSubscriptionSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(
lookup_field='uid',
view_name='userassetsubscription-detail'
)
asset = RelativePrefixHyperlinkedRelatedField(
lookup_field='uid',
view_name='asset-detail',
queryset=Asset.objects.none() # will be set in __init__()
)
uid = serializers.ReadOnlyField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['asset'].queryset = get_objects_for_user(
get_anonymous_user(),
[PERM_VIEW_ASSET, PERM_DISCOVER_ASSET],
Asset
)
class Meta:
model = UserAssetSubscription
lookup_field = 'uid'
fields = ('url', 'asset', 'uid')
def validate_asset(self, asset):
if asset.asset_type != ASSET_TYPE_COLLECTION:
raise serializers.ValidationError(
_('Invalid asset type. Only `{asset_type}` is allowed').format(
asset_type=ASSET_TYPE_COLLECTION
)
)
return asset
|
# ... existing code ...
def validate_asset(self, asset):
if asset.asset_type != ASSET_TYPE_COLLECTION:
raise serializers.ValidationError(
_('Invalid asset type. Only `{asset_type}` is allowed').format(
asset_type=ASSET_TYPE_COLLECTION
)
)
# ... rest of the code ...
|
75606e2b13a29a5d68894eda86dbede8292fb0c8
|
website/project/taxonomies/__init__.py
|
website/project/taxonomies/__init__.py
|
from modularodm import fields
from framework.mongo import (
ObjectId,
StoredObject,
utils as mongo_utils
)
from website.util import api_v2_url
@mongo_utils.unique_on(['text'])
class Subject(StoredObject):
_id = fields.StringField(primary=True, default=lambda: str(ObjectId()))
text = fields.StringField(required=True)
parents = fields.ForeignField('subject', list=True)
@property
def absolute_api_v2_url(self):
return api_v2_url('taxonomies/{}/'.format(self._id))
def get_absolute_url(self):
return self.absolute_api_v2_url
|
import pymongo
from modularodm import fields
from framework.mongo import (
ObjectId,
StoredObject,
utils as mongo_utils
)
from website.util import api_v2_url
@mongo_utils.unique_on(['text'])
class Subject(StoredObject):
__indices__ = [
{
'unique': True,
'key_or_list': [
('text', pymongo.DESCENDING),
]
}
]
_id = fields.StringField(primary=True, default=lambda: str(ObjectId()))
text = fields.StringField(required=True)
parents = fields.ForeignField('subject', list=True)
@property
def absolute_api_v2_url(self):
return api_v2_url('taxonomies/{}/'.format(self._id))
def get_absolute_url(self):
return self.absolute_api_v2_url
|
Add unique index on the subject model for @chrisseto
|
Add unique index on the subject model for @chrisseto
|
Python
|
apache-2.0
|
hmoco/osf.io,alexschiller/osf.io,CenterForOpenScience/osf.io,Johnetordoff/osf.io,HalcyonChimera/osf.io,baylee-d/osf.io,aaxelb/osf.io,samchrisinger/osf.io,HalcyonChimera/osf.io,CenterForOpenScience/osf.io,cslzchen/osf.io,cwisecarver/osf.io,Johnetordoff/osf.io,crcresearch/osf.io,chrisseto/osf.io,alexschiller/osf.io,aaxelb/osf.io,emetsger/osf.io,Johnetordoff/osf.io,erinspace/osf.io,erinspace/osf.io,sloria/osf.io,mfraezz/osf.io,mfraezz/osf.io,rdhyee/osf.io,brianjgeiger/osf.io,saradbowman/osf.io,mluo613/osf.io,TomBaxter/osf.io,baylee-d/osf.io,samchrisinger/osf.io,mluo613/osf.io,icereval/osf.io,chrisseto/osf.io,caseyrollins/osf.io,sloria/osf.io,laurenrevere/osf.io,cwisecarver/osf.io,binoculars/osf.io,adlius/osf.io,caseyrollins/osf.io,samchrisinger/osf.io,saradbowman/osf.io,monikagrabowska/osf.io,mattclark/osf.io,mluo613/osf.io,binoculars/osf.io,alexschiller/osf.io,alexschiller/osf.io,TomBaxter/osf.io,sloria/osf.io,monikagrabowska/osf.io,aaxelb/osf.io,laurenrevere/osf.io,chrisseto/osf.io,chrisseto/osf.io,emetsger/osf.io,acshi/osf.io,adlius/osf.io,brianjgeiger/osf.io,icereval/osf.io,binoculars/osf.io,CenterForOpenScience/osf.io,cwisecarver/osf.io,leb2dg/osf.io,felliott/osf.io,felliott/osf.io,aaxelb/osf.io,HalcyonChimera/osf.io,caseyrollins/osf.io,chennan47/osf.io,caneruguz/osf.io,monikagrabowska/osf.io,mattclark/osf.io,caneruguz/osf.io,erinspace/osf.io,pattisdr/osf.io,cslzchen/osf.io,icereval/osf.io,acshi/osf.io,mluo613/osf.io,cslzchen/osf.io,mfraezz/osf.io,felliott/osf.io,emetsger/osf.io,hmoco/osf.io,HalcyonChimera/osf.io,Nesiehr/osf.io,laurenrevere/osf.io,crcresearch/osf.io,cslzchen/osf.io,hmoco/osf.io,Nesiehr/osf.io,rdhyee/osf.io,acshi/osf.io,acshi/osf.io,Johnetordoff/osf.io,TomBaxter/osf.io,mluo613/osf.io,crcresearch/osf.io,Nesiehr/osf.io,emetsger/osf.io,leb2dg/osf.io,samchrisinger/osf.io,acshi/osf.io,Nesiehr/osf.io,adlius/osf.io,brianjgeiger/osf.io,leb2dg/osf.io,rdhyee/osf.io,felliott/osf.io,brianjgeiger/osf.io,alexschiller/osf.io,caneruguz/osf.io,pattisdr/osf.io,adlius/osf.io,chennan47/osf.io,mfraezz/osf.io,baylee-d/osf.io,caneruguz/osf.io,chennan47/osf.io,monikagrabowska/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,rdhyee/osf.io,hmoco/osf.io,cwisecarver/osf.io,CenterForOpenScience/osf.io,pattisdr/osf.io,mattclark/osf.io
|
python
|
## Code Before:
from modularodm import fields
from framework.mongo import (
ObjectId,
StoredObject,
utils as mongo_utils
)
from website.util import api_v2_url
@mongo_utils.unique_on(['text'])
class Subject(StoredObject):
_id = fields.StringField(primary=True, default=lambda: str(ObjectId()))
text = fields.StringField(required=True)
parents = fields.ForeignField('subject', list=True)
@property
def absolute_api_v2_url(self):
return api_v2_url('taxonomies/{}/'.format(self._id))
def get_absolute_url(self):
return self.absolute_api_v2_url
## Instruction:
Add unique index on the subject model for @chrisseto
## Code After:
import pymongo
from modularodm import fields
from framework.mongo import (
ObjectId,
StoredObject,
utils as mongo_utils
)
from website.util import api_v2_url
@mongo_utils.unique_on(['text'])
class Subject(StoredObject):
__indices__ = [
{
'unique': True,
'key_or_list': [
('text', pymongo.DESCENDING),
]
}
]
_id = fields.StringField(primary=True, default=lambda: str(ObjectId()))
text = fields.StringField(required=True)
parents = fields.ForeignField('subject', list=True)
@property
def absolute_api_v2_url(self):
return api_v2_url('taxonomies/{}/'.format(self._id))
def get_absolute_url(self):
return self.absolute_api_v2_url
|
...
import pymongo
from modularodm import fields
from framework.mongo import (
...
@mongo_utils.unique_on(['text'])
class Subject(StoredObject):
__indices__ = [
{
'unique': True,
'key_or_list': [
('text', pymongo.DESCENDING),
]
}
]
_id = fields.StringField(primary=True, default=lambda: str(ObjectId()))
text = fields.StringField(required=True)
parents = fields.ForeignField('subject', list=True)
...
|
b545ebcd2b604bf293bfbbb1af5a9ab2ba6965c7
|
wayback3/wayback3.py
|
wayback3/wayback3.py
|
import datetime
import requests
FORMAT_STRING = "%Y%m%d%H%M%S" # Looks like "20130919044612"
AVAILABILITY_URL = "http://archive.org/wayback/available?url=%s"
def availability(url):
response = requests.get(AVAILABILITY_URL % (url))
print(response)
print(response.text)
response_j = response.json()
if response_j.get('archived_snapshots') == {}:
return None
else:
closest = response_j.get('archived_snapshots').get('closest')
avail = closest.get('available')
status = int(closest.get('status'))
timestamp = closest.get('timestamp')
timestamp = datetime.datetime.strptime(timestamp, FORMAT_STRING)
url = closest.get('url')
return {'verbatim': closest, 'url': url, 'timestamp': timestamp}
|
import datetime
import requests
FORMAT_STRING = "%Y%m%d%H%M%S" # Looks like "20130919044612"
AVAILABILITY_URL = "http://archive.org/wayback/available?url=%s"
WAYBACK_URL_ROOT = "http://web.archive.org"
def availability(url):
response = requests.get(AVAILABILITY_URL % (url))
print(response)
print(response.text)
response_j = response.json()
if response_j.get('archived_snapshots') == {}:
return None
else:
closest = response_j.get('archived_snapshots').get('closest')
avail = closest.get('available')
status = int(closest.get('status'))
timestamp = closest.get('timestamp')
timestamp = datetime.datetime.strptime(timestamp, FORMAT_STRING)
url = closest.get('url')
return {'verbatim': closest, 'url': url, 'timestamp': timestamp}
|
Add a constant for WB root URL
|
Add a constant for WB root URL
|
Python
|
agpl-3.0
|
OpenSSR/openssr-parser,OpenSSR/openssr-parser
|
python
|
## Code Before:
import datetime
import requests
FORMAT_STRING = "%Y%m%d%H%M%S" # Looks like "20130919044612"
AVAILABILITY_URL = "http://archive.org/wayback/available?url=%s"
def availability(url):
response = requests.get(AVAILABILITY_URL % (url))
print(response)
print(response.text)
response_j = response.json()
if response_j.get('archived_snapshots') == {}:
return None
else:
closest = response_j.get('archived_snapshots').get('closest')
avail = closest.get('available')
status = int(closest.get('status'))
timestamp = closest.get('timestamp')
timestamp = datetime.datetime.strptime(timestamp, FORMAT_STRING)
url = closest.get('url')
return {'verbatim': closest, 'url': url, 'timestamp': timestamp}
## Instruction:
Add a constant for WB root URL
## Code After:
import datetime
import requests
FORMAT_STRING = "%Y%m%d%H%M%S" # Looks like "20130919044612"
AVAILABILITY_URL = "http://archive.org/wayback/available?url=%s"
WAYBACK_URL_ROOT = "http://web.archive.org"
def availability(url):
response = requests.get(AVAILABILITY_URL % (url))
print(response)
print(response.text)
response_j = response.json()
if response_j.get('archived_snapshots') == {}:
return None
else:
closest = response_j.get('archived_snapshots').get('closest')
avail = closest.get('available')
status = int(closest.get('status'))
timestamp = closest.get('timestamp')
timestamp = datetime.datetime.strptime(timestamp, FORMAT_STRING)
url = closest.get('url')
return {'verbatim': closest, 'url': url, 'timestamp': timestamp}
|
// ... existing code ...
FORMAT_STRING = "%Y%m%d%H%M%S" # Looks like "20130919044612"
AVAILABILITY_URL = "http://archive.org/wayback/available?url=%s"
WAYBACK_URL_ROOT = "http://web.archive.org"
def availability(url):
// ... rest of the code ...
|
8ae27080b8ff9fe124733005a8006261a3d22266
|
migrate/crud/versions/001_create_initial_tables.py
|
migrate/crud/versions/001_create_initial_tables.py
|
from sqlalchemy import *
from migrate import *
metadata = MetaData()
table = Table('crud_versions', metadata,
Column('id', Integer, primary_key=True),
Column('object_type', Text, nullable=False),
Column('object_id', Integer, nullable=False),
Column('commit_time', DateTime, nullable=False),
Column('data', Blob, nullable=False),
Column('blame', Text, nullable=False),
Column('comment', Text, nullable=False),
)
def upgrade(migrate_engine):
# Upgrade operations go here. Don't create your own engine; bind migrate_engine
# to your metadata
metadata.bind = migrate_engine
table.create()
def downgrade(migrate_engine):
# Operations to reverse the above upgrade go here.
table.drop()
|
from sqlalchemy import *
from migrate import *
metadata = MetaData()
table = Table('crud_versions', metadata,
Column('id', Integer, primary_key=True),
Column('object_type', Text, nullable=False),
Column('object_id', Integer, nullable=False),
Column('commit_time', DateTime, nullable=False),
Column('data', LargeBinary, nullable=False),
Column('blame', Text, nullable=False),
Column('comment', Text, nullable=False),
)
def upgrade(migrate_engine):
# Upgrade operations go here. Don't create your own engine; bind migrate_engine
# to your metadata
metadata.bind = migrate_engine
table.create()
def downgrade(migrate_engine):
# Operations to reverse the above upgrade go here.
table.drop()
|
Fix some of the schema.
|
Fix some of the schema.
|
Python
|
bsd-3-clause
|
mikeboers/Nitrogen,mikeboers/Nitrogen,mikeboers/Nitrogen,mikeboers/Nitrogen,mikeboers/Nitrogen,mikeboers/Nitrogen
|
python
|
## Code Before:
from sqlalchemy import *
from migrate import *
metadata = MetaData()
table = Table('crud_versions', metadata,
Column('id', Integer, primary_key=True),
Column('object_type', Text, nullable=False),
Column('object_id', Integer, nullable=False),
Column('commit_time', DateTime, nullable=False),
Column('data', Blob, nullable=False),
Column('blame', Text, nullable=False),
Column('comment', Text, nullable=False),
)
def upgrade(migrate_engine):
# Upgrade operations go here. Don't create your own engine; bind migrate_engine
# to your metadata
metadata.bind = migrate_engine
table.create()
def downgrade(migrate_engine):
# Operations to reverse the above upgrade go here.
table.drop()
## Instruction:
Fix some of the schema.
## Code After:
from sqlalchemy import *
from migrate import *
metadata = MetaData()
table = Table('crud_versions', metadata,
Column('id', Integer, primary_key=True),
Column('object_type', Text, nullable=False),
Column('object_id', Integer, nullable=False),
Column('commit_time', DateTime, nullable=False),
Column('data', LargeBinary, nullable=False),
Column('blame', Text, nullable=False),
Column('comment', Text, nullable=False),
)
def upgrade(migrate_engine):
# Upgrade operations go here. Don't create your own engine; bind migrate_engine
# to your metadata
metadata.bind = migrate_engine
table.create()
def downgrade(migrate_engine):
# Operations to reverse the above upgrade go here.
table.drop()
|
...
Column('object_type', Text, nullable=False),
Column('object_id', Integer, nullable=False),
Column('commit_time', DateTime, nullable=False),
Column('data', LargeBinary, nullable=False),
Column('blame', Text, nullable=False),
Column('comment', Text, nullable=False),
)
...
|
ed64d0611ccf047c1da8ae85d13c89c77dfe1930
|
packages/grid/backend/grid/tests/utils/auth.py
|
packages/grid/backend/grid/tests/utils/auth.py
|
from typing import Dict
# third party
from fastapi import FastAPI
from httpx import AsyncClient
async def authenticate_user(
app: FastAPI, client: AsyncClient, email: str, password: str
) -> Dict[str, str]:
user_login = {"email": email, "password": password}
res = await client.post(app.url_path_for("login"), json=user_login)
res = res.json()
auth_token = res["access_token"]
return {"Authorization": f"Bearer {auth_token}"}
async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]:
return await authenticate_user(
app, client, email="[email protected]", password="changethis"
)
|
from typing import Dict
# third party
from fastapi import FastAPI
from httpx import AsyncClient
OWNER_EMAIL = "[email protected]"
OWNER_PWD = "changethis"
async def authenticate_user(
app: FastAPI, client: AsyncClient, email: str, password: str
) -> Dict[str, str]:
user_login = {"email": email, "password": password}
res = await client.post(app.url_path_for("login"), json=user_login)
res = res.json()
auth_token = res["access_token"]
return {"Authorization": f"Bearer {auth_token}"}
async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]:
return await authenticate_user(
app,
client,
email=OWNER_EMAIL,
password=OWNER_PWD,
)
|
ADD constant test variables OWNER_EMAIL / OWNER_PWD
|
ADD constant test variables OWNER_EMAIL / OWNER_PWD
|
Python
|
apache-2.0
|
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
|
python
|
## Code Before:
from typing import Dict
# third party
from fastapi import FastAPI
from httpx import AsyncClient
async def authenticate_user(
app: FastAPI, client: AsyncClient, email: str, password: str
) -> Dict[str, str]:
user_login = {"email": email, "password": password}
res = await client.post(app.url_path_for("login"), json=user_login)
res = res.json()
auth_token = res["access_token"]
return {"Authorization": f"Bearer {auth_token}"}
async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]:
return await authenticate_user(
app, client, email="[email protected]", password="changethis"
)
## Instruction:
ADD constant test variables OWNER_EMAIL / OWNER_PWD
## Code After:
from typing import Dict
# third party
from fastapi import FastAPI
from httpx import AsyncClient
OWNER_EMAIL = "[email protected]"
OWNER_PWD = "changethis"
async def authenticate_user(
app: FastAPI, client: AsyncClient, email: str, password: str
) -> Dict[str, str]:
user_login = {"email": email, "password": password}
res = await client.post(app.url_path_for("login"), json=user_login)
res = res.json()
auth_token = res["access_token"]
return {"Authorization": f"Bearer {auth_token}"}
async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]:
return await authenticate_user(
app,
client,
email=OWNER_EMAIL,
password=OWNER_PWD,
)
|
// ... existing code ...
# third party
from fastapi import FastAPI
from httpx import AsyncClient
OWNER_EMAIL = "[email protected]"
OWNER_PWD = "changethis"
async def authenticate_user(
// ... modified code ...
async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]:
return await authenticate_user(
app,
client,
email=OWNER_EMAIL,
password=OWNER_PWD,
)
// ... rest of the code ...
|
df3583ba3a7a1bade8b411d885a0df1609dd8465
|
setup.py
|
setup.py
|
import os
from distutils.core import setup
path = os.path.dirname(__file__)
setup(
name='forecast',
version='0.1dev',
author="Osvaldo Santana Neto",
author_email="[email protected]",
packages=[
'forecast',
'forecast.applications',
'forecast.applications.core',
'forecast.applications.core.commands',
'forecast.skels',
'forecast.skels.application',
'forecast.skels.project',
'forecast.skels.project.settings',
'forecast.tests',
'forecast.tests.settings',
'forecast.tests.test_app',
'forecast.tests.test_app.commands',
],
scripts=[os.path.join(path, 'bin', 'forecast-admin.py')],
url="http://github.com/osantana/forecast",
license='MIT',
description="A small wrapper around Tornado Web Server to force project structure",
long_description=open(os.path.join(path, 'README.txt')).read(),
)
|
import os
from distutils.core import setup
path = os.path.dirname(__file__)
setup(
name='forecast',
version='0.1',
author="Osvaldo Santana Neto",
author_email="[email protected]",
packages=[
'forecast',
'forecast.applications',
'forecast.applications.core',
'forecast.applications.core.commands',
'forecast.skels',
'forecast.skels.application',
'forecast.skels.project',
'forecast.skels.project.settings',
'forecast.tests',
'forecast.tests.settings',
'forecast.tests.test_app',
'forecast.tests.test_app.commands',
],
package_dir={
'forecast.skels.project': os.path.join(path, 'forecast', 'skels', 'project'),
},
package_data={
'forecast.skels.project': [
'requirements.txt',
],
},
scripts=[
os.path.join(path, 'bin', 'forecast-admin.py')
],
url="http://github.com/osantana/forecast",
license='MIT',
description="A small wrapper around Tornado Web Server to force project structure",
long_description=open(os.path.join(path, 'README.txt')).read(),
)
|
Remove 'dev' from version name and add data files to install process
|
Remove 'dev' from version name and add data files to install process
|
Python
|
mit
|
osantana/forecast
|
python
|
## Code Before:
import os
from distutils.core import setup
path = os.path.dirname(__file__)
setup(
name='forecast',
version='0.1dev',
author="Osvaldo Santana Neto",
author_email="[email protected]",
packages=[
'forecast',
'forecast.applications',
'forecast.applications.core',
'forecast.applications.core.commands',
'forecast.skels',
'forecast.skels.application',
'forecast.skels.project',
'forecast.skels.project.settings',
'forecast.tests',
'forecast.tests.settings',
'forecast.tests.test_app',
'forecast.tests.test_app.commands',
],
scripts=[os.path.join(path, 'bin', 'forecast-admin.py')],
url="http://github.com/osantana/forecast",
license='MIT',
description="A small wrapper around Tornado Web Server to force project structure",
long_description=open(os.path.join(path, 'README.txt')).read(),
)
## Instruction:
Remove 'dev' from version name and add data files to install process
## Code After:
import os
from distutils.core import setup
path = os.path.dirname(__file__)
setup(
name='forecast',
version='0.1',
author="Osvaldo Santana Neto",
author_email="[email protected]",
packages=[
'forecast',
'forecast.applications',
'forecast.applications.core',
'forecast.applications.core.commands',
'forecast.skels',
'forecast.skels.application',
'forecast.skels.project',
'forecast.skels.project.settings',
'forecast.tests',
'forecast.tests.settings',
'forecast.tests.test_app',
'forecast.tests.test_app.commands',
],
package_dir={
'forecast.skels.project': os.path.join(path, 'forecast', 'skels', 'project'),
},
package_data={
'forecast.skels.project': [
'requirements.txt',
],
},
scripts=[
os.path.join(path, 'bin', 'forecast-admin.py')
],
url="http://github.com/osantana/forecast",
license='MIT',
description="A small wrapper around Tornado Web Server to force project structure",
long_description=open(os.path.join(path, 'README.txt')).read(),
)
|
...
setup(
name='forecast',
version='0.1',
author="Osvaldo Santana Neto",
author_email="[email protected]",
packages=[
...
'forecast.tests.test_app',
'forecast.tests.test_app.commands',
],
package_dir={
'forecast.skels.project': os.path.join(path, 'forecast', 'skels', 'project'),
},
package_data={
'forecast.skels.project': [
'requirements.txt',
],
},
scripts=[
os.path.join(path, 'bin', 'forecast-admin.py')
],
url="http://github.com/osantana/forecast",
license='MIT',
description="A small wrapper around Tornado Web Server to force project structure",
long_description=open(os.path.join(path, 'README.txt')).read(),
)
...
|
c1de1a5406de7e36b3a36f5591aa16f315b1e368
|
opps/images/models.py
|
opps/images/models.py
|
import uuid
import os
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from taggit.managers import TaggableManager
from opps.core.models import Publishable
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "{0}-{1}.{2}".format(uuid.uuid4(), instance.slug, ext)
d = datetime.now()
folder = "images/{0}".format(d.strftime("%Y/%m/%d/"))
return os.path.join(folder, filename)
class Image(Publishable):
title = models.CharField(_(u"Title"), max_length=140, db_index=True)
slug = models.SlugField(_(u"Slug"), max_length=150, blank=True,
db_index=True)
image = models.ImageField(upload_to=get_file_path)
description = models.TextField(_(u"Description"), null=True, blank=True)
tags = TaggableManager(blank=True)
source = models.ForeignKey('sources.Source', null=True, blank=True)
def __unicode__(self):
return u"{0}-{1}".format(self.id, self.slug)
def get_absolute_url(self):
if self.date_available <= timezone.now() and self.published:
return self.image.url
return u""
|
import uuid
import os
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from taggit.models import TaggedItemBase
from taggit.managers import TaggableManager
from opps.core.models import Publishable
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "{0}-{1}.{2}".format(uuid.uuid4(), instance.slug, ext)
d = datetime.now()
folder = "images/{0}".format(d.strftime("%Y/%m/%d/"))
return os.path.join(folder, filename)
class TaggedImage(TaggedItemBase):
"""Tag for images """
content_object = models.ForeignKey('images.Image')
pass
class Image(Publishable):
title = models.CharField(_(u"Title"), max_length=140, db_index=True)
slug = models.SlugField(_(u"Slug"), max_length=150, blank=True,
db_index=True)
image = models.ImageField(upload_to=get_file_path)
description = models.TextField(_(u"Description"), null=True, blank=True)
tags = TaggableManager(blank=True, through=TaggedImage)
source = models.ForeignKey('sources.Source', null=True, blank=True)
def __unicode__(self):
return u"{0}-{1}".format(self.id, self.slug)
def get_absolute_url(self):
if self.date_available <= timezone.now() and self.published:
return self.image.url
return u""
|
Create TaggedImage, unique marker for image
|
Create TaggedImage, unique marker for image
|
Python
|
mit
|
YACOWS/opps,williamroot/opps,YACOWS/opps,opps/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,opps/opps,williamroot/opps,opps/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps
|
python
|
## Code Before:
import uuid
import os
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from taggit.managers import TaggableManager
from opps.core.models import Publishable
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "{0}-{1}.{2}".format(uuid.uuid4(), instance.slug, ext)
d = datetime.now()
folder = "images/{0}".format(d.strftime("%Y/%m/%d/"))
return os.path.join(folder, filename)
class Image(Publishable):
title = models.CharField(_(u"Title"), max_length=140, db_index=True)
slug = models.SlugField(_(u"Slug"), max_length=150, blank=True,
db_index=True)
image = models.ImageField(upload_to=get_file_path)
description = models.TextField(_(u"Description"), null=True, blank=True)
tags = TaggableManager(blank=True)
source = models.ForeignKey('sources.Source', null=True, blank=True)
def __unicode__(self):
return u"{0}-{1}".format(self.id, self.slug)
def get_absolute_url(self):
if self.date_available <= timezone.now() and self.published:
return self.image.url
return u""
## Instruction:
Create TaggedImage, unique marker for image
## Code After:
import uuid
import os
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from taggit.models import TaggedItemBase
from taggit.managers import TaggableManager
from opps.core.models import Publishable
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "{0}-{1}.{2}".format(uuid.uuid4(), instance.slug, ext)
d = datetime.now()
folder = "images/{0}".format(d.strftime("%Y/%m/%d/"))
return os.path.join(folder, filename)
class TaggedImage(TaggedItemBase):
"""Tag for images """
content_object = models.ForeignKey('images.Image')
pass
class Image(Publishable):
title = models.CharField(_(u"Title"), max_length=140, db_index=True)
slug = models.SlugField(_(u"Slug"), max_length=150, blank=True,
db_index=True)
image = models.ImageField(upload_to=get_file_path)
description = models.TextField(_(u"Description"), null=True, blank=True)
tags = TaggableManager(blank=True, through=TaggedImage)
source = models.ForeignKey('sources.Source', null=True, blank=True)
def __unicode__(self):
return u"{0}-{1}".format(self.id, self.slug)
def get_absolute_url(self):
if self.date_available <= timezone.now() and self.published:
return self.image.url
return u""
|
# ... existing code ...
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from taggit.models import TaggedItemBase
from taggit.managers import TaggableManager
from opps.core.models import Publishable
# ... modified code ...
return os.path.join(folder, filename)
class TaggedImage(TaggedItemBase):
"""Tag for images """
content_object = models.ForeignKey('images.Image')
pass
class Image(Publishable):
title = models.CharField(_(u"Title"), max_length=140, db_index=True)
...
db_index=True)
image = models.ImageField(upload_to=get_file_path)
description = models.TextField(_(u"Description"), null=True, blank=True)
tags = TaggableManager(blank=True, through=TaggedImage)
source = models.ForeignKey('sources.Source', null=True, blank=True)
# ... rest of the code ...
|
5a8b53a1e0e481f82c53e5fac84986e6ecc27dac
|
ontology-common/src/main/java/uk/ac/ebi/quickgo/ontology/common/coterms/CoTermRepoConfig.java
|
ontology-common/src/main/java/uk/ac/ebi/quickgo/ontology/common/coterms/CoTermRepoConfig.java
|
package uk.ac.ebi.quickgo.ontology.common.coterms;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
/**
* Configuration class related to loading and using co-occurring terms information.
* @author Tony Wardell
* Date: 29/09/2016
* Time: 11:50
* Created with IntelliJ IDEA.
*/
@Configuration
public class CoTermRepoConfig {
@Value("${coterm.source.manual}")
private Resource manualResource;
@Value("${coterm.source.all}")
private Resource allResource;
@Bean
public CoTermRepository coTermRepository() {
CoTermRepositorySimpleMap coTermRepository = new CoTermRepositorySimpleMap();
CoTermRepositorySimpleMap.CoTermLoader coTermLoader =
coTermRepository.new CoTermLoader(manualResource, allResource);
try {
coTermLoader.load();
} catch (IOException e) {
throw new RuntimeException("Failed to load co-occurring terms from manual source " +
(manualResource!=null?manualResource.getDescription():"unknown") + " or from all source " +
(allResource!=null?allResource.getDescription():"unknown"));
}
return coTermRepository;
}
}
|
package uk.ac.ebi.quickgo.ontology.common.coterms;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
/**
* Configuration class related to loading and using co-occurring terms information.
* @author Tony Wardell
* Date: 29/09/2016
* Time: 11:50
* Created with IntelliJ IDEA.
*/
@Configuration
public class CoTermRepoConfig {
@Value("${coterm.source.manual}")
private Resource manualResource;
@Value("${coterm.source.all}")
private Resource allResource;
@Bean
public CoTermRepository coTermRepository() {
CoTermRepositorySimpleMap coTermRepository;
try{
coTermRepository = CoTermRepositorySimpleMap.createCoTermRepositorySimpleMap(manualResource, allResource);
} catch (IOException e) {
throw new RuntimeException("Failed to load co-occurring terms from manual source " +
(manualResource!=null?manualResource.getDescription():"unknown") + " or from all source " +
(allResource!=null?allResource.getDescription():"unknown"));
}
return coTermRepository;
}
}
|
Replace constructors with static factory methods.
|
Replace constructors with static factory methods.
|
Java
|
apache-2.0
|
ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE
|
java
|
## Code Before:
package uk.ac.ebi.quickgo.ontology.common.coterms;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
/**
* Configuration class related to loading and using co-occurring terms information.
* @author Tony Wardell
* Date: 29/09/2016
* Time: 11:50
* Created with IntelliJ IDEA.
*/
@Configuration
public class CoTermRepoConfig {
@Value("${coterm.source.manual}")
private Resource manualResource;
@Value("${coterm.source.all}")
private Resource allResource;
@Bean
public CoTermRepository coTermRepository() {
CoTermRepositorySimpleMap coTermRepository = new CoTermRepositorySimpleMap();
CoTermRepositorySimpleMap.CoTermLoader coTermLoader =
coTermRepository.new CoTermLoader(manualResource, allResource);
try {
coTermLoader.load();
} catch (IOException e) {
throw new RuntimeException("Failed to load co-occurring terms from manual source " +
(manualResource!=null?manualResource.getDescription():"unknown") + " or from all source " +
(allResource!=null?allResource.getDescription():"unknown"));
}
return coTermRepository;
}
}
## Instruction:
Replace constructors with static factory methods.
## Code After:
package uk.ac.ebi.quickgo.ontology.common.coterms;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
/**
* Configuration class related to loading and using co-occurring terms information.
* @author Tony Wardell
* Date: 29/09/2016
* Time: 11:50
* Created with IntelliJ IDEA.
*/
@Configuration
public class CoTermRepoConfig {
@Value("${coterm.source.manual}")
private Resource manualResource;
@Value("${coterm.source.all}")
private Resource allResource;
@Bean
public CoTermRepository coTermRepository() {
CoTermRepositorySimpleMap coTermRepository;
try{
coTermRepository = CoTermRepositorySimpleMap.createCoTermRepositorySimpleMap(manualResource, allResource);
} catch (IOException e) {
throw new RuntimeException("Failed to load co-occurring terms from manual source " +
(manualResource!=null?manualResource.getDescription():"unknown") + " or from all source " +
(allResource!=null?allResource.getDescription():"unknown"));
}
return coTermRepository;
}
}
|
...
@Bean
public CoTermRepository coTermRepository() {
CoTermRepositorySimpleMap coTermRepository;
try{
coTermRepository = CoTermRepositorySimpleMap.createCoTermRepositorySimpleMap(manualResource, allResource);
} catch (IOException e) {
throw new RuntimeException("Failed to load co-occurring terms from manual source " +
(manualResource!=null?manualResource.getDescription():"unknown") + " or from all source " +
...
|
8da134823a56567e09a09aefc44837a837644912
|
ddcz/urls.py
|
ddcz/urls.py
|
from django.urls import path
from . import views
app_name='ddcz'
urlpatterns = [
path('', views.index, name='news'),
path('rubriky/<creative_page_slug>/', views.common_articles, name='common-article-list'),
path('rubriky/<creative_page_slug>/<int:article_id>-<article_slug>/', views.common_article_detail, name='common-article-detail'),
path('seznamka/', views.dating, name='dating'),
path('nastaveni/zmena-skinu/', views.change_skin, name='change-skin'),
]
|
from django.urls import path
from django.views.generic.base import RedirectView
from . import views
app_name='ddcz'
urlpatterns = [
path('', RedirectView.as_view(url='aktuality/', permanent=True)),
path('aktuality/', views.index, name='news'),
path('rubriky/<creative_page_slug>/', views.common_articles, name='common-article-list'),
path('rubriky/<creative_page_slug>/<int:article_id>-<article_slug>/', views.common_article_detail, name='common-article-detail'),
path('seznamka/', views.dating, name='dating'),
path('nastaveni/zmena-skinu/', views.change_skin, name='change-skin'),
]
|
Put news on non-root path for clarity
|
Put news on non-root path for clarity
|
Python
|
mit
|
dracidoupe/graveyard,dracidoupe/graveyard,dracidoupe/graveyard,dracidoupe/graveyard
|
python
|
## Code Before:
from django.urls import path
from . import views
app_name='ddcz'
urlpatterns = [
path('', views.index, name='news'),
path('rubriky/<creative_page_slug>/', views.common_articles, name='common-article-list'),
path('rubriky/<creative_page_slug>/<int:article_id>-<article_slug>/', views.common_article_detail, name='common-article-detail'),
path('seznamka/', views.dating, name='dating'),
path('nastaveni/zmena-skinu/', views.change_skin, name='change-skin'),
]
## Instruction:
Put news on non-root path for clarity
## Code After:
from django.urls import path
from django.views.generic.base import RedirectView
from . import views
app_name='ddcz'
urlpatterns = [
path('', RedirectView.as_view(url='aktuality/', permanent=True)),
path('aktuality/', views.index, name='news'),
path('rubriky/<creative_page_slug>/', views.common_articles, name='common-article-list'),
path('rubriky/<creative_page_slug>/<int:article_id>-<article_slug>/', views.common_article_detail, name='common-article-detail'),
path('seznamka/', views.dating, name='dating'),
path('nastaveni/zmena-skinu/', views.change_skin, name='change-skin'),
]
|
// ... existing code ...
from django.urls import path
from django.views.generic.base import RedirectView
from . import views
// ... modified code ...
app_name='ddcz'
urlpatterns = [
path('', RedirectView.as_view(url='aktuality/', permanent=True)),
path('aktuality/', views.index, name='news'),
path('rubriky/<creative_page_slug>/', views.common_articles, name='common-article-list'),
path('rubriky/<creative_page_slug>/<int:article_id>-<article_slug>/', views.common_article_detail, name='common-article-detail'),
// ... rest of the code ...
|
3bc4605780b134b5e2c9d292f70d58c65ddd01a9
|
wicket/src/test/wicket/util/time/TimeOfDayTest.java
|
wicket/src/test/wicket/util/time/TimeOfDayTest.java
|
/*
* $Id$
* $Revision$
* $Date$
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package wicket.util.time;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* Test cases for this object
* @author Jonathan Locke
*/
public final class TimeOfDayTest extends TestCase
{
/**
*
*/
public void test()
{
Assert.assertTrue(TimeOfDay.MIDNIGHT.hour() == 0);
Assert.assertTrue(TimeOfDay.valueOf(TimeOfDay.MIDNIGHT.next()).equals(TimeOfDay.MIDNIGHT));
final TimeOfDay three = TimeOfDay.time(3, 0, TimeOfDay.PM);
final TimeOfDay five = TimeOfDay.time(5, 0, TimeOfDay.PM);
Assert.assertTrue(five.after(three));
}
}
|
/*
* $Id$
* $Revision$
* $Date$
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package wicket.util.time;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* Test cases for this object
* @author Jonathan Locke
*/
public final class TimeOfDayTest extends TestCase
{
/**
*
*/
public void test()
{
Assert.assertEquals(0, TimeOfDay.MIDNIGHT.hour());
Assert.assertEquals(TimeOfDay.MIDNIGHT, TimeOfDay.valueOf(TimeOfDay.MIDNIGHT.next()));
final TimeOfDay three = TimeOfDay.time(3, 0, TimeOfDay.PM);
final TimeOfDay five = TimeOfDay.time(5, 0, TimeOfDay.PM);
Assert.assertTrue(five.after(three));
}
}
|
Use the appropriate methods for checking equality. This gives better results when debugging the errors.
|
Use the appropriate methods for checking equality. This gives better results when debugging the errors.
git-svn-id: ac804e38dcddf5e42ac850d29d9218b7df6087b7@459989 13f79535-47bb-0310-9956-ffa450edef68
|
Java
|
apache-2.0
|
apache/wicket,AlienQueen/wicket,mosoft521/wicket,martin-g/wicket-osgi,mosoft521/wicket,zwsong/wicket,AlienQueen/wicket,mafulafunk/wicket,astrapi69/wicket,apache/wicket,klopfdreh/wicket,mosoft521/wicket,aldaris/wicket,freiheit-com/wicket,dashorst/wicket,topicusonderwijs/wicket,klopfdreh/wicket,Servoy/wicket,mosoft521/wicket,selckin/wicket,freiheit-com/wicket,topicusonderwijs/wicket,dashorst/wicket,zwsong/wicket,selckin/wicket,klopfdreh/wicket,zwsong/wicket,apache/wicket,martin-g/wicket-osgi,freiheit-com/wicket,mafulafunk/wicket,mosoft521/wicket,Servoy/wicket,bitstorm/wicket,astrapi69/wicket,topicusonderwijs/wicket,astrapi69/wicket,bitstorm/wicket,selckin/wicket,bitstorm/wicket,aldaris/wicket,dashorst/wicket,apache/wicket,selckin/wicket,Servoy/wicket,selckin/wicket,aldaris/wicket,martin-g/wicket-osgi,dashorst/wicket,mafulafunk/wicket,apache/wicket,bitstorm/wicket,freiheit-com/wicket,Servoy/wicket,zwsong/wicket,klopfdreh/wicket,aldaris/wicket,freiheit-com/wicket,AlienQueen/wicket,Servoy/wicket,topicusonderwijs/wicket,bitstorm/wicket,klopfdreh/wicket,aldaris/wicket,topicusonderwijs/wicket,dashorst/wicket,AlienQueen/wicket,astrapi69/wicket,AlienQueen/wicket
|
java
|
## Code Before:
/*
* $Id$
* $Revision$
* $Date$
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package wicket.util.time;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* Test cases for this object
* @author Jonathan Locke
*/
public final class TimeOfDayTest extends TestCase
{
/**
*
*/
public void test()
{
Assert.assertTrue(TimeOfDay.MIDNIGHT.hour() == 0);
Assert.assertTrue(TimeOfDay.valueOf(TimeOfDay.MIDNIGHT.next()).equals(TimeOfDay.MIDNIGHT));
final TimeOfDay three = TimeOfDay.time(3, 0, TimeOfDay.PM);
final TimeOfDay five = TimeOfDay.time(5, 0, TimeOfDay.PM);
Assert.assertTrue(five.after(three));
}
}
## Instruction:
Use the appropriate methods for checking equality. This gives better results when debugging the errors.
git-svn-id: ac804e38dcddf5e42ac850d29d9218b7df6087b7@459989 13f79535-47bb-0310-9956-ffa450edef68
## Code After:
/*
* $Id$
* $Revision$
* $Date$
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package wicket.util.time;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* Test cases for this object
* @author Jonathan Locke
*/
public final class TimeOfDayTest extends TestCase
{
/**
*
*/
public void test()
{
Assert.assertEquals(0, TimeOfDay.MIDNIGHT.hour());
Assert.assertEquals(TimeOfDay.MIDNIGHT, TimeOfDay.valueOf(TimeOfDay.MIDNIGHT.next()));
final TimeOfDay three = TimeOfDay.time(3, 0, TimeOfDay.PM);
final TimeOfDay five = TimeOfDay.time(5, 0, TimeOfDay.PM);
Assert.assertTrue(five.after(three));
}
}
|
...
*/
public void test()
{
Assert.assertEquals(0, TimeOfDay.MIDNIGHT.hour());
Assert.assertEquals(TimeOfDay.MIDNIGHT, TimeOfDay.valueOf(TimeOfDay.MIDNIGHT.next()));
final TimeOfDay three = TimeOfDay.time(3, 0, TimeOfDay.PM);
final TimeOfDay five = TimeOfDay.time(5, 0, TimeOfDay.PM);
...
|
dbbdfc477cca5961e9fa89b3627f909ab34a3fd3
|
assets/src/RubotoBroadcastReceiver.java
|
assets/src/RubotoBroadcastReceiver.java
|
package THE_PACKAGE;
public class THE_RUBOTO_CLASS THE_ACTION THE_ANDROID_CLASS {
private String scriptName;
private boolean initialized = false;
public void setCallbackProc(int id, Object obj) {
// Error: no callbacks
throw new RuntimeException("RubotoBroadcastReceiver does not accept callbacks");
}
public void setScriptName(String name){
scriptName = name;
}
public THE_RUBOTO_CLASS() {
this(null);
}
public THE_RUBOTO_CLASS(String name) {
super();
if (name != null)
setScriptName(name);
}
public void onReceive(android.content.Context context, android.content.Intent intent) {
if (Script.setUpJRuby(context)) {
Script.defineGlobalVariable("$context", context);
Script.defineGlobalVariable("$broadcast_receiver", this);
Script.defineGlobalVariable("$intent", intent);
try {
if (scriptName != null && !initialized) {
new Script(scriptName).execute();
initialized = true;
} else {
Script.execute("$broadcast_receiver.on_receive($context, $intent)");
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
|
package THE_PACKAGE;
import java.io.IOException;
public class THE_RUBOTO_CLASS THE_ACTION THE_ANDROID_CLASS {
private String scriptName = null;
private boolean initialized = false;
public void setCallbackProc(int id, Object obj) {
// Error: no callbacks
throw new RuntimeException("RubotoBroadcastReceiver does not accept callbacks");
}
public void setScriptName(String name){
scriptName = name;
}
public THE_RUBOTO_CLASS() {
this(null);
}
public THE_RUBOTO_CLASS(String name) {
super();
if (name != null) {
setScriptName(name);
if (Script.isInitialized()) {
loadScript();
}
}
}
protected void loadScript() {
Script.put("$broadcast_receiver", this);
if (scriptName != null) {
try {
new Script(scriptName).execute();
} catch(IOException e) {
throw new RuntimeException("IOException loading broadcast receiver script", e);
}
}
}
public void onReceive(android.content.Context context, android.content.Intent intent) {
Script.put("$context", context);
Script.put("$broadcast_receiver", this);
Script.put("$intent", intent);
try {
Script.execute("$broadcast_receiver.on_receive($context, $intent)");
} catch(Exception e) {
e.printStackTrace();
}
}
}
|
Update to work through manifest and directly
|
Update to work through manifest and directly
|
Java
|
mit
|
lucasallan/ruboto,Jodell88/ruboto,lucasallan/ruboto,baberthal/ruboto,baberthal/ruboto,Jodell88/ruboto,lucasallan/ruboto,ruboto/ruboto,ruboto/ruboto,Jodell88/ruboto,ruboto/ruboto,baberthal/ruboto
|
java
|
## Code Before:
package THE_PACKAGE;
public class THE_RUBOTO_CLASS THE_ACTION THE_ANDROID_CLASS {
private String scriptName;
private boolean initialized = false;
public void setCallbackProc(int id, Object obj) {
// Error: no callbacks
throw new RuntimeException("RubotoBroadcastReceiver does not accept callbacks");
}
public void setScriptName(String name){
scriptName = name;
}
public THE_RUBOTO_CLASS() {
this(null);
}
public THE_RUBOTO_CLASS(String name) {
super();
if (name != null)
setScriptName(name);
}
public void onReceive(android.content.Context context, android.content.Intent intent) {
if (Script.setUpJRuby(context)) {
Script.defineGlobalVariable("$context", context);
Script.defineGlobalVariable("$broadcast_receiver", this);
Script.defineGlobalVariable("$intent", intent);
try {
if (scriptName != null && !initialized) {
new Script(scriptName).execute();
initialized = true;
} else {
Script.execute("$broadcast_receiver.on_receive($context, $intent)");
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
## Instruction:
Update to work through manifest and directly
## Code After:
package THE_PACKAGE;
import java.io.IOException;
public class THE_RUBOTO_CLASS THE_ACTION THE_ANDROID_CLASS {
private String scriptName = null;
private boolean initialized = false;
public void setCallbackProc(int id, Object obj) {
// Error: no callbacks
throw new RuntimeException("RubotoBroadcastReceiver does not accept callbacks");
}
public void setScriptName(String name){
scriptName = name;
}
public THE_RUBOTO_CLASS() {
this(null);
}
public THE_RUBOTO_CLASS(String name) {
super();
if (name != null) {
setScriptName(name);
if (Script.isInitialized()) {
loadScript();
}
}
}
protected void loadScript() {
Script.put("$broadcast_receiver", this);
if (scriptName != null) {
try {
new Script(scriptName).execute();
} catch(IOException e) {
throw new RuntimeException("IOException loading broadcast receiver script", e);
}
}
}
public void onReceive(android.content.Context context, android.content.Intent intent) {
Script.put("$context", context);
Script.put("$broadcast_receiver", this);
Script.put("$intent", intent);
try {
Script.execute("$broadcast_receiver.on_receive($context, $intent)");
} catch(Exception e) {
e.printStackTrace();
}
}
}
|
// ... existing code ...
package THE_PACKAGE;
import java.io.IOException;
public class THE_RUBOTO_CLASS THE_ACTION THE_ANDROID_CLASS {
private String scriptName = null;
private boolean initialized = false;
public void setCallbackProc(int id, Object obj) {
// ... modified code ...
public THE_RUBOTO_CLASS(String name) {
super();
if (name != null) {
setScriptName(name);
if (Script.isInitialized()) {
loadScript();
}
}
}
protected void loadScript() {
Script.put("$broadcast_receiver", this);
if (scriptName != null) {
try {
new Script(scriptName).execute();
} catch(IOException e) {
throw new RuntimeException("IOException loading broadcast receiver script", e);
}
}
}
public void onReceive(android.content.Context context, android.content.Intent intent) {
Script.put("$context", context);
Script.put("$broadcast_receiver", this);
Script.put("$intent", intent);
try {
Script.execute("$broadcast_receiver.on_receive($context, $intent)");
} catch(Exception e) {
e.printStackTrace();
}
}
}
// ... rest of the code ...
|
425056e6196dbce50f08d94f1578a2984b8a1c21
|
setup.py
|
setup.py
|
from __future__ import print_function
from setuptools import setup
setup(
name="rpe-lib",
description="A resource policy evaluation library",
author="Joe Ceresini",
url="https://github.com/forseti-security/resource-policy-evaluation-library",
use_scm_version=True,
setup_requires=['setuptools_scm'],
install_requires=[
'google-api-python-client',
'google-api-python-client-helpers',
'tenacity',
],
packages=[
'rpe',
'rpe.engines',
'rpe.resources',
],
package_data={},
license="Apache 2.0",
keywords="gcp policy enforcement",
)
|
from __future__ import print_function
from setuptools import setup
setup(
name="rpe-lib",
description="A resource policy evaluation library",
long_description=open('README.md').read(),
author="Joe Ceresini",
url="https://github.com/forseti-security/resource-policy-evaluation-library",
use_scm_version=True,
setup_requires=['setuptools_scm'],
install_requires=[
'google-api-python-client',
'google-api-python-client-helpers',
'tenacity',
],
packages=[
'rpe',
'rpe.engines',
'rpe.resources',
],
package_data={},
license="Apache 2.0",
keywords="gcp policy enforcement",
)
|
Read in README.md as long description
|
Read in README.md as long description
|
Python
|
apache-2.0
|
forseti-security/resource-policy-evaluation-library
|
python
|
## Code Before:
from __future__ import print_function
from setuptools import setup
setup(
name="rpe-lib",
description="A resource policy evaluation library",
author="Joe Ceresini",
url="https://github.com/forseti-security/resource-policy-evaluation-library",
use_scm_version=True,
setup_requires=['setuptools_scm'],
install_requires=[
'google-api-python-client',
'google-api-python-client-helpers',
'tenacity',
],
packages=[
'rpe',
'rpe.engines',
'rpe.resources',
],
package_data={},
license="Apache 2.0",
keywords="gcp policy enforcement",
)
## Instruction:
Read in README.md as long description
## Code After:
from __future__ import print_function
from setuptools import setup
setup(
name="rpe-lib",
description="A resource policy evaluation library",
long_description=open('README.md').read(),
author="Joe Ceresini",
url="https://github.com/forseti-security/resource-policy-evaluation-library",
use_scm_version=True,
setup_requires=['setuptools_scm'],
install_requires=[
'google-api-python-client',
'google-api-python-client-helpers',
'tenacity',
],
packages=[
'rpe',
'rpe.engines',
'rpe.resources',
],
package_data={},
license="Apache 2.0",
keywords="gcp policy enforcement",
)
|
# ... existing code ...
setup(
name="rpe-lib",
description="A resource policy evaluation library",
long_description=open('README.md').read(),
author="Joe Ceresini",
url="https://github.com/forseti-security/resource-policy-evaluation-library",
use_scm_version=True,
# ... rest of the code ...
|
6520fde5be81eb3d1a91662edeef8bd2a1f6389c
|
stonemason/service/tileserver/helper.py
|
stonemason/service/tileserver/helper.py
|
__author__ = 'ray'
__date__ = '4/4/15'
from stonemason.mason import Portrayal
from stonemason.mason.theme import Theme
def jsonify_portrayal(portrayal):
assert isinstance(portrayal, Portrayal)
template = {
'name': portrayal.name,
'metadata': {
'version': portrayal.metadata.version,
'abstract': portrayal.metadata.abstract,
'attribution': portrayal.metadata.attribution,
'center': portrayal.metadata.center,
'center_zoom': portrayal.metadata.center_zoom
},
'maptype': portrayal.bundle.map_type,
'tileformat': portrayal.bundle.tile_format,
'pyramid': portrayal.pyramid,
'schemas': []
}
for tag in portrayal.iter_schema():
template['schemas'].append(tag)
return template
def jsonify_map_theme(map_theme):
assert isinstance(map_theme, Theme)
return repr(map_theme)
|
__author__ = 'ray'
__date__ = '4/4/15'
from stonemason.mason import Portrayal
from stonemason.mason.theme import Theme
def jsonify_portrayal(portrayal):
assert isinstance(portrayal, Portrayal)
template = {
'name': portrayal.name,
'metadata': {
'title': portrayal.metadata.title,
'version': portrayal.metadata.version,
'abstract': portrayal.metadata.abstract,
'attribution': portrayal.metadata.attribution,
'center': portrayal.metadata.center,
'center_zoom': portrayal.metadata.center_zoom
},
'maptype': portrayal.bundle.map_type,
'tileformat': portrayal.bundle.tile_format,
'pyramid': portrayal.pyramid,
'schemas': []
}
for tag in portrayal.iter_schema():
template['schemas'].append(tag)
return template
def jsonify_map_theme(map_theme):
assert isinstance(map_theme, Theme)
return repr(map_theme)
|
Add metadata title in portrayal view
|
FEATURE: Add metadata title in portrayal view
|
Python
|
mit
|
Kotaimen/stonemason,Kotaimen/stonemason
|
python
|
## Code Before:
__author__ = 'ray'
__date__ = '4/4/15'
from stonemason.mason import Portrayal
from stonemason.mason.theme import Theme
def jsonify_portrayal(portrayal):
assert isinstance(portrayal, Portrayal)
template = {
'name': portrayal.name,
'metadata': {
'version': portrayal.metadata.version,
'abstract': portrayal.metadata.abstract,
'attribution': portrayal.metadata.attribution,
'center': portrayal.metadata.center,
'center_zoom': portrayal.metadata.center_zoom
},
'maptype': portrayal.bundle.map_type,
'tileformat': portrayal.bundle.tile_format,
'pyramid': portrayal.pyramid,
'schemas': []
}
for tag in portrayal.iter_schema():
template['schemas'].append(tag)
return template
def jsonify_map_theme(map_theme):
assert isinstance(map_theme, Theme)
return repr(map_theme)
## Instruction:
FEATURE: Add metadata title in portrayal view
## Code After:
__author__ = 'ray'
__date__ = '4/4/15'
from stonemason.mason import Portrayal
from stonemason.mason.theme import Theme
def jsonify_portrayal(portrayal):
assert isinstance(portrayal, Portrayal)
template = {
'name': portrayal.name,
'metadata': {
'title': portrayal.metadata.title,
'version': portrayal.metadata.version,
'abstract': portrayal.metadata.abstract,
'attribution': portrayal.metadata.attribution,
'center': portrayal.metadata.center,
'center_zoom': portrayal.metadata.center_zoom
},
'maptype': portrayal.bundle.map_type,
'tileformat': portrayal.bundle.tile_format,
'pyramid': portrayal.pyramid,
'schemas': []
}
for tag in portrayal.iter_schema():
template['schemas'].append(tag)
return template
def jsonify_map_theme(map_theme):
assert isinstance(map_theme, Theme)
return repr(map_theme)
|
...
template = {
'name': portrayal.name,
'metadata': {
'title': portrayal.metadata.title,
'version': portrayal.metadata.version,
'abstract': portrayal.metadata.abstract,
'attribution': portrayal.metadata.attribution,
...
|
80f95f92bde7a9043283c1b7e466796463ccd398
|
src/math/DivideByZeroException.java
|
src/math/DivideByZeroException.java
|
package math;
public class DivideByZeroException
extends
Exception
{
public DivideByZeroException(String reason){
super(reason);
}
public DivideByZeroException(){
super();
}
public String printException(){
return "Divide by zero!";
}
}
|
package math;
public class DivideByZeroException
extends
Exception
{
/**
*
*/
private static final long serialVersionUID = 1L;
/*
* @param String reason
* @purpose calls super constructor of same param
*/
public DivideByZeroException(String reason){
super(reason);
} // DivideByZeroException(String)
/*
* @purpose calls super constructor of same param
*/
public DivideByZeroException(){
super();
}// DivideByZeroException()
/*
* @purpose returns customized message
*/
public String printException(){
return "Divide by zero!";
} // printException()
} // class DivideByZeroException
|
Add comments for custom exception
|
Add comments for custom exception
|
Java
|
apache-2.0
|
nguyengi/csc207-hw4
|
java
|
## Code Before:
package math;
public class DivideByZeroException
extends
Exception
{
public DivideByZeroException(String reason){
super(reason);
}
public DivideByZeroException(){
super();
}
public String printException(){
return "Divide by zero!";
}
}
## Instruction:
Add comments for custom exception
## Code After:
package math;
public class DivideByZeroException
extends
Exception
{
/**
*
*/
private static final long serialVersionUID = 1L;
/*
* @param String reason
* @purpose calls super constructor of same param
*/
public DivideByZeroException(String reason){
super(reason);
} // DivideByZeroException(String)
/*
* @purpose calls super constructor of same param
*/
public DivideByZeroException(){
super();
}// DivideByZeroException()
/*
* @purpose returns customized message
*/
public String printException(){
return "Divide by zero!";
} // printException()
} // class DivideByZeroException
|
# ... existing code ...
extends
Exception
{
/**
*
*/
private static final long serialVersionUID = 1L;
/*
* @param String reason
* @purpose calls super constructor of same param
*/
public DivideByZeroException(String reason){
super(reason);
} // DivideByZeroException(String)
/*
* @purpose calls super constructor of same param
*/
public DivideByZeroException(){
super();
}// DivideByZeroException()
/*
* @purpose returns customized message
*/
public String printException(){
return "Divide by zero!";
} // printException()
} // class DivideByZeroException
# ... rest of the code ...
|
5117af4672b9d59251320341727256e97405c807
|
subprojects/playpens/java-playpen/aop/aspectj-playpen/src/test/java/com/fenixinfotech/aspectj/playpen/AspectedFunctionalityTest.java
|
subprojects/playpens/java-playpen/aop/aspectj-playpen/src/test/java/com/fenixinfotech/aspectj/playpen/AspectedFunctionalityTest.java
|
package com.fenixinfotech.aspectj.playpen;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by 700608667 on 11/09/2015.
*/
public class AspectedFunctionalityTest
{
@Test
public void testPower() throws Exception
{
new AspectedFunctionality().power(2, 3);
}
}
|
package com.fenixinfotech.aspectj.playpen;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by 700608667 on 11/09/2015.
*/
public class AspectedFunctionalityTest
{
@Test
public void testPower() throws Exception
{
assertEquals(8, new AspectedFunctionality().power(2, 3), 0);
}
}
|
Check expected output of aspected operation.
|
Check expected output of aspected operation.
|
Java
|
mit
|
stevocurtis/public-development,stevocurtis/public-development,stevocurtis/public-development,stevocurtis/public-development,stevocurtis/public-development,stevocurtis/public-development
|
java
|
## Code Before:
package com.fenixinfotech.aspectj.playpen;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by 700608667 on 11/09/2015.
*/
public class AspectedFunctionalityTest
{
@Test
public void testPower() throws Exception
{
new AspectedFunctionality().power(2, 3);
}
}
## Instruction:
Check expected output of aspected operation.
## Code After:
package com.fenixinfotech.aspectj.playpen;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by 700608667 on 11/09/2015.
*/
public class AspectedFunctionalityTest
{
@Test
public void testPower() throws Exception
{
assertEquals(8, new AspectedFunctionality().power(2, 3), 0);
}
}
|
// ... existing code ...
@Test
public void testPower() throws Exception
{
assertEquals(8, new AspectedFunctionality().power(2, 3), 0);
}
}
// ... rest of the code ...
|
dc1cf6fabcf871e3661125f7ac5d1cf9567798d6
|
cms/management/commands/load_dev_fixtures.py
|
cms/management/commands/load_dev_fixtures.py
|
import requests
from django.core.management import call_command
from django.core.management.base import NoArgsCommand
from django.conf import settings
from django.utils.six.moves import input
class Command(NoArgsCommand):
"""
Download and load dev fixtures from www.python.org
"""
help = "Download and load dev fixtures from python.org"
def handle_noargs(self, **options):
# Confirm the user wants to do this
confirm = input("""You have requested to load the python.org development fixtures.
This will IRREVERSIBLY DESTROY all data currently in your local database.
Are you sure you want to do this?
Type 'y' or 'yes' to continue, 'n' or 'no' to cancel: """)
if confirm in ('y', 'yes'):
if confirm:
print()
print("Beginning download, note this can take a couple of minutes...")
r = requests.get(settings.DEV_FIXTURE_URL, stream=True)
if r.status_code != 200:
print("Unable to download file: Received status code {}".format(r.status_code))
with open('/tmp/dev-fixtures.json.gz', 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
f.write(chunk)
f.flush()
print("Download complete, loading fixtures")
call_command('loaddata', '/tmp/dev-fixtures.json')
print("END: Fixtures loaded")
|
import requests
from django.core.management import call_command
from django.core.management.base import NoArgsCommand
from django.conf import settings
from django.utils.six.moves import input
class Command(NoArgsCommand):
"""
Download and load dev fixtures from www.python.org
"""
help = "Download and load dev fixtures from python.org"
def handle_noargs(self, **options):
# Confirm the user wants to do this
confirm = input("""You have requested to load the python.org development fixtures.
This will IRREVERSIBLY DESTROY all data currently in your local database.
Are you sure you want to do this?
Type 'y' or 'yes' to continue, 'n' or 'no' to cancel: """)
if confirm in ('y', 'yes'):
self.stdout.write("\nBeginning download, note this can take a couple of minutes...")
r = requests.get(settings.DEV_FIXTURE_URL, stream=True)
if r.status_code != 200:
self.stdout.write("Unable to download file: Received status code {}".format(r.status_code))
with open('/tmp/dev-fixtures.json.gz', 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
f.write(chunk)
f.flush()
self.stdout.write("Download complete, loading fixtures")
call_command('loaddata', '/tmp/dev-fixtures.json')
self.stdout.write("END: Fixtures loaded")
|
Use self.stdout.write() instead of print().
|
Use self.stdout.write() instead of print().
This is the recommended way in the Django documentation:
https://docs.djangoproject.com/en/1.7/howto/custom-management-commands/
|
Python
|
apache-2.0
|
manhhomienbienthuy/pythondotorg,python/pythondotorg,SujaySKumar/pythondotorg,lebronhkh/pythondotorg,SujaySKumar/pythondotorg,lepture/pythondotorg,python/pythondotorg,proevo/pythondotorg,Mariatta/pythondotorg,malemburg/pythondotorg,willingc/pythondotorg,fe11x/pythondotorg,berkerpeksag/pythondotorg,demvher/pythondotorg,python/pythondotorg,SujaySKumar/pythondotorg,berkerpeksag/pythondotorg,lepture/pythondotorg,manhhomienbienthuy/pythondotorg,ahua/pythondotorg,Mariatta/pythondotorg,lepture/pythondotorg,malemburg/pythondotorg,demvher/pythondotorg,fe11x/pythondotorg,SujaySKumar/pythondotorg,willingc/pythondotorg,Mariatta/pythondotorg,demvher/pythondotorg,proevo/pythondotorg,proevo/pythondotorg,SujaySKumar/pythondotorg,demvher/pythondotorg,ahua/pythondotorg,fe11x/pythondotorg,proevo/pythondotorg,manhhomienbienthuy/pythondotorg,fe11x/pythondotorg,willingc/pythondotorg,lebronhkh/pythondotorg,lepture/pythondotorg,berkerpeksag/pythondotorg,ahua/pythondotorg,manhhomienbienthuy/pythondotorg,Mariatta/pythondotorg,malemburg/pythondotorg,berkerpeksag/pythondotorg,lebronhkh/pythondotorg,ahua/pythondotorg,malemburg/pythondotorg,lepture/pythondotorg,fe11x/pythondotorg,willingc/pythondotorg,python/pythondotorg,ahua/pythondotorg,lebronhkh/pythondotorg,lebronhkh/pythondotorg,demvher/pythondotorg,berkerpeksag/pythondotorg
|
python
|
## Code Before:
import requests
from django.core.management import call_command
from django.core.management.base import NoArgsCommand
from django.conf import settings
from django.utils.six.moves import input
class Command(NoArgsCommand):
"""
Download and load dev fixtures from www.python.org
"""
help = "Download and load dev fixtures from python.org"
def handle_noargs(self, **options):
# Confirm the user wants to do this
confirm = input("""You have requested to load the python.org development fixtures.
This will IRREVERSIBLY DESTROY all data currently in your local database.
Are you sure you want to do this?
Type 'y' or 'yes' to continue, 'n' or 'no' to cancel: """)
if confirm in ('y', 'yes'):
if confirm:
print()
print("Beginning download, note this can take a couple of minutes...")
r = requests.get(settings.DEV_FIXTURE_URL, stream=True)
if r.status_code != 200:
print("Unable to download file: Received status code {}".format(r.status_code))
with open('/tmp/dev-fixtures.json.gz', 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
f.write(chunk)
f.flush()
print("Download complete, loading fixtures")
call_command('loaddata', '/tmp/dev-fixtures.json')
print("END: Fixtures loaded")
## Instruction:
Use self.stdout.write() instead of print().
This is the recommended way in the Django documentation:
https://docs.djangoproject.com/en/1.7/howto/custom-management-commands/
## Code After:
import requests
from django.core.management import call_command
from django.core.management.base import NoArgsCommand
from django.conf import settings
from django.utils.six.moves import input
class Command(NoArgsCommand):
"""
Download and load dev fixtures from www.python.org
"""
help = "Download and load dev fixtures from python.org"
def handle_noargs(self, **options):
# Confirm the user wants to do this
confirm = input("""You have requested to load the python.org development fixtures.
This will IRREVERSIBLY DESTROY all data currently in your local database.
Are you sure you want to do this?
Type 'y' or 'yes' to continue, 'n' or 'no' to cancel: """)
if confirm in ('y', 'yes'):
self.stdout.write("\nBeginning download, note this can take a couple of minutes...")
r = requests.get(settings.DEV_FIXTURE_URL, stream=True)
if r.status_code != 200:
self.stdout.write("Unable to download file: Received status code {}".format(r.status_code))
with open('/tmp/dev-fixtures.json.gz', 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
f.write(chunk)
f.flush()
self.stdout.write("Download complete, loading fixtures")
call_command('loaddata', '/tmp/dev-fixtures.json')
self.stdout.write("END: Fixtures loaded")
|
...
Type 'y' or 'yes' to continue, 'n' or 'no' to cancel: """)
if confirm in ('y', 'yes'):
self.stdout.write("\nBeginning download, note this can take a couple of minutes...")
r = requests.get(settings.DEV_FIXTURE_URL, stream=True)
if r.status_code != 200:
self.stdout.write("Unable to download file: Received status code {}".format(r.status_code))
with open('/tmp/dev-fixtures.json.gz', 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
...
f.write(chunk)
f.flush()
self.stdout.write("Download complete, loading fixtures")
call_command('loaddata', '/tmp/dev-fixtures.json')
self.stdout.write("END: Fixtures loaded")
...
|
1285e4bcbdbcf3c28eced497c8585892f3ae1239
|
django_summernote/admin.py
|
django_summernote/admin.py
|
from django.contrib import admin
from django.db import models
from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget
from django_summernote.models import Attachment
from django_summernote.settings import summernote_config, get_attachment_model
__widget__ = SummernoteWidget if summernote_config['iframe'] \
else SummernoteInplaceWidget
class SummernoteInlineModelAdmin(admin.options.InlineModelAdmin):
formfield_overrides = {models.TextField: {'widget': __widget__}}
class SummernoteModelAdmin(admin.ModelAdmin):
formfield_overrides = {models.TextField: {'widget': __widget__}}
class AttachmentAdmin(admin.ModelAdmin):
list_display = ['name', 'file', 'uploaded']
search_fields = ['name']
ordering = ('-id',)
def save_model(self, request, obj, form, change):
obj.name = obj.file.name if (not obj.name) else obj.name
super(AttachmentAdmin, self).save_model(request, obj, form, change)
admin.site.register(get_attachment_model(), AttachmentAdmin)
|
from django.contrib import admin
from django.db import models
from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget
from django_summernote.settings import summernote_config, get_attachment_model
__widget__ = SummernoteWidget if summernote_config['iframe'] \
else SummernoteInplaceWidget
class SummernoteInlineModelAdmin(admin.options.InlineModelAdmin):
formfield_overrides = {models.TextField: {'widget': __widget__}}
class SummernoteModelAdmin(admin.ModelAdmin):
formfield_overrides = {models.TextField: {'widget': __widget__}}
class AttachmentAdmin(admin.ModelAdmin):
list_display = ['name', 'file', 'uploaded']
search_fields = ['name']
ordering = ('-id',)
def save_model(self, request, obj, form, change):
obj.name = obj.file.name if (not obj.name) else obj.name
super(AttachmentAdmin, self).save_model(request, obj, form, change)
admin.site.register(get_attachment_model(), AttachmentAdmin)
|
Remove a non-used module importing
|
Remove a non-used module importing
|
Python
|
mit
|
lqez/django-summernote,summernote/django-summernote,lqez/django-summernote,lqez/django-summernote,summernote/django-summernote,summernote/django-summernote
|
python
|
## Code Before:
from django.contrib import admin
from django.db import models
from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget
from django_summernote.models import Attachment
from django_summernote.settings import summernote_config, get_attachment_model
__widget__ = SummernoteWidget if summernote_config['iframe'] \
else SummernoteInplaceWidget
class SummernoteInlineModelAdmin(admin.options.InlineModelAdmin):
formfield_overrides = {models.TextField: {'widget': __widget__}}
class SummernoteModelAdmin(admin.ModelAdmin):
formfield_overrides = {models.TextField: {'widget': __widget__}}
class AttachmentAdmin(admin.ModelAdmin):
list_display = ['name', 'file', 'uploaded']
search_fields = ['name']
ordering = ('-id',)
def save_model(self, request, obj, form, change):
obj.name = obj.file.name if (not obj.name) else obj.name
super(AttachmentAdmin, self).save_model(request, obj, form, change)
admin.site.register(get_attachment_model(), AttachmentAdmin)
## Instruction:
Remove a non-used module importing
## Code After:
from django.contrib import admin
from django.db import models
from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget
from django_summernote.settings import summernote_config, get_attachment_model
__widget__ = SummernoteWidget if summernote_config['iframe'] \
else SummernoteInplaceWidget
class SummernoteInlineModelAdmin(admin.options.InlineModelAdmin):
formfield_overrides = {models.TextField: {'widget': __widget__}}
class SummernoteModelAdmin(admin.ModelAdmin):
formfield_overrides = {models.TextField: {'widget': __widget__}}
class AttachmentAdmin(admin.ModelAdmin):
list_display = ['name', 'file', 'uploaded']
search_fields = ['name']
ordering = ('-id',)
def save_model(self, request, obj, form, change):
obj.name = obj.file.name if (not obj.name) else obj.name
super(AttachmentAdmin, self).save_model(request, obj, form, change)
admin.site.register(get_attachment_model(), AttachmentAdmin)
|
// ... existing code ...
from django.contrib import admin
from django.db import models
from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget
from django_summernote.settings import summernote_config, get_attachment_model
__widget__ = SummernoteWidget if summernote_config['iframe'] \
// ... rest of the code ...
|
f3eb6cbc0f518ed8ec6098d3dfdd205ed734022c
|
eval_kernel/eval_kernel.py
|
eval_kernel/eval_kernel.py
|
from __future__ import print_function
from jupyter_kernel import MagicKernel
class EvalKernel(MagicKernel):
implementation = 'Eval'
implementation_version = '1.0'
language = 'python'
language_version = '0.1'
banner = "Eval kernel - evaluates simple Python statements and expressions"
env = {}
def get_usage(self):
return "This is a usage statement."
def set_variable(self, name, value):
"""
Set a variable in the kernel language.
"""
self.env[name] = value
def get_variable(self, name):
"""
Get a variable from the kernel language.
"""
return self.env.get(name, None)
def do_execute_direct(self, code):
python_magic = self.line_magics['python']
resp = python_magic.eval(code.strip())
if not resp is None:
self.Print(str(resp))
def get_completions(self, token):
python_magic = self.line_magics['python']
return python_magic.get_completions(token)
def get_kernel_help_on(self, expr, level=0):
python_magic = self.line_magics['python']
return python_magic.get_help_on(expr, level)
if __name__ == '__main__':
from IPython.kernel.zmq.kernelapp import IPKernelApp
IPKernelApp.launch_instance(kernel_class=EvalKernel)
|
from __future__ import print_function
from jupyter_kernel import MagicKernel
class EvalKernel(MagicKernel):
implementation = 'Eval'
implementation_version = '1.0'
language = 'python'
language_version = '0.1'
banner = "Eval kernel - evaluates simple Python statements and expressions"
env = {}
def get_usage(self):
return "This is a usage statement."
def set_variable(self, name, value):
"""
Set a variable in the kernel language.
"""
self.env[name] = value
def get_variable(self, name):
"""
Get a variable from the kernel language.
"""
return self.env.get(name, None)
def do_execute_direct(self, code):
python_magic = self.line_magics['python']
return python_magic.eval(code.strip())
def get_completions(self, token):
python_magic = self.line_magics['python']
return python_magic.get_completions(token)
def get_kernel_help_on(self, expr, level=0):
python_magic = self.line_magics['python']
return python_magic.get_help_on(expr, level)
if __name__ == '__main__':
from IPython.kernel.zmq.kernelapp import IPKernelApp
IPKernelApp.launch_instance(kernel_class=EvalKernel)
|
Return python eval instead of printing it
|
Return python eval instead of printing it
|
Python
|
bsd-3-clause
|
Calysto/metakernel
|
python
|
## Code Before:
from __future__ import print_function
from jupyter_kernel import MagicKernel
class EvalKernel(MagicKernel):
implementation = 'Eval'
implementation_version = '1.0'
language = 'python'
language_version = '0.1'
banner = "Eval kernel - evaluates simple Python statements and expressions"
env = {}
def get_usage(self):
return "This is a usage statement."
def set_variable(self, name, value):
"""
Set a variable in the kernel language.
"""
self.env[name] = value
def get_variable(self, name):
"""
Get a variable from the kernel language.
"""
return self.env.get(name, None)
def do_execute_direct(self, code):
python_magic = self.line_magics['python']
resp = python_magic.eval(code.strip())
if not resp is None:
self.Print(str(resp))
def get_completions(self, token):
python_magic = self.line_magics['python']
return python_magic.get_completions(token)
def get_kernel_help_on(self, expr, level=0):
python_magic = self.line_magics['python']
return python_magic.get_help_on(expr, level)
if __name__ == '__main__':
from IPython.kernel.zmq.kernelapp import IPKernelApp
IPKernelApp.launch_instance(kernel_class=EvalKernel)
## Instruction:
Return python eval instead of printing it
## Code After:
from __future__ import print_function
from jupyter_kernel import MagicKernel
class EvalKernel(MagicKernel):
implementation = 'Eval'
implementation_version = '1.0'
language = 'python'
language_version = '0.1'
banner = "Eval kernel - evaluates simple Python statements and expressions"
env = {}
def get_usage(self):
return "This is a usage statement."
def set_variable(self, name, value):
"""
Set a variable in the kernel language.
"""
self.env[name] = value
def get_variable(self, name):
"""
Get a variable from the kernel language.
"""
return self.env.get(name, None)
def do_execute_direct(self, code):
python_magic = self.line_magics['python']
return python_magic.eval(code.strip())
def get_completions(self, token):
python_magic = self.line_magics['python']
return python_magic.get_completions(token)
def get_kernel_help_on(self, expr, level=0):
python_magic = self.line_magics['python']
return python_magic.get_help_on(expr, level)
if __name__ == '__main__':
from IPython.kernel.zmq.kernelapp import IPKernelApp
IPKernelApp.launch_instance(kernel_class=EvalKernel)
|
...
def do_execute_direct(self, code):
python_magic = self.line_magics['python']
return python_magic.eval(code.strip())
def get_completions(self, token):
python_magic = self.line_magics['python']
...
|
3a7428723c66010dec1d246beb63be371428d3fe
|
qipipe/staging/staging_helpers.py
|
qipipe/staging/staging_helpers.py
|
"""Pipeline utility functions."""
import re
_SSS_REGEX = '(\w+\d{2})/(session\d{2})/(series\d{3})'
"""The subject/session/series regexp pattern."""
def match_session_hierarchy(path):
"""
Matches the subject, session and series names from the given input path.
@param path: the path to match
@return: the matching (subject, session, series) tuple, or None if no match
"""
match = re.search(_SSS_REGEX, path)
if match:
return match.groups()
|
"""Pipeline utility functions."""
import re
from .staging_error import StagingError
_SSS_REGEX = '(\w+\d{2})/(session\d{2})/(series\d{3})'
"""The subject/session/series regexp pattern."""
def match_series_hierarchy(path):
"""
Matches the subject, session and series names from the given input path.
@param path: the path to match
@return: the matching (subject, session, series) tuple, or None if no match
"""
match = re.search(_SSS_REGEX, path)
if match:
return match.groups()
else:
raise StagingError("The path %s does match the subject/session/series pattern" % path)
|
Raise error if no match.
|
Raise error if no match.
|
Python
|
bsd-2-clause
|
ohsu-qin/qipipe
|
python
|
## Code Before:
"""Pipeline utility functions."""
import re
_SSS_REGEX = '(\w+\d{2})/(session\d{2})/(series\d{3})'
"""The subject/session/series regexp pattern."""
def match_session_hierarchy(path):
"""
Matches the subject, session and series names from the given input path.
@param path: the path to match
@return: the matching (subject, session, series) tuple, or None if no match
"""
match = re.search(_SSS_REGEX, path)
if match:
return match.groups()
## Instruction:
Raise error if no match.
## Code After:
"""Pipeline utility functions."""
import re
from .staging_error import StagingError
_SSS_REGEX = '(\w+\d{2})/(session\d{2})/(series\d{3})'
"""The subject/session/series regexp pattern."""
def match_series_hierarchy(path):
"""
Matches the subject, session and series names from the given input path.
@param path: the path to match
@return: the matching (subject, session, series) tuple, or None if no match
"""
match = re.search(_SSS_REGEX, path)
if match:
return match.groups()
else:
raise StagingError("The path %s does match the subject/session/series pattern" % path)
|
...
"""Pipeline utility functions."""
import re
from .staging_error import StagingError
_SSS_REGEX = '(\w+\d{2})/(session\d{2})/(series\d{3})'
"""The subject/session/series regexp pattern."""
def match_series_hierarchy(path):
"""
Matches the subject, session and series names from the given input path.
...
match = re.search(_SSS_REGEX, path)
if match:
return match.groups()
else:
raise StagingError("The path %s does match the subject/session/series pattern" % path)
...
|
556eada791fca84432e36c3e1fcf722ecf0580ff
|
setup.py
|
setup.py
|
from __future__ import absolute_import
from setuptools import setup, find_packages
long_desc = """
Transform Excel spreadsheets
"""
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers for classifiers
conf = dict(
name='databaker',
version='1.2.1',
description="DataBaker, part of QuickCode for ONS",
long_description=long_desc,
classifiers=[
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",
"Operating System :: POSIX :: Linux",
"Operating System :: Microsoft :: Windows",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
],
keywords='',
author='The Sensible Code Company Ltd',
author_email='[email protected]',
url='https://github.com/sensiblecodeio/databaker',
license='AGPL',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
namespace_packages=[],
include_package_data=False,
zip_safe=False,
install_requires=['docopt', 'xypath>=1.1.0', 'xlutils', 'pyhamcrest'],
tests_require=[],
entry_points={},
)
if __name__ == '__main__':
setup(**conf)
|
from setuptools import setup, find_packages
long_desc = """
Transform Excel spreadsheets
"""
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers for classifiers
conf = dict(
name='databaker',
version='1.2.1',
description="DataBaker, part of QuickCode for ONS",
long_description=long_desc,
classifiers=[
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",
"Operating System :: POSIX :: Linux",
"Operating System :: Microsoft :: Windows",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
],
keywords='',
author='The Sensible Code Company Ltd',
author_email='[email protected]',
url='https://github.com/sensiblecodeio/databaker',
license='AGPL',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
namespace_packages=[],
include_package_data=False,
zip_safe=False,
install_requires=['docopt', 'xypath>=1.1.0', 'xlutils', 'pyhamcrest'],
tests_require=[],
entry_points={},
)
if __name__ == '__main__':
setup(**conf)
|
Remove an overlooked from __future__ import
|
Remove an overlooked from __future__ import
|
Python
|
agpl-3.0
|
scraperwiki/databaker,scraperwiki/databaker
|
python
|
## Code Before:
from __future__ import absolute_import
from setuptools import setup, find_packages
long_desc = """
Transform Excel spreadsheets
"""
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers for classifiers
conf = dict(
name='databaker',
version='1.2.1',
description="DataBaker, part of QuickCode for ONS",
long_description=long_desc,
classifiers=[
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",
"Operating System :: POSIX :: Linux",
"Operating System :: Microsoft :: Windows",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
],
keywords='',
author='The Sensible Code Company Ltd',
author_email='[email protected]',
url='https://github.com/sensiblecodeio/databaker',
license='AGPL',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
namespace_packages=[],
include_package_data=False,
zip_safe=False,
install_requires=['docopt', 'xypath>=1.1.0', 'xlutils', 'pyhamcrest'],
tests_require=[],
entry_points={},
)
if __name__ == '__main__':
setup(**conf)
## Instruction:
Remove an overlooked from __future__ import
## Code After:
from setuptools import setup, find_packages
long_desc = """
Transform Excel spreadsheets
"""
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers for classifiers
conf = dict(
name='databaker',
version='1.2.1',
description="DataBaker, part of QuickCode for ONS",
long_description=long_desc,
classifiers=[
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",
"Operating System :: POSIX :: Linux",
"Operating System :: Microsoft :: Windows",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
],
keywords='',
author='The Sensible Code Company Ltd',
author_email='[email protected]',
url='https://github.com/sensiblecodeio/databaker',
license='AGPL',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
namespace_packages=[],
include_package_data=False,
zip_safe=False,
install_requires=['docopt', 'xypath>=1.1.0', 'xlutils', 'pyhamcrest'],
tests_require=[],
entry_points={},
)
if __name__ == '__main__':
setup(**conf)
|
// ... existing code ...
from setuptools import setup, find_packages
long_desc = """
// ... rest of the code ...
|
fa6eef5b544f0cdd1b697f9856b4390303239aa0
|
pwd-service/src/main/java/org/pwd/web/websites/WebsitesController.java
|
pwd-service/src/main/java/org/pwd/web/websites/WebsitesController.java
|
package org.pwd.web.websites;
import org.pwd.domain.websites.Website;
import org.pwd.domain.websites.WebsiteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
/**
* @author bartosz.walacik
*/
@Controller
@RequestMapping("/serwisy")
class WebsitesController {
private WebsiteRepository websiteRepository;
@Autowired
public WebsitesController(WebsiteRepository websiteRepository) {
this.websiteRepository = websiteRepository;
}
@RequestMapping(method = GET)
public String getWebsites(Model model,
@RequestParam(value = "query", required = false) String query) {
model.addAttribute("query", query);
List<Website> websites;
if (StringUtils.isEmpty(query)) {
websites = websiteRepository.search("XYZ"); //websiteRepository.findAll();
} else {
websites = websiteRepository.search(query);
}
model.addAttribute("websites", websites);
model.addAttribute("websitesTotalCount", websiteRepository.count());
model.addAttribute("websitesCount", websites.size());
return "websites";
}
}
|
package org.pwd.web.websites;
import org.pwd.domain.websites.Website;
import org.pwd.domain.websites.WebsiteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
/**
* @author bartosz.walacik
*/
@Controller
@RequestMapping("/serwisy")
class WebsitesController {
private WebsiteRepository websiteRepository;
@Autowired
public WebsitesController(WebsiteRepository websiteRepository) {
this.websiteRepository = websiteRepository;
}
@RequestMapping(method = GET)
public String getWebsites(Model model,
@RequestParam(value = "query", required = false) String query) {
model.addAttribute("query", query);
List<Website> websites;
if (StringUtils.isEmpty(query)) {
websites = websiteRepository.findAll();
} else {
websites = websiteRepository.search(query);
}
model.addAttribute("websites", websites);
model.addAttribute("websitesTotalCount", websiteRepository.count());
model.addAttribute("websitesCount", websites.size());
return "websites";
}
}
|
Revert "Zastąpienie findAll generowaniem pustej listy"
|
Revert "Zastąpienie findAll generowaniem pustej listy"
This reverts commit b28c03003ff556dd56690ba848062505f951476d.
|
Java
|
apache-2.0
|
pwd-project/pwd,pwd-project/pwd,pwd-project/pwd
|
java
|
## Code Before:
package org.pwd.web.websites;
import org.pwd.domain.websites.Website;
import org.pwd.domain.websites.WebsiteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
/**
* @author bartosz.walacik
*/
@Controller
@RequestMapping("/serwisy")
class WebsitesController {
private WebsiteRepository websiteRepository;
@Autowired
public WebsitesController(WebsiteRepository websiteRepository) {
this.websiteRepository = websiteRepository;
}
@RequestMapping(method = GET)
public String getWebsites(Model model,
@RequestParam(value = "query", required = false) String query) {
model.addAttribute("query", query);
List<Website> websites;
if (StringUtils.isEmpty(query)) {
websites = websiteRepository.search("XYZ"); //websiteRepository.findAll();
} else {
websites = websiteRepository.search(query);
}
model.addAttribute("websites", websites);
model.addAttribute("websitesTotalCount", websiteRepository.count());
model.addAttribute("websitesCount", websites.size());
return "websites";
}
}
## Instruction:
Revert "Zastąpienie findAll generowaniem pustej listy"
This reverts commit b28c03003ff556dd56690ba848062505f951476d.
## Code After:
package org.pwd.web.websites;
import org.pwd.domain.websites.Website;
import org.pwd.domain.websites.WebsiteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
/**
* @author bartosz.walacik
*/
@Controller
@RequestMapping("/serwisy")
class WebsitesController {
private WebsiteRepository websiteRepository;
@Autowired
public WebsitesController(WebsiteRepository websiteRepository) {
this.websiteRepository = websiteRepository;
}
@RequestMapping(method = GET)
public String getWebsites(Model model,
@RequestParam(value = "query", required = false) String query) {
model.addAttribute("query", query);
List<Website> websites;
if (StringUtils.isEmpty(query)) {
websites = websiteRepository.findAll();
} else {
websites = websiteRepository.search(query);
}
model.addAttribute("websites", websites);
model.addAttribute("websitesTotalCount", websiteRepository.count());
model.addAttribute("websitesCount", websites.size());
return "websites";
}
}
|
...
List<Website> websites;
if (StringUtils.isEmpty(query)) {
websites = websiteRepository.findAll();
} else {
websites = websiteRepository.search(query);
}
...
|
f2efe5db345ff4ecd1410d668708c0fdb81ccd9d
|
src/main/java/info/sleeplessacorn/nomagi/client/StateMapperNoCTM.java
|
src/main/java/info/sleeplessacorn/nomagi/client/StateMapperNoCTM.java
|
package info.sleeplessacorn.nomagi.client;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.block.statemap.StateMapperBase;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.Loader;
/**
* Used for blocks that implement the Chisel CTM format
*
* When Chisel is not loaded, a secondary blockstate file, with {@code _noctm} appended, is used instead.
*/
public class StateMapperNoCTM extends StateMapperBase {
@Override
protected ModelResourceLocation getModelResourceLocation(IBlockState state) {
ResourceLocation location = state.getBlock().getRegistryName();
if (!Loader.isModLoaded("chisel"))
location = new ResourceLocation(location.getResourceDomain(), location.getResourcePath() + "_noctm");
return new ModelResourceLocation(location, getPropertyString(state.getProperties()));
}
}
|
package info.sleeplessacorn.nomagi.client;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.block.statemap.StateMapperBase;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.Loader;
/**
* Used for blocks that implement the Chisel CTM format
*
* When neither Chisel nor ConnectedTexturesMod are loaded, a secondary blockstate file, with {@code _noctm} appended, is used instead.
*/
public class StateMapperNoCTM extends StateMapperBase {
@Override
protected ModelResourceLocation getModelResourceLocation(IBlockState state) {
ResourceLocation location = state.getBlock().getRegistryName();
if (!Loader.isModLoaded("chisel") || !Loader.isModLoaded("ctm"))
location = new ResourceLocation(location.getResourceDomain(), location.getResourcePath() + "_noctm");
return new ModelResourceLocation(location, getPropertyString(state.getProperties()));
}
}
|
Update CTM statemapper to check for ConnectedTexturesMod
|
Update CTM statemapper to check for ConnectedTexturesMod
|
Java
|
mit
|
SleeplessAcorn/DimensionallyTranscendentalTents
|
java
|
## Code Before:
package info.sleeplessacorn.nomagi.client;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.block.statemap.StateMapperBase;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.Loader;
/**
* Used for blocks that implement the Chisel CTM format
*
* When Chisel is not loaded, a secondary blockstate file, with {@code _noctm} appended, is used instead.
*/
public class StateMapperNoCTM extends StateMapperBase {
@Override
protected ModelResourceLocation getModelResourceLocation(IBlockState state) {
ResourceLocation location = state.getBlock().getRegistryName();
if (!Loader.isModLoaded("chisel"))
location = new ResourceLocation(location.getResourceDomain(), location.getResourcePath() + "_noctm");
return new ModelResourceLocation(location, getPropertyString(state.getProperties()));
}
}
## Instruction:
Update CTM statemapper to check for ConnectedTexturesMod
## Code After:
package info.sleeplessacorn.nomagi.client;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.block.statemap.StateMapperBase;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.Loader;
/**
* Used for blocks that implement the Chisel CTM format
*
* When neither Chisel nor ConnectedTexturesMod are loaded, a secondary blockstate file, with {@code _noctm} appended, is used instead.
*/
public class StateMapperNoCTM extends StateMapperBase {
@Override
protected ModelResourceLocation getModelResourceLocation(IBlockState state) {
ResourceLocation location = state.getBlock().getRegistryName();
if (!Loader.isModLoaded("chisel") || !Loader.isModLoaded("ctm"))
location = new ResourceLocation(location.getResourceDomain(), location.getResourcePath() + "_noctm");
return new ModelResourceLocation(location, getPropertyString(state.getProperties()));
}
}
|
// ... existing code ...
/**
* Used for blocks that implement the Chisel CTM format
*
* When neither Chisel nor ConnectedTexturesMod are loaded, a secondary blockstate file, with {@code _noctm} appended, is used instead.
*/
public class StateMapperNoCTM extends StateMapperBase {
// ... modified code ...
@Override
protected ModelResourceLocation getModelResourceLocation(IBlockState state) {
ResourceLocation location = state.getBlock().getRegistryName();
if (!Loader.isModLoaded("chisel") || !Loader.isModLoaded("ctm"))
location = new ResourceLocation(location.getResourceDomain(), location.getResourcePath() + "_noctm");
return new ModelResourceLocation(location, getPropertyString(state.getProperties()));
// ... rest of the code ...
|
8c6558267aaed531f66b7036ccec0522e746d860
|
src/android/SamsungPassPlugin.java
|
src/android/SamsungPassPlugin.java
|
package com.cordova.plugin.samsung.pass;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import com.samsung.android.sdk.SsdkUnsupportedException;
import com.samsung.android.sdk.pass.Spass;
import com.samsung.android.sdk.pass.SpassFingerprint;
import com.samsung.android.sdk.pass.SpassInvalidStateException;
public class SamsungPassPlugin extends CordovaPlugin {
}
|
package com.cordova.plugin.samsung.pass;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONException;
import android.util.Log;
import com.samsung.android.sdk.SsdkUnsupportedException;
import com.samsung.android.sdk.pass.Spass;
import com.samsung.android.sdk.pass.SpassFingerprint;
import com.samsung.android.sdk.pass.SpassInvalidStateException;
public class SamsungPassPlugin extends CordovaPlugin {
private Spass mSpass;
private SpassFingerprint mSpassFingerprint;
private boolean isFeatureEnabled = false;
private static final String TAG = "SamsungPassPlugin";
@Override
public void initialize(final CordovaInterface cordova, CordovaWebView webView) {
mSpass = new Spass();
try {
mSpass.initialize(this.cordova.getActivity().getApplicationContext());
Log.d(TAG, "Spass was Initialized");
} catch (SsdkUnsupportedException e) {
Log.d(TAG, "Spass could not initialize" + e);
}
isFeatureEnabled = mSpass.isFeatureEnabled(Spass.DEVICE_FINGERPRINT);
if (isFeatureEnabled) {
mSpassFingerprint = new SpassFingerprint(this.cordova.getActivity().getApplicationContext());
Log.d(TAG, "mSpassFingerprint was Initialized");
} else {
Log.d(TAG, "Fingerprint Service is not supported in the device.");
}
}
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
this.callbackContext = callbackContext;
Log.d(TAG, callbackContext.getCallbackId() + ": " + action);
if (action.equals("CheckSamsungPassSupport")) {
this.checkSamsungPassSupport();
}
else {
return false;
}
return true;
}
private void checkSamsungPassSupport() {
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK));
}
}
|
Initialize Spass, add excute function and test method
|
Initialize Spass, add excute function and test method
|
Java
|
mit
|
tabrindle/cordova-plugin-samsungpass,tabrindle/cordova-plugin-samsungpass
|
java
|
## Code Before:
package com.cordova.plugin.samsung.pass;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import com.samsung.android.sdk.SsdkUnsupportedException;
import com.samsung.android.sdk.pass.Spass;
import com.samsung.android.sdk.pass.SpassFingerprint;
import com.samsung.android.sdk.pass.SpassInvalidStateException;
public class SamsungPassPlugin extends CordovaPlugin {
}
## Instruction:
Initialize Spass, add excute function and test method
## Code After:
package com.cordova.plugin.samsung.pass;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONException;
import android.util.Log;
import com.samsung.android.sdk.SsdkUnsupportedException;
import com.samsung.android.sdk.pass.Spass;
import com.samsung.android.sdk.pass.SpassFingerprint;
import com.samsung.android.sdk.pass.SpassInvalidStateException;
public class SamsungPassPlugin extends CordovaPlugin {
private Spass mSpass;
private SpassFingerprint mSpassFingerprint;
private boolean isFeatureEnabled = false;
private static final String TAG = "SamsungPassPlugin";
@Override
public void initialize(final CordovaInterface cordova, CordovaWebView webView) {
mSpass = new Spass();
try {
mSpass.initialize(this.cordova.getActivity().getApplicationContext());
Log.d(TAG, "Spass was Initialized");
} catch (SsdkUnsupportedException e) {
Log.d(TAG, "Spass could not initialize" + e);
}
isFeatureEnabled = mSpass.isFeatureEnabled(Spass.DEVICE_FINGERPRINT);
if (isFeatureEnabled) {
mSpassFingerprint = new SpassFingerprint(this.cordova.getActivity().getApplicationContext());
Log.d(TAG, "mSpassFingerprint was Initialized");
} else {
Log.d(TAG, "Fingerprint Service is not supported in the device.");
}
}
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
this.callbackContext = callbackContext;
Log.d(TAG, callbackContext.getCallbackId() + ": " + action);
if (action.equals("CheckSamsungPassSupport")) {
this.checkSamsungPassSupport();
}
else {
return false;
}
return true;
}
private void checkSamsungPassSupport() {
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK));
}
}
|
// ... existing code ...
package com.cordova.plugin.samsung.pass;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONException;
import android.util.Log;
import com.samsung.android.sdk.SsdkUnsupportedException;
import com.samsung.android.sdk.pass.Spass;
// ... modified code ...
public class SamsungPassPlugin extends CordovaPlugin {
private Spass mSpass;
private SpassFingerprint mSpassFingerprint;
private boolean isFeatureEnabled = false;
private static final String TAG = "SamsungPassPlugin";
@Override
public void initialize(final CordovaInterface cordova, CordovaWebView webView) {
mSpass = new Spass();
try {
mSpass.initialize(this.cordova.getActivity().getApplicationContext());
Log.d(TAG, "Spass was Initialized");
} catch (SsdkUnsupportedException e) {
Log.d(TAG, "Spass could not initialize" + e);
}
isFeatureEnabled = mSpass.isFeatureEnabled(Spass.DEVICE_FINGERPRINT);
if (isFeatureEnabled) {
mSpassFingerprint = new SpassFingerprint(this.cordova.getActivity().getApplicationContext());
Log.d(TAG, "mSpassFingerprint was Initialized");
} else {
Log.d(TAG, "Fingerprint Service is not supported in the device.");
}
}
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
this.callbackContext = callbackContext;
Log.d(TAG, callbackContext.getCallbackId() + ": " + action);
if (action.equals("CheckSamsungPassSupport")) {
this.checkSamsungPassSupport();
}
else {
return false;
}
return true;
}
private void checkSamsungPassSupport() {
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK));
}
}
// ... rest of the code ...
|
12497f0e8eeee48ca4203ee4a193111af784ff34
|
Sources/com/kaviju/accesscontrol/model/KAAccessListItem.java
|
Sources/com/kaviju/accesscontrol/model/KAAccessListItem.java
|
package com.kaviju.accesscontrol.model;
import org.apache.log4j.Logger;
@SuppressWarnings("serial")
public class KAAccessListItem extends com.kaviju.accesscontrol.model.base._KAAccessListItem {
@SuppressWarnings("unused")
private static Logger log = Logger.getLogger(KAAccessListItem.class);
}
|
package com.kaviju.accesscontrol.model;
import org.apache.log4j.Logger;
import com.webobjects.foundation.NSArray;
@SuppressWarnings("serial")
public class KAAccessListItem extends com.kaviju.accesscontrol.model.base._KAAccessListItem {
@SuppressWarnings("unused")
private static Logger log = Logger.getLogger(KAAccessListItem.class);
public NSArray<? extends KAUserProfile>fetchUserProfileWithItemForRole(String roleCode) {
KARole role = KARole.roleWithCode(editingContext(), roleCode);
NSArray<KAUserProfileRole> userProfileRoles = KAUserProfileRole.fetchKAUserProfileRoles(editingContext(), KAUserProfileRole.ROLE.eq(role), null);
userProfileRoles = KAUserProfileRole.LIST_ITEMS.containsObject(this).filtered(userProfileRoles);
return KAUserProfileRole.USER_PROFILE.arrayValueInObject(userProfileRoles);
}
}
|
Add a way to get all the users with a specific role.
|
Add a way to get all the users with a specific role.
|
Java
|
apache-2.0
|
Kaviju/KAAccessControl,Kaviju/KAAccessControl
|
java
|
## Code Before:
package com.kaviju.accesscontrol.model;
import org.apache.log4j.Logger;
@SuppressWarnings("serial")
public class KAAccessListItem extends com.kaviju.accesscontrol.model.base._KAAccessListItem {
@SuppressWarnings("unused")
private static Logger log = Logger.getLogger(KAAccessListItem.class);
}
## Instruction:
Add a way to get all the users with a specific role.
## Code After:
package com.kaviju.accesscontrol.model;
import org.apache.log4j.Logger;
import com.webobjects.foundation.NSArray;
@SuppressWarnings("serial")
public class KAAccessListItem extends com.kaviju.accesscontrol.model.base._KAAccessListItem {
@SuppressWarnings("unused")
private static Logger log = Logger.getLogger(KAAccessListItem.class);
public NSArray<? extends KAUserProfile>fetchUserProfileWithItemForRole(String roleCode) {
KARole role = KARole.roleWithCode(editingContext(), roleCode);
NSArray<KAUserProfileRole> userProfileRoles = KAUserProfileRole.fetchKAUserProfileRoles(editingContext(), KAUserProfileRole.ROLE.eq(role), null);
userProfileRoles = KAUserProfileRole.LIST_ITEMS.containsObject(this).filtered(userProfileRoles);
return KAUserProfileRole.USER_PROFILE.arrayValueInObject(userProfileRoles);
}
}
|
# ... existing code ...
package com.kaviju.accesscontrol.model;
import org.apache.log4j.Logger;
import com.webobjects.foundation.NSArray;
@SuppressWarnings("serial")
public class KAAccessListItem extends com.kaviju.accesscontrol.model.base._KAAccessListItem {
@SuppressWarnings("unused")
private static Logger log = Logger.getLogger(KAAccessListItem.class);
public NSArray<? extends KAUserProfile>fetchUserProfileWithItemForRole(String roleCode) {
KARole role = KARole.roleWithCode(editingContext(), roleCode);
NSArray<KAUserProfileRole> userProfileRoles = KAUserProfileRole.fetchKAUserProfileRoles(editingContext(), KAUserProfileRole.ROLE.eq(role), null);
userProfileRoles = KAUserProfileRole.LIST_ITEMS.containsObject(this).filtered(userProfileRoles);
return KAUserProfileRole.USER_PROFILE.arrayValueInObject(userProfileRoles);
}
}
# ... rest of the code ...
|
1c4ea5e3d584a3344182d41e286ecbb9967d841a
|
src/includes/TritonTypes.h
|
src/includes/TritonTypes.h
|
/*
** Copyright (C) - Triton
**
** This program is under the terms of the LGPLv3 License.
*/
#ifndef TRITONTYPES_H
#define TRITONTYPES_H
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/numeric/conversion/cast.hpp>
#define BIT_MAX 512
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
typedef unsigned long long uint64;
typedef boost::multiprecision::uint128_t uint128;
typedef boost::multiprecision::uint512_t uint512;
typedef signed char sint8;
typedef signed short sint16;
typedef signed int sint32;
typedef signed long long sint64;
typedef boost::multiprecision::int128_t sint128;
typedef boost::multiprecision::int512_t sint512;
#endif /* !TRITONTYPES_H */
|
/*
** Copyright (C) - Triton
**
** This program is under the terms of the LGPLv3 License.
*/
#ifndef TRITONTYPES_H
#define TRITONTYPES_H
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/numeric/conversion/cast.hpp>
#define BIT_MAX 512
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
typedef boost::multiprecision::uint64 _t uint64;
typedef boost::multiprecision::uint128_t uint128;
typedef boost::multiprecision::uint256_t uint256;
typedef boost::multiprecision::uint512_t uint512;
typedef signed char sint8;
typedef signed short sint16;
typedef signed int sint32;
typedef boost::multiprecision::int64 _t sint64;
typedef boost::multiprecision::int128_t sint128;
typedef boost::multiprecision::int256_t sint256;
typedef boost::multiprecision::int512_t sint512;
#endif /* !TRITONTYPES_H */
|
Use boost multiprecision even for 64b
|
Use boost multiprecision even for 64b
|
C
|
apache-2.0
|
JonathanSalwan/Triton,JonathanSalwan/Triton,JonathanSalwan/Triton,JonathanSalwan/Triton,JonathanSalwan/Triton
|
c
|
## Code Before:
/*
** Copyright (C) - Triton
**
** This program is under the terms of the LGPLv3 License.
*/
#ifndef TRITONTYPES_H
#define TRITONTYPES_H
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/numeric/conversion/cast.hpp>
#define BIT_MAX 512
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
typedef unsigned long long uint64;
typedef boost::multiprecision::uint128_t uint128;
typedef boost::multiprecision::uint512_t uint512;
typedef signed char sint8;
typedef signed short sint16;
typedef signed int sint32;
typedef signed long long sint64;
typedef boost::multiprecision::int128_t sint128;
typedef boost::multiprecision::int512_t sint512;
#endif /* !TRITONTYPES_H */
## Instruction:
Use boost multiprecision even for 64b
## Code After:
/*
** Copyright (C) - Triton
**
** This program is under the terms of the LGPLv3 License.
*/
#ifndef TRITONTYPES_H
#define TRITONTYPES_H
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/numeric/conversion/cast.hpp>
#define BIT_MAX 512
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
typedef boost::multiprecision::uint64 _t uint64;
typedef boost::multiprecision::uint128_t uint128;
typedef boost::multiprecision::uint256_t uint256;
typedef boost::multiprecision::uint512_t uint512;
typedef signed char sint8;
typedef signed short sint16;
typedef signed int sint32;
typedef boost::multiprecision::int64 _t sint64;
typedef boost::multiprecision::int128_t sint128;
typedef boost::multiprecision::int256_t sint256;
typedef boost::multiprecision::int512_t sint512;
#endif /* !TRITONTYPES_H */
|
// ... existing code ...
#ifndef TRITONTYPES_H
#define TRITONTYPES_H
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/numeric/conversion/cast.hpp>
#define BIT_MAX 512
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
typedef boost::multiprecision::uint64 _t uint64;
typedef boost::multiprecision::uint128_t uint128;
typedef boost::multiprecision::uint256_t uint256;
typedef boost::multiprecision::uint512_t uint512;
typedef signed char sint8;
typedef signed short sint16;
typedef signed int sint32;
typedef boost::multiprecision::int64 _t sint64;
typedef boost::multiprecision::int128_t sint128;
typedef boost::multiprecision::int256_t sint256;
typedef boost::multiprecision::int512_t sint512;
#endif /* !TRITONTYPES_H */
// ... rest of the code ...
|
f0ed976786c79e54ce421fe76b27e3d8d22763ec
|
src/main/java/uk/co/todddavies/website/blog/BlogPostServletModule.java
|
src/main/java/uk/co/todddavies/website/blog/BlogPostServletModule.java
|
package uk.co.todddavies.website.blog;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.template.soy.jbcsrc.api.SoySauce;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Singleton
final class BlogPostServletModule extends HttpServlet {
static final ImmutableMap<String, String> PATH_MAP = ImmutableMap.of(
"how-to-pull", "howToPull",
"starting-a-blog", "startingABlog"
);
private final SoySauce soySauce;
@Inject
private BlogPostServletModule(SoySauce soySauce) {
this.soySauce = soySauce;
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String postPath = request.getPathInfo();
if (postPath.startsWith("/")) {
postPath = postPath.substring(1);
}
response.getWriter().print(
soySauce
.renderTemplate("todddavies.website.blog." + PATH_MAP.get(postPath))
.renderHtml().get().getContent());
}
}
|
package uk.co.todddavies.website.blog;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.template.soy.jbcsrc.api.SoySauce;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Singleton
final class BlogPostServletModule extends HttpServlet {
static final ImmutableMap<String, String> PATH_MAP = ImmutableMap.of(
"how-to-pull", "howToPull",
"starting-a-blog", "startingABlog"
);
private final SoySauce soySauce;
@Inject
private BlogPostServletModule(SoySauce soySauce) {
this.soySauce = soySauce;
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String postPath = request.getPathInfo();
if (postPath.startsWith("/")) {
postPath = postPath.substring(1);
}
if (!PATH_MAP.containsKey(postPath)) {
response.sendError(404, String.format("Post '%s' not found.", postPath));
return;
}
response.getWriter().print(
soySauce
.renderTemplate("todddavies.website.blog." + PATH_MAP.get(postPath))
.renderHtml().get().getContent());
}
}
|
Return a 404 response when a blog post isn't found.
|
Return a 404 response when a blog post isn't found.
|
Java
|
apache-2.0
|
Todd-Davies/appengine-website,Todd-Davies/appengine-website,Todd-Davies/appengine-website
|
java
|
## Code Before:
package uk.co.todddavies.website.blog;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.template.soy.jbcsrc.api.SoySauce;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Singleton
final class BlogPostServletModule extends HttpServlet {
static final ImmutableMap<String, String> PATH_MAP = ImmutableMap.of(
"how-to-pull", "howToPull",
"starting-a-blog", "startingABlog"
);
private final SoySauce soySauce;
@Inject
private BlogPostServletModule(SoySauce soySauce) {
this.soySauce = soySauce;
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String postPath = request.getPathInfo();
if (postPath.startsWith("/")) {
postPath = postPath.substring(1);
}
response.getWriter().print(
soySauce
.renderTemplate("todddavies.website.blog." + PATH_MAP.get(postPath))
.renderHtml().get().getContent());
}
}
## Instruction:
Return a 404 response when a blog post isn't found.
## Code After:
package uk.co.todddavies.website.blog;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.template.soy.jbcsrc.api.SoySauce;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Singleton
final class BlogPostServletModule extends HttpServlet {
static final ImmutableMap<String, String> PATH_MAP = ImmutableMap.of(
"how-to-pull", "howToPull",
"starting-a-blog", "startingABlog"
);
private final SoySauce soySauce;
@Inject
private BlogPostServletModule(SoySauce soySauce) {
this.soySauce = soySauce;
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String postPath = request.getPathInfo();
if (postPath.startsWith("/")) {
postPath = postPath.substring(1);
}
if (!PATH_MAP.containsKey(postPath)) {
response.sendError(404, String.format("Post '%s' not found.", postPath));
return;
}
response.getWriter().print(
soySauce
.renderTemplate("todddavies.website.blog." + PATH_MAP.get(postPath))
.renderHtml().get().getContent());
}
}
|
// ... existing code ...
postPath = postPath.substring(1);
}
if (!PATH_MAP.containsKey(postPath)) {
response.sendError(404, String.format("Post '%s' not found.", postPath));
return;
}
response.getWriter().print(
soySauce
.renderTemplate("todddavies.website.blog." + PATH_MAP.get(postPath))
// ... rest of the code ...
|
ad55d04d6688f75f0e441603668e0337a0333d76
|
tests/test_validate.py
|
tests/test_validate.py
|
import pytest
from marshmallow import validate, ValidationError
def test_invalid_email():
invalid1 = "user@example"
with pytest.raises(ValidationError):
validate.email(invalid1)
invalid2 = "example.com"
with pytest.raises(ValidationError):
validate.email(invalid2)
invalid3 = "user"
with pytest.raises(ValidationError):
validate.email(invalid3)
with pytest.raises(ValidationError):
validate.email('@nouser.com')
def test_validate_email_none():
assert validate.email(None) is None
def test_validate_url_none():
assert validate.url(None) is None
|
import pytest
from marshmallow import validate, ValidationError
def test_invalid_email():
invalid1 = "user@example"
with pytest.raises(ValidationError):
validate.email(invalid1)
invalid2 = "example.com"
with pytest.raises(ValidationError):
validate.email(invalid2)
invalid3 = "user"
with pytest.raises(ValidationError):
validate.email(invalid3)
with pytest.raises(ValidationError):
validate.email('@nouser.com')
def test_validate_email_none():
assert validate.email(None) is None
def test_validate_url_none():
assert validate.url(None) is None
def test_min_length():
with pytest.raises(ValidationError):
validate.length('foo', 4, 5)
assert validate.length('foo', 3, 5) == 'foo'
with pytest.raises(ValidationError):
validate.length([1, 2, 3], 4, 5)
assert validate.length([1, 2, 3], 3, 5) == [1, 2, 3]
with pytest.raises(ValidationError):
validate.length('foo', 5)
def test_max_length():
with pytest.raises(ValidationError):
validate.length('foo', 1, 2)
assert validate.length('foo', 1, 3) == 'foo'
with pytest.raises(ValidationError):
validate.length([1, 2, 3], 1, 2)
assert validate.length([1, 2, 3], 1, 3) == [1, 2, 3]
with pytest.raises(ValidationError):
validate.length('foo', None, 2)
def test_validate_length_none():
assert validate.length(None) is None
|
Add length validator unit tests
|
Add length validator unit tests
|
Python
|
mit
|
maximkulkin/marshmallow,0xDCA/marshmallow,Tim-Erwin/marshmallow,xLegoz/marshmallow,marshmallow-code/marshmallow,VladimirPal/marshmallow,0xDCA/marshmallow,daniloakamine/marshmallow,dwieeb/marshmallow,mwstobo/marshmallow,quxiaolong1504/marshmallow,etataurov/marshmallow,Bachmann1234/marshmallow,bartaelterman/marshmallow
|
python
|
## Code Before:
import pytest
from marshmallow import validate, ValidationError
def test_invalid_email():
invalid1 = "user@example"
with pytest.raises(ValidationError):
validate.email(invalid1)
invalid2 = "example.com"
with pytest.raises(ValidationError):
validate.email(invalid2)
invalid3 = "user"
with pytest.raises(ValidationError):
validate.email(invalid3)
with pytest.raises(ValidationError):
validate.email('@nouser.com')
def test_validate_email_none():
assert validate.email(None) is None
def test_validate_url_none():
assert validate.url(None) is None
## Instruction:
Add length validator unit tests
## Code After:
import pytest
from marshmallow import validate, ValidationError
def test_invalid_email():
invalid1 = "user@example"
with pytest.raises(ValidationError):
validate.email(invalid1)
invalid2 = "example.com"
with pytest.raises(ValidationError):
validate.email(invalid2)
invalid3 = "user"
with pytest.raises(ValidationError):
validate.email(invalid3)
with pytest.raises(ValidationError):
validate.email('@nouser.com')
def test_validate_email_none():
assert validate.email(None) is None
def test_validate_url_none():
assert validate.url(None) is None
def test_min_length():
with pytest.raises(ValidationError):
validate.length('foo', 4, 5)
assert validate.length('foo', 3, 5) == 'foo'
with pytest.raises(ValidationError):
validate.length([1, 2, 3], 4, 5)
assert validate.length([1, 2, 3], 3, 5) == [1, 2, 3]
with pytest.raises(ValidationError):
validate.length('foo', 5)
def test_max_length():
with pytest.raises(ValidationError):
validate.length('foo', 1, 2)
assert validate.length('foo', 1, 3) == 'foo'
with pytest.raises(ValidationError):
validate.length([1, 2, 3], 1, 2)
assert validate.length([1, 2, 3], 1, 3) == [1, 2, 3]
with pytest.raises(ValidationError):
validate.length('foo', None, 2)
def test_validate_length_none():
assert validate.length(None) is None
|
// ... existing code ...
def test_validate_url_none():
assert validate.url(None) is None
def test_min_length():
with pytest.raises(ValidationError):
validate.length('foo', 4, 5)
assert validate.length('foo', 3, 5) == 'foo'
with pytest.raises(ValidationError):
validate.length([1, 2, 3], 4, 5)
assert validate.length([1, 2, 3], 3, 5) == [1, 2, 3]
with pytest.raises(ValidationError):
validate.length('foo', 5)
def test_max_length():
with pytest.raises(ValidationError):
validate.length('foo', 1, 2)
assert validate.length('foo', 1, 3) == 'foo'
with pytest.raises(ValidationError):
validate.length([1, 2, 3], 1, 2)
assert validate.length([1, 2, 3], 1, 3) == [1, 2, 3]
with pytest.raises(ValidationError):
validate.length('foo', None, 2)
def test_validate_length_none():
assert validate.length(None) is None
// ... rest of the code ...
|
21dbb8af7412c04b768a9d68e1f8566786d5100c
|
mdot_rest/serializers.py
|
mdot_rest/serializers.py
|
from .models import Resource, ResourceLink, IntendedAudience
from rest_framework import serializers
class ResourceLinkSerializer(serializers.ModelSerializer):
class Meta:
model = ResourceLink
fields = ('link_type', 'url',)
class IntendedAudienceSerializer(serializers.ModelSerializer):
class Meta:
model = IntendedAudience
fields = ('audience',)
class ResourceSerializer(serializers.ModelSerializer):
resource_links = ResourceLinkSerializer(many=True, read_only=True)
intended_audiences = IntendedAudienceSerializer(many=True, read_only=True)
class Meta:
model = Resource
fields = (
'id',
'title',
'feature_desc',
'featured',
'accessible',
'responsive_web',
'resource_links',
'intended_audiences',
'campus_bothell',
'campus_tacoma',
'campus_seattle',
'created_date',
'last_modified',
)
|
from .models import Resource, ResourceLink, IntendedAudience
from rest_framework import serializers
class ResourceLinkSerializer(serializers.ModelSerializer):
class Meta:
model = ResourceLink
fields = ('link_type', 'url',)
class IntendedAudienceSerializer(serializers.ModelSerializer):
class Meta:
model = IntendedAudience
fields = ('audience',)
class ResourceSerializer(serializers.ModelSerializer):
resource_links = ResourceLinkSerializer(many=True, read_only=True)
intended_audiences = IntendedAudienceSerializer(many=True, read_only=True)
class Meta:
model = Resource
fields = (
'id',
'title',
'feature_desc',
'image',
'featured',
'accessible',
'responsive_web',
'resource_links',
'intended_audiences',
'campus_bothell',
'campus_tacoma',
'campus_seattle',
'created_date',
'last_modified',
)
|
Add image field to the resource serialization.
|
Add image field to the resource serialization.
|
Python
|
apache-2.0
|
uw-it-aca/mdot-rest,uw-it-aca/mdot-rest
|
python
|
## Code Before:
from .models import Resource, ResourceLink, IntendedAudience
from rest_framework import serializers
class ResourceLinkSerializer(serializers.ModelSerializer):
class Meta:
model = ResourceLink
fields = ('link_type', 'url',)
class IntendedAudienceSerializer(serializers.ModelSerializer):
class Meta:
model = IntendedAudience
fields = ('audience',)
class ResourceSerializer(serializers.ModelSerializer):
resource_links = ResourceLinkSerializer(many=True, read_only=True)
intended_audiences = IntendedAudienceSerializer(many=True, read_only=True)
class Meta:
model = Resource
fields = (
'id',
'title',
'feature_desc',
'featured',
'accessible',
'responsive_web',
'resource_links',
'intended_audiences',
'campus_bothell',
'campus_tacoma',
'campus_seattle',
'created_date',
'last_modified',
)
## Instruction:
Add image field to the resource serialization.
## Code After:
from .models import Resource, ResourceLink, IntendedAudience
from rest_framework import serializers
class ResourceLinkSerializer(serializers.ModelSerializer):
class Meta:
model = ResourceLink
fields = ('link_type', 'url',)
class IntendedAudienceSerializer(serializers.ModelSerializer):
class Meta:
model = IntendedAudience
fields = ('audience',)
class ResourceSerializer(serializers.ModelSerializer):
resource_links = ResourceLinkSerializer(many=True, read_only=True)
intended_audiences = IntendedAudienceSerializer(many=True, read_only=True)
class Meta:
model = Resource
fields = (
'id',
'title',
'feature_desc',
'image',
'featured',
'accessible',
'responsive_web',
'resource_links',
'intended_audiences',
'campus_bothell',
'campus_tacoma',
'campus_seattle',
'created_date',
'last_modified',
)
|
// ... existing code ...
'id',
'title',
'feature_desc',
'image',
'featured',
'accessible',
'responsive_web',
// ... rest of the code ...
|
20f0d90f5c64322864ad5fda4b4c9314e6c1cb11
|
run.py
|
run.py
|
import sys
from kitchen.text.converters import getwriter
from utils.log import getLogger, open_log, close_log
from utils.misc import output_exception
from system.factory_manager import Manager
sys.stdout = getwriter('utf-8')(sys.stdout)
sys.stderr = getwriter('utf-8')(sys.stderr)
open_log("output.log")
logger = getLogger("System")
logger.info("Starting up..")
try:
manager = Manager()
except Exception:
logger.critical("Runtime error - process cannot continue!")
output_exception(logger)
finally:
close_log("output.log")
try:
raw_input("Press enter to exit.")
except:
pass
|
import os
import sys
from kitchen.text.converters import getwriter
from utils.log import getLogger, open_log, close_log
from utils.misc import output_exception
from system.factory_manager import Manager
sys.stdout = getwriter('utf-8')(sys.stdout)
sys.stderr = getwriter('utf-8')(sys.stderr)
if not os.path.exists("logs"):
os.mkdir("logs")
open_log("output.log")
logger = getLogger("System")
logger.info("Starting up..")
try:
manager = Manager()
except Exception:
logger.critical("Runtime error - process cannot continue!")
output_exception(logger)
finally:
close_log("output.log")
try:
raw_input("Press enter to exit.")
except:
pass
|
Create logs folder if it doesn't exist (to prevent errors)
|
Create logs folder if it doesn't exist (to prevent errors)
|
Python
|
artistic-2.0
|
UltrosBot/Ultros,UltrosBot/Ultros
|
python
|
## Code Before:
import sys
from kitchen.text.converters import getwriter
from utils.log import getLogger, open_log, close_log
from utils.misc import output_exception
from system.factory_manager import Manager
sys.stdout = getwriter('utf-8')(sys.stdout)
sys.stderr = getwriter('utf-8')(sys.stderr)
open_log("output.log")
logger = getLogger("System")
logger.info("Starting up..")
try:
manager = Manager()
except Exception:
logger.critical("Runtime error - process cannot continue!")
output_exception(logger)
finally:
close_log("output.log")
try:
raw_input("Press enter to exit.")
except:
pass
## Instruction:
Create logs folder if it doesn't exist (to prevent errors)
## Code After:
import os
import sys
from kitchen.text.converters import getwriter
from utils.log import getLogger, open_log, close_log
from utils.misc import output_exception
from system.factory_manager import Manager
sys.stdout = getwriter('utf-8')(sys.stdout)
sys.stderr = getwriter('utf-8')(sys.stderr)
if not os.path.exists("logs"):
os.mkdir("logs")
open_log("output.log")
logger = getLogger("System")
logger.info("Starting up..")
try:
manager = Manager()
except Exception:
logger.critical("Runtime error - process cannot continue!")
output_exception(logger)
finally:
close_log("output.log")
try:
raw_input("Press enter to exit.")
except:
pass
|
// ... existing code ...
import os
import sys
from kitchen.text.converters import getwriter
// ... modified code ...
sys.stdout = getwriter('utf-8')(sys.stdout)
sys.stderr = getwriter('utf-8')(sys.stderr)
if not os.path.exists("logs"):
os.mkdir("logs")
open_log("output.log")
// ... rest of the code ...
|
5487126bfc3c4fd16243b9c7e00b204f2f8d7374
|
tests/test_znc.py
|
tests/test_znc.py
|
def test_service_running(Service):
service = Service('znc')
assert service.is_running
def test_socket_listening(Socket):
socket = Socket('tcp://127.0.0.1:6666')
assert socket.is_listening
|
from testinfra.utils.ansible_runner import AnsibleRunner
testinfra_hosts = AnsibleRunner('.molecule/ansible_inventory').get_hosts('all')
def test_service_enabled(Service):
service = Service('znc')
assert service.is_enabled
def test_service_running(Service):
service = Service('znc')
assert service.is_running
def test_socket_listening_ipv4(Socket):
socket = Socket('tcp://0.0.0.0:6666')
assert socket.is_listening
def test_socket_listening_ipv6(Socket):
socket = Socket('tcp://:::6666')
assert not socket.is_listening
|
Tweak the infratest a bit
|
Tweak the infratest a bit
|
Python
|
mit
|
triplepoint/ansible-znc
|
python
|
## Code Before:
def test_service_running(Service):
service = Service('znc')
assert service.is_running
def test_socket_listening(Socket):
socket = Socket('tcp://127.0.0.1:6666')
assert socket.is_listening
## Instruction:
Tweak the infratest a bit
## Code After:
from testinfra.utils.ansible_runner import AnsibleRunner
testinfra_hosts = AnsibleRunner('.molecule/ansible_inventory').get_hosts('all')
def test_service_enabled(Service):
service = Service('znc')
assert service.is_enabled
def test_service_running(Service):
service = Service('znc')
assert service.is_running
def test_socket_listening_ipv4(Socket):
socket = Socket('tcp://0.0.0.0:6666')
assert socket.is_listening
def test_socket_listening_ipv6(Socket):
socket = Socket('tcp://:::6666')
assert not socket.is_listening
|
// ... existing code ...
from testinfra.utils.ansible_runner import AnsibleRunner
testinfra_hosts = AnsibleRunner('.molecule/ansible_inventory').get_hosts('all')
def test_service_enabled(Service):
service = Service('znc')
assert service.is_enabled
def test_service_running(Service):
service = Service('znc')
assert service.is_running
def test_socket_listening_ipv4(Socket):
socket = Socket('tcp://0.0.0.0:6666')
assert socket.is_listening
def test_socket_listening_ipv6(Socket):
socket = Socket('tcp://:::6666')
assert not socket.is_listening
// ... rest of the code ...
|
aecb8ad6cbb8da11712704ac2d229ab3ce3dfcb4
|
test/test/com/maderilo/stringCalculator/StringCalculatorTest.java
|
test/test/com/maderilo/stringCalculator/StringCalculatorTest.java
|
package test.com.maderilo.stringCalculator;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.maderilo.stringCalculator.StringCalculator;
public class StringCalculatorTest {
@Test
public void should_return_0_for_empty_string() throws Exception {
String input = "";
int result = StringCalculator.Add(input);
assertEquals(0, result);
}
@Test
public void should_return_number_for_1number_string() throws Exception {
String input = "12";
int result = StringCalculator.Add(input);
assertEquals(12, result);
}
@Test
public void should_return_sum_for_2number_comma_string() throws Exception {
String input = "12,2";
int result = StringCalculator.Add(input);
assertEquals(14, result);
}
}
|
package test.com.maderilo.stringCalculator;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.maderilo.stringCalculator.StringCalculator;
public class StringCalculatorTest {
@Test
public void should_return_0_for_empty_string() throws Exception {
String input = "";
int result = StringCalculator.Add(input);
assertEquals(0, result);
}
@Test
public void should_return_number_for_1number_string() throws Exception {
String input = "12";
int result = StringCalculator.Add(input);
assertEquals(12, result);
}
@Test
public void should_return_sum_for_more_than_1number_comma_string() throws Exception {
String input = "12,2,3,5";
int result = StringCalculator.Add(input);
assertEquals(22, result);
}
}
|
Add method allowed to handle an unknown amount of numbers
|
Add method allowed to handle an unknown amount of numbers
|
Java
|
mit
|
maderilo/TDDStringCalculator
|
java
|
## Code Before:
package test.com.maderilo.stringCalculator;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.maderilo.stringCalculator.StringCalculator;
public class StringCalculatorTest {
@Test
public void should_return_0_for_empty_string() throws Exception {
String input = "";
int result = StringCalculator.Add(input);
assertEquals(0, result);
}
@Test
public void should_return_number_for_1number_string() throws Exception {
String input = "12";
int result = StringCalculator.Add(input);
assertEquals(12, result);
}
@Test
public void should_return_sum_for_2number_comma_string() throws Exception {
String input = "12,2";
int result = StringCalculator.Add(input);
assertEquals(14, result);
}
}
## Instruction:
Add method allowed to handle an unknown amount of numbers
## Code After:
package test.com.maderilo.stringCalculator;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.maderilo.stringCalculator.StringCalculator;
public class StringCalculatorTest {
@Test
public void should_return_0_for_empty_string() throws Exception {
String input = "";
int result = StringCalculator.Add(input);
assertEquals(0, result);
}
@Test
public void should_return_number_for_1number_string() throws Exception {
String input = "12";
int result = StringCalculator.Add(input);
assertEquals(12, result);
}
@Test
public void should_return_sum_for_more_than_1number_comma_string() throws Exception {
String input = "12,2,3,5";
int result = StringCalculator.Add(input);
assertEquals(22, result);
}
}
|
// ... existing code ...
@Test
public void should_return_sum_for_more_than_1number_comma_string() throws Exception {
String input = "12,2,3,5";
int result = StringCalculator.Add(input);
assertEquals(22, result);
}
}
// ... rest of the code ...
|
1e55d82bee4360608d5053ac05c8a62f57d72bf7
|
erpnext_ebay/custom_methods/website_slideshow_methods.py
|
erpnext_ebay/custom_methods/website_slideshow_methods.py
|
"""Custom methods for Item doctype"""
import frappe
def website_slideshow_validate(doc, _method):
"""On Website Slideshow validate docevent."""
if doc.number_of_ebay_images > 12:
frappe.throw('Number of eBay images must be 12 or fewer!')
if doc.number_of_ebay_images < 1:
frappe.throw('Number of eBay images must be 1 or greater!')
|
"""Custom methods for Item doctype"""
import frappe
MAX_EBAY_IMAGES = 12
def website_slideshow_validate(doc, _method):
"""On Website Slideshow validate docevent."""
if doc.number_of_ebay_images > MAX_EBAY_IMAGES:
frappe.throw(
f'Number of eBay images must be {MAX_EBAY_IMAGES} or fewer!')
if doc.number_of_ebay_images < 1:
frappe.throw('Number of eBay images must be 1 or greater!')
|
Use parameter for maximum number of eBay images
|
fix: Use parameter for maximum number of eBay images
|
Python
|
mit
|
bglazier/erpnext_ebay,bglazier/erpnext_ebay
|
python
|
## Code Before:
"""Custom methods for Item doctype"""
import frappe
def website_slideshow_validate(doc, _method):
"""On Website Slideshow validate docevent."""
if doc.number_of_ebay_images > 12:
frappe.throw('Number of eBay images must be 12 or fewer!')
if doc.number_of_ebay_images < 1:
frappe.throw('Number of eBay images must be 1 or greater!')
## Instruction:
fix: Use parameter for maximum number of eBay images
## Code After:
"""Custom methods for Item doctype"""
import frappe
MAX_EBAY_IMAGES = 12
def website_slideshow_validate(doc, _method):
"""On Website Slideshow validate docevent."""
if doc.number_of_ebay_images > MAX_EBAY_IMAGES:
frappe.throw(
f'Number of eBay images must be {MAX_EBAY_IMAGES} or fewer!')
if doc.number_of_ebay_images < 1:
frappe.throw('Number of eBay images must be 1 or greater!')
|
# ... existing code ...
"""Custom methods for Item doctype"""
import frappe
MAX_EBAY_IMAGES = 12
def website_slideshow_validate(doc, _method):
"""On Website Slideshow validate docevent."""
if doc.number_of_ebay_images > MAX_EBAY_IMAGES:
frappe.throw(
f'Number of eBay images must be {MAX_EBAY_IMAGES} or fewer!')
if doc.number_of_ebay_images < 1:
frappe.throw('Number of eBay images must be 1 or greater!')
# ... rest of the code ...
|
4e9dfbaff5a91af75e3b18e6b4e06379747c6083
|
research_pyutils/__init__.py
|
research_pyutils/__init__.py
|
from .path_related import (mkdir_p, rm_if_exists, remove_empty_paths,
copy_contents_of_folder, count_files,
copy_the_previous_if_missing,
folders_last_modification)
try:
from .menpo_related import (resize_all_images, from_ln_to_bb_path,
process_lns_path, compute_overlap,
rasterize_all_lns, flip_images)
except ImportError:
m1 = ('The menpo related utils are not imported. If '
'you intended to use them please check your '
'menpo installation.')
print(m1)
from .filenames_changes import (rename_files, change_suffix,
strip_filenames)
from .auxiliary import (execution_stats, compare_python_types,
whoami, populate_visual_options)
|
from .path_related import (mkdir_p, rm_if_exists, remove_empty_paths,
copy_contents_of_folder, count_files,
copy_the_previous_if_missing,
folders_last_modification)
try:
from .menpo_related import (resize_all_images, from_ln_to_bb_path,
process_lns_path, compute_overlap,
rasterize_all_lns, flip_images,
check_if_greyscale_values)
except ImportError:
m1 = ('The menpo related utils are not imported. If '
'you intended to use them please check your '
'menpo installation.')
print(m1)
from .filenames_changes import (rename_files, change_suffix,
strip_filenames)
from .auxiliary import (execution_stats, compare_python_types,
whoami, populate_visual_options)
|
Add in the init the newly introduced function
|
Add in the init the newly introduced function
|
Python
|
apache-2.0
|
grigorisg9gr/pyutils,grigorisg9gr/pyutils
|
python
|
## Code Before:
from .path_related import (mkdir_p, rm_if_exists, remove_empty_paths,
copy_contents_of_folder, count_files,
copy_the_previous_if_missing,
folders_last_modification)
try:
from .menpo_related import (resize_all_images, from_ln_to_bb_path,
process_lns_path, compute_overlap,
rasterize_all_lns, flip_images)
except ImportError:
m1 = ('The menpo related utils are not imported. If '
'you intended to use them please check your '
'menpo installation.')
print(m1)
from .filenames_changes import (rename_files, change_suffix,
strip_filenames)
from .auxiliary import (execution_stats, compare_python_types,
whoami, populate_visual_options)
## Instruction:
Add in the init the newly introduced function
## Code After:
from .path_related import (mkdir_p, rm_if_exists, remove_empty_paths,
copy_contents_of_folder, count_files,
copy_the_previous_if_missing,
folders_last_modification)
try:
from .menpo_related import (resize_all_images, from_ln_to_bb_path,
process_lns_path, compute_overlap,
rasterize_all_lns, flip_images,
check_if_greyscale_values)
except ImportError:
m1 = ('The menpo related utils are not imported. If '
'you intended to use them please check your '
'menpo installation.')
print(m1)
from .filenames_changes import (rename_files, change_suffix,
strip_filenames)
from .auxiliary import (execution_stats, compare_python_types,
whoami, populate_visual_options)
|
// ... existing code ...
try:
from .menpo_related import (resize_all_images, from_ln_to_bb_path,
process_lns_path, compute_overlap,
rasterize_all_lns, flip_images,
check_if_greyscale_values)
except ImportError:
m1 = ('The menpo related utils are not imported. If '
'you intended to use them please check your '
// ... rest of the code ...
|
ed5dcd72b661878913be224d641c5595c73ef049
|
tests/test_auditory.py
|
tests/test_auditory.py
|
from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
squeeze_me=True)
envelope = mat['unfiltered_env']
target = mat['lp_filtered_env']
filtered_envelope = aud.lowpass_env_filtering(envelope, 150., 1, 22050.)
assert_allclose(filtered_envelope, target, atol=1e-7)
|
from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
squeeze_me=True)
envelope = mat['unfiltered_env']
target = mat['lp_filtered_env']
filtered_envelope = aud.lowpass_env_filtering(envelope, 150., 1, 22050.)
assert_allclose(filtered_envelope, target, atol=1e-7)
def test_erb():
bw = aud.erbbw(1000)
assert_allclose(bw, 132.63, rtol=1e-4)
|
Test of the erb calculation
|
Test of the erb calculation
|
Python
|
bsd-3-clause
|
achabotl/pambox
|
python
|
## Code Before:
from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
squeeze_me=True)
envelope = mat['unfiltered_env']
target = mat['lp_filtered_env']
filtered_envelope = aud.lowpass_env_filtering(envelope, 150., 1, 22050.)
assert_allclose(filtered_envelope, target, atol=1e-7)
## Instruction:
Test of the erb calculation
## Code After:
from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
squeeze_me=True)
envelope = mat['unfiltered_env']
target = mat['lp_filtered_env']
filtered_envelope = aud.lowpass_env_filtering(envelope, 150., 1, 22050.)
assert_allclose(filtered_envelope, target, atol=1e-7)
def test_erb():
bw = aud.erbbw(1000)
assert_allclose(bw, 132.63, rtol=1e-4)
|
...
assert_allclose(filtered_envelope, target, atol=1e-7)
def test_erb():
bw = aud.erbbw(1000)
assert_allclose(bw, 132.63, rtol=1e-4)
...
|
498e23919b09bfd782da4bb52f19f7c21aa14277
|
plantcv/plantcv/color_palette.py
|
plantcv/plantcv/color_palette.py
|
import numpy as np
from plantcv.plantcv import params
def color_palette(num):
"""color_palette: Returns a list of colors length num
Inputs:
num = number of colors to return.
Returns:
colors = a list of color lists (RGB values)
:param num: int
:return colors: list
"""
from matplotlib import pyplot as plt
# If a previous palette is saved, return it
if params.saved_color_scale is not None:
return params.saved_color_scale
else:
# Retrieve the matplotlib colormap
cmap = plt.get_cmap(params.color_scale)
# Get num evenly spaced colors
colors = cmap(np.linspace(0, 1, num), bytes=True)
colors = colors[:, 0:3].tolist()
# colors are sequential, if params.color_sequence is random then shuffle the colors
if params.color_sequence == "random":
np.random.shuffle(colors)
# Save the color scale for further use
params.saved_color_scale = colors
return colors
|
from matplotlib import pyplot as plt
import numpy as np
from plantcv.plantcv import params
def color_palette(num):
"""color_palette: Returns a list of colors length num
Inputs:
num = number of colors to return.
Returns:
colors = a list of color lists (RGB values)
:param num: int
:return colors: list
"""
# If a previous palette is saved, return it
if params.saved_color_scale is not None:
return params.saved_color_scale
else:
# Retrieve the matplotlib colormap
cmap = plt.get_cmap(params.color_scale)
# Get num evenly spaced colors
colors = cmap(np.linspace(0, 1, num), bytes=True)
colors = colors[:, 0:3].tolist()
# colors are sequential, if params.color_sequence is random then shuffle the colors
if params.color_sequence == "random":
np.random.shuffle(colors)
# Save the color scale for further use
params.saved_color_scale = colors
return colors
|
Move import back to the top
|
Move import back to the top
|
Python
|
mit
|
stiphyMT/plantcv,danforthcenter/plantcv,danforthcenter/plantcv,stiphyMT/plantcv,stiphyMT/plantcv,danforthcenter/plantcv
|
python
|
## Code Before:
import numpy as np
from plantcv.plantcv import params
def color_palette(num):
"""color_palette: Returns a list of colors length num
Inputs:
num = number of colors to return.
Returns:
colors = a list of color lists (RGB values)
:param num: int
:return colors: list
"""
from matplotlib import pyplot as plt
# If a previous palette is saved, return it
if params.saved_color_scale is not None:
return params.saved_color_scale
else:
# Retrieve the matplotlib colormap
cmap = plt.get_cmap(params.color_scale)
# Get num evenly spaced colors
colors = cmap(np.linspace(0, 1, num), bytes=True)
colors = colors[:, 0:3].tolist()
# colors are sequential, if params.color_sequence is random then shuffle the colors
if params.color_sequence == "random":
np.random.shuffle(colors)
# Save the color scale for further use
params.saved_color_scale = colors
return colors
## Instruction:
Move import back to the top
## Code After:
from matplotlib import pyplot as plt
import numpy as np
from plantcv.plantcv import params
def color_palette(num):
"""color_palette: Returns a list of colors length num
Inputs:
num = number of colors to return.
Returns:
colors = a list of color lists (RGB values)
:param num: int
:return colors: list
"""
# If a previous palette is saved, return it
if params.saved_color_scale is not None:
return params.saved_color_scale
else:
# Retrieve the matplotlib colormap
cmap = plt.get_cmap(params.color_scale)
# Get num evenly spaced colors
colors = cmap(np.linspace(0, 1, num), bytes=True)
colors = colors[:, 0:3].tolist()
# colors are sequential, if params.color_sequence is random then shuffle the colors
if params.color_sequence == "random":
np.random.shuffle(colors)
# Save the color scale for further use
params.saved_color_scale = colors
return colors
|
# ... existing code ...
from matplotlib import pyplot as plt
import numpy as np
from plantcv.plantcv import params
# ... modified code ...
:param num: int
:return colors: list
"""
# If a previous palette is saved, return it
if params.saved_color_scale is not None:
return params.saved_color_scale
# ... rest of the code ...
|
5a3ffb93131c83f81eb123c2969714dcc80513ca
|
django/crashreport/processor/signals.py
|
django/crashreport/processor/signals.py
|
from .processor import MinidumpProcessor
from uwsgidecoratorsfallback import spool
import logging
logger = logging.getLogger(__name__)
@spool
def do_process_uploaded_crash(*args, **kwargs):
minproc = MinidumpProcessor()
minproc.process(kwargs['crash_id'])
logger.info('processed: %s' % (kwargs['crash_id']))
# vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
from .processor import MinidumpProcessor
from uwsgidecoratorsfallback import spool
import logging
logger = logging.getLogger(__name__)
@spool
def do_process_uploaded_crash(env):
minproc = MinidumpProcessor()
minproc.process(env['crash_id'])
logger.info('processed: %s' % (env['crash_id']))
# vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
Revert "make the uwsgi spooler code also work with the fallback"
|
Revert "make the uwsgi spooler code also work with the fallback"
This reverts commit 84ab847b444fbd41b9cc17e5c79a609efdcdf6cf.
|
Python
|
mpl-2.0
|
mmohrhard/crash,mmohrhard/crash,Liongold/crash,Liongold/crash,mmohrhard/crash,Liongold/crash
|
python
|
## Code Before:
from .processor import MinidumpProcessor
from uwsgidecoratorsfallback import spool
import logging
logger = logging.getLogger(__name__)
@spool
def do_process_uploaded_crash(*args, **kwargs):
minproc = MinidumpProcessor()
minproc.process(kwargs['crash_id'])
logger.info('processed: %s' % (kwargs['crash_id']))
# vim:set shiftwidth=4 softtabstop=4 expandtab: */
## Instruction:
Revert "make the uwsgi spooler code also work with the fallback"
This reverts commit 84ab847b444fbd41b9cc17e5c79a609efdcdf6cf.
## Code After:
from .processor import MinidumpProcessor
from uwsgidecoratorsfallback import spool
import logging
logger = logging.getLogger(__name__)
@spool
def do_process_uploaded_crash(env):
minproc = MinidumpProcessor()
minproc.process(env['crash_id'])
logger.info('processed: %s' % (env['crash_id']))
# vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
# ... existing code ...
logger = logging.getLogger(__name__)
@spool
def do_process_uploaded_crash(env):
minproc = MinidumpProcessor()
minproc.process(env['crash_id'])
logger.info('processed: %s' % (env['crash_id']))
# vim:set shiftwidth=4 softtabstop=4 expandtab: */
# ... rest of the code ...
|
03eb0081a4037e36775271fb2373277f8e89835b
|
src/mcedit2/resourceloader.py
|
src/mcedit2/resourceloader.py
|
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import zipfile
log = logging.getLogger(__name__)
class ResourceNotFound(KeyError):
pass
class ResourceLoader(object):
def __init__(self):
super(ResourceLoader, self).__init__()
self.zipFiles = []
def addZipFile(self, zipPath):
try:
zf = zipfile.ZipFile(zipPath)
except zipfile.BadZipfile as e:
raise IOError("Could not read %s as a zip file." % zipPath)
self.zipFiles.append(zf)
def openStream(self, path):
for zipFile in self.zipFiles:
try:
stream = zipFile.open(path)
break
except KeyError: # Not found in zip file
continue
else:
raise ResourceNotFound("Resource %s not found in search path" % path)
return stream
|
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import zipfile
log = logging.getLogger(__name__)
class ResourceNotFound(KeyError):
pass
class ResourceLoader(object):
def __init__(self):
super(ResourceLoader, self).__init__()
self.zipFiles = []
def addZipFile(self, zipPath):
try:
zf = zipfile.ZipFile(zipPath)
except zipfile.BadZipfile as e:
raise IOError("Could not read %s as a zip file." % zipPath)
self.zipFiles.append(zf)
def openStream(self, path):
for zipFile in self.zipFiles:
try:
stream = zipFile.open(path)
break
except KeyError: # Not found in zip file
continue
else:
raise ResourceNotFound("Resource %s not found in search path" % path)
return stream
def blockModelPaths(self):
for zf in self.zipFiles:
for name in zf.namelist():
if name.startswith("assets/minecraft/models/block"):
yield name
|
Add function to ResourceLoader for listing all block models
|
Add function to ResourceLoader for listing all block models
xxx only lists Vanilla models. haven't looked at mods with models yet.
|
Python
|
bsd-3-clause
|
vorburger/mcedit2,vorburger/mcedit2,Rubisk/mcedit2,Rubisk/mcedit2
|
python
|
## Code Before:
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import zipfile
log = logging.getLogger(__name__)
class ResourceNotFound(KeyError):
pass
class ResourceLoader(object):
def __init__(self):
super(ResourceLoader, self).__init__()
self.zipFiles = []
def addZipFile(self, zipPath):
try:
zf = zipfile.ZipFile(zipPath)
except zipfile.BadZipfile as e:
raise IOError("Could not read %s as a zip file." % zipPath)
self.zipFiles.append(zf)
def openStream(self, path):
for zipFile in self.zipFiles:
try:
stream = zipFile.open(path)
break
except KeyError: # Not found in zip file
continue
else:
raise ResourceNotFound("Resource %s not found in search path" % path)
return stream
## Instruction:
Add function to ResourceLoader for listing all block models
xxx only lists Vanilla models. haven't looked at mods with models yet.
## Code After:
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import zipfile
log = logging.getLogger(__name__)
class ResourceNotFound(KeyError):
pass
class ResourceLoader(object):
def __init__(self):
super(ResourceLoader, self).__init__()
self.zipFiles = []
def addZipFile(self, zipPath):
try:
zf = zipfile.ZipFile(zipPath)
except zipfile.BadZipfile as e:
raise IOError("Could not read %s as a zip file." % zipPath)
self.zipFiles.append(zf)
def openStream(self, path):
for zipFile in self.zipFiles:
try:
stream = zipFile.open(path)
break
except KeyError: # Not found in zip file
continue
else:
raise ResourceNotFound("Resource %s not found in search path" % path)
return stream
def blockModelPaths(self):
for zf in self.zipFiles:
for name in zf.namelist():
if name.startswith("assets/minecraft/models/block"):
yield name
|
# ... existing code ...
raise ResourceNotFound("Resource %s not found in search path" % path)
return stream
def blockModelPaths(self):
for zf in self.zipFiles:
for name in zf.namelist():
if name.startswith("assets/minecraft/models/block"):
yield name
# ... rest of the code ...
|
cca387dc889b12457c1b1d8bb7b61ad3d2bbd57a
|
tests/test_room.py
|
tests/test_room.py
|
import unittest
from classes.room import Room
class RoomClassTest(unittest.TestCase):
pass
# def test_create_room_successfully(self):
# my_class_instance = Room()
# initial_room_count = len(my_class_instance.all_rooms)
# blue_office = my_class_instance.create_room("Blue", "office")
# self.assertTrue(blue_office)
# new_room_count = len(my_class_instance.all_rooms)
# self.assertEqual(new_room_count - initial_room_count, 1)
#
# def test_inputs_are_strings(self):
# # Test raises an error if either input is not a string
# with self.assertRaises(ValueError, msg='Only strings are allowed as input'):
# my_class_instance = Room()
# blue_office = my_class_instance.create_room(1234, "office")
|
import unittest
from classes.room import Room
from classes.dojo import Dojo
class RoomClassTest(unittest.TestCase):
def test_add_occupant(self):
my_class_instance = Room("Blue", "office", 6)
my_dojo_instance = Dojo()
new_fellow = my_dojo_instance.add_person("fellow", "Peter", "Musonye", "Y")
initial_persons_count = len(my_class_instance.persons)
new_occupant = my_class_instance.add_occupant(new_fellow)
# self.assertTrue(new_occupant)
new_persons_count = len(my_class_instance.persons)
self.assertEqual(new_persons_count - initial_persons_count, 1)
def test_cannot_add_more_than_max_occupants(self):
my_class_instance = Room("Blue", "office", 4)
my_dojo_instance = Dojo()
fellow_1 = my_dojo_instance.add_person("fellow", "Peter", "Musonye", "Y")
fellow_2 = my_dojo_instance.add_person("staff", "Farhan", "Abdi")
fellow_3 = my_dojo_instance.add_person("fellow", "Rose", "Maina", "Y")
fellow_4 = my_dojo_instance.add_person("fellow", "Dennis", "Kola", "Y")
fellow_5 = my_dojo_instance.add_person("fellow", "Eddy", "Karanja", "Y")
occupant_1 = my_class_instance.add_occupant(fellow_1)
occupant_2 = my_class_instance.add_occupant(fellow_2)
occupant_3 = my_class_instance.add_occupant(fellow_3)
occupant_4 = my_class_instance.add_occupant(fellow_4)
occupant_5 = my_class_instance.add_occupant(fellow_5)
self.assertEqual(occupant_5, "Room is at full capacity")
|
Add tests for class Room
|
Add tests for class Room
|
Python
|
mit
|
peterpaints/room-allocator
|
python
|
## Code Before:
import unittest
from classes.room import Room
class RoomClassTest(unittest.TestCase):
pass
# def test_create_room_successfully(self):
# my_class_instance = Room()
# initial_room_count = len(my_class_instance.all_rooms)
# blue_office = my_class_instance.create_room("Blue", "office")
# self.assertTrue(blue_office)
# new_room_count = len(my_class_instance.all_rooms)
# self.assertEqual(new_room_count - initial_room_count, 1)
#
# def test_inputs_are_strings(self):
# # Test raises an error if either input is not a string
# with self.assertRaises(ValueError, msg='Only strings are allowed as input'):
# my_class_instance = Room()
# blue_office = my_class_instance.create_room(1234, "office")
## Instruction:
Add tests for class Room
## Code After:
import unittest
from classes.room import Room
from classes.dojo import Dojo
class RoomClassTest(unittest.TestCase):
def test_add_occupant(self):
my_class_instance = Room("Blue", "office", 6)
my_dojo_instance = Dojo()
new_fellow = my_dojo_instance.add_person("fellow", "Peter", "Musonye", "Y")
initial_persons_count = len(my_class_instance.persons)
new_occupant = my_class_instance.add_occupant(new_fellow)
# self.assertTrue(new_occupant)
new_persons_count = len(my_class_instance.persons)
self.assertEqual(new_persons_count - initial_persons_count, 1)
def test_cannot_add_more_than_max_occupants(self):
my_class_instance = Room("Blue", "office", 4)
my_dojo_instance = Dojo()
fellow_1 = my_dojo_instance.add_person("fellow", "Peter", "Musonye", "Y")
fellow_2 = my_dojo_instance.add_person("staff", "Farhan", "Abdi")
fellow_3 = my_dojo_instance.add_person("fellow", "Rose", "Maina", "Y")
fellow_4 = my_dojo_instance.add_person("fellow", "Dennis", "Kola", "Y")
fellow_5 = my_dojo_instance.add_person("fellow", "Eddy", "Karanja", "Y")
occupant_1 = my_class_instance.add_occupant(fellow_1)
occupant_2 = my_class_instance.add_occupant(fellow_2)
occupant_3 = my_class_instance.add_occupant(fellow_3)
occupant_4 = my_class_instance.add_occupant(fellow_4)
occupant_5 = my_class_instance.add_occupant(fellow_5)
self.assertEqual(occupant_5, "Room is at full capacity")
|
// ... existing code ...
import unittest
from classes.room import Room
from classes.dojo import Dojo
class RoomClassTest(unittest.TestCase):
def test_add_occupant(self):
my_class_instance = Room("Blue", "office", 6)
my_dojo_instance = Dojo()
new_fellow = my_dojo_instance.add_person("fellow", "Peter", "Musonye", "Y")
initial_persons_count = len(my_class_instance.persons)
new_occupant = my_class_instance.add_occupant(new_fellow)
# self.assertTrue(new_occupant)
new_persons_count = len(my_class_instance.persons)
self.assertEqual(new_persons_count - initial_persons_count, 1)
def test_cannot_add_more_than_max_occupants(self):
my_class_instance = Room("Blue", "office", 4)
my_dojo_instance = Dojo()
fellow_1 = my_dojo_instance.add_person("fellow", "Peter", "Musonye", "Y")
fellow_2 = my_dojo_instance.add_person("staff", "Farhan", "Abdi")
fellow_3 = my_dojo_instance.add_person("fellow", "Rose", "Maina", "Y")
fellow_4 = my_dojo_instance.add_person("fellow", "Dennis", "Kola", "Y")
fellow_5 = my_dojo_instance.add_person("fellow", "Eddy", "Karanja", "Y")
occupant_1 = my_class_instance.add_occupant(fellow_1)
occupant_2 = my_class_instance.add_occupant(fellow_2)
occupant_3 = my_class_instance.add_occupant(fellow_3)
occupant_4 = my_class_instance.add_occupant(fellow_4)
occupant_5 = my_class_instance.add_occupant(fellow_5)
self.assertEqual(occupant_5, "Room is at full capacity")
// ... rest of the code ...
|
d7c41853277c1df53192b2f879f47f75f3c62fd5
|
server/covmanager/urls.py
|
server/covmanager/urls.py
|
from django.conf.urls import patterns, include, url
from rest_framework import routers
from covmanager import views
router = routers.DefaultRouter()
router.register(r'collections', views.CollectionViewSet, base_name='collections')
router.register(r'repositories', views.RepositoryViewSet, base_name='repositories')
urlpatterns = patterns('',
url(r'^rest/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^repositories/', views.repositories, name="repositories"),
url(r'^collections/$', views.collections, name="collections"),
url(r'^collections/api/$', views.CollectionViewSet.as_view({'get': 'list'}), name="collections_api"),
url(r'^collections/(?P<collectionid>\d+)/browse/$', views.collections_browse, name="collections_browse"),
url(r'^collections/(?P<collectionid>\d+)/browse/api/(?P<path>.*)', views.collections_browse_api, name="collections_browse_api"),
url(r'^rest/', include(router.urls)),
)
|
from django.conf.urls import patterns, include, url
from rest_framework import routers
from covmanager import views
router = routers.DefaultRouter()
router.register(r'collections', views.CollectionViewSet, base_name='collections')
router.register(r'repositories', views.RepositoryViewSet, base_name='repositories')
urlpatterns = patterns('',
url(r'^rest/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^$', views.index, name='index'),
url(r'^repositories/', views.repositories, name="repositories"),
url(r'^collections/$', views.collections, name="collections"),
url(r'^collections/api/$', views.CollectionViewSet.as_view({'get': 'list'}), name="collections_api"),
url(r'^collections/(?P<collectionid>\d+)/browse/$', views.collections_browse, name="collections_browse"),
url(r'^collections/(?P<collectionid>\d+)/browse/api/(?P<path>.*)', views.collections_browse_api, name="collections_browse_api"),
url(r'^rest/', include(router.urls)),
)
|
Add redirect for / to collections
|
[CovManager] Add redirect for / to collections
|
Python
|
mpl-2.0
|
MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager
|
python
|
## Code Before:
from django.conf.urls import patterns, include, url
from rest_framework import routers
from covmanager import views
router = routers.DefaultRouter()
router.register(r'collections', views.CollectionViewSet, base_name='collections')
router.register(r'repositories', views.RepositoryViewSet, base_name='repositories')
urlpatterns = patterns('',
url(r'^rest/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^repositories/', views.repositories, name="repositories"),
url(r'^collections/$', views.collections, name="collections"),
url(r'^collections/api/$', views.CollectionViewSet.as_view({'get': 'list'}), name="collections_api"),
url(r'^collections/(?P<collectionid>\d+)/browse/$', views.collections_browse, name="collections_browse"),
url(r'^collections/(?P<collectionid>\d+)/browse/api/(?P<path>.*)', views.collections_browse_api, name="collections_browse_api"),
url(r'^rest/', include(router.urls)),
)
## Instruction:
[CovManager] Add redirect for / to collections
## Code After:
from django.conf.urls import patterns, include, url
from rest_framework import routers
from covmanager import views
router = routers.DefaultRouter()
router.register(r'collections', views.CollectionViewSet, base_name='collections')
router.register(r'repositories', views.RepositoryViewSet, base_name='repositories')
urlpatterns = patterns('',
url(r'^rest/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^$', views.index, name='index'),
url(r'^repositories/', views.repositories, name="repositories"),
url(r'^collections/$', views.collections, name="collections"),
url(r'^collections/api/$', views.CollectionViewSet.as_view({'get': 'list'}), name="collections_api"),
url(r'^collections/(?P<collectionid>\d+)/browse/$', views.collections_browse, name="collections_browse"),
url(r'^collections/(?P<collectionid>\d+)/browse/api/(?P<path>.*)', views.collections_browse_api, name="collections_browse_api"),
url(r'^rest/', include(router.urls)),
)
|
# ... existing code ...
urlpatterns = patterns('',
url(r'^rest/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^$', views.index, name='index'),
url(r'^repositories/', views.repositories, name="repositories"),
url(r'^collections/$', views.collections, name="collections"),
url(r'^collections/api/$', views.CollectionViewSet.as_view({'get': 'list'}), name="collections_api"),
# ... rest of the code ...
|
7b05154275ee8eda30763a66dc6bfbbf5de678da
|
.teamcity/src/main/kotlin/vcsroots/VcsRoots.kt
|
.teamcity/src/main/kotlin/vcsroots/VcsRoots.kt
|
package vcsroots
import jetbrains.buildServer.configs.kotlin.v2019_2.AbsoluteId
import jetbrains.buildServer.configs.kotlin.v2019_2.CheckoutMode
import jetbrains.buildServer.configs.kotlin.v2019_2.VcsSettings
import jetbrains.buildServer.configs.kotlin.v2019_2.vcs.GitVcsRoot
object GradleAllBranches : GitVcsRoot({
name = "Gradle All Branches"
url = "https://github.com/gradle/gradle.git"
branch = "master"
branchSpec = "+:refs/heads/*"
agentGitPath = "%env.TEAMCITY_GIT_PATH%"
useMirrors = false
})
val gradleMasterVersionedSettings = "GradleMaster"
val gradleReleaseVersionedSettings = "GradleRelease"
val gradlePromotionMaster = "Gradle_GradlePromoteMaster"
val gradlePromotionBranches = "Gradle_GradlePromoteBranches"
fun VcsSettings.useAbsoluteVcs(absoluteId: String) {
root(AbsoluteId(absoluteId))
checkoutMode = CheckoutMode.ON_AGENT
this.cleanCheckout = cleanCheckout
showDependenciesChanges = true
}
|
package vcsroots
import jetbrains.buildServer.configs.kotlin.v2019_2.AbsoluteId
import jetbrains.buildServer.configs.kotlin.v2019_2.CheckoutMode
import jetbrains.buildServer.configs.kotlin.v2019_2.VcsSettings
import jetbrains.buildServer.configs.kotlin.v2019_2.vcs.GitVcsRoot
object GradleAllBranches : GitVcsRoot({
name = "Gradle All Branches"
url = "https://github.com/gradle/gradle.git"
branch = "%defaultBranchName%"
branchSpec = """+:refs/heads/*
+:refs/(pull/*/head)"""
agentGitPath = "%env.TEAMCITY_GIT_PATH%"
useMirrors = false
})
val gradleMasterVersionedSettings = "GradleMaster"
val gradleReleaseVersionedSettings = "GradleRelease"
val gradlePromotionMaster = "Gradle_GradlePromoteMaster"
val gradlePromotionBranches = "Gradle_GradlePromoteBranches"
fun VcsSettings.useAbsoluteVcs(absoluteId: String) {
root(AbsoluteId(absoluteId))
checkoutMode = CheckoutMode.ON_AGENT
this.cleanCheckout = cleanCheckout
showDependenciesChanges = true
}
|
Use same default branch and branch spec as before
|
Use same default branch and branch spec as before
|
Kotlin
|
apache-2.0
|
gradle/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,gradle/gradle
|
kotlin
|
## Code Before:
package vcsroots
import jetbrains.buildServer.configs.kotlin.v2019_2.AbsoluteId
import jetbrains.buildServer.configs.kotlin.v2019_2.CheckoutMode
import jetbrains.buildServer.configs.kotlin.v2019_2.VcsSettings
import jetbrains.buildServer.configs.kotlin.v2019_2.vcs.GitVcsRoot
object GradleAllBranches : GitVcsRoot({
name = "Gradle All Branches"
url = "https://github.com/gradle/gradle.git"
branch = "master"
branchSpec = "+:refs/heads/*"
agentGitPath = "%env.TEAMCITY_GIT_PATH%"
useMirrors = false
})
val gradleMasterVersionedSettings = "GradleMaster"
val gradleReleaseVersionedSettings = "GradleRelease"
val gradlePromotionMaster = "Gradle_GradlePromoteMaster"
val gradlePromotionBranches = "Gradle_GradlePromoteBranches"
fun VcsSettings.useAbsoluteVcs(absoluteId: String) {
root(AbsoluteId(absoluteId))
checkoutMode = CheckoutMode.ON_AGENT
this.cleanCheckout = cleanCheckout
showDependenciesChanges = true
}
## Instruction:
Use same default branch and branch spec as before
## Code After:
package vcsroots
import jetbrains.buildServer.configs.kotlin.v2019_2.AbsoluteId
import jetbrains.buildServer.configs.kotlin.v2019_2.CheckoutMode
import jetbrains.buildServer.configs.kotlin.v2019_2.VcsSettings
import jetbrains.buildServer.configs.kotlin.v2019_2.vcs.GitVcsRoot
object GradleAllBranches : GitVcsRoot({
name = "Gradle All Branches"
url = "https://github.com/gradle/gradle.git"
branch = "%defaultBranchName%"
branchSpec = """+:refs/heads/*
+:refs/(pull/*/head)"""
agentGitPath = "%env.TEAMCITY_GIT_PATH%"
useMirrors = false
})
val gradleMasterVersionedSettings = "GradleMaster"
val gradleReleaseVersionedSettings = "GradleRelease"
val gradlePromotionMaster = "Gradle_GradlePromoteMaster"
val gradlePromotionBranches = "Gradle_GradlePromoteBranches"
fun VcsSettings.useAbsoluteVcs(absoluteId: String) {
root(AbsoluteId(absoluteId))
checkoutMode = CheckoutMode.ON_AGENT
this.cleanCheckout = cleanCheckout
showDependenciesChanges = true
}
|
# ... existing code ...
object GradleAllBranches : GitVcsRoot({
name = "Gradle All Branches"
url = "https://github.com/gradle/gradle.git"
branch = "%defaultBranchName%"
branchSpec = """+:refs/heads/*
+:refs/(pull/*/head)"""
agentGitPath = "%env.TEAMCITY_GIT_PATH%"
useMirrors = false
})
# ... rest of the code ...
|
011db4c2de258e08e6d547f1dfe89f28f08fa714
|
src/edu/stuy/commands/AutonSetting6.java
|
src/edu/stuy/commands/AutonSetting6.java
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.stuy.commands;
/**
* Shoots from key at 2 point hoop
* @author admin
*/
import edu.stuy.subsystems.Flywheel;
import edu.wpi.first.wpilibj.command.CommandGroup;
public class AutonSetting6 extends CommandGroup {
public AutonSetting6 () {
double distanceInches = Flywheel.distances[Flywheel.KEY_MIDDLE_HOOP_INDEX];
addParallel(new FlywheelRun(distanceInches, Flywheel.speedsTopHoop));
addSequential(new ConveyAutomatic(Autonomous.CONVEY_AUTO_TIME));
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.stuy.commands;
/**
* Shoots from key at 2 point hoop
* @author admin
*/
import edu.stuy.subsystems.Flywheel;
import edu.wpi.first.wpilibj.command.CommandGroup;
public class AutonSetting6 extends CommandGroup {
public AutonSetting6 () {
double distanceInches = Flywheel.distances[Flywheel.KEY_INDEX];
addParallel(new FlywheelRun(distanceInches, Flywheel.speedsTopHoop));
addSequential(new ConveyAutomatic(Autonomous.CONVEY_AUTO_TIME));
}
}
|
Use top hoop for autonsettin6 instead of two-point shot
|
Use top hoop for autonsettin6 instead of two-point shot
|
Java
|
bsd-3-clause
|
Team694/joebot
|
java
|
## Code Before:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.stuy.commands;
/**
* Shoots from key at 2 point hoop
* @author admin
*/
import edu.stuy.subsystems.Flywheel;
import edu.wpi.first.wpilibj.command.CommandGroup;
public class AutonSetting6 extends CommandGroup {
public AutonSetting6 () {
double distanceInches = Flywheel.distances[Flywheel.KEY_MIDDLE_HOOP_INDEX];
addParallel(new FlywheelRun(distanceInches, Flywheel.speedsTopHoop));
addSequential(new ConveyAutomatic(Autonomous.CONVEY_AUTO_TIME));
}
}
## Instruction:
Use top hoop for autonsettin6 instead of two-point shot
## Code After:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.stuy.commands;
/**
* Shoots from key at 2 point hoop
* @author admin
*/
import edu.stuy.subsystems.Flywheel;
import edu.wpi.first.wpilibj.command.CommandGroup;
public class AutonSetting6 extends CommandGroup {
public AutonSetting6 () {
double distanceInches = Flywheel.distances[Flywheel.KEY_INDEX];
addParallel(new FlywheelRun(distanceInches, Flywheel.speedsTopHoop));
addSequential(new ConveyAutomatic(Autonomous.CONVEY_AUTO_TIME));
}
}
|
// ... existing code ...
public class AutonSetting6 extends CommandGroup {
public AutonSetting6 () {
double distanceInches = Flywheel.distances[Flywheel.KEY_INDEX];
addParallel(new FlywheelRun(distanceInches, Flywheel.speedsTopHoop));
addSequential(new ConveyAutomatic(Autonomous.CONVEY_AUTO_TIME));
}
// ... rest of the code ...
|
1bc76e90771befd2be6accd71b32ae2547e98f6a
|
include/user.c
|
include/user.c
|
user_t* NewUser(int fd,char *addr,unsigned short port,char *name){
user_t *user = malloc(sizeof(user_t));
if(user == NULL){
goto ret;
}
if(fd < 0 || addr == NULL || name == NULL){
free(user);
user = NULL;
goto ret;
}
user->fd = fd;
strcpy(user->addr,addr);
user->port = port;
strcpy(user->name,name);
user->next = NULL;
ret:
return user;
}
void AddUserToList(user_t *root,user_t *newUser){
user_t *cur = root;
while(cur->next != NULL){
cur = cur->next;
}
cur->next = newUser;
}
int CheckUserValid(user_t *root,char *name){
user_t *cur=root;
int len = strlen(name);
if(len < 2 || len > 12){
return 0;
}
if(strcmp(name,"anonymous") == 0){
return 0;
}
while(cur != NULL){
if(strcmp(cur->name,name) == 0){
return 0;
}
cur = cur->next;
}
return 1;
}
|
user_t* NewUser(int fd,char *addr,unsigned short port,char *name){
user_t *user = malloc(sizeof(user_t));
if(user == NULL){
goto ret;
}
if(fd < 0 || addr == NULL || name == NULL){
free(user);
user = NULL;
goto ret;
}
user->fd = fd;
strcpy(user->addr,addr);
user->port = port;
strcpy(user->name,name);
user->next = NULL;
ret:
return user;
}
void AddUserToList(user_t *root,user_t *newUser){
user_t *cur = root;
if(root == NULL){
return;
}
while(cur->next != NULL){
cur = cur->next;
}
cur->next = newUser;
}
int CheckUserValid(user_t *root,char *name){
user_t *cur=root;
int len = strlen(name);
if(len < 2 || len > 12){
return 0;
}
if(strcmp(name,"anonymous") == 0){
return 0;
}
while(cur != NULL){
if(strcmp(cur->name,name) == 0){
return 0;
}
cur = cur->next;
}
return 1;
}
|
Fix AddUserToList bug when root is NULL
|
Fix AddUserToList bug when root is NULL
|
C
|
apache-2.0
|
Billy4195/Simple_Chatroom
|
c
|
## Code Before:
user_t* NewUser(int fd,char *addr,unsigned short port,char *name){
user_t *user = malloc(sizeof(user_t));
if(user == NULL){
goto ret;
}
if(fd < 0 || addr == NULL || name == NULL){
free(user);
user = NULL;
goto ret;
}
user->fd = fd;
strcpy(user->addr,addr);
user->port = port;
strcpy(user->name,name);
user->next = NULL;
ret:
return user;
}
void AddUserToList(user_t *root,user_t *newUser){
user_t *cur = root;
while(cur->next != NULL){
cur = cur->next;
}
cur->next = newUser;
}
int CheckUserValid(user_t *root,char *name){
user_t *cur=root;
int len = strlen(name);
if(len < 2 || len > 12){
return 0;
}
if(strcmp(name,"anonymous") == 0){
return 0;
}
while(cur != NULL){
if(strcmp(cur->name,name) == 0){
return 0;
}
cur = cur->next;
}
return 1;
}
## Instruction:
Fix AddUserToList bug when root is NULL
## Code After:
user_t* NewUser(int fd,char *addr,unsigned short port,char *name){
user_t *user = malloc(sizeof(user_t));
if(user == NULL){
goto ret;
}
if(fd < 0 || addr == NULL || name == NULL){
free(user);
user = NULL;
goto ret;
}
user->fd = fd;
strcpy(user->addr,addr);
user->port = port;
strcpy(user->name,name);
user->next = NULL;
ret:
return user;
}
void AddUserToList(user_t *root,user_t *newUser){
user_t *cur = root;
if(root == NULL){
return;
}
while(cur->next != NULL){
cur = cur->next;
}
cur->next = newUser;
}
int CheckUserValid(user_t *root,char *name){
user_t *cur=root;
int len = strlen(name);
if(len < 2 || len > 12){
return 0;
}
if(strcmp(name,"anonymous") == 0){
return 0;
}
while(cur != NULL){
if(strcmp(cur->name,name) == 0){
return 0;
}
cur = cur->next;
}
return 1;
}
|
// ... existing code ...
void AddUserToList(user_t *root,user_t *newUser){
user_t *cur = root;
if(root == NULL){
return;
}
while(cur->next != NULL){
cur = cur->next;
}
// ... rest of the code ...
|
0ec760e3fbabbac7a0d5fb37b4cb659fd113c73d
|
alib/src/main/java/net/darkmist/alib/generics/GenericFudge.java
|
alib/src/main/java/net/darkmist/alib/generics/GenericFudge.java
|
package net.darkmist.alib.generics;
public class GenericFudge
{
@SuppressWarnings("unchecked")
static public <T> Class<? extends T> getClass(T obj)
{
return (Class<? extends T>)obj.getClass();
}
}
|
package net.darkmist.alib.generics;
import java.util.Map;
/**
* Static methods to get around issues with generics...
*/
@SuppressWarnings("unchecked")
public class GenericFudge
{
/** Only static methods. */
private GenericFudge()
{
}
/**
* Fudge the return from getClass to include the generic.
*/
static public <T> Class<? extends T> getClass(T obj)
{
return (Class<? extends T>)obj.getClass();
}
/**
* Fudge a ungenericified map to be one.
*/
static public <K,V> Map<K,V> map(Map map)
{
return map;
}
}
|
Add method to allow ungenericed map to genericed map fudge
|
Add method to allow ungenericed map to genericed map fudge
|
Java
|
lgpl-2.1
|
schallee/alib4j
|
java
|
## Code Before:
package net.darkmist.alib.generics;
public class GenericFudge
{
@SuppressWarnings("unchecked")
static public <T> Class<? extends T> getClass(T obj)
{
return (Class<? extends T>)obj.getClass();
}
}
## Instruction:
Add method to allow ungenericed map to genericed map fudge
## Code After:
package net.darkmist.alib.generics;
import java.util.Map;
/**
* Static methods to get around issues with generics...
*/
@SuppressWarnings("unchecked")
public class GenericFudge
{
/** Only static methods. */
private GenericFudge()
{
}
/**
* Fudge the return from getClass to include the generic.
*/
static public <T> Class<? extends T> getClass(T obj)
{
return (Class<? extends T>)obj.getClass();
}
/**
* Fudge a ungenericified map to be one.
*/
static public <K,V> Map<K,V> map(Map map)
{
return map;
}
}
|
# ... existing code ...
package net.darkmist.alib.generics;
import java.util.Map;
/**
* Static methods to get around issues with generics...
*/
@SuppressWarnings("unchecked")
public class GenericFudge
{
/** Only static methods. */
private GenericFudge()
{
}
/**
* Fudge the return from getClass to include the generic.
*/
static public <T> Class<? extends T> getClass(T obj)
{
return (Class<? extends T>)obj.getClass();
}
/**
* Fudge a ungenericified map to be one.
*/
static public <K,V> Map<K,V> map(Map map)
{
return map;
}
}
# ... rest of the code ...
|
2c1b1a2343f5882ee6f98328ff391478d0d58c23
|
src/3rdparty/win32_src/pdcurses/wincon/pdcwin.h
|
src/3rdparty/win32_src/pdcurses/wincon/pdcwin.h
|
/* PDCurses */
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
# define _CRT_SECURE_NO_DEPRECATE 1 /* kill nonsense warnings */
#endif
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
# define _CRT_SECURE_NO_DEPRECATE 1 /* kill nonsense warnings */
#endif
#if defined(PDC_WIDE) && !defined(UNICODE)
# define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#undef MOUSE_MOVED
#include <curspriv.h>
typedef struct {short r, g, b; bool mapped;} PDCCOLOR;
extern PDCCOLOR pdc_color[PDC_MAXCOL];
extern HANDLE pdc_con_out, pdc_con_in;
extern DWORD pdc_quick_edit;
extern DWORD pdc_last_blink;
extern short pdc_curstoreal[16], pdc_curstoansi[16];
extern short pdc_oldf, pdc_oldb, pdc_oldu;
extern bool pdc_conemu, pdc_wt, pdc_ansi;
extern void PDC_blink_text(void);
|
/* PDCurses */
#ifndef __PDC_WIN_H__
#define __PDC_WIN_H__
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
# define _CRT_SECURE_NO_DEPRECATE 1 /* kill nonsense warnings */
#endif
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
# define _CRT_SECURE_NO_DEPRECATE 1 /* kill nonsense warnings */
#endif
#if defined(PDC_WIDE) && !defined(UNICODE)
# define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#undef MOUSE_MOVED
#include <curspriv.h>
typedef struct {short r, g, b; bool mapped;} PDCCOLOR;
extern PDCCOLOR pdc_color[PDC_MAXCOL];
extern HANDLE pdc_con_out, pdc_con_in;
extern DWORD pdc_quick_edit;
extern DWORD pdc_last_blink;
extern short pdc_curstoreal[16], pdc_curstoansi[16];
extern short pdc_oldf, pdc_oldb, pdc_oldu;
extern bool pdc_conemu, pdc_wt, pdc_ansi;
extern void PDC_blink_text(void);
#endif
|
Add include guard to fix wincon compile.
|
Add include guard to fix wincon compile.
|
C
|
bsd-3-clause
|
clangen/musikcube,clangen/musikcube,clangen/musikcube,clangen/musikcube,clangen/musikcube,clangen/musikcube,clangen/musikcube,clangen/musikcube
|
c
|
## Code Before:
/* PDCurses */
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
# define _CRT_SECURE_NO_DEPRECATE 1 /* kill nonsense warnings */
#endif
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
# define _CRT_SECURE_NO_DEPRECATE 1 /* kill nonsense warnings */
#endif
#if defined(PDC_WIDE) && !defined(UNICODE)
# define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#undef MOUSE_MOVED
#include <curspriv.h>
typedef struct {short r, g, b; bool mapped;} PDCCOLOR;
extern PDCCOLOR pdc_color[PDC_MAXCOL];
extern HANDLE pdc_con_out, pdc_con_in;
extern DWORD pdc_quick_edit;
extern DWORD pdc_last_blink;
extern short pdc_curstoreal[16], pdc_curstoansi[16];
extern short pdc_oldf, pdc_oldb, pdc_oldu;
extern bool pdc_conemu, pdc_wt, pdc_ansi;
extern void PDC_blink_text(void);
## Instruction:
Add include guard to fix wincon compile.
## Code After:
/* PDCurses */
#ifndef __PDC_WIN_H__
#define __PDC_WIN_H__
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
# define _CRT_SECURE_NO_DEPRECATE 1 /* kill nonsense warnings */
#endif
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
# define _CRT_SECURE_NO_DEPRECATE 1 /* kill nonsense warnings */
#endif
#if defined(PDC_WIDE) && !defined(UNICODE)
# define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#undef MOUSE_MOVED
#include <curspriv.h>
typedef struct {short r, g, b; bool mapped;} PDCCOLOR;
extern PDCCOLOR pdc_color[PDC_MAXCOL];
extern HANDLE pdc_con_out, pdc_con_in;
extern DWORD pdc_quick_edit;
extern DWORD pdc_last_blink;
extern short pdc_curstoreal[16], pdc_curstoansi[16];
extern short pdc_oldf, pdc_oldb, pdc_oldu;
extern bool pdc_conemu, pdc_wt, pdc_ansi;
extern void PDC_blink_text(void);
#endif
|
# ... existing code ...
/* PDCurses */
#ifndef __PDC_WIN_H__
#define __PDC_WIN_H__
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
# define _CRT_SECURE_NO_DEPRECATE 1 /* kill nonsense warnings */
# ... modified code ...
extern bool pdc_conemu, pdc_wt, pdc_ansi;
extern void PDC_blink_text(void);
#endif
# ... rest of the code ...
|
c083481eed1578551daab7ece2e34b3ff4aece82
|
accelerator/migrations/0044_add_sitetree_sidenav_toggle.py
|
accelerator/migrations/0044_add_sitetree_sidenav_toggle.py
|
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0043_remove_exclude_fields'),
]
operations = [
migrations.RemoveField(
model_name='programfamily',
name='side_navigation',
),
migrations.AddField(
model_name='programfamily',
name='use_site_tree_side_nav',
field=models.BooleanField(default=False, help_text='Show the new-style side navigation'),
),
]
|
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0043_remove_exclude_fields'),
]
help_text = 'Show the new-style side navigation'
operations = [
migrations.RemoveField(
model_name='programfamily',
name='side_navigation',
),
migrations.AddField(
model_name='programfamily',
name='use_site_tree_side_nav',
field=models.BooleanField(default=False,
help_text=help_text),
),
]
|
Fix style on migration - waste of time, but whatever
|
Fix style on migration - waste of time, but whatever
|
Python
|
mit
|
masschallenge/django-accelerator,masschallenge/django-accelerator
|
python
|
## Code Before:
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0043_remove_exclude_fields'),
]
operations = [
migrations.RemoveField(
model_name='programfamily',
name='side_navigation',
),
migrations.AddField(
model_name='programfamily',
name='use_site_tree_side_nav',
field=models.BooleanField(default=False, help_text='Show the new-style side navigation'),
),
]
## Instruction:
Fix style on migration - waste of time, but whatever
## Code After:
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0043_remove_exclude_fields'),
]
help_text = 'Show the new-style side navigation'
operations = [
migrations.RemoveField(
model_name='programfamily',
name='side_navigation',
),
migrations.AddField(
model_name='programfamily',
name='use_site_tree_side_nav',
field=models.BooleanField(default=False,
help_text=help_text),
),
]
|
...
dependencies = [
('accelerator', '0043_remove_exclude_fields'),
]
help_text = 'Show the new-style side navigation'
operations = [
migrations.RemoveField(
model_name='programfamily',
...
migrations.AddField(
model_name='programfamily',
name='use_site_tree_side_nav',
field=models.BooleanField(default=False,
help_text=help_text),
),
]
...
|
9ba9e26888578e66469a63e412f46cf151fbcfd7
|
common/data_refinery_common/test_microarray.py
|
common/data_refinery_common/test_microarray.py
|
from unittest.mock import Mock, patch
from django.test import TestCase
from data_refinery_common import microarray
CEL_FILE_HUMAN = "test-files/C30057.CEL"
CEL_FILE_RAT = "test-files/SG2_u34a.CEL"
CEL_FILE_MOUSE = "test-files/97_(Mouse430_2).CEL"
CEL_FILE_ZEBRAFISH = "test-files/CONTROL6.cel"
class MicroarrayTestCase(TestCase):
def test_get_platform_from_CEL(self):
self.assertEqual("hgu95av2", microarray.get_platform_from_CEL(CEL_FILE_HUMAN))
self.assertEqual("rgu34a", microarray.get_platform_from_CEL(CEL_FILE_RAT))
self.assertEqual("mouse4302", microarray.get_platform_from_CEL(CEL_FILE_MOUSE))
self.assertEqual("zebgene11st", microarray.get_platform_from_CEL(CEL_FILE_ZEBRAFISH))
|
from unittest.mock import Mock, patch
from django.test import TestCase
from data_refinery_common import microarray
CEL_FILE_HUMAN = "test-files/C30057.CEL.gz"
CEL_FILE_RAT = "test-files/SG2_u34a.CEL.gz"
CEL_FILE_MOUSE = "test-files/97_(Mouse430_2).CEL.gz"
CEL_FILE_ZEBRAFISH = "test-files/CONTROL6.cel.gz"
class MicroarrayTestCase(TestCase):
def test_get_platform_from_CEL(self):
self.assertEqual("hgu95av2", microarray.get_platform_from_CEL(CEL_FILE_HUMAN))
self.assertEqual("rgu34a", microarray.get_platform_from_CEL(CEL_FILE_RAT))
self.assertEqual("mouse4302", microarray.get_platform_from_CEL(CEL_FILE_MOUSE))
self.assertEqual("zebgene11st", microarray.get_platform_from_CEL(CEL_FILE_ZEBRAFISH))
|
Update test file paths for common to point to compressed versions.
|
Update test file paths for common to point to compressed versions.
|
Python
|
bsd-3-clause
|
data-refinery/data_refinery,data-refinery/data_refinery,data-refinery/data_refinery
|
python
|
## Code Before:
from unittest.mock import Mock, patch
from django.test import TestCase
from data_refinery_common import microarray
CEL_FILE_HUMAN = "test-files/C30057.CEL"
CEL_FILE_RAT = "test-files/SG2_u34a.CEL"
CEL_FILE_MOUSE = "test-files/97_(Mouse430_2).CEL"
CEL_FILE_ZEBRAFISH = "test-files/CONTROL6.cel"
class MicroarrayTestCase(TestCase):
def test_get_platform_from_CEL(self):
self.assertEqual("hgu95av2", microarray.get_platform_from_CEL(CEL_FILE_HUMAN))
self.assertEqual("rgu34a", microarray.get_platform_from_CEL(CEL_FILE_RAT))
self.assertEqual("mouse4302", microarray.get_platform_from_CEL(CEL_FILE_MOUSE))
self.assertEqual("zebgene11st", microarray.get_platform_from_CEL(CEL_FILE_ZEBRAFISH))
## Instruction:
Update test file paths for common to point to compressed versions.
## Code After:
from unittest.mock import Mock, patch
from django.test import TestCase
from data_refinery_common import microarray
CEL_FILE_HUMAN = "test-files/C30057.CEL.gz"
CEL_FILE_RAT = "test-files/SG2_u34a.CEL.gz"
CEL_FILE_MOUSE = "test-files/97_(Mouse430_2).CEL.gz"
CEL_FILE_ZEBRAFISH = "test-files/CONTROL6.cel.gz"
class MicroarrayTestCase(TestCase):
def test_get_platform_from_CEL(self):
self.assertEqual("hgu95av2", microarray.get_platform_from_CEL(CEL_FILE_HUMAN))
self.assertEqual("rgu34a", microarray.get_platform_from_CEL(CEL_FILE_RAT))
self.assertEqual("mouse4302", microarray.get_platform_from_CEL(CEL_FILE_MOUSE))
self.assertEqual("zebgene11st", microarray.get_platform_from_CEL(CEL_FILE_ZEBRAFISH))
|
...
from django.test import TestCase
from data_refinery_common import microarray
CEL_FILE_HUMAN = "test-files/C30057.CEL.gz"
CEL_FILE_RAT = "test-files/SG2_u34a.CEL.gz"
CEL_FILE_MOUSE = "test-files/97_(Mouse430_2).CEL.gz"
CEL_FILE_ZEBRAFISH = "test-files/CONTROL6.cel.gz"
class MicroarrayTestCase(TestCase):
...
|
8ffe217fe512296d41ae474c9d145ee2de599eac
|
src/constants.py
|
src/constants.py
|
class AppUrl:
"""Class for storing all the URLs used in the application"""
BASE = "http://www.thehindu.com/"
OP_BASE = BASE + "opinion/"
OPINION = OP_BASE + "?service=rss"
EDITORIAL = OP_BASE + "editorial/?service=rss"
SAMPLE = BASE + "op-ed/a-super-visit-in-the-season-of-hope/article7214799.ece"
RSS_ARGS = "?utm_source=RSS_Feed&utm_medium=RSS&utm_campaign=RSS_Syndication"
class Kind:
#BLOGS = 'blogs'
#CARTOON = 'cartoon'
COLUMNS = 'columns'
EDITORIAL = 'editorial'
INTERVIEW = 'interview'
LEAD = 'lead'
#LETTERS = 'letters'
OP_ED = 'op-ed'
OPEN_PAGE = 'open-page'
#READERS_ED = 'Readers-Editor'
#SUNDAY_ANCHOR = 'sunday-anchor'
class Tags:
accepted = ['a', 'b', 'i', 'p']
|
class AppUrl:
"""Class for storing all the URLs used in the application"""
BASE = "http://www.thehindu.com/"
OP_BASE = BASE + "opinion/"
OPINION = OP_BASE + "?service=rss"
EDITORIAL = OP_BASE + "editorial/?service=rss"
SAMPLE = BASE + "op-ed/a-super-visit-in-the-season-of-hope/article7214799.ece"
RSS_ARGS = "?utm_source=RSS_Feed&utm_medium=RSS&utm_campaign=RSS_Syndication"
class Kind:
BLOGS = 'blogs'
CARTOON = 'cartoon'
COLUMNS = 'columns'
EDITORIAL = 'editorial'
INTERVIEW = 'interview'
LEAD = 'lead'
LETTERS = 'letters'
OP_ED = 'op-ed'
OPEN_PAGE = 'open-page'
READERS_ED = 'Readers-Editor'
SUNDAY_ANCHOR = 'sunday-anchor'
SUPPORTED = [COLUMNS, EDITORIAL, INTERVIEW, LEAD, OP_ED,
OPEN_PAGE]
class Tags:
accepted = ['a', 'b', 'i', 'p']
|
Include all but have a supported set
|
Include all but have a supported set
Rather than commenting out the values, this seems more sensible. And pretty.. of
course.
Signed-off-by: Venkatesh Shukla <[email protected]>
|
Python
|
mit
|
venkateshshukla/th-editorials-server
|
python
|
## Code Before:
class AppUrl:
"""Class for storing all the URLs used in the application"""
BASE = "http://www.thehindu.com/"
OP_BASE = BASE + "opinion/"
OPINION = OP_BASE + "?service=rss"
EDITORIAL = OP_BASE + "editorial/?service=rss"
SAMPLE = BASE + "op-ed/a-super-visit-in-the-season-of-hope/article7214799.ece"
RSS_ARGS = "?utm_source=RSS_Feed&utm_medium=RSS&utm_campaign=RSS_Syndication"
class Kind:
#BLOGS = 'blogs'
#CARTOON = 'cartoon'
COLUMNS = 'columns'
EDITORIAL = 'editorial'
INTERVIEW = 'interview'
LEAD = 'lead'
#LETTERS = 'letters'
OP_ED = 'op-ed'
OPEN_PAGE = 'open-page'
#READERS_ED = 'Readers-Editor'
#SUNDAY_ANCHOR = 'sunday-anchor'
class Tags:
accepted = ['a', 'b', 'i', 'p']
## Instruction:
Include all but have a supported set
Rather than commenting out the values, this seems more sensible. And pretty.. of
course.
Signed-off-by: Venkatesh Shukla <[email protected]>
## Code After:
class AppUrl:
"""Class for storing all the URLs used in the application"""
BASE = "http://www.thehindu.com/"
OP_BASE = BASE + "opinion/"
OPINION = OP_BASE + "?service=rss"
EDITORIAL = OP_BASE + "editorial/?service=rss"
SAMPLE = BASE + "op-ed/a-super-visit-in-the-season-of-hope/article7214799.ece"
RSS_ARGS = "?utm_source=RSS_Feed&utm_medium=RSS&utm_campaign=RSS_Syndication"
class Kind:
BLOGS = 'blogs'
CARTOON = 'cartoon'
COLUMNS = 'columns'
EDITORIAL = 'editorial'
INTERVIEW = 'interview'
LEAD = 'lead'
LETTERS = 'letters'
OP_ED = 'op-ed'
OPEN_PAGE = 'open-page'
READERS_ED = 'Readers-Editor'
SUNDAY_ANCHOR = 'sunday-anchor'
SUPPORTED = [COLUMNS, EDITORIAL, INTERVIEW, LEAD, OP_ED,
OPEN_PAGE]
class Tags:
accepted = ['a', 'b', 'i', 'p']
|
// ... existing code ...
RSS_ARGS = "?utm_source=RSS_Feed&utm_medium=RSS&utm_campaign=RSS_Syndication"
class Kind:
BLOGS = 'blogs'
CARTOON = 'cartoon'
COLUMNS = 'columns'
EDITORIAL = 'editorial'
INTERVIEW = 'interview'
LEAD = 'lead'
LETTERS = 'letters'
OP_ED = 'op-ed'
OPEN_PAGE = 'open-page'
READERS_ED = 'Readers-Editor'
SUNDAY_ANCHOR = 'sunday-anchor'
SUPPORTED = [COLUMNS, EDITORIAL, INTERVIEW, LEAD, OP_ED,
OPEN_PAGE]
class Tags:
accepted = ['a', 'b', 'i', 'p']
// ... rest of the code ...
|
f20e9bdc00909dab230c7135068abb32243f0cae
|
stroom-kafka/stroom-kafka-api/src/main/java/stroom/kafka/api/KafkaProducerSupplierKey.java
|
stroom-kafka/stroom-kafka-api/src/main/java/stroom/kafka/api/KafkaProducerSupplierKey.java
|
package stroom.kafka.api;
import stroom.kafka.shared.KafkaConfigDoc;
import java.util.Objects;
public class KafkaProducerSupplierKey {
private final String uuid;
private final String version;
public KafkaProducerSupplierKey(final KafkaConfigDoc kafkaConfigDoc) {
Objects.requireNonNull(kafkaConfigDoc);
this.uuid = Objects.requireNonNull(kafkaConfigDoc.getUuid());
this.version = Objects.requireNonNull(kafkaConfigDoc.getVersion());
}
public KafkaProducerSupplierKey(final String uuid, final String version) {
this.uuid = Objects.requireNonNull(uuid);
this.version = Objects.requireNonNull(version);
}
public String getUuid() {
return uuid;
}
public String getVersion() {
return version;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final KafkaProducerSupplierKey that = (KafkaProducerSupplierKey) o;
return uuid.equals(that.uuid) &&
version.equals(that.version);
}
@Override
public int hashCode() {
return Objects.hash(uuid, version);
}
@Override
public String toString() {
return "KafkaProducerSupplierKey{" +
"uuid='" + uuid + '\'' +
", version='" + version + '\'' +
'}';
}
}
|
package stroom.kafka.api;
import stroom.kafka.shared.KafkaConfigDoc;
import java.util.Objects;
public class KafkaProducerSupplierKey {
private final String uuid;
private final String version;
public KafkaProducerSupplierKey(final KafkaConfigDoc kafkaConfigDoc) {
Objects.requireNonNull(kafkaConfigDoc);
this.uuid = Objects.requireNonNull(kafkaConfigDoc.getUuid(), "KafkaConfigDoc is missing a UUID");
this.version = Objects.requireNonNull(kafkaConfigDoc.getVersion(), "KafkaConfigDoc is missing a version");
}
public KafkaProducerSupplierKey(final String uuid, final String version) {
this.uuid = Objects.requireNonNull(uuid);
this.version = Objects.requireNonNull(version);
}
public String getUuid() {
return uuid;
}
public String getVersion() {
return version;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final KafkaProducerSupplierKey that = (KafkaProducerSupplierKey) o;
return uuid.equals(that.uuid) &&
version.equals(that.version);
}
@Override
public int hashCode() {
return Objects.hash(uuid, version);
}
@Override
public String toString() {
return "KafkaProducerSupplierKey{" +
"uuid='" + uuid + '\'' +
", version='" + version + '\'' +
'}';
}
}
|
Add msgs to null check
|
Add msgs to null check
|
Java
|
apache-2.0
|
gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom
|
java
|
## Code Before:
package stroom.kafka.api;
import stroom.kafka.shared.KafkaConfigDoc;
import java.util.Objects;
public class KafkaProducerSupplierKey {
private final String uuid;
private final String version;
public KafkaProducerSupplierKey(final KafkaConfigDoc kafkaConfigDoc) {
Objects.requireNonNull(kafkaConfigDoc);
this.uuid = Objects.requireNonNull(kafkaConfigDoc.getUuid());
this.version = Objects.requireNonNull(kafkaConfigDoc.getVersion());
}
public KafkaProducerSupplierKey(final String uuid, final String version) {
this.uuid = Objects.requireNonNull(uuid);
this.version = Objects.requireNonNull(version);
}
public String getUuid() {
return uuid;
}
public String getVersion() {
return version;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final KafkaProducerSupplierKey that = (KafkaProducerSupplierKey) o;
return uuid.equals(that.uuid) &&
version.equals(that.version);
}
@Override
public int hashCode() {
return Objects.hash(uuid, version);
}
@Override
public String toString() {
return "KafkaProducerSupplierKey{" +
"uuid='" + uuid + '\'' +
", version='" + version + '\'' +
'}';
}
}
## Instruction:
Add msgs to null check
## Code After:
package stroom.kafka.api;
import stroom.kafka.shared.KafkaConfigDoc;
import java.util.Objects;
public class KafkaProducerSupplierKey {
private final String uuid;
private final String version;
public KafkaProducerSupplierKey(final KafkaConfigDoc kafkaConfigDoc) {
Objects.requireNonNull(kafkaConfigDoc);
this.uuid = Objects.requireNonNull(kafkaConfigDoc.getUuid(), "KafkaConfigDoc is missing a UUID");
this.version = Objects.requireNonNull(kafkaConfigDoc.getVersion(), "KafkaConfigDoc is missing a version");
}
public KafkaProducerSupplierKey(final String uuid, final String version) {
this.uuid = Objects.requireNonNull(uuid);
this.version = Objects.requireNonNull(version);
}
public String getUuid() {
return uuid;
}
public String getVersion() {
return version;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final KafkaProducerSupplierKey that = (KafkaProducerSupplierKey) o;
return uuid.equals(that.uuid) &&
version.equals(that.version);
}
@Override
public int hashCode() {
return Objects.hash(uuid, version);
}
@Override
public String toString() {
return "KafkaProducerSupplierKey{" +
"uuid='" + uuid + '\'' +
", version='" + version + '\'' +
'}';
}
}
|
// ... existing code ...
public KafkaProducerSupplierKey(final KafkaConfigDoc kafkaConfigDoc) {
Objects.requireNonNull(kafkaConfigDoc);
this.uuid = Objects.requireNonNull(kafkaConfigDoc.getUuid(), "KafkaConfigDoc is missing a UUID");
this.version = Objects.requireNonNull(kafkaConfigDoc.getVersion(), "KafkaConfigDoc is missing a version");
}
public KafkaProducerSupplierKey(final String uuid, final String version) {
// ... rest of the code ...
|
414f2dfe65cabed8ffd2913e35ed1d2db8ffd3bf
|
android/app/src/main/java/edu/berkeley/eecs/cfc_tracker/Constants.java
|
android/app/src/main/java/edu/berkeley/eecs/cfc_tracker/Constants.java
|
package edu.berkeley.eecs.cfc_tracker;
public final class Constants {
public static String LONGITUDE = "longitude";
public static String LATITUDE = "latitude";
public static String ACCELERATOR_X = "ax";
public static String ACCELERATOR_Y = "ay";
public static String ACCELERATOR_Z = "az";
public static String BATTERY_LEVEL = "battery_level";
public static String ACTIVITY_TYPE = "activity_type";
public static String ACTIVITY_CONFIDENCE = "activity_confidence";
public static int TRIP_EDGE_THRESHOLD = 100; // meters
public static final int MILLISECONDS = 1000; // used to make constants like 30 * MILLISECONDS
public static final int THIRTY_SECONDS = 30 * MILLISECONDS; // 30 secs, keep it similar to GPS
public static final int TWO_SECONDS = 2 * MILLISECONDS; // 2 secs, similar to Zheng 2010 paper
public static final int SIXTY_SECONDS = 60 * MILLISECONDS; // 1 min, similar to smalldata mobility
public static final long NANO2MS = 1000000;
public static String[] sensors = {LONGITUDE,
LATITUDE,
ACCELERATOR_X,
ACCELERATOR_Y,
ACCELERATOR_Z,
BATTERY_LEVEL,
ACTIVITY_TYPE,
ACTIVITY_CONFIDENCE};
}
|
package edu.berkeley.eecs.cfc_tracker;
public final class Constants {
public static String LONGITUDE = "longitude";
public static String LATITUDE = "latitude";
public static String ACCELERATOR_X = "ax";
public static String ACCELERATOR_Y = "ay";
public static String ACCELERATOR_Z = "az";
public static String BATTERY_LEVEL = "battery_level";
public static String ACTIVITY_TYPE = "activity_type";
public static String ACTIVITY_CONFIDENCE = "activity_confidence";
public static int TRIP_EDGE_THRESHOLD = 100; // meters
public static final int MILLISECONDS = 1000; // used to make constants like 30 * MILLISECONDS
public static final int THIRTY_SECONDS = 30 * MILLISECONDS; // 30 secs, keep it similar to GPS
public static final int TEN_SECONDS = 10 * MILLISECONDS; // 10 secs, similar to sensys paper
public static final int TWO_SECONDS = 2 * MILLISECONDS; // 2 secs, similar to Zheng 2010 paper
public static final int SIXTY_SECONDS = 60 * MILLISECONDS; // 1 min, similar to smalldata mobility
public static final long NANO2MS = 1000000;
public static String[] sensors = {LONGITUDE,
LATITUDE,
ACCELERATOR_X,
ACCELERATOR_Y,
ACCELERATOR_Z,
BATTERY_LEVEL,
ACTIVITY_TYPE,
ACTIVITY_CONFIDENCE};
}
|
Add a new constant for ten minutes, so that we can use it in the config
|
Add a new constant for ten minutes, so that we can use it in the config
|
Java
|
bsd-3-clause
|
e-mission/e-mission-data-collection,e-mission/e-mission-data-collection,shankari/e-mission-data-collection,shankari/e-mission-data-collection,e-mission/e-mission-data-collection,shankari/e-mission-data-collection
|
java
|
## Code Before:
package edu.berkeley.eecs.cfc_tracker;
public final class Constants {
public static String LONGITUDE = "longitude";
public static String LATITUDE = "latitude";
public static String ACCELERATOR_X = "ax";
public static String ACCELERATOR_Y = "ay";
public static String ACCELERATOR_Z = "az";
public static String BATTERY_LEVEL = "battery_level";
public static String ACTIVITY_TYPE = "activity_type";
public static String ACTIVITY_CONFIDENCE = "activity_confidence";
public static int TRIP_EDGE_THRESHOLD = 100; // meters
public static final int MILLISECONDS = 1000; // used to make constants like 30 * MILLISECONDS
public static final int THIRTY_SECONDS = 30 * MILLISECONDS; // 30 secs, keep it similar to GPS
public static final int TWO_SECONDS = 2 * MILLISECONDS; // 2 secs, similar to Zheng 2010 paper
public static final int SIXTY_SECONDS = 60 * MILLISECONDS; // 1 min, similar to smalldata mobility
public static final long NANO2MS = 1000000;
public static String[] sensors = {LONGITUDE,
LATITUDE,
ACCELERATOR_X,
ACCELERATOR_Y,
ACCELERATOR_Z,
BATTERY_LEVEL,
ACTIVITY_TYPE,
ACTIVITY_CONFIDENCE};
}
## Instruction:
Add a new constant for ten minutes, so that we can use it in the config
## Code After:
package edu.berkeley.eecs.cfc_tracker;
public final class Constants {
public static String LONGITUDE = "longitude";
public static String LATITUDE = "latitude";
public static String ACCELERATOR_X = "ax";
public static String ACCELERATOR_Y = "ay";
public static String ACCELERATOR_Z = "az";
public static String BATTERY_LEVEL = "battery_level";
public static String ACTIVITY_TYPE = "activity_type";
public static String ACTIVITY_CONFIDENCE = "activity_confidence";
public static int TRIP_EDGE_THRESHOLD = 100; // meters
public static final int MILLISECONDS = 1000; // used to make constants like 30 * MILLISECONDS
public static final int THIRTY_SECONDS = 30 * MILLISECONDS; // 30 secs, keep it similar to GPS
public static final int TEN_SECONDS = 10 * MILLISECONDS; // 10 secs, similar to sensys paper
public static final int TWO_SECONDS = 2 * MILLISECONDS; // 2 secs, similar to Zheng 2010 paper
public static final int SIXTY_SECONDS = 60 * MILLISECONDS; // 1 min, similar to smalldata mobility
public static final long NANO2MS = 1000000;
public static String[] sensors = {LONGITUDE,
LATITUDE,
ACCELERATOR_X,
ACCELERATOR_Y,
ACCELERATOR_Z,
BATTERY_LEVEL,
ACTIVITY_TYPE,
ACTIVITY_CONFIDENCE};
}
|
// ... existing code ...
public static final int MILLISECONDS = 1000; // used to make constants like 30 * MILLISECONDS
public static final int THIRTY_SECONDS = 30 * MILLISECONDS; // 30 secs, keep it similar to GPS
public static final int TEN_SECONDS = 10 * MILLISECONDS; // 10 secs, similar to sensys paper
public static final int TWO_SECONDS = 2 * MILLISECONDS; // 2 secs, similar to Zheng 2010 paper
public static final int SIXTY_SECONDS = 60 * MILLISECONDS; // 1 min, similar to smalldata mobility
public static final long NANO2MS = 1000000;
// ... rest of the code ...
|
d599ba152a6b52e0ea0aad387b08348f6bdb628a
|
app/src/main/java/cn/sunner/sms2calendar/N12306Parser.java
|
app/src/main/java/cn/sunner/sms2calendar/N12306Parser.java
|
package cn.sunner.sms2calendar;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by Sunner on 6/29/16.
*/
public class N12306Parser extends SMSParser {
public N12306Parser(String text) {
super(text);
}
@Override
protected boolean parse() {
String pattern = ".*[购|签](\\d+)月(\\d+)日(.+[号|铺])([^\\d]+)(\\d+):(\\d+)开。.*";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(text);
if (!m.matches()) {
return false;
}
this.title = m.group(3);
this.location = m.group(4);
this.beginTime = new GregorianCalendar(
Calendar.getInstance().get(Calendar.YEAR), // Use this year
Integer.parseInt(m.group(1)), // Month
Integer.parseInt(m.group(2)), // Day
Integer.parseInt(m.group(5)), // Hour
Integer.parseInt(m.group(6)) // Minute
);
// set end time to 1 hour later
endTime = (Calendar) beginTime.clone();
endTime.add(Calendar.HOUR, 1);
return true;
}
}
|
package cn.sunner.sms2calendar;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by Sunner on 6/29/16.
*/
public class N12306Parser extends SMSParser {
public N12306Parser(String text) {
super(text);
}
@Override
protected boolean parse() {
String pattern = ".*[购|签](\\d+)月(\\d+)日(.+[号|铺])([^\\d]+)(\\d+):(\\d+)开。.*";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(text);
if (!m.matches()) {
return false;
}
title = m.group(3);
location = m.group(4) + "站"; // Append 站 to make it more accurate for maps
beginTime = new GregorianCalendar(
Calendar.getInstance().get(Calendar.YEAR), // Use this year
Integer.parseInt(m.group(1)), // Month
Integer.parseInt(m.group(2)), // Day
Integer.parseInt(m.group(5)), // Hour
Integer.parseInt(m.group(6)) // Minute
);
// set end time to 1 hour later
endTime = (Calendar) beginTime.clone();
endTime.add(Calendar.HOUR, 1);
return true;
}
}
|
Append 站 to train station name
|
Append 站 to train station name
|
Java
|
mit
|
sunner/SMS2Calendar
|
java
|
## Code Before:
package cn.sunner.sms2calendar;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by Sunner on 6/29/16.
*/
public class N12306Parser extends SMSParser {
public N12306Parser(String text) {
super(text);
}
@Override
protected boolean parse() {
String pattern = ".*[购|签](\\d+)月(\\d+)日(.+[号|铺])([^\\d]+)(\\d+):(\\d+)开。.*";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(text);
if (!m.matches()) {
return false;
}
this.title = m.group(3);
this.location = m.group(4);
this.beginTime = new GregorianCalendar(
Calendar.getInstance().get(Calendar.YEAR), // Use this year
Integer.parseInt(m.group(1)), // Month
Integer.parseInt(m.group(2)), // Day
Integer.parseInt(m.group(5)), // Hour
Integer.parseInt(m.group(6)) // Minute
);
// set end time to 1 hour later
endTime = (Calendar) beginTime.clone();
endTime.add(Calendar.HOUR, 1);
return true;
}
}
## Instruction:
Append 站 to train station name
## Code After:
package cn.sunner.sms2calendar;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by Sunner on 6/29/16.
*/
public class N12306Parser extends SMSParser {
public N12306Parser(String text) {
super(text);
}
@Override
protected boolean parse() {
String pattern = ".*[购|签](\\d+)月(\\d+)日(.+[号|铺])([^\\d]+)(\\d+):(\\d+)开。.*";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(text);
if (!m.matches()) {
return false;
}
title = m.group(3);
location = m.group(4) + "站"; // Append 站 to make it more accurate for maps
beginTime = new GregorianCalendar(
Calendar.getInstance().get(Calendar.YEAR), // Use this year
Integer.parseInt(m.group(1)), // Month
Integer.parseInt(m.group(2)), // Day
Integer.parseInt(m.group(5)), // Hour
Integer.parseInt(m.group(6)) // Minute
);
// set end time to 1 hour later
endTime = (Calendar) beginTime.clone();
endTime.add(Calendar.HOUR, 1);
return true;
}
}
|
...
return false;
}
title = m.group(3);
location = m.group(4) + "站"; // Append 站 to make it more accurate for maps
beginTime = new GregorianCalendar(
Calendar.getInstance().get(Calendar.YEAR), // Use this year
Integer.parseInt(m.group(1)), // Month
Integer.parseInt(m.group(2)), // Day
...
|
741ffd11fa79172b6727c23a719704e4b1fa590a
|
org.springsource.ide.eclipse.commons.livexp/src/org/springsource/ide/eclipse/commons/livexp/core/ValueListener.java
|
org.springsource.ide.eclipse.commons.livexp/src/org/springsource/ide/eclipse/commons/livexp/core/ValueListener.java
|
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.livexp.core;
/**
* The interface that all those interested in receiving updates of the value of a Live expression
* should implement.
*
* @author Kris De Volder
*/
public interface ValueListener<T> {
void gotValue(LiveExpression<T> exp, T value);
}
|
/*******************************************************************************
* Copyright (c) 2012, 2017 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.livexp.core;
/**
* The interface that all those interested in receiving updates of the value of a Live expression
* should implement.
*
* @author Kris De Volder
*/
@FunctionalInterface
public interface ValueListener<T> {
void gotValue(LiveExpression<T> exp, T value);
}
|
Make it a functional interface to enable lambda syntax
|
Make it a functional interface to enable lambda syntax
|
Java
|
epl-1.0
|
spring-projects/eclipse-integration-commons,spring-projects/eclipse-integration-commons,spring-projects/eclipse-integration-commons
|
java
|
## Code Before:
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.livexp.core;
/**
* The interface that all those interested in receiving updates of the value of a Live expression
* should implement.
*
* @author Kris De Volder
*/
public interface ValueListener<T> {
void gotValue(LiveExpression<T> exp, T value);
}
## Instruction:
Make it a functional interface to enable lambda syntax
## Code After:
/*******************************************************************************
* Copyright (c) 2012, 2017 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.livexp.core;
/**
* The interface that all those interested in receiving updates of the value of a Live expression
* should implement.
*
* @author Kris De Volder
*/
@FunctionalInterface
public interface ValueListener<T> {
void gotValue(LiveExpression<T> exp, T value);
}
|
...
/*******************************************************************************
* Copyright (c) 2012, 2017 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
...
*
* @author Kris De Volder
*/
@FunctionalInterface
public interface ValueListener<T> {
void gotValue(LiveExpression<T> exp, T value);
}
...
|
71bc0919dd19f943624178639a6883ed4b26af7c
|
src/org/pentaho/ui/xul/swing/tags/SwingTab.java
|
src/org/pentaho/ui/xul/swing/tags/SwingTab.java
|
package org.pentaho.ui.xul.swing.tags;
import java.awt.GridBagLayout;
import javax.swing.JPanel;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.components.XulTab;
import org.pentaho.ui.xul.swing.SwingElement;
import org.pentaho.ui.xul.util.Orient;
public class SwingTab extends SwingElement implements XulTab{
private String label;
private boolean disabled = false;
private String onclick;
public SwingTab(XulComponent parent, XulDomContainer domContainer, String tagName) {
super("tab");
}
public boolean isDisabled() {
return disabled;
}
public String getLabel() {
return label;
}
public String getOnclick() {
return onclick;
}
public void setDisabled(boolean disabled) {
this.disabled = disabled;
}
public void setLabel(String label) {
this.label = label;
}
public void setOnclick(String onClick) {
this.onclick = onClick;
}
@Override
public void layout() {
}
}
|
package org.pentaho.ui.xul.swing.tags;
import java.awt.GridBagLayout;
import javax.swing.JPanel;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.components.XulTab;
import org.pentaho.ui.xul.swing.SwingElement;
import org.pentaho.ui.xul.util.Orient;
public class SwingTab extends SwingElement implements XulTab{
private String label;
private boolean disabled = false;
private String onclick;
public SwingTab(XulComponent parent, XulDomContainer domContainer, String tagName) {
super("tab");
managedObject = "empty";
}
public boolean isDisabled() {
return disabled;
}
public String getLabel() {
return label;
}
public String getOnclick() {
return onclick;
}
public void setDisabled(boolean disabled) {
this.disabled = disabled;
}
public void setLabel(String label) {
this.label = label;
}
public void setOnclick(String onClick) {
this.onclick = onClick;
}
@Override
public void layout() {
}
}
|
Set the ManagedObject to empty
|
Set the ManagedObject to empty
|
Java
|
lgpl-2.1
|
pentaho/pentaho-commons-xul
|
java
|
## Code Before:
package org.pentaho.ui.xul.swing.tags;
import java.awt.GridBagLayout;
import javax.swing.JPanel;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.components.XulTab;
import org.pentaho.ui.xul.swing.SwingElement;
import org.pentaho.ui.xul.util.Orient;
public class SwingTab extends SwingElement implements XulTab{
private String label;
private boolean disabled = false;
private String onclick;
public SwingTab(XulComponent parent, XulDomContainer domContainer, String tagName) {
super("tab");
}
public boolean isDisabled() {
return disabled;
}
public String getLabel() {
return label;
}
public String getOnclick() {
return onclick;
}
public void setDisabled(boolean disabled) {
this.disabled = disabled;
}
public void setLabel(String label) {
this.label = label;
}
public void setOnclick(String onClick) {
this.onclick = onClick;
}
@Override
public void layout() {
}
}
## Instruction:
Set the ManagedObject to empty
## Code After:
package org.pentaho.ui.xul.swing.tags;
import java.awt.GridBagLayout;
import javax.swing.JPanel;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.components.XulTab;
import org.pentaho.ui.xul.swing.SwingElement;
import org.pentaho.ui.xul.util.Orient;
public class SwingTab extends SwingElement implements XulTab{
private String label;
private boolean disabled = false;
private String onclick;
public SwingTab(XulComponent parent, XulDomContainer domContainer, String tagName) {
super("tab");
managedObject = "empty";
}
public boolean isDisabled() {
return disabled;
}
public String getLabel() {
return label;
}
public String getOnclick() {
return onclick;
}
public void setDisabled(boolean disabled) {
this.disabled = disabled;
}
public void setLabel(String label) {
this.label = label;
}
public void setOnclick(String onClick) {
this.onclick = onClick;
}
@Override
public void layout() {
}
}
|
...
public SwingTab(XulComponent parent, XulDomContainer domContainer, String tagName) {
super("tab");
managedObject = "empty";
}
public boolean isDisabled() {
...
|
6d2255b6f44a18bae0b50fb528564c6767683c68
|
src/bindings/python/test/test.py
|
src/bindings/python/test/test.py
|
def test_error(msg):
import sys
sys.stderr.write('Error: %s\n' % msg)
def expect_exception(action, kind, func, *args):
got_exception = False
try:
func(*args)
except kind:
got_exception = True
except:
pass
if not got_exception:
test_error('Did not get exception when %s' % action)
|
def test_error(msg):
import sys
sys.stderr.write('Error: %s\n' % msg)
def expect_exception(action, kind, func, *args):
got_exception = False
try:
func(*args)
except kind:
got_exception = True
except BaseException as e:
test_error('Got unexpected exception: %s' % str(e))
got_exception = True
except:
test_error('Got non-standard exception')
got_exception = True
if not got_exception:
test_error('Did not get exception when %s' % action)
|
Update Python expect_exception to be like C++'s
|
Update Python expect_exception to be like C++'s
|
Python
|
bsd-3-clause
|
Kitware/sprokit,Kitware/sprokit,linus-sherrill/sprokit,Kitware/sprokit,mathstuf/sprokit,linus-sherrill/sprokit,linus-sherrill/sprokit,mathstuf/sprokit,mathstuf/sprokit,mathstuf/sprokit,linus-sherrill/sprokit,Kitware/sprokit
|
python
|
## Code Before:
def test_error(msg):
import sys
sys.stderr.write('Error: %s\n' % msg)
def expect_exception(action, kind, func, *args):
got_exception = False
try:
func(*args)
except kind:
got_exception = True
except:
pass
if not got_exception:
test_error('Did not get exception when %s' % action)
## Instruction:
Update Python expect_exception to be like C++'s
## Code After:
def test_error(msg):
import sys
sys.stderr.write('Error: %s\n' % msg)
def expect_exception(action, kind, func, *args):
got_exception = False
try:
func(*args)
except kind:
got_exception = True
except BaseException as e:
test_error('Got unexpected exception: %s' % str(e))
got_exception = True
except:
test_error('Got non-standard exception')
got_exception = True
if not got_exception:
test_error('Did not get exception when %s' % action)
|
// ... existing code ...
func(*args)
except kind:
got_exception = True
except BaseException as e:
test_error('Got unexpected exception: %s' % str(e))
got_exception = True
except:
test_error('Got non-standard exception')
got_exception = True
if not got_exception:
test_error('Did not get exception when %s' % action)
// ... rest of the code ...
|
c79489d69b73dc523442fa797b5cc38a8c841f35
|
src/kernel/thread/signal/sigstd_stub.h
|
src/kernel/thread/signal/sigstd_stub.h
|
/**
* @file
* @brief Stubs for standard signals.
*
* @date 07.10.2013
* @author Eldar Abusalimov
*/
#ifndef KERNEL_THREAD_SIGSTD_STUB_H_
#define KERNEL_THREAD_SIGSTD_STUB_H_
#include <errno.h>
#define SIGSTD_MIN 0
#define SIGSTD_MAX -1
struct sigstd_data { }; /* stub */
static inline struct sigstd_data * sigstd_data_init(
struct sigstd_data *sigstd_data) {
return sigstd_data;
}
static inline int sigstd_raise(struct sigstd_data *data, int sig) {
return -ENOSYS;
}
static inline void sigstd_handle(struct sigstd_data *data,
struct sigaction *sig_table) {
/* no-op */
}
#endif /* KERNEL_THREAD_SIGSTD_STUB_H_ */
|
/**
* @file
* @brief Stubs for standard signals.
*
* @date 07.10.2013
* @author Eldar Abusalimov
*/
#ifndef KERNEL_THREAD_SIGSTD_STUB_H_
#define KERNEL_THREAD_SIGSTD_STUB_H_
#include <errno.h>
#include <signal.h>
#define SIGSTD_MIN 0
#define SIGSTD_MAX -1
struct sigstd_data { }; /* stub */
static inline struct sigstd_data * sigstd_data_init(
struct sigstd_data *sigstd_data) {
return sigstd_data;
}
static inline int sigstd_raise(struct sigstd_data *data, int sig) {
return -ENOSYS;
}
static inline void sigstd_handle(struct sigstd_data *data,
struct sigaction *sig_table) {
/* no-op */
}
#endif /* KERNEL_THREAD_SIGSTD_STUB_H_ */
|
Fix stub implementation (add missing sigaction decl)
|
signal: Fix stub implementation (add missing sigaction decl)
|
C
|
bsd-2-clause
|
mike2390/embox,Kefir0192/embox,mike2390/embox,Kakadu/embox,embox/embox,embox/embox,vrxfile/embox-trik,vrxfile/embox-trik,Kakadu/embox,Kefir0192/embox,Kefir0192/embox,Kefir0192/embox,embox/embox,abusalimov/embox,vrxfile/embox-trik,abusalimov/embox,mike2390/embox,Kefir0192/embox,gzoom13/embox,Kakadu/embox,vrxfile/embox-trik,Kakadu/embox,embox/embox,gzoom13/embox,mike2390/embox,mike2390/embox,gzoom13/embox,Kakadu/embox,gzoom13/embox,abusalimov/embox,embox/embox,Kakadu/embox,mike2390/embox,vrxfile/embox-trik,gzoom13/embox,Kefir0192/embox,embox/embox,abusalimov/embox,gzoom13/embox,vrxfile/embox-trik,vrxfile/embox-trik,Kakadu/embox,gzoom13/embox,abusalimov/embox,abusalimov/embox,mike2390/embox,Kefir0192/embox
|
c
|
## Code Before:
/**
* @file
* @brief Stubs for standard signals.
*
* @date 07.10.2013
* @author Eldar Abusalimov
*/
#ifndef KERNEL_THREAD_SIGSTD_STUB_H_
#define KERNEL_THREAD_SIGSTD_STUB_H_
#include <errno.h>
#define SIGSTD_MIN 0
#define SIGSTD_MAX -1
struct sigstd_data { }; /* stub */
static inline struct sigstd_data * sigstd_data_init(
struct sigstd_data *sigstd_data) {
return sigstd_data;
}
static inline int sigstd_raise(struct sigstd_data *data, int sig) {
return -ENOSYS;
}
static inline void sigstd_handle(struct sigstd_data *data,
struct sigaction *sig_table) {
/* no-op */
}
#endif /* KERNEL_THREAD_SIGSTD_STUB_H_ */
## Instruction:
signal: Fix stub implementation (add missing sigaction decl)
## Code After:
/**
* @file
* @brief Stubs for standard signals.
*
* @date 07.10.2013
* @author Eldar Abusalimov
*/
#ifndef KERNEL_THREAD_SIGSTD_STUB_H_
#define KERNEL_THREAD_SIGSTD_STUB_H_
#include <errno.h>
#include <signal.h>
#define SIGSTD_MIN 0
#define SIGSTD_MAX -1
struct sigstd_data { }; /* stub */
static inline struct sigstd_data * sigstd_data_init(
struct sigstd_data *sigstd_data) {
return sigstd_data;
}
static inline int sigstd_raise(struct sigstd_data *data, int sig) {
return -ENOSYS;
}
static inline void sigstd_handle(struct sigstd_data *data,
struct sigaction *sig_table) {
/* no-op */
}
#endif /* KERNEL_THREAD_SIGSTD_STUB_H_ */
|
...
#define KERNEL_THREAD_SIGSTD_STUB_H_
#include <errno.h>
#include <signal.h>
#define SIGSTD_MIN 0
#define SIGSTD_MAX -1
...
|
0acc6aa692d3993548db0daac61212b80b931b9b
|
archetypes/quickstart/src/main/resources/archetype-resources/src/main/java/WicketApplication.java
|
archetypes/quickstart/src/main/resources/archetype-resources/src/main/java/WicketApplication.java
|
package ${package};
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.protocol.http.WebApplication;
/**
* Application object for your web application.
* If you want to run this application without deploying, run the Start class.
*
* @see ${package}.Start#main(String[])
*/
public class WicketApplication extends WebApplication
{
/**
* @see org.apache.wicket.Application#getHomePage()
*/
@Override
public Class<? extends WebPage> getHomePage()
{
return HomePage.class;
}
/**
* @see org.apache.wicket.Application#init()
*/
@Override
public void init()
{
super.init();
// add your configuration here
}
}
|
package ${package};
import org.apache.wicket.csp.CSPDirective;
import org.apache.wicket.csp.CSPDirectiveSrcValue;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.protocol.http.WebApplication;
/**
* Application object for your web application.
* If you want to run this application without deploying, run the Start class.
*
* @see ${package}.Start#main(String[])
*/
public class WicketApplication extends WebApplication
{
/**
* @see org.apache.wicket.Application#getHomePage()
*/
@Override
public Class<? extends WebPage> getHomePage()
{
return HomePage.class;
}
/**
* @see org.apache.wicket.Application#init()
*/
@Override
public void init()
{
super.init();
// needed for the styling used by the quickstart
getCspSettings().blocking()
.add(CSPDirective.STYLE_SRC, CSPDirectiveSrcValue.SELF)
.add(CSPDirective.STYLE_SRC, "https://fonts.googleapis.com/css")
.add(CSPDirective.FONT_SRC, "https://fonts.gstatic.com");
// add your configuration here
}
}
|
Fix CSP for styling in quickstart
|
WICKET-6849: Fix CSP for styling in quickstart
|
Java
|
apache-2.0
|
mosoft521/wicket,mosoft521/wicket,mosoft521/wicket,apache/wicket,apache/wicket,mosoft521/wicket,mosoft521/wicket,apache/wicket,apache/wicket,apache/wicket
|
java
|
## Code Before:
package ${package};
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.protocol.http.WebApplication;
/**
* Application object for your web application.
* If you want to run this application without deploying, run the Start class.
*
* @see ${package}.Start#main(String[])
*/
public class WicketApplication extends WebApplication
{
/**
* @see org.apache.wicket.Application#getHomePage()
*/
@Override
public Class<? extends WebPage> getHomePage()
{
return HomePage.class;
}
/**
* @see org.apache.wicket.Application#init()
*/
@Override
public void init()
{
super.init();
// add your configuration here
}
}
## Instruction:
WICKET-6849: Fix CSP for styling in quickstart
## Code After:
package ${package};
import org.apache.wicket.csp.CSPDirective;
import org.apache.wicket.csp.CSPDirectiveSrcValue;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.protocol.http.WebApplication;
/**
* Application object for your web application.
* If you want to run this application without deploying, run the Start class.
*
* @see ${package}.Start#main(String[])
*/
public class WicketApplication extends WebApplication
{
/**
* @see org.apache.wicket.Application#getHomePage()
*/
@Override
public Class<? extends WebPage> getHomePage()
{
return HomePage.class;
}
/**
* @see org.apache.wicket.Application#init()
*/
@Override
public void init()
{
super.init();
// needed for the styling used by the quickstart
getCspSettings().blocking()
.add(CSPDirective.STYLE_SRC, CSPDirectiveSrcValue.SELF)
.add(CSPDirective.STYLE_SRC, "https://fonts.googleapis.com/css")
.add(CSPDirective.FONT_SRC, "https://fonts.gstatic.com");
// add your configuration here
}
}
|
...
package ${package};
import org.apache.wicket.csp.CSPDirective;
import org.apache.wicket.csp.CSPDirectiveSrcValue;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.protocol.http.WebApplication;
...
{
super.init();
// needed for the styling used by the quickstart
getCspSettings().blocking()
.add(CSPDirective.STYLE_SRC, CSPDirectiveSrcValue.SELF)
.add(CSPDirective.STYLE_SRC, "https://fonts.googleapis.com/css")
.add(CSPDirective.FONT_SRC, "https://fonts.gstatic.com");
// add your configuration here
}
}
...
|
fafd639feb967c57a58c7d139f58df9e67b59ca4
|
android/src/playn/android/AndroidFont.java
|
android/src/playn/android/AndroidFont.java
|
/**
* Copyright 2011 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package playn.android;
import android.graphics.Typeface;
import java.util.HashMap;
import java.util.Map;
import playn.core.AbstractFont;
class AndroidFont extends AbstractFont {
public final Typeface typeface;
public AndroidFont(String name, Style style, float size) {
super(name, style, size);
this.typeface = Typeface.create(name, TO_ANDROID_STYLE.get(style));
}
protected static final Map<Style,Integer> TO_ANDROID_STYLE = new HashMap<Style,Integer>();
static {
TO_ANDROID_STYLE.put(Style.PLAIN, Typeface.NORMAL);
TO_ANDROID_STYLE.put(Style.BOLD, Typeface.BOLD);
TO_ANDROID_STYLE.put(Style.ITALIC, Typeface.ITALIC);
TO_ANDROID_STYLE.put(Style.BOLD_ITALIC, Typeface.BOLD_ITALIC);
}
}
|
/**
* Copyright 2011 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package playn.android;
import android.graphics.Typeface;
import java.util.EnumMap;
import java.util.Map;
import playn.core.AbstractFont;
class AndroidFont extends AbstractFont {
public final Typeface typeface;
public AndroidFont(String name, Style style, float size) {
super(name, style, size);
this.typeface = Typeface.create(name, TO_ANDROID_STYLE.get(style));
}
protected static final Map<Style,Integer> TO_ANDROID_STYLE =
new EnumMap<Style,Integer>(Style.class);
static {
TO_ANDROID_STYLE.put(Style.PLAIN, Typeface.NORMAL);
TO_ANDROID_STYLE.put(Style.BOLD, Typeface.BOLD);
TO_ANDROID_STYLE.put(Style.ITALIC, Typeface.ITALIC);
TO_ANDROID_STYLE.put(Style.BOLD_ITALIC, Typeface.BOLD_ITALIC);
}
}
|
Use an EnumMap rather than a HashMap.
|
Use an EnumMap rather than a HashMap.
|
Java
|
apache-2.0
|
Just-/playn,Just-/playn,KoriSamui/PlayN,KoriSamui/PlayN,Just-/playn,Just-/playn,Just-/playn,KoriSamui/PlayN,KoriSamui/PlayN
|
java
|
## Code Before:
/**
* Copyright 2011 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package playn.android;
import android.graphics.Typeface;
import java.util.HashMap;
import java.util.Map;
import playn.core.AbstractFont;
class AndroidFont extends AbstractFont {
public final Typeface typeface;
public AndroidFont(String name, Style style, float size) {
super(name, style, size);
this.typeface = Typeface.create(name, TO_ANDROID_STYLE.get(style));
}
protected static final Map<Style,Integer> TO_ANDROID_STYLE = new HashMap<Style,Integer>();
static {
TO_ANDROID_STYLE.put(Style.PLAIN, Typeface.NORMAL);
TO_ANDROID_STYLE.put(Style.BOLD, Typeface.BOLD);
TO_ANDROID_STYLE.put(Style.ITALIC, Typeface.ITALIC);
TO_ANDROID_STYLE.put(Style.BOLD_ITALIC, Typeface.BOLD_ITALIC);
}
}
## Instruction:
Use an EnumMap rather than a HashMap.
## Code After:
/**
* Copyright 2011 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package playn.android;
import android.graphics.Typeface;
import java.util.EnumMap;
import java.util.Map;
import playn.core.AbstractFont;
class AndroidFont extends AbstractFont {
public final Typeface typeface;
public AndroidFont(String name, Style style, float size) {
super(name, style, size);
this.typeface = Typeface.create(name, TO_ANDROID_STYLE.get(style));
}
protected static final Map<Style,Integer> TO_ANDROID_STYLE =
new EnumMap<Style,Integer>(Style.class);
static {
TO_ANDROID_STYLE.put(Style.PLAIN, Typeface.NORMAL);
TO_ANDROID_STYLE.put(Style.BOLD, Typeface.BOLD);
TO_ANDROID_STYLE.put(Style.ITALIC, Typeface.ITALIC);
TO_ANDROID_STYLE.put(Style.BOLD_ITALIC, Typeface.BOLD_ITALIC);
}
}
|
...
import android.graphics.Typeface;
import java.util.EnumMap;
import java.util.Map;
import playn.core.AbstractFont;
...
this.typeface = Typeface.create(name, TO_ANDROID_STYLE.get(style));
}
protected static final Map<Style,Integer> TO_ANDROID_STYLE =
new EnumMap<Style,Integer>(Style.class);
static {
TO_ANDROID_STYLE.put(Style.PLAIN, Typeface.NORMAL);
TO_ANDROID_STYLE.put(Style.BOLD, Typeface.BOLD);
...
|
5b554752aaabd59b8248f9eecfc03458dd9f07d0
|
coding/admin.py
|
coding/admin.py
|
from django.contrib import admin
from coding.models import (
Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity)
class SampleAdmin(admin.ModelAdmin):
filter_horizontal = ("pieces",)
admin.site.register(Sample, SampleAdmin)
class AssignmentTagAdmin(admin.ModelAdmin):
list_filter = ("study",)
list_display = ("name", "study",)
admin.site.register(AssignmentTag, AssignmentTagAdmin)
class CodingAssignmentAdmin(admin.ModelAdmin):
list_filter = ("coder", "tags", "piece__tags", "sample", "state")
list_display = (
"piece", "coder",
"sample", "state", "creation_time")
search_fields = ("piece__id", "piece__title", "sample__name")
filter_horizontal = ("tags",)
admin.site.register(CodingAssignment, CodingAssignmentAdmin)
class CodingAssignmentActivityAdmin(admin.ModelAdmin):
search_fields = (
"assignment__piece__id",
"assignment__piece__title",
"actor__name",
)
list_display = ("assignment", "action_time", "actor", "action", "state")
list_filter = ("actor", "action", "state")
admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin)
|
from django.contrib import admin
from coding.models import (
Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity)
class SampleAdmin(admin.ModelAdmin):
filter_horizontal = ("pieces",)
admin.site.register(Sample, SampleAdmin)
class AssignmentTagAdmin(admin.ModelAdmin):
list_filter = ("study",)
list_display = ("name", "study",)
admin.site.register(AssignmentTag, AssignmentTagAdmin)
class CodingAssignmentAdmin(admin.ModelAdmin):
list_filter = ("coder", "tags", "piece__tags", "sample", "state")
list_display = (
"piece", "coder",
"sample", "state", "creation_time")
search_fields = ("piece__id", "piece__title", "sample__name")
filter_horizontal = ("tags",)
admin.site.register(CodingAssignment, CodingAssignmentAdmin)
class CodingAssignmentActivityAdmin(admin.ModelAdmin):
search_fields = (
"assignment__piece__id",
"assignment__piece__title",
"actor__name",
)
list_display = ("assignment", "action_time", "actor", "action", "state")
list_filter = ("actor", "action", "state")
date_hierarchy = "action_time"
admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin)
|
Add date drill down to coding assignment activity list
|
Add date drill down to coding assignment activity list
|
Python
|
mit
|
inducer/codery,inducer/codery
|
python
|
## Code Before:
from django.contrib import admin
from coding.models import (
Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity)
class SampleAdmin(admin.ModelAdmin):
filter_horizontal = ("pieces",)
admin.site.register(Sample, SampleAdmin)
class AssignmentTagAdmin(admin.ModelAdmin):
list_filter = ("study",)
list_display = ("name", "study",)
admin.site.register(AssignmentTag, AssignmentTagAdmin)
class CodingAssignmentAdmin(admin.ModelAdmin):
list_filter = ("coder", "tags", "piece__tags", "sample", "state")
list_display = (
"piece", "coder",
"sample", "state", "creation_time")
search_fields = ("piece__id", "piece__title", "sample__name")
filter_horizontal = ("tags",)
admin.site.register(CodingAssignment, CodingAssignmentAdmin)
class CodingAssignmentActivityAdmin(admin.ModelAdmin):
search_fields = (
"assignment__piece__id",
"assignment__piece__title",
"actor__name",
)
list_display = ("assignment", "action_time", "actor", "action", "state")
list_filter = ("actor", "action", "state")
admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin)
## Instruction:
Add date drill down to coding assignment activity list
## Code After:
from django.contrib import admin
from coding.models import (
Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity)
class SampleAdmin(admin.ModelAdmin):
filter_horizontal = ("pieces",)
admin.site.register(Sample, SampleAdmin)
class AssignmentTagAdmin(admin.ModelAdmin):
list_filter = ("study",)
list_display = ("name", "study",)
admin.site.register(AssignmentTag, AssignmentTagAdmin)
class CodingAssignmentAdmin(admin.ModelAdmin):
list_filter = ("coder", "tags", "piece__tags", "sample", "state")
list_display = (
"piece", "coder",
"sample", "state", "creation_time")
search_fields = ("piece__id", "piece__title", "sample__name")
filter_horizontal = ("tags",)
admin.site.register(CodingAssignment, CodingAssignmentAdmin)
class CodingAssignmentActivityAdmin(admin.ModelAdmin):
search_fields = (
"assignment__piece__id",
"assignment__piece__title",
"actor__name",
)
list_display = ("assignment", "action_time", "actor", "action", "state")
list_filter = ("actor", "action", "state")
date_hierarchy = "action_time"
admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin)
|
...
list_display = ("assignment", "action_time", "actor", "action", "state")
list_filter = ("actor", "action", "state")
date_hierarchy = "action_time"
admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin)
...
|
e91ea4573b33e5c369d98f37a2d2da99e0332299
|
src/com/soofw/trk/ActionDialogFragment.java
|
src/com/soofw/trk/ActionDialogFragment.java
|
package com.soofw.trk;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
public class ActionDialogFragment extends DialogFragment {
final static int EDIT = 0;
Main activity;
Task task;
public ActionDialogFragment(Task task) {
this.task = task;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
this.activity = (Main)this.getActivity();
String[] actions = new String[2];
actions[0] = "Edit";
actions[1] = "(complex tags here)";
AlertDialog.Builder builder = new AlertDialog.Builder(this.activity);
builder.setItems(actions, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(which == ActionDialogFragment.EDIT) {
new EditDialogFragment(ActionDialogFragment.this.task)
.show(ActionDialogFragment.this.activity.getSupportFragmentManager(), "tag!");
}
}
});
return builder.create();
}
}
|
package com.soofw.trk;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
public class ActionDialogFragment extends DialogFragment {
final static int EDIT = 0;
Main activity;
Task task;
public ActionDialogFragment(Task task) {
this.task = task;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
this.activity = (Main)this.getActivity();
String[] tags = this.task.getTags();
String[] actions = new String[tags.length + 1];
actions[0] = "Edit";
System.arraycopy(tags, 0, actions, 1, tags.length);
AlertDialog.Builder builder = new AlertDialog.Builder(this.activity);
builder.setItems(actions, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(which == ActionDialogFragment.EDIT) {
new EditDialogFragment(ActionDialogFragment.this.task)
.show(ActionDialogFragment.this.activity.getSupportFragmentManager(), "tag!");
}
}
});
return builder.create();
}
}
|
Add dummy tag buttons in the menu
|
Add dummy tag buttons in the menu
|
Java
|
mit
|
scizzorz/trk-android
|
java
|
## Code Before:
package com.soofw.trk;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
public class ActionDialogFragment extends DialogFragment {
final static int EDIT = 0;
Main activity;
Task task;
public ActionDialogFragment(Task task) {
this.task = task;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
this.activity = (Main)this.getActivity();
String[] actions = new String[2];
actions[0] = "Edit";
actions[1] = "(complex tags here)";
AlertDialog.Builder builder = new AlertDialog.Builder(this.activity);
builder.setItems(actions, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(which == ActionDialogFragment.EDIT) {
new EditDialogFragment(ActionDialogFragment.this.task)
.show(ActionDialogFragment.this.activity.getSupportFragmentManager(), "tag!");
}
}
});
return builder.create();
}
}
## Instruction:
Add dummy tag buttons in the menu
## Code After:
package com.soofw.trk;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
public class ActionDialogFragment extends DialogFragment {
final static int EDIT = 0;
Main activity;
Task task;
public ActionDialogFragment(Task task) {
this.task = task;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
this.activity = (Main)this.getActivity();
String[] tags = this.task.getTags();
String[] actions = new String[tags.length + 1];
actions[0] = "Edit";
System.arraycopy(tags, 0, actions, 1, tags.length);
AlertDialog.Builder builder = new AlertDialog.Builder(this.activity);
builder.setItems(actions, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(which == ActionDialogFragment.EDIT) {
new EditDialogFragment(ActionDialogFragment.this.task)
.show(ActionDialogFragment.this.activity.getSupportFragmentManager(), "tag!");
}
}
});
return builder.create();
}
}
|
# ... existing code ...
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
this.activity = (Main)this.getActivity();
String[] tags = this.task.getTags();
String[] actions = new String[tags.length + 1];
actions[0] = "Edit";
System.arraycopy(tags, 0, actions, 1, tags.length);
AlertDialog.Builder builder = new AlertDialog.Builder(this.activity);
builder.setItems(actions, new DialogInterface.OnClickListener() {
# ... rest of the code ...
|
1cbd0ce39e2e4d2b704787989bf9deb99c68aaa9
|
setup.py
|
setup.py
|
from distutils.core import setup
import py2exe
setup(
console=[{'script':'check_forbidden.py','version':'1.1.0',}],
)
'''
cd dropbox/codes/check_forbidden
py -3.4 setup.py py2exe
'''
|
from distutils.core import setup
import py2exe
setup(
console=[{'script': 'check_forbidden.py', 'version': '1.1.3', }],
options={'py2exe': {'bundle_files': 2}}
)
'''
cd dropbox/codes/check_forbidden
py -3.4 setup.py py2exe
'''
|
Reduce the number of files in dist folder
|
Reduce the number of files in dist folder
|
Python
|
mit
|
ShunSakurai/check_forbidden,ShunSakurai/check_forbidden
|
python
|
## Code Before:
from distutils.core import setup
import py2exe
setup(
console=[{'script':'check_forbidden.py','version':'1.1.0',}],
)
'''
cd dropbox/codes/check_forbidden
py -3.4 setup.py py2exe
'''
## Instruction:
Reduce the number of files in dist folder
## Code After:
from distutils.core import setup
import py2exe
setup(
console=[{'script': 'check_forbidden.py', 'version': '1.1.3', }],
options={'py2exe': {'bundle_files': 2}}
)
'''
cd dropbox/codes/check_forbidden
py -3.4 setup.py py2exe
'''
|
// ... existing code ...
import py2exe
setup(
console=[{'script': 'check_forbidden.py', 'version': '1.1.3', }],
options={'py2exe': {'bundle_files': 2}}
)
'''
// ... rest of the code ...
|
74dae36d88c535ac54c0f82cc412f576c3d6be86
|
problem-spring-web-autoconfigure/src/main/java/org/zalando/problem/spring/web/autoconfigure/ProblemAutoConfiguration.java
|
problem-spring-web-autoconfigure/src/main/java/org/zalando/problem/spring/web/autoconfigure/ProblemAutoConfiguration.java
|
package org.zalando.problem.spring.web.autoconfigure;
import org.apiguardian.api.API;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
import org.zalando.problem.spring.web.advice.AdviceTrait;
import static org.apiguardian.api.API.Status.INTERNAL;
@API(status = INTERNAL)
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication
@ConditionalOnClass(WebSecurityConfigurer.class)
public class ProblemAutoConfiguration {
@Bean
@ConditionalOnMissingBean(AdviceTrait.class)
public AdviceTrait exceptionHandling() {
return new ExceptionHandling();
}
}
|
package org.zalando.problem.spring.web.autoconfigure;
import org.apiguardian.api.API;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zalando.problem.spring.web.advice.AdviceTrait;
import static org.apiguardian.api.API.Status.INTERNAL;
@API(status = INTERNAL)
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication
public class ProblemAutoConfiguration {
@Bean
@ConditionalOnMissingBean(AdviceTrait.class)
public AdviceTrait exceptionHandling() {
return new ExceptionHandling();
}
}
|
Remove Spring Security class dependency
|
Remove Spring Security class dependency
|
Java
|
mit
|
zalando/problem-spring-web,zalando/problem-spring-web
|
java
|
## Code Before:
package org.zalando.problem.spring.web.autoconfigure;
import org.apiguardian.api.API;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
import org.zalando.problem.spring.web.advice.AdviceTrait;
import static org.apiguardian.api.API.Status.INTERNAL;
@API(status = INTERNAL)
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication
@ConditionalOnClass(WebSecurityConfigurer.class)
public class ProblemAutoConfiguration {
@Bean
@ConditionalOnMissingBean(AdviceTrait.class)
public AdviceTrait exceptionHandling() {
return new ExceptionHandling();
}
}
## Instruction:
Remove Spring Security class dependency
## Code After:
package org.zalando.problem.spring.web.autoconfigure;
import org.apiguardian.api.API;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zalando.problem.spring.web.advice.AdviceTrait;
import static org.apiguardian.api.API.Status.INTERNAL;
@API(status = INTERNAL)
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication
public class ProblemAutoConfiguration {
@Bean
@ConditionalOnMissingBean(AdviceTrait.class)
public AdviceTrait exceptionHandling() {
return new ExceptionHandling();
}
}
|
# ... existing code ...
package org.zalando.problem.spring.web.autoconfigure;
import org.apiguardian.api.API;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zalando.problem.spring.web.advice.AdviceTrait;
import static org.apiguardian.api.API.Status.INTERNAL;
# ... modified code ...
@API(status = INTERNAL)
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication
public class ProblemAutoConfiguration {
@Bean
# ... rest of the code ...
|
599e2328ba0ab4f5fa467a363e35b8c99392ad3c
|
elvis/utils.py
|
elvis/utils.py
|
from datetime import datetime, timedelta
import pytz
DATE_PREFIX = '/Date('
DATE_SUFFIX = ')/'
ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn')
def decode_elvis_timestamp(timestamp: str):
"""Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible"""
str_timestamp = str(timestamp).strip()
if str_timestamp.startswith(DATE_PREFIX) and str_timestamp.endswith(DATE_SUFFIX):
milliseconds = str_timestamp[len(DATE_PREFIX):-len(DATE_SUFFIX)]
timezone_offset = 0
try:
if "+" in milliseconds:
timezone_offset_string = milliseconds[milliseconds.index("+")+1:]
milliseconds = milliseconds[:milliseconds.index("+")]
if len(timezone_offset_string) == 4:
timezone_offset = int(timezone_offset_string[:2])*60+int(timezone_offset_string[2:])
seconds = int(milliseconds) / 1000
except ValueError:
return timestamp
# Elvis Timezone offsets are relevant to Elvis natural timezone (Tallinn)
return datetime.fromtimestamp(seconds).astimezone(
ELVIS_TIMEZONE
) + timedelta(minutes=timezone_offset)
return timestamp
|
from datetime import datetime
import pytz
DATE_PREFIX = '/Date('
DATE_SUFFIX = ')/'
ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn')
UTC = pytz.timezone('UTC')
def decode_elvis_timestamp(timestamp: str):
"""Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible"""
str_timestamp = str(timestamp).strip()
if str_timestamp.startswith(DATE_PREFIX) and str_timestamp.endswith(DATE_SUFFIX):
milliseconds = str_timestamp[len(DATE_PREFIX):-len(DATE_SUFFIX)]
timezone_offset = 0
try:
if "+" in milliseconds:
timezone_offset_string = milliseconds[milliseconds.index("+")+1:]
milliseconds = milliseconds[:milliseconds.index("+")]
if len(timezone_offset_string) == 4:
timezone_offset = int(timezone_offset_string[:2])*60+int(timezone_offset_string[2:])
seconds = int(milliseconds) / 1000
except ValueError:
return timestamp
# Elvis Timezone offsets are relevant to Elvis natural timezone (Tallinn)
return ELVIS_TIMEZONE.localize(datetime.fromtimestamp(seconds).astimezone(
pytz.FixedOffset(-timezone_offset)
).replace(tzinfo=None))
return timestamp
|
Fix date parsing having wrong offset
|
Fix date parsing having wrong offset
|
Python
|
bsd-2-clause
|
thorgate/python-lvis
|
python
|
## Code Before:
from datetime import datetime, timedelta
import pytz
DATE_PREFIX = '/Date('
DATE_SUFFIX = ')/'
ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn')
def decode_elvis_timestamp(timestamp: str):
"""Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible"""
str_timestamp = str(timestamp).strip()
if str_timestamp.startswith(DATE_PREFIX) and str_timestamp.endswith(DATE_SUFFIX):
milliseconds = str_timestamp[len(DATE_PREFIX):-len(DATE_SUFFIX)]
timezone_offset = 0
try:
if "+" in milliseconds:
timezone_offset_string = milliseconds[milliseconds.index("+")+1:]
milliseconds = milliseconds[:milliseconds.index("+")]
if len(timezone_offset_string) == 4:
timezone_offset = int(timezone_offset_string[:2])*60+int(timezone_offset_string[2:])
seconds = int(milliseconds) / 1000
except ValueError:
return timestamp
# Elvis Timezone offsets are relevant to Elvis natural timezone (Tallinn)
return datetime.fromtimestamp(seconds).astimezone(
ELVIS_TIMEZONE
) + timedelta(minutes=timezone_offset)
return timestamp
## Instruction:
Fix date parsing having wrong offset
## Code After:
from datetime import datetime
import pytz
DATE_PREFIX = '/Date('
DATE_SUFFIX = ')/'
ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn')
UTC = pytz.timezone('UTC')
def decode_elvis_timestamp(timestamp: str):
"""Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible"""
str_timestamp = str(timestamp).strip()
if str_timestamp.startswith(DATE_PREFIX) and str_timestamp.endswith(DATE_SUFFIX):
milliseconds = str_timestamp[len(DATE_PREFIX):-len(DATE_SUFFIX)]
timezone_offset = 0
try:
if "+" in milliseconds:
timezone_offset_string = milliseconds[milliseconds.index("+")+1:]
milliseconds = milliseconds[:milliseconds.index("+")]
if len(timezone_offset_string) == 4:
timezone_offset = int(timezone_offset_string[:2])*60+int(timezone_offset_string[2:])
seconds = int(milliseconds) / 1000
except ValueError:
return timestamp
# Elvis Timezone offsets are relevant to Elvis natural timezone (Tallinn)
return ELVIS_TIMEZONE.localize(datetime.fromtimestamp(seconds).astimezone(
pytz.FixedOffset(-timezone_offset)
).replace(tzinfo=None))
return timestamp
|
// ... existing code ...
from datetime import datetime
import pytz
DATE_PREFIX = '/Date('
// ... modified code ...
DATE_SUFFIX = ')/'
ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn')
UTC = pytz.timezone('UTC')
def decode_elvis_timestamp(timestamp: str):
...
return timestamp
# Elvis Timezone offsets are relevant to Elvis natural timezone (Tallinn)
return ELVIS_TIMEZONE.localize(datetime.fromtimestamp(seconds).astimezone(
pytz.FixedOffset(-timezone_offset)
).replace(tzinfo=None))
return timestamp
// ... rest of the code ...
|
659f8258c5e0be937965b2448f38569ecb7a7d13
|
worker/worker-manager/score-worker-manager-impl/src/main/java/io/cloudslang/worker/management/services/WorkerVersionServiceImpl.java
|
worker/worker-manager/score-worker-manager-impl/src/main/java/io/cloudslang/worker/management/services/WorkerVersionServiceImpl.java
|
package io.cloudslang.worker.management.services;
import org.springframework.stereotype.Service;
/**
* Created by kravtsov on 07/12/2015
*/
@Service
public class WorkerVersionServiceImpl implements WorkerVersionService {
@Override
public String getWorkerVersion() {
return "";
}
}
|
package io.cloudslang.worker.management.services;
/**
* Created by kravtsov on 07/12/2015
*/
public class WorkerVersionServiceImpl implements WorkerVersionService {
@Override
public String getWorkerVersion() {
return "";
}
}
|
Remove @Service - was added by mistake
|
Remove @Service - was added by mistake
|
Java
|
apache-2.0
|
hprotem/score,genadi-hp/score,sekler/score,CloudSlang/score,CloudSlang/score
|
java
|
## Code Before:
package io.cloudslang.worker.management.services;
import org.springframework.stereotype.Service;
/**
* Created by kravtsov on 07/12/2015
*/
@Service
public class WorkerVersionServiceImpl implements WorkerVersionService {
@Override
public String getWorkerVersion() {
return "";
}
}
## Instruction:
Remove @Service - was added by mistake
## Code After:
package io.cloudslang.worker.management.services;
/**
* Created by kravtsov on 07/12/2015
*/
public class WorkerVersionServiceImpl implements WorkerVersionService {
@Override
public String getWorkerVersion() {
return "";
}
}
|
// ... existing code ...
package io.cloudslang.worker.management.services;
/**
* Created by kravtsov on 07/12/2015
*/
public class WorkerVersionServiceImpl implements WorkerVersionService {
@Override
public String getWorkerVersion() {
// ... rest of the code ...
|
7f58e395d3aade1e3e44ceeecc4bc3d924d8962c
|
spring-test/src/main/java/org/springframework/mock/jndi/package-info.java
|
spring-test/src/main/java/org/springframework/mock/jndi/package-info.java
|
/**
* <strong>Deprecated</strong> as of Spring Framework 5.2 in favor of complete
* solutions from third parties such as
* <a href="https://github.com/h-thurow/Simple-JNDI">Simple-JNDI</a>.
*
* <p>The simplest implementation of the JNDI SPI that could possibly work.
*
* <p>Useful for setting up a simple JNDI environment for test suites
* or stand-alone applications. If, for example, JDBC DataSources get bound to the
* same JNDI names as within a Java EE container, both application code and
* configuration can be reused without changes.
*/
@Deprecated
@NonNullApi
@NonNullFields
package org.springframework.mock.jndi;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
|
/**
* <strong>Deprecated</strong> as of Spring Framework 5.2 in favor of complete
* solutions from third parties such as
* <a href="https://github.com/h-thurow/Simple-JNDI">Simple-JNDI</a>.
*
* <p>The simplest implementation of the JNDI SPI that could possibly work.
*
* <p>Useful for setting up a simple JNDI environment for test suites
* or stand-alone applications. If, for example, JDBC DataSources get bound to the
* same JNDI names as within a Java EE container, both application code and
* configuration can be reused without changes.
*/
@NonNullApi
@NonNullFields
package org.springframework.mock.jndi;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
|
Remove @Deprecated from org.springframework.mock.jndi package
|
Remove @Deprecated from org.springframework.mock.jndi package
This commit removes the @Deprecated declaration on the
org.springframework.mock.jndi package, since such usage results in a
compiler warning on JDK 9+ which breaks Spring's JDK 9 and JDK 11 CI
builds.
https://bugs.openjdk.java.net/browse/JDK-6481080
See gh-22779
|
Java
|
apache-2.0
|
spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework
|
java
|
## Code Before:
/**
* <strong>Deprecated</strong> as of Spring Framework 5.2 in favor of complete
* solutions from third parties such as
* <a href="https://github.com/h-thurow/Simple-JNDI">Simple-JNDI</a>.
*
* <p>The simplest implementation of the JNDI SPI that could possibly work.
*
* <p>Useful for setting up a simple JNDI environment for test suites
* or stand-alone applications. If, for example, JDBC DataSources get bound to the
* same JNDI names as within a Java EE container, both application code and
* configuration can be reused without changes.
*/
@Deprecated
@NonNullApi
@NonNullFields
package org.springframework.mock.jndi;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
## Instruction:
Remove @Deprecated from org.springframework.mock.jndi package
This commit removes the @Deprecated declaration on the
org.springframework.mock.jndi package, since such usage results in a
compiler warning on JDK 9+ which breaks Spring's JDK 9 and JDK 11 CI
builds.
https://bugs.openjdk.java.net/browse/JDK-6481080
See gh-22779
## Code After:
/**
* <strong>Deprecated</strong> as of Spring Framework 5.2 in favor of complete
* solutions from third parties such as
* <a href="https://github.com/h-thurow/Simple-JNDI">Simple-JNDI</a>.
*
* <p>The simplest implementation of the JNDI SPI that could possibly work.
*
* <p>Useful for setting up a simple JNDI environment for test suites
* or stand-alone applications. If, for example, JDBC DataSources get bound to the
* same JNDI names as within a Java EE container, both application code and
* configuration can be reused without changes.
*/
@NonNullApi
@NonNullFields
package org.springframework.mock.jndi;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
|
...
* same JNDI names as within a Java EE container, both application code and
* configuration can be reused without changes.
*/
@NonNullApi
@NonNullFields
package org.springframework.mock.jndi;
...
|
1308cbcfe115da7d6bb6e0daf6ebaa4591abdd17
|
applications/ticker/src/main/java/com/paritytrading/parity/ticker/MarketDataListener.java
|
applications/ticker/src/main/java/com/paritytrading/parity/ticker/MarketDataListener.java
|
package com.paritytrading.parity.ticker;
import com.paritytrading.parity.book.MarketListener;
abstract class MarketDataListener implements MarketListener {
static final double PRICE_FACTOR = 100.0;
private long second;
private long timestamp;
public void timestamp(long timestamp) {
this.timestamp = timestamp;
}
public long timestampMillis() {
return timestamp / 1_000_000;
}
}
|
package com.paritytrading.parity.ticker;
import com.paritytrading.parity.book.MarketListener;
abstract class MarketDataListener implements MarketListener {
static final double PRICE_FACTOR = 100.0;
private long timestamp;
public void timestamp(long timestamp) {
this.timestamp = timestamp;
}
public long timestampMillis() {
return timestamp / 1_000_000;
}
}
|
Clean up code in stock ticker
|
Clean up code in stock ticker
|
Java
|
apache-2.0
|
paritytrading/parity,pmcs/parity,pmcs/parity,paritytrading/parity
|
java
|
## Code Before:
package com.paritytrading.parity.ticker;
import com.paritytrading.parity.book.MarketListener;
abstract class MarketDataListener implements MarketListener {
static final double PRICE_FACTOR = 100.0;
private long second;
private long timestamp;
public void timestamp(long timestamp) {
this.timestamp = timestamp;
}
public long timestampMillis() {
return timestamp / 1_000_000;
}
}
## Instruction:
Clean up code in stock ticker
## Code After:
package com.paritytrading.parity.ticker;
import com.paritytrading.parity.book.MarketListener;
abstract class MarketDataListener implements MarketListener {
static final double PRICE_FACTOR = 100.0;
private long timestamp;
public void timestamp(long timestamp) {
this.timestamp = timestamp;
}
public long timestampMillis() {
return timestamp / 1_000_000;
}
}
|
...
abstract class MarketDataListener implements MarketListener {
static final double PRICE_FACTOR = 100.0;
private long timestamp;
...
|
e0063c0d5604372c1a07a179f5206a0a27570817
|
package_reviewer/check/repo/check_semver_tags.py
|
package_reviewer/check/repo/check_semver_tags.py
|
import re
from . import RepoChecker
class CheckSemverTags(RepoChecker):
def check(self):
if not self.semver_tags:
msg = "No semantic version tags found. See http://semver.org."
for tag in self.tags:
if re.search(r"(v|^)\d+\.\d+$", tag.name):
msg += " Semantic versions consist of exactly three numeric parts."
break
self.fail(msg)
|
import re
from . import RepoChecker
class CheckSemverTags(RepoChecker):
def check(self):
if not self.semver_tags:
msg = "No semantic version tags found"
for tag in self.tags:
if re.search(r"(v|^)\d+\.\d+$", tag.name):
msg += " (semantic versions consist of exactly three numeric parts)"
break
self.fail(msg)
|
Change message of semver tag check
|
Change message of semver tag check
|
Python
|
mit
|
packagecontrol/st_package_reviewer,packagecontrol/package_reviewer
|
python
|
## Code Before:
import re
from . import RepoChecker
class CheckSemverTags(RepoChecker):
def check(self):
if not self.semver_tags:
msg = "No semantic version tags found. See http://semver.org."
for tag in self.tags:
if re.search(r"(v|^)\d+\.\d+$", tag.name):
msg += " Semantic versions consist of exactly three numeric parts."
break
self.fail(msg)
## Instruction:
Change message of semver tag check
## Code After:
import re
from . import RepoChecker
class CheckSemverTags(RepoChecker):
def check(self):
if not self.semver_tags:
msg = "No semantic version tags found"
for tag in self.tags:
if re.search(r"(v|^)\d+\.\d+$", tag.name):
msg += " (semantic versions consist of exactly three numeric parts)"
break
self.fail(msg)
|
...
def check(self):
if not self.semver_tags:
msg = "No semantic version tags found"
for tag in self.tags:
if re.search(r"(v|^)\d+\.\d+$", tag.name):
msg += " (semantic versions consist of exactly three numeric parts)"
break
self.fail(msg)
...
|
65d2a5f08ee96e80752362f7545167888599819e
|
website/addons/figshare/exceptions.py
|
website/addons/figshare/exceptions.py
|
from website.util.sanitize import escape_html
from website.addons.base.exceptions import AddonEnrichmentError
class FigshareIsDraftError(AddonEnrichmentError):
def __init__(self, file_guid):
self.file_guid = file_guid
@property
def renderable_error(self):
return '''
<div class="alert alert-info" role="alert">
The file "{name}" is still a draft on Figshare. <br>
To view it on the OSF <a href="http://figshare.com/faqs">publish</a> it on Figshare.
</div>
'''.format(name=escape_html(self.file_guid.name))
|
from website.util.sanitize import escape_html
from website.addons.base.exceptions import AddonEnrichmentError
class FigshareIsDraftError(AddonEnrichmentError):
def __init__(self, file_guid):
self.file_guid = file_guid
@property
def can_delete(self):
return True
@property
def renderable_error(self):
return '''
<div class="alert alert-info" role="alert">
The file "{name}" is still a draft on Figshare. <br>
To view it on the OSF <a href="http://figshare.com/faqs">publish</a> it on Figshare.
</div>
'''.format(name=escape_html(self.file_guid.name))
|
Allow deletion of figshare drafts
|
Allow deletion of figshare drafts
|
Python
|
apache-2.0
|
zachjanicki/osf.io,DanielSBrown/osf.io,njantrania/osf.io,kushG/osf.io,erinspace/osf.io,GaryKriebel/osf.io,wearpants/osf.io,chrisseto/osf.io,samchrisinger/osf.io,caneruguz/osf.io,petermalcolm/osf.io,doublebits/osf.io,arpitar/osf.io,cldershem/osf.io,Nesiehr/osf.io,amyshi188/osf.io,brandonPurvis/osf.io,mluo613/osf.io,pattisdr/osf.io,mluo613/osf.io,RomanZWang/osf.io,bdyetton/prettychart,KAsante95/osf.io,HalcyonChimera/osf.io,caneruguz/osf.io,Johnetordoff/osf.io,dplorimer/osf,Nesiehr/osf.io,jinluyuan/osf.io,ZobairAlijan/osf.io,samanehsan/osf.io,danielneis/osf.io,samanehsan/osf.io,brandonPurvis/osf.io,samanehsan/osf.io,adlius/osf.io,himanshuo/osf.io,alexschiller/osf.io,jinluyuan/osf.io,jnayak1/osf.io,CenterForOpenScience/osf.io,mluo613/osf.io,kch8qx/osf.io,erinspace/osf.io,zamattiac/osf.io,haoyuchen1992/osf.io,reinaH/osf.io,pattisdr/osf.io,alexschiller/osf.io,ckc6cz/osf.io,mluo613/osf.io,aaxelb/osf.io,njantrania/osf.io,TomBaxter/osf.io,mfraezz/osf.io,RomanZWang/osf.io,kwierman/osf.io,mluke93/osf.io,icereval/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,kushG/osf.io,KAsante95/osf.io,mfraezz/osf.io,chennan47/osf.io,acshi/osf.io,MerlinZhang/osf.io,ZobairAlijan/osf.io,Ghalko/osf.io,icereval/osf.io,Nesiehr/osf.io,cwisecarver/osf.io,DanielSBrown/osf.io,rdhyee/osf.io,ticklemepierce/osf.io,zamattiac/osf.io,CenterForOpenScience/osf.io,samchrisinger/osf.io,haoyuchen1992/osf.io,acshi/osf.io,asanfilippo7/osf.io,jnayak1/osf.io,zachjanicki/osf.io,DanielSBrown/osf.io,lyndsysimon/osf.io,cwisecarver/osf.io,fabianvf/osf.io,asanfilippo7/osf.io,baylee-d/osf.io,monikagrabowska/osf.io,kch8qx/osf.io,lamdnhan/osf.io,HarryRybacki/osf.io,reinaH/osf.io,lyndsysimon/osf.io,ZobairAlijan/osf.io,monikagrabowska/osf.io,saradbowman/osf.io,alexschiller/osf.io,cslzchen/osf.io,bdyetton/prettychart,hmoco/osf.io,caseyrollins/osf.io,billyhunt/osf.io,erinspace/osf.io,GaryKriebel/osf.io,MerlinZhang/osf.io,cldershem/osf.io,HarryRybacki/osf.io,binoculars/osf.io,revanthkolli/osf.io,brandonPurvis/osf.io,billyhunt/osf.io,brianjgeiger/osf.io,sbt9uc/osf.io,felliott/osf.io,doublebits/osf.io,rdhyee/osf.io,Ghalko/osf.io,billyhunt/osf.io,crcresearch/osf.io,sbt9uc/osf.io,caseyrollins/osf.io,KAsante95/osf.io,KAsante95/osf.io,wearpants/osf.io,TomBaxter/osf.io,HarryRybacki/osf.io,haoyuchen1992/osf.io,zamattiac/osf.io,felliott/osf.io,Johnetordoff/osf.io,jeffreyliu3230/osf.io,petermalcolm/osf.io,danielneis/osf.io,brianjgeiger/osf.io,SSJohns/osf.io,hmoco/osf.io,hmoco/osf.io,billyhunt/osf.io,alexschiller/osf.io,baylee-d/osf.io,aaxelb/osf.io,jeffreyliu3230/osf.io,zachjanicki/osf.io,DanielSBrown/osf.io,crcresearch/osf.io,TomHeatwole/osf.io,mluke93/osf.io,kch8qx/osf.io,njantrania/osf.io,binoculars/osf.io,ckc6cz/osf.io,billyhunt/osf.io,chennan47/osf.io,GaryKriebel/osf.io,leb2dg/osf.io,cosenal/osf.io,TomBaxter/osf.io,cosenal/osf.io,barbour-em/osf.io,Ghalko/osf.io,SSJohns/osf.io,zkraime/osf.io,icereval/osf.io,TomHeatwole/osf.io,HalcyonChimera/osf.io,samchrisinger/osf.io,cslzchen/osf.io,cwisecarver/osf.io,mattclark/osf.io,rdhyee/osf.io,haoyuchen1992/osf.io,caneruguz/osf.io,chrisseto/osf.io,chrisseto/osf.io,GageGaskins/osf.io,laurenrevere/osf.io,barbour-em/osf.io,himanshuo/osf.io,wearpants/osf.io,RomanZWang/osf.io,barbour-em/osf.io,monikagrabowska/osf.io,MerlinZhang/osf.io,TomHeatwole/osf.io,zkraime/osf.io,SSJohns/osf.io,crcresearch/osf.io,jinluyuan/osf.io,sloria/osf.io,revanthkolli/osf.io,laurenrevere/osf.io,HalcyonChimera/osf.io,CenterForOpenScience/osf.io,arpitar/osf.io,petermalcolm/osf.io,hmoco/osf.io,GaryKriebel/osf.io,caseyrygt/osf.io,felliott/osf.io,bdyetton/prettychart,ckc6cz/osf.io,danielneis/osf.io,binoculars/osf.io,ckc6cz/osf.io,samanehsan/osf.io,aaxelb/osf.io,jnayak1/osf.io,mluke93/osf.io,KAsante95/osf.io,arpitar/osf.io,saradbowman/osf.io,Johnetordoff/osf.io,asanfilippo7/osf.io,RomanZWang/osf.io,Ghalko/osf.io,doublebits/osf.io,fabianvf/osf.io,pattisdr/osf.io,jnayak1/osf.io,emetsger/osf.io,fabianvf/osf.io,sloria/osf.io,kch8qx/osf.io,laurenrevere/osf.io,jolene-esposito/osf.io,rdhyee/osf.io,revanthkolli/osf.io,jmcarp/osf.io,jolene-esposito/osf.io,lamdnhan/osf.io,jeffreyliu3230/osf.io,caseyrygt/osf.io,doublebits/osf.io,dplorimer/osf,abought/osf.io,danielneis/osf.io,emetsger/osf.io,sbt9uc/osf.io,adlius/osf.io,njantrania/osf.io,cslzchen/osf.io,cwisecarver/osf.io,mattclark/osf.io,HarryRybacki/osf.io,jolene-esposito/osf.io,barbour-em/osf.io,cosenal/osf.io,zachjanicki/osf.io,monikagrabowska/osf.io,jolene-esposito/osf.io,caseyrygt/osf.io,cosenal/osf.io,zkraime/osf.io,kwierman/osf.io,dplorimer/osf,himanshuo/osf.io,amyshi188/osf.io,lyndsysimon/osf.io,reinaH/osf.io,jmcarp/osf.io,TomHeatwole/osf.io,bdyetton/prettychart,jmcarp/osf.io,mattclark/osf.io,kushG/osf.io,abought/osf.io,acshi/osf.io,samchrisinger/osf.io,jmcarp/osf.io,ZobairAlijan/osf.io,lamdnhan/osf.io,jeffreyliu3230/osf.io,sbt9uc/osf.io,amyshi188/osf.io,lamdnhan/osf.io,cldershem/osf.io,reinaH/osf.io,ticklemepierce/osf.io,brandonPurvis/osf.io,GageGaskins/osf.io,alexschiller/osf.io,asanfilippo7/osf.io,revanthkolli/osf.io,emetsger/osf.io,mluke93/osf.io,baylee-d/osf.io,leb2dg/osf.io,doublebits/osf.io,kushG/osf.io,chrisseto/osf.io,CenterForOpenScience/osf.io,wearpants/osf.io,mfraezz/osf.io,HalcyonChimera/osf.io,SSJohns/osf.io,mfraezz/osf.io,lyndsysimon/osf.io,felliott/osf.io,Johnetordoff/osf.io,MerlinZhang/osf.io,brandonPurvis/osf.io,himanshuo/osf.io,adlius/osf.io,GageGaskins/osf.io,petermalcolm/osf.io,brianjgeiger/osf.io,abought/osf.io,mluo613/osf.io,cslzchen/osf.io,dplorimer/osf,ticklemepierce/osf.io,Nesiehr/osf.io,zkraime/osf.io,leb2dg/osf.io,adlius/osf.io,brianjgeiger/osf.io,ticklemepierce/osf.io,GageGaskins/osf.io,cldershem/osf.io,jinluyuan/osf.io,fabianvf/osf.io,abought/osf.io,caseyrygt/osf.io,arpitar/osf.io,chennan47/osf.io,zamattiac/osf.io,aaxelb/osf.io,emetsger/osf.io,acshi/osf.io,amyshi188/osf.io,GageGaskins/osf.io,caneruguz/osf.io,kwierman/osf.io,kch8qx/osf.io,sloria/osf.io,acshi/osf.io,kwierman/osf.io,RomanZWang/osf.io,caseyrollins/osf.io
|
python
|
## Code Before:
from website.util.sanitize import escape_html
from website.addons.base.exceptions import AddonEnrichmentError
class FigshareIsDraftError(AddonEnrichmentError):
def __init__(self, file_guid):
self.file_guid = file_guid
@property
def renderable_error(self):
return '''
<div class="alert alert-info" role="alert">
The file "{name}" is still a draft on Figshare. <br>
To view it on the OSF <a href="http://figshare.com/faqs">publish</a> it on Figshare.
</div>
'''.format(name=escape_html(self.file_guid.name))
## Instruction:
Allow deletion of figshare drafts
## Code After:
from website.util.sanitize import escape_html
from website.addons.base.exceptions import AddonEnrichmentError
class FigshareIsDraftError(AddonEnrichmentError):
def __init__(self, file_guid):
self.file_guid = file_guid
@property
def can_delete(self):
return True
@property
def renderable_error(self):
return '''
<div class="alert alert-info" role="alert">
The file "{name}" is still a draft on Figshare. <br>
To view it on the OSF <a href="http://figshare.com/faqs">publish</a> it on Figshare.
</div>
'''.format(name=escape_html(self.file_guid.name))
|
# ... existing code ...
self.file_guid = file_guid
@property
def can_delete(self):
return True
@property
def renderable_error(self):
return '''
<div class="alert alert-info" role="alert">
# ... rest of the code ...
|
6cf5d7db54ee272fa9af66d45a504d5994693ae4
|
tests/functional/test_configuration.py
|
tests/functional/test_configuration.py
|
from pip.status_codes import ERROR
from tests.lib.configuration_helpers import kinds, ConfigurationFileIOMixin
def test_no_options_passed_should_error(script):
result = script.pip('config', expect_error=True)
assert result.returncode == ERROR
class TestBasicLoading(ConfigurationFileIOMixin):
def test_reads_user_file(self, script):
contents = """
[test]
hello = 1
"""
with self.patched_file(kinds.USER, contents):
result = script.pip("config", "--list")
assert "test.hello = 1" in result.stdout
|
import pytest
import textwrap
from pip.status_codes import ERROR
from tests.lib.configuration_helpers import kinds, ConfigurationFileIOMixin
def test_no_options_passed_should_error(script):
result = script.pip('config', expect_error=True)
assert result.returncode == ERROR
class TestBasicLoading(ConfigurationFileIOMixin):
@pytest.mark.skip("Can't modify underlying file for any mode")
def test_reads_file_appropriately(self, script):
contents = """
[test]
hello = 1
"""
with self.patched_file(kinds.USER, contents):
result = script.pip("config", "list")
assert "test.hello=1" in result.stdout
def test_modification_pipeline(self, script):
script.pip(
"config", "get", "test.blah", expect_error=True
)
script.pip("config", "set", "test.blah", "1")
result4 = script.pip("config", "get", "test.blah")
assert result4.stdout.strip() == "1"
def test_listing_is_correct(self, script):
script.pip("config", "set", "test.listing-beta", "2")
script.pip("config", "set", "test.listing-alpha", "1")
script.pip("config", "set", "test.listing-gamma", "3")
result = script.pip("config", "list")
lines = list(filter(
lambda x: x.startswith("test.listing-"),
result.stdout.splitlines()
))
expected = """
test.listing-alpha='1'
test.listing-beta='2'
test.listing-gamma='3'
"""
assert lines == textwrap.dedent(expected).strip().splitlines()
|
Add basic tests for configuration
|
Add basic tests for configuration
|
Python
|
mit
|
zvezdan/pip,pypa/pip,xavfernandez/pip,xavfernandez/pip,techtonik/pip,pradyunsg/pip,RonnyPfannschmidt/pip,pradyunsg/pip,zvezdan/pip,RonnyPfannschmidt/pip,RonnyPfannschmidt/pip,rouge8/pip,sbidoul/pip,xavfernandez/pip,rouge8/pip,pfmoore/pip,zvezdan/pip,techtonik/pip,pypa/pip,sbidoul/pip,pfmoore/pip,rouge8/pip,techtonik/pip
|
python
|
## Code Before:
from pip.status_codes import ERROR
from tests.lib.configuration_helpers import kinds, ConfigurationFileIOMixin
def test_no_options_passed_should_error(script):
result = script.pip('config', expect_error=True)
assert result.returncode == ERROR
class TestBasicLoading(ConfigurationFileIOMixin):
def test_reads_user_file(self, script):
contents = """
[test]
hello = 1
"""
with self.patched_file(kinds.USER, contents):
result = script.pip("config", "--list")
assert "test.hello = 1" in result.stdout
## Instruction:
Add basic tests for configuration
## Code After:
import pytest
import textwrap
from pip.status_codes import ERROR
from tests.lib.configuration_helpers import kinds, ConfigurationFileIOMixin
def test_no_options_passed_should_error(script):
result = script.pip('config', expect_error=True)
assert result.returncode == ERROR
class TestBasicLoading(ConfigurationFileIOMixin):
@pytest.mark.skip("Can't modify underlying file for any mode")
def test_reads_file_appropriately(self, script):
contents = """
[test]
hello = 1
"""
with self.patched_file(kinds.USER, contents):
result = script.pip("config", "list")
assert "test.hello=1" in result.stdout
def test_modification_pipeline(self, script):
script.pip(
"config", "get", "test.blah", expect_error=True
)
script.pip("config", "set", "test.blah", "1")
result4 = script.pip("config", "get", "test.blah")
assert result4.stdout.strip() == "1"
def test_listing_is_correct(self, script):
script.pip("config", "set", "test.listing-beta", "2")
script.pip("config", "set", "test.listing-alpha", "1")
script.pip("config", "set", "test.listing-gamma", "3")
result = script.pip("config", "list")
lines = list(filter(
lambda x: x.startswith("test.listing-"),
result.stdout.splitlines()
))
expected = """
test.listing-alpha='1'
test.listing-beta='2'
test.listing-gamma='3'
"""
assert lines == textwrap.dedent(expected).strip().splitlines()
|
...
import pytest
import textwrap
from pip.status_codes import ERROR
from tests.lib.configuration_helpers import kinds, ConfigurationFileIOMixin
...
class TestBasicLoading(ConfigurationFileIOMixin):
@pytest.mark.skip("Can't modify underlying file for any mode")
def test_reads_file_appropriately(self, script):
contents = """
[test]
hello = 1
...
"""
with self.patched_file(kinds.USER, contents):
result = script.pip("config", "list")
assert "test.hello=1" in result.stdout
def test_modification_pipeline(self, script):
script.pip(
"config", "get", "test.blah", expect_error=True
)
script.pip("config", "set", "test.blah", "1")
result4 = script.pip("config", "get", "test.blah")
assert result4.stdout.strip() == "1"
def test_listing_is_correct(self, script):
script.pip("config", "set", "test.listing-beta", "2")
script.pip("config", "set", "test.listing-alpha", "1")
script.pip("config", "set", "test.listing-gamma", "3")
result = script.pip("config", "list")
lines = list(filter(
lambda x: x.startswith("test.listing-"),
result.stdout.splitlines()
))
expected = """
test.listing-alpha='1'
test.listing-beta='2'
test.listing-gamma='3'
"""
assert lines == textwrap.dedent(expected).strip().splitlines()
...
|
d726efa1116f95ced28994c7c6bbcfe4cf703b05
|
wavvy/views.py
|
wavvy/views.py
|
from wavvy import app
from flask import Flask, url_for, render_template, request, session, escape
@app.route('/hello')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
@app.route('/')
def index():
if session.get('logged_in', False):
return 'Logged in as {}'.format(escape(session['username']))
return 'You are not logged in.'
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
session['logged_in'] = True
session['username'] = request.form['username']
password = escape(request.form['password'])
return 'Validating a login! U:{} P:{}'.format(escape(session['username']), password)
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
session['logged_in'] = False
if 'username' in session:
del session['username']
return 'You are logged out.'
|
from wavvy import app
from flask import Flask, url_for, render_template, request, session, escape
def clear_session(s):
if 'username' in s:
del s['username']
s['logged_in'] = False
@app.route('/hello')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
@app.route('/')
def index():
if session.get('logged_in', False):
return 'Logged in as {}'.format(escape(session['username']))
return 'You are not logged in.'
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
session['logged_in'] = True
session['username'] = request.form['username']
password = escape(request.form['password'])
return 'Validating a login! U:{} P:{}'.format(escape(session['username']), password)
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
clear_session(session)
return 'You are logged out.'
|
Generalize the logout a bit
|
Generalize the logout a bit
This is on the road to removing auth from this file.
|
Python
|
mit
|
john-patterson/wavvy,john-patterson/wavvy
|
python
|
## Code Before:
from wavvy import app
from flask import Flask, url_for, render_template, request, session, escape
@app.route('/hello')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
@app.route('/')
def index():
if session.get('logged_in', False):
return 'Logged in as {}'.format(escape(session['username']))
return 'You are not logged in.'
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
session['logged_in'] = True
session['username'] = request.form['username']
password = escape(request.form['password'])
return 'Validating a login! U:{} P:{}'.format(escape(session['username']), password)
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
session['logged_in'] = False
if 'username' in session:
del session['username']
return 'You are logged out.'
## Instruction:
Generalize the logout a bit
This is on the road to removing auth from this file.
## Code After:
from wavvy import app
from flask import Flask, url_for, render_template, request, session, escape
def clear_session(s):
if 'username' in s:
del s['username']
s['logged_in'] = False
@app.route('/hello')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
@app.route('/')
def index():
if session.get('logged_in', False):
return 'Logged in as {}'.format(escape(session['username']))
return 'You are not logged in.'
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
session['logged_in'] = True
session['username'] = request.form['username']
password = escape(request.form['password'])
return 'Validating a login! U:{} P:{}'.format(escape(session['username']), password)
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
clear_session(session)
return 'You are logged out.'
|
...
from wavvy import app
from flask import Flask, url_for, render_template, request, session, escape
def clear_session(s):
if 'username' in s:
del s['username']
s['logged_in'] = False
@app.route('/hello')
...
@app.route('/logout')
def logout():
clear_session(session)
return 'You are logged out.'
...
|
bc78bf85442b0ffb7962a1c9c4a3560a0fd1960d
|
skimage/io/_plugins/matplotlib_plugin.py
|
skimage/io/_plugins/matplotlib_plugin.py
|
import matplotlib.pyplot as plt
def imshow(*args, **kwargs):
kwargs.setdefault('interpolation', 'nearest')
kwargs.setdefault('cmap', 'gray')
plt.imshow(*args, **kwargs)
imread = plt.imread
show = plt.show
def _app_show():
show()
|
import matplotlib.pyplot as plt
def imshow(*args, **kwargs):
if plt.gca().has_data():
plt.figure()
kwargs.setdefault('interpolation', 'nearest')
kwargs.setdefault('cmap', 'gray')
plt.imshow(*args, **kwargs)
imread = plt.imread
show = plt.show
def _app_show():
show()
|
Create a new figure for imshow if there is already data
|
Create a new figure for imshow if there is already data
|
Python
|
bsd-3-clause
|
keflavich/scikit-image,GaZ3ll3/scikit-image,pratapvardhan/scikit-image,jwiggins/scikit-image,oew1v07/scikit-image,robintw/scikit-image,vighneshbirodkar/scikit-image,michaelaye/scikit-image,WarrenWeckesser/scikits-image,ofgulban/scikit-image,paalge/scikit-image,paalge/scikit-image,michaelaye/scikit-image,warmspringwinds/scikit-image,GaZ3ll3/scikit-image,Hiyorimi/scikit-image,WarrenWeckesser/scikits-image,dpshelio/scikit-image,blink1073/scikit-image,Britefury/scikit-image,bsipocz/scikit-image,youprofit/scikit-image,ofgulban/scikit-image,warmspringwinds/scikit-image,robintw/scikit-image,paalge/scikit-image,keflavich/scikit-image,ofgulban/scikit-image,bennlich/scikit-image,ClinicalGraphics/scikit-image,newville/scikit-image,ClinicalGraphics/scikit-image,Midafi/scikit-image,ajaybhat/scikit-image,juliusbierk/scikit-image,juliusbierk/scikit-image,bsipocz/scikit-image,Britefury/scikit-image,oew1v07/scikit-image,Midafi/scikit-image,vighneshbirodkar/scikit-image,emon10005/scikit-image,rjeli/scikit-image,rjeli/scikit-image,chriscrosscutler/scikit-image,michaelpacer/scikit-image,ajaybhat/scikit-image,dpshelio/scikit-image,newville/scikit-image,vighneshbirodkar/scikit-image,pratapvardhan/scikit-image,chriscrosscutler/scikit-image,youprofit/scikit-image,emon10005/scikit-image,blink1073/scikit-image,rjeli/scikit-image,Hiyorimi/scikit-image,bennlich/scikit-image,michaelpacer/scikit-image,jwiggins/scikit-image
|
python
|
## Code Before:
import matplotlib.pyplot as plt
def imshow(*args, **kwargs):
kwargs.setdefault('interpolation', 'nearest')
kwargs.setdefault('cmap', 'gray')
plt.imshow(*args, **kwargs)
imread = plt.imread
show = plt.show
def _app_show():
show()
## Instruction:
Create a new figure for imshow if there is already data
## Code After:
import matplotlib.pyplot as plt
def imshow(*args, **kwargs):
if plt.gca().has_data():
plt.figure()
kwargs.setdefault('interpolation', 'nearest')
kwargs.setdefault('cmap', 'gray')
plt.imshow(*args, **kwargs)
imread = plt.imread
show = plt.show
def _app_show():
show()
|
# ... existing code ...
def imshow(*args, **kwargs):
if plt.gca().has_data():
plt.figure()
kwargs.setdefault('interpolation', 'nearest')
kwargs.setdefault('cmap', 'gray')
plt.imshow(*args, **kwargs)
# ... rest of the code ...
|
3d5c96de5ddd5ac162067b48af33e5dcae338e8d
|
src/main/java/com/thebuerkle/dropwizard/resources/TestResource.java
|
src/main/java/com/thebuerkle/dropwizard/resources/TestResource.java
|
package com.thebuerkle.dropwizard.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.thebuerkle.dropwizard.core.Car;
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public class TestResource {
private static final Logger log = LoggerFactory.getLogger(TestResource.class);
private final Client _client;
public TestResource(Client client) {
_client = client;
}
@Path("/produce")
@GET
public Car produce() {
return new Car("Elantra", "gray");
}
@Path("/consume")
@GET
public void consume() {
WebTarget target = _client.target("http://localhost:8080/produce");
Invocation.Builder invocation = target.request(MediaType.APPLICATION_JSON);
Response response = invocation.get();
log.info(response.readEntity(Car.class).toString());
}
}
|
package com.thebuerkle.dropwizard.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.thebuerkle.dropwizard.core.Car;
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public class TestResource {
private static final Logger log = LoggerFactory.getLogger(TestResource.class);
private final Client _client;
public TestResource(Client client) {
_client = client;
}
@Path("/produce")
@GET
public Car produce() {
return new Car("Elantra", "gray");
}
@Path("/consume")
@GET
public void consume(@QueryParam("string") boolean asString) {
WebTarget target = _client.target("http://localhost:8080/produce");
Invocation.Builder invocation = target.request(MediaType.APPLICATION_JSON);
Response response = invocation.get();
log.info("Status code: " + Response.Status.fromStatusCode(response.getStatus()));
if (asString) {
log.info("Response as string: " + response.readEntity(String.class));
}
else {
log.info("Response as car: " + response.readEntity(Car.class).toString());
}
}
}
|
Add getting response as a string
|
Add getting response as a string
|
Java
|
apache-2.0
|
buerkle/dropwizard-client-example
|
java
|
## Code Before:
package com.thebuerkle.dropwizard.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.thebuerkle.dropwizard.core.Car;
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public class TestResource {
private static final Logger log = LoggerFactory.getLogger(TestResource.class);
private final Client _client;
public TestResource(Client client) {
_client = client;
}
@Path("/produce")
@GET
public Car produce() {
return new Car("Elantra", "gray");
}
@Path("/consume")
@GET
public void consume() {
WebTarget target = _client.target("http://localhost:8080/produce");
Invocation.Builder invocation = target.request(MediaType.APPLICATION_JSON);
Response response = invocation.get();
log.info(response.readEntity(Car.class).toString());
}
}
## Instruction:
Add getting response as a string
## Code After:
package com.thebuerkle.dropwizard.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.thebuerkle.dropwizard.core.Car;
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public class TestResource {
private static final Logger log = LoggerFactory.getLogger(TestResource.class);
private final Client _client;
public TestResource(Client client) {
_client = client;
}
@Path("/produce")
@GET
public Car produce() {
return new Car("Elantra", "gray");
}
@Path("/consume")
@GET
public void consume(@QueryParam("string") boolean asString) {
WebTarget target = _client.target("http://localhost:8080/produce");
Invocation.Builder invocation = target.request(MediaType.APPLICATION_JSON);
Response response = invocation.get();
log.info("Status code: " + Response.Status.fromStatusCode(response.getStatus()));
if (asString) {
log.info("Response as string: " + response.readEntity(String.class));
}
else {
log.info("Response as car: " + response.readEntity(Car.class).toString());
}
}
}
|
...
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
...
@Path("/consume")
@GET
public void consume(@QueryParam("string") boolean asString) {
WebTarget target = _client.target("http://localhost:8080/produce");
Invocation.Builder invocation = target.request(MediaType.APPLICATION_JSON);
Response response = invocation.get();
log.info("Status code: " + Response.Status.fromStatusCode(response.getStatus()));
if (asString) {
log.info("Response as string: " + response.readEntity(String.class));
}
else {
log.info("Response as car: " + response.readEntity(Car.class).toString());
}
}
}
...
|
af56c549a8eae5ebb0d124e2bb397241f11e47af
|
indico/__init__.py
|
indico/__init__.py
|
from indico.util.mimetypes import register_custom_mimetypes
__version__ = '2.1-dev'
register_custom_mimetypes()
# monkeypatch for https://github.com/wtforms/wtforms/issues/373
def _patch_wtforms_sqlalchemy():
from wtforms.ext.sqlalchemy import fields
from sqlalchemy.orm.util import identity_key
def get_pk_from_identity(obj):
key = identity_key(instance=obj)[1]
return u':'.join(map(unicode, key))
fields.get_pk_from_identity = get_pk_from_identity
_patch_wtforms_sqlalchemy()
del _patch_wtforms_sqlalchemy
|
from indico.util.mimetypes import register_custom_mimetypes
__version__ = '2.1-dev'
register_custom_mimetypes()
# monkeypatch for https://github.com/wtforms/wtforms/issues/373
def _patch_wtforms_sqlalchemy():
from wtforms.ext.sqlalchemy import fields
from sqlalchemy.orm.util import identity_key
def get_pk_from_identity(obj):
key = identity_key(instance=obj)[1]
return u':'.join(map(unicode, key))
fields.get_pk_from_identity = get_pk_from_identity
try:
_patch_wtforms_sqlalchemy()
except ImportError as exc:
# pip seems to run this sometimes while uninstalling an old sqlalchemy version
print 'Could not monkeypatch wtforms', exc
finally:
del _patch_wtforms_sqlalchemy
|
Fix pip install failing due to wtforms monkeypatch
|
Fix pip install failing due to wtforms monkeypatch
|
Python
|
mit
|
OmeGak/indico,mvidalgarcia/indico,mvidalgarcia/indico,indico/indico,ThiefMaster/indico,DirkHoffmann/indico,OmeGak/indico,pferreir/indico,pferreir/indico,OmeGak/indico,mvidalgarcia/indico,DirkHoffmann/indico,ThiefMaster/indico,indico/indico,ThiefMaster/indico,DirkHoffmann/indico,mic4ael/indico,mic4ael/indico,mvidalgarcia/indico,ThiefMaster/indico,pferreir/indico,DirkHoffmann/indico,indico/indico,OmeGak/indico,indico/indico,mic4ael/indico,pferreir/indico,mic4ael/indico
|
python
|
## Code Before:
from indico.util.mimetypes import register_custom_mimetypes
__version__ = '2.1-dev'
register_custom_mimetypes()
# monkeypatch for https://github.com/wtforms/wtforms/issues/373
def _patch_wtforms_sqlalchemy():
from wtforms.ext.sqlalchemy import fields
from sqlalchemy.orm.util import identity_key
def get_pk_from_identity(obj):
key = identity_key(instance=obj)[1]
return u':'.join(map(unicode, key))
fields.get_pk_from_identity = get_pk_from_identity
_patch_wtforms_sqlalchemy()
del _patch_wtforms_sqlalchemy
## Instruction:
Fix pip install failing due to wtforms monkeypatch
## Code After:
from indico.util.mimetypes import register_custom_mimetypes
__version__ = '2.1-dev'
register_custom_mimetypes()
# monkeypatch for https://github.com/wtforms/wtforms/issues/373
def _patch_wtforms_sqlalchemy():
from wtforms.ext.sqlalchemy import fields
from sqlalchemy.orm.util import identity_key
def get_pk_from_identity(obj):
key = identity_key(instance=obj)[1]
return u':'.join(map(unicode, key))
fields.get_pk_from_identity = get_pk_from_identity
try:
_patch_wtforms_sqlalchemy()
except ImportError as exc:
# pip seems to run this sometimes while uninstalling an old sqlalchemy version
print 'Could not monkeypatch wtforms', exc
finally:
del _patch_wtforms_sqlalchemy
|
...
fields.get_pk_from_identity = get_pk_from_identity
try:
_patch_wtforms_sqlalchemy()
except ImportError as exc:
# pip seems to run this sometimes while uninstalling an old sqlalchemy version
print 'Could not monkeypatch wtforms', exc
finally:
del _patch_wtforms_sqlalchemy
...
|
1071e663eb38a3981cea047c1b2e24d6e119f94d
|
db/api/serializers.py
|
db/api/serializers.py
|
from rest_framework import serializers
from db.base.models import Satellite, Transponder
class SatelliteSerializer(serializers.ModelSerializer):
class Meta:
model = Satellite
class TransponderSerializer(serializers.ModelSerializer):
norad = serializers.SerializerMethodField()
class Meta:
model = Transponder
fields = ('uuid', 'description', 'alive', 'uplink_low', 'uplink_high',
'downlink_low', 'downlink_high', 'mode', 'invert',
'baud', 'norad')
def get_norad(self, obj):
return obj.satellite.norad_cat_id
|
from rest_framework import serializers
from db.base.models import Satellite, Transponder
class SatelliteSerializer(serializers.ModelSerializer):
class Meta:
model = Satellite
class TransponderSerializer(serializers.ModelSerializer):
norad_cat_id = serializers.SerializerMethodField()
class Meta:
model = Transponder
fields = ('uuid', 'description', 'alive', 'uplink_low', 'uplink_high',
'downlink_low', 'downlink_high', 'mode', 'invert',
'baud', 'norad_cat_id')
def get_norad_cat_id(self, obj):
return obj.satellite.norad_cat_id
|
Change norad API field to proper name
|
Change norad API field to proper name
|
Python
|
agpl-3.0
|
Roboneet/satnogs-db,Roboneet/satnogs-db,Roboneet/satnogs-db,Roboneet/satnogs-db
|
python
|
## Code Before:
from rest_framework import serializers
from db.base.models import Satellite, Transponder
class SatelliteSerializer(serializers.ModelSerializer):
class Meta:
model = Satellite
class TransponderSerializer(serializers.ModelSerializer):
norad = serializers.SerializerMethodField()
class Meta:
model = Transponder
fields = ('uuid', 'description', 'alive', 'uplink_low', 'uplink_high',
'downlink_low', 'downlink_high', 'mode', 'invert',
'baud', 'norad')
def get_norad(self, obj):
return obj.satellite.norad_cat_id
## Instruction:
Change norad API field to proper name
## Code After:
from rest_framework import serializers
from db.base.models import Satellite, Transponder
class SatelliteSerializer(serializers.ModelSerializer):
class Meta:
model = Satellite
class TransponderSerializer(serializers.ModelSerializer):
norad_cat_id = serializers.SerializerMethodField()
class Meta:
model = Transponder
fields = ('uuid', 'description', 'alive', 'uplink_low', 'uplink_high',
'downlink_low', 'downlink_high', 'mode', 'invert',
'baud', 'norad_cat_id')
def get_norad_cat_id(self, obj):
return obj.satellite.norad_cat_id
|
// ... existing code ...
class TransponderSerializer(serializers.ModelSerializer):
norad_cat_id = serializers.SerializerMethodField()
class Meta:
model = Transponder
fields = ('uuid', 'description', 'alive', 'uplink_low', 'uplink_high',
'downlink_low', 'downlink_high', 'mode', 'invert',
'baud', 'norad_cat_id')
def get_norad_cat_id(self, obj):
return obj.satellite.norad_cat_id
// ... rest of the code ...
|
8f0b72dcad39fbd6072185bf2244eb75f0f45a96
|
better_od/core.py
|
better_od/core.py
|
from collections import MutableMapping
class BetterOrderedDict(MutableMapping):
def __init__(self, **kwargs):
self._d = dict()
self._keys = []
def __len__(self):
return len(self._d)
def __iter__(self):
for key in self._keys:
yield key
def __setitem__(self, key, value):
self._keys.append(key)
self._d[key] = value
def __getitem__(self, key):
return self._d[key]
def __delitem__(self, key):
self._keys.pop(key)
del self._d[key]
def key_index(self, key):
return self._keys.index(key)
def insert(self, key, value, index):
if key in self._d:
self._keys.pop(key)
self._keys.insert(index, key)
self._d[key] = value
def reorder_keys(self, keys):
if self._keys != self._d:
raise ValueError('Keys do not match.')
self._keys = keys
|
from collections import MutableMapping
class BetterOrderedDict(MutableMapping):
'''BetterOrderedDict is a mapping object that allows for ordered access
and insertion of keys. With the exception of the key_index, insert, and
reorder_keys methods behavior is identical to stock dictionary objects.'''
def __init__(self, **kwargs):
'''BetterOrderedDict accepts an optional iterable of two-tuples
indicating keys and values.'''
self._d = dict()
self._keys = []
def __len__(self):
return len(self._d)
def __iter__(self):
for key in self._keys:
yield key
def __setitem__(self, key, value):
self._keys.append(key)
self._d[key] = value
def __getitem__(self, key):
return self._d[key]
def __delitem__(self, key):
self._keys.pop(key)
del self._d[key]
def key_index(self, key):
'''Accepts a parameter, :key:, and returns an integer value
representing its index in the ordered list of keys.'''
return self._keys.index(key)
def insert(self, key, value, index):
'''Accepts a :key:, :value:, and :index: parameter and inserts
a new key, value member at the desired index.'''
if key in self._d:
self._keys.pop(key)
self._keys.insert(index, key)
self._d[key] = value
def reorder_keys(self, keys):
'''Accepts a :keys: parameter, an iterable of keys in the
desired new order. The :keys: parameter must contain all
existing keys.'''
if self._keys != self._d:
raise ValueError('Keys do not match.')
self._keys = keys
|
Add docstrings for most public API methods.
|
Add docstrings for most public API methods.
|
Python
|
mit
|
JustusW/BetterOrderedDict,therealfakemoot/collections2
|
python
|
## Code Before:
from collections import MutableMapping
class BetterOrderedDict(MutableMapping):
def __init__(self, **kwargs):
self._d = dict()
self._keys = []
def __len__(self):
return len(self._d)
def __iter__(self):
for key in self._keys:
yield key
def __setitem__(self, key, value):
self._keys.append(key)
self._d[key] = value
def __getitem__(self, key):
return self._d[key]
def __delitem__(self, key):
self._keys.pop(key)
del self._d[key]
def key_index(self, key):
return self._keys.index(key)
def insert(self, key, value, index):
if key in self._d:
self._keys.pop(key)
self._keys.insert(index, key)
self._d[key] = value
def reorder_keys(self, keys):
if self._keys != self._d:
raise ValueError('Keys do not match.')
self._keys = keys
## Instruction:
Add docstrings for most public API methods.
## Code After:
from collections import MutableMapping
class BetterOrderedDict(MutableMapping):
'''BetterOrderedDict is a mapping object that allows for ordered access
and insertion of keys. With the exception of the key_index, insert, and
reorder_keys methods behavior is identical to stock dictionary objects.'''
def __init__(self, **kwargs):
'''BetterOrderedDict accepts an optional iterable of two-tuples
indicating keys and values.'''
self._d = dict()
self._keys = []
def __len__(self):
return len(self._d)
def __iter__(self):
for key in self._keys:
yield key
def __setitem__(self, key, value):
self._keys.append(key)
self._d[key] = value
def __getitem__(self, key):
return self._d[key]
def __delitem__(self, key):
self._keys.pop(key)
del self._d[key]
def key_index(self, key):
'''Accepts a parameter, :key:, and returns an integer value
representing its index in the ordered list of keys.'''
return self._keys.index(key)
def insert(self, key, value, index):
'''Accepts a :key:, :value:, and :index: parameter and inserts
a new key, value member at the desired index.'''
if key in self._d:
self._keys.pop(key)
self._keys.insert(index, key)
self._d[key] = value
def reorder_keys(self, keys):
'''Accepts a :keys: parameter, an iterable of keys in the
desired new order. The :keys: parameter must contain all
existing keys.'''
if self._keys != self._d:
raise ValueError('Keys do not match.')
self._keys = keys
|
// ... existing code ...
class BetterOrderedDict(MutableMapping):
'''BetterOrderedDict is a mapping object that allows for ordered access
and insertion of keys. With the exception of the key_index, insert, and
reorder_keys methods behavior is identical to stock dictionary objects.'''
def __init__(self, **kwargs):
'''BetterOrderedDict accepts an optional iterable of two-tuples
indicating keys and values.'''
self._d = dict()
self._keys = []
// ... modified code ...
del self._d[key]
def key_index(self, key):
'''Accepts a parameter, :key:, and returns an integer value
representing its index in the ordered list of keys.'''
return self._keys.index(key)
def insert(self, key, value, index):
'''Accepts a :key:, :value:, and :index: parameter and inserts
a new key, value member at the desired index.'''
if key in self._d:
self._keys.pop(key)
self._keys.insert(index, key)
...
self._d[key] = value
def reorder_keys(self, keys):
'''Accepts a :keys: parameter, an iterable of keys in the
desired new order. The :keys: parameter must contain all
existing keys.'''
if self._keys != self._d:
raise ValueError('Keys do not match.')
self._keys = keys
// ... rest of the code ...
|
23cbeb30d04a634c6c512e56446c37bf5c10664c
|
modules/junit-jupiter/src/test/java/org/testcontainers/junit/jupiter/inheritance/InheritedTests.java
|
modules/junit-jupiter/src/test/java/org/testcontainers/junit/jupiter/inheritance/InheritedTests.java
|
package org.testcontainers.junit.jupiter.inheritance;
import org.junit.jupiter.api.Test;
import org.testcontainers.junit.jupiter.Container;
import static org.junit.jupiter.api.Assertions.assertEquals;
class InheritedTests extends AbstractTestBase {
@Container
private RedisContainer myRedis = new RedisContainer();
@Test
void step1() {
assertEquals(1, redisPerClass.getJedis().incr("key").longValue());
assertEquals(1, redisPerTest.getJedis().incr("key").longValue());
assertEquals(1, myRedis.getJedis().incr("key").longValue());
}
@Test
void step2() {
assertEquals(2, redisPerClass.getJedis().incr("key").longValue());
assertEquals(1, redisPerTest.getJedis().incr("key").longValue());
assertEquals(1, myRedis.getJedis().incr("key").longValue());
}
}
|
package org.testcontainers.junit.jupiter.inheritance;
import org.junit.jupiter.api.Test;
import org.testcontainers.junit.jupiter.Container;
import static org.junit.jupiter.api.Assertions.assertEquals;
class InheritedTests extends AbstractTestBase {
@Container
private RedisContainer myRedis = new RedisContainer();
@Test
void step1() {
assertEquals(1, redisPerClass.getJedis().incr("key"));
assertEquals(1, redisPerTest.getJedis().incr("key"));
assertEquals(1, myRedis.getJedis().incr("key"));
}
@Test
void step2() {
assertEquals(2, redisPerClass.getJedis().incr("key"));
assertEquals(1, redisPerTest.getJedis().incr("key"));
assertEquals(1, myRedis.getJedis().incr("key"));
}
}
|
Fix for API changes in Jedis
|
Fix for API changes in Jedis
Use `long` primitive instead of boxed type.
|
Java
|
mit
|
testcontainers/testcontainers-java,rnorth/test-containers,rnorth/test-containers,testcontainers/testcontainers-java,rnorth/test-containers,testcontainers/testcontainers-java
|
java
|
## Code Before:
package org.testcontainers.junit.jupiter.inheritance;
import org.junit.jupiter.api.Test;
import org.testcontainers.junit.jupiter.Container;
import static org.junit.jupiter.api.Assertions.assertEquals;
class InheritedTests extends AbstractTestBase {
@Container
private RedisContainer myRedis = new RedisContainer();
@Test
void step1() {
assertEquals(1, redisPerClass.getJedis().incr("key").longValue());
assertEquals(1, redisPerTest.getJedis().incr("key").longValue());
assertEquals(1, myRedis.getJedis().incr("key").longValue());
}
@Test
void step2() {
assertEquals(2, redisPerClass.getJedis().incr("key").longValue());
assertEquals(1, redisPerTest.getJedis().incr("key").longValue());
assertEquals(1, myRedis.getJedis().incr("key").longValue());
}
}
## Instruction:
Fix for API changes in Jedis
Use `long` primitive instead of boxed type.
## Code After:
package org.testcontainers.junit.jupiter.inheritance;
import org.junit.jupiter.api.Test;
import org.testcontainers.junit.jupiter.Container;
import static org.junit.jupiter.api.Assertions.assertEquals;
class InheritedTests extends AbstractTestBase {
@Container
private RedisContainer myRedis = new RedisContainer();
@Test
void step1() {
assertEquals(1, redisPerClass.getJedis().incr("key"));
assertEquals(1, redisPerTest.getJedis().incr("key"));
assertEquals(1, myRedis.getJedis().incr("key"));
}
@Test
void step2() {
assertEquals(2, redisPerClass.getJedis().incr("key"));
assertEquals(1, redisPerTest.getJedis().incr("key"));
assertEquals(1, myRedis.getJedis().incr("key"));
}
}
|
# ... existing code ...
@Test
void step1() {
assertEquals(1, redisPerClass.getJedis().incr("key"));
assertEquals(1, redisPerTest.getJedis().incr("key"));
assertEquals(1, myRedis.getJedis().incr("key"));
}
@Test
void step2() {
assertEquals(2, redisPerClass.getJedis().incr("key"));
assertEquals(1, redisPerTest.getJedis().incr("key"));
assertEquals(1, myRedis.getJedis().incr("key"));
}
}
# ... rest of the code ...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.