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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
ca042edc7f9709f2217b669fb5a68e9aac3ab61c
|
cbv/management/commands/cbv_dumpversion.py
|
cbv/management/commands/cbv_dumpversion.py
|
from django.core.management import call_command
from django.core.management.commands import LabelCommand
class Command(LabelCommand):
def handle_label(self, label, **options):
# Because django will use the default manager of each model, we
# monkeypatch the manager to filter by our label before calling
# the dumpdata command to dump only the subset of data we want.
# Set the
# Call the dumpdata command.
call_command('dumpdata', 'cbv')
|
import json
from django.db.models.query import QuerySet
from django.core.management import call_command
from django.core.management.base import LabelCommand
from django.core import serializers
from cbv import models
class Command(LabelCommand):
"""Dump the django cbv app data for a specific version."""
def handle_label(self, label, **options):
filtered_models = {
models.ProjectVersion: 'version_number',
models.Module: 'project_version__version_number',
models.ModuleAttribute: 'module__project_version__version_number',
models.Function: 'module__project_version__version_number',
models.Klass: 'module__project_version__version_number',
models.KlassAttribute: 'klass__module__project_version__version_number',
models.Method: 'klass__module__project_version__version_number',
}
objects = []
for model, version_arg in filtered_models.items():
filter_kwargs = {version_arg: label}
result = model.objects.filter(**filter_kwargs)
objects = objects + list(result)
for obj in objects:
obj.pk = None
dump = serializers.serialize('json', objects, indent=1, use_natural_keys=True)
self.stdout.write(dump)
|
Allow dumpdata of specific version of cbv.
|
Allow dumpdata of specific version of cbv.
|
Python
|
bsd-2-clause
|
abhijo89/django-cbv-inspector,refreshoxford/django-cbv-inspector,abhijo89/django-cbv-inspector,refreshoxford/django-cbv-inspector,refreshoxford/django-cbv-inspector,abhijo89/django-cbv-inspector,abhijo89/django-cbv-inspector,refreshoxford/django-cbv-inspector
|
python
|
## Code Before:
from django.core.management import call_command
from django.core.management.commands import LabelCommand
class Command(LabelCommand):
def handle_label(self, label, **options):
# Because django will use the default manager of each model, we
# monkeypatch the manager to filter by our label before calling
# the dumpdata command to dump only the subset of data we want.
# Set the
# Call the dumpdata command.
call_command('dumpdata', 'cbv')
## Instruction:
Allow dumpdata of specific version of cbv.
## Code After:
import json
from django.db.models.query import QuerySet
from django.core.management import call_command
from django.core.management.base import LabelCommand
from django.core import serializers
from cbv import models
class Command(LabelCommand):
"""Dump the django cbv app data for a specific version."""
def handle_label(self, label, **options):
filtered_models = {
models.ProjectVersion: 'version_number',
models.Module: 'project_version__version_number',
models.ModuleAttribute: 'module__project_version__version_number',
models.Function: 'module__project_version__version_number',
models.Klass: 'module__project_version__version_number',
models.KlassAttribute: 'klass__module__project_version__version_number',
models.Method: 'klass__module__project_version__version_number',
}
objects = []
for model, version_arg in filtered_models.items():
filter_kwargs = {version_arg: label}
result = model.objects.filter(**filter_kwargs)
objects = objects + list(result)
for obj in objects:
obj.pk = None
dump = serializers.serialize('json', objects, indent=1, use_natural_keys=True)
self.stdout.write(dump)
|
// ... existing code ...
import json
from django.db.models.query import QuerySet
from django.core.management import call_command
from django.core.management.base import LabelCommand
from django.core import serializers
from cbv import models
class Command(LabelCommand):
"""Dump the django cbv app data for a specific version."""
def handle_label(self, label, **options):
filtered_models = {
models.ProjectVersion: 'version_number',
models.Module: 'project_version__version_number',
models.ModuleAttribute: 'module__project_version__version_number',
models.Function: 'module__project_version__version_number',
models.Klass: 'module__project_version__version_number',
models.KlassAttribute: 'klass__module__project_version__version_number',
models.Method: 'klass__module__project_version__version_number',
}
objects = []
for model, version_arg in filtered_models.items():
filter_kwargs = {version_arg: label}
result = model.objects.filter(**filter_kwargs)
objects = objects + list(result)
for obj in objects:
obj.pk = None
dump = serializers.serialize('json', objects, indent=1, use_natural_keys=True)
self.stdout.write(dump)
// ... rest of the code ...
|
0958ec9188bc2017be576de62911e76247cbe45f
|
scikits/gpu/tests/test_fbo.py
|
scikits/gpu/tests/test_fbo.py
|
from nose.tools import *
from scikits.gpu.fbo import *
from pyglet.gl import *
class TestFramebuffer(object):
def create(self, x, y, colours, dtype):
fbo = Framebuffer(x, y, bands=colours, dtype=dtype)
fbo.bind()
fbo.unbind()
fbo.delete()
def test_creation(self):
fbo = Framebuffer(64, 64)
for dtype in [gl.GL_UNSIGNED_BYTE, gl.GL_BYTE,
gl.GL_INT, gl.GL_UNSIGNED_INT,
gl.GL_FLOAT]:
for bands in [1, 2, 3, 4]:
yield self.create, 16, 16, bands, dtype
|
from nose.tools import *
from scikits.gpu.fbo import *
from pyglet.gl import *
class TestFramebuffer(object):
def create(self, x, y, colours, dtype):
fbo = Framebuffer(x, y, bands=colours, dtype=dtype)
fbo.bind()
fbo.unbind()
fbo.delete()
def test_creation(self):
fbo = Framebuffer(64, 64)
for dtype in [gl.GL_UNSIGNED_BYTE, gl.GL_BYTE,
gl.GL_INT, gl.GL_UNSIGNED_INT,
gl.GL_FLOAT]:
for bands in [1, 2, 3, 4]:
yield self.create, 16, 16, bands, dtype
def test_bind_deleted(self):
fbo = Framebuffer(32, 32)
fbo.delete()
assert_raises(RuntimeError, fbo.bind)
|
Test that framebuffer can't be bound after deletion.
|
Test that framebuffer can't be bound after deletion.
|
Python
|
mit
|
certik/scikits.gpu,stefanv/scikits.gpu
|
python
|
## Code Before:
from nose.tools import *
from scikits.gpu.fbo import *
from pyglet.gl import *
class TestFramebuffer(object):
def create(self, x, y, colours, dtype):
fbo = Framebuffer(x, y, bands=colours, dtype=dtype)
fbo.bind()
fbo.unbind()
fbo.delete()
def test_creation(self):
fbo = Framebuffer(64, 64)
for dtype in [gl.GL_UNSIGNED_BYTE, gl.GL_BYTE,
gl.GL_INT, gl.GL_UNSIGNED_INT,
gl.GL_FLOAT]:
for bands in [1, 2, 3, 4]:
yield self.create, 16, 16, bands, dtype
## Instruction:
Test that framebuffer can't be bound after deletion.
## Code After:
from nose.tools import *
from scikits.gpu.fbo import *
from pyglet.gl import *
class TestFramebuffer(object):
def create(self, x, y, colours, dtype):
fbo = Framebuffer(x, y, bands=colours, dtype=dtype)
fbo.bind()
fbo.unbind()
fbo.delete()
def test_creation(self):
fbo = Framebuffer(64, 64)
for dtype in [gl.GL_UNSIGNED_BYTE, gl.GL_BYTE,
gl.GL_INT, gl.GL_UNSIGNED_INT,
gl.GL_FLOAT]:
for bands in [1, 2, 3, 4]:
yield self.create, 16, 16, bands, dtype
def test_bind_deleted(self):
fbo = Framebuffer(32, 32)
fbo.delete()
assert_raises(RuntimeError, fbo.bind)
|
...
gl.GL_FLOAT]:
for bands in [1, 2, 3, 4]:
yield self.create, 16, 16, bands, dtype
def test_bind_deleted(self):
fbo = Framebuffer(32, 32)
fbo.delete()
assert_raises(RuntimeError, fbo.bind)
...
|
9aa17b90b8f3413f0621cc25a686774dd809dc84
|
frigg/projects/serializers.py
|
frigg/projects/serializers.py
|
from rest_framework import serializers
from frigg.builds.serializers import BuildInlineSerializer
from .models import Project
class ProjectSerializer(serializers.ModelSerializer):
builds = BuildInlineSerializer(read_only=True, many=True)
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'private',
'approved',
'should_clone_with_ssh',
'builds'
)
|
from rest_framework import serializers
from frigg.builds.serializers import BuildInlineSerializer
from .models import Project
class EnvironmentVariableSerializer(serializers.ModelSerializer):
def to_representation(self, instance):
representation = super().to_representation(instance)
if instance.is_secret:
representation.value = '[secret]'
return representation
class Meta:
model = Project
fields = (
'id',
'key',
'is_secret',
'value',
)
class ProjectSerializer(serializers.ModelSerializer):
builds = BuildInlineSerializer(read_only=True, many=True)
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'private',
'approved',
'should_clone_with_ssh',
'builds'
)
|
Add drf serializer for environment variables
|
feat: Add drf serializer for environment variables
|
Python
|
mit
|
frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq
|
python
|
## Code Before:
from rest_framework import serializers
from frigg.builds.serializers import BuildInlineSerializer
from .models import Project
class ProjectSerializer(serializers.ModelSerializer):
builds = BuildInlineSerializer(read_only=True, many=True)
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'private',
'approved',
'should_clone_with_ssh',
'builds'
)
## Instruction:
feat: Add drf serializer for environment variables
## Code After:
from rest_framework import serializers
from frigg.builds.serializers import BuildInlineSerializer
from .models import Project
class EnvironmentVariableSerializer(serializers.ModelSerializer):
def to_representation(self, instance):
representation = super().to_representation(instance)
if instance.is_secret:
representation.value = '[secret]'
return representation
class Meta:
model = Project
fields = (
'id',
'key',
'is_secret',
'value',
)
class ProjectSerializer(serializers.ModelSerializer):
builds = BuildInlineSerializer(read_only=True, many=True)
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'private',
'approved',
'should_clone_with_ssh',
'builds'
)
|
// ... existing code ...
from frigg.builds.serializers import BuildInlineSerializer
from .models import Project
class EnvironmentVariableSerializer(serializers.ModelSerializer):
def to_representation(self, instance):
representation = super().to_representation(instance)
if instance.is_secret:
representation.value = '[secret]'
return representation
class Meta:
model = Project
fields = (
'id',
'key',
'is_secret',
'value',
)
class ProjectSerializer(serializers.ModelSerializer):
// ... rest of the code ...
|
94529f62757886d2291cf90596a179dc2d0b6642
|
yutu.py
|
yutu.py
|
import discord
from discord.ext.commands import Bot
import json
client = Bot("~", game=discord.Game(name="~help"))
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.command()
async def highfive(ctx):
'''
Give Yutu a high-five
'''
await ctx.send('{0.mention} :pray: {1.mention}'.format(ctx.me, ctx.author))
@client.command()
async def cute(ctx, member: discord.Member = None):
if member is None:
first = ctx.me
second = ctx.author
else:
first = ctx.author
second = member
post = discord.Embed(description='**{0.name}** thinks that **{1.name}** is cute!'.format(first, second))
post.set_image(url="https://i.imgur.com/MuVAkV2.gif")
await ctx.send(embed=post)
if __name__ == "__main__":
with open("cfg.json") as fh:
token = json.load(fh)['token']
client.run(token)
|
import discord
from discord.ext.commands import Bot
import json
client = Bot("~", game=discord.Game(name="~help"))
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.command()
async def highfive(ctx):
'''
Give Yutu a high-five
'''
await ctx.send('{0.mention} :pray: {1.mention}'.format(ctx.me, ctx.author))
@client.command()
async def cute(ctx, member: discord.Member = None):
if member is None:
first = ctx.me
second = ctx.author
else:
first = ctx.author
second = member
post = discord.Embed(description='**{0.display_name}** thinks that **{1.display_name}** is cute!'.format(first, second))
post.set_image(url="https://i.imgur.com/MuVAkV2.gif")
await ctx.send(embed=post)
if __name__ == "__main__":
with open("cfg.json") as fh:
token = json.load(fh)['token']
client.run(token)
|
Make cute respect guild nicknames
|
Make cute respect guild nicknames
|
Python
|
mit
|
HarkonenBade/yutu
|
python
|
## Code Before:
import discord
from discord.ext.commands import Bot
import json
client = Bot("~", game=discord.Game(name="~help"))
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.command()
async def highfive(ctx):
'''
Give Yutu a high-five
'''
await ctx.send('{0.mention} :pray: {1.mention}'.format(ctx.me, ctx.author))
@client.command()
async def cute(ctx, member: discord.Member = None):
if member is None:
first = ctx.me
second = ctx.author
else:
first = ctx.author
second = member
post = discord.Embed(description='**{0.name}** thinks that **{1.name}** is cute!'.format(first, second))
post.set_image(url="https://i.imgur.com/MuVAkV2.gif")
await ctx.send(embed=post)
if __name__ == "__main__":
with open("cfg.json") as fh:
token = json.load(fh)['token']
client.run(token)
## Instruction:
Make cute respect guild nicknames
## Code After:
import discord
from discord.ext.commands import Bot
import json
client = Bot("~", game=discord.Game(name="~help"))
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.command()
async def highfive(ctx):
'''
Give Yutu a high-five
'''
await ctx.send('{0.mention} :pray: {1.mention}'.format(ctx.me, ctx.author))
@client.command()
async def cute(ctx, member: discord.Member = None):
if member is None:
first = ctx.me
second = ctx.author
else:
first = ctx.author
second = member
post = discord.Embed(description='**{0.display_name}** thinks that **{1.display_name}** is cute!'.format(first, second))
post.set_image(url="https://i.imgur.com/MuVAkV2.gif")
await ctx.send(embed=post)
if __name__ == "__main__":
with open("cfg.json") as fh:
token = json.load(fh)['token']
client.run(token)
|
// ... existing code ...
else:
first = ctx.author
second = member
post = discord.Embed(description='**{0.display_name}** thinks that **{1.display_name}** is cute!'.format(first, second))
post.set_image(url="https://i.imgur.com/MuVAkV2.gif")
await ctx.send(embed=post)
// ... rest of the code ...
|
e3e3be6d5fde6cf02c26dad354a6706896d2bdf1
|
1.7.10/src/main/java/fr/ourten/brokkgui/wrapper/BrokkGuiWrapperMod.java
|
1.7.10/src/main/java/fr/ourten/brokkgui/wrapper/BrokkGuiWrapperMod.java
|
package fr.ourten.brokkgui.wrapper;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import fr.ourten.brokkgui.BrokkGuiPlatform;
/**
* @author Ourten 5 oct. 2016
*/
@Mod(modid = BrokkGuiWrapperMod.MODID, version = BrokkGuiWrapperMod.VERSION, name = BrokkGuiWrapperMod.MODNAME)
public class BrokkGuiWrapperMod
{
public static final String MODID = "brokkguiwrapper";
public static final String MODNAME = "BrokkGui Wrapper";
public static final String VERSION = "0.1.0";
@EventHandler
public void onPreInit(final FMLPreInitializationEvent event)
{
BrokkGuiPlatform.getInstance().setPlatformName("MC1.7.10");
BrokkGuiPlatform.getInstance().setKeyboardUtil(new KeyboardUtil());
BrokkGuiPlatform.getInstance().setMouseUtil(new MouseUtil());
BrokkGuiPlatform.getInstance().setGuiHelper(new GuiHelper());
}
}
|
package fr.ourten.brokkgui.wrapper;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import fr.ourten.brokkgui.BrokkGuiPlatform;
/**
* @author Ourten 5 oct. 2016
*/
@Mod(modid = BrokkGuiWrapperMod.MODID, version = BrokkGuiWrapperMod.VERSION, name = BrokkGuiWrapperMod.MODNAME)
public class BrokkGuiWrapperMod
{
public static final String MODID = "brokkguiwrapper";
public static final String MODNAME = "BrokkGui Wrapper";
public static final String VERSION = "0.1.0";
@EventHandler
public void onPreInit(final FMLPreInitializationEvent event)
{
BrokkGuiPlatform.getInstance().setPlatformName("MC1.7.10");
BrokkGuiPlatform.getInstance().setKeyboardUtil(new KeyboardUtil());
BrokkGuiPlatform.getInstance().setMouseUtil(new MouseUtil());
if (event.getSide().isClient())
BrokkGuiPlatform.getInstance().setGuiHelper(new GuiHelper());
}
}
|
Fix 1.7 wrapper instancing minecraft client class
|
Fix 1.7 wrapper instancing minecraft client class
|
Java
|
apache-2.0
|
Phenix246/BrokkGUI,ZeAmateis/BrokkGUI,Yggard/BrokkGUI,ZeAmateis/BrokkGUI
|
java
|
## Code Before:
package fr.ourten.brokkgui.wrapper;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import fr.ourten.brokkgui.BrokkGuiPlatform;
/**
* @author Ourten 5 oct. 2016
*/
@Mod(modid = BrokkGuiWrapperMod.MODID, version = BrokkGuiWrapperMod.VERSION, name = BrokkGuiWrapperMod.MODNAME)
public class BrokkGuiWrapperMod
{
public static final String MODID = "brokkguiwrapper";
public static final String MODNAME = "BrokkGui Wrapper";
public static final String VERSION = "0.1.0";
@EventHandler
public void onPreInit(final FMLPreInitializationEvent event)
{
BrokkGuiPlatform.getInstance().setPlatformName("MC1.7.10");
BrokkGuiPlatform.getInstance().setKeyboardUtil(new KeyboardUtil());
BrokkGuiPlatform.getInstance().setMouseUtil(new MouseUtil());
BrokkGuiPlatform.getInstance().setGuiHelper(new GuiHelper());
}
}
## Instruction:
Fix 1.7 wrapper instancing minecraft client class
## Code After:
package fr.ourten.brokkgui.wrapper;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import fr.ourten.brokkgui.BrokkGuiPlatform;
/**
* @author Ourten 5 oct. 2016
*/
@Mod(modid = BrokkGuiWrapperMod.MODID, version = BrokkGuiWrapperMod.VERSION, name = BrokkGuiWrapperMod.MODNAME)
public class BrokkGuiWrapperMod
{
public static final String MODID = "brokkguiwrapper";
public static final String MODNAME = "BrokkGui Wrapper";
public static final String VERSION = "0.1.0";
@EventHandler
public void onPreInit(final FMLPreInitializationEvent event)
{
BrokkGuiPlatform.getInstance().setPlatformName("MC1.7.10");
BrokkGuiPlatform.getInstance().setKeyboardUtil(new KeyboardUtil());
BrokkGuiPlatform.getInstance().setMouseUtil(new MouseUtil());
if (event.getSide().isClient())
BrokkGuiPlatform.getInstance().setGuiHelper(new GuiHelper());
}
}
|
# ... existing code ...
BrokkGuiPlatform.getInstance().setPlatformName("MC1.7.10");
BrokkGuiPlatform.getInstance().setKeyboardUtil(new KeyboardUtil());
BrokkGuiPlatform.getInstance().setMouseUtil(new MouseUtil());
if (event.getSide().isClient())
BrokkGuiPlatform.getInstance().setGuiHelper(new GuiHelper());
}
}
# ... rest of the code ...
|
b345c00b41ade2e12449566f7cb013a7bb8d078f
|
democracy/migrations/0032_add_language_code_to_comment.py
|
democracy/migrations/0032_add_language_code_to_comment.py
|
from __future__ import unicode_literals
from django.db import migrations, models
from democracy.models import SectionComment
def forwards_func(apps, schema_editor):
for comment in SectionComment.objects.all():
comment._detect_lang()
comment.save()
def backwards_func(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [
('democracy', '0031_remove_untranslated_fields'),
]
operations = [
migrations.AlterModelOptions(
name='sectionimage',
options={'ordering': ('ordering', 'translations__title'), 'verbose_name': 'section image', 'verbose_name_plural': 'section images'},
),
migrations.AddField(
model_name='sectioncomment',
name='language_code',
field=models.CharField(blank=True, max_length=15, verbose_name='language code'),
),
migrations.RunPython(forwards_func, backwards_func),
]
|
from __future__ import unicode_literals
from django.db import migrations, models
from democracy.models import SectionComment
def forwards_func(apps, schema_editor):
for comment in SectionComment.objects.all():
comment._detect_lang()
comment.save()
def backwards_func(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [
('democracy', '0031_remove_untranslated_fields'),
# comment.save() database operations will require a recent user model with all the fields included
('kerrokantasi', '__latest__'),
]
operations = [
migrations.AlterModelOptions(
name='sectionimage',
options={'ordering': ('ordering', 'translations__title'), 'verbose_name': 'section image', 'verbose_name_plural': 'section images'},
),
migrations.AddField(
model_name='sectioncomment',
name='language_code',
field=models.CharField(blank=True, max_length=15, verbose_name='language code'),
),
migrations.RunPython(forwards_func, backwards_func),
]
|
Add literal dependency so migration 0031 won't fail if run in the wrong order
|
Add literal dependency so migration 0031 won't fail if run in the wrong order
|
Python
|
mit
|
City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi
|
python
|
## Code Before:
from __future__ import unicode_literals
from django.db import migrations, models
from democracy.models import SectionComment
def forwards_func(apps, schema_editor):
for comment in SectionComment.objects.all():
comment._detect_lang()
comment.save()
def backwards_func(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [
('democracy', '0031_remove_untranslated_fields'),
]
operations = [
migrations.AlterModelOptions(
name='sectionimage',
options={'ordering': ('ordering', 'translations__title'), 'verbose_name': 'section image', 'verbose_name_plural': 'section images'},
),
migrations.AddField(
model_name='sectioncomment',
name='language_code',
field=models.CharField(blank=True, max_length=15, verbose_name='language code'),
),
migrations.RunPython(forwards_func, backwards_func),
]
## Instruction:
Add literal dependency so migration 0031 won't fail if run in the wrong order
## Code After:
from __future__ import unicode_literals
from django.db import migrations, models
from democracy.models import SectionComment
def forwards_func(apps, schema_editor):
for comment in SectionComment.objects.all():
comment._detect_lang()
comment.save()
def backwards_func(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [
('democracy', '0031_remove_untranslated_fields'),
# comment.save() database operations will require a recent user model with all the fields included
('kerrokantasi', '__latest__'),
]
operations = [
migrations.AlterModelOptions(
name='sectionimage',
options={'ordering': ('ordering', 'translations__title'), 'verbose_name': 'section image', 'verbose_name_plural': 'section images'},
),
migrations.AddField(
model_name='sectioncomment',
name='language_code',
field=models.CharField(blank=True, max_length=15, verbose_name='language code'),
),
migrations.RunPython(forwards_func, backwards_func),
]
|
...
dependencies = [
('democracy', '0031_remove_untranslated_fields'),
# comment.save() database operations will require a recent user model with all the fields included
('kerrokantasi', '__latest__'),
]
operations = [
...
|
7757576e88be623ae2507795fa08eddd1c0bec94
|
src/main/java/org/purl/wf4ever/robundle/Bundle.java
|
src/main/java/org/purl/wf4ever/robundle/Bundle.java
|
package org.purl.wf4ever.robundle;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import org.purl.wf4ever.robundle.fs.BundleFileSystem;
public class Bundle implements AutoCloseable {
private boolean deleteOnClose;
private final Path root;
public Bundle(Path root, boolean deleteOnClose) {
this.root = root;
this.setDeleteOnClose(deleteOnClose);
}
@Override
public void close() throws IOException {
close(isDeleteOnClose());
}
protected void close(boolean deleteOnClose) throws IOException {
getFileSystem().close();
if (deleteOnClose) {
Files.deleteIfExists(getSource());
}
}
public FileSystem getFileSystem() {
return getRoot().getFileSystem();
}
public Path getRoot() {
return root;
}
public Path getSource() {
BundleFileSystem fs = (BundleFileSystem) getFileSystem();
return fs.getSource();
}
public boolean isDeleteOnClose() {
return deleteOnClose;
}
public void setDeleteOnClose(boolean deleteOnClose) {
this.deleteOnClose = deleteOnClose;
}
}
|
package org.purl.wf4ever.robundle;
import java.io.Closeable;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import org.purl.wf4ever.robundle.fs.BundleFileSystem;
public class Bundle implements Closeable {
private boolean deleteOnClose;
private final Path root;
public Bundle(Path root, boolean deleteOnClose) {
this.root = root;
this.setDeleteOnClose(deleteOnClose);
}
@Override
public void close() throws IOException {
close(isDeleteOnClose());
}
protected void close(boolean deleteOnClose) throws IOException {
if (! getFileSystem().isOpen()) {
return;
}
getFileSystem().close();
if (deleteOnClose) {
Files.deleteIfExists(getSource());
}
}
public FileSystem getFileSystem() {
return getRoot().getFileSystem();
}
public Path getRoot() {
return root;
}
public Path getSource() {
BundleFileSystem fs = (BundleFileSystem) getFileSystem();
return fs.getSource();
}
public boolean isDeleteOnClose() {
return deleteOnClose;
}
public void setDeleteOnClose(boolean deleteOnClose) {
this.deleteOnClose = deleteOnClose;
}
}
|
Make close() idempotent and implement Closable rather than AutoClosable
|
Make close() idempotent and implement Closable rather than AutoClosable
|
Java
|
apache-2.0
|
taverna-incubator/incubator-taverna-language,binfalse/incubator-taverna-language,taverna-incubator/incubator-taverna-language,binfalse/incubator-taverna-language,taverna-incubator/incubator-taverna-language,taverna-incubator/incubator-taverna-language,binfalse/incubator-taverna-language,binfalse/incubator-taverna-language
|
java
|
## Code Before:
package org.purl.wf4ever.robundle;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import org.purl.wf4ever.robundle.fs.BundleFileSystem;
public class Bundle implements AutoCloseable {
private boolean deleteOnClose;
private final Path root;
public Bundle(Path root, boolean deleteOnClose) {
this.root = root;
this.setDeleteOnClose(deleteOnClose);
}
@Override
public void close() throws IOException {
close(isDeleteOnClose());
}
protected void close(boolean deleteOnClose) throws IOException {
getFileSystem().close();
if (deleteOnClose) {
Files.deleteIfExists(getSource());
}
}
public FileSystem getFileSystem() {
return getRoot().getFileSystem();
}
public Path getRoot() {
return root;
}
public Path getSource() {
BundleFileSystem fs = (BundleFileSystem) getFileSystem();
return fs.getSource();
}
public boolean isDeleteOnClose() {
return deleteOnClose;
}
public void setDeleteOnClose(boolean deleteOnClose) {
this.deleteOnClose = deleteOnClose;
}
}
## Instruction:
Make close() idempotent and implement Closable rather than AutoClosable
## Code After:
package org.purl.wf4ever.robundle;
import java.io.Closeable;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import org.purl.wf4ever.robundle.fs.BundleFileSystem;
public class Bundle implements Closeable {
private boolean deleteOnClose;
private final Path root;
public Bundle(Path root, boolean deleteOnClose) {
this.root = root;
this.setDeleteOnClose(deleteOnClose);
}
@Override
public void close() throws IOException {
close(isDeleteOnClose());
}
protected void close(boolean deleteOnClose) throws IOException {
if (! getFileSystem().isOpen()) {
return;
}
getFileSystem().close();
if (deleteOnClose) {
Files.deleteIfExists(getSource());
}
}
public FileSystem getFileSystem() {
return getRoot().getFileSystem();
}
public Path getRoot() {
return root;
}
public Path getSource() {
BundleFileSystem fs = (BundleFileSystem) getFileSystem();
return fs.getSource();
}
public boolean isDeleteOnClose() {
return deleteOnClose;
}
public void setDeleteOnClose(boolean deleteOnClose) {
this.deleteOnClose = deleteOnClose;
}
}
|
# ... existing code ...
package org.purl.wf4ever.robundle;
import java.io.Closeable;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
# ... modified code ...
import org.purl.wf4ever.robundle.fs.BundleFileSystem;
public class Bundle implements Closeable {
private boolean deleteOnClose;
private final Path root;
...
}
protected void close(boolean deleteOnClose) throws IOException {
if (! getFileSystem().isOpen()) {
return;
}
getFileSystem().close();
if (deleteOnClose) {
Files.deleteIfExists(getSource());
# ... rest of the code ...
|
a7028ca3d3dea5a9f8891dfd2947b671bbe02b7e
|
pentai/gui/my_button.py
|
pentai/gui/my_button.py
|
from kivy.uix.button import Button
import audio as a_m
class MyButton(Button):
def on_touch_up(self, touch, *args, **kwargs):
if self.collide_point(*touch.pos):
if not hasattr(self, "silent"):
a_m.instance.click()
super(MyButton, self).on_touch_up(touch, *args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self, ignored=None):
self.state = "normal"
if not hasattr(self, "silent"):
a_m.instance.click()
|
from kivy.uix.button import Button
import audio as a_m
from pentai.base.defines import *
class MyButton(Button):
def __init__(self, *args, **kwargs):
super(MyButton, self).__init__(*args, **kwargs)
self.silent = False
def on_touch_up(self, touch, *args, **kwargs):
if self.collide_point(*touch.pos):
if not self.silent:
a_m.instance.click()
super(MyButton, self).on_touch_up(touch, *args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self, ignored=None):
self.state = "normal"
if not self.silent:
a_m.instance.click()
|
Make "silent" an attribute from __init__
|
Make "silent" an attribute from __init__
|
Python
|
mit
|
cropleyb/pentai,cropleyb/pentai,cropleyb/pentai
|
python
|
## Code Before:
from kivy.uix.button import Button
import audio as a_m
class MyButton(Button):
def on_touch_up(self, touch, *args, **kwargs):
if self.collide_point(*touch.pos):
if not hasattr(self, "silent"):
a_m.instance.click()
super(MyButton, self).on_touch_up(touch, *args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self, ignored=None):
self.state = "normal"
if not hasattr(self, "silent"):
a_m.instance.click()
## Instruction:
Make "silent" an attribute from __init__
## Code After:
from kivy.uix.button import Button
import audio as a_m
from pentai.base.defines import *
class MyButton(Button):
def __init__(self, *args, **kwargs):
super(MyButton, self).__init__(*args, **kwargs)
self.silent = False
def on_touch_up(self, touch, *args, **kwargs):
if self.collide_point(*touch.pos):
if not self.silent:
a_m.instance.click()
super(MyButton, self).on_touch_up(touch, *args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self, ignored=None):
self.state = "normal"
if not self.silent:
a_m.instance.click()
|
...
from kivy.uix.button import Button
import audio as a_m
from pentai.base.defines import *
class MyButton(Button):
def __init__(self, *args, **kwargs):
super(MyButton, self).__init__(*args, **kwargs)
self.silent = False
def on_touch_up(self, touch, *args, **kwargs):
if self.collide_point(*touch.pos):
if not self.silent:
a_m.instance.click()
super(MyButton, self).on_touch_up(touch, *args, **kwargs)
...
def sim_release(self, ignored=None):
self.state = "normal"
if not self.silent:
a_m.instance.click()
...
|
3cbc3b96d3f91c940c5d762ce08da9814c29b04d
|
utils/gyb_syntax_support/protocolsMap.py
|
utils/gyb_syntax_support/protocolsMap.py
|
SYNTAX_BUILDABLE_EXPRESSIBLE_BY_CONFORMANCES = {
'ExpressibleByConditionElement': [
'ExpressibleByConditionElementList'
],
'ExpressibleByDeclBuildable': [
'ExpressibleByCodeBlockItem',
'ExpressibleByMemberDeclListItem',
'ExpressibleBySyntaxBuildable'
],
'ExpressibleByStmtBuildable': [
'ExpressibleByCodeBlockItem',
'ExpressibleBySyntaxBuildable'
],
'ExpressibleByExprList': [
'ExpressibleByConditionElement',
'ExpressibleBySyntaxBuildable'
]
}
|
SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = {
'ExpressibleAsConditionElement': [
'ExpressibleAsConditionElementList'
],
'ExpressibleAsDeclBuildable': [
'ExpressibleAsCodeBlockItem',
'ExpressibleAsMemberDeclListItem',
'ExpressibleAsSyntaxBuildable'
],
'ExpressibleAsStmtBuildable': [
'ExpressibleAsCodeBlockItem',
'ExpressibleAsSyntaxBuildable'
],
'ExpressibleAsExprList': [
'ExpressibleAsConditionElement',
'ExpressibleAsSyntaxBuildable'
]
}
|
Revert "[SwiftSyntax] Replace ExpressibleAs protocols by ExpressibleBy protocols"
|
Revert "[SwiftSyntax] Replace ExpressibleAs protocols by ExpressibleBy protocols"
|
Python
|
apache-2.0
|
roambotics/swift,glessard/swift,ahoppen/swift,roambotics/swift,apple/swift,roambotics/swift,gregomni/swift,ahoppen/swift,JGiola/swift,JGiola/swift,apple/swift,gregomni/swift,benlangmuir/swift,gregomni/swift,glessard/swift,atrick/swift,benlangmuir/swift,ahoppen/swift,atrick/swift,benlangmuir/swift,gregomni/swift,atrick/swift,glessard/swift,rudkx/swift,benlangmuir/swift,glessard/swift,apple/swift,benlangmuir/swift,ahoppen/swift,rudkx/swift,roambotics/swift,roambotics/swift,glessard/swift,glessard/swift,ahoppen/swift,atrick/swift,apple/swift,JGiola/swift,JGiola/swift,rudkx/swift,atrick/swift,rudkx/swift,gregomni/swift,rudkx/swift,rudkx/swift,roambotics/swift,atrick/swift,gregomni/swift,apple/swift,JGiola/swift,ahoppen/swift,JGiola/swift,apple/swift,benlangmuir/swift
|
python
|
## Code Before:
SYNTAX_BUILDABLE_EXPRESSIBLE_BY_CONFORMANCES = {
'ExpressibleByConditionElement': [
'ExpressibleByConditionElementList'
],
'ExpressibleByDeclBuildable': [
'ExpressibleByCodeBlockItem',
'ExpressibleByMemberDeclListItem',
'ExpressibleBySyntaxBuildable'
],
'ExpressibleByStmtBuildable': [
'ExpressibleByCodeBlockItem',
'ExpressibleBySyntaxBuildable'
],
'ExpressibleByExprList': [
'ExpressibleByConditionElement',
'ExpressibleBySyntaxBuildable'
]
}
## Instruction:
Revert "[SwiftSyntax] Replace ExpressibleAs protocols by ExpressibleBy protocols"
## Code After:
SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = {
'ExpressibleAsConditionElement': [
'ExpressibleAsConditionElementList'
],
'ExpressibleAsDeclBuildable': [
'ExpressibleAsCodeBlockItem',
'ExpressibleAsMemberDeclListItem',
'ExpressibleAsSyntaxBuildable'
],
'ExpressibleAsStmtBuildable': [
'ExpressibleAsCodeBlockItem',
'ExpressibleAsSyntaxBuildable'
],
'ExpressibleAsExprList': [
'ExpressibleAsConditionElement',
'ExpressibleAsSyntaxBuildable'
]
}
|
// ... existing code ...
SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = {
'ExpressibleAsConditionElement': [
'ExpressibleAsConditionElementList'
],
'ExpressibleAsDeclBuildable': [
'ExpressibleAsCodeBlockItem',
'ExpressibleAsMemberDeclListItem',
'ExpressibleAsSyntaxBuildable'
],
'ExpressibleAsStmtBuildable': [
'ExpressibleAsCodeBlockItem',
'ExpressibleAsSyntaxBuildable'
],
'ExpressibleAsExprList': [
'ExpressibleAsConditionElement',
'ExpressibleAsSyntaxBuildable'
]
}
// ... rest of the code ...
|
13e4a0ef064460ffa90bc150dc04b9a1fff26a1c
|
blanc_basic_news/news/templatetags/news_tags.py
|
blanc_basic_news/news/templatetags/news_tags.py
|
from django import template
from blanc_basic_news.news.models import Category, Post
register = template.Library()
@register.assignment_tag
def get_news_categories():
return Category.objects.all()
@register.assignment_tag
def get_news_months():
return Post.objects.dates('date', 'month')
|
from django import template
from django.utils import timezone
from blanc_basic_news.news.models import Category, Post
register = template.Library()
@register.assignment_tag
def get_news_categories():
return Category.objects.all()
@register.assignment_tag
def get_news_months():
return Post.objects.dates('date', 'month')
@register.assignment_tag
def get_latest_news(count):
return Post.objects.select_related().filter(
published=True, date__lte=timezone.now())[:count]
|
Add a template tag to get the latest news posts.
|
Add a template tag to get the latest news posts.
|
Python
|
bsd-3-clause
|
blancltd/blanc-basic-news
|
python
|
## Code Before:
from django import template
from blanc_basic_news.news.models import Category, Post
register = template.Library()
@register.assignment_tag
def get_news_categories():
return Category.objects.all()
@register.assignment_tag
def get_news_months():
return Post.objects.dates('date', 'month')
## Instruction:
Add a template tag to get the latest news posts.
## Code After:
from django import template
from django.utils import timezone
from blanc_basic_news.news.models import Category, Post
register = template.Library()
@register.assignment_tag
def get_news_categories():
return Category.objects.all()
@register.assignment_tag
def get_news_months():
return Post.objects.dates('date', 'month')
@register.assignment_tag
def get_latest_news(count):
return Post.objects.select_related().filter(
published=True, date__lte=timezone.now())[:count]
|
// ... existing code ...
from django import template
from django.utils import timezone
from blanc_basic_news.news.models import Category, Post
register = template.Library()
// ... modified code ...
@register.assignment_tag
def get_news_months():
return Post.objects.dates('date', 'month')
@register.assignment_tag
def get_latest_news(count):
return Post.objects.select_related().filter(
published=True, date__lte=timezone.now())[:count]
// ... rest of the code ...
|
0f4ca12e524be7cbd82ac79e81a62015b47ca6ef
|
openfisca_core/tests/formula_helpers.py
|
openfisca_core/tests/formula_helpers.py
|
import numpy
from nose.tools import raises
from openfisca_core.formula_helpers import apply_threshold as apply_threshold
from openfisca_core.tools import assert_near
@raises(AssertionError)
def test_apply_threshold_with_too_many_thresholds():
input = numpy.array([10])
thresholds = [5]
outputs = [10]
return apply_threshold(input, thresholds, outputs)
@raises(AssertionError)
def test_apply_threshold_with_too_few_thresholds():
input = numpy.array([10])
thresholds = [5]
outputs = [10, 15, 20]
return apply_threshold(input, thresholds, outputs)
def test_apply_threshold():
input = numpy.array([4, 5, 6, 7, 8])
thresholds = [5, 7]
outputs = [10, 15, 20]
result = apply_threshold(input, thresholds, outputs)
assert_near(result, [10, 10, 15, 15, 20])
|
import numpy
from nose.tools import raises
from openfisca_core.formula_helpers import apply_threshold as apply_threshold
from openfisca_core.tools import assert_near
@raises(AssertionError)
def test_apply_threshold_with_too_many_thresholds():
input = numpy.array([10])
thresholds = [5]
outputs = [10]
return apply_threshold(input, thresholds, outputs)
@raises(AssertionError)
def test_apply_threshold_with_too_few_thresholds():
input = numpy.array([10])
thresholds = [5]
outputs = [10, 15, 20]
return apply_threshold(input, thresholds, outputs)
def test_apply_threshold():
input = numpy.array([4, 5, 6, 7, 8])
thresholds = [5, 7]
outputs = [10, 15, 20]
result = apply_threshold(input, thresholds, outputs)
assert_near(result, [10, 10, 15, 15, 20])
def test_apply_threshold_with_variable_threshold():
input = numpy.array([1000, 1000, 1000])
thresholds = [numpy.array([500, 1500, 1000])] # Only one thresold, but varies with the person
outputs = [True, False] # True if input <= threshold, false otherwise
result = apply_threshold(input, thresholds, outputs)
assert_near(result, [False, True, True])
|
Add more tricky case test for apply_threshold
|
Add more tricky case test for apply_threshold
|
Python
|
agpl-3.0
|
benjello/openfisca-core,openfisca/openfisca-core,benjello/openfisca-core,sgmap/openfisca-core,openfisca/openfisca-core
|
python
|
## Code Before:
import numpy
from nose.tools import raises
from openfisca_core.formula_helpers import apply_threshold as apply_threshold
from openfisca_core.tools import assert_near
@raises(AssertionError)
def test_apply_threshold_with_too_many_thresholds():
input = numpy.array([10])
thresholds = [5]
outputs = [10]
return apply_threshold(input, thresholds, outputs)
@raises(AssertionError)
def test_apply_threshold_with_too_few_thresholds():
input = numpy.array([10])
thresholds = [5]
outputs = [10, 15, 20]
return apply_threshold(input, thresholds, outputs)
def test_apply_threshold():
input = numpy.array([4, 5, 6, 7, 8])
thresholds = [5, 7]
outputs = [10, 15, 20]
result = apply_threshold(input, thresholds, outputs)
assert_near(result, [10, 10, 15, 15, 20])
## Instruction:
Add more tricky case test for apply_threshold
## Code After:
import numpy
from nose.tools import raises
from openfisca_core.formula_helpers import apply_threshold as apply_threshold
from openfisca_core.tools import assert_near
@raises(AssertionError)
def test_apply_threshold_with_too_many_thresholds():
input = numpy.array([10])
thresholds = [5]
outputs = [10]
return apply_threshold(input, thresholds, outputs)
@raises(AssertionError)
def test_apply_threshold_with_too_few_thresholds():
input = numpy.array([10])
thresholds = [5]
outputs = [10, 15, 20]
return apply_threshold(input, thresholds, outputs)
def test_apply_threshold():
input = numpy.array([4, 5, 6, 7, 8])
thresholds = [5, 7]
outputs = [10, 15, 20]
result = apply_threshold(input, thresholds, outputs)
assert_near(result, [10, 10, 15, 15, 20])
def test_apply_threshold_with_variable_threshold():
input = numpy.array([1000, 1000, 1000])
thresholds = [numpy.array([500, 1500, 1000])] # Only one thresold, but varies with the person
outputs = [True, False] # True if input <= threshold, false otherwise
result = apply_threshold(input, thresholds, outputs)
assert_near(result, [False, True, True])
|
...
outputs = [10, 15, 20]
result = apply_threshold(input, thresholds, outputs)
assert_near(result, [10, 10, 15, 15, 20])
def test_apply_threshold_with_variable_threshold():
input = numpy.array([1000, 1000, 1000])
thresholds = [numpy.array([500, 1500, 1000])] # Only one thresold, but varies with the person
outputs = [True, False] # True if input <= threshold, false otherwise
result = apply_threshold(input, thresholds, outputs)
assert_near(result, [False, True, True])
...
|
3ff2042041f896829937d19cbd0aaab68f51cdd4
|
ktor-client/ktor-client-core/src/io/ktor/client/request/utils.kt
|
ktor-client/ktor-client-core/src/io/ktor/client/request/utils.kt
|
package io.ktor.client.request
import io.ktor.http.*
/**
* Gets the associated URL's host.
*/
var HttpRequestBuilder.host: String
get() = url.host
set(value) {
url.host = value
}
/**
* Gets the associated URL's port.
*/
var HttpRequestBuilder.port: Int
get() = url.port
set(value) {
url.port = value
}
/**
* Sets a single header of [key] with a specific [value] if the value is not null.
*/
fun HttpRequestBuilder.header(key: String, value: Any?): Unit =
value?.let { headers.append(key, it.toString()) } ?: Unit
/**
* Sets a single parameter of [key] with a specific [value] if the value is not null.
*/
fun HttpRequestBuilder.parameter(key: String, value: Any?): Unit =
value?.let { url.parameters.append(key, it.toString()) } ?: Unit
/**
* Sets the `Accept` header with a specific [contentType].
*/
fun HttpRequestBuilder.accept(contentType: ContentType): Unit =
headers.append(HttpHeaders.Accept, contentType.toString())
|
package io.ktor.client.request
import io.ktor.http.*
/**
* Gets the associated URL's host.
*/
var HttpRequestBuilder.host: String
get() = url.host
set(value) {
url.host = value
}
/**
* Gets the associated URL's port.
*/
var HttpRequestBuilder.port: Int
get() = url.port
set(value) {
url.port = value
}
/**
* Sets a single header of [key] with a specific [value] if the value is not null.
*/
fun HttpRequestBuilder.header(key: String, value: Any?): Unit =
value?.let { headers.append(key, it.toString()) } ?: Unit
/**
* Sets a single URL query parameter of [key] with a specific [value] if the value is not null. Can not be used to set
* form parameters in the body.
*/
fun HttpRequestBuilder.parameter(key: String, value: Any?): Unit =
value?.let { url.parameters.append(key, it.toString()) } ?: Unit
/**
* Sets the `Accept` header with a specific [contentType].
*/
fun HttpRequestBuilder.accept(contentType: ContentType): Unit =
headers.append(HttpHeaders.Accept, contentType.toString())
|
Clarify usage of HttpRequestBuilder.parameter() function
|
Clarify usage of HttpRequestBuilder.parameter() function
|
Kotlin
|
apache-2.0
|
ktorio/ktor,ktorio/ktor,ktorio/ktor,ktorio/ktor
|
kotlin
|
## Code Before:
package io.ktor.client.request
import io.ktor.http.*
/**
* Gets the associated URL's host.
*/
var HttpRequestBuilder.host: String
get() = url.host
set(value) {
url.host = value
}
/**
* Gets the associated URL's port.
*/
var HttpRequestBuilder.port: Int
get() = url.port
set(value) {
url.port = value
}
/**
* Sets a single header of [key] with a specific [value] if the value is not null.
*/
fun HttpRequestBuilder.header(key: String, value: Any?): Unit =
value?.let { headers.append(key, it.toString()) } ?: Unit
/**
* Sets a single parameter of [key] with a specific [value] if the value is not null.
*/
fun HttpRequestBuilder.parameter(key: String, value: Any?): Unit =
value?.let { url.parameters.append(key, it.toString()) } ?: Unit
/**
* Sets the `Accept` header with a specific [contentType].
*/
fun HttpRequestBuilder.accept(contentType: ContentType): Unit =
headers.append(HttpHeaders.Accept, contentType.toString())
## Instruction:
Clarify usage of HttpRequestBuilder.parameter() function
## Code After:
package io.ktor.client.request
import io.ktor.http.*
/**
* Gets the associated URL's host.
*/
var HttpRequestBuilder.host: String
get() = url.host
set(value) {
url.host = value
}
/**
* Gets the associated URL's port.
*/
var HttpRequestBuilder.port: Int
get() = url.port
set(value) {
url.port = value
}
/**
* Sets a single header of [key] with a specific [value] if the value is not null.
*/
fun HttpRequestBuilder.header(key: String, value: Any?): Unit =
value?.let { headers.append(key, it.toString()) } ?: Unit
/**
* Sets a single URL query parameter of [key] with a specific [value] if the value is not null. Can not be used to set
* form parameters in the body.
*/
fun HttpRequestBuilder.parameter(key: String, value: Any?): Unit =
value?.let { url.parameters.append(key, it.toString()) } ?: Unit
/**
* Sets the `Accept` header with a specific [contentType].
*/
fun HttpRequestBuilder.accept(contentType: ContentType): Unit =
headers.append(HttpHeaders.Accept, contentType.toString())
|
...
value?.let { headers.append(key, it.toString()) } ?: Unit
/**
* Sets a single URL query parameter of [key] with a specific [value] if the value is not null. Can not be used to set
* form parameters in the body.
*/
fun HttpRequestBuilder.parameter(key: String, value: Any?): Unit =
value?.let { url.parameters.append(key, it.toString()) } ?: Unit
...
|
15d87fb06b3882334f48fd71b258e915dbefa6e1
|
koans/about_list_assignments.py
|
koans/about_list_assignments.py
|
from runner.koan import *
class AboutListAssignments(Koan):
def test_non_parallel_assignment(self):
names = ["John", "Smith"]
self.assertEqual(__, names)
def test_parallel_assignments(self):
first_name, last_name = ["John", "Smith"]
self.assertEqual(__, first_name)
self.assertEqual(__, last_name)
def test_parallel_assignments_with_extra_values(self):
title, *first_names, last_name = ["Sir", "Ricky", "Bobby", "Worthington"]
self.assertEqual(__, title)
self.assertEqual(__, first_names)
self.assertEqual(__, last_name)
def test_parallel_assignments_with_sublists(self):
first_name, last_name = [["Willie", "Rae"], "Johnson"]
self.assertEqual(__, first_name)
self.assertEqual(__, last_name)
def test_swapping_with_parallel_assignment(self):
first_name = "Roy"
last_name = "Rob"
first_name, last_name = last_name, first_name
self.assertEqual(__, first_name)
self.assertEqual(__, last_name)
|
from runner.koan import *
class AboutListAssignments(Koan):
def test_non_parallel_assignment(self):
names = ["John", "Smith"]
self.assertEqual(["John", "Smith"], names)
def test_parallel_assignments(self):
first_name, last_name = ["John", "Smith"]
self.assertEqual("John", first_name)
self.assertEqual("Smith", last_name)
def test_parallel_assignments_with_extra_values(self):
title, *first_names, last_name = ["Sir", "Ricky", "Bobby", "Worthington"]
self.assertEqual("Sir", title)
self.assertEqual(["Ricky", "Bobby"], first_names)
self.assertEqual("Worthington", last_name)
def test_parallel_assignments_with_sublists(self):
first_name, last_name = [["Willie", "Rae"], "Johnson"]
self.assertEqual(["Willie", "Rae"], first_name)
self.assertEqual("Johnson", last_name)
def test_swapping_with_parallel_assignment(self):
first_name = "Roy"
last_name = "Rob"
first_name, last_name = last_name, first_name
self.assertEqual("Rob", first_name)
self.assertEqual("Roy", last_name)
|
Add completed list assignments koan.
|
Add completed list assignments koan.
|
Python
|
mit
|
javierjulio/python-koans-completed,javierjulio/python-koans-completed
|
python
|
## Code Before:
from runner.koan import *
class AboutListAssignments(Koan):
def test_non_parallel_assignment(self):
names = ["John", "Smith"]
self.assertEqual(__, names)
def test_parallel_assignments(self):
first_name, last_name = ["John", "Smith"]
self.assertEqual(__, first_name)
self.assertEqual(__, last_name)
def test_parallel_assignments_with_extra_values(self):
title, *first_names, last_name = ["Sir", "Ricky", "Bobby", "Worthington"]
self.assertEqual(__, title)
self.assertEqual(__, first_names)
self.assertEqual(__, last_name)
def test_parallel_assignments_with_sublists(self):
first_name, last_name = [["Willie", "Rae"], "Johnson"]
self.assertEqual(__, first_name)
self.assertEqual(__, last_name)
def test_swapping_with_parallel_assignment(self):
first_name = "Roy"
last_name = "Rob"
first_name, last_name = last_name, first_name
self.assertEqual(__, first_name)
self.assertEqual(__, last_name)
## Instruction:
Add completed list assignments koan.
## Code After:
from runner.koan import *
class AboutListAssignments(Koan):
def test_non_parallel_assignment(self):
names = ["John", "Smith"]
self.assertEqual(["John", "Smith"], names)
def test_parallel_assignments(self):
first_name, last_name = ["John", "Smith"]
self.assertEqual("John", first_name)
self.assertEqual("Smith", last_name)
def test_parallel_assignments_with_extra_values(self):
title, *first_names, last_name = ["Sir", "Ricky", "Bobby", "Worthington"]
self.assertEqual("Sir", title)
self.assertEqual(["Ricky", "Bobby"], first_names)
self.assertEqual("Worthington", last_name)
def test_parallel_assignments_with_sublists(self):
first_name, last_name = [["Willie", "Rae"], "Johnson"]
self.assertEqual(["Willie", "Rae"], first_name)
self.assertEqual("Johnson", last_name)
def test_swapping_with_parallel_assignment(self):
first_name = "Roy"
last_name = "Rob"
first_name, last_name = last_name, first_name
self.assertEqual("Rob", first_name)
self.assertEqual("Roy", last_name)
|
// ... existing code ...
class AboutListAssignments(Koan):
def test_non_parallel_assignment(self):
names = ["John", "Smith"]
self.assertEqual(["John", "Smith"], names)
def test_parallel_assignments(self):
first_name, last_name = ["John", "Smith"]
self.assertEqual("John", first_name)
self.assertEqual("Smith", last_name)
def test_parallel_assignments_with_extra_values(self):
title, *first_names, last_name = ["Sir", "Ricky", "Bobby", "Worthington"]
self.assertEqual("Sir", title)
self.assertEqual(["Ricky", "Bobby"], first_names)
self.assertEqual("Worthington", last_name)
def test_parallel_assignments_with_sublists(self):
first_name, last_name = [["Willie", "Rae"], "Johnson"]
self.assertEqual(["Willie", "Rae"], first_name)
self.assertEqual("Johnson", last_name)
def test_swapping_with_parallel_assignment(self):
first_name = "Roy"
last_name = "Rob"
first_name, last_name = last_name, first_name
self.assertEqual("Rob", first_name)
self.assertEqual("Roy", last_name)
// ... rest of the code ...
|
4874f1b1a7a3ff465493f601f5f056bf8f3f1921
|
badgekit_webhooks/urls.py
|
badgekit_webhooks/urls.py
|
from __future__ import unicode_literals
from django.conf.urls import patterns, url
from . import views
from django.contrib.admin.views.decorators import staff_member_required
urlpatterns = patterns(
"",
url(r"^hello/$", "badgekit_webhooks.views.hello", name="badgekit_webhooks_hello"),
url(r"^issued/$", "badgekit_webhooks.views.badge_issued_hook",
name="badge_issued_hook"),
url(r"^instances/([-A-Za-z.0-9_]+)/$", staff_member_required(views.badge_instance_list),
name="badge_instance_list"),
url(r"^claim/([-A-Za-z0-9_]+)/$", 'badgekit_webhooks.views.claim_page'),
url(r"^claim/([-A-Za-z0-9_]+)/email/(html|text)$", 'badgekit_webhooks.views.show_claim_email',
name="show_claim_email"),
url(r"^issue/$", staff_member_required(views.SendClaimCodeView.as_view()),
name="badge_issue_form"),
url(r"^claimcode/([-A-Za-z.0-9_]+)/$",
views.ClaimCodeClaimView.as_view(), name='claimcode_claim'),
url(r"^badges/$", "badgekit_webhooks.views.list_badges_view", name="badges_list"),
)
|
from __future__ import unicode_literals
from django.conf.urls import patterns, url
from . import views
from django.contrib.admin.views.decorators import staff_member_required
urlpatterns = patterns(
"",
url(r"^hello/$", "badgekit_webhooks.views.hello", name="badgekit_webhooks_hello"),
url(r"^issued/$", "badgekit_webhooks.views.badge_issued_hook",
name="badge_issued_hook"),
url(r"^claim/([-A-Za-z0-9_]+)/$", 'badgekit_webhooks.views.claim_page'),
url(r"^claim/([-A-Za-z0-9_]+)/email/(html|text)$", 'badgekit_webhooks.views.show_claim_email',
name="show_claim_email"),
url(r"^issue/$", staff_member_required(views.SendClaimCodeView.as_view()),
name="badge_issue_form"),
url(r"^claimcode/([-A-Za-z.0-9_]+)/$",
views.ClaimCodeClaimView.as_view(), name='claimcode_claim'),
url(r"^badges/$", "badgekit_webhooks.views.list_badges_view", name="badges_list"),
url(r"^badges/([-A-Za-z.0-9_]+)/instances/$", staff_member_required(views.badge_instance_list),
name="badge_instance_list"),
)
|
Move badge instance list beneath 'badges' url
|
Move badge instance list beneath 'badges' url
|
Python
|
mit
|
tgs/django-badgekit-webhooks
|
python
|
## Code Before:
from __future__ import unicode_literals
from django.conf.urls import patterns, url
from . import views
from django.contrib.admin.views.decorators import staff_member_required
urlpatterns = patterns(
"",
url(r"^hello/$", "badgekit_webhooks.views.hello", name="badgekit_webhooks_hello"),
url(r"^issued/$", "badgekit_webhooks.views.badge_issued_hook",
name="badge_issued_hook"),
url(r"^instances/([-A-Za-z.0-9_]+)/$", staff_member_required(views.badge_instance_list),
name="badge_instance_list"),
url(r"^claim/([-A-Za-z0-9_]+)/$", 'badgekit_webhooks.views.claim_page'),
url(r"^claim/([-A-Za-z0-9_]+)/email/(html|text)$", 'badgekit_webhooks.views.show_claim_email',
name="show_claim_email"),
url(r"^issue/$", staff_member_required(views.SendClaimCodeView.as_view()),
name="badge_issue_form"),
url(r"^claimcode/([-A-Za-z.0-9_]+)/$",
views.ClaimCodeClaimView.as_view(), name='claimcode_claim'),
url(r"^badges/$", "badgekit_webhooks.views.list_badges_view", name="badges_list"),
)
## Instruction:
Move badge instance list beneath 'badges' url
## Code After:
from __future__ import unicode_literals
from django.conf.urls import patterns, url
from . import views
from django.contrib.admin.views.decorators import staff_member_required
urlpatterns = patterns(
"",
url(r"^hello/$", "badgekit_webhooks.views.hello", name="badgekit_webhooks_hello"),
url(r"^issued/$", "badgekit_webhooks.views.badge_issued_hook",
name="badge_issued_hook"),
url(r"^claim/([-A-Za-z0-9_]+)/$", 'badgekit_webhooks.views.claim_page'),
url(r"^claim/([-A-Za-z0-9_]+)/email/(html|text)$", 'badgekit_webhooks.views.show_claim_email',
name="show_claim_email"),
url(r"^issue/$", staff_member_required(views.SendClaimCodeView.as_view()),
name="badge_issue_form"),
url(r"^claimcode/([-A-Za-z.0-9_]+)/$",
views.ClaimCodeClaimView.as_view(), name='claimcode_claim'),
url(r"^badges/$", "badgekit_webhooks.views.list_badges_view", name="badges_list"),
url(r"^badges/([-A-Za-z.0-9_]+)/instances/$", staff_member_required(views.badge_instance_list),
name="badge_instance_list"),
)
|
...
url(r"^hello/$", "badgekit_webhooks.views.hello", name="badgekit_webhooks_hello"),
url(r"^issued/$", "badgekit_webhooks.views.badge_issued_hook",
name="badge_issued_hook"),
url(r"^claim/([-A-Za-z0-9_]+)/$", 'badgekit_webhooks.views.claim_page'),
url(r"^claim/([-A-Za-z0-9_]+)/email/(html|text)$", 'badgekit_webhooks.views.show_claim_email',
name="show_claim_email"),
...
url(r"^claimcode/([-A-Za-z.0-9_]+)/$",
views.ClaimCodeClaimView.as_view(), name='claimcode_claim'),
url(r"^badges/$", "badgekit_webhooks.views.list_badges_view", name="badges_list"),
url(r"^badges/([-A-Za-z.0-9_]+)/instances/$", staff_member_required(views.badge_instance_list),
name="badge_instance_list"),
)
...
|
525bfce19f593cb598669cdf2eec46747a4b6952
|
goodreadsapi.py
|
goodreadsapi.py
|
import re
from xml.parsers.expat import ExpatError
import requests
import xmltodict
from settings import goodreads_api_key
def get_goodreads_ids(comment_msg):
# receives goodreads url
# returns the id using regex
regex = r'goodreads.com/book/show/(\d+)'
return set(re.findall(regex, comment_msg))
def get_book_details_by_id(goodreads_id):
api_url = 'http://goodreads.com/book/show/{0}?format=xml&key={1}'
r = requests.get(api_url.format(goodreads_id, goodreads_api_key))
try:
book_data = xmltodict.parse(r.content)['GoodreadsResponse']['book']
except (TypeError, KeyError, ExpatError):
return False
keys = ['title', 'average_rating', 'ratings_count', 'description',
'num_pages']
book = {}
for k in keys:
book[k] = book_data[k]
if type(book_data['authors']['author']) == list:
authors = [author['name'] for author in book_data['authors']['author']]
authors = ', '.join(authors)
else:
authors = book_data['authors']['author']['name']
book['authors'] = authors
return book
|
import re
from xml.parsers.expat import ExpatError
import requests
import xmltodict
from settings import goodreads_api_key
def get_goodreads_ids(comment_msg):
# receives goodreads url
# returns the id using regex
regex = r'goodreads.com/book/show/(\d+)'
return set(re.findall(regex, comment_msg))
def get_book_details_by_id(goodreads_id):
api_url = 'http://goodreads.com/book/show/{0}?format=xml&key={1}'
r = requests.get(api_url.format(goodreads_id, goodreads_api_key))
try:
book_data = xmltodict.parse(r.content)['GoodreadsResponse']['book']
except (TypeError, KeyError, ExpatError):
return False
keys = ['title', 'average_rating', 'ratings_count', 'description',
'num_pages', 'publication_year']
book = {}
for k in keys:
book[k] = book_data.get(k)
if type(book_data['authors']['author']) == list:
authors = [author['name'] for author in book_data['authors']['author']]
authors = ', '.join(authors)
else:
authors = book_data['authors']['author']['name']
book['authors'] = authors
return book
|
Add `publication_year` to return data
|
Add `publication_year` to return data
|
Python
|
mit
|
avinassh/Reddit-GoodReads-Bot
|
python
|
## Code Before:
import re
from xml.parsers.expat import ExpatError
import requests
import xmltodict
from settings import goodreads_api_key
def get_goodreads_ids(comment_msg):
# receives goodreads url
# returns the id using regex
regex = r'goodreads.com/book/show/(\d+)'
return set(re.findall(regex, comment_msg))
def get_book_details_by_id(goodreads_id):
api_url = 'http://goodreads.com/book/show/{0}?format=xml&key={1}'
r = requests.get(api_url.format(goodreads_id, goodreads_api_key))
try:
book_data = xmltodict.parse(r.content)['GoodreadsResponse']['book']
except (TypeError, KeyError, ExpatError):
return False
keys = ['title', 'average_rating', 'ratings_count', 'description',
'num_pages']
book = {}
for k in keys:
book[k] = book_data[k]
if type(book_data['authors']['author']) == list:
authors = [author['name'] for author in book_data['authors']['author']]
authors = ', '.join(authors)
else:
authors = book_data['authors']['author']['name']
book['authors'] = authors
return book
## Instruction:
Add `publication_year` to return data
## Code After:
import re
from xml.parsers.expat import ExpatError
import requests
import xmltodict
from settings import goodreads_api_key
def get_goodreads_ids(comment_msg):
# receives goodreads url
# returns the id using regex
regex = r'goodreads.com/book/show/(\d+)'
return set(re.findall(regex, comment_msg))
def get_book_details_by_id(goodreads_id):
api_url = 'http://goodreads.com/book/show/{0}?format=xml&key={1}'
r = requests.get(api_url.format(goodreads_id, goodreads_api_key))
try:
book_data = xmltodict.parse(r.content)['GoodreadsResponse']['book']
except (TypeError, KeyError, ExpatError):
return False
keys = ['title', 'average_rating', 'ratings_count', 'description',
'num_pages', 'publication_year']
book = {}
for k in keys:
book[k] = book_data.get(k)
if type(book_data['authors']['author']) == list:
authors = [author['name'] for author in book_data['authors']['author']]
authors = ', '.join(authors)
else:
authors = book_data['authors']['author']['name']
book['authors'] = authors
return book
|
# ... existing code ...
except (TypeError, KeyError, ExpatError):
return False
keys = ['title', 'average_rating', 'ratings_count', 'description',
'num_pages', 'publication_year']
book = {}
for k in keys:
book[k] = book_data.get(k)
if type(book_data['authors']['author']) == list:
authors = [author['name'] for author in book_data['authors']['author']]
authors = ', '.join(authors)
# ... rest of the code ...
|
f29b65fa18ae5bcae352ad1050a5b83d8ffffd53
|
modules/vf_audio/sources/vf_SampleSource.h
|
modules/vf_audio/sources/vf_SampleSource.h
|
/*============================================================================*/
/*
Copyright (C) 2008 by Vinnie Falco, this file is part of VFLib.
See the file GNU_GPL_v2.txt for full licensing terms.
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option)
any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 51
Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*============================================================================*/
#ifndef VF_SAMPLESOURCE_VFHEADER
#define VF_SAMPLESOURCE_VFHEADER
//==============================================================================
/**
Abstract source of audio samples.
This interface is used to retrieve sequentual raw audio samples from an
abstract source. It is intended as a facade for @ref AudioSource, with these
features:
- No thread safety; the caller is responsible for all synchronization.
- The preparation state feature is removed (along with its methods).
@ingroup vf_audio
*/
class SampleSource
{
public:
/**
Read the next block of samples.
*/
virtual void getNextAudioBlock (AudioSourceChannelInfo const& bufferToFill) = 0;
};
#endif
|
/*============================================================================*/
/*
Copyright (C) 2008 by Vinnie Falco, this file is part of VFLib.
See the file GNU_GPL_v2.txt for full licensing terms.
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option)
any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 51
Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*============================================================================*/
#ifndef VF_SAMPLESOURCE_VFHEADER
#define VF_SAMPLESOURCE_VFHEADER
//==============================================================================
/**
Abstract source of audio samples.
This interface is used to retrieve sequentual raw audio samples from an
abstract source. It is intended as a facade for @ref AudioSource, with these
features:
- No thread safety; the caller is responsible for all synchronization.
- The preparation state feature is removed (along with its methods).
@ingroup vf_audio
*/
class SampleSource
{
public:
virtual ~SampleSource () { }
/**
Read the next block of samples.
*/
virtual void getNextAudioBlock (AudioSourceChannelInfo const& bufferToFill) = 0;
};
#endif
|
Make dtor virtual in SampleSource
|
Make dtor virtual in SampleSource
|
C
|
mit
|
vinniefalco/VFLib,spthaolt/VFLib,spthaolt/VFLib,vinniefalco/VFLib
|
c
|
## Code Before:
/*============================================================================*/
/*
Copyright (C) 2008 by Vinnie Falco, this file is part of VFLib.
See the file GNU_GPL_v2.txt for full licensing terms.
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option)
any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 51
Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*============================================================================*/
#ifndef VF_SAMPLESOURCE_VFHEADER
#define VF_SAMPLESOURCE_VFHEADER
//==============================================================================
/**
Abstract source of audio samples.
This interface is used to retrieve sequentual raw audio samples from an
abstract source. It is intended as a facade for @ref AudioSource, with these
features:
- No thread safety; the caller is responsible for all synchronization.
- The preparation state feature is removed (along with its methods).
@ingroup vf_audio
*/
class SampleSource
{
public:
/**
Read the next block of samples.
*/
virtual void getNextAudioBlock (AudioSourceChannelInfo const& bufferToFill) = 0;
};
#endif
## Instruction:
Make dtor virtual in SampleSource
## Code After:
/*============================================================================*/
/*
Copyright (C) 2008 by Vinnie Falco, this file is part of VFLib.
See the file GNU_GPL_v2.txt for full licensing terms.
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option)
any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 51
Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*============================================================================*/
#ifndef VF_SAMPLESOURCE_VFHEADER
#define VF_SAMPLESOURCE_VFHEADER
//==============================================================================
/**
Abstract source of audio samples.
This interface is used to retrieve sequentual raw audio samples from an
abstract source. It is intended as a facade for @ref AudioSource, with these
features:
- No thread safety; the caller is responsible for all synchronization.
- The preparation state feature is removed (along with its methods).
@ingroup vf_audio
*/
class SampleSource
{
public:
virtual ~SampleSource () { }
/**
Read the next block of samples.
*/
virtual void getNextAudioBlock (AudioSourceChannelInfo const& bufferToFill) = 0;
};
#endif
|
# ... existing code ...
class SampleSource
{
public:
virtual ~SampleSource () { }
/**
Read the next block of samples.
*/
# ... rest of the code ...
|
ae78bd758c690e28abaae2c07e8a3890e76044e0
|
pylearn2/scripts/papers/maxout/tests/test_mnist.py
|
pylearn2/scripts/papers/maxout/tests/test_mnist.py
|
import os
import numpy as np
import pylearn2
from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix
from pylearn2.termination_criteria import EpochCounter
from pylearn2.utils.serial import load_train_file
def test_mnist():
"""
Test the mnist.yaml file from the dropout
paper on random input
"""
train = load_train_file(os.path.join(pylearn2.__path__[0],
"scripts/papers/maxout/mnist.yaml"))
random_X = np.random.rand(10, 784)
random_y = np.random.randint(0, 10, (10, 1))
train.dataset = DenseDesignMatrix(X=random_X, y=random_y, y_labels=10)
train.algorithm.termination_criterion = EpochCounter(max_epochs=1)
train.main_loop()
|
import os
import numpy as np
import pylearn2
from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix
from pylearn2.termination_criteria import EpochCounter
from pylearn2.utils.serial import load_train_file
def test_mnist():
"""
Test the mnist.yaml file from the dropout
paper on random input
"""
train = load_train_file(os.path.join(pylearn2.__path__[0],
"scripts/papers/maxout/mnist.yaml"))
random_X = np.random.rand(10, 784)
random_y = np.random.randint(0, 10, (10, 1))
train.dataset = DenseDesignMatrix(X=random_X, y=random_y, y_labels=10)
train.algorithm.termination_criterion = EpochCounter(max_epochs=1)
train.algorithm._set_monitoring_dataset(train.dataset)
train.main_loop()
|
Allow papers/maxout to be tested without MNIST data
|
Allow papers/maxout to be tested without MNIST data
|
Python
|
bsd-3-clause
|
KennethPierce/pylearnk,KennethPierce/pylearnk,Refefer/pylearn2,JesseLivezey/plankton,goodfeli/pylearn2,theoryno3/pylearn2,alexjc/pylearn2,pkainz/pylearn2,fulmicoton/pylearn2,alexjc/pylearn2,alexjc/pylearn2,kastnerkyle/pylearn2,ddboline/pylearn2,se4u/pylearn2,hantek/pylearn2,jeremyfix/pylearn2,nouiz/pylearn2,abergeron/pylearn2,sandeepkbhat/pylearn2,chrish42/pylearn,msingh172/pylearn2,caidongyun/pylearn2,fulmicoton/pylearn2,Refefer/pylearn2,skearnes/pylearn2,sandeepkbhat/pylearn2,mclaughlin6464/pylearn2,hantek/pylearn2,sandeepkbhat/pylearn2,fyffyt/pylearn2,bartvm/pylearn2,fulmicoton/pylearn2,jamessergeant/pylearn2,se4u/pylearn2,mkraemer67/pylearn2,TNick/pylearn2,junbochen/pylearn2,sandeepkbhat/pylearn2,hyqneuron/pylearn2-maxsom,woozzu/pylearn2,CIFASIS/pylearn2,pombredanne/pylearn2,fishcorn/pylearn2,JesseLivezey/pylearn2,ashhher3/pylearn2,lunyang/pylearn2,mkraemer67/pylearn2,lisa-lab/pylearn2,pombredanne/pylearn2,daemonmaker/pylearn2,ddboline/pylearn2,junbochen/pylearn2,JesseLivezey/plankton,hantek/pylearn2,msingh172/pylearn2,ashhher3/pylearn2,ddboline/pylearn2,matrogers/pylearn2,abergeron/pylearn2,ashhher3/pylearn2,shiquanwang/pylearn2,goodfeli/pylearn2,pombredanne/pylearn2,nouiz/pylearn2,nouiz/pylearn2,matrogers/pylearn2,cosmoharrigan/pylearn2,kastnerkyle/pylearn2,shiquanwang/pylearn2,kose-y/pylearn2,aalmah/pylearn2,abergeron/pylearn2,junbochen/pylearn2,w1kke/pylearn2,fyffyt/pylearn2,daemonmaker/pylearn2,fyffyt/pylearn2,skearnes/pylearn2,JesseLivezey/plankton,mclaughlin6464/pylearn2,nouiz/pylearn2,hantek/pylearn2,se4u/pylearn2,lamblin/pylearn2,ddboline/pylearn2,lisa-lab/pylearn2,kastnerkyle/pylearn2,aalmah/pylearn2,lamblin/pylearn2,theoryno3/pylearn2,JesseLivezey/pylearn2,TNick/pylearn2,bartvm/pylearn2,shiquanwang/pylearn2,JesseLivezey/plankton,shiquanwang/pylearn2,chrish42/pylearn,CIFASIS/pylearn2,chrish42/pylearn,mclaughlin6464/pylearn2,jamessergeant/pylearn2,lancezlin/pylearn2,lisa-lab/pylearn2,jamessergeant/pylearn2,lancezlin/pylearn2,matrogers/pylearn2,mkraemer67/pylearn2,theoryno3/pylearn2,junbochen/pylearn2,daemonmaker/pylearn2,pkainz/pylearn2,theoryno3/pylearn2,CIFASIS/pylearn2,cosmoharrigan/pylearn2,jeremyfix/pylearn2,caidongyun/pylearn2,bartvm/pylearn2,se4u/pylearn2,kose-y/pylearn2,msingh172/pylearn2,KennethPierce/pylearnk,hyqneuron/pylearn2-maxsom,hyqneuron/pylearn2-maxsom,fishcorn/pylearn2,KennethPierce/pylearnk,fyffyt/pylearn2,kose-y/pylearn2,jamessergeant/pylearn2,lancezlin/pylearn2,caidongyun/pylearn2,lamblin/pylearn2,cosmoharrigan/pylearn2,skearnes/pylearn2,goodfeli/pylearn2,matrogers/pylearn2,fishcorn/pylearn2,fulmicoton/pylearn2,w1kke/pylearn2,caidongyun/pylearn2,CIFASIS/pylearn2,msingh172/pylearn2,pkainz/pylearn2,Refefer/pylearn2,aalmah/pylearn2,chrish42/pylearn,pkainz/pylearn2,bartvm/pylearn2,woozzu/pylearn2,jeremyfix/pylearn2,ashhher3/pylearn2,pombredanne/pylearn2,jeremyfix/pylearn2,Refefer/pylearn2,lunyang/pylearn2,lisa-lab/pylearn2,JesseLivezey/pylearn2,skearnes/pylearn2,lunyang/pylearn2,TNick/pylearn2,goodfeli/pylearn2,kose-y/pylearn2,woozzu/pylearn2,lancezlin/pylearn2,fishcorn/pylearn2,aalmah/pylearn2,lamblin/pylearn2,daemonmaker/pylearn2,kastnerkyle/pylearn2,JesseLivezey/pylearn2,mclaughlin6464/pylearn2,hyqneuron/pylearn2-maxsom,lunyang/pylearn2,woozzu/pylearn2,abergeron/pylearn2,w1kke/pylearn2,cosmoharrigan/pylearn2,alexjc/pylearn2,TNick/pylearn2,mkraemer67/pylearn2,w1kke/pylearn2
|
python
|
## Code Before:
import os
import numpy as np
import pylearn2
from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix
from pylearn2.termination_criteria import EpochCounter
from pylearn2.utils.serial import load_train_file
def test_mnist():
"""
Test the mnist.yaml file from the dropout
paper on random input
"""
train = load_train_file(os.path.join(pylearn2.__path__[0],
"scripts/papers/maxout/mnist.yaml"))
random_X = np.random.rand(10, 784)
random_y = np.random.randint(0, 10, (10, 1))
train.dataset = DenseDesignMatrix(X=random_X, y=random_y, y_labels=10)
train.algorithm.termination_criterion = EpochCounter(max_epochs=1)
train.main_loop()
## Instruction:
Allow papers/maxout to be tested without MNIST data
## Code After:
import os
import numpy as np
import pylearn2
from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix
from pylearn2.termination_criteria import EpochCounter
from pylearn2.utils.serial import load_train_file
def test_mnist():
"""
Test the mnist.yaml file from the dropout
paper on random input
"""
train = load_train_file(os.path.join(pylearn2.__path__[0],
"scripts/papers/maxout/mnist.yaml"))
random_X = np.random.rand(10, 784)
random_y = np.random.randint(0, 10, (10, 1))
train.dataset = DenseDesignMatrix(X=random_X, y=random_y, y_labels=10)
train.algorithm.termination_criterion = EpochCounter(max_epochs=1)
train.algorithm._set_monitoring_dataset(train.dataset)
train.main_loop()
|
# ... existing code ...
from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix
from pylearn2.termination_criteria import EpochCounter
from pylearn2.utils.serial import load_train_file
def test_mnist():
"""
# ... modified code ...
random_X = np.random.rand(10, 784)
random_y = np.random.randint(0, 10, (10, 1))
train.dataset = DenseDesignMatrix(X=random_X, y=random_y, y_labels=10)
train.algorithm.termination_criterion = EpochCounter(max_epochs=1)
train.algorithm._set_monitoring_dataset(train.dataset)
train.main_loop()
# ... rest of the code ...
|
a03b166f8297783819a43eeb78e5af4d52d11bcc
|
carbonate/list.py
|
carbonate/list.py
|
import os
import re
# Use the built-in version of scandir/walk if possible, otherwise
# use the scandir module version
try:
from os import scandir, walk
except ImportError:
from scandir import scandir, walk
def listMetrics(storage_dir, follow_sym_links=False, metric_suffix='wsp'):
metric_regex = re.compile(".*\.%s$" % metric_suffix)
storage_dir = storage_dir.rstrip(os.sep)
for root, dirnames, filenames in walk(storage_dir,
followlinks=follow_sym_links):
for filename in filenames:
if metric_regex.match(filename):
root_path = root[len(storage_dir) + 1:]
m_path = os.path.join(root_path, filename)
m_name, m_ext = os.path.splitext(m_path)
m_name = m_name.replace('/', '.')
yield m_name
|
import os
import re
# Use the built-in version of scandir/walk if possible, otherwise
# use the scandir module version
try:
from os import scandir, walk # noqa # pylint: disable=unused-import
except ImportError:
from scandir import scandir, walk # noqa # pylint: disable=unused-import
def listMetrics(storage_dir, follow_sym_links=False, metric_suffix='wsp'):
metric_regex = re.compile(".*\.%s$" % metric_suffix)
storage_dir = storage_dir.rstrip(os.sep)
for root, _, filenames in walk(storage_dir, followlinks=follow_sym_links):
for filename in filenames:
if metric_regex.match(filename):
root_path = root[len(storage_dir) + 1:]
m_path = os.path.join(root_path, filename)
m_name, m_ext = os.path.splitext(m_path)
m_name = m_name.replace('/', '.')
yield m_name
|
Make pylint happy as per graphite-web example
|
Make pylint happy as per graphite-web example
|
Python
|
mit
|
criteo-forks/carbonate,jssjr/carbonate,deniszh/carbonate,graphite-project/carbonate,jssjr/carbonate,graphite-project/carbonate,criteo-forks/carbonate,jssjr/carbonate,deniszh/carbonate,deniszh/carbonate,criteo-forks/carbonate,graphite-project/carbonate
|
python
|
## Code Before:
import os
import re
# Use the built-in version of scandir/walk if possible, otherwise
# use the scandir module version
try:
from os import scandir, walk
except ImportError:
from scandir import scandir, walk
def listMetrics(storage_dir, follow_sym_links=False, metric_suffix='wsp'):
metric_regex = re.compile(".*\.%s$" % metric_suffix)
storage_dir = storage_dir.rstrip(os.sep)
for root, dirnames, filenames in walk(storage_dir,
followlinks=follow_sym_links):
for filename in filenames:
if metric_regex.match(filename):
root_path = root[len(storage_dir) + 1:]
m_path = os.path.join(root_path, filename)
m_name, m_ext = os.path.splitext(m_path)
m_name = m_name.replace('/', '.')
yield m_name
## Instruction:
Make pylint happy as per graphite-web example
## Code After:
import os
import re
# Use the built-in version of scandir/walk if possible, otherwise
# use the scandir module version
try:
from os import scandir, walk # noqa # pylint: disable=unused-import
except ImportError:
from scandir import scandir, walk # noqa # pylint: disable=unused-import
def listMetrics(storage_dir, follow_sym_links=False, metric_suffix='wsp'):
metric_regex = re.compile(".*\.%s$" % metric_suffix)
storage_dir = storage_dir.rstrip(os.sep)
for root, _, filenames in walk(storage_dir, followlinks=follow_sym_links):
for filename in filenames:
if metric_regex.match(filename):
root_path = root[len(storage_dir) + 1:]
m_path = os.path.join(root_path, filename)
m_name, m_ext = os.path.splitext(m_path)
m_name = m_name.replace('/', '.')
yield m_name
|
...
# Use the built-in version of scandir/walk if possible, otherwise
# use the scandir module version
try:
from os import scandir, walk # noqa # pylint: disable=unused-import
except ImportError:
from scandir import scandir, walk # noqa # pylint: disable=unused-import
def listMetrics(storage_dir, follow_sym_links=False, metric_suffix='wsp'):
...
storage_dir = storage_dir.rstrip(os.sep)
for root, _, filenames in walk(storage_dir, followlinks=follow_sym_links):
for filename in filenames:
if metric_regex.match(filename):
root_path = root[len(storage_dir) + 1:]
...
|
c9e2c70e05ade220e5aa6a4790ee2a9b720cc46e
|
sorting_test.py
|
sorting_test.py
|
import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint
def main(max_len):
for n in [2**(n+1) for n in range(max_len)]:
print 'Array size: %d' % n
arr = [randint(0, 2**max_len) for n in range(n)]
current_time = time.time()
quicksort.quicksort.check(mergesort.merge_sort.sort(arr))
print 'Merge sort: %f' % (time.time() - current_time)
current_time = time.time()
quicksort.quicksort.check(quicksort.quicksort.sort(arr, 0, len(arr)))
print 'Quicksort: %f' % (time.time() - current_time)
print '-----------------'
if __name__ == '__main__':
try:
max_len = int(sys.argv[1])
except (IndexError, ValueError):
print 'Format: python sorting_test.py <log(max input)>'
main(max_len)
|
import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint
def multi_size(max_len):
for n in [2**(n+1) for n in range(max_len)]:
print 'Array size: %d' % n
arr = [randint(0, 2**max_len) for n in range(n)]
current_time = time.time()
quicksort.quicksort.check(mergesort.merge_sort.sort(arr), n+1)
print 'Merge sort: %f' % (time.time() - current_time)
current_time = time.time()
quicksort.quicksort.check(quicksort.quicksort.sort(arr, 0, n+1), n+1)
print 'Quicksort: %f' % (time.time() - current_time)
print '-----------------'
def fixed_time(sec, length):
count = 0
start = time.time()
end = start + sec
while time.time() < end:
arr = [randint(0, length) for n in range(length)]
mergesort.merge_sort.sort(arr)
count += 1
print 'Merge sort: %d %d-element arrays in %d seconds' % (count, length, sec)
count = 0
start = time.time()
end = start + sec
while time.time() < end:
arr = [randint(0, length) for n in range(length)]
quicksort.quicksort.sort(arr, 0, length)
count += 1
print 'Quicksort: %d %d-element arrays in %d seconds' % (count, length, sec)
if __name__ == '__main__':
if len(sys.argv) > 2:
fixed_time(int(sys.argv[1]), int(sys.argv[2]))
else:
multi_size(int(sys.argv[1]))
|
Allow comparison within a fixed time period
|
Allow comparison within a fixed time period
To get an idea of average run-time, I wanted to be able to test
mergesort and quicksort with the same inputs many times over;
now by specifying a time limit and array length, the script will
run each algorithm on as many times as possible on random arrays
and report how many arrays were sorted within the time period.
|
Python
|
mit
|
timpel/stanford-algs,timpel/stanford-algs
|
python
|
## Code Before:
import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint
def main(max_len):
for n in [2**(n+1) for n in range(max_len)]:
print 'Array size: %d' % n
arr = [randint(0, 2**max_len) for n in range(n)]
current_time = time.time()
quicksort.quicksort.check(mergesort.merge_sort.sort(arr))
print 'Merge sort: %f' % (time.time() - current_time)
current_time = time.time()
quicksort.quicksort.check(quicksort.quicksort.sort(arr, 0, len(arr)))
print 'Quicksort: %f' % (time.time() - current_time)
print '-----------------'
if __name__ == '__main__':
try:
max_len = int(sys.argv[1])
except (IndexError, ValueError):
print 'Format: python sorting_test.py <log(max input)>'
main(max_len)
## Instruction:
Allow comparison within a fixed time period
To get an idea of average run-time, I wanted to be able to test
mergesort and quicksort with the same inputs many times over;
now by specifying a time limit and array length, the script will
run each algorithm on as many times as possible on random arrays
and report how many arrays were sorted within the time period.
## Code After:
import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint
def multi_size(max_len):
for n in [2**(n+1) for n in range(max_len)]:
print 'Array size: %d' % n
arr = [randint(0, 2**max_len) for n in range(n)]
current_time = time.time()
quicksort.quicksort.check(mergesort.merge_sort.sort(arr), n+1)
print 'Merge sort: %f' % (time.time() - current_time)
current_time = time.time()
quicksort.quicksort.check(quicksort.quicksort.sort(arr, 0, n+1), n+1)
print 'Quicksort: %f' % (time.time() - current_time)
print '-----------------'
def fixed_time(sec, length):
count = 0
start = time.time()
end = start + sec
while time.time() < end:
arr = [randint(0, length) for n in range(length)]
mergesort.merge_sort.sort(arr)
count += 1
print 'Merge sort: %d %d-element arrays in %d seconds' % (count, length, sec)
count = 0
start = time.time()
end = start + sec
while time.time() < end:
arr = [randint(0, length) for n in range(length)]
quicksort.quicksort.sort(arr, 0, length)
count += 1
print 'Quicksort: %d %d-element arrays in %d seconds' % (count, length, sec)
if __name__ == '__main__':
if len(sys.argv) > 2:
fixed_time(int(sys.argv[1]), int(sys.argv[2]))
else:
multi_size(int(sys.argv[1]))
|
// ... existing code ...
import time
from random import randint
def multi_size(max_len):
for n in [2**(n+1) for n in range(max_len)]:
print 'Array size: %d' % n
// ... modified code ...
arr = [randint(0, 2**max_len) for n in range(n)]
current_time = time.time()
quicksort.quicksort.check(mergesort.merge_sort.sort(arr), n+1)
print 'Merge sort: %f' % (time.time() - current_time)
current_time = time.time()
quicksort.quicksort.check(quicksort.quicksort.sort(arr, 0, n+1), n+1)
print 'Quicksort: %f' % (time.time() - current_time)
print '-----------------'
def fixed_time(sec, length):
count = 0
start = time.time()
end = start + sec
while time.time() < end:
arr = [randint(0, length) for n in range(length)]
mergesort.merge_sort.sort(arr)
count += 1
print 'Merge sort: %d %d-element arrays in %d seconds' % (count, length, sec)
count = 0
start = time.time()
end = start + sec
while time.time() < end:
arr = [randint(0, length) for n in range(length)]
quicksort.quicksort.sort(arr, 0, length)
count += 1
print 'Quicksort: %d %d-element arrays in %d seconds' % (count, length, sec)
if __name__ == '__main__':
if len(sys.argv) > 2:
fixed_time(int(sys.argv[1]), int(sys.argv[2]))
else:
multi_size(int(sys.argv[1]))
// ... rest of the code ...
|
51185cff2c75da068f2f250a61e99472880f11d6
|
app/duckbot.py
|
app/duckbot.py
|
import argparse
import discord
from discord.ext import commands
import config
from cmd import general, emotes
_DESCRIPTION = '''quack'''
def parse_arguments():
parser = argparse.ArgumentParser(description="quack")
parser.add_argument('-b', '--botname',
required=True,
choices=config.bots.keys(),
help="Name of bot in config file")
return parser.parse_args()
args = parse_arguments()
bot_info = config.bots[args.botname]
CLIENT_ID = bot_info['client_id']
TOKEN = bot_info['token']
bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
# Register commands to bot
general.register(bot)
emotes.register(bot)
@bot.event
async def on_ready():
print('logged in: %s (%s)' % (bot.user.name, bot.user.id))
oauth_url = discord.utils.oauth_url(
CLIENT_ID, permissions=discord.Permissions.text())
print('invite me: %s' % oauth_url)
bot.run(TOKEN)
|
import argparse
import discord
from discord.ext import commands
import config
from cmd import general, emotes
_DESCRIPTION = '''quack'''
def parse_arguments():
parser = argparse.ArgumentParser(description="quack")
parser.add_argument('-b', '--botname',
required=True,
choices=config.bots.keys(),
help="Name of bot in config file")
return parser.parse_args()
def main():
args = parse_arguments()
bot_info = config.bots[args.botname]
client_id = bot_info['client_id']
token = bot_info['token']
bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
# Register commands to bot
general.register(bot)
emotes.register(bot)
@bot.event
async def on_ready():
print('logged in: %s (%s)' % (bot.user.name, bot.user.id))
oauth_url = discord.utils.oauth_url(
client_id, permissions=discord.Permissions.text())
print('invite me: %s' % oauth_url)
bot.run(token)
if __name__ == '__main__':
main()
|
Put main bot setup code inside main function
|
Put main bot setup code inside main function
|
Python
|
mit
|
andrewlin16/duckbot,andrewlin16/duckbot
|
python
|
## Code Before:
import argparse
import discord
from discord.ext import commands
import config
from cmd import general, emotes
_DESCRIPTION = '''quack'''
def parse_arguments():
parser = argparse.ArgumentParser(description="quack")
parser.add_argument('-b', '--botname',
required=True,
choices=config.bots.keys(),
help="Name of bot in config file")
return parser.parse_args()
args = parse_arguments()
bot_info = config.bots[args.botname]
CLIENT_ID = bot_info['client_id']
TOKEN = bot_info['token']
bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
# Register commands to bot
general.register(bot)
emotes.register(bot)
@bot.event
async def on_ready():
print('logged in: %s (%s)' % (bot.user.name, bot.user.id))
oauth_url = discord.utils.oauth_url(
CLIENT_ID, permissions=discord.Permissions.text())
print('invite me: %s' % oauth_url)
bot.run(TOKEN)
## Instruction:
Put main bot setup code inside main function
## Code After:
import argparse
import discord
from discord.ext import commands
import config
from cmd import general, emotes
_DESCRIPTION = '''quack'''
def parse_arguments():
parser = argparse.ArgumentParser(description="quack")
parser.add_argument('-b', '--botname',
required=True,
choices=config.bots.keys(),
help="Name of bot in config file")
return parser.parse_args()
def main():
args = parse_arguments()
bot_info = config.bots[args.botname]
client_id = bot_info['client_id']
token = bot_info['token']
bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
# Register commands to bot
general.register(bot)
emotes.register(bot)
@bot.event
async def on_ready():
print('logged in: %s (%s)' % (bot.user.name, bot.user.id))
oauth_url = discord.utils.oauth_url(
client_id, permissions=discord.Permissions.text())
print('invite me: %s' % oauth_url)
bot.run(token)
if __name__ == '__main__':
main()
|
# ... existing code ...
return parser.parse_args()
def main():
args = parse_arguments()
bot_info = config.bots[args.botname]
client_id = bot_info['client_id']
token = bot_info['token']
bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
# Register commands to bot
general.register(bot)
emotes.register(bot)
@bot.event
async def on_ready():
print('logged in: %s (%s)' % (bot.user.name, bot.user.id))
oauth_url = discord.utils.oauth_url(
client_id, permissions=discord.Permissions.text())
print('invite me: %s' % oauth_url)
bot.run(token)
if __name__ == '__main__':
main()
# ... rest of the code ...
|
b1a15ffe1c5f916076ac107735baf76e1da23bea
|
aiopg/__init__.py
|
aiopg/__init__.py
|
import re
import sys
from collections import namedtuple
from .connection import connect, Connection
from .cursor import Cursor
from .pool import create_pool, Pool
__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool')
__version__ = '0.3.0'
version = __version__ + ' , Python ' + sys.version
VersionInfo = namedtuple('VersionInfo',
'major minor micro releaselevel serial')
def _parse_version(ver):
RE = (r'^(?P<major>\d+)\.(?P<minor>\d+)\.'
'(?P<micro>\d+)((?P<releaselevel>[a-z]+)(?P<serial>\d+)?)?$')
match = re.match(RE, ver)
try:
major = int(match.group('major'))
minor = int(match.group('minor'))
micro = int(match.group('micro'))
levels = {'rc': 'candidate',
'a': 'alpha',
'b': 'beta',
None: 'final'}
releaselevel = levels[match.group('releaselevel')]
serial = int(match.group('serial')) if match.group('serial') else 0
return VersionInfo(major, minor, micro, releaselevel, serial)
except Exception:
raise ImportError("Invalid package version {}".format(ver))
version_info = _parse_version(__version__)
# make pyflakes happy
(connect, create_pool, Connection, Cursor, Pool)
|
import re
import sys
from collections import namedtuple
from .connection import connect, Connection
from .cursor import Cursor
from .pool import create_pool, Pool
__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool',
'version', 'version_info')
__version__ = '0.3.0'
version = __version__ + ' , Python ' + sys.version
VersionInfo = namedtuple('VersionInfo',
'major minor micro releaselevel serial')
def _parse_version(ver):
RE = (r'^(?P<major>\d+)\.(?P<minor>\d+)\.'
'(?P<micro>\d+)((?P<releaselevel>[a-z]+)(?P<serial>\d+)?)?$')
match = re.match(RE, ver)
try:
major = int(match.group('major'))
minor = int(match.group('minor'))
micro = int(match.group('micro'))
levels = {'rc': 'candidate',
'a': 'alpha',
'b': 'beta',
None: 'final'}
releaselevel = levels[match.group('releaselevel')]
serial = int(match.group('serial')) if match.group('serial') else 0
return VersionInfo(major, minor, micro, releaselevel, serial)
except Exception:
raise ImportError("Invalid package version {}".format(ver))
version_info = _parse_version(__version__)
# make pyflakes happy
(connect, create_pool, Connection, Cursor, Pool)
|
Add version and version_info to exported public API
|
Add version and version_info to exported public API
|
Python
|
bsd-2-clause
|
eirnym/aiopg,nerandell/aiopg,hyzhak/aiopg,aio-libs/aiopg,luhn/aiopg,graingert/aiopg
|
python
|
## Code Before:
import re
import sys
from collections import namedtuple
from .connection import connect, Connection
from .cursor import Cursor
from .pool import create_pool, Pool
__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool')
__version__ = '0.3.0'
version = __version__ + ' , Python ' + sys.version
VersionInfo = namedtuple('VersionInfo',
'major minor micro releaselevel serial')
def _parse_version(ver):
RE = (r'^(?P<major>\d+)\.(?P<minor>\d+)\.'
'(?P<micro>\d+)((?P<releaselevel>[a-z]+)(?P<serial>\d+)?)?$')
match = re.match(RE, ver)
try:
major = int(match.group('major'))
minor = int(match.group('minor'))
micro = int(match.group('micro'))
levels = {'rc': 'candidate',
'a': 'alpha',
'b': 'beta',
None: 'final'}
releaselevel = levels[match.group('releaselevel')]
serial = int(match.group('serial')) if match.group('serial') else 0
return VersionInfo(major, minor, micro, releaselevel, serial)
except Exception:
raise ImportError("Invalid package version {}".format(ver))
version_info = _parse_version(__version__)
# make pyflakes happy
(connect, create_pool, Connection, Cursor, Pool)
## Instruction:
Add version and version_info to exported public API
## Code After:
import re
import sys
from collections import namedtuple
from .connection import connect, Connection
from .cursor import Cursor
from .pool import create_pool, Pool
__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool',
'version', 'version_info')
__version__ = '0.3.0'
version = __version__ + ' , Python ' + sys.version
VersionInfo = namedtuple('VersionInfo',
'major minor micro releaselevel serial')
def _parse_version(ver):
RE = (r'^(?P<major>\d+)\.(?P<minor>\d+)\.'
'(?P<micro>\d+)((?P<releaselevel>[a-z]+)(?P<serial>\d+)?)?$')
match = re.match(RE, ver)
try:
major = int(match.group('major'))
minor = int(match.group('minor'))
micro = int(match.group('micro'))
levels = {'rc': 'candidate',
'a': 'alpha',
'b': 'beta',
None: 'final'}
releaselevel = levels[match.group('releaselevel')]
serial = int(match.group('serial')) if match.group('serial') else 0
return VersionInfo(major, minor, micro, releaselevel, serial)
except Exception:
raise ImportError("Invalid package version {}".format(ver))
version_info = _parse_version(__version__)
# make pyflakes happy
(connect, create_pool, Connection, Cursor, Pool)
|
...
from .pool import create_pool, Pool
__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool',
'version', 'version_info')
__version__ = '0.3.0'
...
|
8982d3f5ea40b688ec7e1da18403d89ab2994a95
|
comics/comics/yamac.py
|
comics/comics/yamac.py
|
from comics.aggregator.crawler import CrawlerBase
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "you and me and cats"
language = "en"
url = "http://strawberry-pie.net/SA/"
start_date = "2009-07-01"
rights = "bubble"
active = False
class Crawler(CrawlerBase):
history_capable_days = 365
time_zone = "US/Pacific"
def crawl(self, pub_date):
pass
|
from comics.aggregator.crawler import CrawlerBase
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "you and me and cats"
language = "en"
url = "http://strawberry-pie.net/SA/"
start_date = "2009-07-01"
rights = "bubble"
active = False
class Crawler(CrawlerBase):
time_zone = "US/Pacific"
def crawl(self, pub_date):
pass
|
Remove history capable date for "you and me and cats"
|
Remove history capable date for "you and me and cats"
|
Python
|
agpl-3.0
|
jodal/comics,jodal/comics,datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics
|
python
|
## Code Before:
from comics.aggregator.crawler import CrawlerBase
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "you and me and cats"
language = "en"
url = "http://strawberry-pie.net/SA/"
start_date = "2009-07-01"
rights = "bubble"
active = False
class Crawler(CrawlerBase):
history_capable_days = 365
time_zone = "US/Pacific"
def crawl(self, pub_date):
pass
## Instruction:
Remove history capable date for "you and me and cats"
## Code After:
from comics.aggregator.crawler import CrawlerBase
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "you and me and cats"
language = "en"
url = "http://strawberry-pie.net/SA/"
start_date = "2009-07-01"
rights = "bubble"
active = False
class Crawler(CrawlerBase):
time_zone = "US/Pacific"
def crawl(self, pub_date):
pass
|
...
class Crawler(CrawlerBase):
time_zone = "US/Pacific"
def crawl(self, pub_date):
...
|
c547677d56e7243fe3ed603c62d54679c7116fd4
|
src/main/java/com/gruppe27/fellesprosjekt/server/CalendarServer.java
|
src/main/java/com/gruppe27/fellesprosjekt/server/CalendarServer.java
|
package com.gruppe27.fellesprosjekt.server;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Server;
import com.gruppe27.fellesprosjekt.common.Network;
import java.io.IOException;
public class CalendarServer {
Server server;
DatabaseConnector connector;
public CalendarServer() {
server = new Server() {
protected Connection newConnection() {
return new CalendarConnection();
}
};
Network.register(server);
server.addListener(new CalendarListener(server));
try {
server.bind(Network.PORT);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
server.start();
}
public static void main(String[] args) {
CalendarServer server = new CalendarServer();
}
}
|
package com.gruppe27.fellesprosjekt.server;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Server;
import com.gruppe27.fellesprosjekt.common.Network;
import java.io.IOException;
public class CalendarServer {
private static Server server = null;
DatabaseConnector connector;
protected CalendarServer() {
}
public static Server getServer() {
if (server == null) {
server = new Server() {
protected Connection newConnection() {
return new CalendarConnection();
}
};
Network.register(server);
server.addListener(new CalendarListener(server));
try {
server.bind(Network.PORT);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
server.start();
}
return server;
}
public static void main(String[] args) {
CalendarServer.getServer();
}
}
|
Make the calendar server a singleton
|
Make the calendar server a singleton
|
Java
|
mit
|
Fellesprosjekt-27/fellesprosjekt
|
java
|
## Code Before:
package com.gruppe27.fellesprosjekt.server;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Server;
import com.gruppe27.fellesprosjekt.common.Network;
import java.io.IOException;
public class CalendarServer {
Server server;
DatabaseConnector connector;
public CalendarServer() {
server = new Server() {
protected Connection newConnection() {
return new CalendarConnection();
}
};
Network.register(server);
server.addListener(new CalendarListener(server));
try {
server.bind(Network.PORT);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
server.start();
}
public static void main(String[] args) {
CalendarServer server = new CalendarServer();
}
}
## Instruction:
Make the calendar server a singleton
## Code After:
package com.gruppe27.fellesprosjekt.server;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Server;
import com.gruppe27.fellesprosjekt.common.Network;
import java.io.IOException;
public class CalendarServer {
private static Server server = null;
DatabaseConnector connector;
protected CalendarServer() {
}
public static Server getServer() {
if (server == null) {
server = new Server() {
protected Connection newConnection() {
return new CalendarConnection();
}
};
Network.register(server);
server.addListener(new CalendarListener(server));
try {
server.bind(Network.PORT);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
server.start();
}
return server;
}
public static void main(String[] args) {
CalendarServer.getServer();
}
}
|
# ... existing code ...
public class CalendarServer {
private static Server server = null;
DatabaseConnector connector;
protected CalendarServer() {
}
public static Server getServer() {
if (server == null) {
server = new Server() {
protected Connection newConnection() {
return new CalendarConnection();
}
};
Network.register(server);
server.addListener(new CalendarListener(server));
try {
server.bind(Network.PORT);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
server.start();
}
return server;
}
public static void main(String[] args) {
CalendarServer.getServer();
}
}
# ... rest of the code ...
|
88f1ce548a1e06c1d40dea57346dcd654f718fb7
|
test/Profile/c-linkage-available_externally.c
|
test/Profile/c-linkage-available_externally.c
|
// Make sure instrumentation data from available_externally functions doesn't
// get thrown out and are emitted with the expected linkage.
// RUN: %clang_cc1 -O2 -triple x86_64-apple-macosx10.9 -main-file-name c-linkage-available_externally.c %s -o - -emit-llvm -fprofile-instrument=clang | FileCheck %s
// CHECK: @__profc_foo = linkonce_odr hidden global [1 x i64] zeroinitializer, section "__DATA,__llvm_prf_cnts", align 8
// CHECK: @__profd_foo = linkonce_odr hidden global {{.*}} i64* getelementptr inbounds ([1 x i64], [1 x i64]* @__profc_foo, i32 0, i32 0){{.*}}, section "__DATA,__llvm_prf_data", align 8
inline int foo(void) { return 1; }
int main(void) {
return foo();
}
|
// Make sure instrumentation data from available_externally functions doesn't
// get thrown out and are emitted with the expected linkage.
// RUN: %clang_cc1 -O2 -triple x86_64-apple-macosx10.9 -main-file-name c-linkage-available_externally.c %s -o - -emit-llvm -fprofile-instrument=clang | FileCheck %s
// CHECK: @__profc_foo = linkonce_odr hidden global [1 x i64] zeroinitializer, section "__DATA,__llvm_prf_cnts", align 8
// CHECK: @__profd_foo = linkonce_odr hidden global {{.*}} i64* getelementptr inbounds ([1 x i64], [1 x i64]* @__profc_foo, i32 0, i32 0){{.*}}, section "__DATA,__llvm_prf_data,regular,live_support", align 8
inline int foo(void) { return 1; }
int main(void) {
return foo();
}
|
Update testcase for r283948 (NFC)
|
[Profile] Update testcase for r283948 (NFC)
Old: "__DATA,__llvm_prf_data"
New: "__DATA,__llvm_prf_data,regular,live_support"
This should fix the following bot failure:
http://bb.pgr.jp/builders/cmake-clang-x86_64-linux/builds/55158
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@283949 91177308-0d34-0410-b5e6-96231b3b80d8
|
C
|
apache-2.0
|
llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang
|
c
|
## Code Before:
// Make sure instrumentation data from available_externally functions doesn't
// get thrown out and are emitted with the expected linkage.
// RUN: %clang_cc1 -O2 -triple x86_64-apple-macosx10.9 -main-file-name c-linkage-available_externally.c %s -o - -emit-llvm -fprofile-instrument=clang | FileCheck %s
// CHECK: @__profc_foo = linkonce_odr hidden global [1 x i64] zeroinitializer, section "__DATA,__llvm_prf_cnts", align 8
// CHECK: @__profd_foo = linkonce_odr hidden global {{.*}} i64* getelementptr inbounds ([1 x i64], [1 x i64]* @__profc_foo, i32 0, i32 0){{.*}}, section "__DATA,__llvm_prf_data", align 8
inline int foo(void) { return 1; }
int main(void) {
return foo();
}
## Instruction:
[Profile] Update testcase for r283948 (NFC)
Old: "__DATA,__llvm_prf_data"
New: "__DATA,__llvm_prf_data,regular,live_support"
This should fix the following bot failure:
http://bb.pgr.jp/builders/cmake-clang-x86_64-linux/builds/55158
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@283949 91177308-0d34-0410-b5e6-96231b3b80d8
## Code After:
// Make sure instrumentation data from available_externally functions doesn't
// get thrown out and are emitted with the expected linkage.
// RUN: %clang_cc1 -O2 -triple x86_64-apple-macosx10.9 -main-file-name c-linkage-available_externally.c %s -o - -emit-llvm -fprofile-instrument=clang | FileCheck %s
// CHECK: @__profc_foo = linkonce_odr hidden global [1 x i64] zeroinitializer, section "__DATA,__llvm_prf_cnts", align 8
// CHECK: @__profd_foo = linkonce_odr hidden global {{.*}} i64* getelementptr inbounds ([1 x i64], [1 x i64]* @__profc_foo, i32 0, i32 0){{.*}}, section "__DATA,__llvm_prf_data,regular,live_support", align 8
inline int foo(void) { return 1; }
int main(void) {
return foo();
}
|
// ... existing code ...
// RUN: %clang_cc1 -O2 -triple x86_64-apple-macosx10.9 -main-file-name c-linkage-available_externally.c %s -o - -emit-llvm -fprofile-instrument=clang | FileCheck %s
// CHECK: @__profc_foo = linkonce_odr hidden global [1 x i64] zeroinitializer, section "__DATA,__llvm_prf_cnts", align 8
// CHECK: @__profd_foo = linkonce_odr hidden global {{.*}} i64* getelementptr inbounds ([1 x i64], [1 x i64]* @__profc_foo, i32 0, i32 0){{.*}}, section "__DATA,__llvm_prf_data,regular,live_support", align 8
inline int foo(void) { return 1; }
int main(void) {
// ... rest of the code ...
|
b3db48274c0cda90bc003376083a620a98fec35c
|
src/main/java/at/ac/tuwien/inso/controller/student/StudentRegisterForCourseController.java
|
src/main/java/at/ac/tuwien/inso/controller/student/StudentRegisterForCourseController.java
|
package at.ac.tuwien.inso.controller.student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.service.CourseService;
import at.ac.tuwien.inso.service.StudentService;
@Controller
@RequestMapping("/student/register")
public class StudentRegisterForCourseController {
@Autowired
private CourseService courseService;
@GetMapping
private String registerStudent(@RequestParam Long courseId,
RedirectAttributes redirectAttributes) {
Course course = courseService.findCourseWithId(courseId);
if (courseService.registerStudentForCourse(course)) {
redirectAttributes.addFlashAttribute("registeredForCourse", course.getSubject().getName());
return "redirect:/student/courses";
} else {
redirectAttributes.addFlashAttribute("notRegisteredForCourse", course.getSubject().getName());
return "redirect:/student/courses";
}
}
}
|
package at.ac.tuwien.inso.controller.student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.service.CourseService;
@Controller
@RequestMapping("/student/register")
public class StudentRegisterForCourseController {
@Autowired
private CourseService courseService;
@GetMapping
private String registerStudent(@RequestParam Long courseId,
RedirectAttributes redirectAttributes) {
Course course = courseService.findCourseWithId(courseId);
if (courseService.registerStudentForCourse(course)) {
redirectAttributes.addFlashAttribute("registeredForCourse", course.getSubject().getName());
return "redirect:/student/courses";
} else {
redirectAttributes.addFlashAttribute("notRegisteredForCourse", course.getSubject().getName());
return "redirect:/student/courses";
}
}
}
|
Refactor - remove unused imports
|
Refactor - remove unused imports
|
Java
|
mit
|
university-information-system/uis,university-information-system/uis,university-information-system/uis,university-information-system/uis
|
java
|
## Code Before:
package at.ac.tuwien.inso.controller.student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.service.CourseService;
import at.ac.tuwien.inso.service.StudentService;
@Controller
@RequestMapping("/student/register")
public class StudentRegisterForCourseController {
@Autowired
private CourseService courseService;
@GetMapping
private String registerStudent(@RequestParam Long courseId,
RedirectAttributes redirectAttributes) {
Course course = courseService.findCourseWithId(courseId);
if (courseService.registerStudentForCourse(course)) {
redirectAttributes.addFlashAttribute("registeredForCourse", course.getSubject().getName());
return "redirect:/student/courses";
} else {
redirectAttributes.addFlashAttribute("notRegisteredForCourse", course.getSubject().getName());
return "redirect:/student/courses";
}
}
}
## Instruction:
Refactor - remove unused imports
## Code After:
package at.ac.tuwien.inso.controller.student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.service.CourseService;
@Controller
@RequestMapping("/student/register")
public class StudentRegisterForCourseController {
@Autowired
private CourseService courseService;
@GetMapping
private String registerStudent(@RequestParam Long courseId,
RedirectAttributes redirectAttributes) {
Course course = courseService.findCourseWithId(courseId);
if (courseService.registerStudentForCourse(course)) {
redirectAttributes.addFlashAttribute("registeredForCourse", course.getSubject().getName());
return "redirect:/student/courses";
} else {
redirectAttributes.addFlashAttribute("notRegisteredForCourse", course.getSubject().getName());
return "redirect:/student/courses";
}
}
}
|
...
import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.service.CourseService;
@Controller
@RequestMapping("/student/register")
...
|
8ba05402376dc2d368bae226f929b9a0b448a3c5
|
localized_fields/admin.py
|
localized_fields/admin.py
|
from django.contrib.admin import ModelAdmin
from . import widgets
from .fields import LocalizedField, LocalizedCharField, LocalizedTextField, \
LocalizedFileField
FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS = {
LocalizedField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedCharField: {'widget': widgets.AdminLocalizedCharFieldWidget},
LocalizedTextField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedFileField: {'widget': widgets.AdminLocalizedFileFieldWidget},
}
class LocalizedFieldsAdminMixin(ModelAdmin):
"""Mixin for making the fancy widgets work in Django Admin."""
class Media:
css = {
'all': (
'localized_fields/localized-fields-admin.css',
)
}
js = (
'localized_fields/localized-fields-admin.js',
)
def __init__(self, *args, **kwargs):
"""Initializes a new instance of :see:LocalizedFieldsAdminMixin."""
super().__init__(*args, **kwargs)
overrides = FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS.copy()
overrides.update(self.formfield_overrides)
self.formfield_overrides = overrides
|
from . import widgets
from .fields import LocalizedField, LocalizedCharField, LocalizedTextField, \
LocalizedFileField
FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS = {
LocalizedField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedCharField: {'widget': widgets.AdminLocalizedCharFieldWidget},
LocalizedTextField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedFileField: {'widget': widgets.AdminLocalizedFileFieldWidget},
}
class LocalizedFieldsAdminMixin:
"""Mixin for making the fancy widgets work in Django Admin."""
class Media:
css = {
'all': (
'localized_fields/localized-fields-admin.css',
)
}
js = (
'localized_fields/localized-fields-admin.js',
)
def __init__(self, *args, **kwargs):
"""Initializes a new instance of :see:LocalizedFieldsAdminMixin."""
super().__init__(*args, **kwargs)
overrides = FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS.copy()
overrides.update(self.formfield_overrides)
self.formfield_overrides = overrides
|
Fix using LocalizedFieldsAdminMixin with inlines
|
Fix using LocalizedFieldsAdminMixin with inlines
|
Python
|
mit
|
SectorLabs/django-localized-fields,SectorLabs/django-localized-fields,SectorLabs/django-localized-fields
|
python
|
## Code Before:
from django.contrib.admin import ModelAdmin
from . import widgets
from .fields import LocalizedField, LocalizedCharField, LocalizedTextField, \
LocalizedFileField
FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS = {
LocalizedField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedCharField: {'widget': widgets.AdminLocalizedCharFieldWidget},
LocalizedTextField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedFileField: {'widget': widgets.AdminLocalizedFileFieldWidget},
}
class LocalizedFieldsAdminMixin(ModelAdmin):
"""Mixin for making the fancy widgets work in Django Admin."""
class Media:
css = {
'all': (
'localized_fields/localized-fields-admin.css',
)
}
js = (
'localized_fields/localized-fields-admin.js',
)
def __init__(self, *args, **kwargs):
"""Initializes a new instance of :see:LocalizedFieldsAdminMixin."""
super().__init__(*args, **kwargs)
overrides = FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS.copy()
overrides.update(self.formfield_overrides)
self.formfield_overrides = overrides
## Instruction:
Fix using LocalizedFieldsAdminMixin with inlines
## Code After:
from . import widgets
from .fields import LocalizedField, LocalizedCharField, LocalizedTextField, \
LocalizedFileField
FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS = {
LocalizedField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedCharField: {'widget': widgets.AdminLocalizedCharFieldWidget},
LocalizedTextField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedFileField: {'widget': widgets.AdminLocalizedFileFieldWidget},
}
class LocalizedFieldsAdminMixin:
"""Mixin for making the fancy widgets work in Django Admin."""
class Media:
css = {
'all': (
'localized_fields/localized-fields-admin.css',
)
}
js = (
'localized_fields/localized-fields-admin.js',
)
def __init__(self, *args, **kwargs):
"""Initializes a new instance of :see:LocalizedFieldsAdminMixin."""
super().__init__(*args, **kwargs)
overrides = FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS.copy()
overrides.update(self.formfield_overrides)
self.formfield_overrides = overrides
|
# ... existing code ...
from . import widgets
from .fields import LocalizedField, LocalizedCharField, LocalizedTextField, \
LocalizedFileField
# ... modified code ...
}
class LocalizedFieldsAdminMixin:
"""Mixin for making the fancy widgets work in Django Admin."""
class Media:
# ... rest of the code ...
|
595c211b7e9e60b34564a9fe0239ea4d88bf9546
|
include/WOCStdLib/winnt.h
|
include/WOCStdLib/winnt.h
|
//******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//******************************************************************************
#pragma once
#include_next <winnt.h>
|
//******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//******************************************************************************
#pragma once
#ifdef _ARM_
// winnt.h includes some ARM intrinsics that aren't supported in
// clang and cause front end compilation breaks. Because of this,
// change the MSC version to be less than what is needed to
// support that option.
#pragma push_macro("_MSC_FULL_VER")
#if (_MSC_FULL_VER >= 170040825)
#undef _MSC_FULL_VER
#define _MSC_FULL_VER 170040824
#endif
#include_next <winnt.h>
#pragma pop_macro("_MSC_FULL_VER")
#else // Not _ARM_
#include_next <winnt.h>
#endif
|
Fix ARM build in CoreFoundation
|
Fix ARM build in CoreFoundation
Description:
winnt.h includes some ARM intrinsics that aren't supported in
clang and cause front end compilation breaks. Because of this,
change the MSC version to be less than what is needed to
support that option.
How verified:
Builds now
Reviewed by: jaredh, duhowett, jordansa
|
C
|
mit
|
pradipd/WinObjC,bbowman/WinObjC,bbowman/WinObjC,bbowman/WinObjC,bSr43/WinObjC,yweijiang/WinObjC,nathpete-msft/WinObjC,bSr43/WinObjC,bSr43/WinObjC,rajsesh-msft/WinObjC,ehren/WinObjC,Microsoft/WinObjC,MSFTFox/WinObjC,autodesk-forks/WinObjC,autodesk-forks/WinObjC,nathpete-msft/WinObjC,afaruqui/WinObjC,ehren/WinObjC,autodesk-forks/WinObjC,rajsesh-msft/WinObjC,vkvenkat/WinObjC,ehren/WinObjC,ehren/WinObjC,pradipd/WinObjC,pradipd/WinObjC,afaruqui/WinObjC,vkvenkat/WinObjC,yweijiang/WinObjC,Microsoft/WinObjC,MSFTFox/WinObjC,yweijiang/WinObjC,pradipd/WinObjC,ehren/WinObjC,afaruqui/WinObjC,nathpete-msft/WinObjC,autodesk-forks/WinObjC,MSFTFox/WinObjC,rajsesh-msft/WinObjC,Microsoft/WinObjC,vkvenkat/WinObjC,nathpete-msft/WinObjC,afaruqui/WinObjC,bSr43/WinObjC,bbowman/WinObjC,pradipd/WinObjC,vkvenkat/WinObjC,Microsoft/WinObjC,bbowman/WinObjC,yweijiang/WinObjC,rajsesh-msft/WinObjC,MSFTFox/WinObjC,nathpete-msft/WinObjC
|
c
|
## Code Before:
//******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//******************************************************************************
#pragma once
#include_next <winnt.h>
## Instruction:
Fix ARM build in CoreFoundation
Description:
winnt.h includes some ARM intrinsics that aren't supported in
clang and cause front end compilation breaks. Because of this,
change the MSC version to be less than what is needed to
support that option.
How verified:
Builds now
Reviewed by: jaredh, duhowett, jordansa
## Code After:
//******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//******************************************************************************
#pragma once
#ifdef _ARM_
// winnt.h includes some ARM intrinsics that aren't supported in
// clang and cause front end compilation breaks. Because of this,
// change the MSC version to be less than what is needed to
// support that option.
#pragma push_macro("_MSC_FULL_VER")
#if (_MSC_FULL_VER >= 170040825)
#undef _MSC_FULL_VER
#define _MSC_FULL_VER 170040824
#endif
#include_next <winnt.h>
#pragma pop_macro("_MSC_FULL_VER")
#else // Not _ARM_
#include_next <winnt.h>
#endif
|
...
//******************************************************************************
#pragma once
#ifdef _ARM_
// winnt.h includes some ARM intrinsics that aren't supported in
// clang and cause front end compilation breaks. Because of this,
// change the MSC version to be less than what is needed to
// support that option.
#pragma push_macro("_MSC_FULL_VER")
#if (_MSC_FULL_VER >= 170040825)
#undef _MSC_FULL_VER
#define _MSC_FULL_VER 170040824
#endif
#include_next <winnt.h>
#pragma pop_macro("_MSC_FULL_VER")
#else // Not _ARM_
#include_next <winnt.h>
#endif
...
|
8605544c0b0cbc5ad43d86a71402f3f4075b48e3
|
paddle/utils/Compiler.h
|
paddle/utils/Compiler.h
|
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
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. */
#pragma once
#ifdef __GNUC__
#define GCC_VERSION \
(__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#else
#define GCC_VERSION
#endif
#if GCC_VERSION >= 30400
#define __must_check __attribute__((warn_unused_result))
#else
#define __must_check
#endif
|
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
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. */
#pragma once
/**
* This header defines some useful attribute by each compiler. It is the
* abstract layer of compilers.
*/
#ifdef __GNUC__
#define GCC_VERSION \
(__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#else
#define GCC_VERSION
#endif
/**
* __must_check macro. It make the function's return value must be used,
* otherwise it will raise a compile warning. And also Paddle treat all compile
* warnings as errors.
*/
#if GCC_VERSION >= 30400
#define __must_check __attribute__((warn_unused_result))
#else
#define __must_check
#endif
|
Add some comments to compiler.h
|
Add some comments to compiler.h
|
C
|
apache-2.0
|
livc/Paddle,livc/Paddle,cxysteven/Paddle,wen-bo-yang/Paddle,lispc/Paddle,yu239/Paddle,yu239/Paddle,reyoung/Paddle,lispc/Paddle,luotao1/Paddle,pengli09/Paddle,hedaoyuan/Paddle,lispc/Paddle,yu239/Paddle,pengli09/Paddle,yu239/Paddle,pkuyym/Paddle,chengduoZH/Paddle,reyoung/Paddle,livc/Paddle,cxysteven/Paddle,Canpio/Paddle,putcn/Paddle,cxysteven/Paddle,lcy-seso/Paddle,pkuyym/Paddle,QiJune/Paddle,luotao1/Paddle,putcn/Paddle,chengduoZH/Paddle,hedaoyuan/Paddle,gangliao/Paddle,emailweixu/Paddle,gangliao/Paddle,emailweixu/Paddle,putcn/Paddle,pengli09/Paddle,lcy-seso/Paddle,chengduoZH/Paddle,PaddlePaddle/Paddle,QiJune/Paddle,reyoung/Paddle,tensor-tang/Paddle,reyoung/Paddle,emailweixu/Paddle,baidu/Paddle,lispc/Paddle,PaddlePaddle/Paddle,wen-bo-yang/Paddle,wen-bo-yang/Paddle,Canpio/Paddle,jacquesqiao/Paddle,pengli09/Paddle,livc/Paddle,lispc/Paddle,lcy-seso/Paddle,putcn/Paddle,cxysteven/Paddle,luotao1/Paddle,yu239/Paddle,luotao1/Paddle,gangliao/Paddle,luotao1/Paddle,luotao1/Paddle,reyoung/Paddle,lispc/Paddle,PaddlePaddle/Paddle,cxysteven/Paddle,tensor-tang/Paddle,pengli09/Paddle,wen-bo-yang/Paddle,emailweixu/Paddle,cxysteven/Paddle,lcy-seso/Paddle,pkuyym/Paddle,hedaoyuan/Paddle,QiJune/Paddle,cxysteven/Paddle,tensor-tang/Paddle,putcn/Paddle,Canpio/Paddle,lcy-seso/Paddle,wen-bo-yang/Paddle,tensor-tang/Paddle,jacquesqiao/Paddle,PaddlePaddle/Paddle,hedaoyuan/Paddle,emailweixu/Paddle,livc/Paddle,PaddlePaddle/Paddle,yu239/Paddle,baidu/Paddle,QiJune/Paddle,tensor-tang/Paddle,pengli09/Paddle,gangliao/Paddle,gangliao/Paddle,pkuyym/Paddle,pkuyym/Paddle,jacquesqiao/Paddle,Canpio/Paddle,lcy-seso/Paddle,pkuyym/Paddle,hedaoyuan/Paddle,reyoung/Paddle,lispc/Paddle,emailweixu/Paddle,gangliao/Paddle,jacquesqiao/Paddle,PaddlePaddle/Paddle,pengli09/Paddle,gangliao/Paddle,Canpio/Paddle,jacquesqiao/Paddle,Canpio/Paddle,yu239/Paddle,QiJune/Paddle,chengduoZH/Paddle,PaddlePaddle/Paddle,yu239/Paddle,jacquesqiao/Paddle,Canpio/Paddle,baidu/Paddle,wen-bo-yang/Paddle,chengduoZH/Paddle,putcn/Paddle,livc/Paddle,baidu/Paddle,lispc/Paddle,baidu/Paddle,QiJune/Paddle,wen-bo-yang/Paddle,emailweixu/Paddle,hedaoyuan/Paddle,Canpio/Paddle,pengli09/Paddle,hedaoyuan/Paddle,livc/Paddle,hedaoyuan/Paddle,luotao1/Paddle
|
c
|
## Code Before:
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
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. */
#pragma once
#ifdef __GNUC__
#define GCC_VERSION \
(__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#else
#define GCC_VERSION
#endif
#if GCC_VERSION >= 30400
#define __must_check __attribute__((warn_unused_result))
#else
#define __must_check
#endif
## Instruction:
Add some comments to compiler.h
## Code After:
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
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. */
#pragma once
/**
* This header defines some useful attribute by each compiler. It is the
* abstract layer of compilers.
*/
#ifdef __GNUC__
#define GCC_VERSION \
(__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#else
#define GCC_VERSION
#endif
/**
* __must_check macro. It make the function's return value must be used,
* otherwise it will raise a compile warning. And also Paddle treat all compile
* warnings as errors.
*/
#if GCC_VERSION >= 30400
#define __must_check __attribute__((warn_unused_result))
#else
#define __must_check
#endif
|
...
limitations under the License. */
#pragma once
/**
* This header defines some useful attribute by each compiler. It is the
* abstract layer of compilers.
*/
#ifdef __GNUC__
#define GCC_VERSION \
(__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
...
#define GCC_VERSION
#endif
/**
* __must_check macro. It make the function's return value must be used,
* otherwise it will raise a compile warning. And also Paddle treat all compile
* warnings as errors.
*/
#if GCC_VERSION >= 30400
#define __must_check __attribute__((warn_unused_result))
#else
...
|
ee87b5104e98575990936708ba776492b006fbe7
|
src/main/java/nl/hsac/fitnesse/fixture/slim/web/xebium/HsacXebiumBrowserTest.java
|
src/main/java/nl/hsac/fitnesse/fixture/slim/web/xebium/HsacXebiumBrowserTest.java
|
package nl.hsac.fitnesse.fixture.slim.web.xebium;
import nl.hsac.fitnesse.fixture.slim.SlimFixtureException;
import nl.hsac.fitnesse.fixture.slim.web.BrowserTest;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
/**
* BrowserTest with some extra methods to assist HsacSeleniumDriverFixture.
*/
public class HsacXebiumBrowserTest extends BrowserTest {
public HsacXebiumBrowserTest() {
waitMilliSecondAfterScroll(250);
}
public boolean clickByXPath(String xPath) {
WebElement element = findByXPath(xPath);
return clickElement(element);
}
public boolean waitForXPathVisible(final String xPath) {
By by = By.xpath(xPath);
return waitForVisible(by);
}
public boolean waitForVisible(final By by) {
return waitUntil(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
Boolean result = Boolean.FALSE;
WebElement element = getSeleniumHelper().findElement(by);
if (element != null) {
scrollIfNotOnScreen(element);
result = element.isDisplayed();
}
return result;
}
});
}
public SlimFixtureException asSlimFixtureException(Throwable t) {
return (SlimFixtureException) handleException(null, null, t);
}
}
|
package nl.hsac.fitnesse.fixture.slim.web.xebium;
import nl.hsac.fitnesse.fixture.slim.SlimFixtureException;
import nl.hsac.fitnesse.fixture.slim.web.BrowserTest;
import org.openqa.selenium.By;
/**
* BrowserTest with some extra methods to assist HsacSeleniumDriverFixture.
*/
public class HsacXebiumBrowserTest extends BrowserTest {
@Override
public boolean waitForVisible(final By by) {
return super.waitForVisible(by);
}
public SlimFixtureException asSlimFixtureException(Throwable t) {
return (SlimFixtureException) handleException(null, null, t);
}
}
|
Simplify class, using methods now available in its superclass.
|
Simplify class, using methods now available in its superclass.
|
Java
|
apache-2.0
|
fhoeben/hsac-xebium-bridge,fhoeben/hsac-xebium-bridge
|
java
|
## Code Before:
package nl.hsac.fitnesse.fixture.slim.web.xebium;
import nl.hsac.fitnesse.fixture.slim.SlimFixtureException;
import nl.hsac.fitnesse.fixture.slim.web.BrowserTest;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
/**
* BrowserTest with some extra methods to assist HsacSeleniumDriverFixture.
*/
public class HsacXebiumBrowserTest extends BrowserTest {
public HsacXebiumBrowserTest() {
waitMilliSecondAfterScroll(250);
}
public boolean clickByXPath(String xPath) {
WebElement element = findByXPath(xPath);
return clickElement(element);
}
public boolean waitForXPathVisible(final String xPath) {
By by = By.xpath(xPath);
return waitForVisible(by);
}
public boolean waitForVisible(final By by) {
return waitUntil(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
Boolean result = Boolean.FALSE;
WebElement element = getSeleniumHelper().findElement(by);
if (element != null) {
scrollIfNotOnScreen(element);
result = element.isDisplayed();
}
return result;
}
});
}
public SlimFixtureException asSlimFixtureException(Throwable t) {
return (SlimFixtureException) handleException(null, null, t);
}
}
## Instruction:
Simplify class, using methods now available in its superclass.
## Code After:
package nl.hsac.fitnesse.fixture.slim.web.xebium;
import nl.hsac.fitnesse.fixture.slim.SlimFixtureException;
import nl.hsac.fitnesse.fixture.slim.web.BrowserTest;
import org.openqa.selenium.By;
/**
* BrowserTest with some extra methods to assist HsacSeleniumDriverFixture.
*/
public class HsacXebiumBrowserTest extends BrowserTest {
@Override
public boolean waitForVisible(final By by) {
return super.waitForVisible(by);
}
public SlimFixtureException asSlimFixtureException(Throwable t) {
return (SlimFixtureException) handleException(null, null, t);
}
}
|
# ... existing code ...
import nl.hsac.fitnesse.fixture.slim.SlimFixtureException;
import nl.hsac.fitnesse.fixture.slim.web.BrowserTest;
import org.openqa.selenium.By;
/**
* BrowserTest with some extra methods to assist HsacSeleniumDriverFixture.
*/
public class HsacXebiumBrowserTest extends BrowserTest {
@Override
public boolean waitForVisible(final By by) {
return super.waitForVisible(by);
}
public SlimFixtureException asSlimFixtureException(Throwable t) {
# ... rest of the code ...
|
46511322dc8d738cc43561025bca3298946da2e6
|
server.py
|
server.py
|
from swiftdav.swiftdav import SwiftProvider, WsgiDAVDomainController
from waitress import serve
from wsgidav.wsgidav_app import DEFAULT_CONFIG, WsgiDAVApp
proxy = 'http://127.0.0.1:8080/auth/v1.0'
insecure = False # Set to True to disable SSL certificate validation
config = DEFAULT_CONFIG.copy()
config.update({
"provider_mapping": {"": SwiftProvider()},
"verbose": 1,
"propsmanager": True,
"locksmanager": True,
"acceptbasic": True,
"acceptdigest": False,
"defaultdigest": False,
"domaincontroller": WsgiDAVDomainController(proxy, insecure)
})
app = WsgiDAVApp(config)
serve(app, host="0.0.0.0", port=8000)
|
from swiftdav.swiftdav import SwiftProvider, WsgiDAVDomainController
from waitress import serve
from wsgidav.wsgidav_app import DEFAULT_CONFIG, WsgiDAVApp
proxy = 'http://127.0.0.1:8080/auth/v1.0'
insecure = False # Set to True to disable SSL certificate validation
config = DEFAULT_CONFIG.copy()
config.update({
"provider_mapping": {"": SwiftProvider()},
"verbose": 1,
"propsmanager": True,
"locksmanager": True,
"acceptbasic": True,
"acceptdigest": False,
"defaultdigest": False,
"domaincontroller": WsgiDAVDomainController(proxy, insecure)
})
app = WsgiDAVApp(config)
serve(app, host="0.0.0.0", port=8000, max_request_body_size=5*1024*1024*1024)
|
Increase waitress setting max_request_body_size to 5GiB
|
Increase waitress setting max_request_body_size to 5GiB
Python waitress limits the body size to 1GiB by default, thus
uploading of larger objects will fail if this value is not
increased.
Please note that this value should be increased if your Swift
cluster supports uploading of objects larger than 5GiB.
|
Python
|
apache-2.0
|
cschwede/swiftdav,cschwede/swiftdav
|
python
|
## Code Before:
from swiftdav.swiftdav import SwiftProvider, WsgiDAVDomainController
from waitress import serve
from wsgidav.wsgidav_app import DEFAULT_CONFIG, WsgiDAVApp
proxy = 'http://127.0.0.1:8080/auth/v1.0'
insecure = False # Set to True to disable SSL certificate validation
config = DEFAULT_CONFIG.copy()
config.update({
"provider_mapping": {"": SwiftProvider()},
"verbose": 1,
"propsmanager": True,
"locksmanager": True,
"acceptbasic": True,
"acceptdigest": False,
"defaultdigest": False,
"domaincontroller": WsgiDAVDomainController(proxy, insecure)
})
app = WsgiDAVApp(config)
serve(app, host="0.0.0.0", port=8000)
## Instruction:
Increase waitress setting max_request_body_size to 5GiB
Python waitress limits the body size to 1GiB by default, thus
uploading of larger objects will fail if this value is not
increased.
Please note that this value should be increased if your Swift
cluster supports uploading of objects larger than 5GiB.
## Code After:
from swiftdav.swiftdav import SwiftProvider, WsgiDAVDomainController
from waitress import serve
from wsgidav.wsgidav_app import DEFAULT_CONFIG, WsgiDAVApp
proxy = 'http://127.0.0.1:8080/auth/v1.0'
insecure = False # Set to True to disable SSL certificate validation
config = DEFAULT_CONFIG.copy()
config.update({
"provider_mapping": {"": SwiftProvider()},
"verbose": 1,
"propsmanager": True,
"locksmanager": True,
"acceptbasic": True,
"acceptdigest": False,
"defaultdigest": False,
"domaincontroller": WsgiDAVDomainController(proxy, insecure)
})
app = WsgiDAVApp(config)
serve(app, host="0.0.0.0", port=8000, max_request_body_size=5*1024*1024*1024)
|
// ... existing code ...
})
app = WsgiDAVApp(config)
serve(app, host="0.0.0.0", port=8000, max_request_body_size=5*1024*1024*1024)
// ... rest of the code ...
|
f188799a9a768d8a7ab9a2755fa00f2f80b1f551
|
models/src/main/java/com/vimeo/networking2/VimeoAccount.kt
|
models/src/main/java/com/vimeo/networking2/VimeoAccount.kt
|
package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import java.util.*
/**
* This class represents an authenticated account with Vimeo. It can be through client credentials
* or a truly authenticated [User].
*/
@JsonClass(generateAdapter = true)
data class VimeoAccount(
/**
* The access token string.
*/
@Json(name = "access_token")
val accessToken: String? = null,
/**
* The date and time that the token expires.
*/
@Json(name = "expires_on")
val expiresOn: Date? = null,
/**
* The refresh token string.
*/
@Json(name = "refresh_token")
val refreshToken: String? = null,
/**
* The scope or scopes that the token supports.
*/
@Json(name = "scope")
val scope: String? = null,
/**
* The token type.
*/
@Json(name = "token_type")
val tokenType: String? = null
)
|
package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import java.util.*
/**
* This class represents an authenticated account with Vimeo. It can be through client credentials
* or a truly authenticated [User].
*/
@JsonClass(generateAdapter = true)
data class VimeoAccount(
/**
* The access token string.
*/
@Json(name = "access_token")
val accessToken: String? = null,
/**
* The date and time that the token expires.
*/
@Json(name = "expires_on")
val expiresOn: Date? = null,
/**
* The refresh token string.
*/
@Json(name = "refresh_token")
val refreshToken: String? = null,
/**
* The scope or scopes that the token supports.
*/
@Json(name = "scope")
val scope: String? = null,
/**
* The authenticated user.
*/
@Json(name = "user")
val user: User? = null,
/**
* The token type.
*/
@Json(name = "token_type")
val tokenType: String? = null
)
|
Add user object to vimeo account
|
Add user object to vimeo account
|
Kotlin
|
mit
|
vimeo/vimeo-networking-java,vimeo/vimeo-networking-java,vimeo/vimeo-networking-java
|
kotlin
|
## Code Before:
package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import java.util.*
/**
* This class represents an authenticated account with Vimeo. It can be through client credentials
* or a truly authenticated [User].
*/
@JsonClass(generateAdapter = true)
data class VimeoAccount(
/**
* The access token string.
*/
@Json(name = "access_token")
val accessToken: String? = null,
/**
* The date and time that the token expires.
*/
@Json(name = "expires_on")
val expiresOn: Date? = null,
/**
* The refresh token string.
*/
@Json(name = "refresh_token")
val refreshToken: String? = null,
/**
* The scope or scopes that the token supports.
*/
@Json(name = "scope")
val scope: String? = null,
/**
* The token type.
*/
@Json(name = "token_type")
val tokenType: String? = null
)
## Instruction:
Add user object to vimeo account
## Code After:
package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import java.util.*
/**
* This class represents an authenticated account with Vimeo. It can be through client credentials
* or a truly authenticated [User].
*/
@JsonClass(generateAdapter = true)
data class VimeoAccount(
/**
* The access token string.
*/
@Json(name = "access_token")
val accessToken: String? = null,
/**
* The date and time that the token expires.
*/
@Json(name = "expires_on")
val expiresOn: Date? = null,
/**
* The refresh token string.
*/
@Json(name = "refresh_token")
val refreshToken: String? = null,
/**
* The scope or scopes that the token supports.
*/
@Json(name = "scope")
val scope: String? = null,
/**
* The authenticated user.
*/
@Json(name = "user")
val user: User? = null,
/**
* The token type.
*/
@Json(name = "token_type")
val tokenType: String? = null
)
|
# ... existing code ...
val scope: String? = null,
/**
* The authenticated user.
*/
@Json(name = "user")
val user: User? = null,
/**
* The token type.
*/
@Json(name = "token_type")
# ... rest of the code ...
|
eebb736bf83c572b797931c571e7416223436461
|
homeassistant/components/light/insteon.py
|
homeassistant/components/light/insteon.py
|
from homeassistant.components.insteon import (INSTEON, InsteonToggleDevice)
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the Insteon Hub light platform. """
devs = []
for device in INSTEON.devices:
if device.DeviceCategory == "Switched Lighting Control":
devs.append(InsteonToggleDevice(device))
add_devices(devs)
|
from homeassistant.components.insteon import (INSTEON, InsteonToggleDevice)
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the Insteon Hub light platform. """
devs = []
for device in INSTEON.devices:
if device.DeviceCategory == "Switched Lighting Control":
devs.append(InsteonToggleDevice(device))
if device.DeviceCategory == "Dimmable Lighting Control":
devs.append(InsteonToggleDevice(device))
add_devices(devs)
|
Add ability to control dimmable sources
|
Add ability to control dimmable sources
|
Python
|
mit
|
emilhetty/home-assistant,Duoxilian/home-assistant,rohitranjan1991/home-assistant,toddeye/home-assistant,ct-23/home-assistant,florianholzapfel/home-assistant,kennedyshead/home-assistant,keerts/home-assistant,lukas-hetzenecker/home-assistant,jabesq/home-assistant,JshWright/home-assistant,open-homeautomation/home-assistant,molobrakos/home-assistant,dmeulen/home-assistant,qedi-r/home-assistant,coteyr/home-assistant,molobrakos/home-assistant,leppa/home-assistant,miniconfig/home-assistant,alexmogavero/home-assistant,Duoxilian/home-assistant,DavidLP/home-assistant,instantchow/home-assistant,mKeRix/home-assistant,Smart-Torvy/torvy-home-assistant,hmronline/home-assistant,LinuxChristian/home-assistant,Julian/home-assistant,varunr047/homefile,balloob/home-assistant,kyvinh/home-assistant,rohitranjan1991/home-assistant,aequitas/home-assistant,dmeulen/home-assistant,postlund/home-assistant,luxus/home-assistant,jawilson/home-assistant,auduny/home-assistant,Zac-HD/home-assistant,LinuxChristian/home-assistant,tchellomello/home-assistant,Duoxilian/home-assistant,Julian/home-assistant,mikaelboman/home-assistant,shaftoe/home-assistant,luxus/home-assistant,tboyce1/home-assistant,happyleavesaoc/home-assistant,w1ll1am23/home-assistant,robjohnson189/home-assistant,JshWright/home-assistant,nkgilley/home-assistant,stefan-jonasson/home-assistant,pschmitt/home-assistant,balloob/home-assistant,hmronline/home-assistant,molobrakos/home-assistant,Zac-HD/home-assistant,betrisey/home-assistant,robjohnson189/home-assistant,sffjunkie/home-assistant,mezz64/home-assistant,Smart-Torvy/torvy-home-assistant,varunr047/homefile,jnewland/home-assistant,keerts/home-assistant,tinloaf/home-assistant,sander76/home-assistant,robbiet480/home-assistant,tinloaf/home-assistant,deisi/home-assistant,leoc/home-assistant,ma314smith/home-assistant,mikaelboman/home-assistant,morphis/home-assistant,DavidLP/home-assistant,varunr047/homefile,robjohnson189/home-assistant,ma314smith/home-assistant,open-homeautomation/home-assistant,oandrew/home-assistant,stefan-jonasson/home-assistant,keerts/home-assistant,titilambert/home-assistant,ma314smith/home-assistant,ct-23/home-assistant,tboyce1/home-assistant,toddeye/home-assistant,philipbl/home-assistant,emilhetty/home-assistant,shaftoe/home-assistant,nnic/home-assistant,florianholzapfel/home-assistant,Danielhiversen/home-assistant,xifle/home-assistant,auduny/home-assistant,fbradyirl/home-assistant,philipbl/home-assistant,coteyr/home-assistant,LinuxChristian/home-assistant,jamespcole/home-assistant,mKeRix/home-assistant,alexmogavero/home-assistant,jaharkes/home-assistant,turbokongen/home-assistant,shaftoe/home-assistant,jnewland/home-assistant,betrisey/home-assistant,MungoRae/home-assistant,MungoRae/home-assistant,nugget/home-assistant,oandrew/home-assistant,PetePriority/home-assistant,devdelay/home-assistant,aoakeson/home-assistant,eagleamon/home-assistant,titilambert/home-assistant,nnic/home-assistant,rohitranjan1991/home-assistant,jaharkes/home-assistant,hmronline/home-assistant,tinloaf/home-assistant,devdelay/home-assistant,MungoRae/home-assistant,srcLurker/home-assistant,aronsky/home-assistant,kyvinh/home-assistant,tchellomello/home-assistant,tboyce021/home-assistant,florianholzapfel/home-assistant,Zac-HD/home-assistant,jamespcole/home-assistant,alexmogavero/home-assistant,nugget/home-assistant,eagleamon/home-assistant,alexmogavero/home-assistant,happyleavesaoc/home-assistant,Theb-1/home-assistant,HydrelioxGitHub/home-assistant,luxus/home-assistant,Zac-HD/home-assistant,eagleamon/home-assistant,leoc/home-assistant,mikaelboman/home-assistant,deisi/home-assistant,postlund/home-assistant,mKeRix/home-assistant,ct-23/home-assistant,jawilson/home-assistant,leppa/home-assistant,auduny/home-assistant,happyleavesaoc/home-assistant,soldag/home-assistant,bdfoster/blumate,stefan-jonasson/home-assistant,leoc/home-assistant,instantchow/home-assistant,sffjunkie/home-assistant,sffjunkie/home-assistant,qedi-r/home-assistant,morphis/home-assistant,varunr047/homefile,jaharkes/home-assistant,betrisey/home-assistant,mKeRix/home-assistant,deisi/home-assistant,morphis/home-assistant,persandstrom/home-assistant,oandrew/home-assistant,MartinHjelmare/home-assistant,adrienbrault/home-assistant,Zyell/home-assistant,emilhetty/home-assistant,turbokongen/home-assistant,jabesq/home-assistant,emilhetty/home-assistant,srcLurker/home-assistant,Julian/home-assistant,HydrelioxGitHub/home-assistant,leoc/home-assistant,MartinHjelmare/home-assistant,Cinntax/home-assistant,hexxter/home-assistant,dmeulen/home-assistant,robjohnson189/home-assistant,aequitas/home-assistant,DavidLP/home-assistant,joopert/home-assistant,kennedyshead/home-assistant,philipbl/home-assistant,justyns/home-assistant,instantchow/home-assistant,w1ll1am23/home-assistant,FreekingDean/home-assistant,hexxter/home-assistant,Danielhiversen/home-assistant,betrisey/home-assistant,nnic/home-assistant,Cinntax/home-assistant,varunr047/homefile,mikaelboman/home-assistant,hmronline/home-assistant,Teagan42/home-assistant,mezz64/home-assistant,jabesq/home-assistant,keerts/home-assistant,sdague/home-assistant,morphis/home-assistant,xifle/home-assistant,devdelay/home-assistant,sander76/home-assistant,LinuxChristian/home-assistant,joopert/home-assistant,hmronline/home-assistant,kyvinh/home-assistant,sdague/home-assistant,eagleamon/home-assistant,Smart-Torvy/torvy-home-assistant,tboyce021/home-assistant,ewandor/home-assistant,bdfoster/blumate,ewandor/home-assistant,PetePriority/home-assistant,bdfoster/blumate,open-homeautomation/home-assistant,dmeulen/home-assistant,shaftoe/home-assistant,MungoRae/home-assistant,aequitas/home-assistant,ct-23/home-assistant,xifle/home-assistant,JshWright/home-assistant,LinuxChristian/home-assistant,kyvinh/home-assistant,partofthething/home-assistant,bdfoster/blumate,ewandor/home-assistant,Zyell/home-assistant,emilhetty/home-assistant,FreekingDean/home-assistant,miniconfig/home-assistant,coteyr/home-assistant,Teagan42/home-assistant,mikaelboman/home-assistant,Julian/home-assistant,philipbl/home-assistant,PetePriority/home-assistant,Theb-1/home-assistant,jnewland/home-assistant,ma314smith/home-assistant,GenericStudent/home-assistant,deisi/home-assistant,Smart-Torvy/torvy-home-assistant,nugget/home-assistant,soldag/home-assistant,home-assistant/home-assistant,MungoRae/home-assistant,deisi/home-assistant,robbiet480/home-assistant,sffjunkie/home-assistant,GenericStudent/home-assistant,aoakeson/home-assistant,justyns/home-assistant,xifle/home-assistant,oandrew/home-assistant,Zyell/home-assistant,justyns/home-assistant,sffjunkie/home-assistant,pschmitt/home-assistant,fbradyirl/home-assistant,miniconfig/home-assistant,hexxter/home-assistant,srcLurker/home-assistant,open-homeautomation/home-assistant,srcLurker/home-assistant,JshWright/home-assistant,aronsky/home-assistant,home-assistant/home-assistant,nkgilley/home-assistant,jamespcole/home-assistant,bdfoster/blumate,miniconfig/home-assistant,fbradyirl/home-assistant,Duoxilian/home-assistant,devdelay/home-assistant,jaharkes/home-assistant,Theb-1/home-assistant,stefan-jonasson/home-assistant,florianholzapfel/home-assistant,balloob/home-assistant,ct-23/home-assistant,tboyce1/home-assistant,tboyce1/home-assistant,happyleavesaoc/home-assistant,hexxter/home-assistant,lukas-hetzenecker/home-assistant,adrienbrault/home-assistant,HydrelioxGitHub/home-assistant,partofthething/home-assistant,persandstrom/home-assistant,MartinHjelmare/home-assistant,aoakeson/home-assistant,persandstrom/home-assistant
|
python
|
## Code Before:
from homeassistant.components.insteon import (INSTEON, InsteonToggleDevice)
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the Insteon Hub light platform. """
devs = []
for device in INSTEON.devices:
if device.DeviceCategory == "Switched Lighting Control":
devs.append(InsteonToggleDevice(device))
add_devices(devs)
## Instruction:
Add ability to control dimmable sources
## Code After:
from homeassistant.components.insteon import (INSTEON, InsteonToggleDevice)
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the Insteon Hub light platform. """
devs = []
for device in INSTEON.devices:
if device.DeviceCategory == "Switched Lighting Control":
devs.append(InsteonToggleDevice(device))
if device.DeviceCategory == "Dimmable Lighting Control":
devs.append(InsteonToggleDevice(device))
add_devices(devs)
|
// ... existing code ...
for device in INSTEON.devices:
if device.DeviceCategory == "Switched Lighting Control":
devs.append(InsteonToggleDevice(device))
if device.DeviceCategory == "Dimmable Lighting Control":
devs.append(InsteonToggleDevice(device))
add_devices(devs)
// ... rest of the code ...
|
0c785e349c2000bbf3b22671071a66eaca4d82d0
|
astropy/io/votable/__init__.py
|
astropy/io/votable/__init__.py
|
from .table import (
parse, parse_single_table, validate, from_table, is_votable)
from .exceptions import (
VOWarning, VOTableChangeWarning, VOTableSpecWarning, UnimplementedWarning,
IOWarning, VOTableSpecError)
__all__ = [
'parse', 'parse_single_table', 'validate', 'from_table',
'is_votable', 'VOWarning', 'VOTableChangeWarning', 'VOTableSpecWarning',
'UnimplementedWarning', 'IOWarning', 'VOTableSpecError']
|
from .table import (
parse, parse_single_table, validate, from_table, is_votable, writeto)
from .exceptions import (
VOWarning, VOTableChangeWarning, VOTableSpecWarning, UnimplementedWarning,
IOWarning, VOTableSpecError)
__all__ = [
'parse', 'parse_single_table', 'validate', 'from_table',
'is_votable', 'writeto', 'VOWarning', 'VOTableChangeWarning',
'VOTableSpecWarning', 'UnimplementedWarning', 'IOWarning',
'VOTableSpecError']
|
Put astropy.io.votable.writeto in the top-level namespace
|
Put astropy.io.votable.writeto in the top-level namespace
|
Python
|
bsd-3-clause
|
DougBurke/astropy,AustereCuriosity/astropy,funbaker/astropy,joergdietrich/astropy,StuartLittlefair/astropy,larrybradley/astropy,tbabej/astropy,mhvk/astropy,pllim/astropy,stargaser/astropy,lpsinger/astropy,joergdietrich/astropy,lpsinger/astropy,AustereCuriosity/astropy,kelle/astropy,saimn/astropy,DougBurke/astropy,bsipocz/astropy,mhvk/astropy,pllim/astropy,StuartLittlefair/astropy,astropy/astropy,saimn/astropy,dhomeier/astropy,StuartLittlefair/astropy,tbabej/astropy,joergdietrich/astropy,larrybradley/astropy,aleksandr-bakanov/astropy,funbaker/astropy,lpsinger/astropy,tbabej/astropy,AustereCuriosity/astropy,larrybradley/astropy,larrybradley/astropy,kelle/astropy,lpsinger/astropy,dhomeier/astropy,bsipocz/astropy,bsipocz/astropy,pllim/astropy,astropy/astropy,lpsinger/astropy,StuartLittlefair/astropy,joergdietrich/astropy,kelle/astropy,pllim/astropy,astropy/astropy,aleksandr-bakanov/astropy,MSeifert04/astropy,joergdietrich/astropy,stargaser/astropy,saimn/astropy,tbabej/astropy,AustereCuriosity/astropy,aleksandr-bakanov/astropy,mhvk/astropy,saimn/astropy,mhvk/astropy,dhomeier/astropy,DougBurke/astropy,dhomeier/astropy,funbaker/astropy,DougBurke/astropy,funbaker/astropy,mhvk/astropy,MSeifert04/astropy,larrybradley/astropy,stargaser/astropy,stargaser/astropy,bsipocz/astropy,kelle/astropy,saimn/astropy,astropy/astropy,dhomeier/astropy,aleksandr-bakanov/astropy,kelle/astropy,MSeifert04/astropy,MSeifert04/astropy,astropy/astropy,tbabej/astropy,StuartLittlefair/astropy,pllim/astropy,AustereCuriosity/astropy
|
python
|
## Code Before:
from .table import (
parse, parse_single_table, validate, from_table, is_votable)
from .exceptions import (
VOWarning, VOTableChangeWarning, VOTableSpecWarning, UnimplementedWarning,
IOWarning, VOTableSpecError)
__all__ = [
'parse', 'parse_single_table', 'validate', 'from_table',
'is_votable', 'VOWarning', 'VOTableChangeWarning', 'VOTableSpecWarning',
'UnimplementedWarning', 'IOWarning', 'VOTableSpecError']
## Instruction:
Put astropy.io.votable.writeto in the top-level namespace
## Code After:
from .table import (
parse, parse_single_table, validate, from_table, is_votable, writeto)
from .exceptions import (
VOWarning, VOTableChangeWarning, VOTableSpecWarning, UnimplementedWarning,
IOWarning, VOTableSpecError)
__all__ = [
'parse', 'parse_single_table', 'validate', 'from_table',
'is_votable', 'writeto', 'VOWarning', 'VOTableChangeWarning',
'VOTableSpecWarning', 'UnimplementedWarning', 'IOWarning',
'VOTableSpecError']
|
// ... existing code ...
from .table import (
parse, parse_single_table, validate, from_table, is_votable, writeto)
from .exceptions import (
VOWarning, VOTableChangeWarning, VOTableSpecWarning, UnimplementedWarning,
IOWarning, VOTableSpecError)
// ... modified code ...
__all__ = [
'parse', 'parse_single_table', 'validate', 'from_table',
'is_votable', 'writeto', 'VOWarning', 'VOTableChangeWarning',
'VOTableSpecWarning', 'UnimplementedWarning', 'IOWarning',
'VOTableSpecError']
// ... rest of the code ...
|
95e347ae4086d05aadf91a393b856961b34026a5
|
website_field_autocomplete/controllers/main.py
|
website_field_autocomplete/controllers/main.py
|
import json
from openerp import http
from openerp.http import request
from openerp.addons.website.controllers.main import Website
class Website(Website):
@http.route(
'/website/field_autocomplete/<string:model>',
type='http',
auth='public',
methods=['GET'],
website=True,
)
def _get_field_autocomplete(self, model, **kwargs):
""" Return json autocomplete data """
domain = json.loads(kwargs.get('domain', "[]"))
fields = json.loads(kwargs.get('fields', "[]"))
limit = kwargs.get('limit', None)
res = self._get_autocomplete_data(model, domain, fields, limit)
return json.dumps(res.values())
def _get_autocomplete_data(self, model, domain, fields, limit=None):
""" Gets and returns raw record data
Params:
model: Model name to query on
domain: Search domain
fields: List of fields to get
limit: Limit results to
Returns:
Dict of record dicts, keyed by ID
"""
res = {}
if limit:
limit = int(limit)
self.record_ids = request.env[model].search(domain, limit=limit)
for rec_id in self.record_ids:
res[rec_id.id] = {
k: getattr(rec_id, k, None) for k in fields
}
return res
|
import json
from openerp import http
from openerp.http import request
from openerp.addons.website.controllers.main import Website
class Website(Website):
@http.route(
'/website/field_autocomplete/<string:model>',
type='http',
auth='public',
methods=['GET'],
website=True,
)
def _get_field_autocomplete(self, model, **kwargs):
""" Return json autocomplete data """
domain = json.loads(kwargs.get('domain', "[]"))
fields = json.loads(kwargs.get('fields', "[]"))
limit = kwargs.get('limit', None)
res = self._get_autocomplete_data(model, domain, fields, limit)
return json.dumps(res.values())
def _get_autocomplete_data(self, model, domain, fields, limit=None):
""" Gets and returns raw record data
Params:
model: Model name to query on
domain: Search domain
fields: List of fields to get
limit: Limit results to
Returns:
Dict of record dicts, keyed by ID
"""
if limit:
limit = int(limit)
res = request.env[model].search_read(
domain, fields, limit=limit
)
return {r['id']: r for r in res}
|
Use search_read * Use search_read in controller data getter, instead of custom implementation
|
[FIX] website_field_autocomplete: Use search_read
* Use search_read in controller data getter, instead of custom implementation
|
Python
|
agpl-3.0
|
Tecnativa/website,nicolas-petit/website,khaeusler/website,JayVora-SerpentCS/website,RoelAdriaans-B-informed/website,JayVora-SerpentCS/website,khaeusler/website,nicolas-petit/website,Tecnativa/website,khaeusler/website,Tecnativa/website,RoelAdriaans-B-informed/website,nicolas-petit/website,JayVora-SerpentCS/website,RoelAdriaans-B-informed/website,RoelAdriaans-B-informed/website
|
python
|
## Code Before:
import json
from openerp import http
from openerp.http import request
from openerp.addons.website.controllers.main import Website
class Website(Website):
@http.route(
'/website/field_autocomplete/<string:model>',
type='http',
auth='public',
methods=['GET'],
website=True,
)
def _get_field_autocomplete(self, model, **kwargs):
""" Return json autocomplete data """
domain = json.loads(kwargs.get('domain', "[]"))
fields = json.loads(kwargs.get('fields', "[]"))
limit = kwargs.get('limit', None)
res = self._get_autocomplete_data(model, domain, fields, limit)
return json.dumps(res.values())
def _get_autocomplete_data(self, model, domain, fields, limit=None):
""" Gets and returns raw record data
Params:
model: Model name to query on
domain: Search domain
fields: List of fields to get
limit: Limit results to
Returns:
Dict of record dicts, keyed by ID
"""
res = {}
if limit:
limit = int(limit)
self.record_ids = request.env[model].search(domain, limit=limit)
for rec_id in self.record_ids:
res[rec_id.id] = {
k: getattr(rec_id, k, None) for k in fields
}
return res
## Instruction:
[FIX] website_field_autocomplete: Use search_read
* Use search_read in controller data getter, instead of custom implementation
## Code After:
import json
from openerp import http
from openerp.http import request
from openerp.addons.website.controllers.main import Website
class Website(Website):
@http.route(
'/website/field_autocomplete/<string:model>',
type='http',
auth='public',
methods=['GET'],
website=True,
)
def _get_field_autocomplete(self, model, **kwargs):
""" Return json autocomplete data """
domain = json.loads(kwargs.get('domain', "[]"))
fields = json.loads(kwargs.get('fields', "[]"))
limit = kwargs.get('limit', None)
res = self._get_autocomplete_data(model, domain, fields, limit)
return json.dumps(res.values())
def _get_autocomplete_data(self, model, domain, fields, limit=None):
""" Gets and returns raw record data
Params:
model: Model name to query on
domain: Search domain
fields: List of fields to get
limit: Limit results to
Returns:
Dict of record dicts, keyed by ID
"""
if limit:
limit = int(limit)
res = request.env[model].search_read(
domain, fields, limit=limit
)
return {r['id']: r for r in res}
|
...
Returns:
Dict of record dicts, keyed by ID
"""
if limit:
limit = int(limit)
res = request.env[model].search_read(
domain, fields, limit=limit
)
return {r['id']: r for r in res}
...
|
03913013e30c31a646def283cdec44f153adb572
|
src/test/java/org/realityforge/jeo/geolatte/jpa/eclipselink/DatabaseTestUtil.java
|
src/test/java/org/realityforge/jeo/geolatte/jpa/eclipselink/DatabaseTestUtil.java
|
package org.realityforge.jeo.geolatte.jpa.eclipselink;
import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class DatabaseTestUtil
{
static Properties initDatabaseProperties()
{
final Properties properties = new Properties();
properties.put( "javax.persistence.jdbc.driver", "org.postgis.DriverWrapperAutoprobe" );
final String databaseUrl = "jdbc:postgresql_autogis://127.0.0.1:5432/geolatte_test";
setProperty( properties, "javax.persistence.jdbc.url", "test.db.url", databaseUrl );
setProperty( properties, "javax.persistence.jdbc.user", "test.db.user", "geolatte" );
setProperty( properties, "javax.persistence.jdbc.password", "test.db.password", null );
properties.put( "eclipselink.session-event-listener", GeolatteExtension.class.getName() );
return properties;
}
private static void setProperty( final Properties properties,
final String key,
final String systemPropertyKey, final String defaultValue )
{
final String value = System.getProperty( systemPropertyKey, defaultValue );
if ( null != value )
{
properties.put( key, value );
}
}
public static EntityManager createEntityManager( final String persistenceUnitName )
{
final Properties properties = initDatabaseProperties();
final EntityManagerFactory factory = Persistence.createEntityManagerFactory( persistenceUnitName, properties );
return factory.createEntityManager();
}
}
|
package org.realityforge.jeo.geolatte.jpa.eclipselink;
import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class DatabaseTestUtil
{
static Properties initDatabaseProperties()
{
final Properties properties = new Properties();
properties.put( "javax.persistence.jdbc.driver", "org.postgresql.Driver" );
final String databaseUrl = "jdbc:postgresql://127.0.0.1:5432/geolatte_test";
setProperty( properties, "javax.persistence.jdbc.url", "test.db.url", databaseUrl );
setProperty( properties, "javax.persistence.jdbc.user", "test.db.user", "geolatte" );
setProperty( properties, "javax.persistence.jdbc.password", "test.db.password", null );
properties.put( "eclipselink.session-event-listener", GeolatteExtension.class.getName() );
return properties;
}
private static void setProperty( final Properties properties,
final String key,
final String systemPropertyKey, final String defaultValue )
{
final String value = System.getProperty( systemPropertyKey, defaultValue );
if ( null != value )
{
properties.put( key, value );
}
}
public static EntityManager createEntityManager( final String persistenceUnitName )
{
final Properties properties = initDatabaseProperties();
final EntityManagerFactory factory = Persistence.createEntityManagerFactory( persistenceUnitName, properties );
return factory.createEntityManager();
}
}
|
Revert to using the base postgres driver in tests
|
Revert to using the base postgres driver in tests
|
Java
|
apache-2.0
|
realityforge/geolatte-geom-eclipselink,realityforge/geolatte-geom-jpa,realityforge/geolatte-geom-jpa,realityforge/geolatte-geom-eclipselink
|
java
|
## Code Before:
package org.realityforge.jeo.geolatte.jpa.eclipselink;
import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class DatabaseTestUtil
{
static Properties initDatabaseProperties()
{
final Properties properties = new Properties();
properties.put( "javax.persistence.jdbc.driver", "org.postgis.DriverWrapperAutoprobe" );
final String databaseUrl = "jdbc:postgresql_autogis://127.0.0.1:5432/geolatte_test";
setProperty( properties, "javax.persistence.jdbc.url", "test.db.url", databaseUrl );
setProperty( properties, "javax.persistence.jdbc.user", "test.db.user", "geolatte" );
setProperty( properties, "javax.persistence.jdbc.password", "test.db.password", null );
properties.put( "eclipselink.session-event-listener", GeolatteExtension.class.getName() );
return properties;
}
private static void setProperty( final Properties properties,
final String key,
final String systemPropertyKey, final String defaultValue )
{
final String value = System.getProperty( systemPropertyKey, defaultValue );
if ( null != value )
{
properties.put( key, value );
}
}
public static EntityManager createEntityManager( final String persistenceUnitName )
{
final Properties properties = initDatabaseProperties();
final EntityManagerFactory factory = Persistence.createEntityManagerFactory( persistenceUnitName, properties );
return factory.createEntityManager();
}
}
## Instruction:
Revert to using the base postgres driver in tests
## Code After:
package org.realityforge.jeo.geolatte.jpa.eclipselink;
import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class DatabaseTestUtil
{
static Properties initDatabaseProperties()
{
final Properties properties = new Properties();
properties.put( "javax.persistence.jdbc.driver", "org.postgresql.Driver" );
final String databaseUrl = "jdbc:postgresql://127.0.0.1:5432/geolatte_test";
setProperty( properties, "javax.persistence.jdbc.url", "test.db.url", databaseUrl );
setProperty( properties, "javax.persistence.jdbc.user", "test.db.user", "geolatte" );
setProperty( properties, "javax.persistence.jdbc.password", "test.db.password", null );
properties.put( "eclipselink.session-event-listener", GeolatteExtension.class.getName() );
return properties;
}
private static void setProperty( final Properties properties,
final String key,
final String systemPropertyKey, final String defaultValue )
{
final String value = System.getProperty( systemPropertyKey, defaultValue );
if ( null != value )
{
properties.put( key, value );
}
}
public static EntityManager createEntityManager( final String persistenceUnitName )
{
final Properties properties = initDatabaseProperties();
final EntityManagerFactory factory = Persistence.createEntityManagerFactory( persistenceUnitName, properties );
return factory.createEntityManager();
}
}
|
...
static Properties initDatabaseProperties()
{
final Properties properties = new Properties();
properties.put( "javax.persistence.jdbc.driver", "org.postgresql.Driver" );
final String databaseUrl = "jdbc:postgresql://127.0.0.1:5432/geolatte_test";
setProperty( properties, "javax.persistence.jdbc.url", "test.db.url", databaseUrl );
setProperty( properties, "javax.persistence.jdbc.user", "test.db.user", "geolatte" );
setProperty( properties, "javax.persistence.jdbc.password", "test.db.password", null );
...
|
92c70c5f54b6822f0f3815b66852a2771ef5d49c
|
scheduling/student_invite.py
|
scheduling/student_invite.py
|
from aiohttp.web import Application
from db_helper import get_most_recent_group
from mail import send_user_email
from permissions import get_users_with_permission
async def student_invite(app: Application) -> None:
print("Inviting students")
session = app["session"]
group = get_most_recent_group(session)
group.student_viewable = True
group.student_choosable = True
for user in get_users_with_permission(app, "join_projects"):
await send_user_email(app,
user,
"invite_sent",
group=group)
|
from aiohttp.web import Application
from db_helper import get_most_recent_group
from mail import send_user_email
from permissions import get_users_with_permission
async def student_invite(app: Application) -> None:
print("Inviting students")
session = app["session"]
group = get_most_recent_group(session)
group.student_viewable = True
group.student_choosable = True
group.read_only = True
for user in get_users_with_permission(app, "join_projects"):
await send_user_email(app,
user,
"invite_sent",
group=group)
|
Set group as read only when inviting students
|
Set group as read only when inviting students
|
Python
|
agpl-3.0
|
wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp
|
python
|
## Code Before:
from aiohttp.web import Application
from db_helper import get_most_recent_group
from mail import send_user_email
from permissions import get_users_with_permission
async def student_invite(app: Application) -> None:
print("Inviting students")
session = app["session"]
group = get_most_recent_group(session)
group.student_viewable = True
group.student_choosable = True
for user in get_users_with_permission(app, "join_projects"):
await send_user_email(app,
user,
"invite_sent",
group=group)
## Instruction:
Set group as read only when inviting students
## Code After:
from aiohttp.web import Application
from db_helper import get_most_recent_group
from mail import send_user_email
from permissions import get_users_with_permission
async def student_invite(app: Application) -> None:
print("Inviting students")
session = app["session"]
group = get_most_recent_group(session)
group.student_viewable = True
group.student_choosable = True
group.read_only = True
for user in get_users_with_permission(app, "join_projects"):
await send_user_email(app,
user,
"invite_sent",
group=group)
|
...
group = get_most_recent_group(session)
group.student_viewable = True
group.student_choosable = True
group.read_only = True
for user in get_users_with_permission(app, "join_projects"):
await send_user_email(app,
user,
...
|
2af2e83757582fdc8f5838562d2c6377afef4536
|
include/Mixer.h
|
include/Mixer.h
|
/* $Id$ */
/* Copyright (c) 2017 Pierre Pronchery <[email protected]> */
/* This file is part of DeforaOS Desktop Mixer */
/* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef DESKTOP_MIXER_H
# define DESKTOP_MIXER_H
# include "Mixer/control.h"
#endif /* !DESKTOP_MIXER_H */
|
/* $Id$ */
/* Copyright (c) 2017 Pierre Pronchery <[email protected]> */
/* This file is part of DeforaOS Desktop Mixer */
/* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
#ifndef DESKTOP_MIXER_H
# define DESKTOP_MIXER_H
# include "Mixer/control.h"
#endif /* !DESKTOP_MIXER_H */
|
Complete the license switch to 2-clause BSD
|
Complete the license switch to 2-clause BSD
Thanks ocochard for the heads up!
|
C
|
bsd-2-clause
|
DeforaOS/Mixer,DeforaOS/Mixer
|
c
|
## Code Before:
/* $Id$ */
/* Copyright (c) 2017 Pierre Pronchery <[email protected]> */
/* This file is part of DeforaOS Desktop Mixer */
/* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef DESKTOP_MIXER_H
# define DESKTOP_MIXER_H
# include "Mixer/control.h"
#endif /* !DESKTOP_MIXER_H */
## Instruction:
Complete the license switch to 2-clause BSD
Thanks ocochard for the heads up!
## Code After:
/* $Id$ */
/* Copyright (c) 2017 Pierre Pronchery <[email protected]> */
/* This file is part of DeforaOS Desktop Mixer */
/* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
#ifndef DESKTOP_MIXER_H
# define DESKTOP_MIXER_H
# include "Mixer/control.h"
#endif /* !DESKTOP_MIXER_H */
|
# ... existing code ...
/* $Id$ */
/* Copyright (c) 2017 Pierre Pronchery <[email protected]> */
/* This file is part of DeforaOS Desktop Mixer */
/* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
# ... rest of the code ...
|
6a6d7c90e7447ee059538c3876ca5f35b57f86cc
|
app/src/main/java/io/github/droidkaigi/confsched2017/viewmodel/ContributorViewModel.java
|
app/src/main/java/io/github/droidkaigi/confsched2017/viewmodel/ContributorViewModel.java
|
package io.github.droidkaigi.confsched2017.viewmodel;
import android.databinding.BaseObservable;
import android.support.annotation.NonNull;
import io.github.droidkaigi.confsched2017.model.Contributor;
public class ContributorViewModel extends BaseObservable implements ViewModel {
private Callback callback;
private Contributor contributor;
private String name;
private String avatarUrl;
private String htmlUrl;
private int contributions;
public ContributorViewModel(@NonNull Contributor contributor) {
this.contributor = contributor;
this.avatarUrl = contributor.avatarUrl;
this.name = contributor.name;
this.htmlUrl = contributor.htmlUrl;
this.contributions = contributor.contributions;
}
public void setCallback(Callback callback) {
this.callback = callback;
}
@Override
public void destroy() {
this.callback = null;
}
public interface Callback {
void onClickContributor();
}
public int getContributions() {
return contributions;
}
public Contributor getContributor() {
return contributor;
}
public String getName() {
return name;
}
public String getAvatarUrl() {
return avatarUrl;
}
public String getHtmlUrl() {
return htmlUrl;
}
}
|
package io.github.droidkaigi.confsched2017.viewmodel;
import android.databinding.BaseObservable;
import android.support.annotation.NonNull;
import android.view.View;
import io.github.droidkaigi.confsched2017.model.Contributor;
public class ContributorViewModel extends BaseObservable implements ViewModel {
private Callback callback;
private Contributor contributor;
private String name;
private String avatarUrl;
private String htmlUrl;
private int contributions;
public ContributorViewModel(@NonNull Contributor contributor) {
this.contributor = contributor;
this.avatarUrl = contributor.avatarUrl;
this.name = contributor.name;
this.htmlUrl = contributor.htmlUrl;
this.contributions = contributor.contributions;
}
public void setCallback(Callback callback) {
this.callback = callback;
}
@Override
public void destroy() {
this.callback = null;
}
public interface Callback {
void onClickContributor(String htmlUrl);
}
public void onClickContributor(@SuppressWarnings("UnusedParameters") View view) {
if (callback != null) {
callback.onClickContributor(htmlUrl);
}
}
public int getContributions() {
return contributions;
}
public Contributor getContributor() {
return contributor;
}
public String getName() {
return name;
}
public String getAvatarUrl() {
return avatarUrl;
}
public String getHtmlUrl() {
return htmlUrl;
}
}
|
Fix the problem with handling onClick event
|
Fix the problem with handling onClick event
|
Java
|
apache-2.0
|
u-nation/conference-app-2017,DroidKaigi/conference-app-2017,horie1024/conference-app-2017,hironytic/conference-app-2017,yatatsu/conference-app-2017,shaunkawano/conference-app-2017,u-nation/conference-app-2017,k-kagurazaka/conference-app-2017,kgmyshin/conference-app-2017,kobakei/conference-app-2017,ryugoo/conference-app-2017,DroidKaigi/conference-app-2017,futabooo/conference-app-2017,kgmyshin/conference-app-2017,futabooo/conference-app-2017,wakwak3125/conference-app-2017,takuaraki/conference-app-2017,sys1yagi/conference-app-2017,sys1yagi/conference-app-2017,takuaraki/conference-app-2017,kobakei/conference-app-2017,kikuchy/conference-app-2017,takuaraki/conference-app-2017,kobakei/conference-app-2017,chibatching/conference-app-2017,gen0083/conference-app-2017,sys1yagi/conference-app-2017,k-kagurazaka/conference-app-2017,futabooo/conference-app-2017,sys1yagi/conference-app-2017,shaunkawano/conference-app-2017,kikuchy/conference-app-2017,yatatsu/conference-app-2017,DroidKaigi/conference-app-2017,kikuchy/conference-app-2017,kaelaela/conference-app-2017,ryugoo/conference-app-2017,u-nation/conference-app-2017,horie1024/conference-app-2017,wakwak3125/conference-app-2017,ryugoo/conference-app-2017,DroidKaigi/conference-app-2017,k-kagurazaka/conference-app-2017,hironytic/conference-app-2017,ogapants/conference-app-2017,ryugoo/conference-app-2017,kaelaela/conference-app-2017,gen0083/conference-app-2017,wakwak3125/conference-app-2017,eyedol/conference-app-2017,kikuchy/conference-app-2017,chibatching/conference-app-2017,sys1yagi/conference-app-2017,eyedol/conference-app-2017,chibatching/conference-app-2017,kitwtnb/conference-app-2017,ogapants/conference-app-2017,wakwak3125/conference-app-2017,ogapants/conference-app-2017,kitwtnb/conference-app-2017,ryugoo/conference-app-2017,kobakei/conference-app-2017,eyedol/conference-app-2017,gen0083/conference-app-2017,DroidKaigi/conference-app-2017,kgmyshin/conference-app-2017,takuaraki/conference-app-2017,gen0083/conference-app-2017,hironytic/conference-app-2017,eyedol/conference-app-2017,yatatsu/conference-app-2017,hironytic/conference-app-2017,eyedol/conference-app-2017,kaelaela/conference-app-2017,shaunkawano/conference-app-2017,yatatsu/conference-app-2017,k-kagurazaka/conference-app-2017,chibatching/conference-app-2017,kitwtnb/conference-app-2017,kitwtnb/conference-app-2017,futabooo/conference-app-2017,hironytic/conference-app-2017,kgmyshin/conference-app-2017,futabooo/conference-app-2017,wakwak3125/conference-app-2017,yatatsu/conference-app-2017,kgmyshin/conference-app-2017,kobakei/conference-app-2017,u-nation/conference-app-2017,gen0083/conference-app-2017,shaunkawano/conference-app-2017,kaelaela/conference-app-2017,chibatching/conference-app-2017,kikuchy/conference-app-2017,kaelaela/conference-app-2017,takuaraki/conference-app-2017,ogapants/conference-app-2017,shaunkawano/conference-app-2017,horie1024/conference-app-2017,horie1024/conference-app-2017,k-kagurazaka/conference-app-2017,kitwtnb/conference-app-2017,u-nation/conference-app-2017,horie1024/conference-app-2017,ogapants/conference-app-2017
|
java
|
## Code Before:
package io.github.droidkaigi.confsched2017.viewmodel;
import android.databinding.BaseObservable;
import android.support.annotation.NonNull;
import io.github.droidkaigi.confsched2017.model.Contributor;
public class ContributorViewModel extends BaseObservable implements ViewModel {
private Callback callback;
private Contributor contributor;
private String name;
private String avatarUrl;
private String htmlUrl;
private int contributions;
public ContributorViewModel(@NonNull Contributor contributor) {
this.contributor = contributor;
this.avatarUrl = contributor.avatarUrl;
this.name = contributor.name;
this.htmlUrl = contributor.htmlUrl;
this.contributions = contributor.contributions;
}
public void setCallback(Callback callback) {
this.callback = callback;
}
@Override
public void destroy() {
this.callback = null;
}
public interface Callback {
void onClickContributor();
}
public int getContributions() {
return contributions;
}
public Contributor getContributor() {
return contributor;
}
public String getName() {
return name;
}
public String getAvatarUrl() {
return avatarUrl;
}
public String getHtmlUrl() {
return htmlUrl;
}
}
## Instruction:
Fix the problem with handling onClick event
## Code After:
package io.github.droidkaigi.confsched2017.viewmodel;
import android.databinding.BaseObservable;
import android.support.annotation.NonNull;
import android.view.View;
import io.github.droidkaigi.confsched2017.model.Contributor;
public class ContributorViewModel extends BaseObservable implements ViewModel {
private Callback callback;
private Contributor contributor;
private String name;
private String avatarUrl;
private String htmlUrl;
private int contributions;
public ContributorViewModel(@NonNull Contributor contributor) {
this.contributor = contributor;
this.avatarUrl = contributor.avatarUrl;
this.name = contributor.name;
this.htmlUrl = contributor.htmlUrl;
this.contributions = contributor.contributions;
}
public void setCallback(Callback callback) {
this.callback = callback;
}
@Override
public void destroy() {
this.callback = null;
}
public interface Callback {
void onClickContributor(String htmlUrl);
}
public void onClickContributor(@SuppressWarnings("UnusedParameters") View view) {
if (callback != null) {
callback.onClickContributor(htmlUrl);
}
}
public int getContributions() {
return contributions;
}
public Contributor getContributor() {
return contributor;
}
public String getName() {
return name;
}
public String getAvatarUrl() {
return avatarUrl;
}
public String getHtmlUrl() {
return htmlUrl;
}
}
|
# ... existing code ...
import android.databinding.BaseObservable;
import android.support.annotation.NonNull;
import android.view.View;
import io.github.droidkaigi.confsched2017.model.Contributor;
# ... modified code ...
public interface Callback {
void onClickContributor(String htmlUrl);
}
public void onClickContributor(@SuppressWarnings("UnusedParameters") View view) {
if (callback != null) {
callback.onClickContributor(htmlUrl);
}
}
public int getContributions() {
# ... rest of the code ...
|
e16b6dec212a86fb65db026ddcfcdd89efd30ec5
|
master.c
|
master.c
|
//Master configurations
MODBUSMasterStatus MODBUSMaster;
void MODBUSParseResponse( uint8_t *Frame, uint8_t FrameLength )
{
//This function parses response from master
//Calling it will lead to losing all data and exceptions stored in MODBUSMaster (space will be reallocated)
//Allocate memory for union and copy frame to it
union MODBUSParser *Parser = malloc( FrameLength );
memcpy( ( *Parser ).Frame, Frame, FrameLength );
if ( MODBUS_MASTER_BASIC )
MODBUSParseResponseBasic( Parser );
//Free used memory
free( Parser );
}
void MODBUSMasterInit( )
{
//Very basic init of master side
MODBUSMaster.Request.Frame = malloc( 8 );
MODBUSMaster.Request.Length = 0;
MODBUSMaster.Data = malloc( sizeof( MODBUSData ) );
MODBUSMaster.DataLength = 0;
}
|
//Master configurations
MODBUSMasterStatus MODBUSMaster;
void MODBUSParseException( union MODBUSParser *Parser )
{
//Parse exception frame and write data to MODBUSMaster structure
//Allocate memory for exception parser
union MODBUSException *Exception = malloc( sizeof( union MODBUSException ) );
memcpy( ( *Exception ).Frame, ( *Parser ).Frame, sizeof( union MODBUSException ) );
//Check CRC
if ( MODBUSCRC16( ( *Exception ).Frame, 3 ) != ( *Exception ).Exception.CRC )
{
free( Exception );
return;
}
//Copy data
MODBUSMaster.Exception.Address = ( *Exception ).Exception.Address;
MODBUSMaster.Exception.Function = ( *Exception ).Exception.Function;
MODBUSMaster.Exception.Code = ( *Exception ).Exception.ExceptionCode;
MODBUSMaster.Error = 1;
free( Exception );
}
void MODBUSParseResponse( uint8_t *Frame, uint8_t FrameLength )
{
//This function parses response from master
//Calling it will lead to losing all data and exceptions stored in MODBUSMaster (space will be reallocated)
//Allocate memory for union and copy frame to it
union MODBUSParser *Parser = malloc( FrameLength );
memcpy( ( *Parser ).Frame, Frame, FrameLength );
//Check if frame is exception response
if ( ( *Parser ).Base.Function & 128 )
{
MODBUSParseException( Parser );
}
else
{
if ( MODBUS_MASTER_BASIC )
MODBUSParseResponseBasic( Parser );
}
//Free used memory
free( Parser );
}
void MODBUSMasterInit( )
{
//Very basic init of master side
MODBUSMaster.Request.Frame = malloc( 8 );
MODBUSMaster.Request.Length = 0;
MODBUSMaster.Data = malloc( sizeof( MODBUSData ) );
MODBUSMaster.DataLength = 0;
}
|
Add exceptions parsing (not tested yet)
|
Add exceptions parsing (not tested yet)
|
C
|
mit
|
Jacajack/modlib
|
c
|
## Code Before:
//Master configurations
MODBUSMasterStatus MODBUSMaster;
void MODBUSParseResponse( uint8_t *Frame, uint8_t FrameLength )
{
//This function parses response from master
//Calling it will lead to losing all data and exceptions stored in MODBUSMaster (space will be reallocated)
//Allocate memory for union and copy frame to it
union MODBUSParser *Parser = malloc( FrameLength );
memcpy( ( *Parser ).Frame, Frame, FrameLength );
if ( MODBUS_MASTER_BASIC )
MODBUSParseResponseBasic( Parser );
//Free used memory
free( Parser );
}
void MODBUSMasterInit( )
{
//Very basic init of master side
MODBUSMaster.Request.Frame = malloc( 8 );
MODBUSMaster.Request.Length = 0;
MODBUSMaster.Data = malloc( sizeof( MODBUSData ) );
MODBUSMaster.DataLength = 0;
}
## Instruction:
Add exceptions parsing (not tested yet)
## Code After:
//Master configurations
MODBUSMasterStatus MODBUSMaster;
void MODBUSParseException( union MODBUSParser *Parser )
{
//Parse exception frame and write data to MODBUSMaster structure
//Allocate memory for exception parser
union MODBUSException *Exception = malloc( sizeof( union MODBUSException ) );
memcpy( ( *Exception ).Frame, ( *Parser ).Frame, sizeof( union MODBUSException ) );
//Check CRC
if ( MODBUSCRC16( ( *Exception ).Frame, 3 ) != ( *Exception ).Exception.CRC )
{
free( Exception );
return;
}
//Copy data
MODBUSMaster.Exception.Address = ( *Exception ).Exception.Address;
MODBUSMaster.Exception.Function = ( *Exception ).Exception.Function;
MODBUSMaster.Exception.Code = ( *Exception ).Exception.ExceptionCode;
MODBUSMaster.Error = 1;
free( Exception );
}
void MODBUSParseResponse( uint8_t *Frame, uint8_t FrameLength )
{
//This function parses response from master
//Calling it will lead to losing all data and exceptions stored in MODBUSMaster (space will be reallocated)
//Allocate memory for union and copy frame to it
union MODBUSParser *Parser = malloc( FrameLength );
memcpy( ( *Parser ).Frame, Frame, FrameLength );
//Check if frame is exception response
if ( ( *Parser ).Base.Function & 128 )
{
MODBUSParseException( Parser );
}
else
{
if ( MODBUS_MASTER_BASIC )
MODBUSParseResponseBasic( Parser );
}
//Free used memory
free( Parser );
}
void MODBUSMasterInit( )
{
//Very basic init of master side
MODBUSMaster.Request.Frame = malloc( 8 );
MODBUSMaster.Request.Length = 0;
MODBUSMaster.Data = malloc( sizeof( MODBUSData ) );
MODBUSMaster.DataLength = 0;
}
|
// ... existing code ...
//Master configurations
MODBUSMasterStatus MODBUSMaster;
void MODBUSParseException( union MODBUSParser *Parser )
{
//Parse exception frame and write data to MODBUSMaster structure
//Allocate memory for exception parser
union MODBUSException *Exception = malloc( sizeof( union MODBUSException ) );
memcpy( ( *Exception ).Frame, ( *Parser ).Frame, sizeof( union MODBUSException ) );
//Check CRC
if ( MODBUSCRC16( ( *Exception ).Frame, 3 ) != ( *Exception ).Exception.CRC )
{
free( Exception );
return;
}
//Copy data
MODBUSMaster.Exception.Address = ( *Exception ).Exception.Address;
MODBUSMaster.Exception.Function = ( *Exception ).Exception.Function;
MODBUSMaster.Exception.Code = ( *Exception ).Exception.ExceptionCode;
MODBUSMaster.Error = 1;
free( Exception );
}
void MODBUSParseResponse( uint8_t *Frame, uint8_t FrameLength )
{
// ... modified code ...
union MODBUSParser *Parser = malloc( FrameLength );
memcpy( ( *Parser ).Frame, Frame, FrameLength );
//Check if frame is exception response
if ( ( *Parser ).Base.Function & 128 )
{
MODBUSParseException( Parser );
}
else
{
if ( MODBUS_MASTER_BASIC )
MODBUSParseResponseBasic( Parser );
}
//Free used memory
free( Parser );
// ... rest of the code ...
|
470b7313fa9b176fa4492ac9f355acd21542265d
|
tests/test_lib_fallback.py
|
tests/test_lib_fallback.py
|
from mock import patch
from pytest import raises
from tvrenamr.errors import NoMoreLibrariesException
from tvrenamr.main import Episode
from .base import BaseTest
from .mock_requests import initially_bad_xml, invalid_xml
class TestLibrariesFallback(BaseTest):
@patch('tvrenamr.libraries.requests.get', new=invalid_xml)
def test_rename_with_all_libraries_returning_invalid_xml(self):
with raises(NoMoreLibrariesException):
self.tv.retrieve_episode_title(self._file.episodes[0])
@patch('tvrenamr.libraries.requests.get', new=initially_bad_xml)
def test_rename_with_tvdb_falling_over(self):
episode = Episode(self._file, '8')
title = self.tv.retrieve_episode_title(episode)
assert title == 'The Adhesive Duck Deficiency'
|
from mock import patch
from pytest import raises
from tvrenamr.errors import NoMoreLibrariesException
from tvrenamr.libraries import TheTvDb, TvRage
from tvrenamr.main import Episode
from .base import BaseTest
from .mock_requests import initially_bad_xml, invalid_xml
class TestLibrariesFallback(BaseTest):
@patch('tvrenamr.libraries.requests.get', new=invalid_xml)
def test_rename_with_all_libraries_returning_invalid_xml(self):
with raises(NoMoreLibrariesException):
self.tv.retrieve_episode_title(self._file.episodes[0])
@patch('tvrenamr.libraries.requests.get', new=initially_bad_xml)
def test_rename_with_tvdb_falling_over(self):
episode = Episode(self._file, '8')
title = self.tv.retrieve_episode_title(episode)
assert title == 'The Adhesive Duck Deficiency'
def test_setting_library_stops_fallback(self):
libraries = self.tv._get_libraries('thetvdb')
assert type(libraries) == list
assert len(libraries) == 1
assert libraries[0] == TheTvDb
libraries = self.tv._get_libraries('tvrage')
assert type(libraries) == list
assert len(libraries) == 1
assert libraries[0] == TvRage
|
Test library fallback is overridden by setting a library
|
Test library fallback is overridden by setting a library
|
Python
|
mit
|
wintersandroid/tvrenamr,ghickman/tvrenamr
|
python
|
## Code Before:
from mock import patch
from pytest import raises
from tvrenamr.errors import NoMoreLibrariesException
from tvrenamr.main import Episode
from .base import BaseTest
from .mock_requests import initially_bad_xml, invalid_xml
class TestLibrariesFallback(BaseTest):
@patch('tvrenamr.libraries.requests.get', new=invalid_xml)
def test_rename_with_all_libraries_returning_invalid_xml(self):
with raises(NoMoreLibrariesException):
self.tv.retrieve_episode_title(self._file.episodes[0])
@patch('tvrenamr.libraries.requests.get', new=initially_bad_xml)
def test_rename_with_tvdb_falling_over(self):
episode = Episode(self._file, '8')
title = self.tv.retrieve_episode_title(episode)
assert title == 'The Adhesive Duck Deficiency'
## Instruction:
Test library fallback is overridden by setting a library
## Code After:
from mock import patch
from pytest import raises
from tvrenamr.errors import NoMoreLibrariesException
from tvrenamr.libraries import TheTvDb, TvRage
from tvrenamr.main import Episode
from .base import BaseTest
from .mock_requests import initially_bad_xml, invalid_xml
class TestLibrariesFallback(BaseTest):
@patch('tvrenamr.libraries.requests.get', new=invalid_xml)
def test_rename_with_all_libraries_returning_invalid_xml(self):
with raises(NoMoreLibrariesException):
self.tv.retrieve_episode_title(self._file.episodes[0])
@patch('tvrenamr.libraries.requests.get', new=initially_bad_xml)
def test_rename_with_tvdb_falling_over(self):
episode = Episode(self._file, '8')
title = self.tv.retrieve_episode_title(episode)
assert title == 'The Adhesive Duck Deficiency'
def test_setting_library_stops_fallback(self):
libraries = self.tv._get_libraries('thetvdb')
assert type(libraries) == list
assert len(libraries) == 1
assert libraries[0] == TheTvDb
libraries = self.tv._get_libraries('tvrage')
assert type(libraries) == list
assert len(libraries) == 1
assert libraries[0] == TvRage
|
// ... existing code ...
from pytest import raises
from tvrenamr.errors import NoMoreLibrariesException
from tvrenamr.libraries import TheTvDb, TvRage
from tvrenamr.main import Episode
from .base import BaseTest
// ... modified code ...
episode = Episode(self._file, '8')
title = self.tv.retrieve_episode_title(episode)
assert title == 'The Adhesive Duck Deficiency'
def test_setting_library_stops_fallback(self):
libraries = self.tv._get_libraries('thetvdb')
assert type(libraries) == list
assert len(libraries) == 1
assert libraries[0] == TheTvDb
libraries = self.tv._get_libraries('tvrage')
assert type(libraries) == list
assert len(libraries) == 1
assert libraries[0] == TvRage
// ... rest of the code ...
|
e524e7ee97dcc87aee0616328e9be64d1c3daf57
|
The_Eye/inc/Biquad_Filter.h
|
The_Eye/inc/Biquad_Filter.h
|
/*
* Biquad_Filter.h
*
* Created on: 24. 6. 2017
* Author: michp
*/
#ifndef BIQUAD_FILTER_H_
#define BIQUAD_FILTER_H_
#include <cmath>
namespace flyhero {
// Many thanks to http://www.earlevel.com/main/2012/11/26/biquad-c-source-code/
class Biquad_Filter {
private:
const double PI = 3.14159265358979323846;
float a0, a1, a2;
float b1, b2;
float z1, z2;
public:
enum Filter_Type { FILTER_LOW_PASS, FILTER_NOTCH };
Biquad_Filter(Filter_Type type, float sample_frequency, float cut_frequency);
inline float Apply_Filter(float value);
};
// 10 us
float Biquad_Filter::Apply_Filter(float value) {
float ret = value * this->a0 + this->z1;
this->z1 = value * this->a1 + this->z2 - this->b1 * ret;
this->z2 = value * this->a2 - this->b2 * ret;
return ret;
}
} /* namespace flyhero */
#endif /* BIQUAD_FILTER_H_ */
|
/*
* Biquad_Filter.h
*
* Created on: 24. 6. 2017
* Author: michp
*/
#ifndef BIQUAD_FILTER_H_
#define BIQUAD_FILTER_H_
#include <cmath>
namespace flyhero {
// Many thanks to http://www.earlevel.com/main/2012/11/26/biquad-c-source-code/
class Biquad_Filter {
private:
const double PI = 3.14159265358979323846;
float a0, a1, a2;
float b1, b2;
float z1, z2;
public:
enum Filter_Type { FILTER_LOW_PASS, FILTER_NOTCH };
Biquad_Filter(Filter_Type type, float sample_frequency, float cut_frequency);
inline float Apply_Filter(float value);
};
// 10 us
// https://en.wikipedia.org/wiki/Digital_biquad_filter - Transposed direct forms
float Biquad_Filter::Apply_Filter(float value) {
float ret = value * this->a0 + this->z1;
this->z1 = value * this->a1 + this->z2 - this->b1 * ret;
this->z2 = value * this->a2 - this->b2 * ret;
return ret;
}
} /* namespace flyhero */
#endif /* BIQUAD_FILTER_H_ */
|
Add source of formulas used in biquad filters
|
Add source of formulas used in biquad filters
|
C
|
mit
|
michprev/flyhero-esp32,michprev/flyhero-esp32
|
c
|
## Code Before:
/*
* Biquad_Filter.h
*
* Created on: 24. 6. 2017
* Author: michp
*/
#ifndef BIQUAD_FILTER_H_
#define BIQUAD_FILTER_H_
#include <cmath>
namespace flyhero {
// Many thanks to http://www.earlevel.com/main/2012/11/26/biquad-c-source-code/
class Biquad_Filter {
private:
const double PI = 3.14159265358979323846;
float a0, a1, a2;
float b1, b2;
float z1, z2;
public:
enum Filter_Type { FILTER_LOW_PASS, FILTER_NOTCH };
Biquad_Filter(Filter_Type type, float sample_frequency, float cut_frequency);
inline float Apply_Filter(float value);
};
// 10 us
float Biquad_Filter::Apply_Filter(float value) {
float ret = value * this->a0 + this->z1;
this->z1 = value * this->a1 + this->z2 - this->b1 * ret;
this->z2 = value * this->a2 - this->b2 * ret;
return ret;
}
} /* namespace flyhero */
#endif /* BIQUAD_FILTER_H_ */
## Instruction:
Add source of formulas used in biquad filters
## Code After:
/*
* Biquad_Filter.h
*
* Created on: 24. 6. 2017
* Author: michp
*/
#ifndef BIQUAD_FILTER_H_
#define BIQUAD_FILTER_H_
#include <cmath>
namespace flyhero {
// Many thanks to http://www.earlevel.com/main/2012/11/26/biquad-c-source-code/
class Biquad_Filter {
private:
const double PI = 3.14159265358979323846;
float a0, a1, a2;
float b1, b2;
float z1, z2;
public:
enum Filter_Type { FILTER_LOW_PASS, FILTER_NOTCH };
Biquad_Filter(Filter_Type type, float sample_frequency, float cut_frequency);
inline float Apply_Filter(float value);
};
// 10 us
// https://en.wikipedia.org/wiki/Digital_biquad_filter - Transposed direct forms
float Biquad_Filter::Apply_Filter(float value) {
float ret = value * this->a0 + this->z1;
this->z1 = value * this->a1 + this->z2 - this->b1 * ret;
this->z2 = value * this->a2 - this->b2 * ret;
return ret;
}
} /* namespace flyhero */
#endif /* BIQUAD_FILTER_H_ */
|
// ... existing code ...
};
// 10 us
// https://en.wikipedia.org/wiki/Digital_biquad_filter - Transposed direct forms
float Biquad_Filter::Apply_Filter(float value) {
float ret = value * this->a0 + this->z1;
this->z1 = value * this->a1 + this->z2 - this->b1 * ret;
// ... rest of the code ...
|
db0be000a99e0dac7c9d37817cfd5000b7121ef3
|
stream/rest/views.py
|
stream/rest/views.py
|
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
import uuid
from dash.models import Post
from .serializers import PostSerializer
# Initially taken from
# http://www.django-rest-framework.org/tutorial/1-serialization/
class JSONResponse(HttpResponse):
"""
An HttpResponse that renders its content into JSON.
"""
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
@csrf_exempt
def post(request, pid=None):
"""
REST view of Post.
pid = Post id (uuid4)
"""
try:
uuid.UUID(pid)
except ValueError:
return HttpResponse(status=500) # Bad uuid = malformed client request
try:
post = Post.objects.get(id=pid)
except Post.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = PostSerializer(post)
return JSONResponse(serializer.data)
elif request.method == 'DELETE':
post.delete()
return HttpResponse(status=204)
|
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
import uuid
from dash.models import Post
from .serializers import PostSerializer
# Initially taken from
# http://www.django-rest-framework.org/tutorial/1-serialization/
class JSONResponse(HttpResponse):
"""
An HttpResponse that renders its content into JSON.
"""
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
@csrf_exempt
def post(request, pid=None):
"""
REST view of Post.
pid = Post id (uuid4)
"""
try:
uuid.UUID(pid)
except ValueError:
return HttpResponse(status=500) # Bad uuid = malformed client request
try:
post = Post.objects.get(id=pid)
except Post.DoesNotExist:
return HttpResponse(status=404)
except Post.MultipleObjectsReturned:
return HttpResponse(status=500) # Some how the UUID matched multiple
# posts
if request.method == 'GET':
serializer = PostSerializer(post)
return JSONResponse(serializer.data)
elif request.method == 'DELETE':
post.delete()
return HttpResponse(status=204)
|
Add multiple objects returned error.
|
Add multiple objects returned error.
|
Python
|
apache-2.0
|
CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project
|
python
|
## Code Before:
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
import uuid
from dash.models import Post
from .serializers import PostSerializer
# Initially taken from
# http://www.django-rest-framework.org/tutorial/1-serialization/
class JSONResponse(HttpResponse):
"""
An HttpResponse that renders its content into JSON.
"""
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
@csrf_exempt
def post(request, pid=None):
"""
REST view of Post.
pid = Post id (uuid4)
"""
try:
uuid.UUID(pid)
except ValueError:
return HttpResponse(status=500) # Bad uuid = malformed client request
try:
post = Post.objects.get(id=pid)
except Post.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = PostSerializer(post)
return JSONResponse(serializer.data)
elif request.method == 'DELETE':
post.delete()
return HttpResponse(status=204)
## Instruction:
Add multiple objects returned error.
## Code After:
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
import uuid
from dash.models import Post
from .serializers import PostSerializer
# Initially taken from
# http://www.django-rest-framework.org/tutorial/1-serialization/
class JSONResponse(HttpResponse):
"""
An HttpResponse that renders its content into JSON.
"""
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
@csrf_exempt
def post(request, pid=None):
"""
REST view of Post.
pid = Post id (uuid4)
"""
try:
uuid.UUID(pid)
except ValueError:
return HttpResponse(status=500) # Bad uuid = malformed client request
try:
post = Post.objects.get(id=pid)
except Post.DoesNotExist:
return HttpResponse(status=404)
except Post.MultipleObjectsReturned:
return HttpResponse(status=500) # Some how the UUID matched multiple
# posts
if request.method == 'GET':
serializer = PostSerializer(post)
return JSONResponse(serializer.data)
elif request.method == 'DELETE':
post.delete()
return HttpResponse(status=204)
|
# ... existing code ...
post = Post.objects.get(id=pid)
except Post.DoesNotExist:
return HttpResponse(status=404)
except Post.MultipleObjectsReturned:
return HttpResponse(status=500) # Some how the UUID matched multiple
# posts
if request.method == 'GET':
serializer = PostSerializer(post)
# ... rest of the code ...
|
97ecc9af061d3d58f697e8107d7761d365efe006
|
src/main/java/me/nithanim/mmf4j/Main.java
|
src/main/java/me/nithanim/mmf4j/Main.java
|
package me.nithanim.mmf4j;
import io.netty.buffer.ByteBuf;
import io.netty.util.CharsetUtil;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
MemoryMap mm = MemoryMapFactory.getInstance();
mm.openFile("./test.txt");
mm.openMapping(1000);
ByteBuf b = mm.mapView(20, 30);
b.writeBytes("Hallo".getBytes(CharsetUtil.UTF_8));
//mm.truncateFile(30);
b.writerIndex(0);
b.writeBytes("World".getBytes(CharsetUtil.UTF_8));
b.setBytes(0, "Java".getBytes(CharsetUtil.UTF_8));
ByteBuf c = b.copy();
c.setBytes(0, "AAAA".getBytes(CharsetUtil.UTF_8));
byte[] bytes = new byte[5];
b.getBytes(0, bytes);
System.out.println(new String(bytes, CharsetUtil.UTF_8));
b.release();
mm.truncateFile(25);
mm.resize(50);
mm.close();
}
}
|
package me.nithanim.mmf4j;
import com.sun.jna.Platform;
import io.netty.buffer.ByteBuf;
import io.netty.util.CharsetUtil;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
MemoryMap mm = MemoryMapFactory.getInstance();
mm.openFile(Platform.isWindows() ? "./test.txt" : "~/test.txt");
mm.openMapping(1000);
ByteBuf b = mm.mapView(20, 30);
b.writeBytes("Hallo".getBytes(CharsetUtil.UTF_8));
//mm.truncateFile(30);
b.writerIndex(0);
b.writeBytes("World".getBytes(CharsetUtil.UTF_8));
b.setBytes(0, "Java".getBytes(CharsetUtil.UTF_8));
ByteBuf c = b.copy();
c.setBytes(0, "AAAA".getBytes(CharsetUtil.UTF_8));
byte[] bytes = new byte[5];
b.getBytes(0, bytes);
System.out.println(new String(bytes, CharsetUtil.UTF_8));
b.release();
mm.truncateFile(25);
mm.resize(50);
mm.close();
}
}
|
Fix for my test environment for linux
|
Fix for my test environment for linux
|
Java
|
apache-2.0
|
Nithanim/mmf4j
|
java
|
## Code Before:
package me.nithanim.mmf4j;
import io.netty.buffer.ByteBuf;
import io.netty.util.CharsetUtil;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
MemoryMap mm = MemoryMapFactory.getInstance();
mm.openFile("./test.txt");
mm.openMapping(1000);
ByteBuf b = mm.mapView(20, 30);
b.writeBytes("Hallo".getBytes(CharsetUtil.UTF_8));
//mm.truncateFile(30);
b.writerIndex(0);
b.writeBytes("World".getBytes(CharsetUtil.UTF_8));
b.setBytes(0, "Java".getBytes(CharsetUtil.UTF_8));
ByteBuf c = b.copy();
c.setBytes(0, "AAAA".getBytes(CharsetUtil.UTF_8));
byte[] bytes = new byte[5];
b.getBytes(0, bytes);
System.out.println(new String(bytes, CharsetUtil.UTF_8));
b.release();
mm.truncateFile(25);
mm.resize(50);
mm.close();
}
}
## Instruction:
Fix for my test environment for linux
## Code After:
package me.nithanim.mmf4j;
import com.sun.jna.Platform;
import io.netty.buffer.ByteBuf;
import io.netty.util.CharsetUtil;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
MemoryMap mm = MemoryMapFactory.getInstance();
mm.openFile(Platform.isWindows() ? "./test.txt" : "~/test.txt");
mm.openMapping(1000);
ByteBuf b = mm.mapView(20, 30);
b.writeBytes("Hallo".getBytes(CharsetUtil.UTF_8));
//mm.truncateFile(30);
b.writerIndex(0);
b.writeBytes("World".getBytes(CharsetUtil.UTF_8));
b.setBytes(0, "Java".getBytes(CharsetUtil.UTF_8));
ByteBuf c = b.copy();
c.setBytes(0, "AAAA".getBytes(CharsetUtil.UTF_8));
byte[] bytes = new byte[5];
b.getBytes(0, bytes);
System.out.println(new String(bytes, CharsetUtil.UTF_8));
b.release();
mm.truncateFile(25);
mm.resize(50);
mm.close();
}
}
|
...
package me.nithanim.mmf4j;
import com.sun.jna.Platform;
import io.netty.buffer.ByteBuf;
import io.netty.util.CharsetUtil;
import java.io.IOException;
...
public class Main {
public static void main(String[] args) throws IOException {
MemoryMap mm = MemoryMapFactory.getInstance();
mm.openFile(Platform.isWindows() ? "./test.txt" : "~/test.txt");
mm.openMapping(1000);
ByteBuf b = mm.mapView(20, 30);
b.writeBytes("Hallo".getBytes(CharsetUtil.UTF_8));
...
|
3081fcd1e37520f504804a3efae62c33d3371a21
|
temba/msgs/migrations/0034_move_recording_domains.py
|
temba/msgs/migrations/0034_move_recording_domains.py
|
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('msgs', '0033_exportmessagestask_uuid'),
]
def move_recording_domains(apps, schema_editor):
Msg = apps.get_model('msgs', 'Msg')
# this is our new bucket name
bucket_name = settings.AWS_STORAGE_BUCKET_NAME
# our old bucket name had periods instead of dashes
old_bucket_domain = 'http://' + bucket_name.replace('-', '.')
# our new domain is more specific
new_bucket_domain = 'https://' + settings.AWS_BUCKET_DOMAIN
for msg in Msg.objects.filter(msg_type='V').exclude(recording_url=None):
# if our recording URL is on our old bucket
if msg.recording_url.find(old_bucket_domain) >= 0:
# rename it to our new bucket
old_recording_url = msg.recording_url
msg.recording_url = msg.recording_url.replace(old_bucket_domain,
new_bucket_domain)
print "[%d] %s to %s" % (msg.id, old_recording_url, msg.recording_url)
msg.save(update_fields=['recording_url'])
operations = [
migrations.RunPython(move_recording_domains)
]
|
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('msgs', '0033_exportmessagestask_uuid'),
]
def move_recording_domains(apps, schema_editor):
Msg = apps.get_model('msgs', 'Msg')
# this is our new bucket name
bucket_name = settings.AWS_STORAGE_BUCKET_NAME
# our old bucket name had periods instead of dashes
old_bucket_domain = 'http://' + bucket_name.replace('-', '.')
# our new domain is more specific
new_bucket_domain = 'https://' + settings.AWS_BUCKET_DOMAIN
for msg in Msg.objects.filter(direction='I', msg_type='V').exclude(recording_url=None):
# if our recording URL is on our old bucket
if msg.recording_url.find(old_bucket_domain) >= 0:
# rename it to our new bucket
old_recording_url = msg.recording_url
msg.recording_url = msg.recording_url.replace(old_bucket_domain,
new_bucket_domain)
print "[%d] %s to %s" % (msg.id, old_recording_url, msg.recording_url)
msg.save(update_fields=['recording_url'])
operations = [
migrations.RunPython(move_recording_domains)
]
|
Tweak to migration so it is a bit faster for future migraters
|
Tweak to migration so it is a bit faster for future migraters
|
Python
|
agpl-3.0
|
tsotetsi/textily-web,tsotetsi/textily-web,pulilab/rapidpro,praekelt/rapidpro,ewheeler/rapidpro,reyrodrigues/EU-SMS,reyrodrigues/EU-SMS,ewheeler/rapidpro,reyrodrigues/EU-SMS,tsotetsi/textily-web,tsotetsi/textily-web,pulilab/rapidpro,praekelt/rapidpro,tsotetsi/textily-web,praekelt/rapidpro,pulilab/rapidpro,ewheeler/rapidpro,pulilab/rapidpro,praekelt/rapidpro,ewheeler/rapidpro,pulilab/rapidpro
|
python
|
## Code Before:
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('msgs', '0033_exportmessagestask_uuid'),
]
def move_recording_domains(apps, schema_editor):
Msg = apps.get_model('msgs', 'Msg')
# this is our new bucket name
bucket_name = settings.AWS_STORAGE_BUCKET_NAME
# our old bucket name had periods instead of dashes
old_bucket_domain = 'http://' + bucket_name.replace('-', '.')
# our new domain is more specific
new_bucket_domain = 'https://' + settings.AWS_BUCKET_DOMAIN
for msg in Msg.objects.filter(msg_type='V').exclude(recording_url=None):
# if our recording URL is on our old bucket
if msg.recording_url.find(old_bucket_domain) >= 0:
# rename it to our new bucket
old_recording_url = msg.recording_url
msg.recording_url = msg.recording_url.replace(old_bucket_domain,
new_bucket_domain)
print "[%d] %s to %s" % (msg.id, old_recording_url, msg.recording_url)
msg.save(update_fields=['recording_url'])
operations = [
migrations.RunPython(move_recording_domains)
]
## Instruction:
Tweak to migration so it is a bit faster for future migraters
## Code After:
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('msgs', '0033_exportmessagestask_uuid'),
]
def move_recording_domains(apps, schema_editor):
Msg = apps.get_model('msgs', 'Msg')
# this is our new bucket name
bucket_name = settings.AWS_STORAGE_BUCKET_NAME
# our old bucket name had periods instead of dashes
old_bucket_domain = 'http://' + bucket_name.replace('-', '.')
# our new domain is more specific
new_bucket_domain = 'https://' + settings.AWS_BUCKET_DOMAIN
for msg in Msg.objects.filter(direction='I', msg_type='V').exclude(recording_url=None):
# if our recording URL is on our old bucket
if msg.recording_url.find(old_bucket_domain) >= 0:
# rename it to our new bucket
old_recording_url = msg.recording_url
msg.recording_url = msg.recording_url.replace(old_bucket_domain,
new_bucket_domain)
print "[%d] %s to %s" % (msg.id, old_recording_url, msg.recording_url)
msg.save(update_fields=['recording_url'])
operations = [
migrations.RunPython(move_recording_domains)
]
|
// ... existing code ...
# our new domain is more specific
new_bucket_domain = 'https://' + settings.AWS_BUCKET_DOMAIN
for msg in Msg.objects.filter(direction='I', msg_type='V').exclude(recording_url=None):
# if our recording URL is on our old bucket
if msg.recording_url.find(old_bucket_domain) >= 0:
# rename it to our new bucket
// ... rest of the code ...
|
12b181b585a54301c92103aa6ee979b628b76b59
|
examples/crontabReader.py
|
examples/crontabReader.py
|
from cron_descriptor import Options, ExpressionDescriptor
import re
class CrontabReader(object):
"""
Simple example reading /etc/contab
"""
rex = re.compile("^(\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}).+$")
def __init__(self, cronfile):
"""Initialize CrontabReader
Args:
cronfile: Path to cronfile
Returns:
None
"""
options = Options()
options.day_of_week_start_index_zero = False
options.use_24hour_time_format = True
with open(cronfile) as f:
for line in f.readlines():
parsed_line = self.parse_cron_line(line)
if parsed_line:
print("{} -> {}".format(parsed_line, ExpressionDescriptor(parsed_line, options)))
def parse_cron_line(self, line):
"""Parses crontab line and returns only starting time string
Args:
line: crontab line
Returns:
Time part of cron line
"""
stripped = line.strip()
if stripped and stripped.startswith('#') is False:
rexres = self.rex.search(stripped)
if rexres:
return ' '.join(rexres.group(1).split())
return None
CrontabReader('/etc/crontab')
|
import re
try:
from cron_descriptor import Options, ExpressionDescriptor
except ImportError:
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('\033[1mFailed to import cron_descriptor, maybe ? "pip install cron-descriptor ?"\033[0m')
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
raise
class CrontabReader(object):
"""
Simple example reading /etc/contab
"""
rex = re.compile("^(\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}).+$")
def __init__(self, cronfile):
"""Initialize CrontabReader
Args:
cronfile: Path to cronfile
Returns:
None
"""
options = Options()
options.day_of_week_start_index_zero = False
options.use_24hour_time_format = True
with open(cronfile) as f:
for line in f.readlines():
parsed_line = self.parse_cron_line(line)
if parsed_line:
print("{} -> {}".format(parsed_line, ExpressionDescriptor(parsed_line, options)))
def parse_cron_line(self, line):
"""Parses crontab line and returns only starting time string
Args:
line: crontab line
Returns:
Time part of cron line
"""
stripped = line.strip()
if stripped and stripped.startswith('#') is False:
rexres = self.rex.search(stripped)
if rexres:
return ' '.join(rexres.group(1).split())
return None
CrontabReader('/etc/crontab')
|
Add import error message to example
|
Add import error message to example
|
Python
|
mit
|
Salamek/cron-descriptor,Salamek/cron-descriptor
|
python
|
## Code Before:
from cron_descriptor import Options, ExpressionDescriptor
import re
class CrontabReader(object):
"""
Simple example reading /etc/contab
"""
rex = re.compile("^(\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}).+$")
def __init__(self, cronfile):
"""Initialize CrontabReader
Args:
cronfile: Path to cronfile
Returns:
None
"""
options = Options()
options.day_of_week_start_index_zero = False
options.use_24hour_time_format = True
with open(cronfile) as f:
for line in f.readlines():
parsed_line = self.parse_cron_line(line)
if parsed_line:
print("{} -> {}".format(parsed_line, ExpressionDescriptor(parsed_line, options)))
def parse_cron_line(self, line):
"""Parses crontab line and returns only starting time string
Args:
line: crontab line
Returns:
Time part of cron line
"""
stripped = line.strip()
if stripped and stripped.startswith('#') is False:
rexres = self.rex.search(stripped)
if rexres:
return ' '.join(rexres.group(1).split())
return None
CrontabReader('/etc/crontab')
## Instruction:
Add import error message to example
## Code After:
import re
try:
from cron_descriptor import Options, ExpressionDescriptor
except ImportError:
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('\033[1mFailed to import cron_descriptor, maybe ? "pip install cron-descriptor ?"\033[0m')
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
raise
class CrontabReader(object):
"""
Simple example reading /etc/contab
"""
rex = re.compile("^(\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}).+$")
def __init__(self, cronfile):
"""Initialize CrontabReader
Args:
cronfile: Path to cronfile
Returns:
None
"""
options = Options()
options.day_of_week_start_index_zero = False
options.use_24hour_time_format = True
with open(cronfile) as f:
for line in f.readlines():
parsed_line = self.parse_cron_line(line)
if parsed_line:
print("{} -> {}".format(parsed_line, ExpressionDescriptor(parsed_line, options)))
def parse_cron_line(self, line):
"""Parses crontab line and returns only starting time string
Args:
line: crontab line
Returns:
Time part of cron line
"""
stripped = line.strip()
if stripped and stripped.startswith('#') is False:
rexres = self.rex.search(stripped)
if rexres:
return ' '.join(rexres.group(1).split())
return None
CrontabReader('/etc/crontab')
|
...
import re
try:
from cron_descriptor import Options, ExpressionDescriptor
except ImportError:
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('\033[1mFailed to import cron_descriptor, maybe ? "pip install cron-descriptor ?"\033[0m')
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
raise
class CrontabReader(object):
...
|
c97339e3a121c48ec3eed38e1bf901e2bf1d323c
|
src/proposals/resources.py
|
src/proposals/resources.py
|
from import_export import fields, resources
from .models import TalkProposal
class TalkProposalResource(resources.ModelResource):
name = fields.Field(attribute='submitter__speaker_name')
email = fields.Field(attribute='submitter__email')
class Meta:
model = TalkProposal
fields = [
'id', 'title', 'category', 'python_level', 'duration',
'name', 'email',
]
export_order = fields
|
from import_export import fields, resources
from .models import TalkProposal
class TalkProposalResource(resources.ModelResource):
name = fields.Field(attribute='submitter__speaker_name')
email = fields.Field(attribute='submitter__email')
class Meta:
model = TalkProposal
fields = [
'id', 'title', 'category', 'python_level', 'duration',
'language', 'name', 'email',
]
export_order = fields
|
Add language field to proposal export
|
Add language field to proposal export
|
Python
|
mit
|
pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016
|
python
|
## Code Before:
from import_export import fields, resources
from .models import TalkProposal
class TalkProposalResource(resources.ModelResource):
name = fields.Field(attribute='submitter__speaker_name')
email = fields.Field(attribute='submitter__email')
class Meta:
model = TalkProposal
fields = [
'id', 'title', 'category', 'python_level', 'duration',
'name', 'email',
]
export_order = fields
## Instruction:
Add language field to proposal export
## Code After:
from import_export import fields, resources
from .models import TalkProposal
class TalkProposalResource(resources.ModelResource):
name = fields.Field(attribute='submitter__speaker_name')
email = fields.Field(attribute='submitter__email')
class Meta:
model = TalkProposal
fields = [
'id', 'title', 'category', 'python_level', 'duration',
'language', 'name', 'email',
]
export_order = fields
|
...
model = TalkProposal
fields = [
'id', 'title', 'category', 'python_level', 'duration',
'language', 'name', 'email',
]
export_order = fields
...
|
7f2df3979458df73e4e3f0a9fdcb16905960de81
|
_config.py
|
_config.py
|
AWS_KEY = 'REQUIRED'
AWS_SECRET_KEY = 'REQUIRED'
AWS_BUCKET = 'REQUIRED'
AWS_DIRECTORY = '' # Leave blank *not false* unless project not at base URL
# i.e. example.com/apps/ instead of example.com/
# Cache Settings (units in seconds)
STATIC_EXPIRES = 60 * 24 * 3600
HTML_EXPIRES = 3600
# Upload Settings (ignores anything included below)
IGNORE_DIRECTORIES = ['.git', 'venv', 'sass', 'templates']
IGNORE_FILES = ['.DS_Store']
IGNORE_FILE_TYPES = ['.gz', '.pyc', '.py', '.rb', '.md']
|
FREEZER_DEFAULT_MIMETYPE = 'text/html'
FREEZER_IGNORE_MIMETYPE_WARNINGS = True
# Amazon S3 Settings
AWS_KEY = ''
AWS_SECRET_KEY = ''
AWS_BUCKET = ''
AWS_DIRECTORY = '' # Use if S3 bucket is not root
# Cache Settings (units in seconds)
STATIC_EXPIRES = 60 * 24 * 3600
HTML_EXPIRES = 3600
# Upload Settings (ignores anything included below)
IGNORE_DIRECTORIES = ['.git', 'venv', 'sass', 'templates']
IGNORE_FILES = ['.DS_Store']
IGNORE_FILE_TYPES = ['.gz', '.pyc', '.py', '.rb', '.md']
if AWS_DIRECTORY:
BASE_URL = 'http://' + AWS_BUCKET + '/' + AWS_DIRECTORY
FREEZER_BASE_URL = BASE_URL
else:
BASE_URL = 'http://' + AWS_BUCKET
|
Update settings for new configuration
|
Update settings for new configuration
|
Python
|
apache-2.0
|
vprnet/EOTS-iframe-widget,vprnet/app-template,vprnet/live-from-the-fort,vprnet/timeline-dcf-systemic-failure,vprnet/app-template,vprnet/old-app-template,vprnet/app-template,vprnet/interactive-transcript-gov-peter-shumlins-third-inaugural-address,vprnet/soundcloud-podcast,vprnet/interactive-transcript-gov-peter-shumlins-2015-budget-speech,vprnet/interactive-transcript-gov-peter-shumlins-2015-budget-speech,vprnet/old-app-template,vprnet/EOTS-iframe-widget,vprnet/EOTS-iframe-widget,vprnet/interactive-transcript-gov-peter-shumlins-third-inaugural-address,vprnet/live-from-the-fort,vprnet/timeline-dcf-systemic-failure,vprnet/google-s3-json,vprnet/live-from-the-fort
|
python
|
## Code Before:
AWS_KEY = 'REQUIRED'
AWS_SECRET_KEY = 'REQUIRED'
AWS_BUCKET = 'REQUIRED'
AWS_DIRECTORY = '' # Leave blank *not false* unless project not at base URL
# i.e. example.com/apps/ instead of example.com/
# Cache Settings (units in seconds)
STATIC_EXPIRES = 60 * 24 * 3600
HTML_EXPIRES = 3600
# Upload Settings (ignores anything included below)
IGNORE_DIRECTORIES = ['.git', 'venv', 'sass', 'templates']
IGNORE_FILES = ['.DS_Store']
IGNORE_FILE_TYPES = ['.gz', '.pyc', '.py', '.rb', '.md']
## Instruction:
Update settings for new configuration
## Code After:
FREEZER_DEFAULT_MIMETYPE = 'text/html'
FREEZER_IGNORE_MIMETYPE_WARNINGS = True
# Amazon S3 Settings
AWS_KEY = ''
AWS_SECRET_KEY = ''
AWS_BUCKET = ''
AWS_DIRECTORY = '' # Use if S3 bucket is not root
# Cache Settings (units in seconds)
STATIC_EXPIRES = 60 * 24 * 3600
HTML_EXPIRES = 3600
# Upload Settings (ignores anything included below)
IGNORE_DIRECTORIES = ['.git', 'venv', 'sass', 'templates']
IGNORE_FILES = ['.DS_Store']
IGNORE_FILE_TYPES = ['.gz', '.pyc', '.py', '.rb', '.md']
if AWS_DIRECTORY:
BASE_URL = 'http://' + AWS_BUCKET + '/' + AWS_DIRECTORY
FREEZER_BASE_URL = BASE_URL
else:
BASE_URL = 'http://' + AWS_BUCKET
|
...
FREEZER_DEFAULT_MIMETYPE = 'text/html'
FREEZER_IGNORE_MIMETYPE_WARNINGS = True
# Amazon S3 Settings
AWS_KEY = ''
AWS_SECRET_KEY = ''
AWS_BUCKET = ''
AWS_DIRECTORY = '' # Use if S3 bucket is not root
# Cache Settings (units in seconds)
STATIC_EXPIRES = 60 * 24 * 3600
...
IGNORE_DIRECTORIES = ['.git', 'venv', 'sass', 'templates']
IGNORE_FILES = ['.DS_Store']
IGNORE_FILE_TYPES = ['.gz', '.pyc', '.py', '.rb', '.md']
if AWS_DIRECTORY:
BASE_URL = 'http://' + AWS_BUCKET + '/' + AWS_DIRECTORY
FREEZER_BASE_URL = BASE_URL
else:
BASE_URL = 'http://' + AWS_BUCKET
...
|
e1985056a11ca3fff3896d2e4126b6cdf048336d
|
scrape_affiliation.py
|
scrape_affiliation.py
|
import requests
from lxml import html, etree
def scrape_acm(page):
tree = html.fromstring(page.content)
author_affiliations = []
authors = tree.xpath('//td/a[@title="Author Profile Page"]')
for a in authors:
affiliation = a.getparent().getnext().find("a/small")
# If we don't find it under a URL it's likely just a <small>
if affiliation == None:
affiliation = a.getparent().getnext().find("small")
if affiliation:
affiliation = affiliation.text
else:
affiliation = "None"
author_affiliations.append(affiliation)
return author_affiliations
# Returns an array of the author affilations, ordered by the author appearance list on the paper
# e.g. first author, second author, etc. This is done because we can't assume the names in the DBLP
# database exactly match the names shown on the webpage.
def scrape_affiliation(doi):
# The doi urls are typically just http://dx.doi.org/... and we get the actual publication host
# by following the redirect, so we must hit the page before we know if we can handle the URL
# or not.
page = requests.get(doi)
if page.url.startswith("http://dl.acm.org/"):
return scrape_acm(page)
print("Error! Unhandled Journal Site {}".format(page.url))
return None
|
import requests
from lxml import html, etree
def scrape_acm(page):
tree = html.fromstring(page.content)
author_affiliations = []
# The ACM author affiliations are stored in a kind of nasty table layout,
# best to view source or inspect element on their page for an explanation of this.
authors = tree.xpath('//td/a[@title="Author Profile Page"]')
for a in authors:
affiliation = a.getparent().getnext().find("a/small")
# If we don't find it under a URL it's likely just a <small>
if affiliation == None:
affiliation = a.getparent().getnext().find("small")
if affiliation:
affiliation = affiliation.text
else:
affiliation = "None"
author_affiliations.append(affiliation)
return author_affiliations
# Returns an array of the author affilations, ordered by the author appearance list on the paper
# e.g. first author, second author, etc. This is done because we can't assume the names in the DBLP
# database exactly match the names shown on the webpage.
def scrape_affiliation(doi):
# The doi urls are typically just http://dx.doi.org/... and we get the actual publication host
# by following the redirect, so we must hit the page before we know if we can handle the URL
# or not.
page = requests.get(doi)
if page.url.startswith("http://dl.acm.org/"):
return scrape_acm(page)
print("Warning! Unhandled Journal Site {}".format(page.url))
return None
|
Add comment on ACM affil structure
|
Add comment on ACM affil structure
|
Python
|
mit
|
Twinklebear/dataviscourse-pr-collaboration-networks,Twinklebear/dataviscourse-pr-collaboration-networks,Twinklebear/dataviscourse-pr-collaboration-networks
|
python
|
## Code Before:
import requests
from lxml import html, etree
def scrape_acm(page):
tree = html.fromstring(page.content)
author_affiliations = []
authors = tree.xpath('//td/a[@title="Author Profile Page"]')
for a in authors:
affiliation = a.getparent().getnext().find("a/small")
# If we don't find it under a URL it's likely just a <small>
if affiliation == None:
affiliation = a.getparent().getnext().find("small")
if affiliation:
affiliation = affiliation.text
else:
affiliation = "None"
author_affiliations.append(affiliation)
return author_affiliations
# Returns an array of the author affilations, ordered by the author appearance list on the paper
# e.g. first author, second author, etc. This is done because we can't assume the names in the DBLP
# database exactly match the names shown on the webpage.
def scrape_affiliation(doi):
# The doi urls are typically just http://dx.doi.org/... and we get the actual publication host
# by following the redirect, so we must hit the page before we know if we can handle the URL
# or not.
page = requests.get(doi)
if page.url.startswith("http://dl.acm.org/"):
return scrape_acm(page)
print("Error! Unhandled Journal Site {}".format(page.url))
return None
## Instruction:
Add comment on ACM affil structure
## Code After:
import requests
from lxml import html, etree
def scrape_acm(page):
tree = html.fromstring(page.content)
author_affiliations = []
# The ACM author affiliations are stored in a kind of nasty table layout,
# best to view source or inspect element on their page for an explanation of this.
authors = tree.xpath('//td/a[@title="Author Profile Page"]')
for a in authors:
affiliation = a.getparent().getnext().find("a/small")
# If we don't find it under a URL it's likely just a <small>
if affiliation == None:
affiliation = a.getparent().getnext().find("small")
if affiliation:
affiliation = affiliation.text
else:
affiliation = "None"
author_affiliations.append(affiliation)
return author_affiliations
# Returns an array of the author affilations, ordered by the author appearance list on the paper
# e.g. first author, second author, etc. This is done because we can't assume the names in the DBLP
# database exactly match the names shown on the webpage.
def scrape_affiliation(doi):
# The doi urls are typically just http://dx.doi.org/... and we get the actual publication host
# by following the redirect, so we must hit the page before we know if we can handle the URL
# or not.
page = requests.get(doi)
if page.url.startswith("http://dl.acm.org/"):
return scrape_acm(page)
print("Warning! Unhandled Journal Site {}".format(page.url))
return None
|
// ... existing code ...
def scrape_acm(page):
tree = html.fromstring(page.content)
author_affiliations = []
# The ACM author affiliations are stored in a kind of nasty table layout,
# best to view source or inspect element on their page for an explanation of this.
authors = tree.xpath('//td/a[@title="Author Profile Page"]')
for a in authors:
affiliation = a.getparent().getnext().find("a/small")
// ... modified code ...
page = requests.get(doi)
if page.url.startswith("http://dl.acm.org/"):
return scrape_acm(page)
print("Warning! Unhandled Journal Site {}".format(page.url))
return None
// ... rest of the code ...
|
43b8e4de31d0659561ffedfeb0ab4a42f035eade
|
dev/test_all.py
|
dev/test_all.py
|
"""Runs various tests in the repository."""
import argparse
import subprocess
import repo_util
def main(argv):
root = "//third_party/java_src/j2cl/"
cmd = ["blaze", "test", "--keep_going"]
cmd += [root + t + "/..." for t in argv.test_pattern] or [root + "..."]
cmd += repo_util.create_test_filter(argv.platforms)
subprocess.call(cmd)
def add_arguments(parser):
parser.add_argument(
"test_pattern",
metavar="<root>",
nargs="*",
help="test root(s). e.g. transpiler jre")
def run_for_presubmit():
argv = argparse.Namespace(test_pattern=[])
main(argv)
|
"""Runs various tests in the repository."""
import argparse
import subprocess
import repo_util
def main(argv):
root = "//third_party/java_src/j2cl/"
cmd = ["blaze", "test", "--test_tag_filters=-chamber", "--keep_going"]
cmd += [root + t + "/..." for t in argv.test_pattern] or [root + "..."]
cmd += repo_util.create_test_filter(argv.platforms)
subprocess.call(cmd)
def add_arguments(parser):
parser.add_argument(
"test_pattern",
metavar="<root>",
nargs="*",
help="test root(s). e.g. transpiler jre")
def run_for_presubmit():
argv = argparse.Namespace(test_pattern=[])
main(argv)
|
Exclude chamber workflow from targets tested by j2 testall
|
Exclude chamber workflow from targets tested by j2 testall
PiperOrigin-RevId: 384424406
|
Python
|
apache-2.0
|
google/j2cl,google/j2cl,google/j2cl,google/j2cl,google/j2cl
|
python
|
## Code Before:
"""Runs various tests in the repository."""
import argparse
import subprocess
import repo_util
def main(argv):
root = "//third_party/java_src/j2cl/"
cmd = ["blaze", "test", "--keep_going"]
cmd += [root + t + "/..." for t in argv.test_pattern] or [root + "..."]
cmd += repo_util.create_test_filter(argv.platforms)
subprocess.call(cmd)
def add_arguments(parser):
parser.add_argument(
"test_pattern",
metavar="<root>",
nargs="*",
help="test root(s). e.g. transpiler jre")
def run_for_presubmit():
argv = argparse.Namespace(test_pattern=[])
main(argv)
## Instruction:
Exclude chamber workflow from targets tested by j2 testall
PiperOrigin-RevId: 384424406
## Code After:
"""Runs various tests in the repository."""
import argparse
import subprocess
import repo_util
def main(argv):
root = "//third_party/java_src/j2cl/"
cmd = ["blaze", "test", "--test_tag_filters=-chamber", "--keep_going"]
cmd += [root + t + "/..." for t in argv.test_pattern] or [root + "..."]
cmd += repo_util.create_test_filter(argv.platforms)
subprocess.call(cmd)
def add_arguments(parser):
parser.add_argument(
"test_pattern",
metavar="<root>",
nargs="*",
help="test root(s). e.g. transpiler jre")
def run_for_presubmit():
argv = argparse.Namespace(test_pattern=[])
main(argv)
|
...
def main(argv):
root = "//third_party/java_src/j2cl/"
cmd = ["blaze", "test", "--test_tag_filters=-chamber", "--keep_going"]
cmd += [root + t + "/..." for t in argv.test_pattern] or [root + "..."]
cmd += repo_util.create_test_filter(argv.platforms)
subprocess.call(cmd)
...
|
f0f341cd89f31443aae55eb4dfb092e24a22c6a6
|
src/main/java/se/kits/gakusei/content/repository/LessonRepository.java
|
src/main/java/se/kits/gakusei/content/repository/LessonRepository.java
|
package se.kits.gakusei.content.repository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import se.kits.gakusei.content.model.Lesson;
import se.kits.gakusei.content.model.Nugget;
import java.util.List;
public interface LessonRepository extends CrudRepository<Lesson, Long> {
Lesson findByName(String name);
List<Nugget> findNuggetsByTwoFactTypes(
@Param("lessonName") String lessonName,
@Param("factType1") String questionType,
@Param("factType2") String answerType);
List<Nugget> findNuggetsBySuccessrate(
@Param("username") String username,
@Param("lessonName") String lessonName,
@Param("factType1") String questionType,
@Param("factType2") String answerType);
List<Nugget> findUnansweredNuggets(
@Param("username") String username,
@Param("lessonName") String lessonName,
@Param("factType1") String questionType,
@Param("factType2") String answerType);
@Query("select l from Lesson l where not l.description = 'quiz'")
List<Lesson> findVocabularyLessons();
@Query("select l from Lesson l where l.description = 'quiz'")
List<Lesson> findQuizLessons();
}
|
package se.kits.gakusei.content.repository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import se.kits.gakusei.content.model.Lesson;
import se.kits.gakusei.content.model.Nugget;
import java.util.List;
public interface LessonRepository extends CrudRepository<Lesson, Long> {
Lesson findByName(String name);
List<Nugget> findNuggetsByTwoFactTypes(
@Param("lessonName") String lessonName,
@Param("factType1") String questionType,
@Param("factType2") String answerType);
List<Nugget> findNuggetsBySuccessrate(
@Param("username") String username,
@Param("lessonName") String lessonName,
@Param("factType1") String questionType,
@Param("factType2") String answerType);
List<Nugget> findUnansweredNuggets(
@Param("username") String username,
@Param("lessonName") String lessonName,
@Param("factType1") String questionType,
@Param("factType2") String answerType);
@Query("select l from Lesson l where not l.description = 'quiz' order by l.name")
List<Lesson> findVocabularyLessons();
@Query("select l from Lesson l where l.description = 'quiz' order by l.name")
List<Lesson> findQuizLessons();
}
|
Sort lessons by name when retrieving from db
|
Sort lessons by name when retrieving from db
|
Java
|
mit
|
kits-ab/gakusei,kits-ab/gakusei,kits-ab/gakusei
|
java
|
## Code Before:
package se.kits.gakusei.content.repository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import se.kits.gakusei.content.model.Lesson;
import se.kits.gakusei.content.model.Nugget;
import java.util.List;
public interface LessonRepository extends CrudRepository<Lesson, Long> {
Lesson findByName(String name);
List<Nugget> findNuggetsByTwoFactTypes(
@Param("lessonName") String lessonName,
@Param("factType1") String questionType,
@Param("factType2") String answerType);
List<Nugget> findNuggetsBySuccessrate(
@Param("username") String username,
@Param("lessonName") String lessonName,
@Param("factType1") String questionType,
@Param("factType2") String answerType);
List<Nugget> findUnansweredNuggets(
@Param("username") String username,
@Param("lessonName") String lessonName,
@Param("factType1") String questionType,
@Param("factType2") String answerType);
@Query("select l from Lesson l where not l.description = 'quiz'")
List<Lesson> findVocabularyLessons();
@Query("select l from Lesson l where l.description = 'quiz'")
List<Lesson> findQuizLessons();
}
## Instruction:
Sort lessons by name when retrieving from db
## Code After:
package se.kits.gakusei.content.repository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import se.kits.gakusei.content.model.Lesson;
import se.kits.gakusei.content.model.Nugget;
import java.util.List;
public interface LessonRepository extends CrudRepository<Lesson, Long> {
Lesson findByName(String name);
List<Nugget> findNuggetsByTwoFactTypes(
@Param("lessonName") String lessonName,
@Param("factType1") String questionType,
@Param("factType2") String answerType);
List<Nugget> findNuggetsBySuccessrate(
@Param("username") String username,
@Param("lessonName") String lessonName,
@Param("factType1") String questionType,
@Param("factType2") String answerType);
List<Nugget> findUnansweredNuggets(
@Param("username") String username,
@Param("lessonName") String lessonName,
@Param("factType1") String questionType,
@Param("factType2") String answerType);
@Query("select l from Lesson l where not l.description = 'quiz' order by l.name")
List<Lesson> findVocabularyLessons();
@Query("select l from Lesson l where l.description = 'quiz' order by l.name")
List<Lesson> findQuizLessons();
}
|
...
@Param("factType1") String questionType,
@Param("factType2") String answerType);
@Query("select l from Lesson l where not l.description = 'quiz' order by l.name")
List<Lesson> findVocabularyLessons();
@Query("select l from Lesson l where l.description = 'quiz' order by l.name")
List<Lesson> findQuizLessons();
}
...
|
25b35032828593af3220b4310e6a5bd65f90d197
|
db/editdbfile.py
|
db/editdbfile.py
|
import os
import sys
import json
import getpass
import tempfile
import subprocess
import aespckfile
import aesjsonfile
def editfile(fn, password):
filetype = aespckfile
if ".json" in fn:
filetype = aesjsonfile
db = filetype.load(fn, password)
f = tempfile.NamedTemporaryFile()
json.dump(db, f, indent=2)
f.flush()
while True:
subprocess.call([os.getenv("EDITOR") or "editor", f.name])
try:
f.seek(0)
db = json.load(f)
filetype.dump(fn, db, password)
break
except Exception, e:
print "Error in json"
print e
print "Try again (y/n)? ",
input = raw_input()
if not input.lower().startswith("y"):
break
f.seek(0,2)
len = f.tell()
f.seek(0)
f.write(" " * len)
f.flush()
f.close()
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.exit(1)
fn = sys.argv[1]
password = getpass.getpass()
editfile(fn, password)
|
import os
import sys
import json
import getpass
import tempfile
import subprocess
import aespckfile
import aesjsonfile
def editfile(fn, password):
filetype = aespckfile
if ".json" in fn:
filetype = aesjsonfile
db = filetype.load(fn, password)
f = tempfile.NamedTemporaryFile()
json.dump(db, f, indent=2)
f.flush()
mtime = os.path.getmtime(f.name)
while True:
subprocess.call([os.getenv("EDITOR") or "editor", f.name])
if os.path.getmtime(f.name) == mtime:
print "Not updated"
break
try:
f.seek(0)
db = json.load(f)
filetype.dump(fn, db, password)
break
except Exception, e:
print "Error in json"
print e
print "Try again (y/n)? ",
input = raw_input()
if not input.lower().startswith("y"):
break
# Over-write our temp file
f.seek(0,2)
len = f.tell()
f.seek(0)
f.write(" " * len)
f.flush()
f.close()
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.exit(1)
fn = sys.argv[1]
password = getpass.getpass()
editfile(fn, password)
|
Check mtime to see if we need to write out new db file.
|
Check mtime to see if we need to write out new db file.
|
Python
|
agpl-3.0
|
vincebusam/pyWebCash,vincebusam/pyWebCash,vincebusam/pyWebCash
|
python
|
## Code Before:
import os
import sys
import json
import getpass
import tempfile
import subprocess
import aespckfile
import aesjsonfile
def editfile(fn, password):
filetype = aespckfile
if ".json" in fn:
filetype = aesjsonfile
db = filetype.load(fn, password)
f = tempfile.NamedTemporaryFile()
json.dump(db, f, indent=2)
f.flush()
while True:
subprocess.call([os.getenv("EDITOR") or "editor", f.name])
try:
f.seek(0)
db = json.load(f)
filetype.dump(fn, db, password)
break
except Exception, e:
print "Error in json"
print e
print "Try again (y/n)? ",
input = raw_input()
if not input.lower().startswith("y"):
break
f.seek(0,2)
len = f.tell()
f.seek(0)
f.write(" " * len)
f.flush()
f.close()
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.exit(1)
fn = sys.argv[1]
password = getpass.getpass()
editfile(fn, password)
## Instruction:
Check mtime to see if we need to write out new db file.
## Code After:
import os
import sys
import json
import getpass
import tempfile
import subprocess
import aespckfile
import aesjsonfile
def editfile(fn, password):
filetype = aespckfile
if ".json" in fn:
filetype = aesjsonfile
db = filetype.load(fn, password)
f = tempfile.NamedTemporaryFile()
json.dump(db, f, indent=2)
f.flush()
mtime = os.path.getmtime(f.name)
while True:
subprocess.call([os.getenv("EDITOR") or "editor", f.name])
if os.path.getmtime(f.name) == mtime:
print "Not updated"
break
try:
f.seek(0)
db = json.load(f)
filetype.dump(fn, db, password)
break
except Exception, e:
print "Error in json"
print e
print "Try again (y/n)? ",
input = raw_input()
if not input.lower().startswith("y"):
break
# Over-write our temp file
f.seek(0,2)
len = f.tell()
f.seek(0)
f.write(" " * len)
f.flush()
f.close()
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.exit(1)
fn = sys.argv[1]
password = getpass.getpass()
editfile(fn, password)
|
# ... existing code ...
f = tempfile.NamedTemporaryFile()
json.dump(db, f, indent=2)
f.flush()
mtime = os.path.getmtime(f.name)
while True:
subprocess.call([os.getenv("EDITOR") or "editor", f.name])
if os.path.getmtime(f.name) == mtime:
print "Not updated"
break
try:
f.seek(0)
db = json.load(f)
# ... modified code ...
input = raw_input()
if not input.lower().startswith("y"):
break
# Over-write our temp file
f.seek(0,2)
len = f.tell()
f.seek(0)
# ... rest of the code ...
|
366937921cfb13fd83fb5964d0373be48e3c8564
|
cmsplugin_plain_text/models.py
|
cmsplugin_plain_text/models.py
|
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Plaintext(CMSPlugin):
body = models.TextField(_('Plaintext'))
def __unicode__(self):
return self.body
|
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Plaintext(CMSPlugin):
body = models.TextField(_('Plaintext'))
def __unicode__(self):
return self.body
def __str__(self):
return self.body
|
Add `__str__` method to support Python 3
|
Add `__str__` method to support Python 3
|
Python
|
bsd-3-clause
|
chschuermann/cmsplugin-plain-text,chschuermann/cmsplugin-plain-text
|
python
|
## Code Before:
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Plaintext(CMSPlugin):
body = models.TextField(_('Plaintext'))
def __unicode__(self):
return self.body
## Instruction:
Add `__str__` method to support Python 3
## Code After:
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Plaintext(CMSPlugin):
body = models.TextField(_('Plaintext'))
def __unicode__(self):
return self.body
def __str__(self):
return self.body
|
# ... existing code ...
def __unicode__(self):
return self.body
def __str__(self):
return self.body
# ... rest of the code ...
|
348b7a2df539779e95cb72d00e7577db6740424f
|
corker/tests/test_main.py
|
corker/tests/test_main.py
|
from __future__ import absolute_import
from webob import Request, Response, exc
from routes import Mapper
from corker.controller import BaseController, route
from corker.app import Application
class Index(BaseController):
@route('')
def index(self):
return Response('Hi index!\n')
@route('view/{item}')
def view(self, item):
return Response('Hi view %r!\n' % item)
from webtest import TestApp
from nose.tools import eq_
def test_main():
mapper = Mapper()
Index.setup_routes(mapper)
def bob(request, link, **config):
def inner():
return Response("Bob!")
return inner
mapper.connect('bob', '/bob/', controller=bob)
test_app = Application(mapper) #('./')
app = TestApp(test_app)
ret = app.get('/view/4')
eq_(ret.body, "Hi view u'4'!\n")
ret = app.get('/')
eq_(ret.body, "Hi index!\n")
ret = app.get('/bob/')
eq_(ret.body, "Bob!")
|
from __future__ import absolute_import
from webob import Request, Response, exc
from routes import Mapper
from corker.controller import BaseController, route
from corker.app import Application
class Index(BaseController):
@route('')
def index(self):
return Response('Hi index!\n')
@route('view/{item}')
def view(self, item):
return Response('Hi view %r!\n' % item)
from webtest import TestApp
from nose.tools import eq_
def test_main():
mapper = Mapper()
Index.setup_routes(mapper)
def bob(request, link, **config):
def inner():
return Response("Bob!")
return inner
mapper.connect('bob', '/bob/', controller=bob)
test_app = Application(mapper) #('./')
app = TestApp(test_app)
ret = app.get('/view/4')
eq_(ret.body, "Hi view u'4'!\n")
ret = app.get('/')
eq_(ret.body, "Hi index!\n")
ret = app.get('/bob/')
eq_(ret.body, "Bob!")
def test_config():
mapper = Mapper()
def bob(request, link, **config):
def inner():
print "C:", config
return Response("Bob! %r" % config)
return inner
mapper.connect('bob', '/bob/', controller=bob)
test_app = Application(mapper, config={'DB_URL': 'sqlite://'}) #('./')
app = TestApp(test_app)
ret = app.get('/bob/')
eq_(ret.body, "Bob! {'config': {'DB_URL': 'sqlite://'}}")
|
Add a test to demo config passing.
|
Add a test to demo config passing.
|
Python
|
bsd-2-clause
|
jd-boyd/corker,vs-networks/corker
|
python
|
## Code Before:
from __future__ import absolute_import
from webob import Request, Response, exc
from routes import Mapper
from corker.controller import BaseController, route
from corker.app import Application
class Index(BaseController):
@route('')
def index(self):
return Response('Hi index!\n')
@route('view/{item}')
def view(self, item):
return Response('Hi view %r!\n' % item)
from webtest import TestApp
from nose.tools import eq_
def test_main():
mapper = Mapper()
Index.setup_routes(mapper)
def bob(request, link, **config):
def inner():
return Response("Bob!")
return inner
mapper.connect('bob', '/bob/', controller=bob)
test_app = Application(mapper) #('./')
app = TestApp(test_app)
ret = app.get('/view/4')
eq_(ret.body, "Hi view u'4'!\n")
ret = app.get('/')
eq_(ret.body, "Hi index!\n")
ret = app.get('/bob/')
eq_(ret.body, "Bob!")
## Instruction:
Add a test to demo config passing.
## Code After:
from __future__ import absolute_import
from webob import Request, Response, exc
from routes import Mapper
from corker.controller import BaseController, route
from corker.app import Application
class Index(BaseController):
@route('')
def index(self):
return Response('Hi index!\n')
@route('view/{item}')
def view(self, item):
return Response('Hi view %r!\n' % item)
from webtest import TestApp
from nose.tools import eq_
def test_main():
mapper = Mapper()
Index.setup_routes(mapper)
def bob(request, link, **config):
def inner():
return Response("Bob!")
return inner
mapper.connect('bob', '/bob/', controller=bob)
test_app = Application(mapper) #('./')
app = TestApp(test_app)
ret = app.get('/view/4')
eq_(ret.body, "Hi view u'4'!\n")
ret = app.get('/')
eq_(ret.body, "Hi index!\n")
ret = app.get('/bob/')
eq_(ret.body, "Bob!")
def test_config():
mapper = Mapper()
def bob(request, link, **config):
def inner():
print "C:", config
return Response("Bob! %r" % config)
return inner
mapper.connect('bob', '/bob/', controller=bob)
test_app = Application(mapper, config={'DB_URL': 'sqlite://'}) #('./')
app = TestApp(test_app)
ret = app.get('/bob/')
eq_(ret.body, "Bob! {'config': {'DB_URL': 'sqlite://'}}")
|
// ... existing code ...
ret = app.get('/bob/')
eq_(ret.body, "Bob!")
def test_config():
mapper = Mapper()
def bob(request, link, **config):
def inner():
print "C:", config
return Response("Bob! %r" % config)
return inner
mapper.connect('bob', '/bob/', controller=bob)
test_app = Application(mapper, config={'DB_URL': 'sqlite://'}) #('./')
app = TestApp(test_app)
ret = app.get('/bob/')
eq_(ret.body, "Bob! {'config': {'DB_URL': 'sqlite://'}}")
// ... rest of the code ...
|
213a7a36bd599279d060edc053a86b602c9731b1
|
python/turbodbc_test/test_has_numpy_support.py
|
python/turbodbc_test/test_has_numpy_support.py
|
from mock import patch
from turbodbc.cursor import _has_numpy_support
def test_has_numpy_support_fails():
with patch('__builtin__.__import__', side_effect=ImportError):
assert _has_numpy_support() == False
def test_has_numpy_support_succeeds():
assert _has_numpy_support() == True
|
import six
from mock import patch
from turbodbc.cursor import _has_numpy_support
# Python 2/3 compatibility
_IMPORT_FUNCTION_NAME = "{}.__import__".format(six.moves.builtins.__name__)
def test_has_numpy_support_fails():
with patch(_IMPORT_FUNCTION_NAME, side_effect=ImportError):
assert _has_numpy_support() == False
def test_has_numpy_support_succeeds():
assert _has_numpy_support() == True
|
Fix test issue with mocking import for Python 3
|
Fix test issue with mocking import for Python 3
|
Python
|
mit
|
blue-yonder/turbodbc,blue-yonder/turbodbc,blue-yonder/turbodbc,blue-yonder/turbodbc
|
python
|
## Code Before:
from mock import patch
from turbodbc.cursor import _has_numpy_support
def test_has_numpy_support_fails():
with patch('__builtin__.__import__', side_effect=ImportError):
assert _has_numpy_support() == False
def test_has_numpy_support_succeeds():
assert _has_numpy_support() == True
## Instruction:
Fix test issue with mocking import for Python 3
## Code After:
import six
from mock import patch
from turbodbc.cursor import _has_numpy_support
# Python 2/3 compatibility
_IMPORT_FUNCTION_NAME = "{}.__import__".format(six.moves.builtins.__name__)
def test_has_numpy_support_fails():
with patch(_IMPORT_FUNCTION_NAME, side_effect=ImportError):
assert _has_numpy_support() == False
def test_has_numpy_support_succeeds():
assert _has_numpy_support() == True
|
// ... existing code ...
import six
from mock import patch
from turbodbc.cursor import _has_numpy_support
# Python 2/3 compatibility
_IMPORT_FUNCTION_NAME = "{}.__import__".format(six.moves.builtins.__name__)
def test_has_numpy_support_fails():
with patch(_IMPORT_FUNCTION_NAME, side_effect=ImportError):
assert _has_numpy_support() == False
def test_has_numpy_support_succeeds():
assert _has_numpy_support() == True
// ... rest of the code ...
|
bbf3d7afa296f4c0a3bed25283a664304a51c0d6
|
src/main/java/com/ezardlabs/dethsquare/prefabs/PrefabCreator.java
|
src/main/java/com/ezardlabs/dethsquare/prefabs/PrefabCreator.java
|
package com.ezardlabs.dethsquare.prefabs;
import com.ezardlabs.dethsquare.GameObject;
public abstract class PrefabCreator {
public abstract GameObject create();
}
|
package com.ezardlabs.dethsquare.prefabs;
import com.ezardlabs.dethsquare.GameObject;
public interface PrefabCreator {
GameObject create();
}
|
Change from abstract class to interface
|
Change from abstract class to interface
|
Java
|
mit
|
8-Bit-Warframe/Dethsquare-Engine-core
|
java
|
## Code Before:
package com.ezardlabs.dethsquare.prefabs;
import com.ezardlabs.dethsquare.GameObject;
public abstract class PrefabCreator {
public abstract GameObject create();
}
## Instruction:
Change from abstract class to interface
## Code After:
package com.ezardlabs.dethsquare.prefabs;
import com.ezardlabs.dethsquare.GameObject;
public interface PrefabCreator {
GameObject create();
}
|
# ... existing code ...
import com.ezardlabs.dethsquare.GameObject;
public interface PrefabCreator {
GameObject create();
}
# ... rest of the code ...
|
454e107abfdc9e3038a18500568e9a1357364bd0
|
pygraphc/similarity/JaroWinkler.py
|
pygraphc/similarity/JaroWinkler.py
|
import jellyfish
import multiprocessing
from itertools import combinations
class JaroWinkler(object):
def __init__(self, event_attributes, event_length):
self.event_attributes = event_attributes
self.event_length = event_length
def __jarowinkler(self, unique_event_id):
string1 = unicode(self.event_attributes[unique_event_id[0]]['preprocessed_event'], 'utf-8')
string2 = unicode(self.event_attributes[unique_event_id[1]]['preprocessed_event'], 'utf-8')
return jellyfish.jaro_winkler(string1, string2)
def __call__(self, unique_event_id):
distance = self.__jarowinkler(unique_event_id)
if distance > 0:
distance_with_id = (unique_event_id[0], unique_event_id[1], distance)
return distance_with_id
def get_jarowinkler(self):
# get unique event id combination
event_id_combination = list(combinations(xrange(self.event_length), 2))
# get distance with multiprocessing
pool = multiprocessing.Pool(processes=4)
distances = pool.map(self, event_id_combination)
pool.close()
pool.join()
return distances
|
import jellyfish
import multiprocessing
from itertools import combinations
class JaroWinkler(object):
def __init__(self, event_attributes, event_length):
self.event_attributes = event_attributes
self.event_length = event_length
def __jarowinkler(self, unique_event_id):
string1 = unicode(self.event_attributes[unique_event_id[0]]['preprocessed_event'], 'utf-8')
string2 = unicode(self.event_attributes[unique_event_id[1]]['preprocessed_event'], 'utf-8')
distance = jellyfish.jaro_winkler(string1, string2)
if distance > 0.:
return round(distance, 3)
def __call__(self, unique_event_id):
distance = self.__jarowinkler(unique_event_id)
distance_with_id = (unique_event_id[0], unique_event_id[1], distance)
return distance_with_id
def get_jarowinkler(self):
# get unique event id combination
event_id_combination = list(combinations(xrange(self.event_length), 2))
# get distance with multiprocessing
pool = multiprocessing.Pool(processes=4)
distances = pool.map(self, event_id_combination)
pool.close()
pool.join()
return distances
|
Add checking for zero distance
|
Add checking for zero distance
|
Python
|
mit
|
studiawan/pygraphc
|
python
|
## Code Before:
import jellyfish
import multiprocessing
from itertools import combinations
class JaroWinkler(object):
def __init__(self, event_attributes, event_length):
self.event_attributes = event_attributes
self.event_length = event_length
def __jarowinkler(self, unique_event_id):
string1 = unicode(self.event_attributes[unique_event_id[0]]['preprocessed_event'], 'utf-8')
string2 = unicode(self.event_attributes[unique_event_id[1]]['preprocessed_event'], 'utf-8')
return jellyfish.jaro_winkler(string1, string2)
def __call__(self, unique_event_id):
distance = self.__jarowinkler(unique_event_id)
if distance > 0:
distance_with_id = (unique_event_id[0], unique_event_id[1], distance)
return distance_with_id
def get_jarowinkler(self):
# get unique event id combination
event_id_combination = list(combinations(xrange(self.event_length), 2))
# get distance with multiprocessing
pool = multiprocessing.Pool(processes=4)
distances = pool.map(self, event_id_combination)
pool.close()
pool.join()
return distances
## Instruction:
Add checking for zero distance
## Code After:
import jellyfish
import multiprocessing
from itertools import combinations
class JaroWinkler(object):
def __init__(self, event_attributes, event_length):
self.event_attributes = event_attributes
self.event_length = event_length
def __jarowinkler(self, unique_event_id):
string1 = unicode(self.event_attributes[unique_event_id[0]]['preprocessed_event'], 'utf-8')
string2 = unicode(self.event_attributes[unique_event_id[1]]['preprocessed_event'], 'utf-8')
distance = jellyfish.jaro_winkler(string1, string2)
if distance > 0.:
return round(distance, 3)
def __call__(self, unique_event_id):
distance = self.__jarowinkler(unique_event_id)
distance_with_id = (unique_event_id[0], unique_event_id[1], distance)
return distance_with_id
def get_jarowinkler(self):
# get unique event id combination
event_id_combination = list(combinations(xrange(self.event_length), 2))
# get distance with multiprocessing
pool = multiprocessing.Pool(processes=4)
distances = pool.map(self, event_id_combination)
pool.close()
pool.join()
return distances
|
# ... existing code ...
def __jarowinkler(self, unique_event_id):
string1 = unicode(self.event_attributes[unique_event_id[0]]['preprocessed_event'], 'utf-8')
string2 = unicode(self.event_attributes[unique_event_id[1]]['preprocessed_event'], 'utf-8')
distance = jellyfish.jaro_winkler(string1, string2)
if distance > 0.:
return round(distance, 3)
def __call__(self, unique_event_id):
distance = self.__jarowinkler(unique_event_id)
distance_with_id = (unique_event_id[0], unique_event_id[1], distance)
return distance_with_id
def get_jarowinkler(self):
# get unique event id combination
# ... rest of the code ...
|
fff18e9b2d84d478849624ee57b810441eb2aafd
|
modules/Core/src/main/java/jpower/core/utils/StringScanner.java
|
modules/Core/src/main/java/jpower/core/utils/StringScanner.java
|
package jpower.core.utils;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* Scans a String for Patterns
*/
public class StringScanner
{
private Scanner scanner;
/**
* Creates a new String Scanner
*
* @param str input string
*/
public StringScanner(String str)
{
scanner = new Scanner(str);
}
/**
* Find the next string matching the pattern
* @param pattern pattern
* @return matched
*/
public String scan(String pattern)
{
return scanner.next(pattern);
}
/**
* Find the next string matching the pattern
* @param pattern pattern
* @return matched
*/
public String scan(Pattern pattern)
{
return scanner.next(pattern);
}
}
|
package jpower.core.utils;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* Scans a String for Patterns
*/
public class StringScanner
{
private Scanner scanner;
/**
* Creates a new String Scanner
*
* @param str input string
*/
public StringScanner(String str)
{
scanner = new Scanner(str);
}
/**
* Find the next string matching the pattern
* @param pattern pattern
* @return matched
*/
public String scan(String pattern)
{
return scan(Pattern.compile(pattern));
}
/**
* Find the next string matching the pattern
* @param pattern pattern
* @return matched
*/
public String scan(Pattern pattern)
{
return scanner.hasNext(pattern) ? scanner.next(pattern) : null;
}
/**
* Skips over the specified pattern
*
* @param pattern pattern
*/
public void skip(Pattern pattern)
{
scanner.skip(pattern);
}
/**
* Skips over the specified pattern
*
* @param pattern pattern
*/
public void skip(String pattern)
{
scanner.skip(pattern);
}
/**
* Skips over the specified pattern until it no longer matches
*
* @param pattern pattern
*/
@SuppressWarnings("StatementWithEmptyBody")
public void skipUntil(String pattern)
{
while (scan(pattern) != null)
{
;
}
}
/**
* Skips over the specified pattern until it no longer matches
*
* @param pattern pattern
*/
@SuppressWarnings("StatementWithEmptyBody")
public void skipUntil(Pattern pattern)
{
while (scan(pattern) != null)
{
;
}
}
}
|
Add Super Awesome String Scanner Stuff
|
Add Super Awesome String Scanner Stuff
|
Java
|
mit
|
DirectMyFile/JPower
|
java
|
## Code Before:
package jpower.core.utils;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* Scans a String for Patterns
*/
public class StringScanner
{
private Scanner scanner;
/**
* Creates a new String Scanner
*
* @param str input string
*/
public StringScanner(String str)
{
scanner = new Scanner(str);
}
/**
* Find the next string matching the pattern
* @param pattern pattern
* @return matched
*/
public String scan(String pattern)
{
return scanner.next(pattern);
}
/**
* Find the next string matching the pattern
* @param pattern pattern
* @return matched
*/
public String scan(Pattern pattern)
{
return scanner.next(pattern);
}
}
## Instruction:
Add Super Awesome String Scanner Stuff
## Code After:
package jpower.core.utils;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* Scans a String for Patterns
*/
public class StringScanner
{
private Scanner scanner;
/**
* Creates a new String Scanner
*
* @param str input string
*/
public StringScanner(String str)
{
scanner = new Scanner(str);
}
/**
* Find the next string matching the pattern
* @param pattern pattern
* @return matched
*/
public String scan(String pattern)
{
return scan(Pattern.compile(pattern));
}
/**
* Find the next string matching the pattern
* @param pattern pattern
* @return matched
*/
public String scan(Pattern pattern)
{
return scanner.hasNext(pattern) ? scanner.next(pattern) : null;
}
/**
* Skips over the specified pattern
*
* @param pattern pattern
*/
public void skip(Pattern pattern)
{
scanner.skip(pattern);
}
/**
* Skips over the specified pattern
*
* @param pattern pattern
*/
public void skip(String pattern)
{
scanner.skip(pattern);
}
/**
* Skips over the specified pattern until it no longer matches
*
* @param pattern pattern
*/
@SuppressWarnings("StatementWithEmptyBody")
public void skipUntil(String pattern)
{
while (scan(pattern) != null)
{
;
}
}
/**
* Skips over the specified pattern until it no longer matches
*
* @param pattern pattern
*/
@SuppressWarnings("StatementWithEmptyBody")
public void skipUntil(Pattern pattern)
{
while (scan(pattern) != null)
{
;
}
}
}
|
// ... existing code ...
*/
public String scan(String pattern)
{
return scan(Pattern.compile(pattern));
}
/**
// ... modified code ...
*/
public String scan(Pattern pattern)
{
return scanner.hasNext(pattern) ? scanner.next(pattern) : null;
}
/**
* Skips over the specified pattern
*
* @param pattern pattern
*/
public void skip(Pattern pattern)
{
scanner.skip(pattern);
}
/**
* Skips over the specified pattern
*
* @param pattern pattern
*/
public void skip(String pattern)
{
scanner.skip(pattern);
}
/**
* Skips over the specified pattern until it no longer matches
*
* @param pattern pattern
*/
@SuppressWarnings("StatementWithEmptyBody")
public void skipUntil(String pattern)
{
while (scan(pattern) != null)
{
;
}
}
/**
* Skips over the specified pattern until it no longer matches
*
* @param pattern pattern
*/
@SuppressWarnings("StatementWithEmptyBody")
public void skipUntil(Pattern pattern)
{
while (scan(pattern) != null)
{
;
}
}
}
// ... rest of the code ...
|
8d83907b8528458763dad7212447c0c096ab51d6
|
Client/src/main/java/controller/MessageBoardController.java
|
Client/src/main/java/controller/MessageBoardController.java
|
package controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import model.Message;
import view.MessageBoard;
public class MessageBoardController implements ActionListener{
private Controller controller;
public MessageBoardController(Controller controller) {
this.controller = controller;
}
@Override
public void actionPerformed(ActionEvent e) {
MessageBoard messageBoard =(MessageBoard)((JButton)e.getSource()).getParent();
//System.out.println("Send this message: "+messageBoard.getMessage()+" to: "+messageBoard.getUser().getUserName());
String mess = messageBoard.getMessage();
System.out.println("in controller "+mess);
Message messageToServet = new Message(messageBoard.getUser().getUserName(),mess);
Message messageToDoc = new Message(controller.getModel().getAuthUser().getUserName(),mess);
messageToDoc.printMessage(messageBoard.getUser().getDoc());
controller.getServerHandler().sendMessage(messageToServet);
}
}
|
package controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import model.Message;
import view.MessageBoard;
public class MessageBoardController implements ActionListener{
private Controller controller;
public MessageBoardController(Controller controller) {
this.controller = controller;
}
@Override
public void actionPerformed(ActionEvent e) {
MessageBoard messageBoard =(MessageBoard)((JButton)e.getSource()).getParent();
//System.out.println("Send this message: "+messageBoard.getMessage()+" to: "+messageBoard.getUser().getUserName());
String mess = messageBoard.getMessage();
if(!mess.equals("")){
System.out.println("in controller "+mess);
Message messageToServet = new Message(messageBoard.getUser().getUserName(),mess);
Message messageToDoc = new Message(controller.getModel().getAuthUser().getUserName(),mess);
messageToDoc.printMessage(messageBoard.getUser().getDoc());
controller.getServerHandler().sendMessage(messageToServet);
}
}
}
|
Fix Client Send Empty message
|
Fix Client Send Empty message
|
Java
|
mit
|
ablenesi/ELTEProjectToolsTeam09,ablenesi/ELTEProjectToolsTeam09
|
java
|
## Code Before:
package controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import model.Message;
import view.MessageBoard;
public class MessageBoardController implements ActionListener{
private Controller controller;
public MessageBoardController(Controller controller) {
this.controller = controller;
}
@Override
public void actionPerformed(ActionEvent e) {
MessageBoard messageBoard =(MessageBoard)((JButton)e.getSource()).getParent();
//System.out.println("Send this message: "+messageBoard.getMessage()+" to: "+messageBoard.getUser().getUserName());
String mess = messageBoard.getMessage();
System.out.println("in controller "+mess);
Message messageToServet = new Message(messageBoard.getUser().getUserName(),mess);
Message messageToDoc = new Message(controller.getModel().getAuthUser().getUserName(),mess);
messageToDoc.printMessage(messageBoard.getUser().getDoc());
controller.getServerHandler().sendMessage(messageToServet);
}
}
## Instruction:
Fix Client Send Empty message
## Code After:
package controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import model.Message;
import view.MessageBoard;
public class MessageBoardController implements ActionListener{
private Controller controller;
public MessageBoardController(Controller controller) {
this.controller = controller;
}
@Override
public void actionPerformed(ActionEvent e) {
MessageBoard messageBoard =(MessageBoard)((JButton)e.getSource()).getParent();
//System.out.println("Send this message: "+messageBoard.getMessage()+" to: "+messageBoard.getUser().getUserName());
String mess = messageBoard.getMessage();
if(!mess.equals("")){
System.out.println("in controller "+mess);
Message messageToServet = new Message(messageBoard.getUser().getUserName(),mess);
Message messageToDoc = new Message(controller.getModel().getAuthUser().getUserName(),mess);
messageToDoc.printMessage(messageBoard.getUser().getDoc());
controller.getServerHandler().sendMessage(messageToServet);
}
}
}
|
...
MessageBoard messageBoard =(MessageBoard)((JButton)e.getSource()).getParent();
//System.out.println("Send this message: "+messageBoard.getMessage()+" to: "+messageBoard.getUser().getUserName());
String mess = messageBoard.getMessage();
if(!mess.equals("")){
System.out.println("in controller "+mess);
Message messageToServet = new Message(messageBoard.getUser().getUserName(),mess);
Message messageToDoc = new Message(controller.getModel().getAuthUser().getUserName(),mess);
messageToDoc.printMessage(messageBoard.getUser().getDoc());
controller.getServerHandler().sendMessage(messageToServet);
}
}
}
...
|
61f58317f377d33ebfa437927539f627adb5356f
|
src/main/java/musician101/common/java/minecraft/sponge/command/SpongeHelpCommand.java
|
src/main/java/musician101/common/java/minecraft/sponge/command/SpongeHelpCommand.java
|
package musician101.common.java.minecraft.sponge.command;
import org.spongepowered.api.text.Text.Literal;
import org.spongepowered.api.text.Texts;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import javax.annotation.Nonnull;
import java.util.Arrays;
public class SpongeHelpCommand extends AbstractSpongeCommand
{
private final AbstractSpongeCommand mainCommand;
public SpongeHelpCommand(AbstractSpongeCommand mainCommand, CommandSource source)
{
super("help", "Display help info for " + mainCommand.getUsage(source), Arrays.asList(new SpongeCommandArgument(((Literal) mainCommand.getUsage(source)).getContent()), new SpongeCommandArgument("help")), 1, "", false, null, null);
this.mainCommand = mainCommand;
}
@Nonnull
@Override
public CommandResult process(@Nonnull CommandSource source, @Nonnull String arguments) throws CommandException
{
source.sendMessage(Texts.of());
source.sendMessage(mainCommand.getUsage(source));
mainCommand.getSubCommands().forEach(command -> source.sendMessage(command.getHelp(source).get()));
return CommandResult.success();
}
}
|
package musician101.common.java.minecraft.sponge.command;
import org.spongepowered.api.text.Text.Literal;
import org.spongepowered.api.text.Texts;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import javax.annotation.Nonnull;
import java.util.Arrays;
public class SpongeHelpCommand extends AbstractSpongeCommand
{
private final AbstractSpongeCommand mainCommand;
public SpongeHelpCommand(AbstractSpongeCommand mainCommand, CommandSource source)
{
super("help", "Display help info for " + mainCommand.getUsage(source), Arrays.asList(new SpongeCommandArgument(((Literal) mainCommand.getUsage(source)).getContent()), new SpongeCommandArgument("help")), 1, "", false, null, null);
this.mainCommand = mainCommand;
}
@Nonnull
@Override
public CommandResult process(@Nonnull CommandSource source, @Nonnull String arguments) throws CommandException
{
source.sendMessage(Texts.of(mainCommand.getUsage(source), mainCommand.getShortDescription(source)));
mainCommand.getSubCommands().forEach(command -> source.sendMessage(command.getHelp(source).get()));
return CommandResult.success();
}
}
|
Add description to the help message.
|
Add description to the help message.
|
Java
|
mit
|
Musician101/Common
|
java
|
## Code Before:
package musician101.common.java.minecraft.sponge.command;
import org.spongepowered.api.text.Text.Literal;
import org.spongepowered.api.text.Texts;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import javax.annotation.Nonnull;
import java.util.Arrays;
public class SpongeHelpCommand extends AbstractSpongeCommand
{
private final AbstractSpongeCommand mainCommand;
public SpongeHelpCommand(AbstractSpongeCommand mainCommand, CommandSource source)
{
super("help", "Display help info for " + mainCommand.getUsage(source), Arrays.asList(new SpongeCommandArgument(((Literal) mainCommand.getUsage(source)).getContent()), new SpongeCommandArgument("help")), 1, "", false, null, null);
this.mainCommand = mainCommand;
}
@Nonnull
@Override
public CommandResult process(@Nonnull CommandSource source, @Nonnull String arguments) throws CommandException
{
source.sendMessage(Texts.of());
source.sendMessage(mainCommand.getUsage(source));
mainCommand.getSubCommands().forEach(command -> source.sendMessage(command.getHelp(source).get()));
return CommandResult.success();
}
}
## Instruction:
Add description to the help message.
## Code After:
package musician101.common.java.minecraft.sponge.command;
import org.spongepowered.api.text.Text.Literal;
import org.spongepowered.api.text.Texts;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import javax.annotation.Nonnull;
import java.util.Arrays;
public class SpongeHelpCommand extends AbstractSpongeCommand
{
private final AbstractSpongeCommand mainCommand;
public SpongeHelpCommand(AbstractSpongeCommand mainCommand, CommandSource source)
{
super("help", "Display help info for " + mainCommand.getUsage(source), Arrays.asList(new SpongeCommandArgument(((Literal) mainCommand.getUsage(source)).getContent()), new SpongeCommandArgument("help")), 1, "", false, null, null);
this.mainCommand = mainCommand;
}
@Nonnull
@Override
public CommandResult process(@Nonnull CommandSource source, @Nonnull String arguments) throws CommandException
{
source.sendMessage(Texts.of(mainCommand.getUsage(source), mainCommand.getShortDescription(source)));
mainCommand.getSubCommands().forEach(command -> source.sendMessage(command.getHelp(source).get()));
return CommandResult.success();
}
}
|
...
@Override
public CommandResult process(@Nonnull CommandSource source, @Nonnull String arguments) throws CommandException
{
source.sendMessage(Texts.of(mainCommand.getUsage(source), mainCommand.getShortDescription(source)));
mainCommand.getSubCommands().forEach(command -> source.sendMessage(command.getHelp(source).get()));
return CommandResult.success();
}
...
|
9db141ce4a4033e3c1ac5b7b69d55ff85d62a27f
|
libtu/util.h
|
libtu/util.h
|
/*
* libtu/util.h
*
* Copyright (c) Tuomo Valkonen 1999-2002.
*
* You may distribute and modify this library under the terms of either
* the Clarified Artistic License or the GNU LGPL, version 2.1 or later.
*/
#ifndef LIBTU_UTIL_H
#define LIBTU_UTIL_H
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include "types.h"
#include "optparser.h"
extern void libtu_init(const char *argv0);
extern const char *libtu_progname();
extern const char *libtu_progbasename();
#endif /* LIBTU_UTIL_H */
|
/*
* libtu/util.h
*
* Copyright (c) Tuomo Valkonen 1999-2002.
*
* You may distribute and modify this library under the terms of either
* the Clarified Artistic License or the GNU LGPL, version 2.1 or later.
*/
#ifndef LIBTU_UTIL_H
#define LIBTU_UTIL_H
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include "types.h"
#include "optparser.h"
/**
* @parame argv0 The program name used to invoke the current program, with
* path (if specified). Unfortunately it is generally not easy to determine
* the encoding of this string, so we don't require a specific one here.
*
* @see http://stackoverflow.com/questions/5408730/what-is-the-encoding-of-argv
*/
extern void libtu_init(const char *argv0);
/**
* The program name used to invoke the current program, with path (if
* supplied). Unfortunately the encoding is undefined.
*/
extern const char *libtu_progname();
/**
* The program name used to invoke the current program, without path.
* Unfortunately the encoding is undefined.
*/
extern const char *libtu_progbasename();
#endif /* LIBTU_UTIL_H */
|
Document (lack of) character encoding rules in the API
|
Document (lack of) character encoding rules in the API
|
C
|
lgpl-2.1
|
p5n/notion,dkogan/notion.xfttest,anoduck/notion,anoduck/notion,raboof/notion,knixeur/notion,p5n/notion,dkogan/notion.xfttest,dkogan/notion,dkogan/notion,dkogan/notion.xfttest,neg-serg/notion,anoduck/notion,dkogan/notion,raboof/notion,anoduck/notion,knixeur/notion,dkogan/notion,anoduck/notion,knixeur/notion,neg-serg/notion,neg-serg/notion,dkogan/notion,p5n/notion,p5n/notion,p5n/notion,knixeur/notion,neg-serg/notion,knixeur/notion,raboof/notion,dkogan/notion.xfttest,raboof/notion
|
c
|
## Code Before:
/*
* libtu/util.h
*
* Copyright (c) Tuomo Valkonen 1999-2002.
*
* You may distribute and modify this library under the terms of either
* the Clarified Artistic License or the GNU LGPL, version 2.1 or later.
*/
#ifndef LIBTU_UTIL_H
#define LIBTU_UTIL_H
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include "types.h"
#include "optparser.h"
extern void libtu_init(const char *argv0);
extern const char *libtu_progname();
extern const char *libtu_progbasename();
#endif /* LIBTU_UTIL_H */
## Instruction:
Document (lack of) character encoding rules in the API
## Code After:
/*
* libtu/util.h
*
* Copyright (c) Tuomo Valkonen 1999-2002.
*
* You may distribute and modify this library under the terms of either
* the Clarified Artistic License or the GNU LGPL, version 2.1 or later.
*/
#ifndef LIBTU_UTIL_H
#define LIBTU_UTIL_H
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include "types.h"
#include "optparser.h"
/**
* @parame argv0 The program name used to invoke the current program, with
* path (if specified). Unfortunately it is generally not easy to determine
* the encoding of this string, so we don't require a specific one here.
*
* @see http://stackoverflow.com/questions/5408730/what-is-the-encoding-of-argv
*/
extern void libtu_init(const char *argv0);
/**
* The program name used to invoke the current program, with path (if
* supplied). Unfortunately the encoding is undefined.
*/
extern const char *libtu_progname();
/**
* The program name used to invoke the current program, without path.
* Unfortunately the encoding is undefined.
*/
extern const char *libtu_progbasename();
#endif /* LIBTU_UTIL_H */
|
# ... existing code ...
#include "types.h"
#include "optparser.h"
/**
* @parame argv0 The program name used to invoke the current program, with
* path (if specified). Unfortunately it is generally not easy to determine
* the encoding of this string, so we don't require a specific one here.
*
* @see http://stackoverflow.com/questions/5408730/what-is-the-encoding-of-argv
*/
extern void libtu_init(const char *argv0);
/**
* The program name used to invoke the current program, with path (if
* supplied). Unfortunately the encoding is undefined.
*/
extern const char *libtu_progname();
/**
* The program name used to invoke the current program, without path.
* Unfortunately the encoding is undefined.
*/
extern const char *libtu_progbasename();
#endif /* LIBTU_UTIL_H */
# ... rest of the code ...
|
2722a59aad0775f1bcd1e81232ff445b9012a2ae
|
ssim/compat.py
|
ssim/compat.py
|
"""Compatibility routines."""
from __future__ import absolute_import
import sys
try:
import Image # pylint: disable=import-error,unused-import
except ImportError:
from PIL import Image # pylint: disable=unused-import
try:
import ImageOps # pylint: disable=import-error,unused-import
except ImportError:
from PIL import ImageOps # pylint: disable=unused-import
if sys.version_info[0] > 2:
basestring = (str, bytes) # pylint: disable=redefined-builtin,invalid-name
else:
basestring = basestring # pylint: disable=invalid-name
|
"""Compatibility routines."""
from __future__ import absolute_import
import sys
try:
import Image # pylint: disable=import-error,unused-import
except ImportError:
from PIL import Image # pylint: disable=unused-import
try:
import ImageOps # pylint: disable=import-error,unused-import
except ImportError:
from PIL import ImageOps # pylint: disable=unused-import
if sys.version_info[0] > 2:
basestring = (str, bytes) # pylint: disable=redefined-builtin,invalid-name
else:
# pylint: disable=redefined-variable-type
basestring = basestring # pylint: disable=invalid-name
|
Add pylint to disable redefined variable.
|
Add pylint to disable redefined variable.
|
Python
|
mit
|
jterrace/pyssim
|
python
|
## Code Before:
"""Compatibility routines."""
from __future__ import absolute_import
import sys
try:
import Image # pylint: disable=import-error,unused-import
except ImportError:
from PIL import Image # pylint: disable=unused-import
try:
import ImageOps # pylint: disable=import-error,unused-import
except ImportError:
from PIL import ImageOps # pylint: disable=unused-import
if sys.version_info[0] > 2:
basestring = (str, bytes) # pylint: disable=redefined-builtin,invalid-name
else:
basestring = basestring # pylint: disable=invalid-name
## Instruction:
Add pylint to disable redefined variable.
## Code After:
"""Compatibility routines."""
from __future__ import absolute_import
import sys
try:
import Image # pylint: disable=import-error,unused-import
except ImportError:
from PIL import Image # pylint: disable=unused-import
try:
import ImageOps # pylint: disable=import-error,unused-import
except ImportError:
from PIL import ImageOps # pylint: disable=unused-import
if sys.version_info[0] > 2:
basestring = (str, bytes) # pylint: disable=redefined-builtin,invalid-name
else:
# pylint: disable=redefined-variable-type
basestring = basestring # pylint: disable=invalid-name
|
// ... existing code ...
if sys.version_info[0] > 2:
basestring = (str, bytes) # pylint: disable=redefined-builtin,invalid-name
else:
# pylint: disable=redefined-variable-type
basestring = basestring # pylint: disable=invalid-name
// ... rest of the code ...
|
89132dce0f4341c0dd2c6bdbdd02a89681162acd
|
src/com/redhat/ceylon/common/tool/ToolMessages.java
|
src/com/redhat/ceylon/common/tool/ToolMessages.java
|
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License,
* along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.common.tool;
import java.text.MessageFormat;
import java.util.ResourceBundle;
class ToolMessages {
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("com.redhat.ceylon.common.tool.tools");
public static String msg(String msgKey, Object... msgArgs) {
String msg = RESOURCE_BUNDLE.getString(msgKey);
if (msgArgs != null) {
msg = MessageFormat.format(msg, msgArgs);
}
return msg;
}
}
|
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License,
* along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.common.tool;
import java.util.ResourceBundle;
import com.redhat.ceylon.common.Messages;
class ToolMessages extends Messages {
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("com.redhat.ceylon.common.tool.tools");
public static String msg(String msgKey, Object... msgArgs) {
return msg(RESOURCE_BUNDLE, msgKey, msgArgs);
}
}
|
Extend the common Messages class
|
Extend the common Messages class
|
Java
|
apache-2.0
|
ceylon/ceylon-common,jvasileff/ceylon-common,ceylon/ceylon-common,ceylon/ceylon-common,jvasileff/ceylon-common,jvasileff/ceylon-common
|
java
|
## Code Before:
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License,
* along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.common.tool;
import java.text.MessageFormat;
import java.util.ResourceBundle;
class ToolMessages {
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("com.redhat.ceylon.common.tool.tools");
public static String msg(String msgKey, Object... msgArgs) {
String msg = RESOURCE_BUNDLE.getString(msgKey);
if (msgArgs != null) {
msg = MessageFormat.format(msg, msgArgs);
}
return msg;
}
}
## Instruction:
Extend the common Messages class
## Code After:
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License,
* along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.common.tool;
import java.util.ResourceBundle;
import com.redhat.ceylon.common.Messages;
class ToolMessages extends Messages {
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("com.redhat.ceylon.common.tool.tools");
public static String msg(String msgKey, Object... msgArgs) {
return msg(RESOURCE_BUNDLE, msgKey, msgArgs);
}
}
|
...
*/
package com.redhat.ceylon.common.tool;
import java.util.ResourceBundle;
import com.redhat.ceylon.common.Messages;
class ToolMessages extends Messages {
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("com.redhat.ceylon.common.tool.tools");
public static String msg(String msgKey, Object... msgArgs) {
return msg(RESOURCE_BUNDLE, msgKey, msgArgs);
}
}
...
|
fd48211548c8c2d5daec0994155ddb7e8d226882
|
tests/test_anki_sync.py
|
tests/test_anki_sync.py
|
import pytest
import os
import rememberberry
from rememberscript import RememberMachine, FileStorage
from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story
@pytest.mark.asyncio
@tmp_data_path('/tmp/data/', delete=True)
async def test_anki_account():
storage = FileStorage()
m, storage = get_isolated_story('login_anki', storage)
await assert_replies(m.reply(''), 'What is your Anki username?')
await assert_replies(m.reply('ajshdkajhsdkajshd'), 'And now the password')
await assert_replies(m.reply('jkdhskjhgdksjhg'),
'Authentication with ankiweb failed, try again?',
'What is your Anki username?')
await assert_replies(m.reply('[email protected]'), 'And now the password')
await assert_replies(m.reply('ankitest'),
'Authentication worked, now I\'ll try to sync your account',
'Syncing anki database',
'Syncing media files (this may take a while)',
'Syncing done',
'Great, you\'re all synced up!',
'enter init')
|
import pytest
import os
import rememberberry
from rememberscript import RememberMachine, FileStorage
from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story
@pytest.mark.asyncio
@tmp_data_path('/tmp/data/', delete=True)
async def test_anki_account():
storage = FileStorage()
storage['username'] = 'alice'
m, storage = get_isolated_story('login_anki', storage)
await assert_replies(m.reply(''), 'What is your Anki username?')
await assert_replies(m.reply('ajshdkajhsdkajshd'), 'And now the password')
await assert_replies(m.reply('jkdhskjhgdksjhg'),
'Authentication with ankiweb failed, try again?',
'What is your Anki username?')
await assert_replies(m.reply('[email protected]'), 'And now the password')
await assert_replies(m.reply('ankitest'),
'Authentication worked, now I\'ll try to sync your account',
'Syncing anki database',
'Syncing media files (this may take a while)',
'Syncing done',
'Great, you\'re all synced up!',
'enter init')
|
Fix missing username in test
|
Fix missing username in test
|
Python
|
agpl-3.0
|
rememberberry/rememberberry-server,rememberberry/rememberberry-server
|
python
|
## Code Before:
import pytest
import os
import rememberberry
from rememberscript import RememberMachine, FileStorage
from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story
@pytest.mark.asyncio
@tmp_data_path('/tmp/data/', delete=True)
async def test_anki_account():
storage = FileStorage()
m, storage = get_isolated_story('login_anki', storage)
await assert_replies(m.reply(''), 'What is your Anki username?')
await assert_replies(m.reply('ajshdkajhsdkajshd'), 'And now the password')
await assert_replies(m.reply('jkdhskjhgdksjhg'),
'Authentication with ankiweb failed, try again?',
'What is your Anki username?')
await assert_replies(m.reply('[email protected]'), 'And now the password')
await assert_replies(m.reply('ankitest'),
'Authentication worked, now I\'ll try to sync your account',
'Syncing anki database',
'Syncing media files (this may take a while)',
'Syncing done',
'Great, you\'re all synced up!',
'enter init')
## Instruction:
Fix missing username in test
## Code After:
import pytest
import os
import rememberberry
from rememberscript import RememberMachine, FileStorage
from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story
@pytest.mark.asyncio
@tmp_data_path('/tmp/data/', delete=True)
async def test_anki_account():
storage = FileStorage()
storage['username'] = 'alice'
m, storage = get_isolated_story('login_anki', storage)
await assert_replies(m.reply(''), 'What is your Anki username?')
await assert_replies(m.reply('ajshdkajhsdkajshd'), 'And now the password')
await assert_replies(m.reply('jkdhskjhgdksjhg'),
'Authentication with ankiweb failed, try again?',
'What is your Anki username?')
await assert_replies(m.reply('[email protected]'), 'And now the password')
await assert_replies(m.reply('ankitest'),
'Authentication worked, now I\'ll try to sync your account',
'Syncing anki database',
'Syncing media files (this may take a while)',
'Syncing done',
'Great, you\'re all synced up!',
'enter init')
|
# ... existing code ...
@tmp_data_path('/tmp/data/', delete=True)
async def test_anki_account():
storage = FileStorage()
storage['username'] = 'alice'
m, storage = get_isolated_story('login_anki', storage)
await assert_replies(m.reply(''), 'What is your Anki username?')
await assert_replies(m.reply('ajshdkajhsdkajshd'), 'And now the password')
# ... rest of the code ...
|
8139a3a49e4ee6d1fc8a2a71becbfd6d625b5c5f
|
apps/accounts/serializers.py
|
apps/accounts/serializers.py
|
from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework.fields import HyperlinkedIdentityField
class MemberDetailSerializer(serializers.ModelSerializer):
url = HyperlinkedIdentityField(view_name='member-detail')
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'username', 'url')
class MemberListSerializer(MemberDetailSerializer):
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'username', 'url')
|
from apps.bluebottle_utils.serializers import SorlImageField
from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework.fields import HyperlinkedIdentityField
class MemberDetailSerializer(serializers.ModelSerializer):
url = HyperlinkedIdentityField(view_name='member-detail')
picture = SorlImageField('userprofile.picture', '100x100', crop='center')
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'username', 'url', 'picture')
class MemberListSerializer(MemberDetailSerializer):
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'username', 'url')
|
Add picture field member detail api.
|
Add picture field member detail api.
|
Python
|
bsd-3-clause
|
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
|
python
|
## Code Before:
from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework.fields import HyperlinkedIdentityField
class MemberDetailSerializer(serializers.ModelSerializer):
url = HyperlinkedIdentityField(view_name='member-detail')
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'username', 'url')
class MemberListSerializer(MemberDetailSerializer):
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'username', 'url')
## Instruction:
Add picture field member detail api.
## Code After:
from apps.bluebottle_utils.serializers import SorlImageField
from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework.fields import HyperlinkedIdentityField
class MemberDetailSerializer(serializers.ModelSerializer):
url = HyperlinkedIdentityField(view_name='member-detail')
picture = SorlImageField('userprofile.picture', '100x100', crop='center')
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'username', 'url', 'picture')
class MemberListSerializer(MemberDetailSerializer):
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'username', 'url')
|
// ... existing code ...
from apps.bluebottle_utils.serializers import SorlImageField
from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework.fields import HyperlinkedIdentityField
// ... modified code ...
class MemberDetailSerializer(serializers.ModelSerializer):
url = HyperlinkedIdentityField(view_name='member-detail')
picture = SorlImageField('userprofile.picture', '100x100', crop='center')
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'username', 'url', 'picture')
class MemberListSerializer(MemberDetailSerializer):
// ... rest of the code ...
|
3a47fbdaa44b4371f5c821fec5407020d5bd4aa2
|
src/main/java/org/amc/dao/DAO.java
|
src/main/java/org/amc/dao/DAO.java
|
package org.amc.dao;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import org.apache.log4j.Logger;
/**
* Fetches and holds a reference to the Persistence EntityManager
* @author adrian
*
*/
public abstract class DAO
{
private static Logger logger=Logger.getLogger(DAO.class);
private EntityManagerFactory emf;
private EntityManager em;
private final String PERSISTENCE_UNIT_NAME="myDatabase";
public DAO()
{
emf=Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
em=emf.createEntityManager();
}
@PersistenceUnit(name = PERSISTENCE_UNIT_NAME)
public void setEm(EntityManager em)
{
logger.info("EntityManager set to "+em.toString());
this.em = em;
}
/**
*
* @return EntityManager for subclass to use
*/
protected EntityManager getEntityManager()
{
return em;
}
}
|
package org.amc.dao;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import org.apache.log4j.Logger;
/**
* Fetches and holds a reference to the Persistence EntityManager
* @author adrian
*
*/
public abstract class DAO
{
private static Logger logger=Logger.getLogger(DAO.class);
private EntityManagerFactory emf;
private EntityManager em;
private final String PERSISTENCE_UNIT_NAME="myDatabase";
public DAO()
{
emf=Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
em=emf.createEntityManager();
}
@PersistenceUnit(name = PERSISTENCE_UNIT_NAME)
public void setEm(EntityManager em)
{
logger.info("EntityManager set to "+em.toString());
this.em = em;
}
/**
*
* @return EntityManager for subclass to use
*/
protected EntityManager getEntityManager()
{
//Reopen the EntityManager if closed
if(em!=null && !em.isOpen())
{
em=emf.createEntityManager();
}
return em;
}
@Override
public void finalize()
{
//close EntityManager
if(em!=null && em.isOpen())
em.close();
//close EntityManagerFactory
if(emf!=null && emf.isOpen())
emf.close();
}
}
|
Add handling for a closed entitymanager
|
Add handling for a closed entitymanager
|
Java
|
mit
|
subwoofer359/aplsystem,subwoofer359/aplsystem,subwoofer359/aplsystem,subwoofer359/aplsystem
|
java
|
## Code Before:
package org.amc.dao;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import org.apache.log4j.Logger;
/**
* Fetches and holds a reference to the Persistence EntityManager
* @author adrian
*
*/
public abstract class DAO
{
private static Logger logger=Logger.getLogger(DAO.class);
private EntityManagerFactory emf;
private EntityManager em;
private final String PERSISTENCE_UNIT_NAME="myDatabase";
public DAO()
{
emf=Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
em=emf.createEntityManager();
}
@PersistenceUnit(name = PERSISTENCE_UNIT_NAME)
public void setEm(EntityManager em)
{
logger.info("EntityManager set to "+em.toString());
this.em = em;
}
/**
*
* @return EntityManager for subclass to use
*/
protected EntityManager getEntityManager()
{
return em;
}
}
## Instruction:
Add handling for a closed entitymanager
## Code After:
package org.amc.dao;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import org.apache.log4j.Logger;
/**
* Fetches and holds a reference to the Persistence EntityManager
* @author adrian
*
*/
public abstract class DAO
{
private static Logger logger=Logger.getLogger(DAO.class);
private EntityManagerFactory emf;
private EntityManager em;
private final String PERSISTENCE_UNIT_NAME="myDatabase";
public DAO()
{
emf=Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
em=emf.createEntityManager();
}
@PersistenceUnit(name = PERSISTENCE_UNIT_NAME)
public void setEm(EntityManager em)
{
logger.info("EntityManager set to "+em.toString());
this.em = em;
}
/**
*
* @return EntityManager for subclass to use
*/
protected EntityManager getEntityManager()
{
//Reopen the EntityManager if closed
if(em!=null && !em.isOpen())
{
em=emf.createEntityManager();
}
return em;
}
@Override
public void finalize()
{
//close EntityManager
if(em!=null && em.isOpen())
em.close();
//close EntityManagerFactory
if(emf!=null && emf.isOpen())
emf.close();
}
}
|
// ... existing code ...
*/
protected EntityManager getEntityManager()
{
//Reopen the EntityManager if closed
if(em!=null && !em.isOpen())
{
em=emf.createEntityManager();
}
return em;
}
@Override
public void finalize()
{
//close EntityManager
if(em!=null && em.isOpen())
em.close();
//close EntityManagerFactory
if(emf!=null && emf.isOpen())
emf.close();
}
}
// ... rest of the code ...
|
80312d21ebd1de0af5ab7b192d012d6803fd14a7
|
src/com/gh4a/loader/ReadmeLoader.java
|
src/com/gh4a/loader/ReadmeLoader.java
|
package com.gh4a.loader;
import java.io.InputStream;
import org.eclipse.egit.github.core.RepositoryId;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.eclipse.egit.github.core.service.ContentService;
import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import android.util.Log;
import com.gh4a.Constants;
import com.gh4a.DefaultClient;
import com.gh4a.Gh4Application;
import com.gh4a.utils.StringUtils;
public class ReadmeLoader extends AsyncTaskLoader<String> {
private String mRepoOwner;
private String mRepoName;
public ReadmeLoader(Context context, String repoOwner, String repoName) {
super(context);
mRepoOwner = repoOwner;
mRepoName = repoName;
}
@Override
public String loadInBackground() {
GitHubClient client = new DefaultClient("application/vnd.github.beta.html");
try {
ContentService contentService = new ContentService(client);
InputStream is = contentService.getHtmlReadme(new RepositoryId(mRepoOwner, mRepoName));
if (is != null) {
return StringUtils.convertStreamToString(is);
}
else {
return null;
}
} catch (Exception e) {
Log.e(Constants.LOG_TAG, e.getMessage(), e);
return null;
}
}
}
|
package com.gh4a.loader;
import java.io.InputStream;
import org.eclipse.egit.github.core.RepositoryId;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.eclipse.egit.github.core.service.ContentService;
import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import android.util.Log;
import com.gh4a.Constants;
import com.gh4a.DefaultClient;
import com.gh4a.Gh4Application;
import com.gh4a.utils.StringUtils;
public class ReadmeLoader extends AsyncTaskLoader<String> {
private String mRepoOwner;
private String mRepoName;
public ReadmeLoader(Context context, String repoOwner, String repoName) {
super(context);
mRepoOwner = repoOwner;
mRepoName = repoName;
}
@Override
public String loadInBackground() {
Gh4Application app = (Gh4Application) getContext().getApplicationContext();
GitHubClient client = new DefaultClient("application/vnd.github.beta.html");
client.setOAuth2Token(app.getAuthToken());
try {
ContentService contentService = new ContentService(client);
InputStream is = contentService.getHtmlReadme(new RepositoryId(mRepoOwner, mRepoName));
if (is != null) {
return StringUtils.convertStreamToString(is);
}
else {
return null;
}
} catch (Exception e) {
Log.e(Constants.LOG_TAG, e.getMessage(), e);
return null;
}
}
}
|
Fix README not showing in private repo
|
Fix README not showing in private repo
|
Java
|
apache-2.0
|
DeLaSalleUniversity-Manila/octodroid-ToastyKrabstix,Bloody-Badboy/gh4a,slapperwan/gh4a,shekibobo/gh4a,edyesed/gh4a,shineM/gh4a,AKiniyalocts/gh4a,DeLaSalleUniversity-Manila/octodroid-ToastyKrabstix,sauloaguiar/gh4a,Bloody-Badboy/gh4a,slapperwan/gh4a,shekibobo/gh4a,AKiniyalocts/gh4a,sauloaguiar/gh4a,edyesed/gh4a,shineM/gh4a
|
java
|
## Code Before:
package com.gh4a.loader;
import java.io.InputStream;
import org.eclipse.egit.github.core.RepositoryId;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.eclipse.egit.github.core.service.ContentService;
import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import android.util.Log;
import com.gh4a.Constants;
import com.gh4a.DefaultClient;
import com.gh4a.Gh4Application;
import com.gh4a.utils.StringUtils;
public class ReadmeLoader extends AsyncTaskLoader<String> {
private String mRepoOwner;
private String mRepoName;
public ReadmeLoader(Context context, String repoOwner, String repoName) {
super(context);
mRepoOwner = repoOwner;
mRepoName = repoName;
}
@Override
public String loadInBackground() {
GitHubClient client = new DefaultClient("application/vnd.github.beta.html");
try {
ContentService contentService = new ContentService(client);
InputStream is = contentService.getHtmlReadme(new RepositoryId(mRepoOwner, mRepoName));
if (is != null) {
return StringUtils.convertStreamToString(is);
}
else {
return null;
}
} catch (Exception e) {
Log.e(Constants.LOG_TAG, e.getMessage(), e);
return null;
}
}
}
## Instruction:
Fix README not showing in private repo
## Code After:
package com.gh4a.loader;
import java.io.InputStream;
import org.eclipse.egit.github.core.RepositoryId;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.eclipse.egit.github.core.service.ContentService;
import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import android.util.Log;
import com.gh4a.Constants;
import com.gh4a.DefaultClient;
import com.gh4a.Gh4Application;
import com.gh4a.utils.StringUtils;
public class ReadmeLoader extends AsyncTaskLoader<String> {
private String mRepoOwner;
private String mRepoName;
public ReadmeLoader(Context context, String repoOwner, String repoName) {
super(context);
mRepoOwner = repoOwner;
mRepoName = repoName;
}
@Override
public String loadInBackground() {
Gh4Application app = (Gh4Application) getContext().getApplicationContext();
GitHubClient client = new DefaultClient("application/vnd.github.beta.html");
client.setOAuth2Token(app.getAuthToken());
try {
ContentService contentService = new ContentService(client);
InputStream is = contentService.getHtmlReadme(new RepositoryId(mRepoOwner, mRepoName));
if (is != null) {
return StringUtils.convertStreamToString(is);
}
else {
return null;
}
} catch (Exception e) {
Log.e(Constants.LOG_TAG, e.getMessage(), e);
return null;
}
}
}
|
# ... existing code ...
@Override
public String loadInBackground() {
Gh4Application app = (Gh4Application) getContext().getApplicationContext();
GitHubClient client = new DefaultClient("application/vnd.github.beta.html");
client.setOAuth2Token(app.getAuthToken());
try {
ContentService contentService = new ContentService(client);
InputStream is = contentService.getHtmlReadme(new RepositoryId(mRepoOwner, mRepoName));
# ... rest of the code ...
|
570fdec96555eaf989c91970073a3101334ee508
|
OpERP/src/main/java/devopsdistilled/operp/server/data/service/employee/impl/EmployeeServiceImpl.java
|
OpERP/src/main/java/devopsdistilled/operp/server/data/service/employee/impl/EmployeeServiceImpl.java
|
package devopsdistilled.operp.server.data.service.employee.impl;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import devopsdistilled.operp.server.data.entity.employee.Employee;
import devopsdistilled.operp.server.data.repo.employee.EmployeeRepository;
import devopsdistilled.operp.server.data.service.employee.EmployeeService;
import devopsdistilled.operp.server.data.service.impl.AbstractEntityService;
@Service
public class EmployeeServiceImpl extends
AbstractEntityService<Employee, Long, EmployeeRepository> implements
EmployeeService {
private static final long serialVersionUID = 2648525777561781085L;
@Inject
private EmployeeRepository repo;
@Override
protected EmployeeRepository getRepo() {
return repo;
}
@Override
protected Employee findByEntityName(String entityName) {
return null;
}
}
|
package devopsdistilled.operp.server.data.service.employee.impl;
import java.util.Date;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import devopsdistilled.operp.server.data.entity.employee.Employee;
import devopsdistilled.operp.server.data.repo.employee.EmployeeRepository;
import devopsdistilled.operp.server.data.service.employee.EmployeeService;
import devopsdistilled.operp.server.data.service.impl.AbstractEntityService;
@Service
public class EmployeeServiceImpl extends
AbstractEntityService<Employee, Long, EmployeeRepository> implements
EmployeeService {
private static final long serialVersionUID = 2648525777561781085L;
@Inject
private EmployeeRepository repo;
@Override
protected EmployeeRepository getRepo() {
return repo;
}
@Override
protected Employee findByEntityName(String entityName) {
return null;
}
@Override
public <S extends Employee> S save(S employee) {
if (employee.getJoinedDate() == null)
employee.setJoinedDate(new Date());
return super.save(employee);
}
}
|
Add join date when persist
|
Add join date when persist
OPEN - task 88: Create HR module
http://github.com/DevOpsDistilled/OpERP/issues/issue/88
|
Java
|
mit
|
DevOpsDistilled/OpERP,njmube/OpERP
|
java
|
## Code Before:
package devopsdistilled.operp.server.data.service.employee.impl;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import devopsdistilled.operp.server.data.entity.employee.Employee;
import devopsdistilled.operp.server.data.repo.employee.EmployeeRepository;
import devopsdistilled.operp.server.data.service.employee.EmployeeService;
import devopsdistilled.operp.server.data.service.impl.AbstractEntityService;
@Service
public class EmployeeServiceImpl extends
AbstractEntityService<Employee, Long, EmployeeRepository> implements
EmployeeService {
private static final long serialVersionUID = 2648525777561781085L;
@Inject
private EmployeeRepository repo;
@Override
protected EmployeeRepository getRepo() {
return repo;
}
@Override
protected Employee findByEntityName(String entityName) {
return null;
}
}
## Instruction:
Add join date when persist
OPEN - task 88: Create HR module
http://github.com/DevOpsDistilled/OpERP/issues/issue/88
## Code After:
package devopsdistilled.operp.server.data.service.employee.impl;
import java.util.Date;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import devopsdistilled.operp.server.data.entity.employee.Employee;
import devopsdistilled.operp.server.data.repo.employee.EmployeeRepository;
import devopsdistilled.operp.server.data.service.employee.EmployeeService;
import devopsdistilled.operp.server.data.service.impl.AbstractEntityService;
@Service
public class EmployeeServiceImpl extends
AbstractEntityService<Employee, Long, EmployeeRepository> implements
EmployeeService {
private static final long serialVersionUID = 2648525777561781085L;
@Inject
private EmployeeRepository repo;
@Override
protected EmployeeRepository getRepo() {
return repo;
}
@Override
protected Employee findByEntityName(String entityName) {
return null;
}
@Override
public <S extends Employee> S save(S employee) {
if (employee.getJoinedDate() == null)
employee.setJoinedDate(new Date());
return super.save(employee);
}
}
|
...
package devopsdistilled.operp.server.data.service.employee.impl;
import java.util.Date;
import javax.inject.Inject;
...
return null;
}
@Override
public <S extends Employee> S save(S employee) {
if (employee.getJoinedDate() == null)
employee.setJoinedDate(new Date());
return super.save(employee);
}
}
...
|
99fba41b7392b1e5e4216145f1e8913698b60914
|
mopidy_gmusic/commands.py
|
mopidy_gmusic/commands.py
|
import gmusicapi
from mopidy import commands
from oauth2client.client import OAuth2WebServerFlow
class GMusicCommand(commands.Command):
def __init__(self):
super().__init__()
self.add_child("login", LoginCommand())
class LoginCommand(commands.Command):
def run(self, args, config):
oauth_info = gmusicapi.Mobileclient._session_class.oauth
flow = OAuth2WebServerFlow(**oauth_info._asdict())
print()
print(
"Go to the following URL to get an initial auth code, then "
+ "provide it below: "
+ flow.step1_get_authorize_url()
)
print()
try:
initial_code = raw_input("code: ")
except NameError:
# Python 3
initial_code = input("code: ")
credentials = flow.step2_exchange(initial_code)
refresh_token = credentials.refresh_token
print("\nPlease update your config to include the following:")
print()
print("[gmusic]")
print("refresh_token =", refresh_token)
print()
|
import gmusicapi
from mopidy import commands
from oauth2client.client import OAuth2WebServerFlow
class GMusicCommand(commands.Command):
def __init__(self):
super().__init__()
self.add_child("login", LoginCommand())
class LoginCommand(commands.Command):
def run(self, args, config):
oauth_info = gmusicapi.Mobileclient._session_class.oauth
flow = OAuth2WebServerFlow(**oauth_info._asdict())
print()
print(
"Go to the following URL to get an initial auth code, "
"then provide it below:"
)
print(flow.step1_get_authorize_url())
print()
initial_code = input("code: ")
credentials = flow.step2_exchange(initial_code)
refresh_token = credentials.refresh_token
print("\nPlease update your config to include the following:")
print()
print("[gmusic]")
print("refresh_token =", refresh_token)
print()
|
Remove Python 2 compatibility code
|
py3: Remove Python 2 compatibility code
|
Python
|
apache-2.0
|
hechtus/mopidy-gmusic,mopidy/mopidy-gmusic
|
python
|
## Code Before:
import gmusicapi
from mopidy import commands
from oauth2client.client import OAuth2WebServerFlow
class GMusicCommand(commands.Command):
def __init__(self):
super().__init__()
self.add_child("login", LoginCommand())
class LoginCommand(commands.Command):
def run(self, args, config):
oauth_info = gmusicapi.Mobileclient._session_class.oauth
flow = OAuth2WebServerFlow(**oauth_info._asdict())
print()
print(
"Go to the following URL to get an initial auth code, then "
+ "provide it below: "
+ flow.step1_get_authorize_url()
)
print()
try:
initial_code = raw_input("code: ")
except NameError:
# Python 3
initial_code = input("code: ")
credentials = flow.step2_exchange(initial_code)
refresh_token = credentials.refresh_token
print("\nPlease update your config to include the following:")
print()
print("[gmusic]")
print("refresh_token =", refresh_token)
print()
## Instruction:
py3: Remove Python 2 compatibility code
## Code After:
import gmusicapi
from mopidy import commands
from oauth2client.client import OAuth2WebServerFlow
class GMusicCommand(commands.Command):
def __init__(self):
super().__init__()
self.add_child("login", LoginCommand())
class LoginCommand(commands.Command):
def run(self, args, config):
oauth_info = gmusicapi.Mobileclient._session_class.oauth
flow = OAuth2WebServerFlow(**oauth_info._asdict())
print()
print(
"Go to the following URL to get an initial auth code, "
"then provide it below:"
)
print(flow.step1_get_authorize_url())
print()
initial_code = input("code: ")
credentials = flow.step2_exchange(initial_code)
refresh_token = credentials.refresh_token
print("\nPlease update your config to include the following:")
print()
print("[gmusic]")
print("refresh_token =", refresh_token)
print()
|
...
flow = OAuth2WebServerFlow(**oauth_info._asdict())
print()
print(
"Go to the following URL to get an initial auth code, "
"then provide it below:"
)
print(flow.step1_get_authorize_url())
print()
initial_code = input("code: ")
credentials = flow.step2_exchange(initial_code)
refresh_token = credentials.refresh_token
print("\nPlease update your config to include the following:")
...
|
508c9ef5f7dfd974fdad650cf1a211dad9d41db5
|
skipper/config.py
|
skipper/config.py
|
from string import Template
from collections import defaultdict
import os
import yaml
def load_defaults():
skipper_conf = 'skipper.yaml'
defaults = {}
if os.path.exists(skipper_conf):
with open(skipper_conf) as confile:
config = yaml.load(confile)
containers = config.pop('containers', None)
_normalize_config(config, defaults)
if containers is not None:
defaults['containers'] = containers
return defaults
def _normalize_config(config, normalized_config):
for key, value in config.iteritems():
if isinstance(value, dict):
normalized_config[key] = {}
_normalize_config(value, normalized_config[key])
elif isinstance(value, list):
normalized_config[key] = value
else:
normalized_key = key.replace('-', '_')
normalized_config[normalized_key] = _interpolate_env_vars(value)
def _interpolate_env_vars(key):
return Template(key).substitute(defaultdict(lambda: "", os.environ))
|
from string import Template
from collections import defaultdict
import os
import yaml
def load_defaults():
skipper_conf = 'skipper.yaml'
defaults = {}
if os.path.exists(skipper_conf):
with open(skipper_conf) as confile:
config = yaml.load(confile)
containers = config.pop('containers', None)
_normalize_config(config, defaults)
if containers is not None:
defaults['containers'] = containers
return defaults
def _normalize_config(config, normalized_config):
for key, value in config.iteritems():
if isinstance(value, dict):
normalized_config[key] = {}
_normalize_config(value, normalized_config[key])
elif isinstance(value, list):
normalized_config[key] = [_interpolate_env_vars(x) for x in value]
else:
normalized_key = key.replace('-', '_')
normalized_config[normalized_key] = _interpolate_env_vars(value)
def _interpolate_env_vars(key):
return Template(key).substitute(defaultdict(lambda: "", os.environ))
|
Handle env vars in volumes
|
Handle env vars in volumes
|
Python
|
apache-2.0
|
Stratoscale/skipper,Stratoscale/skipper
|
python
|
## Code Before:
from string import Template
from collections import defaultdict
import os
import yaml
def load_defaults():
skipper_conf = 'skipper.yaml'
defaults = {}
if os.path.exists(skipper_conf):
with open(skipper_conf) as confile:
config = yaml.load(confile)
containers = config.pop('containers', None)
_normalize_config(config, defaults)
if containers is not None:
defaults['containers'] = containers
return defaults
def _normalize_config(config, normalized_config):
for key, value in config.iteritems():
if isinstance(value, dict):
normalized_config[key] = {}
_normalize_config(value, normalized_config[key])
elif isinstance(value, list):
normalized_config[key] = value
else:
normalized_key = key.replace('-', '_')
normalized_config[normalized_key] = _interpolate_env_vars(value)
def _interpolate_env_vars(key):
return Template(key).substitute(defaultdict(lambda: "", os.environ))
## Instruction:
Handle env vars in volumes
## Code After:
from string import Template
from collections import defaultdict
import os
import yaml
def load_defaults():
skipper_conf = 'skipper.yaml'
defaults = {}
if os.path.exists(skipper_conf):
with open(skipper_conf) as confile:
config = yaml.load(confile)
containers = config.pop('containers', None)
_normalize_config(config, defaults)
if containers is not None:
defaults['containers'] = containers
return defaults
def _normalize_config(config, normalized_config):
for key, value in config.iteritems():
if isinstance(value, dict):
normalized_config[key] = {}
_normalize_config(value, normalized_config[key])
elif isinstance(value, list):
normalized_config[key] = [_interpolate_env_vars(x) for x in value]
else:
normalized_key = key.replace('-', '_')
normalized_config[normalized_key] = _interpolate_env_vars(value)
def _interpolate_env_vars(key):
return Template(key).substitute(defaultdict(lambda: "", os.environ))
|
// ... existing code ...
normalized_config[key] = {}
_normalize_config(value, normalized_config[key])
elif isinstance(value, list):
normalized_config[key] = [_interpolate_env_vars(x) for x in value]
else:
normalized_key = key.replace('-', '_')
normalized_config[normalized_key] = _interpolate_env_vars(value)
// ... rest of the code ...
|
344457b498f12dfceb8e687b326ba68064d6bda6
|
run-tests.py
|
run-tests.py
|
import os
PROJECT_DIR = os.path.abspath(os.path.dirname( __file__ ))
SRC_DIR = os.path.join(PROJECT_DIR, "src")
TEST_DIR = os.path.join(PROJECT_DIR, "test")
def runtestdir(subdir):
#cwd = os.getcwd()
#subdir = os.path.join(cwd, subdir)
entries = os.listdir(subdir)
total = 0
errs = 0
for f in entries:
if not f.endswith(".py"):
continue
if not f.startswith("test_"):
continue
cmd = "python %s/%s" % (subdir, f)
print "FILE: %s/%s" % (subdir, f)
exit_code = os.system(cmd)
total += 1
if exit_code != 0:
errs += 1
print "SUMMARY: %s -> %s total / %s error" % (subdir, total, errs)
if __name__ == "__main__":
#
os.chdir(TEST_DIR)
#
os.environ["PYTHONPATH"] = ":".join([SRC_DIR, TEST_DIR])
#
runtestdir("bindertest")
|
import os, sys
PROJECT_DIR = os.path.abspath(os.path.dirname( __file__ ))
SRC_DIR = os.path.join(PROJECT_DIR, "src")
TEST_DIR = os.path.join(PROJECT_DIR, "test")
def runtestdir(subdir):
entries = os.listdir(subdir)
total = 0
errs = 0
for f in entries:
if not f.endswith(".py"):
continue
if not f.startswith("test_"):
continue
test_file = os.path.join(subdir, f)
print "FILE:", test_file
exit_code = os.system(sys.executable + " " + test_file)
total += 1
if exit_code != 0:
errs += 1
print "SUMMARY: %s -> %s total / %s error (%s)" \
% (subdir, total, errs, sys.executable)
if __name__ == "__main__":
os.chdir(TEST_DIR)
os.environ["PYTHONPATH"] = ":".join([SRC_DIR, TEST_DIR])
runtestdir("bindertest")
|
Test runner uses current python
|
Test runner uses current python
|
Python
|
mit
|
divtxt/binder
|
python
|
## Code Before:
import os
PROJECT_DIR = os.path.abspath(os.path.dirname( __file__ ))
SRC_DIR = os.path.join(PROJECT_DIR, "src")
TEST_DIR = os.path.join(PROJECT_DIR, "test")
def runtestdir(subdir):
#cwd = os.getcwd()
#subdir = os.path.join(cwd, subdir)
entries = os.listdir(subdir)
total = 0
errs = 0
for f in entries:
if not f.endswith(".py"):
continue
if not f.startswith("test_"):
continue
cmd = "python %s/%s" % (subdir, f)
print "FILE: %s/%s" % (subdir, f)
exit_code = os.system(cmd)
total += 1
if exit_code != 0:
errs += 1
print "SUMMARY: %s -> %s total / %s error" % (subdir, total, errs)
if __name__ == "__main__":
#
os.chdir(TEST_DIR)
#
os.environ["PYTHONPATH"] = ":".join([SRC_DIR, TEST_DIR])
#
runtestdir("bindertest")
## Instruction:
Test runner uses current python
## Code After:
import os, sys
PROJECT_DIR = os.path.abspath(os.path.dirname( __file__ ))
SRC_DIR = os.path.join(PROJECT_DIR, "src")
TEST_DIR = os.path.join(PROJECT_DIR, "test")
def runtestdir(subdir):
entries = os.listdir(subdir)
total = 0
errs = 0
for f in entries:
if not f.endswith(".py"):
continue
if not f.startswith("test_"):
continue
test_file = os.path.join(subdir, f)
print "FILE:", test_file
exit_code = os.system(sys.executable + " " + test_file)
total += 1
if exit_code != 0:
errs += 1
print "SUMMARY: %s -> %s total / %s error (%s)" \
% (subdir, total, errs, sys.executable)
if __name__ == "__main__":
os.chdir(TEST_DIR)
os.environ["PYTHONPATH"] = ":".join([SRC_DIR, TEST_DIR])
runtestdir("bindertest")
|
...
import os, sys
PROJECT_DIR = os.path.abspath(os.path.dirname( __file__ ))
SRC_DIR = os.path.join(PROJECT_DIR, "src")
...
TEST_DIR = os.path.join(PROJECT_DIR, "test")
def runtestdir(subdir):
entries = os.listdir(subdir)
total = 0
errs = 0
...
continue
if not f.startswith("test_"):
continue
test_file = os.path.join(subdir, f)
print "FILE:", test_file
exit_code = os.system(sys.executable + " " + test_file)
total += 1
if exit_code != 0:
errs += 1
print "SUMMARY: %s -> %s total / %s error (%s)" \
% (subdir, total, errs, sys.executable)
if __name__ == "__main__":
os.chdir(TEST_DIR)
os.environ["PYTHONPATH"] = ":".join([SRC_DIR, TEST_DIR])
runtestdir("bindertest")
...
|
a3c68f6f70a2d4d1ecdcdb982eda9ec15fa4c127
|
utils.py
|
utils.py
|
from google.appengine.api import users
from google.appengine.ext import db
from model import User
@db.transactional
def create_user(google_user):
user = User(
google_user=google_user
)
user.put()
return user
def get_current_user():
google_user = users.get_current_user()
user = get_user_model_for(google_user)
return user
def get_user_model_for(google_user=None):
return User.all().filter('google_user =', google_user).get()
def get_user_model_by_id_or_nick(id_or_nick):
if id_or_nick.isdigit():
return User.get_by_id(int(id_or_nick))
else:
return User.all().filter('nickname_lower = ', id_or_nick.lower()).get()
|
from google.appengine.api import users
from google.appengine.ext import db
from model import User
latest_signup = None
@db.transactional
def create_user(google_user):
global latest_signup
user = User(
google_user=google_user
)
user.put()
latest_signup = user
return user
def get_current_user():
google_user = users.get_current_user()
if latest_signup != None and google_user == latest_signup.google_user:
return latest_signup
user = get_user_model_for(google_user)
return user
def get_user_model_for(google_user=None):
return User.all().filter('google_user =', google_user).get()
def get_user_model_by_id_or_nick(id_or_nick):
if id_or_nick.isdigit():
return User.get_by_id(int(id_or_nick))
else:
return User.all().filter('nickname_lower = ', id_or_nick.lower()).get()
|
Fix bug where user could not be found
|
Fix bug where user could not be found
This problem only occured when a request tried to find the user right
after it had been created.
|
Python
|
mit
|
youtify/newscontrol,studyindenmark/newscontrol,studyindenmark/newscontrol,youtify/newscontrol
|
python
|
## Code Before:
from google.appengine.api import users
from google.appengine.ext import db
from model import User
@db.transactional
def create_user(google_user):
user = User(
google_user=google_user
)
user.put()
return user
def get_current_user():
google_user = users.get_current_user()
user = get_user_model_for(google_user)
return user
def get_user_model_for(google_user=None):
return User.all().filter('google_user =', google_user).get()
def get_user_model_by_id_or_nick(id_or_nick):
if id_or_nick.isdigit():
return User.get_by_id(int(id_or_nick))
else:
return User.all().filter('nickname_lower = ', id_or_nick.lower()).get()
## Instruction:
Fix bug where user could not be found
This problem only occured when a request tried to find the user right
after it had been created.
## Code After:
from google.appengine.api import users
from google.appengine.ext import db
from model import User
latest_signup = None
@db.transactional
def create_user(google_user):
global latest_signup
user = User(
google_user=google_user
)
user.put()
latest_signup = user
return user
def get_current_user():
google_user = users.get_current_user()
if latest_signup != None and google_user == latest_signup.google_user:
return latest_signup
user = get_user_model_for(google_user)
return user
def get_user_model_for(google_user=None):
return User.all().filter('google_user =', google_user).get()
def get_user_model_by_id_or_nick(id_or_nick):
if id_or_nick.isdigit():
return User.get_by_id(int(id_or_nick))
else:
return User.all().filter('nickname_lower = ', id_or_nick.lower()).get()
|
...
from model import User
latest_signup = None
@db.transactional
def create_user(google_user):
global latest_signup
user = User(
google_user=google_user
)
user.put()
latest_signup = user
return user
def get_current_user():
google_user = users.get_current_user()
if latest_signup != None and google_user == latest_signup.google_user:
return latest_signup
user = get_user_model_for(google_user)
return user
...
|
7d88c98fcf6984b07a8b085f8272868b1c23b29e
|
app/status/views.py
|
app/status/views.py
|
from flask import jsonify, current_app
from . import status
from . import utils
from ..main.services.search_service import status_for_all_indexes
@status.route('/_status')
def status():
db_status = status_for_all_indexes()
if db_status['status_code'] == 200:
return jsonify(
status="ok",
version=utils.get_version_label(),
db_status=db_status
)
current_app.logger.exception("Error connecting to elasticsearch")
return jsonify(
status="error",
version=utils.get_version_label(),
message="Error connecting to elasticsearch",
db_status=db_status
), 500
|
from flask import jsonify, current_app
from . import status
from . import utils
from ..main.services.search_service import status_for_all_indexes
@status.route('/_status')
def status():
db_status = status_for_all_indexes()
if db_status['status_code'] == 200:
return jsonify(
status="ok",
version=utils.get_version_label(),
db_status=db_status
)
current_app.logger.exception("Error connecting to elasticsearch")
return jsonify(
status="error",
version=utils.get_version_label(),
message="Error connecting to elasticsearch",
db_status={
'status_code': 500,
'message': db_status['message'][0]
}
), 500
|
Return correct message if elasticsearch fails to connect.
|
Return correct message if elasticsearch fails to connect.
|
Python
|
mit
|
alphagov/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api
|
python
|
## Code Before:
from flask import jsonify, current_app
from . import status
from . import utils
from ..main.services.search_service import status_for_all_indexes
@status.route('/_status')
def status():
db_status = status_for_all_indexes()
if db_status['status_code'] == 200:
return jsonify(
status="ok",
version=utils.get_version_label(),
db_status=db_status
)
current_app.logger.exception("Error connecting to elasticsearch")
return jsonify(
status="error",
version=utils.get_version_label(),
message="Error connecting to elasticsearch",
db_status=db_status
), 500
## Instruction:
Return correct message if elasticsearch fails to connect.
## Code After:
from flask import jsonify, current_app
from . import status
from . import utils
from ..main.services.search_service import status_for_all_indexes
@status.route('/_status')
def status():
db_status = status_for_all_indexes()
if db_status['status_code'] == 200:
return jsonify(
status="ok",
version=utils.get_version_label(),
db_status=db_status
)
current_app.logger.exception("Error connecting to elasticsearch")
return jsonify(
status="error",
version=utils.get_version_label(),
message="Error connecting to elasticsearch",
db_status={
'status_code': 500,
'message': db_status['message'][0]
}
), 500
|
// ... existing code ...
status="error",
version=utils.get_version_label(),
message="Error connecting to elasticsearch",
db_status={
'status_code': 500,
'message': db_status['message'][0]
}
), 500
// ... rest of the code ...
|
1ba9539ab5b61e02626bab65730d33562a6f8924
|
hibernate-ogm-core/src/test/java/org/hibernate/ogm/test/simpleentity/Hypothesis.java
|
hibernate-ogm-core/src/test/java/org/hibernate/ogm/test/simpleentity/Hypothesis.java
|
package org.hibernate.ogm.test.simpleentity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.Persister;
import org.hibernate.ogm.persister.OgmEntityPersister;
/**
* @author Emmanuel Bernard
*/
@Entity @Persister( impl = OgmEntityPersister.class)
public class Hypothesis {
@Id @GeneratedValue
public String getId() { return id; }
public void setId(String id) { this.id = id; }
private String id;
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
private String description;
}
|
package org.hibernate.ogm.test.simpleentity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.Persister;
import org.hibernate.ogm.persister.OgmEntityPersister;
/**
* @author Emmanuel Bernard
*/
@Entity @Persister( impl = OgmEntityPersister.class)
public class Hypothesis {
@Id
public String getId() { return id; }
public void setId(String id) { this.id = id; }
private String id;
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
private String description;
}
|
Remove @GeneratedValue from test entity as the id is provided
|
Remove @GeneratedValue from test entity as the id is provided
|
Java
|
lgpl-2.1
|
DavideD/hibernate-ogm,DavideD/hibernate-ogm,uugaa/hibernate-ogm,gunnarmorling/hibernate-ogm,gunnarmorling/hibernate-ogm,tempbottle/hibernate-ogm,ZJaffee/hibernate-ogm,uugaa/hibernate-ogm,DavideD/hibernate-ogm-contrib,uugaa/hibernate-ogm,Sanne/hibernate-ogm,tempbottle/hibernate-ogm,schernolyas/hibernate-ogm,DavideD/hibernate-ogm,hibernate/hibernate-ogm,schernolyas/hibernate-ogm,mp911de/hibernate-ogm,hibernate/hibernate-ogm,jhalliday/hibernate-ogm,jhalliday/hibernate-ogm,emmanuelbernard/hibernate-ogm,DavideD/hibernate-ogm,jhalliday/hibernate-ogm,Sanne/hibernate-ogm,gunnarmorling/hibernate-ogm,DavideD/hibernate-ogm-cassandra,hibernate/hibernate-ogm,DavideD/hibernate-ogm-cassandra,DavideD/hibernate-ogm-contrib,Sanne/hibernate-ogm,mp911de/hibernate-ogm,mp911de/hibernate-ogm,DavideD/hibernate-ogm-contrib,hferentschik/hibernate-ogm,schernolyas/hibernate-ogm,emmanuelbernard/hibernate-ogm-old,DavideD/hibernate-ogm-cassandra,ZJaffee/hibernate-ogm,hibernate/hibernate-ogm,tempbottle/hibernate-ogm,ZJaffee/hibernate-ogm,Sanne/hibernate-ogm
|
java
|
## Code Before:
package org.hibernate.ogm.test.simpleentity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.Persister;
import org.hibernate.ogm.persister.OgmEntityPersister;
/**
* @author Emmanuel Bernard
*/
@Entity @Persister( impl = OgmEntityPersister.class)
public class Hypothesis {
@Id @GeneratedValue
public String getId() { return id; }
public void setId(String id) { this.id = id; }
private String id;
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
private String description;
}
## Instruction:
Remove @GeneratedValue from test entity as the id is provided
## Code After:
package org.hibernate.ogm.test.simpleentity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.Persister;
import org.hibernate.ogm.persister.OgmEntityPersister;
/**
* @author Emmanuel Bernard
*/
@Entity @Persister( impl = OgmEntityPersister.class)
public class Hypothesis {
@Id
public String getId() { return id; }
public void setId(String id) { this.id = id; }
private String id;
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
private String description;
}
|
# ... existing code ...
@Entity @Persister( impl = OgmEntityPersister.class)
public class Hypothesis {
@Id
public String getId() { return id; }
public void setId(String id) { this.id = id; }
private String id;
# ... rest of the code ...
|
16fd41602effad59961e4004ba9948a5be2364a2
|
src/main/java/com/theironyard/controllers/VertoSwapController.java
|
src/main/java/com/theironyard/controllers/VertoSwapController.java
|
package com.theironyard.controllers;
import com.theironyard.entities.User;
import com.theironyard.services.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
/**
* Created by Dan on 7/19/16.
*/
@RestController
public class VertoSwapController {
@Autowired
UserRepository users;
@RequestMapping(path = "/login", method = RequestMethod.POST)
public void login(HttpSession session, @RequestBody User user) {
//User userFromDB = users.findByName
}
}
|
package com.theironyard.controllers;
import com.theironyard.entities.User;
import com.theironyard.services.UserRepository;
import com.theironyard.utilities.PasswordStorage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpSession;
/**
* Created by Dan on 7/19/16.
*/
@Controller
public class VertoSwapController {
@Autowired
UserRepository users;
@RequestMapping(path = "/account-create", method = RequestMethod.POST)
public String createAccount(HttpSession session, String username, String password) throws Exception {
User user = users.findByName(username);
if (user != null) {
throw new Exception("Username unavailable.");
}
else {
user = new User(username, PasswordStorage.createHash(password));
users.save(user);
session.setAttribute("username", username);
}
return "redirect:/";
}
@RequestMapping(path = "/login", method = RequestMethod.POST)
public String login(HttpSession session, String username, String password) throws Exception {
User userFromDB = users.findByName(username);
if (userFromDB == null) {
return "redirect:/create-account";
}
else if (!PasswordStorage.verifyPassword(password, userFromDB.getPassword())) {
throw new Exception("Wrong password.");
}
session.setAttribute("username", username);
return "redirect:/";
}
@RequestMapping(path = "/logout", method = RequestMethod.POST)
public String logout(HttpSession session) {
session.invalidate();
return "redirect:/";
}
}
|
Create login, logout, create account routes
|
Create login, logout, create account routes
|
Java
|
mit
|
danvoss/VertoSwap,VertoSwap/VertoSwap,errorPort3R/VertoSwap,VertoSwap/VertoSwap,danvoss/VertoSwap,danvoss/VertoSwap,VertoSwap/VertoSwap,errorPort3R/VertoSwap,errorPort3R/VertoSwap
|
java
|
## Code Before:
package com.theironyard.controllers;
import com.theironyard.entities.User;
import com.theironyard.services.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
/**
* Created by Dan on 7/19/16.
*/
@RestController
public class VertoSwapController {
@Autowired
UserRepository users;
@RequestMapping(path = "/login", method = RequestMethod.POST)
public void login(HttpSession session, @RequestBody User user) {
//User userFromDB = users.findByName
}
}
## Instruction:
Create login, logout, create account routes
## Code After:
package com.theironyard.controllers;
import com.theironyard.entities.User;
import com.theironyard.services.UserRepository;
import com.theironyard.utilities.PasswordStorage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpSession;
/**
* Created by Dan on 7/19/16.
*/
@Controller
public class VertoSwapController {
@Autowired
UserRepository users;
@RequestMapping(path = "/account-create", method = RequestMethod.POST)
public String createAccount(HttpSession session, String username, String password) throws Exception {
User user = users.findByName(username);
if (user != null) {
throw new Exception("Username unavailable.");
}
else {
user = new User(username, PasswordStorage.createHash(password));
users.save(user);
session.setAttribute("username", username);
}
return "redirect:/";
}
@RequestMapping(path = "/login", method = RequestMethod.POST)
public String login(HttpSession session, String username, String password) throws Exception {
User userFromDB = users.findByName(username);
if (userFromDB == null) {
return "redirect:/create-account";
}
else if (!PasswordStorage.verifyPassword(password, userFromDB.getPassword())) {
throw new Exception("Wrong password.");
}
session.setAttribute("username", username);
return "redirect:/";
}
@RequestMapping(path = "/logout", method = RequestMethod.POST)
public String logout(HttpSession session) {
session.invalidate();
return "redirect:/";
}
}
|
# ... existing code ...
import com.theironyard.entities.User;
import com.theironyard.services.UserRepository;
import com.theironyard.utilities.PasswordStorage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpSession;
# ... modified code ...
/**
* Created by Dan on 7/19/16.
*/
@Controller
public class VertoSwapController {
@Autowired
UserRepository users;
@RequestMapping(path = "/account-create", method = RequestMethod.POST)
public String createAccount(HttpSession session, String username, String password) throws Exception {
User user = users.findByName(username);
if (user != null) {
throw new Exception("Username unavailable.");
}
else {
user = new User(username, PasswordStorage.createHash(password));
users.save(user);
session.setAttribute("username", username);
}
return "redirect:/";
}
@RequestMapping(path = "/login", method = RequestMethod.POST)
public String login(HttpSession session, String username, String password) throws Exception {
User userFromDB = users.findByName(username);
if (userFromDB == null) {
return "redirect:/create-account";
}
else if (!PasswordStorage.verifyPassword(password, userFromDB.getPassword())) {
throw new Exception("Wrong password.");
}
session.setAttribute("username", username);
return "redirect:/";
}
@RequestMapping(path = "/logout", method = RequestMethod.POST)
public String logout(HttpSession session) {
session.invalidate();
return "redirect:/";
}
}
# ... rest of the code ...
|
af7c239ac6629f7bd102b3e648c0dd86c2054407
|
os/gl/gl_context_nsgl.h
|
os/gl/gl_context_nsgl.h
|
// LAF OS Library
// Copyright (C) 2022 Igara Studio S.A.
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#ifndef OS_GL_CONTEXT_NSGL_INCLUDED
#define OS_GL_CONTEXT_NSGL_INCLUDED
#pragma once
#include "os/gl/gl_context.h"
namespace os {
class GLContextNSGL : public GLContext {
public:
GLContextNSGL();
~GLContextNSGL();
void setView(id view);
bool isValid() override;
bool createGLContext() override;
void destroyGLContext() override;
void makeCurrent() override;
void swapBuffers() override;
id nsglContext() {
return m_nsgl;
}
private:
id m_nsgl = nil; // NSOpenGLContext
id m_view = nil; // NSView
};
} // namespace os
#endif
|
// LAF OS Library
// Copyright (C) 2022 Igara Studio S.A.
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#ifndef OS_GL_CONTEXT_NSGL_INCLUDED
#define OS_GL_CONTEXT_NSGL_INCLUDED
#pragma once
#include "os/gl/gl_context.h"
namespace os {
class GLContextNSGL : public GLContext {
public:
GLContextNSGL();
~GLContextNSGL();
void setView(id view);
bool isValid() override;
bool createGLContext() override;
void destroyGLContext() override;
void makeCurrent() override;
void swapBuffers() override;
id nsglContext() {
return m_nsgl;
}
private:
id m_nsgl = nullptr; // NSOpenGLContext
id m_view = nullptr; // NSView
};
} // namespace os
#endif
|
Replace nil with nullptr in GLContextNSGL to compile correctly
|
[osx] Replace nil with nullptr in GLContextNSGL to compile correctly
|
C
|
mit
|
aseprite/laf,aseprite/laf
|
c
|
## Code Before:
// LAF OS Library
// Copyright (C) 2022 Igara Studio S.A.
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#ifndef OS_GL_CONTEXT_NSGL_INCLUDED
#define OS_GL_CONTEXT_NSGL_INCLUDED
#pragma once
#include "os/gl/gl_context.h"
namespace os {
class GLContextNSGL : public GLContext {
public:
GLContextNSGL();
~GLContextNSGL();
void setView(id view);
bool isValid() override;
bool createGLContext() override;
void destroyGLContext() override;
void makeCurrent() override;
void swapBuffers() override;
id nsglContext() {
return m_nsgl;
}
private:
id m_nsgl = nil; // NSOpenGLContext
id m_view = nil; // NSView
};
} // namespace os
#endif
## Instruction:
[osx] Replace nil with nullptr in GLContextNSGL to compile correctly
## Code After:
// LAF OS Library
// Copyright (C) 2022 Igara Studio S.A.
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#ifndef OS_GL_CONTEXT_NSGL_INCLUDED
#define OS_GL_CONTEXT_NSGL_INCLUDED
#pragma once
#include "os/gl/gl_context.h"
namespace os {
class GLContextNSGL : public GLContext {
public:
GLContextNSGL();
~GLContextNSGL();
void setView(id view);
bool isValid() override;
bool createGLContext() override;
void destroyGLContext() override;
void makeCurrent() override;
void swapBuffers() override;
id nsglContext() {
return m_nsgl;
}
private:
id m_nsgl = nullptr; // NSOpenGLContext
id m_view = nullptr; // NSView
};
} // namespace os
#endif
|
...
}
private:
id m_nsgl = nullptr; // NSOpenGLContext
id m_view = nullptr; // NSView
};
} // namespace os
...
|
6cfb0ca69b43784d495920865f0a250f7d16ff84
|
trump/extensions/loader.py
|
trump/extensions/loader.py
|
from imp import find_module, load_module
import os
class SourceExtension(object):
def __init__(self, mod):
self.initialized = False
self.mod = mod
self.renew = mod.renew
self.Source = mod.Source
def __call__(self, _ses, **kwargs):
if not self.initialized or self.renew:
self.fetcher = self.Source(_ses, **kwargs)
self.initialized = True
return self.fetcher.getseries(_ses, **kwargs)
sources = {}
curdir = os.path.dirname(os.path.realpath(__file__))
extension_names = os.listdir(os.path.join(curdir,'source'))
for name in extension_names:
ext = find_module(name, ['source'])
mod = load_module(name, *ext)
sources[mod.stype] = SourceExtension(mod)
|
from imp import find_module, load_module
import os
class SourceExtension(object):
def __init__(self, mod):
self.initialized = False
self.mod = mod
self.renew = mod.renew
self.Source = mod.Source
def __call__(self, _ses, **kwargs):
if not self.initialized or self.renew:
self.fetcher = self.Source(_ses, **kwargs)
self.initialized = True
return self.fetcher.getseries(_ses, **kwargs)
sources = {}
curdir = os.path.dirname(os.path.realpath(__file__))
sourcedir = os.path.join(curdir,'source')
extension_names = os.listdir(sourcedir)
for name in extension_names:
ext = find_module(name, [sourcedir])
mod = load_module(name, *ext)
sources[mod.stype] = SourceExtension(mod)
|
Use full path to find mods
|
Use full path to find mods
|
Python
|
bsd-3-clause
|
jnmclarty/trump,Equitable/trump
|
python
|
## Code Before:
from imp import find_module, load_module
import os
class SourceExtension(object):
def __init__(self, mod):
self.initialized = False
self.mod = mod
self.renew = mod.renew
self.Source = mod.Source
def __call__(self, _ses, **kwargs):
if not self.initialized or self.renew:
self.fetcher = self.Source(_ses, **kwargs)
self.initialized = True
return self.fetcher.getseries(_ses, **kwargs)
sources = {}
curdir = os.path.dirname(os.path.realpath(__file__))
extension_names = os.listdir(os.path.join(curdir,'source'))
for name in extension_names:
ext = find_module(name, ['source'])
mod = load_module(name, *ext)
sources[mod.stype] = SourceExtension(mod)
## Instruction:
Use full path to find mods
## Code After:
from imp import find_module, load_module
import os
class SourceExtension(object):
def __init__(self, mod):
self.initialized = False
self.mod = mod
self.renew = mod.renew
self.Source = mod.Source
def __call__(self, _ses, **kwargs):
if not self.initialized or self.renew:
self.fetcher = self.Source(_ses, **kwargs)
self.initialized = True
return self.fetcher.getseries(_ses, **kwargs)
sources = {}
curdir = os.path.dirname(os.path.realpath(__file__))
sourcedir = os.path.join(curdir,'source')
extension_names = os.listdir(sourcedir)
for name in extension_names:
ext = find_module(name, [sourcedir])
mod = load_module(name, *ext)
sources[mod.stype] = SourceExtension(mod)
|
# ... existing code ...
sources = {}
curdir = os.path.dirname(os.path.realpath(__file__))
sourcedir = os.path.join(curdir,'source')
extension_names = os.listdir(sourcedir)
for name in extension_names:
ext = find_module(name, [sourcedir])
mod = load_module(name, *ext)
sources[mod.stype] = SourceExtension(mod)
# ... rest of the code ...
|
2f451bfd1a617877816b538b4d57ac9d14a362b4
|
src/main/java/seedu/address/ui/PersonCard.java
|
src/main/java/seedu/address/ui/PersonCard.java
|
package seedu.address.ui;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import seedu.address.model.person.ReadOnlyPerson;
public class PersonCard extends UiPart{
private static final String FXML = "PersonListCard.fxml";
@FXML
private HBox cardPane;
@FXML
private Label name;
@FXML
private Label id;
@FXML
private Label phone;
@FXML
private Label address;
@FXML
private Label email;
@FXML
private Label tags;
private ReadOnlyPerson person;
private int displayedIndex;
public PersonCard(){
}
public static PersonCard load(ReadOnlyPerson person, int displayedIndex){
PersonCard card = new PersonCard();
card.person = person;
card.displayedIndex = displayedIndex;
return UiPartLoader.loadUiPart(card);
}
@FXML
public void initialize() {
name.setText(person.getName().fullName);
id.setText(displayedIndex + ". ");
phone.setText(person.getPhone().value);
address.setText(person.getAddress().value);
email.setText(person.getEmail().value);
tags.setText(person.tagsString());
}
public HBox getLayout() {
return cardPane;
}
@Override
public void setNode(Node node) {
cardPane = (HBox)node;
}
@Override
public String getFxmlPath() {
return FXML;
}
}
|
package seedu.address.ui;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import seedu.address.model.person.ReadOnlyPerson;
public class PersonCard extends UiPart{
private static final String FXML = "PersonListCard.fxml";
@FXML
private HBox cardPane;
@FXML
private Label name;
@FXML
private Label id;
@FXML
private Label tags;
private ReadOnlyPerson person;
private int displayedIndex;
public PersonCard(){
}
public static PersonCard load(ReadOnlyPerson person, int displayedIndex){
PersonCard card = new PersonCard();
card.person = person;
card.displayedIndex = displayedIndex;
return UiPartLoader.loadUiPart(card);
}
@FXML
public void initialize() {
name.setText(person.getName().fullName);
id.setText(displayedIndex + ". ");
tags.setText(person.tagsString());
}
public HBox getLayout() {
return cardPane;
}
@Override
public void setNode(Node node) {
cardPane = (HBox)node;
}
@Override
public String getFxmlPath() {
return FXML;
}
}
|
Remove phone, address and email from Personcard class in UI
|
Remove phone, address and email from Personcard class in UI
|
Java
|
mit
|
CS2103AUG2016-W11-C2/main
|
java
|
## Code Before:
package seedu.address.ui;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import seedu.address.model.person.ReadOnlyPerson;
public class PersonCard extends UiPart{
private static final String FXML = "PersonListCard.fxml";
@FXML
private HBox cardPane;
@FXML
private Label name;
@FXML
private Label id;
@FXML
private Label phone;
@FXML
private Label address;
@FXML
private Label email;
@FXML
private Label tags;
private ReadOnlyPerson person;
private int displayedIndex;
public PersonCard(){
}
public static PersonCard load(ReadOnlyPerson person, int displayedIndex){
PersonCard card = new PersonCard();
card.person = person;
card.displayedIndex = displayedIndex;
return UiPartLoader.loadUiPart(card);
}
@FXML
public void initialize() {
name.setText(person.getName().fullName);
id.setText(displayedIndex + ". ");
phone.setText(person.getPhone().value);
address.setText(person.getAddress().value);
email.setText(person.getEmail().value);
tags.setText(person.tagsString());
}
public HBox getLayout() {
return cardPane;
}
@Override
public void setNode(Node node) {
cardPane = (HBox)node;
}
@Override
public String getFxmlPath() {
return FXML;
}
}
## Instruction:
Remove phone, address and email from Personcard class in UI
## Code After:
package seedu.address.ui;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import seedu.address.model.person.ReadOnlyPerson;
public class PersonCard extends UiPart{
private static final String FXML = "PersonListCard.fxml";
@FXML
private HBox cardPane;
@FXML
private Label name;
@FXML
private Label id;
@FXML
private Label tags;
private ReadOnlyPerson person;
private int displayedIndex;
public PersonCard(){
}
public static PersonCard load(ReadOnlyPerson person, int displayedIndex){
PersonCard card = new PersonCard();
card.person = person;
card.displayedIndex = displayedIndex;
return UiPartLoader.loadUiPart(card);
}
@FXML
public void initialize() {
name.setText(person.getName().fullName);
id.setText(displayedIndex + ". ");
tags.setText(person.tagsString());
}
public HBox getLayout() {
return cardPane;
}
@Override
public void setNode(Node node) {
cardPane = (HBox)node;
}
@Override
public String getFxmlPath() {
return FXML;
}
}
|
# ... existing code ...
private Label name;
@FXML
private Label id;
@FXML
private Label tags;
# ... modified code ...
public void initialize() {
name.setText(person.getName().fullName);
id.setText(displayedIndex + ". ");
tags.setText(person.tagsString());
}
# ... rest of the code ...
|
0b8075e8eb8fb52a9407bfa92d61e5a5363f8861
|
src/example/dump_camera_capabilities.py
|
src/example/dump_camera_capabilities.py
|
import pysony
import fnmatch
camera = pysony.SonyAPI()
#camera = pysony.SonyAPI(QX_ADDR='http://192.168.122.1:8080/')
mode = camera.getAvailableApiList()
print "Available calls:"
for x in (mode["result"]):
for y in x:
print y
filtered = fnmatch.filter(x, "*Supported*")
print "--"
for x in filtered:
print x, ":"
function=getattr(camera, x)
params = function()
print params
print
|
import pysony
import time
import fnmatch
print "Searching for camera"
search = pysony.ControlPoint()
cameras = search.discover()
if len(cameras):
camera = pysony.SonyAPI(QX_ADDR=cameras[0])
else:
print "No camera found, aborting"
quit()
mode = camera.getAvailableApiList()
# For those cameras which need it
if 'startRecMode' in (mode['result'])[0]:
camera.startRecMode()
time.sleep(5)
# and re-read capabilities
mode = camera.getAvailableApiList()
print "Available calls:"
for x in (mode["result"]):
for y in x:
print y
filtered = fnmatch.filter(x, "*Supported*")
print "--"
for x in filtered:
print x, ":"
function=getattr(camera, x)
params = function()
print params
print
|
Add automatic searching capability. Note that camera may return different capabilities depending on its mode dial.
|
Add automatic searching capability.
Note that camera may return different capabilities depending on its mode dial.
|
Python
|
mit
|
Bloodevil/sony_camera_api,mungewell/sony_camera_api,Bloodevil/sony_camera_api
|
python
|
## Code Before:
import pysony
import fnmatch
camera = pysony.SonyAPI()
#camera = pysony.SonyAPI(QX_ADDR='http://192.168.122.1:8080/')
mode = camera.getAvailableApiList()
print "Available calls:"
for x in (mode["result"]):
for y in x:
print y
filtered = fnmatch.filter(x, "*Supported*")
print "--"
for x in filtered:
print x, ":"
function=getattr(camera, x)
params = function()
print params
print
## Instruction:
Add automatic searching capability.
Note that camera may return different capabilities depending on its mode dial.
## Code After:
import pysony
import time
import fnmatch
print "Searching for camera"
search = pysony.ControlPoint()
cameras = search.discover()
if len(cameras):
camera = pysony.SonyAPI(QX_ADDR=cameras[0])
else:
print "No camera found, aborting"
quit()
mode = camera.getAvailableApiList()
# For those cameras which need it
if 'startRecMode' in (mode['result'])[0]:
camera.startRecMode()
time.sleep(5)
# and re-read capabilities
mode = camera.getAvailableApiList()
print "Available calls:"
for x in (mode["result"]):
for y in x:
print y
filtered = fnmatch.filter(x, "*Supported*")
print "--"
for x in filtered:
print x, ":"
function=getattr(camera, x)
params = function()
print params
print
|
// ... existing code ...
import pysony
import time
import fnmatch
print "Searching for camera"
search = pysony.ControlPoint()
cameras = search.discover()
if len(cameras):
camera = pysony.SonyAPI(QX_ADDR=cameras[0])
else:
print "No camera found, aborting"
quit()
mode = camera.getAvailableApiList()
# For those cameras which need it
if 'startRecMode' in (mode['result'])[0]:
camera.startRecMode()
time.sleep(5)
# and re-read capabilities
mode = camera.getAvailableApiList()
print "Available calls:"
for x in (mode["result"]):
// ... rest of the code ...
|
4851829b5d2b6932c94b2e0b59f006a371943c4c
|
src/main/java/com/carrot/carrotshop/listener/PlayerConnexionListener.java
|
src/main/java/com/carrot/carrotshop/listener/PlayerConnexionListener.java
|
package com.carrot.carrotshop.listener;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.Order;
import org.spongepowered.api.event.network.ClientConnectionEvent;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.action.TextActions;
import org.spongepowered.api.text.format.TextColors;
import com.carrot.carrotshop.ShopsData;
public class PlayerConnexionListener {
@Listener(order=Order.LATE)
public void onPlayerJoin(ClientConnectionEvent.Join event)
{
if (ShopsData.hasSoldSomethingOffline(event.getTargetEntity().getUniqueId()) && event.getTargetEntity().hasPermission("carrotshop.report.self")) {
event.getTargetEntity().sendMessage(Text.of(TextColors.YELLOW, "Someone used your shop signs while you were away. Use ",
Text.builder("/cs report")
.color(TextColors.DARK_AQUA)
.onClick(TextActions.runCommand("/cs report")).build(),
TextColors.YELLOW, " for more details" ));
}
}
}
|
package com.carrot.carrotshop.listener;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.Order;
import org.spongepowered.api.event.network.ClientConnectionEvent;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.action.TextActions;
import org.spongepowered.api.text.format.TextColors;
import com.carrot.carrotshop.ShopsData;
public class PlayerConnexionListener {
@Listener(order=Order.LATE)
public void onPlayerJoin(ClientConnectionEvent.Join event)
{
if (ShopsData.hasSoldSomethingOffline(event.getTargetEntity().getUniqueId()) && event.getTargetEntity().hasPermission("carrotshop.report.self")) {
event.getTargetEntity().sendMessage(Text.of(TextColors.YELLOW, "Someone used your shop signs while you were away. Use ",
Text.builder("/carrotreport")
.color(TextColors.DARK_AQUA)
.onClick(TextActions.runCommand("/carrotreport")).build(),
TextColors.YELLOW, " for more details" ));
}
}
}
|
Change command name in hint
|
Change command name in hint
|
Java
|
mit
|
TheoKah/CarrotShop
|
java
|
## Code Before:
package com.carrot.carrotshop.listener;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.Order;
import org.spongepowered.api.event.network.ClientConnectionEvent;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.action.TextActions;
import org.spongepowered.api.text.format.TextColors;
import com.carrot.carrotshop.ShopsData;
public class PlayerConnexionListener {
@Listener(order=Order.LATE)
public void onPlayerJoin(ClientConnectionEvent.Join event)
{
if (ShopsData.hasSoldSomethingOffline(event.getTargetEntity().getUniqueId()) && event.getTargetEntity().hasPermission("carrotshop.report.self")) {
event.getTargetEntity().sendMessage(Text.of(TextColors.YELLOW, "Someone used your shop signs while you were away. Use ",
Text.builder("/cs report")
.color(TextColors.DARK_AQUA)
.onClick(TextActions.runCommand("/cs report")).build(),
TextColors.YELLOW, " for more details" ));
}
}
}
## Instruction:
Change command name in hint
## Code After:
package com.carrot.carrotshop.listener;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.Order;
import org.spongepowered.api.event.network.ClientConnectionEvent;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.action.TextActions;
import org.spongepowered.api.text.format.TextColors;
import com.carrot.carrotshop.ShopsData;
public class PlayerConnexionListener {
@Listener(order=Order.LATE)
public void onPlayerJoin(ClientConnectionEvent.Join event)
{
if (ShopsData.hasSoldSomethingOffline(event.getTargetEntity().getUniqueId()) && event.getTargetEntity().hasPermission("carrotshop.report.self")) {
event.getTargetEntity().sendMessage(Text.of(TextColors.YELLOW, "Someone used your shop signs while you were away. Use ",
Text.builder("/carrotreport")
.color(TextColors.DARK_AQUA)
.onClick(TextActions.runCommand("/carrotreport")).build(),
TextColors.YELLOW, " for more details" ));
}
}
}
|
...
{
if (ShopsData.hasSoldSomethingOffline(event.getTargetEntity().getUniqueId()) && event.getTargetEntity().hasPermission("carrotshop.report.self")) {
event.getTargetEntity().sendMessage(Text.of(TextColors.YELLOW, "Someone used your shop signs while you were away. Use ",
Text.builder("/carrotreport")
.color(TextColors.DARK_AQUA)
.onClick(TextActions.runCommand("/carrotreport")).build(),
TextColors.YELLOW, " for more details" ));
}
}
...
|
b6c8dd224279ad0258b1130f8105059affa7553f
|
Challenges/chall_04.py
|
Challenges/chall_04.py
|
import urllib.request
import re
def main():
'''
http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345
44827
45439
...
'''
base_url = 'http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing='
nothing = '12345'
# nothing = '66831' # Cheat code
pattern = re.compile(r'next nothing is (\d+)')
for i in range(400):
with urllib.request.urlopen(base_url + nothing) as page:
data = page.read().decode('utf-8')
print(data)
match = re.search(pattern, data)
if match:
nothing = match.group(1)
if nothing == '16044':
nothing = str(16044 / 2)
else:
print('Hit break')
break
print('Last nothing found was: {}'.format(nothing))
return 0
# Keyword: peak
if __name__ == '__main__':
main()
|
import urllib.request
import re
def main():
'''
html page shows: linkedlist.php
php page comment: urllib may help. DON'T TRY ALL NOTHINGS, since it will
never end. 400 times is more than enough.
Photo link: linkedlist.php?nothing=12345
http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345
44827
45439
...
'''
base_url = 'http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing='
nothing = '12345'
# nothing = '66831' # Cheat code
pattern = re.compile(r'next nothing is (\d+)')
for i in range(400):
with urllib.request.urlopen(base_url + nothing) as page:
data = page.read().decode('utf-8')
print(data)
match = re.search(pattern, data)
if match:
nothing = match.group(1)
if nothing == '16044':
nothing = str(16044 / 2)
else:
print('Hit break')
break
print('Last nothing found was: {}'.format(nothing))
return 0
if __name__ == '__main__':
main()
|
Refactor code, fix shebang path
|
Refactor code, fix shebang path
|
Python
|
mit
|
HKuz/PythonChallenge
|
python
|
## Code Before:
import urllib.request
import re
def main():
'''
http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345
44827
45439
...
'''
base_url = 'http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing='
nothing = '12345'
# nothing = '66831' # Cheat code
pattern = re.compile(r'next nothing is (\d+)')
for i in range(400):
with urllib.request.urlopen(base_url + nothing) as page:
data = page.read().decode('utf-8')
print(data)
match = re.search(pattern, data)
if match:
nothing = match.group(1)
if nothing == '16044':
nothing = str(16044 / 2)
else:
print('Hit break')
break
print('Last nothing found was: {}'.format(nothing))
return 0
# Keyword: peak
if __name__ == '__main__':
main()
## Instruction:
Refactor code, fix shebang path
## Code After:
import urllib.request
import re
def main():
'''
html page shows: linkedlist.php
php page comment: urllib may help. DON'T TRY ALL NOTHINGS, since it will
never end. 400 times is more than enough.
Photo link: linkedlist.php?nothing=12345
http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345
44827
45439
...
'''
base_url = 'http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing='
nothing = '12345'
# nothing = '66831' # Cheat code
pattern = re.compile(r'next nothing is (\d+)')
for i in range(400):
with urllib.request.urlopen(base_url + nothing) as page:
data = page.read().decode('utf-8')
print(data)
match = re.search(pattern, data)
if match:
nothing = match.group(1)
if nothing == '16044':
nothing = str(16044 / 2)
else:
print('Hit break')
break
print('Last nothing found was: {}'.format(nothing))
return 0
if __name__ == '__main__':
main()
|
// ... existing code ...
def main():
'''
html page shows: linkedlist.php
php page comment: urllib may help. DON'T TRY ALL NOTHINGS, since it will
never end. 400 times is more than enough.
Photo link: linkedlist.php?nothing=12345
http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345
44827
45439
// ... modified code ...
'''
base_url = 'http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing='
nothing = '12345'
# nothing = '66831' # Cheat code
pattern = re.compile(r'next nothing is (\d+)')
for i in range(400):
...
print('Last nothing found was: {}'.format(nothing))
return 0
if __name__ == '__main__':
main()
// ... rest of the code ...
|
bf5ec5a459dc9dbe38a6806b513616aa769134a2
|
amqpy/tests/test_version.py
|
amqpy/tests/test_version.py
|
import re
def get_field(doc: str, name: str):
match = re.search(':{}: (.*)$'.format(name), doc, re.IGNORECASE | re.MULTILINE)
if match:
return match.group(1).strip()
class TestVersion:
def test_version_is_consistent(self):
from .. import VERSION
with open('README.rst') as f:
readme = f.read()
version = get_field(readme, 'version')
version = version.split('.')
version = tuple([int(i) for i in version])
assert VERSION == version
|
import re
def get_field(doc: str, name: str):
match = re.search(':{}: (.*)$'.format(name), doc, re.IGNORECASE | re.MULTILINE)
if match:
return match.group(1).strip()
class TestVersion:
def test_version_is_consistent(self):
from .. import VERSION
with open('README.rst') as f:
readme = f.read()
version = get_field(readme, 'version')
version = tuple(map(int, version.split('.')))
assert VERSION == version
|
Use `map` to test version
|
Use `map` to test version
|
Python
|
mit
|
veegee/amqpy,gst/amqpy
|
python
|
## Code Before:
import re
def get_field(doc: str, name: str):
match = re.search(':{}: (.*)$'.format(name), doc, re.IGNORECASE | re.MULTILINE)
if match:
return match.group(1).strip()
class TestVersion:
def test_version_is_consistent(self):
from .. import VERSION
with open('README.rst') as f:
readme = f.read()
version = get_field(readme, 'version')
version = version.split('.')
version = tuple([int(i) for i in version])
assert VERSION == version
## Instruction:
Use `map` to test version
## Code After:
import re
def get_field(doc: str, name: str):
match = re.search(':{}: (.*)$'.format(name), doc, re.IGNORECASE | re.MULTILINE)
if match:
return match.group(1).strip()
class TestVersion:
def test_version_is_consistent(self):
from .. import VERSION
with open('README.rst') as f:
readme = f.read()
version = get_field(readme, 'version')
version = tuple(map(int, version.split('.')))
assert VERSION == version
|
# ... existing code ...
readme = f.read()
version = get_field(readme, 'version')
version = tuple(map(int, version.split('.')))
assert VERSION == version
# ... rest of the code ...
|
4121dc4b67d198b7aeea16a4c46d7fc85e359190
|
presentation/models.py
|
presentation/models.py
|
from django.db import models
from model_utils.models import TimeStampedModel
from warp.users.models import User
class Presentation(TimeStampedModel):
subject = models.CharField(max_length=50)
author = models.ForeignKey(User, on_delete=models.CASCADE)
views = models.IntegerField(default=0)
markdown = models.TextField()
html = models.TextField()
|
from django.db import models
from model_utils.models import TimeStampedModel
from warp.users.models import User
class Presentation(TimeStampedModel):
subject = models.CharField(max_length=50)
author = models.ForeignKey(User, on_delete=models.CASCADE)
views = models.IntegerField(default=0)
markdown = models.TextField()
html = models.TextField()
is_public = models.BooleanField(default=True)
|
Add 'is_public' field for checking the whether or not presentation is public
|
Add 'is_public' field for checking the whether or not presentation is public
|
Python
|
mit
|
SaturDJang/warp,SaturDJang/warp,SaturDJang/warp,SaturDJang/warp
|
python
|
## Code Before:
from django.db import models
from model_utils.models import TimeStampedModel
from warp.users.models import User
class Presentation(TimeStampedModel):
subject = models.CharField(max_length=50)
author = models.ForeignKey(User, on_delete=models.CASCADE)
views = models.IntegerField(default=0)
markdown = models.TextField()
html = models.TextField()
## Instruction:
Add 'is_public' field for checking the whether or not presentation is public
## Code After:
from django.db import models
from model_utils.models import TimeStampedModel
from warp.users.models import User
class Presentation(TimeStampedModel):
subject = models.CharField(max_length=50)
author = models.ForeignKey(User, on_delete=models.CASCADE)
views = models.IntegerField(default=0)
markdown = models.TextField()
html = models.TextField()
is_public = models.BooleanField(default=True)
|
# ... existing code ...
views = models.IntegerField(default=0)
markdown = models.TextField()
html = models.TextField()
is_public = models.BooleanField(default=True)
# ... rest of the code ...
|
1213144d03d3bc69979ea50b32979ddd2b7f8dd2
|
scanner.def.h
|
scanner.def.h
|
typedef union {
int int_value;
} YYSTYPE;
typedef struct {
int function;
int result;
YYSTYPE lhs;
YYSTYPE rhs;
} BinaryFunction;
class ParserState {
public:
int result;
int eval;
ParserState() : result(0) {
}
};
#endif // CALC_SCANNER_DEF_H_
|
typedef union {
int int_value;
} YYSTYPE;
class ParserState {
public:
int result;
int eval;
ParserState() : result(0) {
}
};
#endif // CALC_SCANNER_DEF_H_
|
Remove silly struct that's silly
|
Remove silly struct that's silly
|
C
|
mit
|
nic0lette/lemony,nic0lette/lemony,nic0lette/lemony
|
c
|
## Code Before:
typedef union {
int int_value;
} YYSTYPE;
typedef struct {
int function;
int result;
YYSTYPE lhs;
YYSTYPE rhs;
} BinaryFunction;
class ParserState {
public:
int result;
int eval;
ParserState() : result(0) {
}
};
#endif // CALC_SCANNER_DEF_H_
## Instruction:
Remove silly struct that's silly
## Code After:
typedef union {
int int_value;
} YYSTYPE;
class ParserState {
public:
int result;
int eval;
ParserState() : result(0) {
}
};
#endif // CALC_SCANNER_DEF_H_
|
# ... existing code ...
typedef union {
int int_value;
} YYSTYPE;
class ParserState {
public:
# ... rest of the code ...
|
6c696b9ddec9e85df253fddb6228549a24f4f26a
|
annotations/src/main/java/org/realityforge/arez/annotations/Computed.java
|
annotations/src/main/java/org/realityforge/arez/annotations/Computed.java
|
package org.realityforge.arez.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Methods marked with this annotation are computed values within Arez.
*
* <p>The method should take zero parameters and return a single value. The value
* should be derived from other {@link org.realityforge.arez.Observable}s
* within the Arez system and the value returned by the method should not change
* unless the state of the other Observables changes. The method should NOT modify
* other state in the system.</p>
*
* <p>The computed method is automatically wrapped in a READ_ONLY transaction
* by the annotation parser.</p>
*/
@Retention( RetentionPolicy.CLASS )
@Target( ElementType.METHOD )
public @interface Computed
{
}
|
package org.realityforge.arez.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Methods marked with this annotation are computed values within Arez.
*
* <p>The method should take zero parameters and return a single value. The value
* should be derived from other Observables within the Arez system and the value
* returned by the method should not change unless the state of the other Observables
* changes. The method should NOT modify other state in the system.</p>
*
* <p>The computed method is automatically wrapped in a READ_ONLY transaction
* by the annotation parser.</p>
*/
@Retention( RetentionPolicy.CLASS )
@Target( ElementType.METHOD )
public @interface Computed
{
}
|
Fix javadocs cross link as Observable is not present locally
|
Fix javadocs cross link as Observable is not present locally
|
Java
|
apache-2.0
|
realityforge/arez,realityforge/arez,realityforge/arez
|
java
|
## Code Before:
package org.realityforge.arez.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Methods marked with this annotation are computed values within Arez.
*
* <p>The method should take zero parameters and return a single value. The value
* should be derived from other {@link org.realityforge.arez.Observable}s
* within the Arez system and the value returned by the method should not change
* unless the state of the other Observables changes. The method should NOT modify
* other state in the system.</p>
*
* <p>The computed method is automatically wrapped in a READ_ONLY transaction
* by the annotation parser.</p>
*/
@Retention( RetentionPolicy.CLASS )
@Target( ElementType.METHOD )
public @interface Computed
{
}
## Instruction:
Fix javadocs cross link as Observable is not present locally
## Code After:
package org.realityforge.arez.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Methods marked with this annotation are computed values within Arez.
*
* <p>The method should take zero parameters and return a single value. The value
* should be derived from other Observables within the Arez system and the value
* returned by the method should not change unless the state of the other Observables
* changes. The method should NOT modify other state in the system.</p>
*
* <p>The computed method is automatically wrapped in a READ_ONLY transaction
* by the annotation parser.</p>
*/
@Retention( RetentionPolicy.CLASS )
@Target( ElementType.METHOD )
public @interface Computed
{
}
|
// ... existing code ...
* Methods marked with this annotation are computed values within Arez.
*
* <p>The method should take zero parameters and return a single value. The value
* should be derived from other Observables within the Arez system and the value
* returned by the method should not change unless the state of the other Observables
* changes. The method should NOT modify other state in the system.</p>
*
* <p>The computed method is automatically wrapped in a READ_ONLY transaction
* by the annotation parser.</p>
// ... rest of the code ...
|
2410255e846c5fbd756ed97868299e1674c89467
|
flash_example.py
|
flash_example.py
|
from BlinkyTape import BlinkyTape
bb = BlinkyTape('/dev/tty.usbmodemfa131')
while True:
for x in range(60):
bb.sendPixel(10, 10, 10)
bb.show()
for x in range(60):
bb.sendPixel(0, 0, 0)
bb.show()
|
from BlinkyTape import BlinkyTape
import time
#bb = BlinkyTape('/dev/tty.usbmodemfa131')
bb = BlinkyTape('COM8')
while True:
for x in range(60):
bb.sendPixel(100, 100, 100)
bb.show()
time.sleep(.5)
for x in range(60):
bb.sendPixel(0, 0, 0)
bb.show()
time.sleep(.5)
|
Set it to flash black and white every second
|
Set it to flash black and white every second
|
Python
|
mit
|
Blinkinlabs/BlinkyTape_Python,jpsingleton/BlinkyTape_Python,railsagainstignorance/blinkytape
|
python
|
## Code Before:
from BlinkyTape import BlinkyTape
bb = BlinkyTape('/dev/tty.usbmodemfa131')
while True:
for x in range(60):
bb.sendPixel(10, 10, 10)
bb.show()
for x in range(60):
bb.sendPixel(0, 0, 0)
bb.show()
## Instruction:
Set it to flash black and white every second
## Code After:
from BlinkyTape import BlinkyTape
import time
#bb = BlinkyTape('/dev/tty.usbmodemfa131')
bb = BlinkyTape('COM8')
while True:
for x in range(60):
bb.sendPixel(100, 100, 100)
bb.show()
time.sleep(.5)
for x in range(60):
bb.sendPixel(0, 0, 0)
bb.show()
time.sleep(.5)
|
# ... existing code ...
from BlinkyTape import BlinkyTape
import time
#bb = BlinkyTape('/dev/tty.usbmodemfa131')
bb = BlinkyTape('COM8')
while True:
for x in range(60):
bb.sendPixel(100, 100, 100)
bb.show()
time.sleep(.5)
for x in range(60):
bb.sendPixel(0, 0, 0)
bb.show()
time.sleep(.5)
# ... rest of the code ...
|
13fec51e6fa3f47d2f3669e789e9d432e092944a
|
celeryconfig.py
|
celeryconfig.py
|
from datetime import timedelta
from private import CELERY_BROKER_URL, CELERY_RESULT_BACKEND
BROKER_URL = CELERY_BROKER_URL
CELERY_RESULT_BACKEND = CELERY_RESULT_BACKEND
CELERY_TIMEZONE = 'UTC'
CELERY_INCLUDE = ['tasks.scraper_task']
CELERYBEAT_SCHEDULE = {
'scrape_users': {
'task': 'tasks.scraper_task.scraper_task',
'schedule': timedelta(minutes=1)
},
}
|
from datetime import timedelta
from private import CELERY_BROKER_URL, CELERY_RESULT_BACKEND
#-------------------------------------------------------------------------------
BROKER_URL = CELERY_BROKER_URL
CELERY_RESULT_BACKEND = CELERY_RESULT_BACKEND
#-------------------------------------------------------------------------------
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
#-------------------------------------------------------------------------------
CELERY_TIMEZONE = 'UTC'
CELERY_INCLUDE = ['tasks.scraper_task']
CELERYBEAT_SCHEDULE = {
'scrape_users': {
'task': 'tasks.scraper_task.scraper_task',
'schedule': timedelta(minutes=1)
},
}
|
Use json for task serialization
|
Use json for task serialization
|
Python
|
mit
|
Trinovantes/MyAnimeList-Cover-CSS-Generator,Trinovantes/MyAnimeList-Cover-CSS-Generator
|
python
|
## Code Before:
from datetime import timedelta
from private import CELERY_BROKER_URL, CELERY_RESULT_BACKEND
BROKER_URL = CELERY_BROKER_URL
CELERY_RESULT_BACKEND = CELERY_RESULT_BACKEND
CELERY_TIMEZONE = 'UTC'
CELERY_INCLUDE = ['tasks.scraper_task']
CELERYBEAT_SCHEDULE = {
'scrape_users': {
'task': 'tasks.scraper_task.scraper_task',
'schedule': timedelta(minutes=1)
},
}
## Instruction:
Use json for task serialization
## Code After:
from datetime import timedelta
from private import CELERY_BROKER_URL, CELERY_RESULT_BACKEND
#-------------------------------------------------------------------------------
BROKER_URL = CELERY_BROKER_URL
CELERY_RESULT_BACKEND = CELERY_RESULT_BACKEND
#-------------------------------------------------------------------------------
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
#-------------------------------------------------------------------------------
CELERY_TIMEZONE = 'UTC'
CELERY_INCLUDE = ['tasks.scraper_task']
CELERYBEAT_SCHEDULE = {
'scrape_users': {
'task': 'tasks.scraper_task.scraper_task',
'schedule': timedelta(minutes=1)
},
}
|
# ... existing code ...
from private import CELERY_BROKER_URL, CELERY_RESULT_BACKEND
#-------------------------------------------------------------------------------
BROKER_URL = CELERY_BROKER_URL
CELERY_RESULT_BACKEND = CELERY_RESULT_BACKEND
#-------------------------------------------------------------------------------
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
#-------------------------------------------------------------------------------
CELERY_TIMEZONE = 'UTC'
# ... rest of the code ...
|
0e59be8483a35c257e1ffed22dcb8a37921895bf
|
src/main/java/bestcoders/library/services/helpers/LibraryStreams.java
|
src/main/java/bestcoders/library/services/helpers/LibraryStreams.java
|
package bestcoders.library.services.helpers;
import java.util.stream.Stream;
import bestcoders.library.Library;
import bestcoders.library.loans.LoanRecord;
import bestcoders.library.loans.LoanState;
import bestcoders.library.members.LibraryMember;
public class LibraryStreams {
private final Library library;
public LibraryStreams(final Library library) {
this.library = library;
}
public Stream<LoanRecord> getLoansForMember(final Stream<LoanRecord> s, final LibraryMember m) {
return s.filter(lr -> lr.getMember().equals(m));
}
Stream<LoanRecord> getLoansStream() {
return library.getLoans().stream();
}
public Stream<LoanRecord> getOpenLoansStream() {
return getLoansStream().filter(lr -> lr.getState() == LoanState.OPEN);
}
}
|
package bestcoders.library.services.helpers;
import java.util.stream.Stream;
import bestcoders.library.Library;
import bestcoders.library.loans.LoanRecord;
import bestcoders.library.loans.LoanState;
import bestcoders.library.members.LibraryMember;
public class LibraryStreams {
private final Library library;
public LibraryStreams(final Library library) {
this.library = library;
}
public Stream<LoanRecord> getLoansForMember(final Stream<LoanRecord> s, final LibraryMember m) {
return s.filter(lr -> lr != null && lr.getMember().equals(m));
}
Stream<LoanRecord> getLoansStream() {
return library.getLoans().stream();
}
public Stream<LoanRecord> getOpenLoansStream() {
return getLoansStream().filter(lr -> lr != null && lr.getState() == LoanState.OPEN);
}
}
|
Add null protection for loan records.
|
Add null protection for loan records.
Intermittent issue with null loan records being logged.
|
Java
|
mit
|
codingSteve/library
|
java
|
## Code Before:
package bestcoders.library.services.helpers;
import java.util.stream.Stream;
import bestcoders.library.Library;
import bestcoders.library.loans.LoanRecord;
import bestcoders.library.loans.LoanState;
import bestcoders.library.members.LibraryMember;
public class LibraryStreams {
private final Library library;
public LibraryStreams(final Library library) {
this.library = library;
}
public Stream<LoanRecord> getLoansForMember(final Stream<LoanRecord> s, final LibraryMember m) {
return s.filter(lr -> lr.getMember().equals(m));
}
Stream<LoanRecord> getLoansStream() {
return library.getLoans().stream();
}
public Stream<LoanRecord> getOpenLoansStream() {
return getLoansStream().filter(lr -> lr.getState() == LoanState.OPEN);
}
}
## Instruction:
Add null protection for loan records.
Intermittent issue with null loan records being logged.
## Code After:
package bestcoders.library.services.helpers;
import java.util.stream.Stream;
import bestcoders.library.Library;
import bestcoders.library.loans.LoanRecord;
import bestcoders.library.loans.LoanState;
import bestcoders.library.members.LibraryMember;
public class LibraryStreams {
private final Library library;
public LibraryStreams(final Library library) {
this.library = library;
}
public Stream<LoanRecord> getLoansForMember(final Stream<LoanRecord> s, final LibraryMember m) {
return s.filter(lr -> lr != null && lr.getMember().equals(m));
}
Stream<LoanRecord> getLoansStream() {
return library.getLoans().stream();
}
public Stream<LoanRecord> getOpenLoansStream() {
return getLoansStream().filter(lr -> lr != null && lr.getState() == LoanState.OPEN);
}
}
|
...
}
public Stream<LoanRecord> getLoansForMember(final Stream<LoanRecord> s, final LibraryMember m) {
return s.filter(lr -> lr != null && lr.getMember().equals(m));
}
Stream<LoanRecord> getLoansStream() {
...
}
public Stream<LoanRecord> getOpenLoansStream() {
return getLoansStream().filter(lr -> lr != null && lr.getState() == LoanState.OPEN);
}
}
...
|
dd11add15f5bb65fa6edfbca54cb3de77e6f8896
|
app/src/main/java/nickrout/lenslauncher/util/ColorUtil.java
|
app/src/main/java/nickrout/lenslauncher/util/ColorUtil.java
|
package nickrout.lenslauncher.util;
import android.graphics.Color;
import android.support.annotation.ColorInt;
import android.support.v7.graphics.Palette;
import nickrout.lenslauncher.model.App;
/**
* Created by nicholasrout on 2016/05/28.
*/
public class ColorUtil {
public static @ColorInt int getPaletteColorFromApp(App app) {
Palette palette = Palette.from(app.getIcon()).generate();
if (palette.getSwatches().size() > 0) {
int swatchIndex = 0;
for (int i = 1; i < palette.getSwatches().size(); i++) {
if (palette.getSwatches().get(i).getPopulation()
> palette.getSwatches().get(swatchIndex).getPopulation()) {
swatchIndex = i;
}
}
return palette.getSwatches().get(swatchIndex).getRgb();
} else {
return Color.BLACK;
}
}
public static float getHueColorFromApp(App app) {
float[] hsvValues = new float[3];
Color.colorToHSV(app.getPaletteColor(), hsvValues);
return hsvValues[0];
}
}
|
package nickrout.lenslauncher.util;
import android.graphics.Color;
import android.support.annotation.ColorInt;
import android.support.v7.graphics.Palette;
import nickrout.lenslauncher.model.App;
/**
* Created by nicholasrout on 2016/05/28.
*/
public class ColorUtil {
public static @ColorInt int getPaletteColorFromApp(App app) {
Palette palette;
try {
palette = Palette.from(app.getIcon()).generate();
} catch (IllegalArgumentException e) {
e.printStackTrace();
return Color.BLACK;
}
if (palette.getSwatches().size() > 0) {
int swatchIndex = 0;
for (int i = 1; i < palette.getSwatches().size(); i++) {
if (palette.getSwatches().get(i).getPopulation()
> palette.getSwatches().get(swatchIndex).getPopulation()) {
swatchIndex = i;
}
}
return palette.getSwatches().get(swatchIndex).getRgb();
} else {
return Color.BLACK;
}
}
public static float getHueColorFromApp(App app) {
float[] hsvValues = new float[3];
Color.colorToHSV(app.getPaletteColor(), hsvValues);
return hsvValues[0];
}
}
|
Fix for occasional Palette crash
|
Fix for occasional Palette crash
|
Java
|
apache-2.0
|
nicholasrout/lens-launcher,nicholasrout/lens-launcher
|
java
|
## Code Before:
package nickrout.lenslauncher.util;
import android.graphics.Color;
import android.support.annotation.ColorInt;
import android.support.v7.graphics.Palette;
import nickrout.lenslauncher.model.App;
/**
* Created by nicholasrout on 2016/05/28.
*/
public class ColorUtil {
public static @ColorInt int getPaletteColorFromApp(App app) {
Palette palette = Palette.from(app.getIcon()).generate();
if (palette.getSwatches().size() > 0) {
int swatchIndex = 0;
for (int i = 1; i < palette.getSwatches().size(); i++) {
if (palette.getSwatches().get(i).getPopulation()
> palette.getSwatches().get(swatchIndex).getPopulation()) {
swatchIndex = i;
}
}
return palette.getSwatches().get(swatchIndex).getRgb();
} else {
return Color.BLACK;
}
}
public static float getHueColorFromApp(App app) {
float[] hsvValues = new float[3];
Color.colorToHSV(app.getPaletteColor(), hsvValues);
return hsvValues[0];
}
}
## Instruction:
Fix for occasional Palette crash
## Code After:
package nickrout.lenslauncher.util;
import android.graphics.Color;
import android.support.annotation.ColorInt;
import android.support.v7.graphics.Palette;
import nickrout.lenslauncher.model.App;
/**
* Created by nicholasrout on 2016/05/28.
*/
public class ColorUtil {
public static @ColorInt int getPaletteColorFromApp(App app) {
Palette palette;
try {
palette = Palette.from(app.getIcon()).generate();
} catch (IllegalArgumentException e) {
e.printStackTrace();
return Color.BLACK;
}
if (palette.getSwatches().size() > 0) {
int swatchIndex = 0;
for (int i = 1; i < palette.getSwatches().size(); i++) {
if (palette.getSwatches().get(i).getPopulation()
> palette.getSwatches().get(swatchIndex).getPopulation()) {
swatchIndex = i;
}
}
return palette.getSwatches().get(swatchIndex).getRgb();
} else {
return Color.BLACK;
}
}
public static float getHueColorFromApp(App app) {
float[] hsvValues = new float[3];
Color.colorToHSV(app.getPaletteColor(), hsvValues);
return hsvValues[0];
}
}
|
// ... existing code ...
public class ColorUtil {
public static @ColorInt int getPaletteColorFromApp(App app) {
Palette palette;
try {
palette = Palette.from(app.getIcon()).generate();
} catch (IllegalArgumentException e) {
e.printStackTrace();
return Color.BLACK;
}
if (palette.getSwatches().size() > 0) {
int swatchIndex = 0;
for (int i = 1; i < palette.getSwatches().size(); i++) {
// ... rest of the code ...
|
bcd8289a0eb5e4005a2ad4e70216839291896c47
|
MOAspects/MOAspects.h
|
MOAspects/MOAspects.h
|
//
// MOAspects.h
// MOAspects
//
// Created by Hiromi Motodera on 2015/03/15.
// Copyright (c) 2015年 MOAI. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSInteger, MOAspectsPosition)
{
MOAspectsPositionBefore,
MOAspectsPositionAfter
};
typedef NS_ENUM(NSInteger, MOAspectsHookRange)
{
MOAspectsHookRangeAll = -1,
MOAspectsHookRangeTargetOnly = -2
};
@interface MOAspects : NSObject
+ (BOOL)hookInstanceMethodForClass:(Class)clazz
selector:(SEL)selector
aspectsPosition:(MOAspectsPosition)aspectsPosition
usingBlock:(id)block;
+ (BOOL)hookInstanceMethodForClass:(Class)clazz
selector:(SEL)selector
aspectsPosition:(MOAspectsPosition)aspectsPosition
hookLevel:(MOAspectsHookRange)hookLevel
usingBlock:(id)block;
+ (BOOL)hookClassMethodForClass:(Class)clazz
selector:(SEL)selector
aspectsPosition:(MOAspectsPosition)aspectsPosition
usingBlock:(id)block;
+ (BOOL)hookClassMethodForClass:(Class)clazz
selector:(SEL)selector
aspectsPosition:(MOAspectsPosition)aspectsPosition
hookLevel:(MOAspectsHookRange)hookLevel
usingBlock:(id)block;
@end
|
//
// MOAspects.h
// MOAspects
//
// Created by Hiromi Motodera on 2015/03/15.
// Copyright (c) 2015年 MOAI. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSInteger, MOAspectsPosition)
{
MOAspectsPositionBefore,
MOAspectsPositionAfter
};
typedef NS_ENUM(NSInteger, MOAspectsHookRange)
{
MOAspectsHookRangeAll = -1,
MOAspectsHookRangeTargetOnly = -2
};
@interface MOAspects : NSObject
+ (BOOL)hookInstanceMethodForClass:(Class)clazz
selector:(SEL)selector
aspectsPosition:(MOAspectsPosition)aspectsPosition
usingBlock:(id)block;
+ (BOOL)hookInstanceMethodForClass:(Class)clazz
selector:(SEL)selector
aspectsPosition:(MOAspectsPosition)aspectsPosition
hookLevel:(MOAspectsHookRange)hookRange
usingBlock:(id)block;
+ (BOOL)hookClassMethodForClass:(Class)clazz
selector:(SEL)selector
aspectsPosition:(MOAspectsPosition)aspectsPosition
usingBlock:(id)block;
+ (BOOL)hookClassMethodForClass:(Class)clazz
selector:(SEL)selector
aspectsPosition:(MOAspectsPosition)aspectsPosition
hookLevel:(MOAspectsHookRange)hookRange
usingBlock:(id)block;
@end
|
Change hook level parameter name to hookRange
|
Change hook level parameter name to hookRange
|
C
|
mit
|
MO-AI/MOAspects,MO-AI/MOAspects
|
c
|
## Code Before:
//
// MOAspects.h
// MOAspects
//
// Created by Hiromi Motodera on 2015/03/15.
// Copyright (c) 2015年 MOAI. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSInteger, MOAspectsPosition)
{
MOAspectsPositionBefore,
MOAspectsPositionAfter
};
typedef NS_ENUM(NSInteger, MOAspectsHookRange)
{
MOAspectsHookRangeAll = -1,
MOAspectsHookRangeTargetOnly = -2
};
@interface MOAspects : NSObject
+ (BOOL)hookInstanceMethodForClass:(Class)clazz
selector:(SEL)selector
aspectsPosition:(MOAspectsPosition)aspectsPosition
usingBlock:(id)block;
+ (BOOL)hookInstanceMethodForClass:(Class)clazz
selector:(SEL)selector
aspectsPosition:(MOAspectsPosition)aspectsPosition
hookLevel:(MOAspectsHookRange)hookLevel
usingBlock:(id)block;
+ (BOOL)hookClassMethodForClass:(Class)clazz
selector:(SEL)selector
aspectsPosition:(MOAspectsPosition)aspectsPosition
usingBlock:(id)block;
+ (BOOL)hookClassMethodForClass:(Class)clazz
selector:(SEL)selector
aspectsPosition:(MOAspectsPosition)aspectsPosition
hookLevel:(MOAspectsHookRange)hookLevel
usingBlock:(id)block;
@end
## Instruction:
Change hook level parameter name to hookRange
## Code After:
//
// MOAspects.h
// MOAspects
//
// Created by Hiromi Motodera on 2015/03/15.
// Copyright (c) 2015年 MOAI. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSInteger, MOAspectsPosition)
{
MOAspectsPositionBefore,
MOAspectsPositionAfter
};
typedef NS_ENUM(NSInteger, MOAspectsHookRange)
{
MOAspectsHookRangeAll = -1,
MOAspectsHookRangeTargetOnly = -2
};
@interface MOAspects : NSObject
+ (BOOL)hookInstanceMethodForClass:(Class)clazz
selector:(SEL)selector
aspectsPosition:(MOAspectsPosition)aspectsPosition
usingBlock:(id)block;
+ (BOOL)hookInstanceMethodForClass:(Class)clazz
selector:(SEL)selector
aspectsPosition:(MOAspectsPosition)aspectsPosition
hookLevel:(MOAspectsHookRange)hookRange
usingBlock:(id)block;
+ (BOOL)hookClassMethodForClass:(Class)clazz
selector:(SEL)selector
aspectsPosition:(MOAspectsPosition)aspectsPosition
usingBlock:(id)block;
+ (BOOL)hookClassMethodForClass:(Class)clazz
selector:(SEL)selector
aspectsPosition:(MOAspectsPosition)aspectsPosition
hookLevel:(MOAspectsHookRange)hookRange
usingBlock:(id)block;
@end
|
// ... existing code ...
+ (BOOL)hookInstanceMethodForClass:(Class)clazz
selector:(SEL)selector
aspectsPosition:(MOAspectsPosition)aspectsPosition
hookLevel:(MOAspectsHookRange)hookRange
usingBlock:(id)block;
+ (BOOL)hookClassMethodForClass:(Class)clazz
// ... modified code ...
+ (BOOL)hookClassMethodForClass:(Class)clazz
selector:(SEL)selector
aspectsPosition:(MOAspectsPosition)aspectsPosition
hookLevel:(MOAspectsHookRange)hookRange
usingBlock:(id)block;
@end
// ... rest of the code ...
|
c9a6e0847be2de61563d66d8d06c998abaf53954
|
gerrit-server/src/main/java/com/google/gerrit/server/plugins/CleanupHandle.java
|
gerrit-server/src/main/java/com/google/gerrit/server/plugins/CleanupHandle.java
|
// Copyright (C) 2012 The Android Open Source Project
//
// 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 com.google.gerrit.server.plugins;
import java.io.File;
import java.io.IOException;
import java.util.jar.JarFile;
class CleanupHandle {
private final File tmpFile;
private final JarFile jarFile;
CleanupHandle(File tmpFile,
JarFile jarFile) {
this.tmpFile = tmpFile;
this.jarFile = jarFile;
}
void cleanup() {
try {
jarFile.close();
} catch (IOException err) {
}
if (!tmpFile.delete() && tmpFile.exists()) {
PluginLoader.log.warn("Cannot delete " + tmpFile.getAbsolutePath()
+ ", retrying to delete it on termination of the virtual machine");
tmpFile.deleteOnExit();
} else {
PluginLoader.log.info("Cleaned plugin " + tmpFile.getName());
}
}
}
|
// Copyright (C) 2012 The Android Open Source Project
//
// 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 com.google.gerrit.server.plugins;
import java.io.File;
import java.io.IOException;
import java.util.jar.JarFile;
class CleanupHandle {
private final File tmpFile;
private final JarFile jarFile;
CleanupHandle(File tmpFile,
JarFile jarFile) {
this.tmpFile = tmpFile;
this.jarFile = jarFile;
}
void cleanup() {
try {
jarFile.close();
} catch (IOException err) {
PluginLoader.log.error("Cannot close " + jarFile.getName(), err);
}
if (!tmpFile.delete() && tmpFile.exists()) {
PluginLoader.log.warn("Cannot delete " + tmpFile.getAbsolutePath()
+ ", retrying to delete it on termination of the virtual machine");
tmpFile.deleteOnExit();
} else {
PluginLoader.log.info("Cleaned plugin " + tmpFile.getName());
}
}
}
|
Print error message to log when plugin loader fails to close JAR file
|
Print error message to log when plugin loader fails to close JAR file
Change-Id: Ic113b7759e094bd18c8c68767d85a25044400cb4
|
Java
|
apache-2.0
|
anminhsu/gerrit,hdost/gerrit,GerritCodeReview/gerrit,joshuawilson/merrit,Seinlin/gerrit,thesamet/gerrit,quyixia/gerrit,Seinlin/gerrit,bootstraponline-archive/gerrit-mirror,Distrotech/gerrit,TonyChai24/test,quyixia/gerrit,Seinlin/gerrit,renchaorevee/gerrit,midnightradio/gerrit,gcoders/gerrit,hdost/gerrit,pkdevbox/gerrit,thinkernel/gerrit,thinkernel/gerrit,Saulis/gerrit,Distrotech/gerrit,thinkernel/gerrit,hdost/gerrit,MerritCR/merrit,joshuawilson/merrit,GerritCodeReview/gerrit,Team-OctOS/host_gerrit,netroby/gerrit,joshuawilson/merrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,TonyChai24/test,jackminicloud/test,jackminicloud/test,joshuawilson/merrit,renchaorevee/gerrit,pkdevbox/gerrit,bootstraponline-archive/gerrit-mirror,dwhipstock/gerrit,anminhsu/gerrit,hdost/gerrit,anminhsu/gerrit,anminhsu/gerrit,Team-OctOS/host_gerrit,quyixia/gerrit,Overruler/gerrit,dwhipstock/gerrit,pkdevbox/gerrit,hdost/gerrit,Distrotech/gerrit,supriyantomaftuh/gerrit,thesamet/gerrit,Seinlin/gerrit,renchaorevee/gerrit,gcoders/gerrit,Overruler/gerrit,Team-OctOS/host_gerrit,renchaorevee/gerrit,Overruler/gerrit,gerrit-review/gerrit,thesamet/gerrit,jackminicloud/test,Seinlin/gerrit,supriyantomaftuh/gerrit,netroby/gerrit,jackminicloud/test,hdost/gerrit,midnightradio/gerrit,bpollack/gerrit,MerritCR/merrit,jackminicloud/test,qtproject/qtqa-gerrit,bpollack/gerrit,bpollack/gerrit,Distrotech/gerrit,midnightradio/gerrit,bpollack/gerrit,dwhipstock/gerrit,WANdisco/gerrit,gcoders/gerrit,bootstraponline-archive/gerrit-mirror,GerritCodeReview/gerrit,thinkernel/gerrit,thesamet/gerrit,midnightradio/gerrit,gcoders/gerrit,MerritCR/merrit,Team-OctOS/host_gerrit,TonyChai24/test,thesamet/gerrit,MerritCR/merrit,bpollack/gerrit,Saulis/gerrit,bpollack/gerrit,netroby/gerrit,gerrit-review/gerrit,Saulis/gerrit,gcoders/gerrit,quyixia/gerrit,gerrit-review/gerrit,supriyantomaftuh/gerrit,WANdisco/gerrit,WANdisco/gerrit,dwhipstock/gerrit,WANdisco/gerrit,quyixia/gerrit,joshuawilson/merrit,MerritCR/merrit,thinkernel/gerrit,qtproject/qtqa-gerrit,joshuawilson/merrit,TonyChai24/test,bootstraponline-archive/gerrit-mirror,Distrotech/gerrit,GerritCodeReview/gerrit,netroby/gerrit,quyixia/gerrit,dwhipstock/gerrit,quyixia/gerrit,TonyChai24/test,GerritCodeReview/gerrit,bootstraponline-archive/gerrit-mirror,anminhsu/gerrit,supriyantomaftuh/gerrit,pkdevbox/gerrit,hdost/gerrit,midnightradio/gerrit,gerrit-review/gerrit,gcoders/gerrit,renchaorevee/gerrit,gcoders/gerrit,Distrotech/gerrit,Saulis/gerrit,Team-OctOS/host_gerrit,dwhipstock/gerrit,MerritCR/merrit,thesamet/gerrit,anminhsu/gerrit,supriyantomaftuh/gerrit,netroby/gerrit,dwhipstock/gerrit,supriyantomaftuh/gerrit,gerrit-review/gerrit,WANdisco/gerrit,pkdevbox/gerrit,Seinlin/gerrit,WANdisco/gerrit,MerritCR/merrit,Overruler/gerrit,thinkernel/gerrit,supriyantomaftuh/gerrit,Distrotech/gerrit,bootstraponline-archive/gerrit-mirror,midnightradio/gerrit,pkdevbox/gerrit,netroby/gerrit,qtproject/qtqa-gerrit,MerritCR/merrit,Team-OctOS/host_gerrit,gerrit-review/gerrit,Seinlin/gerrit,TonyChai24/test,thesamet/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,thinkernel/gerrit,TonyChai24/test,qtproject/qtqa-gerrit,renchaorevee/gerrit,jackminicloud/test,Overruler/gerrit,pkdevbox/gerrit,jackminicloud/test,GerritCodeReview/gerrit,Overruler/gerrit,Saulis/gerrit,netroby/gerrit,qtproject/qtqa-gerrit,renchaorevee/gerrit,WANdisco/gerrit,joshuawilson/merrit,Team-OctOS/host_gerrit,anminhsu/gerrit,Saulis/gerrit,gerrit-review/gerrit,joshuawilson/merrit
|
java
|
## Code Before:
// Copyright (C) 2012 The Android Open Source Project
//
// 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 com.google.gerrit.server.plugins;
import java.io.File;
import java.io.IOException;
import java.util.jar.JarFile;
class CleanupHandle {
private final File tmpFile;
private final JarFile jarFile;
CleanupHandle(File tmpFile,
JarFile jarFile) {
this.tmpFile = tmpFile;
this.jarFile = jarFile;
}
void cleanup() {
try {
jarFile.close();
} catch (IOException err) {
}
if (!tmpFile.delete() && tmpFile.exists()) {
PluginLoader.log.warn("Cannot delete " + tmpFile.getAbsolutePath()
+ ", retrying to delete it on termination of the virtual machine");
tmpFile.deleteOnExit();
} else {
PluginLoader.log.info("Cleaned plugin " + tmpFile.getName());
}
}
}
## Instruction:
Print error message to log when plugin loader fails to close JAR file
Change-Id: Ic113b7759e094bd18c8c68767d85a25044400cb4
## Code After:
// Copyright (C) 2012 The Android Open Source Project
//
// 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 com.google.gerrit.server.plugins;
import java.io.File;
import java.io.IOException;
import java.util.jar.JarFile;
class CleanupHandle {
private final File tmpFile;
private final JarFile jarFile;
CleanupHandle(File tmpFile,
JarFile jarFile) {
this.tmpFile = tmpFile;
this.jarFile = jarFile;
}
void cleanup() {
try {
jarFile.close();
} catch (IOException err) {
PluginLoader.log.error("Cannot close " + jarFile.getName(), err);
}
if (!tmpFile.delete() && tmpFile.exists()) {
PluginLoader.log.warn("Cannot delete " + tmpFile.getAbsolutePath()
+ ", retrying to delete it on termination of the virtual machine");
tmpFile.deleteOnExit();
} else {
PluginLoader.log.info("Cleaned plugin " + tmpFile.getName());
}
}
}
|
...
try {
jarFile.close();
} catch (IOException err) {
PluginLoader.log.error("Cannot close " + jarFile.getName(), err);
}
if (!tmpFile.delete() && tmpFile.exists()) {
PluginLoader.log.warn("Cannot delete " + tmpFile.getAbsolutePath()
...
|
7e2b4cbe764417674928ab535d549caf714f50fe
|
biz.aQute.bndlib/src/aQute/bnd/service/Actionable.java
|
biz.aQute.bndlib/src/aQute/bnd/service/Actionable.java
|
package aQute.bnd.service;
import java.util.*;
/**
* An interface to allow bnd to provide commands on selected entries. Primary
* use case is the repository that provides commands on its entries. The
* interface also provides the possibility to get some details of an entry.
*/
public interface Actionable {
/**
* Return a map with command names (potentially localized) and a Runnable.
* The caller can execute the caller at will.
*
* @param target
* the target object, null if commands for the encompassing
* entity is sought (e.g. the repo itself).
* @return A Map with the actions or null if no actions are available.
* @throws Exception
*/
Map<String,Runnable> actions(Object target) throws Exception;
/**
* Return a tooltip for the given target or the encompassing entity if null
* is passed.
*
* @param target
* the target or null
* @return the tooltip or null
* @throws Exception
*/
String tooltip(Object target) throws Exception;
}
|
package aQute.bnd.service;
import java.util.*;
/**
* An interface to allow bnd to provide commands on selected entries. Primary
* use case is the repository that provides commands on its entries. The
* interface also provides the possibility to get some details of an entry.
*/
public interface Actionable {
/**
* Return a map with command names (potentially localized) and a Runnable.
* The caller can execute the caller at will.
*
* @param target
* the target object, null if commands for the encompassing
* entity is sought (e.g. the repo itself).
* @return A Map with the actions or null if no actions are available.
* @throws Exception
*/
Map<String,Runnable> actions(Object ... target) throws Exception;
/**
* Return a tooltip for the given target or the encompassing entity if null
* is passed.
*
* @param target
* the target, any number of parameters to identify
* @return the tooltip or null
* @throws Exception
*/
String tooltip(Object ... target) throws Exception;
}
|
Use multiple args for identifying the entry
|
Use multiple args for identifying the entry
|
Java
|
apache-2.0
|
mcculls/bnd,GEBIT/bnd,xtracoder/bnd,joansmith/bnd,GEBIT/bnd,lostiniceland/bnd,psoreide/bnd,magnet/bnd,psoreide/bnd,psoreide/bnd,magnet/bnd,magnet/bnd,lostiniceland/bnd,mcculls/bnd,mcculls/bnd,joansmith/bnd,lostiniceland/bnd,xtracoder/bnd
|
java
|
## Code Before:
package aQute.bnd.service;
import java.util.*;
/**
* An interface to allow bnd to provide commands on selected entries. Primary
* use case is the repository that provides commands on its entries. The
* interface also provides the possibility to get some details of an entry.
*/
public interface Actionable {
/**
* Return a map with command names (potentially localized) and a Runnable.
* The caller can execute the caller at will.
*
* @param target
* the target object, null if commands for the encompassing
* entity is sought (e.g. the repo itself).
* @return A Map with the actions or null if no actions are available.
* @throws Exception
*/
Map<String,Runnable> actions(Object target) throws Exception;
/**
* Return a tooltip for the given target or the encompassing entity if null
* is passed.
*
* @param target
* the target or null
* @return the tooltip or null
* @throws Exception
*/
String tooltip(Object target) throws Exception;
}
## Instruction:
Use multiple args for identifying the entry
## Code After:
package aQute.bnd.service;
import java.util.*;
/**
* An interface to allow bnd to provide commands on selected entries. Primary
* use case is the repository that provides commands on its entries. The
* interface also provides the possibility to get some details of an entry.
*/
public interface Actionable {
/**
* Return a map with command names (potentially localized) and a Runnable.
* The caller can execute the caller at will.
*
* @param target
* the target object, null if commands for the encompassing
* entity is sought (e.g. the repo itself).
* @return A Map with the actions or null if no actions are available.
* @throws Exception
*/
Map<String,Runnable> actions(Object ... target) throws Exception;
/**
* Return a tooltip for the given target or the encompassing entity if null
* is passed.
*
* @param target
* the target, any number of parameters to identify
* @return the tooltip or null
* @throws Exception
*/
String tooltip(Object ... target) throws Exception;
}
|
# ... existing code ...
* @return A Map with the actions or null if no actions are available.
* @throws Exception
*/
Map<String,Runnable> actions(Object ... target) throws Exception;
/**
* Return a tooltip for the given target or the encompassing entity if null
# ... modified code ...
* is passed.
*
* @param target
* the target, any number of parameters to identify
* @return the tooltip or null
* @throws Exception
*/
String tooltip(Object ... target) throws Exception;
}
# ... rest of the code ...
|
5ea19da9fdd797963a7b7f1f2fd8f7163200b4bc
|
easy_maps/conf.py
|
easy_maps/conf.py
|
import warnings
from django.conf import settings # pylint: disable=W0611
from appconf import AppConf
class EasyMapsSettings(AppConf):
CENTER = (-41.3, 32)
GEOCODE = 'easy_maps.geocode.google_v3'
ZOOM = 16 # See https://developers.google.com/maps/documentation/javascript/tutorial#MapOptions for more information.
LANGUAGE = 'en' # See https://developers.google.com/maps/faq#languagesupport for supported languages.
GOOGLE_MAPS_API_KEY = None
GOOGLE_KEY = None
CACHE_LIFETIME = 600 # 10 minutes in seconds
class Meta:
prefix = 'easy_maps'
holder = 'easy_maps.conf.settings'
if hasattr(settings, 'EASY_MAPS_GOOGLE_MAPS_API_KEY'):
warnings.warn("EASY_MAPS_GOOGLE_MAPS_API_KEY is deprecated, use EASY_MAPS_GOOGLE_KEY", DeprecationWarning)
|
import warnings
from django.conf import settings # pylint: disable=W0611
from appconf import AppConf
class EasyMapsSettings(AppConf):
CENTER = (-41.3, 32)
GEOCODE = 'easy_maps.geocode.google_v3'
ZOOM = 16 # See https://developers.google.com/maps/documentation/javascript/tutorial#MapOptions for more information.
LANGUAGE = 'en' # See https://developers.google.com/maps/faq#languagesupport for supported languages.
GOOGLE_MAPS_API_KEY = None
GOOGLE_KEY = None
CACHE_LIFETIME = 600 # 10 minutes in seconds
class Meta:
prefix = 'easy_maps'
holder = 'easy_maps.conf.settings'
if settings.EASY_MAPS_GOOGLE_MAPS_API_KEY is not None:
warnings.warn("EASY_MAPS_GOOGLE_MAPS_API_KEY is deprecated, use EASY_MAPS_GOOGLE_KEY", DeprecationWarning)
|
Check is EASY_MAPS_GOOGLE_MAPS_API_KEY is not None before raising warning.
|
Check is EASY_MAPS_GOOGLE_MAPS_API_KEY is not None before raising warning.
|
Python
|
mit
|
kmike/django-easy-maps,kmike/django-easy-maps,bashu/django-easy-maps,bashu/django-easy-maps
|
python
|
## Code Before:
import warnings
from django.conf import settings # pylint: disable=W0611
from appconf import AppConf
class EasyMapsSettings(AppConf):
CENTER = (-41.3, 32)
GEOCODE = 'easy_maps.geocode.google_v3'
ZOOM = 16 # See https://developers.google.com/maps/documentation/javascript/tutorial#MapOptions for more information.
LANGUAGE = 'en' # See https://developers.google.com/maps/faq#languagesupport for supported languages.
GOOGLE_MAPS_API_KEY = None
GOOGLE_KEY = None
CACHE_LIFETIME = 600 # 10 minutes in seconds
class Meta:
prefix = 'easy_maps'
holder = 'easy_maps.conf.settings'
if hasattr(settings, 'EASY_MAPS_GOOGLE_MAPS_API_KEY'):
warnings.warn("EASY_MAPS_GOOGLE_MAPS_API_KEY is deprecated, use EASY_MAPS_GOOGLE_KEY", DeprecationWarning)
## Instruction:
Check is EASY_MAPS_GOOGLE_MAPS_API_KEY is not None before raising warning.
## Code After:
import warnings
from django.conf import settings # pylint: disable=W0611
from appconf import AppConf
class EasyMapsSettings(AppConf):
CENTER = (-41.3, 32)
GEOCODE = 'easy_maps.geocode.google_v3'
ZOOM = 16 # See https://developers.google.com/maps/documentation/javascript/tutorial#MapOptions for more information.
LANGUAGE = 'en' # See https://developers.google.com/maps/faq#languagesupport for supported languages.
GOOGLE_MAPS_API_KEY = None
GOOGLE_KEY = None
CACHE_LIFETIME = 600 # 10 minutes in seconds
class Meta:
prefix = 'easy_maps'
holder = 'easy_maps.conf.settings'
if settings.EASY_MAPS_GOOGLE_MAPS_API_KEY is not None:
warnings.warn("EASY_MAPS_GOOGLE_MAPS_API_KEY is deprecated, use EASY_MAPS_GOOGLE_KEY", DeprecationWarning)
|
// ... existing code ...
prefix = 'easy_maps'
holder = 'easy_maps.conf.settings'
if settings.EASY_MAPS_GOOGLE_MAPS_API_KEY is not None:
warnings.warn("EASY_MAPS_GOOGLE_MAPS_API_KEY is deprecated, use EASY_MAPS_GOOGLE_KEY", DeprecationWarning)
// ... rest of the code ...
|
9440f74bb456fb8a82a92bb662a00e1ecdb1b14f
|
3RVX/OSD/BrightnessOSD.h
|
3RVX/OSD/BrightnessOSD.h
|
// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#pragma once
#include "OSD.h"
class BrightnessOSD : public OSD {
public:
BrightnessOSD();
virtual void Hide();
virtual void ProcessHotkeys(HotkeyInfo &hki);
private:
MeterWnd _mWnd;
virtual void OnDisplayChange();
virtual LRESULT WndProc(HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam);
};
|
// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#pragma once
#include "OSD.h"
class BrightnessOSD : public OSD {
public:
BrightnessOSD();
virtual void Hide();
virtual void ProcessHotkeys(HotkeyInfo &hki);
private:
MeterWnd _mWnd;
BrightnessController *_brightnessCtrl;
virtual void OnDisplayChange();
virtual LRESULT WndProc(HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam);
};
|
Add member variable for brightness controller
|
Add member variable for brightness controller
|
C
|
bsd-2-clause
|
malensek/3RVX,malensek/3RVX,malensek/3RVX
|
c
|
## Code Before:
// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#pragma once
#include "OSD.h"
class BrightnessOSD : public OSD {
public:
BrightnessOSD();
virtual void Hide();
virtual void ProcessHotkeys(HotkeyInfo &hki);
private:
MeterWnd _mWnd;
virtual void OnDisplayChange();
virtual LRESULT WndProc(HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam);
};
## Instruction:
Add member variable for brightness controller
## Code After:
// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#pragma once
#include "OSD.h"
class BrightnessOSD : public OSD {
public:
BrightnessOSD();
virtual void Hide();
virtual void ProcessHotkeys(HotkeyInfo &hki);
private:
MeterWnd _mWnd;
BrightnessController *_brightnessCtrl;
virtual void OnDisplayChange();
virtual LRESULT WndProc(HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam);
};
|
// ... existing code ...
private:
MeterWnd _mWnd;
BrightnessController *_brightnessCtrl;
virtual void OnDisplayChange();
// ... rest of the code ...
|
06fb2ca58ca82bae42a1ec52222a2d2d2c1d16d7
|
src/main/java/hu/bme/mit/spaceship/TorpedoStore.java
|
src/main/java/hu/bme/mit/spaceship/TorpedoStore.java
|
package hu.bme.mit.spaceship;
import java.util.Random;
/**
* Class storing and managing the torpedoes of a ship
*/
public class TorpedoStore {
private int torpedoCount = 0;
private Random generator = new Random();
public TorpedoStore(int numberOfTorpedos){
this.torpedoCount = numberOfTorpedos;
}
public boolean fire(int numberOfTorpedos){
if(numberOfTorpedos < 1 || numberOfTorpedos > this.torpedoCount){
throw new IllegalArgumentException("numberOfTorpedos");
}
boolean success = false;
//simulate random overheating of the launcher bay which prevents firing
double r = generator.nextDouble();
if (r > 0.01) {
// successful firing
this.torpedoCount -= numberOfTorpedos;
success = true;
} else {
// failure
success = false;
}
return success;
}
public boolean isEmpty(){
return this.torpedoCount <= 0;
}
public int getTorpedoCount() {
return this.torpedoCount;
}
}
|
package hu.bme.mit.spaceship;
import java.util.Random;
/**
* Class storing and managing the torpedoes of a ship
*/
public class TorpedoStore {
private double FAILURE_RATE = 0.0;
private int torpedoCount = 0;
private Random generator = new Random();
public TorpedoStore(int numberOfTorpedos){
this.torpedoCount = numberOfTorpedos;
// update failure rate if it was specified in an environment variable
String failureEnv = System.getenv("IVT_RATE");
if (failureEnv != null){
try {
FAILURE_RATE = Double.parseDouble(failureEnv);
} catch (NumberFormatException nfe) {
FAILURE_RATE = 0.0;
}
}
}
public boolean fire(int numberOfTorpedos){
if(numberOfTorpedos < 1 || numberOfTorpedos > this.torpedoCount){
throw new IllegalArgumentException("numberOfTorpedos");
}
boolean success = false;
// simulate random overheating of the launcher bay which prevents firing
double r = generator.nextDouble();
if (r >= FAILURE_RATE) {
// successful firing
this.torpedoCount -= numberOfTorpedos;
success = true;
} else {
// simulated failure
success = false;
}
return success;
}
public boolean isEmpty(){
return this.torpedoCount <= 0;
}
public int getTorpedoCount() {
return this.torpedoCount;
}
}
|
Add torpedo failure rate as an environment variable
|
Add torpedo failure rate as an environment variable
|
Java
|
mit
|
FTSRG/ivt-lab
|
java
|
## Code Before:
package hu.bme.mit.spaceship;
import java.util.Random;
/**
* Class storing and managing the torpedoes of a ship
*/
public class TorpedoStore {
private int torpedoCount = 0;
private Random generator = new Random();
public TorpedoStore(int numberOfTorpedos){
this.torpedoCount = numberOfTorpedos;
}
public boolean fire(int numberOfTorpedos){
if(numberOfTorpedos < 1 || numberOfTorpedos > this.torpedoCount){
throw new IllegalArgumentException("numberOfTorpedos");
}
boolean success = false;
//simulate random overheating of the launcher bay which prevents firing
double r = generator.nextDouble();
if (r > 0.01) {
// successful firing
this.torpedoCount -= numberOfTorpedos;
success = true;
} else {
// failure
success = false;
}
return success;
}
public boolean isEmpty(){
return this.torpedoCount <= 0;
}
public int getTorpedoCount() {
return this.torpedoCount;
}
}
## Instruction:
Add torpedo failure rate as an environment variable
## Code After:
package hu.bme.mit.spaceship;
import java.util.Random;
/**
* Class storing and managing the torpedoes of a ship
*/
public class TorpedoStore {
private double FAILURE_RATE = 0.0;
private int torpedoCount = 0;
private Random generator = new Random();
public TorpedoStore(int numberOfTorpedos){
this.torpedoCount = numberOfTorpedos;
// update failure rate if it was specified in an environment variable
String failureEnv = System.getenv("IVT_RATE");
if (failureEnv != null){
try {
FAILURE_RATE = Double.parseDouble(failureEnv);
} catch (NumberFormatException nfe) {
FAILURE_RATE = 0.0;
}
}
}
public boolean fire(int numberOfTorpedos){
if(numberOfTorpedos < 1 || numberOfTorpedos > this.torpedoCount){
throw new IllegalArgumentException("numberOfTorpedos");
}
boolean success = false;
// simulate random overheating of the launcher bay which prevents firing
double r = generator.nextDouble();
if (r >= FAILURE_RATE) {
// successful firing
this.torpedoCount -= numberOfTorpedos;
success = true;
} else {
// simulated failure
success = false;
}
return success;
}
public boolean isEmpty(){
return this.torpedoCount <= 0;
}
public int getTorpedoCount() {
return this.torpedoCount;
}
}
|
# ... existing code ...
*/
public class TorpedoStore {
private double FAILURE_RATE = 0.0;
private int torpedoCount = 0;
private Random generator = new Random();
public TorpedoStore(int numberOfTorpedos){
this.torpedoCount = numberOfTorpedos;
// update failure rate if it was specified in an environment variable
String failureEnv = System.getenv("IVT_RATE");
if (failureEnv != null){
try {
FAILURE_RATE = Double.parseDouble(failureEnv);
} catch (NumberFormatException nfe) {
FAILURE_RATE = 0.0;
}
}
}
public boolean fire(int numberOfTorpedos){
# ... modified code ...
boolean success = false;
// simulate random overheating of the launcher bay which prevents firing
double r = generator.nextDouble();
if (r >= FAILURE_RATE) {
// successful firing
this.torpedoCount -= numberOfTorpedos;
success = true;
} else {
// simulated failure
success = false;
}
# ... rest of the code ...
|
b51ff5cc660485a7c24667aab450e83d16aabba3
|
Chapter5/src/RandomNumber.java
|
Chapter5/src/RandomNumber.java
|
/**
* Created by Nathan_Zeplowitz on 4/14/15.
*/
public class RandomNumber {
private int number;
public RandomNumber(){
this.number = (int) (Math.random() * 100);
}
public int getNumber() {
return number;
}
}
|
/**
* Created by Nathan_Zeplowitz on 4/14/15.
*/
public class RandomNumber {
private int number;
public RandomNumber(){
this.number = (int) (Math.random() * 100);
}
public int getNumber() {
return number;
}
public String checkGuess(String userGuess) {
int guess = Integer.parseInt(userGuess);
if (guess == getNumber()) {
return "Correct";
} else if (guess < getNumber()) {
return "Your guess was too low.";
} else {
return "Your guess was too high.";
}
}
}
|
Add CheckGuess Method to Random Number
|
Add CheckGuess Method to Random Number
|
Java
|
mit
|
n-zeplo/TW101_Exercises
|
java
|
## Code Before:
/**
* Created by Nathan_Zeplowitz on 4/14/15.
*/
public class RandomNumber {
private int number;
public RandomNumber(){
this.number = (int) (Math.random() * 100);
}
public int getNumber() {
return number;
}
}
## Instruction:
Add CheckGuess Method to Random Number
## Code After:
/**
* Created by Nathan_Zeplowitz on 4/14/15.
*/
public class RandomNumber {
private int number;
public RandomNumber(){
this.number = (int) (Math.random() * 100);
}
public int getNumber() {
return number;
}
public String checkGuess(String userGuess) {
int guess = Integer.parseInt(userGuess);
if (guess == getNumber()) {
return "Correct";
} else if (guess < getNumber()) {
return "Your guess was too low.";
} else {
return "Your guess was too high.";
}
}
}
|
...
public int getNumber() {
return number;
}
public String checkGuess(String userGuess) {
int guess = Integer.parseInt(userGuess);
if (guess == getNumber()) {
return "Correct";
} else if (guess < getNumber()) {
return "Your guess was too low.";
} else {
return "Your guess was too high.";
}
}
}
...
|
56b4532bd330ad4075f882511c87cb97eaeff10e
|
jujupy/__init__.py
|
jujupy/__init__.py
|
from jujupy.client import *
from jujupy.client import _temp_env
__all__ = ['_temp_env']
|
from jujupy.client import (
AgentsNotStarted,
AuthNotAccepted,
AGENTS_READY,
client_from_config,
ConditionList,
coalesce_agent_status,
describe_substrate,
EnvJujuClient,
EnvJujuClient1X,
EnvJujuClient25,
ensure_dir,
get_cache_path,
get_client_class,
get_local_root,
get_machine_dns_name,
get_timeout_path,
get_timeout_prefix,
GroupReporter,
IncompatibleConfigClass,
InvalidEndpoint,
jes_home_path,
JESNotSupported,
JujuData,
JUJU_DEV_FEATURE_FLAGS,
Juju2Backend,
KILL_CONTROLLER,
KVM_MACHINE,
LXC_MACHINE,
LXD_MACHINE,
Machine,
NameNotAccepted,
NoProvider,
parse_new_state_server_from_error,
SimpleEnvironment,
SoftDeadlineExceeded,
Status,
temp_bootstrap_env,
_temp_env,
temp_yaml_file,
TypeNotAccepted,
uniquify_local,
until_timeout,
)
__all__ = [
'AgentsNotStarted',
'AuthNotAccepted',
'AGENTS_READY',
'client_from_config',
'ConditionList',
'coalesce_agent_status',
'describe_substrate',
'EnvJujuClient',
'EnvJujuClient1X',
'EnvJujuClient25',
'ensure_dir',
'get_cache_path',
'get_client_class',
'get_local_root',
'get_machine_dns_name',
'get_timeout_path',
'get_timeout_prefix',
'GroupReporter',
'IncompatibleConfigClass',
'InvalidEndpoint',
'jes_home_path',
'JESNotSupported',
'JujuData',
'JUJU_DEV_FEATURE_FLAGS',
'Juju2Backend',
'KILL_CONTROLLER',
'KVM_MACHINE',
'LXC_MACHINE',
'LXD_MACHINE',
'Machine',
'NameNotAccepted',
'NoProvider',
'parse_new_state_server_from_error',
'SimpleEnvironment',
'SoftDeadlineExceeded',
'Status',
'temp_bootstrap_env',
'_temp_env',
'temp_yaml_file',
'TypeNotAccepted',
'uniquify_local',
'until_timeout',
]
|
Switch to explicit imports for jujupy.
|
Switch to explicit imports for jujupy.
|
Python
|
agpl-3.0
|
mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju
|
python
|
## Code Before:
from jujupy.client import *
from jujupy.client import _temp_env
__all__ = ['_temp_env']
## Instruction:
Switch to explicit imports for jujupy.
## Code After:
from jujupy.client import (
AgentsNotStarted,
AuthNotAccepted,
AGENTS_READY,
client_from_config,
ConditionList,
coalesce_agent_status,
describe_substrate,
EnvJujuClient,
EnvJujuClient1X,
EnvJujuClient25,
ensure_dir,
get_cache_path,
get_client_class,
get_local_root,
get_machine_dns_name,
get_timeout_path,
get_timeout_prefix,
GroupReporter,
IncompatibleConfigClass,
InvalidEndpoint,
jes_home_path,
JESNotSupported,
JujuData,
JUJU_DEV_FEATURE_FLAGS,
Juju2Backend,
KILL_CONTROLLER,
KVM_MACHINE,
LXC_MACHINE,
LXD_MACHINE,
Machine,
NameNotAccepted,
NoProvider,
parse_new_state_server_from_error,
SimpleEnvironment,
SoftDeadlineExceeded,
Status,
temp_bootstrap_env,
_temp_env,
temp_yaml_file,
TypeNotAccepted,
uniquify_local,
until_timeout,
)
__all__ = [
'AgentsNotStarted',
'AuthNotAccepted',
'AGENTS_READY',
'client_from_config',
'ConditionList',
'coalesce_agent_status',
'describe_substrate',
'EnvJujuClient',
'EnvJujuClient1X',
'EnvJujuClient25',
'ensure_dir',
'get_cache_path',
'get_client_class',
'get_local_root',
'get_machine_dns_name',
'get_timeout_path',
'get_timeout_prefix',
'GroupReporter',
'IncompatibleConfigClass',
'InvalidEndpoint',
'jes_home_path',
'JESNotSupported',
'JujuData',
'JUJU_DEV_FEATURE_FLAGS',
'Juju2Backend',
'KILL_CONTROLLER',
'KVM_MACHINE',
'LXC_MACHINE',
'LXD_MACHINE',
'Machine',
'NameNotAccepted',
'NoProvider',
'parse_new_state_server_from_error',
'SimpleEnvironment',
'SoftDeadlineExceeded',
'Status',
'temp_bootstrap_env',
'_temp_env',
'temp_yaml_file',
'TypeNotAccepted',
'uniquify_local',
'until_timeout',
]
|
...
from jujupy.client import (
AgentsNotStarted,
AuthNotAccepted,
AGENTS_READY,
client_from_config,
ConditionList,
coalesce_agent_status,
describe_substrate,
EnvJujuClient,
EnvJujuClient1X,
EnvJujuClient25,
ensure_dir,
get_cache_path,
get_client_class,
get_local_root,
get_machine_dns_name,
get_timeout_path,
get_timeout_prefix,
GroupReporter,
IncompatibleConfigClass,
InvalidEndpoint,
jes_home_path,
JESNotSupported,
JujuData,
JUJU_DEV_FEATURE_FLAGS,
Juju2Backend,
KILL_CONTROLLER,
KVM_MACHINE,
LXC_MACHINE,
LXD_MACHINE,
Machine,
NameNotAccepted,
NoProvider,
parse_new_state_server_from_error,
SimpleEnvironment,
SoftDeadlineExceeded,
Status,
temp_bootstrap_env,
_temp_env,
temp_yaml_file,
TypeNotAccepted,
uniquify_local,
until_timeout,
)
__all__ = [
'AgentsNotStarted',
'AuthNotAccepted',
'AGENTS_READY',
'client_from_config',
'ConditionList',
'coalesce_agent_status',
'describe_substrate',
'EnvJujuClient',
'EnvJujuClient1X',
'EnvJujuClient25',
'ensure_dir',
'get_cache_path',
'get_client_class',
'get_local_root',
'get_machine_dns_name',
'get_timeout_path',
'get_timeout_prefix',
'GroupReporter',
'IncompatibleConfigClass',
'InvalidEndpoint',
'jes_home_path',
'JESNotSupported',
'JujuData',
'JUJU_DEV_FEATURE_FLAGS',
'Juju2Backend',
'KILL_CONTROLLER',
'KVM_MACHINE',
'LXC_MACHINE',
'LXD_MACHINE',
'Machine',
'NameNotAccepted',
'NoProvider',
'parse_new_state_server_from_error',
'SimpleEnvironment',
'SoftDeadlineExceeded',
'Status',
'temp_bootstrap_env',
'_temp_env',
'temp_yaml_file',
'TypeNotAccepted',
'uniquify_local',
'until_timeout',
]
...
|
693346fd3ae93be37fad41bf08acc00d416ba6df
|
examples/specific/functionOverload.h
|
examples/specific/functionOverload.h
|
//! Non overloaded function
void simplefunc();
//! Function which takes two int arguments
void f(int, int);
//! Function which takes two double arguments
void f(double, double);
namespace test {
//! Another function which takes two int arguments
void g(int, int);
//! Another function which takes two double arguments
void g(double, double);
}
class MyType {};
class MyOtherType {};
//! Another function which takes a custom type
void h(std::string, MyType);
//! Another function which takes another custom type
void h(std::string, MyOtherType o);
//! Another function which takes a basic type
void h(std::string, float myfloat);
//! Another function which takes a const custom type
void h(std::string, const MyType& mytype);
//! Another function which takes a const basic type
void h(std::string, const int myint);
//! Another function which takes a const basic type
template <typename T>
void h(std::string, const T myType);
//! Another function which takes a const basic type
template <typename T, typename U>
void h(std::string, const T m, const U n);
|
//! Non overloaded function
void simplefunc();
//! Function which takes two int arguments
void f(int, int);
//! Function which takes two double arguments
void f(double, double);
namespace test {
//! Another function which takes two int arguments
void g(int, int);
//! Another function which takes two double arguments
void g(double, double);
}
class MyType {};
class MyOtherType {};
//! Another function which takes a custom type
void h(std::string, MyType);
//! Another function which takes another custom type
void h(std::string, MyOtherType o);
//! Another function which takes a basic type
void h(std::string, float myfloat);
//! Another function which takes a const custom type
void h(std::string, const MyType& mytype);
//! Another function which takes a const basic type
void h(std::string, const int myint);
//! Another function which takes a const basic type
template <typename T>
void h(std::string, const T myType);
//! Another function which takes a const basic type
template <typename T, typename U>
void h(std::string, const T m, const U n);
/**
* Test function 1.
*/
void j(int);
/**
* Test function 2.
*/
void j(char);
|
Add extra function overload example
|
Add extra function overload example
For some reason this single argument overloaded function reveals a bug
that the more complex examples do not. Thanks to vitaut for providing
it.
|
C
|
bsd-3-clause
|
kirbyfan64/breathe,AnthonyTruchet/breathe,RR2DO2/breathe,AnthonyTruchet/breathe,RR2DO2/breathe,kirbyfan64/breathe,kirbyfan64/breathe,AnthonyTruchet/breathe,AnthonyTruchet/breathe,kirbyfan64/breathe
|
c
|
## Code Before:
//! Non overloaded function
void simplefunc();
//! Function which takes two int arguments
void f(int, int);
//! Function which takes two double arguments
void f(double, double);
namespace test {
//! Another function which takes two int arguments
void g(int, int);
//! Another function which takes two double arguments
void g(double, double);
}
class MyType {};
class MyOtherType {};
//! Another function which takes a custom type
void h(std::string, MyType);
//! Another function which takes another custom type
void h(std::string, MyOtherType o);
//! Another function which takes a basic type
void h(std::string, float myfloat);
//! Another function which takes a const custom type
void h(std::string, const MyType& mytype);
//! Another function which takes a const basic type
void h(std::string, const int myint);
//! Another function which takes a const basic type
template <typename T>
void h(std::string, const T myType);
//! Another function which takes a const basic type
template <typename T, typename U>
void h(std::string, const T m, const U n);
## Instruction:
Add extra function overload example
For some reason this single argument overloaded function reveals a bug
that the more complex examples do not. Thanks to vitaut for providing
it.
## Code After:
//! Non overloaded function
void simplefunc();
//! Function which takes two int arguments
void f(int, int);
//! Function which takes two double arguments
void f(double, double);
namespace test {
//! Another function which takes two int arguments
void g(int, int);
//! Another function which takes two double arguments
void g(double, double);
}
class MyType {};
class MyOtherType {};
//! Another function which takes a custom type
void h(std::string, MyType);
//! Another function which takes another custom type
void h(std::string, MyOtherType o);
//! Another function which takes a basic type
void h(std::string, float myfloat);
//! Another function which takes a const custom type
void h(std::string, const MyType& mytype);
//! Another function which takes a const basic type
void h(std::string, const int myint);
//! Another function which takes a const basic type
template <typename T>
void h(std::string, const T myType);
//! Another function which takes a const basic type
template <typename T, typename U>
void h(std::string, const T m, const U n);
/**
* Test function 1.
*/
void j(int);
/**
* Test function 2.
*/
void j(char);
|
...
template <typename T, typename U>
void h(std::string, const T m, const U n);
/**
* Test function 1.
*/
void j(int);
/**
* Test function 2.
*/
void j(char);
...
|
f919aa183d1a82ba745df6a5640e8a7a83f8e87e
|
stix/indicator/valid_time.py
|
stix/indicator/valid_time.py
|
from mixbox import fields
import stix
from stix.common import DateTimeWithPrecision
import stix.bindings.indicator as indicator_binding
class ValidTime(stix.Entity):
_namespace = "http://stix.mitre.org/Indicator-2"
_binding = indicator_binding
_binding_class = _binding.ValidTimeType
start_time = fields.TypedField("Start_Time", DateTimeWithPrecision)
end_time = fields.TypedField("End_Time", DateTimeWithPrecision)
def __init__(self, start_time=None, end_time=None):
self._fields = {}
self.start_time = start_time
self.end_time = end_time
|
from mixbox import fields
import stix
from stix.common import DateTimeWithPrecision
import stix.bindings.indicator as indicator_binding
from mixbox.entities import Entity
class ValidTime(Entity):
_namespace = "http://stix.mitre.org/Indicator-2"
_binding = indicator_binding
_binding_class = _binding.ValidTimeType
start_time = fields.TypedField("Start_Time", DateTimeWithPrecision)
end_time = fields.TypedField("End_Time", DateTimeWithPrecision)
def __init__(self, start_time=None, end_time=None):
super(ValidTime, self).__init__()
self.start_time = start_time
self.end_time = end_time
|
Change ValidTime to a mixbox Entity
|
Change ValidTime to a mixbox Entity
|
Python
|
bsd-3-clause
|
STIXProject/python-stix
|
python
|
## Code Before:
from mixbox import fields
import stix
from stix.common import DateTimeWithPrecision
import stix.bindings.indicator as indicator_binding
class ValidTime(stix.Entity):
_namespace = "http://stix.mitre.org/Indicator-2"
_binding = indicator_binding
_binding_class = _binding.ValidTimeType
start_time = fields.TypedField("Start_Time", DateTimeWithPrecision)
end_time = fields.TypedField("End_Time", DateTimeWithPrecision)
def __init__(self, start_time=None, end_time=None):
self._fields = {}
self.start_time = start_time
self.end_time = end_time
## Instruction:
Change ValidTime to a mixbox Entity
## Code After:
from mixbox import fields
import stix
from stix.common import DateTimeWithPrecision
import stix.bindings.indicator as indicator_binding
from mixbox.entities import Entity
class ValidTime(Entity):
_namespace = "http://stix.mitre.org/Indicator-2"
_binding = indicator_binding
_binding_class = _binding.ValidTimeType
start_time = fields.TypedField("Start_Time", DateTimeWithPrecision)
end_time = fields.TypedField("End_Time", DateTimeWithPrecision)
def __init__(self, start_time=None, end_time=None):
super(ValidTime, self).__init__()
self.start_time = start_time
self.end_time = end_time
|
// ... existing code ...
import stix
from stix.common import DateTimeWithPrecision
import stix.bindings.indicator as indicator_binding
from mixbox.entities import Entity
class ValidTime(Entity):
_namespace = "http://stix.mitre.org/Indicator-2"
_binding = indicator_binding
_binding_class = _binding.ValidTimeType
// ... modified code ...
end_time = fields.TypedField("End_Time", DateTimeWithPrecision)
def __init__(self, start_time=None, end_time=None):
super(ValidTime, self).__init__()
self.start_time = start_time
self.end_time = end_time
// ... rest of the code ...
|
2d295f17d97f65e0da7ac567769703f38d5ae5aa
|
src/main/java/net/glowstone/entity/ai/TransportHelper.java
|
src/main/java/net/glowstone/entity/ai/TransportHelper.java
|
package net.glowstone.entity.ai;
import net.glowstone.entity.GlowLivingEntity;
import org.bukkit.Location;
import org.bukkit.util.Vector;
public class TransportHelper {
public static void moveTowards(GlowLivingEntity entity, Location direction) {
moveTowards(entity, direction, 0.3);
}
public static void moveTowards(GlowLivingEntity entity, Location direction, double speed) {
Location location = entity.getLocation();
double deltaX = (direction.getX() - location.getX());
double deltaZ = (direction.getZ() - location.getZ());
Vector vector = new Vector(deltaX, 0, deltaZ).normalize().multiply(speed);
entity.setVelocity(vector);
}
}
|
package net.glowstone.entity.ai;
import net.glowstone.entity.GlowLivingEntity;
import org.bukkit.Location;
import org.bukkit.util.Vector;
public class TransportHelper {
public static void moveTowards(GlowLivingEntity entity, Location direction) {
moveTowards(entity, direction, 0.3);
}
public static void moveTowards(GlowLivingEntity entity, Location direction, double speed) {
Location location = entity.getLocation();
double deltaX = (direction.getX() - location.getX());
double deltaZ = (direction.getZ() - location.getZ());
Vector vector = new Vector(deltaX, 0, deltaZ).normalize().multiply(speed);
entity.setRawLocation(location.add(vector)); // doesn't work on positive X/Z, why??
}
}
|
Use setRawLocation instead of velocity (still bugged)
|
Use setRawLocation instead of velocity (still bugged)
|
Java
|
mit
|
GlowstoneMC/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus,GlowstoneMC/GlowstonePlusPlus,GlowstoneMC/GlowstonePlusPlus,GlowstoneMC/GlowstonePlusPlus
|
java
|
## Code Before:
package net.glowstone.entity.ai;
import net.glowstone.entity.GlowLivingEntity;
import org.bukkit.Location;
import org.bukkit.util.Vector;
public class TransportHelper {
public static void moveTowards(GlowLivingEntity entity, Location direction) {
moveTowards(entity, direction, 0.3);
}
public static void moveTowards(GlowLivingEntity entity, Location direction, double speed) {
Location location = entity.getLocation();
double deltaX = (direction.getX() - location.getX());
double deltaZ = (direction.getZ() - location.getZ());
Vector vector = new Vector(deltaX, 0, deltaZ).normalize().multiply(speed);
entity.setVelocity(vector);
}
}
## Instruction:
Use setRawLocation instead of velocity (still bugged)
## Code After:
package net.glowstone.entity.ai;
import net.glowstone.entity.GlowLivingEntity;
import org.bukkit.Location;
import org.bukkit.util.Vector;
public class TransportHelper {
public static void moveTowards(GlowLivingEntity entity, Location direction) {
moveTowards(entity, direction, 0.3);
}
public static void moveTowards(GlowLivingEntity entity, Location direction, double speed) {
Location location = entity.getLocation();
double deltaX = (direction.getX() - location.getX());
double deltaZ = (direction.getZ() - location.getZ());
Vector vector = new Vector(deltaX, 0, deltaZ).normalize().multiply(speed);
entity.setRawLocation(location.add(vector)); // doesn't work on positive X/Z, why??
}
}
|
// ... existing code ...
double deltaX = (direction.getX() - location.getX());
double deltaZ = (direction.getZ() - location.getZ());
Vector vector = new Vector(deltaX, 0, deltaZ).normalize().multiply(speed);
entity.setRawLocation(location.add(vector)); // doesn't work on positive X/Z, why??
}
}
// ... rest of the code ...
|
f9f268fd483be1e75a04cd7e74dd726a2dccf814
|
src/test/kotlin/com/demonwav/mcdev/framework/ProjectBuilderTest.kt
|
src/test/kotlin/com/demonwav/mcdev/framework/ProjectBuilderTest.kt
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2017 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.framework
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
abstract class ProjectBuilderTest : LightCodeInsightFixtureTestCase() {
protected fun buildProject(builder: ProjectBuilder.() -> Unit) = ProjectBuilder(myFixture).build(builder)
fun ProjectBuilder.src(block: ProjectBuilder.() -> Unit) {
dir("src", block)
ModuleRootModificationUtil.updateModel(myFixture.module) { model ->
val contentEntry = model.contentEntries.firstOrNull { it.file == project.baseDir } ?:
model.addContentEntry(project.baseDir)
val srcFolder = project.baseDir.findChild("src")!!
if (!contentEntry.sourceFolderFiles.contains(srcFolder)) {
contentEntry.addSourceFolder(srcFolder, false)
}
}
}
}
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2017 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.framework
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
abstract class ProjectBuilderTest : LightCodeInsightFixtureTestCase() {
protected fun buildProject(builder: ProjectBuilder.() -> Unit) = ProjectBuilder(myFixture).build(builder)
fun ProjectBuilder.src(block: ProjectBuilder.() -> Unit) {
dir("src", block)
ModuleRootModificationUtil.updateModel(myFixture.module) { model ->
val contentEntry = model.contentEntries.firstOrNull { it.file == project.baseDir } ?:
model.addContentEntry(project.baseDir)
val srcFolder = project.baseDir.findChild("src")!!
if (!contentEntry.sourceFolderFiles.contains(srcFolder)) {
contentEntry.addSourceFolder(srcFolder, false)
}
}
}
override fun tearDown() {
runWriteAction {
ModuleRootModificationUtil.updateModel(myFixture.module) { model ->
model.removeContentEntry(model.contentEntries.first { it.file == project.baseDir })
}
}
super.tearDown()
}
}
|
Remove content root again after test to dispose added content entries
|
Remove content root again after test to dispose added content entries
|
Kotlin
|
mit
|
DemonWav/MinecraftDev,minecraft-dev/MinecraftDev,DemonWav/IntelliJBukkitSupport,DemonWav/MinecraftDevIntelliJ,DemonWav/MinecraftDev,DemonWav/MinecraftDev,DemonWav/MinecraftDevIntelliJ,minecraft-dev/MinecraftDev,DemonWav/MinecraftDevIntelliJ,minecraft-dev/MinecraftDev
|
kotlin
|
## Code Before:
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2017 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.framework
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
abstract class ProjectBuilderTest : LightCodeInsightFixtureTestCase() {
protected fun buildProject(builder: ProjectBuilder.() -> Unit) = ProjectBuilder(myFixture).build(builder)
fun ProjectBuilder.src(block: ProjectBuilder.() -> Unit) {
dir("src", block)
ModuleRootModificationUtil.updateModel(myFixture.module) { model ->
val contentEntry = model.contentEntries.firstOrNull { it.file == project.baseDir } ?:
model.addContentEntry(project.baseDir)
val srcFolder = project.baseDir.findChild("src")!!
if (!contentEntry.sourceFolderFiles.contains(srcFolder)) {
contentEntry.addSourceFolder(srcFolder, false)
}
}
}
}
## Instruction:
Remove content root again after test to dispose added content entries
## Code After:
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2017 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.framework
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
abstract class ProjectBuilderTest : LightCodeInsightFixtureTestCase() {
protected fun buildProject(builder: ProjectBuilder.() -> Unit) = ProjectBuilder(myFixture).build(builder)
fun ProjectBuilder.src(block: ProjectBuilder.() -> Unit) {
dir("src", block)
ModuleRootModificationUtil.updateModel(myFixture.module) { model ->
val contentEntry = model.contentEntries.firstOrNull { it.file == project.baseDir } ?:
model.addContentEntry(project.baseDir)
val srcFolder = project.baseDir.findChild("src")!!
if (!contentEntry.sourceFolderFiles.contains(srcFolder)) {
contentEntry.addSourceFolder(srcFolder, false)
}
}
}
override fun tearDown() {
runWriteAction {
ModuleRootModificationUtil.updateModel(myFixture.module) { model ->
model.removeContentEntry(model.contentEntries.first { it.file == project.baseDir })
}
}
super.tearDown()
}
}
|
// ... existing code ...
package com.demonwav.mcdev.framework
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
// ... modified code ...
}
}
}
override fun tearDown() {
runWriteAction {
ModuleRootModificationUtil.updateModel(myFixture.module) { model ->
model.removeContentEntry(model.contentEntries.first { it.file == project.baseDir })
}
}
super.tearDown()
}
}
// ... rest of the code ...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.