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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
ca641bb6bfc65d82564cee684bc3192986806b71
|
vdb/flu_download.py
|
vdb/flu_download.py
|
import os,datetime
from download import download
from download import get_parser
class flu_download(download):
def __init__(self, **kwargs):
download.__init__(self, **kwargs)
if __name__=="__main__":
parser = get_parser()
args = parser.parse_args()
fasta_fields = ['strain', 'virus', 'accession', 'collection_date', 'region', 'country', 'division', 'location', 'source', 'locus', 'authors']
args.fasta_fields = fasta_fields
current_date = str(datetime.datetime.strftime(datetime.datetime.now(),'%Y_%m_%d'))
if args.fstem is None:
args.fstem = args.virus + '_' + current_date
if not os.path.isdir(args.path):
os.makedirs(args.path)
connfluVDB = flu_download(**args.__dict__)
connfluVDB.download(**args.__dict__)
|
import os,datetime
from download import download
from download import get_parser
class flu_download(download):
def __init__(self, **kwargs):
download.__init__(self, **kwargs)
if __name__=="__main__":
parser = get_parser()
args = parser.parse_args()
fasta_fields = ['strain', 'virus', 'accession', 'collection_date', 'region', 'country', 'division', 'location', 'passage_category', 'submitting_lab']
args.fasta_fields = fasta_fields
current_date = str(datetime.datetime.strftime(datetime.datetime.now(),'%Y_%m_%d'))
if args.fstem is None:
args.fstem = args.virus + '_' + current_date
if not os.path.isdir(args.path):
os.makedirs(args.path)
connfluVDB = flu_download(**args.__dict__)
connfluVDB.download(**args.__dict__)
|
Revise flu fasta fields to interface with nextflu.
|
Revise flu fasta fields to interface with nextflu.
|
Python
|
agpl-3.0
|
blab/nextstrain-db,nextstrain/fauna,nextstrain/fauna,blab/nextstrain-db
|
python
|
## Code Before:
import os,datetime
from download import download
from download import get_parser
class flu_download(download):
def __init__(self, **kwargs):
download.__init__(self, **kwargs)
if __name__=="__main__":
parser = get_parser()
args = parser.parse_args()
fasta_fields = ['strain', 'virus', 'accession', 'collection_date', 'region', 'country', 'division', 'location', 'source', 'locus', 'authors']
args.fasta_fields = fasta_fields
current_date = str(datetime.datetime.strftime(datetime.datetime.now(),'%Y_%m_%d'))
if args.fstem is None:
args.fstem = args.virus + '_' + current_date
if not os.path.isdir(args.path):
os.makedirs(args.path)
connfluVDB = flu_download(**args.__dict__)
connfluVDB.download(**args.__dict__)
## Instruction:
Revise flu fasta fields to interface with nextflu.
## Code After:
import os,datetime
from download import download
from download import get_parser
class flu_download(download):
def __init__(self, **kwargs):
download.__init__(self, **kwargs)
if __name__=="__main__":
parser = get_parser()
args = parser.parse_args()
fasta_fields = ['strain', 'virus', 'accession', 'collection_date', 'region', 'country', 'division', 'location', 'passage_category', 'submitting_lab']
args.fasta_fields = fasta_fields
current_date = str(datetime.datetime.strftime(datetime.datetime.now(),'%Y_%m_%d'))
if args.fstem is None:
args.fstem = args.virus + '_' + current_date
if not os.path.isdir(args.path):
os.makedirs(args.path)
connfluVDB = flu_download(**args.__dict__)
connfluVDB.download(**args.__dict__)
|
// ... existing code ...
if __name__=="__main__":
parser = get_parser()
args = parser.parse_args()
fasta_fields = ['strain', 'virus', 'accession', 'collection_date', 'region', 'country', 'division', 'location', 'passage_category', 'submitting_lab']
args.fasta_fields = fasta_fields
current_date = str(datetime.datetime.strftime(datetime.datetime.now(),'%Y_%m_%d'))
if args.fstem is None:
// ... rest of the code ...
|
545ae42ea7d0489da564dd61fd3b1b18bf0ebe9c
|
kernel/arch/x86/boot/boot.h
|
kernel/arch/x86/boot/boot.h
|
/* multiboot definitions */
#define MB_HEADER_MAGIC 0x1BADB002
#define MB_BOOT_MAGIC 0x2BADB002
#define MB_PAGE_ALIGN 0x00000001
#define MB_MEMORY_INFO 0x00000002
/* common boot definitions */
#define BOOT_TIME_STACK_SIZE 0x4000
#endif /*__BOOT_H__*/
|
/* multiboot definitions */
#define MB_HEADER_MAGIC 0x1BADB002
#define MB_BOOT_MAGIC 0x2BADB002
#define MB_PAGE_ALIGN 0x00000001
#define MB_MEMORY_INFO 0x00000002
/* common boot definitions */
#define BOOT_TIME_STACK_SIZE 0x4000
#define BOOT_CS_ENTRY 1
#define BOOT_CS (BOOT_CS_ENTRY << 3)
#define BOOT_DS_ENTRY 2
#define BOOT_DS (BOOT_DS_ENTRY << 3)
#define PTE_INIT_ATTR 0x00000003
#define PDE_INIT_ATTR 0x00000003
#endif /*__BOOT_H__*/
|
Add code and data segments definitions.
|
Add code and data segments definitions.
This patch adds boot time data and code segments definitions.
|
C
|
mit
|
krinkinmu/auos,krinkinmu/auos,krinkinmu/auos,krinkinmu/auos
|
c
|
## Code Before:
/* multiboot definitions */
#define MB_HEADER_MAGIC 0x1BADB002
#define MB_BOOT_MAGIC 0x2BADB002
#define MB_PAGE_ALIGN 0x00000001
#define MB_MEMORY_INFO 0x00000002
/* common boot definitions */
#define BOOT_TIME_STACK_SIZE 0x4000
#endif /*__BOOT_H__*/
## Instruction:
Add code and data segments definitions.
This patch adds boot time data and code segments definitions.
## Code After:
/* multiboot definitions */
#define MB_HEADER_MAGIC 0x1BADB002
#define MB_BOOT_MAGIC 0x2BADB002
#define MB_PAGE_ALIGN 0x00000001
#define MB_MEMORY_INFO 0x00000002
/* common boot definitions */
#define BOOT_TIME_STACK_SIZE 0x4000
#define BOOT_CS_ENTRY 1
#define BOOT_CS (BOOT_CS_ENTRY << 3)
#define BOOT_DS_ENTRY 2
#define BOOT_DS (BOOT_DS_ENTRY << 3)
#define PTE_INIT_ATTR 0x00000003
#define PDE_INIT_ATTR 0x00000003
#endif /*__BOOT_H__*/
|
# ... existing code ...
/* common boot definitions */
#define BOOT_TIME_STACK_SIZE 0x4000
#define BOOT_CS_ENTRY 1
#define BOOT_CS (BOOT_CS_ENTRY << 3)
#define BOOT_DS_ENTRY 2
#define BOOT_DS (BOOT_DS_ENTRY << 3)
#define PTE_INIT_ATTR 0x00000003
#define PDE_INIT_ATTR 0x00000003
#endif /*__BOOT_H__*/
# ... rest of the code ...
|
54456e42e2c9d90095b34a30a16940584ebdb29c
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
from os.path import join, dirname
setup(
name='mosecom_air',
version='1.2',
description='Web service dedicated to air pollution in Moscow.',
long_description=open('README.md').read(),
author='elsid',
author_email='[email protected]',
packages=find_packages(),
scripts=['manage.py', 'parse_html.py', 'request.py'],
install_requires=[
'django >= 1.6.1',
'djangorestframework >= 2.3.12',
'flup >= 1.0.2',
'johnny-cache >= 1.4',
'psycopg2 >= 2.4.5',
'pyquery >= 1.2.4',
'simplejson >= 3.3.1',
'yaml >= 3.10',
],
)
|
from setuptools import setup, find_packages
from os.path import join, dirname
setup(
name='mosecom_air',
version='1.2',
description='Web service dedicated to air pollution in Moscow.',
long_description=open('README.md').read(),
author='elsid',
author_email='[email protected]',
packages=find_packages(),
scripts=['manage.py', 'parse_html.py', 'request.py'],
install_requires=[
'django >= 1.6.1',
'djangorestframework >= 2.3.12',
'flup >= 1.0.2',
'johnny-cache >= 1.4',
'memcache >= 1.53',
'psycopg2 >= 2.4.5',
'pyquery >= 1.2.4',
'simplejson >= 3.3.1',
'yaml >= 3.10',
],
)
|
Add python module memcache dependency
|
Add python module memcache dependency
|
Python
|
mit
|
elsid/mosecom-air,elsid/mosecom-air,elsid/mosecom-air
|
python
|
## Code Before:
from setuptools import setup, find_packages
from os.path import join, dirname
setup(
name='mosecom_air',
version='1.2',
description='Web service dedicated to air pollution in Moscow.',
long_description=open('README.md').read(),
author='elsid',
author_email='[email protected]',
packages=find_packages(),
scripts=['manage.py', 'parse_html.py', 'request.py'],
install_requires=[
'django >= 1.6.1',
'djangorestframework >= 2.3.12',
'flup >= 1.0.2',
'johnny-cache >= 1.4',
'psycopg2 >= 2.4.5',
'pyquery >= 1.2.4',
'simplejson >= 3.3.1',
'yaml >= 3.10',
],
)
## Instruction:
Add python module memcache dependency
## Code After:
from setuptools import setup, find_packages
from os.path import join, dirname
setup(
name='mosecom_air',
version='1.2',
description='Web service dedicated to air pollution in Moscow.',
long_description=open('README.md').read(),
author='elsid',
author_email='[email protected]',
packages=find_packages(),
scripts=['manage.py', 'parse_html.py', 'request.py'],
install_requires=[
'django >= 1.6.1',
'djangorestframework >= 2.3.12',
'flup >= 1.0.2',
'johnny-cache >= 1.4',
'memcache >= 1.53',
'psycopg2 >= 2.4.5',
'pyquery >= 1.2.4',
'simplejson >= 3.3.1',
'yaml >= 3.10',
],
)
|
# ... existing code ...
'djangorestframework >= 2.3.12',
'flup >= 1.0.2',
'johnny-cache >= 1.4',
'memcache >= 1.53',
'psycopg2 >= 2.4.5',
'pyquery >= 1.2.4',
'simplejson >= 3.3.1',
# ... rest of the code ...
|
88c8743809cccd5d855599a9c37d3b19a849b465
|
percolation/io_helpers.c
|
percolation/io_helpers.c
|
void print_lattice(int * lattice, int rows, int columns, int with_borders)
{
int i, j;
for (i = 0; i < rows; i++) {
if (with_borders) {
for (j = 0; j < columns; j++) {
printf("------");
}
printf("-\n");
}
for (j = 0; j < columns; j++) {
if (with_borders) {
putchar('|');
putchar(' ');
}
if (lattice[i*columns + j] == 1) {
printf(" x ");
} else if (lattice[i*columns + j] > 1) {
printf("%03d", lattice[i*columns + j]);
} else {
if (with_borders) {
putchar(' ');
putchar(' ');
putchar(' ');
} else {
printf(" o ");
}
}
if (with_borders) {
putchar(' ');
if (j == columns - 1) {
putchar('|');
}
} else {
if (j < columns - 1) {
putchar(' ');
}
}
}
putchar('\n');
}
if (with_borders) {
for (j = 0; j < columns; j++) {
printf("------");
}
printf("-\n");
}
}
|
void print_lattice(int * lattice, int rows, int columns, int with_borders)
{
int i, j;
for (i = 0; i < rows; i++) {
if (with_borders) {
for (j = 0; j < columns; j++) {
printf("------");
}
printf("-\n");
}
for (j = 0; j < columns; j++) {
if (with_borders) {
putchar('|');
putchar(' ');
}
if (lattice[i*columns + j] == 1) {
printf(" x ");
} else if (lattice[i*columns + j] > 1) {
printf("%03d", lattice[i*columns + j]);
} else {
if (with_borders) {
putchar(' ');
putchar(' ');
putchar(' ');
} else {
printf(" o ");
}
}
if (with_borders) {
putchar(' ');
if (j == columns - 1) {
putchar('|');
}
} else {
if (j < columns - 1) {
putchar(' ');
}
}
}
putchar('\n');
}
if (with_borders) {
for (j = 0; j < columns; j++) {
printf("------");
}
printf("-\n");
} else {
putchar('\n');
}
}
|
Add a newline after printing the lattice
|
[percolation] Add a newline after printing the lattice
|
C
|
mit
|
cerisola/fiscomp,cerisola/fiscomp,cerisola/fiscomp
|
c
|
## Code Before:
void print_lattice(int * lattice, int rows, int columns, int with_borders)
{
int i, j;
for (i = 0; i < rows; i++) {
if (with_borders) {
for (j = 0; j < columns; j++) {
printf("------");
}
printf("-\n");
}
for (j = 0; j < columns; j++) {
if (with_borders) {
putchar('|');
putchar(' ');
}
if (lattice[i*columns + j] == 1) {
printf(" x ");
} else if (lattice[i*columns + j] > 1) {
printf("%03d", lattice[i*columns + j]);
} else {
if (with_borders) {
putchar(' ');
putchar(' ');
putchar(' ');
} else {
printf(" o ");
}
}
if (with_borders) {
putchar(' ');
if (j == columns - 1) {
putchar('|');
}
} else {
if (j < columns - 1) {
putchar(' ');
}
}
}
putchar('\n');
}
if (with_borders) {
for (j = 0; j < columns; j++) {
printf("------");
}
printf("-\n");
}
}
## Instruction:
[percolation] Add a newline after printing the lattice
## Code After:
void print_lattice(int * lattice, int rows, int columns, int with_borders)
{
int i, j;
for (i = 0; i < rows; i++) {
if (with_borders) {
for (j = 0; j < columns; j++) {
printf("------");
}
printf("-\n");
}
for (j = 0; j < columns; j++) {
if (with_borders) {
putchar('|');
putchar(' ');
}
if (lattice[i*columns + j] == 1) {
printf(" x ");
} else if (lattice[i*columns + j] > 1) {
printf("%03d", lattice[i*columns + j]);
} else {
if (with_borders) {
putchar(' ');
putchar(' ');
putchar(' ');
} else {
printf(" o ");
}
}
if (with_borders) {
putchar(' ');
if (j == columns - 1) {
putchar('|');
}
} else {
if (j < columns - 1) {
putchar(' ');
}
}
}
putchar('\n');
}
if (with_borders) {
for (j = 0; j < columns; j++) {
printf("------");
}
printf("-\n");
} else {
putchar('\n');
}
}
|
// ... existing code ...
printf("------");
}
printf("-\n");
} else {
putchar('\n');
}
}
// ... rest of the code ...
|
74ae1e2809b2c69db0617e1516f2efc30aba13bb
|
setup.py
|
setup.py
|
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
__version__ = '0.11.10'
packages = [
'lassie',
'lassie.filters',
'lassie.filters.oembed'
]
setup(
name='lassie',
version=__version__,
install_requires=open("requirements.txt").read().split("\n"),
author='Mike Helmick',
license=open('LICENSE').read(),
url='https://github.com/michaelhelmick/lassie/tree/master',
keywords='lassie open graph web content scrape scraper',
description='Lassie is a Python library for retrieving basic content from websites',
long_description=open('README.rst').read(),
long_description_content_type="text/x-rst",
include_package_data=True,
packages=packages,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Internet',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.8',
]
)
|
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
__version__ = '0.11.10'
packages = [
'lassie',
'lassie.filters',
'lassie.filters.oembed'
]
setup(
name='lassie',
version=__version__,
install_requires=open("requirements.txt").read().split("\n"),
author='Mike Helmick',
license=open('LICENSE').read(),
url='https://github.com/michaelhelmick/lassie/tree/master',
keywords='lassie open graph web content scrape scraper',
description='Lassie is a Python library for retrieving content from websites and being returned in a pretty format.',
include_package_data=True,
packages=packages,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Internet',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.8',
]
)
|
Remove long desc for now.
|
Remove long desc for now.
|
Python
|
mit
|
michaelhelmick/lassie,michaelhelmick/lassie
|
python
|
## Code Before:
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
__version__ = '0.11.10'
packages = [
'lassie',
'lassie.filters',
'lassie.filters.oembed'
]
setup(
name='lassie',
version=__version__,
install_requires=open("requirements.txt").read().split("\n"),
author='Mike Helmick',
license=open('LICENSE').read(),
url='https://github.com/michaelhelmick/lassie/tree/master',
keywords='lassie open graph web content scrape scraper',
description='Lassie is a Python library for retrieving basic content from websites',
long_description=open('README.rst').read(),
long_description_content_type="text/x-rst",
include_package_data=True,
packages=packages,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Internet',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.8',
]
)
## Instruction:
Remove long desc for now.
## Code After:
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
__version__ = '0.11.10'
packages = [
'lassie',
'lassie.filters',
'lassie.filters.oembed'
]
setup(
name='lassie',
version=__version__,
install_requires=open("requirements.txt").read().split("\n"),
author='Mike Helmick',
license=open('LICENSE').read(),
url='https://github.com/michaelhelmick/lassie/tree/master',
keywords='lassie open graph web content scrape scraper',
description='Lassie is a Python library for retrieving content from websites and being returned in a pretty format.',
include_package_data=True,
packages=packages,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Internet',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.8',
]
)
|
// ... existing code ...
license=open('LICENSE').read(),
url='https://github.com/michaelhelmick/lassie/tree/master',
keywords='lassie open graph web content scrape scraper',
description='Lassie is a Python library for retrieving content from websites and being returned in a pretty format.',
include_package_data=True,
packages=packages,
classifiers=[
// ... rest of the code ...
|
49c99399c5b0e741e356cf320e338d019e06567d
|
taca/utils/config.py
|
taca/utils/config.py
|
"""Load and parse configuration file."""
import yaml
from io import open
CONFIG = {}
def load_config(config_file):
"""Loads a configuration file."""
config = {}
if type(config_file) is file:
config.update(yaml.load(config_file, Loader=yaml.FullLoader) or {})
return config
else:
try:
with open(config_file, 'r') as f:
content = yaml.load(f, Loader=yaml.FullLoader)
config.update(content)
return content
except IOError as e:
e.message = 'Could not open configuration file "{}".'.format(config_file)
raise e
def load_yaml_config(config_file):
"""Load YAML config file
:param str config_file: The path to the configuration file.
:returns: A dict of the parsed config file.
:rtype: dict
:raises IOError: If the config file cannot be opened.
"""
if type(config_file) is file:
CONFIG.update(yaml.load(config_file, Loader=yaml.FullLoader) or {})
return CONFIG
else:
try:
with open(config_file, 'r') as f:
content = yaml.load(f, Loader=yaml.FullLoader)
CONFIG.update(content)
return content
except IOError as e:
e.message = 'Could not open configuration file "{}".'.format(config_file)
raise e
|
"""Load and parse configuration file."""
import yaml
from io import open
CONFIG = {}
def load_config(config_file):
"""Loads a configuration file."""
config = {}
try:
with open(config_file, 'r') as f:
content = yaml.load(f, Loader=yaml.FullLoader)
config.update(content)
return content
except IOError as e:
e.message = 'Could not open configuration file "{}".'.format(config_file)
raise e
def load_yaml_config(config_file):
"""Load YAML config file
:param str config_file: The path to the configuration file.
:returns: A dict of the parsed config file.
:rtype: dict
:raises IOError: If the config file cannot be opened.
"""
try:
with open(config_file, 'r') as f:
content = yaml.load(f, Loader=yaml.FullLoader)
CONFIG.update(content)
return content
except IOError as e:
e.message = 'Could not open configuration file "{}".'.format(config_file)
raise e
|
Remove unused file type check
|
Remove unused file type check
|
Python
|
mit
|
SciLifeLab/TACA,SciLifeLab/TACA,SciLifeLab/TACA
|
python
|
## Code Before:
"""Load and parse configuration file."""
import yaml
from io import open
CONFIG = {}
def load_config(config_file):
"""Loads a configuration file."""
config = {}
if type(config_file) is file:
config.update(yaml.load(config_file, Loader=yaml.FullLoader) or {})
return config
else:
try:
with open(config_file, 'r') as f:
content = yaml.load(f, Loader=yaml.FullLoader)
config.update(content)
return content
except IOError as e:
e.message = 'Could not open configuration file "{}".'.format(config_file)
raise e
def load_yaml_config(config_file):
"""Load YAML config file
:param str config_file: The path to the configuration file.
:returns: A dict of the parsed config file.
:rtype: dict
:raises IOError: If the config file cannot be opened.
"""
if type(config_file) is file:
CONFIG.update(yaml.load(config_file, Loader=yaml.FullLoader) or {})
return CONFIG
else:
try:
with open(config_file, 'r') as f:
content = yaml.load(f, Loader=yaml.FullLoader)
CONFIG.update(content)
return content
except IOError as e:
e.message = 'Could not open configuration file "{}".'.format(config_file)
raise e
## Instruction:
Remove unused file type check
## Code After:
"""Load and parse configuration file."""
import yaml
from io import open
CONFIG = {}
def load_config(config_file):
"""Loads a configuration file."""
config = {}
try:
with open(config_file, 'r') as f:
content = yaml.load(f, Loader=yaml.FullLoader)
config.update(content)
return content
except IOError as e:
e.message = 'Could not open configuration file "{}".'.format(config_file)
raise e
def load_yaml_config(config_file):
"""Load YAML config file
:param str config_file: The path to the configuration file.
:returns: A dict of the parsed config file.
:rtype: dict
:raises IOError: If the config file cannot be opened.
"""
try:
with open(config_file, 'r') as f:
content = yaml.load(f, Loader=yaml.FullLoader)
CONFIG.update(content)
return content
except IOError as e:
e.message = 'Could not open configuration file "{}".'.format(config_file)
raise e
|
...
def load_config(config_file):
"""Loads a configuration file."""
config = {}
try:
with open(config_file, 'r') as f:
content = yaml.load(f, Loader=yaml.FullLoader)
config.update(content)
return content
except IOError as e:
e.message = 'Could not open configuration file "{}".'.format(config_file)
raise e
def load_yaml_config(config_file):
"""Load YAML config file
...
:rtype: dict
:raises IOError: If the config file cannot be opened.
"""
try:
with open(config_file, 'r') as f:
content = yaml.load(f, Loader=yaml.FullLoader)
CONFIG.update(content)
return content
except IOError as e:
e.message = 'Could not open configuration file "{}".'.format(config_file)
raise e
...
|
2022c5485289712b8de22fe551d65cf005442826
|
massa/domain/__init__.py
|
massa/domain/__init__.py
|
from schematics.exceptions import ConversionError, ValidationError
def validate(schema, data):
try:
schema.import_data(data)
schema.validate()
except (ConversionError, ValidationError) as e:
raise InvalidInputError(details=e.messages)
def weight_validator(value):
if abs(value.as_tuple().exponent) > 1:
raise ValidationError('More than one decimal exponent not allowed')
return value
class DomainError(Exception):
def __init__(self, message=None, details=None):
if message: self.message = message
if details: self.details = details
class EntityNotFoundError(DomainError):
"""Raised when an entity does not exist."""
message = 'Entity does not exist.'
class InvalidInputError(DomainError):
"""Raised when input data is invalid."""
message = 'Input data is invalid.'
|
from schematics.exceptions import ConversionError, ValidationError
def validate(schema, data):
try:
schema.import_data(data)
schema.validate()
except (ConversionError, ValidationError) as e:
raise InvalidInputError(details=e.messages)
def weight_validator(value):
if abs(value.as_tuple().exponent) > 1:
raise ValidationError('Only one decimal point is allowed.')
return value
class DomainError(Exception):
def __init__(self, message=None, details=None):
if message: self.message = message
if details: self.details = details
class EntityNotFoundError(DomainError):
"""Raised when an entity does not exist."""
message = 'Entity does not exist.'
class InvalidInputError(DomainError):
"""Raised when input data is invalid."""
message = 'Input data is invalid.'
|
Change error message of the weight validator.
|
Change error message of the weight validator.
|
Python
|
mit
|
jaapverloop/massa
|
python
|
## Code Before:
from schematics.exceptions import ConversionError, ValidationError
def validate(schema, data):
try:
schema.import_data(data)
schema.validate()
except (ConversionError, ValidationError) as e:
raise InvalidInputError(details=e.messages)
def weight_validator(value):
if abs(value.as_tuple().exponent) > 1:
raise ValidationError('More than one decimal exponent not allowed')
return value
class DomainError(Exception):
def __init__(self, message=None, details=None):
if message: self.message = message
if details: self.details = details
class EntityNotFoundError(DomainError):
"""Raised when an entity does not exist."""
message = 'Entity does not exist.'
class InvalidInputError(DomainError):
"""Raised when input data is invalid."""
message = 'Input data is invalid.'
## Instruction:
Change error message of the weight validator.
## Code After:
from schematics.exceptions import ConversionError, ValidationError
def validate(schema, data):
try:
schema.import_data(data)
schema.validate()
except (ConversionError, ValidationError) as e:
raise InvalidInputError(details=e.messages)
def weight_validator(value):
if abs(value.as_tuple().exponent) > 1:
raise ValidationError('Only one decimal point is allowed.')
return value
class DomainError(Exception):
def __init__(self, message=None, details=None):
if message: self.message = message
if details: self.details = details
class EntityNotFoundError(DomainError):
"""Raised when an entity does not exist."""
message = 'Entity does not exist.'
class InvalidInputError(DomainError):
"""Raised when input data is invalid."""
message = 'Input data is invalid.'
|
...
def weight_validator(value):
if abs(value.as_tuple().exponent) > 1:
raise ValidationError('Only one decimal point is allowed.')
return value
...
|
5a03cd340e5dc8a796c7d430128f0e22be17333e
|
qiime/sdk/__init__.py
|
qiime/sdk/__init__.py
|
from .method import Method
from .plugin_manager import PluginManager
from .provenance import Provenance
from .visualizer import Visualizer
from .result import Result, Artifact, Visualization
from ..core.util import parse_type
__all__ = ['Result', 'Artifact', 'Visualization', 'Method', 'Visualizer',
'PluginManager', 'Provenance', 'parse_type']
|
from .method import Method
from .plugin_manager import PluginManager
from .provenance import Provenance
from .visualizer import Visualizer
from .result import Result, Artifact, Visualization
from ..core.util import parse_type
__all__ = ['Result', 'Artifact', 'Visualization', 'Method', 'Visualizer',
'PluginManager', 'Provenance', 'parse_type']
# Various URLs
CITATION = 'http://www.ncbi.nlm.nih.gov/pubmed/20383131'
HELP_URL = 'http://2.qiime.org'
CONDA_CHANNEL = 'https://anaconda.org/qiime2'
|
Add helper URLs to qiime.sdk
|
ENH: Add helper URLs to qiime.sdk
Adds citation url, help page, and conda channel URLs to qiime.sdk
|
Python
|
bsd-3-clause
|
biocore/qiime2,thermokarst/qiime2,ebolyen/qiime2,jakereps/qiime2,qiime2/qiime2,qiime2/qiime2,nervous-laughter/qiime2,biocore/qiime2,thermokarst/qiime2,jairideout/qiime2,jakereps/qiime2
|
python
|
## Code Before:
from .method import Method
from .plugin_manager import PluginManager
from .provenance import Provenance
from .visualizer import Visualizer
from .result import Result, Artifact, Visualization
from ..core.util import parse_type
__all__ = ['Result', 'Artifact', 'Visualization', 'Method', 'Visualizer',
'PluginManager', 'Provenance', 'parse_type']
## Instruction:
ENH: Add helper URLs to qiime.sdk
Adds citation url, help page, and conda channel URLs to qiime.sdk
## Code After:
from .method import Method
from .plugin_manager import PluginManager
from .provenance import Provenance
from .visualizer import Visualizer
from .result import Result, Artifact, Visualization
from ..core.util import parse_type
__all__ = ['Result', 'Artifact', 'Visualization', 'Method', 'Visualizer',
'PluginManager', 'Provenance', 'parse_type']
# Various URLs
CITATION = 'http://www.ncbi.nlm.nih.gov/pubmed/20383131'
HELP_URL = 'http://2.qiime.org'
CONDA_CHANNEL = 'https://anaconda.org/qiime2'
|
...
__all__ = ['Result', 'Artifact', 'Visualization', 'Method', 'Visualizer',
'PluginManager', 'Provenance', 'parse_type']
# Various URLs
CITATION = 'http://www.ncbi.nlm.nih.gov/pubmed/20383131'
HELP_URL = 'http://2.qiime.org'
CONDA_CHANNEL = 'https://anaconda.org/qiime2'
...
|
d2f1b9311b546c079490e5f0bdb45b9c9d570bb1
|
system/test_coupling_fields.py
|
system/test_coupling_fields.py
|
from __future__ import print_function
import os
import netCDF4 as nc
from model_test_helper import ModelTestHelper
class TestCouplingFields(ModelTestHelper):
def __init__(self):
super(TestCouplingFields, self).__init__()
def test_swflx(self):
"""
Compare short wave flux over a geographic area between low and hi res
models.
"""
hi_fields = os.path.join(self.paths['cm_1440x1080-test']['output'], 'ice',
'fields_a2i_in_ice.nc')
lo_fields = os.path.join(self.paths['cm_360x300-test']['output'], 'ice',
'fields_a2i_in_ice.nc')
f_hi = nc.Dataset(hi_fields)
f_hi.close()
f_lo = nc.Dataset(lo_fields)
f_lo.close()
|
from __future__ import print_function
import os
import netCDF4 as nc
from model_test_helper import ModelTestHelper
class TestCouplingFields(ModelTestHelper):
def __init__(self):
super(TestCouplingFields, self).__init__()
def test_swflx(self):
"""
Compare short wave flux over a geographic area between low and hi res
models.
"""
hi_paths = self.make_paths('cm_1440x1080-test')
lo_paths = self.make_paths('cm_360x300-test')
hi_fields = os.path.join(hi_paths['output'], 'ice',
'fields_a2i_in_ice.nc')
lo_fields = os.path.join(lo_paths['output'], 'ice',
'fields_a2i_in_ice.nc')
f_hi = nc.Dataset(hi_fields)
f_hi.close()
f_lo = nc.Dataset(lo_fields)
f_lo.close()
|
Fix up paths in system test.
|
Fix up paths in system test.
|
Python
|
apache-2.0
|
CWSL/access-om
|
python
|
## Code Before:
from __future__ import print_function
import os
import netCDF4 as nc
from model_test_helper import ModelTestHelper
class TestCouplingFields(ModelTestHelper):
def __init__(self):
super(TestCouplingFields, self).__init__()
def test_swflx(self):
"""
Compare short wave flux over a geographic area between low and hi res
models.
"""
hi_fields = os.path.join(self.paths['cm_1440x1080-test']['output'], 'ice',
'fields_a2i_in_ice.nc')
lo_fields = os.path.join(self.paths['cm_360x300-test']['output'], 'ice',
'fields_a2i_in_ice.nc')
f_hi = nc.Dataset(hi_fields)
f_hi.close()
f_lo = nc.Dataset(lo_fields)
f_lo.close()
## Instruction:
Fix up paths in system test.
## Code After:
from __future__ import print_function
import os
import netCDF4 as nc
from model_test_helper import ModelTestHelper
class TestCouplingFields(ModelTestHelper):
def __init__(self):
super(TestCouplingFields, self).__init__()
def test_swflx(self):
"""
Compare short wave flux over a geographic area between low and hi res
models.
"""
hi_paths = self.make_paths('cm_1440x1080-test')
lo_paths = self.make_paths('cm_360x300-test')
hi_fields = os.path.join(hi_paths['output'], 'ice',
'fields_a2i_in_ice.nc')
lo_fields = os.path.join(lo_paths['output'], 'ice',
'fields_a2i_in_ice.nc')
f_hi = nc.Dataset(hi_fields)
f_hi.close()
f_lo = nc.Dataset(lo_fields)
f_lo.close()
|
...
models.
"""
hi_paths = self.make_paths('cm_1440x1080-test')
lo_paths = self.make_paths('cm_360x300-test')
hi_fields = os.path.join(hi_paths['output'], 'ice',
'fields_a2i_in_ice.nc')
lo_fields = os.path.join(lo_paths['output'], 'ice',
'fields_a2i_in_ice.nc')
f_hi = nc.Dataset(hi_fields)
f_hi.close()
...
|
46f3067650001454ed99351cc5569813a378dcec
|
mopidy_jukebox/frontend.py
|
mopidy_jukebox/frontend.py
|
import pykka
from mopidy import core
class JukeboxFrontend(pykka.ThreadingActor, core.CoreListener):
def __init__(self, config, core):
super(JukeboxFrontend, self).__init__()
self.core = core
def track_playback_ended(self, tl_track, time_position):
# Remove old votes
pass
def track_playback_started(self, tl_track):
pass
|
import pykka
from mopidy import core
from models import Vote
class JukeboxFrontend(pykka.ThreadingActor, core.CoreListener):
def __init__(self, config, core):
super(JukeboxFrontend, self).__init__()
self.core = core
core.tracklist.set_consume(True)
def track_playback_ended(self, tl_track, time_position):
# Remove old votes
Vote.delete().where(Vote.track_uri == tl_track.track.uri).execute()
def track_playback_started(self, tl_track):
pass
|
Delete votes when track is over.
|
Delete votes when track is over.
|
Python
|
mit
|
qurben/mopidy-jukebox,qurben/mopidy-jukebox,qurben/mopidy-jukebox
|
python
|
## Code Before:
import pykka
from mopidy import core
class JukeboxFrontend(pykka.ThreadingActor, core.CoreListener):
def __init__(self, config, core):
super(JukeboxFrontend, self).__init__()
self.core = core
def track_playback_ended(self, tl_track, time_position):
# Remove old votes
pass
def track_playback_started(self, tl_track):
pass
## Instruction:
Delete votes when track is over.
## Code After:
import pykka
from mopidy import core
from models import Vote
class JukeboxFrontend(pykka.ThreadingActor, core.CoreListener):
def __init__(self, config, core):
super(JukeboxFrontend, self).__init__()
self.core = core
core.tracklist.set_consume(True)
def track_playback_ended(self, tl_track, time_position):
# Remove old votes
Vote.delete().where(Vote.track_uri == tl_track.track.uri).execute()
def track_playback_started(self, tl_track):
pass
|
...
import pykka
from mopidy import core
from models import Vote
class JukeboxFrontend(pykka.ThreadingActor, core.CoreListener):
...
def __init__(self, config, core):
super(JukeboxFrontend, self).__init__()
self.core = core
core.tracklist.set_consume(True)
def track_playback_ended(self, tl_track, time_position):
# Remove old votes
Vote.delete().where(Vote.track_uri == tl_track.track.uri).execute()
def track_playback_started(self, tl_track):
pass
...
|
5719b3bc80be0c71c1fc008b15e19ef44485049f
|
src/main/java/me/coley/recaf/decompile/Decompiler.java
|
src/main/java/me/coley/recaf/decompile/Decompiler.java
|
package me.coley.recaf.decompile;
import me.coley.recaf.workspace.Workspace;
import java.util.Map;
/**
* Decompiler base.
*
* @author Matt.
*/
public abstract class Decompiler<OptionType> {
private final Map<String, OptionType> defaultOptions = generateDefaultOptions();
private Map<String, OptionType> options = defaultOptions;
/**
* @return Map of the current options.
*/
public Map<String, OptionType> getOptions() {
return options;
}
/**
* @param options
* Map of the options to use.
*/
public void setOptions(Map<String, OptionType> options) {
this.options = options;
}
/**
* @return Map of the default decompiler options.
*/
public Map<String, OptionType> getDefaultOptions() {
return defaultOptions;
}
/**
* @return Map of the default decompiler options.
*/
protected abstract Map<String, OptionType> generateDefaultOptions();
/**
* @param workspace
* Workspace to pull classes from.
* @param name
* Name of the class to decompile.
*
* @return Decompiled text of the class.
*/
public abstract String decompile(Workspace workspace, String name);
}
|
package me.coley.recaf.decompile;
import me.coley.recaf.workspace.Workspace;
import java.util.*;
/**
* Decompiler base.
*
* @author Matt.
*/
public abstract class Decompiler<OptionType> {
private final Map<String, OptionType> defaultOptions = Collections.unmodifiableMap(generateDefaultOptions());
private Map<String, OptionType> options = new HashMap<>(defaultOptions);
/**
* @return Map of the current options.
*/
public Map<String, OptionType> getOptions() {
return options;
}
/**
* @param options
* Map of the options to use.
*/
public void setOptions(Map<String, OptionType> options) {
this.options = options;
}
/**
* @return Map of the default decompiler options.
*/
public Map<String, OptionType> getDefaultOptions() {
return defaultOptions;
}
/**
* @return Map of the default decompiler options.
*/
protected abstract Map<String, OptionType> generateDefaultOptions();
/**
* @param workspace
* Workspace to pull classes from.
* @param name
* Name of the class to decompile.
*
* @return Decompiled text of the class.
*/
public abstract String decompile(Workspace workspace, String name);
}
|
Make default options map unmodifiable
|
Make default options map unmodifiable
|
Java
|
mit
|
Col-E/Recaf,Col-E/Recaf
|
java
|
## Code Before:
package me.coley.recaf.decompile;
import me.coley.recaf.workspace.Workspace;
import java.util.Map;
/**
* Decompiler base.
*
* @author Matt.
*/
public abstract class Decompiler<OptionType> {
private final Map<String, OptionType> defaultOptions = generateDefaultOptions();
private Map<String, OptionType> options = defaultOptions;
/**
* @return Map of the current options.
*/
public Map<String, OptionType> getOptions() {
return options;
}
/**
* @param options
* Map of the options to use.
*/
public void setOptions(Map<String, OptionType> options) {
this.options = options;
}
/**
* @return Map of the default decompiler options.
*/
public Map<String, OptionType> getDefaultOptions() {
return defaultOptions;
}
/**
* @return Map of the default decompiler options.
*/
protected abstract Map<String, OptionType> generateDefaultOptions();
/**
* @param workspace
* Workspace to pull classes from.
* @param name
* Name of the class to decompile.
*
* @return Decompiled text of the class.
*/
public abstract String decompile(Workspace workspace, String name);
}
## Instruction:
Make default options map unmodifiable
## Code After:
package me.coley.recaf.decompile;
import me.coley.recaf.workspace.Workspace;
import java.util.*;
/**
* Decompiler base.
*
* @author Matt.
*/
public abstract class Decompiler<OptionType> {
private final Map<String, OptionType> defaultOptions = Collections.unmodifiableMap(generateDefaultOptions());
private Map<String, OptionType> options = new HashMap<>(defaultOptions);
/**
* @return Map of the current options.
*/
public Map<String, OptionType> getOptions() {
return options;
}
/**
* @param options
* Map of the options to use.
*/
public void setOptions(Map<String, OptionType> options) {
this.options = options;
}
/**
* @return Map of the default decompiler options.
*/
public Map<String, OptionType> getDefaultOptions() {
return defaultOptions;
}
/**
* @return Map of the default decompiler options.
*/
protected abstract Map<String, OptionType> generateDefaultOptions();
/**
* @param workspace
* Workspace to pull classes from.
* @param name
* Name of the class to decompile.
*
* @return Decompiled text of the class.
*/
public abstract String decompile(Workspace workspace, String name);
}
|
// ... existing code ...
import me.coley.recaf.workspace.Workspace;
import java.util.*;
/**
* Decompiler base.
// ... modified code ...
* @author Matt.
*/
public abstract class Decompiler<OptionType> {
private final Map<String, OptionType> defaultOptions = Collections.unmodifiableMap(generateDefaultOptions());
private Map<String, OptionType> options = new HashMap<>(defaultOptions);
/**
* @return Map of the current options.
// ... rest of the code ...
|
c129b435a7759104feaaa5b828dc2f2ac46d5ab1
|
src/cmdlinetest/afp_mock.py
|
src/cmdlinetest/afp_mock.py
|
from bottle import route
from textwrap import dedent
from bottledaemon import daemon_run
""" Simple AFP mock to allow testing the afp-cli. """
@route('/account')
def account():
return """{"test_account": ["test_role"]}"""
@route('/account/<account>/<role>')
def credentials(account, role):
return dedent("""
{"Code": "Success",
"LastUpdated": "1970-01-01T00:00:00Z",
"AccessKeyId": "XXXXXXXXXXXX",
"SecretAccessKey": "XXXXXXXXXXXX",
"Token": "XXXXXXXXXXXX",
"Expiration": "2032-01-01T00:00:00Z",
"Type": "AWS-HMAC"}""").strip()
daemon_run(host='localhost', port=5555)
|
""" Simple AFP mock to allow testing the afp-cli. """
from bottle import route
from textwrap import dedent
from bottledaemon import daemon_run
@route('/account')
def account():
return """{"test_account": ["test_role"]}"""
@route('/account/<account>/<role>')
def credentials(account, role):
return dedent("""
{"Code": "Success",
"LastUpdated": "1970-01-01T00:00:00Z",
"AccessKeyId": "XXXXXXXXXXXX",
"SecretAccessKey": "XXXXXXXXXXXX",
"Token": "XXXXXXXXXXXX",
"Expiration": "2032-01-01T00:00:00Z",
"Type": "AWS-HMAC"}""").strip()
daemon_run(host='localhost', port=5555)
|
Move string above the imports so it becomes a docstring
|
Move string above the imports so it becomes a docstring
|
Python
|
apache-2.0
|
ImmobilienScout24/afp-cli,ImmobilienScout24/afp-cli,ImmobilienScout24/afp-cli
|
python
|
## Code Before:
from bottle import route
from textwrap import dedent
from bottledaemon import daemon_run
""" Simple AFP mock to allow testing the afp-cli. """
@route('/account')
def account():
return """{"test_account": ["test_role"]}"""
@route('/account/<account>/<role>')
def credentials(account, role):
return dedent("""
{"Code": "Success",
"LastUpdated": "1970-01-01T00:00:00Z",
"AccessKeyId": "XXXXXXXXXXXX",
"SecretAccessKey": "XXXXXXXXXXXX",
"Token": "XXXXXXXXXXXX",
"Expiration": "2032-01-01T00:00:00Z",
"Type": "AWS-HMAC"}""").strip()
daemon_run(host='localhost', port=5555)
## Instruction:
Move string above the imports so it becomes a docstring
## Code After:
""" Simple AFP mock to allow testing the afp-cli. """
from bottle import route
from textwrap import dedent
from bottledaemon import daemon_run
@route('/account')
def account():
return """{"test_account": ["test_role"]}"""
@route('/account/<account>/<role>')
def credentials(account, role):
return dedent("""
{"Code": "Success",
"LastUpdated": "1970-01-01T00:00:00Z",
"AccessKeyId": "XXXXXXXXXXXX",
"SecretAccessKey": "XXXXXXXXXXXX",
"Token": "XXXXXXXXXXXX",
"Expiration": "2032-01-01T00:00:00Z",
"Type": "AWS-HMAC"}""").strip()
daemon_run(host='localhost', port=5555)
|
...
""" Simple AFP mock to allow testing the afp-cli. """
from bottle import route
from textwrap import dedent
from bottledaemon import daemon_run
@route('/account')
def account():
...
|
8dc1bab80e52442999eb59e096abd5848c4e8d66
|
unicornclient/routine.py
|
unicornclient/routine.py
|
import threading
import queue
class Routine(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.queue = queue.Queue()
self.manager = None
self.no_wait = False
def run(self):
while True:
got_task = False
data = None
if self.no_wait:
try:
data = self.queue.get_nowait()
got_task = True
except queue.Empty:
data = None
got_task = False
else:
data = self.queue.get()
got_task = True
if data:
index = 'routine_command'
routine_command = data[index] if index in data else None
if routine_command == 'stop':
return
self.process(data)
if got_task:
self.queue.task_done()
def process(self, data):
pass
|
import threading
import queue
class Routine(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.queue = queue.Queue()
self.manager = None
self.no_wait = False
self.is_stopping = False
def run(self):
while True:
got_task = False
data = None
if self.no_wait:
try:
data = self.queue.get_nowait()
got_task = True
except queue.Empty:
data = None
got_task = False
else:
data = self.queue.get()
got_task = True
if data:
index = 'routine_command'
routine_command = data[index] if index in data else None
if routine_command == 'stop':
self.is_stopping = True
self.process(data)
if got_task:
self.queue.task_done()
if self.is_stopping:
break
def process(self, data):
pass
|
Allow one last call to process before stopping
|
Allow one last call to process before stopping
|
Python
|
mit
|
amm0nite/unicornclient,amm0nite/unicornclient
|
python
|
## Code Before:
import threading
import queue
class Routine(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.queue = queue.Queue()
self.manager = None
self.no_wait = False
def run(self):
while True:
got_task = False
data = None
if self.no_wait:
try:
data = self.queue.get_nowait()
got_task = True
except queue.Empty:
data = None
got_task = False
else:
data = self.queue.get()
got_task = True
if data:
index = 'routine_command'
routine_command = data[index] if index in data else None
if routine_command == 'stop':
return
self.process(data)
if got_task:
self.queue.task_done()
def process(self, data):
pass
## Instruction:
Allow one last call to process before stopping
## Code After:
import threading
import queue
class Routine(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.queue = queue.Queue()
self.manager = None
self.no_wait = False
self.is_stopping = False
def run(self):
while True:
got_task = False
data = None
if self.no_wait:
try:
data = self.queue.get_nowait()
got_task = True
except queue.Empty:
data = None
got_task = False
else:
data = self.queue.get()
got_task = True
if data:
index = 'routine_command'
routine_command = data[index] if index in data else None
if routine_command == 'stop':
self.is_stopping = True
self.process(data)
if got_task:
self.queue.task_done()
if self.is_stopping:
break
def process(self, data):
pass
|
// ... existing code ...
self.queue = queue.Queue()
self.manager = None
self.no_wait = False
self.is_stopping = False
def run(self):
while True:
// ... modified code ...
routine_command = data[index] if index in data else None
if routine_command == 'stop':
self.is_stopping = True
self.process(data)
...
if got_task:
self.queue.task_done()
if self.is_stopping:
break
def process(self, data):
pass
// ... rest of the code ...
|
0aeae63f29184fa3e9ba7717b8d16f190578d3af
|
ejb/src/test/java/javaeems/chapter1/model/ModelEJBTest.java
|
ejb/src/test/java/javaeems/chapter1/model/ModelEJBTest.java
|
package javaeems.chapter1.model;
import static org.junit.Assert.*;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ModelEJBTest {
private ModelEJB ejb;
private EntityManagerFactory emf;
@Before
public void setUp() {
ejb = new ModelEJB();
emf = Persistence.createEntityManagerFactory("ejb-tests-pu");
ejb.em = emf.createEntityManager();
}
@After
public void tearDown() {
if (ejb.em != null) {
ejb.em.close();
}
if (emf != null) {
emf.close();
}
}
@Test(expected=MessageException.class)
public void testNothingInDB() throws MessageException {
ejb.getStoredMessage();
}
@Test
public void testSetAndGet() throws MessageException {
EntityTransaction tx = ejb.em.getTransaction();
try {
tx.begin();
ejb.putUserMessage("hello");
ejb.putUserMessage("some statistically improbable phrase");
} finally {
tx.commit();
}
String message = ejb.getStoredMessage();
assertTrue(message.contains("some statistically improbable phrase"));
}
}
|
package javaeems.chapter1.model;
import static org.junit.Assert.*;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ModelEJBTest {
private ModelEJB ejb;
private EntityManagerFactory emf;
@Before
public void setUp() {
ejb = new ModelEJB();
emf = Persistence.createEntityManagerFactory("ejb-tests-pu");
ejb.em = emf.createEntityManager();
}
@After
public void tearDown() {
if (ejb.em != null) {
ejb.em.close();
}
if (emf != null) {
emf.close();
}
}
@Test(expected=MessageException.class)
public void testNothingInDB() throws MessageException {
ejb.getStoredMessage();
}
@Test
public void testSetAndGet() throws MessageException {
EntityTransaction tx = ejb.em.getTransaction();
try {
tx.begin();
ejb.putUserMessage("hello");
ejb.putUserMessage("some statistically improbable phrase");
} finally {
tx.commit();
}
long numEntries = (long) ejb.em.createQuery("select count(m) from Message m").getSingleResult();
assertEquals(1, numEntries);
String message = ejb.getStoredMessage();
assertTrue(message.contains("some statistically improbable phrase"));
}
}
|
Test that there is only one entry in the DB.
|
Test that there is only one entry in the DB.
|
Java
|
apache-2.0
|
hammingweight/gradle-java-ear,hammingweight/gradle-java-ear
|
java
|
## Code Before:
package javaeems.chapter1.model;
import static org.junit.Assert.*;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ModelEJBTest {
private ModelEJB ejb;
private EntityManagerFactory emf;
@Before
public void setUp() {
ejb = new ModelEJB();
emf = Persistence.createEntityManagerFactory("ejb-tests-pu");
ejb.em = emf.createEntityManager();
}
@After
public void tearDown() {
if (ejb.em != null) {
ejb.em.close();
}
if (emf != null) {
emf.close();
}
}
@Test(expected=MessageException.class)
public void testNothingInDB() throws MessageException {
ejb.getStoredMessage();
}
@Test
public void testSetAndGet() throws MessageException {
EntityTransaction tx = ejb.em.getTransaction();
try {
tx.begin();
ejb.putUserMessage("hello");
ejb.putUserMessage("some statistically improbable phrase");
} finally {
tx.commit();
}
String message = ejb.getStoredMessage();
assertTrue(message.contains("some statistically improbable phrase"));
}
}
## Instruction:
Test that there is only one entry in the DB.
## Code After:
package javaeems.chapter1.model;
import static org.junit.Assert.*;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ModelEJBTest {
private ModelEJB ejb;
private EntityManagerFactory emf;
@Before
public void setUp() {
ejb = new ModelEJB();
emf = Persistence.createEntityManagerFactory("ejb-tests-pu");
ejb.em = emf.createEntityManager();
}
@After
public void tearDown() {
if (ejb.em != null) {
ejb.em.close();
}
if (emf != null) {
emf.close();
}
}
@Test(expected=MessageException.class)
public void testNothingInDB() throws MessageException {
ejb.getStoredMessage();
}
@Test
public void testSetAndGet() throws MessageException {
EntityTransaction tx = ejb.em.getTransaction();
try {
tx.begin();
ejb.putUserMessage("hello");
ejb.putUserMessage("some statistically improbable phrase");
} finally {
tx.commit();
}
long numEntries = (long) ejb.em.createQuery("select count(m) from Message m").getSingleResult();
assertEquals(1, numEntries);
String message = ejb.getStoredMessage();
assertTrue(message.contains("some statistically improbable phrase"));
}
}
|
// ... existing code ...
} finally {
tx.commit();
}
long numEntries = (long) ejb.em.createQuery("select count(m) from Message m").getSingleResult();
assertEquals(1, numEntries);
String message = ejb.getStoredMessage();
assertTrue(message.contains("some statistically improbable phrase"));
}
// ... rest of the code ...
|
188ad806809b4663732b5fadd611d73f2c02fcf4
|
subprojects/format/src/main/groovy/com/github/sherter/googlejavaformatgradleplugin/format/Gjf.java
|
subprojects/format/src/main/groovy/com/github/sherter/googlejavaformatgradleplugin/format/Gjf.java
|
package com.github.sherter.googlejavaformatgradleplugin.format;
import com.google.common.collect.ImmutableList;
/** Static factory method for creating new {@link Formatter}s. */
public class Gjf {
public static final String GROUP_ID = "com.google.googlejavaformat";
public static final String ARTIFACT_ID = "google-java-format";
public static final ImmutableList<String> SUPPORTED_VERSIONS =
ImmutableList.of("1.0", "1.1", "1.2", "1.3");
/**
* Constructs a new formatter that delegates to <a
* href="https://github.com/google/google-java-format">google-java-format</a>.
*
* @param classLoader load {@code google-java-format} classes from this {@code ClassLoader}
* @param config configure the formatter according to this configuration
* @throws ReflectiveOperationException if the requested {@code Formatter} cannot be constructed
*/
public static Formatter newFormatter(ClassLoader classLoader, Configuration config)
throws ReflectiveOperationException {
return newFormatterFactory(classLoader, config).create();
}
private static FormatterFactory newFormatterFactory(
ClassLoader classLoader, Configuration config) {
switch (config.version) {
case "1.0":
return new OneDotZeroFactory(classLoader, config);
case "1.1":
return new OneDotOneFactory(classLoader, config);
default:
return new OneDotOneFactory(classLoader, config);
}
}
}
|
package com.github.sherter.googlejavaformatgradleplugin.format;
import com.google.common.collect.ImmutableList;
/** Static factory method for creating new {@link Formatter}s. */
public class Gjf {
public static final String GROUP_ID = "com.google.googlejavaformat";
public static final String ARTIFACT_ID = "google-java-format";
public static final ImmutableList<String> SUPPORTED_VERSIONS =
ImmutableList.of("1.0", "1.1", "1.2", "1.3", "1.4", "1.5", "1.6");
/**
* Constructs a new formatter that delegates to <a
* href="https://github.com/google/google-java-format">google-java-format</a>.
*
* @param classLoader load {@code google-java-format} classes from this {@code ClassLoader}
* @param config configure the formatter according to this configuration
* @throws ReflectiveOperationException if the requested {@code Formatter} cannot be constructed
*/
public static Formatter newFormatter(ClassLoader classLoader, Configuration config)
throws ReflectiveOperationException {
return newFormatterFactory(classLoader, config).create();
}
private static FormatterFactory newFormatterFactory(
ClassLoader classLoader, Configuration config) {
switch (config.version) {
case "1.0":
return new OneDotZeroFactory(classLoader, config);
case "1.1":
return new OneDotOneFactory(classLoader, config);
default:
return new OneDotOneFactory(classLoader, config);
}
}
}
|
Add support for google-java-format versions 1.4, 1.5 and 1.6
|
Add support for google-java-format versions 1.4, 1.5 and 1.6
|
Java
|
mit
|
sherter/google-java-format-gradle-plugin,sherter/google-java-format-gradle-plugin
|
java
|
## Code Before:
package com.github.sherter.googlejavaformatgradleplugin.format;
import com.google.common.collect.ImmutableList;
/** Static factory method for creating new {@link Formatter}s. */
public class Gjf {
public static final String GROUP_ID = "com.google.googlejavaformat";
public static final String ARTIFACT_ID = "google-java-format";
public static final ImmutableList<String> SUPPORTED_VERSIONS =
ImmutableList.of("1.0", "1.1", "1.2", "1.3");
/**
* Constructs a new formatter that delegates to <a
* href="https://github.com/google/google-java-format">google-java-format</a>.
*
* @param classLoader load {@code google-java-format} classes from this {@code ClassLoader}
* @param config configure the formatter according to this configuration
* @throws ReflectiveOperationException if the requested {@code Formatter} cannot be constructed
*/
public static Formatter newFormatter(ClassLoader classLoader, Configuration config)
throws ReflectiveOperationException {
return newFormatterFactory(classLoader, config).create();
}
private static FormatterFactory newFormatterFactory(
ClassLoader classLoader, Configuration config) {
switch (config.version) {
case "1.0":
return new OneDotZeroFactory(classLoader, config);
case "1.1":
return new OneDotOneFactory(classLoader, config);
default:
return new OneDotOneFactory(classLoader, config);
}
}
}
## Instruction:
Add support for google-java-format versions 1.4, 1.5 and 1.6
## Code After:
package com.github.sherter.googlejavaformatgradleplugin.format;
import com.google.common.collect.ImmutableList;
/** Static factory method for creating new {@link Formatter}s. */
public class Gjf {
public static final String GROUP_ID = "com.google.googlejavaformat";
public static final String ARTIFACT_ID = "google-java-format";
public static final ImmutableList<String> SUPPORTED_VERSIONS =
ImmutableList.of("1.0", "1.1", "1.2", "1.3", "1.4", "1.5", "1.6");
/**
* Constructs a new formatter that delegates to <a
* href="https://github.com/google/google-java-format">google-java-format</a>.
*
* @param classLoader load {@code google-java-format} classes from this {@code ClassLoader}
* @param config configure the formatter according to this configuration
* @throws ReflectiveOperationException if the requested {@code Formatter} cannot be constructed
*/
public static Formatter newFormatter(ClassLoader classLoader, Configuration config)
throws ReflectiveOperationException {
return newFormatterFactory(classLoader, config).create();
}
private static FormatterFactory newFormatterFactory(
ClassLoader classLoader, Configuration config) {
switch (config.version) {
case "1.0":
return new OneDotZeroFactory(classLoader, config);
case "1.1":
return new OneDotOneFactory(classLoader, config);
default:
return new OneDotOneFactory(classLoader, config);
}
}
}
|
// ... existing code ...
public static final String ARTIFACT_ID = "google-java-format";
public static final ImmutableList<String> SUPPORTED_VERSIONS =
ImmutableList.of("1.0", "1.1", "1.2", "1.3", "1.4", "1.5", "1.6");
/**
* Constructs a new formatter that delegates to <a
// ... rest of the code ...
|
06d271da251d3c85266629197d6b31b2ff617623
|
sympy/matrices/expressions/tests/test_hadamard.py
|
sympy/matrices/expressions/tests/test_hadamard.py
|
from sympy.matrices.expressions import MatrixSymbol, HadamardProduct
from sympy.matrices import ShapeError
from sympy import symbols
from sympy.utilities.pytest import raises
def test_HadamardProduct():
n, m, k = symbols('n,m,k')
Z = MatrixSymbol('Z', n, n)
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', n, m)
C = MatrixSymbol('C', m, k)
assert HadamardProduct(A, B, A).shape == A.shape
raises(ShapeError, lambda: HadamardProduct(A, B.T))
raises(TypeError, lambda: A + 1)
raises(TypeError, lambda: 5 + A)
raises(TypeError, lambda: 5 - A)
assert HadamardProduct(A, 2*B, -A)[1, 1] == -2 * A[1, 1]**2 * B[1, 1]
mix = HadamardProduct(Z*A, B)*C
assert mix.shape == (n, k)
|
from sympy.matrices.expressions import MatrixSymbol, HadamardProduct
from sympy.matrices import ShapeError
from sympy import symbols
from sympy.utilities.pytest import raises
def test_HadamardProduct():
n, m, k = symbols('n,m,k')
Z = MatrixSymbol('Z', n, n)
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', n, m)
C = MatrixSymbol('C', m, k)
assert HadamardProduct(A, B, A).shape == A.shape
raises(ShapeError, lambda: HadamardProduct(A, B.T))
raises(TypeError, lambda: A + 1)
raises(TypeError, lambda: 5 + A)
raises(TypeError, lambda: 5 - A)
assert HadamardProduct(A, 2*B, -A)[1, 1] == -2 * A[1, 1]**2 * B[1, 1]
mix = HadamardProduct(Z*A, B)*C
assert mix.shape == (n, k)
def test_mixed_indexing():
X = MatrixSymbol('X', 2, 2)
Y = MatrixSymbol('Y', 2, 2)
Z = MatrixSymbol('Z', 2, 2)
assert (X*HadamardProduct(Y, Z))[0, 0] == \
X[0, 0]*Y[0, 0]*Z[0, 0] + X[0, 1]*Y[1, 0]*Z[1, 0]
|
Add index test for Hadamard+MatMul mix
|
Add index test for Hadamard+MatMul mix
|
Python
|
bsd-3-clause
|
kaichogami/sympy,Sumith1896/sympy,sahmed95/sympy,MridulS/sympy,Gadal/sympy,yashsharan/sympy,Shaswat27/sympy,chaffra/sympy,beni55/sympy,drufat/sympy,MechCoder/sympy,souravsingh/sympy,kaushik94/sympy,abhiii5459/sympy,liangjiaxing/sympy,iamutkarshtiwari/sympy,Gadal/sympy,grevutiu-gabriel/sympy,vipulroxx/sympy,moble/sympy,kevalds51/sympy,atsao72/sympy,atreyv/sympy,lindsayad/sympy,beni55/sympy,asm666/sympy,jbbskinny/sympy,lindsayad/sympy,Designist/sympy,wanglongqi/sympy,lidavidm/sympy,madan96/sympy,meghana1995/sympy,wanglongqi/sympy,kumarkrishna/sympy,cswiercz/sympy,drufat/sympy,farhaanbukhsh/sympy,amitjamadagni/sympy,cccfran/sympy,hrashk/sympy,yashsharan/sympy,cswiercz/sympy,AkademieOlympia/sympy,kmacinnis/sympy,saurabhjn76/sympy,asm666/sympy,hargup/sympy,ahhda/sympy,mafiya69/sympy,liangjiaxing/sympy,VaibhavAgarwalVA/sympy,mafiya69/sympy,moble/sympy,madan96/sympy,emon10005/sympy,debugger22/sympy,Curious72/sympy,garvitr/sympy,ChristinaZografou/sympy,saurabhjn76/sympy,pandeyadarsh/sympy,sahilshekhawat/sympy,shipci/sympy,yukoba/sympy,jamesblunt/sympy,kaushik94/sympy,garvitr/sympy,MechCoder/sympy,mafiya69/sympy,abloomston/sympy,Vishluck/sympy,kmacinnis/sympy,emon10005/sympy,Shaswat27/sympy,madan96/sympy,aktech/sympy,maniteja123/sympy,cccfran/sympy,VaibhavAgarwalVA/sympy,meghana1995/sympy,souravsingh/sympy,cswiercz/sympy,emon10005/sympy,debugger22/sympy,Arafatk/sympy,hrashk/sympy,saurabhjn76/sympy,lindsayad/sympy,Arafatk/sympy,shikil/sympy,yukoba/sympy,farhaanbukhsh/sympy,skidzo/sympy,abloomston/sympy,postvakje/sympy,ahhda/sympy,skidzo/sympy,dqnykamp/sympy,sahmed95/sympy,jerli/sympy,ga7g08/sympy,oliverlee/sympy,sahilshekhawat/sympy,toolforger/sympy,kevalds51/sympy,mcdaniel67/sympy,wanglongqi/sympy,MridulS/sympy,souravsingh/sympy,rahuldan/sympy,Davidjohnwilson/sympy,skidzo/sympy,kaichogami/sympy,rahuldan/sympy,drufat/sympy,Vishluck/sympy,pandeyadarsh/sympy,moble/sympy,jamesblunt/sympy,AunShiLord/sympy,Davidjohnwilson/sympy,MechCoder/sympy,grevutiu-gabriel/sympy,postvakje/sympy,wyom/sympy,jamesblunt/sympy,vipulroxx/sympy,Davidjohnwilson/sympy,Shaswat27/sympy,atsao72/sympy,beni55/sympy,yashsharan/sympy,aktech/sympy,pbrady/sympy,Titan-C/sympy,maniteja123/sympy,chaffra/sympy,jaimahajan1997/sympy,garvitr/sympy,dqnykamp/sympy,amitjamadagni/sympy,lidavidm/sympy,diofant/diofant,Gadal/sympy,ga7g08/sympy,toolforger/sympy,yukoba/sympy,bukzor/sympy,kevalds51/sympy,vipulroxx/sympy,pbrady/sympy,sampadsaha5/sympy,hargup/sympy,bukzor/sympy,jbbskinny/sympy,oliverlee/sympy,abloomston/sympy,AunShiLord/sympy,AkademieOlympia/sympy,sahmed95/sympy,mcdaniel67/sympy,iamutkarshtiwari/sympy,sunny94/temp,hargup/sympy,grevutiu-gabriel/sympy,mcdaniel67/sympy,Sumith1896/sympy,chaffra/sympy,shikil/sympy,meghana1995/sympy,rahuldan/sympy,kumarkrishna/sympy,cccfran/sympy,Curious72/sympy,lidavidm/sympy,toolforger/sympy,kaushik94/sympy,atreyv/sympy,Sumith1896/sympy,atsao72/sympy,postvakje/sympy,dqnykamp/sympy,hrashk/sympy,farhaanbukhsh/sympy,AkademieOlympia/sympy,Mitchkoens/sympy,MridulS/sympy,skirpichev/omg,pandeyadarsh/sympy,Titan-C/sympy,atreyv/sympy,VaibhavAgarwalVA/sympy,Curious72/sympy,bukzor/sympy,sampadsaha5/sympy,Vishluck/sympy,shipci/sympy,kaichogami/sympy,abhiii5459/sympy,jbbskinny/sympy,debugger22/sympy,asm666/sympy,sahilshekhawat/sympy,jaimahajan1997/sympy,shipci/sympy,wyom/sympy,jerli/sympy,liangjiaxing/sympy,iamutkarshtiwari/sympy,abhiii5459/sympy,sunny94/temp,Mitchkoens/sympy,ChristinaZografou/sympy,Designist/sympy,sampadsaha5/sympy,shikil/sympy,sunny94/temp,kmacinnis/sympy,ChristinaZografou/sympy,jerli/sympy,wyom/sympy,ahhda/sympy,oliverlee/sympy,ga7g08/sympy,aktech/sympy,Mitchkoens/sympy,Titan-C/sympy,maniteja123/sympy,jaimahajan1997/sympy,pbrady/sympy,Arafatk/sympy,AunShiLord/sympy,Designist/sympy,kumarkrishna/sympy
|
python
|
## Code Before:
from sympy.matrices.expressions import MatrixSymbol, HadamardProduct
from sympy.matrices import ShapeError
from sympy import symbols
from sympy.utilities.pytest import raises
def test_HadamardProduct():
n, m, k = symbols('n,m,k')
Z = MatrixSymbol('Z', n, n)
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', n, m)
C = MatrixSymbol('C', m, k)
assert HadamardProduct(A, B, A).shape == A.shape
raises(ShapeError, lambda: HadamardProduct(A, B.T))
raises(TypeError, lambda: A + 1)
raises(TypeError, lambda: 5 + A)
raises(TypeError, lambda: 5 - A)
assert HadamardProduct(A, 2*B, -A)[1, 1] == -2 * A[1, 1]**2 * B[1, 1]
mix = HadamardProduct(Z*A, B)*C
assert mix.shape == (n, k)
## Instruction:
Add index test for Hadamard+MatMul mix
## Code After:
from sympy.matrices.expressions import MatrixSymbol, HadamardProduct
from sympy.matrices import ShapeError
from sympy import symbols
from sympy.utilities.pytest import raises
def test_HadamardProduct():
n, m, k = symbols('n,m,k')
Z = MatrixSymbol('Z', n, n)
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', n, m)
C = MatrixSymbol('C', m, k)
assert HadamardProduct(A, B, A).shape == A.shape
raises(ShapeError, lambda: HadamardProduct(A, B.T))
raises(TypeError, lambda: A + 1)
raises(TypeError, lambda: 5 + A)
raises(TypeError, lambda: 5 - A)
assert HadamardProduct(A, 2*B, -A)[1, 1] == -2 * A[1, 1]**2 * B[1, 1]
mix = HadamardProduct(Z*A, B)*C
assert mix.shape == (n, k)
def test_mixed_indexing():
X = MatrixSymbol('X', 2, 2)
Y = MatrixSymbol('Y', 2, 2)
Z = MatrixSymbol('Z', 2, 2)
assert (X*HadamardProduct(Y, Z))[0, 0] == \
X[0, 0]*Y[0, 0]*Z[0, 0] + X[0, 1]*Y[1, 0]*Z[1, 0]
|
...
mix = HadamardProduct(Z*A, B)*C
assert mix.shape == (n, k)
def test_mixed_indexing():
X = MatrixSymbol('X', 2, 2)
Y = MatrixSymbol('Y', 2, 2)
Z = MatrixSymbol('Z', 2, 2)
assert (X*HadamardProduct(Y, Z))[0, 0] == \
X[0, 0]*Y[0, 0]*Z[0, 0] + X[0, 1]*Y[1, 0]*Z[1, 0]
...
|
3735c090702cc8c290dbf8930223ff794c80775a
|
versionsapp.py
|
versionsapp.py
|
from webob import Response
from apiversion import APIVersion
from application import Application
from apiv1app import APIv1App
class VersionsApp(Application):
version_classes = [ APIv1App ]
def APIVersionList(self, args):
return Response(content_type = 'application/json', body = self._resultset_to_json([
{
"id": version._version_identifier(),
"links": [
{
"href": "/" + version._version_identifier(),
"rel": "self"
}
]
} for version in self.version_classes
]))
def APIVersion(self, args):
return Response(content_type = 'application/json', body = self._resultset_to_json({
'todo': 'Report detail'
}))
def factory(global_config, **settings):
return VersionsApp()
|
from webob import Response
import webob.exc
from apiversion import APIVersion
from application import Application
from apiv1app import APIv1App
class VersionsApp(Application):
version_classes = [ APIv1App ]
def _api_version_detail(self, version):
return {
"id": version._version_identifier(),
"links": [
{
"href": "/" + version._version_identifier(),
"rel": "self"
}
]
}
def APIVersionList(self, args):
return Response(status = 300, content_type = 'application/json', body = self._resultset_to_json([
self._api_version_detail(version) for version in self.version_classes
]))
def APIVersion(self, version_identifier):
versions = [ version for version in self.version_classes if version._version_identifier() == version_identifier ]
if not versions:
return webob.exc.HTTPNotFound()
if len(versions) > 1:
raise RuntimeError("Multiple API versions with identifier '%s'" % version_identifier)
return Response(content_type = 'application/json', body = self._resultset_to_json({
self._api_version_detail(versions[0])
}))
def factory(global_config, **settings):
return VersionsApp()
|
Correct the HTTP status from GET / - it should be 300 (Multiple Choices) not 200. Implement the details of a given version.
|
Correct the HTTP status from GET / - it should be 300 (Multiple Choices) not 200. Implement the details of a given version.
|
Python
|
apache-2.0
|
NeCTAR-RC/reporting-api,NCI-Cloud/reporting-api,NeCTAR-RC/reporting-api,NCI-Cloud/reporting-api
|
python
|
## Code Before:
from webob import Response
from apiversion import APIVersion
from application import Application
from apiv1app import APIv1App
class VersionsApp(Application):
version_classes = [ APIv1App ]
def APIVersionList(self, args):
return Response(content_type = 'application/json', body = self._resultset_to_json([
{
"id": version._version_identifier(),
"links": [
{
"href": "/" + version._version_identifier(),
"rel": "self"
}
]
} for version in self.version_classes
]))
def APIVersion(self, args):
return Response(content_type = 'application/json', body = self._resultset_to_json({
'todo': 'Report detail'
}))
def factory(global_config, **settings):
return VersionsApp()
## Instruction:
Correct the HTTP status from GET / - it should be 300 (Multiple Choices) not 200. Implement the details of a given version.
## Code After:
from webob import Response
import webob.exc
from apiversion import APIVersion
from application import Application
from apiv1app import APIv1App
class VersionsApp(Application):
version_classes = [ APIv1App ]
def _api_version_detail(self, version):
return {
"id": version._version_identifier(),
"links": [
{
"href": "/" + version._version_identifier(),
"rel": "self"
}
]
}
def APIVersionList(self, args):
return Response(status = 300, content_type = 'application/json', body = self._resultset_to_json([
self._api_version_detail(version) for version in self.version_classes
]))
def APIVersion(self, version_identifier):
versions = [ version for version in self.version_classes if version._version_identifier() == version_identifier ]
if not versions:
return webob.exc.HTTPNotFound()
if len(versions) > 1:
raise RuntimeError("Multiple API versions with identifier '%s'" % version_identifier)
return Response(content_type = 'application/json', body = self._resultset_to_json({
self._api_version_detail(versions[0])
}))
def factory(global_config, **settings):
return VersionsApp()
|
// ... existing code ...
from webob import Response
import webob.exc
from apiversion import APIVersion
from application import Application
from apiv1app import APIv1App
// ... modified code ...
version_classes = [ APIv1App ]
def _api_version_detail(self, version):
return {
"id": version._version_identifier(),
"links": [
{
"href": "/" + version._version_identifier(),
"rel": "self"
}
]
}
def APIVersionList(self, args):
return Response(status = 300, content_type = 'application/json', body = self._resultset_to_json([
self._api_version_detail(version) for version in self.version_classes
]))
def APIVersion(self, version_identifier):
versions = [ version for version in self.version_classes if version._version_identifier() == version_identifier ]
if not versions:
return webob.exc.HTTPNotFound()
if len(versions) > 1:
raise RuntimeError("Multiple API versions with identifier '%s'" % version_identifier)
return Response(content_type = 'application/json', body = self._resultset_to_json({
self._api_version_detail(versions[0])
}))
def factory(global_config, **settings):
// ... rest of the code ...
|
b24ae1320af5387e339a12dc00e214330525e549
|
src/BibleBot.Frontend/application.py
|
src/BibleBot.Frontend/application.py
|
import disnake
from disnake.ext import commands
from logger import VyLogger
import os
logger = VyLogger("default")
intents = disnake.Intents.default()
intents.message_content = True
bot = commands.AutoShardedBot(
command_prefix=commands.when_mentioned,
intents=intents,
test_guilds=[362503610006765568],
sync_commands_debug=True,
)
bot.load_extension("cogs")
bot.run(os.environ.get("DISCORD_TOKEN"))
|
import disnake
from disnake.ext import commands
from logger import VyLogger
import os
logger = VyLogger("default")
intents = disnake.Intents.default()
intents.message_content = True
bot = commands.AutoShardedBot(
command_prefix=commands.when_mentioned,
intents=intents,
)
bot.load_extension("cogs")
bot.run(os.environ.get("DISCORD_TOKEN"))
|
Move commands out of test.
|
Move commands out of test.
|
Python
|
mpl-2.0
|
BibleBot/BibleBot,BibleBot/BibleBot,BibleBot/BibleBot
|
python
|
## Code Before:
import disnake
from disnake.ext import commands
from logger import VyLogger
import os
logger = VyLogger("default")
intents = disnake.Intents.default()
intents.message_content = True
bot = commands.AutoShardedBot(
command_prefix=commands.when_mentioned,
intents=intents,
test_guilds=[362503610006765568],
sync_commands_debug=True,
)
bot.load_extension("cogs")
bot.run(os.environ.get("DISCORD_TOKEN"))
## Instruction:
Move commands out of test.
## Code After:
import disnake
from disnake.ext import commands
from logger import VyLogger
import os
logger = VyLogger("default")
intents = disnake.Intents.default()
intents.message_content = True
bot = commands.AutoShardedBot(
command_prefix=commands.when_mentioned,
intents=intents,
)
bot.load_extension("cogs")
bot.run(os.environ.get("DISCORD_TOKEN"))
|
...
bot = commands.AutoShardedBot(
command_prefix=commands.when_mentioned,
intents=intents,
)
bot.load_extension("cogs")
...
|
7ea829911d16e63c873330a15e5271fd7fa5da5b
|
lock-contention/LockContention.java
|
lock-contention/LockContention.java
|
import java.util.Random;
public class LockContention {
static Random randomGen = new Random();
static int NTHREAD = 100;
static public void main(String args[]) {
Runnable task = () -> {
for (int i = 0; i < 10000000; i++)
randomGen.nextInt(1000);
};
Thread threads[] = new Thread[NTHREAD];
for (int i = 0; i < NTHREAD; i++) {
threads[i] = new Thread(task);
threads[i].start();
}
try {
for (Thread t : threads)
t.join();
} catch (InterruptedException e) {
System.err.println("Interrupted: " + e);
}
}
}
|
import java.util.Random;
public class LockContention {
static Random randomGen = new Random();
static int NTHREAD = 7;
static Object lock = new Object();
static int counter = 0;
static public void main(String args[]) {
Runnable task = () -> {
for (int i = 0; i < 100000; i++)
synchronized (lock) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
System.err.println("Interrupted sleep: " + e);
}
counter++;
}
};
Thread threads[] = new Thread[NTHREAD];
for (int i = 0; i < NTHREAD; i++) {
threads[i] = new Thread(task);
threads[i].start();
}
try {
for (Thread t : threads)
t.join();
} catch (InterruptedException e) {
System.err.println("Interrupted join: " + e);
}
}
}
|
Use sleep rather than Random
|
Use sleep rather than Random
|
Java
|
apache-2.0
|
dspinellis/effective-debugging,dspinellis/effective-debugging,dspinellis/effective-debugging,dspinellis/effective-debugging,dspinellis/effective-debugging
|
java
|
## Code Before:
import java.util.Random;
public class LockContention {
static Random randomGen = new Random();
static int NTHREAD = 100;
static public void main(String args[]) {
Runnable task = () -> {
for (int i = 0; i < 10000000; i++)
randomGen.nextInt(1000);
};
Thread threads[] = new Thread[NTHREAD];
for (int i = 0; i < NTHREAD; i++) {
threads[i] = new Thread(task);
threads[i].start();
}
try {
for (Thread t : threads)
t.join();
} catch (InterruptedException e) {
System.err.println("Interrupted: " + e);
}
}
}
## Instruction:
Use sleep rather than Random
## Code After:
import java.util.Random;
public class LockContention {
static Random randomGen = new Random();
static int NTHREAD = 7;
static Object lock = new Object();
static int counter = 0;
static public void main(String args[]) {
Runnable task = () -> {
for (int i = 0; i < 100000; i++)
synchronized (lock) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
System.err.println("Interrupted sleep: " + e);
}
counter++;
}
};
Thread threads[] = new Thread[NTHREAD];
for (int i = 0; i < NTHREAD; i++) {
threads[i] = new Thread(task);
threads[i].start();
}
try {
for (Thread t : threads)
t.join();
} catch (InterruptedException e) {
System.err.println("Interrupted join: " + e);
}
}
}
|
# ... existing code ...
public class LockContention {
static Random randomGen = new Random();
static int NTHREAD = 7;
static Object lock = new Object();
static int counter = 0;
static public void main(String args[]) {
Runnable task = () -> {
for (int i = 0; i < 100000; i++)
synchronized (lock) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
System.err.println("Interrupted sleep: " + e);
}
counter++;
}
};
Thread threads[] = new Thread[NTHREAD];
# ... modified code ...
for (Thread t : threads)
t.join();
} catch (InterruptedException e) {
System.err.println("Interrupted join: " + e);
}
}
}
# ... rest of the code ...
|
27f5676656e7507883ba365d2639e5f3cb5b0b58
|
snippets/keras_testing.py
|
snippets/keras_testing.py
|
from keras.models import Sequential
from keras.layers import Dense, Dropout
import sys
import numpy as np
def main():
input_filename = sys.argv[1]
training = np.loadtxt('data/%s.csv' % input_filename, delimiter=',')
test = np.loadtxt('data/%s_test.csv' % input_filename, delimiter=',')
y_train = training[:,3:4]
x_train = training[:,0:3]
y_test = test[:,3:4]
x_test = test[:,0:3]
model = Sequential()
model.add(Dense(10, activation='tanh', input_dim=3))
model.add(Dense(10, activation='tanh'))
model.add(Dense(1, activation='linear'))
model.compile(optimizer='sgd', loss='mean_squared_error')
model.fit(x_train, y_train, epochs=100)
print('Test score: ', model.evaluate(x_test, y_test))
y_network = model.predict(x_test)
out = np.concatenate((x_test, y_test, y_network), axis=1)
np.savetxt('results/%s_kera.csv' % input_filename, out, delimiter=',')
if __name__ == "__main__":
main()
|
from keras.models import Sequential
from keras.layers import Dense, Dropout
import sys
import numpy as np
def main():
input_filename = sys.argv[1]
num_networks = int(sys.argv[2])
training = np.loadtxt('data/%s.csv' % input_filename, delimiter=',')
test = np.loadtxt('data/%s_test.csv' % input_filename, delimiter=',')
y_train = training[:, 3:4]
x_train = training[:, 0:3]
y_test = test[:, 3:4]
x_test = test[:, 0:3]
test_score = 0
result = np.zeros((1,5))
for _ in range(num_networks):
model = Sequential()
model.add(Dense(10, activation='tanh', input_dim=3))
model.add(Dense(10, activation='tanh'))
model.add(Dense(1, activation='linear'))
model.compile(optimizer='sgd', loss='mean_squared_error')
model.fit(x_train, y_train, epochs=20, shuffle=True)
y_network = model.predict_on_batch(x_test)
result = np.concatenate((result, np.concatenate((x_test, y_test, y_network), axis=1)), axis=0)
test_score += model.evaluate(x_test, y_test)
print()
print('Test score: ', test_score / num_networks)
result = np.delete(result, 0, 0)
np.savetxt('results/%s_kera.csv' % input_filename, result, delimiter=',')
if __name__ == "__main__":
main()
|
Tweak parameters and allow runs over multiple networks
|
Tweak parameters and allow runs over multiple networks
|
Python
|
mit
|
farthir/msc-project
|
python
|
## Code Before:
from keras.models import Sequential
from keras.layers import Dense, Dropout
import sys
import numpy as np
def main():
input_filename = sys.argv[1]
training = np.loadtxt('data/%s.csv' % input_filename, delimiter=',')
test = np.loadtxt('data/%s_test.csv' % input_filename, delimiter=',')
y_train = training[:,3:4]
x_train = training[:,0:3]
y_test = test[:,3:4]
x_test = test[:,0:3]
model = Sequential()
model.add(Dense(10, activation='tanh', input_dim=3))
model.add(Dense(10, activation='tanh'))
model.add(Dense(1, activation='linear'))
model.compile(optimizer='sgd', loss='mean_squared_error')
model.fit(x_train, y_train, epochs=100)
print('Test score: ', model.evaluate(x_test, y_test))
y_network = model.predict(x_test)
out = np.concatenate((x_test, y_test, y_network), axis=1)
np.savetxt('results/%s_kera.csv' % input_filename, out, delimiter=',')
if __name__ == "__main__":
main()
## Instruction:
Tweak parameters and allow runs over multiple networks
## Code After:
from keras.models import Sequential
from keras.layers import Dense, Dropout
import sys
import numpy as np
def main():
input_filename = sys.argv[1]
num_networks = int(sys.argv[2])
training = np.loadtxt('data/%s.csv' % input_filename, delimiter=',')
test = np.loadtxt('data/%s_test.csv' % input_filename, delimiter=',')
y_train = training[:, 3:4]
x_train = training[:, 0:3]
y_test = test[:, 3:4]
x_test = test[:, 0:3]
test_score = 0
result = np.zeros((1,5))
for _ in range(num_networks):
model = Sequential()
model.add(Dense(10, activation='tanh', input_dim=3))
model.add(Dense(10, activation='tanh'))
model.add(Dense(1, activation='linear'))
model.compile(optimizer='sgd', loss='mean_squared_error')
model.fit(x_train, y_train, epochs=20, shuffle=True)
y_network = model.predict_on_batch(x_test)
result = np.concatenate((result, np.concatenate((x_test, y_test, y_network), axis=1)), axis=0)
test_score += model.evaluate(x_test, y_test)
print()
print('Test score: ', test_score / num_networks)
result = np.delete(result, 0, 0)
np.savetxt('results/%s_kera.csv' % input_filename, result, delimiter=',')
if __name__ == "__main__":
main()
|
// ... existing code ...
def main():
input_filename = sys.argv[1]
num_networks = int(sys.argv[2])
training = np.loadtxt('data/%s.csv' % input_filename, delimiter=',')
test = np.loadtxt('data/%s_test.csv' % input_filename, delimiter=',')
y_train = training[:, 3:4]
x_train = training[:, 0:3]
y_test = test[:, 3:4]
x_test = test[:, 0:3]
test_score = 0
result = np.zeros((1,5))
for _ in range(num_networks):
model = Sequential()
model.add(Dense(10, activation='tanh', input_dim=3))
model.add(Dense(10, activation='tanh'))
model.add(Dense(1, activation='linear'))
model.compile(optimizer='sgd', loss='mean_squared_error')
model.fit(x_train, y_train, epochs=20, shuffle=True)
y_network = model.predict_on_batch(x_test)
result = np.concatenate((result, np.concatenate((x_test, y_test, y_network), axis=1)), axis=0)
test_score += model.evaluate(x_test, y_test)
print()
print('Test score: ', test_score / num_networks)
result = np.delete(result, 0, 0)
np.savetxt('results/%s_kera.csv' % input_filename, result, delimiter=',')
if __name__ == "__main__":
main()
// ... rest of the code ...
|
0e2e9805547af34eb42392d027e1abcb5ba88241
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
setup(
name='OpenFisca-Country-Template',
version='0.1.0',
author='OpenFisca Team',
author_email='[email protected]',
description=u'Template of a tax and benefit system for OpenFisca',
keywords='benefit microsimulation social tax',
license='http://www.fsf.org/licensing/licenses/agpl-3.0.html',
include_package_data = True, # Will read MANIFEST.in
install_requires=[
'OpenFisca-Core >= 6.1.0, < 11.0',
],
extras_require = {
'api': [
'OpenFisca-Web-API >= 4.0.0, < 6.0',
],
'test': [
'flake8',
'flake8-print',
]
},
packages=find_packages(),
test_suite='nose.collector',
)
|
from setuptools import setup, find_packages
setup(
name='OpenFisca-Country-Template',
version='0.1.0',
author='OpenFisca Team',
author_email='[email protected]',
description=u'Template of a tax and benefit system for OpenFisca',
keywords='benefit microsimulation social tax',
license='http://www.fsf.org/licensing/licenses/agpl-3.0.html',
include_package_data = True, # Will read MANIFEST.in
install_requires=[
'OpenFisca-Core >= 6.1.0, < 11.0',
],
extras_require = {
'api': [
'OpenFisca-Web-API >= 4.0.0, < 6.0',
],
'test': [
'flake8',
'flake8-print',
'nose',
]
},
packages=find_packages(),
test_suite='nose.collector',
)
|
Add nose to tests dependencies
|
Add nose to tests dependencies
|
Python
|
agpl-3.0
|
openfisca/country-template,openfisca/country-template
|
python
|
## Code Before:
from setuptools import setup, find_packages
setup(
name='OpenFisca-Country-Template',
version='0.1.0',
author='OpenFisca Team',
author_email='[email protected]',
description=u'Template of a tax and benefit system for OpenFisca',
keywords='benefit microsimulation social tax',
license='http://www.fsf.org/licensing/licenses/agpl-3.0.html',
include_package_data = True, # Will read MANIFEST.in
install_requires=[
'OpenFisca-Core >= 6.1.0, < 11.0',
],
extras_require = {
'api': [
'OpenFisca-Web-API >= 4.0.0, < 6.0',
],
'test': [
'flake8',
'flake8-print',
]
},
packages=find_packages(),
test_suite='nose.collector',
)
## Instruction:
Add nose to tests dependencies
## Code After:
from setuptools import setup, find_packages
setup(
name='OpenFisca-Country-Template',
version='0.1.0',
author='OpenFisca Team',
author_email='[email protected]',
description=u'Template of a tax and benefit system for OpenFisca',
keywords='benefit microsimulation social tax',
license='http://www.fsf.org/licensing/licenses/agpl-3.0.html',
include_package_data = True, # Will read MANIFEST.in
install_requires=[
'OpenFisca-Core >= 6.1.0, < 11.0',
],
extras_require = {
'api': [
'OpenFisca-Web-API >= 4.0.0, < 6.0',
],
'test': [
'flake8',
'flake8-print',
'nose',
]
},
packages=find_packages(),
test_suite='nose.collector',
)
|
# ... existing code ...
'test': [
'flake8',
'flake8-print',
'nose',
]
},
packages=find_packages(),
# ... rest of the code ...
|
9fd15678a5f149c5ddc5793541c4f3262802e2dd
|
chapter3/Player.h
|
chapter3/Player.h
|
class PLayer: public GameObject
{
public:
void update();
void clean()
{
GameObject::clean();
std::cout << "clean PLayer";
}
};
#endif
|
class Player: public GameObject
{
public:
void update();
void clean()
{
std::cout << "clean PLayer";
}
};
#endif
|
Fix class name and remove GameObject::clean call.
|
Fix class name and remove GameObject::clean call.
|
C
|
bsd-2-clause
|
caiotava/SDLBook
|
c
|
## Code Before:
class PLayer: public GameObject
{
public:
void update();
void clean()
{
GameObject::clean();
std::cout << "clean PLayer";
}
};
#endif
## Instruction:
Fix class name and remove GameObject::clean call.
## Code After:
class Player: public GameObject
{
public:
void update();
void clean()
{
std::cout << "clean PLayer";
}
};
#endif
|
// ... existing code ...
class Player: public GameObject
{
public:
void update();
void clean()
{
std::cout << "clean PLayer";
}
};
// ... rest of the code ...
|
e3bbaf9421bdc5e0ac538c57a9821b5dba0382ef
|
dataviva/apps/title/models.py
|
dataviva/apps/title/models.py
|
from dataviva import db
class GraphTitle(db.Model):
__tablename__ = 'graph_title'
id = db.Column(db.Integer, primary_key=True)
title_en = db.Column(db.String(255))
subtitle_en = db.Column(db.String(255))
title_pt = db.Column(db.String(255))
subtitle_pt = db.Column(db.String(255))
dataset = db.Column(db.String(45))
graph = db.Column(db.String(45))
shapes = db.Column(db.String(45))
type = db.Column(db.String(45))
product = db.Column(db.Boolean)
partner = db.Column(db.Boolean)
location = db.Column(db.Boolean)
industry = db.Column(db.Boolean)
occupation = db.Column(db.Boolean)
establishment = db.Column(db.Boolean)
hedu_course = db.Column(db.Boolean)
university = db.Column(db.Boolean)
sc_course = db.Column(db.Boolean)
|
from dataviva import db
class GraphTitle(db.Model):
__tablename__ = 'graph_title'
id = db.Column(db.Integer, primary_key=True)
title_en = db.Column(db.String(255))
subtitle_en = db.Column(db.String(255))
title_pt = db.Column(db.String(255))
subtitle_pt = db.Column(db.String(255))
dataset = db.Column(db.String(45))
graph = db.Column(db.String(45))
shapes = db.Column(db.String(45))
type = db.Column(db.String(45))
product = db.Column(db.Boolean)
partner = db.Column(db.Boolean)
location = db.Column(db.Boolean)
industry = db.Column(db.Boolean)
occupation = db.Column(db.Boolean)
establishment = db.Column(db.Boolean)
hedu_course = db.Column(db.Boolean)
university = db.Column(db.Boolean)
sc_course = db.Column(db.Boolean)
sc_course_field = db.Column(db.Boolean)
|
Add column to title model
|
Add column to title model
|
Python
|
mit
|
DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site
|
python
|
## Code Before:
from dataviva import db
class GraphTitle(db.Model):
__tablename__ = 'graph_title'
id = db.Column(db.Integer, primary_key=True)
title_en = db.Column(db.String(255))
subtitle_en = db.Column(db.String(255))
title_pt = db.Column(db.String(255))
subtitle_pt = db.Column(db.String(255))
dataset = db.Column(db.String(45))
graph = db.Column(db.String(45))
shapes = db.Column(db.String(45))
type = db.Column(db.String(45))
product = db.Column(db.Boolean)
partner = db.Column(db.Boolean)
location = db.Column(db.Boolean)
industry = db.Column(db.Boolean)
occupation = db.Column(db.Boolean)
establishment = db.Column(db.Boolean)
hedu_course = db.Column(db.Boolean)
university = db.Column(db.Boolean)
sc_course = db.Column(db.Boolean)
## Instruction:
Add column to title model
## Code After:
from dataviva import db
class GraphTitle(db.Model):
__tablename__ = 'graph_title'
id = db.Column(db.Integer, primary_key=True)
title_en = db.Column(db.String(255))
subtitle_en = db.Column(db.String(255))
title_pt = db.Column(db.String(255))
subtitle_pt = db.Column(db.String(255))
dataset = db.Column(db.String(45))
graph = db.Column(db.String(45))
shapes = db.Column(db.String(45))
type = db.Column(db.String(45))
product = db.Column(db.Boolean)
partner = db.Column(db.Boolean)
location = db.Column(db.Boolean)
industry = db.Column(db.Boolean)
occupation = db.Column(db.Boolean)
establishment = db.Column(db.Boolean)
hedu_course = db.Column(db.Boolean)
university = db.Column(db.Boolean)
sc_course = db.Column(db.Boolean)
sc_course_field = db.Column(db.Boolean)
|
...
hedu_course = db.Column(db.Boolean)
university = db.Column(db.Boolean)
sc_course = db.Column(db.Boolean)
sc_course_field = db.Column(db.Boolean)
...
|
76dbe0b44d22d5a179e61ee215ab96db420529b5
|
Common/src/main/java/net/darkhax/bookshelf/api/registry/IRegistryReader.java
|
Common/src/main/java/net/darkhax/bookshelf/api/registry/IRegistryReader.java
|
package net.darkhax.bookshelf.api.registry;
import net.minecraft.resources.ResourceLocation;
import javax.annotation.Nullable;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public interface IRegistryReader<T> extends Iterable<T> {
@Nullable
T get(ResourceLocation id);
@Nullable
ResourceLocation getId(T value);
default Stream<T> streamValues() {
return StreamSupport.stream(spliterator(), false);
}
default Stream<T> parallelStreamValues() {
return StreamSupport.stream(spliterator(), true);
}
}
|
package net.darkhax.bookshelf.api.registry;
import net.minecraft.resources.ResourceLocation;
import javax.annotation.Nullable;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public interface IRegistryReader<T> extends Iterable<T> {
@Nullable
T get(ResourceLocation id);
@Nullable
ResourceLocation getId(T value);
default ResourceLocation getId(T value, ResourceLocation fallback) {
final ResourceLocation id = this.getId(value);
return id != null ? id : fallback;
}
default Stream<T> streamValues() {
return StreamSupport.stream(spliterator(), false);
}
default Stream<T> parallelStreamValues() {
return StreamSupport.stream(spliterator(), true);
}
}
|
Add a registry reader method that gets an ID with an optional fallback.
|
Add a registry reader method that gets an ID with an optional fallback.
|
Java
|
lgpl-2.1
|
Darkhax-Minecraft/Bookshelf
|
java
|
## Code Before:
package net.darkhax.bookshelf.api.registry;
import net.minecraft.resources.ResourceLocation;
import javax.annotation.Nullable;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public interface IRegistryReader<T> extends Iterable<T> {
@Nullable
T get(ResourceLocation id);
@Nullable
ResourceLocation getId(T value);
default Stream<T> streamValues() {
return StreamSupport.stream(spliterator(), false);
}
default Stream<T> parallelStreamValues() {
return StreamSupport.stream(spliterator(), true);
}
}
## Instruction:
Add a registry reader method that gets an ID with an optional fallback.
## Code After:
package net.darkhax.bookshelf.api.registry;
import net.minecraft.resources.ResourceLocation;
import javax.annotation.Nullable;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public interface IRegistryReader<T> extends Iterable<T> {
@Nullable
T get(ResourceLocation id);
@Nullable
ResourceLocation getId(T value);
default ResourceLocation getId(T value, ResourceLocation fallback) {
final ResourceLocation id = this.getId(value);
return id != null ? id : fallback;
}
default Stream<T> streamValues() {
return StreamSupport.stream(spliterator(), false);
}
default Stream<T> parallelStreamValues() {
return StreamSupport.stream(spliterator(), true);
}
}
|
// ... existing code ...
@Nullable
ResourceLocation getId(T value);
default ResourceLocation getId(T value, ResourceLocation fallback) {
final ResourceLocation id = this.getId(value);
return id != null ? id : fallback;
}
default Stream<T> streamValues() {
return StreamSupport.stream(spliterator(), false);
// ... rest of the code ...
|
ad11589eed6c299b36bd335a5e72e029897b05e5
|
test/Driver/integrated-as.c
|
test/Driver/integrated-as.c
|
// RUN: %clang -### -c -save-temps -integrated-as %s 2>&1 | FileCheck %s
// CHECK: cc1as
// CHECK: -mrelax-all
// RUN: %clang -### -fintegrated-as -c -save-temps %s 2>&1 | FileCheck %s -check-prefix FIAS
// FIAS: cc1as
// RUN: %clang -### -fno-integrated-as -S %s 2>&1 \
// RUN: | FileCheck %s -check-prefix NOFIAS
// NOFIAS-NOT: cc1as
// NOFIAS: -cc1
// NOFIAS: -no-integrated-as
|
// RUN: %clang -### -c -save-temps -integrated-as %s 2>&1 | FileCheck %s
// CHECK: cc1as
// CHECK: -mrelax-all
// RUN: %clang -### -fintegrated-as -c -save-temps %s 2>&1 | FileCheck %s -check-prefix FIAS
// FIAS: cc1as
// RUN: %clang -target none -### -fno-integrated-as -S %s 2>&1 \
// RUN: | FileCheck %s -check-prefix NOFIAS
// NOFIAS-NOT: cc1as
// NOFIAS: -cc1
// NOFIAS: -no-integrated-as
|
Use a dummy target so the test passes when default target is for a toolchain implements useIntegratedAs() -> true
|
Use a dummy target so the test passes when default target is for a toolchain implements useIntegratedAs() -> true
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@338553 91177308-0d34-0410-b5e6-96231b3b80d8
|
C
|
apache-2.0
|
apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang
|
c
|
## Code Before:
// RUN: %clang -### -c -save-temps -integrated-as %s 2>&1 | FileCheck %s
// CHECK: cc1as
// CHECK: -mrelax-all
// RUN: %clang -### -fintegrated-as -c -save-temps %s 2>&1 | FileCheck %s -check-prefix FIAS
// FIAS: cc1as
// RUN: %clang -### -fno-integrated-as -S %s 2>&1 \
// RUN: | FileCheck %s -check-prefix NOFIAS
// NOFIAS-NOT: cc1as
// NOFIAS: -cc1
// NOFIAS: -no-integrated-as
## Instruction:
Use a dummy target so the test passes when default target is for a toolchain implements useIntegratedAs() -> true
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@338553 91177308-0d34-0410-b5e6-96231b3b80d8
## Code After:
// RUN: %clang -### -c -save-temps -integrated-as %s 2>&1 | FileCheck %s
// CHECK: cc1as
// CHECK: -mrelax-all
// RUN: %clang -### -fintegrated-as -c -save-temps %s 2>&1 | FileCheck %s -check-prefix FIAS
// FIAS: cc1as
// RUN: %clang -target none -### -fno-integrated-as -S %s 2>&1 \
// RUN: | FileCheck %s -check-prefix NOFIAS
// NOFIAS-NOT: cc1as
// NOFIAS: -cc1
// NOFIAS: -no-integrated-as
|
// ... existing code ...
// FIAS: cc1as
// RUN: %clang -target none -### -fno-integrated-as -S %s 2>&1 \
// RUN: | FileCheck %s -check-prefix NOFIAS
// NOFIAS-NOT: cc1as
// ... rest of the code ...
|
062bb9f847e2fe479a29fa70cce9e3e49bc13111
|
src/main/java/seedu/tache/logic/parser/FindCommandParser.java
|
src/main/java/seedu/tache/logic/parser/FindCommandParser.java
|
package seedu.tache.logic.parser;
import static seedu.tache.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.tache.logic.parser.CliSyntax.KEYWORDS_ARGS_FORMAT;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import seedu.tache.logic.commands.Command;
import seedu.tache.logic.commands.FindCommand;
import seedu.tache.logic.commands.IncorrectCommand;
/**
* Parses input arguments and creates a new FindCommand object
*/
public class FindCommandParser {
/**
* Parses the given {@code String} of arguments in the context of the FindCommand
* and returns an FindCommand object for execution.
*/
public Command parse(String args) {
final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE));
}
//@@author A0139925U
// keywords delimited by whitespace
final String[] keywords = matcher.group("keywords").split("\\s+");
final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords));
return new FindCommand(keywordSet);
}
}
|
package seedu.tache.logic.parser;
import static seedu.tache.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.tache.logic.parser.CliSyntax.KEYWORDS_ARGS_FORMAT;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Matcher;
import seedu.tache.logic.commands.Command;
import seedu.tache.logic.commands.FindCommand;
import seedu.tache.logic.commands.IncorrectCommand;
/**
* Parses input arguments and creates a new FindCommand object
*/
public class FindCommandParser {
/**
* Parses the given {@code String} of arguments in the context of the FindCommand
* and returns an FindCommand object for execution.
*/
public Command parse(String args) {
final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE));
}
//@@author A0139925U
// keywords delimited by whitespace
final String[] keywords = matcher.group("keywords").split("\\s+");
final Set<String> keywordSet = new LinkedHashSet<>(Arrays.asList(keywords));
return new FindCommand(keywordSet);
}
}
|
Convert HashSet to LinkedHashSet to maintain FindCommand keyword sequence
|
Convert HashSet to LinkedHashSet to maintain FindCommand keyword sequence
|
Java
|
mit
|
CS2103JAN2017-T09-B4/main,CS2103JAN2017-T09-B4/main,CS2103JAN2017-T09-B4/main
|
java
|
## Code Before:
package seedu.tache.logic.parser;
import static seedu.tache.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.tache.logic.parser.CliSyntax.KEYWORDS_ARGS_FORMAT;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import seedu.tache.logic.commands.Command;
import seedu.tache.logic.commands.FindCommand;
import seedu.tache.logic.commands.IncorrectCommand;
/**
* Parses input arguments and creates a new FindCommand object
*/
public class FindCommandParser {
/**
* Parses the given {@code String} of arguments in the context of the FindCommand
* and returns an FindCommand object for execution.
*/
public Command parse(String args) {
final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE));
}
//@@author A0139925U
// keywords delimited by whitespace
final String[] keywords = matcher.group("keywords").split("\\s+");
final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords));
return new FindCommand(keywordSet);
}
}
## Instruction:
Convert HashSet to LinkedHashSet to maintain FindCommand keyword sequence
## Code After:
package seedu.tache.logic.parser;
import static seedu.tache.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.tache.logic.parser.CliSyntax.KEYWORDS_ARGS_FORMAT;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Matcher;
import seedu.tache.logic.commands.Command;
import seedu.tache.logic.commands.FindCommand;
import seedu.tache.logic.commands.IncorrectCommand;
/**
* Parses input arguments and creates a new FindCommand object
*/
public class FindCommandParser {
/**
* Parses the given {@code String} of arguments in the context of the FindCommand
* and returns an FindCommand object for execution.
*/
public Command parse(String args) {
final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE));
}
//@@author A0139925U
// keywords delimited by whitespace
final String[] keywords = matcher.group("keywords").split("\\s+");
final Set<String> keywordSet = new LinkedHashSet<>(Arrays.asList(keywords));
return new FindCommand(keywordSet);
}
}
|
# ... existing code ...
import static seedu.tache.logic.parser.CliSyntax.KEYWORDS_ARGS_FORMAT;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Matcher;
# ... modified code ...
//@@author A0139925U
// keywords delimited by whitespace
final String[] keywords = matcher.group("keywords").split("\\s+");
final Set<String> keywordSet = new LinkedHashSet<>(Arrays.asList(keywords));
return new FindCommand(keywordSet);
}
# ... rest of the code ...
|
c14b5190e65a6c506437a6aef00aa72eea9c66e9
|
org.spoofax.jsglr2.integrationtest/src/test/java/org/spoofax/jsglr2/integrationtest/grammars/RejectTest.java
|
org.spoofax.jsglr2.integrationtest/src/test/java/org/spoofax/jsglr2/integrationtest/grammars/RejectTest.java
|
package org.spoofax.jsglr2.integrationtest.grammars;
import java.io.IOException;
import org.junit.Test;
import org.spoofax.jsglr2.integrationtest.BaseTestWithSdf3ParseTables;
import org.spoofax.jsglr2.parsetable.ParseTableReadException;
import org.spoofax.terms.ParseError;
public class RejectTest extends BaseTestWithSdf3ParseTables {
public RejectTest() {
super("reject.sdf3");
}
@Test
public void testReject() throws ParseError, ParseTableReadException, IOException {
testParseFailure("foo");
}
@Test
public void testNestedReject() throws ParseError, ParseTableReadException, IOException {
testParseFailure("bar");
}
@Test
public void testNonReject() throws ParseError, ParseTableReadException, IOException {
testSuccessByAstString("baz", "Id(\"baz\")");
}
}
|
package org.spoofax.jsglr2.integrationtest.grammars;
import java.io.IOException;
import org.junit.Test;
import org.spoofax.jsglr2.integrationtest.BaseTestWithSdf3ParseTables;
import org.spoofax.jsglr2.parsetable.ParseTableReadException;
import org.spoofax.terms.ParseError;
public class RejectTest extends BaseTestWithSdf3ParseTables {
public RejectTest() {
super("reject.sdf3");
}
/*
@Test
public void testReject() throws ParseError, ParseTableReadException, IOException {
testParseFailure("foo");
}
@Test
public void testNestedReject() throws ParseError, ParseTableReadException, IOException {
testParseFailure("bar");
}
@Test
public void testNonReject() throws ParseError, ParseTableReadException, IOException {
testSuccessByAstString("baz", "Id(\"baz\")");
}
*/
}
|
Comment out non-deterministically failing test
|
Comment out non-deterministically failing test
|
Java
|
apache-2.0
|
metaborg/jsglr,metaborg/jsglr,metaborg/jsglr,metaborg/jsglr
|
java
|
## Code Before:
package org.spoofax.jsglr2.integrationtest.grammars;
import java.io.IOException;
import org.junit.Test;
import org.spoofax.jsglr2.integrationtest.BaseTestWithSdf3ParseTables;
import org.spoofax.jsglr2.parsetable.ParseTableReadException;
import org.spoofax.terms.ParseError;
public class RejectTest extends BaseTestWithSdf3ParseTables {
public RejectTest() {
super("reject.sdf3");
}
@Test
public void testReject() throws ParseError, ParseTableReadException, IOException {
testParseFailure("foo");
}
@Test
public void testNestedReject() throws ParseError, ParseTableReadException, IOException {
testParseFailure("bar");
}
@Test
public void testNonReject() throws ParseError, ParseTableReadException, IOException {
testSuccessByAstString("baz", "Id(\"baz\")");
}
}
## Instruction:
Comment out non-deterministically failing test
## Code After:
package org.spoofax.jsglr2.integrationtest.grammars;
import java.io.IOException;
import org.junit.Test;
import org.spoofax.jsglr2.integrationtest.BaseTestWithSdf3ParseTables;
import org.spoofax.jsglr2.parsetable.ParseTableReadException;
import org.spoofax.terms.ParseError;
public class RejectTest extends BaseTestWithSdf3ParseTables {
public RejectTest() {
super("reject.sdf3");
}
/*
@Test
public void testReject() throws ParseError, ParseTableReadException, IOException {
testParseFailure("foo");
}
@Test
public void testNestedReject() throws ParseError, ParseTableReadException, IOException {
testParseFailure("bar");
}
@Test
public void testNonReject() throws ParseError, ParseTableReadException, IOException {
testSuccessByAstString("baz", "Id(\"baz\")");
}
*/
}
|
// ... existing code ...
super("reject.sdf3");
}
/*
@Test
public void testReject() throws ParseError, ParseTableReadException, IOException {
testParseFailure("foo");
// ... modified code ...
public void testNonReject() throws ParseError, ParseTableReadException, IOException {
testSuccessByAstString("baz", "Id(\"baz\")");
}
*/
}
// ... rest of the code ...
|
33106b55d6503c26b56a1a3da7e568762eb4a390
|
src/main/java/com/github/macrodata/skyprint/section/RootSection.java
|
src/main/java/com/github/macrodata/skyprint/section/RootSection.java
|
package com.github.macrodata.skyprint.section;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
import static com.github.macrodata.skyprint.section.SectionHelper.*;
@ToString
public class RootSection extends Section {
@Setter
private MetadataSection metadata;
@Setter
private String name;
@Setter
private List<ResourceSection> resources;
@Setter
private List<GroupSection> groups;
public MetadataSection getMetadata() {
if (metadata == null)
lazy(this::setMetadata, get(this, MetadataSection.class));
return metadata;
}
public String getName() {
if (name == null)
lazy(this::setName, get(this, OverviewSection.class).getName());
return name;
}
@Override
public String getDescription() {
if (super.getDescription() == null)
lazy(this::setDescription, get(this, OverviewSection.class).getDescription());
return super.getDescription();
}
public List<ResourceSection> getResources() {
if (resources == null)
lazy(this::setResources, list(this, ResourceSection.class));
return resources;
}
public List<GroupSection> getGroups() {
if (groups == null)
lazy(this::setGroups, list(this, GroupSection.class));
return groups;
}
}
|
package com.github.macrodata.skyprint.section;
import lombok.Setter;
import lombok.ToString;
import javax.xml.transform.stream.StreamSource;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static com.github.macrodata.skyprint.section.SectionHelper.*;
@ToString
public class RootSection extends Section {
@Setter
private Map<String, String> metadata;
@Setter
private String name;
@Setter
private List<ResourceSection> resources;
@Setter
private List<GroupSection> groups;
public Map<String, String> getMetadata() {
if (metadata == null)
lazy(this::setMetadata, get(this, MetadataSection.class));
return metadata;
}
public String getName() {
if (name == null)
lazy(this::setName, get(this, OverviewSection.class).getName());
return name;
}
@Override
public String getDescription() {
if (super.getDescription() == null)
lazy(this::setDescription, get(this, OverviewSection.class).getDescription());
return super.getDescription();
}
public List<ResourceSection> getResources() {
if (resources == null)
lazy(this::setResources, list(this, ResourceSection.class));
return resources;
}
public List<GroupSection> getGroups() {
if (groups == null)
lazy(this::setGroups, list(this, GroupSection.class));
return groups;
}
}
|
Change metadata type to map
|
Change metadata type to map
|
Java
|
apache-2.0
|
MacroData/skyprint
|
java
|
## Code Before:
package com.github.macrodata.skyprint.section;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
import static com.github.macrodata.skyprint.section.SectionHelper.*;
@ToString
public class RootSection extends Section {
@Setter
private MetadataSection metadata;
@Setter
private String name;
@Setter
private List<ResourceSection> resources;
@Setter
private List<GroupSection> groups;
public MetadataSection getMetadata() {
if (metadata == null)
lazy(this::setMetadata, get(this, MetadataSection.class));
return metadata;
}
public String getName() {
if (name == null)
lazy(this::setName, get(this, OverviewSection.class).getName());
return name;
}
@Override
public String getDescription() {
if (super.getDescription() == null)
lazy(this::setDescription, get(this, OverviewSection.class).getDescription());
return super.getDescription();
}
public List<ResourceSection> getResources() {
if (resources == null)
lazy(this::setResources, list(this, ResourceSection.class));
return resources;
}
public List<GroupSection> getGroups() {
if (groups == null)
lazy(this::setGroups, list(this, GroupSection.class));
return groups;
}
}
## Instruction:
Change metadata type to map
## Code After:
package com.github.macrodata.skyprint.section;
import lombok.Setter;
import lombok.ToString;
import javax.xml.transform.stream.StreamSource;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static com.github.macrodata.skyprint.section.SectionHelper.*;
@ToString
public class RootSection extends Section {
@Setter
private Map<String, String> metadata;
@Setter
private String name;
@Setter
private List<ResourceSection> resources;
@Setter
private List<GroupSection> groups;
public Map<String, String> getMetadata() {
if (metadata == null)
lazy(this::setMetadata, get(this, MetadataSection.class));
return metadata;
}
public String getName() {
if (name == null)
lazy(this::setName, get(this, OverviewSection.class).getName());
return name;
}
@Override
public String getDescription() {
if (super.getDescription() == null)
lazy(this::setDescription, get(this, OverviewSection.class).getDescription());
return super.getDescription();
}
public List<ResourceSection> getResources() {
if (resources == null)
lazy(this::setResources, list(this, ResourceSection.class));
return resources;
}
public List<GroupSection> getGroups() {
if (groups == null)
lazy(this::setGroups, list(this, GroupSection.class));
return groups;
}
}
|
// ... existing code ...
import lombok.Setter;
import lombok.ToString;
import javax.xml.transform.stream.StreamSource;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static com.github.macrodata.skyprint.section.SectionHelper.*;
// ... modified code ...
public class RootSection extends Section {
@Setter
private Map<String, String> metadata;
@Setter
private String name;
...
@Setter
private List<GroupSection> groups;
public Map<String, String> getMetadata() {
if (metadata == null)
lazy(this::setMetadata, get(this, MetadataSection.class));
return metadata;
// ... rest of the code ...
|
00b822d2523708f333e214fc7f507ef3bf1ca865
|
setup.py
|
setup.py
|
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from pypvwatts.__version__ import VERSION
setup(
name='pypvwatts',
version=VERSION,
author='Miguel Paolino',
author_email='[email protected]',
url='https://github.com/mpaolino/pypvwatts',
download_url='https://github.com/mpaolino/pypvwatts/archive/master.zip',
description='Python wrapper for NREL PVWatts\'s API.',
long_description=open('README.md').read(),
packages=['pypvwatts'],
provides=['pypvwatts'],
requires=['requests'],
install_requires=['requests >= 2.1.0'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'License :: OSI Approved :: MIT License',
'Topic :: Internet',
'Topic :: Internet :: WWW/HTTP',
],
keywords='nrel pvwatts pypvwatts',
license='MIT',
)
|
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from pypvwatts.__version__ import VERSION
setup(
name='pypvwatts',
version=VERSION,
author='Miguel Paolino',
author_email='[email protected]',
url='https://github.com/mpaolino/pypvwatts',
download_url='https://github.com/mpaolino/pypvwatts/archive/master.zip',
description='Python wrapper for NREL PVWatts\'s API.',
long_description=open('README.md').read(),
packages=['pypvwatts'],
provides=['pypvwatts'],
requires=['requests'],
install_requires=['requests >= 2.1.0'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'License :: OSI Approved :: MIT License',
'Topic :: Internet',
'Topic :: Internet :: WWW/HTTP',
],
keywords='nrel pvwatts pypvwatts',
license='MIT',
python_requires=">=2.7",
)
|
Make sure we require at least python 2.7
|
Make sure we require at least python 2.7
|
Python
|
mit
|
mpaolino/pypvwatts
|
python
|
## Code Before:
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from pypvwatts.__version__ import VERSION
setup(
name='pypvwatts',
version=VERSION,
author='Miguel Paolino',
author_email='[email protected]',
url='https://github.com/mpaolino/pypvwatts',
download_url='https://github.com/mpaolino/pypvwatts/archive/master.zip',
description='Python wrapper for NREL PVWatts\'s API.',
long_description=open('README.md').read(),
packages=['pypvwatts'],
provides=['pypvwatts'],
requires=['requests'],
install_requires=['requests >= 2.1.0'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'License :: OSI Approved :: MIT License',
'Topic :: Internet',
'Topic :: Internet :: WWW/HTTP',
],
keywords='nrel pvwatts pypvwatts',
license='MIT',
)
## Instruction:
Make sure we require at least python 2.7
## Code After:
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from pypvwatts.__version__ import VERSION
setup(
name='pypvwatts',
version=VERSION,
author='Miguel Paolino',
author_email='[email protected]',
url='https://github.com/mpaolino/pypvwatts',
download_url='https://github.com/mpaolino/pypvwatts/archive/master.zip',
description='Python wrapper for NREL PVWatts\'s API.',
long_description=open('README.md').read(),
packages=['pypvwatts'],
provides=['pypvwatts'],
requires=['requests'],
install_requires=['requests >= 2.1.0'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'License :: OSI Approved :: MIT License',
'Topic :: Internet',
'Topic :: Internet :: WWW/HTTP',
],
keywords='nrel pvwatts pypvwatts',
license='MIT',
python_requires=">=2.7",
)
|
// ... existing code ...
],
keywords='nrel pvwatts pypvwatts',
license='MIT',
python_requires=">=2.7",
)
// ... rest of the code ...
|
074c6fb8bf3f7092920ccae04de26a1a822c38a9
|
tohu/v3/derived_generators.py
|
tohu/v3/derived_generators.py
|
from .base import TohuBaseGenerator
DERIVED_GENERATORS = ['Apply']
__all__ = DERIVED_GENERATORS + ['DERIVED_GENERATORS']
class Apply(TohuBaseGenerator):
def __init__(self, func, *arg_gens, **kwarg_gens):
self.func = func
self.orig_arg_gens = arg_gens
self.orig_kwarg_gens = kwarg_gens
self.arg_gens = [g.clone() for g in arg_gens]
self.kwarg_gens = {name: g.clone() for name, g in kwarg_gens.items()}
def __next__(self):
next_args = (next(g) for g in self.arg_gens)
next_kwargs = {name: next(g) for name, g in self.kwarg_gens.items()}
return self.func(*next_args, **next_kwargs)
def reset(self, seed=None):
pass
|
from .base import TohuBaseGenerator
DERIVED_GENERATORS = ['Apply']
__all__ = DERIVED_GENERATORS + ['DERIVED_GENERATORS']
class Apply(TohuBaseGenerator):
def __init__(self, func, *arg_gens, **kwarg_gens):
super().__init__()
self.func = func
self.orig_arg_gens = arg_gens
self.orig_kwarg_gens = kwarg_gens
self.arg_gens = [g.clone() for g in arg_gens]
self.kwarg_gens = {name: g.clone() for name, g in kwarg_gens.items()}
def __next__(self):
next_args = (next(g) for g in self.arg_gens)
next_kwargs = {name: next(g) for name, g in self.kwarg_gens.items()}
return self.func(*next_args, **next_kwargs)
def reset(self, seed=None):
super().reset(seed)
def spawn(self):
return Apply(self.func, *self.orig_arg_gens, **self.orig_kwarg_gens)
|
Add spawn method to Apply; initialise clones by calling super().__init__()
|
Add spawn method to Apply; initialise clones by calling super().__init__()
|
Python
|
mit
|
maxalbert/tohu
|
python
|
## Code Before:
from .base import TohuBaseGenerator
DERIVED_GENERATORS = ['Apply']
__all__ = DERIVED_GENERATORS + ['DERIVED_GENERATORS']
class Apply(TohuBaseGenerator):
def __init__(self, func, *arg_gens, **kwarg_gens):
self.func = func
self.orig_arg_gens = arg_gens
self.orig_kwarg_gens = kwarg_gens
self.arg_gens = [g.clone() for g in arg_gens]
self.kwarg_gens = {name: g.clone() for name, g in kwarg_gens.items()}
def __next__(self):
next_args = (next(g) for g in self.arg_gens)
next_kwargs = {name: next(g) for name, g in self.kwarg_gens.items()}
return self.func(*next_args, **next_kwargs)
def reset(self, seed=None):
pass
## Instruction:
Add spawn method to Apply; initialise clones by calling super().__init__()
## Code After:
from .base import TohuBaseGenerator
DERIVED_GENERATORS = ['Apply']
__all__ = DERIVED_GENERATORS + ['DERIVED_GENERATORS']
class Apply(TohuBaseGenerator):
def __init__(self, func, *arg_gens, **kwarg_gens):
super().__init__()
self.func = func
self.orig_arg_gens = arg_gens
self.orig_kwarg_gens = kwarg_gens
self.arg_gens = [g.clone() for g in arg_gens]
self.kwarg_gens = {name: g.clone() for name, g in kwarg_gens.items()}
def __next__(self):
next_args = (next(g) for g in self.arg_gens)
next_kwargs = {name: next(g) for name, g in self.kwarg_gens.items()}
return self.func(*next_args, **next_kwargs)
def reset(self, seed=None):
super().reset(seed)
def spawn(self):
return Apply(self.func, *self.orig_arg_gens, **self.orig_kwarg_gens)
|
# ... existing code ...
class Apply(TohuBaseGenerator):
def __init__(self, func, *arg_gens, **kwarg_gens):
super().__init__()
self.func = func
self.orig_arg_gens = arg_gens
self.orig_kwarg_gens = kwarg_gens
# ... modified code ...
return self.func(*next_args, **next_kwargs)
def reset(self, seed=None):
super().reset(seed)
def spawn(self):
return Apply(self.func, *self.orig_arg_gens, **self.orig_kwarg_gens)
# ... rest of the code ...
|
f3e1c74d9b85814cd56397560c5023e7ef536caa
|
tests/test_statuspage.py
|
tests/test_statuspage.py
|
import unittest
import sys
from helpers.statuspage import StatusPage
from test_postgresql import MockConnect
if sys.hexversion >= 0x03000000:
from io import BytesIO as IO
else:
from StringIO import StringIO as IO
class TestStatusPage(unittest.TestCase):
def test_do_GET(self):
for mock_recovery in [True, False]:
for page in [b'GET /pg_master', b'GET /pg_slave', b'GET /pg_status', b'GET /not_found']:
self.http_server = MockServer(('0.0.0.0', 8888), StatusPage, page, mock_recovery)
class MockRequest(object):
def __init__(self, path):
self.path = path
def makefile(self, *args, **kwargs):
return IO(self.path)
class MockServer(object):
def __init__(self, ip_port, Handler, path, mock_recovery=False):
self.postgresql = MockConnect()
self.postgresql.mock_values['mock_recovery'] = mock_recovery
Handler(MockRequest(path), ip_port, self)
if __name__ == '__main__':
unittest.main()
|
import unittest
import sys
from helpers.statuspage import StatusPage
from test_postgresql import MockConnect
if sys.hexversion >= 0x03000000:
from io import BytesIO as IO
else:
from StringIO import StringIO as IO
class TestStatusPage(unittest.TestCase):
def test_do_GET(self):
for mock_recovery in [True, False]:
for page in [b'GET /pg_master', b'GET /pg_slave', b'GET /pg_status', b'GET /not_found']:
self.http_server = MockServer(('0.0.0.0', 8888), StatusPage, page, mock_recovery)
class MockRequest(object):
def __init__(self, path):
self.path = path
def makefile(self, *args, **kwargs):
return IO(self.path)
class MockServer(object):
def __init__(self, ip_port, Handler, path, mock_recovery=False):
self.postgresql = MockConnect()
self.postgresql.mock_values['mock_recovery'] = mock_recovery
Handler(MockRequest(path), ip_port, self)
|
Remove some more unneccesary code.
|
Unittests: Remove some more unneccesary code.
|
Python
|
mit
|
zalando/patroni,zalando/patroni,sean-/patroni,pgexperts/patroni,sean-/patroni,pgexperts/patroni,jinty/patroni,jinty/patroni
|
python
|
## Code Before:
import unittest
import sys
from helpers.statuspage import StatusPage
from test_postgresql import MockConnect
if sys.hexversion >= 0x03000000:
from io import BytesIO as IO
else:
from StringIO import StringIO as IO
class TestStatusPage(unittest.TestCase):
def test_do_GET(self):
for mock_recovery in [True, False]:
for page in [b'GET /pg_master', b'GET /pg_slave', b'GET /pg_status', b'GET /not_found']:
self.http_server = MockServer(('0.0.0.0', 8888), StatusPage, page, mock_recovery)
class MockRequest(object):
def __init__(self, path):
self.path = path
def makefile(self, *args, **kwargs):
return IO(self.path)
class MockServer(object):
def __init__(self, ip_port, Handler, path, mock_recovery=False):
self.postgresql = MockConnect()
self.postgresql.mock_values['mock_recovery'] = mock_recovery
Handler(MockRequest(path), ip_port, self)
if __name__ == '__main__':
unittest.main()
## Instruction:
Unittests: Remove some more unneccesary code.
## Code After:
import unittest
import sys
from helpers.statuspage import StatusPage
from test_postgresql import MockConnect
if sys.hexversion >= 0x03000000:
from io import BytesIO as IO
else:
from StringIO import StringIO as IO
class TestStatusPage(unittest.TestCase):
def test_do_GET(self):
for mock_recovery in [True, False]:
for page in [b'GET /pg_master', b'GET /pg_slave', b'GET /pg_status', b'GET /not_found']:
self.http_server = MockServer(('0.0.0.0', 8888), StatusPage, page, mock_recovery)
class MockRequest(object):
def __init__(self, path):
self.path = path
def makefile(self, *args, **kwargs):
return IO(self.path)
class MockServer(object):
def __init__(self, ip_port, Handler, path, mock_recovery=False):
self.postgresql = MockConnect()
self.postgresql.mock_values['mock_recovery'] = mock_recovery
Handler(MockRequest(path), ip_port, self)
|
// ... existing code ...
self.postgresql = MockConnect()
self.postgresql.mock_values['mock_recovery'] = mock_recovery
Handler(MockRequest(path), ip_port, self)
// ... rest of the code ...
|
3f4df8fdcb12689afec4e8e81bd7511e9b84966a
|
app/src/main/java/org/cyanogenmod/launcher/home/api/sdkexample/receiver/CardDeletedBroadcastReceiver.java
|
app/src/main/java/org/cyanogenmod/launcher/home/api/sdkexample/receiver/CardDeletedBroadcastReceiver.java
|
package org.cyanogenmod.launcher.home.api.sdkexample.receiver;
import android.util.Log;
import org.cyanogenmod.launcher.home.api.cards.DataCard;
import org.cyanogenmod.launcher.home.api.receiver.CmHomeCardChangeReceiver;
/**
* An extension of CmHomeCardChangeReceiver, that implements the callback for
* when a card is deleted.
*/
public class CardDeletedBroadcastReceiver extends CmHomeCardChangeReceiver{
public static final String TAG = "CardDeletedBroadcastReceiver";
@Override
protected void onCardDeleted(DataCard.CardDeletedInfo cardDeletedInfo) {
Log.i(TAG, "CM Home API card was deleted: id: " + cardDeletedInfo.getId()
+ ", internalID: " + cardDeletedInfo.getInternalId()
+ ", authority: " + cardDeletedInfo.getAuthority()
+ ", globalID: " + cardDeletedInfo.getGlobalId());
}
}
|
package org.cyanogenmod.launcher.home.api.sdkexample.receiver;
import android.content.Context;
import android.util.Log;
import org.cyanogenmod.launcher.home.api.cards.DataCard;
import org.cyanogenmod.launcher.home.api.receiver.CmHomeCardChangeReceiver;
/**
* An extension of CmHomeCardChangeReceiver, that implements the callback for
* when a card is deleted.
*/
public class CardDeletedBroadcastReceiver extends CmHomeCardChangeReceiver{
public static final String TAG = "CardDeletedBroadcastReceiver";
@Override
protected void onCardDeleted(Context context, DataCard.CardDeletedInfo cardDeletedInfo) {
Log.i(TAG, "CM Home API card was deleted: id: " + cardDeletedInfo.getId()
+ ", internalID: " + cardDeletedInfo.getInternalId()
+ ", authority: " + cardDeletedInfo.getAuthority()
+ ", globalID: " + cardDeletedInfo.getGlobalId()); }
}
|
Add Context parameter to onCardDelete to match SDK
|
Add Context parameter to onCardDelete to match SDK
|
Java
|
apache-2.0
|
mattgmg1990/CMHome-SDK-Example
|
java
|
## Code Before:
package org.cyanogenmod.launcher.home.api.sdkexample.receiver;
import android.util.Log;
import org.cyanogenmod.launcher.home.api.cards.DataCard;
import org.cyanogenmod.launcher.home.api.receiver.CmHomeCardChangeReceiver;
/**
* An extension of CmHomeCardChangeReceiver, that implements the callback for
* when a card is deleted.
*/
public class CardDeletedBroadcastReceiver extends CmHomeCardChangeReceiver{
public static final String TAG = "CardDeletedBroadcastReceiver";
@Override
protected void onCardDeleted(DataCard.CardDeletedInfo cardDeletedInfo) {
Log.i(TAG, "CM Home API card was deleted: id: " + cardDeletedInfo.getId()
+ ", internalID: " + cardDeletedInfo.getInternalId()
+ ", authority: " + cardDeletedInfo.getAuthority()
+ ", globalID: " + cardDeletedInfo.getGlobalId());
}
}
## Instruction:
Add Context parameter to onCardDelete to match SDK
## Code After:
package org.cyanogenmod.launcher.home.api.sdkexample.receiver;
import android.content.Context;
import android.util.Log;
import org.cyanogenmod.launcher.home.api.cards.DataCard;
import org.cyanogenmod.launcher.home.api.receiver.CmHomeCardChangeReceiver;
/**
* An extension of CmHomeCardChangeReceiver, that implements the callback for
* when a card is deleted.
*/
public class CardDeletedBroadcastReceiver extends CmHomeCardChangeReceiver{
public static final String TAG = "CardDeletedBroadcastReceiver";
@Override
protected void onCardDeleted(Context context, DataCard.CardDeletedInfo cardDeletedInfo) {
Log.i(TAG, "CM Home API card was deleted: id: " + cardDeletedInfo.getId()
+ ", internalID: " + cardDeletedInfo.getInternalId()
+ ", authority: " + cardDeletedInfo.getAuthority()
+ ", globalID: " + cardDeletedInfo.getGlobalId()); }
}
|
// ... existing code ...
package org.cyanogenmod.launcher.home.api.sdkexample.receiver;
import android.content.Context;
import android.util.Log;
import org.cyanogenmod.launcher.home.api.cards.DataCard;
// ... modified code ...
public static final String TAG = "CardDeletedBroadcastReceiver";
@Override
protected void onCardDeleted(Context context, DataCard.CardDeletedInfo cardDeletedInfo) {
Log.i(TAG, "CM Home API card was deleted: id: " + cardDeletedInfo.getId()
+ ", internalID: " + cardDeletedInfo.getInternalId()
+ ", authority: " + cardDeletedInfo.getAuthority()
+ ", globalID: " + cardDeletedInfo.getGlobalId()); }
}
// ... rest of the code ...
|
90fa670edc958815fcba4ae9ab151eb4af23143f
|
examples/WebImageList/src/com/wrapp/android/webimageexample/WebImageListAdapter.java
|
examples/WebImageList/src/com/wrapp/android/webimageexample/WebImageListAdapter.java
|
package com.wrapp.android.webimageexample;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class WebImageListAdapter extends BaseAdapter {
private static final boolean USE_AWESOME_IMAGES = true;
private static final int NUM_IMAGES = 100;
private static final int IMAGE_SIZE = 100;
public int getCount() {
return NUM_IMAGES;
}
private String getImageUrl(int i) {
if(USE_AWESOME_IMAGES) {
// Unicorns!
return "http://unicornify.appspot.com/avatar/" + i + "?s=" + IMAGE_SIZE;
}
else {
// Boring identicons
return "http://www.gravatar.com/avatar/" + i + "?s=" + IMAGE_SIZE + "&d=identicon";
}
}
public Object getItem(int i) {
return getImageUrl(i);
}
public long getItemId(int i) {
return i;
}
public View getView(int i, View convertView, ViewGroup parentViewGroup) {
WebImageContainerView containerView;
if(convertView != null) {
containerView = (WebImageContainerView)convertView;
}
else {
containerView = new WebImageContainerView(parentViewGroup.getContext());
}
containerView.setImageUrl(getImageUrl(i));
return containerView;
}
}
|
package com.wrapp.android.webimageexample;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class WebImageListAdapter extends BaseAdapter {
private static final boolean USE_AWESOME_IMAGES = true;
private static final int NUM_IMAGES = 100;
private static final int IMAGE_SIZE = 100;
public int getCount() {
return NUM_IMAGES;
}
private String getImageUrl(int i) {
if(USE_AWESOME_IMAGES) {
// Unicorns!
return "http://unicornify.appspot.com/avatar/" + i + "?s=" + IMAGE_SIZE;
}
else {
// Boring identicons
return "http://www.gravatar.com/avatar/" + i + "?s=" + IMAGE_SIZE + "&d=identicon";
}
}
public Object getItem(int i) {
return getImageUrl(i);
}
public long getItemId(int i) {
return i;
}
public View getView(int i, View convertView, ViewGroup parentViewGroup) {
WebImageContainerView containerView;
if(convertView != null) {
containerView = (WebImageContainerView)convertView;
}
else {
containerView = new WebImageContainerView(parentViewGroup.getContext());
}
containerView.setImageUrl(getImageUrl(i));
containerView.setImageText("Image #" + i);
return containerView;
}
}
|
Set image title in list container views
|
Set image title in list container views
|
Java
|
mit
|
wrapp/WebImage-Android,wrapp/WebImage-Android
|
java
|
## Code Before:
package com.wrapp.android.webimageexample;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class WebImageListAdapter extends BaseAdapter {
private static final boolean USE_AWESOME_IMAGES = true;
private static final int NUM_IMAGES = 100;
private static final int IMAGE_SIZE = 100;
public int getCount() {
return NUM_IMAGES;
}
private String getImageUrl(int i) {
if(USE_AWESOME_IMAGES) {
// Unicorns!
return "http://unicornify.appspot.com/avatar/" + i + "?s=" + IMAGE_SIZE;
}
else {
// Boring identicons
return "http://www.gravatar.com/avatar/" + i + "?s=" + IMAGE_SIZE + "&d=identicon";
}
}
public Object getItem(int i) {
return getImageUrl(i);
}
public long getItemId(int i) {
return i;
}
public View getView(int i, View convertView, ViewGroup parentViewGroup) {
WebImageContainerView containerView;
if(convertView != null) {
containerView = (WebImageContainerView)convertView;
}
else {
containerView = new WebImageContainerView(parentViewGroup.getContext());
}
containerView.setImageUrl(getImageUrl(i));
return containerView;
}
}
## Instruction:
Set image title in list container views
## Code After:
package com.wrapp.android.webimageexample;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class WebImageListAdapter extends BaseAdapter {
private static final boolean USE_AWESOME_IMAGES = true;
private static final int NUM_IMAGES = 100;
private static final int IMAGE_SIZE = 100;
public int getCount() {
return NUM_IMAGES;
}
private String getImageUrl(int i) {
if(USE_AWESOME_IMAGES) {
// Unicorns!
return "http://unicornify.appspot.com/avatar/" + i + "?s=" + IMAGE_SIZE;
}
else {
// Boring identicons
return "http://www.gravatar.com/avatar/" + i + "?s=" + IMAGE_SIZE + "&d=identicon";
}
}
public Object getItem(int i) {
return getImageUrl(i);
}
public long getItemId(int i) {
return i;
}
public View getView(int i, View convertView, ViewGroup parentViewGroup) {
WebImageContainerView containerView;
if(convertView != null) {
containerView = (WebImageContainerView)convertView;
}
else {
containerView = new WebImageContainerView(parentViewGroup.getContext());
}
containerView.setImageUrl(getImageUrl(i));
containerView.setImageText("Image #" + i);
return containerView;
}
}
|
...
}
containerView.setImageUrl(getImageUrl(i));
containerView.setImageText("Image #" + i);
return containerView;
}
}
...
|
eda0dc8bdc89e815ff21be91ade9d53f0c13721a
|
mockito/tests/numpy_test.py
|
mockito/tests/numpy_test.py
|
import mockito
from mockito import when, patch
import numpy as np
from . import module
def xcompare(a, b):
if isinstance(a, mockito.matchers.Matcher):
return a.matches(b)
return np.array_equal(a, b)
class TestEnsureNumpyWorks:
def testEnsureNumpyArrayAllowedWhenStubbing(self):
array = np.array([1, 2, 3])
with patch(mockito.invocation.MatchingInvocation.compare, xcompare):
when(module).one_arg(array).thenReturn('yep')
assert module.one_arg(array) == 'yep'
def testEnsureNumpyArrayAllowedWhenCalling(self):
array = np.array([1, 2, 3])
when(module).one_arg(Ellipsis).thenReturn('yep')
assert module.one_arg(array) == 'yep'
|
import mockito
from mockito import when, patch
import pytest
import numpy as np
from . import module
pytestmark = pytest.mark.usefixtures("unstub")
def xcompare(a, b):
if isinstance(a, mockito.matchers.Matcher):
return a.matches(b)
return np.array_equal(a, b)
class TestEnsureNumpyWorks:
def testEnsureNumpyArrayAllowedWhenStubbing(self):
array = np.array([1, 2, 3])
when(module).one_arg(array).thenReturn('yep')
with patch(mockito.invocation.MatchingInvocation.compare, xcompare):
assert module.one_arg(array) == 'yep'
def testEnsureNumpyArrayAllowedWhenCalling(self):
array = np.array([1, 2, 3])
when(module).one_arg(Ellipsis).thenReturn('yep')
assert module.one_arg(array) == 'yep'
|
Make numpy test clearer and ensure unstub
|
Make numpy test clearer and ensure unstub
|
Python
|
mit
|
kaste/mockito-python
|
python
|
## Code Before:
import mockito
from mockito import when, patch
import numpy as np
from . import module
def xcompare(a, b):
if isinstance(a, mockito.matchers.Matcher):
return a.matches(b)
return np.array_equal(a, b)
class TestEnsureNumpyWorks:
def testEnsureNumpyArrayAllowedWhenStubbing(self):
array = np.array([1, 2, 3])
with patch(mockito.invocation.MatchingInvocation.compare, xcompare):
when(module).one_arg(array).thenReturn('yep')
assert module.one_arg(array) == 'yep'
def testEnsureNumpyArrayAllowedWhenCalling(self):
array = np.array([1, 2, 3])
when(module).one_arg(Ellipsis).thenReturn('yep')
assert module.one_arg(array) == 'yep'
## Instruction:
Make numpy test clearer and ensure unstub
## Code After:
import mockito
from mockito import when, patch
import pytest
import numpy as np
from . import module
pytestmark = pytest.mark.usefixtures("unstub")
def xcompare(a, b):
if isinstance(a, mockito.matchers.Matcher):
return a.matches(b)
return np.array_equal(a, b)
class TestEnsureNumpyWorks:
def testEnsureNumpyArrayAllowedWhenStubbing(self):
array = np.array([1, 2, 3])
when(module).one_arg(array).thenReturn('yep')
with patch(mockito.invocation.MatchingInvocation.compare, xcompare):
assert module.one_arg(array) == 'yep'
def testEnsureNumpyArrayAllowedWhenCalling(self):
array = np.array([1, 2, 3])
when(module).one_arg(Ellipsis).thenReturn('yep')
assert module.one_arg(array) == 'yep'
|
# ... existing code ...
import mockito
from mockito import when, patch
import pytest
import numpy as np
from . import module
pytestmark = pytest.mark.usefixtures("unstub")
def xcompare(a, b):
# ... modified code ...
class TestEnsureNumpyWorks:
def testEnsureNumpyArrayAllowedWhenStubbing(self):
array = np.array([1, 2, 3])
when(module).one_arg(array).thenReturn('yep')
with patch(mockito.invocation.MatchingInvocation.compare, xcompare):
assert module.one_arg(array) == 'yep'
def testEnsureNumpyArrayAllowedWhenCalling(self):
# ... rest of the code ...
|
5e2dbeab75501254da598c6c401cbbd8446f01a5
|
util/timeline_adjust.py
|
util/timeline_adjust.py
|
from __future__ import print_function
import argparse
import re
time_re = re.compile(r"^\s*#?\s*([0-9]+(?:\.[0-9]+)?)\s+\"")
first_num_re = re.compile(r"([0-9]+(?:\.[0-9]+)?)")
def adjust_lines(lines, adjust):
for line in lines:
match = re.match(time_re, line)
if match:
time = float(match.group(1)) + adjust
print(re.sub(first_num_re, str(time), line, 1), end='')
else:
print(line, end='')
def main():
parser = argparse.ArgumentParser(
description="A utility to uniformly adjust times in an act timeline file")
parser.add_argument('--file', required=True, type=argparse.FileType('r', 0),
help="The timeline file to adjust times in")
parser.add_argument('--adjust', required=True, type=float,
help="The amount of time to adjust each entry by")
args = parser.parse_args()
adjust_lines(args.file, args.adjust)
if __name__ == "__main__":
main()
|
from __future__ import print_function
import argparse
import re
time_re = re.compile(r"^\s*#?\s*([0-9]+(?:\.[0-9]+)?)\s+\"")
first_num_re = re.compile(r"([0-9]+(?:\.[0-9]+)?)")
def adjust_lines(lines, adjust):
for line in lines:
match = re.match(time_re, line)
if match:
time = float(match.group(1)) + adjust
print(re.sub(first_num_re, str(time), line, 1), end='')
else:
print(line, end='')
def main():
parser = argparse.ArgumentParser(
description="A utility to uniformly adjust times in an act timeline file")
parser.add_argument('--file', required=True, type=argparse.FileType('r', encoding="utf8"),
help="The timeline file to adjust times in")
parser.add_argument('--adjust', required=True, type=float,
help="The amount of time to adjust each entry by")
args = parser.parse_args()
adjust_lines(args.file, args.adjust)
if __name__ == "__main__":
main()
|
Fix timeline adjust not being able to load Windows files
|
Fix timeline adjust not being able to load Windows files
|
Python
|
apache-2.0
|
quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,sqt/cactbot,sqt/cactbot,sqt/cactbot,sqt/cactbot,quisquous/cactbot,quisquous/cactbot,sqt/cactbot,quisquous/cactbot
|
python
|
## Code Before:
from __future__ import print_function
import argparse
import re
time_re = re.compile(r"^\s*#?\s*([0-9]+(?:\.[0-9]+)?)\s+\"")
first_num_re = re.compile(r"([0-9]+(?:\.[0-9]+)?)")
def adjust_lines(lines, adjust):
for line in lines:
match = re.match(time_re, line)
if match:
time = float(match.group(1)) + adjust
print(re.sub(first_num_re, str(time), line, 1), end='')
else:
print(line, end='')
def main():
parser = argparse.ArgumentParser(
description="A utility to uniformly adjust times in an act timeline file")
parser.add_argument('--file', required=True, type=argparse.FileType('r', 0),
help="The timeline file to adjust times in")
parser.add_argument('--adjust', required=True, type=float,
help="The amount of time to adjust each entry by")
args = parser.parse_args()
adjust_lines(args.file, args.adjust)
if __name__ == "__main__":
main()
## Instruction:
Fix timeline adjust not being able to load Windows files
## Code After:
from __future__ import print_function
import argparse
import re
time_re = re.compile(r"^\s*#?\s*([0-9]+(?:\.[0-9]+)?)\s+\"")
first_num_re = re.compile(r"([0-9]+(?:\.[0-9]+)?)")
def adjust_lines(lines, adjust):
for line in lines:
match = re.match(time_re, line)
if match:
time = float(match.group(1)) + adjust
print(re.sub(first_num_re, str(time), line, 1), end='')
else:
print(line, end='')
def main():
parser = argparse.ArgumentParser(
description="A utility to uniformly adjust times in an act timeline file")
parser.add_argument('--file', required=True, type=argparse.FileType('r', encoding="utf8"),
help="The timeline file to adjust times in")
parser.add_argument('--adjust', required=True, type=float,
help="The amount of time to adjust each entry by")
args = parser.parse_args()
adjust_lines(args.file, args.adjust)
if __name__ == "__main__":
main()
|
# ... existing code ...
def main():
parser = argparse.ArgumentParser(
description="A utility to uniformly adjust times in an act timeline file")
parser.add_argument('--file', required=True, type=argparse.FileType('r', encoding="utf8"),
help="The timeline file to adjust times in")
parser.add_argument('--adjust', required=True, type=float,
help="The amount of time to adjust each entry by")
# ... rest of the code ...
|
c9d381dd5c370c5281dfb0bc4814ca11d51e7ccf
|
src/test/java/hello/HomePageTest.java
|
src/test/java/hello/HomePageTest.java
|
package hello;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import hello.Hello;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Hello.class)
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class HomePageTest {
@Autowired
private MockMvc mvc;
@Test
public void getRoot() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk());
}
@Test
public void getJsonRoot() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound());
}
}
|
package hello;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Hello.class)
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class HomePageTest {
@Autowired
private MockMvc mvc;
@Test
public void getRoot() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk());
}
@Test
public void getJsonRoot() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound());
}
}
|
Remove obsolete import and fix formatting in test.
|
Remove obsolete import and fix formatting in test.
|
Java
|
bsd-3-clause
|
hainesr/mvc-dev,hainesr/mvc-dev
|
java
|
## Code Before:
package hello;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import hello.Hello;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Hello.class)
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class HomePageTest {
@Autowired
private MockMvc mvc;
@Test
public void getRoot() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk());
}
@Test
public void getJsonRoot() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound());
}
}
## Instruction:
Remove obsolete import and fix formatting in test.
## Code After:
package hello;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Hello.class)
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class HomePageTest {
@Autowired
private MockMvc mvc;
@Test
public void getRoot() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk());
}
@Test
public void getJsonRoot() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound());
}
}
|
...
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Hello.class)
...
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound());
}
}
...
|
93644ba1850186eabcfea6bdab47e3e3d223becf
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('requirements.txt') as req_file:
requires = req_file.read().split('\n')
with open('requirements-dev.txt') as req_file:
requires_dev = req_file.read().split('\n')
with open('VERSION') as fp:
version = fp.read().strip()
setup(name='molo.yourwords',
version=version,
description=('A Molo module that enables user generated content '
'competitions'),
long_description=readme,
classifiers=[
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.6",
"Framework :: Django",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='Praekelt Foundation',
author_email='[email protected]',
url='http://github.com/praekelt/molo.yourwords',
license='BSD',
keywords='praekelt, mobi, web, django',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
namespace_packages=['molo'],
install_requires=requires,
tests_require=requires_dev,
entry_points={})
|
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('requirements.txt') as req_file:
requires = [req for req in req_file.read().split('\n') if req]
with open('requirements-dev.txt') as req_file:
requires_dev = [req for req in req_file.read().split('\n') if req]
with open('VERSION') as fp:
version = fp.read().strip()
setup(name='molo.yourwords',
version=version,
description=('A Molo module that enables user generated content '
'competitions'),
long_description=readme,
classifiers=[
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.6",
"Framework :: Django",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='Praekelt Foundation',
author_email='[email protected]',
url='http://github.com/praekelt/molo.yourwords',
license='BSD',
keywords='praekelt, mobi, web, django',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
namespace_packages=['molo'],
install_requires=requires,
tests_require=requires_dev,
entry_points={})
|
Remove empty string from requirements list
|
Remove empty string from requirements list
When we moved to Python 3 we used this simpler method to read the requirements
file. However we need to remove the empty/Falsey elements from the list.
This fixes the error:
```
Failed building wheel for molo.yourwords
```
|
Python
|
bsd-2-clause
|
praekelt/molo.yourwords,praekelt/molo.yourwords
|
python
|
## Code Before:
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('requirements.txt') as req_file:
requires = req_file.read().split('\n')
with open('requirements-dev.txt') as req_file:
requires_dev = req_file.read().split('\n')
with open('VERSION') as fp:
version = fp.read().strip()
setup(name='molo.yourwords',
version=version,
description=('A Molo module that enables user generated content '
'competitions'),
long_description=readme,
classifiers=[
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.6",
"Framework :: Django",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='Praekelt Foundation',
author_email='[email protected]',
url='http://github.com/praekelt/molo.yourwords',
license='BSD',
keywords='praekelt, mobi, web, django',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
namespace_packages=['molo'],
install_requires=requires,
tests_require=requires_dev,
entry_points={})
## Instruction:
Remove empty string from requirements list
When we moved to Python 3 we used this simpler method to read the requirements
file. However we need to remove the empty/Falsey elements from the list.
This fixes the error:
```
Failed building wheel for molo.yourwords
```
## Code After:
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('requirements.txt') as req_file:
requires = [req for req in req_file.read().split('\n') if req]
with open('requirements-dev.txt') as req_file:
requires_dev = [req for req in req_file.read().split('\n') if req]
with open('VERSION') as fp:
version = fp.read().strip()
setup(name='molo.yourwords',
version=version,
description=('A Molo module that enables user generated content '
'competitions'),
long_description=readme,
classifiers=[
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.6",
"Framework :: Django",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='Praekelt Foundation',
author_email='[email protected]',
url='http://github.com/praekelt/molo.yourwords',
license='BSD',
keywords='praekelt, mobi, web, django',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
namespace_packages=['molo'],
install_requires=requires,
tests_require=requires_dev,
entry_points={})
|
# ... existing code ...
readme = readme_file.read()
with open('requirements.txt') as req_file:
requires = [req for req in req_file.read().split('\n') if req]
with open('requirements-dev.txt') as req_file:
requires_dev = [req for req in req_file.read().split('\n') if req]
with open('VERSION') as fp:
version = fp.read().strip()
# ... rest of the code ...
|
22b6fecd95bc9097c9707e46049826810bf0460d
|
src/main/java/editor/util/Lazy.java
|
src/main/java/editor/util/Lazy.java
|
package editor.util;
import java.util.function.Supplier;
/**
* This class "lazily" supplies a value by not evaluating it until the first time
* it is requested. Then that function's result is cached so it doesn't have to
* be reevaluated again.
*
* @param <T> Type of object that is being lazily evaluated
* @author Alec Roelke
*/
public class Lazy<T> implements Supplier<T>
{
/**
* Cached value.
*/
private T value;
/**
* Supplier for the cached value.
*/
private Supplier<T> supplier;
/**
* Create a new Lazy supplier.
*
* @param val Function supplying the value to lazily evaluate.
*/
public Lazy(Supplier<T> val)
{
value = null;
supplier = val;
}
/**
* If the value has not been computed, compute it and then return it. Otherwise,
* just return it.
*
* @return The value computed by the function
*/
@Override
public T get()
{
if (value == null)
value = supplier.get();
return value;
}
}
|
package editor.util;
import java.util.function.Supplier;
/**
* This class "lazily" supplies a value by not evaluating it until the first time
* it is requested. Then that function's result is cached so it doesn't have to
* be reevaluated again.
*
* @param <T> Type of object that is being lazily evaluated
* @author Alec Roelke
*/
public class Lazy<T> implements Supplier<T>
{
/**
* Cached value.
*/
private T value;
/**
* Supplier for the cached value.
*/
private Supplier<T> supplier;
/**
* Create a new Lazy supplier.
*
* @param val Function supplying the value to lazily evaluate.
*/
public Lazy(Supplier<T> val)
{
value = null;
supplier = val;
}
/**
* If the value has not been computed, compute it and then return it. Otherwise,
* just return it.
*
* @return The value computed by the function
*/
@Override
public T get()
{
if (value == null)
{
value = supplier.get();
supplier = null;
}
return value;
}
}
|
Discard supplier after it's used
|
Discard supplier after it's used
|
Java
|
mit
|
aroelke/deck-editor-java
|
java
|
## Code Before:
package editor.util;
import java.util.function.Supplier;
/**
* This class "lazily" supplies a value by not evaluating it until the first time
* it is requested. Then that function's result is cached so it doesn't have to
* be reevaluated again.
*
* @param <T> Type of object that is being lazily evaluated
* @author Alec Roelke
*/
public class Lazy<T> implements Supplier<T>
{
/**
* Cached value.
*/
private T value;
/**
* Supplier for the cached value.
*/
private Supplier<T> supplier;
/**
* Create a new Lazy supplier.
*
* @param val Function supplying the value to lazily evaluate.
*/
public Lazy(Supplier<T> val)
{
value = null;
supplier = val;
}
/**
* If the value has not been computed, compute it and then return it. Otherwise,
* just return it.
*
* @return The value computed by the function
*/
@Override
public T get()
{
if (value == null)
value = supplier.get();
return value;
}
}
## Instruction:
Discard supplier after it's used
## Code After:
package editor.util;
import java.util.function.Supplier;
/**
* This class "lazily" supplies a value by not evaluating it until the first time
* it is requested. Then that function's result is cached so it doesn't have to
* be reevaluated again.
*
* @param <T> Type of object that is being lazily evaluated
* @author Alec Roelke
*/
public class Lazy<T> implements Supplier<T>
{
/**
* Cached value.
*/
private T value;
/**
* Supplier for the cached value.
*/
private Supplier<T> supplier;
/**
* Create a new Lazy supplier.
*
* @param val Function supplying the value to lazily evaluate.
*/
public Lazy(Supplier<T> val)
{
value = null;
supplier = val;
}
/**
* If the value has not been computed, compute it and then return it. Otherwise,
* just return it.
*
* @return The value computed by the function
*/
@Override
public T get()
{
if (value == null)
{
value = supplier.get();
supplier = null;
}
return value;
}
}
|
...
public T get()
{
if (value == null)
{
value = supplier.get();
supplier = null;
}
return value;
}
}
...
|
1e17e868ff332003da959a397b8846c9386b35e8
|
API_to_backend.py
|
API_to_backend.py
|
from multiprocessing import Queue, Process
import time
import backend
command_queue = Queue()
response_queue = Queue()
def start_backend():
if handler:
handler.stop()
handler = Process(target=backend.start, args=(command_queue, response_queue))
handler.start()
def get_for(url, queue, timeout):
beginning = time.time()
result = queue.get(timeout=timeout)
if result["url"] == url:
return result["body"]
else:
queue.put(result)
return get_for(url, queue, timeout - (time.time()-beginning))
|
from multiprocessing import Queue, Process
import time
import backend
command_queue = Queue()
response_queue = Queue()
def start_backend():
handler = Process(target=backend.start, args=(command_queue, response_queue))
handler.start()
def get_for(url, queue, timeout):
beginning = time.time()
result = queue.get(timeout=timeout)
if result["url"] == url:
return result["body"]
else:
queue.put(result)
return get_for(url, queue, timeout - (time.time()-beginning))
|
Revert "Quit Backend If Running"
|
Revert "Quit Backend If Running"
This reverts commit a00432191e2575aba0f20ffb1a96a323699ae4fc.
|
Python
|
mit
|
IAPark/PITherm
|
python
|
## Code Before:
from multiprocessing import Queue, Process
import time
import backend
command_queue = Queue()
response_queue = Queue()
def start_backend():
if handler:
handler.stop()
handler = Process(target=backend.start, args=(command_queue, response_queue))
handler.start()
def get_for(url, queue, timeout):
beginning = time.time()
result = queue.get(timeout=timeout)
if result["url"] == url:
return result["body"]
else:
queue.put(result)
return get_for(url, queue, timeout - (time.time()-beginning))
## Instruction:
Revert "Quit Backend If Running"
This reverts commit a00432191e2575aba0f20ffb1a96a323699ae4fc.
## Code After:
from multiprocessing import Queue, Process
import time
import backend
command_queue = Queue()
response_queue = Queue()
def start_backend():
handler = Process(target=backend.start, args=(command_queue, response_queue))
handler.start()
def get_for(url, queue, timeout):
beginning = time.time()
result = queue.get(timeout=timeout)
if result["url"] == url:
return result["body"]
else:
queue.put(result)
return get_for(url, queue, timeout - (time.time()-beginning))
|
...
def start_backend():
handler = Process(target=backend.start, args=(command_queue, response_queue))
handler.start()
...
|
8dbcd07e0db34d39ad8f79067282d4359d79439d
|
usr/bin/graphical-app-launcher.py
|
usr/bin/graphical-app-launcher.py
|
import os
import subprocess
if __name__ == '__main__':
if os.environ.has_key('APP'):
graphical_app = os.environ['APP']
process = subprocess.Popen(graphical_app, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdoutdata, stderrordata = process.communicate()
print(stdoutdata)
subprocess.call(['sudo', 'supervisorctl', 'shutdown'],
stdout=subprocess.PIPE)
|
import os
import subprocess
if __name__ == '__main__':
if os.environ.has_key('APP'):
graphical_app = os.environ['APP']
if os.environ.has_key('ARGS'):
extra_args = os.environ['ARGS']
command = graphical_app + ' ' + extra_args
else:
command = graphical_app
process = subprocess.Popen(command, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdoutdata, stderrordata = process.communicate()
print(stdoutdata)
subprocess.call(['sudo', 'supervisorctl', 'shutdown'],
stdout=subprocess.PIPE)
|
Support an ARGS enviromental variable for extra command arguments.
|
Support an ARGS enviromental variable for extra command arguments.
|
Python
|
apache-2.0
|
thewtex/docker-opengl,thewtex/docker-opengl
|
python
|
## Code Before:
import os
import subprocess
if __name__ == '__main__':
if os.environ.has_key('APP'):
graphical_app = os.environ['APP']
process = subprocess.Popen(graphical_app, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdoutdata, stderrordata = process.communicate()
print(stdoutdata)
subprocess.call(['sudo', 'supervisorctl', 'shutdown'],
stdout=subprocess.PIPE)
## Instruction:
Support an ARGS enviromental variable for extra command arguments.
## Code After:
import os
import subprocess
if __name__ == '__main__':
if os.environ.has_key('APP'):
graphical_app = os.environ['APP']
if os.environ.has_key('ARGS'):
extra_args = os.environ['ARGS']
command = graphical_app + ' ' + extra_args
else:
command = graphical_app
process = subprocess.Popen(command, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdoutdata, stderrordata = process.communicate()
print(stdoutdata)
subprocess.call(['sudo', 'supervisorctl', 'shutdown'],
stdout=subprocess.PIPE)
|
// ... existing code ...
if __name__ == '__main__':
if os.environ.has_key('APP'):
graphical_app = os.environ['APP']
if os.environ.has_key('ARGS'):
extra_args = os.environ['ARGS']
command = graphical_app + ' ' + extra_args
else:
command = graphical_app
process = subprocess.Popen(command, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdoutdata, stderrordata = process.communicate()
print(stdoutdata)
// ... rest of the code ...
|
8225105cf2e72560d8c53ec58c1b98683a613381
|
util/versioncheck.py
|
util/versioncheck.py
|
from subprocess import check_output as co
from sys import exit
# Actually run bin/mn rather than importing via python path
version = 'Mininet ' + co( 'PYTHONPATH=. bin/mn --version', shell=True )
version = version.strip()
# Find all Mininet path references
lines = co( "grep -or 'Mininet \w\+\.\w\+\.\w\+[+]*' *", shell=True )
error = False
for line in lines.split( '\n' ):
if line and 'Binary' not in line:
fname, fversion = line.split( ':' )
if version != fversion:
print "%s: incorrect version '%s' (should be '%s')" % (
fname, fversion, version )
error = True
if error:
exit( 1 )
|
from subprocess import check_output as co
from sys import exit
# Actually run bin/mn rather than importing via python path
version = 'Mininet ' + co( 'PYTHONPATH=. bin/mn --version', shell=True )
version = version.strip()
# Find all Mininet path references
lines = co( "egrep -or 'Mininet [0-9\.]+\w*' *", shell=True )
error = False
for line in lines.split( '\n' ):
if line and 'Binary' not in line:
fname, fversion = line.split( ':' )
if version != fversion:
print "%s: incorrect version '%s' (should be '%s')" % (
fname, fversion, version )
error = True
if error:
exit( 1 )
|
Fix to allow more flexible version numbers
|
Fix to allow more flexible version numbers
|
Python
|
bsd-3-clause
|
mininet/mininet,mininet/mininet,mininet/mininet
|
python
|
## Code Before:
from subprocess import check_output as co
from sys import exit
# Actually run bin/mn rather than importing via python path
version = 'Mininet ' + co( 'PYTHONPATH=. bin/mn --version', shell=True )
version = version.strip()
# Find all Mininet path references
lines = co( "grep -or 'Mininet \w\+\.\w\+\.\w\+[+]*' *", shell=True )
error = False
for line in lines.split( '\n' ):
if line and 'Binary' not in line:
fname, fversion = line.split( ':' )
if version != fversion:
print "%s: incorrect version '%s' (should be '%s')" % (
fname, fversion, version )
error = True
if error:
exit( 1 )
## Instruction:
Fix to allow more flexible version numbers
## Code After:
from subprocess import check_output as co
from sys import exit
# Actually run bin/mn rather than importing via python path
version = 'Mininet ' + co( 'PYTHONPATH=. bin/mn --version', shell=True )
version = version.strip()
# Find all Mininet path references
lines = co( "egrep -or 'Mininet [0-9\.]+\w*' *", shell=True )
error = False
for line in lines.split( '\n' ):
if line and 'Binary' not in line:
fname, fversion = line.split( ':' )
if version != fversion:
print "%s: incorrect version '%s' (should be '%s')" % (
fname, fversion, version )
error = True
if error:
exit( 1 )
|
...
version = version.strip()
# Find all Mininet path references
lines = co( "egrep -or 'Mininet [0-9\.]+\w*' *", shell=True )
error = False
...
|
437ed5ee5e919186eabd1d71b0c1949adc1cf378
|
src/orca/gnome-terminal.py
|
src/orca/gnome-terminal.py
|
import a11y
import speech
def onTextInserted (e):
if e.source.role != "terminal":
return
speech.say ("default", e.any_data)
def onTextDeleted (event):
"""Called whenever text is deleted from an object.
Arguments:
- event: the Event
"""
# Ignore text deletions from non-focused objects, unless the
# currently focused object is the parent of the object from which
# text was deleted
#
if (event.source != a11y.focusedObject) \
and (event.source.parent != a11y.focusedObject):
pass
else:
brlUpdateText (event.source)
|
import a11y
import speech
import default
def onTextInserted (e):
if e.source.role != "terminal":
return
speech.say ("default", e.any_data)
def onTextDeleted (event):
"""Called whenever text is deleted from an object.
Arguments:
- event: the Event
"""
# Ignore text deletions from non-focused objects, unless the
# currently focused object is the parent of the object from which
# text was deleted
#
if (event.source != a11y.focusedObject) \
and (event.source.parent != a11y.focusedObject):
pass
else:
default.brlUpdateText (event.source)
|
Call default.brlUpdateText instead of brlUpdateText (which was undefined)
|
Call default.brlUpdateText instead of brlUpdateText (which was undefined)
|
Python
|
lgpl-2.1
|
GNOME/orca,h4ck3rm1k3/orca-sonar,pvagner/orca,h4ck3rm1k3/orca-sonar,GNOME/orca,pvagner/orca,h4ck3rm1k3/orca-sonar,chrys87/orca-beep,chrys87/orca-beep,pvagner/orca,pvagner/orca,chrys87/orca-beep,GNOME/orca,chrys87/orca-beep,GNOME/orca
|
python
|
## Code Before:
import a11y
import speech
def onTextInserted (e):
if e.source.role != "terminal":
return
speech.say ("default", e.any_data)
def onTextDeleted (event):
"""Called whenever text is deleted from an object.
Arguments:
- event: the Event
"""
# Ignore text deletions from non-focused objects, unless the
# currently focused object is the parent of the object from which
# text was deleted
#
if (event.source != a11y.focusedObject) \
and (event.source.parent != a11y.focusedObject):
pass
else:
brlUpdateText (event.source)
## Instruction:
Call default.brlUpdateText instead of brlUpdateText (which was undefined)
## Code After:
import a11y
import speech
import default
def onTextInserted (e):
if e.source.role != "terminal":
return
speech.say ("default", e.any_data)
def onTextDeleted (event):
"""Called whenever text is deleted from an object.
Arguments:
- event: the Event
"""
# Ignore text deletions from non-focused objects, unless the
# currently focused object is the parent of the object from which
# text was deleted
#
if (event.source != a11y.focusedObject) \
and (event.source.parent != a11y.focusedObject):
pass
else:
default.brlUpdateText (event.source)
|
// ... existing code ...
import a11y
import speech
import default
def onTextInserted (e):
if e.source.role != "terminal":
// ... modified code ...
and (event.source.parent != a11y.focusedObject):
pass
else:
default.brlUpdateText (event.source)
// ... rest of the code ...
|
3c1f2c46485aee91dbf4c61b7b096c2cc4b28c06
|
kcdc3/apps/pinata/urls.py
|
kcdc3/apps/pinata/urls.py
|
from django.conf.urls import patterns, include, url
from models import Page
urlpatterns = patterns('kcdc3.apps.pinata.views',
url(r'^$', 'page_view'),
url(r'^[0-9a-zA-Z_-]+/$', 'page_view'),
)
|
from django.conf.urls import patterns, include, url
from models import Page
urlpatterns = patterns('kcdc3.apps.pinata.views',
url(r'^$', 'page_view'),
url(r'^[0-9a-zA-Z_-]+/$', 'page_view'),
url(r'^[0-9a-zA-Z_-]+/[0-9a-zA-Z_-]+/$', 'page_view'),
# Surely there's a better way to handle paths that contain several slashes
)
|
Allow three-deep paths in Pinata
|
Allow three-deep paths in Pinata
|
Python
|
mit
|
knowledgecommonsdc/kcdc3,knowledgecommonsdc/kcdc3,knowledgecommonsdc/kcdc3,knowledgecommonsdc/kcdc3,knowledgecommonsdc/kcdc3,knowledgecommonsdc/kcdc3
|
python
|
## Code Before:
from django.conf.urls import patterns, include, url
from models import Page
urlpatterns = patterns('kcdc3.apps.pinata.views',
url(r'^$', 'page_view'),
url(r'^[0-9a-zA-Z_-]+/$', 'page_view'),
)
## Instruction:
Allow three-deep paths in Pinata
## Code After:
from django.conf.urls import patterns, include, url
from models import Page
urlpatterns = patterns('kcdc3.apps.pinata.views',
url(r'^$', 'page_view'),
url(r'^[0-9a-zA-Z_-]+/$', 'page_view'),
url(r'^[0-9a-zA-Z_-]+/[0-9a-zA-Z_-]+/$', 'page_view'),
# Surely there's a better way to handle paths that contain several slashes
)
|
...
url(r'^$', 'page_view'),
url(r'^[0-9a-zA-Z_-]+/$', 'page_view'),
url(r'^[0-9a-zA-Z_-]+/[0-9a-zA-Z_-]+/$', 'page_view'),
# Surely there's a better way to handle paths that contain several slashes
)
...
|
47c64794ce46dad12edd32d31b164e97e9ed4936
|
src/main/java/edu/northwestern/bioinformatics/studycalendar/dao/PeriodDao.java
|
src/main/java/edu/northwestern/bioinformatics/studycalendar/dao/PeriodDao.java
|
package edu.northwestern.bioinformatics.studycalendar.dao;
import edu.northwestern.bioinformatics.studycalendar.domain.Period;
import org.springframework.transaction.annotation.Transactional;
/**
* @author Rhett Sutphin
*/
@Transactional(readOnly = true)
public class PeriodDao extends StudyCalendarMutableDomainObjectDao<Period> {
@Override
public Class<Period> domainClass() {
return Period.class;
}
public void evict(Period period) {
getHibernateTemplate().evict(period);
}
public void delete(Period period) {
getHibernateTemplate().delete(period);
}
}
|
package edu.northwestern.bioinformatics.studycalendar.dao;
import edu.northwestern.bioinformatics.studycalendar.domain.Period;
import org.springframework.transaction.annotation.Transactional;
/**
* @author Rhett Sutphin
*/
@Transactional(readOnly = true)
public class PeriodDao extends StudyCalendarMutableDomainObjectDao<Period> {
@Override
public Class<Period> domainClass() {
return Period.class;
}
/**
* To manage caching of a period, this method will remove the period specified from hibernate's first level cache
*
* @param period the period to remove from the cache
*/
public void evict(Period period) {
getHibernateTemplate().evict(period);
}
/**
* Deletes a period
*
* @param period the period to delete
*/
public void delete(Period period) {
getHibernateTemplate().delete(period);
}
}
|
Add javadoc to period dao.
|
Add javadoc to period dao.
|
Java
|
bsd-3-clause
|
NCIP/psc,NCIP/psc,NCIP/psc,NCIP/psc
|
java
|
## Code Before:
package edu.northwestern.bioinformatics.studycalendar.dao;
import edu.northwestern.bioinformatics.studycalendar.domain.Period;
import org.springframework.transaction.annotation.Transactional;
/**
* @author Rhett Sutphin
*/
@Transactional(readOnly = true)
public class PeriodDao extends StudyCalendarMutableDomainObjectDao<Period> {
@Override
public Class<Period> domainClass() {
return Period.class;
}
public void evict(Period period) {
getHibernateTemplate().evict(period);
}
public void delete(Period period) {
getHibernateTemplate().delete(period);
}
}
## Instruction:
Add javadoc to period dao.
## Code After:
package edu.northwestern.bioinformatics.studycalendar.dao;
import edu.northwestern.bioinformatics.studycalendar.domain.Period;
import org.springframework.transaction.annotation.Transactional;
/**
* @author Rhett Sutphin
*/
@Transactional(readOnly = true)
public class PeriodDao extends StudyCalendarMutableDomainObjectDao<Period> {
@Override
public Class<Period> domainClass() {
return Period.class;
}
/**
* To manage caching of a period, this method will remove the period specified from hibernate's first level cache
*
* @param period the period to remove from the cache
*/
public void evict(Period period) {
getHibernateTemplate().evict(period);
}
/**
* Deletes a period
*
* @param period the period to delete
*/
public void delete(Period period) {
getHibernateTemplate().delete(period);
}
}
|
// ... existing code ...
return Period.class;
}
/**
* To manage caching of a period, this method will remove the period specified from hibernate's first level cache
*
* @param period the period to remove from the cache
*/
public void evict(Period period) {
getHibernateTemplate().evict(period);
}
/**
* Deletes a period
*
* @param period the period to delete
*/
public void delete(Period period) {
getHibernateTemplate().delete(period);
}
// ... rest of the code ...
|
9f13b732b68c62a90bbfd2f3fc9ad0c93d54f1e7
|
likes/utils.py
|
likes/utils.py
|
from likes.signals import likes_enabled_test, can_vote_test
from likes.exceptions import LikesNotEnabledException, CannotVoteException
def _votes_enabled(obj):
"""See if voting is enabled on the class. Made complicated because
secretballot.enable_voting_on takes parameters to set attribute names, so
we can't safely check for eg. "add_vote" presence on obj. The safest bet is
to check for the 'votes' attribute.
The correct approach is to contact the secretballot developers and ask them
to set some unique marker on a class that can be voted on."""
return hasattr(obj.__class__, 'votes')
def likes_enabled(obj, request):
if not _votes_enabled(obj):
return False, None
try:
likes_enabled_test.send(obj, request=request)
except LikesNotEnabledException:
return False
return True
def can_vote(obj, user, request):
if not _votes_enabled(obj):
return False
try:
can_vote_test.send(obj, user=user, request=request)
except CannotVoteException:
return False
return True
|
from secretballot.models import Vote
from likes.signals import likes_enabled_test, can_vote_test
from likes.exceptions import LikesNotEnabledException, CannotVoteException
def _votes_enabled(obj):
"""See if voting is enabled on the class. Made complicated because
secretballot.enable_voting_on takes parameters to set attribute names, so
we can't safely check for eg. "add_vote" presence on obj. The safest bet is
to check for the 'votes' attribute.
The correct approach is to contact the secretballot developers and ask them
to set some unique marker on a class that can be voted on."""
return hasattr(obj.__class__, 'votes')
def likes_enabled(obj, request):
if not _votes_enabled(obj):
return False, None
try:
likes_enabled_test.send(obj, request=request)
except LikesNotEnabledException:
return False
return True
def can_vote(obj, user, request):
if not _votes_enabled(obj):
return False
# Common predicate
if Vote.objects.filter(
object_id=modelbase_obj.id,
token=request.secretballot_token
).count() != 0:
return False
try:
can_vote_test.send(obj, user=user, request=request)
except CannotVoteException:
return False
return True
|
Add common predicate for can_vote
|
Add common predicate for can_vote
|
Python
|
bsd-3-clause
|
sandow-digital/django-likes,just-work/django-likes,Afnarel/django-likes,Afnarel/django-likes,just-work/django-likes,chuck211991/django-likes,Afnarel/django-likes,sandow-digital/django-likes,chuck211991/django-likes,chuck211991/django-likes,just-work/django-likes
|
python
|
## Code Before:
from likes.signals import likes_enabled_test, can_vote_test
from likes.exceptions import LikesNotEnabledException, CannotVoteException
def _votes_enabled(obj):
"""See if voting is enabled on the class. Made complicated because
secretballot.enable_voting_on takes parameters to set attribute names, so
we can't safely check for eg. "add_vote" presence on obj. The safest bet is
to check for the 'votes' attribute.
The correct approach is to contact the secretballot developers and ask them
to set some unique marker on a class that can be voted on."""
return hasattr(obj.__class__, 'votes')
def likes_enabled(obj, request):
if not _votes_enabled(obj):
return False, None
try:
likes_enabled_test.send(obj, request=request)
except LikesNotEnabledException:
return False
return True
def can_vote(obj, user, request):
if not _votes_enabled(obj):
return False
try:
can_vote_test.send(obj, user=user, request=request)
except CannotVoteException:
return False
return True
## Instruction:
Add common predicate for can_vote
## Code After:
from secretballot.models import Vote
from likes.signals import likes_enabled_test, can_vote_test
from likes.exceptions import LikesNotEnabledException, CannotVoteException
def _votes_enabled(obj):
"""See if voting is enabled on the class. Made complicated because
secretballot.enable_voting_on takes parameters to set attribute names, so
we can't safely check for eg. "add_vote" presence on obj. The safest bet is
to check for the 'votes' attribute.
The correct approach is to contact the secretballot developers and ask them
to set some unique marker on a class that can be voted on."""
return hasattr(obj.__class__, 'votes')
def likes_enabled(obj, request):
if not _votes_enabled(obj):
return False, None
try:
likes_enabled_test.send(obj, request=request)
except LikesNotEnabledException:
return False
return True
def can_vote(obj, user, request):
if not _votes_enabled(obj):
return False
# Common predicate
if Vote.objects.filter(
object_id=modelbase_obj.id,
token=request.secretballot_token
).count() != 0:
return False
try:
can_vote_test.send(obj, user=user, request=request)
except CannotVoteException:
return False
return True
|
# ... existing code ...
from secretballot.models import Vote
from likes.signals import likes_enabled_test, can_vote_test
from likes.exceptions import LikesNotEnabledException, CannotVoteException
# ... modified code ...
def can_vote(obj, user, request):
if not _votes_enabled(obj):
return False
# Common predicate
if Vote.objects.filter(
object_id=modelbase_obj.id,
token=request.secretballot_token
).count() != 0:
return False
try:
can_vote_test.send(obj, user=user, request=request)
except CannotVoteException:
# ... rest of the code ...
|
05a03b02ca0a0d80542a74d1e9cc55d794dca595
|
src/chrono/core/ChChrono.h
|
src/chrono/core/ChChrono.h
|
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
#ifndef CHCHRONO_H
#define CHCHRONO_H
// Definition of the main module and sub-modules in the main Chrono library
/**
@defgroup chrono Chrono::Engine
@brief Core Functionality
@{
@defgroup chrono_physics Physics objects
@defgroup chrono_geometry Geometric objects
@defgroup chrono_collision Collision objects
@defgroup chrono_assets Asset objects
@defgroup chrono_solver Solver
@defgroup chrono_timestepper Time integrators
@defgroup chrono_functions Function objects
@defgroup chrono_particles Particle factory
@defgroup chrono_serialization Serialization
@defgroup chrono_utils Utility classes
@defgroup chrono_fea Finite Element Analysis
@{
@defgroup fea_nodes Nodes
@defgroup fea_elements Elements
@defgroup fea_constraints Constraints
@defgroup fea_contact Contact
@defgroup fea_math Mathematical support
@defgroup fea_utils Utility classes
@}
@}
*/
/// @addtogroup chrono
/// @{
/// This is the main namespace for the Chrono package.
namespace chrono {}
/// @} chrono
#endif
|
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
#ifndef CHCHRONO_H
#define CHCHRONO_H
// Definition of the main module and sub-modules in the main Chrono library
/**
@defgroup chrono Chrono::Engine
@brief Core Functionality
@{
@defgroup chrono_physics Physics objects
@defgroup chrono_geometry Geometric objects
@defgroup chrono_collision Collision objects
@defgroup chrono_assets Asset objects
@defgroup chrono_solver Solver
@defgroup chrono_timestepper Time integrators
@defgroup chrono_functions Function objects
@defgroup chrono_particles Particle factory
@defgroup chrono_serialization Serialization
@defgroup chrono_utils Utility classes
@defgroup chrono_fea Finite Element Analysis
@{
@defgroup fea_nodes Nodes
@defgroup fea_elements Elements
@defgroup fea_constraints Constraints
@defgroup fea_contact Contact
@defgroup fea_math Mathematical support
@defgroup fea_utils Utility classes
@}
@}
*/
/// @addtogroup chrono
/// @{
/// Main namespace for the Chrono package.
namespace chrono {
/// Namespace for FEA classes.
namespace fea {}
}
/// @} chrono
#endif
|
Add description of the `chrono::fea` namespace
|
Add description of the `chrono::fea` namespace
|
C
|
bsd-3-clause
|
rserban/chrono,projectchrono/chrono,projectchrono/chrono,Milad-Rakhsha/chrono,dariomangoni/chrono,Milad-Rakhsha/chrono,dariomangoni/chrono,rserban/chrono,projectchrono/chrono,rserban/chrono,rserban/chrono,rserban/chrono,dariomangoni/chrono,Milad-Rakhsha/chrono,dariomangoni/chrono,rserban/chrono,projectchrono/chrono,dariomangoni/chrono,projectchrono/chrono,Milad-Rakhsha/chrono,projectchrono/chrono,rserban/chrono,dariomangoni/chrono,Milad-Rakhsha/chrono,Milad-Rakhsha/chrono
|
c
|
## Code Before:
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
#ifndef CHCHRONO_H
#define CHCHRONO_H
// Definition of the main module and sub-modules in the main Chrono library
/**
@defgroup chrono Chrono::Engine
@brief Core Functionality
@{
@defgroup chrono_physics Physics objects
@defgroup chrono_geometry Geometric objects
@defgroup chrono_collision Collision objects
@defgroup chrono_assets Asset objects
@defgroup chrono_solver Solver
@defgroup chrono_timestepper Time integrators
@defgroup chrono_functions Function objects
@defgroup chrono_particles Particle factory
@defgroup chrono_serialization Serialization
@defgroup chrono_utils Utility classes
@defgroup chrono_fea Finite Element Analysis
@{
@defgroup fea_nodes Nodes
@defgroup fea_elements Elements
@defgroup fea_constraints Constraints
@defgroup fea_contact Contact
@defgroup fea_math Mathematical support
@defgroup fea_utils Utility classes
@}
@}
*/
/// @addtogroup chrono
/// @{
/// This is the main namespace for the Chrono package.
namespace chrono {}
/// @} chrono
#endif
## Instruction:
Add description of the `chrono::fea` namespace
## Code After:
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
#ifndef CHCHRONO_H
#define CHCHRONO_H
// Definition of the main module and sub-modules in the main Chrono library
/**
@defgroup chrono Chrono::Engine
@brief Core Functionality
@{
@defgroup chrono_physics Physics objects
@defgroup chrono_geometry Geometric objects
@defgroup chrono_collision Collision objects
@defgroup chrono_assets Asset objects
@defgroup chrono_solver Solver
@defgroup chrono_timestepper Time integrators
@defgroup chrono_functions Function objects
@defgroup chrono_particles Particle factory
@defgroup chrono_serialization Serialization
@defgroup chrono_utils Utility classes
@defgroup chrono_fea Finite Element Analysis
@{
@defgroup fea_nodes Nodes
@defgroup fea_elements Elements
@defgroup fea_constraints Constraints
@defgroup fea_contact Contact
@defgroup fea_math Mathematical support
@defgroup fea_utils Utility classes
@}
@}
*/
/// @addtogroup chrono
/// @{
/// Main namespace for the Chrono package.
namespace chrono {
/// Namespace for FEA classes.
namespace fea {}
}
/// @} chrono
#endif
|
# ... existing code ...
/// @addtogroup chrono
/// @{
/// Main namespace for the Chrono package.
namespace chrono {
/// Namespace for FEA classes.
namespace fea {}
}
/// @} chrono
# ... rest of the code ...
|
dec7c3ed334e21bb0b4768d720cd1cf8fdf6b50a
|
ethereumj-core/src/test/java/org/ethereum/net/shh/TopicTest.java
|
ethereumj-core/src/test/java/org/ethereum/net/shh/TopicTest.java
|
package org.ethereum.net.shh;
import org.junit.Test;
import org.spongycastle.util.encoders.Hex;
import static org.junit.Assert.assertEquals;
public class TopicTest {
@Test
public void test1(){
Topic topic = new Topic("cow");
assertEquals("c85ef7d7", Hex.toHexString(topic.getBytes()));
}
@Test
public void test2(){
Topic topic = new Topic("cowcowcow");
assertEquals("25068349", Hex.toHexString(topic.getBytes()));
}
}
|
package org.ethereum.net.shh;
import org.junit.Test;
import org.spongycastle.util.encoders.Hex;
import static org.junit.Assert.assertEquals;
public class TopicTest {
@Test
public void test1(){
Topic topic = new Topic("cow");
assertEquals("91887637", Hex.toHexString(topic.getBytes()));
}
@Test
public void test2(){
Topic topic = new Topic("cowcowcow");
assertEquals("3a6de614", Hex.toHexString(topic.getBytes()));
}
}
|
Change test to conform version 3 topic encoding
|
Change test to conform version 3 topic encoding
|
Java
|
mit
|
loxal/FreeEthereum,chengtalent/ethereumj,loxal/FreeEthereum,loxal/ethereumj,loxal/FreeEthereum,caxqueiroz/ethereumj
|
java
|
## Code Before:
package org.ethereum.net.shh;
import org.junit.Test;
import org.spongycastle.util.encoders.Hex;
import static org.junit.Assert.assertEquals;
public class TopicTest {
@Test
public void test1(){
Topic topic = new Topic("cow");
assertEquals("c85ef7d7", Hex.toHexString(topic.getBytes()));
}
@Test
public void test2(){
Topic topic = new Topic("cowcowcow");
assertEquals("25068349", Hex.toHexString(topic.getBytes()));
}
}
## Instruction:
Change test to conform version 3 topic encoding
## Code After:
package org.ethereum.net.shh;
import org.junit.Test;
import org.spongycastle.util.encoders.Hex;
import static org.junit.Assert.assertEquals;
public class TopicTest {
@Test
public void test1(){
Topic topic = new Topic("cow");
assertEquals("91887637", Hex.toHexString(topic.getBytes()));
}
@Test
public void test2(){
Topic topic = new Topic("cowcowcow");
assertEquals("3a6de614", Hex.toHexString(topic.getBytes()));
}
}
|
...
@Test
public void test1(){
Topic topic = new Topic("cow");
assertEquals("91887637", Hex.toHexString(topic.getBytes()));
}
@Test
public void test2(){
Topic topic = new Topic("cowcowcow");
assertEquals("3a6de614", Hex.toHexString(topic.getBytes()));
}
}
...
|
332ed6c26830bf2ac8e154948c4c58b745d5b5ae
|
cosmo_tester/test_suites/snapshots/conftest.py
|
cosmo_tester/test_suites/snapshots/conftest.py
|
import pytest
from cosmo_tester.framework.test_hosts import Hosts, get_image
from cosmo_tester.test_suites.snapshots import get_multi_tenant_versions_list
@pytest.fixture(scope='function', params=get_multi_tenant_versions_list())
def hosts(request, ssh_key, module_tmpdir, test_config, logger):
hosts = Hosts(
ssh_key, module_tmpdir,
test_config, logger, request,
number_of_instances=4,
)
hosts.instances[0] = get_image(request.param, test_config)
hosts.instances[1] = get_image('master', test_config)
hosts.instances[2] = get_image('centos', test_config)
hosts.instances[3] = get_image('centos', test_config)
win_vm = hosts.instances[2]
win_vm.prepare_for_windows('windows_2012')
lin_vm = hosts.instances[3]
lin_vm.image_name = test_config.platform['centos_7_image']
lin_vm.username = test_config['test_os_usernames']['centos_7']
hosts.create()
try:
yield hosts
finally:
hosts.destroy()
|
import pytest
from cosmo_tester.framework.test_hosts import Hosts, get_image
from cosmo_tester.test_suites.snapshots import get_multi_tenant_versions_list
@pytest.fixture(scope='function', params=get_multi_tenant_versions_list())
def hosts(request, ssh_key, module_tmpdir, test_config, logger):
hosts = Hosts(
ssh_key, module_tmpdir,
test_config, logger, request,
number_of_instances=4,
)
hosts.instances[0] = get_image(request.param, test_config)
hosts.instances[1] = get_image('master', test_config)
hosts.instances[2] = get_image('centos', test_config)
hosts.instances[3] = get_image('centos', test_config)
win_vm = hosts.instances[2]
win_vm.prepare_for_windows('windows_2012')
lin_vm = hosts.instances[3]
lin_vm.image_name = test_config.platform['centos_7_image']
lin_vm.username = test_config['test_os_usernames']['centos_7']
hosts.create()
try:
if request.param in ['5.0.5', '5.1.0']:
old_mgr = hosts.instances[0]
old_mgr.wait_for_manager()
old_mgr.run_command('mv /etc/cloudify/ssl/rabbitmq{_,-}cert.pem',
use_sudo=True)
old_mgr.run_command('mv /etc/cloudify/ssl/rabbitmq{_,-}key.pem',
use_sudo=True)
old_mgr.run_command(
'chown rabbitmq. /etc/cloudify/ssl/rabbitmq-*', use_sudo=True)
old_mgr.run_command('systemctl restart cloudify-rabbitmq',
use_sudo=True)
yield hosts
finally:
hosts.destroy()
|
Use correct rabbit certs on old IP setter
|
Use correct rabbit certs on old IP setter
|
Python
|
apache-2.0
|
cloudify-cosmo/cloudify-system-tests,cloudify-cosmo/cloudify-system-tests
|
python
|
## Code Before:
import pytest
from cosmo_tester.framework.test_hosts import Hosts, get_image
from cosmo_tester.test_suites.snapshots import get_multi_tenant_versions_list
@pytest.fixture(scope='function', params=get_multi_tenant_versions_list())
def hosts(request, ssh_key, module_tmpdir, test_config, logger):
hosts = Hosts(
ssh_key, module_tmpdir,
test_config, logger, request,
number_of_instances=4,
)
hosts.instances[0] = get_image(request.param, test_config)
hosts.instances[1] = get_image('master', test_config)
hosts.instances[2] = get_image('centos', test_config)
hosts.instances[3] = get_image('centos', test_config)
win_vm = hosts.instances[2]
win_vm.prepare_for_windows('windows_2012')
lin_vm = hosts.instances[3]
lin_vm.image_name = test_config.platform['centos_7_image']
lin_vm.username = test_config['test_os_usernames']['centos_7']
hosts.create()
try:
yield hosts
finally:
hosts.destroy()
## Instruction:
Use correct rabbit certs on old IP setter
## Code After:
import pytest
from cosmo_tester.framework.test_hosts import Hosts, get_image
from cosmo_tester.test_suites.snapshots import get_multi_tenant_versions_list
@pytest.fixture(scope='function', params=get_multi_tenant_versions_list())
def hosts(request, ssh_key, module_tmpdir, test_config, logger):
hosts = Hosts(
ssh_key, module_tmpdir,
test_config, logger, request,
number_of_instances=4,
)
hosts.instances[0] = get_image(request.param, test_config)
hosts.instances[1] = get_image('master', test_config)
hosts.instances[2] = get_image('centos', test_config)
hosts.instances[3] = get_image('centos', test_config)
win_vm = hosts.instances[2]
win_vm.prepare_for_windows('windows_2012')
lin_vm = hosts.instances[3]
lin_vm.image_name = test_config.platform['centos_7_image']
lin_vm.username = test_config['test_os_usernames']['centos_7']
hosts.create()
try:
if request.param in ['5.0.5', '5.1.0']:
old_mgr = hosts.instances[0]
old_mgr.wait_for_manager()
old_mgr.run_command('mv /etc/cloudify/ssl/rabbitmq{_,-}cert.pem',
use_sudo=True)
old_mgr.run_command('mv /etc/cloudify/ssl/rabbitmq{_,-}key.pem',
use_sudo=True)
old_mgr.run_command(
'chown rabbitmq. /etc/cloudify/ssl/rabbitmq-*', use_sudo=True)
old_mgr.run_command('systemctl restart cloudify-rabbitmq',
use_sudo=True)
yield hosts
finally:
hosts.destroy()
|
# ... existing code ...
hosts.create()
try:
if request.param in ['5.0.5', '5.1.0']:
old_mgr = hosts.instances[0]
old_mgr.wait_for_manager()
old_mgr.run_command('mv /etc/cloudify/ssl/rabbitmq{_,-}cert.pem',
use_sudo=True)
old_mgr.run_command('mv /etc/cloudify/ssl/rabbitmq{_,-}key.pem',
use_sudo=True)
old_mgr.run_command(
'chown rabbitmq. /etc/cloudify/ssl/rabbitmq-*', use_sudo=True)
old_mgr.run_command('systemctl restart cloudify-rabbitmq',
use_sudo=True)
yield hosts
finally:
hosts.destroy()
# ... rest of the code ...
|
295285a0a13207dac276da6e3b41e2057a7efee8
|
test/tests/constant_damper_test/constant_damper_test.py
|
test/tests/constant_damper_test/constant_damper_test.py
|
import tools
def testdirichlet(dofs=0, np=0, n_threads=0):
tools.executeAppAndDiff(__file__,'constant_damper_test.i',['out.e'], dofs, np, n_threads)
|
import tools
def testdamper(dofs=0, np=0, n_threads=0):
tools.executeAppAndDiff(__file__,'constant_damper_test.i',['out.e'], dofs, np, n_threads)
# Make sure the damping causes 8 NL steps
def testverifydamping(dofs=0, np=0, n_threads=0):
tools.executeAppExpectError(__file__,'constant_damper_test.i','NL step\s+8')
|
Verify additional steps in damping problem
|
Verify additional steps in damping problem
r4199
|
Python
|
lgpl-2.1
|
jinmm1992/moose,stimpsonsg/moose,andrsd/moose,mellis13/moose,jinmm1992/moose,permcody/moose,liuwenf/moose,harterj/moose,jhbradley/moose,nuclear-wizard/moose,jhbradley/moose,adamLange/moose,roystgnr/moose,SudiptaBiswas/moose,katyhuff/moose,harterj/moose,roystgnr/moose,zzyfisherman/moose,roystgnr/moose,jasondhales/moose,katyhuff/moose,lindsayad/moose,dschwen/moose,jasondhales/moose,shanestafford/moose,cpritam/moose,raghavaggarwal/moose,andrsd/moose,bwspenc/moose,backmari/moose,joshua-cogliati-inl/moose,waxmanr/moose,milljm/moose,capitalaslash/moose,bwspenc/moose,zzyfisherman/moose,danielru/moose,apc-llc/moose,liuwenf/moose,yipenggao/moose,roystgnr/moose,markr622/moose,YaqiWang/moose,waxmanr/moose,idaholab/moose,capitalaslash/moose,jiangwen84/moose,milljm/moose,danielru/moose,YaqiWang/moose,adamLange/moose,jiangwen84/moose,lindsayad/moose,bwspenc/moose,jasondhales/moose,permcody/moose,sapitts/moose,backmari/moose,nuclear-wizard/moose,tonkmr/moose,jbair34/moose,sapitts/moose,markr622/moose,laagesen/moose,WilkAndy/moose,jinmm1992/moose,jbair34/moose,markr622/moose,mellis13/moose,stimpsonsg/moose,jiangwen84/moose,Chuban/moose,harterj/moose,zzyfisherman/moose,tonkmr/moose,WilkAndy/moose,waxmanr/moose,giopastor/moose,Chuban/moose,joshua-cogliati-inl/moose,xy515258/moose,bwspenc/moose,shanestafford/moose,markr622/moose,tonkmr/moose,giopastor/moose,andrsd/moose,danielru/moose,cpritam/moose,idaholab/moose,dschwen/moose,stimpsonsg/moose,katyhuff/moose,tonkmr/moose,WilkAndy/moose,Chuban/moose,laagesen/moose,idaholab/moose,shanestafford/moose,dschwen/moose,lindsayad/moose,adamLange/moose,wgapl/moose,zzyfisherman/moose,backmari/moose,danielru/moose,apc-llc/moose,tonkmr/moose,sapitts/moose,jessecarterMOOSE/moose,cpritam/moose,laagesen/moose,milljm/moose,waxmanr/moose,SudiptaBiswas/moose,shanestafford/moose,backmari/moose,mellis13/moose,raghavaggarwal/moose,friedmud/moose,cpritam/moose,SudiptaBiswas/moose,xy515258/moose,milljm/moose,WilkAndy/moose,jessecarterMOOSE/moose,stimpsonsg/moose,friedmud/moose,wgapl/moose,jinmm1992/moose,laagesen/moose,YaqiWang/moose,friedmud/moose,jbair34/moose,dschwen/moose,yipenggao/moose,jhbradley/moose,wgapl/moose,yipenggao/moose,liuwenf/moose,Chuban/moose,roystgnr/moose,idaholab/moose,nuclear-wizard/moose,SudiptaBiswas/moose,mellis13/moose,kasra83/moose,shanestafford/moose,jessecarterMOOSE/moose,liuwenf/moose,jasondhales/moose,jhbradley/moose,cpritam/moose,xy515258/moose,wgapl/moose,WilkAndy/moose,cpritam/moose,WilkAndy/moose,dschwen/moose,shanestafford/moose,zzyfisherman/moose,raghavaggarwal/moose,nuclear-wizard/moose,zzyfisherman/moose,friedmud/moose,roystgnr/moose,permcody/moose,sapitts/moose,lindsayad/moose,jiangwen84/moose,jbair34/moose,giopastor/moose,tonkmr/moose,capitalaslash/moose,YaqiWang/moose,laagesen/moose,jessecarterMOOSE/moose,joshua-cogliati-inl/moose,milljm/moose,giopastor/moose,sapitts/moose,raghavaggarwal/moose,bwspenc/moose,andrsd/moose,idaholab/moose,liuwenf/moose,kasra83/moose,permcody/moose,apc-llc/moose,xy515258/moose,roystgnr/moose,kasra83/moose,jessecarterMOOSE/moose,lindsayad/moose,kasra83/moose,liuwenf/moose,harterj/moose,capitalaslash/moose,yipenggao/moose,harterj/moose,katyhuff/moose,apc-llc/moose,joshua-cogliati-inl/moose,andrsd/moose,adamLange/moose,SudiptaBiswas/moose
|
python
|
## Code Before:
import tools
def testdirichlet(dofs=0, np=0, n_threads=0):
tools.executeAppAndDiff(__file__,'constant_damper_test.i',['out.e'], dofs, np, n_threads)
## Instruction:
Verify additional steps in damping problem
r4199
## Code After:
import tools
def testdamper(dofs=0, np=0, n_threads=0):
tools.executeAppAndDiff(__file__,'constant_damper_test.i',['out.e'], dofs, np, n_threads)
# Make sure the damping causes 8 NL steps
def testverifydamping(dofs=0, np=0, n_threads=0):
tools.executeAppExpectError(__file__,'constant_damper_test.i','NL step\s+8')
|
# ... existing code ...
import tools
def testdamper(dofs=0, np=0, n_threads=0):
tools.executeAppAndDiff(__file__,'constant_damper_test.i',['out.e'], dofs, np, n_threads)
# Make sure the damping causes 8 NL steps
def testverifydamping(dofs=0, np=0, n_threads=0):
tools.executeAppExpectError(__file__,'constant_damper_test.i','NL step\s+8')
# ... rest of the code ...
|
fc3f2e2f9fdf8a19756bbf8b5bd1442b71ac3a87
|
scrapi/settings/__init__.py
|
scrapi/settings/__init__.py
|
import logging
from raven import Client
from fluent import sender
from raven.contrib.celery import register_signal
from scrapi.settings.defaults import *
from scrapi.settings.local import *
logging.basicConfig(level=logging.INFO)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.WARNING)
if USE_FLUENTD:
sender.setup(**FLUENTD_ARGS)
if SENTRY_DSN:
client = Client(SENTRY_DSN)
register_signal(client)
CELERY_ENABLE_UTC = True
CELERY_RESULT_BACKEND = None
CELERY_TASK_SERIALIZER = 'pickle'
CELERY_ACCEPT_CONTENT = ['pickle']
CELERY_RESULT_SERIALIZER = 'pickle'
CELERY_IMPORTS = ('scrapi.tasks', )
|
import logging
from raven import Client
from fluent import sender
from raven.contrib.celery import register_signal
from scrapi.settings.defaults import *
from scrapi.settings.local import *
logging.basicConfig(level=logging.INFO)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.WARNING)
if USE_FLUENTD:
sender.setup(**FLUENTD_ARGS)
if SENTRY_DSN:
client = Client(SENTRY_DSN)
register_signal(client)
CELERY_ENABLE_UTC = True
CELERY_RESULT_BACKEND = None
CELERY_TASK_SERIALIZER = 'pickle'
CELERY_ACCEPT_CONTENT = ['pickle']
CELERY_RESULT_SERIALIZER = 'pickle'
CELERY_IMPORTS = ('scrapi.tasks', 'scrapi.migrations')
|
Add new place to look for celery tasks
|
Add new place to look for celery tasks
|
Python
|
apache-2.0
|
CenterForOpenScience/scrapi,erinspace/scrapi,felliott/scrapi,mehanig/scrapi,fabianvf/scrapi,mehanig/scrapi,felliott/scrapi,jeffreyliu3230/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi,alexgarciac/scrapi,fabianvf/scrapi,ostwald/scrapi,icereval/scrapi
|
python
|
## Code Before:
import logging
from raven import Client
from fluent import sender
from raven.contrib.celery import register_signal
from scrapi.settings.defaults import *
from scrapi.settings.local import *
logging.basicConfig(level=logging.INFO)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.WARNING)
if USE_FLUENTD:
sender.setup(**FLUENTD_ARGS)
if SENTRY_DSN:
client = Client(SENTRY_DSN)
register_signal(client)
CELERY_ENABLE_UTC = True
CELERY_RESULT_BACKEND = None
CELERY_TASK_SERIALIZER = 'pickle'
CELERY_ACCEPT_CONTENT = ['pickle']
CELERY_RESULT_SERIALIZER = 'pickle'
CELERY_IMPORTS = ('scrapi.tasks', )
## Instruction:
Add new place to look for celery tasks
## Code After:
import logging
from raven import Client
from fluent import sender
from raven.contrib.celery import register_signal
from scrapi.settings.defaults import *
from scrapi.settings.local import *
logging.basicConfig(level=logging.INFO)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.WARNING)
if USE_FLUENTD:
sender.setup(**FLUENTD_ARGS)
if SENTRY_DSN:
client = Client(SENTRY_DSN)
register_signal(client)
CELERY_ENABLE_UTC = True
CELERY_RESULT_BACKEND = None
CELERY_TASK_SERIALIZER = 'pickle'
CELERY_ACCEPT_CONTENT = ['pickle']
CELERY_RESULT_SERIALIZER = 'pickle'
CELERY_IMPORTS = ('scrapi.tasks', 'scrapi.migrations')
|
# ... existing code ...
CELERY_TASK_SERIALIZER = 'pickle'
CELERY_ACCEPT_CONTENT = ['pickle']
CELERY_RESULT_SERIALIZER = 'pickle'
CELERY_IMPORTS = ('scrapi.tasks', 'scrapi.migrations')
# ... rest of the code ...
|
005d74dcb1f1f3e576af71e7cb3fb1e1d6d4df08
|
scripts/lib/paths.py
|
scripts/lib/paths.py
|
details_source = './source/details/'
xml_source = './source/raw_xml/'
term_dest = './courses/terms/'
course_dest = './source/courses/'
info_path = './courses/info.json'
mappings_path = './related-data/generated/'
handmade_path = './related-data/handmade/'
def find_details_subdir(clbid):
str_clbid = str(clbid).zfill(10)
n_thousand = int(int(clbid) / 1000)
thousands_subdir = (n_thousand * 1000)
return str(thousands_subdir).zfill(5) + '/' + str_clbid
def make_course_path(clbid):
clbid = str(clbid).zfill(10)
course_path = course_dest + find_details_subdir(clbid) + '.json'
return course_path
def make_html_path(clbid):
clbid = str(clbid).zfill(10)
return details_source + find_details_subdir(clbid) + '.html'
def make_xml_term_path(term):
return xml_source + str(term) + '.xml'
|
details_source = './source/details/'
xml_source = './source/raw_xml/'
term_dest = './courses/terms/'
course_dest = './source/courses/'
info_path = './courses/info.json'
mappings_path = './related-data/generated/'
handmade_path = './related-data/handmade/'
def find_details_subdir(clbid):
str_clbid = str(clbid).zfill(10)
n_thousand = int(int(clbid) / 1000)
thousands_subdir = (n_thousand * 1000)
return str(thousands_subdir).zfill(5) + '/' + str_clbid
def make_course_path(clbid):
clbid = str(clbid).zfill(10)
return course_dest + find_details_subdir(clbid) + '.json'
def make_html_path(clbid):
clbid = str(clbid).zfill(10)
return details_source + find_details_subdir(clbid) + '.html'
def make_xml_term_path(term):
return xml_source + str(term) + '.xml'
|
Remove the allocation of a variable in make_course_path
|
Remove the allocation of a variable in make_course_path
|
Python
|
mit
|
StoDevX/course-data-tools,StoDevX/course-data-tools
|
python
|
## Code Before:
details_source = './source/details/'
xml_source = './source/raw_xml/'
term_dest = './courses/terms/'
course_dest = './source/courses/'
info_path = './courses/info.json'
mappings_path = './related-data/generated/'
handmade_path = './related-data/handmade/'
def find_details_subdir(clbid):
str_clbid = str(clbid).zfill(10)
n_thousand = int(int(clbid) / 1000)
thousands_subdir = (n_thousand * 1000)
return str(thousands_subdir).zfill(5) + '/' + str_clbid
def make_course_path(clbid):
clbid = str(clbid).zfill(10)
course_path = course_dest + find_details_subdir(clbid) + '.json'
return course_path
def make_html_path(clbid):
clbid = str(clbid).zfill(10)
return details_source + find_details_subdir(clbid) + '.html'
def make_xml_term_path(term):
return xml_source + str(term) + '.xml'
## Instruction:
Remove the allocation of a variable in make_course_path
## Code After:
details_source = './source/details/'
xml_source = './source/raw_xml/'
term_dest = './courses/terms/'
course_dest = './source/courses/'
info_path = './courses/info.json'
mappings_path = './related-data/generated/'
handmade_path = './related-data/handmade/'
def find_details_subdir(clbid):
str_clbid = str(clbid).zfill(10)
n_thousand = int(int(clbid) / 1000)
thousands_subdir = (n_thousand * 1000)
return str(thousands_subdir).zfill(5) + '/' + str_clbid
def make_course_path(clbid):
clbid = str(clbid).zfill(10)
return course_dest + find_details_subdir(clbid) + '.json'
def make_html_path(clbid):
clbid = str(clbid).zfill(10)
return details_source + find_details_subdir(clbid) + '.html'
def make_xml_term_path(term):
return xml_source + str(term) + '.xml'
|
# ... existing code ...
def make_course_path(clbid):
clbid = str(clbid).zfill(10)
return course_dest + find_details_subdir(clbid) + '.json'
def make_html_path(clbid):
clbid = str(clbid).zfill(10)
# ... rest of the code ...
|
85a763e3f007a6479c9be36aa18dffe24ea16bfa
|
kaadin-core/src/main/kotlin/ch/frankel/kaadin/Common.kt
|
kaadin-core/src/main/kotlin/ch/frankel/kaadin/Common.kt
|
package ch.frankel.kaadin
import com.vaadin.server.*
fun Sizeable.height(height: String) = setHeight(height)
fun Sizeable.height(height: Float, unit: Sizeable.Unit) = setHeight(height, unit)
fun Sizeable.heightUndefined() = setHeightUndefined()
fun Sizeable.width(width: String) = setWidth(width)
fun Sizeable.width(width: Float, unit: Sizeable.Unit) = setWidth(width, unit)
fun Sizeable.widthUndefined() = setWidthUndefined()
fun Sizeable.size(width: String, height: String) {
width(width)
height(height)
}
fun Sizeable.size(width: Float, height: Float, unit: Sizeable.Unit) {
width(width, unit)
height(height, unit)
}
fun Sizeable.size(width: Float, widthUnit: Sizeable.Unit, height: Float, heightUnit: Sizeable.Unit) {
width(width, widthUnit)
height(height, heightUnit)
}
fun Sizeable.sizeUndefined() = setSizeUndefined()
fun Sizeable.sizeFull() = setSizeFull()
|
package ch.frankel.kaadin
import com.vaadin.server.*
fun Sizeable.height(height: String) = setHeight(height)
fun Sizeable.height(height: Float, unit: Sizeable.Unit) = setHeight(height, unit)
fun Sizeable.height(height: Height) = setHeight(height.size, height.unit)
fun Sizeable.heightUndefined() = setHeightUndefined()
fun Sizeable.width(width: String) = setWidth(width)
fun Sizeable.width(width: Float, unit: Sizeable.Unit) = setWidth(width, unit)
fun Sizeable.width(width: Width) = setWidth(width.size, width.unit)
fun Sizeable.widthUndefined() = setWidthUndefined()
fun Sizeable.size(width: String, height: String) {
width(width)
height(height)
}
fun Sizeable.size(width: Float, height: Float, unit: Sizeable.Unit) {
width(width, unit)
height(height, unit)
}
fun Sizeable.size(width: Float, widthUnit: Sizeable.Unit, height: Float, heightUnit: Sizeable.Unit) {
width(width, widthUnit)
height(height, heightUnit)
}
fun Sizeable.size(width: Width, height: Height) {
width(width)
height(height)
}
fun Sizeable.sizeUndefined() = setSizeUndefined()
fun Sizeable.sizeFull() = setSizeFull()
open class Size(val size: Float, val unit: Sizeable.Unit)
class Height(size: Float, unit: Sizeable.Unit) : Size(size, unit)
class Width(size: Float, unit: Sizeable.Unit) : Size(size, unit)
|
Introduce proper Width and Height abstractions
|
Introduce proper Width and Height abstractions
|
Kotlin
|
apache-2.0
|
nfrankel/kaadin,nfrankel/kaadin,nfrankel/kaadin
|
kotlin
|
## Code Before:
package ch.frankel.kaadin
import com.vaadin.server.*
fun Sizeable.height(height: String) = setHeight(height)
fun Sizeable.height(height: Float, unit: Sizeable.Unit) = setHeight(height, unit)
fun Sizeable.heightUndefined() = setHeightUndefined()
fun Sizeable.width(width: String) = setWidth(width)
fun Sizeable.width(width: Float, unit: Sizeable.Unit) = setWidth(width, unit)
fun Sizeable.widthUndefined() = setWidthUndefined()
fun Sizeable.size(width: String, height: String) {
width(width)
height(height)
}
fun Sizeable.size(width: Float, height: Float, unit: Sizeable.Unit) {
width(width, unit)
height(height, unit)
}
fun Sizeable.size(width: Float, widthUnit: Sizeable.Unit, height: Float, heightUnit: Sizeable.Unit) {
width(width, widthUnit)
height(height, heightUnit)
}
fun Sizeable.sizeUndefined() = setSizeUndefined()
fun Sizeable.sizeFull() = setSizeFull()
## Instruction:
Introduce proper Width and Height abstractions
## Code After:
package ch.frankel.kaadin
import com.vaadin.server.*
fun Sizeable.height(height: String) = setHeight(height)
fun Sizeable.height(height: Float, unit: Sizeable.Unit) = setHeight(height, unit)
fun Sizeable.height(height: Height) = setHeight(height.size, height.unit)
fun Sizeable.heightUndefined() = setHeightUndefined()
fun Sizeable.width(width: String) = setWidth(width)
fun Sizeable.width(width: Float, unit: Sizeable.Unit) = setWidth(width, unit)
fun Sizeable.width(width: Width) = setWidth(width.size, width.unit)
fun Sizeable.widthUndefined() = setWidthUndefined()
fun Sizeable.size(width: String, height: String) {
width(width)
height(height)
}
fun Sizeable.size(width: Float, height: Float, unit: Sizeable.Unit) {
width(width, unit)
height(height, unit)
}
fun Sizeable.size(width: Float, widthUnit: Sizeable.Unit, height: Float, heightUnit: Sizeable.Unit) {
width(width, widthUnit)
height(height, heightUnit)
}
fun Sizeable.size(width: Width, height: Height) {
width(width)
height(height)
}
fun Sizeable.sizeUndefined() = setSizeUndefined()
fun Sizeable.sizeFull() = setSizeFull()
open class Size(val size: Float, val unit: Sizeable.Unit)
class Height(size: Float, unit: Sizeable.Unit) : Size(size, unit)
class Width(size: Float, unit: Sizeable.Unit) : Size(size, unit)
|
...
fun Sizeable.height(height: String) = setHeight(height)
fun Sizeable.height(height: Float, unit: Sizeable.Unit) = setHeight(height, unit)
fun Sizeable.height(height: Height) = setHeight(height.size, height.unit)
fun Sizeable.heightUndefined() = setHeightUndefined()
fun Sizeable.width(width: String) = setWidth(width)
fun Sizeable.width(width: Float, unit: Sizeable.Unit) = setWidth(width, unit)
fun Sizeable.width(width: Width) = setWidth(width.size, width.unit)
fun Sizeable.widthUndefined() = setWidthUndefined()
fun Sizeable.size(width: String, height: String) {
width(width)
...
width(width, widthUnit)
height(height, heightUnit)
}
fun Sizeable.size(width: Width, height: Height) {
width(width)
height(height)
}
fun Sizeable.sizeUndefined() = setSizeUndefined()
fun Sizeable.sizeFull() = setSizeFull()
open class Size(val size: Float, val unit: Sizeable.Unit)
class Height(size: Float, unit: Sizeable.Unit) : Size(size, unit)
class Width(size: Float, unit: Sizeable.Unit) : Size(size, unit)
...
|
2b603ebe92e308aa78928772e8681f3cc46775cb
|
numba/cloudpickle/compat.py
|
numba/cloudpickle/compat.py
|
import sys
if sys.version_info < (3, 8):
try:
import pickle5 as pickle # noqa: F401
from pickle5 import Pickler # noqa: F401
except ImportError:
import pickle # noqa: F401
from pickle import _Pickler as Pickler # noqa: F401
else:
import pickle # noqa: F401
from _pickle import Pickler # noqa: F401
|
import sys
if sys.version_info < (3, 8):
# NOTE: pickle5 is disabled due to problems in testing.
# try:
# import pickle5 as pickle # noqa: F401
# from pickle5 import Pickler # noqa: F401
# except ImportError:
import pickle # noqa: F401
from pickle import _Pickler as Pickler # noqa: F401
else:
import pickle # noqa: F401
from _pickle import Pickler # noqa: F401
|
Disable pickle5 use in cloudpickle
|
Disable pickle5 use in cloudpickle
|
Python
|
bsd-2-clause
|
numba/numba,IntelLabs/numba,stuartarchibald/numba,stonebig/numba,seibert/numba,cpcloud/numba,stonebig/numba,cpcloud/numba,numba/numba,IntelLabs/numba,stuartarchibald/numba,seibert/numba,cpcloud/numba,numba/numba,IntelLabs/numba,cpcloud/numba,seibert/numba,cpcloud/numba,stonebig/numba,stonebig/numba,stuartarchibald/numba,seibert/numba,stuartarchibald/numba,stuartarchibald/numba,stonebig/numba,seibert/numba,IntelLabs/numba,numba/numba,numba/numba,IntelLabs/numba
|
python
|
## Code Before:
import sys
if sys.version_info < (3, 8):
try:
import pickle5 as pickle # noqa: F401
from pickle5 import Pickler # noqa: F401
except ImportError:
import pickle # noqa: F401
from pickle import _Pickler as Pickler # noqa: F401
else:
import pickle # noqa: F401
from _pickle import Pickler # noqa: F401
## Instruction:
Disable pickle5 use in cloudpickle
## Code After:
import sys
if sys.version_info < (3, 8):
# NOTE: pickle5 is disabled due to problems in testing.
# try:
# import pickle5 as pickle # noqa: F401
# from pickle5 import Pickler # noqa: F401
# except ImportError:
import pickle # noqa: F401
from pickle import _Pickler as Pickler # noqa: F401
else:
import pickle # noqa: F401
from _pickle import Pickler # noqa: F401
|
...
if sys.version_info < (3, 8):
# NOTE: pickle5 is disabled due to problems in testing.
# try:
# import pickle5 as pickle # noqa: F401
# from pickle5 import Pickler # noqa: F401
# except ImportError:
import pickle # noqa: F401
from pickle import _Pickler as Pickler # noqa: F401
else:
import pickle # noqa: F401
from _pickle import Pickler # noqa: F401
...
|
cc3f363c1fefb758302b82e7d0ddff69d55a8261
|
recognition/scrobbleTrack.py
|
recognition/scrobbleTrack.py
|
import os, sys, json, pylast, calendar
from datetime import datetime
resultJson = json.loads(sys.stdin.read())
# exit immediately if recognition failed
if resultJson["status"]["msg"] != "Success":
print "Recognition failed."
sys.exit(2)
# load Last.fm auth details into environment variables
apiKey = os.environ["LASTFM_API_KEY"]
apiSecret = os.environ["LASTFM_API_SECRET"]
username = os.environ["LASTFM_USERNAME"]
password = os.environ["LASTFM_PASSWORD"]
passwordHash = pylast.md5(password)
# load song details from JSON object
songName = resultJson["metadata"]["music"][0]["title"]
songArtist = resultJson["metadata"]["music"][0]["artists"][0]["name"]
network = pylast.LastFMNetwork(api_key=apiKey, api_secret=apiSecret,
username=username, password_hash=passwordHash)
d = datetime.utcnow()
unixtime = calendar.timegm(d.utctimetuple())
network.scrobble(songArtist, songName, unixtime)
|
import os, sys, json, pylast, calendar
from datetime import datetime
resultJson = json.loads(sys.stdin.read())
# exit immediately if recognition failed
if resultJson["status"]["msg"] != "Success":
print "Recognition failed."
sys.exit(2)
# load Last.fm auth details into environment variables
apiKey = os.environ["LASTFM_API_KEY"]
apiSecret = os.environ["LASTFM_API_SECRET"]
username = os.environ["LASTFM_USERNAME"]
password = os.environ["LASTFM_PASSWORD"]
passwordHash = pylast.md5(password)
if not apiKey:
print "No Last.fm API Key was found."
sys.exit(3)
if not apiSecret:
print "No Last.fm API Secret was found."
sys.exit(3)
if not username:
print "No Last.fm username was found."
sys.exit(3)
if not password:
print "No Last.fm password was found."
sys.exit(3)
# load song details from JSON object
songName = resultJson["metadata"]["music"][0]["title"]
songArtist = resultJson["metadata"]["music"][0]["artists"][0]["name"]
network = pylast.LastFMNetwork(api_key=apiKey, api_secret=apiSecret,
username=username, password_hash=passwordHash)
d = datetime.utcnow()
unixtime = calendar.timegm(d.utctimetuple())
network.scrobble(songArtist, songName, unixtime)
|
Check for existing Last.fm creds before scrobbling
|
Check for existing Last.fm creds before scrobbling
|
Python
|
mit
|
jeffstephens/pi-resto,jeffstephens/pi-resto
|
python
|
## Code Before:
import os, sys, json, pylast, calendar
from datetime import datetime
resultJson = json.loads(sys.stdin.read())
# exit immediately if recognition failed
if resultJson["status"]["msg"] != "Success":
print "Recognition failed."
sys.exit(2)
# load Last.fm auth details into environment variables
apiKey = os.environ["LASTFM_API_KEY"]
apiSecret = os.environ["LASTFM_API_SECRET"]
username = os.environ["LASTFM_USERNAME"]
password = os.environ["LASTFM_PASSWORD"]
passwordHash = pylast.md5(password)
# load song details from JSON object
songName = resultJson["metadata"]["music"][0]["title"]
songArtist = resultJson["metadata"]["music"][0]["artists"][0]["name"]
network = pylast.LastFMNetwork(api_key=apiKey, api_secret=apiSecret,
username=username, password_hash=passwordHash)
d = datetime.utcnow()
unixtime = calendar.timegm(d.utctimetuple())
network.scrobble(songArtist, songName, unixtime)
## Instruction:
Check for existing Last.fm creds before scrobbling
## Code After:
import os, sys, json, pylast, calendar
from datetime import datetime
resultJson = json.loads(sys.stdin.read())
# exit immediately if recognition failed
if resultJson["status"]["msg"] != "Success":
print "Recognition failed."
sys.exit(2)
# load Last.fm auth details into environment variables
apiKey = os.environ["LASTFM_API_KEY"]
apiSecret = os.environ["LASTFM_API_SECRET"]
username = os.environ["LASTFM_USERNAME"]
password = os.environ["LASTFM_PASSWORD"]
passwordHash = pylast.md5(password)
if not apiKey:
print "No Last.fm API Key was found."
sys.exit(3)
if not apiSecret:
print "No Last.fm API Secret was found."
sys.exit(3)
if not username:
print "No Last.fm username was found."
sys.exit(3)
if not password:
print "No Last.fm password was found."
sys.exit(3)
# load song details from JSON object
songName = resultJson["metadata"]["music"][0]["title"]
songArtist = resultJson["metadata"]["music"][0]["artists"][0]["name"]
network = pylast.LastFMNetwork(api_key=apiKey, api_secret=apiSecret,
username=username, password_hash=passwordHash)
d = datetime.utcnow()
unixtime = calendar.timegm(d.utctimetuple())
network.scrobble(songArtist, songName, unixtime)
|
// ... existing code ...
password = os.environ["LASTFM_PASSWORD"]
passwordHash = pylast.md5(password)
if not apiKey:
print "No Last.fm API Key was found."
sys.exit(3)
if not apiSecret:
print "No Last.fm API Secret was found."
sys.exit(3)
if not username:
print "No Last.fm username was found."
sys.exit(3)
if not password:
print "No Last.fm password was found."
sys.exit(3)
# load song details from JSON object
songName = resultJson["metadata"]["music"][0]["title"]
songArtist = resultJson["metadata"]["music"][0]["artists"][0]["name"]
// ... rest of the code ...
|
34fe6e4f499385cc437a720db0f54db0f0ba07d2
|
tests/tests_twobody/test_mean_elements.py
|
tests/tests_twobody/test_mean_elements.py
|
import pytest
from poliastro.twobody.mean_elements import get_mean_elements
def test_get_mean_elements_raises_error_if_invalid_body():
body = "Sun"
with pytest.raises(ValueError) as excinfo:
get_mean_elements(body)
assert f"The input body is invalid." in excinfo.exconly()
|
import pytest
from poliastro.twobody.mean_elements import get_mean_elements
def test_get_mean_elements_raises_error_if_invalid_body():
body = "Sun"
with pytest.raises(ValueError) as excinfo:
get_mean_elements(body)
assert f"The input body '{body}' is invalid." in excinfo.exconly()
|
Add test for error check
|
Add test for error check
|
Python
|
mit
|
poliastro/poliastro
|
python
|
## Code Before:
import pytest
from poliastro.twobody.mean_elements import get_mean_elements
def test_get_mean_elements_raises_error_if_invalid_body():
body = "Sun"
with pytest.raises(ValueError) as excinfo:
get_mean_elements(body)
assert f"The input body is invalid." in excinfo.exconly()
## Instruction:
Add test for error check
## Code After:
import pytest
from poliastro.twobody.mean_elements import get_mean_elements
def test_get_mean_elements_raises_error_if_invalid_body():
body = "Sun"
with pytest.raises(ValueError) as excinfo:
get_mean_elements(body)
assert f"The input body '{body}' is invalid." in excinfo.exconly()
|
...
import pytest
from poliastro.twobody.mean_elements import get_mean_elements
def test_get_mean_elements_raises_error_if_invalid_body():
body = "Sun"
...
with pytest.raises(ValueError) as excinfo:
get_mean_elements(body)
assert f"The input body '{body}' is invalid." in excinfo.exconly()
...
|
a55dd124d54955476411ee8ae830c9fd3c4f00dc
|
tests/test_pdfbuild.py
|
tests/test_pdfbuild.py
|
from latex import build_pdf
from latex.exc import LatexBuildError
import pytest
def test_generates_something():
min_latex = r"""
\documentclass{article}
\begin{document}
Hello, world!
\end{document}
"""
pdf = build_pdf(min_latex)
assert pdf
def test_raises_correct_exception_on_fail():
broken_latex = r"""foo"""
with pytest.raises(LatexBuildError):
build_pdf(broken_latex)
|
from latex import build_pdf, LatexBuildError
from latex.errors import parse_log
import pytest
def test_generates_something():
min_latex = r"""
\documentclass{article}
\begin{document}
Hello, world!
\end{document}
"""
pdf = build_pdf(min_latex)
assert pdf
def test_raises_correct_exception_on_fail():
broken_latex = r"""foo"""
with pytest.raises(LatexBuildError):
build_pdf(broken_latex)
def test_finds_errors_correctly():
broken_latex = r"""
\documentclass{article}
\begin{document}
All good
\undefinedcontrolsequencehere
\end{document}
"""
try:
build_pdf(broken_latex)
except LatexBuildError as e:
assert parse_log(e.log) == e.get_errors()
else:
assert False, 'no exception raised'
|
Test get_errors() method of LatexBuildError.
|
Test get_errors() method of LatexBuildError.
|
Python
|
bsd-3-clause
|
mbr/latex
|
python
|
## Code Before:
from latex import build_pdf
from latex.exc import LatexBuildError
import pytest
def test_generates_something():
min_latex = r"""
\documentclass{article}
\begin{document}
Hello, world!
\end{document}
"""
pdf = build_pdf(min_latex)
assert pdf
def test_raises_correct_exception_on_fail():
broken_latex = r"""foo"""
with pytest.raises(LatexBuildError):
build_pdf(broken_latex)
## Instruction:
Test get_errors() method of LatexBuildError.
## Code After:
from latex import build_pdf, LatexBuildError
from latex.errors import parse_log
import pytest
def test_generates_something():
min_latex = r"""
\documentclass{article}
\begin{document}
Hello, world!
\end{document}
"""
pdf = build_pdf(min_latex)
assert pdf
def test_raises_correct_exception_on_fail():
broken_latex = r"""foo"""
with pytest.raises(LatexBuildError):
build_pdf(broken_latex)
def test_finds_errors_correctly():
broken_latex = r"""
\documentclass{article}
\begin{document}
All good
\undefinedcontrolsequencehere
\end{document}
"""
try:
build_pdf(broken_latex)
except LatexBuildError as e:
assert parse_log(e.log) == e.get_errors()
else:
assert False, 'no exception raised'
|
// ... existing code ...
from latex import build_pdf, LatexBuildError
from latex.errors import parse_log
import pytest
// ... modified code ...
with pytest.raises(LatexBuildError):
build_pdf(broken_latex)
def test_finds_errors_correctly():
broken_latex = r"""
\documentclass{article}
\begin{document}
All good
\undefinedcontrolsequencehere
\end{document}
"""
try:
build_pdf(broken_latex)
except LatexBuildError as e:
assert parse_log(e.log) == e.get_errors()
else:
assert False, 'no exception raised'
// ... rest of the code ...
|
e50c9e7c523703bebe2078830cbd598119009e7b
|
app/src/main/java/org/stepic/droid/storage/migration/MigrationFrom75To76.kt
|
app/src/main/java/org/stepic/droid/storage/migration/MigrationFrom75To76.kt
|
package org.stepic.droid.storage.migration
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import org.stepic.droid.storage.structure.DbStructureCourse
object MigrationFrom75To76 : Migration(75, 76) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE ${DbStructureCourse.TABLE_NAME} ADD COLUMN ${DbStructureCourse.Columns.IS_IN_WISHLIST} INTEGER")
db.execSQL("CREATE TABLE IF NOT EXISTS `WishlistEntry` (`id` INTEGER NOT NULL, `course` INTEGER NOT NULL, `user` INTEGER NOT NULL, `createDate` INTEGER NOT NULL, `platform` TEXT NOT NULL, PRIMARY KEY(`id`))")
}
}
|
package org.stepic.droid.storage.migration
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import org.stepic.droid.storage.structure.DbStructureCourse
object MigrationFrom75To76 : Migration(75, 76) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE ${DbStructureCourse.TABLE_NAME} ADD COLUMN ${DbStructureCourse.Columns.IS_IN_WISHLIST} INTEGER")
db.execSQL("CREATE TABLE IF NOT EXISTS `WishlistEntry` (`id` INTEGER NOT NULL, `course` INTEGER NOT NULL, `user` INTEGER NOT NULL, `createDate` INTEGER NOT NULL, `platform` TEXT NOT NULL, PRIMARY KEY(`id`))")
db.execSQL("DELETE FROM ${DbStructureCourse.TABLE_NAME} WHERE ${DbStructureCourse.Columns.ID} IN (SELECT `course` FROM `VisitedCourse`)")
}
}
|
Remove visited courses from courses table upon migration
|
Remove visited courses from courses table upon migration
|
Kotlin
|
apache-2.0
|
StepicOrg/stepik-android,StepicOrg/stepik-android,StepicOrg/stepik-android
|
kotlin
|
## Code Before:
package org.stepic.droid.storage.migration
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import org.stepic.droid.storage.structure.DbStructureCourse
object MigrationFrom75To76 : Migration(75, 76) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE ${DbStructureCourse.TABLE_NAME} ADD COLUMN ${DbStructureCourse.Columns.IS_IN_WISHLIST} INTEGER")
db.execSQL("CREATE TABLE IF NOT EXISTS `WishlistEntry` (`id` INTEGER NOT NULL, `course` INTEGER NOT NULL, `user` INTEGER NOT NULL, `createDate` INTEGER NOT NULL, `platform` TEXT NOT NULL, PRIMARY KEY(`id`))")
}
}
## Instruction:
Remove visited courses from courses table upon migration
## Code After:
package org.stepic.droid.storage.migration
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import org.stepic.droid.storage.structure.DbStructureCourse
object MigrationFrom75To76 : Migration(75, 76) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE ${DbStructureCourse.TABLE_NAME} ADD COLUMN ${DbStructureCourse.Columns.IS_IN_WISHLIST} INTEGER")
db.execSQL("CREATE TABLE IF NOT EXISTS `WishlistEntry` (`id` INTEGER NOT NULL, `course` INTEGER NOT NULL, `user` INTEGER NOT NULL, `createDate` INTEGER NOT NULL, `platform` TEXT NOT NULL, PRIMARY KEY(`id`))")
db.execSQL("DELETE FROM ${DbStructureCourse.TABLE_NAME} WHERE ${DbStructureCourse.Columns.ID} IN (SELECT `course` FROM `VisitedCourse`)")
}
}
|
// ... existing code ...
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE ${DbStructureCourse.TABLE_NAME} ADD COLUMN ${DbStructureCourse.Columns.IS_IN_WISHLIST} INTEGER")
db.execSQL("CREATE TABLE IF NOT EXISTS `WishlistEntry` (`id` INTEGER NOT NULL, `course` INTEGER NOT NULL, `user` INTEGER NOT NULL, `createDate` INTEGER NOT NULL, `platform` TEXT NOT NULL, PRIMARY KEY(`id`))")
db.execSQL("DELETE FROM ${DbStructureCourse.TABLE_NAME} WHERE ${DbStructureCourse.Columns.ID} IN (SELECT `course` FROM `VisitedCourse`)")
}
}
// ... rest of the code ...
|
c407c067495d76ebed7c36ef005861c80fdcfdce
|
textx/__init__.py
|
textx/__init__.py
|
__version__ = "1.6.dev"
|
from textx.metamodel import metamodel_from_file, metamodel_from_str # noqa
from textx.langapi import get_language, iter_languages # noqa
__version__ = "1.6.dev"
|
Make metamodel factory methods and lang API available in textx package.
|
Make metamodel factory methods and lang API available in textx package.
|
Python
|
mit
|
igordejanovic/textX,igordejanovic/textX,igordejanovic/textX
|
python
|
## Code Before:
__version__ = "1.6.dev"
## Instruction:
Make metamodel factory methods and lang API available in textx package.
## Code After:
from textx.metamodel import metamodel_from_file, metamodel_from_str # noqa
from textx.langapi import get_language, iter_languages # noqa
__version__ = "1.6.dev"
|
# ... existing code ...
from textx.metamodel import metamodel_from_file, metamodel_from_str # noqa
from textx.langapi import get_language, iter_languages # noqa
__version__ = "1.6.dev"
# ... rest of the code ...
|
6cf9624275da920d283635c43cb39de0bd7b4350
|
src/modules/conf_randr/e_smart_randr.h
|
src/modules/conf_randr/e_smart_randr.h
|
Evas_Object *e_smart_randr_add(Evas *evas);
# endif
#endif
|
Evas_Object *e_smart_randr_add(Evas *evas);
void e_smart_randr_monitors_create(Evas_Object *obj);
# endif
#endif
|
Add header function for monitors_create.
|
Add header function for monitors_create.
Signed-off-by: Christopher Michael <[email protected]>
SVN revision: 84126
|
C
|
bsd-2-clause
|
rvandegrift/e,tasn/enlightenment,tizenorg/platform.upstream.enlightenment,FlorentRevest/Enlightenment,rvandegrift/e,FlorentRevest/Enlightenment,tasn/enlightenment,FlorentRevest/Enlightenment,tasn/enlightenment,rvandegrift/e,tizenorg/platform.upstream.enlightenment,tizenorg/platform.upstream.enlightenment
|
c
|
## Code Before:
Evas_Object *e_smart_randr_add(Evas *evas);
# endif
#endif
## Instruction:
Add header function for monitors_create.
Signed-off-by: Christopher Michael <[email protected]>
SVN revision: 84126
## Code After:
Evas_Object *e_smart_randr_add(Evas *evas);
void e_smart_randr_monitors_create(Evas_Object *obj);
# endif
#endif
|
# ... existing code ...
Evas_Object *e_smart_randr_add(Evas *evas);
void e_smart_randr_monitors_create(Evas_Object *obj);
# endif
#endif
# ... rest of the code ...
|
90fe366aff1531c6c613e99d018afee6650a000f
|
src/java/com/threerings/whirled/server/SceneManager.java
|
src/java/com/threerings/whirled/server/SceneManager.java
|
//
// $Id: SceneManager.java,v 1.2 2001/08/21 01:07:19 mdb Exp $
package com.threerings.whirled.server;
import com.threerings.cocktail.party.server.PlaceManager;
import com.threerings.whirled.data.Scene;
public class SceneManager extends PlaceManager
{
public Scene getScene ()
{
return _scene;
}
/**
* Called by the scene registry once the scene manager has been
* created (and initialized), but before it is started up.
*/
protected void postInit (Scene scene, SceneRegistry screg)
{
_scene = scene;
_screg = screg;
}
/**
* We're fully ready to go, so now we register ourselves with the
* scene registry which will make us available to the clients and
* system at large.
*/
protected void didStartup ()
{
super.didStartup();
_screg.sceneManagerDidInit(this);
}
protected void toString (StringBuffer buf)
{
super.toString(buf);
buf.append("scene=").append(_scene);
}
protected Scene _scene;
protected SceneRegistry _screg;
}
|
//
// $Id: SceneManager.java,v 1.3 2001/08/22 00:09:52 mdb Exp $
package com.threerings.whirled.server;
import com.threerings.cocktail.party.chat.ChatMessageHandler;
import com.threerings.cocktail.party.chat.ChatService;
import com.threerings.cocktail.party.server.PlaceManager;
import com.threerings.whirled.data.Scene;
public class SceneManager extends PlaceManager
{
public Scene getScene ()
{
return _scene;
}
/**
* Called by the scene registry once the scene manager has been
* created (and initialized), but before it is started up.
*/
protected void postInit (Scene scene, SceneRegistry screg)
{
_scene = scene;
_screg = screg;
}
/**
* We're fully ready to go, so now we register ourselves with the
* scene registry which will make us available to the clients and
* system at large.
*/
protected void didStartup ()
{
super.didStartup();
_screg.sceneManagerDidInit(this);
// register a chat message handler because we want to support
// chatting
MessageHandler handler = new ChatMessageHandler();
registerMessageHandler(ChatService.SPEAK_REQUEST, handler);
}
protected void toString (StringBuffer buf)
{
super.toString(buf);
buf.append("scene=").append(_scene);
}
protected Scene _scene;
protected SceneRegistry _screg;
}
|
Add chat support by default into the Whirled scene manager. This will probably come out again because it should really be added by the manager used by the target application. They may not want exactly the same kind of chat support.
|
Add chat support by default into the Whirled scene manager. This will
probably come out again because it should really be added by the manager
used by the target application. They may not want exactly the same kind of
chat support.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@307 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
Java
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
java
|
## Code Before:
//
// $Id: SceneManager.java,v 1.2 2001/08/21 01:07:19 mdb Exp $
package com.threerings.whirled.server;
import com.threerings.cocktail.party.server.PlaceManager;
import com.threerings.whirled.data.Scene;
public class SceneManager extends PlaceManager
{
public Scene getScene ()
{
return _scene;
}
/**
* Called by the scene registry once the scene manager has been
* created (and initialized), but before it is started up.
*/
protected void postInit (Scene scene, SceneRegistry screg)
{
_scene = scene;
_screg = screg;
}
/**
* We're fully ready to go, so now we register ourselves with the
* scene registry which will make us available to the clients and
* system at large.
*/
protected void didStartup ()
{
super.didStartup();
_screg.sceneManagerDidInit(this);
}
protected void toString (StringBuffer buf)
{
super.toString(buf);
buf.append("scene=").append(_scene);
}
protected Scene _scene;
protected SceneRegistry _screg;
}
## Instruction:
Add chat support by default into the Whirled scene manager. This will
probably come out again because it should really be added by the manager
used by the target application. They may not want exactly the same kind of
chat support.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@307 542714f4-19e9-0310-aa3c-eee0fc999fb1
## Code After:
//
// $Id: SceneManager.java,v 1.3 2001/08/22 00:09:52 mdb Exp $
package com.threerings.whirled.server;
import com.threerings.cocktail.party.chat.ChatMessageHandler;
import com.threerings.cocktail.party.chat.ChatService;
import com.threerings.cocktail.party.server.PlaceManager;
import com.threerings.whirled.data.Scene;
public class SceneManager extends PlaceManager
{
public Scene getScene ()
{
return _scene;
}
/**
* Called by the scene registry once the scene manager has been
* created (and initialized), but before it is started up.
*/
protected void postInit (Scene scene, SceneRegistry screg)
{
_scene = scene;
_screg = screg;
}
/**
* We're fully ready to go, so now we register ourselves with the
* scene registry which will make us available to the clients and
* system at large.
*/
protected void didStartup ()
{
super.didStartup();
_screg.sceneManagerDidInit(this);
// register a chat message handler because we want to support
// chatting
MessageHandler handler = new ChatMessageHandler();
registerMessageHandler(ChatService.SPEAK_REQUEST, handler);
}
protected void toString (StringBuffer buf)
{
super.toString(buf);
buf.append("scene=").append(_scene);
}
protected Scene _scene;
protected SceneRegistry _screg;
}
|
# ... existing code ...
//
// $Id: SceneManager.java,v 1.3 2001/08/22 00:09:52 mdb Exp $
package com.threerings.whirled.server;
import com.threerings.cocktail.party.chat.ChatMessageHandler;
import com.threerings.cocktail.party.chat.ChatService;
import com.threerings.cocktail.party.server.PlaceManager;
import com.threerings.whirled.data.Scene;
public class SceneManager extends PlaceManager
# ... modified code ...
{
super.didStartup();
_screg.sceneManagerDidInit(this);
// register a chat message handler because we want to support
// chatting
MessageHandler handler = new ChatMessageHandler();
registerMessageHandler(ChatService.SPEAK_REQUEST, handler);
}
protected void toString (StringBuffer buf)
# ... rest of the code ...
|
80c192155256aa02f290130f792fc804fb59a4d7
|
pycat/talk.py
|
pycat/talk.py
|
"""Communication link driver."""
import sys
import selectors
CLIENT_TO_SERVER = object()
SERVER_TO_CLIENT = object()
def talk(socket, source=sys.stdin.buffer, sink=sys.stdout.buffer):
"""Run communication, in a loop. Input from `source` is sent on `socket`,
and data received on `socket` is forwarded to `sink`.
All file descriptors must be non-blocking.
"""
OUTPUT_BUFFER_SIZE = 1024
with selectors.DefaultSelector() as selector:
selector.register(source, selectors.EVENT_READ, CLIENT_TO_SERVER)
selector.register(socket, selectors.EVENT_READ, SERVER_TO_CLIENT)
while True:
for key, events in selector.select():
if key.data is CLIENT_TO_SERVER:
data = source.readline()
socket.send(data)
elif key.data is SERVER_TO_CLIENT:
data = socket.recv(OUTPUT_BUFFER_SIZE)
sink.write(data)
sink.flush()
|
"""Communication link driver."""
import sys
import select
def talk(socket, source=sys.stdin.buffer, sink=sys.stdout.buffer):
"""Run communication, in a loop. Input from `source` is sent on `socket`,
and data received on `socket` is forwarded to `sink`.
All file descriptors must be non-blocking.
"""
OUTPUT_BUFFER_SIZE = 1024
while True:
readable, writable, exceptional = select.select((socket, source),
(),
(socket, source, sink))
if source in readable:
socket.send(source.readline())
if socket in readable:
sink.write(socket.recv(OUTPUT_BUFFER_SIZE))
sink.flush()
|
Switch to just using `select` directly
|
Switch to just using `select` directly
This is less efficient, but does let use get the "exceptional" cases
and handle them more pleasantly.
|
Python
|
mit
|
prophile/pycat
|
python
|
## Code Before:
"""Communication link driver."""
import sys
import selectors
CLIENT_TO_SERVER = object()
SERVER_TO_CLIENT = object()
def talk(socket, source=sys.stdin.buffer, sink=sys.stdout.buffer):
"""Run communication, in a loop. Input from `source` is sent on `socket`,
and data received on `socket` is forwarded to `sink`.
All file descriptors must be non-blocking.
"""
OUTPUT_BUFFER_SIZE = 1024
with selectors.DefaultSelector() as selector:
selector.register(source, selectors.EVENT_READ, CLIENT_TO_SERVER)
selector.register(socket, selectors.EVENT_READ, SERVER_TO_CLIENT)
while True:
for key, events in selector.select():
if key.data is CLIENT_TO_SERVER:
data = source.readline()
socket.send(data)
elif key.data is SERVER_TO_CLIENT:
data = socket.recv(OUTPUT_BUFFER_SIZE)
sink.write(data)
sink.flush()
## Instruction:
Switch to just using `select` directly
This is less efficient, but does let use get the "exceptional" cases
and handle them more pleasantly.
## Code After:
"""Communication link driver."""
import sys
import select
def talk(socket, source=sys.stdin.buffer, sink=sys.stdout.buffer):
"""Run communication, in a loop. Input from `source` is sent on `socket`,
and data received on `socket` is forwarded to `sink`.
All file descriptors must be non-blocking.
"""
OUTPUT_BUFFER_SIZE = 1024
while True:
readable, writable, exceptional = select.select((socket, source),
(),
(socket, source, sink))
if source in readable:
socket.send(source.readline())
if socket in readable:
sink.write(socket.recv(OUTPUT_BUFFER_SIZE))
sink.flush()
|
...
"""Communication link driver."""
import sys
import select
def talk(socket, source=sys.stdin.buffer, sink=sys.stdout.buffer):
...
OUTPUT_BUFFER_SIZE = 1024
while True:
readable, writable, exceptional = select.select((socket, source),
(),
(socket, source, sink))
if source in readable:
socket.send(source.readline())
if socket in readable:
sink.write(socket.recv(OUTPUT_BUFFER_SIZE))
sink.flush()
...
|
a5b70775d106d07acfb54ce0b3998a03ed195de7
|
test/uritemplate_test.py
|
test/uritemplate_test.py
|
import uritemplate
import simplejson
import sys
filename = sys.argv[1]
print "Running", filename
f = file(filename)
testdata = simplejson.load(f)
try:
desired_level = int(sys.argv[2])
except IndexError:
desired_level = 4
for name, testsuite in testdata.iteritems():
vars = testsuite['variables']
testcases = testsuite['testcases']
level = testsuite.get('level', 4)
if level > desired_level:
continue
print name
for testcase in testcases:
template = testcase[0]
expected = testcase[1]
actual = uritemplate.expand(template, vars)
sys.stdout.write(".")
if expected != actual:
print "Template %s expected to expand to %s, got %s instead" % (template, expected, actual)
assert 0
print
|
import uritemplate
import simplejson
import sys
filename = sys.argv[1]
print "Running", filename
f = file(filename)
testdata = simplejson.load(f)
try:
desired_level = int(sys.argv[2])
except IndexError:
desired_level = 4
for name, testsuite in testdata.iteritems():
vars = testsuite['variables']
testcases = testsuite['testcases']
level = testsuite.get('level', 4)
if level > desired_level:
continue
print name
for testcase in testcases:
template = testcase[0]
expected = testcase[1]
actual = uritemplate.expand(template, vars)
sys.stdout.write(".")
if type(expected) == type([]):
if actual not in expected:
sys.stderr.write("%s didn't expand as expected, got %s instead\n" % (template, actual))
assert 0
else:
if actual != expected:
sys.stderr.write("%s expected to expand to %s, got %s instead\n" % (template, expected, actual))
assert 0
print
|
Handle lists of possibilities in tests
|
Handle lists of possibilities in tests
|
Python
|
apache-2.0
|
uri-templates/uritemplate-py
|
python
|
## Code Before:
import uritemplate
import simplejson
import sys
filename = sys.argv[1]
print "Running", filename
f = file(filename)
testdata = simplejson.load(f)
try:
desired_level = int(sys.argv[2])
except IndexError:
desired_level = 4
for name, testsuite in testdata.iteritems():
vars = testsuite['variables']
testcases = testsuite['testcases']
level = testsuite.get('level', 4)
if level > desired_level:
continue
print name
for testcase in testcases:
template = testcase[0]
expected = testcase[1]
actual = uritemplate.expand(template, vars)
sys.stdout.write(".")
if expected != actual:
print "Template %s expected to expand to %s, got %s instead" % (template, expected, actual)
assert 0
print
## Instruction:
Handle lists of possibilities in tests
## Code After:
import uritemplate
import simplejson
import sys
filename = sys.argv[1]
print "Running", filename
f = file(filename)
testdata = simplejson.load(f)
try:
desired_level = int(sys.argv[2])
except IndexError:
desired_level = 4
for name, testsuite in testdata.iteritems():
vars = testsuite['variables']
testcases = testsuite['testcases']
level = testsuite.get('level', 4)
if level > desired_level:
continue
print name
for testcase in testcases:
template = testcase[0]
expected = testcase[1]
actual = uritemplate.expand(template, vars)
sys.stdout.write(".")
if type(expected) == type([]):
if actual not in expected:
sys.stderr.write("%s didn't expand as expected, got %s instead\n" % (template, actual))
assert 0
else:
if actual != expected:
sys.stderr.write("%s expected to expand to %s, got %s instead\n" % (template, expected, actual))
assert 0
print
|
# ... existing code ...
expected = testcase[1]
actual = uritemplate.expand(template, vars)
sys.stdout.write(".")
if type(expected) == type([]):
if actual not in expected:
sys.stderr.write("%s didn't expand as expected, got %s instead\n" % (template, actual))
assert 0
else:
if actual != expected:
sys.stderr.write("%s expected to expand to %s, got %s instead\n" % (template, expected, actual))
assert 0
print
# ... rest of the code ...
|
8fccfa505f23f64fe722b7c4fcf3453b406387bf
|
sample/src/main/kotlin/com/louiscad/splittiessample/extensions/View.kt
|
sample/src/main/kotlin/com/louiscad/splittiessample/extensions/View.kt
|
package com.louiscad.splittiessample.extensions
import android.view.View
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
@ExperimentalContracts
inline fun <R> View.visibleInScope(finallyInvisible: Boolean = false, block: () -> R): R {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
return try {
isVisible = true
block()
} finally {
visibility = if (finallyInvisible) View.INVISIBLE else View.GONE
}
}
@ExperimentalContracts
inline fun <R> View.goneInScope(block: () -> R): R {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
return try {
isVisible = false
block()
} finally {
isVisible = true
}
}
@ExperimentalContracts
inline fun <R> View.invisibleInScope(block: () -> R): R {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
return try {
isInvisible = true
block()
} finally {
isInvisible = false
}
}
|
package com.louiscad.splittiessample.extensions
import android.view.View
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
@UseExperimental(ExperimentalContracts::class)
inline fun <R> View.visibleInScope(finallyInvisible: Boolean = false, block: () -> R): R {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
return try {
isVisible = true
block()
} finally {
visibility = if (finallyInvisible) View.INVISIBLE else View.GONE
}
}
@UseExperimental(ExperimentalContracts::class)
inline fun <R> View.goneInScope(block: () -> R): R {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
return try {
isVisible = false
block()
} finally {
isVisible = true
}
}
@UseExperimental(ExperimentalContracts::class)
inline fun <R> View.invisibleInScope(block: () -> R): R {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
return try {
isInvisible = true
block()
} finally {
isInvisible = false
}
}
|
Replace experimental annotation with UseExperimental
|
Replace experimental annotation with UseExperimental
|
Kotlin
|
apache-2.0
|
LouisCAD/Splitties,LouisCAD/Splitties,LouisCAD/Splitties
|
kotlin
|
## Code Before:
package com.louiscad.splittiessample.extensions
import android.view.View
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
@ExperimentalContracts
inline fun <R> View.visibleInScope(finallyInvisible: Boolean = false, block: () -> R): R {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
return try {
isVisible = true
block()
} finally {
visibility = if (finallyInvisible) View.INVISIBLE else View.GONE
}
}
@ExperimentalContracts
inline fun <R> View.goneInScope(block: () -> R): R {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
return try {
isVisible = false
block()
} finally {
isVisible = true
}
}
@ExperimentalContracts
inline fun <R> View.invisibleInScope(block: () -> R): R {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
return try {
isInvisible = true
block()
} finally {
isInvisible = false
}
}
## Instruction:
Replace experimental annotation with UseExperimental
## Code After:
package com.louiscad.splittiessample.extensions
import android.view.View
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
@UseExperimental(ExperimentalContracts::class)
inline fun <R> View.visibleInScope(finallyInvisible: Boolean = false, block: () -> R): R {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
return try {
isVisible = true
block()
} finally {
visibility = if (finallyInvisible) View.INVISIBLE else View.GONE
}
}
@UseExperimental(ExperimentalContracts::class)
inline fun <R> View.goneInScope(block: () -> R): R {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
return try {
isVisible = false
block()
} finally {
isVisible = true
}
}
@UseExperimental(ExperimentalContracts::class)
inline fun <R> View.invisibleInScope(block: () -> R): R {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
return try {
isInvisible = true
block()
} finally {
isInvisible = false
}
}
|
# ... existing code ...
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
@UseExperimental(ExperimentalContracts::class)
inline fun <R> View.visibleInScope(finallyInvisible: Boolean = false, block: () -> R): R {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
return try {
# ... modified code ...
}
}
@UseExperimental(ExperimentalContracts::class)
inline fun <R> View.goneInScope(block: () -> R): R {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
return try {
...
}
}
@UseExperimental(ExperimentalContracts::class)
inline fun <R> View.invisibleInScope(block: () -> R): R {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
return try {
# ... rest of the code ...
|
86ec56b0de1e822af2e03fedd2a67a3c555a7d18
|
versebot/regex.py
|
versebot/regex.py
|
import re
def find_verses(message_body):
""" Uses regex to search comment body for verse quotations. Returns
a list of matches if found, None otherwise. """
regex = (r"(?<=\[)(?P<book>[\d\w\s]+)(?P<chapter>\d+)\:?(?P<verse>\d+"
+ r"\-?\d*)?\s*\(?(?P<translation>[\w\-\d]+)?\)?(?=\])")
return re.findall(regex, message_body)
|
import re
def find_verses(message_body):
""" Uses regex to search comment body for verse quotations. Returns
a list of matches if found, None otherwise. """
regex = (r"(?<=\[)(?P<book>[\d\w\s]+)(?P<chapter>\d+)\:?(?P<verse>\d+"
+ r"\-?\d*)?\s*\(?(?P<translation>[\w\-\d]+)?\)?(?=\])")
matches = re.findall(regex, message_body)
if len(matches) == 0:
return None
else:
return matches
|
Fix return value from find_verses()
|
Fix return value from find_verses()
|
Python
|
mit
|
Matthew-Arnold/slack-versebot,Matthew-Arnold/slack-versebot
|
python
|
## Code Before:
import re
def find_verses(message_body):
""" Uses regex to search comment body for verse quotations. Returns
a list of matches if found, None otherwise. """
regex = (r"(?<=\[)(?P<book>[\d\w\s]+)(?P<chapter>\d+)\:?(?P<verse>\d+"
+ r"\-?\d*)?\s*\(?(?P<translation>[\w\-\d]+)?\)?(?=\])")
return re.findall(regex, message_body)
## Instruction:
Fix return value from find_verses()
## Code After:
import re
def find_verses(message_body):
""" Uses regex to search comment body for verse quotations. Returns
a list of matches if found, None otherwise. """
regex = (r"(?<=\[)(?P<book>[\d\w\s]+)(?P<chapter>\d+)\:?(?P<verse>\d+"
+ r"\-?\d*)?\s*\(?(?P<translation>[\w\-\d]+)?\)?(?=\])")
matches = re.findall(regex, message_body)
if len(matches) == 0:
return None
else:
return matches
|
// ... existing code ...
regex = (r"(?<=\[)(?P<book>[\d\w\s]+)(?P<chapter>\d+)\:?(?P<verse>\d+"
+ r"\-?\d*)?\s*\(?(?P<translation>[\w\-\d]+)?\)?(?=\])")
matches = re.findall(regex, message_body)
if len(matches) == 0:
return None
else:
return matches
// ... rest of the code ...
|
c2e36b8f4bcbd3a8bec4d5d4bfc6d5a5a669b5c6
|
src/utils.h
|
src/utils.h
|
/**
* @file utils.h
* @brief Storj utilities.
*
* Helper utilities
*/
#ifndef STORJ_UTILS_H
#define STORJ_UTILS_H
#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <math.h>
#include <stdbool.h>
#ifdef _WIN32
#include <windows.h>
#include <time.h>
ssize_t pread(int fd, void *buf, size_t count, uint64_t offset);
#else
#include <sys/time.h>
#endif
int hex2str(unsigned length, uint8_t *data, char *buffer);
void print_int_array(uint8_t *array, unsigned length);
int str2hex(unsigned length, char *data, uint8_t *buffer);
char *str_concat_many(int count, ...);
void random_buffer(uint8_t *buf, size_t len);
uint64_t shard_size(int hops);
uint64_t get_time_milliseconds();
void memset_zero(void *v, size_t n);
#endif /* STORJ_UTILS_H */
|
/**
* @file utils.h
* @brief Storj utilities.
*
* Helper utilities
*/
#ifndef STORJ_UTILS_H
#define STORJ_UTILS_H
#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <math.h>
#include <stdbool.h>
#ifdef _WIN32
#include <windows.h>
#include <time.h>
#include <io.h>
ssize_t pread(int fd, void *buf, size_t count, uint64_t offset);
#else
#include <sys/time.h>
#endif
int hex2str(unsigned length, uint8_t *data, char *buffer);
void print_int_array(uint8_t *array, unsigned length);
int str2hex(unsigned length, char *data, uint8_t *buffer);
char *str_concat_many(int count, ...);
void random_buffer(uint8_t *buf, size_t len);
uint64_t shard_size(int hops);
uint64_t get_time_milliseconds();
void memset_zero(void *v, size_t n);
#endif /* STORJ_UTILS_H */
|
Include io.h for mingw builds
|
Include io.h for mingw builds
|
C
|
lgpl-2.1
|
braydonf/libstorj,braydonf/libstorj-c,Storj/libstorj-c,braydonf/libstorj-c,Storj/libstorj-c,aleitner/libstorj-c,aleitner/libstorj-c,braydonf/libstorj
|
c
|
## Code Before:
/**
* @file utils.h
* @brief Storj utilities.
*
* Helper utilities
*/
#ifndef STORJ_UTILS_H
#define STORJ_UTILS_H
#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <math.h>
#include <stdbool.h>
#ifdef _WIN32
#include <windows.h>
#include <time.h>
ssize_t pread(int fd, void *buf, size_t count, uint64_t offset);
#else
#include <sys/time.h>
#endif
int hex2str(unsigned length, uint8_t *data, char *buffer);
void print_int_array(uint8_t *array, unsigned length);
int str2hex(unsigned length, char *data, uint8_t *buffer);
char *str_concat_many(int count, ...);
void random_buffer(uint8_t *buf, size_t len);
uint64_t shard_size(int hops);
uint64_t get_time_milliseconds();
void memset_zero(void *v, size_t n);
#endif /* STORJ_UTILS_H */
## Instruction:
Include io.h for mingw builds
## Code After:
/**
* @file utils.h
* @brief Storj utilities.
*
* Helper utilities
*/
#ifndef STORJ_UTILS_H
#define STORJ_UTILS_H
#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <math.h>
#include <stdbool.h>
#ifdef _WIN32
#include <windows.h>
#include <time.h>
#include <io.h>
ssize_t pread(int fd, void *buf, size_t count, uint64_t offset);
#else
#include <sys/time.h>
#endif
int hex2str(unsigned length, uint8_t *data, char *buffer);
void print_int_array(uint8_t *array, unsigned length);
int str2hex(unsigned length, char *data, uint8_t *buffer);
char *str_concat_many(int count, ...);
void random_buffer(uint8_t *buf, size_t len);
uint64_t shard_size(int hops);
uint64_t get_time_milliseconds();
void memset_zero(void *v, size_t n);
#endif /* STORJ_UTILS_H */
|
...
#ifdef _WIN32
#include <windows.h>
#include <time.h>
#include <io.h>
ssize_t pread(int fd, void *buf, size_t count, uint64_t offset);
#else
...
|
7d0b32e31b2d4bb9b994e6df0bfc076b82557225
|
spring-server/src/main/java/ch/heigvd/quaris/config/CorsFilter.java
|
spring-server/src/main/java/ch/heigvd/quaris/config/CorsFilter.java
|
package ch.heigvd.quaris.config;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by Fabien Salathe on 26.01.17.
*/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter extends OncePerRequestFilter {
/**
* Enable CORS
*
* @param request
* @param response
* @param filterChain
* @throws ServletException
* @throws IOException
*/
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.addHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Access-Control-Request-Method, Authorization");
response.addHeader("Access-Control-Expose-Headers", "Origin, Content-Type, Accept, Access-Control-Request-Method, Authorization");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
filterChain.doFilter(request, response);
}
}
|
package ch.heigvd.quaris.config;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by Fabien Salathe on 26.01.17.
*/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter extends OncePerRequestFilter {
/**
* Enable CORS
*
* @param request
* @param response
* @param filterChain
* @throws ServletException
* @throws IOException
*/
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.addHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Access-Control-Request-Method, Authorization");
response.addHeader("Access-Control-Expose-Headers", "Origin, Content-Type, Accept, Access-Control-Request-Method, Authorization");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
if (!request.getMethod().equals("OPTIONS")) {
filterChain.doFilter(request, response);
}
}
}
|
Fix preflights for all rules
|
Fix preflights for all rules
|
Java
|
mit
|
BafS/Quaris,BafS/Quaris,BafS/Quaris
|
java
|
## Code Before:
package ch.heigvd.quaris.config;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by Fabien Salathe on 26.01.17.
*/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter extends OncePerRequestFilter {
/**
* Enable CORS
*
* @param request
* @param response
* @param filterChain
* @throws ServletException
* @throws IOException
*/
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.addHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Access-Control-Request-Method, Authorization");
response.addHeader("Access-Control-Expose-Headers", "Origin, Content-Type, Accept, Access-Control-Request-Method, Authorization");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
filterChain.doFilter(request, response);
}
}
## Instruction:
Fix preflights for all rules
## Code After:
package ch.heigvd.quaris.config;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by Fabien Salathe on 26.01.17.
*/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter extends OncePerRequestFilter {
/**
* Enable CORS
*
* @param request
* @param response
* @param filterChain
* @throws ServletException
* @throws IOException
*/
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.addHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Access-Control-Request-Method, Authorization");
response.addHeader("Access-Control-Expose-Headers", "Origin, Content-Type, Accept, Access-Control-Request-Method, Authorization");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
if (!request.getMethod().equals("OPTIONS")) {
filterChain.doFilter(request, response);
}
}
}
|
# ... existing code ...
response.addHeader("Access-Control-Expose-Headers", "Origin, Content-Type, Accept, Access-Control-Request-Method, Authorization");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
if (!request.getMethod().equals("OPTIONS")) {
filterChain.doFilter(request, response);
}
}
}
# ... rest of the code ...
|
f016f03079f9c9c5065b6ce4227b4323a32e610e
|
core/src/main/java/foundation/stack/datamill/db/impl/UnsubscribeOnNextOperator.java
|
core/src/main/java/foundation/stack/datamill/db/impl/UnsubscribeOnNextOperator.java
|
package foundation.stack.datamill.db.impl;
import rx.Observable;
import rx.Subscriber;
import rx.exceptions.Exceptions;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Ravi Chodavarapu ([email protected])
*/
public class UnsubscribeOnNextOperator<T> implements Observable.Operator<T, T> {
private final AtomicBoolean completed = new AtomicBoolean();
@Override
public Subscriber<? super T> call(Subscriber<? super T> subscriber) {
return new Subscriber<T>() {
@Override
public void onCompleted() {
this.unsubscribe();
if (!subscriber.isUnsubscribed()) {
if (completed.compareAndSet(false, true)) {
subscriber.onCompleted();
}
}
}
@Override
public void onError(Throwable e) {
this.unsubscribe();
if (!subscriber.isUnsubscribed()) {
if (completed.compareAndSet(false, true)) {
subscriber.onError(e);
}
}
}
@Override
public void onNext(T t) {
this.unsubscribe();
if (!subscriber.isUnsubscribed()) {
if (completed.compareAndSet(false, true)) {
try {
subscriber.onNext(t);
subscriber.onCompleted();
} catch (Throwable e) {
Exceptions.throwIfFatal(e);
subscriber.onError(e);
}
}
}
}
};
}
}
|
package foundation.stack.datamill.db.impl;
import rx.Observable;
import rx.Subscriber;
import rx.exceptions.Exceptions;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Ravi Chodavarapu ([email protected])
*/
public class UnsubscribeOnNextOperator<T> implements Observable.Operator<T, T> {
@Override
public Subscriber<? super T> call(Subscriber<? super T> subscriber) {
return new Subscriber<T>() {
private final AtomicBoolean completed = new AtomicBoolean();
@Override
public void onCompleted() {
this.unsubscribe();
if (!subscriber.isUnsubscribed()) {
if (completed.compareAndSet(false, true)) {
subscriber.onCompleted();
}
}
}
@Override
public void onError(Throwable e) {
this.unsubscribe();
if (!subscriber.isUnsubscribed()) {
if (completed.compareAndSet(false, true)) {
subscriber.onError(e);
}
}
}
@Override
public void onNext(T t) {
this.unsubscribe();
if (!subscriber.isUnsubscribed()) {
if (completed.compareAndSet(false, true)) {
try {
subscriber.onNext(t);
subscriber.onCompleted();
} catch (Throwable e) {
Exceptions.throwIfFatal(e);
subscriber.onError(e);
}
}
}
}
};
}
}
|
Fix to ensure the unsubscribe on next operator used for database queries can be reused
|
Fix to ensure the unsubscribe on next operator used for database queries can be reused
|
Java
|
isc
|
rchodava/datamill
|
java
|
## Code Before:
package foundation.stack.datamill.db.impl;
import rx.Observable;
import rx.Subscriber;
import rx.exceptions.Exceptions;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Ravi Chodavarapu ([email protected])
*/
public class UnsubscribeOnNextOperator<T> implements Observable.Operator<T, T> {
private final AtomicBoolean completed = new AtomicBoolean();
@Override
public Subscriber<? super T> call(Subscriber<? super T> subscriber) {
return new Subscriber<T>() {
@Override
public void onCompleted() {
this.unsubscribe();
if (!subscriber.isUnsubscribed()) {
if (completed.compareAndSet(false, true)) {
subscriber.onCompleted();
}
}
}
@Override
public void onError(Throwable e) {
this.unsubscribe();
if (!subscriber.isUnsubscribed()) {
if (completed.compareAndSet(false, true)) {
subscriber.onError(e);
}
}
}
@Override
public void onNext(T t) {
this.unsubscribe();
if (!subscriber.isUnsubscribed()) {
if (completed.compareAndSet(false, true)) {
try {
subscriber.onNext(t);
subscriber.onCompleted();
} catch (Throwable e) {
Exceptions.throwIfFatal(e);
subscriber.onError(e);
}
}
}
}
};
}
}
## Instruction:
Fix to ensure the unsubscribe on next operator used for database queries can be reused
## Code After:
package foundation.stack.datamill.db.impl;
import rx.Observable;
import rx.Subscriber;
import rx.exceptions.Exceptions;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Ravi Chodavarapu ([email protected])
*/
public class UnsubscribeOnNextOperator<T> implements Observable.Operator<T, T> {
@Override
public Subscriber<? super T> call(Subscriber<? super T> subscriber) {
return new Subscriber<T>() {
private final AtomicBoolean completed = new AtomicBoolean();
@Override
public void onCompleted() {
this.unsubscribe();
if (!subscriber.isUnsubscribed()) {
if (completed.compareAndSet(false, true)) {
subscriber.onCompleted();
}
}
}
@Override
public void onError(Throwable e) {
this.unsubscribe();
if (!subscriber.isUnsubscribed()) {
if (completed.compareAndSet(false, true)) {
subscriber.onError(e);
}
}
}
@Override
public void onNext(T t) {
this.unsubscribe();
if (!subscriber.isUnsubscribed()) {
if (completed.compareAndSet(false, true)) {
try {
subscriber.onNext(t);
subscriber.onCompleted();
} catch (Throwable e) {
Exceptions.throwIfFatal(e);
subscriber.onError(e);
}
}
}
}
};
}
}
|
# ... existing code ...
* @author Ravi Chodavarapu ([email protected])
*/
public class UnsubscribeOnNextOperator<T> implements Observable.Operator<T, T> {
@Override
public Subscriber<? super T> call(Subscriber<? super T> subscriber) {
return new Subscriber<T>() {
private final AtomicBoolean completed = new AtomicBoolean();
@Override
public void onCompleted() {
this.unsubscribe();
# ... rest of the code ...
|
71cffcb8a8ec7e36dc389a5aa6dc2cc9769a9e97
|
distutils/tests/test_ccompiler.py
|
distutils/tests/test_ccompiler.py
|
import os
import sys
import platform
import textwrap
import sysconfig
import pytest
from distutils import ccompiler
def _make_strs(paths):
"""
Convert paths to strings for legacy compatibility.
"""
if sys.version_info > (3, 8) and platform.system() != "Windows":
return paths
return list(map(os.fspath, paths))
@pytest.fixture
def c_file(tmp_path):
c_file = tmp_path / 'foo.c'
gen_headers = ('Python.h',)
is_windows = platform.system() == "Windows"
plat_headers = ('windows.h',) * is_windows
all_headers = gen_headers + plat_headers
headers = '\n'.join(f'#include <{header}>\n' for header in all_headers)
payload = (
textwrap.dedent(
"""
#headers
void PyInit_foo(void) {}
"""
)
.lstrip()
.replace('#headers', headers)
)
c_file.write_text(payload)
return c_file
def test_set_include_dirs(c_file):
"""
Extensions should build even if set_include_dirs is invoked.
In particular, compiler-specific paths should not be overridden.
"""
compiler = ccompiler.new_compiler()
python = sysconfig.get_paths()['include']
compiler.set_include_dirs([python])
compiler.compile(_make_strs([c_file]))
|
import os
import sys
import platform
import textwrap
import sysconfig
import pytest
from distutils import ccompiler
def _make_strs(paths):
"""
Convert paths to strings for legacy compatibility.
"""
if sys.version_info > (3, 8) and platform.system() != "Windows":
return paths
return list(map(os.fspath, paths))
@pytest.fixture
def c_file(tmp_path):
c_file = tmp_path / 'foo.c'
gen_headers = ('Python.h',)
is_windows = platform.system() == "Windows"
plat_headers = ('windows.h',) * is_windows
all_headers = gen_headers + plat_headers
headers = '\n'.join(f'#include <{header}>\n' for header in all_headers)
payload = (
textwrap.dedent(
"""
#headers
void PyInit_foo(void) {}
"""
)
.lstrip()
.replace('#headers', headers)
)
c_file.write_text(payload)
return c_file
def test_set_include_dirs(c_file):
"""
Extensions should build even if set_include_dirs is invoked.
In particular, compiler-specific paths should not be overridden.
"""
compiler = ccompiler.new_compiler()
python = sysconfig.get_paths()['include']
compiler.set_include_dirs([python])
compiler.compile(_make_strs([c_file]))
# do it again, setting include dirs after any initialization
compiler.set_include_dirs([python])
compiler.compile(_make_strs([c_file]))
|
Extend the test to compile a second time after setting include dirs again.
|
Extend the test to compile a second time after setting include dirs again.
|
Python
|
mit
|
pypa/setuptools,pypa/setuptools,pypa/setuptools
|
python
|
## Code Before:
import os
import sys
import platform
import textwrap
import sysconfig
import pytest
from distutils import ccompiler
def _make_strs(paths):
"""
Convert paths to strings for legacy compatibility.
"""
if sys.version_info > (3, 8) and platform.system() != "Windows":
return paths
return list(map(os.fspath, paths))
@pytest.fixture
def c_file(tmp_path):
c_file = tmp_path / 'foo.c'
gen_headers = ('Python.h',)
is_windows = platform.system() == "Windows"
plat_headers = ('windows.h',) * is_windows
all_headers = gen_headers + plat_headers
headers = '\n'.join(f'#include <{header}>\n' for header in all_headers)
payload = (
textwrap.dedent(
"""
#headers
void PyInit_foo(void) {}
"""
)
.lstrip()
.replace('#headers', headers)
)
c_file.write_text(payload)
return c_file
def test_set_include_dirs(c_file):
"""
Extensions should build even if set_include_dirs is invoked.
In particular, compiler-specific paths should not be overridden.
"""
compiler = ccompiler.new_compiler()
python = sysconfig.get_paths()['include']
compiler.set_include_dirs([python])
compiler.compile(_make_strs([c_file]))
## Instruction:
Extend the test to compile a second time after setting include dirs again.
## Code After:
import os
import sys
import platform
import textwrap
import sysconfig
import pytest
from distutils import ccompiler
def _make_strs(paths):
"""
Convert paths to strings for legacy compatibility.
"""
if sys.version_info > (3, 8) and platform.system() != "Windows":
return paths
return list(map(os.fspath, paths))
@pytest.fixture
def c_file(tmp_path):
c_file = tmp_path / 'foo.c'
gen_headers = ('Python.h',)
is_windows = platform.system() == "Windows"
plat_headers = ('windows.h',) * is_windows
all_headers = gen_headers + plat_headers
headers = '\n'.join(f'#include <{header}>\n' for header in all_headers)
payload = (
textwrap.dedent(
"""
#headers
void PyInit_foo(void) {}
"""
)
.lstrip()
.replace('#headers', headers)
)
c_file.write_text(payload)
return c_file
def test_set_include_dirs(c_file):
"""
Extensions should build even if set_include_dirs is invoked.
In particular, compiler-specific paths should not be overridden.
"""
compiler = ccompiler.new_compiler()
python = sysconfig.get_paths()['include']
compiler.set_include_dirs([python])
compiler.compile(_make_strs([c_file]))
# do it again, setting include dirs after any initialization
compiler.set_include_dirs([python])
compiler.compile(_make_strs([c_file]))
|
...
python = sysconfig.get_paths()['include']
compiler.set_include_dirs([python])
compiler.compile(_make_strs([c_file]))
# do it again, setting include dirs after any initialization
compiler.set_include_dirs([python])
compiler.compile(_make_strs([c_file]))
...
|
23f404b61f2c9b89bb631ad0e60edf4416500f28
|
django_split/utils.py
|
django_split/utils.py
|
def overlapping(interval_a, interval_b):
al, ah = interval_a
bl, bh = interval_b
if al > ah:
raise ValueError("Interval A bounds are inverted")
if bl > bh:
raise ValueError("Interval B bounds are inverted")
return ah >= bl and bh >= al
|
from __future__ import division
import scipy
import scipy.stats
def overlapping(interval_a, interval_b):
al, ah = interval_a
bl, bh = interval_b
if al > ah:
raise ValueError("Interval A bounds are inverted")
if bl > bh:
raise ValueError("Interval B bounds are inverted")
return ah >= bl and bh >= al
def compute_normal_ppf(data_points):
mean, var = scipy.mean(data_points), scipy.var(data_points)
return scipy.stats.norm(mean, var).ppf
def compute_binomial_rate_ppf(hits, total):
if total == 0:
return lambda p: 0
distribution = scipy.binom((hits / total), total)
return lambda p: distribution.ppf(p) / total
def compute_poisson_daily_rate_ppf(start_date, end_date, hits):
days = (end_date - start_date).days
return scipy.poisson(hits / days).ppf
|
Add utilities for computing metrics
|
Add utilities for computing metrics
|
Python
|
mit
|
prophile/django_split
|
python
|
## Code Before:
def overlapping(interval_a, interval_b):
al, ah = interval_a
bl, bh = interval_b
if al > ah:
raise ValueError("Interval A bounds are inverted")
if bl > bh:
raise ValueError("Interval B bounds are inverted")
return ah >= bl and bh >= al
## Instruction:
Add utilities for computing metrics
## Code After:
from __future__ import division
import scipy
import scipy.stats
def overlapping(interval_a, interval_b):
al, ah = interval_a
bl, bh = interval_b
if al > ah:
raise ValueError("Interval A bounds are inverted")
if bl > bh:
raise ValueError("Interval B bounds are inverted")
return ah >= bl and bh >= al
def compute_normal_ppf(data_points):
mean, var = scipy.mean(data_points), scipy.var(data_points)
return scipy.stats.norm(mean, var).ppf
def compute_binomial_rate_ppf(hits, total):
if total == 0:
return lambda p: 0
distribution = scipy.binom((hits / total), total)
return lambda p: distribution.ppf(p) / total
def compute_poisson_daily_rate_ppf(start_date, end_date, hits):
days = (end_date - start_date).days
return scipy.poisson(hits / days).ppf
|
// ... existing code ...
from __future__ import division
import scipy
import scipy.stats
def overlapping(interval_a, interval_b):
al, ah = interval_a
bl, bh = interval_b
// ... modified code ...
raise ValueError("Interval B bounds are inverted")
return ah >= bl and bh >= al
def compute_normal_ppf(data_points):
mean, var = scipy.mean(data_points), scipy.var(data_points)
return scipy.stats.norm(mean, var).ppf
def compute_binomial_rate_ppf(hits, total):
if total == 0:
return lambda p: 0
distribution = scipy.binom((hits / total), total)
return lambda p: distribution.ppf(p) / total
def compute_poisson_daily_rate_ppf(start_date, end_date, hits):
days = (end_date - start_date).days
return scipy.poisson(hits / days).ppf
// ... rest of the code ...
|
e388c79e5e3c85a7bc99b7c287ef458cb0ecb951
|
src/main/java/com/github/aureliano/damihilogs/config/input/JdbcConnectionModel.java
|
src/main/java/com/github/aureliano/damihilogs/config/input/JdbcConnectionModel.java
|
package com.github.aureliano.damihilogs.config.input;
public class JdbcConnectionModel {
private String user;
private String password;
private String driver;
private String sql;
private String url;
public JdbcConnectionModel() {
super();
}
public String getUser() {
return user;
}
public JdbcConnectionModel withUser(String user) {
this.user = user;
return this;
}
public String getPassword() {
return password;
}
public JdbcConnectionModel withPassword(String password) {
this.password = password;
return this;
}
public String getSql() {
return sql;
}
public JdbcConnectionModel withSql(String sql) {
this.sql = sql;
return this;
}
public String getDriver() {
return driver;
}
public JdbcConnectionModel withDriver(String driver) {
this.driver = driver;
return this;
}
public String getOptionalUrl() {
return url;
}
public JdbcConnectionModel withOptionalUrl(String url) {
this.url = url;
return this;
}
@Override
public JdbcConnectionModel clone() {
return new JdbcConnectionModel()
.withUser(this.user)
.withPassword(this.password)
.withSql(this.sql)
.withDriver(this.driver)
.withOptionalUrl(this.url);
}
}
|
package com.github.aureliano.damihilogs.config.input;
public class JdbcConnectionModel {
private String user;
private String password;
private String driver;
private String sql;
private String url;
public JdbcConnectionModel() {
super();
}
public String getUser() {
return user;
}
public JdbcConnectionModel withUser(String user) {
this.user = user;
return this;
}
public String getPassword() {
return password;
}
public JdbcConnectionModel withPassword(String password) {
this.password = password;
return this;
}
public String getSql() {
return sql;
}
public JdbcConnectionModel withSql(String sql) {
this.sql = sql;
return this;
}
public String getDriver() {
return driver;
}
public JdbcConnectionModel withDriver(String driver) {
this.driver = driver;
return this;
}
public String getUrl() {
return url;
}
public JdbcConnectionModel withUrl(String url) {
this.url = url;
return this;
}
@Override
public JdbcConnectionModel clone() {
return new JdbcConnectionModel()
.withUser(this.user)
.withPassword(this.password)
.withSql(this.sql)
.withDriver(this.driver)
.withUrl(this.url);
}
}
|
Create input config for JDBC.
|
Create input config for JDBC.
|
Java
|
mit
|
aureliano/da-mihi-logs,aureliano/da-mihi-logs
|
java
|
## Code Before:
package com.github.aureliano.damihilogs.config.input;
public class JdbcConnectionModel {
private String user;
private String password;
private String driver;
private String sql;
private String url;
public JdbcConnectionModel() {
super();
}
public String getUser() {
return user;
}
public JdbcConnectionModel withUser(String user) {
this.user = user;
return this;
}
public String getPassword() {
return password;
}
public JdbcConnectionModel withPassword(String password) {
this.password = password;
return this;
}
public String getSql() {
return sql;
}
public JdbcConnectionModel withSql(String sql) {
this.sql = sql;
return this;
}
public String getDriver() {
return driver;
}
public JdbcConnectionModel withDriver(String driver) {
this.driver = driver;
return this;
}
public String getOptionalUrl() {
return url;
}
public JdbcConnectionModel withOptionalUrl(String url) {
this.url = url;
return this;
}
@Override
public JdbcConnectionModel clone() {
return new JdbcConnectionModel()
.withUser(this.user)
.withPassword(this.password)
.withSql(this.sql)
.withDriver(this.driver)
.withOptionalUrl(this.url);
}
}
## Instruction:
Create input config for JDBC.
## Code After:
package com.github.aureliano.damihilogs.config.input;
public class JdbcConnectionModel {
private String user;
private String password;
private String driver;
private String sql;
private String url;
public JdbcConnectionModel() {
super();
}
public String getUser() {
return user;
}
public JdbcConnectionModel withUser(String user) {
this.user = user;
return this;
}
public String getPassword() {
return password;
}
public JdbcConnectionModel withPassword(String password) {
this.password = password;
return this;
}
public String getSql() {
return sql;
}
public JdbcConnectionModel withSql(String sql) {
this.sql = sql;
return this;
}
public String getDriver() {
return driver;
}
public JdbcConnectionModel withDriver(String driver) {
this.driver = driver;
return this;
}
public String getUrl() {
return url;
}
public JdbcConnectionModel withUrl(String url) {
this.url = url;
return this;
}
@Override
public JdbcConnectionModel clone() {
return new JdbcConnectionModel()
.withUser(this.user)
.withPassword(this.password)
.withSql(this.sql)
.withDriver(this.driver)
.withUrl(this.url);
}
}
|
...
return this;
}
public String getUrl() {
return url;
}
public JdbcConnectionModel withUrl(String url) {
this.url = url;
return this;
}
...
.withPassword(this.password)
.withSql(this.sql)
.withDriver(this.driver)
.withUrl(this.url);
}
}
...
|
602c9e312d0781b38d6119ad7b4e5f41fb808c8b
|
app/src/main/java/fr/neamar/kiss/db/DB.java
|
app/src/main/java/fr/neamar/kiss/db/DB.java
|
package fr.neamar.kiss.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
class DB extends SQLiteOpenHelper {
private final static int DB_VERSION = 1;
private final static String DB_NAME = "summon.s3db";
public DB(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL("CREATE TABLE history ( _id INTEGER PRIMARY KEY AUTOINCREMENT, query TEXT NOT NULL, record TEXT NOT NULL)");
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// See
// http://www.drdobbs.com/database/using-sqlite-on-android/232900584
}
}
|
package fr.neamar.kiss.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
class DB extends SQLiteOpenHelper {
private final static int DB_VERSION = 1;
private final static String DB_NAME = "kiss.s3db";
public DB(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL("CREATE TABLE history ( _id INTEGER PRIMARY KEY AUTOINCREMENT, query TEXT, record TEXT NOT NULL)");
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// See
// http://www.drdobbs.com/database/using-sqlite-on-android/232900584
}
}
|
Store empty queries in history
|
Store empty queries in history
|
Java
|
mit
|
7ShaYaN7/SmartLauncher,kuroidoruido/KISS,alexander255/KISS,bdube/KISS,Pluggi/KISS,bitcores/KISS,losingkeys/KISS,cerisara/KISS,wilderjds/KISS,amonaslaju/KISS
|
java
|
## Code Before:
package fr.neamar.kiss.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
class DB extends SQLiteOpenHelper {
private final static int DB_VERSION = 1;
private final static String DB_NAME = "summon.s3db";
public DB(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL("CREATE TABLE history ( _id INTEGER PRIMARY KEY AUTOINCREMENT, query TEXT NOT NULL, record TEXT NOT NULL)");
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// See
// http://www.drdobbs.com/database/using-sqlite-on-android/232900584
}
}
## Instruction:
Store empty queries in history
## Code After:
package fr.neamar.kiss.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
class DB extends SQLiteOpenHelper {
private final static int DB_VERSION = 1;
private final static String DB_NAME = "kiss.s3db";
public DB(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL("CREATE TABLE history ( _id INTEGER PRIMARY KEY AUTOINCREMENT, query TEXT, record TEXT NOT NULL)");
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// See
// http://www.drdobbs.com/database/using-sqlite-on-android/232900584
}
}
|
...
class DB extends SQLiteOpenHelper {
private final static int DB_VERSION = 1;
private final static String DB_NAME = "kiss.s3db";
public DB(Context context) {
super(context, DB_NAME, null, DB_VERSION);
...
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL("CREATE TABLE history ( _id INTEGER PRIMARY KEY AUTOINCREMENT, query TEXT, record TEXT NOT NULL)");
}
@Override
...
|
bb9d1255548b46dc2ba7a85e26606b7dd4c926f3
|
examples/greeting.py
|
examples/greeting.py
|
from pyparsing import Word, alphas
# define grammar
greet = Word( alphas ) + "," + Word( alphas ) + "!"
# input string
hello = "Hello, World!"
# parse input string
print(hello, "->", greet.parseString( hello ))
|
import pyparsing as pp
# define grammar
greet = pp.Word(pp.alphas) + "," + pp.Word(pp.alphas) + pp.oneOf("! ? .")
# input string
hello = "Hello, World!"
# parse input string
print(hello, "->", greet.parseString( hello ))
# parse a bunch of input strings
greet.runTests("""\
Hello, World!
Ahoy, Matey!
Howdy, Pardner!
Morning, Neighbor!
""")
|
Update original "Hello, World!" parser to latest coding, plus runTests
|
Update original "Hello, World!" parser to latest coding, plus runTests
|
Python
|
mit
|
pyparsing/pyparsing,pyparsing/pyparsing
|
python
|
## Code Before:
from pyparsing import Word, alphas
# define grammar
greet = Word( alphas ) + "," + Word( alphas ) + "!"
# input string
hello = "Hello, World!"
# parse input string
print(hello, "->", greet.parseString( hello ))
## Instruction:
Update original "Hello, World!" parser to latest coding, plus runTests
## Code After:
import pyparsing as pp
# define grammar
greet = pp.Word(pp.alphas) + "," + pp.Word(pp.alphas) + pp.oneOf("! ? .")
# input string
hello = "Hello, World!"
# parse input string
print(hello, "->", greet.parseString( hello ))
# parse a bunch of input strings
greet.runTests("""\
Hello, World!
Ahoy, Matey!
Howdy, Pardner!
Morning, Neighbor!
""")
|
...
import pyparsing as pp
# define grammar
greet = pp.Word(pp.alphas) + "," + pp.Word(pp.alphas) + pp.oneOf("! ? .")
# input string
hello = "Hello, World!"
...
# parse input string
print(hello, "->", greet.parseString( hello ))
# parse a bunch of input strings
greet.runTests("""\
Hello, World!
Ahoy, Matey!
Howdy, Pardner!
Morning, Neighbor!
""")
...
|
be6318b2f02e14a1b717d30691351e8415e246c1
|
test/Driver/tsan.c
|
test/Driver/tsan.c
|
// RUN: %clang -target i386-unknown-unknown -fthread-sanitizer %s -S -emit-llvm -o - | FileCheck %s
// RUN: %clang -O1 -target i386-unknown-unknown -fthread-sanitizer %s -S -emit-llvm -o - | FileCheck %s
// RUN: %clang -O2 -target i386-unknown-unknown -fthread-sanitizer %s -S -emit-llvm -o - | FileCheck %s
// RUN: %clang -O3 -target i386-unknown-unknown -fthread-sanitizer %s -S -emit-llvm -o - | FileCheck %s
// RUN: %clang -target i386-unknown-unknown -fsanitize=thread %s -S -emit-llvm -o - | FileCheck %s
// Verify that -fthread-sanitizer invokes tsan instrumentation.
int foo(int *a) { return *a; }
// CHECK: __tsan_init
|
// RUN: %clang -target i386-unknown-unknown -fsanitize=thread %s -S -emit-llvm -o - | FileCheck %s
// RUN: %clang -O1 -target i386-unknown-unknown -fsanitize=thread %s -S -emit-llvm -o - | FileCheck %s
// RUN: %clang -O2 -target i386-unknown-unknown -fsanitize=thread %s -S -emit-llvm -o - | FileCheck %s
// RUN: %clang -O3 -target i386-unknown-unknown -fsanitize=thread %s -S -emit-llvm -o - | FileCheck %s
// RUN: %clang -target i386-unknown-unknown -fsanitize=thread %s -S -emit-llvm -o - | FileCheck %s
// Verify that -fsanitize=thread invokes tsan instrumentation.
int foo(int *a) { return *a; }
// CHECK: __tsan_init
|
Use the -fsanitize=thread flag to unbreak buildbot.
|
Use the -fsanitize=thread flag to unbreak buildbot.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@167472 91177308-0d34-0410-b5e6-96231b3b80d8
|
C
|
apache-2.0
|
apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang
|
c
|
## Code Before:
// RUN: %clang -target i386-unknown-unknown -fthread-sanitizer %s -S -emit-llvm -o - | FileCheck %s
// RUN: %clang -O1 -target i386-unknown-unknown -fthread-sanitizer %s -S -emit-llvm -o - | FileCheck %s
// RUN: %clang -O2 -target i386-unknown-unknown -fthread-sanitizer %s -S -emit-llvm -o - | FileCheck %s
// RUN: %clang -O3 -target i386-unknown-unknown -fthread-sanitizer %s -S -emit-llvm -o - | FileCheck %s
// RUN: %clang -target i386-unknown-unknown -fsanitize=thread %s -S -emit-llvm -o - | FileCheck %s
// Verify that -fthread-sanitizer invokes tsan instrumentation.
int foo(int *a) { return *a; }
// CHECK: __tsan_init
## Instruction:
Use the -fsanitize=thread flag to unbreak buildbot.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@167472 91177308-0d34-0410-b5e6-96231b3b80d8
## Code After:
// RUN: %clang -target i386-unknown-unknown -fsanitize=thread %s -S -emit-llvm -o - | FileCheck %s
// RUN: %clang -O1 -target i386-unknown-unknown -fsanitize=thread %s -S -emit-llvm -o - | FileCheck %s
// RUN: %clang -O2 -target i386-unknown-unknown -fsanitize=thread %s -S -emit-llvm -o - | FileCheck %s
// RUN: %clang -O3 -target i386-unknown-unknown -fsanitize=thread %s -S -emit-llvm -o - | FileCheck %s
// RUN: %clang -target i386-unknown-unknown -fsanitize=thread %s -S -emit-llvm -o - | FileCheck %s
// Verify that -fsanitize=thread invokes tsan instrumentation.
int foo(int *a) { return *a; }
// CHECK: __tsan_init
|
# ... existing code ...
// RUN: %clang -target i386-unknown-unknown -fsanitize=thread %s -S -emit-llvm -o - | FileCheck %s
// RUN: %clang -O1 -target i386-unknown-unknown -fsanitize=thread %s -S -emit-llvm -o - | FileCheck %s
// RUN: %clang -O2 -target i386-unknown-unknown -fsanitize=thread %s -S -emit-llvm -o - | FileCheck %s
// RUN: %clang -O3 -target i386-unknown-unknown -fsanitize=thread %s -S -emit-llvm -o - | FileCheck %s
// RUN: %clang -target i386-unknown-unknown -fsanitize=thread %s -S -emit-llvm -o - | FileCheck %s
// Verify that -fsanitize=thread invokes tsan instrumentation.
int foo(int *a) { return *a; }
// CHECK: __tsan_init
# ... rest of the code ...
|
8d3160f15b3c328ba86d6348a278c6825fcfa6c2
|
wcontrol/src/results.py
|
wcontrol/src/results.py
|
from wcontrol.conf.config import BMI, BFP
class results(object):
def __init__(self, control, gender):
self.bmi = self.get_bmi(control.bmi)
self.fat = self.get_fat(control.fat, gender)
def get_bmi(self, bmi):
for limit, msg in BMI:
if bmi <= limit:
return msg
def get_fat(self, fat, gender):
for limit_w, limit_m, msg in BFP:
if gender == 'Feminine' and fat <= limit_w:
return msg
if gender == 'Masculine' and fat <= limit_m:
return msg
|
from wcontrol.conf.config import BMI, BFP, MUSCLE
class results(object):
def __init__(self, control, gender):
self.bmi = self.get_bmi(control.bmi)
self.fat = self.get_fat(control.fat, gender)
self.muscle = self.get_muscle(control.muscle, gender)
def get_bmi(self, bmi):
for limit, msg in BMI:
if bmi <= limit:
return msg
def get_fat(self, fat, gender):
for limit_w, limit_m, msg in BFP:
if gender == 'Feminine' and fat <= limit_w:
return msg
if gender == 'Masculine' and fat <= limit_m:
return msg
def get_muscle(self, muscle, gender):
for limit_w, limit_m, msg in MUSCLE:
if gender == 'Feminine' and muscle <= limit_w:
return msg
if gender == 'Masculine' and muscle <= limit_m:
return msg
|
Add function to get the skeletal muscle result
|
Add function to get the skeletal muscle result
|
Python
|
mit
|
pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control
|
python
|
## Code Before:
from wcontrol.conf.config import BMI, BFP
class results(object):
def __init__(self, control, gender):
self.bmi = self.get_bmi(control.bmi)
self.fat = self.get_fat(control.fat, gender)
def get_bmi(self, bmi):
for limit, msg in BMI:
if bmi <= limit:
return msg
def get_fat(self, fat, gender):
for limit_w, limit_m, msg in BFP:
if gender == 'Feminine' and fat <= limit_w:
return msg
if gender == 'Masculine' and fat <= limit_m:
return msg
## Instruction:
Add function to get the skeletal muscle result
## Code After:
from wcontrol.conf.config import BMI, BFP, MUSCLE
class results(object):
def __init__(self, control, gender):
self.bmi = self.get_bmi(control.bmi)
self.fat = self.get_fat(control.fat, gender)
self.muscle = self.get_muscle(control.muscle, gender)
def get_bmi(self, bmi):
for limit, msg in BMI:
if bmi <= limit:
return msg
def get_fat(self, fat, gender):
for limit_w, limit_m, msg in BFP:
if gender == 'Feminine' and fat <= limit_w:
return msg
if gender == 'Masculine' and fat <= limit_m:
return msg
def get_muscle(self, muscle, gender):
for limit_w, limit_m, msg in MUSCLE:
if gender == 'Feminine' and muscle <= limit_w:
return msg
if gender == 'Masculine' and muscle <= limit_m:
return msg
|
...
from wcontrol.conf.config import BMI, BFP, MUSCLE
class results(object):
...
def __init__(self, control, gender):
self.bmi = self.get_bmi(control.bmi)
self.fat = self.get_fat(control.fat, gender)
self.muscle = self.get_muscle(control.muscle, gender)
def get_bmi(self, bmi):
for limit, msg in BMI:
...
return msg
if gender == 'Masculine' and fat <= limit_m:
return msg
def get_muscle(self, muscle, gender):
for limit_w, limit_m, msg in MUSCLE:
if gender == 'Feminine' and muscle <= limit_w:
return msg
if gender == 'Masculine' and muscle <= limit_m:
return msg
...
|
e8e00b0bc9c9552858f364526803eb9edcaf52c3
|
01/test_directions.py
|
01/test_directions.py
|
from directions import load_directions, turn, follow_directions
def test_load_directions():
with open("directions.txt") as f:
directions = [direction.strip(',')
for direction
in f.readline().strip().split()]
assert load_directions("directions.txt") == directions, \
"Failed to load directions from directions.txt."
def test_turn():
assert turn('N', 'R') == 'E'
assert turn('N', 'L') == 'W'
assert turn('E', 'R') == 'S'
assert turn('E', 'L') == 'N'
assert turn('S', 'R') == 'W'
assert turn('S', 'L') == 'E'
assert turn('W', 'R') == 'N'
assert turn('W', 'L') == 'S'
def test_follow_directions():
starting_point = (0, 0)
starting_orientation = 'N'
directions = ['R2', 'L3', 'R1']
ending_point = (3, 3)
ending_orientation = 'E'
assert (follow_directions(starting_point, starting_orientation, *directions)
== (ending_point, ending_orientation))
test_load_directions()
test_turn()
test_follow_directions()
print("All tests passed.")
|
from directions import load_directions, turn, follow_directions, expand_path
import unittest
class TestDirections(unittest.TestCase):
def test_load_directions(self):
with open("directions.txt") as f:
directions = [direction.strip(',')
for direction
in f.readline().strip().split()]
assert load_directions("directions.txt") == directions, \
"Failed to load directions from directions.txt."
def test_turn(self):
assert turn('N', 'R') == 'E'
assert turn('N', 'L') == 'W'
assert turn('E', 'R') == 'S'
assert turn('E', 'L') == 'N'
assert turn('S', 'R') == 'W'
assert turn('S', 'L') == 'E'
assert turn('W', 'R') == 'N'
assert turn('W', 'L') == 'S'
def test_follow_directions(self):
starting_point = (0, 0)
starting_orientation = 'N'
directions = ['R2', 'L3', 'R1']
ending_point = (3, 3)
ending_orientation = 'E'
assert (follow_directions(starting_point, starting_orientation, *directions)
== (ending_point, ending_orientation))
def test_expand_path(self):
assert expand_path((0, 0), (0, 3)) == [(0, 0), (0, 1), (0, 2), (0, 3)]
assert expand_path((0, 0), (3, 0)) == [(0, 0), (1, 0), (2, 0), (3, 0)]
with self.assertRaises(ValueError):
expand_path((0, 0), (1, 1))
|
Convert to unittest and add test for expand_path.
|
Convert to unittest and add test for expand_path.
|
Python
|
mit
|
machinelearningdeveloper/aoc_2016
|
python
|
## Code Before:
from directions import load_directions, turn, follow_directions
def test_load_directions():
with open("directions.txt") as f:
directions = [direction.strip(',')
for direction
in f.readline().strip().split()]
assert load_directions("directions.txt") == directions, \
"Failed to load directions from directions.txt."
def test_turn():
assert turn('N', 'R') == 'E'
assert turn('N', 'L') == 'W'
assert turn('E', 'R') == 'S'
assert turn('E', 'L') == 'N'
assert turn('S', 'R') == 'W'
assert turn('S', 'L') == 'E'
assert turn('W', 'R') == 'N'
assert turn('W', 'L') == 'S'
def test_follow_directions():
starting_point = (0, 0)
starting_orientation = 'N'
directions = ['R2', 'L3', 'R1']
ending_point = (3, 3)
ending_orientation = 'E'
assert (follow_directions(starting_point, starting_orientation, *directions)
== (ending_point, ending_orientation))
test_load_directions()
test_turn()
test_follow_directions()
print("All tests passed.")
## Instruction:
Convert to unittest and add test for expand_path.
## Code After:
from directions import load_directions, turn, follow_directions, expand_path
import unittest
class TestDirections(unittest.TestCase):
def test_load_directions(self):
with open("directions.txt") as f:
directions = [direction.strip(',')
for direction
in f.readline().strip().split()]
assert load_directions("directions.txt") == directions, \
"Failed to load directions from directions.txt."
def test_turn(self):
assert turn('N', 'R') == 'E'
assert turn('N', 'L') == 'W'
assert turn('E', 'R') == 'S'
assert turn('E', 'L') == 'N'
assert turn('S', 'R') == 'W'
assert turn('S', 'L') == 'E'
assert turn('W', 'R') == 'N'
assert turn('W', 'L') == 'S'
def test_follow_directions(self):
starting_point = (0, 0)
starting_orientation = 'N'
directions = ['R2', 'L3', 'R1']
ending_point = (3, 3)
ending_orientation = 'E'
assert (follow_directions(starting_point, starting_orientation, *directions)
== (ending_point, ending_orientation))
def test_expand_path(self):
assert expand_path((0, 0), (0, 3)) == [(0, 0), (0, 1), (0, 2), (0, 3)]
assert expand_path((0, 0), (3, 0)) == [(0, 0), (1, 0), (2, 0), (3, 0)]
with self.assertRaises(ValueError):
expand_path((0, 0), (1, 1))
|
...
from directions import load_directions, turn, follow_directions, expand_path
import unittest
class TestDirections(unittest.TestCase):
def test_load_directions(self):
with open("directions.txt") as f:
directions = [direction.strip(',')
for direction
in f.readline().strip().split()]
assert load_directions("directions.txt") == directions, \
"Failed to load directions from directions.txt."
def test_turn(self):
assert turn('N', 'R') == 'E'
assert turn('N', 'L') == 'W'
assert turn('E', 'R') == 'S'
assert turn('E', 'L') == 'N'
assert turn('S', 'R') == 'W'
assert turn('S', 'L') == 'E'
assert turn('W', 'R') == 'N'
assert turn('W', 'L') == 'S'
def test_follow_directions(self):
starting_point = (0, 0)
starting_orientation = 'N'
directions = ['R2', 'L3', 'R1']
ending_point = (3, 3)
ending_orientation = 'E'
assert (follow_directions(starting_point, starting_orientation, *directions)
== (ending_point, ending_orientation))
def test_expand_path(self):
assert expand_path((0, 0), (0, 3)) == [(0, 0), (0, 1), (0, 2), (0, 3)]
assert expand_path((0, 0), (3, 0)) == [(0, 0), (1, 0), (2, 0), (3, 0)]
with self.assertRaises(ValueError):
expand_path((0, 0), (1, 1))
...
|
fa5bb37159d09c5bff53b83a4821e3f154892d1d
|
numba/cuda/device_init.py
|
numba/cuda/device_init.py
|
from __future__ import print_function, absolute_import, division
# Re export
from .stubs import (threadIdx, blockIdx, blockDim, gridDim, syncthreads,
shared, local, const, grid, gridsize, atomic,
threadfence_block, threadfence_system,
threadfence)
from .cudadrv.error import CudaSupportError
from .cudadrv import nvvm
from . import initialize
from .errors import KernelRuntimeError
from .decorators import jit, autojit, declare_device
from .api import *
from .api import _auto_device
from .kernels import reduction
reduce = Reduce = reduction.Reduce
def is_available():
"""Returns a boolean to indicate the availability of a CUDA GPU.
This will initialize the driver if it hasn't been initialized.
"""
return driver.driver.is_available and nvvm.is_available()
def cuda_error():
"""Returns None or an exception if the CUDA driver fails to initialize.
"""
return driver.driver.initialization_error
initialize.initialize_all()
|
from __future__ import print_function, absolute_import, division
# Re export
from .stubs import (threadIdx, blockIdx, blockDim, gridDim, syncthreads,
shared, local, const, grid, gridsize, atomic,
threadfence_block, threadfence_system,
threadfence)
from .cudadrv.error import CudaSupportError
from .cudadrv import nvvm
from . import initialize
from .errors import KernelRuntimeError
from .decorators import jit, autojit, declare_device
from .api import *
from .api import _auto_device
from .kernels import reduction
reduce = Reduce = reduction.Reduce
def is_available():
"""Returns a boolean to indicate the availability of a CUDA GPU.
This will initialize the driver if it hasn't been initialized.
"""
# whilst `driver.is_available` will init the driver itself,
# the driver initialization may raise and as a result break
# test discovery/orchestration as `cuda.is_available` is often
# used as a guard for whether to run a CUDA test, the try/except
# below is to handle this case.
driver_is_available = False
try:
driver_is_available = driver.driver.is_available
except CudaSupportError:
pass
return driver_is_available and nvvm.is_available()
def cuda_error():
"""Returns None or an exception if the CUDA driver fails to initialize.
"""
return driver.driver.initialization_error
initialize.initialize_all()
|
Fix issue with test discovery and broken CUDA drivers.
|
Fix issue with test discovery and broken CUDA drivers.
This patch allows the test discovery mechanism to work even in the
case of a broken/misconfigured CUDA driver.
Fixes #2841
|
Python
|
bsd-2-clause
|
sklam/numba,cpcloud/numba,sklam/numba,numba/numba,seibert/numba,jriehl/numba,numba/numba,stuartarchibald/numba,jriehl/numba,IntelLabs/numba,cpcloud/numba,stuartarchibald/numba,gmarkall/numba,IntelLabs/numba,jriehl/numba,seibert/numba,numba/numba,jriehl/numba,gmarkall/numba,numba/numba,sklam/numba,seibert/numba,stuartarchibald/numba,IntelLabs/numba,sklam/numba,IntelLabs/numba,jriehl/numba,stonebig/numba,cpcloud/numba,IntelLabs/numba,stonebig/numba,stonebig/numba,gmarkall/numba,stonebig/numba,seibert/numba,cpcloud/numba,stuartarchibald/numba,gmarkall/numba,sklam/numba,seibert/numba,stonebig/numba,gmarkall/numba,numba/numba,stuartarchibald/numba,cpcloud/numba
|
python
|
## Code Before:
from __future__ import print_function, absolute_import, division
# Re export
from .stubs import (threadIdx, blockIdx, blockDim, gridDim, syncthreads,
shared, local, const, grid, gridsize, atomic,
threadfence_block, threadfence_system,
threadfence)
from .cudadrv.error import CudaSupportError
from .cudadrv import nvvm
from . import initialize
from .errors import KernelRuntimeError
from .decorators import jit, autojit, declare_device
from .api import *
from .api import _auto_device
from .kernels import reduction
reduce = Reduce = reduction.Reduce
def is_available():
"""Returns a boolean to indicate the availability of a CUDA GPU.
This will initialize the driver if it hasn't been initialized.
"""
return driver.driver.is_available and nvvm.is_available()
def cuda_error():
"""Returns None or an exception if the CUDA driver fails to initialize.
"""
return driver.driver.initialization_error
initialize.initialize_all()
## Instruction:
Fix issue with test discovery and broken CUDA drivers.
This patch allows the test discovery mechanism to work even in the
case of a broken/misconfigured CUDA driver.
Fixes #2841
## Code After:
from __future__ import print_function, absolute_import, division
# Re export
from .stubs import (threadIdx, blockIdx, blockDim, gridDim, syncthreads,
shared, local, const, grid, gridsize, atomic,
threadfence_block, threadfence_system,
threadfence)
from .cudadrv.error import CudaSupportError
from .cudadrv import nvvm
from . import initialize
from .errors import KernelRuntimeError
from .decorators import jit, autojit, declare_device
from .api import *
from .api import _auto_device
from .kernels import reduction
reduce = Reduce = reduction.Reduce
def is_available():
"""Returns a boolean to indicate the availability of a CUDA GPU.
This will initialize the driver if it hasn't been initialized.
"""
# whilst `driver.is_available` will init the driver itself,
# the driver initialization may raise and as a result break
# test discovery/orchestration as `cuda.is_available` is often
# used as a guard for whether to run a CUDA test, the try/except
# below is to handle this case.
driver_is_available = False
try:
driver_is_available = driver.driver.is_available
except CudaSupportError:
pass
return driver_is_available and nvvm.is_available()
def cuda_error():
"""Returns None or an exception if the CUDA driver fails to initialize.
"""
return driver.driver.initialization_error
initialize.initialize_all()
|
...
This will initialize the driver if it hasn't been initialized.
"""
# whilst `driver.is_available` will init the driver itself,
# the driver initialization may raise and as a result break
# test discovery/orchestration as `cuda.is_available` is often
# used as a guard for whether to run a CUDA test, the try/except
# below is to handle this case.
driver_is_available = False
try:
driver_is_available = driver.driver.is_available
except CudaSupportError:
pass
return driver_is_available and nvvm.is_available()
def cuda_error():
"""Returns None or an exception if the CUDA driver fails to initialize.
...
|
fff33f72d40399bcb5e562f52f42d389117c9e5e
|
examples/simple/src/main/java/coffee/CoffeeApp.java
|
examples/simple/src/main/java/coffee/CoffeeApp.java
|
package coffee;
import dagger.Component;
import javax.inject.Singleton;
public class CoffeeApp {
@Singleton
@Component(modules = { DripCoffeeModule.class })
public interface Coffee {
CoffeeMaker maker();
}
public static void main(String[] args) {
Coffee coffee = DaggerCoffeeApp_Coffee.builder().build();
coffee.maker().brew();
}
}
|
package coffee;
import dagger.Component;
import javax.inject.Singleton;
public class CoffeeApp {
@Singleton
@Component(modules = { DripCoffeeModule.class })
public interface CoffeeShop {
CoffeeMaker maker();
}
public static void main(String[] args) {
CoffeeShop coffeeShop = DaggerCoffeeApp_CoffeeShop.builder().build();
coffeeShop.maker().brew();
}
}
|
Align the user's guide's usage of CoffeeShop with the sample code
|
Align the user's guide's usage of CoffeeShop with the sample code
Fixes https://github.com/google/dagger/pull/809
Closes https://github.com/google/dagger/pull/810
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=167519876
|
Java
|
apache-2.0
|
google/dagger,dushmis/dagger,cgruber/dagger,ronshapiro/dagger,ronshapiro/dagger,cgruber/dagger,dushmis/dagger,ze-pequeno/dagger,ze-pequeno/dagger,google/dagger,google/dagger,cgruber/dagger,ze-pequeno/dagger,google/dagger,ronshapiro/dagger,ze-pequeno/dagger
|
java
|
## Code Before:
package coffee;
import dagger.Component;
import javax.inject.Singleton;
public class CoffeeApp {
@Singleton
@Component(modules = { DripCoffeeModule.class })
public interface Coffee {
CoffeeMaker maker();
}
public static void main(String[] args) {
Coffee coffee = DaggerCoffeeApp_Coffee.builder().build();
coffee.maker().brew();
}
}
## Instruction:
Align the user's guide's usage of CoffeeShop with the sample code
Fixes https://github.com/google/dagger/pull/809
Closes https://github.com/google/dagger/pull/810
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=167519876
## Code After:
package coffee;
import dagger.Component;
import javax.inject.Singleton;
public class CoffeeApp {
@Singleton
@Component(modules = { DripCoffeeModule.class })
public interface CoffeeShop {
CoffeeMaker maker();
}
public static void main(String[] args) {
CoffeeShop coffeeShop = DaggerCoffeeApp_CoffeeShop.builder().build();
coffeeShop.maker().brew();
}
}
|
// ... existing code ...
public class CoffeeApp {
@Singleton
@Component(modules = { DripCoffeeModule.class })
public interface CoffeeShop {
CoffeeMaker maker();
}
public static void main(String[] args) {
CoffeeShop coffeeShop = DaggerCoffeeApp_CoffeeShop.builder().build();
coffeeShop.maker().brew();
}
}
// ... rest of the code ...
|
3047ec8ca34de9cafbf774bad49ef2d5cf7d8dd1
|
src/main/java/com/lyubenblagoev/postfixrest/configuration/CorsConfiguration.java
|
src/main/java/com/lyubenblagoev/postfixrest/configuration/CorsConfiguration.java
|
package com.lyubenblagoev.postfixrest.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfiguration {
@Bean
WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/v1/**");
}
};
}
}
|
package com.lyubenblagoev.postfixrest.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfiguration {
@Bean
WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/v1/**")
.allowedMethods("*")
.allowedOrigins("*");
}
};
}
}
|
Improve CORS configuration to allow all methods and origins
|
Improve CORS configuration to allow all methods and origins
|
Java
|
apache-2.0
|
lyubenblagoev/postfix-rest-server
|
java
|
## Code Before:
package com.lyubenblagoev.postfixrest.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfiguration {
@Bean
WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/v1/**");
}
};
}
}
## Instruction:
Improve CORS configuration to allow all methods and origins
## Code After:
package com.lyubenblagoev.postfixrest.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfiguration {
@Bean
WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/v1/**")
.allowedMethods("*")
.allowedOrigins("*");
}
};
}
}
|
// ... existing code ...
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/v1/**")
.allowedMethods("*")
.allowedOrigins("*");
}
};
}
// ... rest of the code ...
|
4771a29b5042fc9496f4d72f76c0151fe73716ba
|
src/placement/apollonius_labels_arranger.h
|
src/placement/apollonius_labels_arranger.h
|
class CudaArrayProvider;
namespace Placement
{
/**
* \brief Returns the labels in an order defined by the apollonius graph
*
*/
class ApolloniusLabelsArranger : public LabelsArranger
{
public:
ApolloniusLabelsArranger() = default;
virtual ~ApolloniusLabelsArranger();
void
initialize(std::shared_ptr<CudaArrayProvider> distanceTransformTextureMapper,
std::shared_ptr<CudaArrayProvider> apolloniusTextureMapper);
virtual std::vector<Label>
getArrangement(const LabellerFrameData &frameData,
std::shared_ptr<LabelsContainer> labels);
private:
std::shared_ptr<CudaArrayProvider> distanceTransformTextureMapper;
std::shared_ptr<CudaArrayProvider> apolloniusTextureMapper;
std::vector<Eigen::Vector4f>
createLabelSeeds(Eigen::Vector2i size, Eigen::Matrix4f viewProjection,
std::shared_ptr<LabelsContainer> labels);
};
} // namespace Placement
#endif // SRC_PLACEMENT_APOLLONIUS_LABELS_ARRANGER_H_
|
class CudaArrayProvider;
namespace Placement
{
/**
* \brief Returns the labels in an order defined by the apollonius graph
*
*/
class ApolloniusLabelsArranger : public LabelsArranger
{
public:
ApolloniusLabelsArranger() = default;
void
initialize(std::shared_ptr<CudaArrayProvider> distanceTransformTextureMapper,
std::shared_ptr<CudaArrayProvider> apolloniusTextureMapper);
virtual std::vector<Label>
getArrangement(const LabellerFrameData &frameData,
std::shared_ptr<LabelsContainer> labels);
private:
std::shared_ptr<CudaArrayProvider> distanceTransformTextureMapper;
std::shared_ptr<CudaArrayProvider> apolloniusTextureMapper;
std::vector<Eigen::Vector4f>
createLabelSeeds(Eigen::Vector2i size, Eigen::Matrix4f viewProjection,
std::shared_ptr<LabelsContainer> labels);
};
} // namespace Placement
#endif // SRC_PLACEMENT_APOLLONIUS_LABELS_ARRANGER_H_
|
Remove unused and not implement ApolloniusLabelsArranger destructor.
|
Remove unused and not implement ApolloniusLabelsArranger destructor.
|
C
|
mit
|
Christof/voly-labeller,Christof/voly-labeller,Christof/voly-labeller,Christof/voly-labeller
|
c
|
## Code Before:
class CudaArrayProvider;
namespace Placement
{
/**
* \brief Returns the labels in an order defined by the apollonius graph
*
*/
class ApolloniusLabelsArranger : public LabelsArranger
{
public:
ApolloniusLabelsArranger() = default;
virtual ~ApolloniusLabelsArranger();
void
initialize(std::shared_ptr<CudaArrayProvider> distanceTransformTextureMapper,
std::shared_ptr<CudaArrayProvider> apolloniusTextureMapper);
virtual std::vector<Label>
getArrangement(const LabellerFrameData &frameData,
std::shared_ptr<LabelsContainer> labels);
private:
std::shared_ptr<CudaArrayProvider> distanceTransformTextureMapper;
std::shared_ptr<CudaArrayProvider> apolloniusTextureMapper;
std::vector<Eigen::Vector4f>
createLabelSeeds(Eigen::Vector2i size, Eigen::Matrix4f viewProjection,
std::shared_ptr<LabelsContainer> labels);
};
} // namespace Placement
#endif // SRC_PLACEMENT_APOLLONIUS_LABELS_ARRANGER_H_
## Instruction:
Remove unused and not implement ApolloniusLabelsArranger destructor.
## Code After:
class CudaArrayProvider;
namespace Placement
{
/**
* \brief Returns the labels in an order defined by the apollonius graph
*
*/
class ApolloniusLabelsArranger : public LabelsArranger
{
public:
ApolloniusLabelsArranger() = default;
void
initialize(std::shared_ptr<CudaArrayProvider> distanceTransformTextureMapper,
std::shared_ptr<CudaArrayProvider> apolloniusTextureMapper);
virtual std::vector<Label>
getArrangement(const LabellerFrameData &frameData,
std::shared_ptr<LabelsContainer> labels);
private:
std::shared_ptr<CudaArrayProvider> distanceTransformTextureMapper;
std::shared_ptr<CudaArrayProvider> apolloniusTextureMapper;
std::vector<Eigen::Vector4f>
createLabelSeeds(Eigen::Vector2i size, Eigen::Matrix4f viewProjection,
std::shared_ptr<LabelsContainer> labels);
};
} // namespace Placement
#endif // SRC_PLACEMENT_APOLLONIUS_LABELS_ARRANGER_H_
|
// ... existing code ...
{
public:
ApolloniusLabelsArranger() = default;
void
initialize(std::shared_ptr<CudaArrayProvider> distanceTransformTextureMapper,
// ... rest of the code ...
|
41c7d60556dff4be1c5f39cf694470d3af4869f0
|
qual/iso.py
|
qual/iso.py
|
from datetime import date, timedelta
def iso_to_gregorian(year, week, weekday):
jan_8 = date(year, 1, 8).isocalendar()
offset = (week - jan_8[1]) * 7 + (weekday - jan_8[2])
return date(year, 1, 8) + timedelta(days=offset)
|
from datetime import date, timedelta
def iso_to_gregorian(year, week, weekday):
if week < 1 or week > 54:
raise ValueError("Week number %d is invalid for an ISO calendar." % (week, ))
jan_8 = date(year, 1, 8).isocalendar()
offset = (week - jan_8[1]) * 7 + (weekday - jan_8[2])
d = date(year, 1, 8) + timedelta(days=offset)
if d.isocalendar()[0] != year:
raise ValueError("Week number %d is invalid for ISO year %d." % (week, year))
return d
|
Add checks for a reasonable week number.
|
Add checks for a reasonable week number.
|
Python
|
apache-2.0
|
jwg4/calexicon,jwg4/qual
|
python
|
## Code Before:
from datetime import date, timedelta
def iso_to_gregorian(year, week, weekday):
jan_8 = date(year, 1, 8).isocalendar()
offset = (week - jan_8[1]) * 7 + (weekday - jan_8[2])
return date(year, 1, 8) + timedelta(days=offset)
## Instruction:
Add checks for a reasonable week number.
## Code After:
from datetime import date, timedelta
def iso_to_gregorian(year, week, weekday):
if week < 1 or week > 54:
raise ValueError("Week number %d is invalid for an ISO calendar." % (week, ))
jan_8 = date(year, 1, 8).isocalendar()
offset = (week - jan_8[1]) * 7 + (weekday - jan_8[2])
d = date(year, 1, 8) + timedelta(days=offset)
if d.isocalendar()[0] != year:
raise ValueError("Week number %d is invalid for ISO year %d." % (week, year))
return d
|
# ... existing code ...
from datetime import date, timedelta
def iso_to_gregorian(year, week, weekday):
if week < 1 or week > 54:
raise ValueError("Week number %d is invalid for an ISO calendar." % (week, ))
jan_8 = date(year, 1, 8).isocalendar()
offset = (week - jan_8[1]) * 7 + (weekday - jan_8[2])
d = date(year, 1, 8) + timedelta(days=offset)
if d.isocalendar()[0] != year:
raise ValueError("Week number %d is invalid for ISO year %d." % (week, year))
return d
# ... rest of the code ...
|
7f42966277eff0d16fd15d5192cffcf7a91aae2e
|
expyfun/__init__.py
|
expyfun/__init__.py
|
__version__ = '1.1.0.git'
# have to import verbose first since it's needed by many things
from ._utils import set_log_level, set_config, \
get_config, get_config_path
from ._utils import verbose_dec as verbose
from ._experiment_controller import ExperimentController, wait_secs
from ._eyelink_controller import EyelinkController
from ._create_system_config import create_system_config
# initialize logging
set_log_level(None, False)
|
__version__ = '1.1.0.git'
# have to import verbose first since it's needed by many things
from ._utils import set_log_level, set_config, \
get_config, get_config_path
from ._utils import verbose_dec as verbose
from ._experiment_controller import ExperimentController, wait_secs
from ._eyelink_controller import EyelinkController
from ._create_system_config import create_system_config
from . import analyze # fast enough, include here
# initialize logging
set_log_level(None, False)
|
Add `analyze` to `expyfun` init
|
FIX: Add `analyze` to `expyfun` init
|
Python
|
bsd-3-clause
|
LABSN/expyfun,rkmaddox/expyfun,Eric89GXL/expyfun,lkishline/expyfun,drammock/expyfun
|
python
|
## Code Before:
__version__ = '1.1.0.git'
# have to import verbose first since it's needed by many things
from ._utils import set_log_level, set_config, \
get_config, get_config_path
from ._utils import verbose_dec as verbose
from ._experiment_controller import ExperimentController, wait_secs
from ._eyelink_controller import EyelinkController
from ._create_system_config import create_system_config
# initialize logging
set_log_level(None, False)
## Instruction:
FIX: Add `analyze` to `expyfun` init
## Code After:
__version__ = '1.1.0.git'
# have to import verbose first since it's needed by many things
from ._utils import set_log_level, set_config, \
get_config, get_config_path
from ._utils import verbose_dec as verbose
from ._experiment_controller import ExperimentController, wait_secs
from ._eyelink_controller import EyelinkController
from ._create_system_config import create_system_config
from . import analyze # fast enough, include here
# initialize logging
set_log_level(None, False)
|
...
from ._experiment_controller import ExperimentController, wait_secs
from ._eyelink_controller import EyelinkController
from ._create_system_config import create_system_config
from . import analyze # fast enough, include here
# initialize logging
set_log_level(None, False)
...
|
f5aeb949f781cb1f10e99916822d977b946ad3c7
|
src/test/java/com/github/ferstl/ParallelStreamSupportTest.java
|
src/test/java/com/github/ferstl/ParallelStreamSupportTest.java
|
package com.github.ferstl;
import java.util.Arrays;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ParallelStreamSupportTest {
private ForkJoinPool workerPool;
@Before
public void before() {
this.workerPool = new ForkJoinPool(1);
}
@After
public void after() throws InterruptedException {
this.workerPool.shutdown();
this.workerPool.awaitTermination(1, TimeUnit.SECONDS);
}
@Test
public void test() {
ParallelStreamSupport.parallelStream(Arrays.asList("a"), this.workerPool)
.forEach(e -> System.out.println(Thread.currentThread().getName()));
}
}
|
package com.github.ferstl;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.matchesPattern;
import static org.junit.Assert.assertThat;
public class ParallelStreamSupportTest {
private static final Pattern FORK_JOIN_THREAD_NAME_PATTERN = Pattern.compile("ForkJoinPool-\\d+-worker-\\d+");
private ForkJoinPool workerPool;
@Before
public void before() {
this.workerPool = new ForkJoinPool(1);
}
@After
public void after() throws InterruptedException {
this.workerPool.shutdown();
this.workerPool.awaitTermination(1, TimeUnit.SECONDS);
}
/**
* Verify that we use the correct thread name pattern.
*/
@Test
public void testForkJoinPoolThreadNamePattern() {
ForkJoinTask<String> task = ForkJoinTask.adapt(() -> Thread.currentThread().getName());
String threadName = this.workerPool.invoke(task);
assertThat(threadName, matchesPattern(FORK_JOIN_THREAD_NAME_PATTERN));
}
@Test
@Ignore("Not yet implemented")
public void collect() {
List<String> result = ParallelStreamSupport.parallelStream(singletonList("a"), this.workerPool)
.map(e -> Thread.currentThread().getName())
.collect(toList());
assertThat(result, contains(matchesPattern(FORK_JOIN_THREAD_NAME_PATTERN)));
}
}
|
Add tets for thread name
|
Add tets for thread name
|
Java
|
mit
|
ferstl/parallel-stream-support
|
java
|
## Code Before:
package com.github.ferstl;
import java.util.Arrays;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ParallelStreamSupportTest {
private ForkJoinPool workerPool;
@Before
public void before() {
this.workerPool = new ForkJoinPool(1);
}
@After
public void after() throws InterruptedException {
this.workerPool.shutdown();
this.workerPool.awaitTermination(1, TimeUnit.SECONDS);
}
@Test
public void test() {
ParallelStreamSupport.parallelStream(Arrays.asList("a"), this.workerPool)
.forEach(e -> System.out.println(Thread.currentThread().getName()));
}
}
## Instruction:
Add tets for thread name
## Code After:
package com.github.ferstl;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.matchesPattern;
import static org.junit.Assert.assertThat;
public class ParallelStreamSupportTest {
private static final Pattern FORK_JOIN_THREAD_NAME_PATTERN = Pattern.compile("ForkJoinPool-\\d+-worker-\\d+");
private ForkJoinPool workerPool;
@Before
public void before() {
this.workerPool = new ForkJoinPool(1);
}
@After
public void after() throws InterruptedException {
this.workerPool.shutdown();
this.workerPool.awaitTermination(1, TimeUnit.SECONDS);
}
/**
* Verify that we use the correct thread name pattern.
*/
@Test
public void testForkJoinPoolThreadNamePattern() {
ForkJoinTask<String> task = ForkJoinTask.adapt(() -> Thread.currentThread().getName());
String threadName = this.workerPool.invoke(task);
assertThat(threadName, matchesPattern(FORK_JOIN_THREAD_NAME_PATTERN));
}
@Test
@Ignore("Not yet implemented")
public void collect() {
List<String> result = ParallelStreamSupport.parallelStream(singletonList("a"), this.workerPool)
.map(e -> Thread.currentThread().getName())
.collect(toList());
assertThat(result, contains(matchesPattern(FORK_JOIN_THREAD_NAME_PATTERN)));
}
}
|
// ... existing code ...
package com.github.ferstl;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.matchesPattern;
import static org.junit.Assert.assertThat;
public class ParallelStreamSupportTest {
private static final Pattern FORK_JOIN_THREAD_NAME_PATTERN = Pattern.compile("ForkJoinPool-\\d+-worker-\\d+");
private ForkJoinPool workerPool;
// ... modified code ...
this.workerPool.awaitTermination(1, TimeUnit.SECONDS);
}
/**
* Verify that we use the correct thread name pattern.
*/
@Test
public void testForkJoinPoolThreadNamePattern() {
ForkJoinTask<String> task = ForkJoinTask.adapt(() -> Thread.currentThread().getName());
String threadName = this.workerPool.invoke(task);
assertThat(threadName, matchesPattern(FORK_JOIN_THREAD_NAME_PATTERN));
}
@Test
@Ignore("Not yet implemented")
public void collect() {
List<String> result = ParallelStreamSupport.parallelStream(singletonList("a"), this.workerPool)
.map(e -> Thread.currentThread().getName())
.collect(toList());
assertThat(result, contains(matchesPattern(FORK_JOIN_THREAD_NAME_PATTERN)));
}
}
// ... rest of the code ...
|
1e6aeb9c7b07313a9efe7cb0e1380f4f2219c7dc
|
tests/utils.py
|
tests/utils.py
|
import os
from carrot.connection import BrokerConnection
AMQP_HOST = os.environ.get('AMQP_HOST', "localhost")
AMQP_PORT = os.environ.get('AMQP_PORT', 5672)
AMQP_VHOST = os.environ.get('AMQP_VHOST', "/")
AMQP_USER = os.environ.get('AMQP_USER', "guest")
AMQP_PASSWORD = os.environ.get('AMQP_PASSWORD', "guest")
STOMP_HOST = os.environ.get('STOMP_HOST', 'localhost')
STOMP_PORT = os.environ.get('STOMP_PORT', 61613)
def test_connection_args():
return {"hostname": AMQP_HOST, "port": AMQP_PORT,
"virtual_host": AMQP_VHOST, "userid": AMQP_USER,
"password": AMQP_PASSWORD}
def test_stomp_connection_args():
return {"hostname": STOMP_HOST, "port": STOMP_PORT}
def establish_test_connection():
return BrokerConnection(**test_connection_args())
|
import os
from carrot.connection import BrokerConnection
AMQP_HOST = os.environ.get('AMQP_HOST', "localhost")
AMQP_PORT = os.environ.get('AMQP_PORT', 5672)
AMQP_VHOST = os.environ.get('AMQP_VHOST', "/")
AMQP_USER = os.environ.get('AMQP_USER', "guest")
AMQP_PASSWORD = os.environ.get('AMQP_PASSWORD', "guest")
STOMP_HOST = os.environ.get('STOMP_HOST', 'localhost')
STOMP_PORT = os.environ.get('STOMP_PORT', 61613)
STOMP_QUEUE = os.environ.get('STOMP_QUEUE', '/queue/testcarrot')
def test_connection_args():
return {"hostname": AMQP_HOST, "port": AMQP_PORT,
"virtual_host": AMQP_VHOST, "userid": AMQP_USER,
"password": AMQP_PASSWORD}
def test_stomp_connection_args():
return {"hostname": STOMP_HOST, "port": STOMP_PORT}
def establish_test_connection():
return BrokerConnection(**test_connection_args())
|
Add test configuration vars: STOMP_HOST + STOMP_PORT
|
Add test configuration vars: STOMP_HOST + STOMP_PORT
|
Python
|
bsd-3-clause
|
ask/carrot,ask/carrot
|
python
|
## Code Before:
import os
from carrot.connection import BrokerConnection
AMQP_HOST = os.environ.get('AMQP_HOST', "localhost")
AMQP_PORT = os.environ.get('AMQP_PORT', 5672)
AMQP_VHOST = os.environ.get('AMQP_VHOST', "/")
AMQP_USER = os.environ.get('AMQP_USER', "guest")
AMQP_PASSWORD = os.environ.get('AMQP_PASSWORD', "guest")
STOMP_HOST = os.environ.get('STOMP_HOST', 'localhost')
STOMP_PORT = os.environ.get('STOMP_PORT', 61613)
def test_connection_args():
return {"hostname": AMQP_HOST, "port": AMQP_PORT,
"virtual_host": AMQP_VHOST, "userid": AMQP_USER,
"password": AMQP_PASSWORD}
def test_stomp_connection_args():
return {"hostname": STOMP_HOST, "port": STOMP_PORT}
def establish_test_connection():
return BrokerConnection(**test_connection_args())
## Instruction:
Add test configuration vars: STOMP_HOST + STOMP_PORT
## Code After:
import os
from carrot.connection import BrokerConnection
AMQP_HOST = os.environ.get('AMQP_HOST', "localhost")
AMQP_PORT = os.environ.get('AMQP_PORT', 5672)
AMQP_VHOST = os.environ.get('AMQP_VHOST', "/")
AMQP_USER = os.environ.get('AMQP_USER', "guest")
AMQP_PASSWORD = os.environ.get('AMQP_PASSWORD', "guest")
STOMP_HOST = os.environ.get('STOMP_HOST', 'localhost')
STOMP_PORT = os.environ.get('STOMP_PORT', 61613)
STOMP_QUEUE = os.environ.get('STOMP_QUEUE', '/queue/testcarrot')
def test_connection_args():
return {"hostname": AMQP_HOST, "port": AMQP_PORT,
"virtual_host": AMQP_VHOST, "userid": AMQP_USER,
"password": AMQP_PASSWORD}
def test_stomp_connection_args():
return {"hostname": STOMP_HOST, "port": STOMP_PORT}
def establish_test_connection():
return BrokerConnection(**test_connection_args())
|
# ... existing code ...
STOMP_HOST = os.environ.get('STOMP_HOST', 'localhost')
STOMP_PORT = os.environ.get('STOMP_PORT', 61613)
STOMP_QUEUE = os.environ.get('STOMP_QUEUE', '/queue/testcarrot')
def test_connection_args():
# ... rest of the code ...
|
ef43e04970151ec5bba9688f268b2f85b5debd3f
|
bfg9000/builtins/__init__.py
|
bfg9000/builtins/__init__.py
|
import functools
import glob
import os
import pkgutil
_all_builtins = {}
_loaded_builtins = False
class Binder(object):
def __init__(self, fn):
self.fn = fn
def bind(self, build_inputs, env):
return functools.partial(self.fn, build_inputs, env)
def builtin(fn):
bound = Binder(fn)
_all_builtins[fn.__name__] = bound
return bound
def _load_builtins():
for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'):
loader.find_module(name).load_module(name)
def bind(build_inputs, env):
global _loaded_builtins
if not _loaded_builtins:
_load_builtins()
_loaded_builtins = True
result = {}
for k, v in _all_builtins.iteritems():
result[k] = v.bind(build_inputs, env)
return result
|
import functools
import glob
import os
import pkgutil
_all_builtins = {}
_loaded_builtins = False
class Binder(object):
def __init__(self, fn):
self.fn = fn
def bind(self, build_inputs, env):
return functools.partial(self.fn, build_inputs, env)
def builtin(fn):
bound = Binder(fn)
_all_builtins[fn.__name__] = bound
return bound
def _load_builtins():
for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'):
loader.find_module(name).load_module(name)
def bind(build_inputs, env):
global _loaded_builtins
if not _loaded_builtins:
_load_builtins()
_loaded_builtins = True
result = {}
for k, v in _all_builtins.iteritems():
result[k] = v.bind(build_inputs, env)
result['env'] = env
return result
|
Make the Environment object available to build.bfg files
|
Make the Environment object available to build.bfg files
|
Python
|
bsd-3-clause
|
jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000
|
python
|
## Code Before:
import functools
import glob
import os
import pkgutil
_all_builtins = {}
_loaded_builtins = False
class Binder(object):
def __init__(self, fn):
self.fn = fn
def bind(self, build_inputs, env):
return functools.partial(self.fn, build_inputs, env)
def builtin(fn):
bound = Binder(fn)
_all_builtins[fn.__name__] = bound
return bound
def _load_builtins():
for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'):
loader.find_module(name).load_module(name)
def bind(build_inputs, env):
global _loaded_builtins
if not _loaded_builtins:
_load_builtins()
_loaded_builtins = True
result = {}
for k, v in _all_builtins.iteritems():
result[k] = v.bind(build_inputs, env)
return result
## Instruction:
Make the Environment object available to build.bfg files
## Code After:
import functools
import glob
import os
import pkgutil
_all_builtins = {}
_loaded_builtins = False
class Binder(object):
def __init__(self, fn):
self.fn = fn
def bind(self, build_inputs, env):
return functools.partial(self.fn, build_inputs, env)
def builtin(fn):
bound = Binder(fn)
_all_builtins[fn.__name__] = bound
return bound
def _load_builtins():
for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'):
loader.find_module(name).load_module(name)
def bind(build_inputs, env):
global _loaded_builtins
if not _loaded_builtins:
_load_builtins()
_loaded_builtins = True
result = {}
for k, v in _all_builtins.iteritems():
result[k] = v.bind(build_inputs, env)
result['env'] = env
return result
|
# ... existing code ...
result = {}
for k, v in _all_builtins.iteritems():
result[k] = v.bind(build_inputs, env)
result['env'] = env
return result
# ... rest of the code ...
|
b7174c504f0a59b9084a8c53a9999aac8ae1fcfc
|
src/main/java/com/skelril/skree/service/ModifierService.java
|
src/main/java/com/skelril/skree/service/ModifierService.java
|
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.skelril.skree.service;
import com.skelril.nitro.Clause;
import java.util.Collection;
public interface ModifierService {
void setExpiry(String modifierName, long time);
long expiryOf(String modifierName);
default long statusOf(String modifierName) {
return Math.max(expiryOf(modifierName) - System.currentTimeMillis(), 0);
}
default boolean isActive(String modifierName) {
return statusOf(modifierName) != 0;
}
Collection<Clause<String, Long>> getActiveModifiers();
}
|
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.skelril.skree.service;
import com.skelril.nitro.Clause;
import java.util.Collection;
public interface ModifierService {
void setExpiry(String modifier, long time);
long expiryOf(String modifier);
default long statusOf(String modifier) {
return Math.max(expiryOf(modifier) - System.currentTimeMillis(), 0);
}
default boolean isActive(String modifier) {
return statusOf(modifier) != 0;
}
Collection<Clause<String, Long>> getActiveModifiers();
}
|
Change the variable name modifierName to modifier
|
Change the variable name modifierName to modifier
|
Java
|
mpl-2.0
|
Skelril/Skree
|
java
|
## Code Before:
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.skelril.skree.service;
import com.skelril.nitro.Clause;
import java.util.Collection;
public interface ModifierService {
void setExpiry(String modifierName, long time);
long expiryOf(String modifierName);
default long statusOf(String modifierName) {
return Math.max(expiryOf(modifierName) - System.currentTimeMillis(), 0);
}
default boolean isActive(String modifierName) {
return statusOf(modifierName) != 0;
}
Collection<Clause<String, Long>> getActiveModifiers();
}
## Instruction:
Change the variable name modifierName to modifier
## Code After:
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.skelril.skree.service;
import com.skelril.nitro.Clause;
import java.util.Collection;
public interface ModifierService {
void setExpiry(String modifier, long time);
long expiryOf(String modifier);
default long statusOf(String modifier) {
return Math.max(expiryOf(modifier) - System.currentTimeMillis(), 0);
}
default boolean isActive(String modifier) {
return statusOf(modifier) != 0;
}
Collection<Clause<String, Long>> getActiveModifiers();
}
|
// ... existing code ...
import java.util.Collection;
public interface ModifierService {
void setExpiry(String modifier, long time);
long expiryOf(String modifier);
default long statusOf(String modifier) {
return Math.max(expiryOf(modifier) - System.currentTimeMillis(), 0);
}
default boolean isActive(String modifier) {
return statusOf(modifier) != 0;
}
Collection<Clause<String, Long>> getActiveModifiers();
// ... rest of the code ...
|
4610690d3b1e8cee462fc057120ac70f3d1d1bfc
|
01/E1_02/E1_02.java
|
01/E1_02/E1_02.java
|
/*
Write a program that displays Welcome to Java five times.
*/
public class E1_02 {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("Welcome to Java");
}
//OR
int i = 0;
while (i < 5) {
System.out.println("Welcome to Java");
}
i = 0;
//OR
do {
System.out.println("Welcome to Java");
} while (i < 5);
}
}
|
/*
Write a program that displays Welcome to Java five times.
*/
public class E1_02 {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("Welcome to Java");
}
}
}
|
Revert back to original solution.
|
Revert back to original solution.
|
Java
|
mit
|
maxalthoff/intro-to-java-exercises
|
java
|
## Code Before:
/*
Write a program that displays Welcome to Java five times.
*/
public class E1_02 {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("Welcome to Java");
}
//OR
int i = 0;
while (i < 5) {
System.out.println("Welcome to Java");
}
i = 0;
//OR
do {
System.out.println("Welcome to Java");
} while (i < 5);
}
}
## Instruction:
Revert back to original solution.
## Code After:
/*
Write a program that displays Welcome to Java five times.
*/
public class E1_02 {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("Welcome to Java");
}
}
}
|
// ... existing code ...
for (int i = 0; i < 5; i++) {
System.out.println("Welcome to Java");
}
}
}
// ... rest of the code ...
|
49d67984d318d64528244ff525062210f94bd033
|
tests/helpers.py
|
tests/helpers.py
|
import numpy as np
import glfw
def step_env(env, max_path_length=100, iterations=1):
"""Step env helper."""
for _ in range(iterations):
env.reset()
for _ in range(max_path_length):
_, _, done, _ = env.step(env.action_space.sample())
env.render()
if done:
break
def close_env(env):
"""Close env helper."""
if env.viewer is not None:
glfw.destroy_window(env.viewer.window)
env.viewer = None
|
import numpy as np
import glfw
def step_env(env, max_path_length=100, iterations=1):
"""Step env helper."""
for _ in range(iterations):
env.reset()
for _ in range(max_path_length):
_, _, done, _ = env.step(env.action_space.sample())
env.render()
if done:
break
def close_env(env):
"""Close env helper."""
if env.viewer is not None:
glfw.destroy_window(env.viewer.window)
env.viewer = None
|
Fix indentation to pass the tests
|
Fix indentation to pass the tests
|
Python
|
mit
|
rlworkgroup/metaworld,rlworkgroup/metaworld
|
python
|
## Code Before:
import numpy as np
import glfw
def step_env(env, max_path_length=100, iterations=1):
"""Step env helper."""
for _ in range(iterations):
env.reset()
for _ in range(max_path_length):
_, _, done, _ = env.step(env.action_space.sample())
env.render()
if done:
break
def close_env(env):
"""Close env helper."""
if env.viewer is not None:
glfw.destroy_window(env.viewer.window)
env.viewer = None
## Instruction:
Fix indentation to pass the tests
## Code After:
import numpy as np
import glfw
def step_env(env, max_path_length=100, iterations=1):
"""Step env helper."""
for _ in range(iterations):
env.reset()
for _ in range(max_path_length):
_, _, done, _ = env.step(env.action_space.sample())
env.render()
if done:
break
def close_env(env):
"""Close env helper."""
if env.viewer is not None:
glfw.destroy_window(env.viewer.window)
env.viewer = None
|
...
def close_env(env):
"""Close env helper."""
if env.viewer is not None:
glfw.destroy_window(env.viewer.window)
env.viewer = None
...
|
99eafe1fb8ed3edce0d8d025b74ffdffa3bf8ae6
|
fabfile.py
|
fabfile.py
|
import sys
import sh
from fabric import api as fab
sed = sh.sed.bake('-i bak -e')
TRAVIS_YAML = '.travis.yml'
REPLACE_LANGUAGE = 's/language: .*/language: {}/'
def is_dirty():
return "" != sh.git.status(porcelain=True).strip()
def release(language, message):
if is_dirty():
sys.exit("Repo must be in clean state before deploying. Please commit changes.")
sed(REPLACE_LANGUAGE.format(language), TRAVIS_YAML)
if is_dirty():
sh.git.add(TRAVIS_YAML)
sh.git.commit(m=message, allow_empty=True)
sh.git.pull(rebase=True)
sh.git.push()
@fab.task
def update():
if is_dirty():
sys.exit("Repo must be in clean state before deploying. Please commit changes.")
sh.git.submodule.update(remote=True, rebase=True)
if is_dirty():
sh.git.add(all=True)
sh.git.commit(m="Update submodules to origin")
@fab.task
def release_osx():
release('objective-c', "Release OS X")
@fab.task
def release_linux():
release('python', "Release Linux")
|
import sys
import sh
from fabric import api as fab
sed = sh.sed.bake('-i bak -e')
TRAVIS_YAML = '.travis.yml'
REPLACE_LANGUAGE = 's/language: .*/language: {}/'
def is_dirty():
return "" != sh.git.status(porcelain=True).strip()
def release(language, message):
if is_dirty():
sys.exit("Repo must be in clean state before deploying. Please commit changes.")
sed(REPLACE_LANGUAGE.format(language), TRAVIS_YAML)
if is_dirty():
sh.git.add(TRAVIS_YAML)
sh.git.commit(m=message, allow_empty=True)
sh.git.pull(rebase=True)
sh.git.push()
@fab.task
def update():
if is_dirty():
sys.exit("Repo must be in clean state before deploying. Please commit changes.")
sh.git.submodule.update(remote=True, rebase=True)
if is_dirty():
sh.git.add(all=True)
sh.git.commit(m="Update submodules to origin")
else:
sys.exit('Nothing to update.')
@fab.task
def release_osx():
release('objective-c', "Release OS X")
@fab.task
def release_linux():
release('python', "Release Linux")
|
Print if nothing to update
|
Print if nothing to update
|
Python
|
bsd-3-clause
|
datamicroscopes/release,jzf2101/release,jzf2101/release,datamicroscopes/release
|
python
|
## Code Before:
import sys
import sh
from fabric import api as fab
sed = sh.sed.bake('-i bak -e')
TRAVIS_YAML = '.travis.yml'
REPLACE_LANGUAGE = 's/language: .*/language: {}/'
def is_dirty():
return "" != sh.git.status(porcelain=True).strip()
def release(language, message):
if is_dirty():
sys.exit("Repo must be in clean state before deploying. Please commit changes.")
sed(REPLACE_LANGUAGE.format(language), TRAVIS_YAML)
if is_dirty():
sh.git.add(TRAVIS_YAML)
sh.git.commit(m=message, allow_empty=True)
sh.git.pull(rebase=True)
sh.git.push()
@fab.task
def update():
if is_dirty():
sys.exit("Repo must be in clean state before deploying. Please commit changes.")
sh.git.submodule.update(remote=True, rebase=True)
if is_dirty():
sh.git.add(all=True)
sh.git.commit(m="Update submodules to origin")
@fab.task
def release_osx():
release('objective-c', "Release OS X")
@fab.task
def release_linux():
release('python', "Release Linux")
## Instruction:
Print if nothing to update
## Code After:
import sys
import sh
from fabric import api as fab
sed = sh.sed.bake('-i bak -e')
TRAVIS_YAML = '.travis.yml'
REPLACE_LANGUAGE = 's/language: .*/language: {}/'
def is_dirty():
return "" != sh.git.status(porcelain=True).strip()
def release(language, message):
if is_dirty():
sys.exit("Repo must be in clean state before deploying. Please commit changes.")
sed(REPLACE_LANGUAGE.format(language), TRAVIS_YAML)
if is_dirty():
sh.git.add(TRAVIS_YAML)
sh.git.commit(m=message, allow_empty=True)
sh.git.pull(rebase=True)
sh.git.push()
@fab.task
def update():
if is_dirty():
sys.exit("Repo must be in clean state before deploying. Please commit changes.")
sh.git.submodule.update(remote=True, rebase=True)
if is_dirty():
sh.git.add(all=True)
sh.git.commit(m="Update submodules to origin")
else:
sys.exit('Nothing to update.')
@fab.task
def release_osx():
release('objective-c', "Release OS X")
@fab.task
def release_linux():
release('python', "Release Linux")
|
...
if is_dirty():
sh.git.add(all=True)
sh.git.commit(m="Update submodules to origin")
else:
sys.exit('Nothing to update.')
@fab.task
...
|
54add3fa95ab450e5afcbbf7fe8a3205bfc5889c
|
indra/tests/test_reading_scripts_aws.py
|
indra/tests/test_reading_scripts_aws.py
|
import boto3
from os import path, chdir
from subprocess import check_call
from nose.plugins.attrib import attr
from indra.tools.reading import submit_reading_pipeline as srp
s3 = boto3.client('s3')
HERE = path.dirname(path.abspath(__file__))
@attr('nonpublic')
def test_normal_pmid_reading_call():
chdir(path.expanduser('~'))
# Put an id file on s3
basename = 'local_pmid_test_run'
s3_prefix = 'reading_results/%s/' % basename
s3.put_object(Bucket='bigmech', Key=s3_prefix + 'pmids',
Body='\n'.join(['PMID000test%d' % n for n in range(4)]))
# Call the reading tool
sub = srp.PmidSubmitter(basename, ['sparser'])
job_name, cmd = sub._make_command(0, 2)
check_call(cmd)
# Remove garbage on s3
res = s3.list_objects(Bucket='bigmech', Prefix=s3_prefix)
for entry in res['Contents']:
print("Removing %s..." % entry['Key'])
s3.delete_object(Bucket='bigmech', Key=entry['Key'])
return
|
import boto3
from os import path, chdir
from subprocess import check_call
from nose.plugins.attrib import attr
from indra.tools.reading import submit_reading_pipeline as srp
from indra.sources import sparser
s3 = boto3.client('s3')
HERE = path.dirname(path.abspath(__file__))
@attr('nonpublic')
def test_normal_pmid_reading_call():
chdir(path.expanduser('~'))
# Put an id file on s3
basename = 'local_pmid_test_run'
s3_prefix = 'reading_results/%s/' % basename
s3.put_object(Bucket='bigmech', Key=s3_prefix + 'pmids',
Body='\n'.join(['PMID000test%d' % n for n in range(4)]))
# Call the reading tool
sub = srp.PmidSubmitter(basename, ['sparser'])
job_name, cmd = sub._make_command(0, 2)
check_call(cmd)
# Remove garbage on s3
res = s3.list_objects(Bucket='bigmech', Prefix=s3_prefix)
for entry in res['Contents']:
print("Removing %s..." % entry['Key'])
s3.delete_object(Bucket='bigmech', Key=entry['Key'])
return
@attr('nonpublic')
def test_bad_sparser():
txt = ('Disruption of the AP-1 binding site reversed the transcriptional '
'responses seen with Fos and Jun.')
sp = sparser.process_text(txt, timeout=1)
assert sp is None, "Reading succeeded unexpectedly."
|
Add test with currently known-stall sentance.
|
Add test with currently known-stall sentance.
|
Python
|
bsd-2-clause
|
bgyori/indra,pvtodorov/indra,pvtodorov/indra,sorgerlab/indra,sorgerlab/indra,sorgerlab/indra,pvtodorov/indra,bgyori/indra,johnbachman/indra,pvtodorov/indra,sorgerlab/belpy,johnbachman/indra,johnbachman/indra,johnbachman/belpy,johnbachman/belpy,sorgerlab/belpy,sorgerlab/belpy,johnbachman/belpy,bgyori/indra
|
python
|
## Code Before:
import boto3
from os import path, chdir
from subprocess import check_call
from nose.plugins.attrib import attr
from indra.tools.reading import submit_reading_pipeline as srp
s3 = boto3.client('s3')
HERE = path.dirname(path.abspath(__file__))
@attr('nonpublic')
def test_normal_pmid_reading_call():
chdir(path.expanduser('~'))
# Put an id file on s3
basename = 'local_pmid_test_run'
s3_prefix = 'reading_results/%s/' % basename
s3.put_object(Bucket='bigmech', Key=s3_prefix + 'pmids',
Body='\n'.join(['PMID000test%d' % n for n in range(4)]))
# Call the reading tool
sub = srp.PmidSubmitter(basename, ['sparser'])
job_name, cmd = sub._make_command(0, 2)
check_call(cmd)
# Remove garbage on s3
res = s3.list_objects(Bucket='bigmech', Prefix=s3_prefix)
for entry in res['Contents']:
print("Removing %s..." % entry['Key'])
s3.delete_object(Bucket='bigmech', Key=entry['Key'])
return
## Instruction:
Add test with currently known-stall sentance.
## Code After:
import boto3
from os import path, chdir
from subprocess import check_call
from nose.plugins.attrib import attr
from indra.tools.reading import submit_reading_pipeline as srp
from indra.sources import sparser
s3 = boto3.client('s3')
HERE = path.dirname(path.abspath(__file__))
@attr('nonpublic')
def test_normal_pmid_reading_call():
chdir(path.expanduser('~'))
# Put an id file on s3
basename = 'local_pmid_test_run'
s3_prefix = 'reading_results/%s/' % basename
s3.put_object(Bucket='bigmech', Key=s3_prefix + 'pmids',
Body='\n'.join(['PMID000test%d' % n for n in range(4)]))
# Call the reading tool
sub = srp.PmidSubmitter(basename, ['sparser'])
job_name, cmd = sub._make_command(0, 2)
check_call(cmd)
# Remove garbage on s3
res = s3.list_objects(Bucket='bigmech', Prefix=s3_prefix)
for entry in res['Contents']:
print("Removing %s..." % entry['Key'])
s3.delete_object(Bucket='bigmech', Key=entry['Key'])
return
@attr('nonpublic')
def test_bad_sparser():
txt = ('Disruption of the AP-1 binding site reversed the transcriptional '
'responses seen with Fos and Jun.')
sp = sparser.process_text(txt, timeout=1)
assert sp is None, "Reading succeeded unexpectedly."
|
...
from nose.plugins.attrib import attr
from indra.tools.reading import submit_reading_pipeline as srp
from indra.sources import sparser
s3 = boto3.client('s3')
...
print("Removing %s..." % entry['Key'])
s3.delete_object(Bucket='bigmech', Key=entry['Key'])
return
@attr('nonpublic')
def test_bad_sparser():
txt = ('Disruption of the AP-1 binding site reversed the transcriptional '
'responses seen with Fos and Jun.')
sp = sparser.process_text(txt, timeout=1)
assert sp is None, "Reading succeeded unexpectedly."
...
|
99a8147a31060442368d79ebeee231744183a6d1
|
tests/test_adam.py
|
tests/test_adam.py
|
import pytest
from adam.adam import *
def test_contains_asset():
storage = AssetStorage()
a = Asset()
storage['key'] = a
assert storage['key'] == a
def test_contains_key():
storage = AssetStorage()
a = Asset()
assert 'key' not in storage
storage['key'] = a
assert 'key' in storage
def test_asset_is_versioned():
storage = AssetStorage()
a = Asset()
updated_a = Asset()
storage['key'] = a
storage['key'] = updated_a
versions = storage.versions_of('key')
assert len(versions) == 2
assert versions[0] == a
assert versions[1] == updated_a
def test_asset_is_deleted():
storage = AssetStorage()
a = Asset()
storage['key'] = a
del storage['key']
assert 'key' not in storage
def test_deleting_unkown_key_raises_exception():
storage = AssetStorage()
with pytest.raises(KeyError):
del storage['key']
def test_create_asset_from_wav():
reader = WavReader()
asset = reader.read('tests/16-bit-mono.wav')
assert asset.mime_type == 'audio/wav'
assert asset.framerate == 48000
assert asset.channels == 1
|
import pytest
from adam.adam import *
def test_contains_asset():
storage = AssetStorage()
a = Asset()
storage['key'] = a
assert storage['key'] == a
def test_contains_key():
storage = AssetStorage()
a = Asset()
assert 'key' not in storage
storage['key'] = a
assert 'key' in storage
def test_asset_is_versioned():
storage = AssetStorage()
a = Asset()
updated_a = Asset()
storage['key'] = a
storage['key'] = updated_a
versions = storage.versions_of('key')
assert len(versions) == 2
assert versions[0] == a
assert versions[1] == updated_a
def test_asset_is_deleted():
storage = AssetStorage()
a = Asset()
storage['key'] = a
del storage['key']
assert 'key' not in storage
def test_deleting_unkown_key_raises_exception():
storage = AssetStorage()
with pytest.raises(KeyError):
del storage['key']
def test_create_asset_from_wav():
reader = WavReader()
asset = reader.read('tests/16-bit-mono.wav')
assert asset.mime_type == 'audio/wav'
assert asset.framerate == 48000
assert asset.channels == 1
assert asset.essence != None
|
Test for reading a wave file asserts that the essence is set.
|
Test for reading a wave file asserts that the essence is set.
|
Python
|
agpl-3.0
|
eseifert/madam
|
python
|
## Code Before:
import pytest
from adam.adam import *
def test_contains_asset():
storage = AssetStorage()
a = Asset()
storage['key'] = a
assert storage['key'] == a
def test_contains_key():
storage = AssetStorage()
a = Asset()
assert 'key' not in storage
storage['key'] = a
assert 'key' in storage
def test_asset_is_versioned():
storage = AssetStorage()
a = Asset()
updated_a = Asset()
storage['key'] = a
storage['key'] = updated_a
versions = storage.versions_of('key')
assert len(versions) == 2
assert versions[0] == a
assert versions[1] == updated_a
def test_asset_is_deleted():
storage = AssetStorage()
a = Asset()
storage['key'] = a
del storage['key']
assert 'key' not in storage
def test_deleting_unkown_key_raises_exception():
storage = AssetStorage()
with pytest.raises(KeyError):
del storage['key']
def test_create_asset_from_wav():
reader = WavReader()
asset = reader.read('tests/16-bit-mono.wav')
assert asset.mime_type == 'audio/wav'
assert asset.framerate == 48000
assert asset.channels == 1
## Instruction:
Test for reading a wave file asserts that the essence is set.
## Code After:
import pytest
from adam.adam import *
def test_contains_asset():
storage = AssetStorage()
a = Asset()
storage['key'] = a
assert storage['key'] == a
def test_contains_key():
storage = AssetStorage()
a = Asset()
assert 'key' not in storage
storage['key'] = a
assert 'key' in storage
def test_asset_is_versioned():
storage = AssetStorage()
a = Asset()
updated_a = Asset()
storage['key'] = a
storage['key'] = updated_a
versions = storage.versions_of('key')
assert len(versions) == 2
assert versions[0] == a
assert versions[1] == updated_a
def test_asset_is_deleted():
storage = AssetStorage()
a = Asset()
storage['key'] = a
del storage['key']
assert 'key' not in storage
def test_deleting_unkown_key_raises_exception():
storage = AssetStorage()
with pytest.raises(KeyError):
del storage['key']
def test_create_asset_from_wav():
reader = WavReader()
asset = reader.read('tests/16-bit-mono.wav')
assert asset.mime_type == 'audio/wav'
assert asset.framerate == 48000
assert asset.channels == 1
assert asset.essence != None
|
...
assert asset.mime_type == 'audio/wav'
assert asset.framerate == 48000
assert asset.channels == 1
assert asset.essence != None
...
|
bfe884723d06252648cb95fdfc0f9dd0f804795f
|
proxyswitch/driver.py
|
proxyswitch/driver.py
|
from flask import Flask
class Driver:
'''
Holds the driver state so the flasked script can change behaviour based
on what the user injects via HTTP
'''
name = 'nobody'
def start(self, name):
self.name = name
return self.name
def stop(self):
self.name = 'nobody'
return self.name
app = Flask('proxapp')
driver = Driver()
def register(context):
context.app_registry.add(app, 'proxapp', 5000)
return context
@app.route('/')
def index():
return 'Try /start/:driver or /stop/:driver instead'
@app.route('/stop')
def stop_driver():
driver.stop()
return 'No drivers running\n'
@app.route('/<driver_name>/start')
def start_driver(driver_name):
print(driver.start(driver_name))
return '{} driver started\n'.format(driver_name)
|
from flask import Flask
class Driver:
'''
Holds the driver state so the flasked script can change behaviour based
on what the user injects via HTTP
'''
name = 'nobody'
def start(self, name):
self.name = name
return self.name
def stop(self):
self.name = 'nobody'
return self.name
app = Flask('proxapp')
app.host = '0.0.0.0'
driver = Driver()
def register(context):
context.app_registry.add(app, 'proxapp', 5000)
return context
@app.route('/')
def index():
return 'Try /start/:driver or /stop/:driver instead'
@app.route('/stop')
def stop_driver():
driver.stop()
return 'No drivers running\n'
@app.route('/<driver_name>/start')
def start_driver(driver_name):
print(driver.start(driver_name))
return '{} driver started\n'.format(driver_name)
|
Change Flask interface to 0.0.0.0
|
Change Flask interface to 0.0.0.0
|
Python
|
mit
|
ustwo/mastermind,ustwo/mastermind
|
python
|
## Code Before:
from flask import Flask
class Driver:
'''
Holds the driver state so the flasked script can change behaviour based
on what the user injects via HTTP
'''
name = 'nobody'
def start(self, name):
self.name = name
return self.name
def stop(self):
self.name = 'nobody'
return self.name
app = Flask('proxapp')
driver = Driver()
def register(context):
context.app_registry.add(app, 'proxapp', 5000)
return context
@app.route('/')
def index():
return 'Try /start/:driver or /stop/:driver instead'
@app.route('/stop')
def stop_driver():
driver.stop()
return 'No drivers running\n'
@app.route('/<driver_name>/start')
def start_driver(driver_name):
print(driver.start(driver_name))
return '{} driver started\n'.format(driver_name)
## Instruction:
Change Flask interface to 0.0.0.0
## Code After:
from flask import Flask
class Driver:
'''
Holds the driver state so the flasked script can change behaviour based
on what the user injects via HTTP
'''
name = 'nobody'
def start(self, name):
self.name = name
return self.name
def stop(self):
self.name = 'nobody'
return self.name
app = Flask('proxapp')
app.host = '0.0.0.0'
driver = Driver()
def register(context):
context.app_registry.add(app, 'proxapp', 5000)
return context
@app.route('/')
def index():
return 'Try /start/:driver or /stop/:driver instead'
@app.route('/stop')
def stop_driver():
driver.stop()
return 'No drivers running\n'
@app.route('/<driver_name>/start')
def start_driver(driver_name):
print(driver.start(driver_name))
return '{} driver started\n'.format(driver_name)
|
# ... existing code ...
return self.name
app = Flask('proxapp')
app.host = '0.0.0.0'
driver = Driver()
def register(context):
# ... rest of the code ...
|
c39260e64c8820bad9243c35f10b352419425810
|
marble/tests/test_exposure.py
|
marble/tests/test_exposure.py
|
""" Tests for the exposure computation """
from nose.tools import *
import marble as mb
# Test maximum value of exposure
# Test maximum value of isolation
# Test minimum of exposure
# Test minimum of isolation
|
""" Tests for the exposure computation """
from __future__ import division
from nose.tools import *
import itertools
import marble as mb
#
# Synthetic data for tests
#
def segregated_city():
""" perfect segregation """
city = {"A":{1:7, 2:0, 3:0},
"B":{1:0, 2:0, 3:14},
"C":{1:0, 2:42, 3:0}}
return city
def two_way_city():
""" perfect two-way exposure for 1 and 2 """
city = {"A":{1:7, 2:13, 3:0},
"B":{1:7, 2:13, 3:0},
"C":{1:0, 2:0, 3:37}}
return city
def uniform_city():
""" Uniform representation """
city = {"A":{1:1, 2:10, 3:7},
"B":{1:2, 2:20, 3:14},
"C":{1:4, 2:40, 3:28}}
return city
#
# Test
#
class TestExposure(object):
def test_maximum_isolation(city):
city = segregated_city()
exp = mb.exposure(city)
N_cl = {i: sum([city[au][i] for au in city]) for i in [1,2,3]}
N_tot = sum(N_cl.values())
for c in exp:
assert_almost_equal(exp[c][c][0],
N_tot/N_cl[c],
places=3)
def test_minimum_exposure(city):
city = segregated_city()
exp = mb.exposure(city)
for c0,c1 in itertools.permutations([1,2,3], 2):
assert_almost_equal(exp[c0][c1][0],
0.0)
def test_maximum_exposure(city):
city = two_way_city()
exp = mb.exposure(city)
N_cl = {i: sum([city[au][i] for au in city]) for i in [1,2,3]}
N_tot = sum(N_cl.values())
assert_almost_equal(exp[2][1][0],
N_tot/(N_cl[1]+N_cl[2]),
places=3)
def test_minimum_isolation(city):
city = uniform_city()
exp = mb.exposure(city)
for c in [1,2,3]:
assert_almost_equal(exp[c][c][0],
1.0,
places=3)
|
Write tests for the exposure
|
Write tests for the exposure
|
Python
|
bsd-3-clause
|
walkerke/marble,scities/marble
|
python
|
## Code Before:
""" Tests for the exposure computation """
from nose.tools import *
import marble as mb
# Test maximum value of exposure
# Test maximum value of isolation
# Test minimum of exposure
# Test minimum of isolation
## Instruction:
Write tests for the exposure
## Code After:
""" Tests for the exposure computation """
from __future__ import division
from nose.tools import *
import itertools
import marble as mb
#
# Synthetic data for tests
#
def segregated_city():
""" perfect segregation """
city = {"A":{1:7, 2:0, 3:0},
"B":{1:0, 2:0, 3:14},
"C":{1:0, 2:42, 3:0}}
return city
def two_way_city():
""" perfect two-way exposure for 1 and 2 """
city = {"A":{1:7, 2:13, 3:0},
"B":{1:7, 2:13, 3:0},
"C":{1:0, 2:0, 3:37}}
return city
def uniform_city():
""" Uniform representation """
city = {"A":{1:1, 2:10, 3:7},
"B":{1:2, 2:20, 3:14},
"C":{1:4, 2:40, 3:28}}
return city
#
# Test
#
class TestExposure(object):
def test_maximum_isolation(city):
city = segregated_city()
exp = mb.exposure(city)
N_cl = {i: sum([city[au][i] for au in city]) for i in [1,2,3]}
N_tot = sum(N_cl.values())
for c in exp:
assert_almost_equal(exp[c][c][0],
N_tot/N_cl[c],
places=3)
def test_minimum_exposure(city):
city = segregated_city()
exp = mb.exposure(city)
for c0,c1 in itertools.permutations([1,2,3], 2):
assert_almost_equal(exp[c0][c1][0],
0.0)
def test_maximum_exposure(city):
city = two_way_city()
exp = mb.exposure(city)
N_cl = {i: sum([city[au][i] for au in city]) for i in [1,2,3]}
N_tot = sum(N_cl.values())
assert_almost_equal(exp[2][1][0],
N_tot/(N_cl[1]+N_cl[2]),
places=3)
def test_minimum_isolation(city):
city = uniform_city()
exp = mb.exposure(city)
for c in [1,2,3]:
assert_almost_equal(exp[c][c][0],
1.0,
places=3)
|
...
""" Tests for the exposure computation """
from __future__ import division
from nose.tools import *
import itertools
import marble as mb
#
# Synthetic data for tests
#
def segregated_city():
""" perfect segregation """
city = {"A":{1:7, 2:0, 3:0},
"B":{1:0, 2:0, 3:14},
"C":{1:0, 2:42, 3:0}}
return city
def two_way_city():
""" perfect two-way exposure for 1 and 2 """
city = {"A":{1:7, 2:13, 3:0},
"B":{1:7, 2:13, 3:0},
"C":{1:0, 2:0, 3:37}}
return city
def uniform_city():
""" Uniform representation """
city = {"A":{1:1, 2:10, 3:7},
"B":{1:2, 2:20, 3:14},
"C":{1:4, 2:40, 3:28}}
return city
#
# Test
#
class TestExposure(object):
def test_maximum_isolation(city):
city = segregated_city()
exp = mb.exposure(city)
N_cl = {i: sum([city[au][i] for au in city]) for i in [1,2,3]}
N_tot = sum(N_cl.values())
for c in exp:
assert_almost_equal(exp[c][c][0],
N_tot/N_cl[c],
places=3)
def test_minimum_exposure(city):
city = segregated_city()
exp = mb.exposure(city)
for c0,c1 in itertools.permutations([1,2,3], 2):
assert_almost_equal(exp[c0][c1][0],
0.0)
def test_maximum_exposure(city):
city = two_way_city()
exp = mb.exposure(city)
N_cl = {i: sum([city[au][i] for au in city]) for i in [1,2,3]}
N_tot = sum(N_cl.values())
assert_almost_equal(exp[2][1][0],
N_tot/(N_cl[1]+N_cl[2]),
places=3)
def test_minimum_isolation(city):
city = uniform_city()
exp = mb.exposure(city)
for c in [1,2,3]:
assert_almost_equal(exp[c][c][0],
1.0,
places=3)
...
|
f67746750bdd2a1d6e662b1fc36d5a6fa13098c5
|
scripts/generate.py
|
scripts/generate.py
|
params = [
("dict(dim=250, dim_mlp=250)", "run1"),
("dict(dim=500, dim_mlp=500)", "run2"),
("dict(rank_n_approx=200)", "run3"),
("dict(rank_n_approx=500)", "run4"),
("dict(avg_word=False)", "run5")
]
for options, name in params:
with open("{}.sh".format(name), "w") as script:
log = "{}.log".format(name)
print >>script, template.format(**locals())
|
params = [
("dict(dim=250, dim_mlp=250, prefix='model_run1_')", "run1"),
("dict(dim=500, dim_mlp=500, prefix='model_run2_')", "run2"),
("dict(rank_n_approx=200, prefix='model_run3_')", "run3"),
("dict(rank_n_approx=500, prefix='model_run4_')", "run4"),
("dict(avg_word=False, prefix='model_run5_')", "run5")
]
for options, name in params:
with open("{}.sh".format(name), "w") as script:
log = "{}.log".format(name)
print >>script, template.format(**locals())
|
Add different prefixes for the experiments
|
Add different prefixes for the experiments
|
Python
|
bsd-3-clause
|
rizar/groundhog-private
|
python
|
## Code Before:
params = [
("dict(dim=250, dim_mlp=250)", "run1"),
("dict(dim=500, dim_mlp=500)", "run2"),
("dict(rank_n_approx=200)", "run3"),
("dict(rank_n_approx=500)", "run4"),
("dict(avg_word=False)", "run5")
]
for options, name in params:
with open("{}.sh".format(name), "w") as script:
log = "{}.log".format(name)
print >>script, template.format(**locals())
## Instruction:
Add different prefixes for the experiments
## Code After:
params = [
("dict(dim=250, dim_mlp=250, prefix='model_run1_')", "run1"),
("dict(dim=500, dim_mlp=500, prefix='model_run2_')", "run2"),
("dict(rank_n_approx=200, prefix='model_run3_')", "run3"),
("dict(rank_n_approx=500, prefix='model_run4_')", "run4"),
("dict(avg_word=False, prefix='model_run5_')", "run5")
]
for options, name in params:
with open("{}.sh".format(name), "w") as script:
log = "{}.log".format(name)
print >>script, template.format(**locals())
|
# ... existing code ...
params = [
("dict(dim=250, dim_mlp=250, prefix='model_run1_')", "run1"),
("dict(dim=500, dim_mlp=500, prefix='model_run2_')", "run2"),
("dict(rank_n_approx=200, prefix='model_run3_')", "run3"),
("dict(rank_n_approx=500, prefix='model_run4_')", "run4"),
("dict(avg_word=False, prefix='model_run5_')", "run5")
]
for options, name in params:
# ... rest of the code ...
|
fb3486feeece1887c5654fa6d27d6104975f3790
|
app/src/main/java/net/squanchy/service/firebase/model/schedule/FirestoreSchedule.kt
|
app/src/main/java/net/squanchy/service/firebase/model/schedule/FirestoreSchedule.kt
|
package net.squanchy.service.firebase.model.schedule
import java.util.Date
class FirestoreSchedulePage {
lateinit var day: FirestoreDay
var events: List<FirestoreEvent> = emptyList()
}
class FirestoreDay {
lateinit var id: String
lateinit var date: Date
}
class FirestoreEvent {
lateinit var id: String
lateinit var title: String
lateinit var startTime: Date
lateinit var endTime: Date
var place: FirestorePlace? = null
var track: FirestoreTrack? = null
var speakers: List<FirestoreSpeaker> = emptyList()
var experienceLevel: String? = null
lateinit var type: String
var description: String? = null
}
class FirestorePlace {
lateinit var id: String
lateinit var name: String
var floor: String? = null
var position: Int = -1
}
class FirestoreTrack {
lateinit var id: String
lateinit var name: String
var accentColor: String? = null
var textColor: String? = null
var iconUrl: String? = null
}
class FirestoreSpeaker {
lateinit var id: String
lateinit var name: String
lateinit var bio: String
var companyName: String? = null
var companyUrl: String? = null
var personalUrl: String? = null
var photoUrl: String? = null
var twitterUsername: String? = null
}
class FirestoreFavorite {
lateinit var id: String
}
|
package net.squanchy.service.firebase.model.schedule
import com.google.firebase.firestore.IgnoreExtraProperties
import java.util.Date
class FirestoreSchedulePage {
lateinit var day: FirestoreDay
var events: List<FirestoreEvent> = emptyList()
}
@IgnoreExtraProperties
class FirestoreDay {
lateinit var id: String
lateinit var date: Date
}
@IgnoreExtraProperties
class FirestoreEvent {
lateinit var id: String
lateinit var title: String
lateinit var startTime: Date
lateinit var endTime: Date
var place: FirestorePlace? = null
var track: FirestoreTrack? = null
var speakers: List<FirestoreSpeaker> = emptyList()
var experienceLevel: String? = null
lateinit var type: String
var description: String? = null
}
class FirestorePlace {
lateinit var id: String
lateinit var name: String
var floor: String? = null
var position: Int = -1
}
class FirestoreTrack {
lateinit var id: String
lateinit var name: String
var accentColor: String? = null
var textColor: String? = null
var iconUrl: String? = null
}
class FirestoreSpeaker {
lateinit var id: String
lateinit var name: String
lateinit var bio: String
var companyName: String? = null
var companyUrl: String? = null
var personalUrl: String? = null
var photoUrl: String? = null
var twitterUsername: String? = null
}
class FirestoreFavorite {
lateinit var id: String
}
|
Add @IgnoreExtraProperties to FirestoreEvent and FirestoreDay
|
Add @IgnoreExtraProperties to FirestoreEvent and FirestoreDay
They have extra fields we don't really care about in the app and the
warnings we get in the log because of it are annoying.
|
Kotlin
|
apache-2.0
|
squanchy-dev/squanchy-android,squanchy-dev/squanchy-android,squanchy-dev/squanchy-android
|
kotlin
|
## Code Before:
package net.squanchy.service.firebase.model.schedule
import java.util.Date
class FirestoreSchedulePage {
lateinit var day: FirestoreDay
var events: List<FirestoreEvent> = emptyList()
}
class FirestoreDay {
lateinit var id: String
lateinit var date: Date
}
class FirestoreEvent {
lateinit var id: String
lateinit var title: String
lateinit var startTime: Date
lateinit var endTime: Date
var place: FirestorePlace? = null
var track: FirestoreTrack? = null
var speakers: List<FirestoreSpeaker> = emptyList()
var experienceLevel: String? = null
lateinit var type: String
var description: String? = null
}
class FirestorePlace {
lateinit var id: String
lateinit var name: String
var floor: String? = null
var position: Int = -1
}
class FirestoreTrack {
lateinit var id: String
lateinit var name: String
var accentColor: String? = null
var textColor: String? = null
var iconUrl: String? = null
}
class FirestoreSpeaker {
lateinit var id: String
lateinit var name: String
lateinit var bio: String
var companyName: String? = null
var companyUrl: String? = null
var personalUrl: String? = null
var photoUrl: String? = null
var twitterUsername: String? = null
}
class FirestoreFavorite {
lateinit var id: String
}
## Instruction:
Add @IgnoreExtraProperties to FirestoreEvent and FirestoreDay
They have extra fields we don't really care about in the app and the
warnings we get in the log because of it are annoying.
## Code After:
package net.squanchy.service.firebase.model.schedule
import com.google.firebase.firestore.IgnoreExtraProperties
import java.util.Date
class FirestoreSchedulePage {
lateinit var day: FirestoreDay
var events: List<FirestoreEvent> = emptyList()
}
@IgnoreExtraProperties
class FirestoreDay {
lateinit var id: String
lateinit var date: Date
}
@IgnoreExtraProperties
class FirestoreEvent {
lateinit var id: String
lateinit var title: String
lateinit var startTime: Date
lateinit var endTime: Date
var place: FirestorePlace? = null
var track: FirestoreTrack? = null
var speakers: List<FirestoreSpeaker> = emptyList()
var experienceLevel: String? = null
lateinit var type: String
var description: String? = null
}
class FirestorePlace {
lateinit var id: String
lateinit var name: String
var floor: String? = null
var position: Int = -1
}
class FirestoreTrack {
lateinit var id: String
lateinit var name: String
var accentColor: String? = null
var textColor: String? = null
var iconUrl: String? = null
}
class FirestoreSpeaker {
lateinit var id: String
lateinit var name: String
lateinit var bio: String
var companyName: String? = null
var companyUrl: String? = null
var personalUrl: String? = null
var photoUrl: String? = null
var twitterUsername: String? = null
}
class FirestoreFavorite {
lateinit var id: String
}
|
// ... existing code ...
package net.squanchy.service.firebase.model.schedule
import com.google.firebase.firestore.IgnoreExtraProperties
import java.util.Date
class FirestoreSchedulePage {
// ... modified code ...
var events: List<FirestoreEvent> = emptyList()
}
@IgnoreExtraProperties
class FirestoreDay {
lateinit var id: String
lateinit var date: Date
}
@IgnoreExtraProperties
class FirestoreEvent {
lateinit var id: String
lateinit var title: String
// ... rest of the code ...
|
2544f892f93ab2ddf95ef3634c39e7c3840fb03a
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
import sys, os
version = '1.5.2'
install_requires = [
# -*- Extra requirements: -*-
]
if sys.version_info < (2,6,):
install_requires.append("simplejson>=1.7.1")
setup(name='twitter3',
version=version,
description="An API and command-line toolset for Twitter (twitter.com)",
long_description=open("./README", "r").read(),
# Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Intended Audience :: End Users/Desktop",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Topic :: Communications :: Chat :: Internet Relay Chat",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries",
"Topic :: Utilities",
"License :: OSI Approved :: MIT License",
],
keywords='twitter, IRC, command-line tools, web 2.0',
author='Mike Verdone',
author_email='[email protected]',
url='http://mike.verdone.ca/twitter/',
license='MIT License',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=True,
install_requires=install_requires,
entry_points="""
# -*- Entry points: -*-
[console_scripts]
twitter=twitter.cmdline:main
""",
)
|
from setuptools import setup, find_packages
import sys, os
version = '1.5.2'
install_requires = [
# -*- Extra requirements: -*-
]
setup(name='twitter3',
version=version,
description="An API and command-line toolset for Twitter (twitter.com)",
long_description=open("./README", "r").read(),
# Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Intended Audience :: End Users/Desktop",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Topic :: Communications :: Chat :: Internet Relay Chat",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries",
"Topic :: Utilities",
"License :: OSI Approved :: MIT License",
],
keywords='twitter, IRC, command-line tools, web 2.0',
author='Mike Verdone',
author_email='[email protected]',
url='http://mike.verdone.ca/twitter/',
license='MIT License',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=True,
install_requires=install_requires,
entry_points="""
# -*- Entry points: -*-
[console_scripts]
twitter=twitter.cmdline:main
twitterbot=twitter.ircbot:main
""",
)
|
Enable the twitterbot since dateutil requirement is now gone.
|
Enable the twitterbot since dateutil requirement is now gone.
|
Python
|
mit
|
tytek2012/twitter,adonoho/twitter,durden/frappy,Adai0808/twitter,hugovk/twitter,miragshin/twitter,sixohsix/twitter,jessamynsmith/twitter
|
python
|
## Code Before:
from setuptools import setup, find_packages
import sys, os
version = '1.5.2'
install_requires = [
# -*- Extra requirements: -*-
]
if sys.version_info < (2,6,):
install_requires.append("simplejson>=1.7.1")
setup(name='twitter3',
version=version,
description="An API and command-line toolset for Twitter (twitter.com)",
long_description=open("./README", "r").read(),
# Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Intended Audience :: End Users/Desktop",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Topic :: Communications :: Chat :: Internet Relay Chat",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries",
"Topic :: Utilities",
"License :: OSI Approved :: MIT License",
],
keywords='twitter, IRC, command-line tools, web 2.0',
author='Mike Verdone',
author_email='[email protected]',
url='http://mike.verdone.ca/twitter/',
license='MIT License',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=True,
install_requires=install_requires,
entry_points="""
# -*- Entry points: -*-
[console_scripts]
twitter=twitter.cmdline:main
""",
)
## Instruction:
Enable the twitterbot since dateutil requirement is now gone.
## Code After:
from setuptools import setup, find_packages
import sys, os
version = '1.5.2'
install_requires = [
# -*- Extra requirements: -*-
]
setup(name='twitter3',
version=version,
description="An API and command-line toolset for Twitter (twitter.com)",
long_description=open("./README", "r").read(),
# Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Intended Audience :: End Users/Desktop",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Topic :: Communications :: Chat :: Internet Relay Chat",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries",
"Topic :: Utilities",
"License :: OSI Approved :: MIT License",
],
keywords='twitter, IRC, command-line tools, web 2.0',
author='Mike Verdone',
author_email='[email protected]',
url='http://mike.verdone.ca/twitter/',
license='MIT License',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=True,
install_requires=install_requires,
entry_points="""
# -*- Entry points: -*-
[console_scripts]
twitter=twitter.cmdline:main
twitterbot=twitter.ircbot:main
""",
)
|
// ... existing code ...
install_requires = [
# -*- Extra requirements: -*-
]
setup(name='twitter3',
version=version,
// ... modified code ...
# -*- Entry points: -*-
[console_scripts]
twitter=twitter.cmdline:main
twitterbot=twitter.ircbot:main
""",
)
// ... rest of the code ...
|
97d9b86d1aa443dfb04852a8695beb1b0ad9814f
|
core/src/androidTest/java/com/github/kubode/wiggle/MockView.java
|
core/src/androidTest/java/com/github/kubode/wiggle/MockView.java
|
package com.github.kubode.wiggle;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
public class MockView extends View {
private final WiggleHelper helper = new WiggleHelper();
public MockView(Context context) {
super(context);
}
public MockView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MockView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
helper.onViewAttachedToWindow(this);
}
@Override
protected void onDetachedFromWindow() {
helper.onViewDetachedFromWindow(this);
super.onDetachedFromWindow();
}
}
|
package com.github.kubode.wiggle;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
public class MockView extends TextView {
private final WiggleHelper helper = new WiggleHelper();
public MockView(Context context) {
super(context);
}
public MockView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MockView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
helper.onViewAttachedToWindow(this);
}
@Override
protected void onDetachedFromWindow() {
helper.onViewDetachedFromWindow(this);
super.onDetachedFromWindow();
}
@SuppressLint("SetTextI18n")
@Override
public void setTranslationY(float translationY) {
super.setTranslationY(translationY);
setText("translationY=" + translationY);
}
}
|
Add readable text for debugging.
|
Add readable text for debugging.
|
Java
|
apache-2.0
|
kubode/Wiggle
|
java
|
## Code Before:
package com.github.kubode.wiggle;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
public class MockView extends View {
private final WiggleHelper helper = new WiggleHelper();
public MockView(Context context) {
super(context);
}
public MockView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MockView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
helper.onViewAttachedToWindow(this);
}
@Override
protected void onDetachedFromWindow() {
helper.onViewDetachedFromWindow(this);
super.onDetachedFromWindow();
}
}
## Instruction:
Add readable text for debugging.
## Code After:
package com.github.kubode.wiggle;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
public class MockView extends TextView {
private final WiggleHelper helper = new WiggleHelper();
public MockView(Context context) {
super(context);
}
public MockView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MockView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
helper.onViewAttachedToWindow(this);
}
@Override
protected void onDetachedFromWindow() {
helper.onViewDetachedFromWindow(this);
super.onDetachedFromWindow();
}
@SuppressLint("SetTextI18n")
@Override
public void setTranslationY(float translationY) {
super.setTranslationY(translationY);
setText("translationY=" + translationY);
}
}
|
// ... existing code ...
package com.github.kubode.wiggle;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
public class MockView extends TextView {
private final WiggleHelper helper = new WiggleHelper();
// ... modified code ...
helper.onViewDetachedFromWindow(this);
super.onDetachedFromWindow();
}
@SuppressLint("SetTextI18n")
@Override
public void setTranslationY(float translationY) {
super.setTranslationY(translationY);
setText("translationY=" + translationY);
}
}
// ... rest of the code ...
|
6f3336ef5dd43c02c851001715cf0f231c269276
|
pyramid_keystone/__init__.py
|
pyramid_keystone/__init__.py
|
default_settings = [
('auth_url', str, 'http://localhost:5000/v3'),
('region', str, 'RegionOne'),
('user_domain_name', str, 'Default'),
('cacert', str, ''),
]
def parse_settings(settings):
parsed = {}
def populate(name, convert, default):
sname = '%s%s' % ('keystone.', name)
value = convert(settings.get(sname, default))
parsed[sname] = value
for name, convert, default in default_settings:
populate(name, convert, default)
return parsed
def includeme(config):
""" Set up standard configurator registrations. Use via:
.. code-block:: python
config = Configurator()
config.include('pyramid_keystone')
"""
# We use an action so that the user can include us, and then add the
# required variables, upon commit we will pick up those changes.
def register():
registry = config.registry
settings = parse_settings(registry.settings)
registry.settings.update(settings)
config.action('keystone-configure', register)
config.add_directive('keystone_auth_policy', '.authentication.add_auth_policy')
|
default_settings = [
('auth_url', str, 'http://localhost:5000/v3'),
('region', str, 'RegionOne'),
('user_domain_name', str, 'Default'),
('cacert', str, ''),
]
def parse_settings(settings):
parsed = {}
def populate(name, convert, default):
sname = '%s%s' % ('keystone.', name)
value = convert(settings.get(sname, default))
parsed[sname] = value
for name, convert, default in default_settings:
populate(name, convert, default)
return parsed
def includeme(config):
""" Set up standard configurator registrations. Use via:
.. code-block:: python
config = Configurator()
config.include('pyramid_keystone')
"""
# We use an action so that the user can include us, and then add the
# required variables, upon commit we will pick up those changes.
def register():
registry = config.registry
settings = parse_settings(registry.settings)
registry.settings.update(settings)
config.action('keystone-configure', register)
# Allow the user to use our auth policy (recommended)
config.add_directive('keystone_auth_policy', '.authentication.add_auth_policy')
# Add the keystone property to the request
config.add_request_method('.keystone.request_keystone', name='keystone', property=True, reify=True)
|
Add keystone to the request
|
Add keystone to the request
|
Python
|
isc
|
bertjwregeer/pyramid_keystone
|
python
|
## Code Before:
default_settings = [
('auth_url', str, 'http://localhost:5000/v3'),
('region', str, 'RegionOne'),
('user_domain_name', str, 'Default'),
('cacert', str, ''),
]
def parse_settings(settings):
parsed = {}
def populate(name, convert, default):
sname = '%s%s' % ('keystone.', name)
value = convert(settings.get(sname, default))
parsed[sname] = value
for name, convert, default in default_settings:
populate(name, convert, default)
return parsed
def includeme(config):
""" Set up standard configurator registrations. Use via:
.. code-block:: python
config = Configurator()
config.include('pyramid_keystone')
"""
# We use an action so that the user can include us, and then add the
# required variables, upon commit we will pick up those changes.
def register():
registry = config.registry
settings = parse_settings(registry.settings)
registry.settings.update(settings)
config.action('keystone-configure', register)
config.add_directive('keystone_auth_policy', '.authentication.add_auth_policy')
## Instruction:
Add keystone to the request
## Code After:
default_settings = [
('auth_url', str, 'http://localhost:5000/v3'),
('region', str, 'RegionOne'),
('user_domain_name', str, 'Default'),
('cacert', str, ''),
]
def parse_settings(settings):
parsed = {}
def populate(name, convert, default):
sname = '%s%s' % ('keystone.', name)
value = convert(settings.get(sname, default))
parsed[sname] = value
for name, convert, default in default_settings:
populate(name, convert, default)
return parsed
def includeme(config):
""" Set up standard configurator registrations. Use via:
.. code-block:: python
config = Configurator()
config.include('pyramid_keystone')
"""
# We use an action so that the user can include us, and then add the
# required variables, upon commit we will pick up those changes.
def register():
registry = config.registry
settings = parse_settings(registry.settings)
registry.settings.update(settings)
config.action('keystone-configure', register)
# Allow the user to use our auth policy (recommended)
config.add_directive('keystone_auth_policy', '.authentication.add_auth_policy')
# Add the keystone property to the request
config.add_request_method('.keystone.request_keystone', name='keystone', property=True, reify=True)
|
# ... existing code ...
config.action('keystone-configure', register)
# Allow the user to use our auth policy (recommended)
config.add_directive('keystone_auth_policy', '.authentication.add_auth_policy')
# Add the keystone property to the request
config.add_request_method('.keystone.request_keystone', name='keystone', property=True, reify=True)
# ... rest of the code ...
|
ed434c7724cf2e7731c0b0b91a4b8efa7c424106
|
nbt/src/main/java/com/voxelwind/nbt/util/CompoundTagBuilder.java
|
nbt/src/main/java/com/voxelwind/nbt/util/CompoundTagBuilder.java
|
package com.voxelwind.nbt.util;
import com.voxelwind.nbt.tags.CompoundTag;
import com.voxelwind.nbt.tags.Tag;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.util.HashMap;
import java.util.Map;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class CompoundTagBuilder {
private final Map<String, Tag<?>> tagMap = new HashMap<>();
public static CompoundTagBuilder builder() {
return new CompoundTagBuilder();
}
public static CompoundTagBuilder from(CompoundTag tag) {
CompoundTagBuilder builder = new CompoundTagBuilder();
builder.tagMap.putAll(tag.getValue());
return builder;
}
public CompoundTagBuilder tag(Tag<?> tag) {
tagMap.put(tag.getName(), tag);
return this;
}
public CompoundTag buildRootTag() {
return new CompoundTag("", tagMap);
}
public CompoundTag build(String tagName) {
return new CompoundTag(tagName, tagMap);
}
}
|
package com.voxelwind.nbt.util;
import com.voxelwind.nbt.tags.*;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.util.HashMap;
import java.util.Map;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class CompoundTagBuilder {
private final Map<String, Tag<?>> tagMap = new HashMap<>();
public static CompoundTagBuilder builder() {
return new CompoundTagBuilder();
}
public static CompoundTagBuilder from(CompoundTag tag) {
CompoundTagBuilder builder = new CompoundTagBuilder();
builder.tagMap.putAll(tag.getValue());
return builder;
}
public CompoundTagBuilder tag(Tag<?> tag) {
tagMap.put(tag.getName(), tag);
return this;
}
public CompoundTagBuilder tag(String name, byte value) {
return tag(new ByteTag(name, value));
}
public CompoundTagBuilder tag(String name, byte [] value) {
return tag(new ByteArrayTag(name, value));
}
public CompoundTagBuilder tag(String name, double value) {
return tag(new DoubleTag(name, value));
}
public CompoundTagBuilder tag(String name, float value) {
return tag(new FloatTag(name, value));
}
public CompoundTagBuilder tag(String name, int[] value) {
return tag(new IntArrayTag(name, value));
}
public CompoundTagBuilder tag(String name, int value) {
return tag(new IntTag(name, value));
}
public CompoundTagBuilder tag(String name, long value) {
return tag(new LongTag(name, value));
}
public CompoundTagBuilder tag(String name, short value) {
return tag(new ShortTag(name, value));
}
public CompoundTagBuilder tag(String name, String value) {
return tag(new StringTag(name, value));
}
public CompoundTag buildRootTag() {
return new CompoundTag("", tagMap);
}
public CompoundTag build(String tagName) {
return new CompoundTag(tagName, tagMap);
}
}
|
Add type-related tag methods to nbt-builder
|
Add type-related tag methods to nbt-builder
|
Java
|
mit
|
voxelwind/voxelwind,voxelwind/voxelwind,minecrafter/voxelwind,voxelwind/voxelwind,minecrafter/voxelwind,minecrafter/voxelwind,minecrafter/voxelwind,voxelwind/voxelwind
|
java
|
## Code Before:
package com.voxelwind.nbt.util;
import com.voxelwind.nbt.tags.CompoundTag;
import com.voxelwind.nbt.tags.Tag;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.util.HashMap;
import java.util.Map;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class CompoundTagBuilder {
private final Map<String, Tag<?>> tagMap = new HashMap<>();
public static CompoundTagBuilder builder() {
return new CompoundTagBuilder();
}
public static CompoundTagBuilder from(CompoundTag tag) {
CompoundTagBuilder builder = new CompoundTagBuilder();
builder.tagMap.putAll(tag.getValue());
return builder;
}
public CompoundTagBuilder tag(Tag<?> tag) {
tagMap.put(tag.getName(), tag);
return this;
}
public CompoundTag buildRootTag() {
return new CompoundTag("", tagMap);
}
public CompoundTag build(String tagName) {
return new CompoundTag(tagName, tagMap);
}
}
## Instruction:
Add type-related tag methods to nbt-builder
## Code After:
package com.voxelwind.nbt.util;
import com.voxelwind.nbt.tags.*;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.util.HashMap;
import java.util.Map;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class CompoundTagBuilder {
private final Map<String, Tag<?>> tagMap = new HashMap<>();
public static CompoundTagBuilder builder() {
return new CompoundTagBuilder();
}
public static CompoundTagBuilder from(CompoundTag tag) {
CompoundTagBuilder builder = new CompoundTagBuilder();
builder.tagMap.putAll(tag.getValue());
return builder;
}
public CompoundTagBuilder tag(Tag<?> tag) {
tagMap.put(tag.getName(), tag);
return this;
}
public CompoundTagBuilder tag(String name, byte value) {
return tag(new ByteTag(name, value));
}
public CompoundTagBuilder tag(String name, byte [] value) {
return tag(new ByteArrayTag(name, value));
}
public CompoundTagBuilder tag(String name, double value) {
return tag(new DoubleTag(name, value));
}
public CompoundTagBuilder tag(String name, float value) {
return tag(new FloatTag(name, value));
}
public CompoundTagBuilder tag(String name, int[] value) {
return tag(new IntArrayTag(name, value));
}
public CompoundTagBuilder tag(String name, int value) {
return tag(new IntTag(name, value));
}
public CompoundTagBuilder tag(String name, long value) {
return tag(new LongTag(name, value));
}
public CompoundTagBuilder tag(String name, short value) {
return tag(new ShortTag(name, value));
}
public CompoundTagBuilder tag(String name, String value) {
return tag(new StringTag(name, value));
}
public CompoundTag buildRootTag() {
return new CompoundTag("", tagMap);
}
public CompoundTag build(String tagName) {
return new CompoundTag(tagName, tagMap);
}
}
|
# ... existing code ...
package com.voxelwind.nbt.util;
import com.voxelwind.nbt.tags.*;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
# ... modified code ...
return this;
}
public CompoundTagBuilder tag(String name, byte value) {
return tag(new ByteTag(name, value));
}
public CompoundTagBuilder tag(String name, byte [] value) {
return tag(new ByteArrayTag(name, value));
}
public CompoundTagBuilder tag(String name, double value) {
return tag(new DoubleTag(name, value));
}
public CompoundTagBuilder tag(String name, float value) {
return tag(new FloatTag(name, value));
}
public CompoundTagBuilder tag(String name, int[] value) {
return tag(new IntArrayTag(name, value));
}
public CompoundTagBuilder tag(String name, int value) {
return tag(new IntTag(name, value));
}
public CompoundTagBuilder tag(String name, long value) {
return tag(new LongTag(name, value));
}
public CompoundTagBuilder tag(String name, short value) {
return tag(new ShortTag(name, value));
}
public CompoundTagBuilder tag(String name, String value) {
return tag(new StringTag(name, value));
}
public CompoundTag buildRootTag() {
return new CompoundTag("", tagMap);
}
# ... rest of the code ...
|
547e2cbddd26f2e158fbbdab8ae22605cbd270c9
|
joby/items.py
|
joby/items.py
|
from scrapy import Item, Field
class JobItem(Item):
website_url = Field()
website_language = Field()
publication_date = Field()
posting_id = Field()
url = Field()
number_of_views = Field()
contact_email = Field()
contact_name = Field()
employment_type = Field()
workload = Field()
duration = Field()
remote = Field()
title = Field(primary_key=True)
keywords = Field()
abstract = Field()
description = Field()
salary = Field()
level = Field()
responsabilities = Field()
required_skills = Field()
required_languages = Field()
company = Field(primary_key=True)
city = Field()
country = Field()
postal_code = Field()
company_website = Field()
company_category = Field()
company_description = Field()
start_date = Field()
end_date = Field()
class DataScienceJobsJobItem(Job):
pass
|
from scrapy import Item, Field
from scrapy.loader import Identity, ItemLoader
from scrapy.loader.processors import TakeFirst
class JobItem(Item):
website_url = Field()
website_language = Field()
publication_date = Field()
posting_id = Field()
url = Field()
number_of_views = Field()
contact_email = Field()
contact_name = Field()
employment_type = Field()
workload = Field()
duration = Field()
remote = Field()
title = Field(primary_key=True)
keywords = Field()
abstract = Field()
description = Field()
salary = Field()
level = Field()
responsabilities = Field()
required_skills = Field()
required_languages = Field()
company = Field(primary_key=True)
city = Field()
country = Field()
postal_code = Field()
company_website = Field()
company_category = Field()
company_description = Field()
start_date = Field()
end_date = Field()
class DataScienceJobsJobItem(JobItem):
pass
class JobItemLoader(ItemLoader):
default_input_processor = Identity()
default_output_processor = TakeFirst()
class DataScienceJobsItemLoader(JobItemLoader):
pass
|
Add JobItemLoader and DataScienceJobsItemLoader class.
|
Add JobItemLoader and DataScienceJobsItemLoader class.
|
Python
|
mit
|
cyberbikepunk/job-spiders
|
python
|
## Code Before:
from scrapy import Item, Field
class JobItem(Item):
website_url = Field()
website_language = Field()
publication_date = Field()
posting_id = Field()
url = Field()
number_of_views = Field()
contact_email = Field()
contact_name = Field()
employment_type = Field()
workload = Field()
duration = Field()
remote = Field()
title = Field(primary_key=True)
keywords = Field()
abstract = Field()
description = Field()
salary = Field()
level = Field()
responsabilities = Field()
required_skills = Field()
required_languages = Field()
company = Field(primary_key=True)
city = Field()
country = Field()
postal_code = Field()
company_website = Field()
company_category = Field()
company_description = Field()
start_date = Field()
end_date = Field()
class DataScienceJobsJobItem(Job):
pass
## Instruction:
Add JobItemLoader and DataScienceJobsItemLoader class.
## Code After:
from scrapy import Item, Field
from scrapy.loader import Identity, ItemLoader
from scrapy.loader.processors import TakeFirst
class JobItem(Item):
website_url = Field()
website_language = Field()
publication_date = Field()
posting_id = Field()
url = Field()
number_of_views = Field()
contact_email = Field()
contact_name = Field()
employment_type = Field()
workload = Field()
duration = Field()
remote = Field()
title = Field(primary_key=True)
keywords = Field()
abstract = Field()
description = Field()
salary = Field()
level = Field()
responsabilities = Field()
required_skills = Field()
required_languages = Field()
company = Field(primary_key=True)
city = Field()
country = Field()
postal_code = Field()
company_website = Field()
company_category = Field()
company_description = Field()
start_date = Field()
end_date = Field()
class DataScienceJobsJobItem(JobItem):
pass
class JobItemLoader(ItemLoader):
default_input_processor = Identity()
default_output_processor = TakeFirst()
class DataScienceJobsItemLoader(JobItemLoader):
pass
|
// ... existing code ...
from scrapy import Item, Field
from scrapy.loader import Identity, ItemLoader
from scrapy.loader.processors import TakeFirst
class JobItem(Item):
// ... modified code ...
end_date = Field()
class DataScienceJobsJobItem(JobItem):
pass
class JobItemLoader(ItemLoader):
default_input_processor = Identity()
default_output_processor = TakeFirst()
class DataScienceJobsItemLoader(JobItemLoader):
pass
// ... rest of the code ...
|
f00fd0fde81a340cf00030bbe2562b8c878edd41
|
src/yawf/signals.py
|
src/yawf/signals.py
|
from django.dispatch import Signal
message_handled = Signal(providing_args=['message', 'instance', 'new_revision'])
|
from django.dispatch import Signal
message_handled = Signal(
providing_args=['message', 'instance', 'new_revision', 'transition_result']
)
|
Add new arg in message_handled signal definition
|
Add new arg in message_handled signal definition
|
Python
|
mit
|
freevoid/yawf
|
python
|
## Code Before:
from django.dispatch import Signal
message_handled = Signal(providing_args=['message', 'instance', 'new_revision'])
## Instruction:
Add new arg in message_handled signal definition
## Code After:
from django.dispatch import Signal
message_handled = Signal(
providing_args=['message', 'instance', 'new_revision', 'transition_result']
)
|
...
from django.dispatch import Signal
message_handled = Signal(
providing_args=['message', 'instance', 'new_revision', 'transition_result']
)
...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.