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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
2acca2ea2ae2dc86d4b09ce21c88d578bbea6ea3
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
__about__ = {}
with open("warehouse/__about__.py") as fp:
exec(fp, None, __about__)
setup(
name=__about__["__title__"],
version=__about__["__version__"],
description=__about__["__summary__"],
long_description=open("README.rst").read(),
url=__about__["__uri__"],
license=__about__["__license__"],
author=__about__["__author__"],
author_email=__about__["__email__"],
install_requires=[
"Flask",
"Flask-SQLAlchemy",
"Flask-Script",
"boto",
"eventlet",
"progress",
"psycopg2",
"python-s3file>=1.1",
"requests",
"schema",
"xmlrpc2",
],
extras_require={
"tests": [
"pylint",
],
},
packages=find_packages(exclude=["tests"]),
package_data={
"": ["LICENSE"],
"warehouse": [
"simple/templates/*.html",
"synchronize/*.crt",
],
},
include_package_data=True,
entry_points={
"console_scripts": [
"warehouse = warehouse.__main__:main",
],
},
classifiers=[
"License :: OSI Approved :: BSD License",
"Operating System :: POSIX",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
],
zip_safe=False,
)
|
from setuptools import setup, find_packages
__about__ = {}
with open("warehouse/__about__.py") as fp:
exec(fp, None, __about__)
setup(
name=__about__["__title__"],
version=__about__["__version__"],
description=__about__["__summary__"],
long_description=open("README.rst").read(),
url=__about__["__uri__"],
license=__about__["__license__"],
author=__about__["__author__"],
author_email=__about__["__email__"],
install_requires=[
"Flask",
"Flask-SQLAlchemy",
"Flask-Script",
"boto",
"eventlet",
"progress",
"psycopg2",
"python-s3file>=1.1",
"requests",
"schema",
"xmlrpc2",
],
extras_require={
"tests": [
"pylint",
],
},
packages=find_packages(exclude=["tests"]),
package_data={
"warehouse": [
"simple/templates/*.html",
"synchronize/*.crt",
],
},
include_package_data=True,
entry_points={
"console_scripts": [
"warehouse = warehouse.__main__:main",
],
},
classifiers=[
"License :: OSI Approved :: BSD License",
"Operating System :: POSIX",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
],
zip_safe=False,
)
|
Remove no longer needed package_data
|
Remove no longer needed package_data
|
Python
|
bsd-2-clause
|
davidfischer/warehouse
|
python
|
## Code Before:
from setuptools import setup, find_packages
__about__ = {}
with open("warehouse/__about__.py") as fp:
exec(fp, None, __about__)
setup(
name=__about__["__title__"],
version=__about__["__version__"],
description=__about__["__summary__"],
long_description=open("README.rst").read(),
url=__about__["__uri__"],
license=__about__["__license__"],
author=__about__["__author__"],
author_email=__about__["__email__"],
install_requires=[
"Flask",
"Flask-SQLAlchemy",
"Flask-Script",
"boto",
"eventlet",
"progress",
"psycopg2",
"python-s3file>=1.1",
"requests",
"schema",
"xmlrpc2",
],
extras_require={
"tests": [
"pylint",
],
},
packages=find_packages(exclude=["tests"]),
package_data={
"": ["LICENSE"],
"warehouse": [
"simple/templates/*.html",
"synchronize/*.crt",
],
},
include_package_data=True,
entry_points={
"console_scripts": [
"warehouse = warehouse.__main__:main",
],
},
classifiers=[
"License :: OSI Approved :: BSD License",
"Operating System :: POSIX",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
],
zip_safe=False,
)
## Instruction:
Remove no longer needed package_data
## Code After:
from setuptools import setup, find_packages
__about__ = {}
with open("warehouse/__about__.py") as fp:
exec(fp, None, __about__)
setup(
name=__about__["__title__"],
version=__about__["__version__"],
description=__about__["__summary__"],
long_description=open("README.rst").read(),
url=__about__["__uri__"],
license=__about__["__license__"],
author=__about__["__author__"],
author_email=__about__["__email__"],
install_requires=[
"Flask",
"Flask-SQLAlchemy",
"Flask-Script",
"boto",
"eventlet",
"progress",
"psycopg2",
"python-s3file>=1.1",
"requests",
"schema",
"xmlrpc2",
],
extras_require={
"tests": [
"pylint",
],
},
packages=find_packages(exclude=["tests"]),
package_data={
"warehouse": [
"simple/templates/*.html",
"synchronize/*.crt",
],
},
include_package_data=True,
entry_points={
"console_scripts": [
"warehouse = warehouse.__main__:main",
],
},
classifiers=[
"License :: OSI Approved :: BSD License",
"Operating System :: POSIX",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
],
zip_safe=False,
)
|
// ... existing code ...
packages=find_packages(exclude=["tests"]),
package_data={
"warehouse": [
"simple/templates/*.html",
"synchronize/*.crt",
// ... rest of the code ...
|
129cd22de51d58cc956ca5586fc15cd2e247446b
|
gpkitmodels/GP/aircraft/prop/propeller.py
|
gpkitmodels/GP/aircraft/prop/propeller.py
|
" propeller model "
from numpy import pi
from gpkit import Model, parse_variables, SignomialsEnabled, SignomialEquality
class Propeller(Model):
""" Propeller Model
Variables
---------
R 10 [m] prop radius
"""
def setup(self):
exec parse_variables(Propeller.__doc__)
def performance(state):
return Propeller_Performance(self, state)
class Propeller_Performance(Model):
""" Propeller Model
Variables
---------
T [N] thrust
Tc [-] coefficient of thrust
etaadd 0.7 [-] swirl and nonuniformity losses
etav 0.85 [-] viscous losses
etai [-] inviscid losses
eta [-] overall efficiency
z1 self.helper [-] efficiency helper 1
z2 [-] efficiency helper 2
"""
def helper(self, c):
return 2. - 1./c[self.etaadd]
def setup(self, state):
exec parse_variables(Propeller.__doc__)
V = state.V
rho = state.rho
constraints = [eta <= etav*etai,
Tc == T/(0.5*rho*V**2*pi*R**2),
z2 >= Tc + 1,
etai*(z1 + z2**0.5/etaadd) <= 2]
return constraints
|
" propeller model "
from numpy import pi
from gpkit import Model, parse_variables, SignomialsEnabled, SignomialEquality
class Propeller(Model):
""" Propeller Model
Variables
---------
R 10 [m] prop radius
W 10 [lbf] prop weight
"""
def setup(self):
exec parse_variables(Propeller.__doc__)
def performance(state):
return Propeller_Performance(self, state)
class Propeller_Performance(Model):
""" Propeller Model
Variables
---------
T [N] thrust
Tc [-] coefficient of thrust
etaadd 0.7 [-] swirl and nonuniformity losses
etav 0.85 [-] viscous losses
etai [-] inviscid losses
eta [-] overall efficiency
z1 self.helper [-] efficiency helper 1
z2 [-] efficiency helper 2
"""
def helper(self, c):
return 2. - 1./c[self.etaadd]
def setup(self,parent, state):
exec parse_variables(Propeller.__doc__)
V = state.V
rho = state.rho
R = parent.R
constraints = [eta <= etav*etai,
Tc == T/(0.5*rho*V**2*pi*R**2),
z2 >= Tc + 1,
etai*(z1 + z2**0.5/etaadd) <= 2]
return constraints
|
Add prop structure and performance models
|
Add prop structure and performance models
|
Python
|
mit
|
convexengineering/gplibrary,convexengineering/gplibrary
|
python
|
## Code Before:
" propeller model "
from numpy import pi
from gpkit import Model, parse_variables, SignomialsEnabled, SignomialEquality
class Propeller(Model):
""" Propeller Model
Variables
---------
R 10 [m] prop radius
"""
def setup(self):
exec parse_variables(Propeller.__doc__)
def performance(state):
return Propeller_Performance(self, state)
class Propeller_Performance(Model):
""" Propeller Model
Variables
---------
T [N] thrust
Tc [-] coefficient of thrust
etaadd 0.7 [-] swirl and nonuniformity losses
etav 0.85 [-] viscous losses
etai [-] inviscid losses
eta [-] overall efficiency
z1 self.helper [-] efficiency helper 1
z2 [-] efficiency helper 2
"""
def helper(self, c):
return 2. - 1./c[self.etaadd]
def setup(self, state):
exec parse_variables(Propeller.__doc__)
V = state.V
rho = state.rho
constraints = [eta <= etav*etai,
Tc == T/(0.5*rho*V**2*pi*R**2),
z2 >= Tc + 1,
etai*(z1 + z2**0.5/etaadd) <= 2]
return constraints
## Instruction:
Add prop structure and performance models
## Code After:
" propeller model "
from numpy import pi
from gpkit import Model, parse_variables, SignomialsEnabled, SignomialEquality
class Propeller(Model):
""" Propeller Model
Variables
---------
R 10 [m] prop radius
W 10 [lbf] prop weight
"""
def setup(self):
exec parse_variables(Propeller.__doc__)
def performance(state):
return Propeller_Performance(self, state)
class Propeller_Performance(Model):
""" Propeller Model
Variables
---------
T [N] thrust
Tc [-] coefficient of thrust
etaadd 0.7 [-] swirl and nonuniformity losses
etav 0.85 [-] viscous losses
etai [-] inviscid losses
eta [-] overall efficiency
z1 self.helper [-] efficiency helper 1
z2 [-] efficiency helper 2
"""
def helper(self, c):
return 2. - 1./c[self.etaadd]
def setup(self,parent, state):
exec parse_variables(Propeller.__doc__)
V = state.V
rho = state.rho
R = parent.R
constraints = [eta <= etav*etai,
Tc == T/(0.5*rho*V**2*pi*R**2),
z2 >= Tc + 1,
etai*(z1 + z2**0.5/etaadd) <= 2]
return constraints
|
// ... existing code ...
Variables
---------
R 10 [m] prop radius
W 10 [lbf] prop weight
"""
def setup(self):
// ... modified code ...
def helper(self, c):
return 2. - 1./c[self.etaadd]
def setup(self,parent, state):
exec parse_variables(Propeller.__doc__)
V = state.V
rho = state.rho
R = parent.R
constraints = [eta <= etav*etai,
Tc == T/(0.5*rho*V**2*pi*R**2),
// ... rest of the code ...
|
1c467ec74899e69df8cf9f18b8814883388f14b2
|
library/src/main/java/com/hivedi/statfscompat/StatFsCompat.java
|
library/src/main/java/com/hivedi/statfscompat/StatFsCompat.java
|
package com.hivedi.statfscompat;
import android.os.Build;
import android.os.StatFs;
import java.io.File;
/**
* Created by Hivedi2 on 2015-11-24.
*
*/
public class StatFsCompat {
@SuppressWarnings("deprecation")
public static long getStatFsTotal(File f) {
StatFs statFs = new StatFs(f.getAbsolutePath());
if (Build.VERSION.SDK_INT >= 18) {
return statFs.getTotalBytes();
} else {
return statFs.getBlockCount() * statFs.getBlockSize();
}
}
@SuppressWarnings("deprecation")
public static long getStatFsFree(File f) {
StatFs statFs = new StatFs(f.getAbsolutePath());
if (Build.VERSION.SDK_INT >= 18) {
return statFs.getAvailableBlocksLong() * statFs.getBlockSizeLong();
} else {
return statFs.getAvailableBlocks() * (long) statFs.getBlockSize();
}
}
}
|
package com.hivedi.statfscompat;
import android.os.Build;
import android.os.StatFs;
import java.io.File;
/**
* Created by Hivedi2 on 2015-11-24.
*
*/
public class StatFsCompat {
public static final long STAT_FS_ERROR = -1L;
@SuppressWarnings("deprecation")
public static long getStatFsTotal(File f) {
try {
StatFs statFs = new StatFs(f.getAbsolutePath());
if (Build.VERSION.SDK_INT >= 18) {
return statFs.getTotalBytes();
} else {
return statFs.getBlockCount() * statFs.getBlockSize();
}
} catch (IllegalArgumentException e) {
return STAT_FS_ERROR;
}
}
@SuppressWarnings("deprecation")
public static long getStatFsFree(File f) {
try {
StatFs statFs = new StatFs(f.getAbsolutePath());
if (Build.VERSION.SDK_INT >= 18) {
return statFs.getAvailableBlocksLong() * statFs.getBlockSizeLong();
} else {
return statFs.getAvailableBlocks() * (long) statFs.getBlockSize();
}
} catch (IllegalArgumentException e) {
return STAT_FS_ERROR;
}
}
}
|
Handle error if file not exists
|
Handle error if file not exists
|
Java
|
apache-2.0
|
Hivedi/StatFsCompat
|
java
|
## Code Before:
package com.hivedi.statfscompat;
import android.os.Build;
import android.os.StatFs;
import java.io.File;
/**
* Created by Hivedi2 on 2015-11-24.
*
*/
public class StatFsCompat {
@SuppressWarnings("deprecation")
public static long getStatFsTotal(File f) {
StatFs statFs = new StatFs(f.getAbsolutePath());
if (Build.VERSION.SDK_INT >= 18) {
return statFs.getTotalBytes();
} else {
return statFs.getBlockCount() * statFs.getBlockSize();
}
}
@SuppressWarnings("deprecation")
public static long getStatFsFree(File f) {
StatFs statFs = new StatFs(f.getAbsolutePath());
if (Build.VERSION.SDK_INT >= 18) {
return statFs.getAvailableBlocksLong() * statFs.getBlockSizeLong();
} else {
return statFs.getAvailableBlocks() * (long) statFs.getBlockSize();
}
}
}
## Instruction:
Handle error if file not exists
## Code After:
package com.hivedi.statfscompat;
import android.os.Build;
import android.os.StatFs;
import java.io.File;
/**
* Created by Hivedi2 on 2015-11-24.
*
*/
public class StatFsCompat {
public static final long STAT_FS_ERROR = -1L;
@SuppressWarnings("deprecation")
public static long getStatFsTotal(File f) {
try {
StatFs statFs = new StatFs(f.getAbsolutePath());
if (Build.VERSION.SDK_INT >= 18) {
return statFs.getTotalBytes();
} else {
return statFs.getBlockCount() * statFs.getBlockSize();
}
} catch (IllegalArgumentException e) {
return STAT_FS_ERROR;
}
}
@SuppressWarnings("deprecation")
public static long getStatFsFree(File f) {
try {
StatFs statFs = new StatFs(f.getAbsolutePath());
if (Build.VERSION.SDK_INT >= 18) {
return statFs.getAvailableBlocksLong() * statFs.getBlockSizeLong();
} else {
return statFs.getAvailableBlocks() * (long) statFs.getBlockSize();
}
} catch (IllegalArgumentException e) {
return STAT_FS_ERROR;
}
}
}
|
...
*/
public class StatFsCompat {
public static final long STAT_FS_ERROR = -1L;
@SuppressWarnings("deprecation")
public static long getStatFsTotal(File f) {
try {
StatFs statFs = new StatFs(f.getAbsolutePath());
if (Build.VERSION.SDK_INT >= 18) {
return statFs.getTotalBytes();
} else {
return statFs.getBlockCount() * statFs.getBlockSize();
}
} catch (IllegalArgumentException e) {
return STAT_FS_ERROR;
}
}
@SuppressWarnings("deprecation")
public static long getStatFsFree(File f) {
try {
StatFs statFs = new StatFs(f.getAbsolutePath());
if (Build.VERSION.SDK_INT >= 18) {
return statFs.getAvailableBlocksLong() * statFs.getBlockSizeLong();
} else {
return statFs.getAvailableBlocks() * (long) statFs.getBlockSize();
}
} catch (IllegalArgumentException e) {
return STAT_FS_ERROR;
}
}
...
|
a540a68561db4067b66b4d4d0920b217fea4fda4
|
var/spack/packages/openssl/package.py
|
var/spack/packages/openssl/package.py
|
from spack import *
class Openssl(Package):
"""The OpenSSL Project is a collaborative effort to develop a
robust, commercial-grade, full-featured, and Open Source
toolkit implementing the Secure Sockets Layer (SSL v2/v3) and
Transport Layer Security (TLS v1) protocols as well as a
full-strength general purpose cryptography library."""
homepage = "http://www.openssl.org"
url = "http://www.openssl.org/source/openssl-1.0.1h.tar.gz"
version('1.0.1h', '8d6d684a9430d5cc98a62a5d8fbda8cf')
version('1.0.2d', '38dd619b2e77cbac69b99f52a053d25a')
version('1.0.2e', '5262bfa25b60ed9de9f28d5d52d77fc5')
depends_on("zlib")
parallel = False
def install(self, spec, prefix):
config = Executable("./config")
config("--prefix=%s" % prefix,
"--openssldir=%s/etc/openssl" % prefix,
"zlib",
"no-krb5",
"shared")
make()
make("install")
|
from spack import *
class Openssl(Package):
"""The OpenSSL Project is a collaborative effort to develop a
robust, commercial-grade, full-featured, and Open Source
toolkit implementing the Secure Sockets Layer (SSL v2/v3) and
Transport Layer Security (TLS v1) protocols as well as a
full-strength general purpose cryptography library."""
homepage = "http://www.openssl.org"
url = "http://www.openssl.org/source/openssl-1.0.1h.tar.gz"
version('1.0.1h', '8d6d684a9430d5cc98a62a5d8fbda8cf')
version('1.0.2d', '38dd619b2e77cbac69b99f52a053d25a')
version('1.0.2e', '5262bfa25b60ed9de9f28d5d52d77fc5')
depends_on("zlib")
parallel = False
def install(self, spec, prefix):
if spec.satisfies("=darwin-x86_64"):
perl = which('perl')
perl("./Configure",
"--prefix=%s" % prefix,
"--openssldir=%s/etc/openssl" % prefix,
"zlib",
"no-krb5",
"shared",
"darwin64-x86_64-cc")
perl('-pi', '-e', 's/-arch x86_64//g', 'Makefile')
else:
exit(1)
config = Executable("./config")
config("--prefix=%s" % prefix,
"--openssldir=%s/etc/openssl" % prefix,
"zlib",
"no-krb5",
"shared")
make()
make("install")
|
Make OpenSSL build on Darwin
|
Make OpenSSL build on Darwin
|
Python
|
lgpl-2.1
|
matthiasdiener/spack,EmreAtes/spack,krafczyk/spack,iulian787/spack,matthiasdiener/spack,tmerrick1/spack,krafczyk/spack,lgarren/spack,TheTimmy/spack,iulian787/spack,EmreAtes/spack,EmreAtes/spack,skosukhin/spack,krafczyk/spack,mfherbst/spack,LLNL/spack,mfherbst/spack,skosukhin/spack,krafczyk/spack,mfherbst/spack,tmerrick1/spack,lgarren/spack,matthiasdiener/spack,lgarren/spack,EmreAtes/spack,mfherbst/spack,LLNL/spack,tmerrick1/spack,TheTimmy/spack,skosukhin/spack,iulian787/spack,mfherbst/spack,skosukhin/spack,tmerrick1/spack,EmreAtes/spack,iulian787/spack,LLNL/spack,iulian787/spack,krafczyk/spack,lgarren/spack,skosukhin/spack,TheTimmy/spack,TheTimmy/spack,matthiasdiener/spack,lgarren/spack,TheTimmy/spack,tmerrick1/spack,matthiasdiener/spack,LLNL/spack,LLNL/spack
|
python
|
## Code Before:
from spack import *
class Openssl(Package):
"""The OpenSSL Project is a collaborative effort to develop a
robust, commercial-grade, full-featured, and Open Source
toolkit implementing the Secure Sockets Layer (SSL v2/v3) and
Transport Layer Security (TLS v1) protocols as well as a
full-strength general purpose cryptography library."""
homepage = "http://www.openssl.org"
url = "http://www.openssl.org/source/openssl-1.0.1h.tar.gz"
version('1.0.1h', '8d6d684a9430d5cc98a62a5d8fbda8cf')
version('1.0.2d', '38dd619b2e77cbac69b99f52a053d25a')
version('1.0.2e', '5262bfa25b60ed9de9f28d5d52d77fc5')
depends_on("zlib")
parallel = False
def install(self, spec, prefix):
config = Executable("./config")
config("--prefix=%s" % prefix,
"--openssldir=%s/etc/openssl" % prefix,
"zlib",
"no-krb5",
"shared")
make()
make("install")
## Instruction:
Make OpenSSL build on Darwin
## Code After:
from spack import *
class Openssl(Package):
"""The OpenSSL Project is a collaborative effort to develop a
robust, commercial-grade, full-featured, and Open Source
toolkit implementing the Secure Sockets Layer (SSL v2/v3) and
Transport Layer Security (TLS v1) protocols as well as a
full-strength general purpose cryptography library."""
homepage = "http://www.openssl.org"
url = "http://www.openssl.org/source/openssl-1.0.1h.tar.gz"
version('1.0.1h', '8d6d684a9430d5cc98a62a5d8fbda8cf')
version('1.0.2d', '38dd619b2e77cbac69b99f52a053d25a')
version('1.0.2e', '5262bfa25b60ed9de9f28d5d52d77fc5')
depends_on("zlib")
parallel = False
def install(self, spec, prefix):
if spec.satisfies("=darwin-x86_64"):
perl = which('perl')
perl("./Configure",
"--prefix=%s" % prefix,
"--openssldir=%s/etc/openssl" % prefix,
"zlib",
"no-krb5",
"shared",
"darwin64-x86_64-cc")
perl('-pi', '-e', 's/-arch x86_64//g', 'Makefile')
else:
exit(1)
config = Executable("./config")
config("--prefix=%s" % prefix,
"--openssldir=%s/etc/openssl" % prefix,
"zlib",
"no-krb5",
"shared")
make()
make("install")
|
# ... existing code ...
parallel = False
def install(self, spec, prefix):
if spec.satisfies("=darwin-x86_64"):
perl = which('perl')
perl("./Configure",
"--prefix=%s" % prefix,
"--openssldir=%s/etc/openssl" % prefix,
"zlib",
"no-krb5",
"shared",
"darwin64-x86_64-cc")
perl('-pi', '-e', 's/-arch x86_64//g', 'Makefile')
else:
exit(1)
config = Executable("./config")
config("--prefix=%s" % prefix,
"--openssldir=%s/etc/openssl" % prefix,
"zlib",
"no-krb5",
"shared")
make()
make("install")
# ... rest of the code ...
|
68cd7a11b50c4f4a194f6d439e6b83b3b2f46243
|
src/main/java/org/openlmis/stockmanagement/domain/reason/ReasonType.java
|
src/main/java/org/openlmis/stockmanagement/domain/reason/ReasonType.java
|
/*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2017 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms
* of the GNU Affero General Public License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details. You should have received a copy of
* the GNU Affero General Public License along with this program. If not, see
* http://www.gnu.org/licenses. For additional information contact [email protected].
*/
package org.openlmis.stockmanagement.domain.reason;
import lombok.Getter;
public enum ReasonType {
CREDIT(2),
DEBIT(1),
BALANCE_ADJUSTMENT(0);
/**
* Value of this field will be used to set correct order of stock card line items if both
* occurred and processed dates have the same date for the following line items. It is
* important that types that are used to increase (like {@link #CREDIT}) should have higher
* priority than types that are used to decrease (like {@link #DEBIT}).
*/
@Getter
private int priority;
ReasonType(int priority) {
this.priority = priority;
}
}
|
/*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2017 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms
* of the GNU Affero General Public License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details. You should have received a copy of
* the GNU Affero General Public License along with this program. If not, see
* http://www.gnu.org/licenses. For additional information contact [email protected].
*/
package org.openlmis.stockmanagement.domain.reason;
import lombok.Getter;
public enum ReasonType {
CREDIT(2),
DEBIT(1),
BALANCE_ADJUSTMENT(0);
@Getter
private int priority;
ReasonType(int priority) {
this.priority = priority;
}
}
|
Revert "OLMIS-3533: Added javadoc for Reason type priority field"
|
Revert "OLMIS-3533: Added javadoc for Reason type priority field"
This reverts commit e5ccc08d57d538b6d6a4c6a8fd099f50e3a769af.
|
Java
|
agpl-3.0
|
OpenLMIS/openlmis-stockmanagement,OpenLMIS/openlmis-stockmanagement,OpenLMIS/openlmis-stockmanagement,OpenLMIS/openlmis-stockmanagement
|
java
|
## Code Before:
/*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2017 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms
* of the GNU Affero General Public License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details. You should have received a copy of
* the GNU Affero General Public License along with this program. If not, see
* http://www.gnu.org/licenses. For additional information contact [email protected].
*/
package org.openlmis.stockmanagement.domain.reason;
import lombok.Getter;
public enum ReasonType {
CREDIT(2),
DEBIT(1),
BALANCE_ADJUSTMENT(0);
/**
* Value of this field will be used to set correct order of stock card line items if both
* occurred and processed dates have the same date for the following line items. It is
* important that types that are used to increase (like {@link #CREDIT}) should have higher
* priority than types that are used to decrease (like {@link #DEBIT}).
*/
@Getter
private int priority;
ReasonType(int priority) {
this.priority = priority;
}
}
## Instruction:
Revert "OLMIS-3533: Added javadoc for Reason type priority field"
This reverts commit e5ccc08d57d538b6d6a4c6a8fd099f50e3a769af.
## Code After:
/*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2017 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms
* of the GNU Affero General Public License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details. You should have received a copy of
* the GNU Affero General Public License along with this program. If not, see
* http://www.gnu.org/licenses. For additional information contact [email protected].
*/
package org.openlmis.stockmanagement.domain.reason;
import lombok.Getter;
public enum ReasonType {
CREDIT(2),
DEBIT(1),
BALANCE_ADJUSTMENT(0);
@Getter
private int priority;
ReasonType(int priority) {
this.priority = priority;
}
}
|
# ... existing code ...
DEBIT(1),
BALANCE_ADJUSTMENT(0);
@Getter
private int priority;
# ... rest of the code ...
|
f61ba51f92ff47716128bb9d607b4cb46e7bfa4b
|
gblinks/cli.py
|
gblinks/cli.py
|
import click
import json
import sys
from gblinks import Gblinks
def check_broken_links(gblinks):
broken_links = gblinks.check_broken_links()
if broken_links:
print_links(broken_links)
click.echo(
click.style(
'%d broken links found in the given path' % len(broken_links)
, fg='red'
)
)
sys.exit(-1)
else:
click.echo('No broken links found in the given path')
def list_links(gblinks):
links = gblinks.get_links()
print_links(links)
click.echo('%d links found in the given path' % len(links))
def print_links(links):
for link in links:
click.echo(json.dumps(link, sort_keys=True, indent=4))
@click.command()
@click.argument('path')
@click.option('--check/--no-check', default=False)
@click.option('--list/--no-list', default=False)
def main(path, check, list):
gblinks = Gblinks(path)
if check:
check_broken_links(gblinks)
if list:
list_links(gblinks)
if __name__ == "__main__":
main()
|
import click
import json
import sys
from gblinks import Gblinks
def check_broken_links(gblinks):
broken_links = gblinks.check_broken_links()
if broken_links:
print_links(broken_links)
click.echo(
click.style(
'%d broken links found in the given path' % len(broken_links)
, fg='red'
)
)
sys.exit(-2)
else:
click.echo('No broken links found in the given path')
def list_links(gblinks):
links = gblinks.get_links()
print_links(links)
click.echo('%d links found in the given path' % len(links))
def print_links(links):
for link in links:
click.echo(json.dumps(link, sort_keys=True, indent=4))
@click.command()
@click.argument('path')
@click.option('--check/--no-check', default=False)
@click.option('--list/--no-list', default=False)
def main(path, check, list):
try:
gblinks = Gblinks(path)
if check:
check_broken_links(gblinks)
if list:
list_links(gblinks)
except ValueError, e:
click.echo(click.style(str(e), fg='red'))
sys.exit(-1)
if __name__ == "__main__":
main()
|
Add code to handle exception
|
Add code to handle exception
|
Python
|
mit
|
davidmogar/gblinks
|
python
|
## Code Before:
import click
import json
import sys
from gblinks import Gblinks
def check_broken_links(gblinks):
broken_links = gblinks.check_broken_links()
if broken_links:
print_links(broken_links)
click.echo(
click.style(
'%d broken links found in the given path' % len(broken_links)
, fg='red'
)
)
sys.exit(-1)
else:
click.echo('No broken links found in the given path')
def list_links(gblinks):
links = gblinks.get_links()
print_links(links)
click.echo('%d links found in the given path' % len(links))
def print_links(links):
for link in links:
click.echo(json.dumps(link, sort_keys=True, indent=4))
@click.command()
@click.argument('path')
@click.option('--check/--no-check', default=False)
@click.option('--list/--no-list', default=False)
def main(path, check, list):
gblinks = Gblinks(path)
if check:
check_broken_links(gblinks)
if list:
list_links(gblinks)
if __name__ == "__main__":
main()
## Instruction:
Add code to handle exception
## Code After:
import click
import json
import sys
from gblinks import Gblinks
def check_broken_links(gblinks):
broken_links = gblinks.check_broken_links()
if broken_links:
print_links(broken_links)
click.echo(
click.style(
'%d broken links found in the given path' % len(broken_links)
, fg='red'
)
)
sys.exit(-2)
else:
click.echo('No broken links found in the given path')
def list_links(gblinks):
links = gblinks.get_links()
print_links(links)
click.echo('%d links found in the given path' % len(links))
def print_links(links):
for link in links:
click.echo(json.dumps(link, sort_keys=True, indent=4))
@click.command()
@click.argument('path')
@click.option('--check/--no-check', default=False)
@click.option('--list/--no-list', default=False)
def main(path, check, list):
try:
gblinks = Gblinks(path)
if check:
check_broken_links(gblinks)
if list:
list_links(gblinks)
except ValueError, e:
click.echo(click.style(str(e), fg='red'))
sys.exit(-1)
if __name__ == "__main__":
main()
|
# ... existing code ...
)
)
sys.exit(-2)
else:
click.echo('No broken links found in the given path')
# ... modified code ...
@click.option('--check/--no-check', default=False)
@click.option('--list/--no-list', default=False)
def main(path, check, list):
try:
gblinks = Gblinks(path)
if check:
check_broken_links(gblinks)
if list:
list_links(gblinks)
except ValueError, e:
click.echo(click.style(str(e), fg='red'))
sys.exit(-1)
if __name__ == "__main__":
main()
# ... rest of the code ...
|
0922c8d06264f02f9b8de59e3546e499c8599326
|
tests/test_views.py
|
tests/test_views.py
|
import unittest
from flask import current_app, url_for, get_flashed_messages
from app import create_app, db
from app.models import *
class TestCreateAdmissionView(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
self.client = self.app.test_client(use_cookies=True)
self.valid_admission_form = {
'id_lvrs_intern': 1,
}
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_context.pop()
def test_duplicate_id_lvrs_intern(self):
a = Admission(id_lvrs_intern=1)
db.session.add(a)
db.session.commit()
data = {
'id_lvrs_intern': 1,
'samples-0-collection_date': '12/12/2012',
'samples-0-admission_date': '13/12/2012',
}
duplicate_id_lvrs_intern = 'Número Interno já cadastrado!'
response = self.client.post(
url_for('main.create_admission'), data=data, follow_redirects=True)
self.assertTrue(
duplicate_id_lvrs_intern in response.get_data(as_text=True))
|
import unittest
from flask import current_app, url_for, get_flashed_messages
from app import create_app, db
from app.models import *
class TestCreateAdmissionView(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
self.client = self.app.test_client(use_cookies=True)
self.valid_admission_form = {
'id_lvrs_intern': 1,
}
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_context.pop()
def test_duplicate_id_lvrs_intern(self):
a = Admission(id_lvrs_intern=1)
db.session.add(a)
db.session.commit()
data = {
'id_lvrs_intern': '1',
'samples-0-collection_date': '12/12/2012',
'samples-0-admission_date': '13/12/2012',
}
duplicate_id_lvrs_intern = 'Número Interno já cadastrado!'
response = self.client.post(
url_for('main.create_admission'), data=data, follow_redirects=True)
self.assertTrue(
duplicate_id_lvrs_intern in response.get_data(as_text=True))
self.assertTrue(
len(Admission.query.filter_by(id_lvrs_intern='1').all()), 1)
|
Change id_lvrs_internt to string. Test if there's only one created
|
:bug: Change id_lvrs_internt to string. Test if there's only one created
|
Python
|
mit
|
gems-uff/labsys,gems-uff/labsys,gems-uff/labsys
|
python
|
## Code Before:
import unittest
from flask import current_app, url_for, get_flashed_messages
from app import create_app, db
from app.models import *
class TestCreateAdmissionView(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
self.client = self.app.test_client(use_cookies=True)
self.valid_admission_form = {
'id_lvrs_intern': 1,
}
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_context.pop()
def test_duplicate_id_lvrs_intern(self):
a = Admission(id_lvrs_intern=1)
db.session.add(a)
db.session.commit()
data = {
'id_lvrs_intern': 1,
'samples-0-collection_date': '12/12/2012',
'samples-0-admission_date': '13/12/2012',
}
duplicate_id_lvrs_intern = 'Número Interno já cadastrado!'
response = self.client.post(
url_for('main.create_admission'), data=data, follow_redirects=True)
self.assertTrue(
duplicate_id_lvrs_intern in response.get_data(as_text=True))
## Instruction:
:bug: Change id_lvrs_internt to string. Test if there's only one created
## Code After:
import unittest
from flask import current_app, url_for, get_flashed_messages
from app import create_app, db
from app.models import *
class TestCreateAdmissionView(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
self.client = self.app.test_client(use_cookies=True)
self.valid_admission_form = {
'id_lvrs_intern': 1,
}
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_context.pop()
def test_duplicate_id_lvrs_intern(self):
a = Admission(id_lvrs_intern=1)
db.session.add(a)
db.session.commit()
data = {
'id_lvrs_intern': '1',
'samples-0-collection_date': '12/12/2012',
'samples-0-admission_date': '13/12/2012',
}
duplicate_id_lvrs_intern = 'Número Interno já cadastrado!'
response = self.client.post(
url_for('main.create_admission'), data=data, follow_redirects=True)
self.assertTrue(
duplicate_id_lvrs_intern in response.get_data(as_text=True))
self.assertTrue(
len(Admission.query.filter_by(id_lvrs_intern='1').all()), 1)
|
# ... existing code ...
db.session.add(a)
db.session.commit()
data = {
'id_lvrs_intern': '1',
'samples-0-collection_date': '12/12/2012',
'samples-0-admission_date': '13/12/2012',
}
# ... modified code ...
url_for('main.create_admission'), data=data, follow_redirects=True)
self.assertTrue(
duplicate_id_lvrs_intern in response.get_data(as_text=True))
self.assertTrue(
len(Admission.query.filter_by(id_lvrs_intern='1').all()), 1)
# ... rest of the code ...
|
6894bd3cfc010c371478e7ae9e5e0b3ba108e165
|
plugins/configuration/configurationtype/configuration_registrar.py
|
plugins/configuration/configurationtype/configuration_registrar.py
|
import luna.plugins
_configurations = {}
"""
The configuration classes that have been registered here so far, keyed by their
identities.
"""
def register(identity, metadata):
"""
Registers a new configuration plug-in to track configuration with.
This expects the metadata to already be verified as configuration's
metadata.
:param identity: The identity of the plug-in to register.
:param metadata: The metadata of a configuration plug-in.
"""
if identity in _configurations:
luna.plugins.api("logger").warning("Configuration {configuration} is already registered.", configuration=identity)
return
_configurations[identity] = metadata["configuration"]["class"]
def unregister(identity):
raise Exception("Not implemented yet.")
def validate_metadata(metadata):
raise Exception("Not implemented yet.")
|
import luna.plugins
_configurations = {}
"""
The configuration classes that have been registered here so far, keyed by their
identities.
"""
def register(identity, metadata):
"""
Registers a new configuration plug-in to track configuration with.
This expects the metadata to already be verified as configuration's
metadata.
:param identity: The identity of the plug-in to register.
:param metadata: The metadata of a configuration plug-in.
"""
if identity in _configurations:
luna.plugins.api("logger").warning("Configuration {configuration} is already registered.", configuration=identity)
return
_configurations[identity] = metadata["configuration"]["class"]
def unregister(identity):
"""
Undoes the registration of a configuration plug-in.
The configuration plug-in will no longer keep track of any configuration.
Existing configuration will be stored persistently.
:param identity: The identity of the plug-in to unregister.
"""
if identity not in _configurations:
luna.plugins.api("logger").warning("Configuration {configuration} is not registered, so I can't unregister it.", configuration=identity)
return
del _configurations[identity] #The actual unregistration.
def validate_metadata(metadata):
raise Exception("Not implemented yet.")
|
Implement unregistration of configuration plug-ins
|
Implement unregistration of configuration plug-ins
Perhaps we should not give a warning, but instead an exception, when registering or unregistering fails?
|
Python
|
cc0-1.0
|
Ghostkeeper/Luna
|
python
|
## Code Before:
import luna.plugins
_configurations = {}
"""
The configuration classes that have been registered here so far, keyed by their
identities.
"""
def register(identity, metadata):
"""
Registers a new configuration plug-in to track configuration with.
This expects the metadata to already be verified as configuration's
metadata.
:param identity: The identity of the plug-in to register.
:param metadata: The metadata of a configuration plug-in.
"""
if identity in _configurations:
luna.plugins.api("logger").warning("Configuration {configuration} is already registered.", configuration=identity)
return
_configurations[identity] = metadata["configuration"]["class"]
def unregister(identity):
raise Exception("Not implemented yet.")
def validate_metadata(metadata):
raise Exception("Not implemented yet.")
## Instruction:
Implement unregistration of configuration plug-ins
Perhaps we should not give a warning, but instead an exception, when registering or unregistering fails?
## Code After:
import luna.plugins
_configurations = {}
"""
The configuration classes that have been registered here so far, keyed by their
identities.
"""
def register(identity, metadata):
"""
Registers a new configuration plug-in to track configuration with.
This expects the metadata to already be verified as configuration's
metadata.
:param identity: The identity of the plug-in to register.
:param metadata: The metadata of a configuration plug-in.
"""
if identity in _configurations:
luna.plugins.api("logger").warning("Configuration {configuration} is already registered.", configuration=identity)
return
_configurations[identity] = metadata["configuration"]["class"]
def unregister(identity):
"""
Undoes the registration of a configuration plug-in.
The configuration plug-in will no longer keep track of any configuration.
Existing configuration will be stored persistently.
:param identity: The identity of the plug-in to unregister.
"""
if identity not in _configurations:
luna.plugins.api("logger").warning("Configuration {configuration} is not registered, so I can't unregister it.", configuration=identity)
return
del _configurations[identity] #The actual unregistration.
def validate_metadata(metadata):
raise Exception("Not implemented yet.")
|
// ... existing code ...
_configurations[identity] = metadata["configuration"]["class"]
def unregister(identity):
"""
Undoes the registration of a configuration plug-in.
The configuration plug-in will no longer keep track of any configuration.
Existing configuration will be stored persistently.
:param identity: The identity of the plug-in to unregister.
"""
if identity not in _configurations:
luna.plugins.api("logger").warning("Configuration {configuration} is not registered, so I can't unregister it.", configuration=identity)
return
del _configurations[identity] #The actual unregistration.
def validate_metadata(metadata):
raise Exception("Not implemented yet.")
// ... rest of the code ...
|
32c9a7f80d9e46f8236c20af9eda0d7516181085
|
src/main/java/reborncore/common/BaseTileBlock.java
|
src/main/java/reborncore/common/BaseTileBlock.java
|
package reborncore.common;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import reborncore.RebornCore;
public abstract class BaseTileBlock extends Block implements ITileEntityProvider
{
protected BaseTileBlock(Material materialIn)
{
super(materialIn);
RebornCore.jsonDestroyer.registerObject(this);
}
public int getRenderType()
{
return 3;
}
@Override
public void breakBlock(World worldIn, BlockPos pos, IBlockState state)
{
super.breakBlock(worldIn, pos, state);
worldIn.removeTileEntity(pos);
}
}
|
package reborncore.common;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import reborncore.RebornCore;
public abstract class BaseTileBlock extends Block implements ITileEntityProvider
{
protected BaseTileBlock(Material materialIn)
{
super(materialIn);
RebornCore.jsonDestroyer.registerObject(this);
setHardness(1F);
}
public int getRenderType()
{
return 3;
}
@Override
public void breakBlock(World worldIn, BlockPos pos, IBlockState state)
{
super.breakBlock(worldIn, pos, state);
worldIn.removeTileEntity(pos);
}
}
|
Add a hardness to the base block
|
Add a hardness to the base block
|
Java
|
mit
|
TechReborn/RebornCore
|
java
|
## Code Before:
package reborncore.common;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import reborncore.RebornCore;
public abstract class BaseTileBlock extends Block implements ITileEntityProvider
{
protected BaseTileBlock(Material materialIn)
{
super(materialIn);
RebornCore.jsonDestroyer.registerObject(this);
}
public int getRenderType()
{
return 3;
}
@Override
public void breakBlock(World worldIn, BlockPos pos, IBlockState state)
{
super.breakBlock(worldIn, pos, state);
worldIn.removeTileEntity(pos);
}
}
## Instruction:
Add a hardness to the base block
## Code After:
package reborncore.common;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import reborncore.RebornCore;
public abstract class BaseTileBlock extends Block implements ITileEntityProvider
{
protected BaseTileBlock(Material materialIn)
{
super(materialIn);
RebornCore.jsonDestroyer.registerObject(this);
setHardness(1F);
}
public int getRenderType()
{
return 3;
}
@Override
public void breakBlock(World worldIn, BlockPos pos, IBlockState state)
{
super.breakBlock(worldIn, pos, state);
worldIn.removeTileEntity(pos);
}
}
|
# ... existing code ...
{
super(materialIn);
RebornCore.jsonDestroyer.registerObject(this);
setHardness(1F);
}
public int getRenderType()
# ... rest of the code ...
|
623326c3fe15ab3c365ffba81f78ced5003a8193
|
org.jrebirth.af/core/src/test/java/org/jrebirth/af/core/command/basic/multi/MultiCommandTest.java
|
org.jrebirth.af/core/src/test/java/org/jrebirth/af/core/command/basic/multi/MultiCommandTest.java
|
package org.jrebirth.af.core.command.basic.multi;
import org.jrebirth.af.core.command.basic.BasicCommandTest;
import org.junit.Test;
//@Ignore("JavaFX can't be run in headless mode yet")
public class MultiCommandTest extends BasicCommandTest {
@Test
public void sequentialTest1() {
System.out.println("Sequential Test default");
runCommand(DefaultSequentialCommand.class);
}
@Test
public void sequentialTest2() {
System.out.println("Sequential Test annotation");
runCommand(AnnotatedSequentialCommand.class);
}
@Test
public void sequentialTest3() {
System.out.println("Sequential Test constructor");
runCommand(ConstructorSequentialCommand.class);
}
@Test
public void parallelTest1() {
System.out.println("Parallel Test default");
runCommand(DefaultParallelCommand.class);
}
@Test
public void parallelTest2() {
System.out.println("Parallel Test annotation");
runCommand(AnnotatedParallelCommand.class);
}
@Test
public void parallelTest3() {
System.out.println("Parallel Test constructor");
runCommand(ConstructorParallelCommand.class);
}
}
|
package org.jrebirth.af.core.command.basic.multi;
import org.jrebirth.af.core.command.basic.BasicCommandTest;
import org.junit.Ignore;
import org.junit.Test;
@Ignore("JavaFX can't be run in headless mode yet")
public class MultiCommandTest extends BasicCommandTest {
@Test
public void sequentialTest1() {
System.out.println("Sequential Test default");
runCommand(DefaultSequentialCommand.class);
}
@Test
public void sequentialTest2() {
System.out.println("Sequential Test annotation");
runCommand(AnnotatedSequentialCommand.class);
}
@Test
public void sequentialTest3() {
System.out.println("Sequential Test constructor");
runCommand(ConstructorSequentialCommand.class);
}
@Test
public void parallelTest1() {
System.out.println("Parallel Test default");
runCommand(DefaultParallelCommand.class);
}
@Test
public void parallelTest2() {
System.out.println("Parallel Test annotation");
runCommand(AnnotatedParallelCommand.class);
}
@Test
public void parallelTest3() {
System.out.println("Parallel Test constructor");
runCommand(ConstructorParallelCommand.class);
}
}
|
Disable test untestable without x server
|
Disable test untestable without x server
|
Java
|
apache-2.0
|
Rizen59/JRebirth,Rizen59/JRebirth,JRebirth/JRebirth,JRebirth/JRebirth
|
java
|
## Code Before:
package org.jrebirth.af.core.command.basic.multi;
import org.jrebirth.af.core.command.basic.BasicCommandTest;
import org.junit.Test;
//@Ignore("JavaFX can't be run in headless mode yet")
public class MultiCommandTest extends BasicCommandTest {
@Test
public void sequentialTest1() {
System.out.println("Sequential Test default");
runCommand(DefaultSequentialCommand.class);
}
@Test
public void sequentialTest2() {
System.out.println("Sequential Test annotation");
runCommand(AnnotatedSequentialCommand.class);
}
@Test
public void sequentialTest3() {
System.out.println("Sequential Test constructor");
runCommand(ConstructorSequentialCommand.class);
}
@Test
public void parallelTest1() {
System.out.println("Parallel Test default");
runCommand(DefaultParallelCommand.class);
}
@Test
public void parallelTest2() {
System.out.println("Parallel Test annotation");
runCommand(AnnotatedParallelCommand.class);
}
@Test
public void parallelTest3() {
System.out.println("Parallel Test constructor");
runCommand(ConstructorParallelCommand.class);
}
}
## Instruction:
Disable test untestable without x server
## Code After:
package org.jrebirth.af.core.command.basic.multi;
import org.jrebirth.af.core.command.basic.BasicCommandTest;
import org.junit.Ignore;
import org.junit.Test;
@Ignore("JavaFX can't be run in headless mode yet")
public class MultiCommandTest extends BasicCommandTest {
@Test
public void sequentialTest1() {
System.out.println("Sequential Test default");
runCommand(DefaultSequentialCommand.class);
}
@Test
public void sequentialTest2() {
System.out.println("Sequential Test annotation");
runCommand(AnnotatedSequentialCommand.class);
}
@Test
public void sequentialTest3() {
System.out.println("Sequential Test constructor");
runCommand(ConstructorSequentialCommand.class);
}
@Test
public void parallelTest1() {
System.out.println("Parallel Test default");
runCommand(DefaultParallelCommand.class);
}
@Test
public void parallelTest2() {
System.out.println("Parallel Test annotation");
runCommand(AnnotatedParallelCommand.class);
}
@Test
public void parallelTest3() {
System.out.println("Parallel Test constructor");
runCommand(ConstructorParallelCommand.class);
}
}
|
...
import org.jrebirth.af.core.command.basic.BasicCommandTest;
import org.junit.Ignore;
import org.junit.Test;
@Ignore("JavaFX can't be run in headless mode yet")
public class MultiCommandTest extends BasicCommandTest {
@Test
...
|
fc1cb951991cc9b4b0cdb9d533127d26eb21ea57
|
rave/__main__.py
|
rave/__main__.py
|
import argparse
import sys
from os import path
def parse_arguments():
parser = argparse.ArgumentParser(description='A modular and extensible visual novel engine.', prog='rave')
parser.add_argument('-b', '--bootstrapper', help='Select bootstrapper to bootstrap the engine with. (default: autoselect)')
parser.add_argument('-B', '--game-bootstrapper', metavar='BOOTSTRAPPER', help='Select bootstrapper to bootstrap the game with. (default: autoselect)')
parser.add_argument('-d', '--debug', action='store_true', help='Enable debug logging.')
parser.add_argument('game', metavar='GAME', nargs='?', help='The game to run. Format dependent on used bootstrapper.')
arguments = parser.parse_args()
return arguments
def main():
args = parse_arguments()
if args.debug:
from . import log
log.Logger.LEVEL |= log.DEBUG
from . import bootstrap
bootstrap.bootstrap_engine(args.bootstrapper)
if args.game:
game = bootstrap.bootstrap_game(args.game_bootstrapper, args.game)
bootstrap.shutdown_game(game)
bootstrap.shutdown()
main()
|
import argparse
import sys
from os import path
def parse_arguments():
parser = argparse.ArgumentParser(description='A modular and extensible visual novel engine.', prog='rave')
parser.add_argument('-b', '--bootstrapper', help='Select bootstrapper to bootstrap the engine with. (default: autoselect)')
parser.add_argument('-B', '--game-bootstrapper', metavar='BOOTSTRAPPER', help='Select bootstrapper to bootstrap the game with. (default: autoselect)')
parser.add_argument('game', metavar='GAME', nargs='?', help='The game to run. Format dependent on used bootstrapper.')
arguments = parser.parse_args()
return arguments
def main():
args = parse_arguments()
from . import bootstrap
bootstrap.bootstrap_engine(args.bootstrapper)
if args.game:
game = bootstrap.bootstrap_game(args.game_bootstrapper, args.game)
bootstrap.shutdown_game(game)
bootstrap.shutdown()
main()
|
Remove -d command line argument in favour of __debug__.
|
rave: Remove -d command line argument in favour of __debug__.
|
Python
|
bsd-2-clause
|
rave-engine/rave
|
python
|
## Code Before:
import argparse
import sys
from os import path
def parse_arguments():
parser = argparse.ArgumentParser(description='A modular and extensible visual novel engine.', prog='rave')
parser.add_argument('-b', '--bootstrapper', help='Select bootstrapper to bootstrap the engine with. (default: autoselect)')
parser.add_argument('-B', '--game-bootstrapper', metavar='BOOTSTRAPPER', help='Select bootstrapper to bootstrap the game with. (default: autoselect)')
parser.add_argument('-d', '--debug', action='store_true', help='Enable debug logging.')
parser.add_argument('game', metavar='GAME', nargs='?', help='The game to run. Format dependent on used bootstrapper.')
arguments = parser.parse_args()
return arguments
def main():
args = parse_arguments()
if args.debug:
from . import log
log.Logger.LEVEL |= log.DEBUG
from . import bootstrap
bootstrap.bootstrap_engine(args.bootstrapper)
if args.game:
game = bootstrap.bootstrap_game(args.game_bootstrapper, args.game)
bootstrap.shutdown_game(game)
bootstrap.shutdown()
main()
## Instruction:
rave: Remove -d command line argument in favour of __debug__.
## Code After:
import argparse
import sys
from os import path
def parse_arguments():
parser = argparse.ArgumentParser(description='A modular and extensible visual novel engine.', prog='rave')
parser.add_argument('-b', '--bootstrapper', help='Select bootstrapper to bootstrap the engine with. (default: autoselect)')
parser.add_argument('-B', '--game-bootstrapper', metavar='BOOTSTRAPPER', help='Select bootstrapper to bootstrap the game with. (default: autoselect)')
parser.add_argument('game', metavar='GAME', nargs='?', help='The game to run. Format dependent on used bootstrapper.')
arguments = parser.parse_args()
return arguments
def main():
args = parse_arguments()
from . import bootstrap
bootstrap.bootstrap_engine(args.bootstrapper)
if args.game:
game = bootstrap.bootstrap_game(args.game_bootstrapper, args.game)
bootstrap.shutdown_game(game)
bootstrap.shutdown()
main()
|
# ... existing code ...
parser = argparse.ArgumentParser(description='A modular and extensible visual novel engine.', prog='rave')
parser.add_argument('-b', '--bootstrapper', help='Select bootstrapper to bootstrap the engine with. (default: autoselect)')
parser.add_argument('-B', '--game-bootstrapper', metavar='BOOTSTRAPPER', help='Select bootstrapper to bootstrap the game with. (default: autoselect)')
parser.add_argument('game', metavar='GAME', nargs='?', help='The game to run. Format dependent on used bootstrapper.')
arguments = parser.parse_args()
# ... modified code ...
def main():
args = parse_arguments()
from . import bootstrap
bootstrap.bootstrap_engine(args.bootstrapper)
# ... rest of the code ...
|
7be606951b22d77a53274d014cd94aae30af93f5
|
samples/oauth2_for_devices.py
|
samples/oauth2_for_devices.py
|
import httplib2
from six.moves import input
from oauth2client.client import OAuth2WebServerFlow
from googleapiclient.discovery import build
CLIENT_ID = "some+client+id"
CLIENT_SECRET = "some+client+secret"
SCOPES = ("https://www.googleapis.com/auth/youtube",)
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, " ".join(SCOPES))
# Step 1: get user code and verification URL
# https://developers.google.com/accounts/docs/OAuth2ForDevices#obtainingacode
flow_info = flow.step1_get_device_and_user_codes()
print "Enter the following code at %s: %s" % (flow_info.verification_url,
flow_info.user_code)
print "Then press Enter."
input()
# Step 2: get credentials
# https://developers.google.com/accounts/docs/OAuth2ForDevices#obtainingatoken
credentials = flow.step2_exchange(device_flow_info=flow_info)
print "Access token:", credentials.access_token
print "Refresh token:", credentials.refresh_token
# Get YouTube service
# https://developers.google.com/accounts/docs/OAuth2ForDevices#callinganapi
youtube = build("youtube", "v3", http=credentials.authorize(httplib2.Http()))
|
import httplib2
from six.moves import input
from oauth2client.client import OAuth2WebServerFlow
from googleapiclient.discovery import build
CLIENT_ID = "some+client+id"
CLIENT_SECRET = "some+client+secret"
SCOPES = ("https://www.googleapis.com/auth/youtube",)
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, " ".join(SCOPES))
# Step 1: get user code and verification URL
# https://developers.google.com/accounts/docs/OAuth2ForDevices#obtainingacode
flow_info = flow.step1_get_device_and_user_codes()
print("Enter the following code at {0}: {1}".format(flow_info.verification_url,
flow_info.user_code))
print("Then press Enter.")
input()
# Step 2: get credentials
# https://developers.google.com/accounts/docs/OAuth2ForDevices#obtainingatoken
credentials = flow.step2_exchange(device_flow_info=flow_info)
print("Access token: {0}".format(credentials.access_token))
print("Refresh token: {0}".format(credentials.refresh_token))
# Get YouTube service
# https://developers.google.com/accounts/docs/OAuth2ForDevices#callinganapi
youtube = build("youtube", "v3", http=credentials.authorize(httplib2.Http()))
|
Fix example to be Python3 compatible, use format()
|
Fix example to be Python3 compatible, use format()
Both print() and format() are compatible from 2.6. Also, format() is much nicer to use for internationalization since you can define the location of your substitutions. It works similarly to Java and .net's format() as well. Great stuff!
Should I tackle the other examples as well, or is piece meal all right?
|
Python
|
apache-2.0
|
googleapis/oauth2client,jonparrott/oauth2client,google/oauth2client,jonparrott/oauth2client,clancychilds/oauth2client,googleapis/oauth2client,google/oauth2client,clancychilds/oauth2client
|
python
|
## Code Before:
import httplib2
from six.moves import input
from oauth2client.client import OAuth2WebServerFlow
from googleapiclient.discovery import build
CLIENT_ID = "some+client+id"
CLIENT_SECRET = "some+client+secret"
SCOPES = ("https://www.googleapis.com/auth/youtube",)
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, " ".join(SCOPES))
# Step 1: get user code and verification URL
# https://developers.google.com/accounts/docs/OAuth2ForDevices#obtainingacode
flow_info = flow.step1_get_device_and_user_codes()
print "Enter the following code at %s: %s" % (flow_info.verification_url,
flow_info.user_code)
print "Then press Enter."
input()
# Step 2: get credentials
# https://developers.google.com/accounts/docs/OAuth2ForDevices#obtainingatoken
credentials = flow.step2_exchange(device_flow_info=flow_info)
print "Access token:", credentials.access_token
print "Refresh token:", credentials.refresh_token
# Get YouTube service
# https://developers.google.com/accounts/docs/OAuth2ForDevices#callinganapi
youtube = build("youtube", "v3", http=credentials.authorize(httplib2.Http()))
## Instruction:
Fix example to be Python3 compatible, use format()
Both print() and format() are compatible from 2.6. Also, format() is much nicer to use for internationalization since you can define the location of your substitutions. It works similarly to Java and .net's format() as well. Great stuff!
Should I tackle the other examples as well, or is piece meal all right?
## Code After:
import httplib2
from six.moves import input
from oauth2client.client import OAuth2WebServerFlow
from googleapiclient.discovery import build
CLIENT_ID = "some+client+id"
CLIENT_SECRET = "some+client+secret"
SCOPES = ("https://www.googleapis.com/auth/youtube",)
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, " ".join(SCOPES))
# Step 1: get user code and verification URL
# https://developers.google.com/accounts/docs/OAuth2ForDevices#obtainingacode
flow_info = flow.step1_get_device_and_user_codes()
print("Enter the following code at {0}: {1}".format(flow_info.verification_url,
flow_info.user_code))
print("Then press Enter.")
input()
# Step 2: get credentials
# https://developers.google.com/accounts/docs/OAuth2ForDevices#obtainingatoken
credentials = flow.step2_exchange(device_flow_info=flow_info)
print("Access token: {0}".format(credentials.access_token))
print("Refresh token: {0}".format(credentials.refresh_token))
# Get YouTube service
# https://developers.google.com/accounts/docs/OAuth2ForDevices#callinganapi
youtube = build("youtube", "v3", http=credentials.authorize(httplib2.Http()))
|
...
# Step 1: get user code and verification URL
# https://developers.google.com/accounts/docs/OAuth2ForDevices#obtainingacode
flow_info = flow.step1_get_device_and_user_codes()
print("Enter the following code at {0}: {1}".format(flow_info.verification_url,
flow_info.user_code))
print("Then press Enter.")
input()
# Step 2: get credentials
# https://developers.google.com/accounts/docs/OAuth2ForDevices#obtainingatoken
credentials = flow.step2_exchange(device_flow_info=flow_info)
print("Access token: {0}".format(credentials.access_token))
print("Refresh token: {0}".format(credentials.refresh_token))
# Get YouTube service
# https://developers.google.com/accounts/docs/OAuth2ForDevices#callinganapi
...
|
6506ece45d123bcf615a636245bc12498b5348de
|
hsdecomp/ptrutil.py
|
hsdecomp/ptrutil.py
|
import struct
from hsdecomp.types import *
def read_half_word(settings, file_offset):
return struct.unpack(settings.rt.halfword.struct, settings.binary[file_offset:file_offset+settings.rt.halfword.size])[0]
def read_word(settings, file_offset):
return struct.unpack(settings.rt.word.struct, settings.binary[file_offset:file_offset+settings.rt.word.size])[0]
def pointer_offset(settings, pointer, offset):
if isinstance(pointer, Tagged):
offset += pointer.tag
assert isinstance(pointer.untagged, Offset)
return Tagged(untagged = Offset(base = pointer.untagged.base, index = pointer.untagged.index + offset // settings.rt.word.size), tag = offset % settings.rt.word.size)
elif isinstance(pointer, StaticValue):
return StaticValue(value = pointer.value + offset)
elif isinstance(pointer, UnknownValue):
return UnknownValue()
else:
assert False,"bad pointer to offset"
def dereference(settings, parsed, pointer, stack):
if isinstance(pointer, Offset):
if isinstance(pointer.base, HeapPointer):
return parsed['heaps'][pointer.base.heap_segment][pointer.index]
elif isinstance(pointer.base, StackPointer):
return stack[pointer.index]
elif isinstance(pointer, StaticValue):
assert pointer.value % settings.rt.word.size == 0
return Tagged(StaticValue(value = read_word(settings, settings.data_offset + pointer.value)), tag = 0)
|
import struct
from hsdecomp.types import *
def read_half_word(settings, file_offset):
return struct.unpack(settings.rt.halfword.struct, settings.binary[file_offset:file_offset+settings.rt.halfword.size])[0]
def read_word(settings, file_offset):
return struct.unpack(settings.rt.word.struct, settings.binary[file_offset:file_offset+settings.rt.word.size])[0]
def pointer_offset(settings, pointer, offset):
if isinstance(pointer, Tagged):
offset += pointer.tag
assert isinstance(pointer.untagged, Offset)
return Tagged(untagged = Offset(base = pointer.untagged.base, index = pointer.untagged.index + offset // settings.rt.word.size), tag = offset % settings.rt.word.size)
elif isinstance(pointer, UnknownValue):
return UnknownValue()
else:
assert False,"bad pointer to offset"
def dereference(settings, parsed, pointer, stack):
if isinstance(pointer, Offset):
if isinstance(pointer.base, HeapPointer):
return parsed['heaps'][pointer.base.heap_segment][pointer.index]
elif isinstance(pointer.base, StackPointer):
return stack[pointer.index]
elif isinstance(pointer, StaticValue):
assert pointer.value % settings.rt.word.size == 0
return Tagged(StaticValue(value = read_word(settings, settings.data_offset + pointer.value)), tag = 0)
|
Kill obsolete case in pointer_offset
|
Kill obsolete case in pointer_offset
|
Python
|
mit
|
gereeter/hsdecomp
|
python
|
## Code Before:
import struct
from hsdecomp.types import *
def read_half_word(settings, file_offset):
return struct.unpack(settings.rt.halfword.struct, settings.binary[file_offset:file_offset+settings.rt.halfword.size])[0]
def read_word(settings, file_offset):
return struct.unpack(settings.rt.word.struct, settings.binary[file_offset:file_offset+settings.rt.word.size])[0]
def pointer_offset(settings, pointer, offset):
if isinstance(pointer, Tagged):
offset += pointer.tag
assert isinstance(pointer.untagged, Offset)
return Tagged(untagged = Offset(base = pointer.untagged.base, index = pointer.untagged.index + offset // settings.rt.word.size), tag = offset % settings.rt.word.size)
elif isinstance(pointer, StaticValue):
return StaticValue(value = pointer.value + offset)
elif isinstance(pointer, UnknownValue):
return UnknownValue()
else:
assert False,"bad pointer to offset"
def dereference(settings, parsed, pointer, stack):
if isinstance(pointer, Offset):
if isinstance(pointer.base, HeapPointer):
return parsed['heaps'][pointer.base.heap_segment][pointer.index]
elif isinstance(pointer.base, StackPointer):
return stack[pointer.index]
elif isinstance(pointer, StaticValue):
assert pointer.value % settings.rt.word.size == 0
return Tagged(StaticValue(value = read_word(settings, settings.data_offset + pointer.value)), tag = 0)
## Instruction:
Kill obsolete case in pointer_offset
## Code After:
import struct
from hsdecomp.types import *
def read_half_word(settings, file_offset):
return struct.unpack(settings.rt.halfword.struct, settings.binary[file_offset:file_offset+settings.rt.halfword.size])[0]
def read_word(settings, file_offset):
return struct.unpack(settings.rt.word.struct, settings.binary[file_offset:file_offset+settings.rt.word.size])[0]
def pointer_offset(settings, pointer, offset):
if isinstance(pointer, Tagged):
offset += pointer.tag
assert isinstance(pointer.untagged, Offset)
return Tagged(untagged = Offset(base = pointer.untagged.base, index = pointer.untagged.index + offset // settings.rt.word.size), tag = offset % settings.rt.word.size)
elif isinstance(pointer, UnknownValue):
return UnknownValue()
else:
assert False,"bad pointer to offset"
def dereference(settings, parsed, pointer, stack):
if isinstance(pointer, Offset):
if isinstance(pointer.base, HeapPointer):
return parsed['heaps'][pointer.base.heap_segment][pointer.index]
elif isinstance(pointer.base, StackPointer):
return stack[pointer.index]
elif isinstance(pointer, StaticValue):
assert pointer.value % settings.rt.word.size == 0
return Tagged(StaticValue(value = read_word(settings, settings.data_offset + pointer.value)), tag = 0)
|
// ... existing code ...
offset += pointer.tag
assert isinstance(pointer.untagged, Offset)
return Tagged(untagged = Offset(base = pointer.untagged.base, index = pointer.untagged.index + offset // settings.rt.word.size), tag = offset % settings.rt.word.size)
elif isinstance(pointer, UnknownValue):
return UnknownValue()
else:
// ... rest of the code ...
|
bf7f726821f2ac74e99fd5fd06729ea2becab0c9
|
ModuleInterface.py
|
ModuleInterface.py
|
import GlobalVars
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
def __init__(self):
self.onStart()
def onStart(self):
pass
def hasAlias(self, message):
if message.Type in self.acceptedTypes and message.Command in GlobalVars.commandAliases.keys():
return True
def shouldTrigger(self, message):
if message.Type not in self.acceptedTypes:
return False
if message.Command not in self.triggers:
return False
return True
def onTrigger(self, Hubbot, message):
pass
|
import GlobalVars
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
def __init__(self):
self.onStart()
def onStart(self):
pass
def hasAlias(self, message):
if message.Type in self.acceptedTypes and message.Command in GlobalVars.commandAliases.keys():
return True
else:
return False
def shouldTrigger(self, message):
if message.Type not in self.acceptedTypes:
return False
if message.Command not in self.triggers:
return False
return True
def onTrigger(self, Hubbot, message):
pass
|
Return false if no alias.
|
[ModuleInteface] Return false if no alias.
|
Python
|
mit
|
HubbeKing/Hubbot_Twisted
|
python
|
## Code Before:
import GlobalVars
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
def __init__(self):
self.onStart()
def onStart(self):
pass
def hasAlias(self, message):
if message.Type in self.acceptedTypes and message.Command in GlobalVars.commandAliases.keys():
return True
def shouldTrigger(self, message):
if message.Type not in self.acceptedTypes:
return False
if message.Command not in self.triggers:
return False
return True
def onTrigger(self, Hubbot, message):
pass
## Instruction:
[ModuleInteface] Return false if no alias.
## Code After:
import GlobalVars
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
def __init__(self):
self.onStart()
def onStart(self):
pass
def hasAlias(self, message):
if message.Type in self.acceptedTypes and message.Command in GlobalVars.commandAliases.keys():
return True
else:
return False
def shouldTrigger(self, message):
if message.Type not in self.acceptedTypes:
return False
if message.Command not in self.triggers:
return False
return True
def onTrigger(self, Hubbot, message):
pass
|
# ... existing code ...
def hasAlias(self, message):
if message.Type in self.acceptedTypes and message.Command in GlobalVars.commandAliases.keys():
return True
else:
return False
def shouldTrigger(self, message):
if message.Type not in self.acceptedTypes:
# ... rest of the code ...
|
269b3951049255fd3b459ce254afe3b8d6ffea1b
|
setup.py
|
setup.py
|
"""Setup for drewtils project."""
import os
try:
from setuptools import setup
setupTools = True
except ImportError:
from distutils.core import setup
setupTools = False
_classifiers = [
'License :: OSI Approved :: MIT License',
]
if os.path.exists('README.rst'):
with open('README.rst') as readme:
long_description = readme.read()
else:
long_description = ''
setupArgs = {
'name': 'drewtils',
'version': "0.1.9",
'packages': ['drewtils'],
'author': 'Andrew Johnson',
'author_email': '[email protected]',
'description': 'Simple tools to make testing and file parsing easier',
'long_description': long_description,
'license': 'MIT',
'keywords': 'parsing files',
'url': 'https://github.com/drewejohnson/drewtils',
'classifiers': _classifiers,
}
if setupTools:
setupArgs.update(**{
'test_suite': 'drewtils.tests',
'python_requires': '>=2.7,!=3.1,!=3.2,!=3.3,!=3.4'
})
setup(**setupArgs)
|
"""Setup for drewtils project."""
try:
from setuptools import setup
setupTools = True
except ImportError:
from distutils.core import setup
setupTools = False
_classifiers = [
'License :: OSI Approved :: MIT License',
]
with open('README.rst') as readme:
long_description = readme.read()
setupArgs = {
'name': 'drewtils',
'version': "0.1.9",
'packages': ['drewtils'],
'author': 'Andrew Johnson',
'author_email': '[email protected]',
'description': 'Simple tools to make testing and file parsing easier',
'long_description': long_description,
'license': 'MIT',
'keywords': 'parsing files',
'url': 'https://github.com/drewejohnson/drewtils',
'classifiers': _classifiers,
}
if setupTools:
setupArgs.update(**{
'test_suite': 'drewtils.tests',
'python_requires': '>=2.7,!=3.1,!=3.2,!=3.3,!=3.4'
})
setup(**setupArgs)
|
Read long description from readme always
|
Read long description from readme always
|
Python
|
mit
|
drewejohnson/drewtils
|
python
|
## Code Before:
"""Setup for drewtils project."""
import os
try:
from setuptools import setup
setupTools = True
except ImportError:
from distutils.core import setup
setupTools = False
_classifiers = [
'License :: OSI Approved :: MIT License',
]
if os.path.exists('README.rst'):
with open('README.rst') as readme:
long_description = readme.read()
else:
long_description = ''
setupArgs = {
'name': 'drewtils',
'version': "0.1.9",
'packages': ['drewtils'],
'author': 'Andrew Johnson',
'author_email': '[email protected]',
'description': 'Simple tools to make testing and file parsing easier',
'long_description': long_description,
'license': 'MIT',
'keywords': 'parsing files',
'url': 'https://github.com/drewejohnson/drewtils',
'classifiers': _classifiers,
}
if setupTools:
setupArgs.update(**{
'test_suite': 'drewtils.tests',
'python_requires': '>=2.7,!=3.1,!=3.2,!=3.3,!=3.4'
})
setup(**setupArgs)
## Instruction:
Read long description from readme always
## Code After:
"""Setup for drewtils project."""
try:
from setuptools import setup
setupTools = True
except ImportError:
from distutils.core import setup
setupTools = False
_classifiers = [
'License :: OSI Approved :: MIT License',
]
with open('README.rst') as readme:
long_description = readme.read()
setupArgs = {
'name': 'drewtils',
'version': "0.1.9",
'packages': ['drewtils'],
'author': 'Andrew Johnson',
'author_email': '[email protected]',
'description': 'Simple tools to make testing and file parsing easier',
'long_description': long_description,
'license': 'MIT',
'keywords': 'parsing files',
'url': 'https://github.com/drewejohnson/drewtils',
'classifiers': _classifiers,
}
if setupTools:
setupArgs.update(**{
'test_suite': 'drewtils.tests',
'python_requires': '>=2.7,!=3.1,!=3.2,!=3.3,!=3.4'
})
setup(**setupArgs)
|
...
"""Setup for drewtils project."""
try:
from setuptools import setup
...
'License :: OSI Approved :: MIT License',
]
with open('README.rst') as readme:
long_description = readme.read()
setupArgs = {
'name': 'drewtils',
...
|
53764e4ce0f82dc0706a9fd64877ccda5e97c32f
|
compd-score-match.py
|
compd-score-match.py
|
import os
import sys
import yaml
import score
def usage():
print "Usage: score-match.py MATCH_NUMBER"
print " Scores the match file at matches/MATCH_NUMBER.yaml"
print " Outputs scoring format suitable for piping at compd"
if len(sys.argv) is not 2:
usage()
exit(1)
match_num = sys.argv[1]
match_file = "matches/{0}.yaml".format(match_num)
if not os.path.exists(match_file):
print "Match file '{0}' doesn't exist. Have you created it?".format(match_file)
usage()
exit(2)
scores = yaml.load(open(match_file).read())
scorer = score.StrangeGameScorer(scores)
scorer.compute_cell_winners()
for tla in scores.keys():
this_score = scorer.compute_game_score(tla)
print 'set-score {0} {1} {2}'.format(match_num, tla, this_score)
print 'calc-league-points {0}'.format(match_num)
|
import os
import sys
import yaml
import score
MATCH_ID = 'match-{0}'
def usage():
print "Usage: score-match.py MATCH_NUMBER"
print " Scores the match file at matches/MATCH_NUMBER.yaml"
print " Outputs scoring format suitable for piping at compd"
if len(sys.argv) is not 2:
usage()
exit(1)
match_num = sys.argv[1]
match_file = "matches/{0}.yaml".format(match_num)
if not os.path.exists(match_file):
print "Match file '{0}' doesn't exist. Have you created it?".format(match_file)
usage()
exit(2)
scores = yaml.load(open(match_file).read())
scorer = score.StrangeGameScorer(scores)
scorer.compute_cell_winners()
match_id = MATCH_ID.format(match_num)
for tla in scores.keys():
this_score = scorer.compute_game_score(tla)
print 'set-score {0} {1} {2}'.format(match_id, tla, this_score)
print 'calc-league-points {0}'.format(match_id)
|
Update match-id to equal that used in compd.
|
Update match-id to equal that used in compd.
|
Python
|
mit
|
samphippen/scoring_2013,samphippen/scoring_2013
|
python
|
## Code Before:
import os
import sys
import yaml
import score
def usage():
print "Usage: score-match.py MATCH_NUMBER"
print " Scores the match file at matches/MATCH_NUMBER.yaml"
print " Outputs scoring format suitable for piping at compd"
if len(sys.argv) is not 2:
usage()
exit(1)
match_num = sys.argv[1]
match_file = "matches/{0}.yaml".format(match_num)
if not os.path.exists(match_file):
print "Match file '{0}' doesn't exist. Have you created it?".format(match_file)
usage()
exit(2)
scores = yaml.load(open(match_file).read())
scorer = score.StrangeGameScorer(scores)
scorer.compute_cell_winners()
for tla in scores.keys():
this_score = scorer.compute_game_score(tla)
print 'set-score {0} {1} {2}'.format(match_num, tla, this_score)
print 'calc-league-points {0}'.format(match_num)
## Instruction:
Update match-id to equal that used in compd.
## Code After:
import os
import sys
import yaml
import score
MATCH_ID = 'match-{0}'
def usage():
print "Usage: score-match.py MATCH_NUMBER"
print " Scores the match file at matches/MATCH_NUMBER.yaml"
print " Outputs scoring format suitable for piping at compd"
if len(sys.argv) is not 2:
usage()
exit(1)
match_num = sys.argv[1]
match_file = "matches/{0}.yaml".format(match_num)
if not os.path.exists(match_file):
print "Match file '{0}' doesn't exist. Have you created it?".format(match_file)
usage()
exit(2)
scores = yaml.load(open(match_file).read())
scorer = score.StrangeGameScorer(scores)
scorer.compute_cell_winners()
match_id = MATCH_ID.format(match_num)
for tla in scores.keys():
this_score = scorer.compute_game_score(tla)
print 'set-score {0} {1} {2}'.format(match_id, tla, this_score)
print 'calc-league-points {0}'.format(match_id)
|
...
import yaml
import score
MATCH_ID = 'match-{0}'
def usage():
print "Usage: score-match.py MATCH_NUMBER"
...
scorer = score.StrangeGameScorer(scores)
scorer.compute_cell_winners()
match_id = MATCH_ID.format(match_num)
for tla in scores.keys():
this_score = scorer.compute_game_score(tla)
print 'set-score {0} {1} {2}'.format(match_id, tla, this_score)
print 'calc-league-points {0}'.format(match_id)
...
|
3d48f181f90995bd66dc436acccde9d18c5cfa3c
|
tests/settings.py
|
tests/settings.py
|
import django
DATABASE_ENGINE = 'sqlite3'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = [
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',
'django.contrib.comments',
'avatar',
]
ROOT_URLCONF = 'tests.urls'
SITE_ID = 1
SECRET_KEY = 'something-something'
if django.VERSION[:2] < (1, 6):
TEST_RUNNER = 'discover_runner.DiscoverRunner'
ROOT_URLCONF = 'tests.urls'
STATIC_URL = '/site_media/static/'
AVATAR_ALLOWED_FILE_EXTS = ('.jpg', '.png')
AVATAR_MAX_SIZE = 1024 * 1024
AVATAR_MAX_AVATARS_PER_USER = 20
|
import django
DATABASE_ENGINE = 'sqlite3'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = [
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',
'avatar',
]
MIDDLEWARE_CLASSES = (
"django.middleware.common.BrokenLinkEmailsMiddleware",
"django.middleware.common.CommonMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
)
ROOT_URLCONF = 'tests.urls'
SITE_ID = 1
SECRET_KEY = 'something-something'
if django.VERSION[:2] < (1, 6):
TEST_RUNNER = 'discover_runner.DiscoverRunner'
ROOT_URLCONF = 'tests.urls'
STATIC_URL = '/site_media/static/'
AVATAR_ALLOWED_FILE_EXTS = ('.jpg', '.png')
AVATAR_MAX_SIZE = 1024 * 1024
AVATAR_MAX_AVATARS_PER_USER = 20
|
Remove django.contrib.comments and add MIDDLEWARE_CLASSES
|
Remove django.contrib.comments and add MIDDLEWARE_CLASSES
|
Python
|
bsd-3-clause
|
imgmix/django-avatar,barbuza/django-avatar,grantmcconnaughey/django-avatar,ad-m/django-avatar,jezdez/django-avatar,MachineandMagic/django-avatar,barbuza/django-avatar,ad-m/django-avatar,grantmcconnaughey/django-avatar,dannybrowne86/django-avatar,dannybrowne86/django-avatar,therocode/django-avatar,therocode/django-avatar,MachineandMagic/django-avatar,imgmix/django-avatar,brajeshvit/avatarmodule,brajeshvit/avatarmodule,jezdez/django-avatar
|
python
|
## Code Before:
import django
DATABASE_ENGINE = 'sqlite3'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = [
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',
'django.contrib.comments',
'avatar',
]
ROOT_URLCONF = 'tests.urls'
SITE_ID = 1
SECRET_KEY = 'something-something'
if django.VERSION[:2] < (1, 6):
TEST_RUNNER = 'discover_runner.DiscoverRunner'
ROOT_URLCONF = 'tests.urls'
STATIC_URL = '/site_media/static/'
AVATAR_ALLOWED_FILE_EXTS = ('.jpg', '.png')
AVATAR_MAX_SIZE = 1024 * 1024
AVATAR_MAX_AVATARS_PER_USER = 20
## Instruction:
Remove django.contrib.comments and add MIDDLEWARE_CLASSES
## Code After:
import django
DATABASE_ENGINE = 'sqlite3'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = [
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',
'avatar',
]
MIDDLEWARE_CLASSES = (
"django.middleware.common.BrokenLinkEmailsMiddleware",
"django.middleware.common.CommonMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
)
ROOT_URLCONF = 'tests.urls'
SITE_ID = 1
SECRET_KEY = 'something-something'
if django.VERSION[:2] < (1, 6):
TEST_RUNNER = 'discover_runner.DiscoverRunner'
ROOT_URLCONF = 'tests.urls'
STATIC_URL = '/site_media/static/'
AVATAR_ALLOWED_FILE_EXTS = ('.jpg', '.png')
AVATAR_MAX_SIZE = 1024 * 1024
AVATAR_MAX_AVATARS_PER_USER = 20
|
# ... existing code ...
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',
'avatar',
]
MIDDLEWARE_CLASSES = (
"django.middleware.common.BrokenLinkEmailsMiddleware",
"django.middleware.common.CommonMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
)
ROOT_URLCONF = 'tests.urls'
# ... rest of the code ...
|
42d51980ef24c2e9b93fcfd2d3aa8c0e50dc27a7
|
CefSharp.Core/RequestContext.h
|
CefSharp.Core/RequestContext.h
|
// Copyright 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#pragma once
#include "Stdafx.h"
#include "Internals\MCefRefPtr.h"
#include "RequestContextSettings.h"
#include "include\cef_request_context.h"
using namespace CefSharp;
namespace CefSharp
{
public ref class RequestContext
{
private:
MCefRefPtr<CefRequestContext> _requestContext;
RequestContextSettings^ _settings;
public:
RequestContext()
{
CefRequestContextSettings settings;
_requestContext = CefRequestContext::CreateContext(settings, NULL);
}
RequestContext(RequestContextSettings^ settings) : _settings(settings)
{
_requestContext = CefRequestContext::CreateContext(settings, NULL);
}
!RequestContext()
{
_requestContext = NULL;
}
~RequestContext()
{
this->!RequestContext();
delete _settings;
}
operator CefRefPtr<CefRequestContext>()
{
return _requestContext.get();
}
};
}
|
// Copyright 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#pragma once
#include "Stdafx.h"
#include "Internals\MCefRefPtr.h"
#include "RequestContextSettings.h"
#include "include\cef_request_context.h"
using namespace CefSharp;
namespace CefSharp
{
public ref class RequestContext
{
private:
MCefRefPtr<CefRequestContext> _requestContext;
RequestContextSettings^ _settings;
public:
RequestContext()
{
CefRequestContextSettings settings;
_requestContext = CefRequestContext::CreateContext(settings, NULL);
}
RequestContext(RequestContextSettings^ settings) : _settings(settings)
{
_requestContext = CefRequestContext::CreateContext(settings, NULL);
}
!RequestContext()
{
_requestContext = NULL;
}
~RequestContext()
{
this->!RequestContext();
delete _settings;
}
operator CefRefPtr<CefRequestContext>()
{
if(this == nullptr)
{
return NULL;
}
return _requestContext.get();
}
};
}
|
Add nullptr check and return NULL for implicitor operator when object is not initialized
|
Add nullptr check and return NULL for implicitor operator when object is not initialized
|
C
|
bsd-3-clause
|
jamespearce2006/CefSharp,dga711/CefSharp,twxstar/CefSharp,battewr/CefSharp,windygu/CefSharp,Haraguroicha/CefSharp,yoder/CefSharp,gregmartinhtc/CefSharp,rlmcneary2/CefSharp,Livit/CefSharp,windygu/CefSharp,joshvera/CefSharp,yoder/CefSharp,jamespearce2006/CefSharp,AJDev77/CefSharp,ITGlobal/CefSharp,ITGlobal/CefSharp,VioletLife/CefSharp,battewr/CefSharp,NumbersInternational/CefSharp,Haraguroicha/CefSharp,haozhouxu/CefSharp,NumbersInternational/CefSharp,AJDev77/CefSharp,windygu/CefSharp,illfang/CefSharp,dga711/CefSharp,dga711/CefSharp,wangzheng888520/CefSharp,twxstar/CefSharp,illfang/CefSharp,rlmcneary2/CefSharp,gregmartinhtc/CefSharp,yoder/CefSharp,VioletLife/CefSharp,rlmcneary2/CefSharp,ruisebastiao/CefSharp,haozhouxu/CefSharp,Livit/CefSharp,rlmcneary2/CefSharp,gregmartinhtc/CefSharp,twxstar/CefSharp,zhangjingpu/CefSharp,jamespearce2006/CefSharp,wangzheng888520/CefSharp,illfang/CefSharp,haozhouxu/CefSharp,battewr/CefSharp,wangzheng888520/CefSharp,twxstar/CefSharp,jamespearce2006/CefSharp,ITGlobal/CefSharp,haozhouxu/CefSharp,windygu/CefSharp,AJDev77/CefSharp,Livit/CefSharp,ruisebastiao/CefSharp,dga711/CefSharp,AJDev77/CefSharp,Haraguroicha/CefSharp,battewr/CefSharp,zhangjingpu/CefSharp,ruisebastiao/CefSharp,joshvera/CefSharp,jamespearce2006/CefSharp,ruisebastiao/CefSharp,NumbersInternational/CefSharp,illfang/CefSharp,Haraguroicha/CefSharp,zhangjingpu/CefSharp,Haraguroicha/CefSharp,VioletLife/CefSharp,joshvera/CefSharp,ITGlobal/CefSharp,NumbersInternational/CefSharp,joshvera/CefSharp,gregmartinhtc/CefSharp,Livit/CefSharp,wangzheng888520/CefSharp,VioletLife/CefSharp,zhangjingpu/CefSharp,yoder/CefSharp
|
c
|
## Code Before:
// Copyright 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#pragma once
#include "Stdafx.h"
#include "Internals\MCefRefPtr.h"
#include "RequestContextSettings.h"
#include "include\cef_request_context.h"
using namespace CefSharp;
namespace CefSharp
{
public ref class RequestContext
{
private:
MCefRefPtr<CefRequestContext> _requestContext;
RequestContextSettings^ _settings;
public:
RequestContext()
{
CefRequestContextSettings settings;
_requestContext = CefRequestContext::CreateContext(settings, NULL);
}
RequestContext(RequestContextSettings^ settings) : _settings(settings)
{
_requestContext = CefRequestContext::CreateContext(settings, NULL);
}
!RequestContext()
{
_requestContext = NULL;
}
~RequestContext()
{
this->!RequestContext();
delete _settings;
}
operator CefRefPtr<CefRequestContext>()
{
return _requestContext.get();
}
};
}
## Instruction:
Add nullptr check and return NULL for implicitor operator when object is not initialized
## Code After:
// Copyright 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#pragma once
#include "Stdafx.h"
#include "Internals\MCefRefPtr.h"
#include "RequestContextSettings.h"
#include "include\cef_request_context.h"
using namespace CefSharp;
namespace CefSharp
{
public ref class RequestContext
{
private:
MCefRefPtr<CefRequestContext> _requestContext;
RequestContextSettings^ _settings;
public:
RequestContext()
{
CefRequestContextSettings settings;
_requestContext = CefRequestContext::CreateContext(settings, NULL);
}
RequestContext(RequestContextSettings^ settings) : _settings(settings)
{
_requestContext = CefRequestContext::CreateContext(settings, NULL);
}
!RequestContext()
{
_requestContext = NULL;
}
~RequestContext()
{
this->!RequestContext();
delete _settings;
}
operator CefRefPtr<CefRequestContext>()
{
if(this == nullptr)
{
return NULL;
}
return _requestContext.get();
}
};
}
|
// ... existing code ...
operator CefRefPtr<CefRequestContext>()
{
if(this == nullptr)
{
return NULL;
}
return _requestContext.get();
}
};
// ... rest of the code ...
|
785639006cc1fb5168d40c2ae7906b086b2f93b6
|
Drinks/src/main/java/fr/masciulli/drinks/model/Drink.java
|
Drinks/src/main/java/fr/masciulli/drinks/model/Drink.java
|
package fr.masciulli.drinks.model;
public class Drink {
private String mName;
private String mImageURL;
public Drink(String name, String imageURL) {
mName = name;
mImageURL = imageURL;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getImageURL() {
return mImageURL;
}
public void setImageURL(String imageURL) {
mImageURL = imageURL;
}
}
|
package fr.masciulli.drinks.model;
import java.util.LinkedList;
import java.util.List;
public class Drink {
private String mName;
private String mImageURL;
private String mHistory;
private List<String> mIngredients = new LinkedList<String>();
private List<String> mInstructions = new LinkedList<String>();
public Drink(String name, String imageURL) {
mName = name;
mImageURL = imageURL;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getImageURL() {
return mImageURL;
}
public void setImageURL(String imageURL) {
mImageURL = imageURL;
}
public String getHistory() {
return mHistory;
}
public void setHistory(String history) {
mHistory = history;
}
public void addIngredient(String ingredient) {
mIngredients.add(ingredient);
}
public List<String> getIngredients() {
return mIngredients;
}
public void addIntruction(String instruction) {
mInstructions.add(instruction);
}
public List<String> getInstructions() {
return mInstructions;
}
}
|
Improve drink model with ingredients, instructions and history
|
Improve drink model with ingredients, instructions and history
|
Java
|
apache-2.0
|
amasciul/Drinks,vbarthel-fr/Drinks,vbarthel-fr/Drinks,amasciul/Drinks,amasciul/Drinks,mechdome/Drinks,mechdome/Drinks
|
java
|
## Code Before:
package fr.masciulli.drinks.model;
public class Drink {
private String mName;
private String mImageURL;
public Drink(String name, String imageURL) {
mName = name;
mImageURL = imageURL;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getImageURL() {
return mImageURL;
}
public void setImageURL(String imageURL) {
mImageURL = imageURL;
}
}
## Instruction:
Improve drink model with ingredients, instructions and history
## Code After:
package fr.masciulli.drinks.model;
import java.util.LinkedList;
import java.util.List;
public class Drink {
private String mName;
private String mImageURL;
private String mHistory;
private List<String> mIngredients = new LinkedList<String>();
private List<String> mInstructions = new LinkedList<String>();
public Drink(String name, String imageURL) {
mName = name;
mImageURL = imageURL;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getImageURL() {
return mImageURL;
}
public void setImageURL(String imageURL) {
mImageURL = imageURL;
}
public String getHistory() {
return mHistory;
}
public void setHistory(String history) {
mHistory = history;
}
public void addIngredient(String ingredient) {
mIngredients.add(ingredient);
}
public List<String> getIngredients() {
return mIngredients;
}
public void addIntruction(String instruction) {
mInstructions.add(instruction);
}
public List<String> getInstructions() {
return mInstructions;
}
}
|
// ... existing code ...
package fr.masciulli.drinks.model;
import java.util.LinkedList;
import java.util.List;
public class Drink {
private String mName;
private String mImageURL;
private String mHistory;
private List<String> mIngredients = new LinkedList<String>();
private List<String> mInstructions = new LinkedList<String>();
public Drink(String name, String imageURL) {
mName = name;
// ... modified code ...
public void setImageURL(String imageURL) {
mImageURL = imageURL;
}
public String getHistory() {
return mHistory;
}
public void setHistory(String history) {
mHistory = history;
}
public void addIngredient(String ingredient) {
mIngredients.add(ingredient);
}
public List<String> getIngredients() {
return mIngredients;
}
public void addIntruction(String instruction) {
mInstructions.add(instruction);
}
public List<String> getInstructions() {
return mInstructions;
}
}
// ... rest of the code ...
|
049a01d148c757a17e9804a2b1e42c918e29b094
|
tests/basics/for_break.py
|
tests/basics/for_break.py
|
def foo():
seq = [1, 2, 3]
v = 100
i = 5
while i > 0:
print(i)
for a in seq:
if a == 2:
break
i -= 1
foo()
|
def foo():
seq = [1, 2, 3]
v = 100
i = 5
while i > 0:
print(i)
for a in seq:
if a == 2:
break
i -= 1
foo()
# break from within nested for loop
def bar():
l = [1, 2, 3]
for e1 in l:
print(e1)
for e2 in l:
print(e1, e2)
if e2 == 2:
break
bar()
|
Add another test for break-from-for-loop.
|
tests: Add another test for break-from-for-loop.
|
Python
|
mit
|
neilh10/micropython,galenhz/micropython,heisewangluo/micropython,heisewangluo/micropython,ruffy91/micropython,mgyenik/micropython,ericsnowcurrently/micropython,cnoviello/micropython,lbattraw/micropython,lbattraw/micropython,hosaka/micropython,EcmaXp/micropython,alex-march/micropython,Timmenem/micropython,cwyark/micropython,xhat/micropython,blazewicz/micropython,jlillest/micropython,jlillest/micropython,hosaka/micropython,tralamazza/micropython,MrSurly/micropython,ryannathans/micropython,feilongfl/micropython,PappaPeppar/micropython,orionrobots/micropython,pozetroninc/micropython,dhylands/micropython,MrSurly/micropython-esp32,adafruit/circuitpython,stonegithubs/micropython,slzatz/micropython,oopy/micropython,alex-robbins/micropython,martinribelotta/micropython,paul-xxx/micropython,firstval/micropython,kerneltask/micropython,utopiaprince/micropython,dinau/micropython,aethaniel/micropython,deshipu/micropython,dinau/micropython,tdautc19841202/micropython,tdautc19841202/micropython,puuu/micropython,orionrobots/micropython,pfalcon/micropython,AriZuu/micropython,galenhz/micropython,alex-march/micropython,bvernoux/micropython,bvernoux/micropython,infinnovation/micropython,feilongfl/micropython,xuxiaoxin/micropython,TDAbboud/micropython,praemdonck/micropython,micropython/micropython-esp32,matthewelse/micropython,hiway/micropython,vriera/micropython,pfalcon/micropython,vriera/micropython,deshipu/micropython,stonegithubs/micropython,suda/micropython,EcmaXp/micropython,jimkmc/micropython,redbear/micropython,tuc-osg/micropython,turbinenreiter/micropython,firstval/micropython,neilh10/micropython,mpalomer/micropython,ericsnowcurrently/micropython,mgyenik/micropython,skybird6672/micropython,lowRISC/micropython,redbear/micropython,chrisdearman/micropython,martinribelotta/micropython,KISSMonX/micropython,praemdonck/micropython,cnoviello/micropython,adafruit/circuitpython,mpalomer/micropython,chrisdearman/micropython,adafruit/micropython,selste/micropython,jmarcelino/pycom-micropython,dmazzella/micropython,martinribelotta/micropython,ryannathans/micropython,xhat/micropython,xuxiaoxin/micropython,MrSurly/micropython,deshipu/micropython,noahchense/micropython,TDAbboud/micropython,MrSurly/micropython-esp32,selste/micropython,pozetroninc/micropython,rubencabrera/micropython,utopiaprince/micropython,dxxb/micropython,jimkmc/micropython,neilh10/micropython,vitiral/micropython,paul-xxx/micropython,ericsnowcurrently/micropython,selste/micropython,suda/micropython,tobbad/micropython,jimkmc/micropython,MrSurly/micropython,adamkh/micropython,trezor/micropython,AriZuu/micropython,tralamazza/micropython,feilongfl/micropython,ruffy91/micropython,ahotam/micropython,KISSMonX/micropython,stonegithubs/micropython,xuxiaoxin/micropython,kostyll/micropython,jimkmc/micropython,cnoviello/micropython,dxxb/micropython,misterdanb/micropython,omtinez/micropython,HenrikSolver/micropython,supergis/micropython,jlillest/micropython,xyb/micropython,swegener/micropython,tobbad/micropython,SHA2017-badge/micropython-esp32,dhylands/micropython,ceramos/micropython,kerneltask/micropython,torwag/micropython,TDAbboud/micropython,oopy/micropython,stonegithubs/micropython,bvernoux/micropython,cloudformdesign/micropython,Vogtinator/micropython,tobbad/micropython,swegener/micropython,turbinenreiter/micropython,bvernoux/micropython,ericsnowcurrently/micropython,tralamazza/micropython,danicampora/micropython,ChuckM/micropython,kerneltask/micropython,mhoffma/micropython,utopiaprince/micropython,dxxb/micropython,hosaka/micropython,pramasoul/micropython,adafruit/micropython,noahwilliamsson/micropython,cwyark/micropython,xhat/micropython,ernesto-g/micropython,oopy/micropython,adamkh/micropython,mpalomer/micropython,Peetz0r/micropython-esp32,hiway/micropython,mgyenik/micropython,SHA2017-badge/micropython-esp32,mpalomer/micropython,skybird6672/micropython,jimkmc/micropython,dhylands/micropython,KISSMonX/micropython,xyb/micropython,ganshun666/micropython,mgyenik/micropython,bvernoux/micropython,pozetroninc/micropython,blmorris/micropython,matthewelse/micropython,henriknelson/micropython,tuc-osg/micropython,alex-march/micropython,utopiaprince/micropython,mianos/micropython,MrSurly/micropython,orionrobots/micropython,TDAbboud/micropython,tobbad/micropython,ryannathans/micropython,noahwilliamsson/micropython,tralamazza/micropython,tdautc19841202/micropython,jlillest/micropython,mianos/micropython,torwag/micropython,alex-march/micropython,redbear/micropython,omtinez/micropython,ganshun666/micropython,ahotam/micropython,turbinenreiter/micropython,infinnovation/micropython,matthewelse/micropython,firstval/micropython,MrSurly/micropython-esp32,tobbad/micropython,methoxid/micropystat,EcmaXp/micropython,matthewelse/micropython,ernesto-g/micropython,neilh10/micropython,adafruit/circuitpython,pfalcon/micropython,utopiaprince/micropython,torwag/micropython,emfcamp/micropython,ruffy91/micropython,lowRISC/micropython,noahchense/micropython,ahotam/micropython,selste/micropython,hiway/micropython,hiway/micropython,EcmaXp/micropython,firstval/micropython,oopy/micropython,rubencabrera/micropython,pramasoul/micropython,ceramos/micropython,firstval/micropython,slzatz/micropython,xyb/micropython,mgyenik/micropython,drrk/micropython,dinau/micropython,supergis/micropython,suda/micropython,kostyll/micropython,adafruit/circuitpython,rubencabrera/micropython,stonegithubs/micropython,hiway/micropython,Timmenem/micropython,Vogtinator/micropython,Peetz0r/micropython-esp32,SungEun-Steve-Kim/test-mp,tuc-osg/micropython,skybird6672/micropython,supergis/micropython,tdautc19841202/micropython,hosaka/micropython,adamkh/micropython,swegener/micropython,ceramos/micropython,dmazzella/micropython,danicampora/micropython,tuc-osg/micropython,tuc-osg/micropython,tdautc19841202/micropython,jmarcelino/pycom-micropython,PappaPeppar/micropython,lbattraw/micropython,ernesto-g/micropython,pramasoul/micropython,skybird6672/micropython,dhylands/micropython,Peetz0r/micropython-esp32,heisewangluo/micropython,TDAbboud/micropython,dxxb/micropython,ruffy91/micropython,noahwilliamsson/micropython,selste/micropython,swegener/micropython,galenhz/micropython,supergis/micropython,turbinenreiter/micropython,ceramos/micropython,danicampora/micropython,neilh10/micropython,paul-xxx/micropython,toolmacher/micropython,SHA2017-badge/micropython-esp32,noahchense/micropython,slzatz/micropython,omtinez/micropython,dmazzella/micropython,chrisdearman/micropython,deshipu/micropython,pfalcon/micropython,cloudformdesign/micropython,feilongfl/micropython,aethaniel/micropython,cwyark/micropython,cloudformdesign/micropython,adafruit/micropython,misterdanb/micropython,blazewicz/micropython,misterdanb/micropython,cnoviello/micropython,ceramos/micropython,xuxiaoxin/micropython,micropython/micropython-esp32,danicampora/micropython,deshipu/micropython,jlillest/micropython,dmazzella/micropython,HenrikSolver/micropython,emfcamp/micropython,warner83/micropython,ganshun666/micropython,HenrikSolver/micropython,adamkh/micropython,xhat/micropython,cloudformdesign/micropython,ganshun666/micropython,SungEun-Steve-Kim/test-mp,dhylands/micropython,misterdanb/micropython,micropython/micropython-esp32,mhoffma/micropython,orionrobots/micropython,skybird6672/micropython,MrSurly/micropython-esp32,lbattraw/micropython,pramasoul/micropython,cwyark/micropython,blazewicz/micropython,ernesto-g/micropython,warner83/micropython,lbattraw/micropython,vitiral/micropython,praemdonck/micropython,torwag/micropython,puuu/micropython,Peetz0r/micropython-esp32,omtinez/micropython,noahchense/micropython,MrSurly/micropython-esp32,emfcamp/micropython,misterdanb/micropython,redbear/micropython,toolmacher/micropython,ahotam/micropython,AriZuu/micropython,kostyll/micropython,alex-robbins/micropython,adafruit/circuitpython,trezor/micropython,ChuckM/micropython,warner83/micropython,cloudformdesign/micropython,orionrobots/micropython,danicampora/micropython,galenhz/micropython,micropython/micropython-esp32,martinribelotta/micropython,methoxid/micropystat,heisewangluo/micropython,mpalomer/micropython,adamkh/micropython,supergis/micropython,henriknelson/micropython,paul-xxx/micropython,drrk/micropython,feilongfl/micropython,SungEun-Steve-Kim/test-mp,AriZuu/micropython,vriera/micropython,aethaniel/micropython,PappaPeppar/micropython,puuu/micropython,matthewelse/micropython,chrisdearman/micropython,HenrikSolver/micropython,lowRISC/micropython,Timmenem/micropython,jmarcelino/pycom-micropython,methoxid/micropystat,jmarcelino/pycom-micropython,pozetroninc/micropython,galenhz/micropython,torwag/micropython,drrk/micropython,KISSMonX/micropython,adafruit/circuitpython,mianos/micropython,drrk/micropython,AriZuu/micropython,Peetz0r/micropython-esp32,ChuckM/micropython,rubencabrera/micropython,noahwilliamsson/micropython,blazewicz/micropython,pozetroninc/micropython,aethaniel/micropython,noahwilliamsson/micropython,pramasoul/micropython,warner83/micropython,ruffy91/micropython,SungEun-Steve-Kim/test-mp,Vogtinator/micropython,cnoviello/micropython,martinribelotta/micropython,suda/micropython,xhat/micropython,Timmenem/micropython,blmorris/micropython,infinnovation/micropython,infinnovation/micropython,praemdonck/micropython,jmarcelino/pycom-micropython,PappaPeppar/micropython,trezor/micropython,puuu/micropython,hosaka/micropython,paul-xxx/micropython,blazewicz/micropython,chrisdearman/micropython,mianos/micropython,methoxid/micropystat,ericsnowcurrently/micropython,vitiral/micropython,Vogtinator/micropython,mhoffma/micropython,toolmacher/micropython,blmorris/micropython,lowRISC/micropython,heisewangluo/micropython,adafruit/micropython,EcmaXp/micropython,drrk/micropython,MrSurly/micropython,toolmacher/micropython,emfcamp/micropython,redbear/micropython,praemdonck/micropython,ChuckM/micropython,xyb/micropython,aethaniel/micropython,slzatz/micropython,alex-robbins/micropython,ryannathans/micropython,suda/micropython,emfcamp/micropython,lowRISC/micropython,kerneltask/micropython,HenrikSolver/micropython,rubencabrera/micropython,vriera/micropython,Vogtinator/micropython,SHA2017-badge/micropython-esp32,henriknelson/micropython,noahchense/micropython,vriera/micropython,puuu/micropython,toolmacher/micropython,xuxiaoxin/micropython,ernesto-g/micropython,PappaPeppar/micropython,pfalcon/micropython,SHA2017-badge/micropython-esp32,dinau/micropython,matthewelse/micropython,kostyll/micropython,alex-robbins/micropython,slzatz/micropython,trezor/micropython,alex-robbins/micropython,methoxid/micropystat,dxxb/micropython,trezor/micropython,adafruit/micropython,vitiral/micropython,SungEun-Steve-Kim/test-mp,xyb/micropython,kerneltask/micropython,mhoffma/micropython,vitiral/micropython,henriknelson/micropython,infinnovation/micropython,blmorris/micropython,micropython/micropython-esp32,swegener/micropython,ChuckM/micropython,kostyll/micropython,cwyark/micropython,KISSMonX/micropython,ganshun666/micropython,Timmenem/micropython,mianos/micropython,ryannathans/micropython,omtinez/micropython,turbinenreiter/micropython,oopy/micropython,dinau/micropython,mhoffma/micropython,blmorris/micropython,henriknelson/micropython,alex-march/micropython,warner83/micropython,ahotam/micropython
|
python
|
## Code Before:
def foo():
seq = [1, 2, 3]
v = 100
i = 5
while i > 0:
print(i)
for a in seq:
if a == 2:
break
i -= 1
foo()
## Instruction:
tests: Add another test for break-from-for-loop.
## Code After:
def foo():
seq = [1, 2, 3]
v = 100
i = 5
while i > 0:
print(i)
for a in seq:
if a == 2:
break
i -= 1
foo()
# break from within nested for loop
def bar():
l = [1, 2, 3]
for e1 in l:
print(e1)
for e2 in l:
print(e1, e2)
if e2 == 2:
break
bar()
|
...
i -= 1
foo()
# break from within nested for loop
def bar():
l = [1, 2, 3]
for e1 in l:
print(e1)
for e2 in l:
print(e1, e2)
if e2 == 2:
break
bar()
...
|
d9eb347432f247879ba10da2a64f810657a09c84
|
source/core/recommend-manager/RandGenerator.h
|
source/core/recommend-manager/RandGenerator.h
|
/**
* @file RandGenerator.h
* @brief generate random item ids
* @author Jun Jiang
* @date 2011-11-30
*/
#ifndef RAND_GENERATOR_H
#define RAND_GENERATOR_H
#include <util/ThreadModel.h>
#include <boost/random.hpp>
namespace sf1r
{
template<typename ValueType = int,
typename Distribution = boost::uniform_int<ValueType>,
typename Engine = boost::mt19937,
typename LockType = izenelib::util::ReadWriteLock>
class RandGenerator
{
public:
RandGenerator()
: generator_(Engine(), Distribution())
{}
void seed(int value)
{
ScopedWriteLock lock(lock_);
generator_.engine().seed(value);
}
ValueType generate(ValueType min, ValueType max)
{
ScopedWriteLock lock(lock_);
Distribution& dist = generator_.distribution();
if (dist.min() != min || dist.max() != max)
{
dist = Distribution(min, max);
}
return generator_();
}
private:
typedef boost::variate_generator<Engine, Distribution> Generator;
Generator generator_;
typedef izenelib::util::ScopedWriteLock<LockType> ScopedWriteLock;
LockType lock_;
};
} // namespace sf1r
#endif // RAND_GENERATOR_H
|
/**
* @file RandGenerator.h
* @brief generate random item ids
* @author Jun Jiang
* @date 2011-11-30
*/
#ifndef RAND_GENERATOR_H
#define RAND_GENERATOR_H
#include <util/ThreadModel.h>
#include <boost/random.hpp>
namespace sf1r
{
template<typename ValueType = int,
typename Distribution = boost::uniform_int<ValueType>,
typename Engine = boost::mt19937,
typename LockType = izenelib::util::ReadWriteLock>
class RandGenerator
{
public:
RandGenerator()
: generator_(Engine(), Distribution())
{}
void seed(unsigned int value)
{
ScopedWriteLock lock(lock_);
Engine& engine = generator_.engine();
engine.seed(value);
}
ValueType generate(ValueType min, ValueType max)
{
ScopedWriteLock lock(lock_);
Distribution& dist = generator_.distribution();
if (dist.min() != min || dist.max() != max)
{
dist = Distribution(min, max);
}
return generator_();
}
private:
typedef boost::variate_generator<Engine, Distribution> Generator;
Generator generator_;
typedef izenelib::util::ScopedWriteLock<LockType> ScopedWriteLock;
LockType lock_;
};
} // namespace sf1r
#endif // RAND_GENERATOR_H
|
Fix compile error under boost 1.38, caused by boost/random.hpp seed()
|
Fix compile error under boost 1.38, caused by boost/random.hpp seed()
|
C
|
apache-2.0
|
pombredanne/sf1r-lite,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-lite,izenecloud/sf1r-lite,izenecloud/sf1r-lite,pombredanne/sf1r-lite,pombredanne/sf1r-lite,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-lite,pombredanne/sf1r-lite,izenecloud/sf1r-ad-delivery,pombredanne/sf1r-lite,izenecloud/sf1r-lite,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-ad-delivery
|
c
|
## Code Before:
/**
* @file RandGenerator.h
* @brief generate random item ids
* @author Jun Jiang
* @date 2011-11-30
*/
#ifndef RAND_GENERATOR_H
#define RAND_GENERATOR_H
#include <util/ThreadModel.h>
#include <boost/random.hpp>
namespace sf1r
{
template<typename ValueType = int,
typename Distribution = boost::uniform_int<ValueType>,
typename Engine = boost::mt19937,
typename LockType = izenelib::util::ReadWriteLock>
class RandGenerator
{
public:
RandGenerator()
: generator_(Engine(), Distribution())
{}
void seed(int value)
{
ScopedWriteLock lock(lock_);
generator_.engine().seed(value);
}
ValueType generate(ValueType min, ValueType max)
{
ScopedWriteLock lock(lock_);
Distribution& dist = generator_.distribution();
if (dist.min() != min || dist.max() != max)
{
dist = Distribution(min, max);
}
return generator_();
}
private:
typedef boost::variate_generator<Engine, Distribution> Generator;
Generator generator_;
typedef izenelib::util::ScopedWriteLock<LockType> ScopedWriteLock;
LockType lock_;
};
} // namespace sf1r
#endif // RAND_GENERATOR_H
## Instruction:
Fix compile error under boost 1.38, caused by boost/random.hpp seed()
## Code After:
/**
* @file RandGenerator.h
* @brief generate random item ids
* @author Jun Jiang
* @date 2011-11-30
*/
#ifndef RAND_GENERATOR_H
#define RAND_GENERATOR_H
#include <util/ThreadModel.h>
#include <boost/random.hpp>
namespace sf1r
{
template<typename ValueType = int,
typename Distribution = boost::uniform_int<ValueType>,
typename Engine = boost::mt19937,
typename LockType = izenelib::util::ReadWriteLock>
class RandGenerator
{
public:
RandGenerator()
: generator_(Engine(), Distribution())
{}
void seed(unsigned int value)
{
ScopedWriteLock lock(lock_);
Engine& engine = generator_.engine();
engine.seed(value);
}
ValueType generate(ValueType min, ValueType max)
{
ScopedWriteLock lock(lock_);
Distribution& dist = generator_.distribution();
if (dist.min() != min || dist.max() != max)
{
dist = Distribution(min, max);
}
return generator_();
}
private:
typedef boost::variate_generator<Engine, Distribution> Generator;
Generator generator_;
typedef izenelib::util::ScopedWriteLock<LockType> ScopedWriteLock;
LockType lock_;
};
} // namespace sf1r
#endif // RAND_GENERATOR_H
|
...
: generator_(Engine(), Distribution())
{}
void seed(unsigned int value)
{
ScopedWriteLock lock(lock_);
Engine& engine = generator_.engine();
engine.seed(value);
}
ValueType generate(ValueType min, ValueType max)
...
|
d86a4b75b1d8b4d18aadbb2bc98387b5ce78f939
|
tests/web/splinter/test_view_album.py
|
tests/web/splinter/test_view_album.py
|
from __future__ import unicode_literals
from tests import with_settings
from tests.web.splinter import TestCase
from catsnap import Client
from catsnap.table.image import Image
from catsnap.table.album import Album
from nose.tools import eq_
class TestUploadImage(TestCase):
@with_settings(bucket='humptydump')
def test_view_an_album(self):
session = Client().session()
album = Album(name="photo sesh")
session.add(album)
session.flush()
silly = Image(album_id=album.album_id, filename="silly")
serious = Image(album_id=album.album_id, filename="serious")
session.add(silly)
session.add(serious)
session.flush()
self.visit_url('/album/{0}'.format(album.album_id))
images = self.browser.find_by_tag('img')
eq_(map(lambda i: i['src'], images), [
'https://s3.amazonaws.com/humptydump/silly',
'https://s3.amazonaws.com/humptydump/serious',
])
eq_(map(lambda i: i['alt'], images), ['silly', 'serious'])
assert self.browser.is_text_present('silly')
assert self.browser.is_text_present('serious')
|
from __future__ import unicode_literals
from tests import with_settings
from tests.web.splinter import TestCase
from catsnap import Client
from catsnap.table.image import Image
from catsnap.table.album import Album
from nose.tools import eq_
class TestViewAlbum(TestCase):
@with_settings(bucket='humptydump')
def test_view_an_album(self):
session = Client().session()
album = Album(name="photo sesh")
session.add(album)
session.flush()
silly = Image(album_id=album.album_id, filename="silly")
serious = Image(album_id=album.album_id, filename="serious")
session.add(silly)
session.add(serious)
session.flush()
self.visit_url('/album/{0}'.format(album.album_id))
images = self.browser.find_by_tag('img')
eq_(map(lambda i: i['src'], images), [
'https://s3.amazonaws.com/humptydump/silly',
'https://s3.amazonaws.com/humptydump/serious',
])
eq_(map(lambda i: i['alt'], images), ['silly', 'serious'])
assert self.browser.is_text_present('silly')
assert self.browser.is_text_present('serious')
|
Fix a test class name
|
Fix a test class name
|
Python
|
mit
|
ErinCall/catsnap,ErinCall/catsnap,ErinCall/catsnap
|
python
|
## Code Before:
from __future__ import unicode_literals
from tests import with_settings
from tests.web.splinter import TestCase
from catsnap import Client
from catsnap.table.image import Image
from catsnap.table.album import Album
from nose.tools import eq_
class TestUploadImage(TestCase):
@with_settings(bucket='humptydump')
def test_view_an_album(self):
session = Client().session()
album = Album(name="photo sesh")
session.add(album)
session.flush()
silly = Image(album_id=album.album_id, filename="silly")
serious = Image(album_id=album.album_id, filename="serious")
session.add(silly)
session.add(serious)
session.flush()
self.visit_url('/album/{0}'.format(album.album_id))
images = self.browser.find_by_tag('img')
eq_(map(lambda i: i['src'], images), [
'https://s3.amazonaws.com/humptydump/silly',
'https://s3.amazonaws.com/humptydump/serious',
])
eq_(map(lambda i: i['alt'], images), ['silly', 'serious'])
assert self.browser.is_text_present('silly')
assert self.browser.is_text_present('serious')
## Instruction:
Fix a test class name
## Code After:
from __future__ import unicode_literals
from tests import with_settings
from tests.web.splinter import TestCase
from catsnap import Client
from catsnap.table.image import Image
from catsnap.table.album import Album
from nose.tools import eq_
class TestViewAlbum(TestCase):
@with_settings(bucket='humptydump')
def test_view_an_album(self):
session = Client().session()
album = Album(name="photo sesh")
session.add(album)
session.flush()
silly = Image(album_id=album.album_id, filename="silly")
serious = Image(album_id=album.album_id, filename="serious")
session.add(silly)
session.add(serious)
session.flush()
self.visit_url('/album/{0}'.format(album.album_id))
images = self.browser.find_by_tag('img')
eq_(map(lambda i: i['src'], images), [
'https://s3.amazonaws.com/humptydump/silly',
'https://s3.amazonaws.com/humptydump/serious',
])
eq_(map(lambda i: i['alt'], images), ['silly', 'serious'])
assert self.browser.is_text_present('silly')
assert self.browser.is_text_present('serious')
|
# ... existing code ...
from catsnap.table.album import Album
from nose.tools import eq_
class TestViewAlbum(TestCase):
@with_settings(bucket='humptydump')
def test_view_an_album(self):
session = Client().session()
# ... rest of the code ...
|
5e4545a5a91f37a278d583b9b41baeb801c612a5
|
app/src/main/java/edu/deanza/calendar/activities/OrganizationInfo.java
|
app/src/main/java/edu/deanza/calendar/activities/OrganizationInfo.java
|
package edu.deanza.calendar.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;
import edu.deanza.calendar.OrganizationSubscribeOnClickListener;
import edu.deanza.calendar.R;
import edu.deanza.calendar.dal.FirebaseSubscriptionDao;
import edu.deanza.calendar.dal.SubscriptionDao;
import edu.deanza.calendar.domain.models.Organization;
public class OrganizationInfo extends AppCompatActivity {
Organization organization;
SubscriptionDao subscriptionDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_organization_info);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
organization = (Organization) intent.getSerializableExtra("edu.deanza.calendar.models.Organization");
subscriptionDao = new FirebaseSubscriptionDao(intent.getStringExtra("UID"));
setTitle(organization.getName());
// TODO: set image button icon depending on org.getsub
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new OrganizationSubscribeOnClickListener(this, organization, subscriptionDao));
}
}
|
package edu.deanza.calendar.activities;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.ImageButton;
import android.widget.TextView;
import edu.deanza.calendar.OrganizationSubscribeOnClickListener;
import edu.deanza.calendar.R;
import edu.deanza.calendar.dal.FirebaseSubscriptionDao;
import edu.deanza.calendar.dal.SubscriptionDao;
import edu.deanza.calendar.domain.models.Organization;
public class OrganizationInfo extends AppCompatActivity {
Organization organization;
SubscriptionDao subscriptionDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_organization_info);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
organization = (Organization) intent.getSerializableExtra("edu.deanza.calendar.models.Organization");
subscriptionDao = new FirebaseSubscriptionDao(intent.getStringExtra("UID"));
setTitle(organization.getName());
TextView descriptionView = (TextView) findViewById(R.id.organization_description);
descriptionView.setText(organization.getDescription());
FloatingActionButton subscribeButton = (FloatingActionButton) findViewById(R.id.fab);
if (organization.getSubscription() == null) {
subscribeButton.setImageResource(R.drawable.ic_favorite_border);
}
else {
subscribeButton.setImageResource(R.drawable.ic_favorite);
}
subscribeButton.setOnClickListener(new OrganizationSubscribeOnClickListener(this, organization, subscriptionDao));
}
}
|
Set subscribe button image based on Subscription in OrgInfo
|
Set subscribe button image based on Subscription in OrgInfo
|
Java
|
apache-2.0
|
saraelz/DA-Now
|
java
|
## Code Before:
package edu.deanza.calendar.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;
import edu.deanza.calendar.OrganizationSubscribeOnClickListener;
import edu.deanza.calendar.R;
import edu.deanza.calendar.dal.FirebaseSubscriptionDao;
import edu.deanza.calendar.dal.SubscriptionDao;
import edu.deanza.calendar.domain.models.Organization;
public class OrganizationInfo extends AppCompatActivity {
Organization organization;
SubscriptionDao subscriptionDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_organization_info);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
organization = (Organization) intent.getSerializableExtra("edu.deanza.calendar.models.Organization");
subscriptionDao = new FirebaseSubscriptionDao(intent.getStringExtra("UID"));
setTitle(organization.getName());
// TODO: set image button icon depending on org.getsub
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new OrganizationSubscribeOnClickListener(this, organization, subscriptionDao));
}
}
## Instruction:
Set subscribe button image based on Subscription in OrgInfo
## Code After:
package edu.deanza.calendar.activities;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.ImageButton;
import android.widget.TextView;
import edu.deanza.calendar.OrganizationSubscribeOnClickListener;
import edu.deanza.calendar.R;
import edu.deanza.calendar.dal.FirebaseSubscriptionDao;
import edu.deanza.calendar.dal.SubscriptionDao;
import edu.deanza.calendar.domain.models.Organization;
public class OrganizationInfo extends AppCompatActivity {
Organization organization;
SubscriptionDao subscriptionDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_organization_info);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
organization = (Organization) intent.getSerializableExtra("edu.deanza.calendar.models.Organization");
subscriptionDao = new FirebaseSubscriptionDao(intent.getStringExtra("UID"));
setTitle(organization.getName());
TextView descriptionView = (TextView) findViewById(R.id.organization_description);
descriptionView.setText(organization.getDescription());
FloatingActionButton subscribeButton = (FloatingActionButton) findViewById(R.id.fab);
if (organization.getSubscription() == null) {
subscribeButton.setImageResource(R.drawable.ic_favorite_border);
}
else {
subscribeButton.setImageResource(R.drawable.ic_favorite);
}
subscribeButton.setOnClickListener(new OrganizationSubscribeOnClickListener(this, organization, subscriptionDao));
}
}
|
// ... existing code ...
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.ImageButton;
import android.widget.TextView;
import edu.deanza.calendar.OrganizationSubscribeOnClickListener;
// ... modified code ...
subscriptionDao = new FirebaseSubscriptionDao(intent.getStringExtra("UID"));
setTitle(organization.getName());
TextView descriptionView = (TextView) findViewById(R.id.organization_description);
descriptionView.setText(organization.getDescription());
FloatingActionButton subscribeButton = (FloatingActionButton) findViewById(R.id.fab);
if (organization.getSubscription() == null) {
subscribeButton.setImageResource(R.drawable.ic_favorite_border);
}
else {
subscribeButton.setImageResource(R.drawable.ic_favorite);
}
subscribeButton.setOnClickListener(new OrganizationSubscribeOnClickListener(this, organization, subscriptionDao));
}
}
// ... rest of the code ...
|
d4811ebf3c136bba2559a2156b88909a76cfac7b
|
setup.py
|
setup.py
|
from distutils.core import setup
setup(
name='enumerator',
version='0.1.4',
author='Erik Dominguez, Steve Coward',
author_email='[email protected], [email protected]',
maintainer='Steve Coward',
maintainer_email='[email protected]',
scripts=['bin/enumerator'],
packages=['enumerator', 'enumerator.static', 'enumerator.lib', 'enumerator.lib.services'],
package_data={
'': ['*.txt'],
},
url='http://pypi.python.org/pypi/enumerator/',
license='LICENSE.txt',
description='enumerator is a tool built to assist in automating the often tedious task of enumerating a target or list of targets during a penetration test.',
long_description=open('README.txt').read(),
install_requires=[
'blinker==1.3',
],
)
|
from setuptools import setup
setup(
name='enumerator',
version='0.1.4',
author='Erik Dominguez, Steve Coward',
author_email='[email protected], [email protected]',
maintainer='Steve Coward',
maintainer_email='[email protected]',
scripts=['bin/enumerator'],
packages=['enumerator', 'enumerator.static', 'enumerator.lib', 'enumerator.lib.services'],
package_data={
'': ['*.txt'],
},
url='http://pypi.python.org/pypi/enumerator/',
license='LICENSE.txt',
description='enumerator is a tool built to assist in automating the often tedious task of enumerating a target or list of targets during a penetration test.',
long_description=open('README.txt').read(),
install_requires=[
'blinker==1.3',
],
)
|
Use Setuptools instead of the deprecated Disutils
|
Use Setuptools instead of the deprecated Disutils
|
Python
|
mit
|
sgabe/Enumerator
|
python
|
## Code Before:
from distutils.core import setup
setup(
name='enumerator',
version='0.1.4',
author='Erik Dominguez, Steve Coward',
author_email='[email protected], [email protected]',
maintainer='Steve Coward',
maintainer_email='[email protected]',
scripts=['bin/enumerator'],
packages=['enumerator', 'enumerator.static', 'enumerator.lib', 'enumerator.lib.services'],
package_data={
'': ['*.txt'],
},
url='http://pypi.python.org/pypi/enumerator/',
license='LICENSE.txt',
description='enumerator is a tool built to assist in automating the often tedious task of enumerating a target or list of targets during a penetration test.',
long_description=open('README.txt').read(),
install_requires=[
'blinker==1.3',
],
)
## Instruction:
Use Setuptools instead of the deprecated Disutils
## Code After:
from setuptools import setup
setup(
name='enumerator',
version='0.1.4',
author='Erik Dominguez, Steve Coward',
author_email='[email protected], [email protected]',
maintainer='Steve Coward',
maintainer_email='[email protected]',
scripts=['bin/enumerator'],
packages=['enumerator', 'enumerator.static', 'enumerator.lib', 'enumerator.lib.services'],
package_data={
'': ['*.txt'],
},
url='http://pypi.python.org/pypi/enumerator/',
license='LICENSE.txt',
description='enumerator is a tool built to assist in automating the often tedious task of enumerating a target or list of targets during a penetration test.',
long_description=open('README.txt').read(),
install_requires=[
'blinker==1.3',
],
)
|
// ... existing code ...
from setuptools import setup
setup(
name='enumerator',
// ... rest of the code ...
|
1ccd9e7f15cfaccfadf7e4e977dbde724885cab9
|
tests/test_sync_call.py
|
tests/test_sync_call.py
|
import time
from switchy import sync_caller
from switchy.apps.players import TonePlay
def test_toneplay(fsip):
'''Test the synchronous caller with a simple toneplay
'''
with sync_caller(fsip, apps={"TonePlay": TonePlay}) as caller:
# have the external prof call itself by default
assert 'TonePlay' in caller.app_names
sess, waitfor = caller(
"doggy@{}:{}".format(caller.client.server, 5080),
'TonePlay',
timeout=3,
)
assert sess.is_outbound()
time.sleep(1)
sess.hangup()
time.sleep(0.1)
assert caller.client.listener.count_calls() == 0
|
import time
from switchy import sync_caller
from switchy.apps.players import TonePlay, PlayRec
def test_toneplay(fsip):
'''Test the synchronous caller with a simple toneplay
'''
with sync_caller(fsip, apps={"TonePlay": TonePlay}) as caller:
# have the external prof call itself by default
assert 'TonePlay' in caller.app_names
sess, waitfor = caller(
"doggy@{}:{}".format(caller.client.server, 5080),
'TonePlay',
timeout=3,
)
assert sess.is_outbound()
time.sleep(1)
sess.hangup()
time.sleep(0.1)
assert caller.client.listener.count_calls() == 0
def test_playrec(fsip):
'''Test the synchronous caller with a simulated conversation using the the
`PlayRec` app. Currently this test does no audio checking but merely verifies
the callback chain is invoked as expected.
'''
with sync_caller(fsip, apps={"PlayRec": PlayRec}) as caller:
# have the external prof call itself by default
caller.apps.PlayRec.sim_convo = True
sess, waitfor = caller(
"doggy@{}:{}".format(caller.client.server, 5080),
'PlayRec',
timeout=10,
)
waitfor(sess, 'recorded', timeout=15)
waitfor(sess.call.get_peer(sess), 'recorded', timeout=15)
assert sess.call.vars['record']
time.sleep(1)
assert sess.hungup
|
Add a `PlayRec` app unit test
|
Add a `PlayRec` app unit test
Merely checks that all sessions are recorded as expected and that the call
is hung up afterwards. None of the recorded audio content is verified.
|
Python
|
mpl-2.0
|
sangoma/switchy,wwezhuimeng/switch
|
python
|
## Code Before:
import time
from switchy import sync_caller
from switchy.apps.players import TonePlay
def test_toneplay(fsip):
'''Test the synchronous caller with a simple toneplay
'''
with sync_caller(fsip, apps={"TonePlay": TonePlay}) as caller:
# have the external prof call itself by default
assert 'TonePlay' in caller.app_names
sess, waitfor = caller(
"doggy@{}:{}".format(caller.client.server, 5080),
'TonePlay',
timeout=3,
)
assert sess.is_outbound()
time.sleep(1)
sess.hangup()
time.sleep(0.1)
assert caller.client.listener.count_calls() == 0
## Instruction:
Add a `PlayRec` app unit test
Merely checks that all sessions are recorded as expected and that the call
is hung up afterwards. None of the recorded audio content is verified.
## Code After:
import time
from switchy import sync_caller
from switchy.apps.players import TonePlay, PlayRec
def test_toneplay(fsip):
'''Test the synchronous caller with a simple toneplay
'''
with sync_caller(fsip, apps={"TonePlay": TonePlay}) as caller:
# have the external prof call itself by default
assert 'TonePlay' in caller.app_names
sess, waitfor = caller(
"doggy@{}:{}".format(caller.client.server, 5080),
'TonePlay',
timeout=3,
)
assert sess.is_outbound()
time.sleep(1)
sess.hangup()
time.sleep(0.1)
assert caller.client.listener.count_calls() == 0
def test_playrec(fsip):
'''Test the synchronous caller with a simulated conversation using the the
`PlayRec` app. Currently this test does no audio checking but merely verifies
the callback chain is invoked as expected.
'''
with sync_caller(fsip, apps={"PlayRec": PlayRec}) as caller:
# have the external prof call itself by default
caller.apps.PlayRec.sim_convo = True
sess, waitfor = caller(
"doggy@{}:{}".format(caller.client.server, 5080),
'PlayRec',
timeout=10,
)
waitfor(sess, 'recorded', timeout=15)
waitfor(sess.call.get_peer(sess), 'recorded', timeout=15)
assert sess.call.vars['record']
time.sleep(1)
assert sess.hungup
|
// ... existing code ...
import time
from switchy import sync_caller
from switchy.apps.players import TonePlay, PlayRec
def test_toneplay(fsip):
// ... modified code ...
sess.hangup()
time.sleep(0.1)
assert caller.client.listener.count_calls() == 0
def test_playrec(fsip):
'''Test the synchronous caller with a simulated conversation using the the
`PlayRec` app. Currently this test does no audio checking but merely verifies
the callback chain is invoked as expected.
'''
with sync_caller(fsip, apps={"PlayRec": PlayRec}) as caller:
# have the external prof call itself by default
caller.apps.PlayRec.sim_convo = True
sess, waitfor = caller(
"doggy@{}:{}".format(caller.client.server, 5080),
'PlayRec',
timeout=10,
)
waitfor(sess, 'recorded', timeout=15)
waitfor(sess.call.get_peer(sess), 'recorded', timeout=15)
assert sess.call.vars['record']
time.sleep(1)
assert sess.hungup
// ... rest of the code ...
|
e467aa0a6c47be82285111e50238422c99d87cd9
|
android-framework/src/main/java/io/blushine/android/ui/list/ClickFunctionality.java
|
android-framework/src/main/java/io/blushine/android/ui/list/ClickFunctionality.java
|
package io.blushine.android.ui.list;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Edit an item by long clicking on it
*/
class ClickFunctionality<T> implements PostBindFunctionality<T> {
private ClickListener<T> mListener;
public ClickFunctionality(ClickListener<T> listener) {
if (listener == null) {
throw new IllegalArgumentException("listener is null");
}
mListener = listener;
}
@Override
public void applyFunctionality(AdvancedAdapter<T, ?> adapter, RecyclerView recyclerView) {
// Does nothing
}
@Override
public void onPostBind(final AdvancedAdapter<T, ?> adapter, RecyclerView.ViewHolder viewHolder, final int position) {
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
T item = adapter.getItem(position);
mListener.onClick(item);
}
});
}
}
|
package io.blushine.android.ui.list;
import android.support.v7.widget.RecyclerView;
/**
* Edit an item by long clicking on it
*/
class ClickFunctionality<T> implements PostBindFunctionality<T> {
private ClickListener<T> mListener;
ClickFunctionality(ClickListener<T> listener) {
if (listener == null) {
throw new IllegalArgumentException("listener is null");
}
mListener = listener;
}
@Override
public void applyFunctionality(AdvancedAdapter<T, ?> adapter, RecyclerView recyclerView) {
// Does nothing
}
@Override
public void onPostBind(final AdvancedAdapter<T, ?> adapter, RecyclerView.ViewHolder viewHolder, int position) {
viewHolder.itemView.setOnClickListener(view -> {
int adapterPosition = viewHolder.getAdapterPosition();
T item = adapter.getItem(adapterPosition);
mListener.onClick(item);
});
}
}
|
Fix so that onClick in adapters get the correct item
|
Fix so that onClick in adapters get the correct item
|
Java
|
mit
|
Spiddekauga/android-utils
|
java
|
## Code Before:
package io.blushine.android.ui.list;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Edit an item by long clicking on it
*/
class ClickFunctionality<T> implements PostBindFunctionality<T> {
private ClickListener<T> mListener;
public ClickFunctionality(ClickListener<T> listener) {
if (listener == null) {
throw new IllegalArgumentException("listener is null");
}
mListener = listener;
}
@Override
public void applyFunctionality(AdvancedAdapter<T, ?> adapter, RecyclerView recyclerView) {
// Does nothing
}
@Override
public void onPostBind(final AdvancedAdapter<T, ?> adapter, RecyclerView.ViewHolder viewHolder, final int position) {
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
T item = adapter.getItem(position);
mListener.onClick(item);
}
});
}
}
## Instruction:
Fix so that onClick in adapters get the correct item
## Code After:
package io.blushine.android.ui.list;
import android.support.v7.widget.RecyclerView;
/**
* Edit an item by long clicking on it
*/
class ClickFunctionality<T> implements PostBindFunctionality<T> {
private ClickListener<T> mListener;
ClickFunctionality(ClickListener<T> listener) {
if (listener == null) {
throw new IllegalArgumentException("listener is null");
}
mListener = listener;
}
@Override
public void applyFunctionality(AdvancedAdapter<T, ?> adapter, RecyclerView recyclerView) {
// Does nothing
}
@Override
public void onPostBind(final AdvancedAdapter<T, ?> adapter, RecyclerView.ViewHolder viewHolder, int position) {
viewHolder.itemView.setOnClickListener(view -> {
int adapterPosition = viewHolder.getAdapterPosition();
T item = adapter.getItem(adapterPosition);
mListener.onClick(item);
});
}
}
|
// ... existing code ...
package io.blushine.android.ui.list;
import android.support.v7.widget.RecyclerView;
/**
* Edit an item by long clicking on it
// ... modified code ...
class ClickFunctionality<T> implements PostBindFunctionality<T> {
private ClickListener<T> mListener;
ClickFunctionality(ClickListener<T> listener) {
if (listener == null) {
throw new IllegalArgumentException("listener is null");
}
mListener = listener;
}
...
}
@Override
public void onPostBind(final AdvancedAdapter<T, ?> adapter, RecyclerView.ViewHolder viewHolder, int position) {
viewHolder.itemView.setOnClickListener(view -> {
int adapterPosition = viewHolder.getAdapterPosition();
T item = adapter.getItem(adapterPosition);
mListener.onClick(item);
});
}
}
// ... rest of the code ...
|
03ebfe0518a7ac39f9414b3e8d8638c9dcba917c
|
tests/auth/test_models.py
|
tests/auth/test_models.py
|
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.utils import unittest
from bakery.auth.models import BakeryUser
class TestBakeryUserModel(TestCase):
@unittest.skip('Not yet implemented')
def test_get_absolute_url(self):
user = BakeryUser.objects.create_user('user', 'password')
user.name = 'John Doe'
self.assertEqual(user.get_absolute_url(), reverse('user-detail-view'))
def test_get_full_name(self):
user = BakeryUser.objects.create_user('user', 'password')
user.name = 'John Doe'
self.assertEqual(user.get_full_name(), 'John Doe')
def test_get_short_name(self):
user = BakeryUser.objects.create_user('user', 'password')
user.name = 'John Doe'
self.assertEqual(user.get_short_name(), 'John Doe')
|
from django.test import TestCase
from bakery.auth.models import BakeryUser
class TestBakeryUserModel(TestCase):
def test_get_absolute_url(self):
user = BakeryUser.objects.create_user('user', 'password')
user.name = 'John Doe'
self.assertEqual(user.get_absolute_url(), '/profile/user/')
def test_get_full_name(self):
user = BakeryUser.objects.create_user('user', 'password')
user.name = 'John Doe'
self.assertEqual(user.get_full_name(), 'John Doe')
def test_get_short_name(self):
user = BakeryUser.objects.create_user('user', 'password')
user.name = 'John Doe'
self.assertEqual(user.get_short_name(), 'John Doe')
|
Adjust test (refers prev commit)
|
Adjust test (refers prev commit)
|
Python
|
bsd-3-clause
|
muffins-on-dope/bakery,muffins-on-dope/bakery,muffins-on-dope/bakery
|
python
|
## Code Before:
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.utils import unittest
from bakery.auth.models import BakeryUser
class TestBakeryUserModel(TestCase):
@unittest.skip('Not yet implemented')
def test_get_absolute_url(self):
user = BakeryUser.objects.create_user('user', 'password')
user.name = 'John Doe'
self.assertEqual(user.get_absolute_url(), reverse('user-detail-view'))
def test_get_full_name(self):
user = BakeryUser.objects.create_user('user', 'password')
user.name = 'John Doe'
self.assertEqual(user.get_full_name(), 'John Doe')
def test_get_short_name(self):
user = BakeryUser.objects.create_user('user', 'password')
user.name = 'John Doe'
self.assertEqual(user.get_short_name(), 'John Doe')
## Instruction:
Adjust test (refers prev commit)
## Code After:
from django.test import TestCase
from bakery.auth.models import BakeryUser
class TestBakeryUserModel(TestCase):
def test_get_absolute_url(self):
user = BakeryUser.objects.create_user('user', 'password')
user.name = 'John Doe'
self.assertEqual(user.get_absolute_url(), '/profile/user/')
def test_get_full_name(self):
user = BakeryUser.objects.create_user('user', 'password')
user.name = 'John Doe'
self.assertEqual(user.get_full_name(), 'John Doe')
def test_get_short_name(self):
user = BakeryUser.objects.create_user('user', 'password')
user.name = 'John Doe'
self.assertEqual(user.get_short_name(), 'John Doe')
|
# ... existing code ...
from django.test import TestCase
from bakery.auth.models import BakeryUser
# ... modified code ...
class TestBakeryUserModel(TestCase):
def test_get_absolute_url(self):
user = BakeryUser.objects.create_user('user', 'password')
user.name = 'John Doe'
self.assertEqual(user.get_absolute_url(), '/profile/user/')
def test_get_full_name(self):
user = BakeryUser.objects.create_user('user', 'password')
# ... rest of the code ...
|
9c923b8a94ea534c5b18983e81add7301a1dfa66
|
waterbutler/core/streams/file.py
|
waterbutler/core/streams/file.py
|
import os
from waterbutler.core.streams import BaseStream
class FileStreamReader(BaseStream):
def __init__(self, file_pointer):
super().__init__()
self.file_gen = None
self.file_pointer = file_pointer
self.read_size = None
self.content_type = 'application/octet-stream'
@property
def size(self):
cursor = self.file_pointer.tell()
self.file_pointer.seek(0, os.SEEK_END)
ret = self.file_pointer.tell()
self.file_pointer.seek(cursor)
return ret
def close(self):
self.file_pointer.close()
self.feed_eof()
def read_as_gen(self):
self.file_pointer.seek(0)
while True:
chunk = self.file_pointer.read(self.read_size)
if not chunk:
self.feed_eof()
chunk = b''
yield chunk
async def _read(self, size):
self.file_gen = self.file_gen or self.read_as_gen()
self.read_size = size
return next(self.file_gen)
|
import os
# import asyncio
from waterbutler.core.streams import BaseStream
class FileStreamReader(BaseStream):
def __init__(self, file_pointer):
super().__init__()
self.file_gen = None
self.file_pointer = file_pointer
self.read_size = None
self.content_type = 'application/octet-stream'
@property
def size(self):
cursor = self.file_pointer.tell()
self.file_pointer.seek(0, os.SEEK_END)
ret = self.file_pointer.tell()
self.file_pointer.seek(cursor)
return ret
def close(self):
self.file_pointer.close()
self.feed_eof()
class read_chunks:
def __init__(self, read_size, fp):
self.done = False
self.read_size = read_size
self.fp = fp
async def __aiter__(self):
return self
async def __anext__(self):
if self.done:
raise StopAsyncIteration
return await self.get_chunk()
async def get_chunk(self):
while True:
chunk = self.fp.read(self.read_size)
if not chunk:
chunk = b''
self.done = True
return chunk
async def _read(self, read_size):
async for chunk in self.read_chunks(read_size, self.file_pointer):
if chunk == b'':
self.feed_eof()
return chunk
|
Update FileStreamReader to use async generator
|
Update FileStreamReader to use async generator
|
Python
|
apache-2.0
|
RCOSDP/waterbutler,TomBaxter/waterbutler,rdhyee/waterbutler,CenterForOpenScience/waterbutler,felliott/waterbutler,Johnetordoff/waterbutler
|
python
|
## Code Before:
import os
from waterbutler.core.streams import BaseStream
class FileStreamReader(BaseStream):
def __init__(self, file_pointer):
super().__init__()
self.file_gen = None
self.file_pointer = file_pointer
self.read_size = None
self.content_type = 'application/octet-stream'
@property
def size(self):
cursor = self.file_pointer.tell()
self.file_pointer.seek(0, os.SEEK_END)
ret = self.file_pointer.tell()
self.file_pointer.seek(cursor)
return ret
def close(self):
self.file_pointer.close()
self.feed_eof()
def read_as_gen(self):
self.file_pointer.seek(0)
while True:
chunk = self.file_pointer.read(self.read_size)
if not chunk:
self.feed_eof()
chunk = b''
yield chunk
async def _read(self, size):
self.file_gen = self.file_gen or self.read_as_gen()
self.read_size = size
return next(self.file_gen)
## Instruction:
Update FileStreamReader to use async generator
## Code After:
import os
# import asyncio
from waterbutler.core.streams import BaseStream
class FileStreamReader(BaseStream):
def __init__(self, file_pointer):
super().__init__()
self.file_gen = None
self.file_pointer = file_pointer
self.read_size = None
self.content_type = 'application/octet-stream'
@property
def size(self):
cursor = self.file_pointer.tell()
self.file_pointer.seek(0, os.SEEK_END)
ret = self.file_pointer.tell()
self.file_pointer.seek(cursor)
return ret
def close(self):
self.file_pointer.close()
self.feed_eof()
class read_chunks:
def __init__(self, read_size, fp):
self.done = False
self.read_size = read_size
self.fp = fp
async def __aiter__(self):
return self
async def __anext__(self):
if self.done:
raise StopAsyncIteration
return await self.get_chunk()
async def get_chunk(self):
while True:
chunk = self.fp.read(self.read_size)
if not chunk:
chunk = b''
self.done = True
return chunk
async def _read(self, read_size):
async for chunk in self.read_chunks(read_size, self.file_pointer):
if chunk == b'':
self.feed_eof()
return chunk
|
// ... existing code ...
import os
# import asyncio
from waterbutler.core.streams import BaseStream
// ... modified code ...
self.file_pointer.close()
self.feed_eof()
class read_chunks:
def __init__(self, read_size, fp):
self.done = False
self.read_size = read_size
self.fp = fp
async def __aiter__(self):
return self
async def __anext__(self):
if self.done:
raise StopAsyncIteration
return await self.get_chunk()
async def get_chunk(self):
while True:
chunk = self.fp.read(self.read_size)
if not chunk:
chunk = b''
self.done = True
return chunk
async def _read(self, read_size):
async for chunk in self.read_chunks(read_size, self.file_pointer):
if chunk == b'':
self.feed_eof()
return chunk
// ... rest of the code ...
|
234dd098ccca89c0a547f6d6cf5175a39b3b429b
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
import versioneer
setup(name='pycompmusic',
version=versioneer.get_version(),
description='Tools for playing with the compmusic collection',
author='CompMusic / MTG UPF',
url='http://compmusic.upf.edu',
install_requires=['musicbrainzngs', 'requests', 'six', 'eyed3'],
packages=find_packages(exclude=["test"]),
cmdclass=versioneer.get_cmdclass()
)
|
from setuptools import setup, find_packages
import versioneer
setup(name='pycompmusic',
version=versioneer.get_version(),
description='Tools for playing with the compmusic collection',
author='CompMusic / MTG UPF',
author_email='[email protected]',
url='http://compmusic.upf.edu',
install_requires=['musicbrainzngs', 'requests', 'six', 'eyed3'],
packages=find_packages(exclude=["test"]),
cmdclass=versioneer.get_cmdclass()
)
|
Add author info to package config
|
Add author info to package config
|
Python
|
agpl-3.0
|
MTG/pycompmusic
|
python
|
## Code Before:
from setuptools import setup, find_packages
import versioneer
setup(name='pycompmusic',
version=versioneer.get_version(),
description='Tools for playing with the compmusic collection',
author='CompMusic / MTG UPF',
url='http://compmusic.upf.edu',
install_requires=['musicbrainzngs', 'requests', 'six', 'eyed3'],
packages=find_packages(exclude=["test"]),
cmdclass=versioneer.get_cmdclass()
)
## Instruction:
Add author info to package config
## Code After:
from setuptools import setup, find_packages
import versioneer
setup(name='pycompmusic',
version=versioneer.get_version(),
description='Tools for playing with the compmusic collection',
author='CompMusic / MTG UPF',
author_email='[email protected]',
url='http://compmusic.upf.edu',
install_requires=['musicbrainzngs', 'requests', 'six', 'eyed3'],
packages=find_packages(exclude=["test"]),
cmdclass=versioneer.get_cmdclass()
)
|
// ... existing code ...
version=versioneer.get_version(),
description='Tools for playing with the compmusic collection',
author='CompMusic / MTG UPF',
author_email='[email protected]',
url='http://compmusic.upf.edu',
install_requires=['musicbrainzngs', 'requests', 'six', 'eyed3'],
packages=find_packages(exclude=["test"]),
// ... rest of the code ...
|
2e9b87a7409f1995f96867270361f23a9fc3d1ab
|
flaskext/clevercss.py
|
flaskext/clevercss.py
|
import os
import sys
import orig_clevercss
def clevercss(app):
@app.before_request
def _render_clever_css():
static_dir = app.root_path + app.static_path
clever_paths = []
for path, subdirs, filenames in os.walk(static_dir):
clever_paths.extend([
os.path.join(path, f)
for f in filenames if os.path.splitext(f)[1] == '.ccss'
])
for clever_path in clever_paths:
css_path = os.path.splitext(clever_path)[0] + '.css'
if not os.path.isfile(css_path):
css_mtime = -1
else:
css_mtime = os.path.getmtime(css_path)
clever_mtime = os.path.getmtime(clever_path)
if clever_mtime >= css_mtime:
sys.argv[1:] = [clever_path]
orig_clevercss.main()
|
import os
import sys
import orig_clevercss
def clevercss(app):
@app.before_request
def _render_clever_css():
static_dir = os.path.join(app.root_path, app._static_folder)
clever_paths = []
for path, subdirs, filenames in os.walk(static_dir):
clever_paths.extend([
os.path.join(path, f)
for f in filenames if os.path.splitext(f)[1] == '.ccss'
])
for clever_path in clever_paths:
css_path = os.path.splitext(clever_path)[0] + '.css'
if not os.path.isfile(css_path):
css_mtime = -1
else:
css_mtime = os.path.getmtime(css_path)
clever_mtime = os.path.getmtime(clever_path)
if clever_mtime >= css_mtime:
sys.argv[1:] = [clever_path]
orig_clevercss.main()
|
Fix for specifying the static directory in later versions of flask
|
Fix for specifying the static directory in later versions of flask
|
Python
|
mit
|
suzanshakya/flask-clevercss,suzanshakya/flask-clevercss
|
python
|
## Code Before:
import os
import sys
import orig_clevercss
def clevercss(app):
@app.before_request
def _render_clever_css():
static_dir = app.root_path + app.static_path
clever_paths = []
for path, subdirs, filenames in os.walk(static_dir):
clever_paths.extend([
os.path.join(path, f)
for f in filenames if os.path.splitext(f)[1] == '.ccss'
])
for clever_path in clever_paths:
css_path = os.path.splitext(clever_path)[0] + '.css'
if not os.path.isfile(css_path):
css_mtime = -1
else:
css_mtime = os.path.getmtime(css_path)
clever_mtime = os.path.getmtime(clever_path)
if clever_mtime >= css_mtime:
sys.argv[1:] = [clever_path]
orig_clevercss.main()
## Instruction:
Fix for specifying the static directory in later versions of flask
## Code After:
import os
import sys
import orig_clevercss
def clevercss(app):
@app.before_request
def _render_clever_css():
static_dir = os.path.join(app.root_path, app._static_folder)
clever_paths = []
for path, subdirs, filenames in os.walk(static_dir):
clever_paths.extend([
os.path.join(path, f)
for f in filenames if os.path.splitext(f)[1] == '.ccss'
])
for clever_path in clever_paths:
css_path = os.path.splitext(clever_path)[0] + '.css'
if not os.path.isfile(css_path):
css_mtime = -1
else:
css_mtime = os.path.getmtime(css_path)
clever_mtime = os.path.getmtime(clever_path)
if clever_mtime >= css_mtime:
sys.argv[1:] = [clever_path]
orig_clevercss.main()
|
...
def clevercss(app):
@app.before_request
def _render_clever_css():
static_dir = os.path.join(app.root_path, app._static_folder)
clever_paths = []
for path, subdirs, filenames in os.walk(static_dir):
...
|
2b37c13dcf9f8460bf86c4b9096dcc49aed72a44
|
src/lib/utils/rotate.h
|
src/lib/utils/rotate.h
|
/*
* Word Rotation Operations
* (C) 1999-2008 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#ifndef BOTAN_WORD_ROTATE_H__
#define BOTAN_WORD_ROTATE_H__
#include <botan/types.h>
namespace Botan {
/**
* Bit rotation left
* @param input the input word
* @param rot the number of bits to rotate
* @return input rotated left by rot bits
*/
template<typename T> inline T rotate_left(T input, size_t rot)
{
return (rot == 0) ? input : static_cast<T>((input << rot) | (input >> (8*sizeof(T)-rot)));;
}
/**
* Bit rotation right
* @param input the input word
* @param rot the number of bits to rotate
* @return input rotated right by rot bits
*/
template<typename T> inline T rotate_right(T input, size_t rot)
{
return (rot == 0) ? input : static_cast<T>((input >> rot) | (input << (8*sizeof(T)-rot)));
}
}
#endif
|
/*
* Word Rotation Operations
* (C) 1999-2008 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#ifndef BOTAN_WORD_ROTATE_H__
#define BOTAN_WORD_ROTATE_H__
#include <botan/types.h>
namespace Botan {
/**
* Bit rotation left
* @param input the input word
* @param rot the number of bits to rotate
* @return input rotated left by rot bits
*/
template<typename T> inline T rotate_left(T input, size_t rot)
{
rot %= 8 * sizeof(T);
return (rot == 0) ? input : static_cast<T>((input << rot) | (input >> (8*sizeof(T)-rot)));;
}
/**
* Bit rotation right
* @param input the input word
* @param rot the number of bits to rotate
* @return input rotated right by rot bits
*/
template<typename T> inline T rotate_right(T input, size_t rot)
{
rot %= 8 * sizeof(T);
return (rot == 0) ? input : static_cast<T>((input >> rot) | (input << (8*sizeof(T)-rot)));
}
}
#endif
|
Allow bit rotation by more than sizeof(T)*8 bits.
|
Allow bit rotation by more than sizeof(T)*8 bits.
Currently these functions will happily bit shift by >= sizeof(T)*8 bits.
However, this is undefined behavior, and results in unexpected results (0)
on at least one platform I've tested.
With this update, you can expect that rotate_left<uint32_t>(1, 32)==1
and rotate_right<uint32_t>(1, 32)==1.
|
C
|
bsd-2-clause
|
randombit/botan,webmaster128/botan,webmaster128/botan,randombit/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,randombit/botan
|
c
|
## Code Before:
/*
* Word Rotation Operations
* (C) 1999-2008 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#ifndef BOTAN_WORD_ROTATE_H__
#define BOTAN_WORD_ROTATE_H__
#include <botan/types.h>
namespace Botan {
/**
* Bit rotation left
* @param input the input word
* @param rot the number of bits to rotate
* @return input rotated left by rot bits
*/
template<typename T> inline T rotate_left(T input, size_t rot)
{
return (rot == 0) ? input : static_cast<T>((input << rot) | (input >> (8*sizeof(T)-rot)));;
}
/**
* Bit rotation right
* @param input the input word
* @param rot the number of bits to rotate
* @return input rotated right by rot bits
*/
template<typename T> inline T rotate_right(T input, size_t rot)
{
return (rot == 0) ? input : static_cast<T>((input >> rot) | (input << (8*sizeof(T)-rot)));
}
}
#endif
## Instruction:
Allow bit rotation by more than sizeof(T)*8 bits.
Currently these functions will happily bit shift by >= sizeof(T)*8 bits.
However, this is undefined behavior, and results in unexpected results (0)
on at least one platform I've tested.
With this update, you can expect that rotate_left<uint32_t>(1, 32)==1
and rotate_right<uint32_t>(1, 32)==1.
## Code After:
/*
* Word Rotation Operations
* (C) 1999-2008 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#ifndef BOTAN_WORD_ROTATE_H__
#define BOTAN_WORD_ROTATE_H__
#include <botan/types.h>
namespace Botan {
/**
* Bit rotation left
* @param input the input word
* @param rot the number of bits to rotate
* @return input rotated left by rot bits
*/
template<typename T> inline T rotate_left(T input, size_t rot)
{
rot %= 8 * sizeof(T);
return (rot == 0) ? input : static_cast<T>((input << rot) | (input >> (8*sizeof(T)-rot)));;
}
/**
* Bit rotation right
* @param input the input word
* @param rot the number of bits to rotate
* @return input rotated right by rot bits
*/
template<typename T> inline T rotate_right(T input, size_t rot)
{
rot %= 8 * sizeof(T);
return (rot == 0) ? input : static_cast<T>((input >> rot) | (input << (8*sizeof(T)-rot)));
}
}
#endif
|
...
*/
template<typename T> inline T rotate_left(T input, size_t rot)
{
rot %= 8 * sizeof(T);
return (rot == 0) ? input : static_cast<T>((input << rot) | (input >> (8*sizeof(T)-rot)));;
}
...
*/
template<typename T> inline T rotate_right(T input, size_t rot)
{
rot %= 8 * sizeof(T);
return (rot == 0) ? input : static_cast<T>((input >> rot) | (input << (8*sizeof(T)-rot)));
}
...
|
04a2d921dca91d30f1f4a683bb47b23f0421490c
|
samples/multi-kotlin-project-config-injection/build.gradle.kts
|
samples/multi-kotlin-project-config-injection/build.gradle.kts
|
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
buildscript {
repositories { gradleScriptKotlin() }
dependencies { classpath(kotlinModule("gradle-plugin")) }
}
allprojects {
group = "org.gradle.script.kotlin.samples.multiprojectci"
version = "1.0"
configure(listOf(repositories, buildscript.repositories)) {
gradleScriptKotlin()
}
}
// Configure all KotlinCompile tasks on each sub-project
subprojects {
tasks.withType<KotlinCompile> {
println("Configuring ${name} in project ${project.name}...")
kotlinOptions {
suppressWarnings = true
}
}
}
apply {
plugin("base")
}
dependencies {
// Make the root project archives configuration depend on every subproject
subprojects.forEach {
archives(it)
}
}
|
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
buildscript {
repositories { gradleScriptKotlin() }
dependencies { classpath(kotlinModule("gradle-plugin")) }
}
allprojects {
group = "org.gradle.script.kotlin.samples.multiprojectci"
version = "1.0"
configure(listOf(repositories, buildscript.repositories)) {
gradleScriptKotlin()
}
}
// Configure all KotlinCompile tasks on each sub-project
subprojects {
tasks.withType<KotlinCompile> {
println("Configuring ${name} in project ${project.name}...")
kotlinOptions.suppressWarnings = true
}
}
apply {
plugin("base")
}
dependencies {
// Make the root project archives configuration depend on every subproject
subprojects.forEach {
archives(it)
}
}
|
Revert sample to form compatible with dev version
|
Revert sample to form compatible with dev version
Just so we can run at least one successful benchmark on CI.
It will be reverted later.
|
Kotlin
|
apache-2.0
|
gradle/gradle-script-kotlin,blindpirate/gradle,gradle/gradle,gradle/gradle,robinverduijn/gradle,gradle/gradle-script-kotlin,robinverduijn/gradle,gradle/gradle,blindpirate/gradle,robinverduijn/gradle,gradle/gradle,robinverduijn/gradle,robinverduijn/gradle,blindpirate/gradle,robinverduijn/gradle,robinverduijn/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,robinverduijn/gradle,blindpirate/gradle,robinverduijn/gradle,blindpirate/gradle,blindpirate/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle,robinverduijn/gradle,gradle/gradle,blindpirate/gradle
|
kotlin
|
## Code Before:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
buildscript {
repositories { gradleScriptKotlin() }
dependencies { classpath(kotlinModule("gradle-plugin")) }
}
allprojects {
group = "org.gradle.script.kotlin.samples.multiprojectci"
version = "1.0"
configure(listOf(repositories, buildscript.repositories)) {
gradleScriptKotlin()
}
}
// Configure all KotlinCompile tasks on each sub-project
subprojects {
tasks.withType<KotlinCompile> {
println("Configuring ${name} in project ${project.name}...")
kotlinOptions {
suppressWarnings = true
}
}
}
apply {
plugin("base")
}
dependencies {
// Make the root project archives configuration depend on every subproject
subprojects.forEach {
archives(it)
}
}
## Instruction:
Revert sample to form compatible with dev version
Just so we can run at least one successful benchmark on CI.
It will be reverted later.
## Code After:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
buildscript {
repositories { gradleScriptKotlin() }
dependencies { classpath(kotlinModule("gradle-plugin")) }
}
allprojects {
group = "org.gradle.script.kotlin.samples.multiprojectci"
version = "1.0"
configure(listOf(repositories, buildscript.repositories)) {
gradleScriptKotlin()
}
}
// Configure all KotlinCompile tasks on each sub-project
subprojects {
tasks.withType<KotlinCompile> {
println("Configuring ${name} in project ${project.name}...")
kotlinOptions.suppressWarnings = true
}
}
apply {
plugin("base")
}
dependencies {
// Make the root project archives configuration depend on every subproject
subprojects.forEach {
archives(it)
}
}
|
# ... existing code ...
subprojects {
tasks.withType<KotlinCompile> {
println("Configuring ${name} in project ${project.name}...")
kotlinOptions.suppressWarnings = true
}
}
# ... rest of the code ...
|
ee74135a46ed1757a2f67e74a116a6ccfcdf7552
|
ReactAndroid/src/main/java/com/facebook/react/bridge/ReactBridge.java
|
ReactAndroid/src/main/java/com/facebook/react/bridge/ReactBridge.java
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.bridge;
import com.facebook.soloader.SoLoader;
public class ReactBridge {
private static boolean sDidInit = false;
public static void staticInit() {
// No locking required here, worst case we'll call into SoLoader twice
// which will do its own locking internally
if (!sDidInit) {
SoLoader.loadLibrary("reactnativejni");
sDidInit = true;
}
}
}
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.bridge;
import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE;
import com.facebook.soloader.SoLoader;
import com.facebook.systrace.Systrace;
public class ReactBridge {
private static boolean sDidInit = false;
public static void staticInit() {
// No locking required here, worst case we'll call into SoLoader twice
// which will do its own locking internally
if (!sDidInit) {
Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactBridge.staticInit::load:reactnativejni");
SoLoader.loadLibrary("reactnativejni");
sDidInit = true;
Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
}
}
}
|
Add tracing to when SO libraries are loaded
|
Add tracing to when SO libraries are loaded
Summary:
Currently, loading SO libraries is pretty expensive. While they are triggered due to accessing `ReadableNativeArray`. However, with preloader experiments, this block seems to move around and is loaded when the first dependent class loads it.
Also, as a part of D10108380, this will be moved again.
Adding a trace to keep track of where it moves.
Reviewed By: achen1
Differential Revision: D9890280
fbshipit-source-id: 4b331ef1d7e824935bf3708442537349d2d631d0
|
Java
|
bsd-3-clause
|
exponent/react-native,arthuralee/react-native,javache/react-native,exponent/react-native,pandiaraj44/react-native,janicduplessis/react-native,hoangpham95/react-native,pandiaraj44/react-native,facebook/react-native,exponent/react-native,facebook/react-native,exponentjs/react-native,hoangpham95/react-native,javache/react-native,janicduplessis/react-native,arthuralee/react-native,arthuralee/react-native,exponentjs/react-native,exponentjs/react-native,pandiaraj44/react-native,janicduplessis/react-native,hammerandchisel/react-native,myntra/react-native,javache/react-native,hoangpham95/react-native,hammerandchisel/react-native,myntra/react-native,hammerandchisel/react-native,pandiaraj44/react-native,hammerandchisel/react-native,myntra/react-native,hoangpham95/react-native,janicduplessis/react-native,janicduplessis/react-native,myntra/react-native,facebook/react-native,myntra/react-native,exponent/react-native,facebook/react-native,janicduplessis/react-native,janicduplessis/react-native,hammerandchisel/react-native,hoangpham95/react-native,javache/react-native,javache/react-native,facebook/react-native,facebook/react-native,arthuralee/react-native,myntra/react-native,facebook/react-native,exponent/react-native,exponentjs/react-native,hoangpham95/react-native,javache/react-native,hammerandchisel/react-native,exponentjs/react-native,javache/react-native,exponent/react-native,facebook/react-native,javache/react-native,pandiaraj44/react-native,hoangpham95/react-native,myntra/react-native,hammerandchisel/react-native,myntra/react-native,janicduplessis/react-native,exponentjs/react-native,myntra/react-native,hammerandchisel/react-native,exponentjs/react-native,pandiaraj44/react-native,exponentjs/react-native,pandiaraj44/react-native,pandiaraj44/react-native,javache/react-native,exponent/react-native,exponent/react-native,facebook/react-native,hoangpham95/react-native,arthuralee/react-native
|
java
|
## Code Before:
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.bridge;
import com.facebook.soloader.SoLoader;
public class ReactBridge {
private static boolean sDidInit = false;
public static void staticInit() {
// No locking required here, worst case we'll call into SoLoader twice
// which will do its own locking internally
if (!sDidInit) {
SoLoader.loadLibrary("reactnativejni");
sDidInit = true;
}
}
}
## Instruction:
Add tracing to when SO libraries are loaded
Summary:
Currently, loading SO libraries is pretty expensive. While they are triggered due to accessing `ReadableNativeArray`. However, with preloader experiments, this block seems to move around and is loaded when the first dependent class loads it.
Also, as a part of D10108380, this will be moved again.
Adding a trace to keep track of where it moves.
Reviewed By: achen1
Differential Revision: D9890280
fbshipit-source-id: 4b331ef1d7e824935bf3708442537349d2d631d0
## Code After:
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.bridge;
import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE;
import com.facebook.soloader.SoLoader;
import com.facebook.systrace.Systrace;
public class ReactBridge {
private static boolean sDidInit = false;
public static void staticInit() {
// No locking required here, worst case we'll call into SoLoader twice
// which will do its own locking internally
if (!sDidInit) {
Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactBridge.staticInit::load:reactnativejni");
SoLoader.loadLibrary("reactnativejni");
sDidInit = true;
Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
}
}
}
|
...
package com.facebook.react.bridge;
import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE;
import com.facebook.soloader.SoLoader;
import com.facebook.systrace.Systrace;
public class ReactBridge {
private static boolean sDidInit = false;
...
// No locking required here, worst case we'll call into SoLoader twice
// which will do its own locking internally
if (!sDidInit) {
Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactBridge.staticInit::load:reactnativejni");
SoLoader.loadLibrary("reactnativejni");
sDidInit = true;
Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
}
}
}
...
|
d569c69ea1a361ada0e09f2c58bd611b686d82e9
|
modules/dcc_chat.h
|
modules/dcc_chat.h
|
class dccChat : public Module {
public:
void onDCCReceive(std::string dccid, std::string message);
};
class dccSender : public Module {
public:
void dccSend(std::string dccid, std::string message);
};
|
class dccChat : public Module {
public:
virtual void onDCCReceive(std::string dccid, std::string message);
};
class dccSender : public Module {
public:
virtual void dccSend(std::string dccid, std::string message);
virtual bool hookDCCMessage(std::string modName, std::string hookMsg);
};
|
Fix those functions not being virtual.
|
Fix those functions not being virtual.
|
C
|
mit
|
ElementalAlchemist/RoBoBo,ElementalAlchemist/RoBoBo
|
c
|
## Code Before:
class dccChat : public Module {
public:
void onDCCReceive(std::string dccid, std::string message);
};
class dccSender : public Module {
public:
void dccSend(std::string dccid, std::string message);
};
## Instruction:
Fix those functions not being virtual.
## Code After:
class dccChat : public Module {
public:
virtual void onDCCReceive(std::string dccid, std::string message);
};
class dccSender : public Module {
public:
virtual void dccSend(std::string dccid, std::string message);
virtual bool hookDCCMessage(std::string modName, std::string hookMsg);
};
|
// ... existing code ...
class dccChat : public Module {
public:
virtual void onDCCReceive(std::string dccid, std::string message);
};
class dccSender : public Module {
public:
virtual void dccSend(std::string dccid, std::string message);
virtual bool hookDCCMessage(std::string modName, std::string hookMsg);
};
// ... rest of the code ...
|
26e0d89e5178fb05b95f56cbef58ac37bfa6f1d9
|
camera_opencv.py
|
camera_opencv.py
|
import cv2
from base_camera import BaseCamera
class Camera(BaseCamera):
video_source = 0
@staticmethod
def set_video_source(source):
Camera.video_source = source
@staticmethod
def frames():
camera = cv2.VideoCapture(Camera.video_source)
if not camera.isOpened():
raise RuntimeError('Could not start camera.')
while True:
# read current frame
_, img = camera.read()
# encode as a jpeg image and return it
yield cv2.imencode('.jpg', img)[1].tobytes()
|
import os
import cv2
from base_camera import BaseCamera
class Camera(BaseCamera):
video_source = 0
def __init__(self):
if os.environ.get('OPENCV_CAMERA_SOURCE'):
Camera.set_video_source(int(os.environ['OPENCV_CAMERA_SOURCE']))
super(Camera, self).__init__()
@staticmethod
def set_video_source(source):
Camera.video_source = source
@staticmethod
def frames():
camera = cv2.VideoCapture(Camera.video_source)
if not camera.isOpened():
raise RuntimeError('Could not start camera.')
while True:
# read current frame
_, img = camera.read()
# encode as a jpeg image and return it
yield cv2.imencode('.jpg', img)[1].tobytes()
|
Use OPENCV_CAMERA_SOURCE environment variable to set source
|
Use OPENCV_CAMERA_SOURCE environment variable to set source
|
Python
|
mit
|
miguelgrinberg/flask-video-streaming,miguelgrinberg/flask-video-streaming
|
python
|
## Code Before:
import cv2
from base_camera import BaseCamera
class Camera(BaseCamera):
video_source = 0
@staticmethod
def set_video_source(source):
Camera.video_source = source
@staticmethod
def frames():
camera = cv2.VideoCapture(Camera.video_source)
if not camera.isOpened():
raise RuntimeError('Could not start camera.')
while True:
# read current frame
_, img = camera.read()
# encode as a jpeg image and return it
yield cv2.imencode('.jpg', img)[1].tobytes()
## Instruction:
Use OPENCV_CAMERA_SOURCE environment variable to set source
## Code After:
import os
import cv2
from base_camera import BaseCamera
class Camera(BaseCamera):
video_source = 0
def __init__(self):
if os.environ.get('OPENCV_CAMERA_SOURCE'):
Camera.set_video_source(int(os.environ['OPENCV_CAMERA_SOURCE']))
super(Camera, self).__init__()
@staticmethod
def set_video_source(source):
Camera.video_source = source
@staticmethod
def frames():
camera = cv2.VideoCapture(Camera.video_source)
if not camera.isOpened():
raise RuntimeError('Could not start camera.')
while True:
# read current frame
_, img = camera.read()
# encode as a jpeg image and return it
yield cv2.imencode('.jpg', img)[1].tobytes()
|
# ... existing code ...
import os
import cv2
from base_camera import BaseCamera
# ... modified code ...
class Camera(BaseCamera):
video_source = 0
def __init__(self):
if os.environ.get('OPENCV_CAMERA_SOURCE'):
Camera.set_video_source(int(os.environ['OPENCV_CAMERA_SOURCE']))
super(Camera, self).__init__()
@staticmethod
def set_video_source(source):
# ... rest of the code ...
|
dd54e6b9aded46da7a74eede6f935b289a979912
|
WidgetTimeInput.h
|
WidgetTimeInput.h
|
/**
* @file WidgetTimeInput.h
* @author Volodymyr Shymanskyy
* @license This project is released under the MIT License (MIT)
* @copyright Copyright (c) 2015 Volodymyr Shymanskyy
* @date Aug 2016
* @brief
*
*/
#ifndef WidgetTimeInput_h
#define WidgetTimeInput_h
#include <Blynk/BlynkApi.h>
#include <utility/BlynkDateTime.h>
class TimeInputParam
{
public:
TimeInputParam(const BlynkParam& param)
: mStart (param[0].asLong())
, mStop (param[1].asLong())
{
mTZ = param[2].asLong();
}
BlynkDateTime& getStart() { return mStart; }
BlynkDateTime& getStop() { return mStop; }
long getTZ() const { return mTZ; }
private:
BlynkDateTime mStart;
BlynkDateTime mStop;
long mTZ;
};
#endif
|
/**
* @file WidgetTimeInput.h
* @author Volodymyr Shymanskyy
* @license This project is released under the MIT License (MIT)
* @copyright Copyright (c) 2015 Volodymyr Shymanskyy
* @date Aug 2016
* @brief
*
*/
#ifndef WidgetTimeInput_h
#define WidgetTimeInput_h
#include <Blynk/BlynkApi.h>
#include <utility/BlynkDateTime.h>
class TimeInputParam
{
public:
TimeInputParam(const BlynkParam& param)
{
if (strlen(param[0].asStr())) {
mStart = param[0].asLong();
}
if (strlen(param[1].asStr())) {
mStop = param[1].asLong();
}
mTZ = param[2].asLong();
}
BlynkTime& getStart() { return mStart; }
BlynkTime& getStop() { return mStop; }
long getTZ() const { return mTZ; }
private:
BlynkTime mStart;
BlynkTime mStop;
long mTZ;
};
#endif
|
Switch to Time instead of DateTime
|
Switch to Time instead of DateTime
|
C
|
mit
|
ivankravets/blynk-library,blynkkk/blynk-library,blynkkk/blynk-library,ivankravets/blynk-library,blynkkk/blynk-library,blynkkk/blynk-library,ivankravets/blynk-library,ivankravets/blynk-library,ivankravets/blynk-library,blynkkk/blynk-library
|
c
|
## Code Before:
/**
* @file WidgetTimeInput.h
* @author Volodymyr Shymanskyy
* @license This project is released under the MIT License (MIT)
* @copyright Copyright (c) 2015 Volodymyr Shymanskyy
* @date Aug 2016
* @brief
*
*/
#ifndef WidgetTimeInput_h
#define WidgetTimeInput_h
#include <Blynk/BlynkApi.h>
#include <utility/BlynkDateTime.h>
class TimeInputParam
{
public:
TimeInputParam(const BlynkParam& param)
: mStart (param[0].asLong())
, mStop (param[1].asLong())
{
mTZ = param[2].asLong();
}
BlynkDateTime& getStart() { return mStart; }
BlynkDateTime& getStop() { return mStop; }
long getTZ() const { return mTZ; }
private:
BlynkDateTime mStart;
BlynkDateTime mStop;
long mTZ;
};
#endif
## Instruction:
Switch to Time instead of DateTime
## Code After:
/**
* @file WidgetTimeInput.h
* @author Volodymyr Shymanskyy
* @license This project is released under the MIT License (MIT)
* @copyright Copyright (c) 2015 Volodymyr Shymanskyy
* @date Aug 2016
* @brief
*
*/
#ifndef WidgetTimeInput_h
#define WidgetTimeInput_h
#include <Blynk/BlynkApi.h>
#include <utility/BlynkDateTime.h>
class TimeInputParam
{
public:
TimeInputParam(const BlynkParam& param)
{
if (strlen(param[0].asStr())) {
mStart = param[0].asLong();
}
if (strlen(param[1].asStr())) {
mStop = param[1].asLong();
}
mTZ = param[2].asLong();
}
BlynkTime& getStart() { return mStart; }
BlynkTime& getStop() { return mStop; }
long getTZ() const { return mTZ; }
private:
BlynkTime mStart;
BlynkTime mStop;
long mTZ;
};
#endif
|
# ... existing code ...
public:
TimeInputParam(const BlynkParam& param)
{
if (strlen(param[0].asStr())) {
mStart = param[0].asLong();
}
if (strlen(param[1].asStr())) {
mStop = param[1].asLong();
}
mTZ = param[2].asLong();
}
BlynkTime& getStart() { return mStart; }
BlynkTime& getStop() { return mStop; }
long getTZ() const { return mTZ; }
private:
BlynkTime mStart;
BlynkTime mStop;
long mTZ;
};
# ... rest of the code ...
|
7dcd285bb9e1b48c70d39eb35d132277e4d8ee88
|
setup.py
|
setup.py
|
from __future__ import print_function
from setuptools import setup, find_packages
entry_points = """
[glue.plugins]
vispy_volume=glue_vispy_viewers.volume:setup
vispy_scatter=glue_vispy_viewers.scatter:setup
"""
# Add the following to the above entry points to enable the isosurface viewer
# vispy_isosurface=glue_vispy_viewers.isosurface:setup
try:
import pypandoc
LONG_DESCRIPTION = pypandoc.convert('README.md', 'rst')
except (IOError, ImportError):
with open('README.md') as infile:
LONG_DESCRIPTION = infile.read()
setup(name='glue-vispy-viewers',
version="0.2.dev0",
description='Vispy-based viewers for Glue',
long_description=LONG_DESCRIPTION,
url="https://github.com/glue-viz/glue-3d-viewer",
author='Penny Qian, Maxwell Tsai, and Thomas Robitaille',
author_email='[email protected]',
packages = find_packages(),
package_data={'glue_vispy_viewers.volume': ['*.ui'],
'glue_vispy_viewers.common': ['*.ui'],
'glue_vispy_viewers.isosurface': ['*.ui'],
'glue_vispy_viewers.scatter': ['*.ui']},
entry_points=entry_points
)
|
from __future__ import print_function
from setuptools import setup, find_packages
entry_points = """
[glue.plugins]
vispy_volume=glue_vispy_viewers.volume:setup
vispy_scatter=glue_vispy_viewers.scatter:setup
vispy_isosurface=glue_vispy_viewers.isosurface:setup
"""
# Add the following to the above entry points to enable the isosurface viewer
# vispy_isosurface=glue_vispy_viewers.isosurface:setup
try:
import pypandoc
LONG_DESCRIPTION = pypandoc.convert('README.md', 'rst')
except (IOError, ImportError):
with open('README.md') as infile:
LONG_DESCRIPTION = infile.read()
setup(name='glue-vispy-viewers',
version="0.2.dev0",
description='Vispy-based viewers for Glue',
long_description=LONG_DESCRIPTION,
url="https://github.com/glue-viz/glue-3d-viewer",
author='Penny Qian, Maxwell Tsai, and Thomas Robitaille',
author_email='[email protected]',
packages = find_packages(),
package_data={'glue_vispy_viewers.volume': ['*.ui'],
'glue_vispy_viewers.common': ['*.ui'],
'glue_vispy_viewers.isosurface': ['*.ui'],
'glue_vispy_viewers.scatter': ['*.ui']},
entry_points=entry_points
)
|
Enable Isosurface class by default
|
Enable Isosurface class by default
|
Python
|
bsd-2-clause
|
glue-viz/glue-3d-viewer,PennyQ/astro-vispy,PennyQ/glue-3d-viewer,glue-viz/glue-vispy-viewers,astrofrog/glue-vispy-viewers,astrofrog/glue-3d-viewer
|
python
|
## Code Before:
from __future__ import print_function
from setuptools import setup, find_packages
entry_points = """
[glue.plugins]
vispy_volume=glue_vispy_viewers.volume:setup
vispy_scatter=glue_vispy_viewers.scatter:setup
"""
# Add the following to the above entry points to enable the isosurface viewer
# vispy_isosurface=glue_vispy_viewers.isosurface:setup
try:
import pypandoc
LONG_DESCRIPTION = pypandoc.convert('README.md', 'rst')
except (IOError, ImportError):
with open('README.md') as infile:
LONG_DESCRIPTION = infile.read()
setup(name='glue-vispy-viewers',
version="0.2.dev0",
description='Vispy-based viewers for Glue',
long_description=LONG_DESCRIPTION,
url="https://github.com/glue-viz/glue-3d-viewer",
author='Penny Qian, Maxwell Tsai, and Thomas Robitaille',
author_email='[email protected]',
packages = find_packages(),
package_data={'glue_vispy_viewers.volume': ['*.ui'],
'glue_vispy_viewers.common': ['*.ui'],
'glue_vispy_viewers.isosurface': ['*.ui'],
'glue_vispy_viewers.scatter': ['*.ui']},
entry_points=entry_points
)
## Instruction:
Enable Isosurface class by default
## Code After:
from __future__ import print_function
from setuptools import setup, find_packages
entry_points = """
[glue.plugins]
vispy_volume=glue_vispy_viewers.volume:setup
vispy_scatter=glue_vispy_viewers.scatter:setup
vispy_isosurface=glue_vispy_viewers.isosurface:setup
"""
# Add the following to the above entry points to enable the isosurface viewer
# vispy_isosurface=glue_vispy_viewers.isosurface:setup
try:
import pypandoc
LONG_DESCRIPTION = pypandoc.convert('README.md', 'rst')
except (IOError, ImportError):
with open('README.md') as infile:
LONG_DESCRIPTION = infile.read()
setup(name='glue-vispy-viewers',
version="0.2.dev0",
description='Vispy-based viewers for Glue',
long_description=LONG_DESCRIPTION,
url="https://github.com/glue-viz/glue-3d-viewer",
author='Penny Qian, Maxwell Tsai, and Thomas Robitaille',
author_email='[email protected]',
packages = find_packages(),
package_data={'glue_vispy_viewers.volume': ['*.ui'],
'glue_vispy_viewers.common': ['*.ui'],
'glue_vispy_viewers.isosurface': ['*.ui'],
'glue_vispy_viewers.scatter': ['*.ui']},
entry_points=entry_points
)
|
# ... existing code ...
[glue.plugins]
vispy_volume=glue_vispy_viewers.volume:setup
vispy_scatter=glue_vispy_viewers.scatter:setup
vispy_isosurface=glue_vispy_viewers.isosurface:setup
"""
# Add the following to the above entry points to enable the isosurface viewer
# ... rest of the code ...
|
769c2c7be646091ca003605c6dde6747c92f73e8
|
lib/xray/xray_emulate_tsc.h
|
lib/xray/xray_emulate_tsc.h
|
//===-- xray_emulate_tsc.h --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of XRay, a dynamic runtime instrumentation system.
//
//===----------------------------------------------------------------------===//
#ifndef XRAY_EMULATE_TSC_H
#define XRAY_EMULATE_TSC_H
#include "sanitizer_common/sanitizer_internal_defs.h"
#include "xray_defs.h"
#include <cstdint>
#include <time.h>
namespace __xray {
static constexpr uint64_t NanosecondsPerSecond = 1000ULL * 1000 * 1000;
ALWAYS_INLINE uint64_t readTSC(uint8_t &CPU) XRAY_NEVER_INSTRUMENT {
timespec TS;
int result = clock_gettime(CLOCK_REALTIME, &TS);
if (result != 0) {
Report("clock_gettime(2) returned %d, errno=%d.", result, int(errno));
TS.tv_sec = 0;
TS.tv_nsec = 0;
}
CPU = 0;
return TS.tv_sec * NanosecondsPerSecond + TS.tv_nsec;
}
}
#endif // XRAY_EMULATE_TSC_H
|
//===-- xray_emulate_tsc.h --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of XRay, a dynamic runtime instrumentation system.
//
//===----------------------------------------------------------------------===//
#ifndef XRAY_EMULATE_TSC_H
#define XRAY_EMULATE_TSC_H
#include "sanitizer_common/sanitizer_internal_defs.h"
#include "xray_defs.h"
#include <cerrno>
#include <cstdint>
#include <time.h>
namespace __xray {
static constexpr uint64_t NanosecondsPerSecond = 1000ULL * 1000 * 1000;
ALWAYS_INLINE uint64_t readTSC(uint8_t &CPU) XRAY_NEVER_INSTRUMENT {
timespec TS;
int result = clock_gettime(CLOCK_REALTIME, &TS);
if (result != 0) {
Report("clock_gettime(2) returned %d, errno=%d.", result, int(errno));
TS.tv_sec = 0;
TS.tv_nsec = 0;
}
CPU = 0;
return TS.tv_sec * NanosecondsPerSecond + TS.tv_nsec;
}
}
#endif // XRAY_EMULATE_TSC_H
|
Fix missing include of <cerrno>
|
[XRay][compiler-rt] Fix missing include of <cerrno>
Futher attempt to un-break ARM and AArch64 build.
Follow-up on D25360.
git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@290083 91177308-0d34-0410-b5e6-96231b3b80d8
|
C
|
apache-2.0
|
llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt
|
c
|
## Code Before:
//===-- xray_emulate_tsc.h --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of XRay, a dynamic runtime instrumentation system.
//
//===----------------------------------------------------------------------===//
#ifndef XRAY_EMULATE_TSC_H
#define XRAY_EMULATE_TSC_H
#include "sanitizer_common/sanitizer_internal_defs.h"
#include "xray_defs.h"
#include <cstdint>
#include <time.h>
namespace __xray {
static constexpr uint64_t NanosecondsPerSecond = 1000ULL * 1000 * 1000;
ALWAYS_INLINE uint64_t readTSC(uint8_t &CPU) XRAY_NEVER_INSTRUMENT {
timespec TS;
int result = clock_gettime(CLOCK_REALTIME, &TS);
if (result != 0) {
Report("clock_gettime(2) returned %d, errno=%d.", result, int(errno));
TS.tv_sec = 0;
TS.tv_nsec = 0;
}
CPU = 0;
return TS.tv_sec * NanosecondsPerSecond + TS.tv_nsec;
}
}
#endif // XRAY_EMULATE_TSC_H
## Instruction:
[XRay][compiler-rt] Fix missing include of <cerrno>
Futher attempt to un-break ARM and AArch64 build.
Follow-up on D25360.
git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@290083 91177308-0d34-0410-b5e6-96231b3b80d8
## Code After:
//===-- xray_emulate_tsc.h --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of XRay, a dynamic runtime instrumentation system.
//
//===----------------------------------------------------------------------===//
#ifndef XRAY_EMULATE_TSC_H
#define XRAY_EMULATE_TSC_H
#include "sanitizer_common/sanitizer_internal_defs.h"
#include "xray_defs.h"
#include <cerrno>
#include <cstdint>
#include <time.h>
namespace __xray {
static constexpr uint64_t NanosecondsPerSecond = 1000ULL * 1000 * 1000;
ALWAYS_INLINE uint64_t readTSC(uint8_t &CPU) XRAY_NEVER_INSTRUMENT {
timespec TS;
int result = clock_gettime(CLOCK_REALTIME, &TS);
if (result != 0) {
Report("clock_gettime(2) returned %d, errno=%d.", result, int(errno));
TS.tv_sec = 0;
TS.tv_nsec = 0;
}
CPU = 0;
return TS.tv_sec * NanosecondsPerSecond + TS.tv_nsec;
}
}
#endif // XRAY_EMULATE_TSC_H
|
# ... existing code ...
#include "sanitizer_common/sanitizer_internal_defs.h"
#include "xray_defs.h"
#include <cerrno>
#include <cstdint>
#include <time.h>
# ... rest of the code ...
|
640ce1a3b4f9cca4ebcc10f3d62b1d4d995dd0c5
|
src/foremast/pipeline/create_pipeline_manual.py
|
src/foremast/pipeline/create_pipeline_manual.py
|
"""Create manual Pipeline for Spinnaker."""
from ..utils.lookups import FileLookup
from .create_pipeline import SpinnakerPipeline
class SpinnakerPipelineManual(SpinnakerPipeline):
"""Manual JSON configured Spinnaker Pipelines."""
def create_pipeline(self):
"""Use JSON files to create Pipelines."""
self.log.info('Uploading manual Pipelines: %s')
lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir)
for json_file in self.settings['pipeline']['pipeline_files']:
json_dict = lookup.json(filename=json_file)
json_dict['name'] = json_file
self.post_pipeline(json_dict)
return True
|
"""Create manual Pipeline for Spinnaker."""
from ..utils.lookups import FileLookup
from .clean_pipelines import delete_pipeline
from .create_pipeline import SpinnakerPipeline
class SpinnakerPipelineManual(SpinnakerPipeline):
"""Manual JSON configured Spinnaker Pipelines."""
def create_pipeline(self):
"""Use JSON files to create Pipelines."""
self.log.info('Uploading manual Pipelines: %s')
lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir)
for json_file in self.settings['pipeline']['pipeline_files']:
delete_pipeline(app=self.app_name, pipeline_name=json_file)
json_dict = lookup.json(filename=json_file)
json_dict['name'] = json_file
self.post_pipeline(json_dict)
return True
|
Delete manual Pipeline before creating
|
fix: Delete manual Pipeline before creating
See also: #72
|
Python
|
apache-2.0
|
gogoair/foremast,gogoair/foremast
|
python
|
## Code Before:
"""Create manual Pipeline for Spinnaker."""
from ..utils.lookups import FileLookup
from .create_pipeline import SpinnakerPipeline
class SpinnakerPipelineManual(SpinnakerPipeline):
"""Manual JSON configured Spinnaker Pipelines."""
def create_pipeline(self):
"""Use JSON files to create Pipelines."""
self.log.info('Uploading manual Pipelines: %s')
lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir)
for json_file in self.settings['pipeline']['pipeline_files']:
json_dict = lookup.json(filename=json_file)
json_dict['name'] = json_file
self.post_pipeline(json_dict)
return True
## Instruction:
fix: Delete manual Pipeline before creating
See also: #72
## Code After:
"""Create manual Pipeline for Spinnaker."""
from ..utils.lookups import FileLookup
from .clean_pipelines import delete_pipeline
from .create_pipeline import SpinnakerPipeline
class SpinnakerPipelineManual(SpinnakerPipeline):
"""Manual JSON configured Spinnaker Pipelines."""
def create_pipeline(self):
"""Use JSON files to create Pipelines."""
self.log.info('Uploading manual Pipelines: %s')
lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir)
for json_file in self.settings['pipeline']['pipeline_files']:
delete_pipeline(app=self.app_name, pipeline_name=json_file)
json_dict = lookup.json(filename=json_file)
json_dict['name'] = json_file
self.post_pipeline(json_dict)
return True
|
# ... existing code ...
"""Create manual Pipeline for Spinnaker."""
from ..utils.lookups import FileLookup
from .clean_pipelines import delete_pipeline
from .create_pipeline import SpinnakerPipeline
# ... modified code ...
lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir)
for json_file in self.settings['pipeline']['pipeline_files']:
delete_pipeline(app=self.app_name, pipeline_name=json_file)
json_dict = lookup.json(filename=json_file)
json_dict['name'] = json_file
self.post_pipeline(json_dict)
# ... rest of the code ...
|
342b576de5cc3fd0aad536171d68b414ffc0fc3d
|
libc/sys_io.c
|
libc/sys_io.c
|
void outb(uint16_t port, uint8_t value) {
asm volatile ("outb %1, %0" : : "dN" (port), "a" (value));
}
unsigned char inb(uint16_t port) {
unsigned char ret;
asm volatile ("inb %1, %0" : "=a" (ret) : "dN" (port));
return ret;
}
|
void outb(uint16_t port, uint8_t value) {
asm volatile ("outb %1, %0" : : "dN" (port), "a" (value));
}
unsigned char inb(uint16_t port) {
unsigned char ret;
asm volatile ("inb %1, %0" : "=a" (ret) : "dN" (port));
return ret;
}
void outl(uint16_t port, uint32_t value) {
asm volatile ("outl %1, %0" : : "dN" (port), "a" (value));
}
uint32_t inl(uint16_t port) {
uint32_t ret;
asm volatile ("inl %1, %0" : "=a" (ret) : "dN" (port));
return ret;
}
|
Add inl and outl functions
|
Add inl and outl functions
|
C
|
mit
|
simon-andrews/norby,simon-andrews/norby,simon-andrews/norby
|
c
|
## Code Before:
void outb(uint16_t port, uint8_t value) {
asm volatile ("outb %1, %0" : : "dN" (port), "a" (value));
}
unsigned char inb(uint16_t port) {
unsigned char ret;
asm volatile ("inb %1, %0" : "=a" (ret) : "dN" (port));
return ret;
}
## Instruction:
Add inl and outl functions
## Code After:
void outb(uint16_t port, uint8_t value) {
asm volatile ("outb %1, %0" : : "dN" (port), "a" (value));
}
unsigned char inb(uint16_t port) {
unsigned char ret;
asm volatile ("inb %1, %0" : "=a" (ret) : "dN" (port));
return ret;
}
void outl(uint16_t port, uint32_t value) {
asm volatile ("outl %1, %0" : : "dN" (port), "a" (value));
}
uint32_t inl(uint16_t port) {
uint32_t ret;
asm volatile ("inl %1, %0" : "=a" (ret) : "dN" (port));
return ret;
}
|
# ... existing code ...
asm volatile ("inb %1, %0" : "=a" (ret) : "dN" (port));
return ret;
}
void outl(uint16_t port, uint32_t value) {
asm volatile ("outl %1, %0" : : "dN" (port), "a" (value));
}
uint32_t inl(uint16_t port) {
uint32_t ret;
asm volatile ("inl %1, %0" : "=a" (ret) : "dN" (port));
return ret;
}
# ... rest of the code ...
|
28bd2f6c727644858f497d8e68cb5c64ceb603fe
|
jpa-model/src/main/java/org/ihtsdo/otf/mapping/rf2/jpa/AbstractDescriptionRefSetMember.java
|
jpa-model/src/main/java/org/ihtsdo/otf/mapping/rf2/jpa/AbstractDescriptionRefSetMember.java
|
package org.ihtsdo.otf.mapping.rf2.jpa;
import org.hibernate.search.annotations.ContainedIn;
import com.fasterxml.jackson.annotation.JsonBackReference;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlIDREF;
import org.hibernate.envers.Audited;
import org.ihtsdo.otf.mapping.rf2.Description;
import org.ihtsdo.otf.mapping.rf2.DescriptionRefSetMember;
/**
* Abstract implementation of {@link DescriptionRefSetMember}.
*/
@MappedSuperclass
@Audited
public abstract class AbstractDescriptionRefSetMember extends
AbstractRefSetMember implements DescriptionRefSetMember {
@ManyToOne(targetEntity=DescriptionJpa.class)
/* *//** The Description associated with this element *//*
@ManyToOne(cascade = {
CascadeType.PERSIST, CascadeType.MERGE
}, targetEntity=DescriptionJpa.class)*/
@JsonBackReference
@ContainedIn
private Description description;
/**
* {@inheritDoc}
*/
@Override
@XmlIDREF
@XmlAttribute
public DescriptionJpa getDescription() {
return (DescriptionJpa)this.description;
}
/**
* {@inheritDoc}
*/
@Override
public void setDescription(Description description) {
this.description = description;
}
}
|
package org.ihtsdo.otf.mapping.rf2.jpa;
import org.hibernate.search.annotations.ContainedIn;
import com.fasterxml.jackson.annotation.JsonBackReference;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlIDREF;
import org.hibernate.envers.Audited;
import org.ihtsdo.otf.mapping.rf2.Description;
import org.ihtsdo.otf.mapping.rf2.DescriptionRefSetMember;
/**
* Abstract implementation of {@link DescriptionRefSetMember}.
*/
@MappedSuperclass
@Audited
public abstract class AbstractDescriptionRefSetMember extends
AbstractRefSetMember implements DescriptionRefSetMember {
@ManyToOne(targetEntity=DescriptionJpa.class, optional=false)
/* *//** The Description associated with this element *//*
@ManyToOne(cascade = {
CascadeType.PERSIST, CascadeType.MERGE
}, targetEntity=DescriptionJpa.class)*/
@JsonBackReference
@ContainedIn
private Description description;
/**
* {@inheritDoc}
*/
@Override
@XmlIDREF
@XmlAttribute
public DescriptionJpa getDescription() {
return (DescriptionJpa)this.description;
}
/**
* {@inheritDoc}
*/
@Override
public void setDescription(Description description) {
this.description = description;
}
}
|
Add another optional=false for the description refset member.
|
Add another optional=false for the description refset member.
|
Java
|
apache-2.0
|
IHTSDO/OTF-Mapping-Service,IHTSDO/OTF-Mapping-Service,IHTSDO/OTF-Mapping-Service,IHTSDO/OTF-Mapping-Service,IHTSDO/OTF-Mapping-Service,IHTSDO/OTF-Mapping-Service
|
java
|
## Code Before:
package org.ihtsdo.otf.mapping.rf2.jpa;
import org.hibernate.search.annotations.ContainedIn;
import com.fasterxml.jackson.annotation.JsonBackReference;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlIDREF;
import org.hibernate.envers.Audited;
import org.ihtsdo.otf.mapping.rf2.Description;
import org.ihtsdo.otf.mapping.rf2.DescriptionRefSetMember;
/**
* Abstract implementation of {@link DescriptionRefSetMember}.
*/
@MappedSuperclass
@Audited
public abstract class AbstractDescriptionRefSetMember extends
AbstractRefSetMember implements DescriptionRefSetMember {
@ManyToOne(targetEntity=DescriptionJpa.class)
/* *//** The Description associated with this element *//*
@ManyToOne(cascade = {
CascadeType.PERSIST, CascadeType.MERGE
}, targetEntity=DescriptionJpa.class)*/
@JsonBackReference
@ContainedIn
private Description description;
/**
* {@inheritDoc}
*/
@Override
@XmlIDREF
@XmlAttribute
public DescriptionJpa getDescription() {
return (DescriptionJpa)this.description;
}
/**
* {@inheritDoc}
*/
@Override
public void setDescription(Description description) {
this.description = description;
}
}
## Instruction:
Add another optional=false for the description refset member.
## Code After:
package org.ihtsdo.otf.mapping.rf2.jpa;
import org.hibernate.search.annotations.ContainedIn;
import com.fasterxml.jackson.annotation.JsonBackReference;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlIDREF;
import org.hibernate.envers.Audited;
import org.ihtsdo.otf.mapping.rf2.Description;
import org.ihtsdo.otf.mapping.rf2.DescriptionRefSetMember;
/**
* Abstract implementation of {@link DescriptionRefSetMember}.
*/
@MappedSuperclass
@Audited
public abstract class AbstractDescriptionRefSetMember extends
AbstractRefSetMember implements DescriptionRefSetMember {
@ManyToOne(targetEntity=DescriptionJpa.class, optional=false)
/* *//** The Description associated with this element *//*
@ManyToOne(cascade = {
CascadeType.PERSIST, CascadeType.MERGE
}, targetEntity=DescriptionJpa.class)*/
@JsonBackReference
@ContainedIn
private Description description;
/**
* {@inheritDoc}
*/
@Override
@XmlIDREF
@XmlAttribute
public DescriptionJpa getDescription() {
return (DescriptionJpa)this.description;
}
/**
* {@inheritDoc}
*/
@Override
public void setDescription(Description description) {
this.description = description;
}
}
|
# ... existing code ...
public abstract class AbstractDescriptionRefSetMember extends
AbstractRefSetMember implements DescriptionRefSetMember {
@ManyToOne(targetEntity=DescriptionJpa.class, optional=false)
/* *//** The Description associated with this element *//*
@ManyToOne(cascade = {
CascadeType.PERSIST, CascadeType.MERGE
# ... rest of the code ...
|
f1279f1446c3a6643ca338c4ac9eaaa565ff37b8
|
app/src/main/java/com/tristanwiley/chatse/extensions/ImageViewExtensions.kt
|
app/src/main/java/com/tristanwiley/chatse/extensions/ImageViewExtensions.kt
|
package com.tristanwiley.chatse.extensions
import android.widget.ImageView
import com.koushikdutta.ion.Ion
fun ImageView.loadUrl(url: String) {
Ion.with(context).load(url).intoImageView(this)
}
|
package com.tristanwiley.chatse.extensions
import android.widget.ImageView
import com.bumptech.glide.Glide
fun ImageView.loadUrl(url: String) {
Glide.with(this).load(url).into(this)
}
|
Use Glide to load images instead Ion
|
Use Glide to load images instead Ion
|
Kotlin
|
apache-2.0
|
room-15/ChatSE,room-15/ChatSE
|
kotlin
|
## Code Before:
package com.tristanwiley.chatse.extensions
import android.widget.ImageView
import com.koushikdutta.ion.Ion
fun ImageView.loadUrl(url: String) {
Ion.with(context).load(url).intoImageView(this)
}
## Instruction:
Use Glide to load images instead Ion
## Code After:
package com.tristanwiley.chatse.extensions
import android.widget.ImageView
import com.bumptech.glide.Glide
fun ImageView.loadUrl(url: String) {
Glide.with(this).load(url).into(this)
}
|
...
package com.tristanwiley.chatse.extensions
import android.widget.ImageView
import com.bumptech.glide.Glide
fun ImageView.loadUrl(url: String) {
Glide.with(this).load(url).into(this)
}
...
|
384f7a8da21ca5e4ffa529e0e5f9407ce2ec0142
|
backend/unichat/models/user.py
|
backend/unichat/models/user.py
|
from __future__ import unicode_literals
from django.db import models
class User(models.Model):
MALE = -1
UNDEFINED = 0
FEMALE = 1
GENDER_CHOICES = (
(MALE, 'Male'),
(UNDEFINED, 'Undefined'),
(FEMALE, 'Female')
)
school = models.ForeignKey('unichat.School')
email = models.EmailField(
unique=True,
help_text=("The user's academic email.")
)
password = models.CharField(
max_length=100,
help_text=("The user's password.")
)
gender = models.IntegerField(
default=0,
choices=GENDER_CHOICES,
help_text=("The user's gender, by default UNDEFINED, unless otherwise "
"explicitly specified by the user.")
)
interestedInGender = models.IntegerField(
default=0,
choices=GENDER_CHOICES,
help_text=("The gender that the user is interested in talking to, by "
"default UNDEFINED.")
)
interestedInSchools = models.ManyToManyField('unichat.School', related_name='user_interested_schools')
cookie = models.CharField(
default='',
max_length=100,
db_index=True,
help_text=("The user's active cookie.")
)
|
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from .managers import UserManager
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
unique=True,
help_text=("The user's academic email.")
)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
class Meta:
verbose_name = 'user'
verbose_name_plural = 'users'
date_joined = models.DateTimeField(
auto_now_add=True,
help_text=("The date the user joined")
)
is_active = models.BooleanField(
default=True,
help_text=("The user active state")
)
MALE = -1
UNDEFINED = 0
FEMALE = 1
GENDER_CHOICES = (
(MALE, 'Male'),
(UNDEFINED, 'Undefined'),
(FEMALE, 'Female')
)
school = models.ForeignKey('unichat.School')
gender = models.IntegerField(
default=0,
choices=GENDER_CHOICES,
help_text=("The user's gender, by default UNDEFINED, unless otherwise "
"explicitly specified by the user.")
)
interestedInGender = models.IntegerField(
default=0,
choices=GENDER_CHOICES,
help_text=("The gender that the user is interested in talking to, by "
"default UNDEFINED.")
)
interestedInSchools = models.ManyToManyField('unichat.School', related_name='user_interested_schools')
|
Change User to use Django's AbstractBaseUser
|
Change User to use Django's AbstractBaseUser
|
Python
|
mit
|
dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet
|
python
|
## Code Before:
from __future__ import unicode_literals
from django.db import models
class User(models.Model):
MALE = -1
UNDEFINED = 0
FEMALE = 1
GENDER_CHOICES = (
(MALE, 'Male'),
(UNDEFINED, 'Undefined'),
(FEMALE, 'Female')
)
school = models.ForeignKey('unichat.School')
email = models.EmailField(
unique=True,
help_text=("The user's academic email.")
)
password = models.CharField(
max_length=100,
help_text=("The user's password.")
)
gender = models.IntegerField(
default=0,
choices=GENDER_CHOICES,
help_text=("The user's gender, by default UNDEFINED, unless otherwise "
"explicitly specified by the user.")
)
interestedInGender = models.IntegerField(
default=0,
choices=GENDER_CHOICES,
help_text=("The gender that the user is interested in talking to, by "
"default UNDEFINED.")
)
interestedInSchools = models.ManyToManyField('unichat.School', related_name='user_interested_schools')
cookie = models.CharField(
default='',
max_length=100,
db_index=True,
help_text=("The user's active cookie.")
)
## Instruction:
Change User to use Django's AbstractBaseUser
## Code After:
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from .managers import UserManager
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
unique=True,
help_text=("The user's academic email.")
)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
class Meta:
verbose_name = 'user'
verbose_name_plural = 'users'
date_joined = models.DateTimeField(
auto_now_add=True,
help_text=("The date the user joined")
)
is_active = models.BooleanField(
default=True,
help_text=("The user active state")
)
MALE = -1
UNDEFINED = 0
FEMALE = 1
GENDER_CHOICES = (
(MALE, 'Male'),
(UNDEFINED, 'Undefined'),
(FEMALE, 'Female')
)
school = models.ForeignKey('unichat.School')
gender = models.IntegerField(
default=0,
choices=GENDER_CHOICES,
help_text=("The user's gender, by default UNDEFINED, unless otherwise "
"explicitly specified by the user.")
)
interestedInGender = models.IntegerField(
default=0,
choices=GENDER_CHOICES,
help_text=("The gender that the user is interested in talking to, by "
"default UNDEFINED.")
)
interestedInSchools = models.ManyToManyField('unichat.School', related_name='user_interested_schools')
|
// ... existing code ...
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from .managers import UserManager
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
unique=True,
help_text=("The user's academic email.")
)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
class Meta:
verbose_name = 'user'
verbose_name_plural = 'users'
date_joined = models.DateTimeField(
auto_now_add=True,
help_text=("The date the user joined")
)
is_active = models.BooleanField(
default=True,
help_text=("The user active state")
)
MALE = -1
UNDEFINED = 0
FEMALE = 1
// ... modified code ...
)
school = models.ForeignKey('unichat.School')
gender = models.IntegerField(
default=0,
...
)
interestedInSchools = models.ManyToManyField('unichat.School', related_name='user_interested_schools')
// ... rest of the code ...
|
287e33837692871a59192a7498bffc0d22ffe9ba
|
bndtools.builder/src/org/bndtools/builder/BuilderPlugin.java
|
bndtools.builder/src/org/bndtools/builder/BuilderPlugin.java
|
package org.bndtools.builder;
import org.osgi.framework.BundleContext;
public class BuilderPlugin extends org.eclipse.core.runtime.Plugin {
private static BuilderPlugin instance = null;
public static BuilderPlugin getInstance() {
synchronized (BuilderPlugin.class) {
return instance;
}
}
public void start(BundleContext context) throws Exception {
super.start(context);
synchronized (BuilderPlugin.class) {
instance = this;
}
}
public void stop(BundleContext context) throws Exception {
synchronized (BuilderPlugin.class) {
instance = null;
}
super.stop(context);
}
}
|
package org.bndtools.builder;
import org.osgi.framework.BundleContext;
public class BuilderPlugin extends org.eclipse.core.runtime.Plugin {
private static BuilderPlugin instance = null;
public static BuilderPlugin getInstance() {
synchronized (BuilderPlugin.class) {
return instance;
}
}
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
synchronized (BuilderPlugin.class) {
instance = this;
}
}
@Override
public void stop(BundleContext context) throws Exception {
synchronized (BuilderPlugin.class) {
instance = null;
}
super.stop(context);
}
}
|
Add 2 missing @Override annotations
|
Add 2 missing @Override annotations
Signed-off-by: Ferry Huberts <[email protected]>
|
Java
|
epl-1.0
|
bndtools/bndtools,njbartlett/bndtools,grfield/bndtools,bjhargrave/bndtools,bndtools/bndtools,wodencafe/bndtools,pkriens/bndtools,lostiniceland/bndtools,seanbright/bndtools,grfield/bndtools,psoreide/bnd,timothyjward/bndtools,bndtools/bndtools,timothyjward/bndtools,bjhargrave/bndtools,wodencafe/bndtools,bjhargrave/bndtools,lostiniceland/bndtools,njbartlett/bndtools,lostiniceland/bndtools,bjhargrave/bndtools,pkriens/bndtools,pkriens/bndtools,bndtools/bndtools,lostiniceland/bndtools,timothyjward/bndtools,timothyjward/bndtools,wodencafe/bndtools,psoreide/bnd,njbartlett/bndtools,bndtools/bndtools,lostiniceland/bndtools,psoreide/bnd,njbartlett/bndtools,bjhargrave/bndtools,seanbright/bndtools,pkriens/bndtools,wodencafe/bndtools,pkriens/bndtools,grfield/bndtools,bjhargrave/bndtools,njbartlett/bndtools,seanbright/bndtools,wodencafe/bndtools,pkriens/bndtools,timothyjward/bndtools,njbartlett/bndtools,grfield/bndtools,wodencafe/bndtools,seanbright/bndtools,grfield/bndtools,lostiniceland/bndtools,seanbright/bndtools
|
java
|
## Code Before:
package org.bndtools.builder;
import org.osgi.framework.BundleContext;
public class BuilderPlugin extends org.eclipse.core.runtime.Plugin {
private static BuilderPlugin instance = null;
public static BuilderPlugin getInstance() {
synchronized (BuilderPlugin.class) {
return instance;
}
}
public void start(BundleContext context) throws Exception {
super.start(context);
synchronized (BuilderPlugin.class) {
instance = this;
}
}
public void stop(BundleContext context) throws Exception {
synchronized (BuilderPlugin.class) {
instance = null;
}
super.stop(context);
}
}
## Instruction:
Add 2 missing @Override annotations
Signed-off-by: Ferry Huberts <[email protected]>
## Code After:
package org.bndtools.builder;
import org.osgi.framework.BundleContext;
public class BuilderPlugin extends org.eclipse.core.runtime.Plugin {
private static BuilderPlugin instance = null;
public static BuilderPlugin getInstance() {
synchronized (BuilderPlugin.class) {
return instance;
}
}
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
synchronized (BuilderPlugin.class) {
instance = this;
}
}
@Override
public void stop(BundleContext context) throws Exception {
synchronized (BuilderPlugin.class) {
instance = null;
}
super.stop(context);
}
}
|
# ... existing code ...
public class BuilderPlugin extends org.eclipse.core.runtime.Plugin {
private static BuilderPlugin instance = null;
public static BuilderPlugin getInstance() {
synchronized (BuilderPlugin.class) {
return instance;
}
}
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
synchronized (BuilderPlugin.class) {
instance = this;
}
}
@Override
public void stop(BundleContext context) throws Exception {
synchronized (BuilderPlugin.class) {
instance = null;
}
super.stop(context);
}
}
# ... rest of the code ...
|
521ebf29990de4d997c90f4168ea300d75776cfc
|
components/utilities.py
|
components/utilities.py
|
"""Utilities for general operations."""
def IsNumeric(num_str):
try:
val = int(num_str)
except ValueError:
return False
else:
return True
|
"""Utilities for general operations."""
def IsNumeric(num_str):
try:
val = int(num_str)
except ValueError:
return False
else:
return True
def GuaranteeUnicode(obj):
if type(obj) == unicode:
return obj
elif type(obj) == str:
return unicode(obj, "utf-8")
else:
return unicode(str(obj), "utf-8")
|
Add GuranteeUnicode function which always returns a unicode object
|
Add GuranteeUnicode function which always returns a unicode object
|
Python
|
mit
|
lnishan/SQLGitHub
|
python
|
## Code Before:
"""Utilities for general operations."""
def IsNumeric(num_str):
try:
val = int(num_str)
except ValueError:
return False
else:
return True
## Instruction:
Add GuranteeUnicode function which always returns a unicode object
## Code After:
"""Utilities for general operations."""
def IsNumeric(num_str):
try:
val = int(num_str)
except ValueError:
return False
else:
return True
def GuaranteeUnicode(obj):
if type(obj) == unicode:
return obj
elif type(obj) == str:
return unicode(obj, "utf-8")
else:
return unicode(str(obj), "utf-8")
|
# ... existing code ...
return False
else:
return True
def GuaranteeUnicode(obj):
if type(obj) == unicode:
return obj
elif type(obj) == str:
return unicode(obj, "utf-8")
else:
return unicode(str(obj), "utf-8")
# ... rest of the code ...
|
03b0df95cdef76fcdbad84bb10817733bd03220f
|
test/CodeGen/unwind-attr.c
|
test/CodeGen/unwind-attr.c
|
// RUN: %clang_cc1 -fexceptions -emit-llvm -o - %s | FileCheck %s
// RUN: %clang_cc1 -emit-llvm -o - %s | FileCheck -check-prefix NOEXC %s
int opaque();
// CHECK: define [[INT:i.*]] @test0() {
// CHECK-NOEXC: define [[INT:i.*]] @test0() nounwind {
int test0(void) {
return opaque();
}
// <rdar://problem/8087431>: locally infer nounwind at -O0
// CHECK: define [[INT:i.*]] @test1() nounwind {
// CHECK-NOEXC: define [[INT:i.*]] @test1() nounwind {
int test1(void) {
}
|
// RUN: %clang_cc1 -fexceptions -emit-llvm -o - %s | FileCheck %s
// RUN: %clang_cc1 -emit-llvm -o - %s | FileCheck -check-prefix NOEXC %s
int opaque();
// CHECK: define [[INT:i.*]] @test0() {
// CHECK-NOEXC: define [[INT:i.*]] @test0() nounwind {
int test0(void) {
return opaque();
}
// <rdar://problem/8087431>: locally infer nounwind at -O0
// CHECK: define [[INT:i.*]] @test1() nounwind {
// CHECK-NOEXC: define [[INT:i.*]] @test1() nounwind {
int test1(void) {
return 0;
}
|
Fix a warning on a test.
|
Fix a warning on a test.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@110165 91177308-0d34-0410-b5e6-96231b3b80d8
|
C
|
apache-2.0
|
llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang
|
c
|
## Code Before:
// RUN: %clang_cc1 -fexceptions -emit-llvm -o - %s | FileCheck %s
// RUN: %clang_cc1 -emit-llvm -o - %s | FileCheck -check-prefix NOEXC %s
int opaque();
// CHECK: define [[INT:i.*]] @test0() {
// CHECK-NOEXC: define [[INT:i.*]] @test0() nounwind {
int test0(void) {
return opaque();
}
// <rdar://problem/8087431>: locally infer nounwind at -O0
// CHECK: define [[INT:i.*]] @test1() nounwind {
// CHECK-NOEXC: define [[INT:i.*]] @test1() nounwind {
int test1(void) {
}
## Instruction:
Fix a warning on a test.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@110165 91177308-0d34-0410-b5e6-96231b3b80d8
## Code After:
// RUN: %clang_cc1 -fexceptions -emit-llvm -o - %s | FileCheck %s
// RUN: %clang_cc1 -emit-llvm -o - %s | FileCheck -check-prefix NOEXC %s
int opaque();
// CHECK: define [[INT:i.*]] @test0() {
// CHECK-NOEXC: define [[INT:i.*]] @test0() nounwind {
int test0(void) {
return opaque();
}
// <rdar://problem/8087431>: locally infer nounwind at -O0
// CHECK: define [[INT:i.*]] @test1() nounwind {
// CHECK-NOEXC: define [[INT:i.*]] @test1() nounwind {
int test1(void) {
return 0;
}
|
# ... existing code ...
// CHECK: define [[INT:i.*]] @test1() nounwind {
// CHECK-NOEXC: define [[INT:i.*]] @test1() nounwind {
int test1(void) {
return 0;
}
# ... rest of the code ...
|
b6208c1f9b6f0afca1dff40a66d2c915594b1946
|
blaze/io/server/tests/start_simple_server.py
|
blaze/io/server/tests/start_simple_server.py
|
import sys, os
import blaze
from blaze.io.server.app import app
blaze.catalog.load_config(sys.argv[1])
app.run(port=int(sys.argv[2]), use_reloader=False)
|
import sys, os
if os.name == 'nt':
old_excepthook = sys.excepthook
# Exclude this from our autogenerated API docs.
undoc = lambda func: func
@undoc
def gui_excepthook(exctype, value, tb):
try:
import ctypes, traceback
MB_ICONERROR = 0x00000010
title = u'Error starting test Blaze server'
msg = u''.join(traceback.format_exception(exctype, value, tb))
ctypes.windll.user32.MessageBoxW(0, msg, title, MB_ICONERROR)
finally:
# Also call the old exception hook to let it do
# its thing too.
old_excepthook(exctype, value, tb)
sys.excepthook = gui_excepthook
import blaze
from blaze.io.server.app import app
blaze.catalog.load_config(sys.argv[1])
app.run(port=int(sys.argv[2]), use_reloader=False)
|
Add exception hook to help diagnose server test errors in python3 gui mode
|
Add exception hook to help diagnose server test errors in python3 gui mode
|
Python
|
bsd-3-clause
|
caseyclements/blaze,dwillmer/blaze,jcrist/blaze,mrocklin/blaze,cowlicks/blaze,ContinuumIO/blaze,jcrist/blaze,xlhtc007/blaze,FrancescAlted/blaze,aterrel/blaze,nkhuyu/blaze,AbhiAgarwal/blaze,markflorisson/blaze-core,nkhuyu/blaze,FrancescAlted/blaze,ChinaQuants/blaze,markflorisson/blaze-core,alexmojaki/blaze,alexmojaki/blaze,jdmcbr/blaze,mrocklin/blaze,AbhiAgarwal/blaze,maxalbert/blaze,dwillmer/blaze,markflorisson/blaze-core,AbhiAgarwal/blaze,scls19fr/blaze,LiaoPan/blaze,scls19fr/blaze,mwiebe/blaze,aterrel/blaze,xlhtc007/blaze,aterrel/blaze,ContinuumIO/blaze,AbhiAgarwal/blaze,ChinaQuants/blaze,jdmcbr/blaze,cpcloud/blaze,LiaoPan/blaze,maxalbert/blaze,cpcloud/blaze,cowlicks/blaze,mwiebe/blaze,mwiebe/blaze,markflorisson/blaze-core,FrancescAlted/blaze,caseyclements/blaze,mwiebe/blaze,FrancescAlted/blaze
|
python
|
## Code Before:
import sys, os
import blaze
from blaze.io.server.app import app
blaze.catalog.load_config(sys.argv[1])
app.run(port=int(sys.argv[2]), use_reloader=False)
## Instruction:
Add exception hook to help diagnose server test errors in python3 gui mode
## Code After:
import sys, os
if os.name == 'nt':
old_excepthook = sys.excepthook
# Exclude this from our autogenerated API docs.
undoc = lambda func: func
@undoc
def gui_excepthook(exctype, value, tb):
try:
import ctypes, traceback
MB_ICONERROR = 0x00000010
title = u'Error starting test Blaze server'
msg = u''.join(traceback.format_exception(exctype, value, tb))
ctypes.windll.user32.MessageBoxW(0, msg, title, MB_ICONERROR)
finally:
# Also call the old exception hook to let it do
# its thing too.
old_excepthook(exctype, value, tb)
sys.excepthook = gui_excepthook
import blaze
from blaze.io.server.app import app
blaze.catalog.load_config(sys.argv[1])
app.run(port=int(sys.argv[2]), use_reloader=False)
|
// ... existing code ...
import sys, os
if os.name == 'nt':
old_excepthook = sys.excepthook
# Exclude this from our autogenerated API docs.
undoc = lambda func: func
@undoc
def gui_excepthook(exctype, value, tb):
try:
import ctypes, traceback
MB_ICONERROR = 0x00000010
title = u'Error starting test Blaze server'
msg = u''.join(traceback.format_exception(exctype, value, tb))
ctypes.windll.user32.MessageBoxW(0, msg, title, MB_ICONERROR)
finally:
# Also call the old exception hook to let it do
# its thing too.
old_excepthook(exctype, value, tb)
sys.excepthook = gui_excepthook
import blaze
from blaze.io.server.app import app
// ... rest of the code ...
|
be0a9da80d46630d8958aa95838c5c7c67dda375
|
blanc_basic_podcast/podcast/views.py
|
blanc_basic_podcast/podcast/views.py
|
from django.views.generic import ListView, DateDetailView
from .models import PodcastFile
class PodcastFileListView(ListView):
queryset = PodcastFile.objects.filter(published=True)
class PodcastFileDetailView(DateDetailView):
queryset = PodcastFile.objects.filter(published=True)
month_format = '%m'
date_field = 'date'
|
from django.views.generic import ListView, DateDetailView
from django.utils import timezone
from django.conf import settings
from .models import PodcastFile
class PodcastFileListView(ListView):
paginate_by = getattr(settings, 'PODCAST_PER_PAGE', 10)
def get_queryset(self):
return PodcastFile.objects.filter(published=True,
date__lte=timezone.now())
class PodcastFileDetailView(DateDetailView):
queryset = PodcastFile.objects.filter(published=True)
month_format = '%m'
date_field = 'date'
|
Fix the list view for podcast files, and allow custom per page number in settings
|
Fix the list view for podcast files, and allow custom per page number in settings
|
Python
|
bsd-2-clause
|
blancltd/blanc-basic-podcast
|
python
|
## Code Before:
from django.views.generic import ListView, DateDetailView
from .models import PodcastFile
class PodcastFileListView(ListView):
queryset = PodcastFile.objects.filter(published=True)
class PodcastFileDetailView(DateDetailView):
queryset = PodcastFile.objects.filter(published=True)
month_format = '%m'
date_field = 'date'
## Instruction:
Fix the list view for podcast files, and allow custom per page number in settings
## Code After:
from django.views.generic import ListView, DateDetailView
from django.utils import timezone
from django.conf import settings
from .models import PodcastFile
class PodcastFileListView(ListView):
paginate_by = getattr(settings, 'PODCAST_PER_PAGE', 10)
def get_queryset(self):
return PodcastFile.objects.filter(published=True,
date__lte=timezone.now())
class PodcastFileDetailView(DateDetailView):
queryset = PodcastFile.objects.filter(published=True)
month_format = '%m'
date_field = 'date'
|
# ... existing code ...
from django.views.generic import ListView, DateDetailView
from django.utils import timezone
from django.conf import settings
from .models import PodcastFile
class PodcastFileListView(ListView):
paginate_by = getattr(settings, 'PODCAST_PER_PAGE', 10)
def get_queryset(self):
return PodcastFile.objects.filter(published=True,
date__lte=timezone.now())
class PodcastFileDetailView(DateDetailView):
# ... rest of the code ...
|
4bb8a61cde27575865cdd2b7df5afcb5d6860523
|
fmriprep/interfaces/tests/test_reports.py
|
fmriprep/interfaces/tests/test_reports.py
|
import pytest
from ..reports import get_world_pedir
@pytest.mark.parametrize("orientation,pe_dir,expected", [
('RAS', 'j', 'Posterior-Anterior'),
('RAS', 'j-', 'Anterior-Posterior'),
('RAS', 'i', 'Left-Right'),
('RAS', 'i-', 'Right-Left'),
('RAS', 'k', 'Inferior-Superior'),
('RAS', 'k-', 'Superior-Inferior'),
('LAS', 'j', 'Posterior-Anterior'),
('LAS', 'i-', 'Left-Right'),
('LAS', 'k-', 'Superior-Inferior'),
('LPI', 'j', 'Anterior-Posterior'),
('LPI', 'i-', 'Left-Right'),
('LPI', 'k-', 'Inferior-Superior'),
])
def test_get_world_pedir(tmpdir, orientation, pe_dir, expected):
assert get_world_pedir(orientation, pe_dir) == expected
|
import pytest
from ..reports import get_world_pedir
@pytest.mark.parametrize("orientation,pe_dir,expected", [
('RAS', 'j', 'Posterior-Anterior'),
('RAS', 'j-', 'Anterior-Posterior'),
('RAS', 'i', 'Left-Right'),
('RAS', 'i-', 'Right-Left'),
('RAS', 'k', 'Inferior-Superior'),
('RAS', 'k-', 'Superior-Inferior'),
('LAS', 'j', 'Posterior-Anterior'),
('LAS', 'i-', 'Left-Right'),
('LAS', 'k-', 'Superior-Inferior'),
('LPI', 'j', 'Anterior-Posterior'),
('LPI', 'i-', 'Left-Right'),
('LPI', 'k-', 'Inferior-Superior'),
('SLP', 'k-', 'Posterior-Anterior'),
('SLP', 'k', 'Anterior-Posterior'),
('SLP', 'j-', 'Left-Right'),
('SLP', 'j', 'Right-Left'),
('SLP', 'i', 'Inferior-Superior'),
('SLP', 'i-', 'Superior-Inferior'),
])
def test_get_world_pedir(tmpdir, orientation, pe_dir, expected):
assert get_world_pedir(orientation, pe_dir) == expected
|
Add weird SLP orientation to get_world_pedir
|
TEST: Add weird SLP orientation to get_world_pedir
|
Python
|
bsd-3-clause
|
oesteban/fmriprep,poldracklab/preprocessing-workflow,oesteban/fmriprep,poldracklab/preprocessing-workflow,oesteban/fmriprep
|
python
|
## Code Before:
import pytest
from ..reports import get_world_pedir
@pytest.mark.parametrize("orientation,pe_dir,expected", [
('RAS', 'j', 'Posterior-Anterior'),
('RAS', 'j-', 'Anterior-Posterior'),
('RAS', 'i', 'Left-Right'),
('RAS', 'i-', 'Right-Left'),
('RAS', 'k', 'Inferior-Superior'),
('RAS', 'k-', 'Superior-Inferior'),
('LAS', 'j', 'Posterior-Anterior'),
('LAS', 'i-', 'Left-Right'),
('LAS', 'k-', 'Superior-Inferior'),
('LPI', 'j', 'Anterior-Posterior'),
('LPI', 'i-', 'Left-Right'),
('LPI', 'k-', 'Inferior-Superior'),
])
def test_get_world_pedir(tmpdir, orientation, pe_dir, expected):
assert get_world_pedir(orientation, pe_dir) == expected
## Instruction:
TEST: Add weird SLP orientation to get_world_pedir
## Code After:
import pytest
from ..reports import get_world_pedir
@pytest.mark.parametrize("orientation,pe_dir,expected", [
('RAS', 'j', 'Posterior-Anterior'),
('RAS', 'j-', 'Anterior-Posterior'),
('RAS', 'i', 'Left-Right'),
('RAS', 'i-', 'Right-Left'),
('RAS', 'k', 'Inferior-Superior'),
('RAS', 'k-', 'Superior-Inferior'),
('LAS', 'j', 'Posterior-Anterior'),
('LAS', 'i-', 'Left-Right'),
('LAS', 'k-', 'Superior-Inferior'),
('LPI', 'j', 'Anterior-Posterior'),
('LPI', 'i-', 'Left-Right'),
('LPI', 'k-', 'Inferior-Superior'),
('SLP', 'k-', 'Posterior-Anterior'),
('SLP', 'k', 'Anterior-Posterior'),
('SLP', 'j-', 'Left-Right'),
('SLP', 'j', 'Right-Left'),
('SLP', 'i', 'Inferior-Superior'),
('SLP', 'i-', 'Superior-Inferior'),
])
def test_get_world_pedir(tmpdir, orientation, pe_dir, expected):
assert get_world_pedir(orientation, pe_dir) == expected
|
# ... existing code ...
('LPI', 'j', 'Anterior-Posterior'),
('LPI', 'i-', 'Left-Right'),
('LPI', 'k-', 'Inferior-Superior'),
('SLP', 'k-', 'Posterior-Anterior'),
('SLP', 'k', 'Anterior-Posterior'),
('SLP', 'j-', 'Left-Right'),
('SLP', 'j', 'Right-Left'),
('SLP', 'i', 'Inferior-Superior'),
('SLP', 'i-', 'Superior-Inferior'),
])
def test_get_world_pedir(tmpdir, orientation, pe_dir, expected):
assert get_world_pedir(orientation, pe_dir) == expected
# ... rest of the code ...
|
c230967d63978b4e7d2e8942d15bee6f7c43f694
|
src/main/java/com/headius/invokebinder/Util.java
|
src/main/java/com/headius/invokebinder/Util.java
|
package com.headius.invokebinder;
/**
* Created by headius on 6/27/17.
*/
public class Util {
public static boolean isJava9() {
try {
return System.getProperty("java.specification.version", "").equals("9");
} catch (Exception e) {
return false;
}
}
}
|
package com.headius.invokebinder;
/**
* Utilities used by InvokeBinder classes.
*/
public class Util {
public static boolean IS_JAVA9;
static {
boolean isJava9;
try {
Class.forName("java.lang.Module");
isJava9 = true;
} catch (Exception e) {
isJava9 = false;
}
IS_JAVA9 = isJava9;
}
public static boolean isJava9() {
return IS_JAVA9;
}
}
|
Fix this to run on all Java 9+ JVMs
|
Fix this to run on all Java 9+ JVMs
Also cache the result so it does not keep checking.
|
Java
|
apache-2.0
|
headius/invokebinder,headius/invokebinder
|
java
|
## Code Before:
package com.headius.invokebinder;
/**
* Created by headius on 6/27/17.
*/
public class Util {
public static boolean isJava9() {
try {
return System.getProperty("java.specification.version", "").equals("9");
} catch (Exception e) {
return false;
}
}
}
## Instruction:
Fix this to run on all Java 9+ JVMs
Also cache the result so it does not keep checking.
## Code After:
package com.headius.invokebinder;
/**
* Utilities used by InvokeBinder classes.
*/
public class Util {
public static boolean IS_JAVA9;
static {
boolean isJava9;
try {
Class.forName("java.lang.Module");
isJava9 = true;
} catch (Exception e) {
isJava9 = false;
}
IS_JAVA9 = isJava9;
}
public static boolean isJava9() {
return IS_JAVA9;
}
}
|
...
package com.headius.invokebinder;
/**
* Utilities used by InvokeBinder classes.
*/
public class Util {
public static boolean IS_JAVA9;
static {
boolean isJava9;
try {
Class.forName("java.lang.Module");
isJava9 = true;
} catch (Exception e) {
isJava9 = false;
}
IS_JAVA9 = isJava9;
}
public static boolean isJava9() {
return IS_JAVA9;
}
}
...
|
9ba4f34f11902e16fb17ec08f66a1c9f27817359
|
main.c
|
main.c
|
int main(int argc, char* argv[])
{
FILE * stream;
int FEN_status;
if (argc < 2)
FEN_status = load_FEN(
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
);
else
FEN_status = load_FEN(argv[1]);
#if defined(TEST_MATE_IN_ONE)
memcpy(&square(a8), "nk....bq", 8);
memcpy(&square(a7), "ppp.r...", 8);
memcpy(&square(a6), "........", 8);
memcpy(&square(a5), "........", 8);
memcpy(&square(a4), "........", 8);
memcpy(&square(a3), "........", 8);
memcpy(&square(a2), "...R.PPP", 8);
memcpy(&square(a1), "QB....KN", 8);
#endif
if (FEN_status != FEN_OK)
{
fprintf(stderr, "(%i): FEN record is corrupt!\n\n", FEN_status);
return (FEN_status);
}
stream = (argc < 3) ? stdout : fopen(argv[2], "w");
load_Forsyth(stream);
fclose(stream);
return 0;
}
|
int main(int argc, char* argv[])
{
FILE * stream;
int FEN_status;
if (argc < 2)
FEN_status = load_FEN(
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
);
else
FEN_status = load_FEN(argv[1]);
#if defined(TEST_MATE_IN_ONE)
memcpy(&square(a8), "nk....bq", 8);
memcpy(&square(a7), "ppp.r...", 8);
memcpy(&square(a6), "........", 8);
memcpy(&square(a5), "........", 8);
memcpy(&square(a4), "........", 8);
memcpy(&square(a3), "........", 8);
memcpy(&square(a2), "...R.PPP", 8);
memcpy(&square(a1), "QB....KN", 8);
#endif
if (FEN_status != FEN_OK)
{
fprintf(stderr, "(%i): FEN record is corrupt!\n\n", FEN_status);
return (FEN_status);
}
stream = (argc < 3) ? stdout : fopen(argv[2], "w");
load_Forsyth(stream);
fclose(stream);
if (in_check(WHITE))
puts("White is in check.");
if (in_check(BLACK))
puts("Black is in check.");
return 0;
}
|
Debug check analysis for both sides.
|
Debug check analysis for both sides.
|
C
|
cc0-1.0
|
cxd4/chess,cxd4/chess,cxd4/chess
|
c
|
## Code Before:
int main(int argc, char* argv[])
{
FILE * stream;
int FEN_status;
if (argc < 2)
FEN_status = load_FEN(
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
);
else
FEN_status = load_FEN(argv[1]);
#if defined(TEST_MATE_IN_ONE)
memcpy(&square(a8), "nk....bq", 8);
memcpy(&square(a7), "ppp.r...", 8);
memcpy(&square(a6), "........", 8);
memcpy(&square(a5), "........", 8);
memcpy(&square(a4), "........", 8);
memcpy(&square(a3), "........", 8);
memcpy(&square(a2), "...R.PPP", 8);
memcpy(&square(a1), "QB....KN", 8);
#endif
if (FEN_status != FEN_OK)
{
fprintf(stderr, "(%i): FEN record is corrupt!\n\n", FEN_status);
return (FEN_status);
}
stream = (argc < 3) ? stdout : fopen(argv[2], "w");
load_Forsyth(stream);
fclose(stream);
return 0;
}
## Instruction:
Debug check analysis for both sides.
## Code After:
int main(int argc, char* argv[])
{
FILE * stream;
int FEN_status;
if (argc < 2)
FEN_status = load_FEN(
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
);
else
FEN_status = load_FEN(argv[1]);
#if defined(TEST_MATE_IN_ONE)
memcpy(&square(a8), "nk....bq", 8);
memcpy(&square(a7), "ppp.r...", 8);
memcpy(&square(a6), "........", 8);
memcpy(&square(a5), "........", 8);
memcpy(&square(a4), "........", 8);
memcpy(&square(a3), "........", 8);
memcpy(&square(a2), "...R.PPP", 8);
memcpy(&square(a1), "QB....KN", 8);
#endif
if (FEN_status != FEN_OK)
{
fprintf(stderr, "(%i): FEN record is corrupt!\n\n", FEN_status);
return (FEN_status);
}
stream = (argc < 3) ? stdout : fopen(argv[2], "w");
load_Forsyth(stream);
fclose(stream);
if (in_check(WHITE))
puts("White is in check.");
if (in_check(BLACK))
puts("Black is in check.");
return 0;
}
|
...
stream = (argc < 3) ? stdout : fopen(argv[2], "w");
load_Forsyth(stream);
fclose(stream);
if (in_check(WHITE))
puts("White is in check.");
if (in_check(BLACK))
puts("Black is in check.");
return 0;
}
...
|
5adfa9687fc3a70ad00918004f013e056f8d14b0
|
test/Driver/noexecstack.c
|
test/Driver/noexecstack.c
|
// RUN: %clang -### %s -c -o tmp.o -triple i686-pc-linux-gnu -integrated-as -Wa,--noexecstack 2>&1 | grep "mnoexecstack"
|
// RUN: %clang -### %s -c -o tmp.o -target i686-pc-linux-gnu -integrated-as -Wa,--noexecstack 2>&1 | FileCheck %s
// CHECK: "-cc1" {{.*}} "-mnoexecstack"
|
Use -target instead of triple and use FileCheck.
|
Use -target instead of triple and use FileCheck.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@193502 91177308-0d34-0410-b5e6-96231b3b80d8
|
C
|
apache-2.0
|
apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/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
|
c
|
## Code Before:
// RUN: %clang -### %s -c -o tmp.o -triple i686-pc-linux-gnu -integrated-as -Wa,--noexecstack 2>&1 | grep "mnoexecstack"
## Instruction:
Use -target instead of triple and use FileCheck.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@193502 91177308-0d34-0410-b5e6-96231b3b80d8
## Code After:
// RUN: %clang -### %s -c -o tmp.o -target i686-pc-linux-gnu -integrated-as -Wa,--noexecstack 2>&1 | FileCheck %s
// CHECK: "-cc1" {{.*}} "-mnoexecstack"
|
// ... existing code ...
// RUN: %clang -### %s -c -o tmp.o -target i686-pc-linux-gnu -integrated-as -Wa,--noexecstack 2>&1 | FileCheck %s
// CHECK: "-cc1" {{.*}} "-mnoexecstack"
// ... rest of the code ...
|
80cecb69170adf7235ecbff3eec4e737cf5d9292
|
impersonate/urls.py
|
impersonate/urls.py
|
from django.conf.urls import patterns, url
urlpatterns = patterns('impersonate.views',
url(r'^stop/$',
'stop_impersonate',
name='impersonate-stop'),
url(r'^list/$',
'list_users',
{'template': 'impersonate/list_users.html'},
name='impersonate-list'),
url(r'^search/$',
'search_users',
{'template': 'impersonate/search_users.html'},
name='impersonate-search'),
url(r'^(?P<uid>.+)/$',
'impersonate',
name='impersonate-start'),
)
|
from django.conf.urls import url
from .views import stop_impersonate, list_users, search_users, impersonate
urlpatterns = [
url(r'^stop/$',
stop_impersonate,
name='impersonate-stop'),
url(r'^list/$',
list_users,
{'template': 'impersonate/list_users.html'},
name='impersonate-list'),
url(r'^search/$',
search_users,
{'template': 'impersonate/search_users.html'},
name='impersonate-search'),
url(r'^(?P<uid>.+)/$',
impersonate,
name='impersonate-start'),
]
|
Replace deprecated string view arguments to url
|
Replace deprecated string view arguments to url
|
Python
|
bsd-3-clause
|
Top20Talent/django-impersonate,Top20Talent/django-impersonate
|
python
|
## Code Before:
from django.conf.urls import patterns, url
urlpatterns = patterns('impersonate.views',
url(r'^stop/$',
'stop_impersonate',
name='impersonate-stop'),
url(r'^list/$',
'list_users',
{'template': 'impersonate/list_users.html'},
name='impersonate-list'),
url(r'^search/$',
'search_users',
{'template': 'impersonate/search_users.html'},
name='impersonate-search'),
url(r'^(?P<uid>.+)/$',
'impersonate',
name='impersonate-start'),
)
## Instruction:
Replace deprecated string view arguments to url
## Code After:
from django.conf.urls import url
from .views import stop_impersonate, list_users, search_users, impersonate
urlpatterns = [
url(r'^stop/$',
stop_impersonate,
name='impersonate-stop'),
url(r'^list/$',
list_users,
{'template': 'impersonate/list_users.html'},
name='impersonate-list'),
url(r'^search/$',
search_users,
{'template': 'impersonate/search_users.html'},
name='impersonate-search'),
url(r'^(?P<uid>.+)/$',
impersonate,
name='impersonate-start'),
]
|
// ... existing code ...
from django.conf.urls import url
from .views import stop_impersonate, list_users, search_users, impersonate
urlpatterns = [
url(r'^stop/$',
stop_impersonate,
name='impersonate-stop'),
url(r'^list/$',
list_users,
{'template': 'impersonate/list_users.html'},
name='impersonate-list'),
url(r'^search/$',
search_users,
{'template': 'impersonate/search_users.html'},
name='impersonate-search'),
url(r'^(?P<uid>.+)/$',
impersonate,
name='impersonate-start'),
]
// ... rest of the code ...
|
f2c793c9fcbb3ad8b9e79dc703d04c1a49329a99
|
src/gui/org/deidentifier/arx/gui/view/impl/analyze/ViewStatistics.java
|
src/gui/org/deidentifier/arx/gui/view/impl/analyze/ViewStatistics.java
|
package org.deidentifier.arx.gui.view.impl.analyze;
import java.awt.Panel;
import org.deidentifier.arx.DataHandle;
import org.deidentifier.arx.gui.model.Model;
import org.deidentifier.arx.gui.model.ModelEvent.ModelPart;
public abstract class ViewStatistics extends Panel{
private static final long serialVersionUID = 5170104283288654748L;
protected ModelPart target;
protected Model model;
/**
* Returns the data handle
* @return
*/
protected DataHandle getHandle() {
if (model != null){
if (target == ModelPart.INPUT){
DataHandle handle = model.getInputConfig().getInput().getHandle();
if (model.getViewConfig().isSubset() &&
model.getOutputConfig() != null &&
model.getOutputConfig().getConfig() != null) {
handle = handle.getView();
}
return handle;
} else {
DataHandle handle = model.getOutput();
if (model.getViewConfig().isSubset() &&
model.getOutputConfig() != null &&
model.getOutputConfig().getConfig() != null) {
handle = handle.getView();
}
return handle;
}
} else {
return null;
}
}
}
|
package org.deidentifier.arx.gui.view.impl.analyze;
import java.awt.Panel;
import org.deidentifier.arx.DataHandle;
import org.deidentifier.arx.gui.model.Model;
import org.deidentifier.arx.gui.model.ModelEvent.ModelPart;
public abstract class ViewStatistics extends Panel{
private static final long serialVersionUID = 5170104283288654748L;
protected ModelPart target;
protected Model model;
/**
* Returns the data handle
* @return
*/
protected DataHandle getHandle() {
if (model != null){
if (target == ModelPart.INPUT){
DataHandle handle = model.getInputConfig().getInput().getHandle();
if (model.getViewConfig().isSubset() &&
model.getOutputConfig() != null &&
model.getOutputConfig().getConfig() != null &&
handle != null) {
handle = handle.getView();
}
return handle;
} else {
DataHandle handle = model.getOutput();
if (model.getViewConfig().isSubset() &&
model.getOutputConfig() != null &&
model.getOutputConfig().getConfig() != null &&
handle != null) {
handle = handle.getView();
}
return handle;
}
} else {
return null;
}
}
}
|
Fix bug when loading projects
|
Fix bug when loading projects
|
Java
|
apache-2.0
|
TheRealRasu/arx,bitraten/arx,arx-deidentifier/arx,bitraten/arx,fstahnke/arx,tijanat/arx,jgaupp/arx,tijanat/arx,RaffaelBild/arx,kbabioch/arx,RaffaelBild/arx,kentoa/arx,COWYARD/arx,fstahnke/arx,COWYARD/arx,jgaupp/arx,arx-deidentifier/arx,TheRealRasu/arx,kentoa/arx,kbabioch/arx
|
java
|
## Code Before:
package org.deidentifier.arx.gui.view.impl.analyze;
import java.awt.Panel;
import org.deidentifier.arx.DataHandle;
import org.deidentifier.arx.gui.model.Model;
import org.deidentifier.arx.gui.model.ModelEvent.ModelPart;
public abstract class ViewStatistics extends Panel{
private static final long serialVersionUID = 5170104283288654748L;
protected ModelPart target;
protected Model model;
/**
* Returns the data handle
* @return
*/
protected DataHandle getHandle() {
if (model != null){
if (target == ModelPart.INPUT){
DataHandle handle = model.getInputConfig().getInput().getHandle();
if (model.getViewConfig().isSubset() &&
model.getOutputConfig() != null &&
model.getOutputConfig().getConfig() != null) {
handle = handle.getView();
}
return handle;
} else {
DataHandle handle = model.getOutput();
if (model.getViewConfig().isSubset() &&
model.getOutputConfig() != null &&
model.getOutputConfig().getConfig() != null) {
handle = handle.getView();
}
return handle;
}
} else {
return null;
}
}
}
## Instruction:
Fix bug when loading projects
## Code After:
package org.deidentifier.arx.gui.view.impl.analyze;
import java.awt.Panel;
import org.deidentifier.arx.DataHandle;
import org.deidentifier.arx.gui.model.Model;
import org.deidentifier.arx.gui.model.ModelEvent.ModelPart;
public abstract class ViewStatistics extends Panel{
private static final long serialVersionUID = 5170104283288654748L;
protected ModelPart target;
protected Model model;
/**
* Returns the data handle
* @return
*/
protected DataHandle getHandle() {
if (model != null){
if (target == ModelPart.INPUT){
DataHandle handle = model.getInputConfig().getInput().getHandle();
if (model.getViewConfig().isSubset() &&
model.getOutputConfig() != null &&
model.getOutputConfig().getConfig() != null &&
handle != null) {
handle = handle.getView();
}
return handle;
} else {
DataHandle handle = model.getOutput();
if (model.getViewConfig().isSubset() &&
model.getOutputConfig() != null &&
model.getOutputConfig().getConfig() != null &&
handle != null) {
handle = handle.getView();
}
return handle;
}
} else {
return null;
}
}
}
|
// ... existing code ...
DataHandle handle = model.getInputConfig().getInput().getHandle();
if (model.getViewConfig().isSubset() &&
model.getOutputConfig() != null &&
model.getOutputConfig().getConfig() != null &&
handle != null) {
handle = handle.getView();
}
return handle;
// ... modified code ...
DataHandle handle = model.getOutput();
if (model.getViewConfig().isSubset() &&
model.getOutputConfig() != null &&
model.getOutputConfig().getConfig() != null &&
handle != null) {
handle = handle.getView();
}
return handle;
// ... rest of the code ...
|
aa10ac1ec3010aa471fe7570cdcf2dc52e9c6ecd
|
ribbon-transport/src/test/java/com/netflix/client/netty/udp/HelloUdpServerExternalResource.java
|
ribbon-transport/src/test/java/com/netflix/client/netty/udp/HelloUdpServerExternalResource.java
|
package com.netflix.client.netty.udp;
import io.netty.channel.socket.DatagramPacket;
import io.reactivex.netty.protocol.udp.server.UdpServer;
import java.net.DatagramSocket;
import java.net.SocketException;
import org.junit.rules.ExternalResource;
public class HelloUdpServerExternalResource extends ExternalResource {
private UdpServer<DatagramPacket, DatagramPacket> server;
private int timeout = 0;
public HelloUdpServerExternalResource() {
}
private int choosePort() throws SocketException {
DatagramSocket serverSocket = new DatagramSocket();
int port = serverSocket.getLocalPort();
serverSocket.close();
return port;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
protected void before() throws Throwable {
int port = choosePort();
server = new HelloUdpServer(port, timeout).createServer();
}
public void start() {
server.start();
}
/**
* Override to tear down your specific external resource.
*/
protected void after() {
if (server != null) {
try {
server.shutdown();
} catch (InterruptedException e) {
System.out.println("Failed to shut down server");
e.printStackTrace();
}
}
}
public int getServerPort() {
return server.getServerPort();
}
}
|
package com.netflix.client.netty.udp;
import io.netty.channel.socket.DatagramPacket;
import io.reactivex.netty.protocol.udp.server.UdpServer;
import java.net.DatagramSocket;
import java.net.SocketException;
import org.junit.rules.ExternalResource;
public class HelloUdpServerExternalResource extends ExternalResource {
private UdpServer<DatagramPacket, DatagramPacket> server;
private int timeout = 0;
public HelloUdpServerExternalResource() {
}
private int choosePort() throws SocketException {
DatagramSocket serverSocket = new DatagramSocket();
int port = serverSocket.getLocalPort();
serverSocket.close();
return port;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public void start() {
int port;
try {
port = choosePort();
} catch (SocketException e) {
throw new RuntimeException("Error choosing point", e);
}
server = new HelloUdpServer(port, timeout).createServer();
server.start();
}
/**
* Override to tear down your specific external resource.
*/
protected void after() {
if (server != null) {
try {
server.shutdown();
} catch (InterruptedException e) {
System.out.println("Failed to shut down server");
e.printStackTrace();
}
}
}
public int getServerPort() {
return server.getServerPort();
}
}
|
Move server config from before() to start()
|
Move server config from before() to start()
|
Java
|
apache-2.0
|
bondj/ribbon,drtechniko/ribbon,roykachouh/ribbon,drmaas/ribbon,elandau/ribbon,spencergibb/ribbon,robertroeser/ribbon,enriclluelles/ribbon,brajput24/ribbon,Netflix/ribbon,elandau/ribbon
|
java
|
## Code Before:
package com.netflix.client.netty.udp;
import io.netty.channel.socket.DatagramPacket;
import io.reactivex.netty.protocol.udp.server.UdpServer;
import java.net.DatagramSocket;
import java.net.SocketException;
import org.junit.rules.ExternalResource;
public class HelloUdpServerExternalResource extends ExternalResource {
private UdpServer<DatagramPacket, DatagramPacket> server;
private int timeout = 0;
public HelloUdpServerExternalResource() {
}
private int choosePort() throws SocketException {
DatagramSocket serverSocket = new DatagramSocket();
int port = serverSocket.getLocalPort();
serverSocket.close();
return port;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
protected void before() throws Throwable {
int port = choosePort();
server = new HelloUdpServer(port, timeout).createServer();
}
public void start() {
server.start();
}
/**
* Override to tear down your specific external resource.
*/
protected void after() {
if (server != null) {
try {
server.shutdown();
} catch (InterruptedException e) {
System.out.println("Failed to shut down server");
e.printStackTrace();
}
}
}
public int getServerPort() {
return server.getServerPort();
}
}
## Instruction:
Move server config from before() to start()
## Code After:
package com.netflix.client.netty.udp;
import io.netty.channel.socket.DatagramPacket;
import io.reactivex.netty.protocol.udp.server.UdpServer;
import java.net.DatagramSocket;
import java.net.SocketException;
import org.junit.rules.ExternalResource;
public class HelloUdpServerExternalResource extends ExternalResource {
private UdpServer<DatagramPacket, DatagramPacket> server;
private int timeout = 0;
public HelloUdpServerExternalResource() {
}
private int choosePort() throws SocketException {
DatagramSocket serverSocket = new DatagramSocket();
int port = serverSocket.getLocalPort();
serverSocket.close();
return port;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public void start() {
int port;
try {
port = choosePort();
} catch (SocketException e) {
throw new RuntimeException("Error choosing point", e);
}
server = new HelloUdpServer(port, timeout).createServer();
server.start();
}
/**
* Override to tear down your specific external resource.
*/
protected void after() {
if (server != null) {
try {
server.shutdown();
} catch (InterruptedException e) {
System.out.println("Failed to shut down server");
e.printStackTrace();
}
}
}
public int getServerPort() {
return server.getServerPort();
}
}
|
// ... existing code ...
this.timeout = timeout;
}
public void start() {
int port;
try {
port = choosePort();
} catch (SocketException e) {
throw new RuntimeException("Error choosing point", e);
}
server = new HelloUdpServer(port, timeout).createServer();
server.start();
}
// ... rest of the code ...
|
a5befe542e857ec36717f7f8da53ff9f2c2af7e6
|
natasha/__init__.py
|
natasha/__init__.py
|
from copy import copy
from collections import deque
from yargy import FactParser
from natasha.grammars import Person, Geo
class Combinator(object):
DEFAULT_GRAMMARS = [
Person,
Geo,
]
def __init__(self, grammars=None, cache_size=50000):
self.grammars = grammars or self.DEFAULT_GRAMMARS
self.parser = FactParser(cache_size=cache_size)
def extract(self, text):
tokens = deque(self.parser.tokenizer.transform(text))
for grammar in self.grammars:
for grammar_type, rule in grammar.__members__.items():
for match in self.parser.extract(copy(tokens), rule.value):
yield (grammar, grammar_type, match)
|
from copy import copy
from collections import deque
from yargy import FactParser
from natasha.grammars import Person, Geo, Money, Date
class Combinator(object):
DEFAULT_GRAMMARS = [
Money,
Person,
Geo,
Date,
]
def __init__(self, grammars=None, cache_size=50000):
self.grammars = grammars or self.DEFAULT_GRAMMARS
self.parser = FactParser(cache_size=cache_size)
def extract(self, text):
tokens = deque(self.parser.tokenizer.transform(text))
for grammar in self.grammars:
for grammar_type, rule in grammar.__members__.items():
for match in self.parser.extract(copy(tokens), rule.value):
yield (grammar, grammar_type, match)
|
Add new grammars to Combinator.DEFAULT_GRAMMARS
|
Add new grammars to Combinator.DEFAULT_GRAMMARS
|
Python
|
mit
|
natasha/natasha
|
python
|
## Code Before:
from copy import copy
from collections import deque
from yargy import FactParser
from natasha.grammars import Person, Geo
class Combinator(object):
DEFAULT_GRAMMARS = [
Person,
Geo,
]
def __init__(self, grammars=None, cache_size=50000):
self.grammars = grammars or self.DEFAULT_GRAMMARS
self.parser = FactParser(cache_size=cache_size)
def extract(self, text):
tokens = deque(self.parser.tokenizer.transform(text))
for grammar in self.grammars:
for grammar_type, rule in grammar.__members__.items():
for match in self.parser.extract(copy(tokens), rule.value):
yield (grammar, grammar_type, match)
## Instruction:
Add new grammars to Combinator.DEFAULT_GRAMMARS
## Code After:
from copy import copy
from collections import deque
from yargy import FactParser
from natasha.grammars import Person, Geo, Money, Date
class Combinator(object):
DEFAULT_GRAMMARS = [
Money,
Person,
Geo,
Date,
]
def __init__(self, grammars=None, cache_size=50000):
self.grammars = grammars or self.DEFAULT_GRAMMARS
self.parser = FactParser(cache_size=cache_size)
def extract(self, text):
tokens = deque(self.parser.tokenizer.transform(text))
for grammar in self.grammars:
for grammar_type, rule in grammar.__members__.items():
for match in self.parser.extract(copy(tokens), rule.value):
yield (grammar, grammar_type, match)
|
...
from yargy import FactParser
from natasha.grammars import Person, Geo, Money, Date
class Combinator(object):
DEFAULT_GRAMMARS = [
Money,
Person,
Geo,
Date,
]
def __init__(self, grammars=None, cache_size=50000):
...
|
307265aaabc5d61e1aa3add68f87911e003a85fa
|
support/c/idris_directory.h
|
support/c/idris_directory.h
|
char* idris2_currentDirectory();
int idris2_changeDir(char* dir);
int idris2_createDir(char* dir);
void* idris2_openDir(char* dir);
void idris2_dirClose(void* d);
char* idris2_nextDirEntry(void* d);
#endif
|
char* idris2_currentDirectory();
int idris2_changeDir(char* dir);
int idris2_createDir(char* dir);
void* idris2_openDir(char* dir);
void idris2_closeDIr(void* d);
int idris2_removeDir(char* path);
char* idris2_nextDirEntry(void* d);
#endif
|
Update C support header files
|
Update C support header files
|
C
|
bsd-3-clause
|
mmhelloworld/idris-jvm,mmhelloworld/idris-jvm,mmhelloworld/idris-jvm,mmhelloworld/idris-jvm,mmhelloworld/idris-jvm,mmhelloworld/idris-jvm
|
c
|
## Code Before:
char* idris2_currentDirectory();
int idris2_changeDir(char* dir);
int idris2_createDir(char* dir);
void* idris2_openDir(char* dir);
void idris2_dirClose(void* d);
char* idris2_nextDirEntry(void* d);
#endif
## Instruction:
Update C support header files
## Code After:
char* idris2_currentDirectory();
int idris2_changeDir(char* dir);
int idris2_createDir(char* dir);
void* idris2_openDir(char* dir);
void idris2_closeDIr(void* d);
int idris2_removeDir(char* path);
char* idris2_nextDirEntry(void* d);
#endif
|
# ... existing code ...
int idris2_changeDir(char* dir);
int idris2_createDir(char* dir);
void* idris2_openDir(char* dir);
void idris2_closeDIr(void* d);
int idris2_removeDir(char* path);
char* idris2_nextDirEntry(void* d);
#endif
# ... rest of the code ...
|
d1ce68480868775897e643a8248479895696c2a4
|
encode-and-decode-tinyurl/Codec.java
|
encode-and-decode-tinyurl/Codec.java
|
public class Codec {
private Map<String, String> urlMapper = new HashMap<>();
private Random rand = new Random();
private byte[] stringArray = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".getBytes();
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
String shortened = getShortUrl(longUrl);
urlMapper.put(shortened, longUrl);
return shortened;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return urlMapper.get(shortUrl);
}
}
|
public class Codec {
private Map<String, String> urlMapper = new HashMap<>();
private Random rand = new Random();
private byte[] stringArray = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".getBytes();
private String getShortUrl() {
byte[] s = new byte[6];
for (int i = 0; i < 6; i++) {
int n = rand.nextInt(62);
s[i] = stringArray[n];
}
return "http://tinyurl.com/" + new String(s);
}
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
String shortened = null;
int count = 0;
while (count < 10) {
shortened = getShortUrl();
if (urlMapper.get(shortened) == null) {
urlMapper.put(shortened, longUrl);
break;
}
count++;
}
return shortened;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return urlMapper.get(shortUrl);
}
}
|
Update java solution for 'Encode and Decode TinyURL'
|
Update java solution for 'Encode and Decode TinyURL'
|
Java
|
mit
|
mysangle/algorithm-study,mysangle/algorithm-study
|
java
|
## Code Before:
public class Codec {
private Map<String, String> urlMapper = new HashMap<>();
private Random rand = new Random();
private byte[] stringArray = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".getBytes();
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
String shortened = getShortUrl(longUrl);
urlMapper.put(shortened, longUrl);
return shortened;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return urlMapper.get(shortUrl);
}
}
## Instruction:
Update java solution for 'Encode and Decode TinyURL'
## Code After:
public class Codec {
private Map<String, String> urlMapper = new HashMap<>();
private Random rand = new Random();
private byte[] stringArray = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".getBytes();
private String getShortUrl() {
byte[] s = new byte[6];
for (int i = 0; i < 6; i++) {
int n = rand.nextInt(62);
s[i] = stringArray[n];
}
return "http://tinyurl.com/" + new String(s);
}
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
String shortened = null;
int count = 0;
while (count < 10) {
shortened = getShortUrl();
if (urlMapper.get(shortened) == null) {
urlMapper.put(shortened, longUrl);
break;
}
count++;
}
return shortened;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return urlMapper.get(shortUrl);
}
}
|
// ... existing code ...
public class Codec {
private Map<String, String> urlMapper = new HashMap<>();
private Random rand = new Random();
private byte[] stringArray = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".getBytes();
private String getShortUrl() {
byte[] s = new byte[6];
for (int i = 0; i < 6; i++) {
int n = rand.nextInt(62);
s[i] = stringArray[n];
}
return "http://tinyurl.com/" + new String(s);
}
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
String shortened = null;
int count = 0;
while (count < 10) {
shortened = getShortUrl();
if (urlMapper.get(shortened) == null) {
urlMapper.put(shortened, longUrl);
break;
}
count++;
}
return shortened;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return urlMapper.get(shortUrl);
}
}
// ... rest of the code ...
|
1270c31dcf35c17a26a282605d2e04ffd2e8d985
|
tests/test_ftp.py
|
tests/test_ftp.py
|
from wex.url import URL
expected_lines = [
b"FTP/1.0 200 OK\r\n",
b"X-wex-url: ftp://anonymous:[email protected]/pub/site/README\r\n",
b"\r\n",
b"This directory contains files related to the operation of the\n",
]
expected_content = b''.join(expected_lines)
url = 'ftp://anonymous:[email protected]/pub/site/README'
def test_ftp_read():
readables = list(URL(url).get())
assert len(readables) == 1
r0 = readables[0]
chunk = r0.read(2**16)
content = chunk
chunk = r0.read(2**16)
assert not chunk
assert content.startswith(expected_content)
def test_ftp_readline():
readables = list(URL(url).get())
assert len(readables) == 1
r0 = readables[0]
first_four_lines = [r0.readline() for i in range(4)]
assert first_four_lines == expected_lines[:4]
|
from wex.url import URL
url = 'ftp://anonymous:[email protected]/1KB.zip'
expected_lines = [
b"FTP/1.0 200 OK\r\n",
b"X-wex-url: " + url + "\r\n",
b"\r\n",
]
expected_content = b''.join(expected_lines)
def test_ftp_read():
readables = list(URL(url).get())
assert len(readables) == 1
r0 = readables[0]
chunk = r0.read(2**16)
content = chunk
chunk = r0.read(2**16)
assert not chunk
assert content.startswith(expected_content)
def test_ftp_readline():
readables = list(URL(url).get())
assert len(readables) == 1
n = 3
r0 = readables[0]
first_few_lines = [r0.readline() for i in range(n)]
assert first_few_lines == expected_lines[:n]
|
Switch ftp server now ftp.kernel.org closed
|
Switch ftp server now ftp.kernel.org closed
|
Python
|
bsd-3-clause
|
eBay/wextracto,gilessbrown/wextracto,gilessbrown/wextracto,eBay/wextracto
|
python
|
## Code Before:
from wex.url import URL
expected_lines = [
b"FTP/1.0 200 OK\r\n",
b"X-wex-url: ftp://anonymous:[email protected]/pub/site/README\r\n",
b"\r\n",
b"This directory contains files related to the operation of the\n",
]
expected_content = b''.join(expected_lines)
url = 'ftp://anonymous:[email protected]/pub/site/README'
def test_ftp_read():
readables = list(URL(url).get())
assert len(readables) == 1
r0 = readables[0]
chunk = r0.read(2**16)
content = chunk
chunk = r0.read(2**16)
assert not chunk
assert content.startswith(expected_content)
def test_ftp_readline():
readables = list(URL(url).get())
assert len(readables) == 1
r0 = readables[0]
first_four_lines = [r0.readline() for i in range(4)]
assert first_four_lines == expected_lines[:4]
## Instruction:
Switch ftp server now ftp.kernel.org closed
## Code After:
from wex.url import URL
url = 'ftp://anonymous:[email protected]/1KB.zip'
expected_lines = [
b"FTP/1.0 200 OK\r\n",
b"X-wex-url: " + url + "\r\n",
b"\r\n",
]
expected_content = b''.join(expected_lines)
def test_ftp_read():
readables = list(URL(url).get())
assert len(readables) == 1
r0 = readables[0]
chunk = r0.read(2**16)
content = chunk
chunk = r0.read(2**16)
assert not chunk
assert content.startswith(expected_content)
def test_ftp_readline():
readables = list(URL(url).get())
assert len(readables) == 1
n = 3
r0 = readables[0]
first_few_lines = [r0.readline() for i in range(n)]
assert first_few_lines == expected_lines[:n]
|
// ... existing code ...
from wex.url import URL
url = 'ftp://anonymous:[email protected]/1KB.zip'
expected_lines = [
b"FTP/1.0 200 OK\r\n",
b"X-wex-url: " + url + "\r\n",
b"\r\n",
]
expected_content = b''.join(expected_lines)
def test_ftp_read():
// ... modified code ...
def test_ftp_readline():
readables = list(URL(url).get())
assert len(readables) == 1
n = 3
r0 = readables[0]
first_few_lines = [r0.readline() for i in range(n)]
assert first_few_lines == expected_lines[:n]
// ... rest of the code ...
|
aaba085cd2e97c8c23e6724da3313d42d12798f0
|
app/grandchallenge/annotations/validators.py
|
app/grandchallenge/annotations/validators.py
|
from rest_framework import serializers
from django.conf import settings
def validate_grader_is_current_retina_user(grader, context):
"""
This method checks if the passed grader equals the request.user that is passed in the context.
Only applies to users that are in the retina_graders group.
"""
request = context.get("request")
if request and request.user.is_authenticated:
user = request.user
if user.groups.filter(
name=settings.RETINA_GRADERS_GROUP_NAME
).exists():
if grader != user:
raise serializers.ValidationError(
"User is not allowed to create annotation for other grader"
)
|
from rest_framework import serializers
from django.conf import settings
def validate_grader_is_current_retina_user(grader, context):
"""
This method checks if the passed grader equals the request.user that is passed in the context.
Only applies to users that are in the retina_graders group.
"""
request = context.get("request")
if (
request is not None
and request.user is not None
and request.user.is_authenticated
):
user = request.user
if user.groups.filter(
name=settings.RETINA_GRADERS_GROUP_NAME
).exists():
if grader != user:
raise serializers.ValidationError(
"User is not allowed to create annotation for other grader"
)
|
Make sure request.user is a user
|
Make sure request.user is a user
|
Python
|
apache-2.0
|
comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django
|
python
|
## Code Before:
from rest_framework import serializers
from django.conf import settings
def validate_grader_is_current_retina_user(grader, context):
"""
This method checks if the passed grader equals the request.user that is passed in the context.
Only applies to users that are in the retina_graders group.
"""
request = context.get("request")
if request and request.user.is_authenticated:
user = request.user
if user.groups.filter(
name=settings.RETINA_GRADERS_GROUP_NAME
).exists():
if grader != user:
raise serializers.ValidationError(
"User is not allowed to create annotation for other grader"
)
## Instruction:
Make sure request.user is a user
## Code After:
from rest_framework import serializers
from django.conf import settings
def validate_grader_is_current_retina_user(grader, context):
"""
This method checks if the passed grader equals the request.user that is passed in the context.
Only applies to users that are in the retina_graders group.
"""
request = context.get("request")
if (
request is not None
and request.user is not None
and request.user.is_authenticated
):
user = request.user
if user.groups.filter(
name=settings.RETINA_GRADERS_GROUP_NAME
).exists():
if grader != user:
raise serializers.ValidationError(
"User is not allowed to create annotation for other grader"
)
|
# ... existing code ...
Only applies to users that are in the retina_graders group.
"""
request = context.get("request")
if (
request is not None
and request.user is not None
and request.user.is_authenticated
):
user = request.user
if user.groups.filter(
name=settings.RETINA_GRADERS_GROUP_NAME
# ... rest of the code ...
|
ead1a6d6f094a3187b8973a195d967b2fe7ddda2
|
src/main/java/sssj/Utils.java
|
src/main/java/sssj/Utils.java
|
package sssj;
import com.google.common.base.Preconditions;
import com.google.common.collect.ForwardingTable;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
public class Utils {
public static double computeTau(double theta, double lambda) {
Preconditions.checkArgument(theta > 0 && theta < 1);
Preconditions.checkArgument(lambda > 0);
double tau = 1 / lambda * Math.log(1 / theta);
return tau;
}
public static class BatchResult extends ForwardingTable<Long, Long, Double> {
private final HashBasedTable<Long, Long, Double> delegate = HashBasedTable.create();
@Override
protected Table<Long, Long, Double> delegate() {
return delegate;
}
}
public static enum IndexType {
INVERTED, ALL_PAIRS, L2AP;
}
}
|
package sssj;
import com.google.common.base.Preconditions;
import com.google.common.collect.ForwardingTable;
import com.google.common.collect.Table;
import com.google.common.collect.TreeBasedTable;
public class Utils {
public static double computeTau(double theta, double lambda) {
Preconditions.checkArgument(theta > 0 && theta < 1);
Preconditions.checkArgument(lambda > 0);
double tau = 1 / lambda * Math.log(1 / theta);
return tau;
}
public static class BatchResult extends ForwardingTable<Long, Long, Double> {
private final Table<Long, Long, Double> delegate = TreeBasedTable.create();
@Override
protected Table<Long, Long, Double> delegate() {
return delegate;
}
}
public static enum IndexType {
INVERTED, ALL_PAIRS, L2AP;
}
}
|
Sort results in minibatch mode
|
Sort results in minibatch mode
|
Java
|
apache-2.0
|
gdfm/sssj,gdfm/sssj,gdfm/sssj
|
java
|
## Code Before:
package sssj;
import com.google.common.base.Preconditions;
import com.google.common.collect.ForwardingTable;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
public class Utils {
public static double computeTau(double theta, double lambda) {
Preconditions.checkArgument(theta > 0 && theta < 1);
Preconditions.checkArgument(lambda > 0);
double tau = 1 / lambda * Math.log(1 / theta);
return tau;
}
public static class BatchResult extends ForwardingTable<Long, Long, Double> {
private final HashBasedTable<Long, Long, Double> delegate = HashBasedTable.create();
@Override
protected Table<Long, Long, Double> delegate() {
return delegate;
}
}
public static enum IndexType {
INVERTED, ALL_PAIRS, L2AP;
}
}
## Instruction:
Sort results in minibatch mode
## Code After:
package sssj;
import com.google.common.base.Preconditions;
import com.google.common.collect.ForwardingTable;
import com.google.common.collect.Table;
import com.google.common.collect.TreeBasedTable;
public class Utils {
public static double computeTau(double theta, double lambda) {
Preconditions.checkArgument(theta > 0 && theta < 1);
Preconditions.checkArgument(lambda > 0);
double tau = 1 / lambda * Math.log(1 / theta);
return tau;
}
public static class BatchResult extends ForwardingTable<Long, Long, Double> {
private final Table<Long, Long, Double> delegate = TreeBasedTable.create();
@Override
protected Table<Long, Long, Double> delegate() {
return delegate;
}
}
public static enum IndexType {
INVERTED, ALL_PAIRS, L2AP;
}
}
|
// ... existing code ...
import com.google.common.base.Preconditions;
import com.google.common.collect.ForwardingTable;
import com.google.common.collect.Table;
import com.google.common.collect.TreeBasedTable;
public class Utils {
// ... modified code ...
}
public static class BatchResult extends ForwardingTable<Long, Long, Double> {
private final Table<Long, Long, Double> delegate = TreeBasedTable.create();
@Override
protected Table<Long, Long, Double> delegate() {
// ... rest of the code ...
|
b43dfa19979dc74efb27e56771535b102547e792
|
utils.py
|
utils.py
|
import sqlite3
import shelve
def connect_db(name):
"""
Open a connection to the database used to store quotes.
:param name: (str) Name of database file
:return: (shelve.DbfilenameShelf)
"""
try:
return shelve.open(name)
except Exception:
raise Exception('Unable to connect to database with name {}'.format(name))
class DBClient(object):
"""Client for interacting with database for the application"""
def __init__(self, database_name):
self.conn = sqlite3.connect(database_name)
self._create_quotes_table()
def _create_quotes_table(self):
"""
Create the table used for storing quotes if it does not exist already
"""
with self.conn:
self.conn.execute('''
CREATE TABLE IF NOT EXISTS quotes (
author TEXT
quote TEXT
created_at TEXT
)
''')
def close_connection(self):
"""
Close connection to the database
"""
self.conn.close()
|
import sqlite3
import shelve
def connect_db(name):
"""
Open a connection to the database used to store quotes.
:param name: (str) Name of database file
:return: (shelve.DbfilenameShelf)
"""
try:
return shelve.open(name)
except Exception:
raise Exception('Unable to connect to database with name {}'.format(name))
class DBClient(object):
"""Client for interacting with database for the application"""
def __init__(self, database_name: str):
self.conn = sqlite3.connect(database_name)
self._create_quotes_table()
def _create_quotes_table(self):
"""
Create the table used for storing quotes if it does not exist already
"""
with self.conn:
self.conn.execute('''
CREATE TABLE IF NOT EXISTS quotes (
author TEXT,
quote TEXT,
created_at TEXT
);
''')
def close_connection(self):
"""
Close connection to the database
"""
self.conn.close()
def insert_quote(self, author: str, quote: str, created_at: str):
"""
Insert a quote into the database
:param author: (str) Name of the author that said the quote
:param quote: (str) The quote for the author
:param created_at: (str) Timestamp for when the quote was saved to database
"""
with self.conn:
self.conn.execute('''
INSERT INTO quotes VALUES (?, ?, ?)
''', (author, quote, created_at))
|
Add method to insert quotes into database
|
Add method to insert quotes into database
Fix schema for quotes table
|
Python
|
mit
|
nickdibari/Get-Quote
|
python
|
## Code Before:
import sqlite3
import shelve
def connect_db(name):
"""
Open a connection to the database used to store quotes.
:param name: (str) Name of database file
:return: (shelve.DbfilenameShelf)
"""
try:
return shelve.open(name)
except Exception:
raise Exception('Unable to connect to database with name {}'.format(name))
class DBClient(object):
"""Client for interacting with database for the application"""
def __init__(self, database_name):
self.conn = sqlite3.connect(database_name)
self._create_quotes_table()
def _create_quotes_table(self):
"""
Create the table used for storing quotes if it does not exist already
"""
with self.conn:
self.conn.execute('''
CREATE TABLE IF NOT EXISTS quotes (
author TEXT
quote TEXT
created_at TEXT
)
''')
def close_connection(self):
"""
Close connection to the database
"""
self.conn.close()
## Instruction:
Add method to insert quotes into database
Fix schema for quotes table
## Code After:
import sqlite3
import shelve
def connect_db(name):
"""
Open a connection to the database used to store quotes.
:param name: (str) Name of database file
:return: (shelve.DbfilenameShelf)
"""
try:
return shelve.open(name)
except Exception:
raise Exception('Unable to connect to database with name {}'.format(name))
class DBClient(object):
"""Client for interacting with database for the application"""
def __init__(self, database_name: str):
self.conn = sqlite3.connect(database_name)
self._create_quotes_table()
def _create_quotes_table(self):
"""
Create the table used for storing quotes if it does not exist already
"""
with self.conn:
self.conn.execute('''
CREATE TABLE IF NOT EXISTS quotes (
author TEXT,
quote TEXT,
created_at TEXT
);
''')
def close_connection(self):
"""
Close connection to the database
"""
self.conn.close()
def insert_quote(self, author: str, quote: str, created_at: str):
"""
Insert a quote into the database
:param author: (str) Name of the author that said the quote
:param quote: (str) The quote for the author
:param created_at: (str) Timestamp for when the quote was saved to database
"""
with self.conn:
self.conn.execute('''
INSERT INTO quotes VALUES (?, ?, ?)
''', (author, quote, created_at))
|
# ... existing code ...
class DBClient(object):
"""Client for interacting with database for the application"""
def __init__(self, database_name: str):
self.conn = sqlite3.connect(database_name)
self._create_quotes_table()
# ... modified code ...
with self.conn:
self.conn.execute('''
CREATE TABLE IF NOT EXISTS quotes (
author TEXT,
quote TEXT,
created_at TEXT
);
''')
def close_connection(self):
...
Close connection to the database
"""
self.conn.close()
def insert_quote(self, author: str, quote: str, created_at: str):
"""
Insert a quote into the database
:param author: (str) Name of the author that said the quote
:param quote: (str) The quote for the author
:param created_at: (str) Timestamp for when the quote was saved to database
"""
with self.conn:
self.conn.execute('''
INSERT INTO quotes VALUES (?, ?, ?)
''', (author, quote, created_at))
# ... rest of the code ...
|
64b4abde42b653e66444876dee0700afa64e6c6b
|
releasetasks/test/__init__.py
|
releasetasks/test/__init__.py
|
import os
import yaml
def read_file(path):
with open(path) as f:
return f.read()
PVT_KEY_FILE = os.path.join(os.path.dirname(__file__), "id_rsa")
PVT_KEY = read_file(PVT_KEY_FILE)
PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "id_rsa.pub"))
OTHER_PUB_KEY = read_file(os.path.join(os.path.dirname(__file__),
"other_rsa.pub"))
DUMMY_PUBLIC_KEY = os.path.join(os.path.dirname(__file__), "public.key")
def create_test_args(non_standard_arguments, permitted_defaults=None):
with open(os.path.join(os.path.dirname(__file__), 'test_graph_parameters.yml')) as f:
default_arguments = yaml.safe_load(f)
default_arguments.update(non_standard_arguments)
if permitted_defaults is not None:
default_arguments = {
key: val
for key, val in default_arguments.items()
if key in non_standard_arguments or key in permitted_defaults
}
return default_arguments
|
import os
import yaml
def read_file(path):
with open(path) as f:
return f.read()
PVT_KEY_FILE = os.path.join(os.path.dirname(__file__), "id_rsa")
PVT_KEY = read_file(PVT_KEY_FILE)
PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "id_rsa.pub"))
OTHER_PUB_KEY = read_file(os.path.join(os.path.dirname(__file__),
"other_rsa.pub"))
DUMMY_PUBLIC_KEY = os.path.join(os.path.dirname(__file__), "public.key")
def create_test_args(non_standard_arguments):
with open(os.path.join(os.path.dirname(__file__), 'test_graph_parameters.yml')) as f:
default_arguments = yaml.safe_load(f)
default_arguments.update(non_standard_arguments)
return default_arguments
|
Remove redundant keyword argument from create_test_args
|
Remove redundant keyword argument from create_test_args
|
Python
|
mpl-2.0
|
mozilla/releasetasks,bhearsum/releasetasks,rail/releasetasks
|
python
|
## Code Before:
import os
import yaml
def read_file(path):
with open(path) as f:
return f.read()
PVT_KEY_FILE = os.path.join(os.path.dirname(__file__), "id_rsa")
PVT_KEY = read_file(PVT_KEY_FILE)
PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "id_rsa.pub"))
OTHER_PUB_KEY = read_file(os.path.join(os.path.dirname(__file__),
"other_rsa.pub"))
DUMMY_PUBLIC_KEY = os.path.join(os.path.dirname(__file__), "public.key")
def create_test_args(non_standard_arguments, permitted_defaults=None):
with open(os.path.join(os.path.dirname(__file__), 'test_graph_parameters.yml')) as f:
default_arguments = yaml.safe_load(f)
default_arguments.update(non_standard_arguments)
if permitted_defaults is not None:
default_arguments = {
key: val
for key, val in default_arguments.items()
if key in non_standard_arguments or key in permitted_defaults
}
return default_arguments
## Instruction:
Remove redundant keyword argument from create_test_args
## Code After:
import os
import yaml
def read_file(path):
with open(path) as f:
return f.read()
PVT_KEY_FILE = os.path.join(os.path.dirname(__file__), "id_rsa")
PVT_KEY = read_file(PVT_KEY_FILE)
PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "id_rsa.pub"))
OTHER_PUB_KEY = read_file(os.path.join(os.path.dirname(__file__),
"other_rsa.pub"))
DUMMY_PUBLIC_KEY = os.path.join(os.path.dirname(__file__), "public.key")
def create_test_args(non_standard_arguments):
with open(os.path.join(os.path.dirname(__file__), 'test_graph_parameters.yml')) as f:
default_arguments = yaml.safe_load(f)
default_arguments.update(non_standard_arguments)
return default_arguments
|
# ... existing code ...
DUMMY_PUBLIC_KEY = os.path.join(os.path.dirname(__file__), "public.key")
def create_test_args(non_standard_arguments):
with open(os.path.join(os.path.dirname(__file__), 'test_graph_parameters.yml')) as f:
default_arguments = yaml.safe_load(f)
default_arguments.update(non_standard_arguments)
return default_arguments
# ... rest of the code ...
|
50e86d63b382378f534c50769c2580abe903028e
|
src/test/java/de/bmoth/typechecker/TypeErrorExceptionTest.java
|
src/test/java/de/bmoth/typechecker/TypeErrorExceptionTest.java
|
package de.bmoth.typechecker;
import de.bmoth.parser.Parser;
import de.bmoth.parser.ast.TypeErrorException;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class TypeErrorExceptionTest {
@Test(expected = TypeErrorException.class)
public void testTypeErrorException() {
String formula = "a = TRUE & b = 1 & a = b";
Parser.getFormulaAsSemanticAst(formula);
}
@Test(expected = TypeErrorException.class)
public void testTypeErrorException2() {
String formula = "a = TRUE & a = 1 + 1";
Parser.getFormulaAsSemanticAst(formula);
}
@Test
public void testSetEnumeration() {
String formula = "x = {1,2,(3,4)}";
String exceptionMessage = getExceptionMessage(formula);
assertTrue(exceptionMessage != null &&exceptionMessage.contains("Expected INTEGER but found INTEGER*INTEGER"));
}
@Test
public void testSetEnumeration2() {
String formula = "x = {1,2,{3,4}}";
String exceptionMessage = getExceptionMessage(formula);
assertTrue(exceptionMessage != null &&exceptionMessage.contains("found POW"));
}
private static String getExceptionMessage(String formula) {
try {
Parser.getFormulaAsSemanticAst(formula);
fail("Expected a type error exception.");
return "";
} catch (TypeErrorException e) {
return e.getMessage();
}
}
}
|
package de.bmoth.typechecker;
import de.bmoth.parser.Parser;
import de.bmoth.parser.ast.TypeErrorException;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class TypeErrorExceptionTest {
@Test(expected = TypeErrorException.class)
public void testTypeErrorException() {
String formula = "a = TRUE & b = 1 & a = b";
Parser.getFormulaAsSemanticAst(formula);
}
@Test(expected = TypeErrorException.class)
public void testTypeErrorException2() {
String formula = "a = TRUE & a = 1 + 1";
Parser.getFormulaAsSemanticAst(formula);
}
@Test
public void testSetEnumeration() {
String formula = "x = {1,2,(3,4)}";
String exceptionMessage = getExceptionMessage(formula);
assertTrue(exceptionMessage.contains("Expected INTEGER but found INTEGER*INTEGER"));
}
@Test
public void testSetEnumeration2() {
String formula = "x = {1,2,{3,4}}";
String exceptionMessage = getExceptionMessage(formula);
assertTrue(exceptionMessage.contains("found POW"));
}
private static String getExceptionMessage(String formula) {
try {
Parser.getFormulaAsSemanticAst(formula);
fail("Expected a type error exception.");
return "";
} catch (TypeErrorException e) {
return e.getMessage();
}
}
}
|
Revert "fix "NullPionterException could be thrown"-bug, see sonar qube L28, L35"
|
Revert "fix "NullPionterException could be thrown"-bug, see sonar qube L28, L35"
This reverts commit 7acc0b6500e513183324e369455e5ebcce412087.
|
Java
|
mit
|
hhu-stups/bmoth
|
java
|
## Code Before:
package de.bmoth.typechecker;
import de.bmoth.parser.Parser;
import de.bmoth.parser.ast.TypeErrorException;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class TypeErrorExceptionTest {
@Test(expected = TypeErrorException.class)
public void testTypeErrorException() {
String formula = "a = TRUE & b = 1 & a = b";
Parser.getFormulaAsSemanticAst(formula);
}
@Test(expected = TypeErrorException.class)
public void testTypeErrorException2() {
String formula = "a = TRUE & a = 1 + 1";
Parser.getFormulaAsSemanticAst(formula);
}
@Test
public void testSetEnumeration() {
String formula = "x = {1,2,(3,4)}";
String exceptionMessage = getExceptionMessage(formula);
assertTrue(exceptionMessage != null &&exceptionMessage.contains("Expected INTEGER but found INTEGER*INTEGER"));
}
@Test
public void testSetEnumeration2() {
String formula = "x = {1,2,{3,4}}";
String exceptionMessage = getExceptionMessage(formula);
assertTrue(exceptionMessage != null &&exceptionMessage.contains("found POW"));
}
private static String getExceptionMessage(String formula) {
try {
Parser.getFormulaAsSemanticAst(formula);
fail("Expected a type error exception.");
return "";
} catch (TypeErrorException e) {
return e.getMessage();
}
}
}
## Instruction:
Revert "fix "NullPionterException could be thrown"-bug, see sonar qube L28, L35"
This reverts commit 7acc0b6500e513183324e369455e5ebcce412087.
## Code After:
package de.bmoth.typechecker;
import de.bmoth.parser.Parser;
import de.bmoth.parser.ast.TypeErrorException;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class TypeErrorExceptionTest {
@Test(expected = TypeErrorException.class)
public void testTypeErrorException() {
String formula = "a = TRUE & b = 1 & a = b";
Parser.getFormulaAsSemanticAst(formula);
}
@Test(expected = TypeErrorException.class)
public void testTypeErrorException2() {
String formula = "a = TRUE & a = 1 + 1";
Parser.getFormulaAsSemanticAst(formula);
}
@Test
public void testSetEnumeration() {
String formula = "x = {1,2,(3,4)}";
String exceptionMessage = getExceptionMessage(formula);
assertTrue(exceptionMessage.contains("Expected INTEGER but found INTEGER*INTEGER"));
}
@Test
public void testSetEnumeration2() {
String formula = "x = {1,2,{3,4}}";
String exceptionMessage = getExceptionMessage(formula);
assertTrue(exceptionMessage.contains("found POW"));
}
private static String getExceptionMessage(String formula) {
try {
Parser.getFormulaAsSemanticAst(formula);
fail("Expected a type error exception.");
return "";
} catch (TypeErrorException e) {
return e.getMessage();
}
}
}
|
# ... existing code ...
public void testSetEnumeration() {
String formula = "x = {1,2,(3,4)}";
String exceptionMessage = getExceptionMessage(formula);
assertTrue(exceptionMessage.contains("Expected INTEGER but found INTEGER*INTEGER"));
}
@Test
# ... modified code ...
public void testSetEnumeration2() {
String formula = "x = {1,2,{3,4}}";
String exceptionMessage = getExceptionMessage(formula);
assertTrue(exceptionMessage.contains("found POW"));
}
private static String getExceptionMessage(String formula) {
# ... rest of the code ...
|
c74b3a4d80b8d7002b6836a421cf2b3032377545
|
filterable.py
|
filterable.py
|
class Filterable:
no_delays_filter = lambda filterable: filterable.condition.record_id == str(6)
query_delay_filter = lambda filterable: filterable.condition.record_id == str(7)
document_delay_filter = lambda filterable: filterable.condition.record_id == str(8)
combined_delay_filter = lambda filterable: filterable.condition.record_id == str(9)
identity_filter = lambda filterable: True
@staticmethod
def combine_filters( *filters ):
return lambda filterable: all([fil( filterable ) for fil in filters])
|
class Filterable:
no_delays_filter = lambda filterable: filterable.condition.record_id == str(6)
query_delay_filter = lambda filterable: filterable.condition.record_id == str(7)
document_delay_filter = lambda filterable: filterable.condition.record_id == str(8)
combined_delay_filter = lambda filterable: filterable.condition.record_id == str(9)
practice_topic_reject_filter = lambda filterable: filterable.topic.record_id != str(367)
identity_filter = lambda filterable: True
@staticmethod
def combine_filters( *filters ):
return lambda filterable: all([fil( filterable ) for fil in filters])
|
Add filter for rejecting practice topic
|
Add filter for rejecting practice topic
|
Python
|
mit
|
fire-uta/iiix-data-parser
|
python
|
## Code Before:
class Filterable:
no_delays_filter = lambda filterable: filterable.condition.record_id == str(6)
query_delay_filter = lambda filterable: filterable.condition.record_id == str(7)
document_delay_filter = lambda filterable: filterable.condition.record_id == str(8)
combined_delay_filter = lambda filterable: filterable.condition.record_id == str(9)
identity_filter = lambda filterable: True
@staticmethod
def combine_filters( *filters ):
return lambda filterable: all([fil( filterable ) for fil in filters])
## Instruction:
Add filter for rejecting practice topic
## Code After:
class Filterable:
no_delays_filter = lambda filterable: filterable.condition.record_id == str(6)
query_delay_filter = lambda filterable: filterable.condition.record_id == str(7)
document_delay_filter = lambda filterable: filterable.condition.record_id == str(8)
combined_delay_filter = lambda filterable: filterable.condition.record_id == str(9)
practice_topic_reject_filter = lambda filterable: filterable.topic.record_id != str(367)
identity_filter = lambda filterable: True
@staticmethod
def combine_filters( *filters ):
return lambda filterable: all([fil( filterable ) for fil in filters])
|
// ... existing code ...
document_delay_filter = lambda filterable: filterable.condition.record_id == str(8)
combined_delay_filter = lambda filterable: filterable.condition.record_id == str(9)
practice_topic_reject_filter = lambda filterable: filterable.topic.record_id != str(367)
identity_filter = lambda filterable: True
@staticmethod
// ... rest of the code ...
|
c4b67845124470a2f7609643412e480fad3ae4dd
|
src/com/joelapenna/foursquared/test/FoursquaredAppTestCase.java
|
src/com/joelapenna/foursquared/test/FoursquaredAppTestCase.java
|
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.test;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquared.Foursquared;
import android.test.ApplicationTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
/**
* @author Joe LaPenna ([email protected])
*
*/
public class FoursquaredAppTestCase extends ApplicationTestCase<Foursquared> {
public FoursquaredAppTestCase() {
super(Foursquared.class);
}
@MediumTest
public void testLocationMethods() {
createApplication();
getApplication().getLastKnownLocation();
getApplication().getLocationListener();
}
@SmallTest
public void testPreferences() {
createApplication();
Foursquared foursquared = getApplication();
Foursquare foursquare = foursquared.getFoursquare();
// ... to be continued.
}
}
|
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.test;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquared.Foursquared;
import android.test.ApplicationTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
/**
* @author Joe LaPenna ([email protected])
*/
public class FoursquaredAppTestCase extends ApplicationTestCase<Foursquared> {
public FoursquaredAppTestCase() {
super(Foursquared.class);
}
@MediumTest
public void testLocationMethods() {
createApplication();
getApplication().getLastKnownLocation();
getApplication().getLocationListener();
}
@SmallTest
public void testPreferences() {
createApplication();
Foursquared foursquared = getApplication();
foursquared.getFoursquare();
// ... to be continued.
}
}
|
Fix formatting and a warning for FoursqauredAppTestCase.
|
Fix formatting and a warning for FoursqauredAppTestCase.
committer: Joe LaPenna <[email protected]>
|
Java
|
apache-2.0
|
izBasit/foursquared.eclair,idmouh/foursquared.eclair,weizp/foursquared.eclair,sevenOneHero/foursquared.eclair,appoll/foursquared,rihtak/foursquared.eclair,nextzy/foursquared.eclair,since2014/foursquared,edwinsnao/foursquared.eclair,kvnh/foursquared,xytrams/foursquared.eclair,navesdad/foursquared,BinodAryal/foursquared,summerzhao/foursquared,gokultaka/foursquared,rahulnagar8/foursquared,harajuko/foursquared.eclair,sbolisetty/foursquared,foobarprime/foursquared,sathiamour/foursquared,smakeit/foursquared,kiruthikak/foursquared.eclair,BinodAryal/foursquared.eclair,shivasrinath/foursquared.eclair,hejie/foursquared.eclair,RameshBhupathi/foursquared.eclair,kvnh/foursquared,tyzhaoqi/foursquared,osiloke/foursquared.eclair,ramaraokotu/foursquared,smallperson/foursquared.eclair,akhilesh9205/foursquared.eclair,savelees/foursquared,solubrew/foursquared,manisoni28/foursquared,bubao/foursquared,waasilzamri/foursquared,psvijayk/foursquared,zhoujianhanyu/foursquared,votinhaooo/foursquared.eclair,weizp/foursquared.eclair,sbagadi/foursquared,azai91/foursquared,isaiasmercadom/foursquared.eclair,RameshBhupathi/foursquared,ekospinach/foursquared.eclair,starspace/foursquared.eclair,appoll/foursquared,mypapit/foursquared,artificiallight92/foursquared.eclair,tahainfocreator/foursquared,ACCTFORGH/foursquared,isaiasmercadom/foursquared,jotish/foursquared,ACCTFORGH/foursquared.eclair,tianyong2/foursquared.eclair,harajuko/foursquared,thenewnewbie/foursquared.eclair,sandeip-yadav/foursquared,lxz2014/foursquared.eclair,yusuf-shalahuddin/foursquared.eclair,donka-s27/foursquared,gabtni/foursquared,nasvil/foursquared,harajuko/foursquared,Mutai/foursquared.eclair,foobarprime/foursquared,tamzi/foursquared.eclair,coersum01/foursquared,solubrew/foursquared,sbagadi/foursquared.eclair,RameshBhupathi/foursquared,kolawoletech/foursquared,sovaa/foursquared,4DvAnCeBoY/foursquared,CoderJackyHuang/foursquared.eclair,davideuler/foursquared,martadewi/foursquared,karthikkumar12/foursquared.eclair,EphraimKigamba/foursquared,hunanlike/foursquared,psvijayk/foursquared,ckarademir/foursquared.eclair,xuyunhong/foursquared,ksrpraneeth/foursquared.eclair,ayndev/foursquared.eclair,zhoujianhanyu/foursquared,abedmaatalla/foursquared,ksrpraneeth/foursquared.eclair,malathicode/foursquared,since2014/foursquared.eclair,MarginC/foursquared,sibendu/foursquared,sonyraj/foursquared.eclair,daya-shankar/foursquared.eclair,pratikjk/foursquared.eclair,osiloke/foursquared,psvijayk/foursquared.eclair,osiloke/foursquared.eclair,nasvil/foursquared,Bishwajet/foursquared,shrikantzarekar/foursquared,Archenemy-xiatian/foursquared,azai91/foursquared.eclair,lxz2014/foursquared,edwinsnao/foursquared,Bishwajet/foursquared.eclair,lenkyun/foursquared,azizjonm/foursquared,itzmesayooj/foursquared,abdallahynajar/foursquared,savelees/foursquared.eclair,votinhaooo/foursquared,ragesh91/foursquared,akhilesh9205/foursquared,sevenOneHero/foursquared.eclair,zhmkof/foursquared.eclair,psvijayk/foursquared.eclair,haithemhamzaoui/foursquared,waasilzamri/foursquared,manisoni28/foursquared.eclair,rahulnagar8/foursquared,RahulRavindren/foursquared,NarikSmouke228/foursquared.eclair,hunanlike/foursquared.eclair,karthikkumar12/foursquared.eclair,shivasrinath/foursquared.eclair,donka-s27/foursquared,Zebronaft/foursquared,izBasit/foursquared,karanVkgp/foursquared.eclair,ckarademir/foursquared,izBasit/foursquared,pratikjk/foursquared.eclair,edwinsnao/foursquared.eclair,haithemhamzaoui/foursquared.eclair,navesdad/foursquared.eclair,malathicode/foursquared.eclair,nluetkemeyer/foursquared,edwinsnao/foursquared,murat8505/foursquared.eclair,martinx/martinxus-foursquared,varunprathap/foursquared.eclair,shivasrinath/foursquared,sbagadi/foursquared.eclair,smallperson/foursquared.eclair,ekospinach/foursquared,ramaraokotu/foursquared.eclair,yusuf-shalahuddin/foursquared,kvnh/foursquared.eclair,dhysf/foursquared,Bishwajet/foursquared,rguindon/raymondeguindon-foursquared,itrobertson/foursquared,coersum01/foursquared.eclair,tianyong2/foursquared,jamesmartins/foursquared.eclair,foobarprime/foursquared,rahul18cool/foursquared.eclair,4DvAnCeBoY/foursquared,sibendu/foursquared,yusuf-shalahuddin/foursquared.eclair,ragesh91/foursquared.eclair,martinx/martinxus-foursquared,nasvil/foursquared,tianyong2/foursquared.eclair,sbolisetty/foursquared.eclair,tamzi/foursquared.eclair,rahul18cool/foursquared.eclair,karanVkgp/foursquared,ming0627/foursquared,idmouh/foursquared,lenkyun/foursquared,ksrpraneeth/foursquared,varunprathap/foursquared,jamesmartins/foursquared,bancool/foursquared.eclair,sathiamour/foursquared,donka-s27/foursquared,codingz/foursquared,vsvankhede/foursquared.eclair,jotish/foursquared.eclair,zhoujianhanyu/foursquared.eclair,zhmkof/foursquared.eclair,itzmesayooj/foursquared,prashantkumar0509/foursquared,ekospinach/foursquared,xzamirx/foursquared.eclair,foobarprime/foursquared.eclair,waasilzamri/foursquared,gtostock/foursquared.eclair,andrewjsauer/foursquared,jiveshwar/foursquared.eclair,davideuler/foursquared.eclair,ewugreensignal/foursquared,BinodAryal/foursquared.eclair,santoshmehta82/foursquared,solubrew/foursquared,osiloke/foursquared,psvijayk/foursquared,dhysf/foursquared,malathicode/foursquared,ksrpraneeth/foursquared,yusuf-shalahuddin/foursquared,osiloke/foursquared,bubao/foursquared.eclair,abdallahynajar/foursquared.eclair,nluetkemeyer/foursquared,shrikantzarekar/foursquared,ayndev/foursquared,kitencx/foursquared,cairenjie1985/foursquared,mikehowson/foursquared,since2014/foursquared,kvnh/foursquared.eclair,donka-s27/foursquared.eclair,sovaa/foursquared,tianyong2/foursquared,dreamapps786/foursquared,ramaraokotu/foursquared,mansourifatimaezzahraa/foursquared,pratikjk/foursquared,Mutai/foursquared,4DvAnCeBoY/foursquared.eclair,starspace/foursquared,lepinay/foursquared,fatihcelik/foursquared.eclair,navesdad/foursquared,jotish/foursquared,karthikkumar12/foursquared,malathicode/foursquared,dreamapps786/foursquared.eclair,xytrams/foursquared,sovaa/foursquared,Zebronaft/foursquared,rguindon/raymondeguindon-foursquared,isaiasmercadom/foursquared,suman4674/foursquared,itzmesayooj/foursquared.eclair,stonyyi/foursquared,waasilzamri/foursquared.eclair,forevervhuo/foursquared.eclair,akhilesh9205/foursquared,zhoujianhanyu/foursquared,mikehowson/foursquared.eclair,tyzhaoqi/foursquared.eclair,4DvAnCeBoY/foursquared,murat8505/foursquared.eclair,nehalok/foursquared,kitencx/foursquared,srikanthguduru/foursquared,dreamapps786/foursquared.eclair,mayankz/foursquared,tahainfocreator/foursquared,PriteshJain/foursquared.eclair,NarikSmouke228/foursquared,lepinay/foursquared,suripaleru/foursquared,sandeip-yadav/foursquared.eclair,gtostock/foursquared,tyzhaoqi/foursquared,Zebronaft/foursquared.eclair,suman4674/foursquared,jamesmartins/foursquared,lxz2014/foursquared.eclair,sibendu/foursquared,stonyyi/foursquared,EphraimKigamba/foursquared,nextzy/foursquared,BinodAryal/foursquared,votinhaooo/foursquared.eclair,RameshBhupathi/foursquared.eclair,coersum01/foursquared,savelees/foursquared,kolawoletech/foursquared,votinhaooo/foursquared,wenkeyang/foursquared,AnthonyCAS/foursquared.eclair,NarikSmouke228/foursquared.eclair,sakethkaparthi/foursquared,sbolisetty/foursquared,xytrams/foursquared,ckarademir/foursquared,edwinsnao/foursquared,rihtak/foursquared.eclair,codingz/foursquared,rihtak/foursquared,xuyunhong/foursquared,omondiy/foursquared,thenewnewbie/foursquared,aasaandinesh/foursquared.eclair,jamesmartins/foursquared,rahulnagar8/foursquared.eclair,BinodAryal/foursquared,pratikjk/foursquared,martadewi/foursquared,mansourifatimaezzahraa/foursquared,paulodiogo/foursquared.eclair,ACCTFORGH/foursquared.eclair,lxz2014/foursquared,martadewi/foursquared.eclair,foobarprime/foursquared.eclair,tyzhaoqi/foursquared.eclair,vsvankhede/foursquared.eclair,santoshmehta82/foursquared.eclair,abedmaatalla/foursquared.eclair,Archenemy-xiatian/foursquared.eclair,gabtni/foursquared,cairenjie1985/foursquared.eclair,abedmaatalla/foursquared.eclair,smakeit/foursquared.eclair,manisoni28/foursquared,tyzhaoqi/foursquared,sathiamour/foursquared,shivasrinath/foursquared,savelees/foursquared.eclair,daya-shankar/foursquared,thenewnewbie/foursquared.eclair,paulodiogo/foursquared.eclair,andrewjsauer/foursquared,azai91/foursquared,632840804/foursquared.eclair,AnthonyCAS/foursquared.eclair,tahainfocreator/foursquared.eclair,haithemhamzaoui/foursquared.eclair,xytrams/foursquared.eclair,hardikamal/foursquared,mansourifatimaezzahraa/foursquared.eclair,RahulRavindren/foursquared.eclair,suman4674/foursquared.eclair,nehalok/foursquared,Zebronaft/foursquared,RahulRavindren/foursquared,thtak/foursquared,cairenjie1985/foursquared,itrobertson/foursquared,jiveshwar/foursquared.eclair,gabtni/foursquared,coersum01/foursquared,mayankz/foursquared,stonyyi/foursquared.eclair,hejie/foursquared,fatihcelik/foursquared,vsvankhede/foursquared,nextzy/foursquared,CoderJackyHuang/foursquared.eclair,weizp/foursquared,sonyraj/foursquared,varunprathap/foursquared,stonyyi/foursquared,PriteshJain/foursquared,gtostock/foursquared,nara-l/foursquared,kiruthikak/foursquared,idmouh/foursquared.eclair,karanVkgp/foursquared.eclair,wenkeyang/foursquared,fuzhou0099/foursquared.eclair,prashantkumar0509/foursquared,fatihcelik/foursquared.eclair,kolawoletech/foursquared,nara-l/foursquared,itzmesayooj/foursquared.eclair,loganj/foursquared,waasilzamri/foursquared.eclair,hardikamal/foursquared.eclair,Zebronaft/foursquared.eclair,ramaraokotu/foursquared.eclair,lxz2014/foursquared,haithemhamzaoui/foursquared,martadewi/foursquared,sathiamour/foursquared.eclair,wenkeyang/foursquared.eclair,andrewjsauer/foursquared,savelees/foursquared,abou78180/foursquared,artificiallight92/foursquared,NarikSmouke228/foursquared,shrikantzarekar/foursquared.eclair,Archenemy-xiatian/foursquared.eclair,rahulnagar8/foursquared,dreamapps786/foursquared,RameshBhupathi/foursquared,gtostock/foursquared.eclair,dhysf/foursquared.eclair,donka-s27/foursquared.eclair,mansourifatimaezzahraa/foursquared,sovaa/foursquared.eclair,bancool/foursquared.eclair,abedmaatalla/foursquared,lepinay/foursquared.eclair,EphraimKigamba/foursquared.eclair,Mutai/foursquared,hejie/foursquared,smallperson/foursquared,ckarademir/foursquared.eclair,xuyunhong/foursquared.eclair,gokultaka/foursquared.eclair,ksrpraneeth/foursquared,bubao/foursquared,abou78180/foursquared.eclair,dhysf/foursquared,ragesh91/foursquared,artificiallight92/foursquared,harajuko/foursquared.eclair,Bishwajet/foursquared.eclair,suripaleru/foursquared.eclair,lepinay/foursquared.eclair,santoshmehta82/foursquared.eclair,suman4674/foursquared,abdallahynajar/foursquared,daya-shankar/foursquared.eclair,EphraimKigamba/foursquared.eclair,davideuler/foursquared,mypapit/foursquared,nasvil/foursquared.eclair,smakeit/foursquared.eclair,kiruthikak/foursquared,bancool/foursquared,nextzy/foursquared,aasaandinesh/foursquared,Archenemy-xiatian/foursquared,nasvil/foursquared.eclair,kitencx/foursquared,nluetkemeyer/foursquared,murat8505/foursquared,hunanlike/foursquared,hunanlike/foursquared.eclair,ekospinach/foursquared,sbolisetty/foursquared,ACCTFORGH/foursquared,omondiy/foursquared.eclair,gabtni/foursquared.eclair,izBasit/foursquared.eclair,nara-l/foursquared,bubao/foursquared,ming0627/foursquared,codingz/foursquared,mayankz/foursquared,smallperson/foursquared,thtak/foursquared,daya-shankar/foursquared,summerzhao/foursquared,karanVkgp/foursquared,hejie/foursquared.eclair,murat8505/foursquared,harajuko/foursquared,shrikantzarekar/foursquared,ACCTFORGH/foursquared,sbagadi/foursquared,RahulRavindren/foursquared.eclair,4DvAnCeBoY/foursquared.eclair,votinhaooo/foursquared,shrikantzarekar/foursquared.eclair,abou78180/foursquared,omondiy/foursquared,thenewnewbie/foursquared,prashantkumar0509/foursquared.eclair,kiruthikak/foursquared,tamzi/foursquared,isaiasmercadom/foursquared,srikanthguduru/foursquared.eclair,since2014/foursquared,weizp/foursquared,srikanthguduru/foursquared.eclair,rahul18cool/foursquared,summerzhao/foursquared.eclair,yusuf-shalahuddin/foursquared,loganj/foursquared,ewugreensignal/foursquared,kolawoletech/foursquared.eclair,azai91/foursquared,ramaraokotu/foursquared,wenkeyang/foursquared,Bishwajet/foursquared,vsvankhede/foursquared,varunprathap/foursquared.eclair,since2014/foursquared.eclair,dreamapps786/foursquared,Mutai/foursquared.eclair,fatihcelik/foursquared,artificiallight92/foursquared.eclair,ayndev/foursquared.eclair,xuyunhong/foursquared,hardikamal/foursquared,izBasit/foursquared,srikanthguduru/foursquared,kiruthikak/foursquared.eclair,gtostock/foursquared,gokultaka/foursquared,abou78180/foursquared.eclair,azizjonm/foursquared,sonyraj/foursquared,suman4674/foursquared.eclair,nara-l/foursquared.eclair,rguindon/raymondeguindon-foursquared,mikehowson/foursquared,jotish/foursquared,suripaleru/foursquared,itrobertson/foursquared,aasaandinesh/foursquared.eclair,gokultaka/foursquared.eclair,sevenOneHero/foursquared.eclair,azizjonm/foursquared,dhysf/foursquared.eclair,tahainfocreator/foursquared,nluetkemeyer/foursquared.eclair,karthikkumar12/foursquared,PriteshJain/foursquared,summerzhao/foursquared.eclair,weizp/foursquared,manisoni28/foursquared.eclair,appoll/foursquared,ayndev/foursquared,rahul18cool/foursquared,jotish/foursquared.eclair,starspace/foursquared,santoshmehta82/foursquared,isaiasmercadom/foursquared.eclair,varunprathap/foursquared,idmouh/foursquared,rihtak/foursquared,itzmesayooj/foursquared,thtak/foursquared,tianyong2/foursquared,haithemhamzaoui/foursquared,sovaa/foursquared.eclair,srikanthguduru/foursquared,smakeit/foursquared,rihtak/foursquared,Archenemy-xiatian/foursquared,daya-shankar/foursquared,solubrew/foursquared.eclair,bancool/foursquared,ckarademir/foursquared,smakeit/foursquared,hunanlike/foursquared,sonyraj/foursquared,thtak/foursquared.eclair,bancool/foursquared,zhoujianhanyu/foursquared.eclair,starspace/foursquared,codingz/foursquared.eclair,PriteshJain/foursquared,thtak/foursquared.eclair,azai91/foursquared.eclair,sbolisetty/foursquared.eclair,kvnh/foursquared,rahulnagar8/foursquared.eclair,cairenjie1985/foursquared,sonyraj/foursquared.eclair,suripaleru/foursquared.eclair,stonyyi/foursquared.eclair,wenkeyang/foursquared.eclair,sathiamour/foursquared.eclair,prashantkumar0509/foursquared.eclair,karanVkgp/foursquared,summerzhao/foursquared,prashantkumar0509/foursquared,sakethkaparthi/foursquared,artificiallight92/foursquared,sibendu/foursquared.eclair,mypapit/foursquared,abedmaatalla/foursquared,davideuler/foursquared.eclair,starspace/foursquared.eclair,pratikjk/foursquared,lenkyun/foursquared,davideuler/foursquared,PriteshJain/foursquared.eclair,mansourifatimaezzahraa/foursquared.eclair,forevervhuo/foursquared.eclair,thenewnewbie/foursquared,xytrams/foursquared,hardikamal/foursquared,idmouh/foursquared,aasaandinesh/foursquared,ewugreensignal/foursquared,ming0627/foursquared,sbagadi/foursquared,nextzy/foursquared.eclair,akhilesh9205/foursquared,RahulRavindren/foursquared,NarikSmouke228/foursquared,sakethkaparthi/foursquared,ekospinach/foursquared.eclair,akhilesh9205/foursquared.eclair,gokultaka/foursquared,navesdad/foursquared,ragesh91/foursquared,fatihcelik/foursquared,ragesh91/foursquared.eclair,Mutai/foursquared,murat8505/foursquared,sandeip-yadav/foursquared.eclair,fuzhou0099/foursquared.eclair,tahainfocreator/foursquared.eclair,martadewi/foursquared.eclair,sibendu/foursquared.eclair,lepinay/foursquared,karthikkumar12/foursquared,nara-l/foursquared.eclair,632840804/foursquared.eclair,omondiy/foursquared,tamzi/foursquared,hejie/foursquared,kolawoletech/foursquared.eclair,smallperson/foursquared,santoshmehta82/foursquared,xuyunhong/foursquared.eclair,mikehowson/foursquared.eclair,nehalok/foursquared.eclair,ming0627/foursquared.eclair,xzamirx/foursquared.eclair,manisoni28/foursquared,abdallahynajar/foursquared.eclair,bubao/foursquared.eclair,malathicode/foursquared.eclair,MarginC/foursquared,mikehowson/foursquared,tamzi/foursquared,EphraimKigamba/foursquared,navesdad/foursquared.eclair,gabtni/foursquared.eclair,sandeip-yadav/foursquared,martinx/martinxus-foursquared,aasaandinesh/foursquared,jamesmartins/foursquared.eclair,ewugreensignal/foursquared.eclair,nehalok/foursquared,cairenjie1985/foursquared.eclair,abou78180/foursquared,vsvankhede/foursquared,codingz/foursquared.eclair,nluetkemeyer/foursquared.eclair,shivasrinath/foursquared,hardikamal/foursquared.eclair,abdallahynajar/foursquared,ming0627/foursquared.eclair,MarginC/foursquared,sandeip-yadav/foursquared,ewugreensignal/foursquared.eclair,ayndev/foursquared,solubrew/foursquared.eclair,coersum01/foursquared.eclair,rahul18cool/foursquared,nehalok/foursquared.eclair,omondiy/foursquared.eclair,suripaleru/foursquared
|
java
|
## Code Before:
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.test;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquared.Foursquared;
import android.test.ApplicationTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
/**
* @author Joe LaPenna ([email protected])
*
*/
public class FoursquaredAppTestCase extends ApplicationTestCase<Foursquared> {
public FoursquaredAppTestCase() {
super(Foursquared.class);
}
@MediumTest
public void testLocationMethods() {
createApplication();
getApplication().getLastKnownLocation();
getApplication().getLocationListener();
}
@SmallTest
public void testPreferences() {
createApplication();
Foursquared foursquared = getApplication();
Foursquare foursquare = foursquared.getFoursquare();
// ... to be continued.
}
}
## Instruction:
Fix formatting and a warning for FoursqauredAppTestCase.
committer: Joe LaPenna <[email protected]>
## Code After:
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.test;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquared.Foursquared;
import android.test.ApplicationTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
/**
* @author Joe LaPenna ([email protected])
*/
public class FoursquaredAppTestCase extends ApplicationTestCase<Foursquared> {
public FoursquaredAppTestCase() {
super(Foursquared.class);
}
@MediumTest
public void testLocationMethods() {
createApplication();
getApplication().getLastKnownLocation();
getApplication().getLocationListener();
}
@SmallTest
public void testPreferences() {
createApplication();
Foursquared foursquared = getApplication();
foursquared.getFoursquare();
// ... to be continued.
}
}
|
// ... existing code ...
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.test;
import com.joelapenna.foursquare.Foursquare;
// ... modified code ...
/**
* @author Joe LaPenna ([email protected])
*/
public class FoursquaredAppTestCase extends ApplicationTestCase<Foursquared> {
...
public void testPreferences() {
createApplication();
Foursquared foursquared = getApplication();
foursquared.getFoursquare();
// ... to be continued.
}
}
// ... rest of the code ...
|
8ebf9e62be0107957f868578fe704f05fde6329f
|
view/src/main/java/org/xcolab/view/pages/contestmanagement/beans/BatchRegisterBean.java
|
view/src/main/java/org/xcolab/view/pages/contestmanagement/beans/BatchRegisterBean.java
|
package org.xcolab.view.pages.contestmanagement.beans;
import org.hibernate.validator.constraints.NotBlank;
import java.io.Serializable;
public class BatchRegisterBean implements Serializable {
@NotBlank
private Boolean asGuests;
@NotBlank
private String batchText;
public String getBatchText() {
return batchText;
}
public void setBatchText(String batchText) {
this.batchText = batchText;
}
public Boolean getAsGuests() {
return asGuests;
}
public void setAsGuest(Boolean asGuests) {
this.asGuests = asGuests;
}
@Override
public String toString() {
return "BatchRegisterBean [batchText='" + batchText + "', asGuests='" + asGuests.toString() + "']";
}
}
|
package org.xcolab.view.pages.contestmanagement.beans;
import org.hibernate.validator.constraints.NotBlank;
import java.io.Serializable;
public class BatchRegisterBean implements Serializable {
@NotBlank
private boolean asGuests;
@NotBlank
private String batchText;
public String getBatchText() {
return batchText;
}
public void setBatchText(String batchText) {
this.batchText = batchText;
}
public boolean getAsGuests() {
return asGuests;
}
public void setAsGuest(boolean asGuests) {
this.asGuests = asGuests;
}
@Override
public String toString() {
return "BatchRegisterBean [batchText='" + batchText + "', asGuests='" + String.valueOf(asGuests) + "']";
}
}
|
Fix null pointer error for asGuests in batchRegister
|
Fix null pointer error for asGuests in batchRegister
|
Java
|
mit
|
CCI-MIT/XCoLab,CCI-MIT/XCoLab,CCI-MIT/XCoLab,CCI-MIT/XCoLab
|
java
|
## Code Before:
package org.xcolab.view.pages.contestmanagement.beans;
import org.hibernate.validator.constraints.NotBlank;
import java.io.Serializable;
public class BatchRegisterBean implements Serializable {
@NotBlank
private Boolean asGuests;
@NotBlank
private String batchText;
public String getBatchText() {
return batchText;
}
public void setBatchText(String batchText) {
this.batchText = batchText;
}
public Boolean getAsGuests() {
return asGuests;
}
public void setAsGuest(Boolean asGuests) {
this.asGuests = asGuests;
}
@Override
public String toString() {
return "BatchRegisterBean [batchText='" + batchText + "', asGuests='" + asGuests.toString() + "']";
}
}
## Instruction:
Fix null pointer error for asGuests in batchRegister
## Code After:
package org.xcolab.view.pages.contestmanagement.beans;
import org.hibernate.validator.constraints.NotBlank;
import java.io.Serializable;
public class BatchRegisterBean implements Serializable {
@NotBlank
private boolean asGuests;
@NotBlank
private String batchText;
public String getBatchText() {
return batchText;
}
public void setBatchText(String batchText) {
this.batchText = batchText;
}
public boolean getAsGuests() {
return asGuests;
}
public void setAsGuest(boolean asGuests) {
this.asGuests = asGuests;
}
@Override
public String toString() {
return "BatchRegisterBean [batchText='" + batchText + "', asGuests='" + String.valueOf(asGuests) + "']";
}
}
|
...
public class BatchRegisterBean implements Serializable {
@NotBlank
private boolean asGuests;
@NotBlank
private String batchText;
...
this.batchText = batchText;
}
public boolean getAsGuests() {
return asGuests;
}
public void setAsGuest(boolean asGuests) {
this.asGuests = asGuests;
}
@Override
public String toString() {
return "BatchRegisterBean [batchText='" + batchText + "', asGuests='" + String.valueOf(asGuests) + "']";
}
}
...
|
8c73f1845a1807b506cac1797e2f1247cde5a164
|
setup.py
|
setup.py
|
"""Setup for PyPi"""
from setuptools import setup
setup(
name='nik',
packages=['nik'],
version='1.0',
description='Nifty tools and containers',
author='Nik Vanderhoof',
author_email='[email protected]',
url='https://github.com/nvander1/nik',
download_url='https://github.com/nvander1/nik/archive/1.0.tar.gz',
keywords=['container', 'namedtuple'],
classifiers=[]
)
|
"""Setup for PyPi"""
from setuptools import setup
setup(
name='nik',
packages=['nik'],
version='1.0',
description='Nifty tools and containers',
author='Nik Vanderhoof',
author_email='[email protected]',
url='https://github.com/nvander1/nik',
download_url='https://github.com/nvander1/nik/archive/1.0.tar.gz',
keywords=['container', 'namedtuple'],
classifiers=[]
)
|
Stop using borked local pylintrc
|
Stop using borked local pylintrc
|
Python
|
mit
|
nvander1/skrt
|
python
|
## Code Before:
"""Setup for PyPi"""
from setuptools import setup
setup(
name='nik',
packages=['nik'],
version='1.0',
description='Nifty tools and containers',
author='Nik Vanderhoof',
author_email='[email protected]',
url='https://github.com/nvander1/nik',
download_url='https://github.com/nvander1/nik/archive/1.0.tar.gz',
keywords=['container', 'namedtuple'],
classifiers=[]
)
## Instruction:
Stop using borked local pylintrc
## Code After:
"""Setup for PyPi"""
from setuptools import setup
setup(
name='nik',
packages=['nik'],
version='1.0',
description='Nifty tools and containers',
author='Nik Vanderhoof',
author_email='[email protected]',
url='https://github.com/nvander1/nik',
download_url='https://github.com/nvander1/nik/archive/1.0.tar.gz',
keywords=['container', 'namedtuple'],
classifiers=[]
)
|
# ... existing code ...
from setuptools import setup
setup(
name='nik',
packages=['nik'],
version='1.0',
description='Nifty tools and containers',
author='Nik Vanderhoof',
author_email='[email protected]',
url='https://github.com/nvander1/nik',
download_url='https://github.com/nvander1/nik/archive/1.0.tar.gz',
keywords=['container', 'namedtuple'],
classifiers=[]
)
# ... rest of the code ...
|
97461cc2b13d7084eeb38442b845cf1d96621364
|
Ashton/AshtonObjc/AshtonObjcMixedContentPreprocessor.h
|
Ashton/AshtonObjc/AshtonObjcMixedContentPreprocessor.h
|
//
// AshtonObjcMixedContentPreprocessor.h
// Ashton
//
// Created by Michael Schwarz on 15.01.18.
// Copyright © 2018 Michael Schwarz. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface AshtonObjcMixedContentPreprocessor: NSObject
- (NSString *)preprocessHTMLString:(NSString *)htmlString;
@end
NS_ASSUME_NONNULL_END
|
//
// AshtonObjcMixedContentPreprocessor.h
// Ashton
//
// Created by Michael Schwarz on 15.01.18.
// Copyright © 2018 Michael Schwarz. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/// TBXML parser cannot handle html mixed content, therefore we have to preprocess it
/// mixedContent = "<html>test <strong>sample</strong></html>", will be processed to
/// "<html><wrapped>test </wrapped><strong><wrapped>sample</wrapped></strong></html>
@interface AshtonObjcMixedContentPreprocessor: NSObject
- (NSString *)preprocessHTMLString:(NSString *)htmlString;
@end
NS_ASSUME_NONNULL_END
|
Add comment regarding mixed content preprocessor
|
Add comment regarding mixed content preprocessor
|
C
|
mit
|
IdeasOnCanvas/Ashton,IdeasOnCanvas/Ashton,IdeasOnCanvas/Ashton
|
c
|
## Code Before:
//
// AshtonObjcMixedContentPreprocessor.h
// Ashton
//
// Created by Michael Schwarz on 15.01.18.
// Copyright © 2018 Michael Schwarz. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface AshtonObjcMixedContentPreprocessor: NSObject
- (NSString *)preprocessHTMLString:(NSString *)htmlString;
@end
NS_ASSUME_NONNULL_END
## Instruction:
Add comment regarding mixed content preprocessor
## Code After:
//
// AshtonObjcMixedContentPreprocessor.h
// Ashton
//
// Created by Michael Schwarz on 15.01.18.
// Copyright © 2018 Michael Schwarz. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/// TBXML parser cannot handle html mixed content, therefore we have to preprocess it
/// mixedContent = "<html>test <strong>sample</strong></html>", will be processed to
/// "<html><wrapped>test </wrapped><strong><wrapped>sample</wrapped></strong></html>
@interface AshtonObjcMixedContentPreprocessor: NSObject
- (NSString *)preprocessHTMLString:(NSString *)htmlString;
@end
NS_ASSUME_NONNULL_END
|
...
NS_ASSUME_NONNULL_BEGIN
/// TBXML parser cannot handle html mixed content, therefore we have to preprocess it
/// mixedContent = "<html>test <strong>sample</strong></html>", will be processed to
/// "<html><wrapped>test </wrapped><strong><wrapped>sample</wrapped></strong></html>
@interface AshtonObjcMixedContentPreprocessor: NSObject
- (NSString *)preprocessHTMLString:(NSString *)htmlString;
...
|
91a0c9a9633a1d795934091fec5abd053730758c
|
hist/inc/TH1I.h
|
hist/inc/TH1I.h
|
// @(#)root/hist:$Name: $:$Id: TH1I.h,v 1.1 2002/05/18 11:02:49 brun Exp $
// Author: Rene Brun 08/09/2003
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TH1I
#define ROOT_TH1I
//////////////////////////////////////////////////////////////////////////
// //
// TH1I //
// //
// 1-Dim histogram with a 4 bits integer per channel //
// //
//////////////////////////////////////////////////////////////////////////
#ifndef ROOT_TH1
#include "TH1.h"
#endif
#endif
|
// @(#)root/hist:$Name: $:$Id: TH1I.h,v 1.1 2003/09/08 12:50:23 brun Exp $
// Author: Rene Brun 08/09/2003
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TH1I
#define ROOT_TH1I
//////////////////////////////////////////////////////////////////////////
// //
// TH1I //
// //
// 1-Dim histogram with a 32 bits integer per channel //
// //
//////////////////////////////////////////////////////////////////////////
#ifndef ROOT_TH1
#include "TH1.h"
#endif
#endif
|
Fix a typo (thanks to Robert Hatcher)
|
Fix a typo (thanks to Robert Hatcher)
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@10919 27541ba8-7e3a-0410-8455-c3a389f83636
|
C
|
lgpl-2.1
|
omazapa/root-old,arch1tect0r/root,perovic/root,nilqed/root,CristinaCristescu/root,esakellari/my_root_for_test,simonpf/root,abhinavmoudgil95/root,simonpf/root,mattkretz/root,Y--/root,tc3t/qoot,veprbl/root,0x0all/ROOT,buuck/root,sbinet/cxx-root,omazapa/root,smarinac/root,simonpf/root,bbockelm/root,beniz/root,vukasinmilosevic/root,buuck/root,nilqed/root,ffurano/root5,omazapa/root,olifre/root,dfunke/root,Duraznos/root,krafczyk/root,omazapa/root-old,ffurano/root5,CristinaCristescu/root,perovic/root,georgtroska/root,smarinac/root,davidlt/root,satyarth934/root,0x0all/ROOT,mkret2/root,gganis/root,simonpf/root,evgeny-boger/root,Duraznos/root,abhinavmoudgil95/root,BerserkerTroll/root,arch1tect0r/root,omazapa/root,mkret2/root,esakellari/my_root_for_test,Y--/root,mattkretz/root,CristinaCristescu/root,lgiommi/root,beniz/root,sbinet/cxx-root,veprbl/root,pspe/root,nilqed/root,simonpf/root,karies/root,beniz/root,bbockelm/root,CristinaCristescu/root,lgiommi/root,BerserkerTroll/root,zzxuanyuan/root-compressor-dummy,pspe/root,bbockelm/root,gbitzes/root,0x0all/ROOT,agarciamontoro/root,vukasinmilosevic/root,zzxuanyuan/root-compressor-dummy,strykejern/TTreeReader,agarciamontoro/root,arch1tect0r/root,root-mirror/root,olifre/root,abhinavmoudgil95/root,perovic/root,satyarth934/root,satyarth934/root,strykejern/TTreeReader,esakellari/root,Y--/root,BerserkerTroll/root,evgeny-boger/root,sirinath/root,davidlt/root,bbockelm/root,evgeny-boger/root,veprbl/root,mattkretz/root,perovic/root,abhinavmoudgil95/root,zzxuanyuan/root,vukasinmilosevic/root,mattkretz/root,Duraznos/root,bbockelm/root,alexschlueter/cern-root,buuck/root,omazapa/root-old,mhuwiler/rootauto,sawenzel/root,davidlt/root,zzxuanyuan/root,sbinet/cxx-root,perovic/root,olifre/root,lgiommi/root,zzxuanyuan/root-compressor-dummy,lgiommi/root,CristinaCristescu/root,omazapa/root-old,zzxuanyuan/root-compressor-dummy,mkret2/root,zzxuanyuan/root-compressor-dummy,bbockelm/root,simonpf/root,dfunke/root,tc3t/qoot,strykejern/TTreeReader,dfunke/root,arch1tect0r/root,sirinath/root,evgeny-boger/root,mattkretz/root,Dr15Jones/root,jrtomps/root,smarinac/root,davidlt/root,sbinet/cxx-root,davidlt/root,arch1tect0r/root,satyarth934/root,dfunke/root,beniz/root,jrtomps/root,alexschlueter/cern-root,vukasinmilosevic/root,jrtomps/root,thomaskeck/root,zzxuanyuan/root,krafczyk/root,arch1tect0r/root,dfunke/root,Y--/root,arch1tect0r/root,zzxuanyuan/root-compressor-dummy,veprbl/root,sirinath/root,georgtroska/root,smarinac/root,nilqed/root,karies/root,davidlt/root,esakellari/my_root_for_test,cxx-hep/root-cern,vukasinmilosevic/root,satyarth934/root,esakellari/root,pspe/root,esakellari/my_root_for_test,gganis/root,kirbyherm/root-r-tools,sawenzel/root,krafczyk/root,pspe/root,sirinath/root,evgeny-boger/root,Dr15Jones/root,veprbl/root,veprbl/root,nilqed/root,vukasinmilosevic/root,gbitzes/root,beniz/root,tc3t/qoot,mkret2/root,BerserkerTroll/root,gganis/root,0x0all/ROOT,esakellari/root,esakellari/root,karies/root,agarciamontoro/root,bbockelm/root,agarciamontoro/root,arch1tect0r/root,arch1tect0r/root,sbinet/cxx-root,ffurano/root5,mhuwiler/rootauto,jrtomps/root,karies/root,abhinavmoudgil95/root,tc3t/qoot,thomaskeck/root,mkret2/root,olifre/root,kirbyherm/root-r-tools,mattkretz/root,zzxuanyuan/root-compressor-dummy,sirinath/root,esakellari/root,root-mirror/root,davidlt/root,tc3t/qoot,satyarth934/root,Duraznos/root,georgtroska/root,mhuwiler/rootauto,BerserkerTroll/root,nilqed/root,zzxuanyuan/root-compressor-dummy,tc3t/qoot,agarciamontoro/root,pspe/root,thomaskeck/root,smarinac/root,olifre/root,pspe/root,kirbyherm/root-r-tools,Y--/root,tc3t/qoot,0x0all/ROOT,olifre/root,beniz/root,sbinet/cxx-root,sawenzel/root,sawenzel/root,georgtroska/root,smarinac/root,Duraznos/root,esakellari/root,esakellari/root,root-mirror/root,gganis/root,ffurano/root5,zzxuanyuan/root-compressor-dummy,omazapa/root,bbockelm/root,sbinet/cxx-root,mhuwiler/rootauto,pspe/root,sirinath/root,krafczyk/root,abhinavmoudgil95/root,karies/root,tc3t/qoot,0x0all/ROOT,omazapa/root-old,arch1tect0r/root,mkret2/root,cxx-hep/root-cern,georgtroska/root,evgeny-boger/root,davidlt/root,jrtomps/root,esakellari/my_root_for_test,mhuwiler/rootauto,karies/root,alexschlueter/cern-root,mhuwiler/rootauto,0x0all/ROOT,sawenzel/root,bbockelm/root,agarciamontoro/root,Duraznos/root,tc3t/qoot,gganis/root,zzxuanyuan/root-compressor-dummy,davidlt/root,lgiommi/root,gbitzes/root,Duraznos/root,zzxuanyuan/root,krafczyk/root,olifre/root,vukasinmilosevic/root,BerserkerTroll/root,tc3t/qoot,mattkretz/root,kirbyherm/root-r-tools,thomaskeck/root,Duraznos/root,mkret2/root,omazapa/root,Y--/root,sawenzel/root,root-mirror/root,thomaskeck/root,zzxuanyuan/root,olifre/root,georgtroska/root,veprbl/root,simonpf/root,karies/root,arch1tect0r/root,gbitzes/root,esakellari/my_root_for_test,buuck/root,buuck/root,gganis/root,abhinavmoudgil95/root,jrtomps/root,olifre/root,0x0all/ROOT,Dr15Jones/root,Dr15Jones/root,georgtroska/root,georgtroska/root,veprbl/root,esakellari/root,lgiommi/root,krafczyk/root,0x0all/ROOT,mattkretz/root,krafczyk/root,smarinac/root,evgeny-boger/root,dfunke/root,BerserkerTroll/root,karies/root,cxx-hep/root-cern,jrtomps/root,CristinaCristescu/root,perovic/root,root-mirror/root,root-mirror/root,sawenzel/root,perovic/root,satyarth934/root,beniz/root,omazapa/root,jrtomps/root,lgiommi/root,gbitzes/root,Y--/root,thomaskeck/root,thomaskeck/root,mattkretz/root,nilqed/root,perovic/root,evgeny-boger/root,sirinath/root,satyarth934/root,agarciamontoro/root,omazapa/root-old,alexschlueter/cern-root,beniz/root,BerserkerTroll/root,omazapa/root,kirbyherm/root-r-tools,sirinath/root,vukasinmilosevic/root,smarinac/root,lgiommi/root,satyarth934/root,satyarth934/root,abhinavmoudgil95/root,mhuwiler/rootauto,sirinath/root,omazapa/root-old,georgtroska/root,evgeny-boger/root,karies/root,evgeny-boger/root,esakellari/root,mkret2/root,gbitzes/root,strykejern/TTreeReader,jrtomps/root,buuck/root,davidlt/root,gbitzes/root,gbitzes/root,agarciamontoro/root,smarinac/root,dfunke/root,thomaskeck/root,agarciamontoro/root,omazapa/root,gbitzes/root,krafczyk/root,vukasinmilosevic/root,gbitzes/root,perovic/root,zzxuanyuan/root,buuck/root,root-mirror/root,sawenzel/root,CristinaCristescu/root,beniz/root,ffurano/root5,omazapa/root-old,ffurano/root5,esakellari/my_root_for_test,abhinavmoudgil95/root,buuck/root,mhuwiler/rootauto,zzxuanyuan/root,mattkretz/root,mhuwiler/rootauto,simonpf/root,sbinet/cxx-root,perovic/root,abhinavmoudgil95/root,BerserkerTroll/root,buuck/root,mattkretz/root,krafczyk/root,sbinet/cxx-root,lgiommi/root,mkret2/root,olifre/root,Y--/root,Duraznos/root,cxx-hep/root-cern,lgiommi/root,smarinac/root,pspe/root,kirbyherm/root-r-tools,pspe/root,dfunke/root,gganis/root,mkret2/root,beniz/root,alexschlueter/cern-root,zzxuanyuan/root,vukasinmilosevic/root,gganis/root,sbinet/cxx-root,vukasinmilosevic/root,cxx-hep/root-cern,pspe/root,cxx-hep/root-cern,cxx-hep/root-cern,CristinaCristescu/root,sirinath/root,strykejern/TTreeReader,satyarth934/root,veprbl/root,simonpf/root,sawenzel/root,CristinaCristescu/root,georgtroska/root,simonpf/root,perovic/root,veprbl/root,gganis/root,lgiommi/root,zzxuanyuan/root,jrtomps/root,gganis/root,gbitzes/root,buuck/root,omazapa/root-old,krafczyk/root,buuck/root,alexschlueter/cern-root,omazapa/root,simonpf/root,Y--/root,pspe/root,esakellari/root,BerserkerTroll/root,Dr15Jones/root,jrtomps/root,karies/root,zzxuanyuan/root,zzxuanyuan/root,abhinavmoudgil95/root,olifre/root,agarciamontoro/root,esakellari/my_root_for_test,thomaskeck/root,Y--/root,bbockelm/root,veprbl/root,Duraznos/root,nilqed/root,root-mirror/root,alexschlueter/cern-root,Duraznos/root,sawenzel/root,zzxuanyuan/root-compressor-dummy,dfunke/root,mkret2/root,davidlt/root,beniz/root,sawenzel/root,strykejern/TTreeReader,sbinet/cxx-root,dfunke/root,omazapa/root,evgeny-boger/root,gganis/root,ffurano/root5,root-mirror/root,thomaskeck/root,agarciamontoro/root,nilqed/root,krafczyk/root,esakellari/root,georgtroska/root,omazapa/root-old,Dr15Jones/root,mhuwiler/rootauto,sirinath/root,omazapa/root-old,nilqed/root,root-mirror/root,esakellari/my_root_for_test,cxx-hep/root-cern,dfunke/root,omazapa/root,nilqed/root,CristinaCristescu/root,root-mirror/root,Y--/root,CristinaCristescu/root,mhuwiler/rootauto,bbockelm/root,esakellari/my_root_for_test,zzxuanyuan/root,BerserkerTroll/root,strykejern/TTreeReader,kirbyherm/root-r-tools,karies/root,Dr15Jones/root
|
c
|
## Code Before:
// @(#)root/hist:$Name: $:$Id: TH1I.h,v 1.1 2002/05/18 11:02:49 brun Exp $
// Author: Rene Brun 08/09/2003
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TH1I
#define ROOT_TH1I
//////////////////////////////////////////////////////////////////////////
// //
// TH1I //
// //
// 1-Dim histogram with a 4 bits integer per channel //
// //
//////////////////////////////////////////////////////////////////////////
#ifndef ROOT_TH1
#include "TH1.h"
#endif
#endif
## Instruction:
Fix a typo (thanks to Robert Hatcher)
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@10919 27541ba8-7e3a-0410-8455-c3a389f83636
## Code After:
// @(#)root/hist:$Name: $:$Id: TH1I.h,v 1.1 2003/09/08 12:50:23 brun Exp $
// Author: Rene Brun 08/09/2003
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TH1I
#define ROOT_TH1I
//////////////////////////////////////////////////////////////////////////
// //
// TH1I //
// //
// 1-Dim histogram with a 32 bits integer per channel //
// //
//////////////////////////////////////////////////////////////////////////
#ifndef ROOT_TH1
#include "TH1.h"
#endif
#endif
|
...
// @(#)root/hist:$Name: $:$Id: TH1I.h,v 1.1 2003/09/08 12:50:23 brun Exp $
// Author: Rene Brun 08/09/2003
/*************************************************************************
...
// //
// TH1I //
// //
// 1-Dim histogram with a 32 bits integer per channel //
// //
//////////////////////////////////////////////////////////////////////////
...
|
29b26aa8b44ea5820cfcd20e324d2c3631338228
|
portal/models/research_protocol.py
|
portal/models/research_protocol.py
|
"""Research Protocol module"""
from datetime import datetime
from ..database import db
from ..date_tools import FHIR_datetime
class ResearchProtocol(db.Model):
"""ResearchProtocol model for tracking QB versions"""
__tablename__ = 'research_protocols'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False, unique=True)
created_at = db.Column(db.DateTime, nullable=False)
def __init__(self, name):
self.name = name
self.created_at = datetime.utcnow()
@classmethod
def from_json(cls, data):
if 'name' not in data:
raise ValueError("missing required name field")
rp = ResearchProtocol.query.filter_by(name=data['name']).first()
if not rp:
rp = cls(data['name'])
return rp
def as_json(self):
d = {}
d['id'] = self.id
d['resourceType'] = 'ResearchProtocol'
d['name'] = self.name
d['created_at'] = FHIR_datetime.as_fhir(self.created_at)
return d
|
"""Research Protocol module"""
from datetime import datetime
from ..database import db
from ..date_tools import FHIR_datetime
class ResearchProtocol(db.Model):
"""ResearchProtocol model for tracking QB versions"""
__tablename__ = 'research_protocols'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False, unique=True)
created_at = db.Column(db.DateTime, nullable=False)
def __init__(self, name):
self.name = name
self.created_at = datetime.utcnow()
@classmethod
def from_json(cls, data):
if 'name' not in data:
raise ValueError("missing required name field")
instance = cls(data['name'])
return instance.update_from_json(data)
def update_from_json(self, data):
self.name = data['name']
if 'created_at' in data:
self.created_at = data['created_at']
return self
def as_json(self):
d = {}
d['id'] = self.id
d['resourceType'] = 'ResearchProtocol'
d['name'] = self.name
d['created_at'] = FHIR_datetime.as_fhir(self.created_at)
return d
|
Implement common pattern from_json calls update_from_json
|
Implement common pattern from_json calls update_from_json
|
Python
|
bsd-3-clause
|
uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal
|
python
|
## Code Before:
"""Research Protocol module"""
from datetime import datetime
from ..database import db
from ..date_tools import FHIR_datetime
class ResearchProtocol(db.Model):
"""ResearchProtocol model for tracking QB versions"""
__tablename__ = 'research_protocols'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False, unique=True)
created_at = db.Column(db.DateTime, nullable=False)
def __init__(self, name):
self.name = name
self.created_at = datetime.utcnow()
@classmethod
def from_json(cls, data):
if 'name' not in data:
raise ValueError("missing required name field")
rp = ResearchProtocol.query.filter_by(name=data['name']).first()
if not rp:
rp = cls(data['name'])
return rp
def as_json(self):
d = {}
d['id'] = self.id
d['resourceType'] = 'ResearchProtocol'
d['name'] = self.name
d['created_at'] = FHIR_datetime.as_fhir(self.created_at)
return d
## Instruction:
Implement common pattern from_json calls update_from_json
## Code After:
"""Research Protocol module"""
from datetime import datetime
from ..database import db
from ..date_tools import FHIR_datetime
class ResearchProtocol(db.Model):
"""ResearchProtocol model for tracking QB versions"""
__tablename__ = 'research_protocols'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False, unique=True)
created_at = db.Column(db.DateTime, nullable=False)
def __init__(self, name):
self.name = name
self.created_at = datetime.utcnow()
@classmethod
def from_json(cls, data):
if 'name' not in data:
raise ValueError("missing required name field")
instance = cls(data['name'])
return instance.update_from_json(data)
def update_from_json(self, data):
self.name = data['name']
if 'created_at' in data:
self.created_at = data['created_at']
return self
def as_json(self):
d = {}
d['id'] = self.id
d['resourceType'] = 'ResearchProtocol'
d['name'] = self.name
d['created_at'] = FHIR_datetime.as_fhir(self.created_at)
return d
|
// ... existing code ...
def from_json(cls, data):
if 'name' not in data:
raise ValueError("missing required name field")
instance = cls(data['name'])
return instance.update_from_json(data)
def update_from_json(self, data):
self.name = data['name']
if 'created_at' in data:
self.created_at = data['created_at']
return self
def as_json(self):
d = {}
// ... rest of the code ...
|
29ea7bc48cc4ef81466764bdda3729ac44345154
|
annotation-rest/src/main/java/uk/ac/ebi/quickgo/annotation/service/statistics/RequiredStatisticsProvider.java
|
annotation-rest/src/main/java/uk/ac/ebi/quickgo/annotation/service/statistics/RequiredStatisticsProvider.java
|
package uk.ac.ebi.quickgo.annotation.service.statistics;
import java.util.List;
/**
* A source of {@link RequiredStatistics} instances.
*
* @author Tony Wardell
* Date: 19/12/2017
* Time: 11:04
* Created with IntelliJ IDEA.
*/
public class RequiredStatisticsProvider {
private final RequiredStatistics standardUsage;
private final RequiredStatistics downloadUsage;
private final RequiredStatistics standardUsageWithGeneProductFiltering;
private final RequiredStatistics downloadUsageWithGeneProductFiltering;
public RequiredStatisticsProvider(StatisticsTypeConfigurer standardConfiguration, StatisticsTypeConfigurer
downloadConfiguration) {
standardUsage = new RequiredStatistics(standardConfiguration);
downloadUsage = new RequiredStatistics(downloadConfiguration);
standardUsageWithGeneProductFiltering = new RequiredStatisticsWithGeneProduct(standardConfiguration);
downloadUsageWithGeneProductFiltering = new RequiredStatisticsWithGeneProduct(downloadConfiguration);
}
public List<RequiredStatistic> getStandardUsage() {
return standardUsage.getRequiredStatistics();
}
public List<RequiredStatistic> getDownloadUsage() {
return downloadUsage.getRequiredStatistics();
}
public List<RequiredStatistic> getStandardUsageWithGeneProductFiltering() {
return standardUsageWithGeneProductFiltering.getRequiredStatistics();
}
public List<RequiredStatistic> getDownloadUsageWithGeneProductFiltering() {
return downloadUsageWithGeneProductFiltering.getRequiredStatistics();
}
}
|
package uk.ac.ebi.quickgo.annotation.service.statistics;
import java.util.List;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkArgument;
/**
* A source of {@link RequiredStatistics} instances.
*
* @author Tony Wardell
* Date: 19/12/2017
* Time: 11:04
* Created with IntelliJ IDEA.
*/
public class RequiredStatisticsProvider {
private final RequiredStatistics standardUsage;
private final RequiredStatistics downloadUsage;
private final RequiredStatistics standardUsageWithGeneProductFiltering;
private final RequiredStatistics downloadUsageWithGeneProductFiltering;
public RequiredStatisticsProvider(StatisticsTypeConfigurer standardConfiguration, StatisticsTypeConfigurer
downloadConfiguration) {
checkArgument(Objects.nonNull(standardConfiguration), "The standard StatisticsTypeConfigurer instance cannot" +
" be null");
checkArgument(Objects.nonNull(standardConfiguration), "The download StatisticsTypeConfigurer instance cannot" +
" be null");
standardUsage = new RequiredStatistics(standardConfiguration);
downloadUsage = new RequiredStatistics(downloadConfiguration);
standardUsageWithGeneProductFiltering = new RequiredStatisticsWithGeneProduct(standardConfiguration);
downloadUsageWithGeneProductFiltering = new RequiredStatisticsWithGeneProduct(downloadConfiguration);
}
public List<RequiredStatistic> getStandardUsage() {
return standardUsage.getRequiredStatistics();
}
public List<RequiredStatistic> getDownloadUsage() {
return downloadUsage.getRequiredStatistics();
}
public List<RequiredStatistic> getStandardUsageWithGeneProductFiltering() {
return standardUsageWithGeneProductFiltering.getRequiredStatistics();
}
public List<RequiredStatistic> getDownloadUsageWithGeneProductFiltering() {
return downloadUsageWithGeneProductFiltering.getRequiredStatistics();
}
}
|
Check configuration objects passed to the constructor are not null.
|
Check configuration objects passed to the constructor are not null.
|
Java
|
apache-2.0
|
ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE
|
java
|
## Code Before:
package uk.ac.ebi.quickgo.annotation.service.statistics;
import java.util.List;
/**
* A source of {@link RequiredStatistics} instances.
*
* @author Tony Wardell
* Date: 19/12/2017
* Time: 11:04
* Created with IntelliJ IDEA.
*/
public class RequiredStatisticsProvider {
private final RequiredStatistics standardUsage;
private final RequiredStatistics downloadUsage;
private final RequiredStatistics standardUsageWithGeneProductFiltering;
private final RequiredStatistics downloadUsageWithGeneProductFiltering;
public RequiredStatisticsProvider(StatisticsTypeConfigurer standardConfiguration, StatisticsTypeConfigurer
downloadConfiguration) {
standardUsage = new RequiredStatistics(standardConfiguration);
downloadUsage = new RequiredStatistics(downloadConfiguration);
standardUsageWithGeneProductFiltering = new RequiredStatisticsWithGeneProduct(standardConfiguration);
downloadUsageWithGeneProductFiltering = new RequiredStatisticsWithGeneProduct(downloadConfiguration);
}
public List<RequiredStatistic> getStandardUsage() {
return standardUsage.getRequiredStatistics();
}
public List<RequiredStatistic> getDownloadUsage() {
return downloadUsage.getRequiredStatistics();
}
public List<RequiredStatistic> getStandardUsageWithGeneProductFiltering() {
return standardUsageWithGeneProductFiltering.getRequiredStatistics();
}
public List<RequiredStatistic> getDownloadUsageWithGeneProductFiltering() {
return downloadUsageWithGeneProductFiltering.getRequiredStatistics();
}
}
## Instruction:
Check configuration objects passed to the constructor are not null.
## Code After:
package uk.ac.ebi.quickgo.annotation.service.statistics;
import java.util.List;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkArgument;
/**
* A source of {@link RequiredStatistics} instances.
*
* @author Tony Wardell
* Date: 19/12/2017
* Time: 11:04
* Created with IntelliJ IDEA.
*/
public class RequiredStatisticsProvider {
private final RequiredStatistics standardUsage;
private final RequiredStatistics downloadUsage;
private final RequiredStatistics standardUsageWithGeneProductFiltering;
private final RequiredStatistics downloadUsageWithGeneProductFiltering;
public RequiredStatisticsProvider(StatisticsTypeConfigurer standardConfiguration, StatisticsTypeConfigurer
downloadConfiguration) {
checkArgument(Objects.nonNull(standardConfiguration), "The standard StatisticsTypeConfigurer instance cannot" +
" be null");
checkArgument(Objects.nonNull(standardConfiguration), "The download StatisticsTypeConfigurer instance cannot" +
" be null");
standardUsage = new RequiredStatistics(standardConfiguration);
downloadUsage = new RequiredStatistics(downloadConfiguration);
standardUsageWithGeneProductFiltering = new RequiredStatisticsWithGeneProduct(standardConfiguration);
downloadUsageWithGeneProductFiltering = new RequiredStatisticsWithGeneProduct(downloadConfiguration);
}
public List<RequiredStatistic> getStandardUsage() {
return standardUsage.getRequiredStatistics();
}
public List<RequiredStatistic> getDownloadUsage() {
return downloadUsage.getRequiredStatistics();
}
public List<RequiredStatistic> getStandardUsageWithGeneProductFiltering() {
return standardUsageWithGeneProductFiltering.getRequiredStatistics();
}
public List<RequiredStatistic> getDownloadUsageWithGeneProductFiltering() {
return downloadUsageWithGeneProductFiltering.getRequiredStatistics();
}
}
|
...
package uk.ac.ebi.quickgo.annotation.service.statistics;
import java.util.List;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkArgument;
/**
* A source of {@link RequiredStatistics} instances.
...
public RequiredStatisticsProvider(StatisticsTypeConfigurer standardConfiguration, StatisticsTypeConfigurer
downloadConfiguration) {
checkArgument(Objects.nonNull(standardConfiguration), "The standard StatisticsTypeConfigurer instance cannot" +
" be null");
checkArgument(Objects.nonNull(standardConfiguration), "The download StatisticsTypeConfigurer instance cannot" +
" be null");
standardUsage = new RequiredStatistics(standardConfiguration);
downloadUsage = new RequiredStatistics(downloadConfiguration);
standardUsageWithGeneProductFiltering = new RequiredStatisticsWithGeneProduct(standardConfiguration);
...
|
96dc9e590b81926fddb83a85a1352039c10c1509
|
links/mlp.py
|
links/mlp.py
|
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import super
from builtins import range
from future import standard_library
standard_library.install_aliases()
import random
import numpy as np
import chainer
from chainer import functions as F
from chainer import links as L
from chainer import cuda
class MLP(chainer.Chain):
"""Multi-Layer Perceptron"""
def __init__(self, in_size, out_size, hidden_sizes):
self.in_size = in_size
self.out_size = out_size
self.hidden_sizes = hidden_sizes
layers = {}
if hidden_sizes:
hidden_layers = []
hidden_layers.append(L.Linear(in_size, hidden_sizes[0]))
for hin, hout in zip(hidden_sizes, hidden_sizes[1:]):
hidden_layers.append(L.Linear(hin, hout))
layers['hidden_layers'] = chainer.ChainList(*hidden_layers)
layers['output'] = L.Linear(hidden_sizes[-1], out_size)
else:
layers['output'] = L.Linear(in_size, out_size)
super().__init__(**layers)
def __call__(self, x, test=False):
h = x
for l in self.hidden_layers:
h = F.relu(l(h))
return self.output(h)
|
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import super
from builtins import range
from future import standard_library
standard_library.install_aliases()
import random
import numpy as np
import chainer
from chainer import functions as F
from chainer import links as L
from chainer import cuda
class MLP(chainer.Chain):
"""Multi-Layer Perceptron"""
def __init__(self, in_size, out_size, hidden_sizes):
self.in_size = in_size
self.out_size = out_size
self.hidden_sizes = hidden_sizes
layers = {}
if hidden_sizes:
hidden_layers = []
hidden_layers.append(L.Linear(in_size, hidden_sizes[0]))
for hin, hout in zip(hidden_sizes, hidden_sizes[1:]):
hidden_layers.append(L.Linear(hin, hout))
layers['hidden_layers'] = chainer.ChainList(*hidden_layers)
layers['output'] = L.Linear(hidden_sizes[-1], out_size)
else:
layers['output'] = L.Linear(in_size, out_size)
super().__init__(**layers)
def __call__(self, x, test=False):
h = x
if self.hidden_sizes:
for l in self.hidden_layers:
h = F.relu(l(h))
return self.output(h)
|
Support configuration with no hidden-layer
|
Support configuration with no hidden-layer
|
Python
|
mit
|
toslunar/chainerrl,toslunar/chainerrl
|
python
|
## Code Before:
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import super
from builtins import range
from future import standard_library
standard_library.install_aliases()
import random
import numpy as np
import chainer
from chainer import functions as F
from chainer import links as L
from chainer import cuda
class MLP(chainer.Chain):
"""Multi-Layer Perceptron"""
def __init__(self, in_size, out_size, hidden_sizes):
self.in_size = in_size
self.out_size = out_size
self.hidden_sizes = hidden_sizes
layers = {}
if hidden_sizes:
hidden_layers = []
hidden_layers.append(L.Linear(in_size, hidden_sizes[0]))
for hin, hout in zip(hidden_sizes, hidden_sizes[1:]):
hidden_layers.append(L.Linear(hin, hout))
layers['hidden_layers'] = chainer.ChainList(*hidden_layers)
layers['output'] = L.Linear(hidden_sizes[-1], out_size)
else:
layers['output'] = L.Linear(in_size, out_size)
super().__init__(**layers)
def __call__(self, x, test=False):
h = x
for l in self.hidden_layers:
h = F.relu(l(h))
return self.output(h)
## Instruction:
Support configuration with no hidden-layer
## Code After:
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import super
from builtins import range
from future import standard_library
standard_library.install_aliases()
import random
import numpy as np
import chainer
from chainer import functions as F
from chainer import links as L
from chainer import cuda
class MLP(chainer.Chain):
"""Multi-Layer Perceptron"""
def __init__(self, in_size, out_size, hidden_sizes):
self.in_size = in_size
self.out_size = out_size
self.hidden_sizes = hidden_sizes
layers = {}
if hidden_sizes:
hidden_layers = []
hidden_layers.append(L.Linear(in_size, hidden_sizes[0]))
for hin, hout in zip(hidden_sizes, hidden_sizes[1:]):
hidden_layers.append(L.Linear(hin, hout))
layers['hidden_layers'] = chainer.ChainList(*hidden_layers)
layers['output'] = L.Linear(hidden_sizes[-1], out_size)
else:
layers['output'] = L.Linear(in_size, out_size)
super().__init__(**layers)
def __call__(self, x, test=False):
h = x
if self.hidden_sizes:
for l in self.hidden_layers:
h = F.relu(l(h))
return self.output(h)
|
# ... existing code ...
def __call__(self, x, test=False):
h = x
if self.hidden_sizes:
for l in self.hidden_layers:
h = F.relu(l(h))
return self.output(h)
# ... rest of the code ...
|
6a5c9ccf0bd2582cf42577712309b8fd6e912966
|
blo/__init__.py
|
blo/__init__.py
|
import configparser
from blo.BloArticle import BloArticle
from blo.DBControl import DBControl
class Blo:
def __init__(self, config_file_path):
config = configparser.ConfigParser()
config.read(config_file_path)
self._db_file_path = config['DB']['DB_PATH']
self._template_dir = config['TEMPLATE']['TEMPLATE_DIR']
self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE']
# create tables
self._db_control = DBControl(self._db_file_path)
self._db_control.create_tables()
self._db_control.close_connect()
def insert_article(self, file_path):
self._db_control = DBControl(self._db_file_path)
article = BloArticle(self._template_dir)
article.load_from_file(file_path)
self._db_control.insert_article(article, self._default_template_file)
self._db_control.close_connect()
|
import configparser
from blo.BloArticle import BloArticle
from blo.DBControl import DBControl
class Blo:
def __init__(self, config_file_path):
config = configparser.ConfigParser()
config.read(config_file_path)
self._db_file_path = config['DB']['DB_PATH'].replace('"', '')
self._template_dir = config['TEMPLATE']['TEMPLATE_DIR'].replace('"', '')
self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE'].replace('"', '')
# create tables
self._db_control = DBControl(self._db_file_path)
self._db_control.create_tables()
self._db_control.close_connect()
def insert_article(self, file_path):
self._db_control = DBControl(self._db_file_path)
article = BloArticle(self._template_dir)
article.load_from_file(file_path)
self._db_control.insert_article(article, self._default_template_file)
self._db_control.close_connect()
|
Add replace double quotation mark from configuration file parameters.
|
Add replace double quotation mark from configuration file parameters.
|
Python
|
mit
|
10nin/blo,10nin/blo
|
python
|
## Code Before:
import configparser
from blo.BloArticle import BloArticle
from blo.DBControl import DBControl
class Blo:
def __init__(self, config_file_path):
config = configparser.ConfigParser()
config.read(config_file_path)
self._db_file_path = config['DB']['DB_PATH']
self._template_dir = config['TEMPLATE']['TEMPLATE_DIR']
self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE']
# create tables
self._db_control = DBControl(self._db_file_path)
self._db_control.create_tables()
self._db_control.close_connect()
def insert_article(self, file_path):
self._db_control = DBControl(self._db_file_path)
article = BloArticle(self._template_dir)
article.load_from_file(file_path)
self._db_control.insert_article(article, self._default_template_file)
self._db_control.close_connect()
## Instruction:
Add replace double quotation mark from configuration file parameters.
## Code After:
import configparser
from blo.BloArticle import BloArticle
from blo.DBControl import DBControl
class Blo:
def __init__(self, config_file_path):
config = configparser.ConfigParser()
config.read(config_file_path)
self._db_file_path = config['DB']['DB_PATH'].replace('"', '')
self._template_dir = config['TEMPLATE']['TEMPLATE_DIR'].replace('"', '')
self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE'].replace('"', '')
# create tables
self._db_control = DBControl(self._db_file_path)
self._db_control.create_tables()
self._db_control.close_connect()
def insert_article(self, file_path):
self._db_control = DBControl(self._db_file_path)
article = BloArticle(self._template_dir)
article.load_from_file(file_path)
self._db_control.insert_article(article, self._default_template_file)
self._db_control.close_connect()
|
# ... existing code ...
def __init__(self, config_file_path):
config = configparser.ConfigParser()
config.read(config_file_path)
self._db_file_path = config['DB']['DB_PATH'].replace('"', '')
self._template_dir = config['TEMPLATE']['TEMPLATE_DIR'].replace('"', '')
self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE'].replace('"', '')
# create tables
self._db_control = DBControl(self._db_file_path)
# ... rest of the code ...
|
273249d28f038c94e3890dd7679f067409970ac5
|
xfire-core/src/main/org/codehaus/xfire/handler/EndpointHandler.java
|
xfire-core/src/main/org/codehaus/xfire/handler/EndpointHandler.java
|
package org.codehaus.xfire.handler;
import org.codehaus.xfire.MessageContext;
/**
* By virtue of XFire being stream based, a service can not write its
* response until the very end of processing. So a service which needs
* to write response headers but do so first before writing the
* SOAP Body. The writeResponse method tells an Endpoint that it is
* now okay (i.e. there have been no Faults) to write the
* response to the OutputStream (if there is an response to the
* sender at all) or to another endpoint.
* <p>
* If a Service does not wishes to write its response immediately when
* reading the incoming stream, it may do so and not implement the
* <code>writeResponse</code> method. The service must then realize that
* the response Handler pipeline will not be able to outgoing stream.
*
* @author <a href="mailto:[email protected]">Dan Diephouse</a>
*/
public interface EndpointHandler
extends Handler
{
public void writeResponse(MessageContext context);
}
|
package org.codehaus.xfire.handler;
import org.codehaus.xfire.MessageContext;
import org.codehaus.xfire.fault.XFireFault;
/**
* By virtue of XFire being stream based, a service can not write its
* response until the very end of processing. So a service which needs
* to write response headers but do so first before writing the
* SOAP Body. The writeResponse method tells an Endpoint that it is
* now okay (i.e. there have been no Faults) to write the
* response to the OutputStream (if there is an response to the
* sender at all) or to another endpoint.
* <p>
* If a Service does not wishes to write its response immediately when
* reading the incoming stream, it may do so and not implement the
* <code>writeResponse</code> method. The service must then realize that
* the response Handler pipeline will not be able to outgoing stream.
*
* @author <a href="mailto:[email protected]">Dan Diephouse</a>
*/
public interface EndpointHandler
extends Handler
{
public void writeResponse(MessageContext context) throws XFireFault;
}
|
Fix the JavaServiceHandler so the response is written when its supposed to be.
|
Fix the JavaServiceHandler so the response is written when its
supposed to be.
git-svn-id: 9326b53cbc4a8f4c3d02979b62b178127d5150fe@101 c7d0bf07-ec0d-0410-b2cc-d48fa9be22ba
|
Java
|
mit
|
eduardodaluz/xfire,eduardodaluz/xfire
|
java
|
## Code Before:
package org.codehaus.xfire.handler;
import org.codehaus.xfire.MessageContext;
/**
* By virtue of XFire being stream based, a service can not write its
* response until the very end of processing. So a service which needs
* to write response headers but do so first before writing the
* SOAP Body. The writeResponse method tells an Endpoint that it is
* now okay (i.e. there have been no Faults) to write the
* response to the OutputStream (if there is an response to the
* sender at all) or to another endpoint.
* <p>
* If a Service does not wishes to write its response immediately when
* reading the incoming stream, it may do so and not implement the
* <code>writeResponse</code> method. The service must then realize that
* the response Handler pipeline will not be able to outgoing stream.
*
* @author <a href="mailto:[email protected]">Dan Diephouse</a>
*/
public interface EndpointHandler
extends Handler
{
public void writeResponse(MessageContext context);
}
## Instruction:
Fix the JavaServiceHandler so the response is written when its
supposed to be.
git-svn-id: 9326b53cbc4a8f4c3d02979b62b178127d5150fe@101 c7d0bf07-ec0d-0410-b2cc-d48fa9be22ba
## Code After:
package org.codehaus.xfire.handler;
import org.codehaus.xfire.MessageContext;
import org.codehaus.xfire.fault.XFireFault;
/**
* By virtue of XFire being stream based, a service can not write its
* response until the very end of processing. So a service which needs
* to write response headers but do so first before writing the
* SOAP Body. The writeResponse method tells an Endpoint that it is
* now okay (i.e. there have been no Faults) to write the
* response to the OutputStream (if there is an response to the
* sender at all) or to another endpoint.
* <p>
* If a Service does not wishes to write its response immediately when
* reading the incoming stream, it may do so and not implement the
* <code>writeResponse</code> method. The service must then realize that
* the response Handler pipeline will not be able to outgoing stream.
*
* @author <a href="mailto:[email protected]">Dan Diephouse</a>
*/
public interface EndpointHandler
extends Handler
{
public void writeResponse(MessageContext context) throws XFireFault;
}
|
...
package org.codehaus.xfire.handler;
import org.codehaus.xfire.MessageContext;
import org.codehaus.xfire.fault.XFireFault;
/**
* By virtue of XFire being stream based, a service can not write its
...
public interface EndpointHandler
extends Handler
{
public void writeResponse(MessageContext context) throws XFireFault;
}
...
|
06fd1674239de71ccbe52398516642d9b19b743b
|
setup.py
|
setup.py
|
from distutils.core import setup
from distutils.command.sdist import sdist as _sdist
class sdist(_sdist):
def run(self):
try:
import sys
sys.path.append("contrib")
import git2changes
print('generating CHANGES.txt')
with open('CHANGES.txt', 'w+') as f:
git2changes.run(f)
except ImportError:
pass
_sdist.run(self)
setup(
name='pyppd',
version='1.0.2',
author='Vitor Baptista',
author_email='[email protected]',
packages=['pyppd'],
package_data={'pyppd': ['*.in']},
scripts=['bin/pyppd'],
url='http://github.com/vitorbaptista/pyppd/',
license='MIT',
description='A CUPS PostScript Printer Driver\'s compressor and generator',
long_description=open('README', 'rb').read().decode('UTF-8') + "\n" +
open('ISSUES', 'rb').read().decode('UTF-8'),
cmdclass={'sdist': sdist},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: System Administrators',
'Operating System :: POSIX',
'License :: OSI Approved :: MIT License',
'Topic :: Printing',
],
)
|
from distutils.core import setup
from distutils.command.sdist import sdist as _sdist
class sdist(_sdist):
def run(self):
try:
import sys
sys.path.append("contrib")
import git2changes
print('generating CHANGES.txt')
with open('CHANGES.txt', 'w+') as f:
git2changes.run(f)
except ImportError:
pass
_sdist.run(self)
setup(
name='pyppd',
version='1.0.2',
author='Vitor Baptista',
author_email='[email protected]',
packages=['pyppd'],
package_data={'pyppd': ['*.in']},
scripts=['bin/pyppd'],
url='https://github.com/OpenPrinting/pyppd/',
license='MIT',
description='A CUPS PostScript Printer Driver\'s compressor and generator',
long_description=open('README', 'rb').read().decode('UTF-8') + "\n" +
open('ISSUES', 'rb').read().decode('UTF-8'),
cmdclass={'sdist': sdist},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: System Administrators',
'Operating System :: POSIX',
'License :: OSI Approved :: MIT License',
'Topic :: Printing',
],
)
|
Change repository URL to point to OpenPrinting's organisation
|
Change repository URL to point to OpenPrinting's organisation
|
Python
|
mit
|
vitorbaptista/pyppd
|
python
|
## Code Before:
from distutils.core import setup
from distutils.command.sdist import sdist as _sdist
class sdist(_sdist):
def run(self):
try:
import sys
sys.path.append("contrib")
import git2changes
print('generating CHANGES.txt')
with open('CHANGES.txt', 'w+') as f:
git2changes.run(f)
except ImportError:
pass
_sdist.run(self)
setup(
name='pyppd',
version='1.0.2',
author='Vitor Baptista',
author_email='[email protected]',
packages=['pyppd'],
package_data={'pyppd': ['*.in']},
scripts=['bin/pyppd'],
url='http://github.com/vitorbaptista/pyppd/',
license='MIT',
description='A CUPS PostScript Printer Driver\'s compressor and generator',
long_description=open('README', 'rb').read().decode('UTF-8') + "\n" +
open('ISSUES', 'rb').read().decode('UTF-8'),
cmdclass={'sdist': sdist},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: System Administrators',
'Operating System :: POSIX',
'License :: OSI Approved :: MIT License',
'Topic :: Printing',
],
)
## Instruction:
Change repository URL to point to OpenPrinting's organisation
## Code After:
from distutils.core import setup
from distutils.command.sdist import sdist as _sdist
class sdist(_sdist):
def run(self):
try:
import sys
sys.path.append("contrib")
import git2changes
print('generating CHANGES.txt')
with open('CHANGES.txt', 'w+') as f:
git2changes.run(f)
except ImportError:
pass
_sdist.run(self)
setup(
name='pyppd',
version='1.0.2',
author='Vitor Baptista',
author_email='[email protected]',
packages=['pyppd'],
package_data={'pyppd': ['*.in']},
scripts=['bin/pyppd'],
url='https://github.com/OpenPrinting/pyppd/',
license='MIT',
description='A CUPS PostScript Printer Driver\'s compressor and generator',
long_description=open('README', 'rb').read().decode('UTF-8') + "\n" +
open('ISSUES', 'rb').read().decode('UTF-8'),
cmdclass={'sdist': sdist},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: System Administrators',
'Operating System :: POSIX',
'License :: OSI Approved :: MIT License',
'Topic :: Printing',
],
)
|
...
packages=['pyppd'],
package_data={'pyppd': ['*.in']},
scripts=['bin/pyppd'],
url='https://github.com/OpenPrinting/pyppd/',
license='MIT',
description='A CUPS PostScript Printer Driver\'s compressor and generator',
long_description=open('README', 'rb').read().decode('UTF-8') + "\n" +
...
|
aeef2c319ea5c7d59a0bdf69a5fbe5dc8a1ab1bc
|
wagtailnews/feeds.py
|
wagtailnews/feeds.py
|
from django.contrib.syndication.views import Feed
from django.utils import timezone
class LatestEnteriesFeed(Feed):
description = "Latest news"
def items(self):
now = timezone.now()
NewsItem = self.news_index.get_newsitem_model()
newsitem_list = NewsItem.objects.live().order_by('-date').filter(
newsindex=self.news_index, date__lte=now)[:20]
return newsitem_list
def item_link(self, item):
return item.url()
def __init__(self, news_index):
super(LatestEnteriesFeed, self).__init__()
self.news_index = news_index
self.title = news_index.title
self.link = news_index.url
def item_pubdate(self, item):
return item.date
|
from django.contrib.syndication.views import Feed
from django.utils import timezone
class LatestEnteriesFeed(Feed):
def items(self):
now = timezone.now()
NewsItem = self.news_index.get_newsitem_model()
newsitem_list = NewsItem.objects.live().order_by('-date').filter(
newsindex=self.news_index, date__lte=now)[:20]
return newsitem_list
def item_link(self, item):
return item.full_url()
def item_guid(self, item):
return item.full_url()
item_guid_is_permalink = True
def item_pubdate(self, item):
return item.date
def __init__(self, news_index):
super(LatestEnteriesFeed, self).__init__()
self.news_index = news_index
self.title = news_index.title
self.description = news_index.title
self.link = news_index.full_url
self.feed_url = self.link + news_index.reverse_subpage('feed')
|
Add some extra item methods / parameters to LatestEntriesFeed
|
Add some extra item methods / parameters to LatestEntriesFeed
|
Python
|
bsd-2-clause
|
takeflight/wagtailnews,takeflight/wagtailnews,takeflight/wagtailnews,takeflight/wagtailnews
|
python
|
## Code Before:
from django.contrib.syndication.views import Feed
from django.utils import timezone
class LatestEnteriesFeed(Feed):
description = "Latest news"
def items(self):
now = timezone.now()
NewsItem = self.news_index.get_newsitem_model()
newsitem_list = NewsItem.objects.live().order_by('-date').filter(
newsindex=self.news_index, date__lte=now)[:20]
return newsitem_list
def item_link(self, item):
return item.url()
def __init__(self, news_index):
super(LatestEnteriesFeed, self).__init__()
self.news_index = news_index
self.title = news_index.title
self.link = news_index.url
def item_pubdate(self, item):
return item.date
## Instruction:
Add some extra item methods / parameters to LatestEntriesFeed
## Code After:
from django.contrib.syndication.views import Feed
from django.utils import timezone
class LatestEnteriesFeed(Feed):
def items(self):
now = timezone.now()
NewsItem = self.news_index.get_newsitem_model()
newsitem_list = NewsItem.objects.live().order_by('-date').filter(
newsindex=self.news_index, date__lte=now)[:20]
return newsitem_list
def item_link(self, item):
return item.full_url()
def item_guid(self, item):
return item.full_url()
item_guid_is_permalink = True
def item_pubdate(self, item):
return item.date
def __init__(self, news_index):
super(LatestEnteriesFeed, self).__init__()
self.news_index = news_index
self.title = news_index.title
self.description = news_index.title
self.link = news_index.full_url
self.feed_url = self.link + news_index.reverse_subpage('feed')
|
// ... existing code ...
class LatestEnteriesFeed(Feed):
def items(self):
now = timezone.now()
// ... modified code ...
return newsitem_list
def item_link(self, item):
return item.full_url()
def item_guid(self, item):
return item.full_url()
item_guid_is_permalink = True
def item_pubdate(self, item):
return item.date
def __init__(self, news_index):
super(LatestEnteriesFeed, self).__init__()
self.news_index = news_index
self.title = news_index.title
self.description = news_index.title
self.link = news_index.full_url
self.feed_url = self.link + news_index.reverse_subpage('feed')
// ... rest of the code ...
|
d0db2fa007600c53b186866e744598897a588cb8
|
org.jrebirth/core/src/main/java/org/jrebirth/core/concurrent/RunInto.java
|
org.jrebirth/core/src/main/java/org/jrebirth/core/concurrent/RunInto.java
|
/**
* Get more info at : www.jrebirth.org .
* Copyright JRebirth.org © 2011-2013
* Contact : [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jrebirth.core.concurrent;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation is used to.
*
* @author Sébastien Bordes
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface RunInto {
/**
* Define the RunType value.
*
* The default value is RunType.JIT
*/
RunType value() default RunType.JIT;
}
|
/**
* Get more info at : www.jrebirth.org .
* Copyright JRebirth.org © 2011-2013
* Contact : [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jrebirth.core.concurrent;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation is used to.
*
* @author Sébastien Bordes
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface RunInto {
/**
* Define the RunType value.
*
* The default value is RunType.JIT
*/
RunType value() default RunType.JIT;
}
|
Document and inherit please :D
|
Document and inherit please :D
|
Java
|
apache-2.0
|
amischler/JRebirth,Rizen59/JRebirth,JRebirth/JRebirth,Rizen59/JRebirth,JRebirth/JRebirth,amischler/JRebirth
|
java
|
## Code Before:
/**
* Get more info at : www.jrebirth.org .
* Copyright JRebirth.org © 2011-2013
* Contact : [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jrebirth.core.concurrent;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation is used to.
*
* @author Sébastien Bordes
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface RunInto {
/**
* Define the RunType value.
*
* The default value is RunType.JIT
*/
RunType value() default RunType.JIT;
}
## Instruction:
Document and inherit please :D
## Code After:
/**
* Get more info at : www.jrebirth.org .
* Copyright JRebirth.org © 2011-2013
* Contact : [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jrebirth.core.concurrent;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation is used to.
*
* @author Sébastien Bordes
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface RunInto {
/**
* Define the RunType value.
*
* The default value is RunType.JIT
*/
RunType value() default RunType.JIT;
}
|
...
*/
package org.jrebirth.core.concurrent;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
...
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface RunInto {
/**
...
|
ba48cd45c56646497bcda70d9a475a40ea44c874
|
dbaas/workflow/steps/mysql/resize/change_config.py
|
dbaas/workflow/steps/mysql/resize/change_config.py
|
import logging
from . import run_vm_script
from ...util.base import BaseStep
LOG = logging.getLogger(__name__)
class ChangeDatabaseConfigFile(BaseStep):
def __unicode__(self):
return "Changing database config file..."
def do(self, workflow_dict):
context_dict = {
'CONFIGFILE': True,
'IS_HA': workflow_dict['databaseinfra'].plan.is_ha
},
ret_script = run_vm_script(
workflow_dict=workflow_dict,
context_dict=context_dict,
script=workflow_dict['cloudstackpack'].script,
)
return ret_script
def undo(self, workflow_dict):
context_dict = {
'CONFIGFILE': True,
}
ret_script = run_vm_script(
workflow_dict=workflow_dict,
context_dict=context_dict,
script=workflow_dict['original_cloudstackpack'].script,
)
return ret_script
|
import logging
from workflow.steps.mysql.resize import run_vm_script
from workflow.steps.util.base import BaseStep
LOG = logging.getLogger(__name__)
class ChangeDatabaseConfigFile(BaseStep):
def __unicode__(self):
return "Changing database config file..."
def do(self, workflow_dict):
context_dict = {
'CONFIGFILE': True,
'IS_HA': workflow_dict['databaseinfra'].plan.is_ha
},
ret_script = run_vm_script(
workflow_dict=workflow_dict,
context_dict=context_dict,
script=workflow_dict['cloudstackpack'].script,
)
return ret_script
def undo(self, workflow_dict):
context_dict = {
'CONFIGFILE': True,
'IS_HA': workflow_dict['databaseinfra'].plan.is_ha,
}
ret_script = run_vm_script(
workflow_dict=workflow_dict,
context_dict=context_dict,
script=workflow_dict['original_cloudstackpack'].script,
)
return ret_script
|
Add is_ha variable to change config rollback
|
Add is_ha variable to change config rollback
|
Python
|
bsd-3-clause
|
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
|
python
|
## Code Before:
import logging
from . import run_vm_script
from ...util.base import BaseStep
LOG = logging.getLogger(__name__)
class ChangeDatabaseConfigFile(BaseStep):
def __unicode__(self):
return "Changing database config file..."
def do(self, workflow_dict):
context_dict = {
'CONFIGFILE': True,
'IS_HA': workflow_dict['databaseinfra'].plan.is_ha
},
ret_script = run_vm_script(
workflow_dict=workflow_dict,
context_dict=context_dict,
script=workflow_dict['cloudstackpack'].script,
)
return ret_script
def undo(self, workflow_dict):
context_dict = {
'CONFIGFILE': True,
}
ret_script = run_vm_script(
workflow_dict=workflow_dict,
context_dict=context_dict,
script=workflow_dict['original_cloudstackpack'].script,
)
return ret_script
## Instruction:
Add is_ha variable to change config rollback
## Code After:
import logging
from workflow.steps.mysql.resize import run_vm_script
from workflow.steps.util.base import BaseStep
LOG = logging.getLogger(__name__)
class ChangeDatabaseConfigFile(BaseStep):
def __unicode__(self):
return "Changing database config file..."
def do(self, workflow_dict):
context_dict = {
'CONFIGFILE': True,
'IS_HA': workflow_dict['databaseinfra'].plan.is_ha
},
ret_script = run_vm_script(
workflow_dict=workflow_dict,
context_dict=context_dict,
script=workflow_dict['cloudstackpack'].script,
)
return ret_script
def undo(self, workflow_dict):
context_dict = {
'CONFIGFILE': True,
'IS_HA': workflow_dict['databaseinfra'].plan.is_ha,
}
ret_script = run_vm_script(
workflow_dict=workflow_dict,
context_dict=context_dict,
script=workflow_dict['original_cloudstackpack'].script,
)
return ret_script
|
...
import logging
from workflow.steps.mysql.resize import run_vm_script
from workflow.steps.util.base import BaseStep
LOG = logging.getLogger(__name__)
...
def undo(self, workflow_dict):
context_dict = {
'CONFIGFILE': True,
'IS_HA': workflow_dict['databaseinfra'].plan.is_ha,
}
ret_script = run_vm_script(
...
|
3ef747eca9e3a22507e196aa41cb03fa11173477
|
src/main/com/faveset/khttp/InvalidRequestException.java
|
src/main/com/faveset/khttp/InvalidRequestException.java
|
// Copyright 2014, Kevin Ko <[email protected]>
package com.faveset.khttp;
class InvalidRequestException extends Exception {
public InvalidRequestException(String reason) {
super(reason);
}
}
|
// Copyright 2014, Kevin Ko <[email protected]>
package com.faveset.khttp;
class InvalidRequestException extends Exception {
private int mErrorCode;
public InvalidRequestException(String reason) {
super(reason);
}
public InvalidRequestException(String reason, int errorCode) {
super(reason);
mErrorCode = errorCode;
}
/**
* @return The error code or 0 if none.
*/
public int getErrorCode() {
return mErrorCode;
}
}
|
Add http error code to constructor.
|
Add http error code to constructor.
|
Java
|
bsd-3-clause
|
kevinko/mahttp,kevinko/mahttp
|
java
|
## Code Before:
// Copyright 2014, Kevin Ko <[email protected]>
package com.faveset.khttp;
class InvalidRequestException extends Exception {
public InvalidRequestException(String reason) {
super(reason);
}
}
## Instruction:
Add http error code to constructor.
## Code After:
// Copyright 2014, Kevin Ko <[email protected]>
package com.faveset.khttp;
class InvalidRequestException extends Exception {
private int mErrorCode;
public InvalidRequestException(String reason) {
super(reason);
}
public InvalidRequestException(String reason, int errorCode) {
super(reason);
mErrorCode = errorCode;
}
/**
* @return The error code or 0 if none.
*/
public int getErrorCode() {
return mErrorCode;
}
}
|
# ... existing code ...
package com.faveset.khttp;
class InvalidRequestException extends Exception {
private int mErrorCode;
public InvalidRequestException(String reason) {
super(reason);
}
public InvalidRequestException(String reason, int errorCode) {
super(reason);
mErrorCode = errorCode;
}
/**
* @return The error code or 0 if none.
*/
public int getErrorCode() {
return mErrorCode;
}
}
# ... rest of the code ...
|
52da8be7ffe6ea2ba09acf3ce44b9a79758b115b
|
glance/version.py
|
glance/version.py
|
import pbr.version
version_info = pbr.version.VersionInfo('glance')
|
GLANCE_VENDOR = "OpenStack Foundation"
GLANCE_PRODUCT = "OpenStack Glance"
GLANCE_PACKAGE = None # OS distro package version suffix
loaded = False
class VersionInfo(object):
release = "REDHATGLANCERELEASE"
version = "REDHATGLANCEVERSION"
def version_string(self):
return self.version
def cached_version_string(self):
return self.version
def release_string(self):
return self.release
def canonical_version_string(self):
return self.version
def version_string_with_vcs(self):
return self.release
version_info = VersionInfo()
|
Remove runtime dep on python pbr
|
Remove runtime dep on python pbr
|
Python
|
apache-2.0
|
redhat-openstack/glance,redhat-openstack/glance
|
python
|
## Code Before:
import pbr.version
version_info = pbr.version.VersionInfo('glance')
## Instruction:
Remove runtime dep on python pbr
## Code After:
GLANCE_VENDOR = "OpenStack Foundation"
GLANCE_PRODUCT = "OpenStack Glance"
GLANCE_PACKAGE = None # OS distro package version suffix
loaded = False
class VersionInfo(object):
release = "REDHATGLANCERELEASE"
version = "REDHATGLANCEVERSION"
def version_string(self):
return self.version
def cached_version_string(self):
return self.version
def release_string(self):
return self.release
def canonical_version_string(self):
return self.version
def version_string_with_vcs(self):
return self.release
version_info = VersionInfo()
|
// ... existing code ...
GLANCE_VENDOR = "OpenStack Foundation"
GLANCE_PRODUCT = "OpenStack Glance"
GLANCE_PACKAGE = None # OS distro package version suffix
loaded = False
class VersionInfo(object):
release = "REDHATGLANCERELEASE"
version = "REDHATGLANCEVERSION"
def version_string(self):
return self.version
def cached_version_string(self):
return self.version
def release_string(self):
return self.release
def canonical_version_string(self):
return self.version
def version_string_with_vcs(self):
return self.release
version_info = VersionInfo()
// ... rest of the code ...
|
fdd5f8d4720d44230a50aca4d086a603945cb6f9
|
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/utils/HTMLUtil.kt
|
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/utils/HTMLUtil.kt
|
package ch.rmy.android.http_shortcuts.utils
import android.os.Build
import android.text.Html
import android.text.Spanned
object HTMLUtil {
@Suppress("DEPRECATION")
fun getHTML(string: String): Spanned =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(string, 0)
} else {
Html.fromHtml(string)
}
fun format(string: String): Spanned = getHTML(
string.replace("\n", "<br>")
)
}
|
package ch.rmy.android.http_shortcuts.utils
import android.os.Build
import android.text.Html
import android.text.Spanned
object HTMLUtil {
fun getHTML(string: String): Spanned =
fromHTML(normalize(string))
private fun normalize(string: String): String =
string.replace("<pre>", "<tt>")
.replace("</pre>", "</tt>")
@Suppress("DEPRECATION")
private fun fromHTML(string: String): Spanned =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(string, 0)
} else {
Html.fromHtml(string)
}
fun format(string: String): Spanned = getHTML(
string.replace("\n", "<br>")
)
}
|
Use monospace font for <pre> in dialogs
|
Use monospace font for <pre> in dialogs
|
Kotlin
|
mit
|
Waboodoo/HTTP-Shortcuts,Waboodoo/HTTP-Shortcuts,Waboodoo/HTTP-Shortcuts
|
kotlin
|
## Code Before:
package ch.rmy.android.http_shortcuts.utils
import android.os.Build
import android.text.Html
import android.text.Spanned
object HTMLUtil {
@Suppress("DEPRECATION")
fun getHTML(string: String): Spanned =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(string, 0)
} else {
Html.fromHtml(string)
}
fun format(string: String): Spanned = getHTML(
string.replace("\n", "<br>")
)
}
## Instruction:
Use monospace font for <pre> in dialogs
## Code After:
package ch.rmy.android.http_shortcuts.utils
import android.os.Build
import android.text.Html
import android.text.Spanned
object HTMLUtil {
fun getHTML(string: String): Spanned =
fromHTML(normalize(string))
private fun normalize(string: String): String =
string.replace("<pre>", "<tt>")
.replace("</pre>", "</tt>")
@Suppress("DEPRECATION")
private fun fromHTML(string: String): Spanned =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(string, 0)
} else {
Html.fromHtml(string)
}
fun format(string: String): Spanned = getHTML(
string.replace("\n", "<br>")
)
}
|
# ... existing code ...
object HTMLUtil {
fun getHTML(string: String): Spanned =
fromHTML(normalize(string))
private fun normalize(string: String): String =
string.replace("<pre>", "<tt>")
.replace("</pre>", "</tt>")
@Suppress("DEPRECATION")
private fun fromHTML(string: String): Spanned =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(string, 0)
} else {
# ... rest of the code ...
|
83bd9b0b1e7de15e9f5c95fdc50b35d0379ce2c8
|
7segments.c
|
7segments.c
|
main(int u,char**a){for(char*c,y;y=u;u*=8)for(c=a[1];*c;)printf("%c%c%c%c",(y="$ֶ<&"[*c++-48])&u/2?33:32,y&u?95:32,y&u/4?33:32,*c?32:10);}
|
main(int u,char**a){for(char*c,y;y=u;u*=8,puts(""))for(c=a[1];*c;)printf("%c%c%c ",(y="$ֶ<&"[*c++-48])&u/2?33:32,y&u?95:32,y&u/4?33:32);}
|
Use puts again in a better position, save one byte (143)
|
Use puts again in a better position, save one byte (143)
|
C
|
mit
|
McZonk/7segements,McZonk/7segements
|
c
|
## Code Before:
main(int u,char**a){for(char*c,y;y=u;u*=8)for(c=a[1];*c;)printf("%c%c%c%c",(y="$ֶ<&"[*c++-48])&u/2?33:32,y&u?95:32,y&u/4?33:32,*c?32:10);}
## Instruction:
Use puts again in a better position, save one byte (143)
## Code After:
main(int u,char**a){for(char*c,y;y=u;u*=8,puts(""))for(c=a[1];*c;)printf("%c%c%c ",(y="$ֶ<&"[*c++-48])&u/2?33:32,y&u?95:32,y&u/4?33:32);}
|
# ... existing code ...
main(int u,char**a){for(char*c,y;y=u;u*=8,puts(""))for(c=a[1];*c;)printf("%c%c%c ",(y="$ֶ<&"[*c++-48])&u/2?33:32,y&u?95:32,y&u/4?33:32);}
# ... rest of the code ...
|
57513dfa0a7503a506751cc07826d16fc134b3f5
|
src/de.sormuras.bach/test/java/de/sormuras/bach/execution/BuildTaskGeneratorTests.java
|
src/de.sormuras.bach/test/java/de/sormuras/bach/execution/BuildTaskGeneratorTests.java
|
/*
* Bach - Java Shell Builder
* Copyright (C) 2020 Christian Stein
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.sormuras.bach.execution;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import de.sormuras.bach.api.Projects;
import org.junit.jupiter.api.Test;
class BuildTaskGeneratorTests {
@Test
void checkBuildTaskGenerationForMultiModuleProjectWithTests() {
var project = Projects.newProjectWithAllBellsAndWhistles();
var generator = new BuildTaskGenerator(project, true);
assertSame(project, generator.project());
assertTrue(generator.verbose());
var root = generator.get();
var program = Snippet.program(root);
assertTrue(program.size() > 10);
// program.forEach(System.out::println);
}
}
|
/*
* Bach - Java Shell Builder
* Copyright (C) 2020 Christian Stein
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.sormuras.bach.execution;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import de.sormuras.bach.api.Projects;
import org.junit.jupiter.api.Test;
import test.base.jdk.Compilation;
class BuildTaskGeneratorTests {
@Test
void checkBuildTaskGenerationForMultiModuleProjectWithTests() {
var project = Projects.newProjectWithAllBellsAndWhistles();
var generator = new BuildTaskGenerator(project, true);
assertSame(project, generator.project());
assertTrue(generator.verbose());
var program = Snippet.program(generator.get());
try {
assertDoesNotThrow(() -> Compilation.compile(program));
} catch (AssertionError e) {
program.forEach(System.err::println);
throw e;
}
}
}
|
Check generated build program is compilable
|
Check generated build program is compilable
|
Java
|
mit
|
sormuras/bach,sormuras/bach
|
java
|
## Code Before:
/*
* Bach - Java Shell Builder
* Copyright (C) 2020 Christian Stein
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.sormuras.bach.execution;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import de.sormuras.bach.api.Projects;
import org.junit.jupiter.api.Test;
class BuildTaskGeneratorTests {
@Test
void checkBuildTaskGenerationForMultiModuleProjectWithTests() {
var project = Projects.newProjectWithAllBellsAndWhistles();
var generator = new BuildTaskGenerator(project, true);
assertSame(project, generator.project());
assertTrue(generator.verbose());
var root = generator.get();
var program = Snippet.program(root);
assertTrue(program.size() > 10);
// program.forEach(System.out::println);
}
}
## Instruction:
Check generated build program is compilable
## Code After:
/*
* Bach - Java Shell Builder
* Copyright (C) 2020 Christian Stein
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.sormuras.bach.execution;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import de.sormuras.bach.api.Projects;
import org.junit.jupiter.api.Test;
import test.base.jdk.Compilation;
class BuildTaskGeneratorTests {
@Test
void checkBuildTaskGenerationForMultiModuleProjectWithTests() {
var project = Projects.newProjectWithAllBellsAndWhistles();
var generator = new BuildTaskGenerator(project, true);
assertSame(project, generator.project());
assertTrue(generator.verbose());
var program = Snippet.program(generator.get());
try {
assertDoesNotThrow(() -> Compilation.compile(program));
} catch (AssertionError e) {
program.forEach(System.err::println);
throw e;
}
}
}
|
...
package de.sormuras.bach.execution;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import de.sormuras.bach.api.Projects;
import org.junit.jupiter.api.Test;
import test.base.jdk.Compilation;
class BuildTaskGeneratorTests {
...
var generator = new BuildTaskGenerator(project, true);
assertSame(project, generator.project());
assertTrue(generator.verbose());
var program = Snippet.program(generator.get());
try {
assertDoesNotThrow(() -> Compilation.compile(program));
} catch (AssertionError e) {
program.forEach(System.err::println);
throw e;
}
}
}
...
|
7b520e973ed9a72cc3b68bda0a48c89b6d60558b
|
examples/connect4_uci_outcomes.py
|
examples/connect4_uci_outcomes.py
|
from __future__ import division, print_function
from collections import Counter
from capstone.util.c4uci import load_instance
FILENAME = 'datasets/connect-4.data'
outcomes = []
with open(FILENAME) as f:
for i, line in enumerate(f, 1):
_, outcome = load_instance(line)
outcomes.append(outcome)
if i % 1000 == 0:
print(i)
counter = Counter(outcomes)
print('\n---------')
print(' Results')
print('---------\n')
print('total: {}'.format(len(outcomes)))
for outcome in ['win', 'loss', 'draw']:
print('{outcome}: {count} ({pct:.2f}%)'.format(
outcome=outcome,
count=counter[outcome],
pct=((counter[outcome] / len(outcomes)) * 100)
))
|
from __future__ import division, print_function
import pandas as pd
from sklearn.linear_model import LinearRegression
from capstone.game import Connect4 as C4
from capstone.util import print_header
FILENAME = 'datasets/connect-4.data'
def column_name(i):
if i == 42:
return 'outcome'
row = chr(ord('a') + (i // C4.ROWS))
col = (i % C4.ROWS) + 1
return '{row}{col}'.format(row=row, col=col)
column_names = [column_name(i) for i in range(43)]
df = pd.read_csv(FILENAME, header=None, names=column_names)
outcomes = df.loc[:, 'outcome']
print_header('Dataset')
print(df, end='\n\n')
print_header('Number of instances')
print(df.shape[0], end='\n\n')
print_header('Outcomes')
print(outcomes.value_counts(), end='\n\n')
print_header('Normalized Outcomes')
print(outcomes.value_counts(normalize=True))
|
Use pandas dataframes for UCI C4 dataset
|
Use pandas dataframes for UCI C4 dataset
|
Python
|
mit
|
davidrobles/mlnd-capstone-code
|
python
|
## Code Before:
from __future__ import division, print_function
from collections import Counter
from capstone.util.c4uci import load_instance
FILENAME = 'datasets/connect-4.data'
outcomes = []
with open(FILENAME) as f:
for i, line in enumerate(f, 1):
_, outcome = load_instance(line)
outcomes.append(outcome)
if i % 1000 == 0:
print(i)
counter = Counter(outcomes)
print('\n---------')
print(' Results')
print('---------\n')
print('total: {}'.format(len(outcomes)))
for outcome in ['win', 'loss', 'draw']:
print('{outcome}: {count} ({pct:.2f}%)'.format(
outcome=outcome,
count=counter[outcome],
pct=((counter[outcome] / len(outcomes)) * 100)
))
## Instruction:
Use pandas dataframes for UCI C4 dataset
## Code After:
from __future__ import division, print_function
import pandas as pd
from sklearn.linear_model import LinearRegression
from capstone.game import Connect4 as C4
from capstone.util import print_header
FILENAME = 'datasets/connect-4.data'
def column_name(i):
if i == 42:
return 'outcome'
row = chr(ord('a') + (i // C4.ROWS))
col = (i % C4.ROWS) + 1
return '{row}{col}'.format(row=row, col=col)
column_names = [column_name(i) for i in range(43)]
df = pd.read_csv(FILENAME, header=None, names=column_names)
outcomes = df.loc[:, 'outcome']
print_header('Dataset')
print(df, end='\n\n')
print_header('Number of instances')
print(df.shape[0], end='\n\n')
print_header('Outcomes')
print(outcomes.value_counts(), end='\n\n')
print_header('Normalized Outcomes')
print(outcomes.value_counts(normalize=True))
|
# ... existing code ...
from __future__ import division, print_function
import pandas as pd
from sklearn.linear_model import LinearRegression
from capstone.game import Connect4 as C4
from capstone.util import print_header
FILENAME = 'datasets/connect-4.data'
def column_name(i):
if i == 42:
return 'outcome'
row = chr(ord('a') + (i // C4.ROWS))
col = (i % C4.ROWS) + 1
return '{row}{col}'.format(row=row, col=col)
column_names = [column_name(i) for i in range(43)]
df = pd.read_csv(FILENAME, header=None, names=column_names)
outcomes = df.loc[:, 'outcome']
print_header('Dataset')
print(df, end='\n\n')
print_header('Number of instances')
print(df.shape[0], end='\n\n')
print_header('Outcomes')
print(outcomes.value_counts(), end='\n\n')
print_header('Normalized Outcomes')
print(outcomes.value_counts(normalize=True))
# ... rest of the code ...
|
00ae10769d95445b80be0e8d129fbc76b63aca5a
|
flexget/utils/soup.py
|
flexget/utils/soup.py
|
import html5lib
from html5lib import treebuilders
from cStringIO import StringIO
def get_soup(obj):
if isinstance(obj, basestring):
obj = StringIO(obj)
parser = html5lib.HTMLParser(tree=treebuilders.getTreeBuilder('beautifulsoup'))
return parser.parse(obj)
|
import html5lib
from html5lib import treebuilders
from cStringIO import StringIO
# Hack, hide DataLossWarnings
# Based on html5lib code namespaceHTMLElements=False should do it, but nope ...
import warnings
from html5lib.constants import DataLossWarning
warnings.simplefilter('ignore', DataLossWarning)
def get_soup(obj):
if isinstance(obj, basestring):
obj = StringIO(obj)
parser = html5lib.HTMLParser(namespaceHTMLElements=False, tree=treebuilders.getTreeBuilder('beautifulsoup'))
return parser.parse(obj)
|
Hide DataLossWarnings that appeared with html5lib 0.90 or so.
|
Hide DataLossWarnings that appeared with html5lib 0.90 or so.
git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@1124 3942dd89-8c5d-46d7-aeed-044bccf3e60c
|
Python
|
mit
|
qk4l/Flexget,sean797/Flexget,ZefQ/Flexget,qk4l/Flexget,tobinjt/Flexget,grrr2/Flexget,jacobmetrick/Flexget,oxc/Flexget,camon/Flexget,crawln45/Flexget,xfouloux/Flexget,thalamus/Flexget,JorisDeRieck/Flexget,vfrc2/Flexget,patsissons/Flexget,cvium/Flexget,ianstalk/Flexget,tvcsantos/Flexget,jawilson/Flexget,OmgOhnoes/Flexget,v17al/Flexget,tvcsantos/Flexget,thalamus/Flexget,xfouloux/Flexget,cvium/Flexget,crawln45/Flexget,tobinjt/Flexget,vfrc2/Flexget,gazpachoking/Flexget,Pretagonist/Flexget,ibrahimkarahan/Flexget,Pretagonist/Flexget,dsemi/Flexget,Danfocus/Flexget,tsnoam/Flexget,lildadou/Flexget,Flexget/Flexget,Danfocus/Flexget,tobinjt/Flexget,ratoaq2/Flexget,camon/Flexget,tobinjt/Flexget,Danfocus/Flexget,OmgOhnoes/Flexget,poulpito/Flexget,v17al/Flexget,lildadou/Flexget,tarzasai/Flexget,offbyone/Flexget,jawilson/Flexget,Pretagonist/Flexget,ianstalk/Flexget,cvium/Flexget,v17al/Flexget,qvazzler/Flexget,X-dark/Flexget,ianstalk/Flexget,vfrc2/Flexget,malkavi/Flexget,sean797/Flexget,spencerjanssen/Flexget,tsnoam/Flexget,JorisDeRieck/Flexget,qvazzler/Flexget,LynxyssCZ/Flexget,antivirtel/Flexget,voriux/Flexget,ratoaq2/Flexget,lildadou/Flexget,drwyrm/Flexget,ZefQ/Flexget,ibrahimkarahan/Flexget,OmgOhnoes/Flexget,spencerjanssen/Flexget,JorisDeRieck/Flexget,antivirtel/Flexget,jacobmetrick/Flexget,drwyrm/Flexget,asm0dey/Flexget,malkavi/Flexget,offbyone/Flexget,offbyone/Flexget,poulpito/Flexget,qk4l/Flexget,asm0dey/Flexget,Flexget/Flexget,X-dark/Flexget,xfouloux/Flexget,voriux/Flexget,tarzasai/Flexget,crawln45/Flexget,ZefQ/Flexget,Flexget/Flexget,Danfocus/Flexget,thalamus/Flexget,drwyrm/Flexget,qvazzler/Flexget,crawln45/Flexget,X-dark/Flexget,tsnoam/Flexget,sean797/Flexget,LynxyssCZ/Flexget,JorisDeRieck/Flexget,dsemi/Flexget,dsemi/Flexget,grrr2/Flexget,patsissons/Flexget,spencerjanssen/Flexget,jacobmetrick/Flexget,malkavi/Flexget,LynxyssCZ/Flexget,tarzasai/Flexget,ibrahimkarahan/Flexget,oxc/Flexget,ratoaq2/Flexget,jawilson/Flexget,poulpito/Flexget,gazpachoking/Flexget,malkavi/Flexget,antivirtel/Flexget,asm0dey/Flexget,Flexget/Flexget,oxc/Flexget,grrr2/Flexget,patsissons/Flexget,LynxyssCZ/Flexget,jawilson/Flexget
|
python
|
## Code Before:
import html5lib
from html5lib import treebuilders
from cStringIO import StringIO
def get_soup(obj):
if isinstance(obj, basestring):
obj = StringIO(obj)
parser = html5lib.HTMLParser(tree=treebuilders.getTreeBuilder('beautifulsoup'))
return parser.parse(obj)
## Instruction:
Hide DataLossWarnings that appeared with html5lib 0.90 or so.
git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@1124 3942dd89-8c5d-46d7-aeed-044bccf3e60c
## Code After:
import html5lib
from html5lib import treebuilders
from cStringIO import StringIO
# Hack, hide DataLossWarnings
# Based on html5lib code namespaceHTMLElements=False should do it, but nope ...
import warnings
from html5lib.constants import DataLossWarning
warnings.simplefilter('ignore', DataLossWarning)
def get_soup(obj):
if isinstance(obj, basestring):
obj = StringIO(obj)
parser = html5lib.HTMLParser(namespaceHTMLElements=False, tree=treebuilders.getTreeBuilder('beautifulsoup'))
return parser.parse(obj)
|
...
from html5lib import treebuilders
from cStringIO import StringIO
# Hack, hide DataLossWarnings
# Based on html5lib code namespaceHTMLElements=False should do it, but nope ...
import warnings
from html5lib.constants import DataLossWarning
warnings.simplefilter('ignore', DataLossWarning)
def get_soup(obj):
if isinstance(obj, basestring):
obj = StringIO(obj)
parser = html5lib.HTMLParser(namespaceHTMLElements=False, tree=treebuilders.getTreeBuilder('beautifulsoup'))
return parser.parse(obj)
...
|
90b92a1977c32dd660533567c0d5034b93d5c9c7
|
pombola/core/management/commands/core_create_places_from_mapit_entries.py
|
pombola/core/management/commands/core_create_places_from_mapit_entries.py
|
from django.core.management.base import LabelCommand
from mapit.models import Type
from pombola.core.models import Place, PlaceKind
from django.template.defaultfilters import slugify
class Command(LabelCommand):
help = 'Copy mapit.areas to core.places'
args = '<mapit.type.code>'
def handle_label(self, mapit_type_code, **options):
# load the mapit type
mapit_type = Type.objects.get(code=mapit_type_code)
# if needed create the core placetype
placekind, created = PlaceKind.objects.get_or_create(
name=mapit_type.description,
defaults={
'slug': slugify(mapit_type.description)
}
)
# create all the places as needed for all mapit areas of that type
for area in mapit_type.areas.all():
print area.name
place, created = Place.objects.get_or_create(
name=area.name,
kind=placekind,
defaults={
'slug': slugify(area.name),
}
)
place.mapit_area = area
place.save()
|
from django.core.management.base import LabelCommand
from mapit.models import Type
from pombola.core.models import Place, PlaceKind
from django.template.defaultfilters import slugify
class Command(LabelCommand):
help = 'Copy mapit.areas to core.places'
args = '<mapit.type.code>'
def handle_label(self, mapit_type_code, **options):
# load the mapit type
mapit_type = Type.objects.get(code=mapit_type_code)
# if needed create the core placetype
placekind, created = PlaceKind.objects.get_or_create(
name=mapit_type.description,
defaults={
'slug': slugify(mapit_type.description)
}
)
# create all the places as needed for all mapit areas of that type
for area in mapit_type.areas.all():
# There may be a slug clash as several areas have the same name but
# are different placekinds. Create the slug and then check to see
# if the slug is already in use for a placekind other than ours. If
# it is append the placekind to the slug.
slug = slugify(area.name)
if Place.objects.filter(slug=slug).exclude(kind=placekind).exists():
slug = slug + '-' + placekind.slug
print "'%s' (%s)" % (area.name, slug)
place, created = Place.objects.get_or_create(
name=area.name,
kind=placekind,
defaults={
'slug': slug,
}
)
place.mapit_area = area
place.save()
|
Add smarts to cope with slug clashes with other places with the same names.
|
Add smarts to cope with slug clashes with other places with the same names.
|
Python
|
agpl-3.0
|
patricmutwiri/pombola,hzj123/56th,geoffkilpin/pombola,patricmutwiri/pombola,hzj123/56th,ken-muturi/pombola,hzj123/56th,hzj123/56th,mysociety/pombola,mysociety/pombola,hzj123/56th,geoffkilpin/pombola,mysociety/pombola,ken-muturi/pombola,hzj123/56th,mysociety/pombola,ken-muturi/pombola,mysociety/pombola,patricmutwiri/pombola,geoffkilpin/pombola,patricmutwiri/pombola,patricmutwiri/pombola,ken-muturi/pombola,geoffkilpin/pombola,mysociety/pombola,ken-muturi/pombola,geoffkilpin/pombola,ken-muturi/pombola,geoffkilpin/pombola,patricmutwiri/pombola
|
python
|
## Code Before:
from django.core.management.base import LabelCommand
from mapit.models import Type
from pombola.core.models import Place, PlaceKind
from django.template.defaultfilters import slugify
class Command(LabelCommand):
help = 'Copy mapit.areas to core.places'
args = '<mapit.type.code>'
def handle_label(self, mapit_type_code, **options):
# load the mapit type
mapit_type = Type.objects.get(code=mapit_type_code)
# if needed create the core placetype
placekind, created = PlaceKind.objects.get_or_create(
name=mapit_type.description,
defaults={
'slug': slugify(mapit_type.description)
}
)
# create all the places as needed for all mapit areas of that type
for area in mapit_type.areas.all():
print area.name
place, created = Place.objects.get_or_create(
name=area.name,
kind=placekind,
defaults={
'slug': slugify(area.name),
}
)
place.mapit_area = area
place.save()
## Instruction:
Add smarts to cope with slug clashes with other places with the same names.
## Code After:
from django.core.management.base import LabelCommand
from mapit.models import Type
from pombola.core.models import Place, PlaceKind
from django.template.defaultfilters import slugify
class Command(LabelCommand):
help = 'Copy mapit.areas to core.places'
args = '<mapit.type.code>'
def handle_label(self, mapit_type_code, **options):
# load the mapit type
mapit_type = Type.objects.get(code=mapit_type_code)
# if needed create the core placetype
placekind, created = PlaceKind.objects.get_or_create(
name=mapit_type.description,
defaults={
'slug': slugify(mapit_type.description)
}
)
# create all the places as needed for all mapit areas of that type
for area in mapit_type.areas.all():
# There may be a slug clash as several areas have the same name but
# are different placekinds. Create the slug and then check to see
# if the slug is already in use for a placekind other than ours. If
# it is append the placekind to the slug.
slug = slugify(area.name)
if Place.objects.filter(slug=slug).exclude(kind=placekind).exists():
slug = slug + '-' + placekind.slug
print "'%s' (%s)" % (area.name, slug)
place, created = Place.objects.get_or_create(
name=area.name,
kind=placekind,
defaults={
'slug': slug,
}
)
place.mapit_area = area
place.save()
|
...
# create all the places as needed for all mapit areas of that type
for area in mapit_type.areas.all():
# There may be a slug clash as several areas have the same name but
# are different placekinds. Create the slug and then check to see
# if the slug is already in use for a placekind other than ours. If
# it is append the placekind to the slug.
slug = slugify(area.name)
if Place.objects.filter(slug=slug).exclude(kind=placekind).exists():
slug = slug + '-' + placekind.slug
print "'%s' (%s)" % (area.name, slug)
place, created = Place.objects.get_or_create(
name=area.name,
kind=placekind,
defaults={
'slug': slug,
}
)
place.mapit_area = area
place.save()
...
|
ddeffc09ce1eab426fe46129bead712059f93f45
|
docker/settings/web.py
|
docker/settings/web.py
|
from .docker_compose import DockerBaseSettings
class WebDevSettings(DockerBaseSettings):
# Needed to serve 404 pages properly
# NOTE: it may introduce some strange behavior
DEBUG = False
WebDevSettings.load_settings(__name__)
|
from .docker_compose import DockerBaseSettings
class WebDevSettings(DockerBaseSettings):
pass
WebDevSettings.load_settings(__name__)
|
Remove DEBUG=False that's not needed anymore
|
Remove DEBUG=False that's not needed anymore
Now we are serving 404s via El Proxito and forcing DEBUG=False is not
needed anymore.
|
Python
|
mit
|
rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org
|
python
|
## Code Before:
from .docker_compose import DockerBaseSettings
class WebDevSettings(DockerBaseSettings):
# Needed to serve 404 pages properly
# NOTE: it may introduce some strange behavior
DEBUG = False
WebDevSettings.load_settings(__name__)
## Instruction:
Remove DEBUG=False that's not needed anymore
Now we are serving 404s via El Proxito and forcing DEBUG=False is not
needed anymore.
## Code After:
from .docker_compose import DockerBaseSettings
class WebDevSettings(DockerBaseSettings):
pass
WebDevSettings.load_settings(__name__)
|
// ... existing code ...
from .docker_compose import DockerBaseSettings
class WebDevSettings(DockerBaseSettings):
pass
WebDevSettings.load_settings(__name__)
// ... rest of the code ...
|
8989258dab574cff0bc8001f1d59232983d15f68
|
grammpy/Grammars/PrettyApiGrammar.py
|
grammpy/Grammars/PrettyApiGrammar.py
|
from .MultipleRulesGrammar import MultipleRulesGrammar as Grammar
class PrettyApiGrammar(Grammar):
def __init__(self,
terminals=None,
nonterminals=None,
rules=None,
start_symbol=None):
if isinstance(terminals, str):
temp = []
for ch in terminals:
temp.append(ch)
terminals = temp
super().__init__(terminals=terminals,
nonterminals=nonterminals,
rules=rules,
start_symbol=start_symbol)
|
from .MultipleRulesGrammar import MultipleRulesGrammar as Grammar
class PrettyApiGrammar(Grammar):
def __init__(self,
terminals=None,
nonterminals=None,
rules=None,
start_symbol=None):
if isinstance(terminals, str):
temp = []
for ch in terminals:
temp.append(ch)
terminals = temp
super().__init__(terminals=terminals,
nonterminals=nonterminals,
rules=rules,
start_symbol=start_symbol)
def __copy__(self):
return PrettyApiGrammar(terminals=(t.s for t in self.terms()),
nonterminals=self.nonterms(),
rules=self.rules(),
start_symbol=self.start_get())
|
Add __copy__ method to grammar
|
Add __copy__ method to grammar
|
Python
|
mit
|
PatrikValkovic/grammpy
|
python
|
## Code Before:
from .MultipleRulesGrammar import MultipleRulesGrammar as Grammar
class PrettyApiGrammar(Grammar):
def __init__(self,
terminals=None,
nonterminals=None,
rules=None,
start_symbol=None):
if isinstance(terminals, str):
temp = []
for ch in terminals:
temp.append(ch)
terminals = temp
super().__init__(terminals=terminals,
nonterminals=nonterminals,
rules=rules,
start_symbol=start_symbol)
## Instruction:
Add __copy__ method to grammar
## Code After:
from .MultipleRulesGrammar import MultipleRulesGrammar as Grammar
class PrettyApiGrammar(Grammar):
def __init__(self,
terminals=None,
nonterminals=None,
rules=None,
start_symbol=None):
if isinstance(terminals, str):
temp = []
for ch in terminals:
temp.append(ch)
terminals = temp
super().__init__(terminals=terminals,
nonterminals=nonterminals,
rules=rules,
start_symbol=start_symbol)
def __copy__(self):
return PrettyApiGrammar(terminals=(t.s for t in self.terms()),
nonterminals=self.nonterms(),
rules=self.rules(),
start_symbol=self.start_get())
|
...
nonterminals=nonterminals,
rules=rules,
start_symbol=start_symbol)
def __copy__(self):
return PrettyApiGrammar(terminals=(t.s for t in self.terms()),
nonterminals=self.nonterms(),
rules=self.rules(),
start_symbol=self.start_get())
...
|
3b8a54f2ce220de26741aa329ebb45ceeb3b99c5
|
external_file_location/__manifest__.py
|
external_file_location/__manifest__.py
|
{
'name': 'External File Location',
'version': '10.0.1.0.0',
'author': 'Akretion,Odoo Community Association (OCA),ThinkOpen Solutions Brasil',
'website': 'http://www.akretion.com/',
'license': 'AGPL-3',
'category': 'Generic Modules',
'depends': [
'attachment_base_synchronize',
],
'external_dependencies': {
'python': [
'fs',
'paramiko',
],
},
'data': [
'views/menu.xml',
'views/attachment_view.xml',
'views/location_view.xml',
'views/task_view.xml',
'data/cron.xml',
'security/ir.model.access.csv',
],
'demo': [
'demo/task_demo.xml',
],
'installable': True,
'application': False,
}
|
{
'name': 'External File Location',
'version': '10.0.1.0.0',
'author': 'Akretion,Odoo Community Association (OCA),'
'ThinkOpen Solutions Brasil',
'website': 'http://www.akretion.com/',
'license': 'AGPL-3',
'category': 'Generic Modules',
'depends': [
'attachment_base_synchronize',
],
'external_dependencies': {
'python': [
'fs',
'paramiko',
],
},
'data': [
'views/menu.xml',
'views/attachment_view.xml',
'views/location_view.xml',
'views/task_view.xml',
'data/cron.xml',
'security/ir.model.access.csv',
],
'demo': [
'demo/task_demo.xml',
],
'installable': True,
'application': False,
}
|
Fix line lenght in manifest
|
Fix line lenght in manifest
|
Python
|
agpl-3.0
|
thinkopensolutions/server-tools,thinkopensolutions/server-tools
|
python
|
## Code Before:
{
'name': 'External File Location',
'version': '10.0.1.0.0',
'author': 'Akretion,Odoo Community Association (OCA),ThinkOpen Solutions Brasil',
'website': 'http://www.akretion.com/',
'license': 'AGPL-3',
'category': 'Generic Modules',
'depends': [
'attachment_base_synchronize',
],
'external_dependencies': {
'python': [
'fs',
'paramiko',
],
},
'data': [
'views/menu.xml',
'views/attachment_view.xml',
'views/location_view.xml',
'views/task_view.xml',
'data/cron.xml',
'security/ir.model.access.csv',
],
'demo': [
'demo/task_demo.xml',
],
'installable': True,
'application': False,
}
## Instruction:
Fix line lenght in manifest
## Code After:
{
'name': 'External File Location',
'version': '10.0.1.0.0',
'author': 'Akretion,Odoo Community Association (OCA),'
'ThinkOpen Solutions Brasil',
'website': 'http://www.akretion.com/',
'license': 'AGPL-3',
'category': 'Generic Modules',
'depends': [
'attachment_base_synchronize',
],
'external_dependencies': {
'python': [
'fs',
'paramiko',
],
},
'data': [
'views/menu.xml',
'views/attachment_view.xml',
'views/location_view.xml',
'views/task_view.xml',
'data/cron.xml',
'security/ir.model.access.csv',
],
'demo': [
'demo/task_demo.xml',
],
'installable': True,
'application': False,
}
|
// ... existing code ...
{
'name': 'External File Location',
'version': '10.0.1.0.0',
'author': 'Akretion,Odoo Community Association (OCA),'
'ThinkOpen Solutions Brasil',
'website': 'http://www.akretion.com/',
'license': 'AGPL-3',
'category': 'Generic Modules',
// ... rest of the code ...
|
a02739581d6c9dbde900c226d121b4fb889b4e2d
|
window.py
|
window.py
|
from PySide import QtGui
from editor import Editor
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
editor = Editor()
self.setCentralWidget(editor)
self.setWindowTitle("RST Previewer")
self.showMaximized()
|
from PySide import QtGui, QtCore
from editor import Editor
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
splitter = QtGui.QSplitter(QtCore.Qt.Horizontal)
treeview = QtGui.QTreeView()
editor = Editor()
self.setCentralWidget(splitter)
splitter.addWidget(treeview)
splitter.addWidget(editor)
self.setWindowTitle("RST Previewer")
self.showMaximized()
|
Add splitter with treeview/editor split.
|
Add splitter with treeview/editor split.
|
Python
|
bsd-3-clause
|
audreyr/sphinx-gui,techdragon/sphinx-gui,audreyr/sphinx-gui,techdragon/sphinx-gui
|
python
|
## Code Before:
from PySide import QtGui
from editor import Editor
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
editor = Editor()
self.setCentralWidget(editor)
self.setWindowTitle("RST Previewer")
self.showMaximized()
## Instruction:
Add splitter with treeview/editor split.
## Code After:
from PySide import QtGui, QtCore
from editor import Editor
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
splitter = QtGui.QSplitter(QtCore.Qt.Horizontal)
treeview = QtGui.QTreeView()
editor = Editor()
self.setCentralWidget(splitter)
splitter.addWidget(treeview)
splitter.addWidget(editor)
self.setWindowTitle("RST Previewer")
self.showMaximized()
|
...
from PySide import QtGui, QtCore
from editor import Editor
...
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
splitter = QtGui.QSplitter(QtCore.Qt.Horizontal)
treeview = QtGui.QTreeView()
editor = Editor()
self.setCentralWidget(splitter)
splitter.addWidget(treeview)
splitter.addWidget(editor)
self.setWindowTitle("RST Previewer")
self.showMaximized()
...
|
c0586ceccbf7ca0fed6f5ef4392df2dda75d782c
|
src/main/java/main/MainClass.java
|
src/main/java/main/MainClass.java
|
/**
*
*/
package main;
<<<<<<< Updated upstream
/**
* @author Bart
*
*/
public class MainClass {
/**
* @param arg - the main arguments
*/
public static void main(String[] args) {
System.out.println("Welcom to the main class of goto-fail;");
}
=======
import lombok.Getter;
import lombok.Setter;
public class MainClass {
@Getter
@Setter
public static int counter;
/**
* @param args - the main arguments.
*/
public static void main(String[] args) {
setCounter(5);
System.out.println(getCounter());
System.out.println("Welcome to the main class of goto-fail;");
}
>>>>>>> Stashed changes
}
|
package main;
import lombok.Getter;
import lombok.Setter;
public class MainClass {
@Getter @Setter
public static int counter;
/**
* @param args - the main arguments.
*/
public static void main(String[] args) {
setCounter(5);
System.out.println(getCounter());
System.out.println("Welcome to the main class of goto-fail;");
}
}
|
Remove wierd git behaviour & Fix name javadoc
|
Remove wierd git behaviour & Fix name javadoc
|
Java
|
apache-2.0
|
bartdejonge1996/goto-fail,bartdejonge1996/goto-fail
|
java
|
## Code Before:
/**
*
*/
package main;
<<<<<<< Updated upstream
/**
* @author Bart
*
*/
public class MainClass {
/**
* @param arg - the main arguments
*/
public static void main(String[] args) {
System.out.println("Welcom to the main class of goto-fail;");
}
=======
import lombok.Getter;
import lombok.Setter;
public class MainClass {
@Getter
@Setter
public static int counter;
/**
* @param args - the main arguments.
*/
public static void main(String[] args) {
setCounter(5);
System.out.println(getCounter());
System.out.println("Welcome to the main class of goto-fail;");
}
>>>>>>> Stashed changes
}
## Instruction:
Remove wierd git behaviour & Fix name javadoc
## Code After:
package main;
import lombok.Getter;
import lombok.Setter;
public class MainClass {
@Getter @Setter
public static int counter;
/**
* @param args - the main arguments.
*/
public static void main(String[] args) {
setCounter(5);
System.out.println(getCounter());
System.out.println("Welcome to the main class of goto-fail;");
}
}
|
...
package main;
import lombok.Getter;
import lombok.Setter;
public class MainClass {
@Getter @Setter
public static int counter;
/**
...
public static void main(String[] args) {
setCounter(5);
System.out.println(getCounter());
System.out.println("Welcome to the main class of goto-fail;");
}
}
...
|
4e306441cbfab5f56eaedcd9af8f71f84e40467c
|
tests/pytests/unit/states/test_makeconf.py
|
tests/pytests/unit/states/test_makeconf.py
|
import pytest
import salt.states.makeconf as makeconf
from tests.support.mock import MagicMock, patch
@pytest.fixture
def configure_loader_modules():
return {makeconf: {}}
def test_present():
"""
Test to verify that the variable is in the ``make.conf``
and has the provided settings.
"""
name = "makeopts"
ret = {"name": name, "result": True, "comment": "", "changes": {}}
mock_t = MagicMock(return_value=True)
with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock_t}):
comt = "Variable {} is already present in make.conf".format(name)
ret.update({"comment": comt})
assert makeconf.present(name) == ret
# 'absent' function tests: 1
def test_absent():
"""
Test to verify that the variable is not in the ``make.conf``.
"""
name = "makeopts"
ret = {"name": name, "result": True, "comment": "", "changes": {}}
mock = MagicMock(return_value=None)
with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock}):
comt = "Variable {} is already absent from make.conf".format(name)
ret.update({"comment": comt})
assert makeconf.absent(name) == ret
|
import pytest
import salt.states.makeconf as makeconf
from tests.support.mock import MagicMock, patch
@pytest.fixture
def configure_loader_modules():
return {makeconf: {}}
def test_present():
"""
Test to verify that the variable is in the ``make.conf``
and has the provided settings.
"""
name = "makeopts"
ret = {"name": name, "result": True, "comment": "", "changes": {}}
mock_t = MagicMock(return_value=True)
with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock_t}):
comt = "Variable {} is already present in make.conf".format(name)
ret.update({"comment": comt})
assert makeconf.present(name) == ret
def test_absent():
"""
Test to verify that the variable is not in the ``make.conf``.
"""
name = "makeopts"
ret = {"name": name, "result": True, "comment": "", "changes": {}}
mock = MagicMock(return_value=None)
with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock}):
comt = "Variable {} is already absent from make.conf".format(name)
ret.update({"comment": comt})
assert makeconf.absent(name) == ret
|
Move makeconf state tests to pytest
|
Move makeconf state tests to pytest
|
Python
|
apache-2.0
|
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
|
python
|
## Code Before:
import pytest
import salt.states.makeconf as makeconf
from tests.support.mock import MagicMock, patch
@pytest.fixture
def configure_loader_modules():
return {makeconf: {}}
def test_present():
"""
Test to verify that the variable is in the ``make.conf``
and has the provided settings.
"""
name = "makeopts"
ret = {"name": name, "result": True, "comment": "", "changes": {}}
mock_t = MagicMock(return_value=True)
with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock_t}):
comt = "Variable {} is already present in make.conf".format(name)
ret.update({"comment": comt})
assert makeconf.present(name) == ret
# 'absent' function tests: 1
def test_absent():
"""
Test to verify that the variable is not in the ``make.conf``.
"""
name = "makeopts"
ret = {"name": name, "result": True, "comment": "", "changes": {}}
mock = MagicMock(return_value=None)
with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock}):
comt = "Variable {} is already absent from make.conf".format(name)
ret.update({"comment": comt})
assert makeconf.absent(name) == ret
## Instruction:
Move makeconf state tests to pytest
## Code After:
import pytest
import salt.states.makeconf as makeconf
from tests.support.mock import MagicMock, patch
@pytest.fixture
def configure_loader_modules():
return {makeconf: {}}
def test_present():
"""
Test to verify that the variable is in the ``make.conf``
and has the provided settings.
"""
name = "makeopts"
ret = {"name": name, "result": True, "comment": "", "changes": {}}
mock_t = MagicMock(return_value=True)
with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock_t}):
comt = "Variable {} is already present in make.conf".format(name)
ret.update({"comment": comt})
assert makeconf.present(name) == ret
def test_absent():
"""
Test to verify that the variable is not in the ``make.conf``.
"""
name = "makeopts"
ret = {"name": name, "result": True, "comment": "", "changes": {}}
mock = MagicMock(return_value=None)
with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock}):
comt = "Variable {} is already absent from make.conf".format(name)
ret.update({"comment": comt})
assert makeconf.absent(name) == ret
|
...
assert makeconf.present(name) == ret
def test_absent():
"""
Test to verify that the variable is not in the ``make.conf``.
...
|
5df350254e966007f80f7a14fde29a8c93316bb3
|
tests/rules/test_git_push.py
|
tests/rules/test_git_push.py
|
import pytest
from thefuck.rules.git_push import match, get_new_command
from tests.utils import Command
@pytest.fixture
def stderr():
return '''fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use
git push --set-upstream origin master
'''
def test_match(stderr):
assert match(Command('git push', stderr=stderr))
assert match(Command('git push master', stderr=stderr))
assert not match(Command('git push master'))
assert not match(Command('ls', stderr=stderr))
def test_get_new_command(stderr):
assert get_new_command(Command('git push', stderr=stderr))\
== "git push --set-upstream origin master"
|
import pytest
from thefuck.rules.git_push import match, get_new_command
from tests.utils import Command
@pytest.fixture
def stderr():
return '''fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use
git push --set-upstream origin master
'''
def test_match(stderr):
assert match(Command('git push', stderr=stderr))
assert match(Command('git push master', stderr=stderr))
assert not match(Command('git push master'))
assert not match(Command('ls', stderr=stderr))
def test_get_new_command(stderr):
assert get_new_command(Command('git push', stderr=stderr))\
== "git push --set-upstream origin master"
assert get_new_command(Command('git push --quiet', stderr=stderr))\
== "git push --set-upstream origin master --quiet"
|
Check arguments are preserved in git_push
|
Check arguments are preserved in git_push
|
Python
|
mit
|
scorphus/thefuck,mlk/thefuck,Clpsplug/thefuck,SimenB/thefuck,nvbn/thefuck,Clpsplug/thefuck,SimenB/thefuck,mlk/thefuck,nvbn/thefuck,scorphus/thefuck
|
python
|
## Code Before:
import pytest
from thefuck.rules.git_push import match, get_new_command
from tests.utils import Command
@pytest.fixture
def stderr():
return '''fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use
git push --set-upstream origin master
'''
def test_match(stderr):
assert match(Command('git push', stderr=stderr))
assert match(Command('git push master', stderr=stderr))
assert not match(Command('git push master'))
assert not match(Command('ls', stderr=stderr))
def test_get_new_command(stderr):
assert get_new_command(Command('git push', stderr=stderr))\
== "git push --set-upstream origin master"
## Instruction:
Check arguments are preserved in git_push
## Code After:
import pytest
from thefuck.rules.git_push import match, get_new_command
from tests.utils import Command
@pytest.fixture
def stderr():
return '''fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use
git push --set-upstream origin master
'''
def test_match(stderr):
assert match(Command('git push', stderr=stderr))
assert match(Command('git push master', stderr=stderr))
assert not match(Command('git push master'))
assert not match(Command('ls', stderr=stderr))
def test_get_new_command(stderr):
assert get_new_command(Command('git push', stderr=stderr))\
== "git push --set-upstream origin master"
assert get_new_command(Command('git push --quiet', stderr=stderr))\
== "git push --set-upstream origin master --quiet"
|
...
def test_get_new_command(stderr):
assert get_new_command(Command('git push', stderr=stderr))\
== "git push --set-upstream origin master"
assert get_new_command(Command('git push --quiet', stderr=stderr))\
== "git push --set-upstream origin master --quiet"
...
|
c3957dbb25a8b5eeeccd37f218976721249b93e2
|
src/competition/tests/validator_tests.py
|
src/competition/tests/validator_tests.py
|
from django.test import TestCase
from django.template.defaultfilters import slugify
from django.core.exceptions import ValidationError
from competition.validators import greater_than_zero, non_negative, validate_name
class ValidationFunctionTest(TestCase):
def test_greater_than_zero(self):
"""Check greater_than_zero validator"""
self.assertRaises(ValidationError, greater_than_zero, 0)
self.assertRaises(ValidationError, greater_than_zero, -1)
self.assertIsNone(greater_than_zero(1))
def test_non_negative(self):
"""Check non_negative validator"""
self.assertRaises(ValidationError, non_negative, -1)
self.assertIsNone(non_negative(0))
self.assertIsNone(non_negative(1))
def test_validate_name(self):
"""Check name validator"""
# Try some valid names
valid_names = ['MegaMiner-AI 10: Galapagos', 'Chess 2012', '2012 Chess',
'B.L.O.O.M. 2: Revenge of the Flowers', '__main__']
for name in valid_names:
self.assertIsNone(validate_name(name))
self.assertRaises(ValidationError, validate_name, "..")
self.assertRaises(ValidationError, validate_name, "_..")
self.assertRaises(ValidationError, validate_name, "_")
self.assertRaises(ValidationError, validate_name, "____")
self.assertRaises(ValidationError, validate_name, ".Nope")
self.assertRaises(ValidationError, validate_name, ".Nope")
|
from django.test import TestCase
from django.template.defaultfilters import slugify
from django.core.exceptions import ValidationError
from competition.validators import greater_than_zero, non_negative, validate_name
class ValidationFunctionTest(TestCase):
def test_greater_than_zero(self):
"""Check greater_than_zero validator"""
self.assertRaises(ValidationError, greater_than_zero, 0)
self.assertRaises(ValidationError, greater_than_zero, -1)
self.assertIsNone(greater_than_zero(1))
def test_non_negative(self):
"""Check non_negative validator"""
self.assertRaises(ValidationError, non_negative, -1)
self.assertIsNone(non_negative(0))
self.assertIsNone(non_negative(1))
def test_validate_name(self):
"""Check name validator"""
# Try some valid names
valid_names = ['MegaMiner-AI 10: Galapagos', 'Chess 2012', '2012 Chess',
'B.L.O.O.M. 2: Revenge of the Flowers']
for name in valid_names:
self.assertIsNone(validate_name(name))
self.assertRaises(ValidationError, validate_name, "..")
self.assertRaises(ValidationError, validate_name, "_..")
self.assertRaises(ValidationError, validate_name, "_")
self.assertRaises(ValidationError, validate_name, "____")
self.assertRaises(ValidationError, validate_name, ".Nope")
self.assertRaises(ValidationError, validate_name, ".Nope")
|
Correct unit tests to comply with new team name RE
|
Correct unit tests to comply with new team name RE
|
Python
|
bsd-3-clause
|
michaelwisely/django-competition,michaelwisely/django-competition,michaelwisely/django-competition
|
python
|
## Code Before:
from django.test import TestCase
from django.template.defaultfilters import slugify
from django.core.exceptions import ValidationError
from competition.validators import greater_than_zero, non_negative, validate_name
class ValidationFunctionTest(TestCase):
def test_greater_than_zero(self):
"""Check greater_than_zero validator"""
self.assertRaises(ValidationError, greater_than_zero, 0)
self.assertRaises(ValidationError, greater_than_zero, -1)
self.assertIsNone(greater_than_zero(1))
def test_non_negative(self):
"""Check non_negative validator"""
self.assertRaises(ValidationError, non_negative, -1)
self.assertIsNone(non_negative(0))
self.assertIsNone(non_negative(1))
def test_validate_name(self):
"""Check name validator"""
# Try some valid names
valid_names = ['MegaMiner-AI 10: Galapagos', 'Chess 2012', '2012 Chess',
'B.L.O.O.M. 2: Revenge of the Flowers', '__main__']
for name in valid_names:
self.assertIsNone(validate_name(name))
self.assertRaises(ValidationError, validate_name, "..")
self.assertRaises(ValidationError, validate_name, "_..")
self.assertRaises(ValidationError, validate_name, "_")
self.assertRaises(ValidationError, validate_name, "____")
self.assertRaises(ValidationError, validate_name, ".Nope")
self.assertRaises(ValidationError, validate_name, ".Nope")
## Instruction:
Correct unit tests to comply with new team name RE
## Code After:
from django.test import TestCase
from django.template.defaultfilters import slugify
from django.core.exceptions import ValidationError
from competition.validators import greater_than_zero, non_negative, validate_name
class ValidationFunctionTest(TestCase):
def test_greater_than_zero(self):
"""Check greater_than_zero validator"""
self.assertRaises(ValidationError, greater_than_zero, 0)
self.assertRaises(ValidationError, greater_than_zero, -1)
self.assertIsNone(greater_than_zero(1))
def test_non_negative(self):
"""Check non_negative validator"""
self.assertRaises(ValidationError, non_negative, -1)
self.assertIsNone(non_negative(0))
self.assertIsNone(non_negative(1))
def test_validate_name(self):
"""Check name validator"""
# Try some valid names
valid_names = ['MegaMiner-AI 10: Galapagos', 'Chess 2012', '2012 Chess',
'B.L.O.O.M. 2: Revenge of the Flowers']
for name in valid_names:
self.assertIsNone(validate_name(name))
self.assertRaises(ValidationError, validate_name, "..")
self.assertRaises(ValidationError, validate_name, "_..")
self.assertRaises(ValidationError, validate_name, "_")
self.assertRaises(ValidationError, validate_name, "____")
self.assertRaises(ValidationError, validate_name, ".Nope")
self.assertRaises(ValidationError, validate_name, ".Nope")
|
...
"""Check name validator"""
# Try some valid names
valid_names = ['MegaMiner-AI 10: Galapagos', 'Chess 2012', '2012 Chess',
'B.L.O.O.M. 2: Revenge of the Flowers']
for name in valid_names:
self.assertIsNone(validate_name(name))
...
|
14e9742d241339e568c9bf2ff27a6c2c5d176109
|
android/src/xyz/igorgee/imagecreator3d/Model.java
|
android/src/xyz/igorgee/imagecreator3d/Model.java
|
package xyz.igorgee.imagecreator3d;
import java.io.File;
public class Model {
String name;
File location;
String modelID;
public Model(String name, File location) {
this.name = name;
this.location = location;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public File getLocation() {
return location;
}
public void setLocation(File location) {
this.location = location;
}
public String getModelID() {
return modelID;
}
public void setModelID(String modelID) {
this.modelID = modelID;
}
}
|
package xyz.igorgee.imagecreator3d;
import java.io.File;
public class Model {
String name;
File location;
Integer modelID;
public Model(String name, File location) {
this.name = name;
this.location = location;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public File getLocation() {
return location;
}
public void setLocation(File location) {
this.location = location;
}
public Integer getModelID() {
return modelID;
}
public void setModelID(Integer modelID) {
this.modelID = modelID;
}
}
|
Change modelId to type Integer
|
Change modelId to type Integer
|
Java
|
mit
|
IgorGee/Carbonizr,IgorGee/3D-Image-Creator,IgorGee/PendantCreator3D
|
java
|
## Code Before:
package xyz.igorgee.imagecreator3d;
import java.io.File;
public class Model {
String name;
File location;
String modelID;
public Model(String name, File location) {
this.name = name;
this.location = location;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public File getLocation() {
return location;
}
public void setLocation(File location) {
this.location = location;
}
public String getModelID() {
return modelID;
}
public void setModelID(String modelID) {
this.modelID = modelID;
}
}
## Instruction:
Change modelId to type Integer
## Code After:
package xyz.igorgee.imagecreator3d;
import java.io.File;
public class Model {
String name;
File location;
Integer modelID;
public Model(String name, File location) {
this.name = name;
this.location = location;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public File getLocation() {
return location;
}
public void setLocation(File location) {
this.location = location;
}
public Integer getModelID() {
return modelID;
}
public void setModelID(Integer modelID) {
this.modelID = modelID;
}
}
|
# ... existing code ...
public class Model {
String name;
File location;
Integer modelID;
public Model(String name, File location) {
this.name = name;
# ... modified code ...
this.location = location;
}
public Integer getModelID() {
return modelID;
}
public void setModelID(Integer modelID) {
this.modelID = modelID;
}
}
# ... rest of the code ...
|
7c63edcaa0c10682b8d5b10618bb726bb7cc614d
|
app/src/main/java/jasenmoloy/wirelesscontrol/helpers/UIHelper.java
|
app/src/main/java/jasenmoloy/wirelesscontrol/helpers/UIHelper.java
|
package jasenmoloy.wirelesscontrol.helpers;
import android.widget.Button;
/**
* Created by jasenmoloy on 5/20/16.
*/
public class UIHelper {
/**
* Visually and functionally enables a button
* @param button The button to enable
*/
public static void enableButton(Button button) {
button.setAlpha(1.0f);
button.setClickable(true);
}
/**
* Visually and functionally disables a button
* @param button The button to disable
*/
public static void disableButton(Button button) {
button.setAlpha(0.25f); //Make the button transparent to visually show the button is disabled.
button.setClickable(false);
}
}
|
package jasenmoloy.wirelesscontrol.helpers;
import android.content.Context;
import android.widget.Button;
import android.widget.Toast;
/**
* Created by jasenmoloy on 5/20/16.
*/
public class UIHelper {
/**
* Visually and functionally enables a button
* @param button The button to enable
*/
public static void enableButton(Button button) {
button.setAlpha(1.0f);
button.setClickable(true);
}
/**
* Visually and functionally disables a button
* @param button The button to disable
*/
public static void disableButton(Button button) {
button.setAlpha(0.25f); //Make the button transparent to visually show the button is disabled.
button.setClickable(false);
}
public static void displayToast(Context context, int duration, String text) {
Toast.makeText(context, text, duration).show();
}
}
|
Add ability to display toasts
|
Add ability to display toasts
|
Java
|
apache-2.0
|
jasenmoloy/wirelesscontrol
|
java
|
## Code Before:
package jasenmoloy.wirelesscontrol.helpers;
import android.widget.Button;
/**
* Created by jasenmoloy on 5/20/16.
*/
public class UIHelper {
/**
* Visually and functionally enables a button
* @param button The button to enable
*/
public static void enableButton(Button button) {
button.setAlpha(1.0f);
button.setClickable(true);
}
/**
* Visually and functionally disables a button
* @param button The button to disable
*/
public static void disableButton(Button button) {
button.setAlpha(0.25f); //Make the button transparent to visually show the button is disabled.
button.setClickable(false);
}
}
## Instruction:
Add ability to display toasts
## Code After:
package jasenmoloy.wirelesscontrol.helpers;
import android.content.Context;
import android.widget.Button;
import android.widget.Toast;
/**
* Created by jasenmoloy on 5/20/16.
*/
public class UIHelper {
/**
* Visually and functionally enables a button
* @param button The button to enable
*/
public static void enableButton(Button button) {
button.setAlpha(1.0f);
button.setClickable(true);
}
/**
* Visually and functionally disables a button
* @param button The button to disable
*/
public static void disableButton(Button button) {
button.setAlpha(0.25f); //Make the button transparent to visually show the button is disabled.
button.setClickable(false);
}
public static void displayToast(Context context, int duration, String text) {
Toast.makeText(context, text, duration).show();
}
}
|
# ... existing code ...
package jasenmoloy.wirelesscontrol.helpers;
import android.content.Context;
import android.widget.Button;
import android.widget.Toast;
/**
* Created by jasenmoloy on 5/20/16.
# ... modified code ...
button.setAlpha(0.25f); //Make the button transparent to visually show the button is disabled.
button.setClickable(false);
}
public static void displayToast(Context context, int duration, String text) {
Toast.makeText(context, text, duration).show();
}
}
# ... rest of the code ...
|
0af35018fbdf2460d8890a7d7b4ad8246a3d121d
|
IPython/testing/__init__.py
|
IPython/testing/__init__.py
|
#-----------------------------------------------------------------------------
# Copyright (C) 2009-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Functions
#-----------------------------------------------------------------------------
# User-level entry point for testing
def test(all=False):
"""Run the entire IPython test suite.
For fine-grained control, you should use the :file:`iptest` script supplied
with the IPython installation."""
# Do the import internally, so that this function doesn't increase total
# import time
from .iptestcontroller import run_iptestall, default_options
options = default_options()
options.all = all
run_iptestall(options)
# So nose doesn't try to run this as a test itself and we end up with an
# infinite test loop
test.__test__ = False
|
#-----------------------------------------------------------------------------
# Copyright (C) 2009-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Functions
#-----------------------------------------------------------------------------
# User-level entry point for testing
def test(**kwargs):
"""Run the entire IPython test suite.
Any of the options for run_iptestall() may be passed as keyword arguments.
"""
# Do the import internally, so that this function doesn't increase total
# import time
from .iptestcontroller import run_iptestall, default_options
options = default_options()
for name, val in kwargs.items():
setattr(options, name, val)
run_iptestall(options)
# So nose doesn't try to run this as a test itself and we end up with an
# infinite test loop
test.__test__ = False
|
Allow any options to be passed through test function
|
Allow any options to be passed through test function
|
Python
|
bsd-3-clause
|
ipython/ipython,ipython/ipython
|
python
|
## Code Before:
#-----------------------------------------------------------------------------
# Copyright (C) 2009-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Functions
#-----------------------------------------------------------------------------
# User-level entry point for testing
def test(all=False):
"""Run the entire IPython test suite.
For fine-grained control, you should use the :file:`iptest` script supplied
with the IPython installation."""
# Do the import internally, so that this function doesn't increase total
# import time
from .iptestcontroller import run_iptestall, default_options
options = default_options()
options.all = all
run_iptestall(options)
# So nose doesn't try to run this as a test itself and we end up with an
# infinite test loop
test.__test__ = False
## Instruction:
Allow any options to be passed through test function
## Code After:
#-----------------------------------------------------------------------------
# Copyright (C) 2009-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Functions
#-----------------------------------------------------------------------------
# User-level entry point for testing
def test(**kwargs):
"""Run the entire IPython test suite.
Any of the options for run_iptestall() may be passed as keyword arguments.
"""
# Do the import internally, so that this function doesn't increase total
# import time
from .iptestcontroller import run_iptestall, default_options
options = default_options()
for name, val in kwargs.items():
setattr(options, name, val)
run_iptestall(options)
# So nose doesn't try to run this as a test itself and we end up with an
# infinite test loop
test.__test__ = False
|
// ... existing code ...
#-----------------------------------------------------------------------------
# User-level entry point for testing
def test(**kwargs):
"""Run the entire IPython test suite.
Any of the options for run_iptestall() may be passed as keyword arguments.
"""
# Do the import internally, so that this function doesn't increase total
# import time
from .iptestcontroller import run_iptestall, default_options
options = default_options()
for name, val in kwargs.items():
setattr(options, name, val)
run_iptestall(options)
# So nose doesn't try to run this as a test itself and we end up with an
// ... rest of the code ...
|
17266889388c6ae45ac5235a8e22900bf169eba3
|
typhon/__init__.py
|
typhon/__init__.py
|
from .version import __version__
try:
__TYPHON_SETUP__
except:
__TYPHON_SETUP__ = False
if not __TYPHON_SETUP__:
from . import arts
from . import atmosphere
from . import config
from . import constants
from . import files
from . import geodesy
from . import geographical
from . import latex
from . import math
from . import oem
from . import physics
from . import plots
from . import spareice
from . import spectroscopy
from . import trees
from . import utils
from .environment import environ
def test():
"""Use pytest to collect and run all tests in typhon.tests."""
import pytest
return pytest.main(['--pyargs', 'typhon.tests'])
|
from .version import __version__
try:
__TYPHON_SETUP__
except:
__TYPHON_SETUP__ = False
if not __TYPHON_SETUP__:
from . import arts
from . import atmosphere
from . import config
from . import constants
from . import files
from . import geodesy
from . import geographical
from . import latex
from . import math
from . import oem
from . import physics
from . import plots
from . import spectroscopy
from . import trees
from . import utils
from .environment import environ
def test():
"""Use pytest to collect and run all tests in typhon.tests."""
import pytest
return pytest.main(['--pyargs', 'typhon.tests'])
|
Revert "Import spareice per default."
|
Revert "Import spareice per default."
This reverts commit d54042d41b981b3479adb140f2534f76c967fa1c.
|
Python
|
mit
|
atmtools/typhon,atmtools/typhon
|
python
|
## Code Before:
from .version import __version__
try:
__TYPHON_SETUP__
except:
__TYPHON_SETUP__ = False
if not __TYPHON_SETUP__:
from . import arts
from . import atmosphere
from . import config
from . import constants
from . import files
from . import geodesy
from . import geographical
from . import latex
from . import math
from . import oem
from . import physics
from . import plots
from . import spareice
from . import spectroscopy
from . import trees
from . import utils
from .environment import environ
def test():
"""Use pytest to collect and run all tests in typhon.tests."""
import pytest
return pytest.main(['--pyargs', 'typhon.tests'])
## Instruction:
Revert "Import spareice per default."
This reverts commit d54042d41b981b3479adb140f2534f76c967fa1c.
## Code After:
from .version import __version__
try:
__TYPHON_SETUP__
except:
__TYPHON_SETUP__ = False
if not __TYPHON_SETUP__:
from . import arts
from . import atmosphere
from . import config
from . import constants
from . import files
from . import geodesy
from . import geographical
from . import latex
from . import math
from . import oem
from . import physics
from . import plots
from . import spectroscopy
from . import trees
from . import utils
from .environment import environ
def test():
"""Use pytest to collect and run all tests in typhon.tests."""
import pytest
return pytest.main(['--pyargs', 'typhon.tests'])
|
...
from . import oem
from . import physics
from . import plots
from . import spectroscopy
from . import trees
from . import utils
...
|
674826aeab8fa0016eed829110740f9a93247b58
|
fedora/manager/manager.py
|
fedora/manager/manager.py
|
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
import inspect
import requests, json
class FedoraConnectionManager:
__oerUri = ''
__parserTemplates = set()
def __init__(self, uri, templates=[], auto_retrieved=True):
validator = URLValidator(verify_exists=False)
try:
validator(uri)
self.__oerUri = uri
for t in templates:
if 'OERTemplate' == t.__class__.__bases__[0].__name__:
self.__parserTemplates.add(t)
if True == auto_retrieved:
self.retrieve_information()
except ValidationError, e:
pass
"""
To retrieve OER content from assigned URI
"""
def retrieve_information(self):
request_header = {'accept': 'application/ld+json'}
r = requests.get(self.__oerUri, headers=request_header)
json_response = r.json()
""" Start parsing information with assigned template """
for template in self.__parserTemplates:
template.parse(json_response)
self += template
def __add__(self, other):
for key in other.__dict__.keys():
setattr(self, key, other.__dict__[key])
|
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
import inspect
import requests, json
class FedoraConnectionManager:
__oerUri = ''
__parserTemplates = set()
def __init__(self, uri, templates=[], auto_retrieved=True):
validator = URLValidator(verify_exists=False)
try:
validator(uri)
self.__oerUri = uri
for t in templates:
if 'OERTemplate' == t.__class__.__bases__[0].__name__:
self.__parserTemplates.add(t)
if True == auto_retrieved:
self.retrieve_information()
except ValidationError, e:
pass
"""
To retrieve OER content from assigned URI
"""
def retrieve_information(self):
request_header = {'accept': 'application/ld+json'}
r = requests.get(self.__oerUri, headers=request_header)
json_response = r.json()
parsed_data = dict();
""" Start parsing information with assigned template """
for template in self.__parserTemplates:
template.parse(json_response)
for key in template.__dict__.keys():
val = getattr(template, key)
parsed_data[key] = val
return parsed_data
|
Change concatination of parsed data
|
Change concatination of parsed data
|
Python
|
mit
|
sitdh/fedora-parser
|
python
|
## Code Before:
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
import inspect
import requests, json
class FedoraConnectionManager:
__oerUri = ''
__parserTemplates = set()
def __init__(self, uri, templates=[], auto_retrieved=True):
validator = URLValidator(verify_exists=False)
try:
validator(uri)
self.__oerUri = uri
for t in templates:
if 'OERTemplate' == t.__class__.__bases__[0].__name__:
self.__parserTemplates.add(t)
if True == auto_retrieved:
self.retrieve_information()
except ValidationError, e:
pass
"""
To retrieve OER content from assigned URI
"""
def retrieve_information(self):
request_header = {'accept': 'application/ld+json'}
r = requests.get(self.__oerUri, headers=request_header)
json_response = r.json()
""" Start parsing information with assigned template """
for template in self.__parserTemplates:
template.parse(json_response)
self += template
def __add__(self, other):
for key in other.__dict__.keys():
setattr(self, key, other.__dict__[key])
## Instruction:
Change concatination of parsed data
## Code After:
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
import inspect
import requests, json
class FedoraConnectionManager:
__oerUri = ''
__parserTemplates = set()
def __init__(self, uri, templates=[], auto_retrieved=True):
validator = URLValidator(verify_exists=False)
try:
validator(uri)
self.__oerUri = uri
for t in templates:
if 'OERTemplate' == t.__class__.__bases__[0].__name__:
self.__parserTemplates.add(t)
if True == auto_retrieved:
self.retrieve_information()
except ValidationError, e:
pass
"""
To retrieve OER content from assigned URI
"""
def retrieve_information(self):
request_header = {'accept': 'application/ld+json'}
r = requests.get(self.__oerUri, headers=request_header)
json_response = r.json()
parsed_data = dict();
""" Start parsing information with assigned template """
for template in self.__parserTemplates:
template.parse(json_response)
for key in template.__dict__.keys():
val = getattr(template, key)
parsed_data[key] = val
return parsed_data
|
...
class FedoraConnectionManager:
__oerUri = ''
__parserTemplates = set()
def __init__(self, uri, templates=[], auto_retrieved=True):
...
json_response = r.json()
parsed_data = dict();
""" Start parsing information with assigned template """
for template in self.__parserTemplates:
template.parse(json_response)
for key in template.__dict__.keys():
val = getattr(template, key)
parsed_data[key] = val
return parsed_data
...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.