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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
79967811ffdd739bd7a653f4644eec5c4b014625
|
setup.py
|
setup.py
|
"""Setuptools configuration for interfaces."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='asyncdef.interfaces',
version='0.1.0',
url='https://github.com/asyncdef/interfaces',
description='Public APIs for the core asyncdef components.',
author="Kevin Conway",
author_email="[email protected]",
long_description=README,
license='Apache 2.0',
packages=find_packages(exclude=['build', 'dist', 'docs']),
install_requires=[
'iface',
],
extras_require={
'testing': [
'pep257',
'pep8',
'pyenchant',
'pyflakes',
'pylint',
],
},
entry_points={
'console_scripts': [
],
},
include_package_data=True,
zip_safe=False,
)
|
"""Setuptools configuration for interfaces."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='asyncdef.interfaces',
version='0.1.3',
url='https://github.com/asyncdef/interfaces',
description='Public APIs for the core asyncdef components.',
author="Kevin Conway",
author_email="[email protected]",
long_description=README,
license='Apache 2.0',
packages=[
'asyncdef',
'asyncdef.interfaces',
'asyncdef.interfaces.engine',
],
install_requires=[
'iface',
],
extras_require={
'testing': [
'pep257',
'pep8',
'pyenchant',
'pyflakes',
'pylint',
],
},
entry_points={
'console_scripts': [
],
},
include_package_data=True,
zip_safe=False,
)
|
Fix packaging to resolve the PEP420 namespace
|
Fix packaging to resolve the PEP420 namespace
Setuptools is still lacking support for PEP480 namespace packages
when using the find_packages function. Until it does all packages,
including the namespace, must be registered in the packages list.
|
Python
|
apache-2.0
|
asyncdef/interfaces
|
python
|
## Code Before:
"""Setuptools configuration for interfaces."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='asyncdef.interfaces',
version='0.1.0',
url='https://github.com/asyncdef/interfaces',
description='Public APIs for the core asyncdef components.',
author="Kevin Conway",
author_email="[email protected]",
long_description=README,
license='Apache 2.0',
packages=find_packages(exclude=['build', 'dist', 'docs']),
install_requires=[
'iface',
],
extras_require={
'testing': [
'pep257',
'pep8',
'pyenchant',
'pyflakes',
'pylint',
],
},
entry_points={
'console_scripts': [
],
},
include_package_data=True,
zip_safe=False,
)
## Instruction:
Fix packaging to resolve the PEP420 namespace
Setuptools is still lacking support for PEP480 namespace packages
when using the find_packages function. Until it does all packages,
including the namespace, must be registered in the packages list.
## Code After:
"""Setuptools configuration for interfaces."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='asyncdef.interfaces',
version='0.1.3',
url='https://github.com/asyncdef/interfaces',
description='Public APIs for the core asyncdef components.',
author="Kevin Conway",
author_email="[email protected]",
long_description=README,
license='Apache 2.0',
packages=[
'asyncdef',
'asyncdef.interfaces',
'asyncdef.interfaces.engine',
],
install_requires=[
'iface',
],
extras_require={
'testing': [
'pep257',
'pep8',
'pyenchant',
'pyflakes',
'pylint',
],
},
entry_points={
'console_scripts': [
],
},
include_package_data=True,
zip_safe=False,
)
|
// ... existing code ...
setup(
name='asyncdef.interfaces',
version='0.1.3',
url='https://github.com/asyncdef/interfaces',
description='Public APIs for the core asyncdef components.',
author="Kevin Conway",
// ... modified code ...
author_email="[email protected]",
long_description=README,
license='Apache 2.0',
packages=[
'asyncdef',
'asyncdef.interfaces',
'asyncdef.interfaces.engine',
],
install_requires=[
'iface',
],
// ... rest of the code ...
|
3f4ad2faf63432601053d41b988e05f58ebdd129
|
plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/core/model/ProjectSourceFile.java
|
plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/core/model/ProjectSourceFile.java
|
package com.redhat.ceylon.eclipse.core.model;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import com.redhat.ceylon.eclipse.core.typechecker.ProjectPhasedUnit;
import com.redhat.ceylon.eclipse.core.vfs.ResourceVirtualFile;
public class ProjectSourceFile extends SourceFile implements IResourceAware {
public ProjectSourceFile(ProjectPhasedUnit phasedUnit) {
super(phasedUnit);
}
@Override
public ProjectPhasedUnit getPhasedUnit() {
return (ProjectPhasedUnit) super.getPhasedUnit();
}
@Override
public IProject getProjectResource() {
return getPhasedUnit().getProjectResource();
}
@Override
public IFile getFileResource() {
return (IFile)((ResourceVirtualFile) (getPhasedUnit().getUnitFile())).getResource();
}
@Override
public IFolder getRootFolderResource() {
return null;
}
}
|
package com.redhat.ceylon.eclipse.core.model;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import com.redhat.ceylon.eclipse.core.typechecker.ProjectPhasedUnit;
import com.redhat.ceylon.eclipse.core.vfs.ResourceVirtualFile;
public class ProjectSourceFile extends SourceFile implements IResourceAware {
public ProjectSourceFile(ProjectPhasedUnit phasedUnit) {
super(phasedUnit);
}
@Override
public ProjectPhasedUnit getPhasedUnit() {
return (ProjectPhasedUnit) super.getPhasedUnit();
}
@Override
public IProject getProjectResource() {
return getPhasedUnit().getProjectResource();
}
@Override
public IFile getFileResource() {
return getPhasedUnit().getSourceFileResource();
}
@Override
public IFolder getRootFolderResource() {
return getPhasedUnit().getSourceFolderResource();
}
}
|
Correct implementation of the IResourceAware methods
|
Correct implementation of the IResourceAware methods
|
Java
|
epl-1.0
|
rohitmohan96/ceylon-ide-eclipse,rohitmohan96/ceylon-ide-eclipse
|
java
|
## Code Before:
package com.redhat.ceylon.eclipse.core.model;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import com.redhat.ceylon.eclipse.core.typechecker.ProjectPhasedUnit;
import com.redhat.ceylon.eclipse.core.vfs.ResourceVirtualFile;
public class ProjectSourceFile extends SourceFile implements IResourceAware {
public ProjectSourceFile(ProjectPhasedUnit phasedUnit) {
super(phasedUnit);
}
@Override
public ProjectPhasedUnit getPhasedUnit() {
return (ProjectPhasedUnit) super.getPhasedUnit();
}
@Override
public IProject getProjectResource() {
return getPhasedUnit().getProjectResource();
}
@Override
public IFile getFileResource() {
return (IFile)((ResourceVirtualFile) (getPhasedUnit().getUnitFile())).getResource();
}
@Override
public IFolder getRootFolderResource() {
return null;
}
}
## Instruction:
Correct implementation of the IResourceAware methods
## Code After:
package com.redhat.ceylon.eclipse.core.model;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import com.redhat.ceylon.eclipse.core.typechecker.ProjectPhasedUnit;
import com.redhat.ceylon.eclipse.core.vfs.ResourceVirtualFile;
public class ProjectSourceFile extends SourceFile implements IResourceAware {
public ProjectSourceFile(ProjectPhasedUnit phasedUnit) {
super(phasedUnit);
}
@Override
public ProjectPhasedUnit getPhasedUnit() {
return (ProjectPhasedUnit) super.getPhasedUnit();
}
@Override
public IProject getProjectResource() {
return getPhasedUnit().getProjectResource();
}
@Override
public IFile getFileResource() {
return getPhasedUnit().getSourceFileResource();
}
@Override
public IFolder getRootFolderResource() {
return getPhasedUnit().getSourceFolderResource();
}
}
|
// ... existing code ...
@Override
public IFile getFileResource() {
return getPhasedUnit().getSourceFileResource();
}
@Override
public IFolder getRootFolderResource() {
return getPhasedUnit().getSourceFolderResource();
}
}
// ... rest of the code ...
|
c269debb2819db246483551d512c33b784bbfd22
|
test.py
|
test.py
|
print "----- import lua -----"
import lua
print "----- lg = lua.globals() -----"
lg = lua.globals()
print "----- lg.foo = \"bar\" -----"
lg.foo = 'bar'
print "----- lg.tmp = [] -----"
lg.tmp = []
print "----- print lg.tmp -----"
print lg.tmp
print "----- lua.execute(\"xxx = {1,2,3,foo={4,5}}\") -----"
lua.execute("xxx = {1,2,3,foo={4,5}}")
print "----- print lg.xxx[1] -----"
print lg.xxx[1]
print "----- print lg.xxx[2] -----"
print lg.xxx[2]
print "----- print lg.xxx[3] -----"
print lg.xxx[3]
print "----- print lg.xxx['foo'][1] -----"
print lg.xxx['foo'][1]
|
print "----- import lua -----"
import lua
print "----- lg = lua.globals() -----"
lg = lua.globals()
print "lg:", lg
print "lg._G:", lg._G
print "lg['_G']:", lg['_G']
print "----- lg.foo = \"bar\" -----"
lg.foo = 'bar'
print "----- lg.tmp = [] -----"
lg.tmp = []
print "----- print lg.tmp -----"
print lg.tmp
print "----- lua.execute(\"xxx = {1,2,3,foo={4,5}}\") -----"
lua.execute("xxx = {1,2,3,foo={4,5}}")
print "----- print lg.xxx[1] -----"
print lg.xxx[1]
print "----- print lg.xxx[2] -----"
print lg.xxx[2]
print "----- print lg.xxx[3] -----"
print lg.xxx[3]
print "----- print lg.xxx['foo'][1] -----"
print lg.xxx['foo'][1]
print "lua.require =", lua.require
try:
lua.require("foo")
except:
print "lua.require('foo') raised an exception"
|
Test Lua's globals() and require() from Python
|
Test Lua's globals() and require() from Python
|
Python
|
lgpl-2.1
|
albanD/lunatic-python,bastibe/lunatic-python,bastibe/lunatic-python,greatwolf/lunatic-python,alexsilva/lunatic-python,greatwolf/lunatic-python,hughperkins/lunatic-python,alexsilva/lunatic-python,hughperkins/lunatic-python,alexsilva/lunatic-python,albanD/lunatic-python
|
python
|
## Code Before:
print "----- import lua -----"
import lua
print "----- lg = lua.globals() -----"
lg = lua.globals()
print "----- lg.foo = \"bar\" -----"
lg.foo = 'bar'
print "----- lg.tmp = [] -----"
lg.tmp = []
print "----- print lg.tmp -----"
print lg.tmp
print "----- lua.execute(\"xxx = {1,2,3,foo={4,5}}\") -----"
lua.execute("xxx = {1,2,3,foo={4,5}}")
print "----- print lg.xxx[1] -----"
print lg.xxx[1]
print "----- print lg.xxx[2] -----"
print lg.xxx[2]
print "----- print lg.xxx[3] -----"
print lg.xxx[3]
print "----- print lg.xxx['foo'][1] -----"
print lg.xxx['foo'][1]
## Instruction:
Test Lua's globals() and require() from Python
## Code After:
print "----- import lua -----"
import lua
print "----- lg = lua.globals() -----"
lg = lua.globals()
print "lg:", lg
print "lg._G:", lg._G
print "lg['_G']:", lg['_G']
print "----- lg.foo = \"bar\" -----"
lg.foo = 'bar'
print "----- lg.tmp = [] -----"
lg.tmp = []
print "----- print lg.tmp -----"
print lg.tmp
print "----- lua.execute(\"xxx = {1,2,3,foo={4,5}}\") -----"
lua.execute("xxx = {1,2,3,foo={4,5}}")
print "----- print lg.xxx[1] -----"
print lg.xxx[1]
print "----- print lg.xxx[2] -----"
print lg.xxx[2]
print "----- print lg.xxx[3] -----"
print lg.xxx[3]
print "----- print lg.xxx['foo'][1] -----"
print lg.xxx['foo'][1]
print "lua.require =", lua.require
try:
lua.require("foo")
except:
print "lua.require('foo') raised an exception"
|
...
import lua
print "----- lg = lua.globals() -----"
lg = lua.globals()
print "lg:", lg
print "lg._G:", lg._G
print "lg['_G']:", lg['_G']
print "----- lg.foo = \"bar\" -----"
lg.foo = 'bar'
print "----- lg.tmp = [] -----"
...
print lg.xxx[3]
print "----- print lg.xxx['foo'][1] -----"
print lg.xxx['foo'][1]
print "lua.require =", lua.require
try:
lua.require("foo")
except:
print "lua.require('foo') raised an exception"
...
|
1dc2856368e5e6852b526d86a0c78c5fe10b1550
|
myhronet/models.py
|
myhronet/models.py
|
import string
from django.db import models
class Blacklist(models.Model):
domain = models.CharField(max_length=255, unique=True, null=True)
def __unicode__(self):
return self.domain
class URL(models.Model):
hashcode = models.CharField(max_length=10, unique=True,
db_index=True, null=True)
longurl = models.CharField(max_length=1024, unique=True,
db_index=True, null=True)
views = models.IntegerField(default=0)
ip = models.GenericIPAddressField(null=True)
data = models.DateTimeField(auto_now_add=True, null=True)
def save(self, *args, **kwargs):
if URL.objects.count():
last = URL.objects.latest('id').pk + 1
alphabet = string.digits + string.ascii_lowercase
base36 = ''
while last != 0:
last, i = divmod(last, len(alphabet))
base36 = alphabet[i] + base36
self.hashcode = base36
else:
self.hashcode = '1'
return super(URL, self).save(*args, **kwargs)
def short_url(self, request):
return ''.join([
request.scheme,
'://', request.get_host(),
'/', self.hashcode,
])
def __unicode__(self):
return ' - '.join([self.hashcode, self.longurl])
|
import string
from django.db import models
class Blacklist(models.Model):
domain = models.CharField(max_length=255, unique=True, null=True)
def __unicode__(self):
return self.domain
class URL(models.Model):
hashcode = models.CharField(max_length=10, unique=True,
db_index=True, null=True)
longurl = models.CharField(max_length=1024, unique=True,
db_index=True, null=True)
views = models.IntegerField(default=0)
ip = models.GenericIPAddressField(null=True)
data = models.DateTimeField(auto_now_add=True, null=True)
def save(self, *args, **kwargs):
if not self.pk:
if URL.objects.count():
last = URL.objects.latest('id').pk + 1
alphabet = string.digits + string.ascii_lowercase
base36 = ''
while last != 0:
last, i = divmod(last, len(alphabet))
base36 = alphabet[i] + base36
self.hashcode = base36
else:
self.hashcode = '1'
return super(URL, self).save(*args, **kwargs)
def short_url(self, request):
return ''.join([
request.scheme,
'://', request.get_host(),
'/', self.hashcode,
])
def __unicode__(self):
return ' - '.join([self.hashcode, self.longurl])
|
Fix hashcode generation for existing URLs
|
Fix hashcode generation for existing URLs
|
Python
|
mit
|
myhro/myhronet,myhro/myhronet
|
python
|
## Code Before:
import string
from django.db import models
class Blacklist(models.Model):
domain = models.CharField(max_length=255, unique=True, null=True)
def __unicode__(self):
return self.domain
class URL(models.Model):
hashcode = models.CharField(max_length=10, unique=True,
db_index=True, null=True)
longurl = models.CharField(max_length=1024, unique=True,
db_index=True, null=True)
views = models.IntegerField(default=0)
ip = models.GenericIPAddressField(null=True)
data = models.DateTimeField(auto_now_add=True, null=True)
def save(self, *args, **kwargs):
if URL.objects.count():
last = URL.objects.latest('id').pk + 1
alphabet = string.digits + string.ascii_lowercase
base36 = ''
while last != 0:
last, i = divmod(last, len(alphabet))
base36 = alphabet[i] + base36
self.hashcode = base36
else:
self.hashcode = '1'
return super(URL, self).save(*args, **kwargs)
def short_url(self, request):
return ''.join([
request.scheme,
'://', request.get_host(),
'/', self.hashcode,
])
def __unicode__(self):
return ' - '.join([self.hashcode, self.longurl])
## Instruction:
Fix hashcode generation for existing URLs
## Code After:
import string
from django.db import models
class Blacklist(models.Model):
domain = models.CharField(max_length=255, unique=True, null=True)
def __unicode__(self):
return self.domain
class URL(models.Model):
hashcode = models.CharField(max_length=10, unique=True,
db_index=True, null=True)
longurl = models.CharField(max_length=1024, unique=True,
db_index=True, null=True)
views = models.IntegerField(default=0)
ip = models.GenericIPAddressField(null=True)
data = models.DateTimeField(auto_now_add=True, null=True)
def save(self, *args, **kwargs):
if not self.pk:
if URL.objects.count():
last = URL.objects.latest('id').pk + 1
alphabet = string.digits + string.ascii_lowercase
base36 = ''
while last != 0:
last, i = divmod(last, len(alphabet))
base36 = alphabet[i] + base36
self.hashcode = base36
else:
self.hashcode = '1'
return super(URL, self).save(*args, **kwargs)
def short_url(self, request):
return ''.join([
request.scheme,
'://', request.get_host(),
'/', self.hashcode,
])
def __unicode__(self):
return ' - '.join([self.hashcode, self.longurl])
|
# ... existing code ...
data = models.DateTimeField(auto_now_add=True, null=True)
def save(self, *args, **kwargs):
if not self.pk:
if URL.objects.count():
last = URL.objects.latest('id').pk + 1
alphabet = string.digits + string.ascii_lowercase
base36 = ''
while last != 0:
last, i = divmod(last, len(alphabet))
base36 = alphabet[i] + base36
self.hashcode = base36
else:
self.hashcode = '1'
return super(URL, self).save(*args, **kwargs)
def short_url(self, request):
# ... rest of the code ...
|
99f7b0edf2b84658e0a03149eb3e999293aa5e95
|
src/model/train_xgb_model.py
|
src/model/train_xgb_model.py
|
import numpy as np
import pandas as pd
import sys
import os
from sklearn.externals import joblib
import xgboost as xgb
scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../'
sys.path.append(os.path.abspath(scriptpath))
import utils
train = joblib.load(utils.processed_data_path + 'train_is_booking_all_top_5_cw_0.05_year_all.pkl')
X_train = train.ix[:,2:]
y_train = pd.DataFrame(train['hotel_cluster'].astype(int))
print "train XGBClassifier..."
cxgb = xgb.XGBClassifier(max_depth=15, n_estimators=100, learning_rate=0.02, colsample_bytree=0.5, min_child_weight=5, verbose=1)
cxgb.fit(X_train, y_train.ravel())
joblib.dump(cxgb, utils.model_path + 'cxgb_all_without_time_top_5_cw_0.05_year_all.pkl')
|
import numpy as np
import pandas as pd
import sys
import os
from sklearn.externals import joblib
import xgboost as xgb
scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../'
sys.path.append(os.path.abspath(scriptpath))
import utils
train = joblib.load(utils.processed_data_path + 'train_is_booking_all_top_5_cw_0.05_year_all.pkl')
X_train = train.ix[:,2:]
y_train = pd.DataFrame(train['hotel_cluster'].astype(int))
print "train XGBClassifier..."
cxgb = xgb.XGBClassifier(max_depth=15, n_estimators=100, learning_rate=0.02, colsample_bytree=0.5, min_child_weight=5)
cxgb.fit(X_train, y_train.ravel(), verbose=True)
joblib.dump(cxgb, utils.model_path + 'cxgb_all_without_time_top_5_cw_0.05_year_all.pkl')
|
Fix bugs in rf and xgb models
|
Fix bugs in rf and xgb models
|
Python
|
bsd-3-clause
|
parkerzf/kaggle-expedia,parkerzf/kaggle-expedia,parkerzf/kaggle-expedia
|
python
|
## Code Before:
import numpy as np
import pandas as pd
import sys
import os
from sklearn.externals import joblib
import xgboost as xgb
scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../'
sys.path.append(os.path.abspath(scriptpath))
import utils
train = joblib.load(utils.processed_data_path + 'train_is_booking_all_top_5_cw_0.05_year_all.pkl')
X_train = train.ix[:,2:]
y_train = pd.DataFrame(train['hotel_cluster'].astype(int))
print "train XGBClassifier..."
cxgb = xgb.XGBClassifier(max_depth=15, n_estimators=100, learning_rate=0.02, colsample_bytree=0.5, min_child_weight=5, verbose=1)
cxgb.fit(X_train, y_train.ravel())
joblib.dump(cxgb, utils.model_path + 'cxgb_all_without_time_top_5_cw_0.05_year_all.pkl')
## Instruction:
Fix bugs in rf and xgb models
## Code After:
import numpy as np
import pandas as pd
import sys
import os
from sklearn.externals import joblib
import xgboost as xgb
scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../'
sys.path.append(os.path.abspath(scriptpath))
import utils
train = joblib.load(utils.processed_data_path + 'train_is_booking_all_top_5_cw_0.05_year_all.pkl')
X_train = train.ix[:,2:]
y_train = pd.DataFrame(train['hotel_cluster'].astype(int))
print "train XGBClassifier..."
cxgb = xgb.XGBClassifier(max_depth=15, n_estimators=100, learning_rate=0.02, colsample_bytree=0.5, min_child_weight=5)
cxgb.fit(X_train, y_train.ravel(), verbose=True)
joblib.dump(cxgb, utils.model_path + 'cxgb_all_without_time_top_5_cw_0.05_year_all.pkl')
|
# ... existing code ...
print "train XGBClassifier..."
cxgb = xgb.XGBClassifier(max_depth=15, n_estimators=100, learning_rate=0.02, colsample_bytree=0.5, min_child_weight=5)
cxgb.fit(X_train, y_train.ravel(), verbose=True)
joblib.dump(cxgb, utils.model_path + 'cxgb_all_without_time_top_5_cw_0.05_year_all.pkl')
# ... rest of the code ...
|
3588c52060b540f6d3ca791c7309b4e9185a60aa
|
config.py
|
config.py
|
class Config(object):
"""
Base configuration class. Contains one method that defines the database URI.
This class is to be subclassed and its attributes defined therein.
"""
def __init__(self):
self.database_uri()
def database_uri(self):
if self.DIALECT == 'sqlite':
self.DATABASE_URI = r'sqlite://{name}'.format(name=self.DBNAME)
else:
self.DATABASE_URI = r'{dialect}://{user}:{passwd}@{host}:{port}/{name}'.format(
dialect=self.DIALECT, user=self.DBUSER, passwd=self.DBPASSWD,
host=self.HOSTNAME, port=self.PORT, name=self.DBNAME
)
|
class Config(object):
"""
Base configuration class. Contains one property that defines the database URI.
This class is to be subclassed and its attributes defined therein.
"""
@property
def database_uri(self):
return r'sqlite://{name}'.format(name=self.DBNAME) if self.DIALECT == 'sqlite' else \
r'{dialect}://{user}:{passwd}@{host}:{port}/{name}'.format(
dialect=self.DIALECT, user=self.DBUSER, passwd=self.DBPASSWD,
host=self.HOSTNAME, port=self.PORT, name=self.DBNAME
)
|
Replace database_uri method with a property
|
Replace database_uri method with a property
|
Python
|
mit
|
soccermetrics/marcotti-mls
|
python
|
## Code Before:
class Config(object):
"""
Base configuration class. Contains one method that defines the database URI.
This class is to be subclassed and its attributes defined therein.
"""
def __init__(self):
self.database_uri()
def database_uri(self):
if self.DIALECT == 'sqlite':
self.DATABASE_URI = r'sqlite://{name}'.format(name=self.DBNAME)
else:
self.DATABASE_URI = r'{dialect}://{user}:{passwd}@{host}:{port}/{name}'.format(
dialect=self.DIALECT, user=self.DBUSER, passwd=self.DBPASSWD,
host=self.HOSTNAME, port=self.PORT, name=self.DBNAME
)
## Instruction:
Replace database_uri method with a property
## Code After:
class Config(object):
"""
Base configuration class. Contains one property that defines the database URI.
This class is to be subclassed and its attributes defined therein.
"""
@property
def database_uri(self):
return r'sqlite://{name}'.format(name=self.DBNAME) if self.DIALECT == 'sqlite' else \
r'{dialect}://{user}:{passwd}@{host}:{port}/{name}'.format(
dialect=self.DIALECT, user=self.DBUSER, passwd=self.DBPASSWD,
host=self.HOSTNAME, port=self.PORT, name=self.DBNAME
)
|
# ... existing code ...
class Config(object):
"""
Base configuration class. Contains one property that defines the database URI.
This class is to be subclassed and its attributes defined therein.
"""
@property
def database_uri(self):
return r'sqlite://{name}'.format(name=self.DBNAME) if self.DIALECT == 'sqlite' else \
r'{dialect}://{user}:{passwd}@{host}:{port}/{name}'.format(
dialect=self.DIALECT, user=self.DBUSER, passwd=self.DBPASSWD,
host=self.HOSTNAME, port=self.PORT, name=self.DBNAME
)
# ... rest of the code ...
|
681cc70a6305451ea1c85dbd239ea3cd38abe7b3
|
simulator/ghc_instruction.h
|
simulator/ghc_instruction.h
|
enum GHCMnemonic {
MOV,
INC,
DEC,
ADD,
SUB,
MUL,
DIV,
AND,
OR,
XOR,
JLT,
JEQ,
JGT,
INT,
HLT
};
enum GHCRegister {
A = 0,
B,
C,
D,
E,
F,
G,
H,
PC
};
enum GHCArgumentType {
Constant,
Register,
Memory
};
struct GHCArgument {
GHCArgumentType type;
unsigned int id;
};
struct GHCInstruction {
GHCMnemonic mnemonic;
std::vector<GHCArgument> arguments;
};
|
enum GHCMnemonic {
MOV,
INC,
DEC,
ADD,
SUB,
MUL,
DIV,
AND,
OR,
XOR,
JLT,
JEQ,
JGT,
INT,
HLT
};
enum GHCRegister {
A = 0,
B,
C,
D,
E,
F,
G,
H,
PC
};
enum GHCArgumentType {
Constant,
Register,
Memory
};
struct GHCArgument {
GHCArgumentType type;
bool as_address;
unsigned int id;
};
struct GHCInstruction {
GHCMnemonic mnemonic;
std::vector<GHCArgument> arguments;
};
|
Add as_address on mnemonic argument.
|
Add as_address on mnemonic argument.
|
C
|
mit
|
fuqinho/icfpc2014,fuqinho/icfpc2014
|
c
|
## Code Before:
enum GHCMnemonic {
MOV,
INC,
DEC,
ADD,
SUB,
MUL,
DIV,
AND,
OR,
XOR,
JLT,
JEQ,
JGT,
INT,
HLT
};
enum GHCRegister {
A = 0,
B,
C,
D,
E,
F,
G,
H,
PC
};
enum GHCArgumentType {
Constant,
Register,
Memory
};
struct GHCArgument {
GHCArgumentType type;
unsigned int id;
};
struct GHCInstruction {
GHCMnemonic mnemonic;
std::vector<GHCArgument> arguments;
};
## Instruction:
Add as_address on mnemonic argument.
## Code After:
enum GHCMnemonic {
MOV,
INC,
DEC,
ADD,
SUB,
MUL,
DIV,
AND,
OR,
XOR,
JLT,
JEQ,
JGT,
INT,
HLT
};
enum GHCRegister {
A = 0,
B,
C,
D,
E,
F,
G,
H,
PC
};
enum GHCArgumentType {
Constant,
Register,
Memory
};
struct GHCArgument {
GHCArgumentType type;
bool as_address;
unsigned int id;
};
struct GHCInstruction {
GHCMnemonic mnemonic;
std::vector<GHCArgument> arguments;
};
|
// ... existing code ...
struct GHCArgument {
GHCArgumentType type;
bool as_address;
unsigned int id;
};
// ... rest of the code ...
|
e1acfc8a05f1a131dc4b146837e007efa58a2ebf
|
theano/learning_rates.py
|
theano/learning_rates.py
|
""" Classes that simplify learning rate modification. """
import theano
import theano.tensor as TT
class _LearningRate(object):
""" Suplerclass for learning rates. """
def __init__(self, initial_rate):
"""
Args:
initial_rate: Initial value of the learning rate. """
self._rate = initial_rate
def get(self, cycle):
"""
Args:
cycle: The symbolic global step.
Returns:
The learning rate to use for this cycle. """
return self.__rate
class Fixed(_LearningRate):
""" The simplest type of learning rate. It is just a fixed value. """
pass
class ExponentialDecay(_LearningRate):
""" A learning rate that decays exponentially with time. """
def __init__(self, decay_rate, decay_steps, *args, **kwargs):
"""
Args:
decay_rate: Number of steps needed to decay by decay_rate.
decay_steps: The decay rate. """
super(ExponentialDecay, self).__init__(*args, **kwargs)
self.__decay_steps = decay_steps
self.__decay_rate = decay_rate
def get(self, cycle):
rate = self._rate * self.__decay_rate ** (cycle / float(self.__decay_steps))
return TT.cast(rate, theano.config.floatX)
|
""" Classes that simplify learning rate modification. """
import theano
import theano.tensor as TT
class _LearningRate(object):
""" Suplerclass for learning rates. """
def __init__(self, initial_rate):
"""
Args:
initial_rate: Initial value of the learning rate. """
self._rate = initial_rate
def get(self, cycle):
"""
Args:
cycle: The symbolic global step.
Returns:
The learning rate to use for this cycle. """
return TT.as_tensor_variable(self._rate, name="lr")
class Fixed(_LearningRate):
""" The simplest type of learning rate. It is just a fixed value. """
pass
class ExponentialDecay(_LearningRate):
""" A learning rate that decays exponentially with time. """
def __init__(self, decay_rate, decay_steps, *args, **kwargs):
"""
Args:
decay_rate: Number of steps needed to decay by decay_rate.
decay_steps: The decay rate. """
super(ExponentialDecay, self).__init__(*args, **kwargs)
self.__decay_steps = decay_steps
self.__decay_rate = decay_rate
def get(self, cycle):
rate = self._rate * self.__decay_rate ** (cycle / float(self.__decay_steps))
return TT.cast(rate, theano.config.floatX)
|
Make fixed learning rates not crash.
|
Make fixed learning rates not crash.
There was a slight bug in this code before, which I fixed.
|
Python
|
mit
|
djpetti/rpinets,djpetti/rpinets
|
python
|
## Code Before:
""" Classes that simplify learning rate modification. """
import theano
import theano.tensor as TT
class _LearningRate(object):
""" Suplerclass for learning rates. """
def __init__(self, initial_rate):
"""
Args:
initial_rate: Initial value of the learning rate. """
self._rate = initial_rate
def get(self, cycle):
"""
Args:
cycle: The symbolic global step.
Returns:
The learning rate to use for this cycle. """
return self.__rate
class Fixed(_LearningRate):
""" The simplest type of learning rate. It is just a fixed value. """
pass
class ExponentialDecay(_LearningRate):
""" A learning rate that decays exponentially with time. """
def __init__(self, decay_rate, decay_steps, *args, **kwargs):
"""
Args:
decay_rate: Number of steps needed to decay by decay_rate.
decay_steps: The decay rate. """
super(ExponentialDecay, self).__init__(*args, **kwargs)
self.__decay_steps = decay_steps
self.__decay_rate = decay_rate
def get(self, cycle):
rate = self._rate * self.__decay_rate ** (cycle / float(self.__decay_steps))
return TT.cast(rate, theano.config.floatX)
## Instruction:
Make fixed learning rates not crash.
There was a slight bug in this code before, which I fixed.
## Code After:
""" Classes that simplify learning rate modification. """
import theano
import theano.tensor as TT
class _LearningRate(object):
""" Suplerclass for learning rates. """
def __init__(self, initial_rate):
"""
Args:
initial_rate: Initial value of the learning rate. """
self._rate = initial_rate
def get(self, cycle):
"""
Args:
cycle: The symbolic global step.
Returns:
The learning rate to use for this cycle. """
return TT.as_tensor_variable(self._rate, name="lr")
class Fixed(_LearningRate):
""" The simplest type of learning rate. It is just a fixed value. """
pass
class ExponentialDecay(_LearningRate):
""" A learning rate that decays exponentially with time. """
def __init__(self, decay_rate, decay_steps, *args, **kwargs):
"""
Args:
decay_rate: Number of steps needed to decay by decay_rate.
decay_steps: The decay rate. """
super(ExponentialDecay, self).__init__(*args, **kwargs)
self.__decay_steps = decay_steps
self.__decay_rate = decay_rate
def get(self, cycle):
rate = self._rate * self.__decay_rate ** (cycle / float(self.__decay_steps))
return TT.cast(rate, theano.config.floatX)
|
# ... existing code ...
cycle: The symbolic global step.
Returns:
The learning rate to use for this cycle. """
return TT.as_tensor_variable(self._rate, name="lr")
class Fixed(_LearningRate):
""" The simplest type of learning rate. It is just a fixed value. """
# ... rest of the code ...
|
9018093933e7f8d04ad5d7f753651e3c77c0cf12
|
pushbullet.py
|
pushbullet.py
|
import weechat
from yapbl import PushBullet
apikey = ""
p = PushBullet(apikey)
weechat.register("pushbullet", "kekskurse", "1.0", "GPL3", "Test
Skript", "", "")
weechat.prnt("", "Hallo, von einem python Skript!")
def notify_show(data, bufferp, uber_empty, tagsn, isdisplayed,
ishilight, prefix, message):
if(ishilight):
buffer = (weechat.buffer_get_string(bufferp, "short_name") or
weechat.buffer_get_string(bufferp, "name"))
p.push_note('Weechat Hilight', buffer+": "+message)
elif(weechat.buffer_get_string(bufferp, "localvar_type") ==
"private"):
buffer = (weechat.buffer_get_string(bufferp, "short_name") or
weechat.buffer_get_string(bufferp, "name"))
p.push_note('Weechat MSG from '+buffer, buffer+": "+message)
return weechat.WEECHAT_RC_OK
weechat.hook_print("", "irc_privmsg", "", 1, "notify_show", "")
|
import weechat
from yapbl import PushBullet
apikey = ""
p = PushBullet(apikey)
weechat.register("pushbullet", "kekskurse", "1.0", "GPL3", "Test
Skript", "", "")
weechat.prnt("", "Hallo, von einem python Skript!")
def notify_show(data, bufferp, uber_empty, tagsn, isdisplayed,
ishilight, prefix, message):
if(ishilight):
buffer = (weechat.buffer_get_string(bufferp, "short_name") or weechat.buffer_get_string(bufferp, "name"))
p.push_note('Weechat Hilight', buffer+": <"+prefix+"> "+message)
elif(weechat.buffer_get_string(bufferp, "localvar_type") == "private"):
buffer = (weechat.buffer_get_string(bufferp, "short_name") or weechat.buffer_get_string(bufferp, "name"))
p.push_note('Weechat MSG from '+buffer, buffer+": "+message)
return weechat.WEECHAT_RC_OK
weechat.hook_print("", "irc_privmsg", "", 1, "notify_show", "")
|
Fix Nano (m() stuff and add nick name
|
Fix Nano (m() stuff and add nick name
|
Python
|
mit
|
sspssp/weechat-pushbullet
|
python
|
## Code Before:
import weechat
from yapbl import PushBullet
apikey = ""
p = PushBullet(apikey)
weechat.register("pushbullet", "kekskurse", "1.0", "GPL3", "Test
Skript", "", "")
weechat.prnt("", "Hallo, von einem python Skript!")
def notify_show(data, bufferp, uber_empty, tagsn, isdisplayed,
ishilight, prefix, message):
if(ishilight):
buffer = (weechat.buffer_get_string(bufferp, "short_name") or
weechat.buffer_get_string(bufferp, "name"))
p.push_note('Weechat Hilight', buffer+": "+message)
elif(weechat.buffer_get_string(bufferp, "localvar_type") ==
"private"):
buffer = (weechat.buffer_get_string(bufferp, "short_name") or
weechat.buffer_get_string(bufferp, "name"))
p.push_note('Weechat MSG from '+buffer, buffer+": "+message)
return weechat.WEECHAT_RC_OK
weechat.hook_print("", "irc_privmsg", "", 1, "notify_show", "")
## Instruction:
Fix Nano (m() stuff and add nick name
## Code After:
import weechat
from yapbl import PushBullet
apikey = ""
p = PushBullet(apikey)
weechat.register("pushbullet", "kekskurse", "1.0", "GPL3", "Test
Skript", "", "")
weechat.prnt("", "Hallo, von einem python Skript!")
def notify_show(data, bufferp, uber_empty, tagsn, isdisplayed,
ishilight, prefix, message):
if(ishilight):
buffer = (weechat.buffer_get_string(bufferp, "short_name") or weechat.buffer_get_string(bufferp, "name"))
p.push_note('Weechat Hilight', buffer+": <"+prefix+"> "+message)
elif(weechat.buffer_get_string(bufferp, "localvar_type") == "private"):
buffer = (weechat.buffer_get_string(bufferp, "short_name") or weechat.buffer_get_string(bufferp, "name"))
p.push_note('Weechat MSG from '+buffer, buffer+": "+message)
return weechat.WEECHAT_RC_OK
weechat.hook_print("", "irc_privmsg", "", 1, "notify_show", "")
|
# ... existing code ...
def notify_show(data, bufferp, uber_empty, tagsn, isdisplayed,
ishilight, prefix, message):
if(ishilight):
buffer = (weechat.buffer_get_string(bufferp, "short_name") or weechat.buffer_get_string(bufferp, "name"))
p.push_note('Weechat Hilight', buffer+": <"+prefix+"> "+message)
elif(weechat.buffer_get_string(bufferp, "localvar_type") == "private"):
buffer = (weechat.buffer_get_string(bufferp, "short_name") or weechat.buffer_get_string(bufferp, "name"))
p.push_note('Weechat MSG from '+buffer, buffer+": "+message)
return weechat.WEECHAT_RC_OK
# ... rest of the code ...
|
3a57dfd7138be531fa265bea282eb7c62a391ac2
|
bin/debug/load_timeline_for_day_and_user.py
|
bin/debug/load_timeline_for_day_and_user.py
|
import json
import bson.json_util as bju
import emission.core.get_database as edb
import argparse
import emission.core.wrapper.user as ecwu
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("timeline_filename",
help="the name of the file that contains the json representation of the timeline")
parser.add_argument("user_email",
help="specify the user email to load the data as")
parser.add_argument("-r", "--retain", action="store_true",
help="specify whether the entries should overwrite existing ones (default) or create new ones")
parser.add_argument("-v", "--verbose",
help="after how many lines we should print a status message.")
args = parser.parse_args()
fn = args.timeline_filename
print fn
print "Loading file " + fn
tsdb = edb.get_timeseries_db()
user = ecwu.User.register(args.user_email)
override_uuid = user.uuid
print("After registration, %s -> %s" % (args.user_email, override_uuid))
entries = json.load(open(fn), object_hook = bju.object_hook)
for i, entry in enumerate(entries):
entry["user_id"] = override_uuid
if not args.retain:
del entry["_id"]
if args.verbose is not None and i % args.verbose == 0:
print "About to save %s" % entry
tsdb.save(entry)
|
import json
import bson.json_util as bju
import emission.core.get_database as edb
import argparse
import emission.core.wrapper.user as ecwu
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("timeline_filename",
help="the name of the file that contains the json representation of the timeline")
parser.add_argument("user_email",
help="specify the user email to load the data as")
parser.add_argument("-r", "--retain", action="store_true",
help="specify whether the entries should overwrite existing ones (default) or create new ones")
parser.add_argument("-v", "--verbose", type=int,
help="after how many lines we should print a status message.")
args = parser.parse_args()
fn = args.timeline_filename
print fn
print "Loading file " + fn
tsdb = edb.get_timeseries_db()
user = ecwu.User.register(args.user_email)
override_uuid = user.uuid
print("After registration, %s -> %s" % (args.user_email, override_uuid))
entries = json.load(open(fn), object_hook = bju.object_hook)
for i, entry in enumerate(entries):
entry["user_id"] = override_uuid
if not args.retain:
del entry["_id"]
if args.verbose is not None and i % args.verbose == 0:
print "About to save %s" % entry
tsdb.save(entry)
|
Fix the --verbose argument to properly take an int
|
Fix the --verbose argument to properly take an int
Without this, the `i % args.verbose` check would fail since `args.verbose` was
a string
|
Python
|
bsd-3-clause
|
e-mission/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server
|
python
|
## Code Before:
import json
import bson.json_util as bju
import emission.core.get_database as edb
import argparse
import emission.core.wrapper.user as ecwu
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("timeline_filename",
help="the name of the file that contains the json representation of the timeline")
parser.add_argument("user_email",
help="specify the user email to load the data as")
parser.add_argument("-r", "--retain", action="store_true",
help="specify whether the entries should overwrite existing ones (default) or create new ones")
parser.add_argument("-v", "--verbose",
help="after how many lines we should print a status message.")
args = parser.parse_args()
fn = args.timeline_filename
print fn
print "Loading file " + fn
tsdb = edb.get_timeseries_db()
user = ecwu.User.register(args.user_email)
override_uuid = user.uuid
print("After registration, %s -> %s" % (args.user_email, override_uuid))
entries = json.load(open(fn), object_hook = bju.object_hook)
for i, entry in enumerate(entries):
entry["user_id"] = override_uuid
if not args.retain:
del entry["_id"]
if args.verbose is not None and i % args.verbose == 0:
print "About to save %s" % entry
tsdb.save(entry)
## Instruction:
Fix the --verbose argument to properly take an int
Without this, the `i % args.verbose` check would fail since `args.verbose` was
a string
## Code After:
import json
import bson.json_util as bju
import emission.core.get_database as edb
import argparse
import emission.core.wrapper.user as ecwu
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("timeline_filename",
help="the name of the file that contains the json representation of the timeline")
parser.add_argument("user_email",
help="specify the user email to load the data as")
parser.add_argument("-r", "--retain", action="store_true",
help="specify whether the entries should overwrite existing ones (default) or create new ones")
parser.add_argument("-v", "--verbose", type=int,
help="after how many lines we should print a status message.")
args = parser.parse_args()
fn = args.timeline_filename
print fn
print "Loading file " + fn
tsdb = edb.get_timeseries_db()
user = ecwu.User.register(args.user_email)
override_uuid = user.uuid
print("After registration, %s -> %s" % (args.user_email, override_uuid))
entries = json.load(open(fn), object_hook = bju.object_hook)
for i, entry in enumerate(entries):
entry["user_id"] = override_uuid
if not args.retain:
del entry["_id"]
if args.verbose is not None and i % args.verbose == 0:
print "About to save %s" % entry
tsdb.save(entry)
|
# ... existing code ...
parser.add_argument("-r", "--retain", action="store_true",
help="specify whether the entries should overwrite existing ones (default) or create new ones")
parser.add_argument("-v", "--verbose", type=int,
help="after how many lines we should print a status message.")
args = parser.parse_args()
# ... rest of the code ...
|
ff9d613897774f3125f2b28905528962b1761deb
|
core/timeline.py
|
core/timeline.py
|
from collections import Counter
from matplotlib import pyplot as plt
import datetime
def create_timeline( data ):
if len(data) == 0:
print "Dataset empty."
return
dates = map( lambda d: d['date'], data )
timeline_data = Counter( dates )
x_axis = sorted( timeline_data )
y_axis = []
for date in x_axis:
y_axis.append( timeline_data[date] )
plt.plot_date( x = x_axis, y = y_axis, fmt = "r-" )
ymin, ymax = plt.ylim()
plt.ylim( 0, ymax + 1 )
|
from collections import Counter
from matplotlib import pyplot as plt
import datetime
import data_loader
def create_timeline( data ):
if len(data) == 0:
print "Dataset empty."
return
dates = map( lambda d: d['date'], data )
timeline_data = Counter( dates )
x_axis = sorted( timeline_data )
y_axis = []
for date in x_axis:
y_axis.append( timeline_data[date] )
plt.plot_date( x = x_axis, y = y_axis, fmt = "r-" )
ymin, ymax = plt.ylim()
plt.ylim( 0, ymax + 1 )
if __name__ == '__main__':
data = data_loader.load_facebook()
create_timeline(data)
plt.show()
|
Add standalone method for using from command line
|
Add standalone method for using from command line
|
Python
|
mit
|
HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core
|
python
|
## Code Before:
from collections import Counter
from matplotlib import pyplot as plt
import datetime
def create_timeline( data ):
if len(data) == 0:
print "Dataset empty."
return
dates = map( lambda d: d['date'], data )
timeline_data = Counter( dates )
x_axis = sorted( timeline_data )
y_axis = []
for date in x_axis:
y_axis.append( timeline_data[date] )
plt.plot_date( x = x_axis, y = y_axis, fmt = "r-" )
ymin, ymax = plt.ylim()
plt.ylim( 0, ymax + 1 )
## Instruction:
Add standalone method for using from command line
## Code After:
from collections import Counter
from matplotlib import pyplot as plt
import datetime
import data_loader
def create_timeline( data ):
if len(data) == 0:
print "Dataset empty."
return
dates = map( lambda d: d['date'], data )
timeline_data = Counter( dates )
x_axis = sorted( timeline_data )
y_axis = []
for date in x_axis:
y_axis.append( timeline_data[date] )
plt.plot_date( x = x_axis, y = y_axis, fmt = "r-" )
ymin, ymax = plt.ylim()
plt.ylim( 0, ymax + 1 )
if __name__ == '__main__':
data = data_loader.load_facebook()
create_timeline(data)
plt.show()
|
...
from collections import Counter
from matplotlib import pyplot as plt
import datetime
import data_loader
def create_timeline( data ):
if len(data) == 0:
...
plt.plot_date( x = x_axis, y = y_axis, fmt = "r-" )
ymin, ymax = plt.ylim()
plt.ylim( 0, ymax + 1 )
if __name__ == '__main__':
data = data_loader.load_facebook()
create_timeline(data)
plt.show()
...
|
e616438f1ae978210dfcd0e9fc52c9f57ca4afd7
|
PerfTestSharedClasses/src/shared/Constants.java
|
PerfTestSharedClasses/src/shared/Constants.java
|
package shared;
/**
*
*/
/**
*
* @author David Lecoconnier [email protected]
* @author Jean-Luc Amitousa-Mankoy [email protected]
* @version 1.0
*/
public class Constants {
/**
* Socket port for objects transmission
*/
public static int SOCKET_OBJECT_PORT = 2000;
/**
* Socket port for commands transmission
*/
public static int SOCKET_INSTRUCTION_PORT = 2001;
}
|
package shared;
/**
*
*/
/**
*
* @author David Lecoconnier [email protected]
* @author Jean-Luc Amitousa-Mankoy [email protected]
* @version 1.0
*/
public class Constants {
/**
* Socket port for objects transmission
*/
public static int SOCKET_OBJECT_PORT = 2000;
/**
* Socket port for commands transmission
*/
public static int SOCKET_COMMAND_PORT = 2001;
}
|
Change name to improve comprehension
|
Change name to improve comprehension
|
Java
|
apache-2.0
|
etrange02/Perftest
|
java
|
## Code Before:
package shared;
/**
*
*/
/**
*
* @author David Lecoconnier [email protected]
* @author Jean-Luc Amitousa-Mankoy [email protected]
* @version 1.0
*/
public class Constants {
/**
* Socket port for objects transmission
*/
public static int SOCKET_OBJECT_PORT = 2000;
/**
* Socket port for commands transmission
*/
public static int SOCKET_INSTRUCTION_PORT = 2001;
}
## Instruction:
Change name to improve comprehension
## Code After:
package shared;
/**
*
*/
/**
*
* @author David Lecoconnier [email protected]
* @author Jean-Luc Amitousa-Mankoy [email protected]
* @version 1.0
*/
public class Constants {
/**
* Socket port for objects transmission
*/
public static int SOCKET_OBJECT_PORT = 2000;
/**
* Socket port for commands transmission
*/
public static int SOCKET_COMMAND_PORT = 2001;
}
|
# ... existing code ...
/**
* Socket port for commands transmission
*/
public static int SOCKET_COMMAND_PORT = 2001;
}
# ... rest of the code ...
|
4beb18c788dfa988297e6604a51b572692f938da
|
sledge/model/llair_intrinsics.h
|
sledge/model/llair_intrinsics.h
|
/*
* 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.
*/
#include <stdbool.h>
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
/* allocation that cannot fail */
void* __llair_alloc(unsigned size);
/* non-deterministic choice */
int __llair_choice();
/* executions that call __llair_unreachable are assumed to be impossible */
__attribute__((noreturn)) void __llair_unreachable();
/* assume a condition */
#define __llair_assume(condition) \
if (!(condition)) \
__llair_unreachable()
/* throw an exception */
__attribute__((noreturn)) void __llair_throw(void* thrown_exception);
/* glibc version */
#define __assert_fail(assertion, file, line, function) abort()
/* macos version */
#define __assert_rtn(function, file, line, assertion) abort()
/*
* threads
*/
typedef int thread_t;
typedef int (*thread_create_routine)(void*);
thread_t sledge_thread_create(thread_create_routine entry, void* arg);
void sledge_thread_resume(thread_t thread);
int sledge_thread_join(thread_t thread);
/*
* cct
*/
void cct_point(void);
#ifdef __cplusplus
}
#endif
|
/*
* 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.
*/
#include <stdbool.h>
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
/* allocation that cannot fail */
void* __llair_alloc(long size);
/* non-deterministic choice */
long __llair_choice();
/* executions that call __llair_unreachable are assumed to be impossible */
__attribute__((noreturn)) void __llair_unreachable();
/* assume a condition */
#define __llair_assume(condition) \
if (!(condition)) \
__llair_unreachable()
/* throw an exception */
__attribute__((noreturn)) void __llair_throw(void* thrown_exception);
/* glibc version */
#define __assert_fail(assertion, file, line, function) abort()
/* macos version */
#define __assert_rtn(function, file, line, assertion) abort()
/*
* threads
*/
typedef int thread_t;
typedef int (*thread_create_routine)(void*);
thread_t sledge_thread_create(thread_create_routine entry, void* arg);
void sledge_thread_resume(thread_t thread);
int sledge_thread_join(thread_t thread);
/*
* cct
*/
void cct_point(void);
#ifdef __cplusplus
}
#endif
|
Adjust declared types of llair intrinsics
|
[sledge] Adjust declared types of llair intrinsics
Summary:
Internally __llair_alloc and __llair_choice are treated as full-width
signed integers, so use the `long` C type.
Differential Revision: D39136450
fbshipit-source-id: 1ebeff4fe2dcd3cb75d7d13e2798a82c275218a4
|
C
|
mit
|
facebook/infer,facebook/infer,facebook/infer,facebook/infer,facebook/infer,facebook/infer,facebook/infer
|
c
|
## 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.
*/
#include <stdbool.h>
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
/* allocation that cannot fail */
void* __llair_alloc(unsigned size);
/* non-deterministic choice */
int __llair_choice();
/* executions that call __llair_unreachable are assumed to be impossible */
__attribute__((noreturn)) void __llair_unreachable();
/* assume a condition */
#define __llair_assume(condition) \
if (!(condition)) \
__llair_unreachable()
/* throw an exception */
__attribute__((noreturn)) void __llair_throw(void* thrown_exception);
/* glibc version */
#define __assert_fail(assertion, file, line, function) abort()
/* macos version */
#define __assert_rtn(function, file, line, assertion) abort()
/*
* threads
*/
typedef int thread_t;
typedef int (*thread_create_routine)(void*);
thread_t sledge_thread_create(thread_create_routine entry, void* arg);
void sledge_thread_resume(thread_t thread);
int sledge_thread_join(thread_t thread);
/*
* cct
*/
void cct_point(void);
#ifdef __cplusplus
}
#endif
## Instruction:
[sledge] Adjust declared types of llair intrinsics
Summary:
Internally __llair_alloc and __llair_choice are treated as full-width
signed integers, so use the `long` C type.
Differential Revision: D39136450
fbshipit-source-id: 1ebeff4fe2dcd3cb75d7d13e2798a82c275218a4
## 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.
*/
#include <stdbool.h>
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
/* allocation that cannot fail */
void* __llair_alloc(long size);
/* non-deterministic choice */
long __llair_choice();
/* executions that call __llair_unreachable are assumed to be impossible */
__attribute__((noreturn)) void __llair_unreachable();
/* assume a condition */
#define __llair_assume(condition) \
if (!(condition)) \
__llair_unreachable()
/* throw an exception */
__attribute__((noreturn)) void __llair_throw(void* thrown_exception);
/* glibc version */
#define __assert_fail(assertion, file, line, function) abort()
/* macos version */
#define __assert_rtn(function, file, line, assertion) abort()
/*
* threads
*/
typedef int thread_t;
typedef int (*thread_create_routine)(void*);
thread_t sledge_thread_create(thread_create_routine entry, void* arg);
void sledge_thread_resume(thread_t thread);
int sledge_thread_join(thread_t thread);
/*
* cct
*/
void cct_point(void);
#ifdef __cplusplus
}
#endif
|
...
#endif
/* allocation that cannot fail */
void* __llair_alloc(long size);
/* non-deterministic choice */
long __llair_choice();
/* executions that call __llair_unreachable are assumed to be impossible */
__attribute__((noreturn)) void __llair_unreachable();
...
|
a137e8a92211d3d344a38b5c97d81073d66a1668
|
alembic/versions/17c1af634026_extract_publication_date.py
|
alembic/versions/17c1af634026_extract_publication_date.py
|
# revision identifiers, used by Alembic.
revision = '17c1af634026'
down_revision = '3c4c29f0a791'
import html5lib
from dateutil.parser import parse as parse_date
import pytips
from pytips.models import Tip
def _extract_publication_date(html):
root = html5lib.parse(html, treebuilder='lxml', namespaceHTMLElements=False)
publication_date_string = root.xpath("//a/@data-datetime")[0]
return parse_date(publication_date_string)
def _update_tip(tip):
tip.publication_date = _extract_publication_date(tip.rendered_html)
def _erase_publication_date(tip):
tip.publication_date = None
def upgrade():
tips = Tip.query.all()
map(_update_tip, tips)
pytips.db.session.commit()
def downgrade():
tips = Tip.query.all()
map(_erase_publication_date, tips)
pytips.db.session.commit()
|
# revision identifiers, used by Alembic.
revision = '17c1af634026'
down_revision = '3c4c29f0a791'
import html5lib
from dateutil.parser import parse as parse_date
import pytips
from pytips.util import extract_publication_date
from pytips.models import Tip
def _update_tip(tip):
tip.publication_date = extract_publication_date(tip.rendered_html)
def _erase_publication_date(tip):
tip.publication_date = None
def upgrade():
tips = Tip.query.all()
map(_update_tip, tips)
pytips.db.session.commit()
def downgrade():
tips = Tip.query.all()
map(_erase_publication_date, tips)
pytips.db.session.commit()
|
Use the utility module's extract_publication_date logic.
|
Use the utility module's extract_publication_date logic.
|
Python
|
isc
|
gthank/pytips,gthank/pytips,gthank/pytips,gthank/pytips
|
python
|
## Code Before:
# revision identifiers, used by Alembic.
revision = '17c1af634026'
down_revision = '3c4c29f0a791'
import html5lib
from dateutil.parser import parse as parse_date
import pytips
from pytips.models import Tip
def _extract_publication_date(html):
root = html5lib.parse(html, treebuilder='lxml', namespaceHTMLElements=False)
publication_date_string = root.xpath("//a/@data-datetime")[0]
return parse_date(publication_date_string)
def _update_tip(tip):
tip.publication_date = _extract_publication_date(tip.rendered_html)
def _erase_publication_date(tip):
tip.publication_date = None
def upgrade():
tips = Tip.query.all()
map(_update_tip, tips)
pytips.db.session.commit()
def downgrade():
tips = Tip.query.all()
map(_erase_publication_date, tips)
pytips.db.session.commit()
## Instruction:
Use the utility module's extract_publication_date logic.
## Code After:
# revision identifiers, used by Alembic.
revision = '17c1af634026'
down_revision = '3c4c29f0a791'
import html5lib
from dateutil.parser import parse as parse_date
import pytips
from pytips.util import extract_publication_date
from pytips.models import Tip
def _update_tip(tip):
tip.publication_date = extract_publication_date(tip.rendered_html)
def _erase_publication_date(tip):
tip.publication_date = None
def upgrade():
tips = Tip.query.all()
map(_update_tip, tips)
pytips.db.session.commit()
def downgrade():
tips = Tip.query.all()
map(_erase_publication_date, tips)
pytips.db.session.commit()
|
# ... existing code ...
import pytips
from pytips.util import extract_publication_date
from pytips.models import Tip
def _update_tip(tip):
tip.publication_date = extract_publication_date(tip.rendered_html)
def _erase_publication_date(tip):
# ... rest of the code ...
|
a61386cbbcbe3e68bcdf0a98c23547117a496fec
|
zerver/views/webhooks/github_dispatcher.py
|
zerver/views/webhooks/github_dispatcher.py
|
from __future__ import absolute_import
from django.http import HttpRequest, HttpResponse
from .github_webhook import api_github_webhook
from .github import api_github_landing
def api_github_webhook_dispatch(request):
# type: (HttpRequest) -> HttpResponse
if request.META.get('HTTP_X_GITHUB_EVENT'):
return api_github_webhook(request)
else:
return api_github_landing(request)
|
from __future__ import absolute_import
from django.http import HttpRequest, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from .github_webhook import api_github_webhook
from .github import api_github_landing
# Since this dispatcher is an API-style endpoint, it needs to be
# explicitly marked as CSRF-exempt
@csrf_exempt
def api_github_webhook_dispatch(request):
# type: (HttpRequest) -> HttpResponse
if request.META.get('HTTP_X_GITHUB_EVENT'):
return api_github_webhook(request)
else:
return api_github_landing(request)
|
Fix GitHub integration CSRF issue.
|
github: Fix GitHub integration CSRF issue.
The new GitHub dispatcher integration was apparently totally broken,
because we hadn't tagged the new dispatcher endpoint as exempt from
CSRF checking. I'm not sure why the test suite didn't catch this.
|
Python
|
apache-2.0
|
AZtheAsian/zulip,dhcrzf/zulip,JPJPJPOPOP/zulip,christi3k/zulip,hackerkid/zulip,verma-varsha/zulip,j831/zulip,Diptanshu8/zulip,dhcrzf/zulip,ryanbackman/zulip,shubhamdhama/zulip,Galexrt/zulip,hackerkid/zulip,andersk/zulip,amyliu345/zulip,j831/zulip,mahim97/zulip,brainwane/zulip,SmartPeople/zulip,ryanbackman/zulip,Galexrt/zulip,dawran6/zulip,JPJPJPOPOP/zulip,rht/zulip,niftynei/zulip,vaidap/zulip,amanharitsh123/zulip,AZtheAsian/zulip,shubhamdhama/zulip,rht/zulip,kou/zulip,jphilipsen05/zulip,mahim97/zulip,verma-varsha/zulip,isht3/zulip,cosmicAsymmetry/zulip,vabs22/zulip,vabs22/zulip,eeshangarg/zulip,showell/zulip,PhilSk/zulip,timabbott/zulip,rishig/zulip,jrowan/zulip,sharmaeklavya2/zulip,aakash-cr7/zulip,tommyip/zulip,JPJPJPOPOP/zulip,zulip/zulip,ryanbackman/zulip,jackrzhang/zulip,jackrzhang/zulip,rht/zulip,cosmicAsymmetry/zulip,brainwane/zulip,brockwhittaker/zulip,timabbott/zulip,andersk/zulip,christi3k/zulip,rishig/zulip,isht3/zulip,blaze225/zulip,punchagan/zulip,kou/zulip,susansls/zulip,brainwane/zulip,eeshangarg/zulip,jainayush975/zulip,brainwane/zulip,susansls/zulip,vabs22/zulip,vabs22/zulip,verma-varsha/zulip,Diptanshu8/zulip,rht/zulip,punchagan/zulip,jrowan/zulip,sonali0901/zulip,dawran6/zulip,eeshangarg/zulip,showell/zulip,eeshangarg/zulip,tommyip/zulip,JPJPJPOPOP/zulip,shubhamdhama/zulip,showell/zulip,shubhamdhama/zulip,christi3k/zulip,sonali0901/zulip,eeshangarg/zulip,dhcrzf/zulip,isht3/zulip,SmartPeople/zulip,vaidap/zulip,Diptanshu8/zulip,kou/zulip,souravbadami/zulip,hackerkid/zulip,tommyip/zulip,souravbadami/zulip,samatdav/zulip,amyliu345/zulip,brockwhittaker/zulip,amanharitsh123/zulip,ryanbackman/zulip,j831/zulip,SmartPeople/zulip,synicalsyntax/zulip,samatdav/zulip,dawran6/zulip,kou/zulip,andersk/zulip,PhilSk/zulip,vaidap/zulip,AZtheAsian/zulip,jrowan/zulip,zulip/zulip,aakash-cr7/zulip,christi3k/zulip,rishig/zulip,souravbadami/zulip,sharmaeklavya2/zulip,zulip/zulip,Diptanshu8/zulip,dawran6/zulip,jackrzhang/zulip,blaze225/zulip,isht3/zulip,brainwane/zulip,synicalsyntax/zulip,punchagan/zulip,synicalsyntax/zulip,amyliu345/zulip,dhcrzf/zulip,sonali0901/zulip,zulip/zulip,rishig/zulip,synicalsyntax/zulip,hackerkid/zulip,samatdav/zulip,susansls/zulip,hackerkid/zulip,susansls/zulip,brockwhittaker/zulip,susansls/zulip,timabbott/zulip,aakash-cr7/zulip,sharmaeklavya2/zulip,rht/zulip,showell/zulip,isht3/zulip,SmartPeople/zulip,jainayush975/zulip,aakash-cr7/zulip,zulip/zulip,shubhamdhama/zulip,brockwhittaker/zulip,andersk/zulip,jackrzhang/zulip,dattatreya303/zulip,Galexrt/zulip,rht/zulip,zulip/zulip,amanharitsh123/zulip,jackrzhang/zulip,j831/zulip,tommyip/zulip,JPJPJPOPOP/zulip,punchagan/zulip,sharmaeklavya2/zulip,souravbadami/zulip,tommyip/zulip,jphilipsen05/zulip,timabbott/zulip,PhilSk/zulip,niftynei/zulip,samatdav/zulip,dattatreya303/zulip,SmartPeople/zulip,kou/zulip,shubhamdhama/zulip,amanharitsh123/zulip,brainwane/zulip,verma-varsha/zulip,blaze225/zulip,j831/zulip,AZtheAsian/zulip,eeshangarg/zulip,Galexrt/zulip,blaze225/zulip,amyliu345/zulip,verma-varsha/zulip,tommyip/zulip,synicalsyntax/zulip,dawran6/zulip,vaidap/zulip,dhcrzf/zulip,showell/zulip,jphilipsen05/zulip,ryanbackman/zulip,sonali0901/zulip,sonali0901/zulip,aakash-cr7/zulip,brainwane/zulip,andersk/zulip,christi3k/zulip,jainayush975/zulip,AZtheAsian/zulip,j831/zulip,rht/zulip,AZtheAsian/zulip,ryanbackman/zulip,vabs22/zulip,zulip/zulip,shubhamdhama/zulip,kou/zulip,rishig/zulip,mahim97/zulip,hackerkid/zulip,timabbott/zulip,mahim97/zulip,niftynei/zulip,jrowan/zulip,sharmaeklavya2/zulip,souravbadami/zulip,jphilipsen05/zulip,verma-varsha/zulip,jackrzhang/zulip,jackrzhang/zulip,dattatreya303/zulip,rishig/zulip,punchagan/zulip,tommyip/zulip,andersk/zulip,jainayush975/zulip,jphilipsen05/zulip,blaze225/zulip,PhilSk/zulip,Diptanshu8/zulip,Diptanshu8/zulip,amyliu345/zulip,timabbott/zulip,dhcrzf/zulip,cosmicAsymmetry/zulip,amanharitsh123/zulip,cosmicAsymmetry/zulip,rishig/zulip,niftynei/zulip,showell/zulip,isht3/zulip,SmartPeople/zulip,vaidap/zulip,vaidap/zulip,PhilSk/zulip,andersk/zulip,sonali0901/zulip,aakash-cr7/zulip,Galexrt/zulip,jrowan/zulip,susansls/zulip,christi3k/zulip,jainayush975/zulip,niftynei/zulip,amyliu345/zulip,PhilSk/zulip,brockwhittaker/zulip,eeshangarg/zulip,synicalsyntax/zulip,hackerkid/zulip,showell/zulip,dattatreya303/zulip,dawran6/zulip,jainayush975/zulip,mahim97/zulip,cosmicAsymmetry/zulip,punchagan/zulip,synicalsyntax/zulip,souravbadami/zulip,cosmicAsymmetry/zulip,timabbott/zulip,dhcrzf/zulip,dattatreya303/zulip,vabs22/zulip,jrowan/zulip,niftynei/zulip,brockwhittaker/zulip,JPJPJPOPOP/zulip,blaze225/zulip,punchagan/zulip,amanharitsh123/zulip,samatdav/zulip,jphilipsen05/zulip,sharmaeklavya2/zulip,samatdav/zulip,Galexrt/zulip,Galexrt/zulip,mahim97/zulip,dattatreya303/zulip,kou/zulip
|
python
|
## Code Before:
from __future__ import absolute_import
from django.http import HttpRequest, HttpResponse
from .github_webhook import api_github_webhook
from .github import api_github_landing
def api_github_webhook_dispatch(request):
# type: (HttpRequest) -> HttpResponse
if request.META.get('HTTP_X_GITHUB_EVENT'):
return api_github_webhook(request)
else:
return api_github_landing(request)
## Instruction:
github: Fix GitHub integration CSRF issue.
The new GitHub dispatcher integration was apparently totally broken,
because we hadn't tagged the new dispatcher endpoint as exempt from
CSRF checking. I'm not sure why the test suite didn't catch this.
## Code After:
from __future__ import absolute_import
from django.http import HttpRequest, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from .github_webhook import api_github_webhook
from .github import api_github_landing
# Since this dispatcher is an API-style endpoint, it needs to be
# explicitly marked as CSRF-exempt
@csrf_exempt
def api_github_webhook_dispatch(request):
# type: (HttpRequest) -> HttpResponse
if request.META.get('HTTP_X_GITHUB_EVENT'):
return api_github_webhook(request)
else:
return api_github_landing(request)
|
# ... existing code ...
from __future__ import absolute_import
from django.http import HttpRequest, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from .github_webhook import api_github_webhook
from .github import api_github_landing
# Since this dispatcher is an API-style endpoint, it needs to be
# explicitly marked as CSRF-exempt
@csrf_exempt
def api_github_webhook_dispatch(request):
# type: (HttpRequest) -> HttpResponse
if request.META.get('HTTP_X_GITHUB_EVENT'):
# ... rest of the code ...
|
a0ff95bed586084cdbd693a3f71e902c7aafa7f2
|
targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_LPC55S69/TARGET_LPCXpresso/PeripheralPins.c
|
targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_LPC55S69/TARGET_LPCXpresso/PeripheralPins.c
|
/* mbed Microcontroller Library
* Copyright (c) 2006-2013 ARM Limited
*
* 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.
*/
#include "PeripheralPins.h"
#include "PeripheralPinMaps.h"
|
/* mbed Microcontroller Library
* Copyright (c) 2006-2013 ARM Limited
*
* 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.
*/
#include "PeripheralPins.h"
#include "PeripheralPinMaps.h"
// List of GPIOs with limited functionality
const PinList *pinmap_gpio_restricted_pins()
{
static const PinName pins[] = {
A4, // fixed pull-up (for I2C)
A5, // fixed pull-up (for I2C)
D5, // fixed pull-up (for LED)
D3, // fixed pull-up (for LED)
D4, // fixed pull-up (for LED)
D7, // fixed pull-up
D15, // fixed pull-up (for I2C)
D14 // fixed pull-up (for I2C)
};
static const PinList pin_list = {
sizeof(pins) / sizeof(pins[0]),
pins
};
return &pin_list;
}
|
Add restricted GPIO pins for FPGA testing
|
LPC55S69: Add restricted GPIO pins for FPGA testing
|
C
|
apache-2.0
|
kjbracey-arm/mbed,mbedmicro/mbed,kjbracey-arm/mbed,kjbracey-arm/mbed,kjbracey-arm/mbed,mbedmicro/mbed,mbedmicro/mbed,mbedmicro/mbed,mbedmicro/mbed
|
c
|
## Code Before:
/* mbed Microcontroller Library
* Copyright (c) 2006-2013 ARM Limited
*
* 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.
*/
#include "PeripheralPins.h"
#include "PeripheralPinMaps.h"
## Instruction:
LPC55S69: Add restricted GPIO pins for FPGA testing
## Code After:
/* mbed Microcontroller Library
* Copyright (c) 2006-2013 ARM Limited
*
* 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.
*/
#include "PeripheralPins.h"
#include "PeripheralPinMaps.h"
// List of GPIOs with limited functionality
const PinList *pinmap_gpio_restricted_pins()
{
static const PinName pins[] = {
A4, // fixed pull-up (for I2C)
A5, // fixed pull-up (for I2C)
D5, // fixed pull-up (for LED)
D3, // fixed pull-up (for LED)
D4, // fixed pull-up (for LED)
D7, // fixed pull-up
D15, // fixed pull-up (for I2C)
D14 // fixed pull-up (for I2C)
};
static const PinList pin_list = {
sizeof(pins) / sizeof(pins[0]),
pins
};
return &pin_list;
}
|
// ... existing code ...
#include "PeripheralPins.h"
#include "PeripheralPinMaps.h"
// List of GPIOs with limited functionality
const PinList *pinmap_gpio_restricted_pins()
{
static const PinName pins[] = {
A4, // fixed pull-up (for I2C)
A5, // fixed pull-up (for I2C)
D5, // fixed pull-up (for LED)
D3, // fixed pull-up (for LED)
D4, // fixed pull-up (for LED)
D7, // fixed pull-up
D15, // fixed pull-up (for I2C)
D14 // fixed pull-up (for I2C)
};
static const PinList pin_list = {
sizeof(pins) / sizeof(pins[0]),
pins
};
return &pin_list;
}
// ... rest of the code ...
|
7b1a1e030e4cec8dba25b346cba14e256c02f798
|
src/main/java/org/littleshoot/proxy/mitm/HostNameMitmManager.java
|
src/main/java/org/littleshoot/proxy/mitm/HostNameMitmManager.java
|
package org.littleshoot.proxy.mitm;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;
import org.littleshoot.proxy.MitmManager;
/**
* {@link MitmManager} that uses the given host name to create a dynamic
* certificate for. If a port is given, it will be truncated.
*/
public class HostNameMitmManager implements MitmManager {
private BouncyCastleSslEngineSource sslEngineSource;
public HostNameMitmManager() throws RootCertificateException {
this(new Authority());
}
public HostNameMitmManager(Authority authority)
throws RootCertificateException {
try {
sslEngineSource = new BouncyCastleSslEngineSource(authority, true,
true);
} catch (final Exception e) {
throw new RootCertificateException(
"Errors during assembling root CA.", e);
}
}
public SSLEngine serverSslEngine() {
return sslEngineSource.newSslEngine();
}
public SSLEngine clientSslEngineFor(SSLSession serverSslSession,
String serverHostAndPort) {
try {
String serverName = serverHostAndPort.split(":")[0];
SubjectAlternativeNameHolder san = new SubjectAlternativeNameHolder();
return sslEngineSource.createCertForHost(serverName, san);
} catch (Exception e) {
throw new FakeCertificateException(
"Creation dynamic certificate failed for "
+ serverHostAndPort, e);
}
}
}
|
package org.littleshoot.proxy.mitm;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;
import org.littleshoot.proxy.MitmManager;
/**
* {@link MitmManager} that uses the given host name to create a dynamic
* certificate for. If a port is given, it will be truncated.
*/
public class HostNameMitmManager implements MitmManager {
private BouncyCastleSslEngineSource sslEngineSource;
public HostNameMitmManager() throws RootCertificateException {
this(new Authority());
}
public HostNameMitmManager(Authority authority)
throws RootCertificateException {
try {
boolean trustAllServers = false;
boolean sendCerts = true;
sslEngineSource = new BouncyCastleSslEngineSource(authority,
trustAllServers, sendCerts);
} catch (final Exception e) {
throw new RootCertificateException(
"Errors during assembling root CA.", e);
}
}
public SSLEngine serverSslEngine() {
return sslEngineSource.newSslEngine();
}
public SSLEngine clientSslEngineFor(SSLSession serverSslSession,
String serverHostAndPort) {
try {
String serverName = serverHostAndPort.split(":")[0];
SubjectAlternativeNameHolder san = new SubjectAlternativeNameHolder();
return sslEngineSource.createCertForHost(serverName, san);
} catch (Exception e) {
throw new FakeCertificateException(
"Creation dynamic certificate failed for "
+ serverHostAndPort, e);
}
}
}
|
Disable trust all servers by default.
|
Disable trust all servers by default.
|
Java
|
apache-2.0
|
ganskef/LittleProxy-mitm
|
java
|
## Code Before:
package org.littleshoot.proxy.mitm;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;
import org.littleshoot.proxy.MitmManager;
/**
* {@link MitmManager} that uses the given host name to create a dynamic
* certificate for. If a port is given, it will be truncated.
*/
public class HostNameMitmManager implements MitmManager {
private BouncyCastleSslEngineSource sslEngineSource;
public HostNameMitmManager() throws RootCertificateException {
this(new Authority());
}
public HostNameMitmManager(Authority authority)
throws RootCertificateException {
try {
sslEngineSource = new BouncyCastleSslEngineSource(authority, true,
true);
} catch (final Exception e) {
throw new RootCertificateException(
"Errors during assembling root CA.", e);
}
}
public SSLEngine serverSslEngine() {
return sslEngineSource.newSslEngine();
}
public SSLEngine clientSslEngineFor(SSLSession serverSslSession,
String serverHostAndPort) {
try {
String serverName = serverHostAndPort.split(":")[0];
SubjectAlternativeNameHolder san = new SubjectAlternativeNameHolder();
return sslEngineSource.createCertForHost(serverName, san);
} catch (Exception e) {
throw new FakeCertificateException(
"Creation dynamic certificate failed for "
+ serverHostAndPort, e);
}
}
}
## Instruction:
Disable trust all servers by default.
## Code After:
package org.littleshoot.proxy.mitm;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;
import org.littleshoot.proxy.MitmManager;
/**
* {@link MitmManager} that uses the given host name to create a dynamic
* certificate for. If a port is given, it will be truncated.
*/
public class HostNameMitmManager implements MitmManager {
private BouncyCastleSslEngineSource sslEngineSource;
public HostNameMitmManager() throws RootCertificateException {
this(new Authority());
}
public HostNameMitmManager(Authority authority)
throws RootCertificateException {
try {
boolean trustAllServers = false;
boolean sendCerts = true;
sslEngineSource = new BouncyCastleSslEngineSource(authority,
trustAllServers, sendCerts);
} catch (final Exception e) {
throw new RootCertificateException(
"Errors during assembling root CA.", e);
}
}
public SSLEngine serverSslEngine() {
return sslEngineSource.newSslEngine();
}
public SSLEngine clientSslEngineFor(SSLSession serverSslSession,
String serverHostAndPort) {
try {
String serverName = serverHostAndPort.split(":")[0];
SubjectAlternativeNameHolder san = new SubjectAlternativeNameHolder();
return sslEngineSource.createCertForHost(serverName, san);
} catch (Exception e) {
throw new FakeCertificateException(
"Creation dynamic certificate failed for "
+ serverHostAndPort, e);
}
}
}
|
...
public HostNameMitmManager(Authority authority)
throws RootCertificateException {
try {
boolean trustAllServers = false;
boolean sendCerts = true;
sslEngineSource = new BouncyCastleSslEngineSource(authority,
trustAllServers, sendCerts);
} catch (final Exception e) {
throw new RootCertificateException(
"Errors during assembling root CA.", e);
...
|
55d10f77f963eb0cdbe29e04fe910f65c4edaec4
|
erpnext/buying/doctype/supplier/supplier_dashboard.py
|
erpnext/buying/doctype/supplier/supplier_dashboard.py
|
from __future__ import unicode_literals
from frappe import _
def get_data():
return {
'heatmap': True,
'heatmap_message': _('This is based on transactions against this Supplier. See timeline below for details'),
'fieldname': 'supplier',
'non_standard_fieldnames': {
'Payment Entry': 'party_name'
},
'transactions': [
{
'label': _('Procurement'),
'items': ['Request for Quotation', 'Supplier Quotation']
},
{
'label': _('Orders'),
'items': ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']
},
{
'label': _('Payments'),
'items': ['Payment Entry']
},
{
'label': _('Pricing'),
'items': ['Pricing Rule']
}
]
}
|
from __future__ import unicode_literals
from frappe import _
def get_data():
return {
'heatmap': True,
'heatmap_message': _('This is based on transactions against this Supplier. See timeline below for details'),
'fieldname': 'supplier',
'non_standard_fieldnames': {
'Payment Entry': 'party_name',
'Bank Account': 'party'
},
'transactions': [
{
'label': _('Procurement'),
'items': ['Request for Quotation', 'Supplier Quotation']
},
{
'label': _('Orders'),
'items': ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']
},
{
'label': _('Payments'),
'items': ['Payment Entry']
},
{
'label': _('Bank'),
'items': ['Bank Account']
},
{
'label': _('Pricing'),
'items': ['Pricing Rule']
}
]
}
|
Add linked bank accounts to supplier dashboard
|
fix: Add linked bank accounts to supplier dashboard
|
Python
|
agpl-3.0
|
gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext
|
python
|
## Code Before:
from __future__ import unicode_literals
from frappe import _
def get_data():
return {
'heatmap': True,
'heatmap_message': _('This is based on transactions against this Supplier. See timeline below for details'),
'fieldname': 'supplier',
'non_standard_fieldnames': {
'Payment Entry': 'party_name'
},
'transactions': [
{
'label': _('Procurement'),
'items': ['Request for Quotation', 'Supplier Quotation']
},
{
'label': _('Orders'),
'items': ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']
},
{
'label': _('Payments'),
'items': ['Payment Entry']
},
{
'label': _('Pricing'),
'items': ['Pricing Rule']
}
]
}
## Instruction:
fix: Add linked bank accounts to supplier dashboard
## Code After:
from __future__ import unicode_literals
from frappe import _
def get_data():
return {
'heatmap': True,
'heatmap_message': _('This is based on transactions against this Supplier. See timeline below for details'),
'fieldname': 'supplier',
'non_standard_fieldnames': {
'Payment Entry': 'party_name',
'Bank Account': 'party'
},
'transactions': [
{
'label': _('Procurement'),
'items': ['Request for Quotation', 'Supplier Quotation']
},
{
'label': _('Orders'),
'items': ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']
},
{
'label': _('Payments'),
'items': ['Payment Entry']
},
{
'label': _('Bank'),
'items': ['Bank Account']
},
{
'label': _('Pricing'),
'items': ['Pricing Rule']
}
]
}
|
# ... existing code ...
'heatmap_message': _('This is based on transactions against this Supplier. See timeline below for details'),
'fieldname': 'supplier',
'non_standard_fieldnames': {
'Payment Entry': 'party_name',
'Bank Account': 'party'
},
'transactions': [
{
# ... modified code ...
'items': ['Payment Entry']
},
{
'label': _('Bank'),
'items': ['Bank Account']
},
{
'label': _('Pricing'),
'items': ['Pricing Rule']
}
# ... rest of the code ...
|
5da3928442a884c7b5905ca2b17362ca99fffc2c
|
marten/__init__.py
|
marten/__init__.py
|
"""Stupid simple Python configuration management"""
from __future__ import absolute_import
import os as _os
__version__ = '0.5.0'
# Attempt to auto-load a default configuration from files in <cwd>/.marten/ based on the MARTEN_ENV env variable
# MARTEN_ENV defaults to 'default'
config = None
_marten_dir = _os.path.join(_os.getcwd(), '.marten')
_os.environ.setdefault('MARTEN_ENV', 'default')
if _os.path.isdir(_marten_dir):
from .configurations import parse_directory as _parse_directory
config = _parse_directory(_marten_dir, _os.environ['MARTEN_ENV'])
|
"""Stupid simple Python configuration management"""
from __future__ import absolute_import
import os as _os
__version__ = '0.5.1'
# Attempt to auto-load a default configuration from files in <cwd>/.marten/ based on the MARTEN_ENV env variable
# MARTEN_ENV defaults to 'default'
_marten_dir = _os.path.join(_os.getcwd(), '.marten')
_os.environ.setdefault('MARTEN_ENV', 'default')
if _os.path.isdir(_marten_dir):
from .configurations import parse_directory as _parse_directory
config = _parse_directory(_marten_dir, _os.environ['MARTEN_ENV'])
else:
from .configurations import Configuration as _Configuration
config = _Configuration({})
|
Return empty Configuration instance when .marten/ directory is missing
|
Return empty Configuration instance when .marten/ directory is missing
|
Python
|
mit
|
nick-allen/marten
|
python
|
## Code Before:
"""Stupid simple Python configuration management"""
from __future__ import absolute_import
import os as _os
__version__ = '0.5.0'
# Attempt to auto-load a default configuration from files in <cwd>/.marten/ based on the MARTEN_ENV env variable
# MARTEN_ENV defaults to 'default'
config = None
_marten_dir = _os.path.join(_os.getcwd(), '.marten')
_os.environ.setdefault('MARTEN_ENV', 'default')
if _os.path.isdir(_marten_dir):
from .configurations import parse_directory as _parse_directory
config = _parse_directory(_marten_dir, _os.environ['MARTEN_ENV'])
## Instruction:
Return empty Configuration instance when .marten/ directory is missing
## Code After:
"""Stupid simple Python configuration management"""
from __future__ import absolute_import
import os as _os
__version__ = '0.5.1'
# Attempt to auto-load a default configuration from files in <cwd>/.marten/ based on the MARTEN_ENV env variable
# MARTEN_ENV defaults to 'default'
_marten_dir = _os.path.join(_os.getcwd(), '.marten')
_os.environ.setdefault('MARTEN_ENV', 'default')
if _os.path.isdir(_marten_dir):
from .configurations import parse_directory as _parse_directory
config = _parse_directory(_marten_dir, _os.environ['MARTEN_ENV'])
else:
from .configurations import Configuration as _Configuration
config = _Configuration({})
|
// ... existing code ...
import os as _os
__version__ = '0.5.1'
# Attempt to auto-load a default configuration from files in <cwd>/.marten/ based on the MARTEN_ENV env variable
# MARTEN_ENV defaults to 'default'
_marten_dir = _os.path.join(_os.getcwd(), '.marten')
_os.environ.setdefault('MARTEN_ENV', 'default')
// ... modified code ...
if _os.path.isdir(_marten_dir):
from .configurations import parse_directory as _parse_directory
config = _parse_directory(_marten_dir, _os.environ['MARTEN_ENV'])
else:
from .configurations import Configuration as _Configuration
config = _Configuration({})
// ... rest of the code ...
|
4e95e9774f8a234c082349353ffcb44510c14181
|
portability-core/src/test/java/org/dataportabilityproject/job/CrypterImplTest.java
|
portability-core/src/test/java/org/dataportabilityproject/job/CrypterImplTest.java
|
package org.dataportabilityproject.job;
import static com.google.common.truth.Truth.assertThat;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.junit.Test;
public class CrypterImplTest {
@Test
public void testRoundTripSecretKey() throws Exception {
KeyGenerator generator = KeyGenerator.getInstance("AES");
SecretKey key = generator.generateKey();
CrypterImpl impl = new CrypterImpl(key);
String data = "The lazy dog didn't jump over anything";
assertThat(impl.decrypt(impl.encrypt(data))).isEqualTo(data);
}
}
|
package org.dataportabilityproject.job;
import static com.google.common.truth.Truth.assertThat;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.junit.Test;
public class CrypterImplTest {
@Test
public void testRoundTripSecretKey() throws Exception {
KeyGenerator generator = KeyGenerator.getInstance("AES");
SecretKey key = generator.generateKey();
CrypterImpl impl = new CrypterImpl(key);
String data = "The lazy dog didn't jump over anything except \u2614, and a \u26F5";
assertThat(impl.decrypt(impl.encrypt(data))).isEqualTo(data);
}
}
|
Add special charecters to the test as per chuy's request
|
Add special charecters to the test as per chuy's request
|
Java
|
apache-2.0
|
google/data-transfer-project,google/data-transfer-project,google/data-transfer-project,google/data-transfer-project,google/data-transfer-project
|
java
|
## Code Before:
package org.dataportabilityproject.job;
import static com.google.common.truth.Truth.assertThat;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.junit.Test;
public class CrypterImplTest {
@Test
public void testRoundTripSecretKey() throws Exception {
KeyGenerator generator = KeyGenerator.getInstance("AES");
SecretKey key = generator.generateKey();
CrypterImpl impl = new CrypterImpl(key);
String data = "The lazy dog didn't jump over anything";
assertThat(impl.decrypt(impl.encrypt(data))).isEqualTo(data);
}
}
## Instruction:
Add special charecters to the test as per chuy's request
## Code After:
package org.dataportabilityproject.job;
import static com.google.common.truth.Truth.assertThat;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.junit.Test;
public class CrypterImplTest {
@Test
public void testRoundTripSecretKey() throws Exception {
KeyGenerator generator = KeyGenerator.getInstance("AES");
SecretKey key = generator.generateKey();
CrypterImpl impl = new CrypterImpl(key);
String data = "The lazy dog didn't jump over anything except \u2614, and a \u26F5";
assertThat(impl.decrypt(impl.encrypt(data))).isEqualTo(data);
}
}
|
# ... existing code ...
KeyGenerator generator = KeyGenerator.getInstance("AES");
SecretKey key = generator.generateKey();
CrypterImpl impl = new CrypterImpl(key);
String data = "The lazy dog didn't jump over anything except \u2614, and a \u26F5";
assertThat(impl.decrypt(impl.encrypt(data))).isEqualTo(data);
}
}
# ... rest of the code ...
|
581f16e30aeb465f80fd28a77404b0375bd197d4
|
code/python/knub/thesis/topic_model.py
|
code/python/knub/thesis/topic_model.py
|
import logging, gensim, bz2
from knub.thesis.util.memory import limit_memory
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
def main():
logging.info("Starting Wikipedia LDA")
# limit memory to 32 GB
limit_memory(32000)
id2word = gensim.corpora.Dictionary.load_from_text(bz2.BZ2File("/data/wikipedia/2016-06-21/gensim_wordids.txt.bz2"))
mm = gensim.corpora.MmCorpus("/data/wikipedia/2016-06-21/gensim_tfidf.mm")
print mm
lda = gensim.models.ldamodel.LdaModel(corpus=mm, num_topics=100, id2word=id2word, chunksize=10000, passes=1)
# lda = gensim.models.ldamodel.LdaModel(corpus=mm, num_topics=100, id2word=id2word, workers=3)
lda.save("/data/wikipedia/2016-06-21/topics.model")
lda.print_topics()
logging.info("Finished Wikipedia LDA")
if __name__ == "__main__":
main()
|
import logging, gensim, bz2
import mkl
from knub.thesis.util.memory import limit_memory
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
mkl.set_num_threads(8)
def main():
logging.info("Starting Wikipedia LDA")
# limit memory to 32 GB
limit_memory(32000)
id2word = gensim.corpora.Dictionary.load_from_text(bz2.BZ2File("/data/wikipedia/2016-06-21/gensim_wordids.txt.bz2"))
mm = gensim.corpora.MmCorpus("/data/wikipedia/2016-06-21/gensim_tfidf.mm")
print mm
lda = gensim.models.ldamodel.LdaModel(corpus=mm, num_topics=100, id2word=id2word, chunksize=10000, passes=1)
# lda = gensim.models.ldamodel.LdaModel(corpus=mm, num_topics=100, id2word=id2word, workers=3)
lda.save("/data/wikipedia/2016-06-21/topics.model")
lda.print_topics()
logging.info("Finished Wikipedia LDA")
if __name__ == "__main__":
main()
|
Set max threads for MKL.
|
Set max threads for MKL.
|
Python
|
apache-2.0
|
knub/master-thesis,knub/master-thesis,knub/master-thesis,knub/master-thesis
|
python
|
## Code Before:
import logging, gensim, bz2
from knub.thesis.util.memory import limit_memory
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
def main():
logging.info("Starting Wikipedia LDA")
# limit memory to 32 GB
limit_memory(32000)
id2word = gensim.corpora.Dictionary.load_from_text(bz2.BZ2File("/data/wikipedia/2016-06-21/gensim_wordids.txt.bz2"))
mm = gensim.corpora.MmCorpus("/data/wikipedia/2016-06-21/gensim_tfidf.mm")
print mm
lda = gensim.models.ldamodel.LdaModel(corpus=mm, num_topics=100, id2word=id2word, chunksize=10000, passes=1)
# lda = gensim.models.ldamodel.LdaModel(corpus=mm, num_topics=100, id2word=id2word, workers=3)
lda.save("/data/wikipedia/2016-06-21/topics.model")
lda.print_topics()
logging.info("Finished Wikipedia LDA")
if __name__ == "__main__":
main()
## Instruction:
Set max threads for MKL.
## Code After:
import logging, gensim, bz2
import mkl
from knub.thesis.util.memory import limit_memory
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
mkl.set_num_threads(8)
def main():
logging.info("Starting Wikipedia LDA")
# limit memory to 32 GB
limit_memory(32000)
id2word = gensim.corpora.Dictionary.load_from_text(bz2.BZ2File("/data/wikipedia/2016-06-21/gensim_wordids.txt.bz2"))
mm = gensim.corpora.MmCorpus("/data/wikipedia/2016-06-21/gensim_tfidf.mm")
print mm
lda = gensim.models.ldamodel.LdaModel(corpus=mm, num_topics=100, id2word=id2word, chunksize=10000, passes=1)
# lda = gensim.models.ldamodel.LdaModel(corpus=mm, num_topics=100, id2word=id2word, workers=3)
lda.save("/data/wikipedia/2016-06-21/topics.model")
lda.print_topics()
logging.info("Finished Wikipedia LDA")
if __name__ == "__main__":
main()
|
# ... existing code ...
import logging, gensim, bz2
import mkl
from knub.thesis.util.memory import limit_memory
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
mkl.set_num_threads(8)
def main():
logging.info("Starting Wikipedia LDA")
# ... rest of the code ...
|
5fd157d37f532e4aadd51475b9b3654bb42febd9
|
rbtools/clients/tests/test_cvs.py
|
rbtools/clients/tests/test_cvs.py
|
"""Unit tests for CVSClient."""
from __future__ import unicode_literals
import kgb
from rbtools.clients import RepositoryInfo
from rbtools.clients.cvs import CVSClient
from rbtools.clients.tests import SCMClientTestCase
class CVSClientTests(kgb.SpyAgency, SCMClientTestCase):
"""Unit tests for CVSClient."""
def setUp(self):
super(CVSClientTests, self).setUp()
self.client = CVSClient(options=self.options)
def test_get_repository_info_with_found(self):
"""Testing CVSClient.get_repository_info with repository found"""
self.spy_on(CVSClient.get_local_path,
op=kgb.SpyOpReturn('/path/to/cvsdir'))
repository_info = self.client.get_repository_info()
self.assertIsInstance(repository_info, RepositoryInfo)
self.assertIsNone(repository_info.base_path)
self.assertEqual(repository_info.path, '/path/to/cvsdir')
self.assertEqual(repository_info.local_path, '/path/to/cvsdir')
def test_get_repository_info_with_not_found(self):
"""Testing CVSClient.get_repository_info with repository not found"""
self.spy_on(CVSClient.get_local_path,
op=kgb.SpyOpReturn(None))
repository_info = self.client.get_repository_info()
self.assertIsNone(repository_info)
|
"""Unit tests for CVSClient."""
from __future__ import unicode_literals
import kgb
from rbtools.clients import RepositoryInfo
from rbtools.clients.cvs import CVSClient
from rbtools.clients.tests import SCMClientTestCase
class CVSClientTests(kgb.SpyAgency, SCMClientTestCase):
"""Unit tests for CVSClient."""
scmclient_cls = CVSClient
def test_get_repository_info_with_found(self):
"""Testing CVSClient.get_repository_info with repository found"""
client = self.build_client()
self.spy_on(client.get_local_path,
op=kgb.SpyOpReturn('/path/to/cvsdir'))
repository_info = client.get_repository_info()
self.assertIsInstance(repository_info, RepositoryInfo)
self.assertIsNone(repository_info.base_path)
self.assertEqual(repository_info.path, '/path/to/cvsdir')
self.assertEqual(repository_info.local_path, '/path/to/cvsdir')
def test_get_repository_info_with_not_found(self):
"""Testing CVSClient.get_repository_info with repository not found"""
client = self.build_client()
self.spy_on(client.get_local_path,
op=kgb.SpyOpReturn(None))
repository_info = client.get_repository_info()
self.assertIsNone(repository_info)
|
Update the CVS unit tests to use build_client().
|
Update the CVS unit tests to use build_client().
This updates the CVS unit tests to build a `CVSClient` in each test
where it's needed, rather than in `setUp()`. This is in prepration for
new tests that will need to handle client construction differently.
Testing Done:
CVS unit tests pass.
Reviewed at https://reviews.reviewboard.org/r/12504/
|
Python
|
mit
|
reviewboard/rbtools,reviewboard/rbtools,reviewboard/rbtools
|
python
|
## Code Before:
"""Unit tests for CVSClient."""
from __future__ import unicode_literals
import kgb
from rbtools.clients import RepositoryInfo
from rbtools.clients.cvs import CVSClient
from rbtools.clients.tests import SCMClientTestCase
class CVSClientTests(kgb.SpyAgency, SCMClientTestCase):
"""Unit tests for CVSClient."""
def setUp(self):
super(CVSClientTests, self).setUp()
self.client = CVSClient(options=self.options)
def test_get_repository_info_with_found(self):
"""Testing CVSClient.get_repository_info with repository found"""
self.spy_on(CVSClient.get_local_path,
op=kgb.SpyOpReturn('/path/to/cvsdir'))
repository_info = self.client.get_repository_info()
self.assertIsInstance(repository_info, RepositoryInfo)
self.assertIsNone(repository_info.base_path)
self.assertEqual(repository_info.path, '/path/to/cvsdir')
self.assertEqual(repository_info.local_path, '/path/to/cvsdir')
def test_get_repository_info_with_not_found(self):
"""Testing CVSClient.get_repository_info with repository not found"""
self.spy_on(CVSClient.get_local_path,
op=kgb.SpyOpReturn(None))
repository_info = self.client.get_repository_info()
self.assertIsNone(repository_info)
## Instruction:
Update the CVS unit tests to use build_client().
This updates the CVS unit tests to build a `CVSClient` in each test
where it's needed, rather than in `setUp()`. This is in prepration for
new tests that will need to handle client construction differently.
Testing Done:
CVS unit tests pass.
Reviewed at https://reviews.reviewboard.org/r/12504/
## Code After:
"""Unit tests for CVSClient."""
from __future__ import unicode_literals
import kgb
from rbtools.clients import RepositoryInfo
from rbtools.clients.cvs import CVSClient
from rbtools.clients.tests import SCMClientTestCase
class CVSClientTests(kgb.SpyAgency, SCMClientTestCase):
"""Unit tests for CVSClient."""
scmclient_cls = CVSClient
def test_get_repository_info_with_found(self):
"""Testing CVSClient.get_repository_info with repository found"""
client = self.build_client()
self.spy_on(client.get_local_path,
op=kgb.SpyOpReturn('/path/to/cvsdir'))
repository_info = client.get_repository_info()
self.assertIsInstance(repository_info, RepositoryInfo)
self.assertIsNone(repository_info.base_path)
self.assertEqual(repository_info.path, '/path/to/cvsdir')
self.assertEqual(repository_info.local_path, '/path/to/cvsdir')
def test_get_repository_info_with_not_found(self):
"""Testing CVSClient.get_repository_info with repository not found"""
client = self.build_client()
self.spy_on(client.get_local_path,
op=kgb.SpyOpReturn(None))
repository_info = client.get_repository_info()
self.assertIsNone(repository_info)
|
...
class CVSClientTests(kgb.SpyAgency, SCMClientTestCase):
"""Unit tests for CVSClient."""
scmclient_cls = CVSClient
def test_get_repository_info_with_found(self):
"""Testing CVSClient.get_repository_info with repository found"""
client = self.build_client()
self.spy_on(client.get_local_path,
op=kgb.SpyOpReturn('/path/to/cvsdir'))
repository_info = client.get_repository_info()
self.assertIsInstance(repository_info, RepositoryInfo)
self.assertIsNone(repository_info.base_path)
...
def test_get_repository_info_with_not_found(self):
"""Testing CVSClient.get_repository_info with repository not found"""
client = self.build_client()
self.spy_on(client.get_local_path,
op=kgb.SpyOpReturn(None))
repository_info = client.get_repository_info()
self.assertIsNone(repository_info)
...
|
713fcc3f86b4be4d35f0c5ba081a4f786648320a
|
vim/pythonx/elixir_helpers.py
|
vim/pythonx/elixir_helpers.py
|
import re
_DASHES_AND_UNDERSCORES = re.compile("[-_]")
_MODULE_FILEPATH = re.compile(r"lib\/([^\/]+)\/([\w+\/]+)*\/([^\/]+).ex")
def closing_character(tabstop):
"""
Return closing character for a tabstop containing an opening character.
"""
if tabstop.startswith("("):
return ")"
if tabstop.startswith("{"):
return "}"
if tabstop.startswith("["):
return "]"
if tabstop.startswith("\""):
return "\""
return ""
def module_path_match(path, regex=_MODULE_FILEPATH):
"""
Return match data for an Elixir module from a file path.
"""
return re.search(regex, path)
def outer_module_name(path):
"""
Return name for an outer Elixir module from a file path.
"""
outer_module_path = module_path_match(path).group(1)
return to_module_name(outer_module_path)
def to_module_name(string):
"""
Convert string into an Elixir module name
"""
return (
re.sub(_DASHES_AND_UNDERSCORES, " ", string)
.title()
.replace(" ", "")
.replace(".ex", "")
)
|
import re
_DASHES_AND_UNDERSCORES = re.compile("[-_]")
_MODULE_FILEPATH = re.compile(r"lib\/([^\/]+)\/([\w+\/]+)*\/([^\/]+).ex")
_CLOSING_CHARACTERS = {
"(": ")",
"{": "}",
"[": "]",
"\"": "\""
}
def closing_character(tabstop):
"""
Return closing character for a tabstop containing an opening character.
"""
if tabstop:
return _CLOSING_CHARACTERS.get(tabstop[0], "")
return ""
def module_path_match(path, regex=_MODULE_FILEPATH):
"""
Return match data for an Elixir module from a file path.
"""
return re.search(regex, path)
def outer_module_name(path):
"""
Return name for an outer Elixir module from a file path.
"""
outer_module_path = module_path_match(path).group(1)
return to_module_name(outer_module_path)
def to_module_name(string):
"""
Convert string into an Elixir module name
"""
return (
re.sub(_DASHES_AND_UNDERSCORES, " ", string)
.title()
.replace(" ", "")
.replace(".ex", "")
)
|
Refactor python if statement into dictionary
|
Refactor python if statement into dictionary
|
Python
|
mit
|
paulfioravanti/dotfiles,paulfioravanti/dotfiles,paulfioravanti/dotfiles
|
python
|
## Code Before:
import re
_DASHES_AND_UNDERSCORES = re.compile("[-_]")
_MODULE_FILEPATH = re.compile(r"lib\/([^\/]+)\/([\w+\/]+)*\/([^\/]+).ex")
def closing_character(tabstop):
"""
Return closing character for a tabstop containing an opening character.
"""
if tabstop.startswith("("):
return ")"
if tabstop.startswith("{"):
return "}"
if tabstop.startswith("["):
return "]"
if tabstop.startswith("\""):
return "\""
return ""
def module_path_match(path, regex=_MODULE_FILEPATH):
"""
Return match data for an Elixir module from a file path.
"""
return re.search(regex, path)
def outer_module_name(path):
"""
Return name for an outer Elixir module from a file path.
"""
outer_module_path = module_path_match(path).group(1)
return to_module_name(outer_module_path)
def to_module_name(string):
"""
Convert string into an Elixir module name
"""
return (
re.sub(_DASHES_AND_UNDERSCORES, " ", string)
.title()
.replace(" ", "")
.replace(".ex", "")
)
## Instruction:
Refactor python if statement into dictionary
## Code After:
import re
_DASHES_AND_UNDERSCORES = re.compile("[-_]")
_MODULE_FILEPATH = re.compile(r"lib\/([^\/]+)\/([\w+\/]+)*\/([^\/]+).ex")
_CLOSING_CHARACTERS = {
"(": ")",
"{": "}",
"[": "]",
"\"": "\""
}
def closing_character(tabstop):
"""
Return closing character for a tabstop containing an opening character.
"""
if tabstop:
return _CLOSING_CHARACTERS.get(tabstop[0], "")
return ""
def module_path_match(path, regex=_MODULE_FILEPATH):
"""
Return match data for an Elixir module from a file path.
"""
return re.search(regex, path)
def outer_module_name(path):
"""
Return name for an outer Elixir module from a file path.
"""
outer_module_path = module_path_match(path).group(1)
return to_module_name(outer_module_path)
def to_module_name(string):
"""
Convert string into an Elixir module name
"""
return (
re.sub(_DASHES_AND_UNDERSCORES, " ", string)
.title()
.replace(" ", "")
.replace(".ex", "")
)
|
# ... existing code ...
_DASHES_AND_UNDERSCORES = re.compile("[-_]")
_MODULE_FILEPATH = re.compile(r"lib\/([^\/]+)\/([\w+\/]+)*\/([^\/]+).ex")
_CLOSING_CHARACTERS = {
"(": ")",
"{": "}",
"[": "]",
"\"": "\""
}
def closing_character(tabstop):
"""
Return closing character for a tabstop containing an opening character.
"""
if tabstop:
return _CLOSING_CHARACTERS.get(tabstop[0], "")
return ""
def module_path_match(path, regex=_MODULE_FILEPATH):
# ... rest of the code ...
|
9a0cab561ea76a3d54cd410bacbe13a4f5e9f35b
|
server/admin.py
|
server/admin.py
|
from django.contrib import admin
from server.models import *
class MachineGroupAdmin(admin.ModelAdmin):
readonly_fields = ('key',)
class MachineAdmin(admin.ModelAdmin):
list_display = ('hostname', 'serial')
admin.site.register(UserProfile)
admin.site.register(BusinessUnit)
admin.site.register(MachineGroup, MachineGroupAdmin)
admin.site.register(Machine, MachineAdmin)
admin.site.register(Fact)
admin.site.register(PluginScriptSubmission)
admin.site.register(PluginScriptRow)
admin.site.register(HistoricalFact)
admin.site.register(Condition)
admin.site.register(PendingUpdate)
admin.site.register(InstalledUpdate)
admin.site.register(PendingAppleUpdate)
admin.site.register(ApiKey)
admin.site.register(Plugin)
admin.site.register(Report)
# admin.site.register(OSQueryResult)
# admin.site.register(OSQueryColumn)
admin.site.register(SalSetting)
admin.site.register(UpdateHistory)
admin.site.register(UpdateHistoryItem)
admin.site.register(MachineDetailPlugin)
|
from django.contrib import admin
from server.models import *
class ApiKeyAdmin(admin.ModelAdmin):
list_display = ('name', 'public_key', 'private_key')
class MachineAdmin(admin.ModelAdmin):
list_display = ('hostname', 'serial')
class MachineGroupAdmin(admin.ModelAdmin):
readonly_fields = ('key',)
admin.site.register(ApiKey, ApiKeyAdmin)
admin.site.register(BusinessUnit)
admin.site.register(Condition)
admin.site.register(Fact)
admin.site.register(HistoricalFact)
admin.site.register(InstalledUpdate)
admin.site.register(Machine, MachineAdmin)
admin.site.register(MachineDetailPlugin)
admin.site.register(MachineGroup, MachineGroupAdmin)
# admin.site.register(OSQueryColumn)
# admin.site.register(OSQueryResult)
admin.site.register(PendingAppleUpdate)
admin.site.register(PendingUpdate)
admin.site.register(Plugin)
admin.site.register(PluginScriptRow)
admin.site.register(PluginScriptSubmission)
admin.site.register(Report)
admin.site.register(SalSetting)
admin.site.register(UpdateHistory)
admin.site.register(UpdateHistoryItem)
admin.site.register(UserProfile)
|
Sort registrations. Separate classes of imports. Add API key display.
|
Sort registrations. Separate classes of imports. Add API key display.
|
Python
|
apache-2.0
|
salopensource/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,sheagcraig/sal
|
python
|
## Code Before:
from django.contrib import admin
from server.models import *
class MachineGroupAdmin(admin.ModelAdmin):
readonly_fields = ('key',)
class MachineAdmin(admin.ModelAdmin):
list_display = ('hostname', 'serial')
admin.site.register(UserProfile)
admin.site.register(BusinessUnit)
admin.site.register(MachineGroup, MachineGroupAdmin)
admin.site.register(Machine, MachineAdmin)
admin.site.register(Fact)
admin.site.register(PluginScriptSubmission)
admin.site.register(PluginScriptRow)
admin.site.register(HistoricalFact)
admin.site.register(Condition)
admin.site.register(PendingUpdate)
admin.site.register(InstalledUpdate)
admin.site.register(PendingAppleUpdate)
admin.site.register(ApiKey)
admin.site.register(Plugin)
admin.site.register(Report)
# admin.site.register(OSQueryResult)
# admin.site.register(OSQueryColumn)
admin.site.register(SalSetting)
admin.site.register(UpdateHistory)
admin.site.register(UpdateHistoryItem)
admin.site.register(MachineDetailPlugin)
## Instruction:
Sort registrations. Separate classes of imports. Add API key display.
## Code After:
from django.contrib import admin
from server.models import *
class ApiKeyAdmin(admin.ModelAdmin):
list_display = ('name', 'public_key', 'private_key')
class MachineAdmin(admin.ModelAdmin):
list_display = ('hostname', 'serial')
class MachineGroupAdmin(admin.ModelAdmin):
readonly_fields = ('key',)
admin.site.register(ApiKey, ApiKeyAdmin)
admin.site.register(BusinessUnit)
admin.site.register(Condition)
admin.site.register(Fact)
admin.site.register(HistoricalFact)
admin.site.register(InstalledUpdate)
admin.site.register(Machine, MachineAdmin)
admin.site.register(MachineDetailPlugin)
admin.site.register(MachineGroup, MachineGroupAdmin)
# admin.site.register(OSQueryColumn)
# admin.site.register(OSQueryResult)
admin.site.register(PendingAppleUpdate)
admin.site.register(PendingUpdate)
admin.site.register(Plugin)
admin.site.register(PluginScriptRow)
admin.site.register(PluginScriptSubmission)
admin.site.register(Report)
admin.site.register(SalSetting)
admin.site.register(UpdateHistory)
admin.site.register(UpdateHistoryItem)
admin.site.register(UserProfile)
|
// ... existing code ...
from django.contrib import admin
from server.models import *
class ApiKeyAdmin(admin.ModelAdmin):
list_display = ('name', 'public_key', 'private_key')
class MachineAdmin(admin.ModelAdmin):
list_display = ('hostname', 'serial')
class MachineGroupAdmin(admin.ModelAdmin):
// ... modified code ...
readonly_fields = ('key',)
admin.site.register(ApiKey, ApiKeyAdmin)
admin.site.register(BusinessUnit)
admin.site.register(Condition)
admin.site.register(Fact)
admin.site.register(HistoricalFact)
admin.site.register(InstalledUpdate)
admin.site.register(Machine, MachineAdmin)
admin.site.register(MachineDetailPlugin)
admin.site.register(MachineGroup, MachineGroupAdmin)
# admin.site.register(OSQueryColumn)
# admin.site.register(OSQueryResult)
admin.site.register(PendingAppleUpdate)
admin.site.register(PendingUpdate)
admin.site.register(Plugin)
admin.site.register(PluginScriptRow)
admin.site.register(PluginScriptSubmission)
admin.site.register(Report)
admin.site.register(SalSetting)
admin.site.register(UpdateHistory)
admin.site.register(UpdateHistoryItem)
admin.site.register(UserProfile)
// ... rest of the code ...
|
dbd9075781f1f83ec53841c162ea027902c3742a
|
queue.c
|
queue.c
|
struct Queue
{
size_t head;
size_t tail;
size_t size;
void** e;
};
Queue* Queue_Create(size_t n)
{
Queue* q = (Queue *)malloc(sizeof(Queue));
q->size = n;
q->head = q->tail = 1;
q->e = (void **)malloc(sizeof(void*) * (n + 1));
return q;
}
int Queue_Empty(Queue* q)
{
return (q->head == q->tail);
}
|
struct Queue
{
size_t head;
size_t tail;
size_t size;
void** e;
};
Queue* Queue_Create(size_t n)
{
Queue* q = (Queue *)malloc(sizeof(Queue));
q->size = n;
q->head = q->tail = 1;
q->e = (void **)malloc(sizeof(void*) * (n + 1));
return q;
}
int Queue_Empty(Queue* q)
{
return (q->head == q->tail);
}
int Queue_Full(Queue* q)
{
return (q->head == q->tail + 1) || (q->head == 1 && q->tail == q->size);
}
|
Add helper function Queue Full implementation
|
Add helper function Queue Full implementation
|
C
|
mit
|
MaxLikelihood/CADT
|
c
|
## Code Before:
struct Queue
{
size_t head;
size_t tail;
size_t size;
void** e;
};
Queue* Queue_Create(size_t n)
{
Queue* q = (Queue *)malloc(sizeof(Queue));
q->size = n;
q->head = q->tail = 1;
q->e = (void **)malloc(sizeof(void*) * (n + 1));
return q;
}
int Queue_Empty(Queue* q)
{
return (q->head == q->tail);
}
## Instruction:
Add helper function Queue Full implementation
## Code After:
struct Queue
{
size_t head;
size_t tail;
size_t size;
void** e;
};
Queue* Queue_Create(size_t n)
{
Queue* q = (Queue *)malloc(sizeof(Queue));
q->size = n;
q->head = q->tail = 1;
q->e = (void **)malloc(sizeof(void*) * (n + 1));
return q;
}
int Queue_Empty(Queue* q)
{
return (q->head == q->tail);
}
int Queue_Full(Queue* q)
{
return (q->head == q->tail + 1) || (q->head == 1 && q->tail == q->size);
}
|
# ... existing code ...
{
return (q->head == q->tail);
}
int Queue_Full(Queue* q)
{
return (q->head == q->tail + 1) || (q->head == 1 && q->tail == q->size);
}
# ... rest of the code ...
|
91651e30d8a20e8412c2a4f4d448ad8af3e7be95
|
src/main/java/Config/Info.java
|
src/main/java/Config/Info.java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Config;
/**
*
* @author liaoyilin
*/
public class Info {
//Main
public static final String BOT_TOKEN = "Mjk0MzI3Nzg1NTEyNzYzMzky.C7Thog.1_sklRqpnW8ECdjQbwDYzL9Um70";
//Icon
public static String I_info = "https://maxcdn.icons8.com/Share/icon/Very_Basic//info1600.png";
public static String I_help = "https://maxcdn.icons8.com/Share/icon/Programming//help1600.png";
//Bot Info
public static String B_URL = "https://bots.discord.pw/bots/294327785512763392";
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Config;
/**
*
* @author liaoyilin
*/
public class Info {
//Icon
public static String I_info = "https://maxcdn.icons8.com/Share/icon/Very_Basic//info1600.png";
public static String I_help = "https://maxcdn.icons8.com/Share/icon/Programming//help1600.png";
//Bot Info
public static String B_URL = "https://bots.discord.pw/bots/294327785512763392";
}
|
Make bot token private :p
|
Make bot token private :p
|
Java
|
mit
|
AlienIdeology/AIBot
|
java
|
## Code Before:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Config;
/**
*
* @author liaoyilin
*/
public class Info {
//Main
public static final String BOT_TOKEN = "Mjk0MzI3Nzg1NTEyNzYzMzky.C7Thog.1_sklRqpnW8ECdjQbwDYzL9Um70";
//Icon
public static String I_info = "https://maxcdn.icons8.com/Share/icon/Very_Basic//info1600.png";
public static String I_help = "https://maxcdn.icons8.com/Share/icon/Programming//help1600.png";
//Bot Info
public static String B_URL = "https://bots.discord.pw/bots/294327785512763392";
}
## Instruction:
Make bot token private :p
## Code After:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Config;
/**
*
* @author liaoyilin
*/
public class Info {
//Icon
public static String I_info = "https://maxcdn.icons8.com/Share/icon/Very_Basic//info1600.png";
public static String I_help = "https://maxcdn.icons8.com/Share/icon/Programming//help1600.png";
//Bot Info
public static String B_URL = "https://bots.discord.pw/bots/294327785512763392";
}
|
# ... existing code ...
* @author liaoyilin
*/
public class Info {
//Icon
public static String I_info = "https://maxcdn.icons8.com/Share/icon/Very_Basic//info1600.png";
public static String I_help = "https://maxcdn.icons8.com/Share/icon/Programming//help1600.png";
# ... rest of the code ...
|
c4903f5b631bba21e17be1b7deb118c0c9571432
|
Lab3/PalindromeExercise.py
|
Lab3/PalindromeExercise.py
|
normStr = raw_input("Enter the word:\n").lower();
# Inverts the string so it can compare it with the original input.
invertStr = normStr[::-1];
|
normStr = raw_input("Enter the word:\n").lower();
# Inverts the string so it can compare it with the original input.
invertStr = normStr[::-1];
# Tests if the string is a palindrome. If so, it prints True. Else, prints False.
if normStr == invertStr:
print 'True';
else:
print 'False';
|
Test added. Program should be complete.
|
Test added. Program should be complete.
|
Python
|
mit
|
lgomie/dt228-3B-cloud-repo
|
python
|
## Code Before:
normStr = raw_input("Enter the word:\n").lower();
# Inverts the string so it can compare it with the original input.
invertStr = normStr[::-1];
## Instruction:
Test added. Program should be complete.
## Code After:
normStr = raw_input("Enter the word:\n").lower();
# Inverts the string so it can compare it with the original input.
invertStr = normStr[::-1];
# Tests if the string is a palindrome. If so, it prints True. Else, prints False.
if normStr == invertStr:
print 'True';
else:
print 'False';
|
# ... existing code ...
# Inverts the string so it can compare it with the original input.
invertStr = normStr[::-1];
# Tests if the string is a palindrome. If so, it prints True. Else, prints False.
if normStr == invertStr:
print 'True';
else:
print 'False';
# ... rest of the code ...
|
fc7ba9019b42f056713b81bfee70f9e780b4aab5
|
models/rasmachine/twitter_client.py
|
models/rasmachine/twitter_client.py
|
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import tweepy
def get_oauth(auth_file):
try:
fh = open(auth_file, 'rt')
except IOError:
print('Could not get Twitter credentials.')
return None
lines = [l.strip() for l in fh.readlines()]
oauth = tweepy.OAuthHandler(lines[0], lines[1])
oauth.set_access_token(lines[2], lines[3])
fh.close()
return oauth
def update_status(msg, auth_file='twitter_cred.txt'):
twitter_auth = get_oauth(auth_file)
if twitter_auth is None:
return
twitter_api = tweepy.API(twitter_auth)
twitter_api.update_status(msg)
|
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import tweepy
def get_oauth_file(auth_file):
try:
fh = open(auth_file, 'rt')
except IOError:
print('Could not get Twitter credentials.')
return None
lines = [l.strip() for l in fh.readlines()]
oauth = tweepy.OAuthHandler(lines[0], lines[1])
oauth.set_access_token(lines[2], lines[3])
fh.close()
return oauth
def get_oauth_dict(auth_dict):
oauth = tweepy.OAuthHandler(auth_dict.get('consumer_token'),
auth_dict.get('consumer_secred'))
oauth.set_access_token(auth_dict.get('access_token'),
auth_dict.get('access_secret'))
return oauth
def update_status(msg, twitter_cred):
twitter_auth = get_oauth_dict(twitter_cred)
if twitter_auth is None:
return
twitter_api = tweepy.API(twitter_auth)
twitter_api.update_status(msg)
|
Implement dict credentials in Twitter client
|
Implement dict credentials in Twitter client
|
Python
|
bsd-2-clause
|
pvtodorov/indra,johnbachman/belpy,jmuhlich/indra,jmuhlich/indra,bgyori/indra,johnbachman/belpy,pvtodorov/indra,sorgerlab/belpy,johnbachman/belpy,pvtodorov/indra,johnbachman/indra,bgyori/indra,pvtodorov/indra,johnbachman/indra,sorgerlab/belpy,johnbachman/indra,sorgerlab/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/indra,jmuhlich/indra,sorgerlab/indra
|
python
|
## Code Before:
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import tweepy
def get_oauth(auth_file):
try:
fh = open(auth_file, 'rt')
except IOError:
print('Could not get Twitter credentials.')
return None
lines = [l.strip() for l in fh.readlines()]
oauth = tweepy.OAuthHandler(lines[0], lines[1])
oauth.set_access_token(lines[2], lines[3])
fh.close()
return oauth
def update_status(msg, auth_file='twitter_cred.txt'):
twitter_auth = get_oauth(auth_file)
if twitter_auth is None:
return
twitter_api = tweepy.API(twitter_auth)
twitter_api.update_status(msg)
## Instruction:
Implement dict credentials in Twitter client
## Code After:
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import tweepy
def get_oauth_file(auth_file):
try:
fh = open(auth_file, 'rt')
except IOError:
print('Could not get Twitter credentials.')
return None
lines = [l.strip() for l in fh.readlines()]
oauth = tweepy.OAuthHandler(lines[0], lines[1])
oauth.set_access_token(lines[2], lines[3])
fh.close()
return oauth
def get_oauth_dict(auth_dict):
oauth = tweepy.OAuthHandler(auth_dict.get('consumer_token'),
auth_dict.get('consumer_secred'))
oauth.set_access_token(auth_dict.get('access_token'),
auth_dict.get('access_secret'))
return oauth
def update_status(msg, twitter_cred):
twitter_auth = get_oauth_dict(twitter_cred)
if twitter_auth is None:
return
twitter_api = tweepy.API(twitter_auth)
twitter_api.update_status(msg)
|
# ... existing code ...
from builtins import dict, str
import tweepy
def get_oauth_file(auth_file):
try:
fh = open(auth_file, 'rt')
except IOError:
# ... modified code ...
fh.close()
return oauth
def get_oauth_dict(auth_dict):
oauth = tweepy.OAuthHandler(auth_dict.get('consumer_token'),
auth_dict.get('consumer_secred'))
oauth.set_access_token(auth_dict.get('access_token'),
auth_dict.get('access_secret'))
return oauth
def update_status(msg, twitter_cred):
twitter_auth = get_oauth_dict(twitter_cred)
if twitter_auth is None:
return
twitter_api = tweepy.API(twitter_auth)
# ... rest of the code ...
|
634f718aa4fe4052a8dc9be1f82078ebcd2338df
|
build-release.py
|
build-release.py
|
import sys
import glob
import re
NEW_VERSION = sys.argv[1]
with open('VERSION') as f:
VERSION=f.read()
print NEW_VERSION
print VERSION
def set_assemblyinfo_version(version):
aLineRe = "AssemblyVersion|AssemblyFileVersion\(\"([\.0-9]+)\"\)"
aVersionRe = "(\d\.\d\.\d)"
print "Changing version numbers in AssemblyInfo.cs files"
for name in glob.glob("./*/Properties/AssemblyInfo.cs"):
print "Working on " + name
new_file = []
with open(name) as f:
for line in f.readlines():
if line.startswith("//") != True:
reProg = re.compile(aLineRe)
result = reProg.search(line)
if (result != None):
line = re.sub(aVersionRe, NEW_VERSION, line)
new_file.append(line)
with open(name, "w") as f:
f.write("".join(new_file))
def set_version_file(version):
print "Working on VERSION file"
with open("VERSION", "w") as f:
f.write(version)
set_verion_file(NEW_VERSION)
set_assemblyinfo_version(NEW_VERSION)
|
import sys
import glob
import re
NEW_VERSION = sys.argv[1]
with open('VERSION') as f:
VERSION=f.read()
print NEW_VERSION
print VERSION
def set_assemblyinfo_version(version):
aLineRe = "AssemblyVersion|AssemblyFileVersion\(\"([\.0-9]+)\"\)"
aVersionRe = "(\d\.\d\.\d)"
print "Changing version numbers in AssemblyInfo.cs files"
for name in glob.glob("./*/Properties/AssemblyInfo.cs"):
print "Working on " + name
new_file = []
with open(name) as f:
for line in f.readlines():
if line.startswith("//") != True:
reProg = re.compile(aLineRe)
result = reProg.search(line)
if (result != None):
line = re.sub(aVersionRe, NEW_VERSION, line)
new_file.append(line)
with open(name, "w") as f:
f.write("".join(new_file))
set_assemblyinfo_version(NEW_VERSION)
|
Revert "working on version file"
|
Revert "working on version file"
This reverts commit cb159cd3d907aeaa65f6a293d95a0aa7d7f2fee8.
|
Python
|
mit
|
psistats/windows-client,psistats/windows-client,psistats/windows-client
|
python
|
## Code Before:
import sys
import glob
import re
NEW_VERSION = sys.argv[1]
with open('VERSION') as f:
VERSION=f.read()
print NEW_VERSION
print VERSION
def set_assemblyinfo_version(version):
aLineRe = "AssemblyVersion|AssemblyFileVersion\(\"([\.0-9]+)\"\)"
aVersionRe = "(\d\.\d\.\d)"
print "Changing version numbers in AssemblyInfo.cs files"
for name in glob.glob("./*/Properties/AssemblyInfo.cs"):
print "Working on " + name
new_file = []
with open(name) as f:
for line in f.readlines():
if line.startswith("//") != True:
reProg = re.compile(aLineRe)
result = reProg.search(line)
if (result != None):
line = re.sub(aVersionRe, NEW_VERSION, line)
new_file.append(line)
with open(name, "w") as f:
f.write("".join(new_file))
def set_version_file(version):
print "Working on VERSION file"
with open("VERSION", "w") as f:
f.write(version)
set_verion_file(NEW_VERSION)
set_assemblyinfo_version(NEW_VERSION)
## Instruction:
Revert "working on version file"
This reverts commit cb159cd3d907aeaa65f6a293d95a0aa7d7f2fee8.
## Code After:
import sys
import glob
import re
NEW_VERSION = sys.argv[1]
with open('VERSION') as f:
VERSION=f.read()
print NEW_VERSION
print VERSION
def set_assemblyinfo_version(version):
aLineRe = "AssemblyVersion|AssemblyFileVersion\(\"([\.0-9]+)\"\)"
aVersionRe = "(\d\.\d\.\d)"
print "Changing version numbers in AssemblyInfo.cs files"
for name in glob.glob("./*/Properties/AssemblyInfo.cs"):
print "Working on " + name
new_file = []
with open(name) as f:
for line in f.readlines():
if line.startswith("//") != True:
reProg = re.compile(aLineRe)
result = reProg.search(line)
if (result != None):
line = re.sub(aVersionRe, NEW_VERSION, line)
new_file.append(line)
with open(name, "w") as f:
f.write("".join(new_file))
set_assemblyinfo_version(NEW_VERSION)
|
# ... existing code ...
with open(name, "w") as f:
f.write("".join(new_file))
set_assemblyinfo_version(NEW_VERSION)
# ... rest of the code ...
|
e6d3d60265db1947b8af2d1c59c575c632ddc20b
|
linter.py
|
linter.py
|
"""This module exports the Stylelint plugin class."""
import os
from SublimeLinter.lint import Linter, util
class Stylelint(Linter):
"""Provides an interface to stylelint."""
syntax = ('css', 'css3', 'sass', 'scss', 'postcss')
cmd = ('node', os.path.dirname(os.path.realpath(__file__)) + '/stylelint_wrapper.js', '@')
error_stream = util.STREAM_BOTH
config_file = ('--config', '.stylelintrc', '~')
tempfile_suffix = 'css'
regex = (
r'^\s*(?P<line>[0-9]+)\:(?P<col>[0-9]+)\s*(?P<message>.+)'
)
|
"""This module exports the Stylelint plugin class."""
import os
from SublimeLinter.lint import Linter, util
class Stylelint(Linter):
"""Provides an interface to stylelint."""
syntax = ('css', 'css3', 'sass', 'scss', 'postcss')
cmd = ('node', os.path.dirname(os.path.realpath(__file__)) + '/stylelint_wrapper.js', '@')
error_stream = util.STREAM_BOTH
config_file = ('--config', '.stylelintrc', '~')
tempfile_suffix = 'css'
regex = (
r'^\s*(?P<line>[0-9]+)\:(?P<col>[0-9]+)\s*(?:(?P<error>✖)|(?P<warning>⚠))\s*(?P<message>.+)'
)
|
Add support for handling errors and warnings
|
Add support for handling errors and warnings
|
Python
|
mit
|
lzwme/SublimeLinter-contrib-stylelint,lzwme/SublimeLinter-contrib-stylelint,kungfusheep/SublimeLinter-contrib-stylelint
|
python
|
## Code Before:
"""This module exports the Stylelint plugin class."""
import os
from SublimeLinter.lint import Linter, util
class Stylelint(Linter):
"""Provides an interface to stylelint."""
syntax = ('css', 'css3', 'sass', 'scss', 'postcss')
cmd = ('node', os.path.dirname(os.path.realpath(__file__)) + '/stylelint_wrapper.js', '@')
error_stream = util.STREAM_BOTH
config_file = ('--config', '.stylelintrc', '~')
tempfile_suffix = 'css'
regex = (
r'^\s*(?P<line>[0-9]+)\:(?P<col>[0-9]+)\s*(?P<message>.+)'
)
## Instruction:
Add support for handling errors and warnings
## Code After:
"""This module exports the Stylelint plugin class."""
import os
from SublimeLinter.lint import Linter, util
class Stylelint(Linter):
"""Provides an interface to stylelint."""
syntax = ('css', 'css3', 'sass', 'scss', 'postcss')
cmd = ('node', os.path.dirname(os.path.realpath(__file__)) + '/stylelint_wrapper.js', '@')
error_stream = util.STREAM_BOTH
config_file = ('--config', '.stylelintrc', '~')
tempfile_suffix = 'css'
regex = (
r'^\s*(?P<line>[0-9]+)\:(?P<col>[0-9]+)\s*(?:(?P<error>✖)|(?P<warning>⚠))\s*(?P<message>.+)'
)
|
...
config_file = ('--config', '.stylelintrc', '~')
tempfile_suffix = 'css'
regex = (
r'^\s*(?P<line>[0-9]+)\:(?P<col>[0-9]+)\s*(?:(?P<error>✖)|(?P<warning>⚠))\s*(?P<message>.+)'
)
...
|
842a64a60c275072a487ae221b49b4c0fac41907
|
RuM_Workspace/src/ee/ut/cs/rum/workspaces/internal/ui/task/newtask/dialog/NewTaskDialogShell.java
|
RuM_Workspace/src/ee/ut/cs/rum/workspaces/internal/ui/task/newtask/dialog/NewTaskDialogShell.java
|
package ee.ut.cs.rum.workspaces.internal.ui.task.newtask.dialog;
import org.eclipse.swt.widgets.Shell;
import ee.ut.cs.rum.plugins.interfaces.factory.RumPluginConfiguration;
public class NewTaskDialogShell extends Shell {
private static final long serialVersionUID = -4970825745896119968L;
NewTaskDialog newTaskDialog;
private RumPluginConfiguration rumPluginConfiguration;
public NewTaskDialogShell(Shell parent, int style, NewTaskDialog newTaskDialog) {
super(parent, style);
this.newTaskDialog=newTaskDialog;
}
public RumPluginConfiguration getRumPluginConfiguration() {
return rumPluginConfiguration;
}
public void setRumPluginConfiguration(RumPluginConfiguration rumPluginConfiguration) {
this.rumPluginConfiguration = rumPluginConfiguration;
}
public NewTaskDialog getNewTaskDialog() {
return newTaskDialog;
}
}
|
package ee.ut.cs.rum.workspaces.internal.ui.task.newtask.dialog;
import org.eclipse.swt.widgets.Shell;
import ee.ut.cs.rum.plugins.interfaces.factory.RumPluginConfiguration;
public class NewTaskDialogShell extends Shell {
private static final long serialVersionUID = -4970825745896119968L;
NewTaskDialog newTaskDialog;
private RumPluginConfiguration rumPluginConfiguration;
public NewTaskDialogShell(Shell parent, int style, NewTaskDialog newTaskDialog) {
super(parent, style);
this.newTaskDialog=newTaskDialog;
}
public RumPluginConfiguration getRumPluginConfiguration() {
return rumPluginConfiguration;
}
public void setRumPluginConfiguration(RumPluginConfiguration rumPluginConfiguration) {
this.pack();
this.rumPluginConfiguration = rumPluginConfiguration;
}
public NewTaskDialog getNewTaskDialog() {
return newTaskDialog;
}
}
|
Update new task dialog size after selecting a plugin
|
Update new task dialog size after selecting a plugin
|
Java
|
agpl-3.0
|
FableBlaze/RuM,FableBlaze/RuM
|
java
|
## Code Before:
package ee.ut.cs.rum.workspaces.internal.ui.task.newtask.dialog;
import org.eclipse.swt.widgets.Shell;
import ee.ut.cs.rum.plugins.interfaces.factory.RumPluginConfiguration;
public class NewTaskDialogShell extends Shell {
private static final long serialVersionUID = -4970825745896119968L;
NewTaskDialog newTaskDialog;
private RumPluginConfiguration rumPluginConfiguration;
public NewTaskDialogShell(Shell parent, int style, NewTaskDialog newTaskDialog) {
super(parent, style);
this.newTaskDialog=newTaskDialog;
}
public RumPluginConfiguration getRumPluginConfiguration() {
return rumPluginConfiguration;
}
public void setRumPluginConfiguration(RumPluginConfiguration rumPluginConfiguration) {
this.rumPluginConfiguration = rumPluginConfiguration;
}
public NewTaskDialog getNewTaskDialog() {
return newTaskDialog;
}
}
## Instruction:
Update new task dialog size after selecting a plugin
## Code After:
package ee.ut.cs.rum.workspaces.internal.ui.task.newtask.dialog;
import org.eclipse.swt.widgets.Shell;
import ee.ut.cs.rum.plugins.interfaces.factory.RumPluginConfiguration;
public class NewTaskDialogShell extends Shell {
private static final long serialVersionUID = -4970825745896119968L;
NewTaskDialog newTaskDialog;
private RumPluginConfiguration rumPluginConfiguration;
public NewTaskDialogShell(Shell parent, int style, NewTaskDialog newTaskDialog) {
super(parent, style);
this.newTaskDialog=newTaskDialog;
}
public RumPluginConfiguration getRumPluginConfiguration() {
return rumPluginConfiguration;
}
public void setRumPluginConfiguration(RumPluginConfiguration rumPluginConfiguration) {
this.pack();
this.rumPluginConfiguration = rumPluginConfiguration;
}
public NewTaskDialog getNewTaskDialog() {
return newTaskDialog;
}
}
|
# ... existing code ...
}
public void setRumPluginConfiguration(RumPluginConfiguration rumPluginConfiguration) {
this.pack();
this.rumPluginConfiguration = rumPluginConfiguration;
}
# ... rest of the code ...
|
6f50381e2e14ab7c1c90e52479ffcfc7748329b3
|
UI/resources/constants.py
|
UI/resources/constants.py
|
SAVE_PASSWORD_HASHED = True
MAX_RETRIES_DOWNLOAD_FROM_SAME_FARMER = 3
MAX_RETRIES_UPLOAD_TO_SAME_FARMER = 3
MAX_RETRIES_NEGOTIATE_CONTRACT = 10
MAX_RETRIES_GET_FILE_POINTERS = 10
FILE_POINTERS_REQUEST_DELAY = 1
# int: file pointers request delay, in seconds.
MAX_DOWNLOAD_REQUEST_BLOCK_SIZE = 32 * 1024
MAX_UPLOAD_REQUEST_BLOCK_SIZE = 4096
MAX_UPLOAD_CONNECTIONS_AT_SAME_TIME = 4
MAX_DOWNLOAD_CONNECTIONS_AT_SAME_TIME = 4
DEFAULT_MAX_BRIDGE_REQUEST_TIMEOUT = 5
# int: maximum bridge request timeout, in seconds.
DEFAULT_BRIDGE_API_URL = 'api.storj.io'
|
SAVE_PASSWORD_HASHED = True
MAX_RETRIES_DOWNLOAD_FROM_SAME_FARMER = 3
MAX_RETRIES_UPLOAD_TO_SAME_FARMER = 3
MAX_RETRIES_NEGOTIATE_CONTRACT = 10
MAX_RETRIES_GET_FILE_POINTERS = 10
FILE_POINTERS_REQUEST_DELAY = 1
# int: file pointers request delay, in seconds.
MAX_DOWNLOAD_REQUEST_BLOCK_SIZE = 32 * 1024
MAX_UPLOAD_REQUEST_BLOCK_SIZE = 4096
MAX_UPLOAD_CONNECTIONS_AT_SAME_TIME = 4
MAX_DOWNLOAD_CONNECTIONS_AT_SAME_TIME = 4
DEFAULT_MAX_BRIDGE_REQUEST_TIMEOUT = 5
DEFAULT_MAX_FARMER_CONNECTION_TIMEOUT = 7
# int: maximum bridge request timeout, in seconds.
DEFAULT_BRIDGE_API_URL = 'api.storj.io'
|
Add farmer max timeout constant
|
Add farmer max timeout constant
|
Python
|
mit
|
lakewik/storj-gui-client
|
python
|
## Code Before:
SAVE_PASSWORD_HASHED = True
MAX_RETRIES_DOWNLOAD_FROM_SAME_FARMER = 3
MAX_RETRIES_UPLOAD_TO_SAME_FARMER = 3
MAX_RETRIES_NEGOTIATE_CONTRACT = 10
MAX_RETRIES_GET_FILE_POINTERS = 10
FILE_POINTERS_REQUEST_DELAY = 1
# int: file pointers request delay, in seconds.
MAX_DOWNLOAD_REQUEST_BLOCK_SIZE = 32 * 1024
MAX_UPLOAD_REQUEST_BLOCK_SIZE = 4096
MAX_UPLOAD_CONNECTIONS_AT_SAME_TIME = 4
MAX_DOWNLOAD_CONNECTIONS_AT_SAME_TIME = 4
DEFAULT_MAX_BRIDGE_REQUEST_TIMEOUT = 5
# int: maximum bridge request timeout, in seconds.
DEFAULT_BRIDGE_API_URL = 'api.storj.io'
## Instruction:
Add farmer max timeout constant
## Code After:
SAVE_PASSWORD_HASHED = True
MAX_RETRIES_DOWNLOAD_FROM_SAME_FARMER = 3
MAX_RETRIES_UPLOAD_TO_SAME_FARMER = 3
MAX_RETRIES_NEGOTIATE_CONTRACT = 10
MAX_RETRIES_GET_FILE_POINTERS = 10
FILE_POINTERS_REQUEST_DELAY = 1
# int: file pointers request delay, in seconds.
MAX_DOWNLOAD_REQUEST_BLOCK_SIZE = 32 * 1024
MAX_UPLOAD_REQUEST_BLOCK_SIZE = 4096
MAX_UPLOAD_CONNECTIONS_AT_SAME_TIME = 4
MAX_DOWNLOAD_CONNECTIONS_AT_SAME_TIME = 4
DEFAULT_MAX_BRIDGE_REQUEST_TIMEOUT = 5
DEFAULT_MAX_FARMER_CONNECTION_TIMEOUT = 7
# int: maximum bridge request timeout, in seconds.
DEFAULT_BRIDGE_API_URL = 'api.storj.io'
|
// ... existing code ...
MAX_DOWNLOAD_CONNECTIONS_AT_SAME_TIME = 4
DEFAULT_MAX_BRIDGE_REQUEST_TIMEOUT = 5
DEFAULT_MAX_FARMER_CONNECTION_TIMEOUT = 7
# int: maximum bridge request timeout, in seconds.
DEFAULT_BRIDGE_API_URL = 'api.storj.io'
// ... rest of the code ...
|
e791a65932b9c83365a0fa5148d685131867b729
|
subprojects/core/src/main/java/org/gradle/internal/fingerprint/GenericFileTreeSnapshotter.java
|
subprojects/core/src/main/java/org/gradle/internal/fingerprint/GenericFileTreeSnapshotter.java
|
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.internal.fingerprint;
import org.gradle.api.file.FileVisitor;
import org.gradle.api.internal.file.FileTreeInternal;
import org.gradle.internal.snapshot.FileSystemSnapshot;
/**
* A snapshotter for generic file trees, which are not based on a directory on disk.
*
* This is needed to build a Merkle directory tree from the elements of a file tree obtained by {@link org.gradle.api.file.FileTree#visit(FileVisitor)}.
*/
public interface GenericFileTreeSnapshotter {
FileSystemSnapshot snapshotFileTree(FileTreeInternal tree);
}
|
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.internal.fingerprint;
import org.gradle.api.file.FileVisitor;
import org.gradle.api.internal.file.FileTreeInternal;
import org.gradle.internal.snapshot.FileSystemSnapshot;
/**
* A snapshotter for generic file trees, which are not based on a directory on disk.
*
* Examples of a generic file tree is a {@link org.gradle.api.internal.file.archive.TarFileTree} backed by a non-file resource.
* This is needed to build a Merkle directory tree from the elements of a file tree obtained by {@link org.gradle.api.file.FileTree#visit(FileVisitor)}.
*/
public interface GenericFileTreeSnapshotter {
FileSystemSnapshot snapshotFileTree(FileTreeInternal tree);
}
|
Add example for generic file tree to Javadoc
|
Add example for generic file tree to Javadoc
`SingletonFileTree`s aren't generic file trees.
|
Java
|
apache-2.0
|
blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle
|
java
|
## Code Before:
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.internal.fingerprint;
import org.gradle.api.file.FileVisitor;
import org.gradle.api.internal.file.FileTreeInternal;
import org.gradle.internal.snapshot.FileSystemSnapshot;
/**
* A snapshotter for generic file trees, which are not based on a directory on disk.
*
* This is needed to build a Merkle directory tree from the elements of a file tree obtained by {@link org.gradle.api.file.FileTree#visit(FileVisitor)}.
*/
public interface GenericFileTreeSnapshotter {
FileSystemSnapshot snapshotFileTree(FileTreeInternal tree);
}
## Instruction:
Add example for generic file tree to Javadoc
`SingletonFileTree`s aren't generic file trees.
## Code After:
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.internal.fingerprint;
import org.gradle.api.file.FileVisitor;
import org.gradle.api.internal.file.FileTreeInternal;
import org.gradle.internal.snapshot.FileSystemSnapshot;
/**
* A snapshotter for generic file trees, which are not based on a directory on disk.
*
* Examples of a generic file tree is a {@link org.gradle.api.internal.file.archive.TarFileTree} backed by a non-file resource.
* This is needed to build a Merkle directory tree from the elements of a file tree obtained by {@link org.gradle.api.file.FileTree#visit(FileVisitor)}.
*/
public interface GenericFileTreeSnapshotter {
FileSystemSnapshot snapshotFileTree(FileTreeInternal tree);
}
|
// ... existing code ...
/**
* A snapshotter for generic file trees, which are not based on a directory on disk.
*
* Examples of a generic file tree is a {@link org.gradle.api.internal.file.archive.TarFileTree} backed by a non-file resource.
* This is needed to build a Merkle directory tree from the elements of a file tree obtained by {@link org.gradle.api.file.FileTree#visit(FileVisitor)}.
*/
public interface GenericFileTreeSnapshotter {
// ... rest of the code ...
|
f6540575792beb2306736e967e5399df58c50337
|
qutip/tests/test_heom.py
|
qutip/tests/test_heom.py
|
from qutip.nonmarkov.heom import (
BathExponent,
Bath,
BosonicBath,
DrudeLorentzBath,
DrudeLorentzPadeBath,
UnderDampedBath,
FermionicBath,
LorentzianBath,
LorentzianPadeBath,
HEOMSolver,
HSolverDL,
)
class TestBathAPI:
def test_api(self):
# just assert that the baths are importable
assert BathExponent
assert Bath
assert BosonicBath
assert DrudeLorentzBath
assert DrudeLorentzPadeBath
assert UnderDampedBath
assert FermionicBath
assert LorentzianBath
assert LorentzianPadeBath
class TestSolverAPI:
def test_api(self):
# just assert that the solvers are importable
assert HEOMSolver
assert HSolverDL
|
from qutip.nonmarkov.heom import (
BathExponent,
Bath,
BosonicBath,
DrudeLorentzBath,
DrudeLorentzPadeBath,
UnderDampedBath,
FermionicBath,
LorentzianBath,
LorentzianPadeBath,
HEOMSolver,
HSolverDL,
HierarchyADOs,
HierarchyADOsState,
)
class TestBathAPI:
def test_api(self):
# just assert that the baths are importable
assert BathExponent
assert Bath
assert BosonicBath
assert DrudeLorentzBath
assert DrudeLorentzPadeBath
assert UnderDampedBath
assert FermionicBath
assert LorentzianBath
assert LorentzianPadeBath
class TestSolverAPI:
def test_api(self):
# just assert that the solvers and associated classes are importable
assert HEOMSolver
assert HSolverDL
assert HierarchyADOs
assert HierarchyADOsState
|
Test that HierarchyADOs and HierarchyADOsState are part of the HEOM api.
|
Test that HierarchyADOs and HierarchyADOsState are part of the HEOM api.
|
Python
|
bsd-3-clause
|
cgranade/qutip,qutip/qutip,qutip/qutip,cgranade/qutip
|
python
|
## Code Before:
from qutip.nonmarkov.heom import (
BathExponent,
Bath,
BosonicBath,
DrudeLorentzBath,
DrudeLorentzPadeBath,
UnderDampedBath,
FermionicBath,
LorentzianBath,
LorentzianPadeBath,
HEOMSolver,
HSolverDL,
)
class TestBathAPI:
def test_api(self):
# just assert that the baths are importable
assert BathExponent
assert Bath
assert BosonicBath
assert DrudeLorentzBath
assert DrudeLorentzPadeBath
assert UnderDampedBath
assert FermionicBath
assert LorentzianBath
assert LorentzianPadeBath
class TestSolverAPI:
def test_api(self):
# just assert that the solvers are importable
assert HEOMSolver
assert HSolverDL
## Instruction:
Test that HierarchyADOs and HierarchyADOsState are part of the HEOM api.
## Code After:
from qutip.nonmarkov.heom import (
BathExponent,
Bath,
BosonicBath,
DrudeLorentzBath,
DrudeLorentzPadeBath,
UnderDampedBath,
FermionicBath,
LorentzianBath,
LorentzianPadeBath,
HEOMSolver,
HSolverDL,
HierarchyADOs,
HierarchyADOsState,
)
class TestBathAPI:
def test_api(self):
# just assert that the baths are importable
assert BathExponent
assert Bath
assert BosonicBath
assert DrudeLorentzBath
assert DrudeLorentzPadeBath
assert UnderDampedBath
assert FermionicBath
assert LorentzianBath
assert LorentzianPadeBath
class TestSolverAPI:
def test_api(self):
# just assert that the solvers and associated classes are importable
assert HEOMSolver
assert HSolverDL
assert HierarchyADOs
assert HierarchyADOsState
|
# ... existing code ...
LorentzianPadeBath,
HEOMSolver,
HSolverDL,
HierarchyADOs,
HierarchyADOsState,
)
# ... modified code ...
class TestSolverAPI:
def test_api(self):
# just assert that the solvers and associated classes are importable
assert HEOMSolver
assert HSolverDL
assert HierarchyADOs
assert HierarchyADOsState
# ... rest of the code ...
|
5b71b9e86dc09fe21717a75e45748a81d833c632
|
src/test-python.py
|
src/test-python.py
|
def test(options, buildout):
from subprocess import Popen, PIPE
import os
import sys
python = options['python']
if not os.path.exists(python):
raise IOError("There is no file at %s" % python)
if sys.platform == 'darwin':
output = Popen([python, "-c", "import platform; print (platform.mac_ver())"], stdout=PIPE).communicate()[0]
if not output.startswith("('10."):
raise IOError("Your python at %s doesn't return proper data for platform.mac_ver(), got: %s" % (python, output))
|
def test(options, buildout):
from subprocess import Popen, PIPE
import os
import sys
python = options['python']
if not os.path.exists(python):
raise IOError("There is no file at %s" % python)
if sys.platform == 'darwin':
output = Popen([python, "-c", "import platform; print (platform.mac_ver())"], stdout=PIPE).communicate()[0]
if not output.startswith("('10."):
raise IOError("Your python at %s doesn't return proper data for platform.mac_ver(), got: %s" % (python, output))
elif sys.platform == 'linux2' and (2, 4) <= sys.version_info < (2, 5):
output = Popen([python, "-c", "import socket; print (hasattr(socket, 'ssl'))"], stdout=PIPE).communicate()[0]
if not output.startswith("True"):
raise IOError("Your python at %s doesn't have ssl support, got: %s" % (python, output))
|
Check if the installed python2.4 have ssl support.
|
Check if the installed python2.4 have ssl support.
|
Python
|
mit
|
upiq/plonebuild,upiq/plonebuild
|
python
|
## Code Before:
def test(options, buildout):
from subprocess import Popen, PIPE
import os
import sys
python = options['python']
if not os.path.exists(python):
raise IOError("There is no file at %s" % python)
if sys.platform == 'darwin':
output = Popen([python, "-c", "import platform; print (platform.mac_ver())"], stdout=PIPE).communicate()[0]
if not output.startswith("('10."):
raise IOError("Your python at %s doesn't return proper data for platform.mac_ver(), got: %s" % (python, output))
## Instruction:
Check if the installed python2.4 have ssl support.
## Code After:
def test(options, buildout):
from subprocess import Popen, PIPE
import os
import sys
python = options['python']
if not os.path.exists(python):
raise IOError("There is no file at %s" % python)
if sys.platform == 'darwin':
output = Popen([python, "-c", "import platform; print (platform.mac_ver())"], stdout=PIPE).communicate()[0]
if not output.startswith("('10."):
raise IOError("Your python at %s doesn't return proper data for platform.mac_ver(), got: %s" % (python, output))
elif sys.platform == 'linux2' and (2, 4) <= sys.version_info < (2, 5):
output = Popen([python, "-c", "import socket; print (hasattr(socket, 'ssl'))"], stdout=PIPE).communicate()[0]
if not output.startswith("True"):
raise IOError("Your python at %s doesn't have ssl support, got: %s" % (python, output))
|
...
output = Popen([python, "-c", "import platform; print (platform.mac_ver())"], stdout=PIPE).communicate()[0]
if not output.startswith("('10."):
raise IOError("Your python at %s doesn't return proper data for platform.mac_ver(), got: %s" % (python, output))
elif sys.platform == 'linux2' and (2, 4) <= sys.version_info < (2, 5):
output = Popen([python, "-c", "import socket; print (hasattr(socket, 'ssl'))"], stdout=PIPE).communicate()[0]
if not output.startswith("True"):
raise IOError("Your python at %s doesn't have ssl support, got: %s" % (python, output))
...
|
3ba1ffb9e5b58b4b9697dfeaa3729b31d79d46a4
|
plugins/korge-gradle-plugin/src/main/kotlin/com/soywiz/korge/gradle/Repos.kt
|
plugins/korge-gradle-plugin/src/main/kotlin/com/soywiz/korge/gradle/Repos.kt
|
package com.soywiz.korge.gradle
import org.gradle.api.Project
import java.net.URI
fun Project.configureRepositories() {
repositories.apply {
mavenLocal().content {
it.excludeGroup("Kotlin/Native")
}
maven {
it.url = URI("https://dl.bintray.com/korlibs/korlibs")
it.content {
it.includeGroup("com.soywiz")
it.excludeGroup("Kotlin/Native")
}
}
if (BuildVersions.KOTLIN.contains("eap")) {
maven {
it.url = URI("https://dl.bintray.com/kotlin/kotlin-eap")
it.content {
it.excludeGroup("Kotlin/Native")
}
}
}
jcenter().content {
it.excludeGroup("Kotlin/Native")
}
mavenCentral().content {
it.excludeGroup("Kotlin/Native")
}
if (BuildVersions.KOTLIN.contains("release")) {
maven { it.url = uri("https://dl.bintray.com/kotlin/kotlin-dev") }
}
}
}
|
package com.soywiz.korge.gradle
import org.gradle.api.Project
import java.net.URI
fun Project.configureRepositories() {
repositories.apply {
mavenLocal().content {
it.excludeGroup("Kotlin/Native")
}
maven {
it.url = URI("https://dl.bintray.com/korlibs/korlibs")
it.content {
it.excludeGroup("Kotlin/Native")
}
}
if (BuildVersions.KOTLIN.contains("eap")) {
maven {
it.url = URI("https://dl.bintray.com/kotlin/kotlin-eap")
it.content {
it.excludeGroup("Kotlin/Native")
}
}
}
jcenter().content {
it.excludeGroup("Kotlin/Native")
}
mavenCentral().content {
it.excludeGroup("Kotlin/Native")
}
if (BuildVersions.KOTLIN.contains("release")) {
maven { it.url = uri("https://dl.bintray.com/kotlin/kotlin-dev") }
}
}
}
|
Remove includeGroup since now it is in separated packages com.soywiz.korlibs.*
|
Remove includeGroup since now it is in separated packages com.soywiz.korlibs.*
|
Kotlin
|
apache-2.0
|
soywiz/korge,soywiz/korge,soywiz/korge
|
kotlin
|
## Code Before:
package com.soywiz.korge.gradle
import org.gradle.api.Project
import java.net.URI
fun Project.configureRepositories() {
repositories.apply {
mavenLocal().content {
it.excludeGroup("Kotlin/Native")
}
maven {
it.url = URI("https://dl.bintray.com/korlibs/korlibs")
it.content {
it.includeGroup("com.soywiz")
it.excludeGroup("Kotlin/Native")
}
}
if (BuildVersions.KOTLIN.contains("eap")) {
maven {
it.url = URI("https://dl.bintray.com/kotlin/kotlin-eap")
it.content {
it.excludeGroup("Kotlin/Native")
}
}
}
jcenter().content {
it.excludeGroup("Kotlin/Native")
}
mavenCentral().content {
it.excludeGroup("Kotlin/Native")
}
if (BuildVersions.KOTLIN.contains("release")) {
maven { it.url = uri("https://dl.bintray.com/kotlin/kotlin-dev") }
}
}
}
## Instruction:
Remove includeGroup since now it is in separated packages com.soywiz.korlibs.*
## Code After:
package com.soywiz.korge.gradle
import org.gradle.api.Project
import java.net.URI
fun Project.configureRepositories() {
repositories.apply {
mavenLocal().content {
it.excludeGroup("Kotlin/Native")
}
maven {
it.url = URI("https://dl.bintray.com/korlibs/korlibs")
it.content {
it.excludeGroup("Kotlin/Native")
}
}
if (BuildVersions.KOTLIN.contains("eap")) {
maven {
it.url = URI("https://dl.bintray.com/kotlin/kotlin-eap")
it.content {
it.excludeGroup("Kotlin/Native")
}
}
}
jcenter().content {
it.excludeGroup("Kotlin/Native")
}
mavenCentral().content {
it.excludeGroup("Kotlin/Native")
}
if (BuildVersions.KOTLIN.contains("release")) {
maven { it.url = uri("https://dl.bintray.com/kotlin/kotlin-dev") }
}
}
}
|
// ... existing code ...
maven {
it.url = URI("https://dl.bintray.com/korlibs/korlibs")
it.content {
it.excludeGroup("Kotlin/Native")
}
}
// ... rest of the code ...
|
594013577541966eaea2aee61acfac93b3d59f96
|
LeakCanarySample/app/src/main/java/anaware/leakcanarysample/AnotherActivity.java
|
LeakCanarySample/app/src/main/java/anaware/leakcanarysample/AnotherActivity.java
|
package anaware.leakcanarysample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.squareup.leakcanary.RefWatcher;
public class AnotherActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
}
@Override
public void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = MyApplication.getRefWatcher(this);
refWatcher.watch(this);
}
}
|
package anaware.leakcanarysample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.squareup.leakcanary.RefWatcher;
public class AnotherActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
// Invoke the GC to accelerate the analysis.
System.gc();
}
@Override
public void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = MyApplication.getRefWatcher(this);
refWatcher.watch(this);
}
}
|
Call GC to accelerate the analysis
|
Call GC to accelerate the analysis
|
Java
|
apache-2.0
|
anaselhajjaji/android-samples,anaselhajjaji/android-samples
|
java
|
## Code Before:
package anaware.leakcanarysample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.squareup.leakcanary.RefWatcher;
public class AnotherActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
}
@Override
public void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = MyApplication.getRefWatcher(this);
refWatcher.watch(this);
}
}
## Instruction:
Call GC to accelerate the analysis
## Code After:
package anaware.leakcanarysample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.squareup.leakcanary.RefWatcher;
public class AnotherActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
// Invoke the GC to accelerate the analysis.
System.gc();
}
@Override
public void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = MyApplication.getRefWatcher(this);
refWatcher.watch(this);
}
}
|
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
// Invoke the GC to accelerate the analysis.
System.gc();
}
@Override
...
|
375b26fbb6e5ba043a1017e28027241c12374207
|
napalm_logs/transport/zeromq.py
|
napalm_logs/transport/zeromq.py
|
'''
ZeroMQ transport for napalm-logs.
'''
from __future__ import absolute_import
from __future__ import unicode_literals
# Import stdlib
import json
# Import third party libs
import zmq
# Import napalm-logs pkgs
from napalm_logs.transport.base import TransportBase
class ZMQTransport(TransportBase):
'''
ZMQ transport class.
'''
def __init__(self, addr, port):
self.addr = addr
self.port = port
def start(self):
self.context = zmq.Context()
self.socket = self.context.socket(zmq.PUB)
self.socket.bind('tcp://{addr}:{port}'.format(
addr=self.addr,
port=self.port)
)
def serialise(self, obj):
return json.dumps(obj)
def publish(self, obj):
self.socket.send(
self.serialise(obj)
)
def tear_down(self):
if hasattr(self, 'socket'):
self.socket.close()
if hasattr(self, 'context'):
self.context.term()
|
'''
ZeroMQ transport for napalm-logs.
'''
from __future__ import absolute_import
from __future__ import unicode_literals
# Import stdlib
import json
import logging
# Import third party libs
import zmq
# Import napalm-logs pkgs
from napalm_logs.exceptions import BindException
from napalm_logs.transport.base import TransportBase
log = logging.getLogger(__name__)
class ZMQTransport(TransportBase):
'''
ZMQ transport class.
'''
def __init__(self, addr, port):
self.addr = addr
self.port = port
def start(self):
self.context = zmq.Context()
self.socket = self.context.socket(zmq.PUB)
try:
self.socket.bind('tcp://{addr}:{port}'.format(
addr=self.addr,
port=self.port)
)
except zmq.error.ZMQError as err:
log.error(err, exc_info=True)
raise BindException(err)
def serialise(self, obj):
return json.dumps(obj)
def publish(self, obj):
self.socket.send(
self.serialise(obj)
)
def tear_down(self):
if hasattr(self, 'socket'):
self.socket.close()
if hasattr(self, 'context'):
self.context.term()
|
Raise bind exception and log
|
Raise bind exception and log
|
Python
|
apache-2.0
|
napalm-automation/napalm-logs,napalm-automation/napalm-logs
|
python
|
## Code Before:
'''
ZeroMQ transport for napalm-logs.
'''
from __future__ import absolute_import
from __future__ import unicode_literals
# Import stdlib
import json
# Import third party libs
import zmq
# Import napalm-logs pkgs
from napalm_logs.transport.base import TransportBase
class ZMQTransport(TransportBase):
'''
ZMQ transport class.
'''
def __init__(self, addr, port):
self.addr = addr
self.port = port
def start(self):
self.context = zmq.Context()
self.socket = self.context.socket(zmq.PUB)
self.socket.bind('tcp://{addr}:{port}'.format(
addr=self.addr,
port=self.port)
)
def serialise(self, obj):
return json.dumps(obj)
def publish(self, obj):
self.socket.send(
self.serialise(obj)
)
def tear_down(self):
if hasattr(self, 'socket'):
self.socket.close()
if hasattr(self, 'context'):
self.context.term()
## Instruction:
Raise bind exception and log
## Code After:
'''
ZeroMQ transport for napalm-logs.
'''
from __future__ import absolute_import
from __future__ import unicode_literals
# Import stdlib
import json
import logging
# Import third party libs
import zmq
# Import napalm-logs pkgs
from napalm_logs.exceptions import BindException
from napalm_logs.transport.base import TransportBase
log = logging.getLogger(__name__)
class ZMQTransport(TransportBase):
'''
ZMQ transport class.
'''
def __init__(self, addr, port):
self.addr = addr
self.port = port
def start(self):
self.context = zmq.Context()
self.socket = self.context.socket(zmq.PUB)
try:
self.socket.bind('tcp://{addr}:{port}'.format(
addr=self.addr,
port=self.port)
)
except zmq.error.ZMQError as err:
log.error(err, exc_info=True)
raise BindException(err)
def serialise(self, obj):
return json.dumps(obj)
def publish(self, obj):
self.socket.send(
self.serialise(obj)
)
def tear_down(self):
if hasattr(self, 'socket'):
self.socket.close()
if hasattr(self, 'context'):
self.context.term()
|
// ... existing code ...
# Import stdlib
import json
import logging
# Import third party libs
import zmq
# Import napalm-logs pkgs
from napalm_logs.exceptions import BindException
from napalm_logs.transport.base import TransportBase
log = logging.getLogger(__name__)
class ZMQTransport(TransportBase):
// ... modified code ...
def start(self):
self.context = zmq.Context()
self.socket = self.context.socket(zmq.PUB)
try:
self.socket.bind('tcp://{addr}:{port}'.format(
addr=self.addr,
port=self.port)
)
except zmq.error.ZMQError as err:
log.error(err, exc_info=True)
raise BindException(err)
def serialise(self, obj):
return json.dumps(obj)
// ... rest of the code ...
|
c66a2933cca12fa27b688f60b3eb70b07bcce4e5
|
src/ggrc/migrations/utils.py
|
src/ggrc/migrations/utils.py
|
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import aliased
def resolve_duplicates(model, attr):
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
v0.id > v1.id
))
for v in query:
setattr(v, attr, getattr(v, attr, model.type) + u"-" + unicode(v.id))
db.session.add(v)
db.session.commit()
|
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import aliased
def resolve_duplicates(model, attr, separator=u"-"):
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
v0.id > v1.id
))
for v in query:
i = 0
nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
while db.session.query(model).\
filter(getattr(model, attr) == nattr).count():
i += 1
nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
setattr(v, attr, nattr)
db.session.add(v)
db.session.commit()
|
Verify that new attribute doesn't already exist in database
|
Verify that new attribute doesn't already exist in database
|
Python
|
apache-2.0
|
prasannav7/ggrc-core,jmakov/ggrc-core,prasannav7/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc-core,jmakov/ggrc-core,kr41/ggrc-core,selahssea/ggrc-core,j0gurt/ggrc-core,edofic/ggrc-core,AleksNeStu/ggrc-core,j0gurt/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core,kr41/ggrc-core,josthkko/ggrc-core,prasannav7/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,kr41/ggrc-core,VinnieJohns/ggrc-core,josthkko/ggrc-core,NejcZupec/ggrc-core,plamut/ggrc-core,prasannav7/ggrc-core,edofic/ggrc-core,edofic/ggrc-core,jmakov/ggrc-core,andrei-karalionak/ggrc-core,andrei-karalionak/ggrc-core,j0gurt/ggrc-core,plamut/ggrc-core,NejcZupec/ggrc-core,josthkko/ggrc-core,josthkko/ggrc-core,edofic/ggrc-core,jmakov/ggrc-core,andrei-karalionak/ggrc-core,jmakov/ggrc-core,kr41/ggrc-core,selahssea/ggrc-core,j0gurt/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,NejcZupec/ggrc-core,VinnieJohns/ggrc-core,NejcZupec/ggrc-core,VinnieJohns/ggrc-core
|
python
|
## Code Before:
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import aliased
def resolve_duplicates(model, attr):
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
v0.id > v1.id
))
for v in query:
setattr(v, attr, getattr(v, attr, model.type) + u"-" + unicode(v.id))
db.session.add(v)
db.session.commit()
## Instruction:
Verify that new attribute doesn't already exist in database
## Code After:
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import aliased
def resolve_duplicates(model, attr, separator=u"-"):
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
v0.id > v1.id
))
for v in query:
i = 0
nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
while db.session.query(model).\
filter(getattr(model, attr) == nattr).count():
i += 1
nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
setattr(v, attr, nattr)
db.session.add(v)
db.session.commit()
|
# ... existing code ...
from sqlalchemy.orm import aliased
def resolve_duplicates(model, attr, separator=u"-"):
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
# ... modified code ...
v0.id > v1.id
))
for v in query:
i = 0
nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
while db.session.query(model).\
filter(getattr(model, attr) == nattr).count():
i += 1
nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
setattr(v, attr, nattr)
db.session.add(v)
db.session.commit()
# ... rest of the code ...
|
c5a929f2bb52ac6683279e8353db58f7064ae54b
|
src/main/java/mezz/jei/gui/DrawableResource.java
|
src/main/java/mezz/jei/gui/DrawableResource.java
|
package mezz.jei.gui;
import mezz.jei.api.gui.IDrawable;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.util.ResourceLocation;
import javax.annotation.Nonnull;
public class DrawableResource extends Gui implements IDrawable {
@Nonnull
private final ResourceLocation resourceLocation;
private final int u;
private final int v;
private final int width;
private final int height;
public DrawableResource(@Nonnull ResourceLocation resourceLocation, int u, int v, int width, int height) {
this.resourceLocation = resourceLocation;
this.u = u;
this.v = v;
this.width = width;
this.height = height;
}
@Override
public int getWidth() {
return width;
}
@Override
public int getHeight() {
return height;
}
public void draw(@Nonnull Minecraft minecraft) {
minecraft.getTextureManager().bindTexture(resourceLocation);
this.drawTexturedModalRect(0, 0, u, v, width, height);
}
}
|
package mezz.jei.gui;
import cpw.mods.fml.client.config.GuiUtils;
import mezz.jei.api.gui.IDrawable;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
import javax.annotation.Nonnull;
public class DrawableResource implements IDrawable {
@Nonnull
private final ResourceLocation resourceLocation;
private final int u;
private final int v;
private final int width;
private final int height;
public DrawableResource(@Nonnull ResourceLocation resourceLocation, int u, int v, int width, int height) {
this.resourceLocation = resourceLocation;
this.u = u;
this.v = v;
this.width = width;
this.height = height;
}
@Override
public int getWidth() {
return width;
}
@Override
public int getHeight() {
return height;
}
public void draw(@Nonnull Minecraft minecraft) {
minecraft.getTextureManager().bindTexture(resourceLocation);
GuiUtils.drawTexturedModalRect(0, 0, u, v, width, height, 0);
}
}
|
Use GuiUtils instead of extending Gui
|
Use GuiUtils instead of extending Gui
|
Java
|
mit
|
mezz/JustEnoughItems,mezz/JustEnoughItems,way2muchnoise/JustEnoughItems,Adaptivity/JustEnoughItems,Adaptivity/JustEnoughItems
|
java
|
## Code Before:
package mezz.jei.gui;
import mezz.jei.api.gui.IDrawable;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.util.ResourceLocation;
import javax.annotation.Nonnull;
public class DrawableResource extends Gui implements IDrawable {
@Nonnull
private final ResourceLocation resourceLocation;
private final int u;
private final int v;
private final int width;
private final int height;
public DrawableResource(@Nonnull ResourceLocation resourceLocation, int u, int v, int width, int height) {
this.resourceLocation = resourceLocation;
this.u = u;
this.v = v;
this.width = width;
this.height = height;
}
@Override
public int getWidth() {
return width;
}
@Override
public int getHeight() {
return height;
}
public void draw(@Nonnull Minecraft minecraft) {
minecraft.getTextureManager().bindTexture(resourceLocation);
this.drawTexturedModalRect(0, 0, u, v, width, height);
}
}
## Instruction:
Use GuiUtils instead of extending Gui
## Code After:
package mezz.jei.gui;
import cpw.mods.fml.client.config.GuiUtils;
import mezz.jei.api.gui.IDrawable;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
import javax.annotation.Nonnull;
public class DrawableResource implements IDrawable {
@Nonnull
private final ResourceLocation resourceLocation;
private final int u;
private final int v;
private final int width;
private final int height;
public DrawableResource(@Nonnull ResourceLocation resourceLocation, int u, int v, int width, int height) {
this.resourceLocation = resourceLocation;
this.u = u;
this.v = v;
this.width = width;
this.height = height;
}
@Override
public int getWidth() {
return width;
}
@Override
public int getHeight() {
return height;
}
public void draw(@Nonnull Minecraft minecraft) {
minecraft.getTextureManager().bindTexture(resourceLocation);
GuiUtils.drawTexturedModalRect(0, 0, u, v, width, height, 0);
}
}
|
...
package mezz.jei.gui;
import cpw.mods.fml.client.config.GuiUtils;
import mezz.jei.api.gui.IDrawable;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
import javax.annotation.Nonnull;
public class DrawableResource implements IDrawable {
@Nonnull
private final ResourceLocation resourceLocation;
...
public void draw(@Nonnull Minecraft minecraft) {
minecraft.getTextureManager().bindTexture(resourceLocation);
GuiUtils.drawTexturedModalRect(0, 0, u, v, width, height, 0);
}
}
...
|
42f3cc3356258289f9272608bdf599ccb7462d32
|
backend/manager/modules/restapi/interface/definition/src/main/java/org/ovirt/engine/api/resource/VmNumaNodesResource.java
|
backend/manager/modules/restapi/interface/definition/src/main/java/org/ovirt/engine/api/resource/VmNumaNodesResource.java
|
package org.ovirt.engine.api.resource;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.annotations.providers.jaxb.Formatted;
import org.ovirt.engine.api.model.NumaNodes;
import org.ovirt.engine.api.model.VirtualNumaNode;
@Produces({ ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML })
public interface VmNumaNodesResource {
@GET
@Formatted
public NumaNodes list();
@POST
@Formatted
@Consumes({ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML})
public Response add(VirtualNumaNode node);
@DELETE
@Path("{id}")
public Response remove(@PathParam("id") String id);
@Path("{iden}")
public VmNumaNodeResource getVmNumaNodeSubResource(@PathParam("iden") String id);
}
|
package org.ovirt.engine.api.resource;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.annotations.providers.jaxb.Formatted;
import org.ovirt.engine.api.model.VirtualNumaNode;
import org.ovirt.engine.api.model.VirtualNumaNodes;
@Produces({ ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML })
public interface VmNumaNodesResource {
@GET
@Formatted
public VirtualNumaNodes list();
@POST
@Formatted
@Consumes({ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML})
public Response add(VirtualNumaNode node);
@DELETE
@Path("{id}")
public Response remove(@PathParam("id") String id);
@Path("{iden}")
public VmNumaNodeResource getVmNumaNodeSubResource(@PathParam("iden") String id);
}
|
Fix return type of vms/{vm:id}/numanodes
|
restapi: Fix return type of vms/{vm:id}/numanodes
Currently the type returned by the "list" operation of this resources is
"NumaNodes", but it should be "VirtualNumaNodes", otherwise the
generator of the Java SDK will not work correctly.
Change-Id: I57af48c044012fe9009e51b48c8813114319980b
Bug-Url: https://bugzilla.redhat.com/1115610
Signed-off-by: Juan Hernandez <[email protected]>
|
Java
|
apache-2.0
|
zerodengxinchao/ovirt-engine,eayun/ovirt-engine,zerodengxinchao/ovirt-engine,yapengsong/ovirt-engine,eayun/ovirt-engine,walteryang47/ovirt-engine,yapengsong/ovirt-engine,OpenUniversity/ovirt-engine,zerodengxinchao/ovirt-engine,zerodengxinchao/ovirt-engine,eayun/ovirt-engine,yingyun001/ovirt-engine,OpenUniversity/ovirt-engine,OpenUniversity/ovirt-engine,walteryang47/ovirt-engine,walteryang47/ovirt-engine,halober/ovirt-engine,eayun/ovirt-engine,yingyun001/ovirt-engine,yapengsong/ovirt-engine,yingyun001/ovirt-engine,halober/ovirt-engine,halober/ovirt-engine,OpenUniversity/ovirt-engine,yingyun001/ovirt-engine,halober/ovirt-engine,OpenUniversity/ovirt-engine,yapengsong/ovirt-engine,zerodengxinchao/ovirt-engine,eayun/ovirt-engine,yingyun001/ovirt-engine,yapengsong/ovirt-engine,walteryang47/ovirt-engine,walteryang47/ovirt-engine
|
java
|
## Code Before:
package org.ovirt.engine.api.resource;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.annotations.providers.jaxb.Formatted;
import org.ovirt.engine.api.model.NumaNodes;
import org.ovirt.engine.api.model.VirtualNumaNode;
@Produces({ ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML })
public interface VmNumaNodesResource {
@GET
@Formatted
public NumaNodes list();
@POST
@Formatted
@Consumes({ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML})
public Response add(VirtualNumaNode node);
@DELETE
@Path("{id}")
public Response remove(@PathParam("id") String id);
@Path("{iden}")
public VmNumaNodeResource getVmNumaNodeSubResource(@PathParam("iden") String id);
}
## Instruction:
restapi: Fix return type of vms/{vm:id}/numanodes
Currently the type returned by the "list" operation of this resources is
"NumaNodes", but it should be "VirtualNumaNodes", otherwise the
generator of the Java SDK will not work correctly.
Change-Id: I57af48c044012fe9009e51b48c8813114319980b
Bug-Url: https://bugzilla.redhat.com/1115610
Signed-off-by: Juan Hernandez <[email protected]>
## Code After:
package org.ovirt.engine.api.resource;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.annotations.providers.jaxb.Formatted;
import org.ovirt.engine.api.model.VirtualNumaNode;
import org.ovirt.engine.api.model.VirtualNumaNodes;
@Produces({ ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML })
public interface VmNumaNodesResource {
@GET
@Formatted
public VirtualNumaNodes list();
@POST
@Formatted
@Consumes({ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML})
public Response add(VirtualNumaNode node);
@DELETE
@Path("{id}")
public Response remove(@PathParam("id") String id);
@Path("{iden}")
public VmNumaNodeResource getVmNumaNodeSubResource(@PathParam("iden") String id);
}
|
// ... existing code ...
import javax.ws.rs.core.Response;
import org.jboss.resteasy.annotations.providers.jaxb.Formatted;
import org.ovirt.engine.api.model.VirtualNumaNode;
import org.ovirt.engine.api.model.VirtualNumaNodes;
@Produces({ ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML })
public interface VmNumaNodesResource {
// ... modified code ...
@GET
@Formatted
public VirtualNumaNodes list();
@POST
@Formatted
// ... rest of the code ...
|
8cc8f9a1535a2361c27e9411f9163ecd2a9958d5
|
utils/__init__.py
|
utils/__init__.py
|
import pymongo
connection = pymongo.MongoClient("mongodb://localhost")
db = connection.vcf_explorer
import database
import parse_vcf
import filter_vcf
import query
|
import pymongo
import config #config.py
connection = pymongo.MongoClient(host=config.MONGODB_HOST, port=config.MONGODB_PORT)
db = connection[config.MONGODB_NAME]
import database
import parse_vcf
import filter_vcf
import query
|
Set mongodb settings using config.py
|
Set mongodb settings using config.py
|
Python
|
mit
|
CuppenResearch/vcf-explorer,CuppenResearch/vcf-explorer,CuppenResearch/vcf-explorer,CuppenResearch/vcf-explorer
|
python
|
## Code Before:
import pymongo
connection = pymongo.MongoClient("mongodb://localhost")
db = connection.vcf_explorer
import database
import parse_vcf
import filter_vcf
import query
## Instruction:
Set mongodb settings using config.py
## Code After:
import pymongo
import config #config.py
connection = pymongo.MongoClient(host=config.MONGODB_HOST, port=config.MONGODB_PORT)
db = connection[config.MONGODB_NAME]
import database
import parse_vcf
import filter_vcf
import query
|
...
import pymongo
import config #config.py
connection = pymongo.MongoClient(host=config.MONGODB_HOST, port=config.MONGODB_PORT)
db = connection[config.MONGODB_NAME]
import database
import parse_vcf
...
|
0068c9da4b8af1d51928ce3d2f326130dbf342f2
|
_scripts/cfdoc_bootstrap.py
|
_scripts/cfdoc_bootstrap.py
|
import cfdoc_environment as environment
import cfdoc_git as git
import sys
config = environment.validate()
try:
git.createData(config)
except:
print "cfdoc_preprocess: Fatal error generating git tags"
sys.stdout.write(" Exception: ")
print sys.exc_info()
exit(1)
exit(0)
|
import cfdoc_environment as environment
import cfdoc_git as git
import sys
config = environment.validate(sys.argv[1])
try:
git.createData(config)
except:
print "cfdoc_preprocess: Fatal error generating git tags"
sys.stdout.write(" Exception: ")
print sys.exc_info()
exit(1)
exit(0)
|
Fix environment.validate() being called without branch name.
|
Fix environment.validate() being called without branch name.
|
Python
|
mit
|
michaelclelland/documentation-generator,stweil/documentation-generator,stweil/documentation-generator,nickanderson/documentation-generator,cfengine/documentation-generator,michaelclelland/documentation-generator,cfengine/documentation-generator,nickanderson/documentation-generator,michaelclelland/documentation-generator,cfengine/documentation-generator,stweil/documentation-generator,cfengine/documentation-generator,nickanderson/documentation-generator,stweil/documentation-generator,cfengine/documentation-generator,nickanderson/documentation-generator,stweil/documentation-generator,michaelclelland/documentation-generator,nickanderson/documentation-generator,michaelclelland/documentation-generator
|
python
|
## Code Before:
import cfdoc_environment as environment
import cfdoc_git as git
import sys
config = environment.validate()
try:
git.createData(config)
except:
print "cfdoc_preprocess: Fatal error generating git tags"
sys.stdout.write(" Exception: ")
print sys.exc_info()
exit(1)
exit(0)
## Instruction:
Fix environment.validate() being called without branch name.
## Code After:
import cfdoc_environment as environment
import cfdoc_git as git
import sys
config = environment.validate(sys.argv[1])
try:
git.createData(config)
except:
print "cfdoc_preprocess: Fatal error generating git tags"
sys.stdout.write(" Exception: ")
print sys.exc_info()
exit(1)
exit(0)
|
# ... existing code ...
import cfdoc_git as git
import sys
config = environment.validate(sys.argv[1])
try:
git.createData(config)
# ... rest of the code ...
|
d7a347b0cee650d7b5cb6a0eca613da543e0e305
|
tests/conftest.py
|
tests/conftest.py
|
import pytest
from flask import Flask, jsonify
@pytest.fixture
def app():
app = Flask(__name__)
app.config['SECRET_KEY'] = '42'
@app.route('/')
def index():
return app.response_class('OK')
@app.route('/ping')
def ping():
return jsonify(ping='pong')
return app
|
import pytest
from textwrap import dedent
from flask import Flask, jsonify
pytest_plugins = 'pytester'
@pytest.fixture
def app():
app = Flask(__name__)
app.config['SECRET_KEY'] = '42'
@app.route('/')
def index():
return app.response_class('OK')
@app.route('/ping')
def ping():
return jsonify(ping='pong')
return app
@pytest.fixture
def appdir(testdir):
app_root = testdir.tmpdir
test_root = app_root.mkdir('tests')
def create_test_module(code, filename='test_app.py'):
f = test_root.join(filename)
f.write(dedent(code), ensure=True)
return f
testdir.create_test_module = create_test_module
testdir.create_test_module('''
import pytest
from flask import Flask
@pytest.fixture
def app():
app = Flask(__name__)
return app
''', filename='conftest.py')
return testdir
|
Add `appdir` fixture to simplify testing
|
Add `appdir` fixture to simplify testing
|
Python
|
mit
|
amateja/pytest-flask
|
python
|
## Code Before:
import pytest
from flask import Flask, jsonify
@pytest.fixture
def app():
app = Flask(__name__)
app.config['SECRET_KEY'] = '42'
@app.route('/')
def index():
return app.response_class('OK')
@app.route('/ping')
def ping():
return jsonify(ping='pong')
return app
## Instruction:
Add `appdir` fixture to simplify testing
## Code After:
import pytest
from textwrap import dedent
from flask import Flask, jsonify
pytest_plugins = 'pytester'
@pytest.fixture
def app():
app = Flask(__name__)
app.config['SECRET_KEY'] = '42'
@app.route('/')
def index():
return app.response_class('OK')
@app.route('/ping')
def ping():
return jsonify(ping='pong')
return app
@pytest.fixture
def appdir(testdir):
app_root = testdir.tmpdir
test_root = app_root.mkdir('tests')
def create_test_module(code, filename='test_app.py'):
f = test_root.join(filename)
f.write(dedent(code), ensure=True)
return f
testdir.create_test_module = create_test_module
testdir.create_test_module('''
import pytest
from flask import Flask
@pytest.fixture
def app():
app = Flask(__name__)
return app
''', filename='conftest.py')
return testdir
|
// ... existing code ...
import pytest
from textwrap import dedent
from flask import Flask, jsonify
pytest_plugins = 'pytester'
@pytest.fixture
// ... modified code ...
return jsonify(ping='pong')
return app
@pytest.fixture
def appdir(testdir):
app_root = testdir.tmpdir
test_root = app_root.mkdir('tests')
def create_test_module(code, filename='test_app.py'):
f = test_root.join(filename)
f.write(dedent(code), ensure=True)
return f
testdir.create_test_module = create_test_module
testdir.create_test_module('''
import pytest
from flask import Flask
@pytest.fixture
def app():
app = Flask(__name__)
return app
''', filename='conftest.py')
return testdir
// ... rest of the code ...
|
b76b3cbe0d86bd5037ccfd21086ab50803606ec2
|
autobuilder/webhooks.py
|
autobuilder/webhooks.py
|
from buildbot.status.web.hooks.github import GitHubEventHandler
from twisted.python import log
import abconfig
class AutobuilderGithubEventHandler(GitHubEventHandler):
def handle_push(self, payload):
# This field is unused:
user = None
# user = payload['pusher']['name']
repo = payload['repository']['name']
repo_url = payload['repository']['url']
# NOTE: what would be a reasonable value for project?
# project = request.args.get('project', [''])[0]
project = abconfig.get_project_for_url(repo_url,
default_if_not_found=payload['repository']['full_name'])
changes = self._process_change(payload, user, repo, repo_url, project)
log.msg("Received %d changes from github" % len(changes))
return changes, 'git'
|
from buildbot.status.web.hooks.github import GitHubEventHandler
from twisted.python import log
import abconfig
def codebasemap(payload):
return abconfig.get_project_for_url(payload['repository']['url'])
class AutobuilderGithubEventHandler(GitHubEventHandler):
def __init__(self, secret, strict codebase=None):
if codebase is None:
codebase = codebasemap
GitHubEventHandler.__init__(self, secret, strict, codebase)
def handle_push(self, payload):
# This field is unused:
user = None
# user = payload['pusher']['name']
repo = payload['repository']['name']
repo_url = payload['repository']['url']
# NOTE: what would be a reasonable value for project?
# project = request.args.get('project', [''])[0]
project = abconfig.get_project_for_url(repo_url,
default_if_not_found=payload['repository']['full_name'])
changes = self._process_change(payload, user, repo, repo_url, project)
log.msg("Received %d changes from github" % len(changes))
return changes, 'git'
|
Add a codebase generator to the Github web hoook handler, to map the URL to the repo name for use as the codebase.
|
Add a codebase generator to the Github web hoook handler,
to map the URL to the repo name for use as the codebase.
|
Python
|
mit
|
madisongh/autobuilder
|
python
|
## Code Before:
from buildbot.status.web.hooks.github import GitHubEventHandler
from twisted.python import log
import abconfig
class AutobuilderGithubEventHandler(GitHubEventHandler):
def handle_push(self, payload):
# This field is unused:
user = None
# user = payload['pusher']['name']
repo = payload['repository']['name']
repo_url = payload['repository']['url']
# NOTE: what would be a reasonable value for project?
# project = request.args.get('project', [''])[0]
project = abconfig.get_project_for_url(repo_url,
default_if_not_found=payload['repository']['full_name'])
changes = self._process_change(payload, user, repo, repo_url, project)
log.msg("Received %d changes from github" % len(changes))
return changes, 'git'
## Instruction:
Add a codebase generator to the Github web hoook handler,
to map the URL to the repo name for use as the codebase.
## Code After:
from buildbot.status.web.hooks.github import GitHubEventHandler
from twisted.python import log
import abconfig
def codebasemap(payload):
return abconfig.get_project_for_url(payload['repository']['url'])
class AutobuilderGithubEventHandler(GitHubEventHandler):
def __init__(self, secret, strict codebase=None):
if codebase is None:
codebase = codebasemap
GitHubEventHandler.__init__(self, secret, strict, codebase)
def handle_push(self, payload):
# This field is unused:
user = None
# user = payload['pusher']['name']
repo = payload['repository']['name']
repo_url = payload['repository']['url']
# NOTE: what would be a reasonable value for project?
# project = request.args.get('project', [''])[0]
project = abconfig.get_project_for_url(repo_url,
default_if_not_found=payload['repository']['full_name'])
changes = self._process_change(payload, user, repo, repo_url, project)
log.msg("Received %d changes from github" % len(changes))
return changes, 'git'
|
# ... existing code ...
from twisted.python import log
import abconfig
def codebasemap(payload):
return abconfig.get_project_for_url(payload['repository']['url'])
class AutobuilderGithubEventHandler(GitHubEventHandler):
def __init__(self, secret, strict codebase=None):
if codebase is None:
codebase = codebasemap
GitHubEventHandler.__init__(self, secret, strict, codebase)
def handle_push(self, payload):
# This field is unused:
# ... rest of the code ...
|
769c83564d5f2272837c2fbea6d781110b71b8ca
|
main.py
|
main.py
|
from sys import argv, stderr
from drawer import *
from kmeans import kmeans
def read_vectors(file_name):
result = None
with open(file_name, 'r') as f:
vector_length = int(f.readline())
vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines()))
if all((len(x) == vector_length for x in vectors)):
result = vectors
return result
def main():
vectors = read_vectors(argv[1])
clusters_count = int(argv[2])
if vectors:
if len(vectors[0]) == 2:
display_source(vectors)
clusters = kmeans(vectors, clusters_count=clusters_count)
display_result(vectors, clusters)
else:
print('Invalid input', file=stderr)
if __name__ == '__main__':
main()
|
from sys import argv, stderr
from drawer import *
from kmeans import kmeans
def read_vectors(file_name):
result = None
with open(file_name, 'r') as f:
vector_length = int(f.readline())
vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines()))
if all((len(x) == vector_length for x in vectors)):
result = vectors
return result
def main():
vectors = read_vectors(argv[1])
clusters_count = int(argv[2])
if vectors:
clusters = kmeans(vectors, clusters_count=clusters_count)
if len(vectors[0]) == 2:
display_source(vectors)
display_result(vectors, clusters)
else:
print('Invalid input', file=stderr)
if __name__ == '__main__':
main()
|
Fix trying to display result in case of not 2D vectors
|
Fix trying to display result in case of not 2D vectors
|
Python
|
mit
|
vanashimko/k-means
|
python
|
## Code Before:
from sys import argv, stderr
from drawer import *
from kmeans import kmeans
def read_vectors(file_name):
result = None
with open(file_name, 'r') as f:
vector_length = int(f.readline())
vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines()))
if all((len(x) == vector_length for x in vectors)):
result = vectors
return result
def main():
vectors = read_vectors(argv[1])
clusters_count = int(argv[2])
if vectors:
if len(vectors[0]) == 2:
display_source(vectors)
clusters = kmeans(vectors, clusters_count=clusters_count)
display_result(vectors, clusters)
else:
print('Invalid input', file=stderr)
if __name__ == '__main__':
main()
## Instruction:
Fix trying to display result in case of not 2D vectors
## Code After:
from sys import argv, stderr
from drawer import *
from kmeans import kmeans
def read_vectors(file_name):
result = None
with open(file_name, 'r') as f:
vector_length = int(f.readline())
vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines()))
if all((len(x) == vector_length for x in vectors)):
result = vectors
return result
def main():
vectors = read_vectors(argv[1])
clusters_count = int(argv[2])
if vectors:
clusters = kmeans(vectors, clusters_count=clusters_count)
if len(vectors[0]) == 2:
display_source(vectors)
display_result(vectors, clusters)
else:
print('Invalid input', file=stderr)
if __name__ == '__main__':
main()
|
...
vectors = read_vectors(argv[1])
clusters_count = int(argv[2])
if vectors:
clusters = kmeans(vectors, clusters_count=clusters_count)
if len(vectors[0]) == 2:
display_source(vectors)
display_result(vectors, clusters)
else:
print('Invalid input', file=stderr)
...
|
589bfc0f5e57215aa69746e82100375d6f3b8cc9
|
kpub/tests/test_counts.py
|
kpub/tests/test_counts.py
|
import kpub
def test_annual_count():
# Does the cumulative count match the annual count?
db = kpub.PublicationDB()
annual = db.get_annual_publication_count()
cumul = db.get_annual_publication_count_cumulative()
assert annual['k2'][2010] == 0 # K2 didn't exist in 2010
# The first K2 papers started appearing in 2014; the cumulative counts should reflect that:
assert (annual['k2'][2014] + annual['k2'][2015]) == cumul['k2'][2015]
assert (annual['k2'][2014] + annual['k2'][2015] + annual['k2'][2016]) == cumul['k2'][2016]
# Are the values returned by get_metrics consistent?
for year in range(2009, 2019):
metrics = db.get_metrics(year=year)
assert metrics['publication_count'] == annual['both'][year]
assert metrics['kepler_count'] == annual['kepler'][year]
assert metrics['k2_count'] == annual['k2'][year]
|
import kpub
def test_annual_count():
# Does the cumulative count match the annual count?
db = kpub.PublicationDB()
annual = db.get_annual_publication_count()
cumul = db.get_annual_publication_count_cumulative()
assert annual['k2'][2010] == 0 # K2 didn't exist in 2010
# The first K2 papers started appearing in 2014; the cumulative counts should reflect that:
assert (annual['k2'][2014] + annual['k2'][2015]) == cumul['k2'][2015]
assert (annual['k2'][2014] + annual['k2'][2015] + annual['k2'][2016]) == cumul['k2'][2016]
# Are the values returned by get_metrics consistent?
for year in range(2009, 2019):
metrics = db.get_metrics(year=year)
assert metrics['publication_count'] == annual['both'][year]
assert metrics['kepler_count'] == annual['kepler'][year]
assert metrics['k2_count'] == annual['k2'][year]
# Can we pass multiple years to get_metrics?
metrics = db.get_metrics(year=[2011, 2012])
assert metrics['publication_count'] == annual['both'][2011] + annual['both'][2012]
|
Add a test for the new multi-year feature
|
Add a test for the new multi-year feature
|
Python
|
mit
|
KeplerGO/kpub
|
python
|
## Code Before:
import kpub
def test_annual_count():
# Does the cumulative count match the annual count?
db = kpub.PublicationDB()
annual = db.get_annual_publication_count()
cumul = db.get_annual_publication_count_cumulative()
assert annual['k2'][2010] == 0 # K2 didn't exist in 2010
# The first K2 papers started appearing in 2014; the cumulative counts should reflect that:
assert (annual['k2'][2014] + annual['k2'][2015]) == cumul['k2'][2015]
assert (annual['k2'][2014] + annual['k2'][2015] + annual['k2'][2016]) == cumul['k2'][2016]
# Are the values returned by get_metrics consistent?
for year in range(2009, 2019):
metrics = db.get_metrics(year=year)
assert metrics['publication_count'] == annual['both'][year]
assert metrics['kepler_count'] == annual['kepler'][year]
assert metrics['k2_count'] == annual['k2'][year]
## Instruction:
Add a test for the new multi-year feature
## Code After:
import kpub
def test_annual_count():
# Does the cumulative count match the annual count?
db = kpub.PublicationDB()
annual = db.get_annual_publication_count()
cumul = db.get_annual_publication_count_cumulative()
assert annual['k2'][2010] == 0 # K2 didn't exist in 2010
# The first K2 papers started appearing in 2014; the cumulative counts should reflect that:
assert (annual['k2'][2014] + annual['k2'][2015]) == cumul['k2'][2015]
assert (annual['k2'][2014] + annual['k2'][2015] + annual['k2'][2016]) == cumul['k2'][2016]
# Are the values returned by get_metrics consistent?
for year in range(2009, 2019):
metrics = db.get_metrics(year=year)
assert metrics['publication_count'] == annual['both'][year]
assert metrics['kepler_count'] == annual['kepler'][year]
assert metrics['k2_count'] == annual['k2'][year]
# Can we pass multiple years to get_metrics?
metrics = db.get_metrics(year=[2011, 2012])
assert metrics['publication_count'] == annual['both'][2011] + annual['both'][2012]
|
# ... existing code ...
assert metrics['publication_count'] == annual['both'][year]
assert metrics['kepler_count'] == annual['kepler'][year]
assert metrics['k2_count'] == annual['k2'][year]
# Can we pass multiple years to get_metrics?
metrics = db.get_metrics(year=[2011, 2012])
assert metrics['publication_count'] == annual['both'][2011] + annual['both'][2012]
# ... rest of the code ...
|
07c874a9c35c14c0eecae6028a42ad0cb8deed33
|
Source/PKMacros.h
|
Source/PKMacros.h
|
//
// PKMacros.h
// PKToolBox
//
// Created by Pavel Kunc on 17/07/2013.
// Copyright (c) 2013 PKToolBox. All rights reserved.
//
#define PK_NIL_IF_NULL(obj) ((obj == [NSNull null]) ? nil : obj)
#define PK_NULL_IF_NIL(obj) ((obj == nil) ? [NSNull null] : obj)
#define PK_BOOL_TO_LOCALIZED_STRING(val) ((val == YES) ? NSLocalizedString(@"Yes", nil) : NSLocalizedString(@"No", nil))
#define PK_IS_WIDESCREEN ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )
#define PK_IS_IPHONE ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone )
#define PK_IS_IPHONE_5 ( PK_IS_IPHONE && PK_IS_WIDESCREEN )
|
//
// PKMacros.h
// PKToolBox
//
// Created by Pavel Kunc on 17/07/2013.
// Copyright (c) 2013 PKToolBox. All rights reserved.
//
#define PK_NIL_IF_NULL(obj) ((obj == [NSNull null]) ? nil : obj)
#define PK_NULL_IF_NIL(obj) ((obj == nil) ? [NSNull null] : obj)
#define PK_BOOL_TO_LOCALIZED_STRING(val) ((val == YES) ? NSLocalizedString(@"Yes", nil) : NSLocalizedString(@"No", nil))
#define PK_IS_WIDESCREEN ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )
#define PK_IS_IPHONE ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone )
#define PK_IS_IPHONE_5 ( PK_IS_IPHONE && PK_IS_WIDESCREEN )
#define PK_IS_IOS7 ( floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1 )
|
Add new macro to detect iOS7.
|
Add new macro to detect iOS7.
|
C
|
mit
|
prajput/pkCode,pk/pktoolbox,prajput/pkCode,pk/pktoolbox
|
c
|
## Code Before:
//
// PKMacros.h
// PKToolBox
//
// Created by Pavel Kunc on 17/07/2013.
// Copyright (c) 2013 PKToolBox. All rights reserved.
//
#define PK_NIL_IF_NULL(obj) ((obj == [NSNull null]) ? nil : obj)
#define PK_NULL_IF_NIL(obj) ((obj == nil) ? [NSNull null] : obj)
#define PK_BOOL_TO_LOCALIZED_STRING(val) ((val == YES) ? NSLocalizedString(@"Yes", nil) : NSLocalizedString(@"No", nil))
#define PK_IS_WIDESCREEN ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )
#define PK_IS_IPHONE ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone )
#define PK_IS_IPHONE_5 ( PK_IS_IPHONE && PK_IS_WIDESCREEN )
## Instruction:
Add new macro to detect iOS7.
## Code After:
//
// PKMacros.h
// PKToolBox
//
// Created by Pavel Kunc on 17/07/2013.
// Copyright (c) 2013 PKToolBox. All rights reserved.
//
#define PK_NIL_IF_NULL(obj) ((obj == [NSNull null]) ? nil : obj)
#define PK_NULL_IF_NIL(obj) ((obj == nil) ? [NSNull null] : obj)
#define PK_BOOL_TO_LOCALIZED_STRING(val) ((val == YES) ? NSLocalizedString(@"Yes", nil) : NSLocalizedString(@"No", nil))
#define PK_IS_WIDESCREEN ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )
#define PK_IS_IPHONE ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone )
#define PK_IS_IPHONE_5 ( PK_IS_IPHONE && PK_IS_WIDESCREEN )
#define PK_IS_IOS7 ( floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1 )
|
// ... existing code ...
#define PK_IS_IPHONE ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone )
#define PK_IS_IPHONE_5 ( PK_IS_IPHONE && PK_IS_WIDESCREEN )
#define PK_IS_IOS7 ( floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1 )
// ... rest of the code ...
|
5a88126b53bbd47a4c8899b50bdbf0d913183bd5
|
norm/test/test_porcelain.py
|
norm/test/test_porcelain.py
|
from twisted.trial.unittest import TestCase
from twisted.internet import defer
import os
from norm.porcelain import makePool
postgres_url = os.environ.get('NORM_POSTGRESQL_URI', None)
skip_postgres = ('You must define NORM_POSTGRESQL_URI in order to run this '
'postgres test')
if postgres_url:
skip_postgres = ''
class PostgresTest(TestCase):
timeout = 2
skip = skip_postgres
@defer.inlineCallbacks
def test_basic(self):
pool = yield makePool(postgres_url)
yield pool.runOperation('''CREATE TEMPORARY TABLE porc1 (
id serial primary key,
created timestamp default current_timestamp,
name text
)''')
def interaction(cursor, name):
d = cursor.execute('insert into foo (name) values (?)', (name,))
d.addCallback(lambda _: cursor.lastRowId())
return d
rowid = yield pool.runInteraction(interaction, 'bob')
rows = yield pool.runQuery('select id, name from foo where id = ?', (rowid,))
self.assertEqual(rows, [(rowid, 'bob')])
|
from twisted.trial.unittest import TestCase
from twisted.internet import defer
import os
from norm.porcelain import makePool
postgres_url = os.environ.get('NORM_POSTGRESQL_URI', None)
skip_postgres = ('You must define NORM_POSTGRESQL_URI in order to run this '
'postgres test')
if postgres_url:
skip_postgres = ''
class PostgresTest(TestCase):
timeout = 2
skip = skip_postgres
@defer.inlineCallbacks
def test_basic(self):
pool = yield makePool(postgres_url)
yield pool.runOperation('''CREATE TEMPORARY TABLE porc1 (
id serial primary key,
created timestamp default current_timestamp,
name text
)''')
def interaction(cursor, name):
d = cursor.execute('insert into porc1 (name) values (?)', (name,))
d.addCallback(lambda _: cursor.lastRowId())
return d
rowid = yield pool.runInteraction(interaction, 'bob')
rows = yield pool.runQuery('select id, name from porc1 where id = ?', (rowid,))
self.assertEqual(rows, [(rowid, 'bob')])
class SqliteTest(TestCase):
timeout = 2
@defer.inlineCallbacks
def test_basic(self):
pool = yield makePool('sqlite:')
yield pool.runOperation('''CREATE TABLE porc1 (
id integer primary key,
created timestamp default current_timestamp,
name text
)''')
def interaction(cursor, name):
d = cursor.execute('insert into porc1 (name) values (?)', (name,))
d.addCallback(lambda _: cursor.lastRowId())
return d
rowid = yield pool.runInteraction(interaction, 'bob')
rows = yield pool.runQuery('select id, name from porc1 where id = ?', (rowid,))
self.assertEqual(rows, [(rowid, 'bob')])
|
Fix postgres porcelain test and add sqlite one
|
Fix postgres porcelain test and add sqlite one
|
Python
|
mit
|
iffy/norm,iffy/norm
|
python
|
## Code Before:
from twisted.trial.unittest import TestCase
from twisted.internet import defer
import os
from norm.porcelain import makePool
postgres_url = os.environ.get('NORM_POSTGRESQL_URI', None)
skip_postgres = ('You must define NORM_POSTGRESQL_URI in order to run this '
'postgres test')
if postgres_url:
skip_postgres = ''
class PostgresTest(TestCase):
timeout = 2
skip = skip_postgres
@defer.inlineCallbacks
def test_basic(self):
pool = yield makePool(postgres_url)
yield pool.runOperation('''CREATE TEMPORARY TABLE porc1 (
id serial primary key,
created timestamp default current_timestamp,
name text
)''')
def interaction(cursor, name):
d = cursor.execute('insert into foo (name) values (?)', (name,))
d.addCallback(lambda _: cursor.lastRowId())
return d
rowid = yield pool.runInteraction(interaction, 'bob')
rows = yield pool.runQuery('select id, name from foo where id = ?', (rowid,))
self.assertEqual(rows, [(rowid, 'bob')])
## Instruction:
Fix postgres porcelain test and add sqlite one
## Code After:
from twisted.trial.unittest import TestCase
from twisted.internet import defer
import os
from norm.porcelain import makePool
postgres_url = os.environ.get('NORM_POSTGRESQL_URI', None)
skip_postgres = ('You must define NORM_POSTGRESQL_URI in order to run this '
'postgres test')
if postgres_url:
skip_postgres = ''
class PostgresTest(TestCase):
timeout = 2
skip = skip_postgres
@defer.inlineCallbacks
def test_basic(self):
pool = yield makePool(postgres_url)
yield pool.runOperation('''CREATE TEMPORARY TABLE porc1 (
id serial primary key,
created timestamp default current_timestamp,
name text
)''')
def interaction(cursor, name):
d = cursor.execute('insert into porc1 (name) values (?)', (name,))
d.addCallback(lambda _: cursor.lastRowId())
return d
rowid = yield pool.runInteraction(interaction, 'bob')
rows = yield pool.runQuery('select id, name from porc1 where id = ?', (rowid,))
self.assertEqual(rows, [(rowid, 'bob')])
class SqliteTest(TestCase):
timeout = 2
@defer.inlineCallbacks
def test_basic(self):
pool = yield makePool('sqlite:')
yield pool.runOperation('''CREATE TABLE porc1 (
id integer primary key,
created timestamp default current_timestamp,
name text
)''')
def interaction(cursor, name):
d = cursor.execute('insert into porc1 (name) values (?)', (name,))
d.addCallback(lambda _: cursor.lastRowId())
return d
rowid = yield pool.runInteraction(interaction, 'bob')
rows = yield pool.runQuery('select id, name from porc1 where id = ?', (rowid,))
self.assertEqual(rows, [(rowid, 'bob')])
|
...
)''')
def interaction(cursor, name):
d = cursor.execute('insert into porc1 (name) values (?)', (name,))
d.addCallback(lambda _: cursor.lastRowId())
return d
rowid = yield pool.runInteraction(interaction, 'bob')
rows = yield pool.runQuery('select id, name from porc1 where id = ?', (rowid,))
self.assertEqual(rows, [(rowid, 'bob')])
class SqliteTest(TestCase):
timeout = 2
@defer.inlineCallbacks
def test_basic(self):
pool = yield makePool('sqlite:')
yield pool.runOperation('''CREATE TABLE porc1 (
id integer primary key,
created timestamp default current_timestamp,
name text
)''')
def interaction(cursor, name):
d = cursor.execute('insert into porc1 (name) values (?)', (name,))
d.addCallback(lambda _: cursor.lastRowId())
return d
rowid = yield pool.runInteraction(interaction, 'bob')
rows = yield pool.runQuery('select id, name from porc1 where id = ?', (rowid,))
self.assertEqual(rows, [(rowid, 'bob')])
...
|
665574a7d5f0f5959a3ca63c2f55844a4323cc6c
|
cracking-the-coding-interview/src/chapter_5/Insertion.java
|
cracking-the-coding-interview/src/chapter_5/Insertion.java
|
package chapter_5;
public class Insertion {
public String insertMIntoN(int m, int n, int i, int j) {
int result = clearBits(n, i, j);
return Integer.toBinaryString(result | (m << i));
}
private int clearBits(int n, int i, int j) {
int val = Integer.MAX_VALUE >>> (31 - j - 1);
int val2 = Integer.MAX_VALUE << i;
int mask = val & val2;
return n & ~(mask);
}
}
|
package chapter_5;
public class Insertion {
public String insertMIntoN(int m, int n, int i, int j) {
int result = clearBits(n, i, j);
return Integer.toBinaryString(result | (m << i));
}
private int clearBits(int n, int i, int j) {
int val = ~(0) >>> (31 - j);
int val2 = ~(0) << i;
int mask = val & val2;
return n & ~(mask);
}
}
|
Use ~0 instead of integer max value, Use Logical right shift which is important here
|
Use ~0 instead of integer max value, Use Logical right shift which is important here
|
Java
|
mit
|
scaffeinate/crack-the-code
|
java
|
## Code Before:
package chapter_5;
public class Insertion {
public String insertMIntoN(int m, int n, int i, int j) {
int result = clearBits(n, i, j);
return Integer.toBinaryString(result | (m << i));
}
private int clearBits(int n, int i, int j) {
int val = Integer.MAX_VALUE >>> (31 - j - 1);
int val2 = Integer.MAX_VALUE << i;
int mask = val & val2;
return n & ~(mask);
}
}
## Instruction:
Use ~0 instead of integer max value, Use Logical right shift which is important here
## Code After:
package chapter_5;
public class Insertion {
public String insertMIntoN(int m, int n, int i, int j) {
int result = clearBits(n, i, j);
return Integer.toBinaryString(result | (m << i));
}
private int clearBits(int n, int i, int j) {
int val = ~(0) >>> (31 - j);
int val2 = ~(0) << i;
int mask = val & val2;
return n & ~(mask);
}
}
|
// ... existing code ...
}
private int clearBits(int n, int i, int j) {
int val = ~(0) >>> (31 - j);
int val2 = ~(0) << i;
int mask = val & val2;
return n & ~(mask);
}
// ... rest of the code ...
|
733710b2daccb85fb0e48a0a4dd98ca10f6e6c9d
|
src/keyimpl.h
|
src/keyimpl.h
|
namespace JWTXX
{
struct Key::Impl
{
virtual std::string sign(const void* data, size_t size) const = 0;
virtual bool verify(const void* data, size_t size, const std::string& signature) const = 0;
};
}
|
namespace JWTXX
{
struct Key::Impl
{
virtual ~Impl() {}
virtual std::string sign(const void* data, size_t size) const = 0;
virtual bool verify(const void* data, size_t size, const std::string& signature) const = 0;
};
}
|
Fix memory leak in key implementations.
|
Fix memory leak in key implementations.
|
C
|
mit
|
RealImage/jwtxx,RealImage/jwtxx,madf/jwtxx,madf/jwtxx
|
c
|
## Code Before:
namespace JWTXX
{
struct Key::Impl
{
virtual std::string sign(const void* data, size_t size) const = 0;
virtual bool verify(const void* data, size_t size, const std::string& signature) const = 0;
};
}
## Instruction:
Fix memory leak in key implementations.
## Code After:
namespace JWTXX
{
struct Key::Impl
{
virtual ~Impl() {}
virtual std::string sign(const void* data, size_t size) const = 0;
virtual bool verify(const void* data, size_t size, const std::string& signature) const = 0;
};
}
|
// ... existing code ...
struct Key::Impl
{
virtual ~Impl() {}
virtual std::string sign(const void* data, size_t size) const = 0;
virtual bool verify(const void* data, size_t size, const std::string& signature) const = 0;
};
// ... rest of the code ...
|
dd35907f9164cd8f75babb1b5b9b6ff9711628fb
|
djangopeople/djangopeople/management/commands/fix_counts.py
|
djangopeople/djangopeople/management/commands/fix_counts.py
|
from django.core.management.base import NoArgsCommand
from ...models import Country, Region
class Command(NoArgsCommand):
"""
Countries and regions keep a denormalized count of people that gets out of
sync during migrate. This updates it.
"""
def handle_noargs(self, **options):
for qs in (Country.objects.all(), Region.objects.all()):
for geo in qs:
qs.model.objects.filter(pk=geo.pk).update(
num_people=geo.djangoperson_set.count(),
)
|
from django.core.management.base import BaseCommand
from ...models import Country, Region
class Command(BaseCommand):
"""
Countries and regions keep a denormalized count of people that gets out of
sync during migrate. This updates it.
"""
def handle(self, **options):
for qs in (Country.objects.all(), Region.objects.all()):
for geo in qs:
qs.model.objects.filter(pk=geo.pk).update(
num_people=geo.djangoperson_set.count(),
)
|
Remove usage of deprecated NoArgsCommand
|
Remove usage of deprecated NoArgsCommand
|
Python
|
mit
|
brutasse/djangopeople,django/djangopeople,django/djangopeople,django/djangopeople,brutasse/djangopeople,brutasse/djangopeople,brutasse/djangopeople
|
python
|
## Code Before:
from django.core.management.base import NoArgsCommand
from ...models import Country, Region
class Command(NoArgsCommand):
"""
Countries and regions keep a denormalized count of people that gets out of
sync during migrate. This updates it.
"""
def handle_noargs(self, **options):
for qs in (Country.objects.all(), Region.objects.all()):
for geo in qs:
qs.model.objects.filter(pk=geo.pk).update(
num_people=geo.djangoperson_set.count(),
)
## Instruction:
Remove usage of deprecated NoArgsCommand
## Code After:
from django.core.management.base import BaseCommand
from ...models import Country, Region
class Command(BaseCommand):
"""
Countries and regions keep a denormalized count of people that gets out of
sync during migrate. This updates it.
"""
def handle(self, **options):
for qs in (Country.objects.all(), Region.objects.all()):
for geo in qs:
qs.model.objects.filter(pk=geo.pk).update(
num_people=geo.djangoperson_set.count(),
)
|
# ... existing code ...
from django.core.management.base import BaseCommand
from ...models import Country, Region
class Command(BaseCommand):
"""
Countries and regions keep a denormalized count of people that gets out of
sync during migrate. This updates it.
"""
def handle(self, **options):
for qs in (Country.objects.all(), Region.objects.all()):
for geo in qs:
qs.model.objects.filter(pk=geo.pk).update(
# ... rest of the code ...
|
3699cc594d9a4f02d24308cb41b8757124616f78
|
boltiot/requesting.py
|
boltiot/requesting.py
|
from boltiot.urls import url
import requests
def request_from(url, *kwargs):
try:
response = str(requests.get(url.format(*kwargs)).text)
return response
except requests.exceptions.ConnectionError as err:
return str({"success":"0", "message":"A Connection error occurred"})
except requests.exceptions.Timeout as err:
return str({"success":"0", "message":"The request timed out"})
except requests.exceptions.TooManyRedirects as err :
return str({"success":"0", "message":"Too many redirects"})
except requests.exceptions.RequestException as err:
return str({"success":"0", "message":"Not able to handle error"})
except Exception as err:
return str({"success":"0", "message":str(err)})
def request_test(function):
result = function
return result
|
from boltiot.urls import url
import requests
def request_from(url, *kwargs):
try:
response = str(requests.get(url.format(*kwargs)).text)
return response
except requests.exceptions.ConnectionError as err:
return str({"success":"0", "message":"A Connection error occurred"})
except requests.exceptions.Timeout as err:
return str({"success":"0", "message":"The request timed out"})
except requests.exceptions.TooManyRedirects as err :
return str({"success":"0", "message":"Too many redirects"})
except requests.exceptions.RequestException as err:
return str({"success":"0", "message":"Not able to handle error"})
except Exception as err:
return str({"success":"0", "message": "ERROR: " + str(err)})
def request_test(function):
result = function
return result
|
Add ERROR: keyword in error message return
|
Add ERROR: keyword in error message return
|
Python
|
mit
|
Inventrom/bolt-api-python
|
python
|
## Code Before:
from boltiot.urls import url
import requests
def request_from(url, *kwargs):
try:
response = str(requests.get(url.format(*kwargs)).text)
return response
except requests.exceptions.ConnectionError as err:
return str({"success":"0", "message":"A Connection error occurred"})
except requests.exceptions.Timeout as err:
return str({"success":"0", "message":"The request timed out"})
except requests.exceptions.TooManyRedirects as err :
return str({"success":"0", "message":"Too many redirects"})
except requests.exceptions.RequestException as err:
return str({"success":"0", "message":"Not able to handle error"})
except Exception as err:
return str({"success":"0", "message":str(err)})
def request_test(function):
result = function
return result
## Instruction:
Add ERROR: keyword in error message return
## Code After:
from boltiot.urls import url
import requests
def request_from(url, *kwargs):
try:
response = str(requests.get(url.format(*kwargs)).text)
return response
except requests.exceptions.ConnectionError as err:
return str({"success":"0", "message":"A Connection error occurred"})
except requests.exceptions.Timeout as err:
return str({"success":"0", "message":"The request timed out"})
except requests.exceptions.TooManyRedirects as err :
return str({"success":"0", "message":"Too many redirects"})
except requests.exceptions.RequestException as err:
return str({"success":"0", "message":"Not able to handle error"})
except Exception as err:
return str({"success":"0", "message": "ERROR: " + str(err)})
def request_test(function):
result = function
return result
|
// ... existing code ...
except requests.exceptions.RequestException as err:
return str({"success":"0", "message":"Not able to handle error"})
except Exception as err:
return str({"success":"0", "message": "ERROR: " + str(err)})
def request_test(function):
// ... rest of the code ...
|
3a8a7661c0aad111dbaace178062352b30f7fac5
|
numcodecs/tests/__init__.py
|
numcodecs/tests/__init__.py
|
from __future__ import absolute_import, print_function, division
|
from __future__ import absolute_import, print_function, division
import pytest
pytest.register_assert_rewrite('numcodecs.tests.common')
|
Enable pytest rewriting in test helper functions.
|
Enable pytest rewriting in test helper functions.
|
Python
|
mit
|
alimanfoo/numcodecs,zarr-developers/numcodecs,alimanfoo/numcodecs
|
python
|
## Code Before:
from __future__ import absolute_import, print_function, division
## Instruction:
Enable pytest rewriting in test helper functions.
## Code After:
from __future__ import absolute_import, print_function, division
import pytest
pytest.register_assert_rewrite('numcodecs.tests.common')
|
// ... existing code ...
from __future__ import absolute_import, print_function, division
import pytest
pytest.register_assert_rewrite('numcodecs.tests.common')
// ... rest of the code ...
|
f2a4362f52cf4c4309bedfec292abdb3d5ea0146
|
c2s-ui-api/src/main/java/gov/samhsa/c2s/c2suiapi/service/PhrServiceImpl.java
|
c2s-ui-api/src/main/java/gov/samhsa/c2s/c2suiapi/service/PhrServiceImpl.java
|
package gov.samhsa.c2s.c2suiapi.service;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import feign.FeignException;
import gov.samhsa.c2s.c2suiapi.infrastructure.PhrClient;
import gov.samhsa.c2s.c2suiapi.service.exception.NoDocumentsFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PhrServiceImpl implements PhrService{
private final PhrClient phrClient;
@Autowired
public PhrServiceImpl(PhrClient phrClient) {
this.phrClient = phrClient;
}
@Override
public List<Object> getAllDocumentTypeCodesList(){
return phrClient.getAllDocumentTypeCodesList();
}
@Override
public List<Object> getPatientDocumentInfoList(String patientMrn){
try{
return phrClient.getPatientDocumentInfoList(patientMrn);
}catch(HystrixRuntimeException err) {
Throwable t = err.getCause();
if(t instanceof FeignException && ((FeignException) t).status() == 404){
throw new NoDocumentsFoundException(t.getMessage());
}
}
return null;
}
}
|
package gov.samhsa.c2s.c2suiapi.service;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import feign.FeignException;
import gov.samhsa.c2s.c2suiapi.infrastructure.PhrClient;
import gov.samhsa.c2s.c2suiapi.service.exception.NoDocumentsFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PhrServiceImpl implements PhrService{
private final PhrClient phrClient;
@Autowired
public PhrServiceImpl(PhrClient phrClient) {
this.phrClient = phrClient;
}
@Override
public List<Object> getAllDocumentTypeCodesList(){
return phrClient.getAllDocumentTypeCodesList();
}
@Override
public List<Object> getPatientDocumentInfoList(String patientMrn){
List<Object> uploadedDocuments = null;
try{
uploadedDocuments = phrClient.getPatientDocumentInfoList(patientMrn);
}catch(HystrixRuntimeException err) {
Throwable t = err.getCause();
if(t instanceof FeignException && ((FeignException) t).status() == 404){
throw new NoDocumentsFoundException(t.getMessage());
}
}
return uploadedDocuments;
}
}
|
Split into declaration and assignment
|
Split into declaration and assignment
#13763:As a developer, I will have implemented the Try My Policy UI and integrated with backend [v3.0]
|
Java
|
apache-2.0
|
bhits-dev/c2s-ui-api-test,bhits-dev/c2s-ui-api-test
|
java
|
## Code Before:
package gov.samhsa.c2s.c2suiapi.service;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import feign.FeignException;
import gov.samhsa.c2s.c2suiapi.infrastructure.PhrClient;
import gov.samhsa.c2s.c2suiapi.service.exception.NoDocumentsFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PhrServiceImpl implements PhrService{
private final PhrClient phrClient;
@Autowired
public PhrServiceImpl(PhrClient phrClient) {
this.phrClient = phrClient;
}
@Override
public List<Object> getAllDocumentTypeCodesList(){
return phrClient.getAllDocumentTypeCodesList();
}
@Override
public List<Object> getPatientDocumentInfoList(String patientMrn){
try{
return phrClient.getPatientDocumentInfoList(patientMrn);
}catch(HystrixRuntimeException err) {
Throwable t = err.getCause();
if(t instanceof FeignException && ((FeignException) t).status() == 404){
throw new NoDocumentsFoundException(t.getMessage());
}
}
return null;
}
}
## Instruction:
Split into declaration and assignment
#13763:As a developer, I will have implemented the Try My Policy UI and integrated with backend [v3.0]
## Code After:
package gov.samhsa.c2s.c2suiapi.service;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import feign.FeignException;
import gov.samhsa.c2s.c2suiapi.infrastructure.PhrClient;
import gov.samhsa.c2s.c2suiapi.service.exception.NoDocumentsFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PhrServiceImpl implements PhrService{
private final PhrClient phrClient;
@Autowired
public PhrServiceImpl(PhrClient phrClient) {
this.phrClient = phrClient;
}
@Override
public List<Object> getAllDocumentTypeCodesList(){
return phrClient.getAllDocumentTypeCodesList();
}
@Override
public List<Object> getPatientDocumentInfoList(String patientMrn){
List<Object> uploadedDocuments = null;
try{
uploadedDocuments = phrClient.getPatientDocumentInfoList(patientMrn);
}catch(HystrixRuntimeException err) {
Throwable t = err.getCause();
if(t instanceof FeignException && ((FeignException) t).status() == 404){
throw new NoDocumentsFoundException(t.getMessage());
}
}
return uploadedDocuments;
}
}
|
// ... existing code ...
@Override
public List<Object> getPatientDocumentInfoList(String patientMrn){
List<Object> uploadedDocuments = null;
try{
uploadedDocuments = phrClient.getPatientDocumentInfoList(patientMrn);
}catch(HystrixRuntimeException err) {
Throwable t = err.getCause();
if(t instanceof FeignException && ((FeignException) t).status() == 404){
// ... modified code ...
throw new NoDocumentsFoundException(t.getMessage());
}
}
return uploadedDocuments;
}
}
// ... rest of the code ...
|
3263a691db55ed72c4f98096748ad930c7ecdd68
|
setup.py
|
setup.py
|
import os.path
from distutils.core import setup
README = open(os.path.join(os.path.dirname(__file__), "README.rst")).read()
CLASSIFIERS = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
]
import ptch
VERSION = ptch.__version__
setup(
name = "python-ptch",
py_modules = ["ptch"],
author = "Jerome Leclanche",
author_email = "[email protected]",
classifiers = CLASSIFIERS,
description = "Blizzard BSDIFF-based PTCH file format support",
download_url = "http://github.com/Adys/python-ptch/tarball/master",
long_description = README,
url = "http://github.com/Adys/python-ptch",
version = VERSION,
)
|
import os.path
from distutils.core import setup
README = open(os.path.join(os.path.dirname(__file__), "README.rst")).read()
CLASSIFIERS = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
]
import ptch
VERSION = ptch.__version__
setup(
name = "python-ptch",
py_modules = ["ptch"],
author = "Jerome Leclanche",
author_email = "[email protected]",
classifiers = CLASSIFIERS,
description = "Blizzard BSDIFF-based PTCH file format support",
download_url = "https://github.com/jleclanche/python-ptch/tarball/master",
long_description = README,
url = "https://github.com/jleclanche/python-ptch",
version = VERSION,
)
|
Update repository addresses and emails
|
Update repository addresses and emails
|
Python
|
mit
|
jleclanche/python-ptch
|
python
|
## Code Before:
import os.path
from distutils.core import setup
README = open(os.path.join(os.path.dirname(__file__), "README.rst")).read()
CLASSIFIERS = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
]
import ptch
VERSION = ptch.__version__
setup(
name = "python-ptch",
py_modules = ["ptch"],
author = "Jerome Leclanche",
author_email = "[email protected]",
classifiers = CLASSIFIERS,
description = "Blizzard BSDIFF-based PTCH file format support",
download_url = "http://github.com/Adys/python-ptch/tarball/master",
long_description = README,
url = "http://github.com/Adys/python-ptch",
version = VERSION,
)
## Instruction:
Update repository addresses and emails
## Code After:
import os.path
from distutils.core import setup
README = open(os.path.join(os.path.dirname(__file__), "README.rst")).read()
CLASSIFIERS = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
]
import ptch
VERSION = ptch.__version__
setup(
name = "python-ptch",
py_modules = ["ptch"],
author = "Jerome Leclanche",
author_email = "[email protected]",
classifiers = CLASSIFIERS,
description = "Blizzard BSDIFF-based PTCH file format support",
download_url = "https://github.com/jleclanche/python-ptch/tarball/master",
long_description = README,
url = "https://github.com/jleclanche/python-ptch",
version = VERSION,
)
|
// ... existing code ...
name = "python-ptch",
py_modules = ["ptch"],
author = "Jerome Leclanche",
author_email = "[email protected]",
classifiers = CLASSIFIERS,
description = "Blizzard BSDIFF-based PTCH file format support",
download_url = "https://github.com/jleclanche/python-ptch/tarball/master",
long_description = README,
url = "https://github.com/jleclanche/python-ptch",
version = VERSION,
)
// ... rest of the code ...
|
f035ea7fb453d09b37f5187c4f61e855b048cbd5
|
aslo/web/__init__.py
|
aslo/web/__init__.py
|
from flask import Blueprint, g
web = Blueprint('web', __name__, template_folder='templates',
static_folder='static',
static_url_path='/web/static',
url_prefix='/<lang_code>')
@web.url_defaults
def add_language_code(endpoint, values):
values.setdefault('lang_code', g.lang_code)
@web.url_value_preprocessor
def pull_lang_code(point, values):
g.lang_code = values.pop('lang_code')
if not g.lang_code.strip():
print("No code :(")
g.lang_code = 'en'
from . import views # noqa
|
from flask import Blueprint, g, session
web = Blueprint('web', __name__, template_folder='templates',
static_folder='static',
static_url_path='/web/static',
url_prefix='/<lang_code>')
@web.url_defaults
def add_language_code(endpoint, values):
values.setdefault('lang_code', g.lang_code)
@web.url_value_preprocessor
def pull_lang_code(point, values):
g.lang_code = values.pop('lang_code')
# Tie user session to a particular language,
# so it can be retrived when we pop the request values
session['lang_code'] = g.lang_code
from . import views # noqa
|
Use sessions to Tie it a with language. Also helps us to retrieve session code later " "
|
Use sessions to Tie it a with language. Also helps us to retrieve session code later "
"
|
Python
|
mit
|
jatindhankhar/aslo-v3,jatindhankhar/aslo-v3,jatindhankhar/aslo-v3,jatindhankhar/aslo-v3
|
python
|
## Code Before:
from flask import Blueprint, g
web = Blueprint('web', __name__, template_folder='templates',
static_folder='static',
static_url_path='/web/static',
url_prefix='/<lang_code>')
@web.url_defaults
def add_language_code(endpoint, values):
values.setdefault('lang_code', g.lang_code)
@web.url_value_preprocessor
def pull_lang_code(point, values):
g.lang_code = values.pop('lang_code')
if not g.lang_code.strip():
print("No code :(")
g.lang_code = 'en'
from . import views # noqa
## Instruction:
Use sessions to Tie it a with language. Also helps us to retrieve session code later "
"
## Code After:
from flask import Blueprint, g, session
web = Blueprint('web', __name__, template_folder='templates',
static_folder='static',
static_url_path='/web/static',
url_prefix='/<lang_code>')
@web.url_defaults
def add_language_code(endpoint, values):
values.setdefault('lang_code', g.lang_code)
@web.url_value_preprocessor
def pull_lang_code(point, values):
g.lang_code = values.pop('lang_code')
# Tie user session to a particular language,
# so it can be retrived when we pop the request values
session['lang_code'] = g.lang_code
from . import views # noqa
|
# ... existing code ...
from flask import Blueprint, g, session
web = Blueprint('web', __name__, template_folder='templates',
static_folder='static',
# ... modified code ...
@web.url_value_preprocessor
def pull_lang_code(point, values):
g.lang_code = values.pop('lang_code')
# Tie user session to a particular language,
# so it can be retrived when we pop the request values
session['lang_code'] = g.lang_code
from . import views # noqa
# ... rest of the code ...
|
7d8d5516a279cf1349af703f9051bb1acf084eaa
|
tests/test_browser_test_case.py
|
tests/test_browser_test_case.py
|
from unittest import TestCase
from keteparaha.browser import BrowserTestCase
class BrowserTestCaseTest(TestCase):
class SubClassed(BrowserTestCase):
def do_nothing(self):
pass
def test_start_browser_when_given_unsupported_driver(self):
bc = self.SubClassed("do_nothing")
with self.assertRaises(ValueError):
bc.start_browser(driver="NoReal")
self.assertEqual(bc._browsers, [])
def test_browser_is_cleaned_up_afterwards(self):
bc = self.SubClassed("do_nothing")
bc.start_browser("Firefox")
bc.doCleanups()
with self.assertRaises(Exception):
bc.title
|
from unittest import TestCase
from keteparaha.browser import BrowserTestCase
class SubClassed(BrowserTestCase):
def do_nothing(self):
pass
class BrowserTestCaseTest(TestCase):
def test_browser_returns_last_browser_started(self):
btc = SubClassed('do_nothing')
btc.browsers.append('b1')
btc.browsers.append('b2')
btc.browsers.append('b3')
self.assertEqual(btc.browser, 'b3')
|
Modify tests for the BrowserTestCase class so they don't hang
|
Modify tests for the BrowserTestCase class so they don't hang
|
Python
|
mit
|
aychedee/keteparaha,tomdottom/keteparaha
|
python
|
## Code Before:
from unittest import TestCase
from keteparaha.browser import BrowserTestCase
class BrowserTestCaseTest(TestCase):
class SubClassed(BrowserTestCase):
def do_nothing(self):
pass
def test_start_browser_when_given_unsupported_driver(self):
bc = self.SubClassed("do_nothing")
with self.assertRaises(ValueError):
bc.start_browser(driver="NoReal")
self.assertEqual(bc._browsers, [])
def test_browser_is_cleaned_up_afterwards(self):
bc = self.SubClassed("do_nothing")
bc.start_browser("Firefox")
bc.doCleanups()
with self.assertRaises(Exception):
bc.title
## Instruction:
Modify tests for the BrowserTestCase class so they don't hang
## Code After:
from unittest import TestCase
from keteparaha.browser import BrowserTestCase
class SubClassed(BrowserTestCase):
def do_nothing(self):
pass
class BrowserTestCaseTest(TestCase):
def test_browser_returns_last_browser_started(self):
btc = SubClassed('do_nothing')
btc.browsers.append('b1')
btc.browsers.append('b2')
btc.browsers.append('b3')
self.assertEqual(btc.browser, 'b3')
|
...
from keteparaha.browser import BrowserTestCase
class SubClassed(BrowserTestCase):
def do_nothing(self):
pass
class BrowserTestCaseTest(TestCase):
def test_browser_returns_last_browser_started(self):
btc = SubClassed('do_nothing')
btc.browsers.append('b1')
btc.browsers.append('b2')
btc.browsers.append('b3')
self.assertEqual(btc.browser, 'b3')
...
|
cfc95643733244275e605a8ff0c00d4861067a13
|
character_shift/character_shift.py
|
character_shift/character_shift.py
|
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c.upper())-65+key*(1-2*decipher)) % 26+65+32*c.islower())
if c.isalpha() else c for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
assert shift('ABCZ+', 1) == 'BCDA+', shift('ABCZ+', 1)
assert shift('bcda+', 1, True) == 'abcz+', shift('bcda+', 1, True)
|
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c) & 224)+((ord(c) & 31)+25+key*(-2*decipher+1)*c.isalpha())
% 26+1) for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
assert shift('ABCZ+', 1) == 'BCDA+', shift('ABCZ+', 1)
assert shift('bcda+', 1, True) == 'abcz+', shift('bcda+', 1, True)
|
Use bitwise operators on ordinals to reduce code size
|
Use bitwise operators on ordinals to reduce code size
The ASCII standard neatly organizes the characters in such a way
that it is easy to manipulate and classify them using bitwise
operators.
|
Python
|
mit
|
TotempaaltJ/tiniest-code,TotempaaltJ/tiniest-code
|
python
|
## Code Before:
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c.upper())-65+key*(1-2*decipher)) % 26+65+32*c.islower())
if c.isalpha() else c for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
assert shift('ABCZ+', 1) == 'BCDA+', shift('ABCZ+', 1)
assert shift('bcda+', 1, True) == 'abcz+', shift('bcda+', 1, True)
## Instruction:
Use bitwise operators on ordinals to reduce code size
The ASCII standard neatly organizes the characters in such a way
that it is easy to manipulate and classify them using bitwise
operators.
## Code After:
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c) & 224)+((ord(c) & 31)+25+key*(-2*decipher+1)*c.isalpha())
% 26+1) for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
assert shift('ABCZ+', 1) == 'BCDA+', shift('ABCZ+', 1)
assert shift('bcda+', 1, True) == 'abcz+', shift('bcda+', 1, True)
|
# ... existing code ...
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c) & 224)+((ord(c) & 31)+25+key*(-2*decipher+1)*c.isalpha())
% 26+1) for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
# ... rest of the code ...
|
61a6d057302767aa49633d6d010f7da583035533
|
web/templatetags/getattribute.py
|
web/templatetags/getattribute.py
|
import re
from django import template
from django.conf import settings
numeric_test = re.compile("^\d+$")
register = template.Library()
def getattribute(value, arg):
"""Gets an attribute of an object dynamically from a string name"""
if hasattr(value, str(arg)):
return getattr(value, arg)
elif hasattr(value, 'has_key') and value.has_key(arg):
return value[arg]
elif numeric_test.match(str(arg)) and len(value) > int(arg):
return value[int(arg)]
else:
return settings.TEMPLATE_STRING_IF_INVALID
register.filter('getattribute', getattribute)
# Then, in template:
# {% load getattribute %}
# {{ object|getattribute:dynamic_string_var }}
|
import re
from django import template
from django.conf import settings
numeric_test = re.compile("^\d+$")
register = template.Library()
def getattribute(value, arg):
"""Gets an attribute of an object dynamically from a string name"""
if hasattr(value, str(arg)):
if callable(getattr(value, arg)):
return getattr(value, arg)()
return getattr(value, arg)
elif hasattr(value, 'has_key') and value.has_key(arg):
return value[arg]
elif numeric_test.match(str(arg)) and len(value) > int(arg):
return value[int(arg)]
else:
return settings.TEMPLATE_STRING_IF_INVALID
register.filter('getattribute', getattribute)
# Then, in template:
# {% load getattribute %}
# {{ object|getattribute:dynamic_string_var }}
|
Call objects methods directly from the templates yay
|
web: Call objects methods directly from the templates yay
|
Python
|
apache-2.0
|
SchoolIdolTomodachi/SchoolIdolAPI,laurenor/SchoolIdolAPI,dburr/SchoolIdolAPI,laurenor/SchoolIdolAPI,rdsathene/SchoolIdolAPI,SchoolIdolTomodachi/SchoolIdolAPI,SchoolIdolTomodachi/SchoolIdolAPI,rdsathene/SchoolIdolAPI,rdsathene/SchoolIdolAPI,dburr/SchoolIdolAPI,dburr/SchoolIdolAPI,laurenor/SchoolIdolAPI
|
python
|
## Code Before:
import re
from django import template
from django.conf import settings
numeric_test = re.compile("^\d+$")
register = template.Library()
def getattribute(value, arg):
"""Gets an attribute of an object dynamically from a string name"""
if hasattr(value, str(arg)):
return getattr(value, arg)
elif hasattr(value, 'has_key') and value.has_key(arg):
return value[arg]
elif numeric_test.match(str(arg)) and len(value) > int(arg):
return value[int(arg)]
else:
return settings.TEMPLATE_STRING_IF_INVALID
register.filter('getattribute', getattribute)
# Then, in template:
# {% load getattribute %}
# {{ object|getattribute:dynamic_string_var }}
## Instruction:
web: Call objects methods directly from the templates yay
## Code After:
import re
from django import template
from django.conf import settings
numeric_test = re.compile("^\d+$")
register = template.Library()
def getattribute(value, arg):
"""Gets an attribute of an object dynamically from a string name"""
if hasattr(value, str(arg)):
if callable(getattr(value, arg)):
return getattr(value, arg)()
return getattr(value, arg)
elif hasattr(value, 'has_key') and value.has_key(arg):
return value[arg]
elif numeric_test.match(str(arg)) and len(value) > int(arg):
return value[int(arg)]
else:
return settings.TEMPLATE_STRING_IF_INVALID
register.filter('getattribute', getattribute)
# Then, in template:
# {% load getattribute %}
# {{ object|getattribute:dynamic_string_var }}
|
// ... existing code ...
"""Gets an attribute of an object dynamically from a string name"""
if hasattr(value, str(arg)):
if callable(getattr(value, arg)):
return getattr(value, arg)()
return getattr(value, arg)
elif hasattr(value, 'has_key') and value.has_key(arg):
return value[arg]
// ... rest of the code ...
|
564ea9613e15ec2ccee31827354de6fb9ccfcdaa
|
src/de/gurkenlabs/litiengine/entities/PropState.java
|
src/de/gurkenlabs/litiengine/entities/PropState.java
|
package de.gurkenlabs.litiengine.entities;
public enum PropState {
INTACT,
DAMAGED,
DESTROYED;
public String spriteString() {
return this.name().toLowerCase();
}
}
|
package de.gurkenlabs.litiengine.entities;
public enum PropState {
INTACT,
DAMAGED,
DESTROYED;
private final String str;
private PropState() {
this.str = this.name().toLowerCase();
}
public String spriteString() {
return this.str;
}
}
|
Store lower-case string because conversion takes time.
|
Store lower-case string because conversion takes time.
|
Java
|
mit
|
gurkenlabs/litiengine,gurkenlabs/litiengine
|
java
|
## Code Before:
package de.gurkenlabs.litiengine.entities;
public enum PropState {
INTACT,
DAMAGED,
DESTROYED;
public String spriteString() {
return this.name().toLowerCase();
}
}
## Instruction:
Store lower-case string because conversion takes time.
## Code After:
package de.gurkenlabs.litiengine.entities;
public enum PropState {
INTACT,
DAMAGED,
DESTROYED;
private final String str;
private PropState() {
this.str = this.name().toLowerCase();
}
public String spriteString() {
return this.str;
}
}
|
# ... existing code ...
DAMAGED,
DESTROYED;
private final String str;
private PropState() {
this.str = this.name().toLowerCase();
}
public String spriteString() {
return this.str;
}
}
# ... rest of the code ...
|
7755dda1449f6264d7d7fe57dc776c731ab22d84
|
src/satosa/micro_services/processors/scope_processor.py
|
src/satosa/micro_services/processors/scope_processor.py
|
from ..attribute_processor import AttributeProcessorError
from .base_processor import BaseProcessor
CONFIG_KEY_SCOPE = 'scope'
CONFIG_DEFAULT_SCOPE = ''
class ScopeProcessor(BaseProcessor):
def process(self, internal_data, attribute, **kwargs):
scope = kwargs.get(CONFIG_KEY_SCOPE, CONFIG_DEFAULT_SCOPE)
if scope is None or scope == '':
raise AttributeProcessorError("No scope set.")
attributes = internal_data.attributes
value = attributes.get(attribute, [None])[0]
attributes[attribute][0] = value + '@' + scope
|
from ..attribute_processor import AttributeProcessorError
from .base_processor import BaseProcessor
CONFIG_KEY_SCOPE = 'scope'
CONFIG_DEFAULT_SCOPE = ''
class ScopeProcessor(BaseProcessor):
def process(self, internal_data, attribute, **kwargs):
scope = kwargs.get(CONFIG_KEY_SCOPE, CONFIG_DEFAULT_SCOPE)
if scope is None or scope == '':
raise AttributeProcessorError("No scope set.")
attributes = internal_data.attributes
values = attributes.get(attribute, [])
if not isinstance(values, list):
values = [values]
if values:
new_values=[]
for value in values:
new_values.append(value + '@' + scope)
attributes[attribute] = new_values
|
Allow scope processor to handle multivalued attributes
|
Allow scope processor to handle multivalued attributes
|
Python
|
apache-2.0
|
its-dirg/SATOSA,irtnog/SATOSA,SUNET/SATOSA,SUNET/SATOSA,irtnog/SATOSA
|
python
|
## Code Before:
from ..attribute_processor import AttributeProcessorError
from .base_processor import BaseProcessor
CONFIG_KEY_SCOPE = 'scope'
CONFIG_DEFAULT_SCOPE = ''
class ScopeProcessor(BaseProcessor):
def process(self, internal_data, attribute, **kwargs):
scope = kwargs.get(CONFIG_KEY_SCOPE, CONFIG_DEFAULT_SCOPE)
if scope is None or scope == '':
raise AttributeProcessorError("No scope set.")
attributes = internal_data.attributes
value = attributes.get(attribute, [None])[0]
attributes[attribute][0] = value + '@' + scope
## Instruction:
Allow scope processor to handle multivalued attributes
## Code After:
from ..attribute_processor import AttributeProcessorError
from .base_processor import BaseProcessor
CONFIG_KEY_SCOPE = 'scope'
CONFIG_DEFAULT_SCOPE = ''
class ScopeProcessor(BaseProcessor):
def process(self, internal_data, attribute, **kwargs):
scope = kwargs.get(CONFIG_KEY_SCOPE, CONFIG_DEFAULT_SCOPE)
if scope is None or scope == '':
raise AttributeProcessorError("No scope set.")
attributes = internal_data.attributes
values = attributes.get(attribute, [])
if not isinstance(values, list):
values = [values]
if values:
new_values=[]
for value in values:
new_values.append(value + '@' + scope)
attributes[attribute] = new_values
|
# ... existing code ...
raise AttributeProcessorError("No scope set.")
attributes = internal_data.attributes
values = attributes.get(attribute, [])
if not isinstance(values, list):
values = [values]
if values:
new_values=[]
for value in values:
new_values.append(value + '@' + scope)
attributes[attribute] = new_values
# ... rest of the code ...
|
4a4eca6fb920d7ba50e97a5bcb0ae8161715ff7a
|
citenet/neighborrank.py
|
citenet/neighborrank.py
|
import networkx as nx
import util
def neighborrank(graph, n=100, neighborhood_depth=2):
"""Compute the NeighborRank of the top n nodes in graph, using the
specified neighborhood_depth."""
# Get top n nodes with highest indegree (most often cited).
nodes = util.top_n_from_dict(graph.in_degree(), n=n)
# Find neighborhood sizes.
nhood_sizes = {}
for root in nodes:
# Neighborhood begins with just the root.
nhood = set([root])
# Expand the neighborhood repeatedly until the depth is reached.
for i in range(neighborhood_depth):
prev_nhood = nhood.copy()
for node in prev_nhood:
nhood |= set(graph.successors(node))
# Update the results dict.
nhood_sizes[root] = len(nhood)
return nhood_sizes
|
import networkx as nx
import util
def neighborrank(graph, n=100, neighborhood_depth=2):
"""Compute the NeighborRank of the top n nodes in graph, using the
specified neighborhood_depth."""
# Get top n nodes with highest outdegree (most often cited).
nodes = util.top_n_from_dict(graph.out_degree(), n=n)
# Find neighborhood sizes.
nhood_sizes = {}
for root in nodes:
# Neighborhood begins with just the root.
nhood = set([root])
# Expand the neighborhood repeatedly until the depth is reached.
for i in range(neighborhood_depth):
prev_nhood = nhood.copy()
for node in prev_nhood:
nhood |= set(graph.predecessors(node))
# Update the results dict.
nhood_sizes[root] = len(nhood)
return nhood_sizes
|
Switch in/out degree for neighbor rank
|
Switch in/out degree for neighbor rank
Edges point in the direction of time, or influence. That means we're
concerned with outdegree (amount of nodes influenced by the current
node), not indegree (amount of nodes that influence the current node).
|
Python
|
mit
|
Pringley/citenet
|
python
|
## Code Before:
import networkx as nx
import util
def neighborrank(graph, n=100, neighborhood_depth=2):
"""Compute the NeighborRank of the top n nodes in graph, using the
specified neighborhood_depth."""
# Get top n nodes with highest indegree (most often cited).
nodes = util.top_n_from_dict(graph.in_degree(), n=n)
# Find neighborhood sizes.
nhood_sizes = {}
for root in nodes:
# Neighborhood begins with just the root.
nhood = set([root])
# Expand the neighborhood repeatedly until the depth is reached.
for i in range(neighborhood_depth):
prev_nhood = nhood.copy()
for node in prev_nhood:
nhood |= set(graph.successors(node))
# Update the results dict.
nhood_sizes[root] = len(nhood)
return nhood_sizes
## Instruction:
Switch in/out degree for neighbor rank
Edges point in the direction of time, or influence. That means we're
concerned with outdegree (amount of nodes influenced by the current
node), not indegree (amount of nodes that influence the current node).
## Code After:
import networkx as nx
import util
def neighborrank(graph, n=100, neighborhood_depth=2):
"""Compute the NeighborRank of the top n nodes in graph, using the
specified neighborhood_depth."""
# Get top n nodes with highest outdegree (most often cited).
nodes = util.top_n_from_dict(graph.out_degree(), n=n)
# Find neighborhood sizes.
nhood_sizes = {}
for root in nodes:
# Neighborhood begins with just the root.
nhood = set([root])
# Expand the neighborhood repeatedly until the depth is reached.
for i in range(neighborhood_depth):
prev_nhood = nhood.copy()
for node in prev_nhood:
nhood |= set(graph.predecessors(node))
# Update the results dict.
nhood_sizes[root] = len(nhood)
return nhood_sizes
|
...
def neighborrank(graph, n=100, neighborhood_depth=2):
"""Compute the NeighborRank of the top n nodes in graph, using the
specified neighborhood_depth."""
# Get top n nodes with highest outdegree (most often cited).
nodes = util.top_n_from_dict(graph.out_degree(), n=n)
# Find neighborhood sizes.
nhood_sizes = {}
...
for i in range(neighborhood_depth):
prev_nhood = nhood.copy()
for node in prev_nhood:
nhood |= set(graph.predecessors(node))
# Update the results dict.
nhood_sizes[root] = len(nhood)
...
|
a0a4ba94cc76d5c4395d869fe5ea70caae14fa36
|
pyroSAR/tests/test_snap_exe.py
|
pyroSAR/tests/test_snap_exe.py
|
import pytest
from contextlib import contextmanager
from pyroSAR._dev_config import ExamineExe
from pyroSAR.snap.auxil import ExamineSnap
@contextmanager
def not_raises(ExpectedException):
try:
yield
except ExpectedException:
raise AssertionError(
"Did raise exception {0} when it should not!".format(
repr(ExpectedException)
)
)
except Exception:
raise AssertionError(
"An unexpected exception {0} raised.".format(repr(Exception))
)
class TestExemineExe:
def test_exception(self):
with pytest.warns(UserWarning):
ExamineExe.examine('some_exe_file.exe')
def test_warn_snap(self):
with pytest.warns(UserWarning):
ExamineExe.examine('snap')
# def test_not_exception(self):
# SNAP_EXECUTABLE = ['snap64.exe', 'snap32.exe', 'snap.exe', 'snap']
# with not_raises(ValueError):
# ExamineExe.examine(SNAP_EXECUTABLE)
class TestExamineSnap:
def test_exception(self):
with pytest.warns(UserWarning):
ExamineExe.examine('some_exe_file.exe')
# def test_not_exception(self):
# with not_raises(AssertionError):
# test_snap_exe = ExamineSnap()
|
from contextlib import contextmanager
import pytest
from pyroSAR._dev_config import ExamineExe
from pyroSAR.snap.auxil import ExamineSnap
@contextmanager
def not_raises(ExpectedException):
try:
yield
except ExpectedException:
raise AssertionError(
"Did raise exception {0} when it should not!".format(
repr(ExpectedException)
)
)
except Exception:
raise AssertionError(
"An unexpected exception {0} raised.".format(repr(Exception))
)
class TestExemineExe:
def test_exception(self):
with pytest.warns(UserWarning):
ExamineExe.examine('some_exe_file.exe')
def test_not_exception(self):
SNAP_EXECUTABLE = ['snap64.exe', 'snap32.exe', 'snap.exe', 'snap']
with pytest.warns(None) as record:
ExamineExe.examine(SNAP_EXECUTABLE)
assert len(record) == 1
class TestExamineSnap:
def test_exception(self):
with pytest.warns(UserWarning):
ExamineSnap(snap_executable='some_exe_file.exe')
def test_not_exception(self):
with pytest.warns(None) as record:
ExamineSnap()
assert len(record) == 0
|
Add unit test to determine if the classes ExamineExe and ExamineSnap will work properly.
|
Add unit test to determine if the classes ExamineExe and ExamineSnap will work properly.
|
Python
|
mit
|
johntruckenbrodt/pyroSAR,johntruckenbrodt/pyroSAR
|
python
|
## Code Before:
import pytest
from contextlib import contextmanager
from pyroSAR._dev_config import ExamineExe
from pyroSAR.snap.auxil import ExamineSnap
@contextmanager
def not_raises(ExpectedException):
try:
yield
except ExpectedException:
raise AssertionError(
"Did raise exception {0} when it should not!".format(
repr(ExpectedException)
)
)
except Exception:
raise AssertionError(
"An unexpected exception {0} raised.".format(repr(Exception))
)
class TestExemineExe:
def test_exception(self):
with pytest.warns(UserWarning):
ExamineExe.examine('some_exe_file.exe')
def test_warn_snap(self):
with pytest.warns(UserWarning):
ExamineExe.examine('snap')
# def test_not_exception(self):
# SNAP_EXECUTABLE = ['snap64.exe', 'snap32.exe', 'snap.exe', 'snap']
# with not_raises(ValueError):
# ExamineExe.examine(SNAP_EXECUTABLE)
class TestExamineSnap:
def test_exception(self):
with pytest.warns(UserWarning):
ExamineExe.examine('some_exe_file.exe')
# def test_not_exception(self):
# with not_raises(AssertionError):
# test_snap_exe = ExamineSnap()
## Instruction:
Add unit test to determine if the classes ExamineExe and ExamineSnap will work properly.
## Code After:
from contextlib import contextmanager
import pytest
from pyroSAR._dev_config import ExamineExe
from pyroSAR.snap.auxil import ExamineSnap
@contextmanager
def not_raises(ExpectedException):
try:
yield
except ExpectedException:
raise AssertionError(
"Did raise exception {0} when it should not!".format(
repr(ExpectedException)
)
)
except Exception:
raise AssertionError(
"An unexpected exception {0} raised.".format(repr(Exception))
)
class TestExemineExe:
def test_exception(self):
with pytest.warns(UserWarning):
ExamineExe.examine('some_exe_file.exe')
def test_not_exception(self):
SNAP_EXECUTABLE = ['snap64.exe', 'snap32.exe', 'snap.exe', 'snap']
with pytest.warns(None) as record:
ExamineExe.examine(SNAP_EXECUTABLE)
assert len(record) == 1
class TestExamineSnap:
def test_exception(self):
with pytest.warns(UserWarning):
ExamineSnap(snap_executable='some_exe_file.exe')
def test_not_exception(self):
with pytest.warns(None) as record:
ExamineSnap()
assert len(record) == 0
|
# ... existing code ...
from contextlib import contextmanager
import pytest
from pyroSAR._dev_config import ExamineExe
from pyroSAR.snap.auxil import ExamineSnap
@contextmanager
def not_raises(ExpectedException):
# ... modified code ...
"An unexpected exception {0} raised.".format(repr(Exception))
)
class TestExemineExe:
def test_exception(self):
with pytest.warns(UserWarning):
ExamineExe.examine('some_exe_file.exe')
def test_not_exception(self):
SNAP_EXECUTABLE = ['snap64.exe', 'snap32.exe', 'snap.exe', 'snap']
with pytest.warns(None) as record:
ExamineExe.examine(SNAP_EXECUTABLE)
assert len(record) == 1
class TestExamineSnap:
def test_exception(self):
with pytest.warns(UserWarning):
ExamineSnap(snap_executable='some_exe_file.exe')
def test_not_exception(self):
with pytest.warns(None) as record:
ExamineSnap()
assert len(record) == 0
# ... rest of the code ...
|
f038d71761b642a0f587dc77c4d108aaa42f7824
|
src/login/PasswordHelper.java
|
src/login/PasswordHelper.java
|
package login;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;
public class PasswordHelper
{
private static String hashAlgorithm = "MD5";
private static String stringEncodingFormat = "UTF-8";
public static String generatePasswordHash(String password)
{
//Create instances of digest and password char array
MessageDigest passDigest;
byte[] passArray;
try
{
//Create instance of MessageDigest we can use to
passDigest = MessageDigest.getInstance(hashAlgorithm);
//Convert password to byte array
passArray = password.getBytes(stringEncodingFormat);
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
return "";
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
return "";
}
//Use digest to get hash as an array of chars and return it as a hex string
byte[] hashArray = passDigest.digest(passArray);
return DatatypeConverter.printHexBinary(hashArray);
}
}
|
package login;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;
public class PasswordHelper
{
private static String hashAlgorithm = "MD5";
private static String stringEncodingFormat = "UTF-8";
/**Returns the hash for a given password string, in hex string format*/
public static String generatePasswordHash(String password)
{
//Create instances of digest and password char array
MessageDigest passDigest;
byte[] passArray;
try
{
//Create instance of MessageDigest we can use to
passDigest = MessageDigest.getInstance(hashAlgorithm);
//Convert password to byte array
passArray = password.getBytes(stringEncodingFormat);
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
return "";
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
return "";
}
//Use digest to get hash as an array of chars and return it as a hex string
byte[] hashArray = passDigest.digest(passArray);
return DatatypeConverter.printHexBinary(hashArray);
}
}
|
Add description to hash function
|
Add description to hash function
|
Java
|
mit
|
TeamRedFox/PointOfSale
|
java
|
## Code Before:
package login;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;
public class PasswordHelper
{
private static String hashAlgorithm = "MD5";
private static String stringEncodingFormat = "UTF-8";
public static String generatePasswordHash(String password)
{
//Create instances of digest and password char array
MessageDigest passDigest;
byte[] passArray;
try
{
//Create instance of MessageDigest we can use to
passDigest = MessageDigest.getInstance(hashAlgorithm);
//Convert password to byte array
passArray = password.getBytes(stringEncodingFormat);
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
return "";
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
return "";
}
//Use digest to get hash as an array of chars and return it as a hex string
byte[] hashArray = passDigest.digest(passArray);
return DatatypeConverter.printHexBinary(hashArray);
}
}
## Instruction:
Add description to hash function
## Code After:
package login;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;
public class PasswordHelper
{
private static String hashAlgorithm = "MD5";
private static String stringEncodingFormat = "UTF-8";
/**Returns the hash for a given password string, in hex string format*/
public static String generatePasswordHash(String password)
{
//Create instances of digest and password char array
MessageDigest passDigest;
byte[] passArray;
try
{
//Create instance of MessageDigest we can use to
passDigest = MessageDigest.getInstance(hashAlgorithm);
//Convert password to byte array
passArray = password.getBytes(stringEncodingFormat);
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
return "";
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
return "";
}
//Use digest to get hash as an array of chars and return it as a hex string
byte[] hashArray = passDigest.digest(passArray);
return DatatypeConverter.printHexBinary(hashArray);
}
}
|
// ... existing code ...
private static String hashAlgorithm = "MD5";
private static String stringEncodingFormat = "UTF-8";
/**Returns the hash for a given password string, in hex string format*/
public static String generatePasswordHash(String password)
{
//Create instances of digest and password char array
// ... rest of the code ...
|
bf006aa3dc8ee331eccb4abd8244a134949c8cc0
|
bawebauth/apps/bawebauth/fields.py
|
bawebauth/apps/bawebauth/fields.py
|
from django.db import models
class PositiveBigIntegerField(models.PositiveIntegerField):
"""Represents MySQL's unsigned BIGINT data type (works with MySQL only!)"""
empty_strings_allowed = False
def get_internal_type(self):
return "PositiveBigIntegerField"
def db_type(self, connection):
if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql':
# This is how MySQL defines 64 bit unsigned integer data types
return "BIGINT UNSIGNED"
return super(PositiveBigIntegerField, self).db_type(connection)
try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ['bawebauth\.fields\.PositiveBigIntegerField'])
except ImportError:
pass
|
from django.db import models
class PositiveBigIntegerField(models.PositiveIntegerField):
"""Represents MySQL's unsigned BIGINT data type (works with MySQL only!)"""
empty_strings_allowed = False
def db_type(self, connection):
if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql':
# This is how MySQL defines 64 bit unsigned integer data types
return "BIGINT UNSIGNED"
return super(PositiveBigIntegerField, self).db_type(connection)
try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ['bawebauth\.fields\.PositiveBigIntegerField'])
except ImportError:
pass
|
Fix tests by removing obsolete internal field type declaration
|
Fix tests by removing obsolete internal field type declaration
|
Python
|
mit
|
mback2k/django-bawebauth,mback2k/django-bawebauth,mback2k/django-bawebauth,mback2k/django-bawebauth
|
python
|
## Code Before:
from django.db import models
class PositiveBigIntegerField(models.PositiveIntegerField):
"""Represents MySQL's unsigned BIGINT data type (works with MySQL only!)"""
empty_strings_allowed = False
def get_internal_type(self):
return "PositiveBigIntegerField"
def db_type(self, connection):
if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql':
# This is how MySQL defines 64 bit unsigned integer data types
return "BIGINT UNSIGNED"
return super(PositiveBigIntegerField, self).db_type(connection)
try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ['bawebauth\.fields\.PositiveBigIntegerField'])
except ImportError:
pass
## Instruction:
Fix tests by removing obsolete internal field type declaration
## Code After:
from django.db import models
class PositiveBigIntegerField(models.PositiveIntegerField):
"""Represents MySQL's unsigned BIGINT data type (works with MySQL only!)"""
empty_strings_allowed = False
def db_type(self, connection):
if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql':
# This is how MySQL defines 64 bit unsigned integer data types
return "BIGINT UNSIGNED"
return super(PositiveBigIntegerField, self).db_type(connection)
try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ['bawebauth\.fields\.PositiveBigIntegerField'])
except ImportError:
pass
|
# ... existing code ...
class PositiveBigIntegerField(models.PositiveIntegerField):
"""Represents MySQL's unsigned BIGINT data type (works with MySQL only!)"""
empty_strings_allowed = False
def db_type(self, connection):
if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql':
# ... rest of the code ...
|
ab91d525abb5bb1ef476f3aac2c034e50f85617a
|
src/apps/contacts/mixins.py
|
src/apps/contacts/mixins.py
|
from apps.contacts.models import BaseContact
class ContactMixin(object):
"""
Would be used for adding contacts functionality to models with contact data.
"""
def get_contacts(self, is_primary=False):
"""
Returns dict with all contacts.
Example:
>> obj.get_contacts()
<< {'email': [], 'skype': []}
:param is_primary:
:return:
"""
subclasses = BaseContact.__subclasses__()
results = {}
for cls in subclasses:
queryset = cls.objects.filter(employee_id=self.id)
key, verbose = cls.CONTACT_EXTRA_DATA
if is_primary:
queryset = queryset.filter(is_primary=True)
results.setdefault(key, queryset)
return results
|
from apps.contacts.models import BaseContact
class ContactMixin(object):
"""
Would be used for adding contacts functionality to models with contact data.
"""
def get_contacts(self, is_primary=False):
"""
Returns dict with all contacts.
Example:
>> obj.get_contacts()
<< {'email': [], 'skype': []}
:param is_primary: bool Return only primary contacts.
:return: dict
"""
subclasses = BaseContact.__subclasses__()
results = {}
for cls in subclasses:
queryset = cls.objects.filter(employee_id=self.id)
key, verbose = cls.CONTACT_EXTRA_DATA
if is_primary:
queryset = queryset.filter(is_primary=True)
results.setdefault(key, queryset)
return results
|
Fix description for contact mixin
|
Fix description for contact mixin
|
Python
|
mit
|
wis-software/office-manager
|
python
|
## Code Before:
from apps.contacts.models import BaseContact
class ContactMixin(object):
"""
Would be used for adding contacts functionality to models with contact data.
"""
def get_contacts(self, is_primary=False):
"""
Returns dict with all contacts.
Example:
>> obj.get_contacts()
<< {'email': [], 'skype': []}
:param is_primary:
:return:
"""
subclasses = BaseContact.__subclasses__()
results = {}
for cls in subclasses:
queryset = cls.objects.filter(employee_id=self.id)
key, verbose = cls.CONTACT_EXTRA_DATA
if is_primary:
queryset = queryset.filter(is_primary=True)
results.setdefault(key, queryset)
return results
## Instruction:
Fix description for contact mixin
## Code After:
from apps.contacts.models import BaseContact
class ContactMixin(object):
"""
Would be used for adding contacts functionality to models with contact data.
"""
def get_contacts(self, is_primary=False):
"""
Returns dict with all contacts.
Example:
>> obj.get_contacts()
<< {'email': [], 'skype': []}
:param is_primary: bool Return only primary contacts.
:return: dict
"""
subclasses = BaseContact.__subclasses__()
results = {}
for cls in subclasses:
queryset = cls.objects.filter(employee_id=self.id)
key, verbose = cls.CONTACT_EXTRA_DATA
if is_primary:
queryset = queryset.filter(is_primary=True)
results.setdefault(key, queryset)
return results
|
...
>> obj.get_contacts()
<< {'email': [], 'skype': []}
:param is_primary: bool Return only primary contacts.
:return: dict
"""
subclasses = BaseContact.__subclasses__()
results = {}
...
|
76ed79593a832c1cf85615d21b31f18f2c7adebf
|
yanico/session/__init__.py
|
yanico/session/__init__.py
|
"""Handle nicovideo.jp user_session."""
import pkg_resources
class LoaderNotFoundError(Exception):
"""Session loader is not found."""
class UserSessionNotFoundError(Exception):
"""Profile exists, but user_session is not found."""
def load(ltype, profile):
for entry in pkg_resources.iter_entry_points('yanico.sessions', ltype):
load_func = entry.load()
return load_func(profile)
raise LoaderNotFoundError('{} loader is not found.'.format(ltype))
|
"""Handle nicovideo.jp user_session."""
import pkg_resources
class LoaderNotFoundError(Exception):
"""Session loader is not found."""
class UserSessionNotFoundError(Exception):
"""Profile exists, but user_session is not found."""
def load(ltype, profile):
"""Return nicovideo.jp user session string.
Args:
ltype (str): loader type
profile (str): file path for profile
Returns:
str: user session
Raises:
LoaderNotFoundError
Error from loader
"""
for entry in pkg_resources.iter_entry_points('yanico.sessions', ltype):
load_func = entry.load()
return load_func(profile)
raise LoaderNotFoundError('{} loader is not found.'.format(ltype))
|
Add docstring into load function
|
Add docstring into load function
Follow to Google style.
|
Python
|
apache-2.0
|
ma8ma/yanico
|
python
|
## Code Before:
"""Handle nicovideo.jp user_session."""
import pkg_resources
class LoaderNotFoundError(Exception):
"""Session loader is not found."""
class UserSessionNotFoundError(Exception):
"""Profile exists, but user_session is not found."""
def load(ltype, profile):
for entry in pkg_resources.iter_entry_points('yanico.sessions', ltype):
load_func = entry.load()
return load_func(profile)
raise LoaderNotFoundError('{} loader is not found.'.format(ltype))
## Instruction:
Add docstring into load function
Follow to Google style.
## Code After:
"""Handle nicovideo.jp user_session."""
import pkg_resources
class LoaderNotFoundError(Exception):
"""Session loader is not found."""
class UserSessionNotFoundError(Exception):
"""Profile exists, but user_session is not found."""
def load(ltype, profile):
"""Return nicovideo.jp user session string.
Args:
ltype (str): loader type
profile (str): file path for profile
Returns:
str: user session
Raises:
LoaderNotFoundError
Error from loader
"""
for entry in pkg_resources.iter_entry_points('yanico.sessions', ltype):
load_func = entry.load()
return load_func(profile)
raise LoaderNotFoundError('{} loader is not found.'.format(ltype))
|
# ... existing code ...
def load(ltype, profile):
"""Return nicovideo.jp user session string.
Args:
ltype (str): loader type
profile (str): file path for profile
Returns:
str: user session
Raises:
LoaderNotFoundError
Error from loader
"""
for entry in pkg_resources.iter_entry_points('yanico.sessions', ltype):
load_func = entry.load()
return load_func(profile)
# ... rest of the code ...
|
09496ed494ebe867f31eda00a11cd7ed4c491341
|
setup.py
|
setup.py
|
from setuptools import setup, Extension
import platform
version = '2.1.0'
setup(name='dronekit',
zip_safe=True,
version=version,
description='Python language bindings for the DroneApi',
long_description='Python language bindings for the DroneApi',
url='https://github.com/dronekit/dronekit-python',
author='3D Robotics',
install_requires=[
'pymavlink>=1.1.62',
'requests>=2.5.0,<=2.99999',
],
author_email='[email protected], [email protected]',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering',
],
license='apache',
packages=[
'dronekit', 'dronekit.cloud', 'dronekit.test'
],
ext_modules=[])
|
from setuptools import setup, Extension
import platform
version = '2.1.0'
setup(name='dronekit',
zip_safe=True,
version=version,
description='Developer Tools for Drones.',
long_description='Python API for communication and control of drones over MAVLink.',
url='https://github.com/dronekit/dronekit-python',
author='3D Robotics',
install_requires=[
'pymavlink>=1.1.62',
'requests>=2.5.0,<=2.99999',
],
author_email='[email protected], [email protected]',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering',
],
license='apache',
packages=[
'dronekit', 'dronekit.cloud', 'dronekit.test'
],
ext_modules=[])
|
Improve description of dronekit on PyPi
|
Improve description of dronekit on PyPi
|
Python
|
apache-2.0
|
hamishwillee/dronekit-python,dronekit/dronekit-python,dronekit/dronekit-python,diydrones/dronekit-python,hamishwillee/dronekit-python,diydrones/dronekit-python
|
python
|
## Code Before:
from setuptools import setup, Extension
import platform
version = '2.1.0'
setup(name='dronekit',
zip_safe=True,
version=version,
description='Python language bindings for the DroneApi',
long_description='Python language bindings for the DroneApi',
url='https://github.com/dronekit/dronekit-python',
author='3D Robotics',
install_requires=[
'pymavlink>=1.1.62',
'requests>=2.5.0,<=2.99999',
],
author_email='[email protected], [email protected]',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering',
],
license='apache',
packages=[
'dronekit', 'dronekit.cloud', 'dronekit.test'
],
ext_modules=[])
## Instruction:
Improve description of dronekit on PyPi
## Code After:
from setuptools import setup, Extension
import platform
version = '2.1.0'
setup(name='dronekit',
zip_safe=True,
version=version,
description='Developer Tools for Drones.',
long_description='Python API for communication and control of drones over MAVLink.',
url='https://github.com/dronekit/dronekit-python',
author='3D Robotics',
install_requires=[
'pymavlink>=1.1.62',
'requests>=2.5.0,<=2.99999',
],
author_email='[email protected], [email protected]',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering',
],
license='apache',
packages=[
'dronekit', 'dronekit.cloud', 'dronekit.test'
],
ext_modules=[])
|
# ... existing code ...
setup(name='dronekit',
zip_safe=True,
version=version,
description='Developer Tools for Drones.',
long_description='Python API for communication and control of drones over MAVLink.',
url='https://github.com/dronekit/dronekit-python',
author='3D Robotics',
install_requires=[
# ... rest of the code ...
|
6cf71c1a6462c59d6686345ed3cd918bc64062ce
|
src/main/java/com/elmakers/mine/bukkit/action/builtin/KillAction.java
|
src/main/java/com/elmakers/mine/bukkit/action/builtin/KillAction.java
|
package com.elmakers.mine.bukkit.action.builtin;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import com.elmakers.mine.bukkit.action.BaseSpellAction;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
public class KillAction extends BaseSpellAction
{
@Override
public SpellResult perform(CastContext context)
{
Entity entity = context.getTargetEntity();
if (!(entity instanceof LivingEntity))
{
return SpellResult.NO_TARGET;
}
LivingEntity targetEntity = (LivingEntity)entity;
// Overkill to bypass protection
if (!targetEntity.isDead()) {
targetEntity.damage(targetEntity.getMaxHealth() * 100);
}
return SpellResult.CAST;
}
@Override
public boolean isUndoable()
{
return true;
}
@Override
public boolean requiresTargetEntity()
{
return true;
}
}
|
package com.elmakers.mine.bukkit.action.builtin;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MageController;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import com.elmakers.mine.bukkit.action.BaseSpellAction;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
public class KillAction extends BaseSpellAction
{
@Override
public SpellResult perform(CastContext context)
{
Entity entity = context.getTargetEntity();
if (!(entity instanceof LivingEntity))
{
return SpellResult.NO_TARGET;
}
LivingEntity targetEntity = (LivingEntity)entity;
MageController controller = context.getController();
if (controller.isMage(targetEntity)) {
Mage mage = controller.getMage(targetEntity);
if (mage.isSuperProtected()) {
return SpellResult.NO_TARGET;
}
}
// Overkill to bypass protection
if (!targetEntity.isDead()) {
targetEntity.damage(targetEntity.getMaxHealth() * 100);
}
return SpellResult.CAST;
}
@Override
public boolean isUndoable()
{
return true;
}
@Override
public boolean requiresTargetEntity()
{
return true;
}
}
|
Add explicit Superprotected check to Kill action
|
Add explicit Superprotected check to Kill action
|
Java
|
mit
|
elBukkit/MagicPlugin,elBukkit/MagicPlugin,elBukkit/MagicPlugin
|
java
|
## Code Before:
package com.elmakers.mine.bukkit.action.builtin;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import com.elmakers.mine.bukkit.action.BaseSpellAction;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
public class KillAction extends BaseSpellAction
{
@Override
public SpellResult perform(CastContext context)
{
Entity entity = context.getTargetEntity();
if (!(entity instanceof LivingEntity))
{
return SpellResult.NO_TARGET;
}
LivingEntity targetEntity = (LivingEntity)entity;
// Overkill to bypass protection
if (!targetEntity.isDead()) {
targetEntity.damage(targetEntity.getMaxHealth() * 100);
}
return SpellResult.CAST;
}
@Override
public boolean isUndoable()
{
return true;
}
@Override
public boolean requiresTargetEntity()
{
return true;
}
}
## Instruction:
Add explicit Superprotected check to Kill action
## Code After:
package com.elmakers.mine.bukkit.action.builtin;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MageController;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import com.elmakers.mine.bukkit.action.BaseSpellAction;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
public class KillAction extends BaseSpellAction
{
@Override
public SpellResult perform(CastContext context)
{
Entity entity = context.getTargetEntity();
if (!(entity instanceof LivingEntity))
{
return SpellResult.NO_TARGET;
}
LivingEntity targetEntity = (LivingEntity)entity;
MageController controller = context.getController();
if (controller.isMage(targetEntity)) {
Mage mage = controller.getMage(targetEntity);
if (mage.isSuperProtected()) {
return SpellResult.NO_TARGET;
}
}
// Overkill to bypass protection
if (!targetEntity.isDead()) {
targetEntity.damage(targetEntity.getMaxHealth() * 100);
}
return SpellResult.CAST;
}
@Override
public boolean isUndoable()
{
return true;
}
@Override
public boolean requiresTargetEntity()
{
return true;
}
}
|
# ... existing code ...
package com.elmakers.mine.bukkit.action.builtin;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MageController;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import com.elmakers.mine.bukkit.action.BaseSpellAction;
import org.bukkit.entity.Entity;
# ... modified code ...
}
LivingEntity targetEntity = (LivingEntity)entity;
MageController controller = context.getController();
if (controller.isMage(targetEntity)) {
Mage mage = controller.getMage(targetEntity);
if (mage.isSuperProtected()) {
return SpellResult.NO_TARGET;
}
}
// Overkill to bypass protection
if (!targetEntity.isDead()) {
targetEntity.damage(targetEntity.getMaxHealth() * 100);
# ... rest of the code ...
|
01faec177c1223cd75ad38241da0dc7bfb805c7b
|
src/main/java/org/cryptomator/cryptofs/health/dirid/MissingDirIdBackup.java
|
src/main/java/org/cryptomator/cryptofs/health/dirid/MissingDirIdBackup.java
|
package org.cryptomator.cryptofs.health.dirid;
import org.cryptomator.cryptofs.CryptoPathMapper;
import org.cryptomator.cryptofs.DirectoryIdBackup;
import org.cryptomator.cryptofs.VaultConfig;
import org.cryptomator.cryptofs.health.api.DiagnosticResult;
import org.cryptomator.cryptolib.api.Cryptor;
import org.cryptomator.cryptolib.api.Masterkey;
import java.io.IOException;
import java.nio.file.Path;
/**
* TODO: adjust DirIdCheck
*/
public class MissingDirIdBackup implements DiagnosticResult {
private final Path cipherDir;
private final String dirId;
MissingDirIdBackup(String dirId, Path cipherDir) {
this.cipherDir = cipherDir;
this.dirId = dirId;
}
@Override
public Severity getSeverity() {
return Severity.WARN; //TODO: decide severity
}
@Override
public void fix(Path pathToVault, VaultConfig config, Masterkey masterkey, Cryptor cryptor) throws IOException {
DirectoryIdBackup dirIdBackup = new DirectoryIdBackup(cryptor);
dirIdBackup.execute(new CryptoPathMapper.CiphertextDirectory(dirId,cipherDir));
}
}
|
package org.cryptomator.cryptofs.health.dirid;
import org.cryptomator.cryptofs.CryptoPathMapper;
import org.cryptomator.cryptofs.DirectoryIdBackup;
import org.cryptomator.cryptofs.VaultConfig;
import org.cryptomator.cryptofs.health.api.DiagnosticResult;
import org.cryptomator.cryptolib.api.Cryptor;
import org.cryptomator.cryptolib.api.Masterkey;
import java.io.IOException;
import java.nio.file.Path;
/**
* The dir id backup file is missing.
*/
public record MissingDirIdBackup(String dirId, Path cipherDir) implements DiagnosticResult {
@Override
public Severity getSeverity() {
return Severity.WARN;
}
@Override
public String toString() {
return String.format("Directory ID backup for directory %s is missing.", cipherDir);
}
@Override
public void fix(Path pathToVault, VaultConfig config, Masterkey masterkey, Cryptor cryptor) throws IOException {
DirectoryIdBackup dirIdBackup = new DirectoryIdBackup(cryptor);
dirIdBackup.execute(new CryptoPathMapper.CiphertextDirectory(dirId, cipherDir));
}
}
|
Refactor to record and add docs.
|
Refactor to record and add docs.
|
Java
|
agpl-3.0
|
cryptomator/cryptofs
|
java
|
## Code Before:
package org.cryptomator.cryptofs.health.dirid;
import org.cryptomator.cryptofs.CryptoPathMapper;
import org.cryptomator.cryptofs.DirectoryIdBackup;
import org.cryptomator.cryptofs.VaultConfig;
import org.cryptomator.cryptofs.health.api.DiagnosticResult;
import org.cryptomator.cryptolib.api.Cryptor;
import org.cryptomator.cryptolib.api.Masterkey;
import java.io.IOException;
import java.nio.file.Path;
/**
* TODO: adjust DirIdCheck
*/
public class MissingDirIdBackup implements DiagnosticResult {
private final Path cipherDir;
private final String dirId;
MissingDirIdBackup(String dirId, Path cipherDir) {
this.cipherDir = cipherDir;
this.dirId = dirId;
}
@Override
public Severity getSeverity() {
return Severity.WARN; //TODO: decide severity
}
@Override
public void fix(Path pathToVault, VaultConfig config, Masterkey masterkey, Cryptor cryptor) throws IOException {
DirectoryIdBackup dirIdBackup = new DirectoryIdBackup(cryptor);
dirIdBackup.execute(new CryptoPathMapper.CiphertextDirectory(dirId,cipherDir));
}
}
## Instruction:
Refactor to record and add docs.
## Code After:
package org.cryptomator.cryptofs.health.dirid;
import org.cryptomator.cryptofs.CryptoPathMapper;
import org.cryptomator.cryptofs.DirectoryIdBackup;
import org.cryptomator.cryptofs.VaultConfig;
import org.cryptomator.cryptofs.health.api.DiagnosticResult;
import org.cryptomator.cryptolib.api.Cryptor;
import org.cryptomator.cryptolib.api.Masterkey;
import java.io.IOException;
import java.nio.file.Path;
/**
* The dir id backup file is missing.
*/
public record MissingDirIdBackup(String dirId, Path cipherDir) implements DiagnosticResult {
@Override
public Severity getSeverity() {
return Severity.WARN;
}
@Override
public String toString() {
return String.format("Directory ID backup for directory %s is missing.", cipherDir);
}
@Override
public void fix(Path pathToVault, VaultConfig config, Masterkey masterkey, Cryptor cryptor) throws IOException {
DirectoryIdBackup dirIdBackup = new DirectoryIdBackup(cryptor);
dirIdBackup.execute(new CryptoPathMapper.CiphertextDirectory(dirId, cipherDir));
}
}
|
// ... existing code ...
import java.nio.file.Path;
/**
* The dir id backup file is missing.
*/
public record MissingDirIdBackup(String dirId, Path cipherDir) implements DiagnosticResult {
@Override
public Severity getSeverity() {
return Severity.WARN;
}
@Override
public String toString() {
return String.format("Directory ID backup for directory %s is missing.", cipherDir);
}
@Override
public void fix(Path pathToVault, VaultConfig config, Masterkey masterkey, Cryptor cryptor) throws IOException {
DirectoryIdBackup dirIdBackup = new DirectoryIdBackup(cryptor);
dirIdBackup.execute(new CryptoPathMapper.CiphertextDirectory(dirId, cipherDir));
}
}
// ... rest of the code ...
|
439ce4a8ccf218c69393773fc9fbba95f8130d4e
|
src/main/java/stream/flarebot/flarebot/util/HelpFormatter.java
|
src/main/java/stream/flarebot/flarebot/util/HelpFormatter.java
|
package stream.flarebot.flarebot.util;
import net.dv8tion.jda.core.entities.TextChannel;
import stream.flarebot.flarebot.FlareBot;
import java.util.regex.Matcher;
public class HelpFormatter {
public static String on(TextChannel channel, String description) {
return description.replaceAll("(?<!\\\\)%p", Matcher.quoteReplacement(String.valueOf(get(channel))));
}
private static char get(TextChannel channel) {
if (channel.getGuild() != null) {
return FlareBot.getPrefixes().get(channel.getGuild().getId());
}
return FlareBot.getPrefixes().get(null);
}
public static String formatCommandUsage(TextChannel channel, String usage) {
String prefix = String.valueOf(get(channel));
return usage.replace("{%}", prefix);
}
}
|
package stream.flarebot.flarebot.util;
import net.dv8tion.jda.core.entities.TextChannel;
import stream.flarebot.flarebot.FlareBot;
import java.util.regex.Matcher;
public class HelpFormatter {
private static char get(TextChannel channel) {
if (channel.getGuild() != null) {
return FlareBot.getPrefixes().get(channel.getGuild().getId());
}
return FlareBot.getPrefixes().get(null);
}
public static String formatCommandPrefix(TextChannel channel, String usage) {
String prefix = String.valueOf(get(channel));
return usage.replaceAll("\\{%\\}", prefix);
}
}
|
Make prefix placeholder "{%}" for everything
|
Make prefix placeholder "{%}" for everything
|
Java
|
mit
|
weeryan17/FlareBot,FlareBot/FlareBot,binaryoverload/FlareBot
|
java
|
## Code Before:
package stream.flarebot.flarebot.util;
import net.dv8tion.jda.core.entities.TextChannel;
import stream.flarebot.flarebot.FlareBot;
import java.util.regex.Matcher;
public class HelpFormatter {
public static String on(TextChannel channel, String description) {
return description.replaceAll("(?<!\\\\)%p", Matcher.quoteReplacement(String.valueOf(get(channel))));
}
private static char get(TextChannel channel) {
if (channel.getGuild() != null) {
return FlareBot.getPrefixes().get(channel.getGuild().getId());
}
return FlareBot.getPrefixes().get(null);
}
public static String formatCommandUsage(TextChannel channel, String usage) {
String prefix = String.valueOf(get(channel));
return usage.replace("{%}", prefix);
}
}
## Instruction:
Make prefix placeholder "{%}" for everything
## Code After:
package stream.flarebot.flarebot.util;
import net.dv8tion.jda.core.entities.TextChannel;
import stream.flarebot.flarebot.FlareBot;
import java.util.regex.Matcher;
public class HelpFormatter {
private static char get(TextChannel channel) {
if (channel.getGuild() != null) {
return FlareBot.getPrefixes().get(channel.getGuild().getId());
}
return FlareBot.getPrefixes().get(null);
}
public static String formatCommandPrefix(TextChannel channel, String usage) {
String prefix = String.valueOf(get(channel));
return usage.replaceAll("\\{%\\}", prefix);
}
}
|
// ... existing code ...
import java.util.regex.Matcher;
public class HelpFormatter {
private static char get(TextChannel channel) {
if (channel.getGuild() != null) {
// ... modified code ...
return FlareBot.getPrefixes().get(null);
}
public static String formatCommandPrefix(TextChannel channel, String usage) {
String prefix = String.valueOf(get(channel));
return usage.replaceAll("\\{%\\}", prefix);
}
}
// ... rest of the code ...
|
d604128015826444be4585c7204030840e9efc88
|
tests/test_java.py
|
tests/test_java.py
|
def test_java_exists(Command):
version_result = Command("java -version")
assert version_result.rc == 0
|
def test_java_exists(Command):
version_result = Command("java -version")
assert version_result.rc == 0
def test_java_certs_exist(File):
assert File("/etc/ssl/certs/java/cacerts").exists
|
Add test to make sure SSL certs are installed.
|
Add test to make sure SSL certs are installed.
|
Python
|
apache-2.0
|
azavea/ansible-java,flibbertigibbet/ansible-java
|
python
|
## Code Before:
def test_java_exists(Command):
version_result = Command("java -version")
assert version_result.rc == 0
## Instruction:
Add test to make sure SSL certs are installed.
## Code After:
def test_java_exists(Command):
version_result = Command("java -version")
assert version_result.rc == 0
def test_java_certs_exist(File):
assert File("/etc/ssl/certs/java/cacerts").exists
|
# ... existing code ...
version_result = Command("java -version")
assert version_result.rc == 0
def test_java_certs_exist(File):
assert File("/etc/ssl/certs/java/cacerts").exists
# ... rest of the code ...
|
f4b3c2ca7d9fdf6bc96202d6c2ad3b16cb6fc3be
|
sedfitter/timer.py
|
sedfitter/timer.py
|
from __future__ import print_function, division
import time
import numpy as np
class Timer(object):
def __init__(self):
self.time1 = time.time()
self.n = 0
self.step = 1
print(" # Sources CPU time (sec) Sources/sec ")
print(" ----------------------------------------------")
def display(self, force=False):
self.n += 1
if np.mod(self.n, self.step) == 0:
self.time2 = time.time()
if self.time2 - self.time1 < 1.:
self.step *= 10
else:
print(" %7i %10.1f %7.2f" % (self.n, self.time2 - self.time1, self.n / (self.time2 - self.time1)))
elif force:
self.time2 = time.time()
print(" %7i %10.1f %7.2f" % (self.n, self.time2 - self.time1, self.n / (self.time2 - self.time1)))
|
from __future__ import print_function, division
import time
import numpy as np
class Timer(object):
def __init__(self):
self.time1 = time.time()
self.n = 0
self.step = 1
print(" # Sources CPU time (sec) Sources/sec ")
print(" ----------------------------------------------")
def display(self, force=False):
self.n += 1
if np.mod(self.n, self.step) == 0:
self.time2 = time.time()
if self.time2 - self.time1 < 1.:
self.step *= 10
else:
print(" %7i %10.1f %7.2f" % (self.n, self.time2 - self.time1, self.n / (self.time2 - self.time1)))
elif force:
self.time2 = time.time()
if self.time2 == self.time1:
print(" %7i %10.1f -------" % (self.n, self.time2 - self.time1))
else:
print(" %7i %10.1f %7.2f" % (self.n, self.time2 - self.time1, self.n / (self.time2 - self.time1)))
|
Fix division by zero error
|
Fix division by zero error
|
Python
|
bsd-2-clause
|
astrofrog/sedfitter
|
python
|
## Code Before:
from __future__ import print_function, division
import time
import numpy as np
class Timer(object):
def __init__(self):
self.time1 = time.time()
self.n = 0
self.step = 1
print(" # Sources CPU time (sec) Sources/sec ")
print(" ----------------------------------------------")
def display(self, force=False):
self.n += 1
if np.mod(self.n, self.step) == 0:
self.time2 = time.time()
if self.time2 - self.time1 < 1.:
self.step *= 10
else:
print(" %7i %10.1f %7.2f" % (self.n, self.time2 - self.time1, self.n / (self.time2 - self.time1)))
elif force:
self.time2 = time.time()
print(" %7i %10.1f %7.2f" % (self.n, self.time2 - self.time1, self.n / (self.time2 - self.time1)))
## Instruction:
Fix division by zero error
## Code After:
from __future__ import print_function, division
import time
import numpy as np
class Timer(object):
def __init__(self):
self.time1 = time.time()
self.n = 0
self.step = 1
print(" # Sources CPU time (sec) Sources/sec ")
print(" ----------------------------------------------")
def display(self, force=False):
self.n += 1
if np.mod(self.n, self.step) == 0:
self.time2 = time.time()
if self.time2 - self.time1 < 1.:
self.step *= 10
else:
print(" %7i %10.1f %7.2f" % (self.n, self.time2 - self.time1, self.n / (self.time2 - self.time1)))
elif force:
self.time2 = time.time()
if self.time2 == self.time1:
print(" %7i %10.1f -------" % (self.n, self.time2 - self.time1))
else:
print(" %7i %10.1f %7.2f" % (self.n, self.time2 - self.time1, self.n / (self.time2 - self.time1)))
|
# ... existing code ...
print(" %7i %10.1f %7.2f" % (self.n, self.time2 - self.time1, self.n / (self.time2 - self.time1)))
elif force:
self.time2 = time.time()
if self.time2 == self.time1:
print(" %7i %10.1f -------" % (self.n, self.time2 - self.time1))
else:
print(" %7i %10.1f %7.2f" % (self.n, self.time2 - self.time1, self.n / (self.time2 - self.time1)))
# ... rest of the code ...
|
62cddf84c9e46bb34c5f8320c0e739e38ebf5fec
|
setup.py
|
setup.py
|
from setuptools import setup
try:
from Cython.Build import cythonize
except ImportError:
CYTHON = False
else:
CYTHON = True
setup(
name='grako',
version='3.1.3-rc.1',
author='Juancarlo Añez',
author_email='[email protected]',
packages=['grako', 'grako.test'],
scripts=['scripts/grako'],
url='http://bitbucket.org/apalala/grako',
license='BSD License',
description='A generator of PEG/Packrat parsers from EBNF grammars.',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Environment :: Console',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Code Generators',
'Topic :: Software Development :: Compilers',
'Topic :: Software Development :: Interpreters',
'Topic :: Text Processing :: General'
],
ext_modules=cythonize(
"grako/**/*.py",
exclude=[
'grako/__main__.py',
'grako/test/__main__.py',
'grako/test/*.py'
]
) if CYTHON else [],
)
|
from setuptools import setup
try:
from Cython.Build import cythonize
except ImportError:
CYTHON = False
else:
CYTHON = True
setup(
name='grako',
version='3.1.3-rc.1',
author='Juancarlo Añez',
author_email='[email protected]',
packages=['grako', 'grako.codegen', 'grako.test'],
scripts=['scripts/grako'],
url='http://bitbucket.org/apalala/grako',
license='BSD License',
description='A generator of PEG/Packrat parsers from EBNF grammars.',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Environment :: Console',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Code Generators',
'Topic :: Software Development :: Compilers',
'Topic :: Software Development :: Interpreters',
'Topic :: Text Processing :: General'
],
ext_modules=cythonize(
"grako/**/*.py",
exclude=[
'grako/__main__.py',
'grako/test/__main__.py',
'grako/test/*.py'
]
) if CYTHON else [],
)
|
Include codegen package in distribution.
|
Include codegen package in distribution.
|
Python
|
bsd-2-clause
|
vmuriart/grako,frnknglrt/grako
|
python
|
## Code Before:
from setuptools import setup
try:
from Cython.Build import cythonize
except ImportError:
CYTHON = False
else:
CYTHON = True
setup(
name='grako',
version='3.1.3-rc.1',
author='Juancarlo Añez',
author_email='[email protected]',
packages=['grako', 'grako.test'],
scripts=['scripts/grako'],
url='http://bitbucket.org/apalala/grako',
license='BSD License',
description='A generator of PEG/Packrat parsers from EBNF grammars.',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Environment :: Console',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Code Generators',
'Topic :: Software Development :: Compilers',
'Topic :: Software Development :: Interpreters',
'Topic :: Text Processing :: General'
],
ext_modules=cythonize(
"grako/**/*.py",
exclude=[
'grako/__main__.py',
'grako/test/__main__.py',
'grako/test/*.py'
]
) if CYTHON else [],
)
## Instruction:
Include codegen package in distribution.
## Code After:
from setuptools import setup
try:
from Cython.Build import cythonize
except ImportError:
CYTHON = False
else:
CYTHON = True
setup(
name='grako',
version='3.1.3-rc.1',
author='Juancarlo Añez',
author_email='[email protected]',
packages=['grako', 'grako.codegen', 'grako.test'],
scripts=['scripts/grako'],
url='http://bitbucket.org/apalala/grako',
license='BSD License',
description='A generator of PEG/Packrat parsers from EBNF grammars.',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Environment :: Console',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Code Generators',
'Topic :: Software Development :: Compilers',
'Topic :: Software Development :: Interpreters',
'Topic :: Text Processing :: General'
],
ext_modules=cythonize(
"grako/**/*.py",
exclude=[
'grako/__main__.py',
'grako/test/__main__.py',
'grako/test/*.py'
]
) if CYTHON else [],
)
|
// ... existing code ...
version='3.1.3-rc.1',
author='Juancarlo Añez',
author_email='[email protected]',
packages=['grako', 'grako.codegen', 'grako.test'],
scripts=['scripts/grako'],
url='http://bitbucket.org/apalala/grako',
license='BSD License',
// ... rest of the code ...
|
0d3322de1944a1a64d6c77d4b52452509979e0c1
|
src/cobwebs/setup.py
|
src/cobwebs/setup.py
|
import sys
import shutil
import os
from setuptools import setup, find_packages
import cobwebs
import subprocess
if len(sys.argv) > 0:
if sys.argv[1] in ("install", "develop"):
try:
os.mkdir("/etc/spider/")
except FileExistsError:
print("Warning: /etc/spider directory already exists...")
print("Copying file to /etc/spider/")
ret = shutil.copy("conf/cobwebs.yaml", "/etc/spider/cobwebs.yaml")
print(ret)
subprocess.call(["ls", "-l", "/etc/spider"])
setup(
name='cobwebs',
version=cobwebs.__version__,
packages=find_packages(),
author="Asteroide",
author_email="asteroide__AT__domtombox.net",
description="A house for spider utilities",
long_description=open('README.md').read(),
# install_requires= ,
include_package_data=True,
url='https://github.com/asteroide/immo_spider',
classifiers=[
"Programming Language :: Python",
"Development Status :: 1 - Planning",
"License :: OSI Approved",
"Natural Language :: French",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.5",
"Topic :: Internet :: WWW/HTTP :: Indexing/Search",
"License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)"
],
)
|
import sys
import shutil
import os
from setuptools import setup, find_packages
import subprocess
if len(sys.argv) > 0:
if sys.argv[1] in ("install", "develop"):
try:
os.mkdir("/etc/spider/")
except FileExistsError:
print("Warning: /etc/spider directory already exists...")
print("Copying file to /etc/spider/")
ret = shutil.copy("conf/cobwebs.yaml", "/etc/spider/cobwebs.yaml")
print(ret)
subprocess.call(["ls", "-l", "/etc/spider"])
import cobwebs
setup(
name='cobwebs',
version=cobwebs.__version__,
packages=find_packages(),
author="Asteroide",
author_email="asteroide__AT__domtombox.net",
description="A house for spider utilities",
long_description=open('README.md').read(),
# install_requires= ,
include_package_data=True,
url='https://github.com/asteroide/immo_spider',
classifiers=[
"Programming Language :: Python",
"Development Status :: 1 - Planning",
"License :: OSI Approved",
"Natural Language :: French",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.5",
"Topic :: Internet :: WWW/HTTP :: Indexing/Search",
"License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)"
],
)
|
Move import of the main library.
|
Move import of the main library.
|
Python
|
apache-2.0
|
asteroide/immo_spider,asteroide/immo_spider,asteroide/immo_spider,asteroide/immo_spider
|
python
|
## Code Before:
import sys
import shutil
import os
from setuptools import setup, find_packages
import cobwebs
import subprocess
if len(sys.argv) > 0:
if sys.argv[1] in ("install", "develop"):
try:
os.mkdir("/etc/spider/")
except FileExistsError:
print("Warning: /etc/spider directory already exists...")
print("Copying file to /etc/spider/")
ret = shutil.copy("conf/cobwebs.yaml", "/etc/spider/cobwebs.yaml")
print(ret)
subprocess.call(["ls", "-l", "/etc/spider"])
setup(
name='cobwebs',
version=cobwebs.__version__,
packages=find_packages(),
author="Asteroide",
author_email="asteroide__AT__domtombox.net",
description="A house for spider utilities",
long_description=open('README.md').read(),
# install_requires= ,
include_package_data=True,
url='https://github.com/asteroide/immo_spider',
classifiers=[
"Programming Language :: Python",
"Development Status :: 1 - Planning",
"License :: OSI Approved",
"Natural Language :: French",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.5",
"Topic :: Internet :: WWW/HTTP :: Indexing/Search",
"License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)"
],
)
## Instruction:
Move import of the main library.
## Code After:
import sys
import shutil
import os
from setuptools import setup, find_packages
import subprocess
if len(sys.argv) > 0:
if sys.argv[1] in ("install", "develop"):
try:
os.mkdir("/etc/spider/")
except FileExistsError:
print("Warning: /etc/spider directory already exists...")
print("Copying file to /etc/spider/")
ret = shutil.copy("conf/cobwebs.yaml", "/etc/spider/cobwebs.yaml")
print(ret)
subprocess.call(["ls", "-l", "/etc/spider"])
import cobwebs
setup(
name='cobwebs',
version=cobwebs.__version__,
packages=find_packages(),
author="Asteroide",
author_email="asteroide__AT__domtombox.net",
description="A house for spider utilities",
long_description=open('README.md').read(),
# install_requires= ,
include_package_data=True,
url='https://github.com/asteroide/immo_spider',
classifiers=[
"Programming Language :: Python",
"Development Status :: 1 - Planning",
"License :: OSI Approved",
"Natural Language :: French",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.5",
"Topic :: Internet :: WWW/HTTP :: Indexing/Search",
"License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)"
],
)
|
...
import shutil
import os
from setuptools import setup, find_packages
import subprocess
...
ret = shutil.copy("conf/cobwebs.yaml", "/etc/spider/cobwebs.yaml")
print(ret)
subprocess.call(["ls", "-l", "/etc/spider"])
import cobwebs
setup(
...
|
0ee59d04cb2cbe93a3f4f87a34725fbcd1a66fc0
|
core/Reader.py
|
core/Reader.py
|
from io import StringIO
from collections import deque
class StreamReader:
def __init__(self, *args, stream_class=StringIO, **kwargs):
self.streamClass = stream_class
self.args = args
self.kwargs = kwargs
def read(self, parsing_pipeline):
parsing_pipeline.reset()
stream = self.streamClass(*self.args, **self.kwargs)
min_position = parsing_pipeline.get_min_position()
max_position = parsing_pipeline.get_max_position()
length = max_position - min_position + 1
current_position = -min_position
ar_index = list()
element = deque(stream.read(length))
while True:
result = parsing_pipeline.check(element, ref_position=-min_position)
if result is not None and result[0]:
ar_index.append((current_position, element[-min_position]))
next_character = stream.read(1)
current_position += 1
if next_character and result is not None:
element.popleft()
element.append(next_character)
else:
break
stream.close()
return ar_index
|
from io import StringIO
from collections import deque
class StreamReader:
def __init__(self, *args, stream_class=StringIO, **kwargs):
self.streamClass = stream_class
self.args = args
self.kwargs = kwargs
def read(self, parsing_pipeline):
parsing_pipeline.reset()
min_position = parsing_pipeline.get_min_position()
max_position = parsing_pipeline.get_max_position()
length = max_position - min_position + 1
stream = self.streamClass(*self.args, **self.kwargs)
current_position = -min_position
ar_index = list()
element = deque(stream.read(length))
if len(element) == length:
while True:
result = parsing_pipeline.check(element, ref_position=-min_position)
if result is not None and result[0]:
ar_index.append((current_position, element[-min_position]))
next_character = stream.read(1)
current_position += 1
if next_character and result is not None:
element.popleft()
element.append(next_character)
else:
break
stream.close()
return ar_index
else:
stream.close()
raise ValueError("Not enough characters to parse : " + str(len(element)))
|
Add not enough characters condition
|
Add not enough characters condition
|
Python
|
mit
|
JCH222/matriochkas
|
python
|
## Code Before:
from io import StringIO
from collections import deque
class StreamReader:
def __init__(self, *args, stream_class=StringIO, **kwargs):
self.streamClass = stream_class
self.args = args
self.kwargs = kwargs
def read(self, parsing_pipeline):
parsing_pipeline.reset()
stream = self.streamClass(*self.args, **self.kwargs)
min_position = parsing_pipeline.get_min_position()
max_position = parsing_pipeline.get_max_position()
length = max_position - min_position + 1
current_position = -min_position
ar_index = list()
element = deque(stream.read(length))
while True:
result = parsing_pipeline.check(element, ref_position=-min_position)
if result is not None and result[0]:
ar_index.append((current_position, element[-min_position]))
next_character = stream.read(1)
current_position += 1
if next_character and result is not None:
element.popleft()
element.append(next_character)
else:
break
stream.close()
return ar_index
## Instruction:
Add not enough characters condition
## Code After:
from io import StringIO
from collections import deque
class StreamReader:
def __init__(self, *args, stream_class=StringIO, **kwargs):
self.streamClass = stream_class
self.args = args
self.kwargs = kwargs
def read(self, parsing_pipeline):
parsing_pipeline.reset()
min_position = parsing_pipeline.get_min_position()
max_position = parsing_pipeline.get_max_position()
length = max_position - min_position + 1
stream = self.streamClass(*self.args, **self.kwargs)
current_position = -min_position
ar_index = list()
element = deque(stream.read(length))
if len(element) == length:
while True:
result = parsing_pipeline.check(element, ref_position=-min_position)
if result is not None and result[0]:
ar_index.append((current_position, element[-min_position]))
next_character = stream.read(1)
current_position += 1
if next_character and result is not None:
element.popleft()
element.append(next_character)
else:
break
stream.close()
return ar_index
else:
stream.close()
raise ValueError("Not enough characters to parse : " + str(len(element)))
|
// ... existing code ...
def read(self, parsing_pipeline):
parsing_pipeline.reset()
min_position = parsing_pipeline.get_min_position()
max_position = parsing_pipeline.get_max_position()
length = max_position - min_position + 1
stream = self.streamClass(*self.args, **self.kwargs)
current_position = -min_position
ar_index = list()
element = deque(stream.read(length))
if len(element) == length:
while True:
result = parsing_pipeline.check(element, ref_position=-min_position)
if result is not None and result[0]:
ar_index.append((current_position, element[-min_position]))
next_character = stream.read(1)
current_position += 1
if next_character and result is not None:
element.popleft()
element.append(next_character)
else:
break
stream.close()
return ar_index
else:
stream.close()
raise ValueError("Not enough characters to parse : " + str(len(element)))
// ... rest of the code ...
|
4387a8a38664abe86f0ff9d531ab3ba937f9adf7
|
tests/unit/test_main_views.py
|
tests/unit/test_main_views.py
|
import pytest
from flask import url_for
from pytest_flask import fixtures
from mdt_app.models import *
@pytest.mark.usefixtures('client_class')
class TestIndex:
def test_page_load(self):
assert self.client.get(url_for('main.index')).status_code == 200
@pytest.mark.usefixtures('client_class')
class TestCaseCreate:
def setup(self):
self.patient1 = Patient(id=1, hospital_number=12345678,
first_name='test1', last_name='patient',
date_of_birth='1988-10-09', sex='F')
def test_page_load(self, db_session):
db_session.add(self.patient1)
db_session.commit()
req_pass = self.client.get(url_for('main.case_create', patient_id=1))
req_no_id = self.client.get(url_for('main.case_create', patient_id=''))
assert req_pass.status_code == 200
assert req_no_id.status_code == 404, 'no id, page not found'
|
import pytest
from flask import url_for
from pytest_flask import fixtures
from mdt_app.models import *
@pytest.mark.usefixtures('client_class')
class TestIndex:
def test_page_load(self):
assert self.client.get(url_for('main.index')).status_code == 200
@pytest.mark.usefixtures('client_class')
class TestCaseCreate:
def test_setup(self, db_session):
patient1 = Patient(id=1, hospital_number=12345678,
first_name='test1', last_name='patient',
date_of_birth='1988-10-09', sex='F')
user = User()
consultant = User()
meeting = Meeting()
db_session.add(patient1)
db_session.commit()
def test_page_load(self):
req_pass = self.client.get(url_for('main.case_create', patient_id=1))
req_no_id = self.client.get(url_for('main.case_create', patient_id=''))
assert req_pass.status_code == 200
assert req_no_id.status_code == 404, 'no id, page not found'
def test_kept_in_db(self):
req_pass = self.client.get(url_for('main.case_create', patient_id=1))
assert req_pass.status_code == 200
|
Add Unit tests for views
|
Add Unit tests for views
|
Python
|
mit
|
stefpiatek/mdt-flask-app,stefpiatek/mdt-flask-app
|
python
|
## Code Before:
import pytest
from flask import url_for
from pytest_flask import fixtures
from mdt_app.models import *
@pytest.mark.usefixtures('client_class')
class TestIndex:
def test_page_load(self):
assert self.client.get(url_for('main.index')).status_code == 200
@pytest.mark.usefixtures('client_class')
class TestCaseCreate:
def setup(self):
self.patient1 = Patient(id=1, hospital_number=12345678,
first_name='test1', last_name='patient',
date_of_birth='1988-10-09', sex='F')
def test_page_load(self, db_session):
db_session.add(self.patient1)
db_session.commit()
req_pass = self.client.get(url_for('main.case_create', patient_id=1))
req_no_id = self.client.get(url_for('main.case_create', patient_id=''))
assert req_pass.status_code == 200
assert req_no_id.status_code == 404, 'no id, page not found'
## Instruction:
Add Unit tests for views
## Code After:
import pytest
from flask import url_for
from pytest_flask import fixtures
from mdt_app.models import *
@pytest.mark.usefixtures('client_class')
class TestIndex:
def test_page_load(self):
assert self.client.get(url_for('main.index')).status_code == 200
@pytest.mark.usefixtures('client_class')
class TestCaseCreate:
def test_setup(self, db_session):
patient1 = Patient(id=1, hospital_number=12345678,
first_name='test1', last_name='patient',
date_of_birth='1988-10-09', sex='F')
user = User()
consultant = User()
meeting = Meeting()
db_session.add(patient1)
db_session.commit()
def test_page_load(self):
req_pass = self.client.get(url_for('main.case_create', patient_id=1))
req_no_id = self.client.get(url_for('main.case_create', patient_id=''))
assert req_pass.status_code == 200
assert req_no_id.status_code == 404, 'no id, page not found'
def test_kept_in_db(self):
req_pass = self.client.get(url_for('main.case_create', patient_id=1))
assert req_pass.status_code == 200
|
// ... existing code ...
@pytest.mark.usefixtures('client_class')
class TestCaseCreate:
def test_setup(self, db_session):
patient1 = Patient(id=1, hospital_number=12345678,
first_name='test1', last_name='patient',
date_of_birth='1988-10-09', sex='F')
user = User()
consultant = User()
meeting = Meeting()
db_session.add(patient1)
db_session.commit()
def test_page_load(self):
req_pass = self.client.get(url_for('main.case_create', patient_id=1))
req_no_id = self.client.get(url_for('main.case_create', patient_id=''))
// ... modified code ...
assert req_pass.status_code == 200
assert req_no_id.status_code == 404, 'no id, page not found'
def test_kept_in_db(self):
req_pass = self.client.get(url_for('main.case_create', patient_id=1))
assert req_pass.status_code == 200
// ... rest of the code ...
|
d833601615d09c98fdc629e9b07490ffc218ff7d
|
bottleopener/platforms.h
|
bottleopener/platforms.h
|
//#define __PLATFORM_CARRIOTS__ 1
//#define __PLATFORM_INITIALSTATE__ 1
#define __PLATFORM_SHIFTR__ 1
#define __PLATFORM_THINGSPEAK__ 1
|
//#define __PLATFORM_INITIALSTATE__ 1
//#define __PLATFORM_SHIFTR__ 1
//#define __PLATFORM_THINGSPEAK__ 1
|
Change platform selection to Carriots
|
Change platform selection to Carriots
|
C
|
mit
|
Zenika/bottleopener_iot,Zenika/bottleopener_iot,Zenika/bottleopener_iot,Zenika/bottleopener_iot
|
c
|
## Code Before:
//#define __PLATFORM_CARRIOTS__ 1
//#define __PLATFORM_INITIALSTATE__ 1
#define __PLATFORM_SHIFTR__ 1
#define __PLATFORM_THINGSPEAK__ 1
## Instruction:
Change platform selection to Carriots
## Code After:
//#define __PLATFORM_INITIALSTATE__ 1
//#define __PLATFORM_SHIFTR__ 1
//#define __PLATFORM_THINGSPEAK__ 1
|
# ... existing code ...
//#define __PLATFORM_INITIALSTATE__ 1
//#define __PLATFORM_SHIFTR__ 1
//#define __PLATFORM_THINGSPEAK__ 1
# ... rest of the code ...
|
58eb4b2b034d90f45b3daa12900f24a390bb4782
|
setuptools/command/bdist_rpm.py
|
setuptools/command/bdist_rpm.py
|
from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm
class bdist_rpm(_bdist_rpm):
def run(self):
# ensure distro name is up-to-date
self.run_command('egg_info')
_bdist_rpm.run(self)
def _make_spec_file(self):
version = self.distribution.get_version()
rpmversion = version.replace('-','_')
spec = _bdist_rpm._make_spec_file(self)
line23 = '%define version ' + version
line24 = '%define version ' + rpmversion
spec = [
line.replace(
"Source0: %{name}-%{version}.tar",
"Source0: %{name}-%{unmangled_version}.tar"
).replace(
"setup.py install ",
"setup.py install --single-version-externally-managed "
).replace(
"%setup",
"%setup -n %{name}-%{unmangled_version}"
).replace(line23, line24)
for line in spec
]
insert_loc = spec.index(line24) + 1
unmangled_version = "%define unmangled_version " + version
spec.insert(insert_loc, unmangled_version)
return spec
|
from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm
class bdist_rpm(_bdist_rpm):
"""
Override the default bdist_rpm behavior to do the following:
1. Run egg_info to ensure the name and version are properly calculated.
2. Always run 'install' using --single-version-externally-managed to
disable eggs in RPM distributions.
3. Replace dash with underscore in the version numbers for better RPM
compatibility.
"""
def run(self):
# ensure distro name is up-to-date
self.run_command('egg_info')
_bdist_rpm.run(self)
def _make_spec_file(self):
version = self.distribution.get_version()
rpmversion = version.replace('-','_')
spec = _bdist_rpm._make_spec_file(self)
line23 = '%define version ' + version
line24 = '%define version ' + rpmversion
spec = [
line.replace(
"Source0: %{name}-%{version}.tar",
"Source0: %{name}-%{unmangled_version}.tar"
).replace(
"setup.py install ",
"setup.py install --single-version-externally-managed "
).replace(
"%setup",
"%setup -n %{name}-%{unmangled_version}"
).replace(line23, line24)
for line in spec
]
insert_loc = spec.index(line24) + 1
unmangled_version = "%define unmangled_version " + version
spec.insert(insert_loc, unmangled_version)
return spec
|
Replace outdated deprecating comments with a proper doc string.
|
Replace outdated deprecating comments with a proper doc string.
|
Python
|
mit
|
pypa/setuptools,pypa/setuptools,pypa/setuptools
|
python
|
## Code Before:
from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm
class bdist_rpm(_bdist_rpm):
def run(self):
# ensure distro name is up-to-date
self.run_command('egg_info')
_bdist_rpm.run(self)
def _make_spec_file(self):
version = self.distribution.get_version()
rpmversion = version.replace('-','_')
spec = _bdist_rpm._make_spec_file(self)
line23 = '%define version ' + version
line24 = '%define version ' + rpmversion
spec = [
line.replace(
"Source0: %{name}-%{version}.tar",
"Source0: %{name}-%{unmangled_version}.tar"
).replace(
"setup.py install ",
"setup.py install --single-version-externally-managed "
).replace(
"%setup",
"%setup -n %{name}-%{unmangled_version}"
).replace(line23, line24)
for line in spec
]
insert_loc = spec.index(line24) + 1
unmangled_version = "%define unmangled_version " + version
spec.insert(insert_loc, unmangled_version)
return spec
## Instruction:
Replace outdated deprecating comments with a proper doc string.
## Code After:
from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm
class bdist_rpm(_bdist_rpm):
"""
Override the default bdist_rpm behavior to do the following:
1. Run egg_info to ensure the name and version are properly calculated.
2. Always run 'install' using --single-version-externally-managed to
disable eggs in RPM distributions.
3. Replace dash with underscore in the version numbers for better RPM
compatibility.
"""
def run(self):
# ensure distro name is up-to-date
self.run_command('egg_info')
_bdist_rpm.run(self)
def _make_spec_file(self):
version = self.distribution.get_version()
rpmversion = version.replace('-','_')
spec = _bdist_rpm._make_spec_file(self)
line23 = '%define version ' + version
line24 = '%define version ' + rpmversion
spec = [
line.replace(
"Source0: %{name}-%{version}.tar",
"Source0: %{name}-%{unmangled_version}.tar"
).replace(
"setup.py install ",
"setup.py install --single-version-externally-managed "
).replace(
"%setup",
"%setup -n %{name}-%{unmangled_version}"
).replace(line23, line24)
for line in spec
]
insert_loc = spec.index(line24) + 1
unmangled_version = "%define unmangled_version " + version
spec.insert(insert_loc, unmangled_version)
return spec
|
...
from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm
class bdist_rpm(_bdist_rpm):
"""
Override the default bdist_rpm behavior to do the following:
1. Run egg_info to ensure the name and version are properly calculated.
2. Always run 'install' using --single-version-externally-managed to
disable eggs in RPM distributions.
3. Replace dash with underscore in the version numbers for better RPM
compatibility.
"""
def run(self):
# ensure distro name is up-to-date
...
|
00208e088ea62eb3c405e22f54a96e6e46869844
|
pubsub/backend/rabbitmq.py
|
pubsub/backend/rabbitmq.py
|
from gevent import monkey
monkey.patch_all()
import uuid
from kombu.mixins import ConsumerMixin
from pubsub.backend.base import BaseSubscriber, BasePublisher
from pubsub.helpers import get_config
from pubsub.backend.handlers import RabbitMQHandler
class RabbitMQPublisher(BasePublisher, RabbitMQHandler):
def __init__(self):
self.config = get_config('rabbitmq').get('publisher', None)
self.connection = self._connect()
def start(self):
self._exchange = self._create_exchange()
self._producer = self._create_producer()
def publish(self, message):
message_id = str(uuid.uuid4())
message = {'payload': message,
'message_id': message_id,
'reply_to': None}
self._producer.publish(
message, exchange=self._exchange, **self.config.get('publish'))
return message_id
class RabbitMQSubscriber(ConsumerMixin, BaseSubscriber, RabbitMQHandler):
def __init__(self):
self.config = get_config('rabbitmq').get('subscriber', None)
self.connection = self._connect()
def start(self):
self._exchange = self._create_exchange()
self._queue = self._create_queue()
def run_forever(self):
self.run()
def get_consumers(self, consumer, channel):
return [consumer(
queues=[self._queue],
callbacks=[self.on_message],
**self.config.get('consumer'))]
def on_message(self, body, message):
message.ack()
|
from gevent import monkey
monkey.patch_all()
import uuid
from kombu.mixins import ConsumerMixin
from pubsub.backend.base import BaseSubscriber, BasePublisher
from pubsub.helpers import get_config
from pubsub.backend.handlers import RabbitMQHandler
class RabbitMQPublisher(BasePublisher, RabbitMQHandler):
def __init__(self, config=None):
self.config = config or get_config('rabbitmq').get('publisher', None)
self.connection = self._connect()
def start(self):
self._exchange = self._create_exchange()
self._producer = self._create_producer()
def publish(self, message):
message_id = str(uuid.uuid4())
message = {'payload': message,
'message_id': message_id,
'reply_to': None}
self._producer.publish(
message, exchange=self._exchange, **self.config.get('publish'))
return message_id
class RabbitMQSubscriber(ConsumerMixin, BaseSubscriber, RabbitMQHandler):
def __init__(self, config=None):
self.config = config or get_config('rabbitmq').get('subscriber', None)
self.connection = self._connect()
def start(self):
self._exchange = self._create_exchange()
self._queue = self._create_queue()
def run_forever(self):
self.run()
def get_consumers(self, consumer, channel):
return [consumer(
queues=[self._queue],
callbacks=[self.on_message],
**self.config.get('consumer'))]
def on_message(self, body, message):
message.ack()
|
Add the possiblity to pass a conf file to Publisher and Subscriber class
|
Add the possiblity to pass a conf file to Publisher and Subscriber class
Closes #20
|
Python
|
mit
|
WeLikeAlpacas/Qpaca,WeLikeAlpacas/python-pubsub,csarcom/python-pubsub
|
python
|
## Code Before:
from gevent import monkey
monkey.patch_all()
import uuid
from kombu.mixins import ConsumerMixin
from pubsub.backend.base import BaseSubscriber, BasePublisher
from pubsub.helpers import get_config
from pubsub.backend.handlers import RabbitMQHandler
class RabbitMQPublisher(BasePublisher, RabbitMQHandler):
def __init__(self):
self.config = get_config('rabbitmq').get('publisher', None)
self.connection = self._connect()
def start(self):
self._exchange = self._create_exchange()
self._producer = self._create_producer()
def publish(self, message):
message_id = str(uuid.uuid4())
message = {'payload': message,
'message_id': message_id,
'reply_to': None}
self._producer.publish(
message, exchange=self._exchange, **self.config.get('publish'))
return message_id
class RabbitMQSubscriber(ConsumerMixin, BaseSubscriber, RabbitMQHandler):
def __init__(self):
self.config = get_config('rabbitmq').get('subscriber', None)
self.connection = self._connect()
def start(self):
self._exchange = self._create_exchange()
self._queue = self._create_queue()
def run_forever(self):
self.run()
def get_consumers(self, consumer, channel):
return [consumer(
queues=[self._queue],
callbacks=[self.on_message],
**self.config.get('consumer'))]
def on_message(self, body, message):
message.ack()
## Instruction:
Add the possiblity to pass a conf file to Publisher and Subscriber class
Closes #20
## Code After:
from gevent import monkey
monkey.patch_all()
import uuid
from kombu.mixins import ConsumerMixin
from pubsub.backend.base import BaseSubscriber, BasePublisher
from pubsub.helpers import get_config
from pubsub.backend.handlers import RabbitMQHandler
class RabbitMQPublisher(BasePublisher, RabbitMQHandler):
def __init__(self, config=None):
self.config = config or get_config('rabbitmq').get('publisher', None)
self.connection = self._connect()
def start(self):
self._exchange = self._create_exchange()
self._producer = self._create_producer()
def publish(self, message):
message_id = str(uuid.uuid4())
message = {'payload': message,
'message_id': message_id,
'reply_to': None}
self._producer.publish(
message, exchange=self._exchange, **self.config.get('publish'))
return message_id
class RabbitMQSubscriber(ConsumerMixin, BaseSubscriber, RabbitMQHandler):
def __init__(self, config=None):
self.config = config or get_config('rabbitmq').get('subscriber', None)
self.connection = self._connect()
def start(self):
self._exchange = self._create_exchange()
self._queue = self._create_queue()
def run_forever(self):
self.run()
def get_consumers(self, consumer, channel):
return [consumer(
queues=[self._queue],
callbacks=[self.on_message],
**self.config.get('consumer'))]
def on_message(self, body, message):
message.ack()
|
# ... existing code ...
class RabbitMQPublisher(BasePublisher, RabbitMQHandler):
def __init__(self, config=None):
self.config = config or get_config('rabbitmq').get('publisher', None)
self.connection = self._connect()
def start(self):
# ... modified code ...
class RabbitMQSubscriber(ConsumerMixin, BaseSubscriber, RabbitMQHandler):
def __init__(self, config=None):
self.config = config or get_config('rabbitmq').get('subscriber', None)
self.connection = self._connect()
def start(self):
# ... rest of the code ...
|
776e7f7c3146a4b3b36674aa6a1cf7a069055efb
|
sensorhub-driver-v4l/src/main/java/org/sensorhub/impl/sensor/v4l/V4LCameraConfig.java
|
sensorhub-driver-v4l/src/main/java/org/sensorhub/impl/sensor/v4l/V4LCameraConfig.java
|
/***************************** BEGIN LICENSE BLOCK ***************************
The contents of this file are subject to the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one
at http://mozilla.org/MPL/2.0/.
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the License.
Copyright (C) 2012-2015 Sensia Software LLC. All Rights Reserved.
******************************* END LICENSE BLOCK ***************************/
package org.sensorhub.impl.sensor.v4l;
import org.sensorhub.api.sensor.SensorConfig;
/**
* <p>
* Configuration class for the generic Video4Linux camera driver
* </p>
*
* @author Alex Robin <[email protected]>
* @since Sep 6, 2013
*/
public class V4LCameraConfig extends SensorConfig
{
/**
* Name of video device to use
* example: /dev/video0
*/
public String deviceName;
/**
* Maximum number of frames that can be kept in storage
* (These last N frames will be stored in memory)
*/
public int frameStorageCapacity;
/**
* Default camera params to use on startup
* These can then be changed with the control interface
*/
public V4LCameraParams defaultParams = new V4LCameraParams();
}
|
/***************************** BEGIN LICENSE BLOCK ***************************
The contents of this file are subject to the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one
at http://mozilla.org/MPL/2.0/.
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the License.
Copyright (C) 2012-2015 Sensia Software LLC. All Rights Reserved.
******************************* END LICENSE BLOCK ***************************/
package org.sensorhub.impl.sensor.v4l;
import org.sensorhub.api.sensor.SensorConfig;
/**
* <p>
* Configuration class for the generic Video4Linux camera driver
* </p>
*
* @author Alex Robin <[email protected]>
* @since Sep 6, 2013
*/
public class V4LCameraConfig extends SensorConfig
{
/**
* Name of video device to use (e.g. /dev/video0)
*/
public String deviceName = "/dev/video0";
/**
* Maximum number of frames that can be kept in storage
* (These last N frames will be stored in memory)
*/
public int frameStorageCapacity;
/**
* Default camera params to use on startup
* These can then be changed with the control interface
*/
public V4LCameraParams defaultParams = new V4LCameraParams();
}
|
Fix in ModuleRegistry to properly disable module without unloading them
|
Fix in ModuleRegistry to properly disable module without unloading them
|
Java
|
mpl-2.0
|
opensensorhub/osh-sensors
|
java
|
## Code Before:
/***************************** BEGIN LICENSE BLOCK ***************************
The contents of this file are subject to the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one
at http://mozilla.org/MPL/2.0/.
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the License.
Copyright (C) 2012-2015 Sensia Software LLC. All Rights Reserved.
******************************* END LICENSE BLOCK ***************************/
package org.sensorhub.impl.sensor.v4l;
import org.sensorhub.api.sensor.SensorConfig;
/**
* <p>
* Configuration class for the generic Video4Linux camera driver
* </p>
*
* @author Alex Robin <[email protected]>
* @since Sep 6, 2013
*/
public class V4LCameraConfig extends SensorConfig
{
/**
* Name of video device to use
* example: /dev/video0
*/
public String deviceName;
/**
* Maximum number of frames that can be kept in storage
* (These last N frames will be stored in memory)
*/
public int frameStorageCapacity;
/**
* Default camera params to use on startup
* These can then be changed with the control interface
*/
public V4LCameraParams defaultParams = new V4LCameraParams();
}
## Instruction:
Fix in ModuleRegistry to properly disable module without unloading them
## Code After:
/***************************** BEGIN LICENSE BLOCK ***************************
The contents of this file are subject to the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one
at http://mozilla.org/MPL/2.0/.
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the License.
Copyright (C) 2012-2015 Sensia Software LLC. All Rights Reserved.
******************************* END LICENSE BLOCK ***************************/
package org.sensorhub.impl.sensor.v4l;
import org.sensorhub.api.sensor.SensorConfig;
/**
* <p>
* Configuration class for the generic Video4Linux camera driver
* </p>
*
* @author Alex Robin <[email protected]>
* @since Sep 6, 2013
*/
public class V4LCameraConfig extends SensorConfig
{
/**
* Name of video device to use (e.g. /dev/video0)
*/
public String deviceName = "/dev/video0";
/**
* Maximum number of frames that can be kept in storage
* (These last N frames will be stored in memory)
*/
public int frameStorageCapacity;
/**
* Default camera params to use on startup
* These can then be changed with the control interface
*/
public V4LCameraParams defaultParams = new V4LCameraParams();
}
|
# ... existing code ...
{
/**
* Name of video device to use (e.g. /dev/video0)
*/
public String deviceName = "/dev/video0";
/**
# ... rest of the code ...
|
3201618e6105204892a52265ecd84372f6b7925b
|
CMake/TestQnanhibit.c
|
CMake/TestQnanhibit.c
|
int
main(int argc, char *argv[])
{
char *me;
float qnan, zero;
int i;
me = argv[0];
if (sizeof(float) != sizeof(int))
{
fprintf(stderr, "%s: MADNESS: sizeof(float)=%d != sizeof(int)=%d\n",
me, (int)sizeof(float), (int)sizeof(int));
return -1;
}
zero = 0;
qnan=zero/zero;
i=*(int*)(&qnan);
printf("-DTEEM_QNANHIBIT=%d\n", (i >> 22) & 1);
return (int)((i >> 22) & 1);
}
|
int
main(int argc, char *argv[])
{
#if defined(__BORLANDC__)
// Disable floating point exceptions in Borland
_control87(MCW_EM, MCW_EM);
#endif // defined(__BORLANDC__)
char *me;
float qnan, zero;
int i;
me = argv[0];
if (sizeof(float) != sizeof(int))
{
fprintf(stderr, "%s: MADNESS: sizeof(float)=%d != sizeof(int)=%d\n",
me, (int)sizeof(float), (int)sizeof(int));
return -1;
}
zero = 0;
qnan=zero/zero;
i=*(int*)(&qnan);
printf("-DTEEM_QNANHIBIT=%d\n", (i >> 22) & 1);
return (int)((i >> 22) & 1);
}
|
Disable floating point exceptions on Borland compiler
|
FIX: Disable floating point exceptions on Borland compiler
|
C
|
apache-2.0
|
LucHermitte/ITK,cpatrick/ITK-RemoteIO,hendradarwin/ITK,PlutoniumHeart/ITK,blowekamp/ITK,InsightSoftwareConsortium/ITK,daviddoria/itkHoughTransform,biotrump/ITK,hendradarwin/ITK,LucHermitte/ITK,CapeDrew/DCMTK-ITK,CapeDrew/DCMTK-ITK,wkjeong/ITK,InsightSoftwareConsortium/ITK,eile/ITK,hinerm/ITK,GEHC-Surgery/ITK,paulnovo/ITK,fbudin69500/ITK,BlueBrain/ITK,vfonov/ITK,jmerkow/ITK,Kitware/ITK,Kitware/ITK,fuentesdt/InsightToolkit-dev,hjmjohnson/ITK,heimdali/ITK,fedral/ITK,fedral/ITK,fedral/ITK,stnava/ITK,GEHC-Surgery/ITK,cpatrick/ITK-RemoteIO,fbudin69500/ITK,Kitware/ITK,heimdali/ITK,hjmjohnson/ITK,BlueBrain/ITK,hinerm/ITK,daviddoria/itkHoughTransform,richardbeare/ITK,heimdali/ITK,hinerm/ITK,hendradarwin/ITK,BlueBrain/ITK,msmolens/ITK,malaterre/ITK,BRAINSia/ITK,atsnyder/ITK,BRAINSia/ITK,Kitware/ITK,heimdali/ITK,daviddoria/itkHoughTransform,PlutoniumHeart/ITK,InsightSoftwareConsortium/ITK,wkjeong/ITK,wkjeong/ITK,BRAINSia/ITK,LucasGandel/ITK,zachary-williamson/ITK,CapeDrew/DCMTK-ITK,ajjl/ITK,rhgong/itk-with-dom,fuentesdt/InsightToolkit-dev,cpatrick/ITK-RemoteIO,thewtex/ITK,biotrump/ITK,fuentesdt/InsightToolkit-dev,stnava/ITK,BRAINSia/ITK,richardbeare/ITK,paulnovo/ITK,paulnovo/ITK,hjmjohnson/ITK,ajjl/ITK,LucasGandel/ITK,jmerkow/ITK,wkjeong/ITK,jmerkow/ITK,hendradarwin/ITK,msmolens/ITK,jcfr/ITK,paulnovo/ITK,blowekamp/ITK,paulnovo/ITK,CapeDrew/DITK,cpatrick/ITK-RemoteIO,zachary-williamson/ITK,msmolens/ITK,LucasGandel/ITK,paulnovo/ITK,InsightSoftwareConsortium/ITK,CapeDrew/DITK,eile/ITK,ajjl/ITK,msmolens/ITK,fbudin69500/ITK,BRAINSia/ITK,PlutoniumHeart/ITK,GEHC-Surgery/ITK,GEHC-Surgery/ITK,jcfr/ITK,malaterre/ITK,CapeDrew/DITK,GEHC-Surgery/ITK,spinicist/ITK,PlutoniumHeart/ITK,malaterre/ITK,biotrump/ITK,ajjl/ITK,thewtex/ITK,biotrump/ITK,CapeDrew/DITK,fbudin69500/ITK,jcfr/ITK,CapeDrew/DITK,LucasGandel/ITK,fedral/ITK,rhgong/itk-with-dom,PlutoniumHeart/ITK,zachary-williamson/ITK,InsightSoftwareConsortium/ITK,itkvideo/ITK,rhgong/itk-with-dom,Kitware/ITK,atsnyder/ITK,malaterre/ITK,ajjl/ITK,fbudin69500/ITK,richardbeare/ITK,fbudin69500/ITK,jmerkow/ITK,thewtex/ITK,heimdali/ITK,heimdali/ITK,spinicist/ITK,hinerm/ITK,paulnovo/ITK,zachary-williamson/ITK,CapeDrew/DCMTK-ITK,richardbeare/ITK,rhgong/itk-with-dom,hinerm/ITK,GEHC-Surgery/ITK,wkjeong/ITK,zachary-williamson/ITK,BRAINSia/ITK,jmerkow/ITK,atsnyder/ITK,blowekamp/ITK,itkvideo/ITK,jcfr/ITK,cpatrick/ITK-RemoteIO,GEHC-Surgery/ITK,itkvideo/ITK,jmerkow/ITK,daviddoria/itkHoughTransform,ajjl/ITK,BRAINSia/ITK,rhgong/itk-with-dom,paulnovo/ITK,malaterre/ITK,jcfr/ITK,hinerm/ITK,richardbeare/ITK,itkvideo/ITK,BlueBrain/ITK,zachary-williamson/ITK,biotrump/ITK,stnava/ITK,hjmjohnson/ITK,PlutoniumHeart/ITK,PlutoniumHeart/ITK,itkvideo/ITK,blowekamp/ITK,blowekamp/ITK,wkjeong/ITK,thewtex/ITK,blowekamp/ITK,richardbeare/ITK,stnava/ITK,malaterre/ITK,rhgong/itk-with-dom,PlutoniumHeart/ITK,eile/ITK,Kitware/ITK,thewtex/ITK,rhgong/itk-with-dom,CapeDrew/DCMTK-ITK,wkjeong/ITK,fuentesdt/InsightToolkit-dev,InsightSoftwareConsortium/ITK,spinicist/ITK,wkjeong/ITK,daviddoria/itkHoughTransform,LucasGandel/ITK,spinicist/ITK,CapeDrew/DITK,atsnyder/ITK,hinerm/ITK,hinerm/ITK,jmerkow/ITK,vfonov/ITK,LucHermitte/ITK,stnava/ITK,blowekamp/ITK,fedral/ITK,LucasGandel/ITK,msmolens/ITK,ajjl/ITK,atsnyder/ITK,BlueBrain/ITK,CapeDrew/DCMTK-ITK,hjmjohnson/ITK,vfonov/ITK,itkvideo/ITK,rhgong/itk-with-dom,fuentesdt/InsightToolkit-dev,heimdali/ITK,jmerkow/ITK,spinicist/ITK,spinicist/ITK,heimdali/ITK,LucHermitte/ITK,zachary-williamson/ITK,fedral/ITK,thewtex/ITK,Kitware/ITK,vfonov/ITK,spinicist/ITK,thewtex/ITK,atsnyder/ITK,vfonov/ITK,fuentesdt/InsightToolkit-dev,hendradarwin/ITK,msmolens/ITK,CapeDrew/DITK,eile/ITK,spinicist/ITK,CapeDrew/DITK,CapeDrew/DCMTK-ITK,InsightSoftwareConsortium/ITK,malaterre/ITK,vfonov/ITK,LucHermitte/ITK,itkvideo/ITK,CapeDrew/DCMTK-ITK,eile/ITK,daviddoria/itkHoughTransform,jcfr/ITK,cpatrick/ITK-RemoteIO,fbudin69500/ITK,vfonov/ITK,stnava/ITK,CapeDrew/DCMTK-ITK,fedral/ITK,hinerm/ITK,hendradarwin/ITK,fuentesdt/InsightToolkit-dev,LucasGandel/ITK,LucHermitte/ITK,atsnyder/ITK,jcfr/ITK,eile/ITK,blowekamp/ITK,malaterre/ITK,cpatrick/ITK-RemoteIO,biotrump/ITK,daviddoria/itkHoughTransform,BlueBrain/ITK,hjmjohnson/ITK,biotrump/ITK,richardbeare/ITK,vfonov/ITK,LucHermitte/ITK,spinicist/ITK,stnava/ITK,vfonov/ITK,fuentesdt/InsightToolkit-dev,atsnyder/ITK,hendradarwin/ITK,eile/ITK,hjmjohnson/ITK,cpatrick/ITK-RemoteIO,msmolens/ITK,stnava/ITK,zachary-williamson/ITK,LucasGandel/ITK,fuentesdt/InsightToolkit-dev,zachary-williamson/ITK,BlueBrain/ITK,daviddoria/itkHoughTransform,stnava/ITK,daviddoria/itkHoughTransform,CapeDrew/DITK,eile/ITK,LucHermitte/ITK,eile/ITK,GEHC-Surgery/ITK,BlueBrain/ITK,itkvideo/ITK,hendradarwin/ITK,atsnyder/ITK,biotrump/ITK,ajjl/ITK,malaterre/ITK,jcfr/ITK,msmolens/ITK,fbudin69500/ITK,itkvideo/ITK,fedral/ITK
|
c
|
## Code Before:
int
main(int argc, char *argv[])
{
char *me;
float qnan, zero;
int i;
me = argv[0];
if (sizeof(float) != sizeof(int))
{
fprintf(stderr, "%s: MADNESS: sizeof(float)=%d != sizeof(int)=%d\n",
me, (int)sizeof(float), (int)sizeof(int));
return -1;
}
zero = 0;
qnan=zero/zero;
i=*(int*)(&qnan);
printf("-DTEEM_QNANHIBIT=%d\n", (i >> 22) & 1);
return (int)((i >> 22) & 1);
}
## Instruction:
FIX: Disable floating point exceptions on Borland compiler
## Code After:
int
main(int argc, char *argv[])
{
#if defined(__BORLANDC__)
// Disable floating point exceptions in Borland
_control87(MCW_EM, MCW_EM);
#endif // defined(__BORLANDC__)
char *me;
float qnan, zero;
int i;
me = argv[0];
if (sizeof(float) != sizeof(int))
{
fprintf(stderr, "%s: MADNESS: sizeof(float)=%d != sizeof(int)=%d\n",
me, (int)sizeof(float), (int)sizeof(int));
return -1;
}
zero = 0;
qnan=zero/zero;
i=*(int*)(&qnan);
printf("-DTEEM_QNANHIBIT=%d\n", (i >> 22) & 1);
return (int)((i >> 22) & 1);
}
|
# ... existing code ...
int
main(int argc, char *argv[])
{
#if defined(__BORLANDC__)
// Disable floating point exceptions in Borland
_control87(MCW_EM, MCW_EM);
#endif // defined(__BORLANDC__)
char *me;
float qnan, zero;
int i;
# ... rest of the code ...
|
3fec4855d53a5077762892295582601cc193d068
|
tests/scoring_engine/models/test_kb.py
|
tests/scoring_engine/models/test_kb.py
|
from scoring_engine.models.kb import KB
from tests.scoring_engine.unit_test import UnitTest
class TestKB(UnitTest):
def test_init_property(self):
kb = KB(name="task_ids", value="1,2,3,4,5,6")
assert kb.id is None
assert kb.name == 'task_ids'
assert kb.value == '1,2,3,4,5,6'
def test_basic_kb(self):
kb = KB(name="task_ids", value="1,2,3,4,5,6")
self.db.save(kb)
assert kb.id is not None
|
from scoring_engine.models.kb import KB
from tests.scoring_engine.unit_test import UnitTest
class TestKB(UnitTest):
def test_init_property(self):
kb = KB(name="task_ids", value="1,2,3,4,5,6", round_num=100)
assert kb.id is None
assert kb.name == 'task_ids'
assert kb.value == '1,2,3,4,5,6'
assert kb.round_num == 100
def test_basic_kb(self):
kb = KB(name="task_ids", value="1,2,3,4,5,6", round_num=50)
self.db.save(kb)
assert kb.id is not None
|
Update kb test to check for port_num
|
Update kb test to check for port_num
Signed-off-by: Brandon Myers <[email protected]>
|
Python
|
mit
|
pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine
|
python
|
## Code Before:
from scoring_engine.models.kb import KB
from tests.scoring_engine.unit_test import UnitTest
class TestKB(UnitTest):
def test_init_property(self):
kb = KB(name="task_ids", value="1,2,3,4,5,6")
assert kb.id is None
assert kb.name == 'task_ids'
assert kb.value == '1,2,3,4,5,6'
def test_basic_kb(self):
kb = KB(name="task_ids", value="1,2,3,4,5,6")
self.db.save(kb)
assert kb.id is not None
## Instruction:
Update kb test to check for port_num
Signed-off-by: Brandon Myers <[email protected]>
## Code After:
from scoring_engine.models.kb import KB
from tests.scoring_engine.unit_test import UnitTest
class TestKB(UnitTest):
def test_init_property(self):
kb = KB(name="task_ids", value="1,2,3,4,5,6", round_num=100)
assert kb.id is None
assert kb.name == 'task_ids'
assert kb.value == '1,2,3,4,5,6'
assert kb.round_num == 100
def test_basic_kb(self):
kb = KB(name="task_ids", value="1,2,3,4,5,6", round_num=50)
self.db.save(kb)
assert kb.id is not None
|
# ... existing code ...
class TestKB(UnitTest):
def test_init_property(self):
kb = KB(name="task_ids", value="1,2,3,4,5,6", round_num=100)
assert kb.id is None
assert kb.name == 'task_ids'
assert kb.value == '1,2,3,4,5,6'
assert kb.round_num == 100
def test_basic_kb(self):
kb = KB(name="task_ids", value="1,2,3,4,5,6", round_num=50)
self.db.save(kb)
assert kb.id is not None
# ... rest of the code ...
|
687fbdc298835b32241457b8efebe55f5d1e65b6
|
OpenTreeMap/src/org/azavea/otm/data/Model.java
|
OpenTreeMap/src/org/azavea/otm/data/Model.java
|
package org.azavea.otm.data;
import org.json.JSONException;
import org.json.JSONObject;
public abstract class Model {
protected JSONObject data;
protected long getLongOrDefault(String key, Long defaultValue) throws JSONException {
if (data.isNull(key)){
return defaultValue;
} else {
return data.getLong(key);
}
}
public void setData(JSONObject data) {
this.data = data;
}
public JSONObject getData() {
return data;
}
}
|
package org.azavea.otm.data;
import org.json.JSONException;
import org.json.JSONObject;
public abstract class Model {
protected JSONObject data;
protected long getLongOrDefault(String key, Long defaultValue) throws JSONException {
if (data.isNull(key)){
return defaultValue;
} else {
return data.getLong(key);
}
}
public void setData(JSONObject data) {
this.data = data;
}
public JSONObject getData() {
return data;
}
public Object getField(String key) {
try {
return data.get(key);
} catch (JSONException e) {
return null;
}
}
}
|
Add getField method to abstract model
|
Add getField method to abstract model
My future implementation of a Field class will depend on getting
plot data by field key, rather than through the model. This opens
access to the underlaying JSON representation with keys identified
in the configuration details.
|
Java
|
agpl-3.0
|
OpenTreeMap/otm-android,maurizi/otm-android,OpenTreeMap/otm-android,maurizi/otm-android,OpenTreeMap/otm-android,maurizi/otm-android
|
java
|
## Code Before:
package org.azavea.otm.data;
import org.json.JSONException;
import org.json.JSONObject;
public abstract class Model {
protected JSONObject data;
protected long getLongOrDefault(String key, Long defaultValue) throws JSONException {
if (data.isNull(key)){
return defaultValue;
} else {
return data.getLong(key);
}
}
public void setData(JSONObject data) {
this.data = data;
}
public JSONObject getData() {
return data;
}
}
## Instruction:
Add getField method to abstract model
My future implementation of a Field class will depend on getting
plot data by field key, rather than through the model. This opens
access to the underlaying JSON representation with keys identified
in the configuration details.
## Code After:
package org.azavea.otm.data;
import org.json.JSONException;
import org.json.JSONObject;
public abstract class Model {
protected JSONObject data;
protected long getLongOrDefault(String key, Long defaultValue) throws JSONException {
if (data.isNull(key)){
return defaultValue;
} else {
return data.getLong(key);
}
}
public void setData(JSONObject data) {
this.data = data;
}
public JSONObject getData() {
return data;
}
public Object getField(String key) {
try {
return data.get(key);
} catch (JSONException e) {
return null;
}
}
}
|
# ... existing code ...
public JSONObject getData() {
return data;
}
public Object getField(String key) {
try {
return data.get(key);
} catch (JSONException e) {
return null;
}
}
}
# ... rest of the code ...
|
53948f31d9054a747853e62cbe63ce91e4fe6e22
|
setup.py
|
setup.py
|
import os
from setuptools import setup
setup(
name = "prometheus_client",
version = "0.0.9",
author = "Brian Brazil",
author_email = "[email protected]",
description = ("Python client for the Prometheus monitoring system."),
long_description = ("See https://github.com/prometheus/client_python/blob/master/README.md for documentation."),
license = "Apache Software License 2.0",
keywords = "prometheus monitoring instrumentation client",
url = "https://github.com/prometheus/client_python",
packages=['prometheus_client'],
test_suite="tests",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"Topic :: System :: Monitoring",
"License :: OSI Approved :: Apache Software License",
],
)
|
import os
from setuptools import setup
setup(
name = "prometheus_client",
version = "0.0.9",
author = "Brian Brazil",
author_email = "[email protected]",
description = ("Python client for the Prometheus monitoring system."),
long_description = ("See https://github.com/prometheus/client_python/blob/master/README.md for documentation."),
license = "Apache Software License 2.0",
keywords = "prometheus monitoring instrumentation client",
url = "https://github.com/prometheus/client_python",
packages=['prometheus_client', 'prometheus_client.bridge'],
test_suite="tests",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"Topic :: System :: Monitoring",
"License :: OSI Approved :: Apache Software License",
],
)
|
Split __init__.py into separate files.
|
Split __init__.py into separate files.
|
Python
|
apache-2.0
|
prometheus/client_python,justyns/client_python,arturhoo/client_python,alexander-95/client_python,thomaso-mirodin/client_python,korfuri/client_python,machinelady/client_python
|
python
|
## Code Before:
import os
from setuptools import setup
setup(
name = "prometheus_client",
version = "0.0.9",
author = "Brian Brazil",
author_email = "[email protected]",
description = ("Python client for the Prometheus monitoring system."),
long_description = ("See https://github.com/prometheus/client_python/blob/master/README.md for documentation."),
license = "Apache Software License 2.0",
keywords = "prometheus monitoring instrumentation client",
url = "https://github.com/prometheus/client_python",
packages=['prometheus_client'],
test_suite="tests",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"Topic :: System :: Monitoring",
"License :: OSI Approved :: Apache Software License",
],
)
## Instruction:
Split __init__.py into separate files.
## Code After:
import os
from setuptools import setup
setup(
name = "prometheus_client",
version = "0.0.9",
author = "Brian Brazil",
author_email = "[email protected]",
description = ("Python client for the Prometheus monitoring system."),
long_description = ("See https://github.com/prometheus/client_python/blob/master/README.md for documentation."),
license = "Apache Software License 2.0",
keywords = "prometheus monitoring instrumentation client",
url = "https://github.com/prometheus/client_python",
packages=['prometheus_client', 'prometheus_client.bridge'],
test_suite="tests",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"Topic :: System :: Monitoring",
"License :: OSI Approved :: Apache Software License",
],
)
|
# ... existing code ...
license = "Apache Software License 2.0",
keywords = "prometheus monitoring instrumentation client",
url = "https://github.com/prometheus/client_python",
packages=['prometheus_client', 'prometheus_client.bridge'],
test_suite="tests",
classifiers=[
"Development Status :: 4 - Beta",
# ... rest of the code ...
|
205616b0a23143cdc5ceb6fb8333cf6074ce737b
|
kitchen/pycompat25/collections/__init__.py
|
kitchen/pycompat25/collections/__init__.py
|
try:
from collections import defaultdict
except ImportError:
from _defaultdict import defaultdict
__all__ = ('defaultdict',)
|
try:
#:E0611: deafultdict doesn't exist in python-2.4 or less but that's why we
# have it in a try: except:. So we can use our version if necessary.
from collections import defaultdict
except ImportError:
from kitchen.pycompat25.collections._defaultdict import defaultdict
__all__ = ('defaultdict',)
|
Fix pylint error in this module
|
Fix pylint error in this module
|
Python
|
lgpl-2.1
|
fedora-infra/kitchen,fedora-infra/kitchen
|
python
|
## Code Before:
try:
from collections import defaultdict
except ImportError:
from _defaultdict import defaultdict
__all__ = ('defaultdict',)
## Instruction:
Fix pylint error in this module
## Code After:
try:
#:E0611: deafultdict doesn't exist in python-2.4 or less but that's why we
# have it in a try: except:. So we can use our version if necessary.
from collections import defaultdict
except ImportError:
from kitchen.pycompat25.collections._defaultdict import defaultdict
__all__ = ('defaultdict',)
|
...
try:
#:E0611: deafultdict doesn't exist in python-2.4 or less but that's why we
# have it in a try: except:. So we can use our version if necessary.
from collections import defaultdict
except ImportError:
from kitchen.pycompat25.collections._defaultdict import defaultdict
__all__ = ('defaultdict',)
...
|
80d3768eb5c31cd5af0b2df6648fa22e79e35379
|
test/main.c
|
test/main.c
|
/***************************************************************************//**
@file main.c
@author Stephen Brennan
@date Created Thursday, 12 September 2013
@brief Run tests on the libstephen library.
@copyright Copyright (c) 2013-2015, Stephen Brennan. Released under the
Revised BSD License. See the LICENSE.txt file for details.
*******************************************************************************/
#include <stdio.h>
#include "libstephen/base.h"
#include "tests.h"
/**
Main test function
*/
int main(int argc, char ** argv)
{
linked_list_test();
array_list_test();
hash_table_test();
bit_field_test();
iter_test();
list_test();
args_test();
charbuf_test();
log_test();
string_test();
fsm_test();
fsm_io_test();
regex_test();
regex_search_test();
// return args_test_main(argc, argv);
}
|
/***************************************************************************//**
@file main.c
@author Stephen Brennan
@date Created Thursday, 12 September 2013
@brief Run tests on the libstephen library.
@copyright Copyright (c) 2013-2015, Stephen Brennan. Released under the
Revised BSD License. See the LICENSE.txt file for details.
*******************************************************************************/
#include <stdio.h>
#include "libstephen/base.h"
#include "libstephen/log.h"
#include "tests.h"
/**
Main test function
*/
int main(int argc, char ** argv)
{
sl_set_level(NULL, LEVEL_INFO);
linked_list_test();
array_list_test();
hash_table_test();
bit_field_test();
iter_test();
list_test();
args_test();
charbuf_test();
string_test();
fsm_test();
fsm_io_test();
regex_test();
regex_search_test();
log_test();
// return args_test_main(argc, argv);
}
|
Set log level in tests.
|
Set log level in tests.
|
C
|
bsd-3-clause
|
brenns10/libstephen,brenns10/libstephen,brenns10/libstephen
|
c
|
## Code Before:
/***************************************************************************//**
@file main.c
@author Stephen Brennan
@date Created Thursday, 12 September 2013
@brief Run tests on the libstephen library.
@copyright Copyright (c) 2013-2015, Stephen Brennan. Released under the
Revised BSD License. See the LICENSE.txt file for details.
*******************************************************************************/
#include <stdio.h>
#include "libstephen/base.h"
#include "tests.h"
/**
Main test function
*/
int main(int argc, char ** argv)
{
linked_list_test();
array_list_test();
hash_table_test();
bit_field_test();
iter_test();
list_test();
args_test();
charbuf_test();
log_test();
string_test();
fsm_test();
fsm_io_test();
regex_test();
regex_search_test();
// return args_test_main(argc, argv);
}
## Instruction:
Set log level in tests.
## Code After:
/***************************************************************************//**
@file main.c
@author Stephen Brennan
@date Created Thursday, 12 September 2013
@brief Run tests on the libstephen library.
@copyright Copyright (c) 2013-2015, Stephen Brennan. Released under the
Revised BSD License. See the LICENSE.txt file for details.
*******************************************************************************/
#include <stdio.h>
#include "libstephen/base.h"
#include "libstephen/log.h"
#include "tests.h"
/**
Main test function
*/
int main(int argc, char ** argv)
{
sl_set_level(NULL, LEVEL_INFO);
linked_list_test();
array_list_test();
hash_table_test();
bit_field_test();
iter_test();
list_test();
args_test();
charbuf_test();
string_test();
fsm_test();
fsm_io_test();
regex_test();
regex_search_test();
log_test();
// return args_test_main(argc, argv);
}
|
// ... existing code ...
#include <stdio.h>
#include "libstephen/base.h"
#include "libstephen/log.h"
#include "tests.h"
/**
// ... modified code ...
*/
int main(int argc, char ** argv)
{
sl_set_level(NULL, LEVEL_INFO);
linked_list_test();
array_list_test();
hash_table_test();
...
list_test();
args_test();
charbuf_test();
string_test();
fsm_test();
fsm_io_test();
regex_test();
regex_search_test();
log_test();
// return args_test_main(argc, argv);
}
// ... rest of the code ...
|
87a4c494c18039a296775dab8acf910f83fb59b8
|
djangoappengine/utils.py
|
djangoappengine/utils.py
|
from google.appengine.api import apiproxy_stub_map
import os
have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3'))
if have_appserver:
appid = os.environ.get('APPLICATION_ID')
else:
try:
from google.appengine.tools import dev_appserver
from .boot import PROJECT_DIR
appconfig, unused = dev_appserver.LoadAppConfig(PROJECT_DIR, {})
appid = appconfig.application
except ImportError, e:
raise Exception('Could not get appid. Is your app.yaml file missing? '
'Error was: %s' % e)
on_production_server = have_appserver and \
not os.environ.get('SERVER_SOFTWARE', '').lower().startswith('devel')
|
from google.appengine.api import apiproxy_stub_map
import os
have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3'))
if have_appserver:
appid = os.environ.get('APPLICATION_ID')
else:
try:
from google.appengine.tools import dev_appserver
from .boot import PROJECT_DIR
try:
appconfig, unused = dev_appserver.LoadAppConfig(PROJECT_DIR, {})
except ValueError:
# https://bitbucket.org/wkornewald/django-nonrel/issue/13/managepy-test-broken-with-gae-sdk-16
appconfig, unused, from_cache = dev_appserver.LoadAppConfig(PROJECT_DIR, {})
appid = appconfig.application
except ImportError, e:
raise Exception('Could not get appid. Is your app.yaml file missing? '
'Error was: %s' % e)
on_production_server = have_appserver and \
not os.environ.get('SERVER_SOFTWARE', '').lower().startswith('devel')
|
Make prosthetic-runner work with GAE SDK 1.6
|
Make prosthetic-runner work with GAE SDK 1.6
|
Python
|
mit
|
philterphactory/prosthetic-runner,philterphactory/prosthetic-runner,philterphactory/prosthetic-runner
|
python
|
## Code Before:
from google.appengine.api import apiproxy_stub_map
import os
have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3'))
if have_appserver:
appid = os.environ.get('APPLICATION_ID')
else:
try:
from google.appengine.tools import dev_appserver
from .boot import PROJECT_DIR
appconfig, unused = dev_appserver.LoadAppConfig(PROJECT_DIR, {})
appid = appconfig.application
except ImportError, e:
raise Exception('Could not get appid. Is your app.yaml file missing? '
'Error was: %s' % e)
on_production_server = have_appserver and \
not os.environ.get('SERVER_SOFTWARE', '').lower().startswith('devel')
## Instruction:
Make prosthetic-runner work with GAE SDK 1.6
## Code After:
from google.appengine.api import apiproxy_stub_map
import os
have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3'))
if have_appserver:
appid = os.environ.get('APPLICATION_ID')
else:
try:
from google.appengine.tools import dev_appserver
from .boot import PROJECT_DIR
try:
appconfig, unused = dev_appserver.LoadAppConfig(PROJECT_DIR, {})
except ValueError:
# https://bitbucket.org/wkornewald/django-nonrel/issue/13/managepy-test-broken-with-gae-sdk-16
appconfig, unused, from_cache = dev_appserver.LoadAppConfig(PROJECT_DIR, {})
appid = appconfig.application
except ImportError, e:
raise Exception('Could not get appid. Is your app.yaml file missing? '
'Error was: %s' % e)
on_production_server = have_appserver and \
not os.environ.get('SERVER_SOFTWARE', '').lower().startswith('devel')
|
// ... existing code ...
try:
from google.appengine.tools import dev_appserver
from .boot import PROJECT_DIR
try:
appconfig, unused = dev_appserver.LoadAppConfig(PROJECT_DIR, {})
except ValueError:
# https://bitbucket.org/wkornewald/django-nonrel/issue/13/managepy-test-broken-with-gae-sdk-16
appconfig, unused, from_cache = dev_appserver.LoadAppConfig(PROJECT_DIR, {})
appid = appconfig.application
except ImportError, e:
raise Exception('Could not get appid. Is your app.yaml file missing? '
// ... rest of the code ...
|
339f5c6d7cc5b3a70fa71fd423c0a4226acc77e7
|
valor/schema.py
|
valor/schema.py
|
import json
class Schema(dict):
"""
Lightweight encapsulation of a JSON Schema.
"""
@classmethod
def from_file(cls, path_or_stream):
"""
Create a schema from a file name or stream.
"""
if hasattr(path_or_stream, 'read'):
return cls(json.load(path_or_stream))
else:
with open(path_or_stream) as fp:
return cls(json.load(fp))
def resolve_ref(self, ref):
return Reference(ref).resolve(self)
class Reference(object):
def __init__(self, ref):
if not ref.startswith('#'):
raise ValueError("non-fragment references are not supported (got: %s)" % ref)
self.ref = ref
def resolve(self, schema):
# Very overly simplisitic - doesn't handle array indexes, etc. However,
# works with Heroku's schema, so good enough for a prototype.
node = schema
for bit in self.ref.split('/')[1:]:
node = node[bit]
return node
|
import json
import jsonpointer
class Schema(dict):
"""
Lightweight encapsulation of a JSON Schema.
"""
@classmethod
def from_file(cls, path_or_stream):
"""
Create a schema from a file name or stream.
"""
if hasattr(path_or_stream, 'read'):
return cls(json.load(path_or_stream))
else:
with open(path_or_stream) as fp:
return cls(json.load(fp))
def resolve_ref(self, ref):
if not ref.startswith('#'):
raise ValueError("non-fragment references are not supported (got: %s)" % ref)
return jsonpointer.resolve_pointer(self, ref.lstrip('#'))
|
Use jsonpointer instead of my own terrible Reference class.
|
Use jsonpointer instead of my own terrible Reference class.
|
Python
|
bsd-3-clause
|
jacobian/valor
|
python
|
## Code Before:
import json
class Schema(dict):
"""
Lightweight encapsulation of a JSON Schema.
"""
@classmethod
def from_file(cls, path_or_stream):
"""
Create a schema from a file name or stream.
"""
if hasattr(path_or_stream, 'read'):
return cls(json.load(path_or_stream))
else:
with open(path_or_stream) as fp:
return cls(json.load(fp))
def resolve_ref(self, ref):
return Reference(ref).resolve(self)
class Reference(object):
def __init__(self, ref):
if not ref.startswith('#'):
raise ValueError("non-fragment references are not supported (got: %s)" % ref)
self.ref = ref
def resolve(self, schema):
# Very overly simplisitic - doesn't handle array indexes, etc. However,
# works with Heroku's schema, so good enough for a prototype.
node = schema
for bit in self.ref.split('/')[1:]:
node = node[bit]
return node
## Instruction:
Use jsonpointer instead of my own terrible Reference class.
## Code After:
import json
import jsonpointer
class Schema(dict):
"""
Lightweight encapsulation of a JSON Schema.
"""
@classmethod
def from_file(cls, path_or_stream):
"""
Create a schema from a file name or stream.
"""
if hasattr(path_or_stream, 'read'):
return cls(json.load(path_or_stream))
else:
with open(path_or_stream) as fp:
return cls(json.load(fp))
def resolve_ref(self, ref):
if not ref.startswith('#'):
raise ValueError("non-fragment references are not supported (got: %s)" % ref)
return jsonpointer.resolve_pointer(self, ref.lstrip('#'))
|
...
import json
import jsonpointer
class Schema(dict):
"""
...
return cls(json.load(fp))
def resolve_ref(self, ref):
if not ref.startswith('#'):
raise ValueError("non-fragment references are not supported (got: %s)" % ref)
return jsonpointer.resolve_pointer(self, ref.lstrip('#'))
...
|
8dc48de240577ebe1ed88d9ca9299cb6e19ef3fe
|
bottomsheet/src/main/java/org/michaelbel/bottomsheet/annotation/New.java
|
bottomsheet/src/main/java/org/michaelbel/bottomsheet/annotation/New.java
|
package org.michaelbel.bottomsheet.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Date: Sut, Mar 3 2018
* Time: 20:09 MSK
*
* @author Michael Bel
*/
@Retention(RetentionPolicy.CLASS)
@Target({
ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR,
ElementType.FIELD,
ElementType.METHOD,
ElementType.TYPE })
@Documented
@SuppressWarnings("all")
public @interface New {}
|
package org.michaelbel.bottomsheet.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Date: Sut, Mar 3 2018
* Time: 20:09 MSK
*
* @author Michael Bel
*/
@Retention(RetentionPolicy.SOURCE)
@Target({
ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR,
ElementType.FIELD,
ElementType.METHOD,
ElementType.TYPE })
@Documented
@SuppressWarnings("all")
public @interface New {
String version();
}
|
Update retention policy and add version field
|
Update retention policy and add version field
|
Java
|
apache-2.0
|
michaelbel/BottomSheet
|
java
|
## Code Before:
package org.michaelbel.bottomsheet.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Date: Sut, Mar 3 2018
* Time: 20:09 MSK
*
* @author Michael Bel
*/
@Retention(RetentionPolicy.CLASS)
@Target({
ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR,
ElementType.FIELD,
ElementType.METHOD,
ElementType.TYPE })
@Documented
@SuppressWarnings("all")
public @interface New {}
## Instruction:
Update retention policy and add version field
## Code After:
package org.michaelbel.bottomsheet.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Date: Sut, Mar 3 2018
* Time: 20:09 MSK
*
* @author Michael Bel
*/
@Retention(RetentionPolicy.SOURCE)
@Target({
ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR,
ElementType.FIELD,
ElementType.METHOD,
ElementType.TYPE })
@Documented
@SuppressWarnings("all")
public @interface New {
String version();
}
|
# ... existing code ...
* @author Michael Bel
*/
@Retention(RetentionPolicy.SOURCE)
@Target({
ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR,
# ... modified code ...
ElementType.TYPE })
@Documented
@SuppressWarnings("all")
public @interface New {
String version();
}
# ... rest of the code ...
|
79f7d8052333fcace914fa27ea2deb5f0d7cdbfc
|
readers/models.py
|
readers/models.py
|
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from model_utils.models import TimeStampedModel
class Reader(TimeStampedModel):
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
(IBOOKS, IBOOKS),
(KINDLE, KINDLE),
)
name = models.CharField(max_length=100, null=True)
user = models.ForeignKey(User)
kind = models.CharField(max_length=10, choices=TYPES)
email = models.EmailField()
def __str__(self):
return "{}'s {}".format(self.user, self.kind)
def get_absolute_url(self):
return reverse("reader-detail", kwargs={'pk': self.id})
|
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from model_utils.models import TimeStampedModel
class Reader(TimeStampedModel):
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
(IBOOKS, 'iBooks (.epub, .pdf)'),
(KINDLE, 'Kindle (.mobi, .pdf)'),
)
name = models.CharField(max_length=100, null=True)
user = models.ForeignKey(User)
kind = models.CharField(max_length=10, choices=TYPES)
email = models.EmailField()
def __str__(self):
return "{}'s {}".format(self.user, self.kind)
def get_absolute_url(self):
return reverse("reader-detail", kwargs={'pk': self.id})
|
Make what reader can handle what clearer
|
Make what reader can handle what clearer
|
Python
|
mit
|
phildini/bockus,phildini/bockus,phildini/bockus
|
python
|
## Code Before:
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from model_utils.models import TimeStampedModel
class Reader(TimeStampedModel):
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
(IBOOKS, IBOOKS),
(KINDLE, KINDLE),
)
name = models.CharField(max_length=100, null=True)
user = models.ForeignKey(User)
kind = models.CharField(max_length=10, choices=TYPES)
email = models.EmailField()
def __str__(self):
return "{}'s {}".format(self.user, self.kind)
def get_absolute_url(self):
return reverse("reader-detail", kwargs={'pk': self.id})
## Instruction:
Make what reader can handle what clearer
## Code After:
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from model_utils.models import TimeStampedModel
class Reader(TimeStampedModel):
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
(IBOOKS, 'iBooks (.epub, .pdf)'),
(KINDLE, 'Kindle (.mobi, .pdf)'),
)
name = models.CharField(max_length=100, null=True)
user = models.ForeignKey(User)
kind = models.CharField(max_length=10, choices=TYPES)
email = models.EmailField()
def __str__(self):
return "{}'s {}".format(self.user, self.kind)
def get_absolute_url(self):
return reverse("reader-detail", kwargs={'pk': self.id})
|
...
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
(IBOOKS, 'iBooks (.epub, .pdf)'),
(KINDLE, 'Kindle (.mobi, .pdf)'),
)
name = models.CharField(max_length=100, null=True)
...
|
e848724c65f5ce2434d866543ba9587ac223d56e
|
premis_event_service/forms.py
|
premis_event_service/forms.py
|
from django import forms
import settings
OUTCOME_CHOICES = settings.EVENT_OUTCOME_CHOICES
EVENT_TYPE_CHOICES = settings.EVENT_TYPE_CHOICES
class EventSearchForm(forms.Form):
outcome = forms.ChoiceField(
widget=forms.Select(
attrs={
'id': 'prependedInput',
'class': 'input-small',
}
),
choices=OUTCOME_CHOICES,
)
event_type = forms.ChoiceField(
widget=forms.Select(
attrs={
'id': 'prependedInput',
'class': 'input-medium',
}
),
choices=EVENT_TYPE_CHOICES,
)
start_date = forms.DateField(
widget=forms.DateInput(
attrs={
'id': 'startdatepicker',
'placeholder': 'Start Date',
'class': 'input-small',
}
)
)
end_date = forms.DateField(
widget=forms.DateInput(
attrs={
'id': 'enddatepicker',
'placeholder': 'End Date',
'class': 'input-small',
}
)
)
linked_object_id = forms.CharField(
widget=forms.TextInput(
attrs={
'placeholder': 'Linked Object ID',
'class': 'input-medium',
}
),
max_length=20,
)
|
from django import forms
import settings
OUTCOME_CHOICES = settings.EVENT_OUTCOME_CHOICES
EVENT_TYPE_CHOICES = settings.EVENT_TYPE_CHOICES
class EventSearchForm(forms.Form):
outcome = forms.ChoiceField(
widget=forms.Select(
attrs={
'id': 'prependedInput',
'class': 'input-small',
}
),
choices=OUTCOME_CHOICES,
required=False)
event_type = forms.ChoiceField(
widget=forms.Select(
attrs={
'id': 'prependedInput',
'class': 'input-medium',
}
),
choices=EVENT_TYPE_CHOICES,
required=False)
start_date = forms.DateField(
widget=forms.DateInput(
attrs={
'id': 'startdatepicker',
'placeholder': 'Start Date',
'class': 'input-small',
}
),
required=False)
end_date = forms.DateField(
widget=forms.DateInput(
attrs={
'id': 'enddatepicker',
'placeholder': 'End Date',
'class': 'input-small',
}
),
required=False)
linked_object_id = forms.CharField(
widget=forms.TextInput(
attrs={
'placeholder': 'Linked Object ID',
'class': 'input-medium',
}
),
max_length=20,
required=False,
)
|
Make all search form fields optional.
|
Make all search form fields optional.
|
Python
|
bsd-3-clause
|
unt-libraries/django-premis-event-service,unt-libraries/django-premis-event-service,unt-libraries/django-premis-event-service
|
python
|
## Code Before:
from django import forms
import settings
OUTCOME_CHOICES = settings.EVENT_OUTCOME_CHOICES
EVENT_TYPE_CHOICES = settings.EVENT_TYPE_CHOICES
class EventSearchForm(forms.Form):
outcome = forms.ChoiceField(
widget=forms.Select(
attrs={
'id': 'prependedInput',
'class': 'input-small',
}
),
choices=OUTCOME_CHOICES,
)
event_type = forms.ChoiceField(
widget=forms.Select(
attrs={
'id': 'prependedInput',
'class': 'input-medium',
}
),
choices=EVENT_TYPE_CHOICES,
)
start_date = forms.DateField(
widget=forms.DateInput(
attrs={
'id': 'startdatepicker',
'placeholder': 'Start Date',
'class': 'input-small',
}
)
)
end_date = forms.DateField(
widget=forms.DateInput(
attrs={
'id': 'enddatepicker',
'placeholder': 'End Date',
'class': 'input-small',
}
)
)
linked_object_id = forms.CharField(
widget=forms.TextInput(
attrs={
'placeholder': 'Linked Object ID',
'class': 'input-medium',
}
),
max_length=20,
)
## Instruction:
Make all search form fields optional.
## Code After:
from django import forms
import settings
OUTCOME_CHOICES = settings.EVENT_OUTCOME_CHOICES
EVENT_TYPE_CHOICES = settings.EVENT_TYPE_CHOICES
class EventSearchForm(forms.Form):
outcome = forms.ChoiceField(
widget=forms.Select(
attrs={
'id': 'prependedInput',
'class': 'input-small',
}
),
choices=OUTCOME_CHOICES,
required=False)
event_type = forms.ChoiceField(
widget=forms.Select(
attrs={
'id': 'prependedInput',
'class': 'input-medium',
}
),
choices=EVENT_TYPE_CHOICES,
required=False)
start_date = forms.DateField(
widget=forms.DateInput(
attrs={
'id': 'startdatepicker',
'placeholder': 'Start Date',
'class': 'input-small',
}
),
required=False)
end_date = forms.DateField(
widget=forms.DateInput(
attrs={
'id': 'enddatepicker',
'placeholder': 'End Date',
'class': 'input-small',
}
),
required=False)
linked_object_id = forms.CharField(
widget=forms.TextInput(
attrs={
'placeholder': 'Linked Object ID',
'class': 'input-medium',
}
),
max_length=20,
required=False,
)
|
// ... existing code ...
}
),
choices=OUTCOME_CHOICES,
required=False)
event_type = forms.ChoiceField(
widget=forms.Select(
attrs={
// ... modified code ...
}
),
choices=EVENT_TYPE_CHOICES,
required=False)
start_date = forms.DateField(
widget=forms.DateInput(
attrs={
...
'placeholder': 'Start Date',
'class': 'input-small',
}
),
required=False)
end_date = forms.DateField(
widget=forms.DateInput(
attrs={
...
'placeholder': 'End Date',
'class': 'input-small',
}
),
required=False)
linked_object_id = forms.CharField(
widget=forms.TextInput(
attrs={
...
}
),
max_length=20,
required=False,
)
// ... rest of the code ...
|
84ebb92850dabfde0318b641ecef8547ce601e95
|
src/nl/rubensten/texifyidea/run/compiler/BiberCompiler.kt
|
src/nl/rubensten/texifyidea/run/compiler/BiberCompiler.kt
|
package nl.rubensten.texifyidea.run.compiler
import com.intellij.openapi.project.Project
import nl.rubensten.texifyidea.run.BibtexRunConfiguration
/**
* @author Thomas Schouten
*/
internal object BiberCompiler : Compiler<BibtexRunConfiguration> {
override val displayName = "Biber"
override val executableName = "biber"
override fun getCommand(runConfig: BibtexRunConfiguration, project: Project): List<String>? {
val command = mutableListOf<String>()
command.apply {
if (runConfig.compilerPath != null) {
add(runConfig.compilerPath!!)
}
else add(executableName)
// Biber can find auxiliary files, but the flag is different from bibtex
// add("--output-directory=${runConfig.auxDir?.path ?: ""}")
add("--output-directory=${runConfig.mainFile?.parent?.path ?: ""}")
runConfig.compilerArguments?.let { addAll(it.split("""\s+""".toRegex())) }
// todo replace this test
add("../auxil/" + (runConfig.mainFile?.nameWithoutExtension ?: return null))
}
return command.toList()
}
}
|
package nl.rubensten.texifyidea.run.compiler
import com.intellij.openapi.project.Project
import nl.rubensten.texifyidea.run.BibtexRunConfiguration
/**
* @author Thomas Schouten
*/
internal object BiberCompiler : Compiler<BibtexRunConfiguration> {
override val displayName = "Biber"
override val executableName = "biber"
override fun getCommand(runConfig: BibtexRunConfiguration, project: Project): List<String>? {
val command = mutableListOf<String>()
command.apply {
if (runConfig.compilerPath != null) {
add(runConfig.compilerPath!!)
}
else add(executableName)
// Biber can find auxiliary files, but the flag is different from bibtex.
// The following flag assumes the command is executed in the directory where the .bcf control file is.
// The extra directory added is the directory from which the path to the .bib resource file is searched as specified in the .bcf file.
add("--input-directory=${runConfig.mainFile?.parent?.path ?: ""}")
runConfig.compilerArguments?.let { addAll(it.split("""\s+""".toRegex())) }
add(runConfig.mainFile?.nameWithoutExtension ?: return null)
}
return command.toList()
}
}
|
Fix biber flag to include resource file
|
Fix biber flag to include resource file
|
Kotlin
|
mit
|
Ruben-Sten/TeXiFy-IDEA,Ruben-Sten/TeXiFy-IDEA,Ruben-Sten/TeXiFy-IDEA,Ruben-Sten/TeXiFy-IDEA
|
kotlin
|
## Code Before:
package nl.rubensten.texifyidea.run.compiler
import com.intellij.openapi.project.Project
import nl.rubensten.texifyidea.run.BibtexRunConfiguration
/**
* @author Thomas Schouten
*/
internal object BiberCompiler : Compiler<BibtexRunConfiguration> {
override val displayName = "Biber"
override val executableName = "biber"
override fun getCommand(runConfig: BibtexRunConfiguration, project: Project): List<String>? {
val command = mutableListOf<String>()
command.apply {
if (runConfig.compilerPath != null) {
add(runConfig.compilerPath!!)
}
else add(executableName)
// Biber can find auxiliary files, but the flag is different from bibtex
// add("--output-directory=${runConfig.auxDir?.path ?: ""}")
add("--output-directory=${runConfig.mainFile?.parent?.path ?: ""}")
runConfig.compilerArguments?.let { addAll(it.split("""\s+""".toRegex())) }
// todo replace this test
add("../auxil/" + (runConfig.mainFile?.nameWithoutExtension ?: return null))
}
return command.toList()
}
}
## Instruction:
Fix biber flag to include resource file
## Code After:
package nl.rubensten.texifyidea.run.compiler
import com.intellij.openapi.project.Project
import nl.rubensten.texifyidea.run.BibtexRunConfiguration
/**
* @author Thomas Schouten
*/
internal object BiberCompiler : Compiler<BibtexRunConfiguration> {
override val displayName = "Biber"
override val executableName = "biber"
override fun getCommand(runConfig: BibtexRunConfiguration, project: Project): List<String>? {
val command = mutableListOf<String>()
command.apply {
if (runConfig.compilerPath != null) {
add(runConfig.compilerPath!!)
}
else add(executableName)
// Biber can find auxiliary files, but the flag is different from bibtex.
// The following flag assumes the command is executed in the directory where the .bcf control file is.
// The extra directory added is the directory from which the path to the .bib resource file is searched as specified in the .bcf file.
add("--input-directory=${runConfig.mainFile?.parent?.path ?: ""}")
runConfig.compilerArguments?.let { addAll(it.split("""\s+""".toRegex())) }
add(runConfig.mainFile?.nameWithoutExtension ?: return null)
}
return command.toList()
}
}
|
# ... existing code ...
}
else add(executableName)
// Biber can find auxiliary files, but the flag is different from bibtex.
// The following flag assumes the command is executed in the directory where the .bcf control file is.
// The extra directory added is the directory from which the path to the .bib resource file is searched as specified in the .bcf file.
add("--input-directory=${runConfig.mainFile?.parent?.path ?: ""}")
runConfig.compilerArguments?.let { addAll(it.split("""\s+""".toRegex())) }
add(runConfig.mainFile?.nameWithoutExtension ?: return null)
}
return command.toList()
# ... rest of the code ...
|
762147b8660a507ac5db8d0408162e8463b2fe8e
|
daiquiri/registry/serializers.py
|
daiquiri/registry/serializers.py
|
from rest_framework import serializers
from daiquiri.core.serializers import JSONListField, JSONDictField
class DublincoreSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
description = serializers.SerializerMethodField()
publisher = serializers.SerializerMethodField()
subjects = serializers.ReadOnlyField()
def get_description(self, obj):
return obj['content']['description']
def get_publisher(self, obj):
return obj['curation']['publisher']
class VoresourceSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
created = serializers.ReadOnlyField()
updated = serializers.ReadOnlyField()
voresource_status = serializers.ReadOnlyField(default='active')
curation = JSONDictField(default={})
content = JSONDictField(default={})
capabilities = JSONListField(default=[])
tableset = JSONListField(default=[])
managed_authority = serializers.ReadOnlyField(default=None)
managing_org = serializers.ReadOnlyField(default=None)
type = serializers.ReadOnlyField()
|
from rest_framework import serializers
from daiquiri.core.serializers import JSONDictField, JSONListField
class DublincoreSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
description = serializers.SerializerMethodField()
publisher = serializers.SerializerMethodField()
subjects = serializers.ReadOnlyField()
def get_description(self, obj):
return obj['content']['description']
def get_publisher(self, obj):
return obj['curation']['publisher']
class VoresourceSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
created = serializers.ReadOnlyField()
updated = serializers.ReadOnlyField()
type = serializers.ReadOnlyField()
status = serializers.ReadOnlyField()
curation = JSONDictField(default={})
content = JSONDictField(default={})
capabilities = JSONListField(default=[])
tableset = JSONListField(default=[])
managed_authority = serializers.ReadOnlyField(default=None)
managing_org = serializers.ReadOnlyField(default=None)
|
Fix status field in OAI-PMH
|
Fix status field in OAI-PMH
|
Python
|
apache-2.0
|
aipescience/django-daiquiri,aipescience/django-daiquiri,aipescience/django-daiquiri
|
python
|
## Code Before:
from rest_framework import serializers
from daiquiri.core.serializers import JSONListField, JSONDictField
class DublincoreSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
description = serializers.SerializerMethodField()
publisher = serializers.SerializerMethodField()
subjects = serializers.ReadOnlyField()
def get_description(self, obj):
return obj['content']['description']
def get_publisher(self, obj):
return obj['curation']['publisher']
class VoresourceSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
created = serializers.ReadOnlyField()
updated = serializers.ReadOnlyField()
voresource_status = serializers.ReadOnlyField(default='active')
curation = JSONDictField(default={})
content = JSONDictField(default={})
capabilities = JSONListField(default=[])
tableset = JSONListField(default=[])
managed_authority = serializers.ReadOnlyField(default=None)
managing_org = serializers.ReadOnlyField(default=None)
type = serializers.ReadOnlyField()
## Instruction:
Fix status field in OAI-PMH
## Code After:
from rest_framework import serializers
from daiquiri.core.serializers import JSONDictField, JSONListField
class DublincoreSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
description = serializers.SerializerMethodField()
publisher = serializers.SerializerMethodField()
subjects = serializers.ReadOnlyField()
def get_description(self, obj):
return obj['content']['description']
def get_publisher(self, obj):
return obj['curation']['publisher']
class VoresourceSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
created = serializers.ReadOnlyField()
updated = serializers.ReadOnlyField()
type = serializers.ReadOnlyField()
status = serializers.ReadOnlyField()
curation = JSONDictField(default={})
content = JSONDictField(default={})
capabilities = JSONListField(default=[])
tableset = JSONListField(default=[])
managed_authority = serializers.ReadOnlyField(default=None)
managing_org = serializers.ReadOnlyField(default=None)
|
// ... existing code ...
from rest_framework import serializers
from daiquiri.core.serializers import JSONDictField, JSONListField
class DublincoreSerializer(serializers.Serializer):
// ... modified code ...
title = serializers.ReadOnlyField()
created = serializers.ReadOnlyField()
updated = serializers.ReadOnlyField()
type = serializers.ReadOnlyField()
status = serializers.ReadOnlyField()
curation = JSONDictField(default={})
content = JSONDictField(default={})
...
managed_authority = serializers.ReadOnlyField(default=None)
managing_org = serializers.ReadOnlyField(default=None)
// ... rest of the code ...
|
ed92a324cceddce96f2cff51a103c6ca15f62d8e
|
asterix/test.py
|
asterix/test.py
|
""" Utility functions to help testing. """
from unittest.mock import Mock
class dummy(object):
def __init__(self):
self.components = {}
def get(self, name, default):
if name not in self.components:
self.components[name] = Mock()
return self.components[name]
class dummy_master(object):
def __init__(self):
setattr(self, "__components", dummy())
|
""" Utility functions to help testing. """
from unittest.mock import Mock
class dummy(object):
def __init__(self):
self.components = {}
def get(self, name, default=None):
if name not in self.components:
self.components[name] = Mock()
return self.components[name]
class dummy_master(object):
def __init__(self):
setattr(self, "__components", dummy())
def get(self, name):
return self.__components.components.get(name)
|
Add facade to mocked components
|
Add facade to mocked components
|
Python
|
mit
|
hkupty/asterix
|
python
|
## Code Before:
""" Utility functions to help testing. """
from unittest.mock import Mock
class dummy(object):
def __init__(self):
self.components = {}
def get(self, name, default):
if name not in self.components:
self.components[name] = Mock()
return self.components[name]
class dummy_master(object):
def __init__(self):
setattr(self, "__components", dummy())
## Instruction:
Add facade to mocked components
## Code After:
""" Utility functions to help testing. """
from unittest.mock import Mock
class dummy(object):
def __init__(self):
self.components = {}
def get(self, name, default=None):
if name not in self.components:
self.components[name] = Mock()
return self.components[name]
class dummy_master(object):
def __init__(self):
setattr(self, "__components", dummy())
def get(self, name):
return self.__components.components.get(name)
|
# ... existing code ...
def __init__(self):
self.components = {}
def get(self, name, default=None):
if name not in self.components:
self.components[name] = Mock()
# ... modified code ...
def __init__(self):
setattr(self, "__components", dummy())
def get(self, name):
return self.__components.components.get(name)
# ... rest of the code ...
|
76ed5eb9d9d2f3a453de6976f52221e6970b6b71
|
tests/unit/test_offline_compression.py
|
tests/unit/test_offline_compression.py
|
import os
import shutil
import tempfile
from django.test import TestCase
from django.core.management import call_command
from django.test.utils import override_settings
TMP_STATIC_DIR = tempfile.mkdtemp()
@override_settings(
COMPRESS_ENABLED=True,
COMPRESS_OFFLINE=True,
COMPRESS_ROOT=TMP_STATIC_DIR
)
class TestOfflineCompression(TestCase):
def tearDown(self):
super(TestOfflineCompression, self).tearDown()
if os.path.exists(TMP_STATIC_DIR):
shutil.rmtree(TMP_STATIC_DIR)
def test_(self):
call_command('compress')
|
import os
import shutil
import tempfile
from django.test import TestCase
from django.core.management import call_command
from django.test.utils import override_settings
TMP_STATIC_DIR = tempfile.mkdtemp()
@override_settings(
COMPRESS_ENABLED=True,
COMPRESS_OFFLINE=True,
COMPRESS_ROOT=TMP_STATIC_DIR
)
class TestOfflineCompression(TestCase):
def tearDown(self):
super(TestOfflineCompression, self).tearDown()
if os.path.exists(TMP_STATIC_DIR):
shutil.rmtree(TMP_STATIC_DIR)
def test_(self):
call_command('compress', verbosity=0)
|
Add test for offline compression using django_compressor
|
Add test for offline compression using django_compressor
|
Python
|
bsd-3-clause
|
tangentlabs/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages
|
python
|
## Code Before:
import os
import shutil
import tempfile
from django.test import TestCase
from django.core.management import call_command
from django.test.utils import override_settings
TMP_STATIC_DIR = tempfile.mkdtemp()
@override_settings(
COMPRESS_ENABLED=True,
COMPRESS_OFFLINE=True,
COMPRESS_ROOT=TMP_STATIC_DIR
)
class TestOfflineCompression(TestCase):
def tearDown(self):
super(TestOfflineCompression, self).tearDown()
if os.path.exists(TMP_STATIC_DIR):
shutil.rmtree(TMP_STATIC_DIR)
def test_(self):
call_command('compress')
## Instruction:
Add test for offline compression using django_compressor
## Code After:
import os
import shutil
import tempfile
from django.test import TestCase
from django.core.management import call_command
from django.test.utils import override_settings
TMP_STATIC_DIR = tempfile.mkdtemp()
@override_settings(
COMPRESS_ENABLED=True,
COMPRESS_OFFLINE=True,
COMPRESS_ROOT=TMP_STATIC_DIR
)
class TestOfflineCompression(TestCase):
def tearDown(self):
super(TestOfflineCompression, self).tearDown()
if os.path.exists(TMP_STATIC_DIR):
shutil.rmtree(TMP_STATIC_DIR)
def test_(self):
call_command('compress', verbosity=0)
|
// ... existing code ...
shutil.rmtree(TMP_STATIC_DIR)
def test_(self):
call_command('compress', verbosity=0)
// ... rest of the code ...
|
15cb279724a646368066591e81467e1b26d61938
|
examples/charts/file/steps.py
|
examples/charts/file/steps.py
|
from bokeh.charts import Step, show, output_file
# build a dataset where multiple columns measure the same thing
data = dict(python=[2, 3, 7, 5, 26, 221, 44, 233, 254, 265, 266, 267, 120, 111],
pypy=[12, 33, 47, 15, 126, 121, 144, 233, 254, 225, 226, 267, 110, 130],
jython=[22, 43, 10, 25, 26, 101, 114, 203, 194, 215, 201, 227, 139, 160],
test=['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'bar']
)
# create a line chart where each column of measures receives a unique color and dash style
line = Step(data, y=['python', 'pypy', 'jython'],
dash=['python', 'pypy', 'jython'],
color=['python', 'pypy', 'jython'],
title="Interpreter Sample Data", ylabel='Duration', legend=True)
output_file("steps.html")
show(line)
|
from bokeh.charts import Step, show, output_file
# build a dataset where multiple columns measure the same thing
data = dict(stamp=[
.33, .33, .34, .37, .37, .37, .37, .39, .41, .42,
.44, .44, .44, .45, .46, .49, .49],
postcard=[
.20, .20, .21, .23, .23, .23, .23, .24, .26, .27,
.28, .28, .29, .32, .33, .34, .35],
)
# create a line chart where each column of measures receives a unique color and dash style
line = Step(data, y=['stamp', 'postcard'],
dash=['stamp', 'postcard'],
color=['stamp', 'postcard'],
title="U.S. Postage Rates (1999-2015)", ylabel='Rate per ounce', legend=True)
output_file("steps.html")
show(line)
|
Change step example to plot US postage rates
|
Change step example to plot US postage rates
|
Python
|
bsd-3-clause
|
ptitjano/bokeh,timsnyder/bokeh,draperjames/bokeh,percyfal/bokeh,justacec/bokeh,clairetang6/bokeh,philippjfr/bokeh,ericmjl/bokeh,rs2/bokeh,azjps/bokeh,DuCorey/bokeh,clairetang6/bokeh,draperjames/bokeh,clairetang6/bokeh,DuCorey/bokeh,aavanian/bokeh,KasperPRasmussen/bokeh,justacec/bokeh,bokeh/bokeh,aiguofer/bokeh,rs2/bokeh,aavanian/bokeh,stonebig/bokeh,schoolie/bokeh,msarahan/bokeh,msarahan/bokeh,jakirkham/bokeh,schoolie/bokeh,Karel-van-de-Plassche/bokeh,Karel-van-de-Plassche/bokeh,phobson/bokeh,stonebig/bokeh,azjps/bokeh,aavanian/bokeh,jakirkham/bokeh,ptitjano/bokeh,bokeh/bokeh,azjps/bokeh,ptitjano/bokeh,msarahan/bokeh,Karel-van-de-Plassche/bokeh,schoolie/bokeh,KasperPRasmussen/bokeh,draperjames/bokeh,phobson/bokeh,schoolie/bokeh,timsnyder/bokeh,azjps/bokeh,quasiben/bokeh,percyfal/bokeh,ericmjl/bokeh,jakirkham/bokeh,timsnyder/bokeh,phobson/bokeh,justacec/bokeh,mindriot101/bokeh,azjps/bokeh,Karel-van-de-Plassche/bokeh,ericmjl/bokeh,quasiben/bokeh,dennisobrien/bokeh,philippjfr/bokeh,clairetang6/bokeh,ptitjano/bokeh,ericmjl/bokeh,quasiben/bokeh,aiguofer/bokeh,timsnyder/bokeh,Karel-van-de-Plassche/bokeh,draperjames/bokeh,dennisobrien/bokeh,phobson/bokeh,dennisobrien/bokeh,aavanian/bokeh,stonebig/bokeh,percyfal/bokeh,aiguofer/bokeh,aiguofer/bokeh,jakirkham/bokeh,rs2/bokeh,draperjames/bokeh,ericmjl/bokeh,bokeh/bokeh,dennisobrien/bokeh,schoolie/bokeh,bokeh/bokeh,KasperPRasmussen/bokeh,percyfal/bokeh,aavanian/bokeh,phobson/bokeh,justacec/bokeh,mindriot101/bokeh,DuCorey/bokeh,stonebig/bokeh,bokeh/bokeh,philippjfr/bokeh,philippjfr/bokeh,DuCorey/bokeh,rs2/bokeh,mindriot101/bokeh,timsnyder/bokeh,DuCorey/bokeh,dennisobrien/bokeh,ptitjano/bokeh,percyfal/bokeh,msarahan/bokeh,rs2/bokeh,KasperPRasmussen/bokeh,jakirkham/bokeh,KasperPRasmussen/bokeh,mindriot101/bokeh,aiguofer/bokeh,philippjfr/bokeh
|
python
|
## Code Before:
from bokeh.charts import Step, show, output_file
# build a dataset where multiple columns measure the same thing
data = dict(python=[2, 3, 7, 5, 26, 221, 44, 233, 254, 265, 266, 267, 120, 111],
pypy=[12, 33, 47, 15, 126, 121, 144, 233, 254, 225, 226, 267, 110, 130],
jython=[22, 43, 10, 25, 26, 101, 114, 203, 194, 215, 201, 227, 139, 160],
test=['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'bar']
)
# create a line chart where each column of measures receives a unique color and dash style
line = Step(data, y=['python', 'pypy', 'jython'],
dash=['python', 'pypy', 'jython'],
color=['python', 'pypy', 'jython'],
title="Interpreter Sample Data", ylabel='Duration', legend=True)
output_file("steps.html")
show(line)
## Instruction:
Change step example to plot US postage rates
## Code After:
from bokeh.charts import Step, show, output_file
# build a dataset where multiple columns measure the same thing
data = dict(stamp=[
.33, .33, .34, .37, .37, .37, .37, .39, .41, .42,
.44, .44, .44, .45, .46, .49, .49],
postcard=[
.20, .20, .21, .23, .23, .23, .23, .24, .26, .27,
.28, .28, .29, .32, .33, .34, .35],
)
# create a line chart where each column of measures receives a unique color and dash style
line = Step(data, y=['stamp', 'postcard'],
dash=['stamp', 'postcard'],
color=['stamp', 'postcard'],
title="U.S. Postage Rates (1999-2015)", ylabel='Rate per ounce', legend=True)
output_file("steps.html")
show(line)
|
// ... existing code ...
from bokeh.charts import Step, show, output_file
# build a dataset where multiple columns measure the same thing
data = dict(stamp=[
.33, .33, .34, .37, .37, .37, .37, .39, .41, .42,
.44, .44, .44, .45, .46, .49, .49],
postcard=[
.20, .20, .21, .23, .23, .23, .23, .24, .26, .27,
.28, .28, .29, .32, .33, .34, .35],
)
# create a line chart where each column of measures receives a unique color and dash style
line = Step(data, y=['stamp', 'postcard'],
dash=['stamp', 'postcard'],
color=['stamp', 'postcard'],
title="U.S. Postage Rates (1999-2015)", ylabel='Rate per ounce', legend=True)
output_file("steps.html")
show(line)
// ... rest of the code ...
|
eb0714767cf5c0fd89ff4e50e22445a5e436f94c
|
iopath/tabular/tabular_io.py
|
iopath/tabular/tabular_io.py
|
from typing import Any, Iterable
from iopath.common.file_io import PathHandler
class TabularUriParser:
def parse_uri(self, uri: str) -> None:
pass
class TabularPathHandler(PathHandler):
def _opent(
self, path: str, mode: str = "r", buffering: int = 32, **kwargs: Any
) -> Iterable[Any]:
assert mode == "r"
|
from typing import Any
from iopath.common.file_io import PathHandler, TabularIO
class TabularUriParser:
def parse_uri(self, uri: str) -> None:
pass
class TabularPathHandler(PathHandler):
def _opent(
self, path: str, mode: str = "r", buffering: int = 32, **kwargs: Any
) -> TabularIO:
assert mode == "r"
|
Update type signature of AIRStorePathHandler.opent()
|
Update type signature of AIRStorePathHandler.opent()
Summary:
The previous diff updated the type signature of the
`PathHandler.opent()` method to return a custom context manager. Here,
we update the return type of the overriden `AIRStorePathHandler.opent()`
method to return an implementation of the `PathHandlerContext` protocol,
namely the `AIRStoreRowDataLoader` instead of `Iterable[Any]` to allow
Pyre to carry out static type checking.
Reviewed By: mackorone
Differential Revision: D33833561
fbshipit-source-id: f642110645b147a955f4375fc24d4c29cdca6f26
|
Python
|
mit
|
facebookresearch/iopath,facebookresearch/iopath
|
python
|
## Code Before:
from typing import Any, Iterable
from iopath.common.file_io import PathHandler
class TabularUriParser:
def parse_uri(self, uri: str) -> None:
pass
class TabularPathHandler(PathHandler):
def _opent(
self, path: str, mode: str = "r", buffering: int = 32, **kwargs: Any
) -> Iterable[Any]:
assert mode == "r"
## Instruction:
Update type signature of AIRStorePathHandler.opent()
Summary:
The previous diff updated the type signature of the
`PathHandler.opent()` method to return a custom context manager. Here,
we update the return type of the overriden `AIRStorePathHandler.opent()`
method to return an implementation of the `PathHandlerContext` protocol,
namely the `AIRStoreRowDataLoader` instead of `Iterable[Any]` to allow
Pyre to carry out static type checking.
Reviewed By: mackorone
Differential Revision: D33833561
fbshipit-source-id: f642110645b147a955f4375fc24d4c29cdca6f26
## Code After:
from typing import Any
from iopath.common.file_io import PathHandler, TabularIO
class TabularUriParser:
def parse_uri(self, uri: str) -> None:
pass
class TabularPathHandler(PathHandler):
def _opent(
self, path: str, mode: str = "r", buffering: int = 32, **kwargs: Any
) -> TabularIO:
assert mode == "r"
|
# ... existing code ...
from typing import Any
from iopath.common.file_io import PathHandler, TabularIO
class TabularUriParser:
# ... modified code ...
class TabularPathHandler(PathHandler):
def _opent(
self, path: str, mode: str = "r", buffering: int = 32, **kwargs: Any
) -> TabularIO:
assert mode == "r"
# ... rest of the code ...
|
c0808574aaf410683f9c405e98be74a3ad4f4f2c
|
tests/events_test.py
|
tests/events_test.py
|
from unittest import TestCase
from mock import Mock
from nyuki.events import EventManager, Event, on_event
class Loop(Mock):
STACK = list()
def async(self, cb, *args):
self.STACK.append(cb)
class TestEventManager(TestCase):
def setUp(self):
loop = Mock()
self.manager = EventManager(loop)
def test_001_init(self):
# Ensure callback tree has been properly setup.
self.assertCountEqual(self.manager._callbacks.keys(), list(Event))
def test_002a_register(self):
pass
def test_002b_register_error(self):
pass
def test_003a_trigger(self):
pass
def test_003b_trigger_error(self):
pass
def tearDown(self):
pass
|
from unittest import TestCase
from mock import Mock
from nyuki.events import EventManager, Event, on_event
class TestOnEvent(TestCase):
def test_001_call(self):
@on_event(Event.Connected, Event.Disconnected)
def test():
pass
self.assertIsInstance(test.on_event, set)
class TestEventManager(TestCase):
def setUp(self):
self.loop = Mock()
self.manager = EventManager(self.loop)
def test_001_init(self):
# Ensure callback tree has been properly setup
self.assertCountEqual(self.manager._callbacks.keys(), list(Event))
def test_002a_register(self):
# For all kind of event, we're ensure we can add a callback
for event in Event:
callback = (lambda x: x)
self.manager.register(event, callback)
self.assertIn(callback, self.manager._callbacks[event])
def test_002b_register_error(self):
# Here's what happens when the specified event does not exists
event = Mock()
callback = (lambda x: x)
self.assertRaises(ValueError, self.manager.register, event, callback)
def test_003a_trigger(self):
# Ensure callbacks are properly scheduled when an event is triggered
callbacks = list()
self.loop.async = (lambda c, *args: callbacks.append(c))
cb = (lambda x: x)
self.manager.register(Event.Connected, cb)
self.manager.trigger(Event.Connected)
self.assertIn(cb, callbacks)
def test_003b_trigger_error(self):
# Ensure we can not trigger an event that does not exists
event = Mock()
self.assertRaises(ValueError, self.manager.trigger, event)
|
Add unit tests on events.
|
Add unit tests on events.
|
Python
|
apache-2.0
|
optiflows/nyuki,optiflows/nyuki,gdraynz/nyuki,gdraynz/nyuki
|
python
|
## Code Before:
from unittest import TestCase
from mock import Mock
from nyuki.events import EventManager, Event, on_event
class Loop(Mock):
STACK = list()
def async(self, cb, *args):
self.STACK.append(cb)
class TestEventManager(TestCase):
def setUp(self):
loop = Mock()
self.manager = EventManager(loop)
def test_001_init(self):
# Ensure callback tree has been properly setup.
self.assertCountEqual(self.manager._callbacks.keys(), list(Event))
def test_002a_register(self):
pass
def test_002b_register_error(self):
pass
def test_003a_trigger(self):
pass
def test_003b_trigger_error(self):
pass
def tearDown(self):
pass
## Instruction:
Add unit tests on events.
## Code After:
from unittest import TestCase
from mock import Mock
from nyuki.events import EventManager, Event, on_event
class TestOnEvent(TestCase):
def test_001_call(self):
@on_event(Event.Connected, Event.Disconnected)
def test():
pass
self.assertIsInstance(test.on_event, set)
class TestEventManager(TestCase):
def setUp(self):
self.loop = Mock()
self.manager = EventManager(self.loop)
def test_001_init(self):
# Ensure callback tree has been properly setup
self.assertCountEqual(self.manager._callbacks.keys(), list(Event))
def test_002a_register(self):
# For all kind of event, we're ensure we can add a callback
for event in Event:
callback = (lambda x: x)
self.manager.register(event, callback)
self.assertIn(callback, self.manager._callbacks[event])
def test_002b_register_error(self):
# Here's what happens when the specified event does not exists
event = Mock()
callback = (lambda x: x)
self.assertRaises(ValueError, self.manager.register, event, callback)
def test_003a_trigger(self):
# Ensure callbacks are properly scheduled when an event is triggered
callbacks = list()
self.loop.async = (lambda c, *args: callbacks.append(c))
cb = (lambda x: x)
self.manager.register(Event.Connected, cb)
self.manager.trigger(Event.Connected)
self.assertIn(cb, callbacks)
def test_003b_trigger_error(self):
# Ensure we can not trigger an event that does not exists
event = Mock()
self.assertRaises(ValueError, self.manager.trigger, event)
|
...
from nyuki.events import EventManager, Event, on_event
class TestOnEvent(TestCase):
def test_001_call(self):
@on_event(Event.Connected, Event.Disconnected)
def test():
pass
self.assertIsInstance(test.on_event, set)
class TestEventManager(TestCase):
def setUp(self):
self.loop = Mock()
self.manager = EventManager(self.loop)
def test_001_init(self):
# Ensure callback tree has been properly setup
self.assertCountEqual(self.manager._callbacks.keys(), list(Event))
def test_002a_register(self):
# For all kind of event, we're ensure we can add a callback
for event in Event:
callback = (lambda x: x)
self.manager.register(event, callback)
self.assertIn(callback, self.manager._callbacks[event])
def test_002b_register_error(self):
# Here's what happens when the specified event does not exists
event = Mock()
callback = (lambda x: x)
self.assertRaises(ValueError, self.manager.register, event, callback)
def test_003a_trigger(self):
# Ensure callbacks are properly scheduled when an event is triggered
callbacks = list()
self.loop.async = (lambda c, *args: callbacks.append(c))
cb = (lambda x: x)
self.manager.register(Event.Connected, cb)
self.manager.trigger(Event.Connected)
self.assertIn(cb, callbacks)
def test_003b_trigger_error(self):
# Ensure we can not trigger an event that does not exists
event = Mock()
self.assertRaises(ValueError, self.manager.trigger, event)
...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.