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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
f45fc8854647754b24df5f9601920368cd2d3c49
|
tests/chainerx_tests/unit_tests/test_cuda.py
|
tests/chainerx_tests/unit_tests/test_cuda.py
|
import pytest
from chainerx import _cuda
try:
import cupy
except Exception:
cupy = None
class CupyTestMemoryHook(cupy.cuda.memory_hook.MemoryHook):
name = 'CupyTestMemoryHook'
def __init__(self):
self.used_bytes = 0
self.acquired_bytes = 0
def alloc_preprocess(self, **kwargs):
self.acquired_bytes += kwargs['mem_size']
def malloc_preprocess(self, **kwargs):
self.used_bytes += kwargs['mem_size']
@pytest.mark.cuda()
def test_cupy_share_allocator():
with CupyTestMemoryHook() as hook:
cp_allocated = cupy.arange(10)
used_bytes = hook.used_bytes
acquired_bytes = hook.acquired_bytes
# Create a new array after changing the allocator to the memory pool
# of ChainerX and make sure that no additional memory has been
# allocated by CuPy.
_cuda.cupy_share_allocator()
chx_allocated = cupy.arange(10)
cupy.testing.assert_array_equal(cp_allocated, chx_allocated)
assert used_bytes == hook.used_bytes
assert acquired_bytes == hook.acquired_bytes
|
import pytest
from chainerx import _cuda
try:
import cupy
except Exception:
cupy = None
class CupyTestMemoryHook(cupy.cuda.memory_hook.MemoryHook):
name = 'CupyTestMemoryHook'
def __init__(self):
self.used_bytes = 0
self.acquired_bytes = 0
def alloc_preprocess(self, **kwargs):
self.acquired_bytes += kwargs['mem_size']
def malloc_preprocess(self, **kwargs):
self.used_bytes += kwargs['mem_size']
@pytest.mark.cuda()
def test_cupy_share_allocator():
with CupyTestMemoryHook() as hook:
cp_allocated = cupy.arange(10)
used_bytes = hook.used_bytes
acquired_bytes = hook.acquired_bytes
assert used_bytes > 0
assert acquired_bytes > 0
# Create a new array after changing the allocator to the memory pool
# of ChainerX and make sure that no additional memory has been
# allocated by CuPy.
_cuda.cupy_share_allocator()
chx_allocated = cupy.arange(10)
cupy.testing.assert_array_equal(cp_allocated, chx_allocated)
assert used_bytes == hook.used_bytes
assert acquired_bytes == hook.acquired_bytes
|
Add safety checks in test
|
Add safety checks in test
|
Python
|
mit
|
wkentaro/chainer,hvy/chainer,niboshi/chainer,okuta/chainer,chainer/chainer,wkentaro/chainer,chainer/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,hvy/chainer,pfnet/chainer,hvy/chainer,chainer/chainer,keisuke-umezawa/chainer,okuta/chainer,chainer/chainer,tkerola/chainer,keisuke-umezawa/chainer,wkentaro/chainer,niboshi/chainer,hvy/chainer,okuta/chainer,niboshi/chainer,niboshi/chainer,okuta/chainer,wkentaro/chainer
|
python
|
## Code Before:
import pytest
from chainerx import _cuda
try:
import cupy
except Exception:
cupy = None
class CupyTestMemoryHook(cupy.cuda.memory_hook.MemoryHook):
name = 'CupyTestMemoryHook'
def __init__(self):
self.used_bytes = 0
self.acquired_bytes = 0
def alloc_preprocess(self, **kwargs):
self.acquired_bytes += kwargs['mem_size']
def malloc_preprocess(self, **kwargs):
self.used_bytes += kwargs['mem_size']
@pytest.mark.cuda()
def test_cupy_share_allocator():
with CupyTestMemoryHook() as hook:
cp_allocated = cupy.arange(10)
used_bytes = hook.used_bytes
acquired_bytes = hook.acquired_bytes
# Create a new array after changing the allocator to the memory pool
# of ChainerX and make sure that no additional memory has been
# allocated by CuPy.
_cuda.cupy_share_allocator()
chx_allocated = cupy.arange(10)
cupy.testing.assert_array_equal(cp_allocated, chx_allocated)
assert used_bytes == hook.used_bytes
assert acquired_bytes == hook.acquired_bytes
## Instruction:
Add safety checks in test
## Code After:
import pytest
from chainerx import _cuda
try:
import cupy
except Exception:
cupy = None
class CupyTestMemoryHook(cupy.cuda.memory_hook.MemoryHook):
name = 'CupyTestMemoryHook'
def __init__(self):
self.used_bytes = 0
self.acquired_bytes = 0
def alloc_preprocess(self, **kwargs):
self.acquired_bytes += kwargs['mem_size']
def malloc_preprocess(self, **kwargs):
self.used_bytes += kwargs['mem_size']
@pytest.mark.cuda()
def test_cupy_share_allocator():
with CupyTestMemoryHook() as hook:
cp_allocated = cupy.arange(10)
used_bytes = hook.used_bytes
acquired_bytes = hook.acquired_bytes
assert used_bytes > 0
assert acquired_bytes > 0
# Create a new array after changing the allocator to the memory pool
# of ChainerX and make sure that no additional memory has been
# allocated by CuPy.
_cuda.cupy_share_allocator()
chx_allocated = cupy.arange(10)
cupy.testing.assert_array_equal(cp_allocated, chx_allocated)
assert used_bytes == hook.used_bytes
assert acquired_bytes == hook.acquired_bytes
|
...
used_bytes = hook.used_bytes
acquired_bytes = hook.acquired_bytes
assert used_bytes > 0
assert acquired_bytes > 0
# Create a new array after changing the allocator to the memory pool
# of ChainerX and make sure that no additional memory has been
...
|
52e12dac4a341ddb7bbbf8bcbf5ee8a0d9dc5ec4
|
treq/test/test_api.py
|
treq/test/test_api.py
|
import mock
from treq.test.util import TestCase
import treq
from treq._utils import set_global_pool
class TreqAPITests(TestCase):
def setUp(self):
set_global_pool(None)
client_patcher = mock.patch('treq.api.HTTPClient')
self.HTTPClient = client_patcher.start()
self.addCleanup(client_patcher.stop)
pool_patcher = mock.patch('treq._utils.HTTPConnectionPool')
self.HTTPConnectionPool = pool_patcher.start()
self.addCleanup(pool_patcher.stop)
self.client = self.HTTPClient.with_config.return_value
def test_default_pool(self):
resp = treq.get('http://test.com')
self.HTTPClient.with_config.assert_called_once_with(
pool=self.HTTPConnectionPool.return_value
)
self.assertEqual(self.client.get.return_value, resp)
def test_cached_pool(self):
pool = self.HTTPConnectionPool.return_value
treq.get('http://test.com')
self.HTTPConnectionPool.return_value = mock.Mock()
treq.get('http://test.com')
self.HTTPClient.with_config.assert_called_with(pool=pool)
|
import mock
from treq.test.util import TestCase
import treq
from treq._utils import set_global_pool
class TreqAPITests(TestCase):
def setUp(self):
set_global_pool(None)
agent_patcher = mock.patch('treq.api.Agent')
self.Agent = agent_patcher.start()
self.addCleanup(agent_patcher.stop)
client_patcher = mock.patch('treq.api.HTTPClient')
self.HTTPClient = client_patcher.start()
self.addCleanup(client_patcher.stop)
pool_patcher = mock.patch('treq._utils.HTTPConnectionPool')
self.HTTPConnectionPool = pool_patcher.start()
self.addCleanup(pool_patcher.stop)
self.client = self.HTTPClient.return_value
def test_default_pool(self):
resp = treq.get('http://test.com')
self.Agent.assert_called_once_with(
mock.ANY,
pool=self.HTTPConnectionPool.return_value
)
self.assertEqual(self.client.get.return_value, resp)
def test_cached_pool(self):
pool = self.HTTPConnectionPool.return_value
treq.get('http://test.com')
self.HTTPConnectionPool.return_value = mock.Mock()
treq.get('http://test.com')
self.Agent.assert_called_with(mock.ANY, pool=pool)
|
Update default_pool tests for new call tree (mocks are fragile).
|
Update default_pool tests for new call tree (mocks are fragile).
|
Python
|
mit
|
hawkowl/treq,hawkowl/treq,habnabit/treq,glyph/treq,cyli/treq,mithrandi/treq,ldanielburr/treq,FxIII/treq,inspectlabs/treq
|
python
|
## Code Before:
import mock
from treq.test.util import TestCase
import treq
from treq._utils import set_global_pool
class TreqAPITests(TestCase):
def setUp(self):
set_global_pool(None)
client_patcher = mock.patch('treq.api.HTTPClient')
self.HTTPClient = client_patcher.start()
self.addCleanup(client_patcher.stop)
pool_patcher = mock.patch('treq._utils.HTTPConnectionPool')
self.HTTPConnectionPool = pool_patcher.start()
self.addCleanup(pool_patcher.stop)
self.client = self.HTTPClient.with_config.return_value
def test_default_pool(self):
resp = treq.get('http://test.com')
self.HTTPClient.with_config.assert_called_once_with(
pool=self.HTTPConnectionPool.return_value
)
self.assertEqual(self.client.get.return_value, resp)
def test_cached_pool(self):
pool = self.HTTPConnectionPool.return_value
treq.get('http://test.com')
self.HTTPConnectionPool.return_value = mock.Mock()
treq.get('http://test.com')
self.HTTPClient.with_config.assert_called_with(pool=pool)
## Instruction:
Update default_pool tests for new call tree (mocks are fragile).
## Code After:
import mock
from treq.test.util import TestCase
import treq
from treq._utils import set_global_pool
class TreqAPITests(TestCase):
def setUp(self):
set_global_pool(None)
agent_patcher = mock.patch('treq.api.Agent')
self.Agent = agent_patcher.start()
self.addCleanup(agent_patcher.stop)
client_patcher = mock.patch('treq.api.HTTPClient')
self.HTTPClient = client_patcher.start()
self.addCleanup(client_patcher.stop)
pool_patcher = mock.patch('treq._utils.HTTPConnectionPool')
self.HTTPConnectionPool = pool_patcher.start()
self.addCleanup(pool_patcher.stop)
self.client = self.HTTPClient.return_value
def test_default_pool(self):
resp = treq.get('http://test.com')
self.Agent.assert_called_once_with(
mock.ANY,
pool=self.HTTPConnectionPool.return_value
)
self.assertEqual(self.client.get.return_value, resp)
def test_cached_pool(self):
pool = self.HTTPConnectionPool.return_value
treq.get('http://test.com')
self.HTTPConnectionPool.return_value = mock.Mock()
treq.get('http://test.com')
self.Agent.assert_called_with(mock.ANY, pool=pool)
|
# ... existing code ...
def setUp(self):
set_global_pool(None)
agent_patcher = mock.patch('treq.api.Agent')
self.Agent = agent_patcher.start()
self.addCleanup(agent_patcher.stop)
client_patcher = mock.patch('treq.api.HTTPClient')
self.HTTPClient = client_patcher.start()
self.addCleanup(client_patcher.stop)
# ... modified code ...
self.HTTPConnectionPool = pool_patcher.start()
self.addCleanup(pool_patcher.stop)
self.client = self.HTTPClient.return_value
def test_default_pool(self):
resp = treq.get('http://test.com')
self.Agent.assert_called_once_with(
mock.ANY,
pool=self.HTTPConnectionPool.return_value
)
...
treq.get('http://test.com')
self.Agent.assert_called_with(mock.ANY, pool=pool)
# ... rest of the code ...
|
619fa5a8345a32eb2913b85f01b9d2bc8453b688
|
sms_939/controllers/sms_notification_controller.py
|
sms_939/controllers/sms_notification_controller.py
|
import logging
import json
from odoo import http, tools
from odoo.http import request
from ..tools import SmsNotificationAnswer
async = not tools.config.get('test_enable')
_logger = logging.getLogger(__name__)
class RestController(http.Controller):
@http.route('/sms/mnc/', type='http', auth='public', methods=['GET'],
csrf=False)
def sms_notification(self, **parameters):
_logger.info("SMS Request received : {}".format(
json.dumps(parameters)))
notification_env = request.env['sms.notification'].sudo()
(notification_env.with_delay() if async else notification_env) \
.send_sms_answer(parameters)
return SmsNotificationAnswer([], costs=[]).get_answer()
|
import logging
import json
from odoo import http, tools
from odoo.http import request
from ..tools import SmsNotificationAnswer
async = not tools.config.get('test_enable')
_logger = logging.getLogger(__name__)
class RestController(http.Controller):
@http.route('/sms/mnc/', type='http', auth='public', methods=['GET'],
csrf=False)
def sms_notification(self, **parameters):
_logger.info("SMS Request received : {}".format(
json.dumps(parameters)))
notification_env = request.env['sms.notification'].sudo()
(notification_env.with_delay(priority=1) if async else
notification_env).send_sms_answer(parameters)
return SmsNotificationAnswer([], costs=[]).get_answer()
|
Put SMS answer job in very high priority
|
Put SMS answer job in very high priority
|
Python
|
agpl-3.0
|
CompassionCH/compassion-switzerland,ecino/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,ecino/compassion-switzerland,ecino/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland
|
python
|
## Code Before:
import logging
import json
from odoo import http, tools
from odoo.http import request
from ..tools import SmsNotificationAnswer
async = not tools.config.get('test_enable')
_logger = logging.getLogger(__name__)
class RestController(http.Controller):
@http.route('/sms/mnc/', type='http', auth='public', methods=['GET'],
csrf=False)
def sms_notification(self, **parameters):
_logger.info("SMS Request received : {}".format(
json.dumps(parameters)))
notification_env = request.env['sms.notification'].sudo()
(notification_env.with_delay() if async else notification_env) \
.send_sms_answer(parameters)
return SmsNotificationAnswer([], costs=[]).get_answer()
## Instruction:
Put SMS answer job in very high priority
## Code After:
import logging
import json
from odoo import http, tools
from odoo.http import request
from ..tools import SmsNotificationAnswer
async = not tools.config.get('test_enable')
_logger = logging.getLogger(__name__)
class RestController(http.Controller):
@http.route('/sms/mnc/', type='http', auth='public', methods=['GET'],
csrf=False)
def sms_notification(self, **parameters):
_logger.info("SMS Request received : {}".format(
json.dumps(parameters)))
notification_env = request.env['sms.notification'].sudo()
(notification_env.with_delay(priority=1) if async else
notification_env).send_sms_answer(parameters)
return SmsNotificationAnswer([], costs=[]).get_answer()
|
// ... existing code ...
json.dumps(parameters)))
notification_env = request.env['sms.notification'].sudo()
(notification_env.with_delay(priority=1) if async else
notification_env).send_sms_answer(parameters)
return SmsNotificationAnswer([], costs=[]).get_answer()
// ... rest of the code ...
|
3da9b0f9472e1174e23337c4ab233119fdef9bfc
|
src/net/java/sip/communicator/impl/gui/main/DialPadButton.java
|
src/net/java/sip/communicator/impl/gui/main/DialPadButton.java
|
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.gui.main;
import java.awt.*;
import java.awt.event.*;
import net.java.sip.communicator.impl.gui.utils.*;
import net.java.sip.communicator.util.swing.*;
/**
* The dial pad button in the contact list.
*
* @author Yana Stamcheva
*/
public class DialPadButton
extends SIPCommTextButton
{
/**
* The dial pad dialog that this button opens.
*/
GeneralDialPadDialog dialPad;
/**
* Creates an instance of <tt>DialPadButton</tt>.
*/
public DialPadButton()
{
super("");
loadSkin();
addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (dialPad == null)
dialPad = new GeneralDialPadDialog();
dialPad.clear();
dialPad.setVisible(true);
}
});
}
/**
* Loads images and sets history view.
*/
public void loadSkin()
{
Image image = ImageLoader.getImage(ImageLoader.CONTACT_LIST_DIAL_BUTTON);
setBgImage(image);
this.setPreferredSize(new Dimension(image.getWidth(this),
image.getHeight(this)));
}
}
|
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.gui.main;
import java.awt.*;
import java.awt.event.*;
import javax.swing.BorderFactory;
import net.java.sip.communicator.impl.gui.utils.*;
import net.java.sip.communicator.util.swing.*;
/**
* The dial pad button in the contact list.
*
* @author Yana Stamcheva
*/
public class DialPadButton
extends SIPCommTextButton
{
/**
* The dial pad dialog that this button opens.
*/
GeneralDialPadDialog dialPad;
/**
* Creates an instance of <tt>DialPadButton</tt>.
*/
public DialPadButton()
{
super("");
loadSkin();
setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (dialPad == null)
dialPad = new GeneralDialPadDialog();
dialPad.clear();
dialPad.setVisible(true);
}
});
}
/**
* Loads images and sets history view.
*/
public void loadSkin()
{
Image image = ImageLoader.getImage(ImageLoader.CONTACT_LIST_DIAL_BUTTON);
setBgImage(image);
this.setPreferredSize(new Dimension(image.getWidth(this),
image.getHeight(this)));
}
}
|
Remove border from dialpad-button to hide the button style on ubuntu
|
Remove border from dialpad-button to hide the button style on ubuntu
|
Java
|
apache-2.0
|
pplatek/jitsi,pplatek/jitsi,jibaro/jitsi,bhatvv/jitsi,mckayclarey/jitsi,459below/jitsi,bhatvv/jitsi,dkcreinoso/jitsi,cobratbq/jitsi,laborautonomo/jitsi,mckayclarey/jitsi,iant-gmbh/jitsi,marclaporte/jitsi,level7systems/jitsi,ringdna/jitsi,damencho/jitsi,ibauersachs/jitsi,ringdna/jitsi,marclaporte/jitsi,gpolitis/jitsi,cobratbq/jitsi,gpolitis/jitsi,Metaswitch/jitsi,jibaro/jitsi,HelioGuilherme66/jitsi,bhatvv/jitsi,jibaro/jitsi,459below/jitsi,dkcreinoso/jitsi,bebo/jitsi,jibaro/jitsi,bhatvv/jitsi,tuijldert/jitsi,procandi/jitsi,pplatek/jitsi,iant-gmbh/jitsi,cobratbq/jitsi,mckayclarey/jitsi,damencho/jitsi,jitsi/jitsi,damencho/jitsi,iant-gmbh/jitsi,dkcreinoso/jitsi,level7systems/jitsi,marclaporte/jitsi,level7systems/jitsi,iant-gmbh/jitsi,procandi/jitsi,damencho/jitsi,HelioGuilherme66/jitsi,jitsi/jitsi,pplatek/jitsi,459below/jitsi,jitsi/jitsi,laborautonomo/jitsi,ibauersachs/jitsi,HelioGuilherme66/jitsi,martin7890/jitsi,iant-gmbh/jitsi,pplatek/jitsi,bebo/jitsi,procandi/jitsi,marclaporte/jitsi,level7systems/jitsi,ibauersachs/jitsi,marclaporte/jitsi,gpolitis/jitsi,cobratbq/jitsi,bebo/jitsi,laborautonomo/jitsi,bhatvv/jitsi,laborautonomo/jitsi,bebo/jitsi,tuijldert/jitsi,damencho/jitsi,jitsi/jitsi,martin7890/jitsi,martin7890/jitsi,tuijldert/jitsi,gpolitis/jitsi,bebo/jitsi,dkcreinoso/jitsi,jitsi/jitsi,tuijldert/jitsi,Metaswitch/jitsi,ringdna/jitsi,martin7890/jitsi,gpolitis/jitsi,cobratbq/jitsi,459below/jitsi,level7systems/jitsi,tuijldert/jitsi,mckayclarey/jitsi,HelioGuilherme66/jitsi,martin7890/jitsi,ibauersachs/jitsi,procandi/jitsi,procandi/jitsi,Metaswitch/jitsi,laborautonomo/jitsi,Metaswitch/jitsi,459below/jitsi,jibaro/jitsi,mckayclarey/jitsi,ibauersachs/jitsi,dkcreinoso/jitsi,HelioGuilherme66/jitsi,ringdna/jitsi,ringdna/jitsi
|
java
|
## Code Before:
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.gui.main;
import java.awt.*;
import java.awt.event.*;
import net.java.sip.communicator.impl.gui.utils.*;
import net.java.sip.communicator.util.swing.*;
/**
* The dial pad button in the contact list.
*
* @author Yana Stamcheva
*/
public class DialPadButton
extends SIPCommTextButton
{
/**
* The dial pad dialog that this button opens.
*/
GeneralDialPadDialog dialPad;
/**
* Creates an instance of <tt>DialPadButton</tt>.
*/
public DialPadButton()
{
super("");
loadSkin();
addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (dialPad == null)
dialPad = new GeneralDialPadDialog();
dialPad.clear();
dialPad.setVisible(true);
}
});
}
/**
* Loads images and sets history view.
*/
public void loadSkin()
{
Image image = ImageLoader.getImage(ImageLoader.CONTACT_LIST_DIAL_BUTTON);
setBgImage(image);
this.setPreferredSize(new Dimension(image.getWidth(this),
image.getHeight(this)));
}
}
## Instruction:
Remove border from dialpad-button to hide the button style on ubuntu
## Code After:
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.gui.main;
import java.awt.*;
import java.awt.event.*;
import javax.swing.BorderFactory;
import net.java.sip.communicator.impl.gui.utils.*;
import net.java.sip.communicator.util.swing.*;
/**
* The dial pad button in the contact list.
*
* @author Yana Stamcheva
*/
public class DialPadButton
extends SIPCommTextButton
{
/**
* The dial pad dialog that this button opens.
*/
GeneralDialPadDialog dialPad;
/**
* Creates an instance of <tt>DialPadButton</tt>.
*/
public DialPadButton()
{
super("");
loadSkin();
setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (dialPad == null)
dialPad = new GeneralDialPadDialog();
dialPad.clear();
dialPad.setVisible(true);
}
});
}
/**
* Loads images and sets history view.
*/
public void loadSkin()
{
Image image = ImageLoader.getImage(ImageLoader.CONTACT_LIST_DIAL_BUTTON);
setBgImage(image);
this.setPreferredSize(new Dimension(image.getWidth(this),
image.getHeight(this)));
}
}
|
// ... existing code ...
import java.awt.*;
import java.awt.event.*;
import javax.swing.BorderFactory;
import net.java.sip.communicator.impl.gui.utils.*;
import net.java.sip.communicator.util.swing.*;
// ... modified code ...
super("");
loadSkin();
setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
addActionListener(new ActionListener()
{
// ... rest of the code ...
|
dc2c960bb937cc287dedf95d407ed2e95f3f6724
|
sigma_files/serializers.py
|
sigma_files/serializers.py
|
from rest_framework import serializers
from sigma.utils import CurrentUserCreateOnlyDefault
from sigma_files.models import Image
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
file = serializers.ImageField(max_length=255)
height = serializers.IntegerField(source='file.height', read_only=True)
width = serializers.IntegerField(source='file.width', read_only=True)
owner = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserCreateOnlyDefault())
|
from rest_framework import serializers
from dry_rest_permissions.generics import DRYPermissionsField
from sigma.utils import CurrentUserCreateOnlyDefault
from sigma_files.models import Image
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
file = serializers.ImageField(max_length=255)
height = serializers.IntegerField(source='file.height', read_only=True)
width = serializers.IntegerField(source='file.width', read_only=True)
owner = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserCreateOnlyDefault())
permissions = DRYPermissionsField(actions=['read', 'write'])
|
Add permissions field on ImageSerializer
|
Add permissions field on ImageSerializer
|
Python
|
agpl-3.0
|
ProjetSigma/backend,ProjetSigma/backend
|
python
|
## Code Before:
from rest_framework import serializers
from sigma.utils import CurrentUserCreateOnlyDefault
from sigma_files.models import Image
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
file = serializers.ImageField(max_length=255)
height = serializers.IntegerField(source='file.height', read_only=True)
width = serializers.IntegerField(source='file.width', read_only=True)
owner = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserCreateOnlyDefault())
## Instruction:
Add permissions field on ImageSerializer
## Code After:
from rest_framework import serializers
from dry_rest_permissions.generics import DRYPermissionsField
from sigma.utils import CurrentUserCreateOnlyDefault
from sigma_files.models import Image
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
file = serializers.ImageField(max_length=255)
height = serializers.IntegerField(source='file.height', read_only=True)
width = serializers.IntegerField(source='file.width', read_only=True)
owner = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserCreateOnlyDefault())
permissions = DRYPermissionsField(actions=['read', 'write'])
|
...
from rest_framework import serializers
from dry_rest_permissions.generics import DRYPermissionsField
from sigma.utils import CurrentUserCreateOnlyDefault
from sigma_files.models import Image
...
height = serializers.IntegerField(source='file.height', read_only=True)
width = serializers.IntegerField(source='file.width', read_only=True)
owner = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserCreateOnlyDefault())
permissions = DRYPermissionsField(actions=['read', 'write'])
...
|
9678a6cf5cb9431419f4f404ec07fc9d4091cbde
|
setup.py
|
setup.py
|
from setuptools import setup
import sys
setup(
name='bbcode',
version='1.0.5',
description='A pure python bbcode parser and formatter.',
author='Dan Watson',
author_email='[email protected]',
url='https://bitbucket.org/dcwatson/bbcode',
license='BSD',
py_modules=['bbcode'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
"Programming Language :: Python :: 3",
'Topic :: Text Processing :: Markup',
]
)
|
from distutils.core import setup
import sys
setup(
name='bbcode',
version='1.0.5',
description='A pure python bbcode parser and formatter.',
author='Dan Watson',
author_email='[email protected]',
url='https://bitbucket.org/dcwatson/bbcode',
license='BSD',
py_modules=['bbcode'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
"Programming Language :: Python :: 3",
'Topic :: Text Processing :: Markup',
]
)
|
Use distutils to avoid external dependencies
|
Use distutils to avoid external dependencies
|
Python
|
bsd-2-clause
|
dcwatson/bbcode
|
python
|
## Code Before:
from setuptools import setup
import sys
setup(
name='bbcode',
version='1.0.5',
description='A pure python bbcode parser and formatter.',
author='Dan Watson',
author_email='[email protected]',
url='https://bitbucket.org/dcwatson/bbcode',
license='BSD',
py_modules=['bbcode'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
"Programming Language :: Python :: 3",
'Topic :: Text Processing :: Markup',
]
)
## Instruction:
Use distutils to avoid external dependencies
## Code After:
from distutils.core import setup
import sys
setup(
name='bbcode',
version='1.0.5',
description='A pure python bbcode parser and formatter.',
author='Dan Watson',
author_email='[email protected]',
url='https://bitbucket.org/dcwatson/bbcode',
license='BSD',
py_modules=['bbcode'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
"Programming Language :: Python :: 3",
'Topic :: Text Processing :: Markup',
]
)
|
# ... existing code ...
from distutils.core import setup
import sys
setup(
# ... rest of the code ...
|
02b194c36659bfd85485aded4e52c3e587df48b0
|
Runtime/Rendering/BufferDX11.h
|
Runtime/Rendering/BufferDX11.h
|
namespace Mile
{
class MEAPI BufferDX11 : public ResourceDX11
{
public:
BufferDX11( RendererDX11* renderer ) :
m_buffer( nullptr ),
ResourceDX11( renderer )
{
}
~BufferDX11( )
{
SafeRelease( m_buffer );
}
virtual ID3D11Resource* GetResource( ) override;
D3D11_BUFFER_DESC GetDesc( ) const { return m_desc; }
virtual void* Map( ) { return nullptr; }
virtual void UnMap( ) { }
protected:
ID3D11Buffer* m_buffer;
D3D11_BUFFER_DESC m_desc;
};
}
|
namespace Mile
{
class MEAPI BufferDX11 : public ResourceDX11
{
public:
BufferDX11( RendererDX11* renderer ) :
m_buffer( nullptr ),
ResourceDX11( renderer )
{
}
~BufferDX11( )
{
SafeRelease( m_buffer );
}
virtual ID3D11Resource* GetResource( ) override;
D3D11_BUFFER_DESC GetDesc( ) const { return m_desc; }
virtual void* Map( ) { return nullptr; }
virtual bool UnMap( ) { return false; }
protected:
ID3D11Buffer* m_buffer;
D3D11_BUFFER_DESC m_desc;
};
}
|
Modify UnMap function return boolean value that succesfully unmaped.
|
Modify UnMap function return boolean value that succesfully unmaped.
|
C
|
mit
|
HoRangDev/MileEngine,HoRangDev/MileEngine
|
c
|
## Code Before:
namespace Mile
{
class MEAPI BufferDX11 : public ResourceDX11
{
public:
BufferDX11( RendererDX11* renderer ) :
m_buffer( nullptr ),
ResourceDX11( renderer )
{
}
~BufferDX11( )
{
SafeRelease( m_buffer );
}
virtual ID3D11Resource* GetResource( ) override;
D3D11_BUFFER_DESC GetDesc( ) const { return m_desc; }
virtual void* Map( ) { return nullptr; }
virtual void UnMap( ) { }
protected:
ID3D11Buffer* m_buffer;
D3D11_BUFFER_DESC m_desc;
};
}
## Instruction:
Modify UnMap function return boolean value that succesfully unmaped.
## Code After:
namespace Mile
{
class MEAPI BufferDX11 : public ResourceDX11
{
public:
BufferDX11( RendererDX11* renderer ) :
m_buffer( nullptr ),
ResourceDX11( renderer )
{
}
~BufferDX11( )
{
SafeRelease( m_buffer );
}
virtual ID3D11Resource* GetResource( ) override;
D3D11_BUFFER_DESC GetDesc( ) const { return m_desc; }
virtual void* Map( ) { return nullptr; }
virtual bool UnMap( ) { return false; }
protected:
ID3D11Buffer* m_buffer;
D3D11_BUFFER_DESC m_desc;
};
}
|
// ... existing code ...
D3D11_BUFFER_DESC GetDesc( ) const { return m_desc; }
virtual void* Map( ) { return nullptr; }
virtual bool UnMap( ) { return false; }
protected:
ID3D11Buffer* m_buffer;
// ... rest of the code ...
|
513c7a2f5c5fb5a8c47b3173a8d5854755f7928f
|
pylab/website/tests/test_about_page.py
|
pylab/website/tests/test_about_page.py
|
import datetime
from django_webtest import WebTest
from django.contrib.auth.models import User
from pylab.core.models import Event
class AboutPageTests(WebTest):
def setUp(self):
self.user = User.objects.create(username='u1')
def test_no_events_on_about_page(self):
resp = self.app.get('/about/')
self.assertEqual(resp.status_int, 200)
self.assertTrue(b'No events yet.' in resp.content)
def test_event_list_on_about_page(self):
Event.objects.create(
author=self.user,
starts=datetime.datetime(2015, 9, 3),
ends=datetime.datetime(2015, 9, 3),
title='Test title',
osm_map_link='http://openstreetmap.org/',
description='Test description',
)
resp = self.app.get('/about/')
self.assertEqual(resp.status_int, 200)
self.assertTrue(b'Test title' in resp.content)
|
import datetime
from django_webtest import WebTest
from pylab.core.models import Event
from pylab.core.factories import EventFactory
class AboutPageTests(WebTest):
def test_no_events_on_about_page(self):
resp = self.app.get('/about/')
self.assertEqual(resp.status_int, 200)
self.assertTrue(b'No events yet.' in resp.content)
def test_event_list_on_about_page(self):
EventFactory(
event_type=Event.WEEKLY_MEETING,
title='Summer Python workshop',
slug='python-workshop',
starts=datetime.datetime(2015, 7, 30, 18, 0),
ends=datetime.datetime(2015, 7, 30, 20, 0),
)
resp = self.app.get('/about/')
self.assertEqual(resp.status_int, 200)
self.assertTrue(b'Summer Python workshop' in resp.content)
|
Use factories instead of creating instance from model
|
Use factories instead of creating instance from model
|
Python
|
agpl-3.0
|
python-dirbtuves/website,python-dirbtuves/website,python-dirbtuves/website
|
python
|
## Code Before:
import datetime
from django_webtest import WebTest
from django.contrib.auth.models import User
from pylab.core.models import Event
class AboutPageTests(WebTest):
def setUp(self):
self.user = User.objects.create(username='u1')
def test_no_events_on_about_page(self):
resp = self.app.get('/about/')
self.assertEqual(resp.status_int, 200)
self.assertTrue(b'No events yet.' in resp.content)
def test_event_list_on_about_page(self):
Event.objects.create(
author=self.user,
starts=datetime.datetime(2015, 9, 3),
ends=datetime.datetime(2015, 9, 3),
title='Test title',
osm_map_link='http://openstreetmap.org/',
description='Test description',
)
resp = self.app.get('/about/')
self.assertEqual(resp.status_int, 200)
self.assertTrue(b'Test title' in resp.content)
## Instruction:
Use factories instead of creating instance from model
## Code After:
import datetime
from django_webtest import WebTest
from pylab.core.models import Event
from pylab.core.factories import EventFactory
class AboutPageTests(WebTest):
def test_no_events_on_about_page(self):
resp = self.app.get('/about/')
self.assertEqual(resp.status_int, 200)
self.assertTrue(b'No events yet.' in resp.content)
def test_event_list_on_about_page(self):
EventFactory(
event_type=Event.WEEKLY_MEETING,
title='Summer Python workshop',
slug='python-workshop',
starts=datetime.datetime(2015, 7, 30, 18, 0),
ends=datetime.datetime(2015, 7, 30, 20, 0),
)
resp = self.app.get('/about/')
self.assertEqual(resp.status_int, 200)
self.assertTrue(b'Summer Python workshop' in resp.content)
|
// ... existing code ...
import datetime
from django_webtest import WebTest
from pylab.core.models import Event
from pylab.core.factories import EventFactory
class AboutPageTests(WebTest):
def test_no_events_on_about_page(self):
resp = self.app.get('/about/')
// ... modified code ...
self.assertTrue(b'No events yet.' in resp.content)
def test_event_list_on_about_page(self):
EventFactory(
event_type=Event.WEEKLY_MEETING,
title='Summer Python workshop',
slug='python-workshop',
starts=datetime.datetime(2015, 7, 30, 18, 0),
ends=datetime.datetime(2015, 7, 30, 20, 0),
)
resp = self.app.get('/about/')
self.assertEqual(resp.status_int, 200)
self.assertTrue(b'Summer Python workshop' in resp.content)
// ... rest of the code ...
|
23b07ee7e556463518185595b3d7384db4949a3e
|
src/main/java/com/aemreunal/repository/scenario/ScenarioRepo.java
|
src/main/java/com/aemreunal/repository/scenario/ScenarioRepo.java
|
package com.aemreunal.repository.scenario;
/*
***************************
* Copyright (c) 2014 *
* *
* This code belongs to: *
* *
* @author Ahmet Emre Ünal *
* S001974 *
* *
* [email protected] *
* [email protected] *
* *
* aemreunal.com *
***************************
*/
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import com.aemreunal.domain.Scenario;
public interface ScenarioRepo extends CrudRepository<Scenario, Long>, JpaSpecificationExecutor {
}
|
package com.aemreunal.repository.scenario;
/*
***************************
* Copyright (c) 2014 *
* *
* This code belongs to: *
* *
* @author Ahmet Emre Ünal *
* S001974 *
* *
* [email protected] *
* [email protected] *
* *
* aemreunal.com *
***************************
*/
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import com.aemreunal.domain.Project;
import com.aemreunal.domain.Scenario;
public interface ScenarioRepo extends CrudRepository<Scenario, Long>, JpaSpecificationExecutor {
public Scenario findByScenarioIdAndProject(Long scenarioId, Project project);
}
|
Add Scenario repo search method
|
Add Scenario repo search method
|
Java
|
mit
|
aemreunal/iBeaconServer,aemreunal/iBeaconServer
|
java
|
## Code Before:
package com.aemreunal.repository.scenario;
/*
***************************
* Copyright (c) 2014 *
* *
* This code belongs to: *
* *
* @author Ahmet Emre Ünal *
* S001974 *
* *
* [email protected] *
* [email protected] *
* *
* aemreunal.com *
***************************
*/
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import com.aemreunal.domain.Scenario;
public interface ScenarioRepo extends CrudRepository<Scenario, Long>, JpaSpecificationExecutor {
}
## Instruction:
Add Scenario repo search method
## Code After:
package com.aemreunal.repository.scenario;
/*
***************************
* Copyright (c) 2014 *
* *
* This code belongs to: *
* *
* @author Ahmet Emre Ünal *
* S001974 *
* *
* [email protected] *
* [email protected] *
* *
* aemreunal.com *
***************************
*/
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import com.aemreunal.domain.Project;
import com.aemreunal.domain.Scenario;
public interface ScenarioRepo extends CrudRepository<Scenario, Long>, JpaSpecificationExecutor {
public Scenario findByScenarioIdAndProject(Long scenarioId, Project project);
}
|
// ... existing code ...
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import com.aemreunal.domain.Project;
import com.aemreunal.domain.Scenario;
public interface ScenarioRepo extends CrudRepository<Scenario, Long>, JpaSpecificationExecutor {
public Scenario findByScenarioIdAndProject(Long scenarioId, Project project);
}
// ... rest of the code ...
|
52a4a10d54374b08c5835d02077fd1edcdc547ac
|
tests/test_union_energy_grids/results.py
|
tests/test_union_energy_grids/results.py
|
import sys
# import statepoint
sys.path.insert(0, '../../src/utils')
import statepoint
# read in statepoint file
if len(sys.argv) > 1:
sp = statepoint.StatePoint(sys.argv[1])
else:
sp = statepoint.StatePoint('statepoint.10.binary')
sp.read_results()
# set up output string
outstr = ''
# write out k-combined
outstr += 'k-combined:\n'
outstr += "{0:12.6E} {1:12.6E}\n".format(sp.k_combined[0], sp.k_combined[1])
# write results to file
with open('results_test.dat','w') as fh:
fh.write(outstr)
|
import sys
sys.path.insert(0, '../../src/utils')
from openmc.statepoint import StatePoint
# read in statepoint file
if len(sys.argv) > 1:
print(sys.argv)
sp = StatePoint(sys.argv[1])
else:
sp = StatePoint('statepoint.10.binary')
sp.read_results()
# set up output string
outstr = ''
# write out k-combined
outstr += 'k-combined:\n'
outstr += "{0:12.6E} {1:12.6E}\n".format(sp.k_combined[0], sp.k_combined[1])
# write results to file
with open('results_test.dat','w') as fh:
fh.write(outstr)
|
Fix import for statepoint for test_union_energy_grids
|
Fix import for statepoint for test_union_energy_grids
|
Python
|
mit
|
smharper/openmc,paulromano/openmc,mit-crpg/openmc,bhermanmit/openmc,wbinventor/openmc,paulromano/openmc,samuelshaner/openmc,mit-crpg/openmc,smharper/openmc,samuelshaner/openmc,johnnyliu27/openmc,mit-crpg/openmc,lilulu/openmc,walshjon/openmc,shikhar413/openmc,liangjg/openmc,shikhar413/openmc,walshjon/openmc,paulromano/openmc,amandalund/openmc,lilulu/openmc,samuelshaner/openmc,kellyrowland/openmc,kellyrowland/openmc,wbinventor/openmc,smharper/openmc,shikhar413/openmc,johnnyliu27/openmc,smharper/openmc,wbinventor/openmc,wbinventor/openmc,walshjon/openmc,lilulu/openmc,amandalund/openmc,johnnyliu27/openmc,mjlong/openmc,liangjg/openmc,mit-crpg/openmc,paulromano/openmc,shikhar413/openmc,bhermanmit/openmc,samuelshaner/openmc,johnnyliu27/openmc,liangjg/openmc,walshjon/openmc,amandalund/openmc,amandalund/openmc,liangjg/openmc,mjlong/openmc
|
python
|
## Code Before:
import sys
# import statepoint
sys.path.insert(0, '../../src/utils')
import statepoint
# read in statepoint file
if len(sys.argv) > 1:
sp = statepoint.StatePoint(sys.argv[1])
else:
sp = statepoint.StatePoint('statepoint.10.binary')
sp.read_results()
# set up output string
outstr = ''
# write out k-combined
outstr += 'k-combined:\n'
outstr += "{0:12.6E} {1:12.6E}\n".format(sp.k_combined[0], sp.k_combined[1])
# write results to file
with open('results_test.dat','w') as fh:
fh.write(outstr)
## Instruction:
Fix import for statepoint for test_union_energy_grids
## Code After:
import sys
sys.path.insert(0, '../../src/utils')
from openmc.statepoint import StatePoint
# read in statepoint file
if len(sys.argv) > 1:
print(sys.argv)
sp = StatePoint(sys.argv[1])
else:
sp = StatePoint('statepoint.10.binary')
sp.read_results()
# set up output string
outstr = ''
# write out k-combined
outstr += 'k-combined:\n'
outstr += "{0:12.6E} {1:12.6E}\n".format(sp.k_combined[0], sp.k_combined[1])
# write results to file
with open('results_test.dat','w') as fh:
fh.write(outstr)
|
// ... existing code ...
import sys
sys.path.insert(0, '../../src/utils')
from openmc.statepoint import StatePoint
# read in statepoint file
if len(sys.argv) > 1:
print(sys.argv)
sp = StatePoint(sys.argv[1])
else:
sp = StatePoint('statepoint.10.binary')
sp.read_results()
# set up output string
outstr = ''
# write out k-combined
outstr += 'k-combined:\n'
outstr += "{0:12.6E} {1:12.6E}\n".format(sp.k_combined[0], sp.k_combined[1])
// ... rest of the code ...
|
e503ef58e801cfbc3ba72ba84bc2150c79a401d3
|
girder/molecules/molecules/models/geometry.py
|
girder/molecules/molecules/models/geometry.py
|
from bson.objectid import ObjectId
from girder.models.model_base import AccessControlledModel
from girder.constants import AccessType
from .molecule import Molecule as MoleculeModel
class Geometry(AccessControlledModel):
def __init__(self):
super(Geometry, self).__init__()
def initialize(self):
self.name = 'geometry'
self.ensureIndex('moleculeId')
self.exposeFields(level=AccessType.READ, fields=(
'_id', 'moleculeId', 'cjson', 'provenanceType', 'provenanceId'))
def validate(self, doc):
# If we have a moleculeId ensure it is valid.
if 'moleculeId' in doc:
mol = MoleculeModel().load(doc['moleculeId'], force=True)
doc['moleculeId'] = mol['_id']
return doc
def create(self, user, moleculeId, cjson, provenanceType=None,
provenanceId=None, public=False):
geometry = {
'moleculeId': moleculeId,
'cjson': cjson
}
if provenanceType is not None:
geometry['provenanceType'] = provenanceType
if provenanceId is not None:
geometry['provenanceId'] = provenanceId
self.setUserAccess(geometry, user=user, level=AccessType.ADMIN)
if public:
self.setPublic(geometry, True)
return self.save(geometry)
def find_geometries(self, moleculeId, user=None):
query = {
'moleculeId': ObjectId(moleculeId)
}
return self.findWithPermissions(query, user=user)
|
from bson.objectid import ObjectId
from girder.models.model_base import AccessControlledModel
from girder.constants import AccessType
from .molecule import Molecule as MoleculeModel
class Geometry(AccessControlledModel):
def __init__(self):
super(Geometry, self).__init__()
def initialize(self):
self.name = 'geometry'
self.ensureIndex('moleculeId')
self.exposeFields(level=AccessType.READ, fields=(
'_id', 'moleculeId', 'cjson', 'provenanceType', 'provenanceId'))
def validate(self, doc):
# If we have a moleculeId ensure it is valid.
if 'moleculeId' in doc:
mol = MoleculeModel().load(doc['moleculeId'], force=True)
doc['moleculeId'] = mol['_id']
return doc
def create(self, user, moleculeId, cjson, provenanceType=None,
provenanceId=None, public=False):
geometry = {
'moleculeId': moleculeId,
'cjson': cjson,
'creatorId': user['_id']
}
if provenanceType is not None:
geometry['provenanceType'] = provenanceType
if provenanceId is not None:
geometry['provenanceId'] = provenanceId
self.setUserAccess(geometry, user=user, level=AccessType.ADMIN)
if public:
self.setPublic(geometry, True)
return self.save(geometry)
def find_geometries(self, moleculeId, user=None):
query = {
'moleculeId': ObjectId(moleculeId)
}
return self.findWithPermissions(query, user=user)
|
Save creatorId as well for geometries
|
Save creatorId as well for geometries
This is to keep track of the creator, even when the provenance
is not the user.
Signed-off-by: Patrick Avery <[email protected]>
|
Python
|
bsd-3-clause
|
OpenChemistry/mongochemserver
|
python
|
## Code Before:
from bson.objectid import ObjectId
from girder.models.model_base import AccessControlledModel
from girder.constants import AccessType
from .molecule import Molecule as MoleculeModel
class Geometry(AccessControlledModel):
def __init__(self):
super(Geometry, self).__init__()
def initialize(self):
self.name = 'geometry'
self.ensureIndex('moleculeId')
self.exposeFields(level=AccessType.READ, fields=(
'_id', 'moleculeId', 'cjson', 'provenanceType', 'provenanceId'))
def validate(self, doc):
# If we have a moleculeId ensure it is valid.
if 'moleculeId' in doc:
mol = MoleculeModel().load(doc['moleculeId'], force=True)
doc['moleculeId'] = mol['_id']
return doc
def create(self, user, moleculeId, cjson, provenanceType=None,
provenanceId=None, public=False):
geometry = {
'moleculeId': moleculeId,
'cjson': cjson
}
if provenanceType is not None:
geometry['provenanceType'] = provenanceType
if provenanceId is not None:
geometry['provenanceId'] = provenanceId
self.setUserAccess(geometry, user=user, level=AccessType.ADMIN)
if public:
self.setPublic(geometry, True)
return self.save(geometry)
def find_geometries(self, moleculeId, user=None):
query = {
'moleculeId': ObjectId(moleculeId)
}
return self.findWithPermissions(query, user=user)
## Instruction:
Save creatorId as well for geometries
This is to keep track of the creator, even when the provenance
is not the user.
Signed-off-by: Patrick Avery <[email protected]>
## Code After:
from bson.objectid import ObjectId
from girder.models.model_base import AccessControlledModel
from girder.constants import AccessType
from .molecule import Molecule as MoleculeModel
class Geometry(AccessControlledModel):
def __init__(self):
super(Geometry, self).__init__()
def initialize(self):
self.name = 'geometry'
self.ensureIndex('moleculeId')
self.exposeFields(level=AccessType.READ, fields=(
'_id', 'moleculeId', 'cjson', 'provenanceType', 'provenanceId'))
def validate(self, doc):
# If we have a moleculeId ensure it is valid.
if 'moleculeId' in doc:
mol = MoleculeModel().load(doc['moleculeId'], force=True)
doc['moleculeId'] = mol['_id']
return doc
def create(self, user, moleculeId, cjson, provenanceType=None,
provenanceId=None, public=False):
geometry = {
'moleculeId': moleculeId,
'cjson': cjson,
'creatorId': user['_id']
}
if provenanceType is not None:
geometry['provenanceType'] = provenanceType
if provenanceId is not None:
geometry['provenanceId'] = provenanceId
self.setUserAccess(geometry, user=user, level=AccessType.ADMIN)
if public:
self.setPublic(geometry, True)
return self.save(geometry)
def find_geometries(self, moleculeId, user=None):
query = {
'moleculeId': ObjectId(moleculeId)
}
return self.findWithPermissions(query, user=user)
|
# ... existing code ...
provenanceId=None, public=False):
geometry = {
'moleculeId': moleculeId,
'cjson': cjson,
'creatorId': user['_id']
}
if provenanceType is not None:
# ... rest of the code ...
|
9534a6450178795f36599fab1d4c9969eeed7c63
|
lang-fluid/src/main/java/com/cedricziel/idea/fluid/codeInsight/ControllerLineMarkerProvider.java
|
lang-fluid/src/main/java/com/cedricziel/idea/fluid/codeInsight/ControllerLineMarkerProvider.java
|
package com.cedricziel.idea.fluid.codeInsight;
import com.cedricziel.idea.fluid.lang.psi.FluidFile;
import com.cedricziel.idea.fluid.util.FluidUtil;
import com.intellij.codeInsight.daemon.RelatedItemLineMarkerInfo;
import com.intellij.codeInsight.daemon.RelatedItemLineMarkerProvider;
import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.lang.psi.elements.Method;
import icons.FluidIcons;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
public class ControllerLineMarkerProvider extends RelatedItemLineMarkerProvider {
@Override
protected void collectNavigationMarkers(@NotNull PsiElement element, @NotNull Collection<? super RelatedItemLineMarkerInfo> result) {
if (!PlatformPatterns.psiElement(Method.class).withName(PlatformPatterns.string().endsWith("Action")).accepts(element)) {
return;
}
Collection<FluidFile> possibleMatchedTemplates = FluidUtil.findTemplatesForControllerAction((Method) element);
if (possibleMatchedTemplates.size() > 0) {
result.add(
NavigationGutterIconBuilder
.create(FluidIcons.TEMPLATE_LINE_MARKER)
.setTargets(possibleMatchedTemplates)
.setTooltipText("Navigate to template")
.createLineMarkerInfo(element)
);
}
}
}
|
package com.cedricziel.idea.fluid.codeInsight;
import com.cedricziel.idea.fluid.lang.psi.FluidFile;
import com.cedricziel.idea.fluid.util.FluidUtil;
import com.intellij.codeInsight.daemon.RelatedItemLineMarkerInfo;
import com.intellij.codeInsight.daemon.RelatedItemLineMarkerProvider;
import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.lang.lexer.PhpTokenTypes;
import com.jetbrains.php.lang.psi.elements.Method;
import icons.FluidIcons;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
public class ControllerLineMarkerProvider extends RelatedItemLineMarkerProvider {
@Override
protected void collectNavigationMarkers(@NotNull PsiElement element, @NotNull Collection<? super RelatedItemLineMarkerInfo> result) {
if (!PlatformPatterns.psiElement(PhpTokenTypes.IDENTIFIER).withParent(PlatformPatterns.psiElement(Method.class).withName(PlatformPatterns.string().endsWith("Action"))).accepts(element)) {
return;
}
Collection<FluidFile> possibleMatchedTemplates = FluidUtil.findTemplatesForControllerAction((Method) element.getParent());
if (possibleMatchedTemplates.size() > 0) {
result.add(
NavigationGutterIconBuilder
.create(FluidIcons.TEMPLATE_LINE_MARKER)
.setTargets(possibleMatchedTemplates)
.setTooltipText("Navigate to template")
.createLineMarkerInfo(element)
);
}
}
}
|
Add lineMarker for template to identifier to prevent flickering
|
[Fluid] Add lineMarker for template to identifier to prevent flickering
|
Java
|
mit
|
cedricziel/idea-php-typo3-plugin,cedricziel/idea-php-typo3-plugin,cedricziel/idea-php-typo3-plugin,cedricziel/idea-php-typo3-plugin
|
java
|
## Code Before:
package com.cedricziel.idea.fluid.codeInsight;
import com.cedricziel.idea.fluid.lang.psi.FluidFile;
import com.cedricziel.idea.fluid.util.FluidUtil;
import com.intellij.codeInsight.daemon.RelatedItemLineMarkerInfo;
import com.intellij.codeInsight.daemon.RelatedItemLineMarkerProvider;
import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.lang.psi.elements.Method;
import icons.FluidIcons;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
public class ControllerLineMarkerProvider extends RelatedItemLineMarkerProvider {
@Override
protected void collectNavigationMarkers(@NotNull PsiElement element, @NotNull Collection<? super RelatedItemLineMarkerInfo> result) {
if (!PlatformPatterns.psiElement(Method.class).withName(PlatformPatterns.string().endsWith("Action")).accepts(element)) {
return;
}
Collection<FluidFile> possibleMatchedTemplates = FluidUtil.findTemplatesForControllerAction((Method) element);
if (possibleMatchedTemplates.size() > 0) {
result.add(
NavigationGutterIconBuilder
.create(FluidIcons.TEMPLATE_LINE_MARKER)
.setTargets(possibleMatchedTemplates)
.setTooltipText("Navigate to template")
.createLineMarkerInfo(element)
);
}
}
}
## Instruction:
[Fluid] Add lineMarker for template to identifier to prevent flickering
## Code After:
package com.cedricziel.idea.fluid.codeInsight;
import com.cedricziel.idea.fluid.lang.psi.FluidFile;
import com.cedricziel.idea.fluid.util.FluidUtil;
import com.intellij.codeInsight.daemon.RelatedItemLineMarkerInfo;
import com.intellij.codeInsight.daemon.RelatedItemLineMarkerProvider;
import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.lang.lexer.PhpTokenTypes;
import com.jetbrains.php.lang.psi.elements.Method;
import icons.FluidIcons;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
public class ControllerLineMarkerProvider extends RelatedItemLineMarkerProvider {
@Override
protected void collectNavigationMarkers(@NotNull PsiElement element, @NotNull Collection<? super RelatedItemLineMarkerInfo> result) {
if (!PlatformPatterns.psiElement(PhpTokenTypes.IDENTIFIER).withParent(PlatformPatterns.psiElement(Method.class).withName(PlatformPatterns.string().endsWith("Action"))).accepts(element)) {
return;
}
Collection<FluidFile> possibleMatchedTemplates = FluidUtil.findTemplatesForControllerAction((Method) element.getParent());
if (possibleMatchedTemplates.size() > 0) {
result.add(
NavigationGutterIconBuilder
.create(FluidIcons.TEMPLATE_LINE_MARKER)
.setTargets(possibleMatchedTemplates)
.setTooltipText("Navigate to template")
.createLineMarkerInfo(element)
);
}
}
}
|
// ... existing code ...
import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.lang.lexer.PhpTokenTypes;
import com.jetbrains.php.lang.psi.elements.Method;
import icons.FluidIcons;
import org.jetbrains.annotations.NotNull;
// ... modified code ...
public class ControllerLineMarkerProvider extends RelatedItemLineMarkerProvider {
@Override
protected void collectNavigationMarkers(@NotNull PsiElement element, @NotNull Collection<? super RelatedItemLineMarkerInfo> result) {
if (!PlatformPatterns.psiElement(PhpTokenTypes.IDENTIFIER).withParent(PlatformPatterns.psiElement(Method.class).withName(PlatformPatterns.string().endsWith("Action"))).accepts(element)) {
return;
}
Collection<FluidFile> possibleMatchedTemplates = FluidUtil.findTemplatesForControllerAction((Method) element.getParent());
if (possibleMatchedTemplates.size() > 0) {
result.add(
NavigationGutterIconBuilder
// ... rest of the code ...
|
671d42de2cefd2001e1cb800023d48cf93bc4b39
|
app/src/org/commcare/utils/AndroidArrayDataSource.java
|
app/src/org/commcare/utils/AndroidArrayDataSource.java
|
package org.commcare.utils;
import android.content.Context;
import org.commcare.util.ArrayDataSource;
/**
* ArrayDataSource that uses the Android 'values' resources
*/
public class AndroidArrayDataSource implements ArrayDataSource {
private Context context;
public AndroidArrayDataSource(Context context){
this.context = context;
}
@Override
public String[] getArray(String key) {
int resourceId = context.getResources().getIdentifier(key, "array", context.getPackageName());
return context.getResources().getStringArray(resourceId);
}
}
|
package org.commcare.utils;
import android.content.Context;
import org.commcare.util.ArrayDataSource;
/**
* ArrayDataSource that uses the Android 'values' resources
*/
public class AndroidArrayDataSource implements ArrayDataSource {
private Context context;
public AndroidArrayDataSource(Context context){
this.context = context;
}
@Override
public String[] getArray(String key) {
int resourceId = context.getResources().getIdentifier(key, "array", context.getPackageName());
if (resourceId == 0) {
throw new RuntimeException("Localized array data for '" + key + "' not found");
}
return context.getResources().getStringArray(resourceId);
}
}
|
Add error handling for missing resource
|
Add error handling for missing resource
|
Java
|
apache-2.0
|
dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android
|
java
|
## Code Before:
package org.commcare.utils;
import android.content.Context;
import org.commcare.util.ArrayDataSource;
/**
* ArrayDataSource that uses the Android 'values' resources
*/
public class AndroidArrayDataSource implements ArrayDataSource {
private Context context;
public AndroidArrayDataSource(Context context){
this.context = context;
}
@Override
public String[] getArray(String key) {
int resourceId = context.getResources().getIdentifier(key, "array", context.getPackageName());
return context.getResources().getStringArray(resourceId);
}
}
## Instruction:
Add error handling for missing resource
## Code After:
package org.commcare.utils;
import android.content.Context;
import org.commcare.util.ArrayDataSource;
/**
* ArrayDataSource that uses the Android 'values' resources
*/
public class AndroidArrayDataSource implements ArrayDataSource {
private Context context;
public AndroidArrayDataSource(Context context){
this.context = context;
}
@Override
public String[] getArray(String key) {
int resourceId = context.getResources().getIdentifier(key, "array", context.getPackageName());
if (resourceId == 0) {
throw new RuntimeException("Localized array data for '" + key + "' not found");
}
return context.getResources().getStringArray(resourceId);
}
}
|
# ... existing code ...
@Override
public String[] getArray(String key) {
int resourceId = context.getResources().getIdentifier(key, "array", context.getPackageName());
if (resourceId == 0) {
throw new RuntimeException("Localized array data for '" + key + "' not found");
}
return context.getResources().getStringArray(resourceId);
}
}
# ... rest of the code ...
|
a8bc6034fc79b86e5724ad890897119886340f47
|
languages/Natlab/src/natlab/Interpreter.java
|
languages/Natlab/src/natlab/Interpreter.java
|
package natlab;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import beaver.Parser;
import natlab.ast.Root;
public class Interpreter {
private Interpreter() {}
public static void main(String[] args) throws IOException {
System.out.println("Welcome to the Natlab Interpreter!");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while(true) {
System.out.print("> ");
System.out.flush();
String line = in.readLine();
if(line == null) {
break;
}
try {
NatlabScanner scanner = new NatlabScanner(new StringReader(line));
NatlabParser parser = new NatlabParser();
Root original = (Root) parser.parse(scanner);
if(parser.hasError()) {
System.out.println("**ERROR**");
for(String error : parser.getErrors()) {
System.out.println(error);
}
} else {
System.out.println(original.getStructureString());
}
} catch(Parser.Exception e) {
System.out.println("**ERROR**");
System.out.println(e.getMessage());
}
}
System.out.println("Goodbye!");
}
}
|
package natlab;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import natlab.ast.Root;
import beaver.Parser;
public class Interpreter {
private Interpreter() {}
public static void main(String[] args) throws IOException {
System.out.println("Welcome to the Natlab Interpreter!");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while(true) {
System.out.print("> ");
System.out.flush();
String line = in.readLine();
if(line == null) {
break;
}
NatlabParser parser = new NatlabParser();
try {
NatlabScanner scanner = new NatlabScanner(new StringReader(line));
Root original = (Root) parser.parse(scanner);
if(parser.hasError()) {
System.out.println("**ERROR**");
for(String error : parser.getErrors()) {
System.out.println(error);
}
} else {
System.out.println(original.getStructureString());
}
} catch(Parser.Exception e) {
System.out.println("**ERROR**");
System.out.println(e.getMessage());
for(String error : parser.getErrors()) {
System.out.println(error);
}
}
}
System.out.println("Goodbye!");
}
}
|
Print error list in exception case.
|
Print error list in exception case.
git-svn-id: https://svn.sable.mcgill.ca/mclab/Project@70 89b902b4-d83f-0410-b942-89f7a419ffdb
Migrated from Sable/mclab@9a207c32906b6562aa0561a839effebf28d29b0b
|
Java
|
apache-2.0
|
Sable/mclab-core,Sable/mclab-core,Sable/mclab-core,Sable/mclab-core,Sable/mclab-core,Sable/mclab-core,Sable/mclab-core,Sable/mclab-core
|
java
|
## Code Before:
package natlab;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import beaver.Parser;
import natlab.ast.Root;
public class Interpreter {
private Interpreter() {}
public static void main(String[] args) throws IOException {
System.out.println("Welcome to the Natlab Interpreter!");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while(true) {
System.out.print("> ");
System.out.flush();
String line = in.readLine();
if(line == null) {
break;
}
try {
NatlabScanner scanner = new NatlabScanner(new StringReader(line));
NatlabParser parser = new NatlabParser();
Root original = (Root) parser.parse(scanner);
if(parser.hasError()) {
System.out.println("**ERROR**");
for(String error : parser.getErrors()) {
System.out.println(error);
}
} else {
System.out.println(original.getStructureString());
}
} catch(Parser.Exception e) {
System.out.println("**ERROR**");
System.out.println(e.getMessage());
}
}
System.out.println("Goodbye!");
}
}
## Instruction:
Print error list in exception case.
git-svn-id: https://svn.sable.mcgill.ca/mclab/Project@70 89b902b4-d83f-0410-b942-89f7a419ffdb
Migrated from Sable/mclab@9a207c32906b6562aa0561a839effebf28d29b0b
## Code After:
package natlab;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import natlab.ast.Root;
import beaver.Parser;
public class Interpreter {
private Interpreter() {}
public static void main(String[] args) throws IOException {
System.out.println("Welcome to the Natlab Interpreter!");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while(true) {
System.out.print("> ");
System.out.flush();
String line = in.readLine();
if(line == null) {
break;
}
NatlabParser parser = new NatlabParser();
try {
NatlabScanner scanner = new NatlabScanner(new StringReader(line));
Root original = (Root) parser.parse(scanner);
if(parser.hasError()) {
System.out.println("**ERROR**");
for(String error : parser.getErrors()) {
System.out.println(error);
}
} else {
System.out.println(original.getStructureString());
}
} catch(Parser.Exception e) {
System.out.println("**ERROR**");
System.out.println(e.getMessage());
for(String error : parser.getErrors()) {
System.out.println(error);
}
}
}
System.out.println("Goodbye!");
}
}
|
# ... existing code ...
import java.io.InputStreamReader;
import java.io.StringReader;
import natlab.ast.Root;
import beaver.Parser;
public class Interpreter {
private Interpreter() {}
# ... modified code ...
break;
}
NatlabParser parser = new NatlabParser();
try {
NatlabScanner scanner = new NatlabScanner(new StringReader(line));
Root original = (Root) parser.parse(scanner);
if(parser.hasError()) {
System.out.println("**ERROR**");
for(String error : parser.getErrors()) {
...
} catch(Parser.Exception e) {
System.out.println("**ERROR**");
System.out.println(e.getMessage());
for(String error : parser.getErrors()) {
System.out.println(error);
}
}
}
System.out.println("Goodbye!");
# ... rest of the code ...
|
b7c967ad0f45cc1144a8713c6513bae5bca89242
|
LiSE/LiSE/test_proxy.py
|
LiSE/LiSE/test_proxy.py
|
from LiSE.proxy import EngineProcessManager
import allegedb.test
class ProxyTest(allegedb.test.AllegedTest):
def setUp(self):
self.manager = EngineProcessManager()
self.engine = self.manager.start('sqlite:///:memory:')
self.graphmakers = (self.engine.new_character,)
def tearDown(self):
self.manager.shutdown()
class ProxyGraphTest(allegedb.test.AbstractGraphTest, ProxyTest):
pass
class BranchLineageTest(ProxyGraphTest, allegedb.test.AbstractBranchLineageTest):
pass
class DictStorageTest(ProxyTest, allegedb.test.DictStorageTest):
pass
class ListStorageTest(ProxyTest, allegedb.test.ListStorageTest):
pass
class SetStorageTest(ProxyTest, allegedb.test.SetStorageTest):
pass
|
from LiSE.proxy import EngineProcessManager
import allegedb.test
class ProxyTest(allegedb.test.AllegedTest):
def setUp(self):
self.manager = EngineProcessManager()
self.engine = self.manager.start('sqlite:///:memory:')
self.graphmakers = (self.engine.new_character,)
def tearDown(self):
self.manager.shutdown()
class ProxyGraphTest(allegedb.test.AbstractGraphTest, ProxyTest):
pass
class DictStorageTest(ProxyTest, allegedb.test.DictStorageTest):
pass
class ListStorageTest(ProxyTest, allegedb.test.ListStorageTest):
pass
class SetStorageTest(ProxyTest, allegedb.test.SetStorageTest):
pass
|
Delete BranchLineageTest, which assumes bidirectional graphs exist
|
Delete BranchLineageTest, which assumes bidirectional graphs exist
|
Python
|
agpl-3.0
|
LogicalDash/LiSE,LogicalDash/LiSE
|
python
|
## Code Before:
from LiSE.proxy import EngineProcessManager
import allegedb.test
class ProxyTest(allegedb.test.AllegedTest):
def setUp(self):
self.manager = EngineProcessManager()
self.engine = self.manager.start('sqlite:///:memory:')
self.graphmakers = (self.engine.new_character,)
def tearDown(self):
self.manager.shutdown()
class ProxyGraphTest(allegedb.test.AbstractGraphTest, ProxyTest):
pass
class BranchLineageTest(ProxyGraphTest, allegedb.test.AbstractBranchLineageTest):
pass
class DictStorageTest(ProxyTest, allegedb.test.DictStorageTest):
pass
class ListStorageTest(ProxyTest, allegedb.test.ListStorageTest):
pass
class SetStorageTest(ProxyTest, allegedb.test.SetStorageTest):
pass
## Instruction:
Delete BranchLineageTest, which assumes bidirectional graphs exist
## Code After:
from LiSE.proxy import EngineProcessManager
import allegedb.test
class ProxyTest(allegedb.test.AllegedTest):
def setUp(self):
self.manager = EngineProcessManager()
self.engine = self.manager.start('sqlite:///:memory:')
self.graphmakers = (self.engine.new_character,)
def tearDown(self):
self.manager.shutdown()
class ProxyGraphTest(allegedb.test.AbstractGraphTest, ProxyTest):
pass
class DictStorageTest(ProxyTest, allegedb.test.DictStorageTest):
pass
class ListStorageTest(ProxyTest, allegedb.test.ListStorageTest):
pass
class SetStorageTest(ProxyTest, allegedb.test.SetStorageTest):
pass
|
# ... existing code ...
pass
class DictStorageTest(ProxyTest, allegedb.test.DictStorageTest):
pass
# ... rest of the code ...
|
bc887c89df35f64f0a19ee5789f8ad811a7691a5
|
src/graphics/style.h
|
src/graphics/style.h
|
//
// Created by gravypod on 9/20/17.
//
#ifndef ENGINE_STYLE_H
#define ENGINE_STYLE_H
#include <duktape.h>
void make_style(const char const *name,
float width, float height,
const char const *vertex_name, const char const *fragment_name);
void draw_style(const char const *name, float x, float y);
__attribute__((unused)) static duk_ret_t native_make_style(duk_context *ctx)
{
const char const *name = duk_require_string(ctx, 0);
const float width = (float) duk_require_number(ctx, 1);
const float height = (float) duk_require_number(ctx, 2);
const char const *vertex_name = duk_require_string(ctx, 3);
const char const *fragment_name = duk_require_string(ctx, 4);
make_style(name, width, height, vertex_name, fragment_name);
return 0;
}
__attribute__((unused)) static duk_ret_t native_draw_style(duk_context *ctx)
{
const char const *name = duk_require_string(ctx, 0);
const float x = (float) duk_require_number(ctx, 1);
const float y = (float) duk_require_number(ctx, 2);
draw_style(name, x, y);
return 0;
}
#endif //ENGINE_STYLE_H
|
//
// Created by gravypod on 9/20/17.
//
#ifndef ENGINE_STYLE_H
#define ENGINE_STYLE_H
#include "lib/duktape/duktape.h"
void make_style(const char const *name,
float width, float height,
const char const *vertex_name, const char const *fragment_name);
void draw_style(const char const *name, float x, float y);
__attribute__((unused)) static duk_ret_t native_make_style(duk_context *ctx)
{
const char const *name = duk_require_string(ctx, 0);
const float width = (float) duk_require_number(ctx, 1);
const float height = (float) duk_require_number(ctx, 2);
const char const *vertex_name = duk_require_string(ctx, 3);
const char const *fragment_name = duk_require_string(ctx, 4);
make_style(name, width, height, vertex_name, fragment_name);
return 0;
}
__attribute__((unused)) static duk_ret_t native_draw_style(duk_context *ctx)
{
const char const *name = duk_require_string(ctx, 0);
const float x = (float) duk_require_number(ctx, 1);
const float y = (float) duk_require_number(ctx, 2);
draw_style(name, x, y);
return 0;
}
#endif //ENGINE_STYLE_H
|
Use local copy of duktape header.
|
Use local copy of duktape header.
|
C
|
mit
|
gravypod/solid-snake,gravypod/solid-snake,gravypod/solid-snake
|
c
|
## Code Before:
//
// Created by gravypod on 9/20/17.
//
#ifndef ENGINE_STYLE_H
#define ENGINE_STYLE_H
#include <duktape.h>
void make_style(const char const *name,
float width, float height,
const char const *vertex_name, const char const *fragment_name);
void draw_style(const char const *name, float x, float y);
__attribute__((unused)) static duk_ret_t native_make_style(duk_context *ctx)
{
const char const *name = duk_require_string(ctx, 0);
const float width = (float) duk_require_number(ctx, 1);
const float height = (float) duk_require_number(ctx, 2);
const char const *vertex_name = duk_require_string(ctx, 3);
const char const *fragment_name = duk_require_string(ctx, 4);
make_style(name, width, height, vertex_name, fragment_name);
return 0;
}
__attribute__((unused)) static duk_ret_t native_draw_style(duk_context *ctx)
{
const char const *name = duk_require_string(ctx, 0);
const float x = (float) duk_require_number(ctx, 1);
const float y = (float) duk_require_number(ctx, 2);
draw_style(name, x, y);
return 0;
}
#endif //ENGINE_STYLE_H
## Instruction:
Use local copy of duktape header.
## Code After:
//
// Created by gravypod on 9/20/17.
//
#ifndef ENGINE_STYLE_H
#define ENGINE_STYLE_H
#include "lib/duktape/duktape.h"
void make_style(const char const *name,
float width, float height,
const char const *vertex_name, const char const *fragment_name);
void draw_style(const char const *name, float x, float y);
__attribute__((unused)) static duk_ret_t native_make_style(duk_context *ctx)
{
const char const *name = duk_require_string(ctx, 0);
const float width = (float) duk_require_number(ctx, 1);
const float height = (float) duk_require_number(ctx, 2);
const char const *vertex_name = duk_require_string(ctx, 3);
const char const *fragment_name = duk_require_string(ctx, 4);
make_style(name, width, height, vertex_name, fragment_name);
return 0;
}
__attribute__((unused)) static duk_ret_t native_draw_style(duk_context *ctx)
{
const char const *name = duk_require_string(ctx, 0);
const float x = (float) duk_require_number(ctx, 1);
const float y = (float) duk_require_number(ctx, 2);
draw_style(name, x, y);
return 0;
}
#endif //ENGINE_STYLE_H
|
...
#ifndef ENGINE_STYLE_H
#define ENGINE_STYLE_H
#include "lib/duktape/duktape.h"
void make_style(const char const *name,
float width, float height,
...
|
50cc2ba3353cdd27513999465e854d01823605a4
|
angr/knowledge_base.py
|
angr/knowledge_base.py
|
"""Representing the artifacts of a project."""
from .knowledge_plugins.plugin import default_plugins
class KnowledgeBase(object):
"""Represents a "model" of knowledge about an artifact.
Contains things like a CFG, data references, etc.
"""
def __init__(self, project, obj):
self._project = project
self.obj = obj
self._plugins = {}
@property
def callgraph(self):
return self.functions.callgraph
@property
def unresolved_indirect_jumps(self):
return self.indirect_jumps.unresolved
@property
def resolved_indirect_jumps(self):
return self.indirect_jumps.resolved
#
# Plugin accessor
#
def __contains__(self, plugin_name):
return plugin_name in self._plugins
def __getattr__(self, v):
try:
return self.get_plugin(v)
except KeyError:
raise AttributeError(v)
#
# Plugins
#
def has_plugin(self, name):
return name in self._plugins
def get_plugin(self, name):
if name not in self._plugins:
p = default_plugins[name](self)
self.register_plugin(name, p)
return p
return self._plugins[name]
def register_plugin(self, name, plugin):
self._plugins[name] = plugin
return plugin
def release_plugin(self, name):
if name in self._plugins:
del self._plugins[name]
|
"""Representing the artifacts of a project."""
from .knowledge_plugins.plugin import default_plugins
class KnowledgeBase(object):
"""Represents a "model" of knowledge about an artifact.
Contains things like a CFG, data references, etc.
"""
def __init__(self, project, obj):
self._project = project
self.obj = obj
self._plugins = {}
@property
def callgraph(self):
return self.functions.callgraph
@property
def unresolved_indirect_jumps(self):
return self.indirect_jumps.unresolved
@property
def resolved_indirect_jumps(self):
return self.indirect_jumps.resolved
def __setstate__(self, state):
self._project = state['project']
self.obj = state['obj']
self._plugins = state['plugins']
def __getstate__(self):
s = {
'project': self._project,
'obj': self.obj,
'plugins': self._plugins,
}
return s
#
# Plugin accessor
#
def __contains__(self, plugin_name):
return plugin_name in self._plugins
def __getattr__(self, v):
try:
return self.get_plugin(v)
except KeyError:
raise AttributeError(v)
#
# Plugins
#
def has_plugin(self, name):
return name in self._plugins
def get_plugin(self, name):
if name not in self._plugins:
p = default_plugins[name](self)
self.register_plugin(name, p)
return p
return self._plugins[name]
def register_plugin(self, name, plugin):
self._plugins[name] = plugin
return plugin
def release_plugin(self, name):
if name in self._plugins:
del self._plugins[name]
|
Fix the recursion bug in KnowledgeBase after the previous refactor.
|
Fix the recursion bug in KnowledgeBase after the previous refactor.
|
Python
|
bsd-2-clause
|
f-prettyland/angr,axt/angr,tyb0807/angr,iamahuman/angr,angr/angr,angr/angr,axt/angr,angr/angr,chubbymaggie/angr,schieb/angr,chubbymaggie/angr,f-prettyland/angr,iamahuman/angr,f-prettyland/angr,tyb0807/angr,iamahuman/angr,axt/angr,schieb/angr,chubbymaggie/angr,schieb/angr,tyb0807/angr
|
python
|
## Code Before:
"""Representing the artifacts of a project."""
from .knowledge_plugins.plugin import default_plugins
class KnowledgeBase(object):
"""Represents a "model" of knowledge about an artifact.
Contains things like a CFG, data references, etc.
"""
def __init__(self, project, obj):
self._project = project
self.obj = obj
self._plugins = {}
@property
def callgraph(self):
return self.functions.callgraph
@property
def unresolved_indirect_jumps(self):
return self.indirect_jumps.unresolved
@property
def resolved_indirect_jumps(self):
return self.indirect_jumps.resolved
#
# Plugin accessor
#
def __contains__(self, plugin_name):
return plugin_name in self._plugins
def __getattr__(self, v):
try:
return self.get_plugin(v)
except KeyError:
raise AttributeError(v)
#
# Plugins
#
def has_plugin(self, name):
return name in self._plugins
def get_plugin(self, name):
if name not in self._plugins:
p = default_plugins[name](self)
self.register_plugin(name, p)
return p
return self._plugins[name]
def register_plugin(self, name, plugin):
self._plugins[name] = plugin
return plugin
def release_plugin(self, name):
if name in self._plugins:
del self._plugins[name]
## Instruction:
Fix the recursion bug in KnowledgeBase after the previous refactor.
## Code After:
"""Representing the artifacts of a project."""
from .knowledge_plugins.plugin import default_plugins
class KnowledgeBase(object):
"""Represents a "model" of knowledge about an artifact.
Contains things like a CFG, data references, etc.
"""
def __init__(self, project, obj):
self._project = project
self.obj = obj
self._plugins = {}
@property
def callgraph(self):
return self.functions.callgraph
@property
def unresolved_indirect_jumps(self):
return self.indirect_jumps.unresolved
@property
def resolved_indirect_jumps(self):
return self.indirect_jumps.resolved
def __setstate__(self, state):
self._project = state['project']
self.obj = state['obj']
self._plugins = state['plugins']
def __getstate__(self):
s = {
'project': self._project,
'obj': self.obj,
'plugins': self._plugins,
}
return s
#
# Plugin accessor
#
def __contains__(self, plugin_name):
return plugin_name in self._plugins
def __getattr__(self, v):
try:
return self.get_plugin(v)
except KeyError:
raise AttributeError(v)
#
# Plugins
#
def has_plugin(self, name):
return name in self._plugins
def get_plugin(self, name):
if name not in self._plugins:
p = default_plugins[name](self)
self.register_plugin(name, p)
return p
return self._plugins[name]
def register_plugin(self, name, plugin):
self._plugins[name] = plugin
return plugin
def release_plugin(self, name):
if name in self._plugins:
del self._plugins[name]
|
# ... existing code ...
@property
def resolved_indirect_jumps(self):
return self.indirect_jumps.resolved
def __setstate__(self, state):
self._project = state['project']
self.obj = state['obj']
self._plugins = state['plugins']
def __getstate__(self):
s = {
'project': self._project,
'obj': self.obj,
'plugins': self._plugins,
}
return s
#
# Plugin accessor
# ... rest of the code ...
|
871974c1be09b831cab6fd206f89b7a5e6bdab03
|
MagicAPI/src/main/java/com/elmakers/mine/bukkit/api/event/CastEvent.java
|
MagicAPI/src/main/java/com/elmakers/mine/bukkit/api/event/CastEvent.java
|
package com.elmakers.mine.bukkit.api.event;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.spell.Spell;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
/**
* A custom event that the Magic plugin will fire any time a
* Mage casts a Spell.
*/
public class CastEvent extends Event {
private final CastContext context;
private static final HandlerList handlers = new HandlerList();
public CastEvent(CastContext context) {
this.context = context;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
public Mage getMage() {
return context.getMage();
}
public Spell getSpell() {
return context.getSpell();
}
public CastContext getContext() {
return context;
}
public SpellResult getSpellResult() {
return context.getResult();
}
}
|
package com.elmakers.mine.bukkit.api.event;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.spell.Spell;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
/**
* A custom event that the Magic plugin will fire any time a
* Mage casts a Spell.
*/
public class CastEvent extends Event {
private final CastContext context;
private static final HandlerList handlers = new HandlerList();
public CastEvent(Mage mage, Spell spell, SpellResult result) {
throw new IllegalArgumentException("Please create a CastEvent with CastContext now .. but also why are you creating a CastEvent?");
}
public CastEvent(CastContext context) {
this.context = context;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
public Mage getMage() {
return context.getMage();
}
public Spell getSpell() {
return context.getSpell();
}
public CastContext getContext() {
return context;
}
public SpellResult getSpellResult() {
return context.getResult();
}
}
|
Add back in previous constructor to make revapi happy, but no one should really be creating these anyway
|
Add back in previous constructor to make revapi happy, but no one should really be creating these anyway
|
Java
|
mit
|
elBukkit/MagicPlugin,elBukkit/MagicPlugin,elBukkit/MagicPlugin
|
java
|
## Code Before:
package com.elmakers.mine.bukkit.api.event;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.spell.Spell;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
/**
* A custom event that the Magic plugin will fire any time a
* Mage casts a Spell.
*/
public class CastEvent extends Event {
private final CastContext context;
private static final HandlerList handlers = new HandlerList();
public CastEvent(CastContext context) {
this.context = context;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
public Mage getMage() {
return context.getMage();
}
public Spell getSpell() {
return context.getSpell();
}
public CastContext getContext() {
return context;
}
public SpellResult getSpellResult() {
return context.getResult();
}
}
## Instruction:
Add back in previous constructor to make revapi happy, but no one should really be creating these anyway
## Code After:
package com.elmakers.mine.bukkit.api.event;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.spell.Spell;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
/**
* A custom event that the Magic plugin will fire any time a
* Mage casts a Spell.
*/
public class CastEvent extends Event {
private final CastContext context;
private static final HandlerList handlers = new HandlerList();
public CastEvent(Mage mage, Spell spell, SpellResult result) {
throw new IllegalArgumentException("Please create a CastEvent with CastContext now .. but also why are you creating a CastEvent?");
}
public CastEvent(CastContext context) {
this.context = context;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
public Mage getMage() {
return context.getMage();
}
public Spell getSpell() {
return context.getSpell();
}
public CastContext getContext() {
return context;
}
public SpellResult getSpellResult() {
return context.getResult();
}
}
|
...
private final CastContext context;
private static final HandlerList handlers = new HandlerList();
public CastEvent(Mage mage, Spell spell, SpellResult result) {
throw new IllegalArgumentException("Please create a CastEvent with CastContext now .. but also why are you creating a CastEvent?");
}
public CastEvent(CastContext context) {
this.context = context;
...
|
b7377196cdd05d9d6d481f7b93308189c4524c52
|
sfm/api/filters.py
|
sfm/api/filters.py
|
from django_filters import FilterSet, CharFilter, IsoDateTimeFilter
from ui.models import Warc, Seed, Harvest
from django_filters import Filter
from django_filters.fields import Lookup
class ListFilter(Filter):
def filter(self, qs, value):
return super(ListFilter, self).filter(qs, Lookup(value.split(u","), "in"))
class WarcFilter(FilterSet):
# Allows queries like /api/v1/warcs/?seedset=39c00280274a4db0b1cb5bfa4d527a1e
seedset = CharFilter(name="harvest__seed_set__seedset_id")
seed = ListFilter(name="harvest__seed_set__seeds__seed_id", distinct=True)
# TODO: This will need to be changed to use historical seeds once #54 is completed.
harvest_date_start = IsoDateTimeFilter(name="harvest__date_started", lookup_type='gte')
harvest_date_end = IsoDateTimeFilter(name="harvest__date_started", lookup_type='lte')
class Meta:
model = Warc
fields = ['seedset']
|
from django_filters import FilterSet, CharFilter, IsoDateTimeFilter
from ui.models import Warc, Seed, Harvest
from django_filters import Filter
from django_filters.fields import Lookup
class ListFilter(Filter):
def filter(self, qs, value):
return super(ListFilter, self).filter(qs, Lookup(value.split(u","), "in"))
class WarcFilter(FilterSet):
# Allows queries like /api/v1/warcs/?seedset=39c00280274a4db0b1cb5bfa4d527a1e
seedset = CharFilter(name="harvest__historical_seed_set__seedset_id")
seed = ListFilter(name="harvest__historical_seeds__seed_id", distinct=True)
harvest_date_start = IsoDateTimeFilter(name="harvest__date_started", lookup_type='gte')
harvest_date_end = IsoDateTimeFilter(name="harvest__date_started", lookup_type='lte')
class Meta:
model = Warc
fields = ['seedset']
|
Fix to take into account history in API queries.
|
Fix to take into account history in API queries.
|
Python
|
mit
|
gwu-libraries/sfm,gwu-libraries/sfm-ui,gwu-libraries/sfm,gwu-libraries/sfm,gwu-libraries/sfm-ui,gwu-libraries/sfm-ui,gwu-libraries/sfm-ui
|
python
|
## Code Before:
from django_filters import FilterSet, CharFilter, IsoDateTimeFilter
from ui.models import Warc, Seed, Harvest
from django_filters import Filter
from django_filters.fields import Lookup
class ListFilter(Filter):
def filter(self, qs, value):
return super(ListFilter, self).filter(qs, Lookup(value.split(u","), "in"))
class WarcFilter(FilterSet):
# Allows queries like /api/v1/warcs/?seedset=39c00280274a4db0b1cb5bfa4d527a1e
seedset = CharFilter(name="harvest__seed_set__seedset_id")
seed = ListFilter(name="harvest__seed_set__seeds__seed_id", distinct=True)
# TODO: This will need to be changed to use historical seeds once #54 is completed.
harvest_date_start = IsoDateTimeFilter(name="harvest__date_started", lookup_type='gte')
harvest_date_end = IsoDateTimeFilter(name="harvest__date_started", lookup_type='lte')
class Meta:
model = Warc
fields = ['seedset']
## Instruction:
Fix to take into account history in API queries.
## Code After:
from django_filters import FilterSet, CharFilter, IsoDateTimeFilter
from ui.models import Warc, Seed, Harvest
from django_filters import Filter
from django_filters.fields import Lookup
class ListFilter(Filter):
def filter(self, qs, value):
return super(ListFilter, self).filter(qs, Lookup(value.split(u","), "in"))
class WarcFilter(FilterSet):
# Allows queries like /api/v1/warcs/?seedset=39c00280274a4db0b1cb5bfa4d527a1e
seedset = CharFilter(name="harvest__historical_seed_set__seedset_id")
seed = ListFilter(name="harvest__historical_seeds__seed_id", distinct=True)
harvest_date_start = IsoDateTimeFilter(name="harvest__date_started", lookup_type='gte')
harvest_date_end = IsoDateTimeFilter(name="harvest__date_started", lookup_type='lte')
class Meta:
model = Warc
fields = ['seedset']
|
...
class WarcFilter(FilterSet):
# Allows queries like /api/v1/warcs/?seedset=39c00280274a4db0b1cb5bfa4d527a1e
seedset = CharFilter(name="harvest__historical_seed_set__seedset_id")
seed = ListFilter(name="harvest__historical_seeds__seed_id", distinct=True)
harvest_date_start = IsoDateTimeFilter(name="harvest__date_started", lookup_type='gte')
harvest_date_end = IsoDateTimeFilter(name="harvest__date_started", lookup_type='lte')
...
|
bb4bff73a1eefad6188f1d1544f3b4106b606d36
|
driller/LibcSimProc.py
|
driller/LibcSimProc.py
|
import simuvex
from simuvex.s_type import SimTypeFd, SimTypeChar, SimTypeArray, SimTypeLength
class DrillerRead(simuvex.SimProcedure):
'''
A custom version of read which has a symbolic return value.
'''
def run(self, fd, dst, length):
self.argument_types = {0: SimTypeFd(),
1: self.ty_ptr(SimTypeArray(SimTypeChar(), length)),
2: SimTypeLength(self.state.arch)}
self.return_type = SimTypeLength(self.state.arch)
if self.state.se.max_int(length) == 0:
return self.state.se.BVV(0, self.state.arch.bits)
sym_length = self.state.se.BV("sym_length", self.state.arch.bits)
self.state.add_constraints(sym_length <= length)
self.state.add_constraints(sym_length >= 0)
_ = self.state.posix.pos(fd)
data = self.state.posix.read(fd, length)
self.state.store_mem(dst, data)
return sym_length
simprocedures = [("read", DrillerRead)]
|
import simuvex
from simuvex.s_type import SimTypeFd, SimTypeChar, SimTypeArray, SimTypeLength
class DrillerRead(simuvex.SimProcedure):
'''
A custom version of read which has a symbolic return value.
'''
def run(self, fd, dst, length):
self.argument_types = {0: SimTypeFd(),
1: self.ty_ptr(SimTypeArray(SimTypeChar(), length)),
2: SimTypeLength(self.state.arch)}
self.return_type = SimTypeLength(self.state.arch)
if self.state.se.max_int(length) == 0:
return self.state.se.BVV(0, self.state.arch.bits)
sym_length = self.state.se.BV("sym_length", self.state.arch.bits)
self.state.add_constraints(sym_length <= length)
self.state.add_constraints(sym_length >= 0)
data = self.state.posix.read(fd, length, dst_addr=dst)
return sym_length
simprocedures = [("read", DrillerRead)]
|
Update libc's DrillerRead to use the new posix read calling convention to support variable read
|
Update libc's DrillerRead to use the new posix read calling convention to support variable read
|
Python
|
bsd-2-clause
|
shellphish/driller
|
python
|
## Code Before:
import simuvex
from simuvex.s_type import SimTypeFd, SimTypeChar, SimTypeArray, SimTypeLength
class DrillerRead(simuvex.SimProcedure):
'''
A custom version of read which has a symbolic return value.
'''
def run(self, fd, dst, length):
self.argument_types = {0: SimTypeFd(),
1: self.ty_ptr(SimTypeArray(SimTypeChar(), length)),
2: SimTypeLength(self.state.arch)}
self.return_type = SimTypeLength(self.state.arch)
if self.state.se.max_int(length) == 0:
return self.state.se.BVV(0, self.state.arch.bits)
sym_length = self.state.se.BV("sym_length", self.state.arch.bits)
self.state.add_constraints(sym_length <= length)
self.state.add_constraints(sym_length >= 0)
_ = self.state.posix.pos(fd)
data = self.state.posix.read(fd, length)
self.state.store_mem(dst, data)
return sym_length
simprocedures = [("read", DrillerRead)]
## Instruction:
Update libc's DrillerRead to use the new posix read calling convention to support variable read
## Code After:
import simuvex
from simuvex.s_type import SimTypeFd, SimTypeChar, SimTypeArray, SimTypeLength
class DrillerRead(simuvex.SimProcedure):
'''
A custom version of read which has a symbolic return value.
'''
def run(self, fd, dst, length):
self.argument_types = {0: SimTypeFd(),
1: self.ty_ptr(SimTypeArray(SimTypeChar(), length)),
2: SimTypeLength(self.state.arch)}
self.return_type = SimTypeLength(self.state.arch)
if self.state.se.max_int(length) == 0:
return self.state.se.BVV(0, self.state.arch.bits)
sym_length = self.state.se.BV("sym_length", self.state.arch.bits)
self.state.add_constraints(sym_length <= length)
self.state.add_constraints(sym_length >= 0)
data = self.state.posix.read(fd, length, dst_addr=dst)
return sym_length
simprocedures = [("read", DrillerRead)]
|
# ... existing code ...
self.state.add_constraints(sym_length <= length)
self.state.add_constraints(sym_length >= 0)
data = self.state.posix.read(fd, length, dst_addr=dst)
return sym_length
simprocedures = [("read", DrillerRead)]
# ... rest of the code ...
|
df9fc4092153291551302534307daf9ef5bf8d35
|
lib_log/src/main/java/no/nordicsemi/android/logger/LoggerAppRunner.kt
|
lib_log/src/main/java/no/nordicsemi/android/logger/LoggerAppRunner.kt
|
package no.nordicsemi.android.logger
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.compose.ui.platform.AndroidUriHandler
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
private const val LOGGER_PACKAGE_NAME = "no.nordicsemi.android.log"
private const val LOGGER_LINK = "https://play.google.com/store/apps/details?id=no.nordicsemi.android.log"
class LoggerAppRunner @Inject constructor(
@ApplicationContext
private val context: Context
) {
fun runLogger() {
val packageManger = context.packageManager
val uriHandler = AndroidUriHandler(context)
val intent = packageManger.getLaunchIntentForPackage(LOGGER_PACKAGE_NAME)
if (intent != null) {
context.startActivity(intent)
} else {
uriHandler.openUri(LOGGER_LINK)
}
}
fun runLogger(uri: Uri?) {
val packageManger = context.packageManager
val intent = packageManger.getLaunchIntentForPackage(LOGGER_PACKAGE_NAME)
val targetUri = if (intent != null && uri != null) {
uri
} else {
Uri.parse(LOGGER_LINK)
}
val launchIntent = Intent(Intent.ACTION_VIEW, targetUri)
launchIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(launchIntent)
}
}
|
package no.nordicsemi.android.logger
import android.content.Context
import android.content.Intent
import android.net.Uri
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
private const val LOGGER_PACKAGE_NAME = "no.nordicsemi.android.log"
private const val LOGGER_LINK = "https://play.google.com/store/apps/details?id=no.nordicsemi.android.log"
class LoggerAppRunner @Inject constructor(
@ApplicationContext
private val context: Context
) {
fun runLogger() {
val packageManger = context.packageManager
val intent = packageManger.getLaunchIntentForPackage(LOGGER_PACKAGE_NAME)
if (intent != null) {
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(intent)
} else {
val launchIntent = Intent(Intent.ACTION_VIEW, Uri.parse(LOGGER_LINK))
launchIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(launchIntent)
}
}
fun runLogger(uri: Uri?) {
val packageManger = context.packageManager
val intent = packageManger.getLaunchIntentForPackage(LOGGER_PACKAGE_NAME)
val targetUri = if (intent != null && uri != null) {
uri
} else {
Uri.parse(LOGGER_LINK)
}
val launchIntent = Intent(Intent.ACTION_VIEW, targetUri)
launchIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(launchIntent)
}
}
|
Fix crash when open logger.
|
Fix crash when open logger.
|
Kotlin
|
bsd-3-clause
|
NordicSemiconductor/Android-nRF-Toolbox,NordicSemiconductor/Android-nRF-Toolbox,NordicSemiconductor/Android-nRF-Toolbox,NordicSemiconductor/Android-nRF-Toolbox
|
kotlin
|
## Code Before:
package no.nordicsemi.android.logger
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.compose.ui.platform.AndroidUriHandler
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
private const val LOGGER_PACKAGE_NAME = "no.nordicsemi.android.log"
private const val LOGGER_LINK = "https://play.google.com/store/apps/details?id=no.nordicsemi.android.log"
class LoggerAppRunner @Inject constructor(
@ApplicationContext
private val context: Context
) {
fun runLogger() {
val packageManger = context.packageManager
val uriHandler = AndroidUriHandler(context)
val intent = packageManger.getLaunchIntentForPackage(LOGGER_PACKAGE_NAME)
if (intent != null) {
context.startActivity(intent)
} else {
uriHandler.openUri(LOGGER_LINK)
}
}
fun runLogger(uri: Uri?) {
val packageManger = context.packageManager
val intent = packageManger.getLaunchIntentForPackage(LOGGER_PACKAGE_NAME)
val targetUri = if (intent != null && uri != null) {
uri
} else {
Uri.parse(LOGGER_LINK)
}
val launchIntent = Intent(Intent.ACTION_VIEW, targetUri)
launchIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(launchIntent)
}
}
## Instruction:
Fix crash when open logger.
## Code After:
package no.nordicsemi.android.logger
import android.content.Context
import android.content.Intent
import android.net.Uri
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
private const val LOGGER_PACKAGE_NAME = "no.nordicsemi.android.log"
private const val LOGGER_LINK = "https://play.google.com/store/apps/details?id=no.nordicsemi.android.log"
class LoggerAppRunner @Inject constructor(
@ApplicationContext
private val context: Context
) {
fun runLogger() {
val packageManger = context.packageManager
val intent = packageManger.getLaunchIntentForPackage(LOGGER_PACKAGE_NAME)
if (intent != null) {
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(intent)
} else {
val launchIntent = Intent(Intent.ACTION_VIEW, Uri.parse(LOGGER_LINK))
launchIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(launchIntent)
}
}
fun runLogger(uri: Uri?) {
val packageManger = context.packageManager
val intent = packageManger.getLaunchIntentForPackage(LOGGER_PACKAGE_NAME)
val targetUri = if (intent != null && uri != null) {
uri
} else {
Uri.parse(LOGGER_LINK)
}
val launchIntent = Intent(Intent.ACTION_VIEW, targetUri)
launchIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(launchIntent)
}
}
|
...
import android.content.Context
import android.content.Intent
import android.net.Uri
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
...
fun runLogger() {
val packageManger = context.packageManager
val intent = packageManger.getLaunchIntentForPackage(LOGGER_PACKAGE_NAME)
if (intent != null) {
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(intent)
} else {
val launchIntent = Intent(Intent.ACTION_VIEW, Uri.parse(LOGGER_LINK))
launchIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(launchIntent)
}
}
...
|
6edd4114c4e715a3a0c440af455fff089a099620
|
scrapy/squeues.py
|
scrapy/squeues.py
|
import marshal
from six.moves import cPickle as pickle
from queuelib import queue
def _serializable_queue(queue_class, serialize, deserialize):
class SerializableQueue(queue_class):
def push(self, obj):
s = serialize(obj)
super(SerializableQueue, self).push(s)
def pop(self):
s = super(SerializableQueue, self).pop()
if s:
return deserialize(s)
return SerializableQueue
def _pickle_serialize(obj):
try:
return pickle.dumps(obj, protocol=2)
# Python<=3.4 raises pickle.PicklingError here while
# Python>=3.5 raises AttributeError and
# Python>=3.6 raises TypeError
except (pickle.PicklingError, AttributeError, TypeError) as e:
raise ValueError(str(e))
PickleFifoDiskQueue = _serializable_queue(queue.FifoDiskQueue, \
_pickle_serialize, pickle.loads)
PickleLifoDiskQueue = _serializable_queue(queue.LifoDiskQueue, \
_pickle_serialize, pickle.loads)
MarshalFifoDiskQueue = _serializable_queue(queue.FifoDiskQueue, \
marshal.dumps, marshal.loads)
MarshalLifoDiskQueue = _serializable_queue(queue.LifoDiskQueue, \
marshal.dumps, marshal.loads)
FifoMemoryQueue = queue.FifoMemoryQueue
LifoMemoryQueue = queue.LifoMemoryQueue
|
import marshal
from six.moves import cPickle as pickle
from queuelib import queue
def _serializable_queue(queue_class, serialize, deserialize):
class SerializableQueue(queue_class):
def push(self, obj):
s = serialize(obj)
super(SerializableQueue, self).push(s)
def pop(self):
s = super(SerializableQueue, self).pop()
if s:
return deserialize(s)
return SerializableQueue
def _pickle_serialize(obj):
try:
return pickle.dumps(obj, protocol=2)
# Python <= 3.4 raises pickle.PicklingError here while
# 3.5 <= Python < 3.6 raises AttributeError and
# Python >= 3.6 raises TypeError
except (pickle.PicklingError, AttributeError, TypeError) as e:
raise ValueError(str(e))
PickleFifoDiskQueue = _serializable_queue(queue.FifoDiskQueue, \
_pickle_serialize, pickle.loads)
PickleLifoDiskQueue = _serializable_queue(queue.LifoDiskQueue, \
_pickle_serialize, pickle.loads)
MarshalFifoDiskQueue = _serializable_queue(queue.FifoDiskQueue, \
marshal.dumps, marshal.loads)
MarshalLifoDiskQueue = _serializable_queue(queue.LifoDiskQueue, \
marshal.dumps, marshal.loads)
FifoMemoryQueue = queue.FifoMemoryQueue
LifoMemoryQueue = queue.LifoMemoryQueue
|
Clarify comment about Pyhton versions
|
Clarify comment about Pyhton versions
|
Python
|
bsd-3-clause
|
pablohoffman/scrapy,pawelmhm/scrapy,finfish/scrapy,Ryezhang/scrapy,ssteo/scrapy,pawelmhm/scrapy,ssteo/scrapy,scrapy/scrapy,pawelmhm/scrapy,starrify/scrapy,ArturGaspar/scrapy,ssteo/scrapy,wujuguang/scrapy,dangra/scrapy,pablohoffman/scrapy,dangra/scrapy,elacuesta/scrapy,starrify/scrapy,scrapy/scrapy,kmike/scrapy,pablohoffman/scrapy,starrify/scrapy,finfish/scrapy,Ryezhang/scrapy,wujuguang/scrapy,elacuesta/scrapy,finfish/scrapy,eLRuLL/scrapy,ArturGaspar/scrapy,Ryezhang/scrapy,wujuguang/scrapy,eLRuLL/scrapy,eLRuLL/scrapy,dangra/scrapy,kmike/scrapy,elacuesta/scrapy,scrapy/scrapy,ArturGaspar/scrapy,kmike/scrapy
|
python
|
## Code Before:
import marshal
from six.moves import cPickle as pickle
from queuelib import queue
def _serializable_queue(queue_class, serialize, deserialize):
class SerializableQueue(queue_class):
def push(self, obj):
s = serialize(obj)
super(SerializableQueue, self).push(s)
def pop(self):
s = super(SerializableQueue, self).pop()
if s:
return deserialize(s)
return SerializableQueue
def _pickle_serialize(obj):
try:
return pickle.dumps(obj, protocol=2)
# Python<=3.4 raises pickle.PicklingError here while
# Python>=3.5 raises AttributeError and
# Python>=3.6 raises TypeError
except (pickle.PicklingError, AttributeError, TypeError) as e:
raise ValueError(str(e))
PickleFifoDiskQueue = _serializable_queue(queue.FifoDiskQueue, \
_pickle_serialize, pickle.loads)
PickleLifoDiskQueue = _serializable_queue(queue.LifoDiskQueue, \
_pickle_serialize, pickle.loads)
MarshalFifoDiskQueue = _serializable_queue(queue.FifoDiskQueue, \
marshal.dumps, marshal.loads)
MarshalLifoDiskQueue = _serializable_queue(queue.LifoDiskQueue, \
marshal.dumps, marshal.loads)
FifoMemoryQueue = queue.FifoMemoryQueue
LifoMemoryQueue = queue.LifoMemoryQueue
## Instruction:
Clarify comment about Pyhton versions
## Code After:
import marshal
from six.moves import cPickle as pickle
from queuelib import queue
def _serializable_queue(queue_class, serialize, deserialize):
class SerializableQueue(queue_class):
def push(self, obj):
s = serialize(obj)
super(SerializableQueue, self).push(s)
def pop(self):
s = super(SerializableQueue, self).pop()
if s:
return deserialize(s)
return SerializableQueue
def _pickle_serialize(obj):
try:
return pickle.dumps(obj, protocol=2)
# Python <= 3.4 raises pickle.PicklingError here while
# 3.5 <= Python < 3.6 raises AttributeError and
# Python >= 3.6 raises TypeError
except (pickle.PicklingError, AttributeError, TypeError) as e:
raise ValueError(str(e))
PickleFifoDiskQueue = _serializable_queue(queue.FifoDiskQueue, \
_pickle_serialize, pickle.loads)
PickleLifoDiskQueue = _serializable_queue(queue.LifoDiskQueue, \
_pickle_serialize, pickle.loads)
MarshalFifoDiskQueue = _serializable_queue(queue.FifoDiskQueue, \
marshal.dumps, marshal.loads)
MarshalLifoDiskQueue = _serializable_queue(queue.LifoDiskQueue, \
marshal.dumps, marshal.loads)
FifoMemoryQueue = queue.FifoMemoryQueue
LifoMemoryQueue = queue.LifoMemoryQueue
|
...
def _pickle_serialize(obj):
try:
return pickle.dumps(obj, protocol=2)
# Python <= 3.4 raises pickle.PicklingError here while
# 3.5 <= Python < 3.6 raises AttributeError and
# Python >= 3.6 raises TypeError
except (pickle.PicklingError, AttributeError, TypeError) as e:
raise ValueError(str(e))
...
|
60b5948508a67cb213ca04b5faacb77e27d8f84c
|
samples/forms.py
|
samples/forms.py
|
import datetime #for checking renewal date range.
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from .models import (Patient, AdmissionNote, FluVaccine,
CollectionType, CollectedSample,
Symptom, ObservedSymptom,
)
from fiocruz.settings.base import DATE_INPUT_FORMATS
class AdmissionNoteForm(forms.ModelForm):
class Meta:
model = AdmissionNote
fields = [
'id_gal_origin',
]
class PatientForm(forms.ModelForm):
class Meta:
model = Patient
fields = [
'name',
]
class FluVaccineForm(forms.ModelForm):
date_applied = forms.DateField(input_formats=DATE_INPUT_FORMATS)
class Meta:
model = FluVaccine
exclude = ['admission_note', ]
|
import datetime #for checking renewal date range.
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from .models import (Patient, AdmissionNote, FluVaccine,
CollectionType, CollectedSample,
Symptom, ObservedSymptom,
)
from fiocruz.settings.base import DATE_INPUT_FORMATS
class AdmissionNoteForm(forms.ModelForm):
class Meta:
model = AdmissionNote
fields = [
'id_gal_origin',
]
class PatientForm(forms.ModelForm):
class Meta:
model = Patient
fields = [
'name',
]
class FluVaccineForm(forms.ModelForm):
date_applied = forms.DateField(input_formats=DATE_INPUT_FORMATS)
class Meta:
model = FluVaccine
fields = ['was_applied', 'date_applied', ]
|
Add fields expicitly declared in form
|
:art: Add fields expicitly declared in form
|
Python
|
mit
|
gems-uff/labsys,gems-uff/labsys,gems-uff/labsys,gcrsaldanha/fiocruz,gcrsaldanha/fiocruz
|
python
|
## Code Before:
import datetime #for checking renewal date range.
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from .models import (Patient, AdmissionNote, FluVaccine,
CollectionType, CollectedSample,
Symptom, ObservedSymptom,
)
from fiocruz.settings.base import DATE_INPUT_FORMATS
class AdmissionNoteForm(forms.ModelForm):
class Meta:
model = AdmissionNote
fields = [
'id_gal_origin',
]
class PatientForm(forms.ModelForm):
class Meta:
model = Patient
fields = [
'name',
]
class FluVaccineForm(forms.ModelForm):
date_applied = forms.DateField(input_formats=DATE_INPUT_FORMATS)
class Meta:
model = FluVaccine
exclude = ['admission_note', ]
## Instruction:
:art: Add fields expicitly declared in form
## Code After:
import datetime #for checking renewal date range.
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from .models import (Patient, AdmissionNote, FluVaccine,
CollectionType, CollectedSample,
Symptom, ObservedSymptom,
)
from fiocruz.settings.base import DATE_INPUT_FORMATS
class AdmissionNoteForm(forms.ModelForm):
class Meta:
model = AdmissionNote
fields = [
'id_gal_origin',
]
class PatientForm(forms.ModelForm):
class Meta:
model = Patient
fields = [
'name',
]
class FluVaccineForm(forms.ModelForm):
date_applied = forms.DateField(input_formats=DATE_INPUT_FORMATS)
class Meta:
model = FluVaccine
fields = ['was_applied', 'date_applied', ]
|
# ... existing code ...
class Meta:
model = FluVaccine
fields = ['was_applied', 'date_applied', ]
# ... rest of the code ...
|
fa14c040e6483087f5b2c78bc1a7aeee9ad2274a
|
Instanssi/kompomaatti/misc/time_formatting.py
|
Instanssi/kompomaatti/misc/time_formatting.py
|
import awesometime
def compo_times_formatter(compo):
compo.compo_time = awesometime.format_single(compo.compo_start)
compo.adding_time = awesometime.format_single(compo.adding_end)
compo.editing_time = awesometime.format_single(compo.editing_end)
compo.voting_time = awesometime.format_between(compo.voting_start, compo.voting_end)
return compo
|
import awesometime
def compo_times_formatter(compo):
compo.compo_time = awesometime.format_single(compo.compo_start)
compo.adding_time = awesometime.format_single(compo.adding_end)
compo.editing_time = awesometime.format_single(compo.editing_end)
compo.voting_time = awesometime.format_between(compo.voting_start, compo.voting_end)
return compo
def competition_times_formatter(competition):
competition.start_time = awesometime.format_single(competition.start)
competition.participation_end_time = awesometime.format_single(competition.participation_end)
return competition
|
Add time formatter for competitions
|
kompomaatti: Add time formatter for competitions
|
Python
|
mit
|
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
|
python
|
## Code Before:
import awesometime
def compo_times_formatter(compo):
compo.compo_time = awesometime.format_single(compo.compo_start)
compo.adding_time = awesometime.format_single(compo.adding_end)
compo.editing_time = awesometime.format_single(compo.editing_end)
compo.voting_time = awesometime.format_between(compo.voting_start, compo.voting_end)
return compo
## Instruction:
kompomaatti: Add time formatter for competitions
## Code After:
import awesometime
def compo_times_formatter(compo):
compo.compo_time = awesometime.format_single(compo.compo_start)
compo.adding_time = awesometime.format_single(compo.adding_end)
compo.editing_time = awesometime.format_single(compo.editing_end)
compo.voting_time = awesometime.format_between(compo.voting_start, compo.voting_end)
return compo
def competition_times_formatter(competition):
competition.start_time = awesometime.format_single(competition.start)
competition.participation_end_time = awesometime.format_single(competition.participation_end)
return competition
|
# ... existing code ...
compo.editing_time = awesometime.format_single(compo.editing_end)
compo.voting_time = awesometime.format_between(compo.voting_start, compo.voting_end)
return compo
def competition_times_formatter(competition):
competition.start_time = awesometime.format_single(competition.start)
competition.participation_end_time = awesometime.format_single(competition.participation_end)
return competition
# ... rest of the code ...
|
938043259eefdec21994489d68b1cf737618ba34
|
test/test_conversion.py
|
test/test_conversion.py
|
import unittest
from src import conversion
class TestNotationConverter(unittest.TestCase):
"""Tests for NotationConverter class"""
def test_alg_search_good_input_a5(self):
"""Input with 'a5'"""
actual_result = main.TileLine('w').line
expected_result = ' '
self.assertEqual(actual_result, expected_result)
|
"""Tests for conversion module"""
import unittest
from src import conversion
class TestNotationConverter(unittest.TestCase):
"""Tests for NotationConverter class"""
def test_alg_search_good_input_a5(self):
"""Input with 'a5'"""
n_con = conversion.NotationConverter()
actual_result = n_con.alg_search('a5')
expected_result = ('a5', 'qr5', 'qr4')
self.assertEqual(actual_result, expected_result)
def test_alg_search_good_input_f7(self):
"""Input with 'f7'"""
n_con = conversion.NotationConverter()
actual_result = n_con.alg_search('f7')
expected_result = ('f7', 'kb7', 'kb2')
self.assertEqual(actual_result, expected_result)
def test_alg_search_nonexistant(self):
"""Input which does not exist"""
n_con = conversion.NotationConverter()
self.assertRaises(LookupError, n_con.alg_search, 'f99')
def test_desc_search_good_white(self):
"""Input with good value"""
n_con = conversion.NotationConverter()
actual_result = n_con.desc_search('qn3', 'white')
expected_result = ('b3', 'qn3', 'qn6')
self.assertEqual(actual_result, expected_result)
def test_desc_search_good_black(self):
"""Input with good value"""
n_con = conversion.NotationConverter()
actual_result = n_con.desc_search('qn6', 'black')
expected_result = ('b3', 'qn3', 'qn6')
self.assertEqual(actual_result, expected_result)
def test_desc_search_nonexistant(self):
"""Input with good value"""
n_con = conversion.NotationConverter()
self.assertRaises(LookupError, n_con.desc_search, 'qn333', 'white')
|
Add tests for NotationConverter methods
|
Add tests for NotationConverter methods
|
Python
|
mit
|
blairck/chess_notation
|
python
|
## Code Before:
import unittest
from src import conversion
class TestNotationConverter(unittest.TestCase):
"""Tests for NotationConverter class"""
def test_alg_search_good_input_a5(self):
"""Input with 'a5'"""
actual_result = main.TileLine('w').line
expected_result = ' '
self.assertEqual(actual_result, expected_result)
## Instruction:
Add tests for NotationConverter methods
## Code After:
"""Tests for conversion module"""
import unittest
from src import conversion
class TestNotationConverter(unittest.TestCase):
"""Tests for NotationConverter class"""
def test_alg_search_good_input_a5(self):
"""Input with 'a5'"""
n_con = conversion.NotationConverter()
actual_result = n_con.alg_search('a5')
expected_result = ('a5', 'qr5', 'qr4')
self.assertEqual(actual_result, expected_result)
def test_alg_search_good_input_f7(self):
"""Input with 'f7'"""
n_con = conversion.NotationConverter()
actual_result = n_con.alg_search('f7')
expected_result = ('f7', 'kb7', 'kb2')
self.assertEqual(actual_result, expected_result)
def test_alg_search_nonexistant(self):
"""Input which does not exist"""
n_con = conversion.NotationConverter()
self.assertRaises(LookupError, n_con.alg_search, 'f99')
def test_desc_search_good_white(self):
"""Input with good value"""
n_con = conversion.NotationConverter()
actual_result = n_con.desc_search('qn3', 'white')
expected_result = ('b3', 'qn3', 'qn6')
self.assertEqual(actual_result, expected_result)
def test_desc_search_good_black(self):
"""Input with good value"""
n_con = conversion.NotationConverter()
actual_result = n_con.desc_search('qn6', 'black')
expected_result = ('b3', 'qn3', 'qn6')
self.assertEqual(actual_result, expected_result)
def test_desc_search_nonexistant(self):
"""Input with good value"""
n_con = conversion.NotationConverter()
self.assertRaises(LookupError, n_con.desc_search, 'qn333', 'white')
|
...
"""Tests for conversion module"""
import unittest
from src import conversion
...
"""Tests for NotationConverter class"""
def test_alg_search_good_input_a5(self):
"""Input with 'a5'"""
n_con = conversion.NotationConverter()
actual_result = n_con.alg_search('a5')
expected_result = ('a5', 'qr5', 'qr4')
self.assertEqual(actual_result, expected_result)
def test_alg_search_good_input_f7(self):
"""Input with 'f7'"""
n_con = conversion.NotationConverter()
actual_result = n_con.alg_search('f7')
expected_result = ('f7', 'kb7', 'kb2')
self.assertEqual(actual_result, expected_result)
def test_alg_search_nonexistant(self):
"""Input which does not exist"""
n_con = conversion.NotationConverter()
self.assertRaises(LookupError, n_con.alg_search, 'f99')
def test_desc_search_good_white(self):
"""Input with good value"""
n_con = conversion.NotationConverter()
actual_result = n_con.desc_search('qn3', 'white')
expected_result = ('b3', 'qn3', 'qn6')
self.assertEqual(actual_result, expected_result)
def test_desc_search_good_black(self):
"""Input with good value"""
n_con = conversion.NotationConverter()
actual_result = n_con.desc_search('qn6', 'black')
expected_result = ('b3', 'qn3', 'qn6')
self.assertEqual(actual_result, expected_result)
def test_desc_search_nonexistant(self):
"""Input with good value"""
n_con = conversion.NotationConverter()
self.assertRaises(LookupError, n_con.desc_search, 'qn333', 'white')
...
|
ec1cbf654d8c280e3094a5917a696c84f1e1264f
|
setup.py
|
setup.py
|
from distutils.core import setup
VERSION = "2.00"
setup(
name = "SocksipyChain",
version = VERSION,
description = "A Python SOCKS/HTTP Proxy module",
long_description = """\
This Python module allows you to create TCP connections through a chain
of SOCKS or HTTP proxies without any special effort. It also supports
TLS/SSL encryption if the OpenSSL modules are installed..",
""",
url = "http://github.com/PageKite/SocksiPyChain",
author = "Bjarni R. Einarsson",
author_email="[email protected]",
license = "BSD",
py_modules=["sockschain"]
)
|
from distutils.core import setup
VERSION = "2.00"
setup(
name = "SocksipyChain",
version = VERSION,
description = "A Python SOCKS/HTTP Proxy module",
long_description = """\
This Python module allows you to create TCP connections through a chain
of SOCKS or HTTP proxies without any special effort. It also supports
TLS/SSL encryption if the OpenSSL modules are installed..",
""",
url = "http://github.com/PageKite/SocksiPyChain",
author = "Bjarni R. Einarsson",
author_email="[email protected]",
license = "BSD",
py_modules=["sockschain"],
scripts=["sockschain.py"]
)
|
Install as a script as well
|
Install as a script as well
|
Python
|
bsd-3-clause
|
locusf/PySocksipyChain,locusf/PySocksipyChain
|
python
|
## Code Before:
from distutils.core import setup
VERSION = "2.00"
setup(
name = "SocksipyChain",
version = VERSION,
description = "A Python SOCKS/HTTP Proxy module",
long_description = """\
This Python module allows you to create TCP connections through a chain
of SOCKS or HTTP proxies without any special effort. It also supports
TLS/SSL encryption if the OpenSSL modules are installed..",
""",
url = "http://github.com/PageKite/SocksiPyChain",
author = "Bjarni R. Einarsson",
author_email="[email protected]",
license = "BSD",
py_modules=["sockschain"]
)
## Instruction:
Install as a script as well
## Code After:
from distutils.core import setup
VERSION = "2.00"
setup(
name = "SocksipyChain",
version = VERSION,
description = "A Python SOCKS/HTTP Proxy module",
long_description = """\
This Python module allows you to create TCP connections through a chain
of SOCKS or HTTP proxies without any special effort. It also supports
TLS/SSL encryption if the OpenSSL modules are installed..",
""",
url = "http://github.com/PageKite/SocksiPyChain",
author = "Bjarni R. Einarsson",
author_email="[email protected]",
license = "BSD",
py_modules=["sockschain"],
scripts=["sockschain.py"]
)
|
# ... existing code ...
author = "Bjarni R. Einarsson",
author_email="[email protected]",
license = "BSD",
py_modules=["sockschain"],
scripts=["sockschain.py"]
)
# ... rest of the code ...
|
2fba1c04c8083211df8664d87080480a1f63ed2a
|
csunplugged/utils/group_lessons_by_age.py
|
csunplugged/utils/group_lessons_by_age.py
|
"""Return ordered groups of lessons."""
from collections import OrderedDict
from topics.models import (
AgeGroup,
LessonNumber,
)
def group_lessons_by_age(lessons):
"""Return ordered groups of lessons.
Lessons are grouped by the lesson minimum age and maximum ages,
and then order by number.
Args:
lessons: QuerySet of Lesson objects (QuerySet).
Returns:
A ordered dictionary of grouped lessons.
The key is a tuple of the minimum age and maximum ages for
the lessons.
The value for a key is a sorted list of lessons (ordered by number).
"""
grouped_lessons = OrderedDict()
for age_group in AgeGroup.objects.distinct():
for lesson in age_group.lessons.filter(id__in=lessons).order_by("lessonnumber"):
lesson.number = LessonNumber.objects.get(lesson=lesson, age_group=age_group).number
if age_group in grouped_lessons.keys():
grouped_lessons[age_group].append(lesson)
else:
grouped_lessons[age_group] = [lesson]
return grouped_lessons
|
"""Return ordered groups of lessons."""
from collections import OrderedDict
from topics.models import (
AgeGroup,
LessonNumber,
)
def group_lessons_by_age(lessons):
"""Return ordered groups of lessons.
Lessons are grouped by the lesson minimum age and maximum ages,
and then order by number.
Args:
lessons: QuerySet of Lesson objects (QuerySet).
Returns:
A ordered dictionary of grouped lessons.
The key is a tuple of the minimum age and maximum ages for
the lessons.
The value for a key is a sorted list of lessons (ordered by number).
"""
grouped_lessons = OrderedDict()
for age_group in AgeGroup.objects.distinct():
for lesson in age_group.lessons.filter(id__in=lessons).order_by("lessonnumber"):
lesson.number = LessonNumber.objects.get(lesson=lesson, age_group=age_group).number
if age_group in grouped_lessons.keys():
grouped_lessons[ages].add(lesson)
else:
grouped_lessons[ages] = set([lesson])
return grouped_lessons
|
Fix bug where lessons are duplicated across age groups.
|
Fix bug where lessons are duplicated across age groups.
|
Python
|
mit
|
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
|
python
|
## Code Before:
"""Return ordered groups of lessons."""
from collections import OrderedDict
from topics.models import (
AgeGroup,
LessonNumber,
)
def group_lessons_by_age(lessons):
"""Return ordered groups of lessons.
Lessons are grouped by the lesson minimum age and maximum ages,
and then order by number.
Args:
lessons: QuerySet of Lesson objects (QuerySet).
Returns:
A ordered dictionary of grouped lessons.
The key is a tuple of the minimum age and maximum ages for
the lessons.
The value for a key is a sorted list of lessons (ordered by number).
"""
grouped_lessons = OrderedDict()
for age_group in AgeGroup.objects.distinct():
for lesson in age_group.lessons.filter(id__in=lessons).order_by("lessonnumber"):
lesson.number = LessonNumber.objects.get(lesson=lesson, age_group=age_group).number
if age_group in grouped_lessons.keys():
grouped_lessons[age_group].append(lesson)
else:
grouped_lessons[age_group] = [lesson]
return grouped_lessons
## Instruction:
Fix bug where lessons are duplicated across age groups.
## Code After:
"""Return ordered groups of lessons."""
from collections import OrderedDict
from topics.models import (
AgeGroup,
LessonNumber,
)
def group_lessons_by_age(lessons):
"""Return ordered groups of lessons.
Lessons are grouped by the lesson minimum age and maximum ages,
and then order by number.
Args:
lessons: QuerySet of Lesson objects (QuerySet).
Returns:
A ordered dictionary of grouped lessons.
The key is a tuple of the minimum age and maximum ages for
the lessons.
The value for a key is a sorted list of lessons (ordered by number).
"""
grouped_lessons = OrderedDict()
for age_group in AgeGroup.objects.distinct():
for lesson in age_group.lessons.filter(id__in=lessons).order_by("lessonnumber"):
lesson.number = LessonNumber.objects.get(lesson=lesson, age_group=age_group).number
if age_group in grouped_lessons.keys():
grouped_lessons[ages].add(lesson)
else:
grouped_lessons[ages] = set([lesson])
return grouped_lessons
|
# ... existing code ...
for lesson in age_group.lessons.filter(id__in=lessons).order_by("lessonnumber"):
lesson.number = LessonNumber.objects.get(lesson=lesson, age_group=age_group).number
if age_group in grouped_lessons.keys():
grouped_lessons[ages].add(lesson)
else:
grouped_lessons[ages] = set([lesson])
return grouped_lessons
# ... rest of the code ...
|
259e196bb08d61c1e78b0666eca79aaa5f8f60e5
|
src/test/java/com/github/ansell/csvsum/CSVSummariserTest.java
|
src/test/java/com/github/ansell/csvsum/CSVSummariserTest.java
|
/**
*
*/
package com.github.ansell.csvsum;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import joptsimple.OptionException;
/**
* Tests for {@link CSVSummariser}.
*
* @author Peter Ansell [email protected]
*/
public class CSVSummariserTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
/**
* Test method for
* {@link com.github.ansell.csvsum.CSVSummariser#main(java.lang.String[])}.
*/
@Test
public final void testMainNoArgs() throws Exception {
thrown.expect(OptionException.class);
CSVSummariser.main();
}
}
|
/**
*
*/
package com.github.ansell.csvsum;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import joptsimple.OptionException;
/**
* Tests for {@link CSVSummariser}.
*
* @author Peter Ansell [email protected]
*/
public class CSVSummariserTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
/**
* Test method for
* {@link com.github.ansell.csvsum.CSVSummariser#main(java.lang.String[])}.
*/
@Test
public final void testMainNoArgs() throws Exception {
thrown.expect(OptionException.class);
CSVSummariser.main();
}
/**
* Test method for
* {@link com.github.ansell.csvsum.CSVSummariser#main(java.lang.String[])}.
*/
@Test
public final void testMainHelp() throws Exception {
CSVSummariser.main("--help");
}
}
|
Add test for CSVSummariser help
|
Add test for CSVSummariser help
|
Java
|
bsd-2-clause
|
ansell/csvsum,ansell/csvsum
|
java
|
## Code Before:
/**
*
*/
package com.github.ansell.csvsum;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import joptsimple.OptionException;
/**
* Tests for {@link CSVSummariser}.
*
* @author Peter Ansell [email protected]
*/
public class CSVSummariserTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
/**
* Test method for
* {@link com.github.ansell.csvsum.CSVSummariser#main(java.lang.String[])}.
*/
@Test
public final void testMainNoArgs() throws Exception {
thrown.expect(OptionException.class);
CSVSummariser.main();
}
}
## Instruction:
Add test for CSVSummariser help
## Code After:
/**
*
*/
package com.github.ansell.csvsum;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import joptsimple.OptionException;
/**
* Tests for {@link CSVSummariser}.
*
* @author Peter Ansell [email protected]
*/
public class CSVSummariserTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
/**
* Test method for
* {@link com.github.ansell.csvsum.CSVSummariser#main(java.lang.String[])}.
*/
@Test
public final void testMainNoArgs() throws Exception {
thrown.expect(OptionException.class);
CSVSummariser.main();
}
/**
* Test method for
* {@link com.github.ansell.csvsum.CSVSummariser#main(java.lang.String[])}.
*/
@Test
public final void testMainHelp() throws Exception {
CSVSummariser.main("--help");
}
}
|
// ... existing code ...
CSVSummariser.main();
}
/**
* Test method for
* {@link com.github.ansell.csvsum.CSVSummariser#main(java.lang.String[])}.
*/
@Test
public final void testMainHelp() throws Exception {
CSVSummariser.main("--help");
}
}
// ... rest of the code ...
|
469e3a65e8e2d570f77bba4ad74472b06f5f0dc0
|
openstack-api/src/main/java/org/openstack/client/internals/OpenstackSerializationModule.java
|
openstack-api/src/main/java/org/openstack/client/internals/OpenstackSerializationModule.java
|
package org.openstack.client.internals;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.module.SimpleModule;
import org.openstack.model.compute.Addresses;
import org.openstack.model.compute.SecurityGroup;
import org.openstack.model.compute.SecurityGroupList;
import org.openstack.model.compute.Server;
import org.openstack.model.identity.Access;
public class OpenstackSerializationModule extends SimpleModule {
public OpenstackSerializationModule() {
super(OpenstackSerializationModule.class.getName(), new Version(1, 0, 0, null));
addSerializer(Addresses.class, new AddressesSerializer());
addDeserializer(Addresses.class, new AddressesDeserializer());
// Compute
installSmartDeserializer(SecurityGroup.class);
installSmartDeserializer(SecurityGroupList.class);
installSmartDeserializer(Server.class);
// Keystone (Redux)
installSmartDeserializer(Access.class);
}
private <T> void installSmartDeserializer(Class<T> c) {
addDeserializer(c, new SmartDeserializer<T>(c));
}
}
|
package org.openstack.client.internals;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.module.SimpleModule;
import org.openstack.model.compute.Addresses;
import org.openstack.model.compute.BadRequest;
import org.openstack.model.compute.SecurityGroup;
import org.openstack.model.compute.SecurityGroupList;
import org.openstack.model.compute.Server;
import org.openstack.model.identity.Access;
public class OpenstackSerializationModule extends SimpleModule {
public OpenstackSerializationModule() {
super(OpenstackSerializationModule.class.getName(), new Version(1, 0, 0, null));
addSerializer(Addresses.class, new AddressesSerializer());
addDeserializer(Addresses.class, new AddressesDeserializer());
// Compute
installSmartDeserializer(SecurityGroup.class);
installSmartDeserializer(SecurityGroupList.class);
installSmartDeserializer(Server.class);
installSmartDeserializer(BadRequest.class);
// Keystone (Redux)
installSmartDeserializer(Access.class);
}
private <T> void installSmartDeserializer(Class<T> c) {
addDeserializer(c, new SmartDeserializer<T>(c));
}
}
|
Use the smart JSON serializer for BadRequest
|
Use the smart JSON serializer for BadRequest
|
Java
|
apache-2.0
|
krishnabrucelee/OpenStack-Nova-Client,zhimin711/openstack-java-sdk,krishnabrucelee/Cloud-stack-Api,krishnabrucelee/Cinder-Krishna,CIETstudents/Cinder-Krishna-Mona,krishnabrucelee/ceilometerModel-Krishna,krishnabrucelee/ceilometerModel-Krishna,woorea/openstack-java-sdk,CIETstudents/Cinder-Krishna-Mona,CIETstudents/Swift-Model-Mona,NareshkumarCIET/Cinder,woorea/openstack-java-sdk,MonaCIET/cinder,krishnabrucelee/Library-Management,krishnabrucelee/OpenStack-Nova-Client,OnePaaS/openstack-java-sdk,KizuRos/openstack-java-sdk,CIETstudents/Swift-Model-Mona,krishnabrucelee/Cloud-stack-Api,vmturbo/openstack-java-sdk,krishnabrucelee/Cinder-Krishna,KizuRos/openstack-java-sdk,zhimin711/openstack-java-sdk,OnePaaS/openstack-java-sdk,NareshkumarCIET/Cinder,krishnabrucelee/Library-Management,MonaCIET/cinder,krishnabrucelee/Library-Management,CIETstudents/openstack-maven-CIET-students,vmturbo/openstack-java-sdk,CIETstudents/openstack-maven-CIET-students
|
java
|
## Code Before:
package org.openstack.client.internals;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.module.SimpleModule;
import org.openstack.model.compute.Addresses;
import org.openstack.model.compute.SecurityGroup;
import org.openstack.model.compute.SecurityGroupList;
import org.openstack.model.compute.Server;
import org.openstack.model.identity.Access;
public class OpenstackSerializationModule extends SimpleModule {
public OpenstackSerializationModule() {
super(OpenstackSerializationModule.class.getName(), new Version(1, 0, 0, null));
addSerializer(Addresses.class, new AddressesSerializer());
addDeserializer(Addresses.class, new AddressesDeserializer());
// Compute
installSmartDeserializer(SecurityGroup.class);
installSmartDeserializer(SecurityGroupList.class);
installSmartDeserializer(Server.class);
// Keystone (Redux)
installSmartDeserializer(Access.class);
}
private <T> void installSmartDeserializer(Class<T> c) {
addDeserializer(c, new SmartDeserializer<T>(c));
}
}
## Instruction:
Use the smart JSON serializer for BadRequest
## Code After:
package org.openstack.client.internals;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.module.SimpleModule;
import org.openstack.model.compute.Addresses;
import org.openstack.model.compute.BadRequest;
import org.openstack.model.compute.SecurityGroup;
import org.openstack.model.compute.SecurityGroupList;
import org.openstack.model.compute.Server;
import org.openstack.model.identity.Access;
public class OpenstackSerializationModule extends SimpleModule {
public OpenstackSerializationModule() {
super(OpenstackSerializationModule.class.getName(), new Version(1, 0, 0, null));
addSerializer(Addresses.class, new AddressesSerializer());
addDeserializer(Addresses.class, new AddressesDeserializer());
// Compute
installSmartDeserializer(SecurityGroup.class);
installSmartDeserializer(SecurityGroupList.class);
installSmartDeserializer(Server.class);
installSmartDeserializer(BadRequest.class);
// Keystone (Redux)
installSmartDeserializer(Access.class);
}
private <T> void installSmartDeserializer(Class<T> c) {
addDeserializer(c, new SmartDeserializer<T>(c));
}
}
|
# ... existing code ...
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.module.SimpleModule;
import org.openstack.model.compute.Addresses;
import org.openstack.model.compute.BadRequest;
import org.openstack.model.compute.SecurityGroup;
import org.openstack.model.compute.SecurityGroupList;
import org.openstack.model.compute.Server;
# ... modified code ...
installSmartDeserializer(SecurityGroup.class);
installSmartDeserializer(SecurityGroupList.class);
installSmartDeserializer(Server.class);
installSmartDeserializer(BadRequest.class);
// Keystone (Redux)
installSmartDeserializer(Access.class);
# ... rest of the code ...
|
104c21379d4fbb54d7c913e0ab10b5e9a1111a62
|
src/main/java/database/DummyDALpug.java
|
src/main/java/database/DummyDALpug.java
|
package database;
import java.util.ArrayList;
import java.util.List;
import interfaces.IDALpug;
import models.GenreTag;
import models.Song;
public class DummyDALpug implements IDALpug
{
private static Song dummySong;
private static List<Song> dummySongCollection;
public DummyDALpug()
{
if(dummySong == null)
{
String fileName = "LooneyToonsEnd.mp3";
String path = System.getProperty("user.dir") + "\\src\\main\\java\\tempFiles\\" + fileName;
dummySong = new Song("LooneyToons", null, path);
dummySongCollection = new ArrayList<Song>();
dummySongCollection.add(dummySong);
}
}
@Override
public Long add(Song song)
{
return 1l;
}
@Override
public Song getById(Long id)
{
return dummySong;
}
@Override
public Song getByTitle(String title)
{
return dummySong;
}
@Override
public List<Song> getByTag(GenreTag tag)
{
return dummySongCollection;
}
@Override
public List<Song> getByTags(List<GenreTag> tag)
{
return dummySongCollection;
}
@Override
public List<Song> getByLyrics(String Lyrics)
{
return dummySongCollection;
}
}
|
package database;
import java.util.ArrayList;
import java.util.List;
import interfaces.IDALpug;
import models.GenreTag;
import models.Song;
public class DummyDALpug implements IDALpug
{
private static Song dummySong;
private static List<Song> dummySongCollection;
public DummyDALpug()
{
if(dummySong == null)
{
String fileName = "LooneyToonsEnd.mp3";
String path = "//src//main//java//tempFiles//" + fileName;
dummySong = new Song("LooneyToons", null, path);
dummySongCollection = new ArrayList<Song>();
dummySongCollection.add(dummySong);
}
}
@Override
public Long add(Song song)
{
return 1l;
}
@Override
public Song getById(Long id)
{
return dummySong;
}
@Override
public Song getByTitle(String title)
{
return dummySong;
}
@Override
public List<Song> getByTag(GenreTag tag)
{
return dummySongCollection;
}
@Override
public List<Song> getByTags(List<GenreTag> tag)
{
return dummySongCollection;
}
@Override
public List<Song> getByLyrics(String Lyrics)
{
return dummySongCollection;
}
}
|
Set DummayDall to pull LooneyToones.mp3 file - BA
|
Set DummayDall to pull LooneyToones.mp3 file - BA
|
Java
|
mit
|
lkawahara/playlistpug,lkawahara/playlistpug
|
java
|
## Code Before:
package database;
import java.util.ArrayList;
import java.util.List;
import interfaces.IDALpug;
import models.GenreTag;
import models.Song;
public class DummyDALpug implements IDALpug
{
private static Song dummySong;
private static List<Song> dummySongCollection;
public DummyDALpug()
{
if(dummySong == null)
{
String fileName = "LooneyToonsEnd.mp3";
String path = System.getProperty("user.dir") + "\\src\\main\\java\\tempFiles\\" + fileName;
dummySong = new Song("LooneyToons", null, path);
dummySongCollection = new ArrayList<Song>();
dummySongCollection.add(dummySong);
}
}
@Override
public Long add(Song song)
{
return 1l;
}
@Override
public Song getById(Long id)
{
return dummySong;
}
@Override
public Song getByTitle(String title)
{
return dummySong;
}
@Override
public List<Song> getByTag(GenreTag tag)
{
return dummySongCollection;
}
@Override
public List<Song> getByTags(List<GenreTag> tag)
{
return dummySongCollection;
}
@Override
public List<Song> getByLyrics(String Lyrics)
{
return dummySongCollection;
}
}
## Instruction:
Set DummayDall to pull LooneyToones.mp3 file - BA
## Code After:
package database;
import java.util.ArrayList;
import java.util.List;
import interfaces.IDALpug;
import models.GenreTag;
import models.Song;
public class DummyDALpug implements IDALpug
{
private static Song dummySong;
private static List<Song> dummySongCollection;
public DummyDALpug()
{
if(dummySong == null)
{
String fileName = "LooneyToonsEnd.mp3";
String path = "//src//main//java//tempFiles//" + fileName;
dummySong = new Song("LooneyToons", null, path);
dummySongCollection = new ArrayList<Song>();
dummySongCollection.add(dummySong);
}
}
@Override
public Long add(Song song)
{
return 1l;
}
@Override
public Song getById(Long id)
{
return dummySong;
}
@Override
public Song getByTitle(String title)
{
return dummySong;
}
@Override
public List<Song> getByTag(GenreTag tag)
{
return dummySongCollection;
}
@Override
public List<Song> getByTags(List<GenreTag> tag)
{
return dummySongCollection;
}
@Override
public List<Song> getByLyrics(String Lyrics)
{
return dummySongCollection;
}
}
|
...
if(dummySong == null)
{
String fileName = "LooneyToonsEnd.mp3";
String path = "//src//main//java//tempFiles//" + fileName;
dummySong = new Song("LooneyToons", null, path);
dummySongCollection = new ArrayList<Song>();
dummySongCollection.add(dummySong);
...
|
5f14b7217f81b6d7653f94065d1a3305204cf83b
|
ddcz/templatetags/creations.py
|
ddcz/templatetags/creations.py
|
from django import template
from django.contrib.staticfiles.storage import staticfiles_storage
from ..creations import RATING_DESCRIPTIONS
register = template.Library()
@register.inclusion_tag('creations/rating.html')
def creation_rating(rating, skin):
return {
'rating_description': RATING_DESCRIPTIONS[round(rating)],
'rating': range(rating),
'skin': skin,
'skin_rating_star_url': staticfiles_storage.url("skins/%s/img/rating-star.gif" % skin),
}
|
from django import template
from django.contrib.staticfiles.storage import staticfiles_storage
from ..creations import RATING_DESCRIPTIONS
register = template.Library()
@register.inclusion_tag('creations/rating.html')
def creation_rating(rating, skin):
return {
'rating_description': "Hodnocení: %s" % RATING_DESCRIPTIONS[round(rating)],
'rating': range(rating),
'skin': skin,
'skin_rating_star_url': staticfiles_storage.url("skins/%s/img/rating-star.gif" % skin),
}
|
Add explicit rating word to rating alt
|
Add explicit rating word to rating alt
|
Python
|
mit
|
dracidoupe/graveyard,dracidoupe/graveyard,dracidoupe/graveyard,dracidoupe/graveyard
|
python
|
## Code Before:
from django import template
from django.contrib.staticfiles.storage import staticfiles_storage
from ..creations import RATING_DESCRIPTIONS
register = template.Library()
@register.inclusion_tag('creations/rating.html')
def creation_rating(rating, skin):
return {
'rating_description': RATING_DESCRIPTIONS[round(rating)],
'rating': range(rating),
'skin': skin,
'skin_rating_star_url': staticfiles_storage.url("skins/%s/img/rating-star.gif" % skin),
}
## Instruction:
Add explicit rating word to rating alt
## Code After:
from django import template
from django.contrib.staticfiles.storage import staticfiles_storage
from ..creations import RATING_DESCRIPTIONS
register = template.Library()
@register.inclusion_tag('creations/rating.html')
def creation_rating(rating, skin):
return {
'rating_description': "Hodnocení: %s" % RATING_DESCRIPTIONS[round(rating)],
'rating': range(rating),
'skin': skin,
'skin_rating_star_url': staticfiles_storage.url("skins/%s/img/rating-star.gif" % skin),
}
|
...
@register.inclusion_tag('creations/rating.html')
def creation_rating(rating, skin):
return {
'rating_description': "Hodnocení: %s" % RATING_DESCRIPTIONS[round(rating)],
'rating': range(rating),
'skin': skin,
'skin_rating_star_url': staticfiles_storage.url("skins/%s/img/rating-star.gif" % skin),
...
|
b965341288bfe4bc748e1e9053d8847b72fa16dc
|
src/main/com/mongodb/MapReduceOutput.java
|
src/main/com/mongodb/MapReduceOutput.java
|
// MapReduceOutput.java
package com.mongodb;
/**
* Represents the result of a map/reduce operation
* @author antoine
*/
public class MapReduceOutput {
MapReduceOutput( DBCollection from , BasicDBObject raw ){
_raw = raw;
if ( raw.containsKey( "results" ) ) {
_coll = null;
_collname = "<<INLINE>>";
_resultSet = (Iterable<DBObject>) raw.get( "results" );
} else {
_collname = raw.getString( "result" );
_coll = from._db.getCollection( _collname );
_resultSet = _coll.find();
}
_counts = (BasicDBObject)raw.get( "counts" );
}
/**
* returns a cursor to the results of the operation
* @return
*/
public Iterable<DBObject> results(){
return _resultSet;
}
/**
* drops the collection that holds the results
*/
public void drop(){
if ( _coll != null)
_coll.drop();
}
/**
* gets the collection that holds the results
* (Will return null if results are Inline)
* @return
*/
public DBCollection getOutputCollection(){
return _coll;
}
public BasicDBObject getRaw(){
return _raw;
}
public String toString(){
return _raw.toString();
}
final BasicDBObject _raw;
final String _collname;
final Iterable<DBObject> _resultSet;
final DBCollection _coll;
final BasicDBObject _counts;
}
|
// MapReduceOutput.java
package com.mongodb;
/**
* Represents the result of a map/reduce operation
* @author antoine
*/
public class MapReduceOutput {
MapReduceOutput( DBCollection from , BasicDBObject raw ){
_raw = raw;
if ( raw.containsKey( "results" ) ) {
_coll = null;
_collname = null;
_resultSet = (Iterable<DBObject>) raw.get( "results" );
} else {
_collname = raw.getString( "result" );
_coll = from._db.getCollection( _collname );
_resultSet = _coll.find();
}
_counts = (BasicDBObject)raw.get( "counts" );
}
/**
* returns a cursor to the results of the operation
* @return
*/
public Iterable<DBObject> results(){
return _resultSet;
}
/**
* drops the collection that holds the results
*/
public void drop(){
if ( _coll != null)
_coll.drop();
}
/**
* gets the collection that holds the results
* (Will return null if results are Inline)
* @return
*/
public DBCollection getOutputCollection(){
return _coll;
}
public BasicDBObject getRaw(){
return _raw;
}
public String toString(){
return _raw.toString();
}
final BasicDBObject _raw;
final String _collname;
final Iterable<DBObject> _resultSet;
final DBCollection _coll;
final BasicDBObject _counts;
}
|
Set collection name to 'null' rather than a placeholder for inline results
|
Set collection name to 'null' rather than a placeholder for inline
results
|
Java
|
apache-2.0
|
PSCGroup/mongo-java-driver,jyemin/mongo-java-driver,kevinsawicki/mongo-java-driver,kevinsawicki/mongo-java-driver,wanggc/mongo-java-driver,rozza/mongo-java-driver,wanggc/mongo-java-driver,jyemin/mongo-java-driver,gianpaj/mongo-java-driver,kevinsawicki/mongo-java-driver,davydotcom/mongo-java-driver,davydotcom/mongo-java-driver,jsonking/mongo-java-driver,rozza/mongo-java-driver,jsonking/mongo-java-driver,kay-kim/mongo-java-driver
|
java
|
## Code Before:
// MapReduceOutput.java
package com.mongodb;
/**
* Represents the result of a map/reduce operation
* @author antoine
*/
public class MapReduceOutput {
MapReduceOutput( DBCollection from , BasicDBObject raw ){
_raw = raw;
if ( raw.containsKey( "results" ) ) {
_coll = null;
_collname = "<<INLINE>>";
_resultSet = (Iterable<DBObject>) raw.get( "results" );
} else {
_collname = raw.getString( "result" );
_coll = from._db.getCollection( _collname );
_resultSet = _coll.find();
}
_counts = (BasicDBObject)raw.get( "counts" );
}
/**
* returns a cursor to the results of the operation
* @return
*/
public Iterable<DBObject> results(){
return _resultSet;
}
/**
* drops the collection that holds the results
*/
public void drop(){
if ( _coll != null)
_coll.drop();
}
/**
* gets the collection that holds the results
* (Will return null if results are Inline)
* @return
*/
public DBCollection getOutputCollection(){
return _coll;
}
public BasicDBObject getRaw(){
return _raw;
}
public String toString(){
return _raw.toString();
}
final BasicDBObject _raw;
final String _collname;
final Iterable<DBObject> _resultSet;
final DBCollection _coll;
final BasicDBObject _counts;
}
## Instruction:
Set collection name to 'null' rather than a placeholder for inline
results
## Code After:
// MapReduceOutput.java
package com.mongodb;
/**
* Represents the result of a map/reduce operation
* @author antoine
*/
public class MapReduceOutput {
MapReduceOutput( DBCollection from , BasicDBObject raw ){
_raw = raw;
if ( raw.containsKey( "results" ) ) {
_coll = null;
_collname = null;
_resultSet = (Iterable<DBObject>) raw.get( "results" );
} else {
_collname = raw.getString( "result" );
_coll = from._db.getCollection( _collname );
_resultSet = _coll.find();
}
_counts = (BasicDBObject)raw.get( "counts" );
}
/**
* returns a cursor to the results of the operation
* @return
*/
public Iterable<DBObject> results(){
return _resultSet;
}
/**
* drops the collection that holds the results
*/
public void drop(){
if ( _coll != null)
_coll.drop();
}
/**
* gets the collection that holds the results
* (Will return null if results are Inline)
* @return
*/
public DBCollection getOutputCollection(){
return _coll;
}
public BasicDBObject getRaw(){
return _raw;
}
public String toString(){
return _raw.toString();
}
final BasicDBObject _raw;
final String _collname;
final Iterable<DBObject> _resultSet;
final DBCollection _coll;
final BasicDBObject _counts;
}
|
...
if ( raw.containsKey( "results" ) ) {
_coll = null;
_collname = null;
_resultSet = (Iterable<DBObject>) raw.get( "results" );
} else {
_collname = raw.getString( "result" );
...
|
029df34ce4a69adf5321531b229503d66169c9a6
|
tests/optimizers/test_conjugate_gradient.py
|
tests/optimizers/test_conjugate_gradient.py
|
from pymanopt.optimizers import ConjugateGradient
from .._test import TestCase
class TestConjugateGradient(TestCase):
def test_beta_type(self):
with self.assertRaises(ValueError):
ConjugateGradient(beta_rule="SomeUnknownBetaRule")
|
import numpy as np
import numpy.testing as np_testing
from nose2.tools import params
import pymanopt
from pymanopt.optimizers import ConjugateGradient
from .._test import TestCase
class TestConjugateGradient(TestCase):
def setUp(self):
n = 32
matrix = np.random.normal(size=(n, n))
matrix = 0.5 * (matrix + matrix.T)
eigenvalues, eigenvectors = np.linalg.eig(matrix)
self.dominant_eigenvector = eigenvectors[:, np.argmax(eigenvalues)]
self.manifold = manifold = pymanopt.manifolds.Sphere(n)
@pymanopt.function.autograd(manifold)
def cost(point):
return -point.T @ matrix @ point
self.problem = pymanopt.Problem(manifold, cost)
@params(
"FletcherReeves",
"HagerZhang",
"HestenesStiefel",
"PolakRibiere",
)
def test_beta_rules(self, beta_rule):
optimizer = ConjugateGradient(beta_rule=beta_rule, verbosity=0)
result = optimizer.run(self.problem)
estimated_dominant_eigenvector = result.point
if np.sign(self.dominant_eigenvector[0]) != np.sign(
estimated_dominant_eigenvector[0]
):
estimated_dominant_eigenvector = -estimated_dominant_eigenvector
np_testing.assert_allclose(
self.dominant_eigenvector,
estimated_dominant_eigenvector,
atol=1e-6,
)
def test_beta_invalid_rule(self):
with self.assertRaises(ValueError):
ConjugateGradient(beta_rule="SomeUnknownBetaRule")
|
Add simple end-to-end test case for beta rules
|
Add simple end-to-end test case for beta rules
Signed-off-by: Niklas Koep <[email protected]>
|
Python
|
bsd-3-clause
|
pymanopt/pymanopt,pymanopt/pymanopt
|
python
|
## Code Before:
from pymanopt.optimizers import ConjugateGradient
from .._test import TestCase
class TestConjugateGradient(TestCase):
def test_beta_type(self):
with self.assertRaises(ValueError):
ConjugateGradient(beta_rule="SomeUnknownBetaRule")
## Instruction:
Add simple end-to-end test case for beta rules
Signed-off-by: Niklas Koep <[email protected]>
## Code After:
import numpy as np
import numpy.testing as np_testing
from nose2.tools import params
import pymanopt
from pymanopt.optimizers import ConjugateGradient
from .._test import TestCase
class TestConjugateGradient(TestCase):
def setUp(self):
n = 32
matrix = np.random.normal(size=(n, n))
matrix = 0.5 * (matrix + matrix.T)
eigenvalues, eigenvectors = np.linalg.eig(matrix)
self.dominant_eigenvector = eigenvectors[:, np.argmax(eigenvalues)]
self.manifold = manifold = pymanopt.manifolds.Sphere(n)
@pymanopt.function.autograd(manifold)
def cost(point):
return -point.T @ matrix @ point
self.problem = pymanopt.Problem(manifold, cost)
@params(
"FletcherReeves",
"HagerZhang",
"HestenesStiefel",
"PolakRibiere",
)
def test_beta_rules(self, beta_rule):
optimizer = ConjugateGradient(beta_rule=beta_rule, verbosity=0)
result = optimizer.run(self.problem)
estimated_dominant_eigenvector = result.point
if np.sign(self.dominant_eigenvector[0]) != np.sign(
estimated_dominant_eigenvector[0]
):
estimated_dominant_eigenvector = -estimated_dominant_eigenvector
np_testing.assert_allclose(
self.dominant_eigenvector,
estimated_dominant_eigenvector,
atol=1e-6,
)
def test_beta_invalid_rule(self):
with self.assertRaises(ValueError):
ConjugateGradient(beta_rule="SomeUnknownBetaRule")
|
# ... existing code ...
import numpy as np
import numpy.testing as np_testing
from nose2.tools import params
import pymanopt
from pymanopt.optimizers import ConjugateGradient
from .._test import TestCase
# ... modified code ...
class TestConjugateGradient(TestCase):
def setUp(self):
n = 32
matrix = np.random.normal(size=(n, n))
matrix = 0.5 * (matrix + matrix.T)
eigenvalues, eigenvectors = np.linalg.eig(matrix)
self.dominant_eigenvector = eigenvectors[:, np.argmax(eigenvalues)]
self.manifold = manifold = pymanopt.manifolds.Sphere(n)
@pymanopt.function.autograd(manifold)
def cost(point):
return -point.T @ matrix @ point
self.problem = pymanopt.Problem(manifold, cost)
@params(
"FletcherReeves",
"HagerZhang",
"HestenesStiefel",
"PolakRibiere",
)
def test_beta_rules(self, beta_rule):
optimizer = ConjugateGradient(beta_rule=beta_rule, verbosity=0)
result = optimizer.run(self.problem)
estimated_dominant_eigenvector = result.point
if np.sign(self.dominant_eigenvector[0]) != np.sign(
estimated_dominant_eigenvector[0]
):
estimated_dominant_eigenvector = -estimated_dominant_eigenvector
np_testing.assert_allclose(
self.dominant_eigenvector,
estimated_dominant_eigenvector,
atol=1e-6,
)
def test_beta_invalid_rule(self):
with self.assertRaises(ValueError):
ConjugateGradient(beta_rule="SomeUnknownBetaRule")
# ... rest of the code ...
|
4a24b874869c49cb551d9946e7eec35a49e66d96
|
edu.oregonstate.cope.eclipse/src/edu/oregonstate/cope/eclipse/listeners/SaveCommandExecutionListener.java
|
edu.oregonstate.cope.eclipse/src/edu/oregonstate/cope/eclipse/listeners/SaveCommandExecutionListener.java
|
package edu.oregonstate.cope.eclipse.listeners;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IExecutionListener;
import org.eclipse.core.commands.NotHandledException;
public class SaveCommandExecutionListener implements IExecutionListener {
private static long lastSaveAction = 0;
/**
* Returns the time (in milliseconds since The Epoch) of the last save
* action.
*
* @return
*/
public static long getLastSaveAction() {
return lastSaveAction;
}
@Override
public void preExecute(String commandId, ExecutionEvent event) {
if (isFileSave(commandId)) {
lastSaveAction = System.currentTimeMillis();
}
}
private boolean isFileSave(String commandId) {
return commandId.equals("org.eclipse.ui.file.save");
}
@Override
public void postExecuteSuccess(String commandId, Object returnValue) {
}
@Override
public void postExecuteFailure(String commandId,
ExecutionException exception) {
}
@Override
public void notHandled(String commandId, NotHandledException exception) {
}
}
|
package edu.oregonstate.cope.eclipse.listeners;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IExecutionListener;
import org.eclipse.core.commands.NotHandledException;
public class SaveCommandExecutionListener implements IExecutionListener {
private static long lastSaveAction = 0;
/**
* Returns the time (in milliseconds since The Epoch) of the last save
* action.
*
* @return
*/
public static long getLastSaveAction() {
return lastSaveAction;
}
@Override
public void preExecute(String commandId, ExecutionEvent event) {
if (isFileSave(commandId)) {
lastSaveAction = System.currentTimeMillis();
}
}
private boolean isFileSave(String commandId) {
return commandId.equals("org.eclipse.ui.file.save") || commandId.equalsIgnoreCase("org.eclipse.ui.file.saveAll");
}
@Override
public void postExecuteSuccess(String commandId, Object returnValue) {
}
@Override
public void postExecuteFailure(String commandId,
ExecutionException exception) {
}
@Override
public void notHandled(String commandId, NotHandledException exception) {
}
}
|
Save All is also a save action
|
Save All is also a save action
|
Java
|
epl-1.0
|
ChangeOrientedProgrammingEnvironment/eclipseRecorder,ChangeOrientedProgrammingEnvironment/eclipseRecorder
|
java
|
## Code Before:
package edu.oregonstate.cope.eclipse.listeners;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IExecutionListener;
import org.eclipse.core.commands.NotHandledException;
public class SaveCommandExecutionListener implements IExecutionListener {
private static long lastSaveAction = 0;
/**
* Returns the time (in milliseconds since The Epoch) of the last save
* action.
*
* @return
*/
public static long getLastSaveAction() {
return lastSaveAction;
}
@Override
public void preExecute(String commandId, ExecutionEvent event) {
if (isFileSave(commandId)) {
lastSaveAction = System.currentTimeMillis();
}
}
private boolean isFileSave(String commandId) {
return commandId.equals("org.eclipse.ui.file.save");
}
@Override
public void postExecuteSuccess(String commandId, Object returnValue) {
}
@Override
public void postExecuteFailure(String commandId,
ExecutionException exception) {
}
@Override
public void notHandled(String commandId, NotHandledException exception) {
}
}
## Instruction:
Save All is also a save action
## Code After:
package edu.oregonstate.cope.eclipse.listeners;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IExecutionListener;
import org.eclipse.core.commands.NotHandledException;
public class SaveCommandExecutionListener implements IExecutionListener {
private static long lastSaveAction = 0;
/**
* Returns the time (in milliseconds since The Epoch) of the last save
* action.
*
* @return
*/
public static long getLastSaveAction() {
return lastSaveAction;
}
@Override
public void preExecute(String commandId, ExecutionEvent event) {
if (isFileSave(commandId)) {
lastSaveAction = System.currentTimeMillis();
}
}
private boolean isFileSave(String commandId) {
return commandId.equals("org.eclipse.ui.file.save") || commandId.equalsIgnoreCase("org.eclipse.ui.file.saveAll");
}
@Override
public void postExecuteSuccess(String commandId, Object returnValue) {
}
@Override
public void postExecuteFailure(String commandId,
ExecutionException exception) {
}
@Override
public void notHandled(String commandId, NotHandledException exception) {
}
}
|
...
}
private boolean isFileSave(String commandId) {
return commandId.equals("org.eclipse.ui.file.save") || commandId.equalsIgnoreCase("org.eclipse.ui.file.saveAll");
}
@Override
...
|
78e6cd5fc57c338ac9c61b6e50a5ac4355a5d8b7
|
json-templates/create-template.py
|
json-templates/create-template.py
|
import blank_template
import json
import os
import subprocess
import sys
import tarfile
if __name__ == '__main__':
# Load template
fname = sys.argv[1]
template = blank_template.load_template(fname)
# Generate ova.xml
version = {'hostname': 'golm-2', 'date': '2016-04-29', 'product_version': '7.0.0', 'product_brand': 'XenServer', 'build_number': '125122c', 'xapi_major': '1', 'xapi_minor': '9', 'export_vsn': '2'}
xml = template.toXML(version)
ova_xml = open("ova.xml", "w")
ova_xml.write(xml)
ova_xml.close()
# Generate tarball containing ova.xml
template_name = os.path.splitext(fname)[0]
tar = tarfile.open("%s.tar" % template_name, "w")
tar.add("ova.xml")
tar.close()
os.remove("ova.xml")
# Import XS template
uuid = subprocess.check_output(["xe", "vm-import", "filename=%s.tar" % template_name, "preserve=true"])
# Set default_template = true
out = subprocess.check_output(["xe", "template-param-set", "other-config:default_template=true", "uuid=%s" % uuid.strip()])
|
import blank_template
import json
import os
import subprocess
import sys
import tarfile
if __name__ == '__main__':
# Load template
fname = sys.argv[1]
template = blank_template.load_template(fname)
# Generate ova.xml
version = {'hostname': 'localhost', 'date': '1970-01-01', 'product_version': '7.0.0', 'product_brand': 'XenServer', 'build_number': '0x', 'xapi_major': '1', 'xapi_minor': '9', 'export_vsn': '2'}
xml = template.toXML(version)
ova_xml = open("ova.xml", "w")
ova_xml.write(xml)
ova_xml.close()
# Generate tarball containing ova.xml
template_name = os.path.splitext(fname)[0]
tar = tarfile.open("%s.tar" % template_name, "w")
tar.add("ova.xml")
tar.close()
os.remove("ova.xml")
# Import XS template
uuid = subprocess.check_output(["xe", "vm-import", "filename=%s.tar" % template_name, "preserve=true"])
# Set default_template = true
out = subprocess.check_output(["xe", "template-param-set", "other-config:default_template=true", "uuid=%s" % uuid.strip()])
|
Use more generic values for version
|
Use more generic values for version
|
Python
|
bsd-2-clause
|
xenserver/guest-templates,xenserver/guest-templates
|
python
|
## Code Before:
import blank_template
import json
import os
import subprocess
import sys
import tarfile
if __name__ == '__main__':
# Load template
fname = sys.argv[1]
template = blank_template.load_template(fname)
# Generate ova.xml
version = {'hostname': 'golm-2', 'date': '2016-04-29', 'product_version': '7.0.0', 'product_brand': 'XenServer', 'build_number': '125122c', 'xapi_major': '1', 'xapi_minor': '9', 'export_vsn': '2'}
xml = template.toXML(version)
ova_xml = open("ova.xml", "w")
ova_xml.write(xml)
ova_xml.close()
# Generate tarball containing ova.xml
template_name = os.path.splitext(fname)[0]
tar = tarfile.open("%s.tar" % template_name, "w")
tar.add("ova.xml")
tar.close()
os.remove("ova.xml")
# Import XS template
uuid = subprocess.check_output(["xe", "vm-import", "filename=%s.tar" % template_name, "preserve=true"])
# Set default_template = true
out = subprocess.check_output(["xe", "template-param-set", "other-config:default_template=true", "uuid=%s" % uuid.strip()])
## Instruction:
Use more generic values for version
## Code After:
import blank_template
import json
import os
import subprocess
import sys
import tarfile
if __name__ == '__main__':
# Load template
fname = sys.argv[1]
template = blank_template.load_template(fname)
# Generate ova.xml
version = {'hostname': 'localhost', 'date': '1970-01-01', 'product_version': '7.0.0', 'product_brand': 'XenServer', 'build_number': '0x', 'xapi_major': '1', 'xapi_minor': '9', 'export_vsn': '2'}
xml = template.toXML(version)
ova_xml = open("ova.xml", "w")
ova_xml.write(xml)
ova_xml.close()
# Generate tarball containing ova.xml
template_name = os.path.splitext(fname)[0]
tar = tarfile.open("%s.tar" % template_name, "w")
tar.add("ova.xml")
tar.close()
os.remove("ova.xml")
# Import XS template
uuid = subprocess.check_output(["xe", "vm-import", "filename=%s.tar" % template_name, "preserve=true"])
# Set default_template = true
out = subprocess.check_output(["xe", "template-param-set", "other-config:default_template=true", "uuid=%s" % uuid.strip()])
|
...
template = blank_template.load_template(fname)
# Generate ova.xml
version = {'hostname': 'localhost', 'date': '1970-01-01', 'product_version': '7.0.0', 'product_brand': 'XenServer', 'build_number': '0x', 'xapi_major': '1', 'xapi_minor': '9', 'export_vsn': '2'}
xml = template.toXML(version)
ova_xml = open("ova.xml", "w")
ova_xml.write(xml)
...
|
9ffe8a195af0a2504728e4764d093152959474e8
|
mrp_product_variants/models/procurement.py
|
mrp_product_variants/models/procurement.py
|
from openerp import api, models
class ProcurementOrder(models.Model):
_inherit = 'procurement.order'
@api.model
def _prepare_mo_vals(self, procurement):
result = super(ProcurementOrder, self)._prepare_mo_vals(procurement)
product_id = result.get('product_id')
product = self.env['product.product'].browse(product_id)
result['product_tmpl_id'] = product.product_tmpl_id.id
result['product_attribute_ids'] = (
(0, 0, x) for x in product._get_product_attributes_values_dict())
for val in result['product_attribute_ids']:
val = val[2]
val['product_tmpl_id'] = product.product_tmpl_id.id
val['owner_model'] = 'mrp.production'
return result
|
from openerp import api, models
class ProcurementOrder(models.Model):
_inherit = 'procurement.order'
@api.model
def _prepare_mo_vals(self, procurement):
result = super(ProcurementOrder, self)._prepare_mo_vals(procurement)
product_id = result.get('product_id')
product = self.env['product.product'].browse(product_id)
result['product_tmpl_id'] = product.product_tmpl_id.id
product_attribute_ids = product._get_product_attributes_values_dict()
result['product_attribute_ids'] = map(
lambda x: (0, 0, x), product_attribute_ids)
for val in result['product_attribute_ids']:
val = val[2]
val['product_tmpl_id'] = product.product_tmpl_id.id
val['owner_model'] = 'mrp.production'
return result
|
Fix MTO configurator not filled
|
[FIX] mrp_product_variants: Fix MTO configurator not filled
|
Python
|
agpl-3.0
|
Eficent/odoomrp-wip,oihane/odoomrp-wip,odoomrp/odoomrp-wip,jobiols/odoomrp-wip,esthermm/odoomrp-wip,esthermm/odoomrp-wip,Eficent/odoomrp-wip,jobiols/odoomrp-wip,Daniel-CA/odoomrp-wip-public,diagramsoftware/odoomrp-wip,diagramsoftware/odoomrp-wip,sergiocorato/odoomrp-wip,sergiocorato/odoomrp-wip,factorlibre/odoomrp-wip,factorlibre/odoomrp-wip,Daniel-CA/odoomrp-wip-public,oihane/odoomrp-wip,agaldona/odoomrp-wip-1,odoomrp/odoomrp-wip,agaldona/odoomrp-wip-1
|
python
|
## Code Before:
from openerp import api, models
class ProcurementOrder(models.Model):
_inherit = 'procurement.order'
@api.model
def _prepare_mo_vals(self, procurement):
result = super(ProcurementOrder, self)._prepare_mo_vals(procurement)
product_id = result.get('product_id')
product = self.env['product.product'].browse(product_id)
result['product_tmpl_id'] = product.product_tmpl_id.id
result['product_attribute_ids'] = (
(0, 0, x) for x in product._get_product_attributes_values_dict())
for val in result['product_attribute_ids']:
val = val[2]
val['product_tmpl_id'] = product.product_tmpl_id.id
val['owner_model'] = 'mrp.production'
return result
## Instruction:
[FIX] mrp_product_variants: Fix MTO configurator not filled
## Code After:
from openerp import api, models
class ProcurementOrder(models.Model):
_inherit = 'procurement.order'
@api.model
def _prepare_mo_vals(self, procurement):
result = super(ProcurementOrder, self)._prepare_mo_vals(procurement)
product_id = result.get('product_id')
product = self.env['product.product'].browse(product_id)
result['product_tmpl_id'] = product.product_tmpl_id.id
product_attribute_ids = product._get_product_attributes_values_dict()
result['product_attribute_ids'] = map(
lambda x: (0, 0, x), product_attribute_ids)
for val in result['product_attribute_ids']:
val = val[2]
val['product_tmpl_id'] = product.product_tmpl_id.id
val['owner_model'] = 'mrp.production'
return result
|
# ... existing code ...
product_id = result.get('product_id')
product = self.env['product.product'].browse(product_id)
result['product_tmpl_id'] = product.product_tmpl_id.id
product_attribute_ids = product._get_product_attributes_values_dict()
result['product_attribute_ids'] = map(
lambda x: (0, 0, x), product_attribute_ids)
for val in result['product_attribute_ids']:
val = val[2]
val['product_tmpl_id'] = product.product_tmpl_id.id
# ... rest of the code ...
|
cdb546a9db593d79c2b9935b746e9862a2b1221c
|
winthrop/people/urls.py
|
winthrop/people/urls.py
|
from django.conf.urls import url
from django.contrib.admin.views.decorators import staff_member_required
from winthrop.people.views import ViafAutoSuggest
urlpatterns = [
url(r'^autocomplete/viaf/suggest/$', staff_member_required(ViafAutoSuggest.as_view()),
name='autocomplete-suggest'),
]
|
from django.conf.urls import url
from django.contrib.admin.views.decorators import staff_member_required
from winthrop.people.views import ViafAutoSuggest
urlpatterns = [
url(r'^autocomplete/viaf/suggest/$', staff_member_required(ViafAutoSuggest.as_view()),
name='viaf-autosuggest'),
]
|
Make the url name for autosuggest clearer
|
Make the url name for autosuggest clearer
|
Python
|
apache-2.0
|
Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django
|
python
|
## Code Before:
from django.conf.urls import url
from django.contrib.admin.views.decorators import staff_member_required
from winthrop.people.views import ViafAutoSuggest
urlpatterns = [
url(r'^autocomplete/viaf/suggest/$', staff_member_required(ViafAutoSuggest.as_view()),
name='autocomplete-suggest'),
]
## Instruction:
Make the url name for autosuggest clearer
## Code After:
from django.conf.urls import url
from django.contrib.admin.views.decorators import staff_member_required
from winthrop.people.views import ViafAutoSuggest
urlpatterns = [
url(r'^autocomplete/viaf/suggest/$', staff_member_required(ViafAutoSuggest.as_view()),
name='viaf-autosuggest'),
]
|
# ... existing code ...
urlpatterns = [
url(r'^autocomplete/viaf/suggest/$', staff_member_required(ViafAutoSuggest.as_view()),
name='viaf-autosuggest'),
]
# ... rest of the code ...
|
c8cfce2cd4820d937d10dced4472055921342582
|
cyder/core/ctnr/forms.py
|
cyder/core/ctnr/forms.py
|
from django import forms
from cyder.base.constants import LEVELS
from cyder.base.mixins import UsabilityFormMixin
from cyder.core.ctnr.models import Ctnr
class CtnrForm(forms.ModelForm, UsabilityFormMixin):
class Meta:
model = Ctnr
exclude = ('users',)
def filter_by_ctnr_all(self, ctnr):
pass
class CtnrUserForm(forms.Form):
level = forms.ChoiceField(widget=forms.RadioSelect,
label="Level*",
choices=[item for item in LEVELS.items()])
class CtnrObjectForm(forms.Form):
obj_type = forms.ChoiceField(
widget=forms.RadioSelect,
label='Type*',
choices=(
('user', 'User'),
('domain', 'Domain'),
('range', 'Range'),
('workgroup', 'Workgroup')))
def __init__(self, *args, **kwargs):
obj_perm = kwargs.pop('obj_perm', False)
super(CtnrObjectForm, self).__init__(*args, **kwargs)
if not obj_perm:
self.fields['obj_type'].choices = (('user', 'User'),)
obj = forms.CharField(
widget=forms.TextInput(attrs={'id': 'object-searchbox'}),
label='Search*')
|
from django import forms
from cyder.base.constants import LEVELS
from cyder.base.mixins import UsabilityFormMixin
from cyder.core.ctnr.models import Ctnr
class CtnrForm(forms.ModelForm, UsabilityFormMixin):
class Meta:
model = Ctnr
exclude = ('users', 'domains', 'ranges', 'workgroups')
def filter_by_ctnr_all(self, ctnr):
pass
class CtnrUserForm(forms.Form):
level = forms.ChoiceField(widget=forms.RadioSelect,
label="Level*",
choices=[item for item in LEVELS.items()])
class CtnrObjectForm(forms.Form):
obj_type = forms.ChoiceField(
widget=forms.RadioSelect,
label='Type*',
choices=(
('user', 'User'),
('domain', 'Domain'),
('range', 'Range'),
('workgroup', 'Workgroup')))
def __init__(self, *args, **kwargs):
obj_perm = kwargs.pop('obj_perm', False)
super(CtnrObjectForm, self).__init__(*args, **kwargs)
if not obj_perm:
self.fields['obj_type'].choices = (('user', 'User'),)
obj = forms.CharField(
widget=forms.TextInput(attrs={'id': 'object-searchbox'}),
label='Search*')
|
Remove m2m fields from ctnr edit form
|
Remove m2m fields from ctnr edit form
|
Python
|
bsd-3-clause
|
akeym/cyder,drkitty/cyder,OSU-Net/cyder,akeym/cyder,OSU-Net/cyder,OSU-Net/cyder,murrown/cyder,drkitty/cyder,OSU-Net/cyder,akeym/cyder,murrown/cyder,drkitty/cyder,murrown/cyder,murrown/cyder,drkitty/cyder,akeym/cyder
|
python
|
## Code Before:
from django import forms
from cyder.base.constants import LEVELS
from cyder.base.mixins import UsabilityFormMixin
from cyder.core.ctnr.models import Ctnr
class CtnrForm(forms.ModelForm, UsabilityFormMixin):
class Meta:
model = Ctnr
exclude = ('users',)
def filter_by_ctnr_all(self, ctnr):
pass
class CtnrUserForm(forms.Form):
level = forms.ChoiceField(widget=forms.RadioSelect,
label="Level*",
choices=[item for item in LEVELS.items()])
class CtnrObjectForm(forms.Form):
obj_type = forms.ChoiceField(
widget=forms.RadioSelect,
label='Type*',
choices=(
('user', 'User'),
('domain', 'Domain'),
('range', 'Range'),
('workgroup', 'Workgroup')))
def __init__(self, *args, **kwargs):
obj_perm = kwargs.pop('obj_perm', False)
super(CtnrObjectForm, self).__init__(*args, **kwargs)
if not obj_perm:
self.fields['obj_type'].choices = (('user', 'User'),)
obj = forms.CharField(
widget=forms.TextInput(attrs={'id': 'object-searchbox'}),
label='Search*')
## Instruction:
Remove m2m fields from ctnr edit form
## Code After:
from django import forms
from cyder.base.constants import LEVELS
from cyder.base.mixins import UsabilityFormMixin
from cyder.core.ctnr.models import Ctnr
class CtnrForm(forms.ModelForm, UsabilityFormMixin):
class Meta:
model = Ctnr
exclude = ('users', 'domains', 'ranges', 'workgroups')
def filter_by_ctnr_all(self, ctnr):
pass
class CtnrUserForm(forms.Form):
level = forms.ChoiceField(widget=forms.RadioSelect,
label="Level*",
choices=[item for item in LEVELS.items()])
class CtnrObjectForm(forms.Form):
obj_type = forms.ChoiceField(
widget=forms.RadioSelect,
label='Type*',
choices=(
('user', 'User'),
('domain', 'Domain'),
('range', 'Range'),
('workgroup', 'Workgroup')))
def __init__(self, *args, **kwargs):
obj_perm = kwargs.pop('obj_perm', False)
super(CtnrObjectForm, self).__init__(*args, **kwargs)
if not obj_perm:
self.fields['obj_type'].choices = (('user', 'User'),)
obj = forms.CharField(
widget=forms.TextInput(attrs={'id': 'object-searchbox'}),
label='Search*')
|
...
class CtnrForm(forms.ModelForm, UsabilityFormMixin):
class Meta:
model = Ctnr
exclude = ('users', 'domains', 'ranges', 'workgroups')
def filter_by_ctnr_all(self, ctnr):
pass
...
|
02363de7bdd7a069243da09248816f3caf38b2e6
|
scripts/get-month.py
|
scripts/get-month.py
|
import pandas as pd
import pdfplumber
import requests
import datetime
import re
from io import BytesIO
def parse_date(pdf):
text = pdf.pages[0].extract_text(x_tolerance=5)
date_pat = r"UPDATED:\s+As of (.+)\n"
updated_date = re.search(date_pat, text).group(1)
d = datetime.datetime.strptime(updated_date, "%B %d, %Y")
return d
if __name__ == "__main__":
URL = "https://www.fbi.gov/about-us/cjis/nics/reports/active_records_in_the_nics-index.pdf"
raw = requests.get(URL).content
pdf = pdfplumber.load(BytesIO(raw))
d = parse_date(pdf)
print(d.strftime("%Y-%m"))
|
import pandas as pd
import pdfplumber
import requests
import datetime
import re
from io import BytesIO
def parse_date(pdf):
text = pdf.pages[0].extract_text(x_tolerance=5)
date_pat = r"UPDATED:\s+As of (.+)\n"
updated_date = re.search(date_pat, text).group(1)
d = datetime.datetime.strptime(updated_date, "%B %d, %Y")
return d
if __name__ == "__main__":
URL = "https://www.fbi.gov/file-repository/active_records_in_the_nics-index.pdf"
raw = requests.get(URL).content
pdf = pdfplumber.load(BytesIO(raw))
d = parse_date(pdf)
print(d.strftime("%Y-%m"))
|
Update "Active Records" PDF URL
|
Update "Active Records" PDF URL
|
Python
|
mit
|
BuzzFeedNews/nics-firearm-background-checks
|
python
|
## Code Before:
import pandas as pd
import pdfplumber
import requests
import datetime
import re
from io import BytesIO
def parse_date(pdf):
text = pdf.pages[0].extract_text(x_tolerance=5)
date_pat = r"UPDATED:\s+As of (.+)\n"
updated_date = re.search(date_pat, text).group(1)
d = datetime.datetime.strptime(updated_date, "%B %d, %Y")
return d
if __name__ == "__main__":
URL = "https://www.fbi.gov/about-us/cjis/nics/reports/active_records_in_the_nics-index.pdf"
raw = requests.get(URL).content
pdf = pdfplumber.load(BytesIO(raw))
d = parse_date(pdf)
print(d.strftime("%Y-%m"))
## Instruction:
Update "Active Records" PDF URL
## Code After:
import pandas as pd
import pdfplumber
import requests
import datetime
import re
from io import BytesIO
def parse_date(pdf):
text = pdf.pages[0].extract_text(x_tolerance=5)
date_pat = r"UPDATED:\s+As of (.+)\n"
updated_date = re.search(date_pat, text).group(1)
d = datetime.datetime.strptime(updated_date, "%B %d, %Y")
return d
if __name__ == "__main__":
URL = "https://www.fbi.gov/file-repository/active_records_in_the_nics-index.pdf"
raw = requests.get(URL).content
pdf = pdfplumber.load(BytesIO(raw))
d = parse_date(pdf)
print(d.strftime("%Y-%m"))
|
// ... existing code ...
return d
if __name__ == "__main__":
URL = "https://www.fbi.gov/file-repository/active_records_in_the_nics-index.pdf"
raw = requests.get(URL).content
pdf = pdfplumber.load(BytesIO(raw))
d = parse_date(pdf)
// ... rest of the code ...
|
122e851cd70ae2fa67a69f8e2f553a5aa20f32a5
|
java/com/google/copybara/util/BadExitStatusWithOutputException.java
|
java/com/google/copybara/util/BadExitStatusWithOutputException.java
|
// Copyright 2016 Google Inc. All Rights Reserved.
package com.google.copybara.util;
import com.google.common.base.Preconditions;
import com.google.devtools.build.lib.shell.AbnormalTerminationException;
import com.google.devtools.build.lib.shell.Command;
import com.google.devtools.build.lib.shell.CommandResult;
import java.nio.charset.StandardCharsets;
/**
* An exception that represents a program that did not exit with 0 exit code.
*
* <p>The reason for this class is that {@link Command#execute} doesn't populate {@link
* CommandResult#stderr} when throwing a {@link com.google.devtools.build.lib.shell.BadExitStatusException}
* exception. This class allows us to collect the error and store in this alternative exception.
*/
public class BadExitStatusWithOutputException extends AbnormalTerminationException {
private final CommandOutputWithStatus output;
BadExitStatusWithOutputException(Command command, CommandResult result, String message,
byte[] stdout, byte[] stderr) {
super(command, result, message);
this.output = new CommandOutputWithStatus(result.getTerminationStatus(), stdout, stderr);
}
public CommandOutputWithStatus getOutput() {
return output;
}
}
|
// Copyright 2016 Google Inc. All Rights Reserved.
package com.google.copybara.util;
import com.google.devtools.build.lib.shell.AbnormalTerminationException;
import com.google.devtools.build.lib.shell.Command;
import com.google.devtools.build.lib.shell.CommandResult;
/**
* An exception that represents a program that did not exit with 0 exit code.
*
* <p>The reason for this class is that {@link Command#execute} doesn't populate {@link
* CommandResult#stderr} when throwing a {@link com.google.devtools.build.lib.shell.BadExitStatusException}
* exception. This class allows us to collect the error and store in this alternative exception.
*/
public class BadExitStatusWithOutputException extends AbnormalTerminationException {
private final CommandOutputWithStatus output;
BadExitStatusWithOutputException(Command command, CommandResult result, String message,
byte[] stdout, byte[] stderr) {
super(command, result, message);
this.output = new CommandOutputWithStatus(result.getTerminationStatus(), stdout, stderr);
}
public CommandOutputWithStatus getOutput() {
return output;
}
}
|
Fix unused import lint error
|
Fix unused import lint error
Change-Id: Ib72b049b4991e48b2ac9ffbc3c5585e676edf781
|
Java
|
apache-2.0
|
google/copybara,google/copybara,google/copybara
|
java
|
## Code Before:
// Copyright 2016 Google Inc. All Rights Reserved.
package com.google.copybara.util;
import com.google.common.base.Preconditions;
import com.google.devtools.build.lib.shell.AbnormalTerminationException;
import com.google.devtools.build.lib.shell.Command;
import com.google.devtools.build.lib.shell.CommandResult;
import java.nio.charset.StandardCharsets;
/**
* An exception that represents a program that did not exit with 0 exit code.
*
* <p>The reason for this class is that {@link Command#execute} doesn't populate {@link
* CommandResult#stderr} when throwing a {@link com.google.devtools.build.lib.shell.BadExitStatusException}
* exception. This class allows us to collect the error and store in this alternative exception.
*/
public class BadExitStatusWithOutputException extends AbnormalTerminationException {
private final CommandOutputWithStatus output;
BadExitStatusWithOutputException(Command command, CommandResult result, String message,
byte[] stdout, byte[] stderr) {
super(command, result, message);
this.output = new CommandOutputWithStatus(result.getTerminationStatus(), stdout, stderr);
}
public CommandOutputWithStatus getOutput() {
return output;
}
}
## Instruction:
Fix unused import lint error
Change-Id: Ib72b049b4991e48b2ac9ffbc3c5585e676edf781
## Code After:
// Copyright 2016 Google Inc. All Rights Reserved.
package com.google.copybara.util;
import com.google.devtools.build.lib.shell.AbnormalTerminationException;
import com.google.devtools.build.lib.shell.Command;
import com.google.devtools.build.lib.shell.CommandResult;
/**
* An exception that represents a program that did not exit with 0 exit code.
*
* <p>The reason for this class is that {@link Command#execute} doesn't populate {@link
* CommandResult#stderr} when throwing a {@link com.google.devtools.build.lib.shell.BadExitStatusException}
* exception. This class allows us to collect the error and store in this alternative exception.
*/
public class BadExitStatusWithOutputException extends AbnormalTerminationException {
private final CommandOutputWithStatus output;
BadExitStatusWithOutputException(Command command, CommandResult result, String message,
byte[] stdout, byte[] stderr) {
super(command, result, message);
this.output = new CommandOutputWithStatus(result.getTerminationStatus(), stdout, stderr);
}
public CommandOutputWithStatus getOutput() {
return output;
}
}
|
// ... existing code ...
// Copyright 2016 Google Inc. All Rights Reserved.
package com.google.copybara.util;
import com.google.devtools.build.lib.shell.AbnormalTerminationException;
import com.google.devtools.build.lib.shell.Command;
import com.google.devtools.build.lib.shell.CommandResult;
/**
* An exception that represents a program that did not exit with 0 exit code.
// ... rest of the code ...
|
edec2186f5a83789a5d6a5dbd112c9ff716c3d46
|
src/python/datamodels/output_models.py
|
src/python/datamodels/output_models.py
|
import hashlib
class Store(object):
def __init__(self):
self.id = None
self.name = None
self.location = None
def __repr__(self):
return "%s,%s,%s" % (self.name, self.location.zipcode, self.location.coords)
class Customer(object):
def __init__(self):
self.id = None
self.name = None
self.location = None
def __repr__(self):
return "(%s, %s, %s)" % \
(self.id, self.name, self.location.zipcode)
class Transaction(object):
def __init__(self, customer=None, trans_time=None, purchased_items=None, store=None,
trans_count=None):
self.store = store
self.customer = customer
self.trans_time = trans_time
self.purchased_items = purchased_items
self.trans_count = trans_count
def transaction_id(self):
return hashlib.md5(repr(self)).hexdigest()
def __repr__(self):
return "(%s, %s, %s, %s)" % (self.store.id,
self.customer.id,
self.trans_time,
self.trans_count)
|
import hashlib
class Store(object):
"""
Record for stores.
id -- integer
name -- string
location -- ZipcodeRecord
"""
def __init__(self):
self.id = None
self.name = None
self.location = None
def __repr__(self):
return "%s,%s,%s" % (self.name, self.location.zipcode, self.location.coords)
class Customer(object):
"""
Record for customers.
id -- integer
name -- string
location -- ZipcodeRecord
"""
def __init__(self):
self.id = None
self.name = None
self.location = None
def __repr__(self):
return "(%s, %s, %s)" % \
(self.id, self.name, self.location.zipcode)
class Transaction(object):
"""
Record for transactions
store -- Store
customer -- Customer
trans_time -- transaction time in days since start of simulation. int or long
purchased_items -- list of products purchased
trans_count -- hidden transaction id
"""
def __init__(self, customer=None, trans_time=None, purchased_items=None, store=None,
trans_count=None):
self.store = store
self.customer = customer
self.trans_time = trans_time
self.purchased_items = purchased_items
self.trans_count = trans_count
def transaction_id(self):
"""
Compute transaction id as a hash of the transaction.
Returns a string
"""
return hashlib.md5(repr(self)).hexdigest()
def __repr__(self):
return "(%s, %s, %s, %s)" % (self.store.id,
self.customer.id,
self.trans_time,
self.trans_count)
|
Add docstrings to output models
|
Add docstrings to output models
|
Python
|
apache-2.0
|
rnowling/bigpetstore-data-generator,rnowling/bigpetstore-data-generator,rnowling/bigpetstore-data-generator
|
python
|
## Code Before:
import hashlib
class Store(object):
def __init__(self):
self.id = None
self.name = None
self.location = None
def __repr__(self):
return "%s,%s,%s" % (self.name, self.location.zipcode, self.location.coords)
class Customer(object):
def __init__(self):
self.id = None
self.name = None
self.location = None
def __repr__(self):
return "(%s, %s, %s)" % \
(self.id, self.name, self.location.zipcode)
class Transaction(object):
def __init__(self, customer=None, trans_time=None, purchased_items=None, store=None,
trans_count=None):
self.store = store
self.customer = customer
self.trans_time = trans_time
self.purchased_items = purchased_items
self.trans_count = trans_count
def transaction_id(self):
return hashlib.md5(repr(self)).hexdigest()
def __repr__(self):
return "(%s, %s, %s, %s)" % (self.store.id,
self.customer.id,
self.trans_time,
self.trans_count)
## Instruction:
Add docstrings to output models
## Code After:
import hashlib
class Store(object):
"""
Record for stores.
id -- integer
name -- string
location -- ZipcodeRecord
"""
def __init__(self):
self.id = None
self.name = None
self.location = None
def __repr__(self):
return "%s,%s,%s" % (self.name, self.location.zipcode, self.location.coords)
class Customer(object):
"""
Record for customers.
id -- integer
name -- string
location -- ZipcodeRecord
"""
def __init__(self):
self.id = None
self.name = None
self.location = None
def __repr__(self):
return "(%s, %s, %s)" % \
(self.id, self.name, self.location.zipcode)
class Transaction(object):
"""
Record for transactions
store -- Store
customer -- Customer
trans_time -- transaction time in days since start of simulation. int or long
purchased_items -- list of products purchased
trans_count -- hidden transaction id
"""
def __init__(self, customer=None, trans_time=None, purchased_items=None, store=None,
trans_count=None):
self.store = store
self.customer = customer
self.trans_time = trans_time
self.purchased_items = purchased_items
self.trans_count = trans_count
def transaction_id(self):
"""
Compute transaction id as a hash of the transaction.
Returns a string
"""
return hashlib.md5(repr(self)).hexdigest()
def __repr__(self):
return "(%s, %s, %s, %s)" % (self.store.id,
self.customer.id,
self.trans_time,
self.trans_count)
|
# ... existing code ...
import hashlib
class Store(object):
"""
Record for stores.
id -- integer
name -- string
location -- ZipcodeRecord
"""
def __init__(self):
self.id = None
self.name = None
# ... modified code ...
return "%s,%s,%s" % (self.name, self.location.zipcode, self.location.coords)
class Customer(object):
"""
Record for customers.
id -- integer
name -- string
location -- ZipcodeRecord
"""
def __init__(self):
self.id = None
self.name = None
...
(self.id, self.name, self.location.zipcode)
class Transaction(object):
"""
Record for transactions
store -- Store
customer -- Customer
trans_time -- transaction time in days since start of simulation. int or long
purchased_items -- list of products purchased
trans_count -- hidden transaction id
"""
def __init__(self, customer=None, trans_time=None, purchased_items=None, store=None,
trans_count=None):
self.store = store
...
self.trans_count = trans_count
def transaction_id(self):
"""
Compute transaction id as a hash of the transaction.
Returns a string
"""
return hashlib.md5(repr(self)).hexdigest()
def __repr__(self):
# ... rest of the code ...
|
aaf067d7b63d3af80b40cc098c585bf269e9aa7f
|
uportal-war/src/main/java/org/jasig/portal/portlets/iframe/IFramePortletMinimizedStateHandlerInterceptor.java
|
uportal-war/src/main/java/org/jasig/portal/portlets/iframe/IFramePortletMinimizedStateHandlerInterceptor.java
|
package org.jasig.portal.portlets.iframe;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.WindowState;
import org.springframework.web.portlet.handler.HandlerInterceptorAdapter;
/**
* @author Jen Bourey, [email protected]
* @version $Revision$
*/
public class IFramePortletMinimizedStateHandlerInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandleRender(RenderRequest request, RenderResponse response, Object handler) throws Exception {
if (WindowState.MINIMIZED.equals(request.getWindowState())) {
String url = request.getPreferences().getValue("src", null);
if (url == null) {
url = request.getPreferences().getValue("url", null);
}
response.setProperty("externalPortletLink", url);
return false;
}
return true;
}
}
|
/**
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.portal.portlets.iframe;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.WindowState;
import org.springframework.web.portlet.handler.HandlerInterceptorAdapter;
/**
* @author Jen Bourey, [email protected]
* @version $Revision$
*/
public class IFramePortletMinimizedStateHandlerInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandleRender(RenderRequest request, RenderResponse response, Object handler) throws Exception {
if (WindowState.MINIMIZED.equals(request.getWindowState())) {
String url = request.getPreferences().getValue("src", null);
if (url == null) {
url = request.getPreferences().getValue("url", null);
}
response.setProperty("externalPortletLink", url);
return false;
}
return true;
}
}
|
Fix license headers Fix notice file
|
Fix license headers
Fix notice file
git-svn-id: 477788cc2a8229a747c5b8073e47c1d0f6ec0604@24364 f5dbab47-78f9-eb45-b975-e544023573eb
|
Java
|
apache-2.0
|
unistra/aboutIFrame-portlet
|
java
|
## Code Before:
package org.jasig.portal.portlets.iframe;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.WindowState;
import org.springframework.web.portlet.handler.HandlerInterceptorAdapter;
/**
* @author Jen Bourey, [email protected]
* @version $Revision$
*/
public class IFramePortletMinimizedStateHandlerInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandleRender(RenderRequest request, RenderResponse response, Object handler) throws Exception {
if (WindowState.MINIMIZED.equals(request.getWindowState())) {
String url = request.getPreferences().getValue("src", null);
if (url == null) {
url = request.getPreferences().getValue("url", null);
}
response.setProperty("externalPortletLink", url);
return false;
}
return true;
}
}
## Instruction:
Fix license headers
Fix notice file
git-svn-id: 477788cc2a8229a747c5b8073e47c1d0f6ec0604@24364 f5dbab47-78f9-eb45-b975-e544023573eb
## Code After:
/**
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.portal.portlets.iframe;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.WindowState;
import org.springframework.web.portlet.handler.HandlerInterceptorAdapter;
/**
* @author Jen Bourey, [email protected]
* @version $Revision$
*/
public class IFramePortletMinimizedStateHandlerInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandleRender(RenderRequest request, RenderResponse response, Object handler) throws Exception {
if (WindowState.MINIMIZED.equals(request.getWindowState())) {
String url = request.getPreferences().getValue("src", null);
if (url == null) {
url = request.getPreferences().getValue("url", null);
}
response.setProperty("externalPortletLink", url);
return false;
}
return true;
}
}
|
# ... existing code ...
/**
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.portal.portlets.iframe;
import javax.portlet.RenderRequest;
# ... rest of the code ...
|
69304be6df25ba2db53985b3d1e2e66954b7d655
|
genes/lib/traits.py
|
genes/lib/traits.py
|
from functools import wraps
def if_any(*conds):
def wrapper(func):
@wraps
def run_if_any(*args, **kwargs):
if any(conds):
return func(*args, **kwargs)
return run_if_any
return wrapper
def if_all(*conds):
def wrapper(func):
@wraps
def run_if_all(*args, **kwargs):
if all(conds):
return func(*args, **kwargs)
return run_if_all
return wrapper
|
from functools import wraps
def if_any(*conds):
def wrapper(func):
@wraps(func)
def run_if_any(*args, **kwargs):
if any(conds):
return func(*args, **kwargs)
return run_if_any
return wrapper
def if_all(*conds):
def wrapper(func):
@wraps(func)
def run_if_all(*args, **kwargs):
if all(conds):
return func(*args, **kwargs)
return run_if_all
return wrapper
|
Add argument to @wraps decorator
|
Add argument to @wraps decorator
|
Python
|
mit
|
hatchery/Genepool2,hatchery/genepool
|
python
|
## Code Before:
from functools import wraps
def if_any(*conds):
def wrapper(func):
@wraps
def run_if_any(*args, **kwargs):
if any(conds):
return func(*args, **kwargs)
return run_if_any
return wrapper
def if_all(*conds):
def wrapper(func):
@wraps
def run_if_all(*args, **kwargs):
if all(conds):
return func(*args, **kwargs)
return run_if_all
return wrapper
## Instruction:
Add argument to @wraps decorator
## Code After:
from functools import wraps
def if_any(*conds):
def wrapper(func):
@wraps(func)
def run_if_any(*args, **kwargs):
if any(conds):
return func(*args, **kwargs)
return run_if_any
return wrapper
def if_all(*conds):
def wrapper(func):
@wraps(func)
def run_if_all(*args, **kwargs):
if all(conds):
return func(*args, **kwargs)
return run_if_all
return wrapper
|
...
def if_any(*conds):
def wrapper(func):
@wraps(func)
def run_if_any(*args, **kwargs):
if any(conds):
return func(*args, **kwargs)
...
def if_all(*conds):
def wrapper(func):
@wraps(func)
def run_if_all(*args, **kwargs):
if all(conds):
return func(*args, **kwargs)
...
|
33ca32bd0f8f8670d1632d9fe3d91bccfca6be6e
|
app/src/main/java/com/satsumasoftware/timetable/db/ClassesSchema.java
|
app/src/main/java/com/satsumasoftware/timetable/db/ClassesSchema.java
|
package com.satsumasoftware.timetable.db;
public final class ClassesSchema {
public static final String TABLE_NAME = "classes";
public static final String COL_ID = "id";
public static final String COL_SUBJECT_ID = "subject_id";
public static final String COL_DAY = "day";
public static final String COL_START_TIME = "start_time";
public static final String COL_END_TIME = "end_time";
public static final String COL_ROOM = "room";
public static final String COL_TEACHER = "teacher";
protected static final String SQL_CREATE = "CREATE TABLE " + TABLE_NAME + "( " +
COL_ID + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_SUBJECT_ID + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_DAY + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_START_TIME + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_END_TIME + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_ROOM + SchemaUtilsKt.TEXT_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_TEACHER + SchemaUtilsKt.TEXT_TYPE +
" )";
protected static final String SQL_DELETE =
"DROP TABLE IF EXISTS " + TABLE_NAME;
}
|
package com.satsumasoftware.timetable.db;
public final class ClassesSchema {
public static final String TABLE_NAME = "classes";
public static final String COL_ID = "id";
public static final String COL_SUBJECT_ID = "subject_id";
public static final String COL_DAY = "day";
public static final String COL_START_TIME_HRS = "start_time_hrs";
public static final String COL_START_TIME_MINS = "start_time_mins";
public static final String COL_END_TIME_HRS = "end_time_hrs";
public static final String COL_END_TIME_MINS = "end_time_mins";
public static final String COL_ROOM = "room";
public static final String COL_TEACHER = "teacher";
protected static final String SQL_CREATE = "CREATE TABLE " + TABLE_NAME + "( " +
COL_ID + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_SUBJECT_ID + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_DAY + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_START_TIME_HRS + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_START_TIME_MINS + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_END_TIME_HRS + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_END_TIME_MINS + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_ROOM + SchemaUtilsKt.TEXT_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_TEACHER + SchemaUtilsKt.TEXT_TYPE +
" )";
protected static final String SQL_DELETE =
"DROP TABLE IF EXISTS " + TABLE_NAME;
}
|
Improve the schema for classes to store hours and minutes separately
|
Improve the schema for classes to store hours and minutes separately
|
Java
|
apache-2.0
|
FarbodSalamat-Zadeh/TimetableApp,FarbodSalamat-Zadeh/TimetableApp
|
java
|
## Code Before:
package com.satsumasoftware.timetable.db;
public final class ClassesSchema {
public static final String TABLE_NAME = "classes";
public static final String COL_ID = "id";
public static final String COL_SUBJECT_ID = "subject_id";
public static final String COL_DAY = "day";
public static final String COL_START_TIME = "start_time";
public static final String COL_END_TIME = "end_time";
public static final String COL_ROOM = "room";
public static final String COL_TEACHER = "teacher";
protected static final String SQL_CREATE = "CREATE TABLE " + TABLE_NAME + "( " +
COL_ID + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_SUBJECT_ID + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_DAY + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_START_TIME + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_END_TIME + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_ROOM + SchemaUtilsKt.TEXT_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_TEACHER + SchemaUtilsKt.TEXT_TYPE +
" )";
protected static final String SQL_DELETE =
"DROP TABLE IF EXISTS " + TABLE_NAME;
}
## Instruction:
Improve the schema for classes to store hours and minutes separately
## Code After:
package com.satsumasoftware.timetable.db;
public final class ClassesSchema {
public static final String TABLE_NAME = "classes";
public static final String COL_ID = "id";
public static final String COL_SUBJECT_ID = "subject_id";
public static final String COL_DAY = "day";
public static final String COL_START_TIME_HRS = "start_time_hrs";
public static final String COL_START_TIME_MINS = "start_time_mins";
public static final String COL_END_TIME_HRS = "end_time_hrs";
public static final String COL_END_TIME_MINS = "end_time_mins";
public static final String COL_ROOM = "room";
public static final String COL_TEACHER = "teacher";
protected static final String SQL_CREATE = "CREATE TABLE " + TABLE_NAME + "( " +
COL_ID + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_SUBJECT_ID + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_DAY + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_START_TIME_HRS + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_START_TIME_MINS + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_END_TIME_HRS + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_END_TIME_MINS + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_ROOM + SchemaUtilsKt.TEXT_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_TEACHER + SchemaUtilsKt.TEXT_TYPE +
" )";
protected static final String SQL_DELETE =
"DROP TABLE IF EXISTS " + TABLE_NAME;
}
|
...
public static final String COL_ID = "id";
public static final String COL_SUBJECT_ID = "subject_id";
public static final String COL_DAY = "day";
public static final String COL_START_TIME_HRS = "start_time_hrs";
public static final String COL_START_TIME_MINS = "start_time_mins";
public static final String COL_END_TIME_HRS = "end_time_hrs";
public static final String COL_END_TIME_MINS = "end_time_mins";
public static final String COL_ROOM = "room";
public static final String COL_TEACHER = "teacher";
...
COL_ID + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_SUBJECT_ID + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_DAY + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_START_TIME_HRS + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_START_TIME_MINS + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_END_TIME_HRS + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_END_TIME_MINS + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_ROOM + SchemaUtilsKt.TEXT_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_TEACHER + SchemaUtilsKt.TEXT_TYPE +
" )";
...
|
603fccbbdda5fa45dcc84421901fec085fffcb81
|
test/test_general.py
|
test/test_general.py
|
import hive
import threading
import time
import sys
import worker
# import pash from another directory
import pash
class ErrWorker(worker.Worker):
def work(self, command):
proc = pash.ShellProc()
proc.run(command)
return "Exit code: %s" % proc.get_val('exit_code')
def test():
apiary = hive.Hive()
apiary.create_queen('A1')
apiary.create_queen('A2')
apiary.start_queen('A1')
apiary.start_queen('A2')
data = ["iscsiadm -m discovery -t st -p 192.168.88.110 -I default","iscsiadm -m discovery -t st -p 192.168.90.110 -I iface1","iscsiadm -m discovery -t st -p 192.168.88.110 -I iface0"]
apiary.instruct_queen('A1',data, ErrWorker)
apiary.kill_queen('A1')
time.sleep(3)
this = apiary.die()
for key in this.keys():
for i in this[key]:
print i
sys.exit(0)
|
import threading
import time
import sys
from busybees import worker
from busybees import hive
import pash
class ErrWorker(worker.Worker):
def work(self, command):
proc = pash.ShellProc()
proc.run(command)
return "Exit code: %s" % proc.get_val('exit_code')
def test():
apiary = hive.Hive()
apiary.create_queen('A1')
apiary.create_queen('A2')
apiary.start_queen('A1')
apiary.start_queen('A2')
data = ["iscsiadm -m discovery -t st -p 192.168.88.110 -I default","iscsiadm -m discovery -t st -p 192.168.90.110 -I iface1","iscsiadm -m discovery -t st -p 192.168.88.110 -I iface0"]
apiary.instruct_queen('A1',data, ErrWorker)
apiary.kill_queen('A1')
time.sleep(3)
this = apiary.die()
for key in this.keys():
for i in this[key]:
print i
sys.exit(0)
|
Change imports to work with new scheme
|
Change imports to work with new scheme
|
Python
|
bsd-3-clause
|
iansmcf/busybees
|
python
|
## Code Before:
import hive
import threading
import time
import sys
import worker
# import pash from another directory
import pash
class ErrWorker(worker.Worker):
def work(self, command):
proc = pash.ShellProc()
proc.run(command)
return "Exit code: %s" % proc.get_val('exit_code')
def test():
apiary = hive.Hive()
apiary.create_queen('A1')
apiary.create_queen('A2')
apiary.start_queen('A1')
apiary.start_queen('A2')
data = ["iscsiadm -m discovery -t st -p 192.168.88.110 -I default","iscsiadm -m discovery -t st -p 192.168.90.110 -I iface1","iscsiadm -m discovery -t st -p 192.168.88.110 -I iface0"]
apiary.instruct_queen('A1',data, ErrWorker)
apiary.kill_queen('A1')
time.sleep(3)
this = apiary.die()
for key in this.keys():
for i in this[key]:
print i
sys.exit(0)
## Instruction:
Change imports to work with new scheme
## Code After:
import threading
import time
import sys
from busybees import worker
from busybees import hive
import pash
class ErrWorker(worker.Worker):
def work(self, command):
proc = pash.ShellProc()
proc.run(command)
return "Exit code: %s" % proc.get_val('exit_code')
def test():
apiary = hive.Hive()
apiary.create_queen('A1')
apiary.create_queen('A2')
apiary.start_queen('A1')
apiary.start_queen('A2')
data = ["iscsiadm -m discovery -t st -p 192.168.88.110 -I default","iscsiadm -m discovery -t st -p 192.168.90.110 -I iface1","iscsiadm -m discovery -t st -p 192.168.88.110 -I iface0"]
apiary.instruct_queen('A1',data, ErrWorker)
apiary.kill_queen('A1')
time.sleep(3)
this = apiary.die()
for key in this.keys():
for i in this[key]:
print i
sys.exit(0)
|
...
import threading
import time
import sys
from busybees import worker
from busybees import hive
import pash
class ErrWorker(worker.Worker):
...
proc = pash.ShellProc()
proc.run(command)
return "Exit code: %s" % proc.get_val('exit_code')
def test():
apiary = hive.Hive()
apiary.create_queen('A1')
...
|
659659270ef067baf0edea5de5bb10fdab532eaa
|
run-tests.py
|
run-tests.py
|
from __future__ import print_function
from optparse import OptionParser
from subprocess import Popen
import os
import sys
def run_command(cmdline):
proc = Popen(cmdline, shell=True)
proc.communicate()
return proc.returncode
def main():
parser = OptionParser()
parser.add_option(
'-c', '--coverage',
action='store_true',
help='Measure code coverage')
options, args = parser.parse_args()
if args:
parser.print_help()
return 2
if run_command('which cram >/dev/null') != 0:
print('Error: cram is not installed', file=sys.stderr)
return 1
if options.coverage:
if run_command('which coverage >/dev/null') != 0:
print('Error: coverage is not installed', file=sys.stderr)
return 1
if options.coverage:
run_command('coverage erase')
os.environ['COVERAGE'] = 'yes'
os.environ['COVERAGE_FILE'] = os.path.abspath('.coverage')
run_command('cram test')
if options.coverage:
run_command('coverage report -m')
if __name__ == '__main__':
sys.exit(main() or 0)
|
from __future__ import print_function
from optparse import OptionParser
from subprocess import Popen
import os
import sys
def run_command(cmdline):
proc = Popen(cmdline, shell=True)
proc.communicate()
return proc.returncode
def main():
parser = OptionParser()
parser.add_option(
'-c', '--coverage',
action='store_true',
help='Measure code coverage')
options, args = parser.parse_args()
if args:
parser.print_help()
return 2
if run_command('which cram >/dev/null') != 0:
print('Error: cram is not installed', file=sys.stderr)
return 1
if options.coverage:
if run_command('which coverage >/dev/null') != 0:
print('Error: coverage is not installed', file=sys.stderr)
return 1
if options.coverage:
run_command('coverage erase')
os.environ['COVERAGE'] = 'yes'
os.environ['COVERAGE_FILE'] = os.path.abspath('.coverage')
if 'SALADIR' in os.environ:
# Remove SALADIR from environ to avoid failing tests
del os.environ['SALADIR']
run_command('cram test')
if options.coverage:
run_command('coverage report -m')
if __name__ == '__main__':
sys.exit(main() or 0)
|
Remove SALADIR from environment if present
|
tests: Remove SALADIR from environment if present
|
Python
|
mit
|
akheron/sala,akheron/sala
|
python
|
## Code Before:
from __future__ import print_function
from optparse import OptionParser
from subprocess import Popen
import os
import sys
def run_command(cmdline):
proc = Popen(cmdline, shell=True)
proc.communicate()
return proc.returncode
def main():
parser = OptionParser()
parser.add_option(
'-c', '--coverage',
action='store_true',
help='Measure code coverage')
options, args = parser.parse_args()
if args:
parser.print_help()
return 2
if run_command('which cram >/dev/null') != 0:
print('Error: cram is not installed', file=sys.stderr)
return 1
if options.coverage:
if run_command('which coverage >/dev/null') != 0:
print('Error: coverage is not installed', file=sys.stderr)
return 1
if options.coverage:
run_command('coverage erase')
os.environ['COVERAGE'] = 'yes'
os.environ['COVERAGE_FILE'] = os.path.abspath('.coverage')
run_command('cram test')
if options.coverage:
run_command('coverage report -m')
if __name__ == '__main__':
sys.exit(main() or 0)
## Instruction:
tests: Remove SALADIR from environment if present
## Code After:
from __future__ import print_function
from optparse import OptionParser
from subprocess import Popen
import os
import sys
def run_command(cmdline):
proc = Popen(cmdline, shell=True)
proc.communicate()
return proc.returncode
def main():
parser = OptionParser()
parser.add_option(
'-c', '--coverage',
action='store_true',
help='Measure code coverage')
options, args = parser.parse_args()
if args:
parser.print_help()
return 2
if run_command('which cram >/dev/null') != 0:
print('Error: cram is not installed', file=sys.stderr)
return 1
if options.coverage:
if run_command('which coverage >/dev/null') != 0:
print('Error: coverage is not installed', file=sys.stderr)
return 1
if options.coverage:
run_command('coverage erase')
os.environ['COVERAGE'] = 'yes'
os.environ['COVERAGE_FILE'] = os.path.abspath('.coverage')
if 'SALADIR' in os.environ:
# Remove SALADIR from environ to avoid failing tests
del os.environ['SALADIR']
run_command('cram test')
if options.coverage:
run_command('coverage report -m')
if __name__ == '__main__':
sys.exit(main() or 0)
|
# ... existing code ...
os.environ['COVERAGE'] = 'yes'
os.environ['COVERAGE_FILE'] = os.path.abspath('.coverage')
if 'SALADIR' in os.environ:
# Remove SALADIR from environ to avoid failing tests
del os.environ['SALADIR']
run_command('cram test')
if options.coverage:
# ... rest of the code ...
|
4858a17940ec4b4425f743813c0c1ecef391d967
|
tests/test_file_handling.py
|
tests/test_file_handling.py
|
import os
from format_sql.file_handling import format_file, load_from_file, main
def get_test_file(filename):
test_data = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
filename = os.path.join(test_data, 'tests/data', filename)
return filename
def test_format_empty_file():
filename = get_test_file('empty.py')
format_file(filename)
assert load_from_file(filename) == ''
|
import os
import sys
from format_sql.file_handling import format_file, load_from_file, main
try:
from unittest.mock import patch
except ImportError:
from mock import patch
def get_test_file(filename):
test_data = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
filename = os.path.join(test_data, 'tests/data', filename)
return filename
def test_format_empty_file():
filename = get_test_file('empty.py')
format_file(filename)
assert load_from_file(filename) == ''
def test_main():
sys.argv = ['NULL', 'tests']
with patch('format_sql.file_handling.format_file') as mocked:
main()
assert mocked.call_count == 19
|
Add test for file iteration
|
Add test for file iteration
|
Python
|
bsd-2-clause
|
paetzke/format-sql
|
python
|
## Code Before:
import os
from format_sql.file_handling import format_file, load_from_file, main
def get_test_file(filename):
test_data = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
filename = os.path.join(test_data, 'tests/data', filename)
return filename
def test_format_empty_file():
filename = get_test_file('empty.py')
format_file(filename)
assert load_from_file(filename) == ''
## Instruction:
Add test for file iteration
## Code After:
import os
import sys
from format_sql.file_handling import format_file, load_from_file, main
try:
from unittest.mock import patch
except ImportError:
from mock import patch
def get_test_file(filename):
test_data = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
filename = os.path.join(test_data, 'tests/data', filename)
return filename
def test_format_empty_file():
filename = get_test_file('empty.py')
format_file(filename)
assert load_from_file(filename) == ''
def test_main():
sys.argv = ['NULL', 'tests']
with patch('format_sql.file_handling.format_file') as mocked:
main()
assert mocked.call_count == 19
|
# ... existing code ...
import os
import sys
from format_sql.file_handling import format_file, load_from_file, main
try:
from unittest.mock import patch
except ImportError:
from mock import patch
def get_test_file(filename):
# ... modified code ...
filename = get_test_file('empty.py')
format_file(filename)
assert load_from_file(filename) == ''
def test_main():
sys.argv = ['NULL', 'tests']
with patch('format_sql.file_handling.format_file') as mocked:
main()
assert mocked.call_count == 19
# ... rest of the code ...
|
9a5aee262b5a89e5a22e9e1390e23898a5373627
|
byceps/util/jobqueue.py
|
byceps/util/jobqueue.py
|
from contextlib import contextmanager
from rq import Connection, Queue
from byceps.redis import redis
@contextmanager
def connection():
with Connection(redis.client):
yield
def get_queue(app):
is_async = app.config['JOBS_ASYNC']
return Queue(is_async=is_async)
def enqueue(*args, **kwargs):
"""Add the function call to the queue as a job."""
with connection():
queue = get_queue()
queue.enqueue(*args, **kwargs)
|
from contextlib import contextmanager
from flask import current_app
from rq import Connection, Queue
from byceps.redis import redis
@contextmanager
def connection():
with Connection(redis.client):
yield
def get_queue(app):
is_async = app.config['JOBS_ASYNC']
return Queue(is_async=is_async)
def enqueue(*args, **kwargs):
"""Add the function call to the queue as a job."""
with connection():
queue = get_queue(current_app)
queue.enqueue(*args, **kwargs)
|
Fix `get_queue` call in `enqueue`
|
Fix `get_queue` call in `enqueue`
|
Python
|
bsd-3-clause
|
homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps
|
python
|
## Code Before:
from contextlib import contextmanager
from rq import Connection, Queue
from byceps.redis import redis
@contextmanager
def connection():
with Connection(redis.client):
yield
def get_queue(app):
is_async = app.config['JOBS_ASYNC']
return Queue(is_async=is_async)
def enqueue(*args, **kwargs):
"""Add the function call to the queue as a job."""
with connection():
queue = get_queue()
queue.enqueue(*args, **kwargs)
## Instruction:
Fix `get_queue` call in `enqueue`
## Code After:
from contextlib import contextmanager
from flask import current_app
from rq import Connection, Queue
from byceps.redis import redis
@contextmanager
def connection():
with Connection(redis.client):
yield
def get_queue(app):
is_async = app.config['JOBS_ASYNC']
return Queue(is_async=is_async)
def enqueue(*args, **kwargs):
"""Add the function call to the queue as a job."""
with connection():
queue = get_queue(current_app)
queue.enqueue(*args, **kwargs)
|
// ... existing code ...
from contextlib import contextmanager
from flask import current_app
from rq import Connection, Queue
from byceps.redis import redis
// ... modified code ...
def enqueue(*args, **kwargs):
"""Add the function call to the queue as a job."""
with connection():
queue = get_queue(current_app)
queue.enqueue(*args, **kwargs)
// ... rest of the code ...
|
86a8034101c27ffd9daf15b6cd884c6b511feecc
|
python/protein-translation/protein_translation.py
|
python/protein-translation/protein_translation.py
|
CODON_TO_PROTEIN = {
"AUG": "Methionine",
"UUU": "Phenylalanine",
"UUC": "Phenylalanine",
"UUA": "Leucine",
"UUG": "Leucine",
"UCU": "Serine",
"UCC": "Serine",
"UCA": "Serine",
"UCG": "Serine",
"UGU": "Cysteine",
"UGC": "Cysteine",
"UGG": "Tryptophan",
"UAA": "STOP",
"UAG": "STOP",
"UGA": "STOP"
}
def proteins(strand):
return [CODON_TO_PROTEIN[strand]]
|
CODON_TO_PROTEIN = {
"AUG": "Methionine",
"UUU": "Phenylalanine",
"UUC": "Phenylalanine",
"UUA": "Leucine",
"UUG": "Leucine",
"UCU": "Serine",
"UCC": "Serine",
"UCA": "Serine",
"UCG": "Serine",
"UAU": "Tyrosine",
"UAC": "Tyrosine",
"UGU": "Cysteine",
"UGC": "Cysteine",
"UGG": "Tryptophan",
"UAA": "STOP",
"UAG": "STOP",
"UGA": "STOP"
}
def proteins(strand):
return [CODON_TO_PROTEIN[strand]]
|
Fix mapping for codon keys for Tyrosine
|
Fix mapping for codon keys for Tyrosine
|
Python
|
mit
|
rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism
|
python
|
## Code Before:
CODON_TO_PROTEIN = {
"AUG": "Methionine",
"UUU": "Phenylalanine",
"UUC": "Phenylalanine",
"UUA": "Leucine",
"UUG": "Leucine",
"UCU": "Serine",
"UCC": "Serine",
"UCA": "Serine",
"UCG": "Serine",
"UGU": "Cysteine",
"UGC": "Cysteine",
"UGG": "Tryptophan",
"UAA": "STOP",
"UAG": "STOP",
"UGA": "STOP"
}
def proteins(strand):
return [CODON_TO_PROTEIN[strand]]
## Instruction:
Fix mapping for codon keys for Tyrosine
## Code After:
CODON_TO_PROTEIN = {
"AUG": "Methionine",
"UUU": "Phenylalanine",
"UUC": "Phenylalanine",
"UUA": "Leucine",
"UUG": "Leucine",
"UCU": "Serine",
"UCC": "Serine",
"UCA": "Serine",
"UCG": "Serine",
"UAU": "Tyrosine",
"UAC": "Tyrosine",
"UGU": "Cysteine",
"UGC": "Cysteine",
"UGG": "Tryptophan",
"UAA": "STOP",
"UAG": "STOP",
"UGA": "STOP"
}
def proteins(strand):
return [CODON_TO_PROTEIN[strand]]
|
# ... existing code ...
"UCC": "Serine",
"UCA": "Serine",
"UCG": "Serine",
"UAU": "Tyrosine",
"UAC": "Tyrosine",
"UGU": "Cysteine",
"UGC": "Cysteine",
"UGG": "Tryptophan",
# ... rest of the code ...
|
2b7bdf39497809749c504d10399dffabe52e97ca
|
testutils/base_server.py
|
testutils/base_server.py
|
from testrunner import testhelp
class BaseServer(object):
"Base server class. Responsible with setting up the ports etc."
# We only want standalone repositories to have SSL support added via
# useSSL
sslEnabled = False
def start(self, resetDir = True):
raise NotImplementedError
def cleanup(self):
pass
def stop(self):
raise NotImplementedError
def reset(self):
raise NotImplementedError
def initPort(self):
ports = testhelp.findPorts(num = 1, closeSockets=False)[0]
self.port = ports[0]
self.socket = ports[1]
|
from testrunner import testhelp
class BaseServer(object):
"Base server class. Responsible with setting up the ports etc."
# We only want standalone repositories to have SSL support added via
# useSSL
sslEnabled = False
def start(self, resetDir = True):
raise NotImplementedError
def cleanup(self):
pass
def stop(self):
raise NotImplementedError
def reset(self):
raise NotImplementedError
def isStarted(self):
raise NotImplementedError
def initPort(self):
ports = testhelp.findPorts(num = 1, closeSockets=False)[0]
self.port = ports[0]
self.socket = ports[1]
def __del__(self):
if self.isStarted():
print 'warning: %r was not stopped before freeing' % self
try:
self.stop()
except:
print 'warning: could not stop %r in __del__' % self
|
Implement a noisy __del__ in BaseServer.
|
Implement a noisy __del__ in BaseServer.
It will complain if the server is still running, and attempt to stop it.
|
Python
|
apache-2.0
|
sassoftware/testutils,sassoftware/testutils,sassoftware/testutils
|
python
|
## Code Before:
from testrunner import testhelp
class BaseServer(object):
"Base server class. Responsible with setting up the ports etc."
# We only want standalone repositories to have SSL support added via
# useSSL
sslEnabled = False
def start(self, resetDir = True):
raise NotImplementedError
def cleanup(self):
pass
def stop(self):
raise NotImplementedError
def reset(self):
raise NotImplementedError
def initPort(self):
ports = testhelp.findPorts(num = 1, closeSockets=False)[0]
self.port = ports[0]
self.socket = ports[1]
## Instruction:
Implement a noisy __del__ in BaseServer.
It will complain if the server is still running, and attempt to stop it.
## Code After:
from testrunner import testhelp
class BaseServer(object):
"Base server class. Responsible with setting up the ports etc."
# We only want standalone repositories to have SSL support added via
# useSSL
sslEnabled = False
def start(self, resetDir = True):
raise NotImplementedError
def cleanup(self):
pass
def stop(self):
raise NotImplementedError
def reset(self):
raise NotImplementedError
def isStarted(self):
raise NotImplementedError
def initPort(self):
ports = testhelp.findPorts(num = 1, closeSockets=False)[0]
self.port = ports[0]
self.socket = ports[1]
def __del__(self):
if self.isStarted():
print 'warning: %r was not stopped before freeing' % self
try:
self.stop()
except:
print 'warning: could not stop %r in __del__' % self
|
// ... existing code ...
def reset(self):
raise NotImplementedError
def isStarted(self):
raise NotImplementedError
def initPort(self):
ports = testhelp.findPorts(num = 1, closeSockets=False)[0]
self.port = ports[0]
self.socket = ports[1]
def __del__(self):
if self.isStarted():
print 'warning: %r was not stopped before freeing' % self
try:
self.stop()
except:
print 'warning: could not stop %r in __del__' % self
// ... rest of the code ...
|
5420d368c064953842023ccc07b531b071ec3514
|
src/tests/test_login_page.py
|
src/tests/test_login_page.py
|
from src.lib.page.login import LoginPage
from src.lib.base import BaseTest
class TestLoginPage(BaseTest):
def test_login_as_admin(self):
login_page = LoginPage(self.driver)
login_page.login()
self.driver.find_element_by_css_selector("li.user.user-dropdown.dropdown")
|
from src.lib.page.login import LoginPage
from src.lib.base import BaseTest
from src.lib.constants import selector
class TestLoginPage(BaseTest):
def test_login_as_admin(self):
login_page = LoginPage(self.driver)
login_page.login()
self.driver.find_element_by_css_selector(selector.LoginPage.BUTTON_LOGIN)
|
Modify login page test to use selectors defined in the module constants.
|
Modify login page test to use selectors defined in the module constants.
|
Python
|
apache-2.0
|
edofic/ggrc-core,kr41/ggrc-core,jmakov/ggrc-core,selahssea/ggrc-core,j0gurt/ggrc-core,kr41/ggrc-core,josthkko/ggrc-core,VinnieJohns/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,j0gurt/ggrc-core,plamut/ggrc-core,edofic/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,j0gurt/ggrc-core,prasannav7/ggrc-core,NejcZupec/ggrc-core,jmakov/ggrc-core,josthkko/ggrc-core,VinnieJohns/ggrc-core,NejcZupec/ggrc-core,plamut/ggrc-core,jmakov/ggrc-core,prasannav7/ggrc-core,plamut/ggrc-core,edofic/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,jmakov/ggrc-core,prasannav7/ggrc-core,j0gurt/ggrc-core,kr41/ggrc-core,AleksNeStu/ggrc-core,andrei-karalionak/ggrc-core,andrei-karalionak/ggrc-core,andrei-karalionak/ggrc-core,selahssea/ggrc-core,NejcZupec/ggrc-core,VinnieJohns/ggrc-core,andrei-karalionak/ggrc-core,josthkko/ggrc-core,NejcZupec/ggrc-core,prasannav7/ggrc-core,kr41/ggrc-core,edofic/ggrc-core,jmakov/ggrc-core,josthkko/ggrc-core
|
python
|
## Code Before:
from src.lib.page.login import LoginPage
from src.lib.base import BaseTest
class TestLoginPage(BaseTest):
def test_login_as_admin(self):
login_page = LoginPage(self.driver)
login_page.login()
self.driver.find_element_by_css_selector("li.user.user-dropdown.dropdown")
## Instruction:
Modify login page test to use selectors defined in the module constants.
## Code After:
from src.lib.page.login import LoginPage
from src.lib.base import BaseTest
from src.lib.constants import selector
class TestLoginPage(BaseTest):
def test_login_as_admin(self):
login_page = LoginPage(self.driver)
login_page.login()
self.driver.find_element_by_css_selector(selector.LoginPage.BUTTON_LOGIN)
|
// ... existing code ...
from src.lib.page.login import LoginPage
from src.lib.base import BaseTest
from src.lib.constants import selector
class TestLoginPage(BaseTest):
// ... modified code ...
login_page = LoginPage(self.driver)
login_page.login()
self.driver.find_element_by_css_selector(selector.LoginPage.BUTTON_LOGIN)
// ... rest of the code ...
|
98a2b7e11eb3e0d5ddc89a4d40c3d10586e400ab
|
website/filters/__init__.py
|
website/filters/__init__.py
|
import hashlib
import urllib
# Adapted from https://github.com/zzzsochi/Flask-Gravatar/blob/master/flaskext/gravatar.py
def gravatar(user, use_ssl=False, d=None, r=None, size=None):
if use_ssl:
base_url = 'https://secure.gravatar.com/avatar/'
else:
base_url = 'http://www.gravatar.com/avatar/'
# user can be a User instance or a username string
username = user.username if hasattr(user, 'username') else user
hash_code = hashlib.md5(unicode(username).encode('utf-8')).hexdigest()
url = base_url + '?'
# Order of query params matters, due to a quirk with gravatar
params = [
('s', size),
('d', 'identicon'),
]
if r:
params.append(('r', r))
url = base_url + hash_code + '?' + urllib.urlencode(params)
return url
|
import hashlib
import urllib
# Adapted from https://github.com/zzzsochi/Flask-Gravatar/blob/master/flaskext/gravatar.py
def gravatar(user, use_ssl=False, d=None, r=None, size=None):
if use_ssl:
base_url = 'https://secure.gravatar.com/avatar/'
else:
base_url = 'http://www.gravatar.com/avatar/'
# user can be a User instance or a username string
username = user.username if hasattr(user, 'username') else user
hash_code = hashlib.md5(unicode(username).encode('utf-8')).hexdigest()
url = base_url + '?'
# Order of query params matters, due to a quirk with gravatar
params = [
('d', 'identicon'),
('s', size),
]
if r:
params.append(('r', r))
url = base_url + hash_code + '?' + urllib.urlencode(params)
return url
|
Fix ordering of query params
|
Fix ordering of query params
3rd time's a charm
|
Python
|
apache-2.0
|
mluke93/osf.io,binoculars/osf.io,leb2dg/osf.io,caseyrygt/osf.io,samanehsan/osf.io,cwisecarver/osf.io,petermalcolm/osf.io,kwierman/osf.io,emetsger/osf.io,mluo613/osf.io,wearpants/osf.io,samchrisinger/osf.io,amyshi188/osf.io,jnayak1/osf.io,TomHeatwole/osf.io,petermalcolm/osf.io,TomBaxter/osf.io,amyshi188/osf.io,TomHeatwole/osf.io,doublebits/osf.io,billyhunt/osf.io,crcresearch/osf.io,Ghalko/osf.io,saradbowman/osf.io,monikagrabowska/osf.io,mluo613/osf.io,alexschiller/osf.io,ticklemepierce/osf.io,njantrania/osf.io,caseyrollins/osf.io,zachjanicki/osf.io,brianjgeiger/osf.io,laurenrevere/osf.io,HalcyonChimera/osf.io,laurenrevere/osf.io,doublebits/osf.io,njantrania/osf.io,acshi/osf.io,danielneis/osf.io,mfraezz/osf.io,cslzchen/osf.io,Johnetordoff/osf.io,alexschiller/osf.io,ZobairAlijan/osf.io,caseyrollins/osf.io,KAsante95/osf.io,brandonPurvis/osf.io,kwierman/osf.io,zamattiac/osf.io,mluke93/osf.io,adlius/osf.io,Ghalko/osf.io,cslzchen/osf.io,kwierman/osf.io,DanielSBrown/osf.io,kch8qx/osf.io,mfraezz/osf.io,kwierman/osf.io,SSJohns/osf.io,asanfilippo7/osf.io,icereval/osf.io,RomanZWang/osf.io,alexschiller/osf.io,chennan47/osf.io,GageGaskins/osf.io,caneruguz/osf.io,baylee-d/osf.io,GageGaskins/osf.io,chennan47/osf.io,samanehsan/osf.io,petermalcolm/osf.io,RomanZWang/osf.io,DanielSBrown/osf.io,brianjgeiger/osf.io,kch8qx/osf.io,laurenrevere/osf.io,caseyrygt/osf.io,billyhunt/osf.io,billyhunt/osf.io,jnayak1/osf.io,chrisseto/osf.io,adlius/osf.io,wearpants/osf.io,cwisecarver/osf.io,samchrisinger/osf.io,cwisecarver/osf.io,alexschiller/osf.io,Nesiehr/osf.io,Johnetordoff/osf.io,acshi/osf.io,abought/osf.io,TomBaxter/osf.io,RomanZWang/osf.io,monikagrabowska/osf.io,wearpants/osf.io,binoculars/osf.io,caseyrollins/osf.io,zamattiac/osf.io,KAsante95/osf.io,mattclark/osf.io,felliott/osf.io,ticklemepierce/osf.io,SSJohns/osf.io,brandonPurvis/osf.io,brianjgeiger/osf.io,baylee-d/osf.io,HalcyonChimera/osf.io,HalcyonChimera/osf.io,mluo613/osf.io,zamattiac/osf.io,GageGaskins/osf.io,rdhyee/osf.io,Johnetordoff/osf.io,CenterForOpenScience/osf.io,cslzchen/osf.io,mattclark/osf.io,zachjanicki/osf.io,kch8qx/osf.io,mluke93/osf.io,KAsante95/osf.io,GageGaskins/osf.io,felliott/osf.io,haoyuchen1992/osf.io,erinspace/osf.io,HalcyonChimera/osf.io,hmoco/osf.io,felliott/osf.io,brandonPurvis/osf.io,zachjanicki/osf.io,ZobairAlijan/osf.io,mfraezz/osf.io,DanielSBrown/osf.io,cslzchen/osf.io,amyshi188/osf.io,saradbowman/osf.io,emetsger/osf.io,pattisdr/osf.io,rdhyee/osf.io,monikagrabowska/osf.io,zamattiac/osf.io,rdhyee/osf.io,erinspace/osf.io,haoyuchen1992/osf.io,chrisseto/osf.io,chrisseto/osf.io,Johnetordoff/osf.io,leb2dg/osf.io,samanehsan/osf.io,mluke93/osf.io,abought/osf.io,abought/osf.io,adlius/osf.io,RomanZWang/osf.io,caneruguz/osf.io,njantrania/osf.io,billyhunt/osf.io,erinspace/osf.io,brianjgeiger/osf.io,monikagrabowska/osf.io,SSJohns/osf.io,Nesiehr/osf.io,petermalcolm/osf.io,KAsante95/osf.io,hmoco/osf.io,caneruguz/osf.io,caseyrygt/osf.io,emetsger/osf.io,doublebits/osf.io,jnayak1/osf.io,danielneis/osf.io,danielneis/osf.io,alexschiller/osf.io,pattisdr/osf.io,CenterForOpenScience/osf.io,mattclark/osf.io,kch8qx/osf.io,cosenal/osf.io,caseyrygt/osf.io,kch8qx/osf.io,icereval/osf.io,aaxelb/osf.io,aaxelb/osf.io,crcresearch/osf.io,felliott/osf.io,mluo613/osf.io,haoyuchen1992/osf.io,sloria/osf.io,Ghalko/osf.io,hmoco/osf.io,aaxelb/osf.io,billyhunt/osf.io,cwisecarver/osf.io,RomanZWang/osf.io,samchrisinger/osf.io,GageGaskins/osf.io,jnayak1/osf.io,cosenal/osf.io,rdhyee/osf.io,Nesiehr/osf.io,acshi/osf.io,KAsante95/osf.io,samanehsan/osf.io,emetsger/osf.io,haoyuchen1992/osf.io,danielneis/osf.io,asanfilippo7/osf.io,TomHeatwole/osf.io,leb2dg/osf.io,adlius/osf.io,hmoco/osf.io,CenterForOpenScience/osf.io,cosenal/osf.io,brandonPurvis/osf.io,crcresearch/osf.io,wearpants/osf.io,mluo613/osf.io,ticklemepierce/osf.io,ticklemepierce/osf.io,aaxelb/osf.io,njantrania/osf.io,acshi/osf.io,mfraezz/osf.io,asanfilippo7/osf.io,brandonPurvis/osf.io,ZobairAlijan/osf.io,sloria/osf.io,binoculars/osf.io,CenterForOpenScience/osf.io,acshi/osf.io,asanfilippo7/osf.io,chrisseto/osf.io,DanielSBrown/osf.io,abought/osf.io,leb2dg/osf.io,TomBaxter/osf.io,samchrisinger/osf.io,amyshi188/osf.io,SSJohns/osf.io,doublebits/osf.io,cosenal/osf.io,caneruguz/osf.io,zachjanicki/osf.io,TomHeatwole/osf.io,pattisdr/osf.io,Nesiehr/osf.io,icereval/osf.io,chennan47/osf.io,monikagrabowska/osf.io,baylee-d/osf.io,doublebits/osf.io,sloria/osf.io,Ghalko/osf.io,ZobairAlijan/osf.io
|
python
|
## Code Before:
import hashlib
import urllib
# Adapted from https://github.com/zzzsochi/Flask-Gravatar/blob/master/flaskext/gravatar.py
def gravatar(user, use_ssl=False, d=None, r=None, size=None):
if use_ssl:
base_url = 'https://secure.gravatar.com/avatar/'
else:
base_url = 'http://www.gravatar.com/avatar/'
# user can be a User instance or a username string
username = user.username if hasattr(user, 'username') else user
hash_code = hashlib.md5(unicode(username).encode('utf-8')).hexdigest()
url = base_url + '?'
# Order of query params matters, due to a quirk with gravatar
params = [
('s', size),
('d', 'identicon'),
]
if r:
params.append(('r', r))
url = base_url + hash_code + '?' + urllib.urlencode(params)
return url
## Instruction:
Fix ordering of query params
3rd time's a charm
## Code After:
import hashlib
import urllib
# Adapted from https://github.com/zzzsochi/Flask-Gravatar/blob/master/flaskext/gravatar.py
def gravatar(user, use_ssl=False, d=None, r=None, size=None):
if use_ssl:
base_url = 'https://secure.gravatar.com/avatar/'
else:
base_url = 'http://www.gravatar.com/avatar/'
# user can be a User instance or a username string
username = user.username if hasattr(user, 'username') else user
hash_code = hashlib.md5(unicode(username).encode('utf-8')).hexdigest()
url = base_url + '?'
# Order of query params matters, due to a quirk with gravatar
params = [
('d', 'identicon'),
('s', size),
]
if r:
params.append(('r', r))
url = base_url + hash_code + '?' + urllib.urlencode(params)
return url
|
// ... existing code ...
# Order of query params matters, due to a quirk with gravatar
params = [
('d', 'identicon'),
('s', size),
]
if r:
params.append(('r', r))
// ... rest of the code ...
|
3ee00fad1965dae23f83da870d7df1cb37727c7a
|
structlog/migrations/0001_initial.py
|
structlog/migrations/0001_initial.py
|
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
]
|
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.postgres.operations import HStoreExtension
class Migration(migrations.Migration):
dependencies = [
]
operations = [
HStoreExtension(),
]
|
Add HStore extension to initial migration.
|
Add HStore extension to initial migration.
|
Python
|
bsd-2-clause
|
carlohamalainen/django-struct-log
|
python
|
## Code Before:
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
]
## Instruction:
Add HStore extension to initial migration.
## Code After:
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.postgres.operations import HStoreExtension
class Migration(migrations.Migration):
dependencies = [
]
operations = [
HStoreExtension(),
]
|
# ... existing code ...
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.postgres.operations import HStoreExtension
class Migration(migrations.Migration):
# ... modified code ...
]
operations = [
HStoreExtension(),
]
# ... rest of the code ...
|
7535bd611b26fa81944058c49e7238bd67a5f577
|
forms_builder/wrapper/forms.py
|
forms_builder/wrapper/forms.py
|
from django import forms
from django.forms.models import inlineformset_factory
from forms_builder.forms.models import Form, Field
class FormToBuildForm(forms.ModelForm):
"""
A form that is used to create or edit an instance of ``forms.models.Form``.
"""
class Meta:
model = Form
# A form set to manage adding, modifying, or deleting fields of a form
FieldFormSet = inlineformset_factory(Form, Field, exclude=('slug',), extra=1, can_delete=True)
|
from django import forms
from django.forms.models import inlineformset_factory
from forms_builder.forms.models import Form, Field
class FormToBuildForm(forms.ModelForm):
"""
A form that is used to create or edit an instance of ``forms.models.Form``.
"""
class Meta:
model = Form
exclude = ('sites', 'redirect_url', 'login_required', 'send_email', 'email_from',
'email_copies', 'email_subject', 'email_message')
# A form set to manage adding, modifying, or deleting fields of a form
FieldFormSet = inlineformset_factory(Form, Field, exclude=('slug',), extra=1, can_delete=True)
|
Exclude unnecessary fields for Enjaz
|
Exclude unnecessary fields for Enjaz
|
Python
|
agpl-3.0
|
enjaz/enjaz,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz,osamak/student-portal,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz
|
python
|
## Code Before:
from django import forms
from django.forms.models import inlineformset_factory
from forms_builder.forms.models import Form, Field
class FormToBuildForm(forms.ModelForm):
"""
A form that is used to create or edit an instance of ``forms.models.Form``.
"""
class Meta:
model = Form
# A form set to manage adding, modifying, or deleting fields of a form
FieldFormSet = inlineformset_factory(Form, Field, exclude=('slug',), extra=1, can_delete=True)
## Instruction:
Exclude unnecessary fields for Enjaz
## Code After:
from django import forms
from django.forms.models import inlineformset_factory
from forms_builder.forms.models import Form, Field
class FormToBuildForm(forms.ModelForm):
"""
A form that is used to create or edit an instance of ``forms.models.Form``.
"""
class Meta:
model = Form
exclude = ('sites', 'redirect_url', 'login_required', 'send_email', 'email_from',
'email_copies', 'email_subject', 'email_message')
# A form set to manage adding, modifying, or deleting fields of a form
FieldFormSet = inlineformset_factory(Form, Field, exclude=('slug',), extra=1, can_delete=True)
|
# ... existing code ...
"""
class Meta:
model = Form
exclude = ('sites', 'redirect_url', 'login_required', 'send_email', 'email_from',
'email_copies', 'email_subject', 'email_message')
# A form set to manage adding, modifying, or deleting fields of a form
FieldFormSet = inlineformset_factory(Form, Field, exclude=('slug',), extra=1, can_delete=True)
# ... rest of the code ...
|
5dfd723b37e208c1b81e65cd2df1b7d9226493b3
|
numpy/_array_api/_sorting_functions.py
|
numpy/_array_api/_sorting_functions.py
|
def argsort(x, /, *, axis=-1, descending=False, stable=True):
from .. import argsort
from .. import flip
# Note: this keyword argument is different, and the default is different.
kind = 'stable' if stable else 'quicksort'
res = argsort(x, axis=axis, kind=kind)
if descending:
res = flip(res, axis=axis)
def sort(x, /, *, axis=-1, descending=False, stable=True):
from .. import sort
from .. import flip
# Note: this keyword argument is different, and the default is different.
kind = 'stable' if stable else 'quicksort'
res = sort(x, axis=axis, kind=kind)
if descending:
res = flip(res, axis=axis)
|
def argsort(x, /, *, axis=-1, descending=False, stable=True):
from .. import argsort
from .. import flip
# Note: this keyword argument is different, and the default is different.
kind = 'stable' if stable else 'quicksort'
res = argsort(x, axis=axis, kind=kind)
if descending:
res = flip(res, axis=axis)
return res
def sort(x, /, *, axis=-1, descending=False, stable=True):
from .. import sort
from .. import flip
# Note: this keyword argument is different, and the default is different.
kind = 'stable' if stable else 'quicksort'
res = sort(x, axis=axis, kind=kind)
if descending:
res = flip(res, axis=axis)
return res
|
Add missing returns to the array API sorting functions
|
Add missing returns to the array API sorting functions
|
Python
|
mit
|
cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy
|
python
|
## Code Before:
def argsort(x, /, *, axis=-1, descending=False, stable=True):
from .. import argsort
from .. import flip
# Note: this keyword argument is different, and the default is different.
kind = 'stable' if stable else 'quicksort'
res = argsort(x, axis=axis, kind=kind)
if descending:
res = flip(res, axis=axis)
def sort(x, /, *, axis=-1, descending=False, stable=True):
from .. import sort
from .. import flip
# Note: this keyword argument is different, and the default is different.
kind = 'stable' if stable else 'quicksort'
res = sort(x, axis=axis, kind=kind)
if descending:
res = flip(res, axis=axis)
## Instruction:
Add missing returns to the array API sorting functions
## Code After:
def argsort(x, /, *, axis=-1, descending=False, stable=True):
from .. import argsort
from .. import flip
# Note: this keyword argument is different, and the default is different.
kind = 'stable' if stable else 'quicksort'
res = argsort(x, axis=axis, kind=kind)
if descending:
res = flip(res, axis=axis)
return res
def sort(x, /, *, axis=-1, descending=False, stable=True):
from .. import sort
from .. import flip
# Note: this keyword argument is different, and the default is different.
kind = 'stable' if stable else 'quicksort'
res = sort(x, axis=axis, kind=kind)
if descending:
res = flip(res, axis=axis)
return res
|
// ... existing code ...
res = argsort(x, axis=axis, kind=kind)
if descending:
res = flip(res, axis=axis)
return res
def sort(x, /, *, axis=-1, descending=False, stable=True):
from .. import sort
// ... modified code ...
res = sort(x, axis=axis, kind=kind)
if descending:
res = flip(res, axis=axis)
return res
// ... rest of the code ...
|
f1df5f74699a152d8dc2cac8e4dcf80a1523ca99
|
setup.py
|
setup.py
|
from distutils.core import setup
setup(name='dshelpers',
version='1.3.0',
description="Provides some helper functions used by the ScraperWiki Data Services team.",
long_description="Provides some helper functions used by the ScraperWiki Data Services team.",
classifiers=["Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
],
author="ScraperWiki Limited",
author_email='[email protected]',
url='https://github.com/scraperwiki/data-services-helpers',
license='BSD',
py_modules=['dshelpers'],
install_requires=['requests',
'requests_cache',
'mock',
'nose',
'scraperwiki'],
)
|
from distutils.core import setup
setup(name='dshelpers',
version='1.3.0',
description="Provides some helper functions used by The Sensible Code Company's Data Services team.",
long_description="Provides some helper functions used by the The Sensible Code Company's Data Services team.",
classifiers=["Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
],
author="The Sensible Code Company Limited",
author_email='[email protected]',
url='https://github.com/scraperwiki/data-services-helpers',
license='BSD',
py_modules=['dshelpers'],
install_requires=['requests',
'requests_cache',
'mock',
'nose',
'scraperwiki'],
)
|
Rename ScraperWiki to Sensible Code in README
|
Rename ScraperWiki to Sensible Code in README
|
Python
|
bsd-2-clause
|
scraperwiki/data-services-helpers
|
python
|
## Code Before:
from distutils.core import setup
setup(name='dshelpers',
version='1.3.0',
description="Provides some helper functions used by the ScraperWiki Data Services team.",
long_description="Provides some helper functions used by the ScraperWiki Data Services team.",
classifiers=["Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
],
author="ScraperWiki Limited",
author_email='[email protected]',
url='https://github.com/scraperwiki/data-services-helpers',
license='BSD',
py_modules=['dshelpers'],
install_requires=['requests',
'requests_cache',
'mock',
'nose',
'scraperwiki'],
)
## Instruction:
Rename ScraperWiki to Sensible Code in README
## Code After:
from distutils.core import setup
setup(name='dshelpers',
version='1.3.0',
description="Provides some helper functions used by The Sensible Code Company's Data Services team.",
long_description="Provides some helper functions used by the The Sensible Code Company's Data Services team.",
classifiers=["Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
],
author="The Sensible Code Company Limited",
author_email='[email protected]',
url='https://github.com/scraperwiki/data-services-helpers',
license='BSD',
py_modules=['dshelpers'],
install_requires=['requests',
'requests_cache',
'mock',
'nose',
'scraperwiki'],
)
|
# ... existing code ...
from distutils.core import setup
setup(name='dshelpers',
version='1.3.0',
description="Provides some helper functions used by The Sensible Code Company's Data Services team.",
long_description="Provides some helper functions used by the The Sensible Code Company's Data Services team.",
classifiers=["Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
# ... modified code ...
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
],
author="The Sensible Code Company Limited",
author_email='[email protected]',
url='https://github.com/scraperwiki/data-services-helpers',
license='BSD',
# ... rest of the code ...
|
ad415f26eec5c6a20c26123ccb6ce3e320ea9a69
|
zou/app/blueprints/crud/asset_instance.py
|
zou/app/blueprints/crud/asset_instance.py
|
from zou.app.models.asset_instance import AssetInstance
from zou.app.services import assets_service, user_service
from zou.app.utils import permissions
from .base import BaseModelResource, BaseModelsResource
class AssetInstancesResource(BaseModelsResource):
def __init__(self):
BaseModelsResource.__init__(self, AssetInstance)
class AssetInstanceResource(BaseModelResource):
def __init__(self):
BaseModelResource.__init__(self, AssetInstance)
def check_read_permissions(self, instance):
if permissions.has_manager_permissions():
return True
else:
asset_instance = self.get_model_or_404(instance["id"])
asset = assets_service.get_asset(asset_instance.asset_id)
return user_service.check_has_task_related(asset["project_id"])
def check_update_permissions(self, asset_instance, data):
if permissions.has_manager_permissions():
return True
else:
return user_service.check_working_on_entity(
asset_instance["entity_id"]
)
|
from zou.app.models.asset_instance import AssetInstance
from zou.app.services import assets_service, user_service
from zou.app.utils import permissions
from .base import BaseModelResource, BaseModelsResource
class AssetInstancesResource(BaseModelsResource):
def __init__(self):
BaseModelsResource.__init__(self, AssetInstance)
class AssetInstanceResource(BaseModelResource):
def __init__(self):
BaseModelResource.__init__(self, AssetInstance)
self.protected_fields.append(["number"])
def check_read_permissions(self, instance):
if permissions.has_manager_permissions():
return True
else:
asset_instance = self.get_model_or_404(instance["id"])
asset = assets_service.get_asset(asset_instance.asset_id)
return user_service.check_has_task_related(asset["project_id"])
def check_update_permissions(self, asset_instance, data):
if permissions.has_manager_permissions():
return True
else:
asset = assets_service.get_asset(asset_instance["asset_id"])
return user_service.check_has_task_related(asset["project_id"])
|
Change asset instance update permissions
|
Change asset instance update permissions
* Do not allow to change instance number
* Allow to change instance name by a CG artist
|
Python
|
agpl-3.0
|
cgwire/zou
|
python
|
## Code Before:
from zou.app.models.asset_instance import AssetInstance
from zou.app.services import assets_service, user_service
from zou.app.utils import permissions
from .base import BaseModelResource, BaseModelsResource
class AssetInstancesResource(BaseModelsResource):
def __init__(self):
BaseModelsResource.__init__(self, AssetInstance)
class AssetInstanceResource(BaseModelResource):
def __init__(self):
BaseModelResource.__init__(self, AssetInstance)
def check_read_permissions(self, instance):
if permissions.has_manager_permissions():
return True
else:
asset_instance = self.get_model_or_404(instance["id"])
asset = assets_service.get_asset(asset_instance.asset_id)
return user_service.check_has_task_related(asset["project_id"])
def check_update_permissions(self, asset_instance, data):
if permissions.has_manager_permissions():
return True
else:
return user_service.check_working_on_entity(
asset_instance["entity_id"]
)
## Instruction:
Change asset instance update permissions
* Do not allow to change instance number
* Allow to change instance name by a CG artist
## Code After:
from zou.app.models.asset_instance import AssetInstance
from zou.app.services import assets_service, user_service
from zou.app.utils import permissions
from .base import BaseModelResource, BaseModelsResource
class AssetInstancesResource(BaseModelsResource):
def __init__(self):
BaseModelsResource.__init__(self, AssetInstance)
class AssetInstanceResource(BaseModelResource):
def __init__(self):
BaseModelResource.__init__(self, AssetInstance)
self.protected_fields.append(["number"])
def check_read_permissions(self, instance):
if permissions.has_manager_permissions():
return True
else:
asset_instance = self.get_model_or_404(instance["id"])
asset = assets_service.get_asset(asset_instance.asset_id)
return user_service.check_has_task_related(asset["project_id"])
def check_update_permissions(self, asset_instance, data):
if permissions.has_manager_permissions():
return True
else:
asset = assets_service.get_asset(asset_instance["asset_id"])
return user_service.check_has_task_related(asset["project_id"])
|
// ... existing code ...
def __init__(self):
BaseModelResource.__init__(self, AssetInstance)
self.protected_fields.append(["number"])
def check_read_permissions(self, instance):
if permissions.has_manager_permissions():
// ... modified code ...
if permissions.has_manager_permissions():
return True
else:
asset = assets_service.get_asset(asset_instance["asset_id"])
return user_service.check_has_task_related(asset["project_id"])
// ... rest of the code ...
|
03d817c853ccfdbe7cddf8103948bc342350907c
|
applicationinsights-android/src/main/java/com/microsoft/applicationinsights/logging/InternalLogging.java
|
applicationinsights-android/src/main/java/com/microsoft/applicationinsights/logging/InternalLogging.java
|
package com.microsoft.applicationinsights.logging;
import android.util.Log;
import com.microsoft.applicationinsights.library.ApplicationInsights;
public class InternalLogging {
private static final String PREFIX = InternalLogging.class.getPackage().getName();
private InternalLogging() {
// hide default constructor
}
/**
* Inform SDK users about SDK activities. This has 3 parameters to avoid the string
* concatenation then verbose mode is disabled.
*
* @param tag the log context
* @param message the log message
* @param payload the payload for the message
*/
public static void info(String tag, String message, String payload) {
if (ApplicationInsights.isDeveloperMode()) {
Log.i(PREFIX + tag, message + ":" + payload);
}
}
/**
* Warn SDK users about non-critical SDK misuse
*
* @param tag the log context
* @param message the log message
*/
public static void warn(String tag, String message) {
if (ApplicationInsights.isDeveloperMode()) {
Log.w(PREFIX + tag, message);
}
}
/**
* Log critical SDK error
*
* @param tag the log context
* @param message the log message
*/
public static void error(String tag, String message) {
Log.e(PREFIX + tag, message);
}
}
|
package com.microsoft.applicationinsights.logging;
import android.util.Log;
import com.microsoft.applicationinsights.library.ApplicationInsights;
public class InternalLogging {
private static final String PREFIX = InternalLogging.class.getPackage().getName();
private InternalLogging() {
// hide default constructor
}
/**
* Inform SDK users about SDK activities. This has 3 parameters to avoid the string
* concatenation then verbose mode is disabled.
*
* @param tag the log context
* @param message the log message
* @param payload the payload for the message
*/
public static void info(String tag, String message, String payload) {
if (ApplicationInsights.isDeveloperMode()) {
Log.i(PREFIX + " " + tag, message + ":" + payload);
}
}
/**
* Warn SDK users about non-critical SDK misuse
*
* @param tag the log context
* @param message the log message
*/
public static void warn(String tag, String message) {
if (ApplicationInsights.isDeveloperMode()) {
Log.w(PREFIX + " " + tag, message);
}
}
/**
* Log critical SDK error
*
* @param tag the log context
* @param message the log message
*/
public static void error(String tag, String message) {
Log.e(PREFIX + " " + tag, message);
}
}
|
Add empty space to logging output
|
Add empty space to logging output
|
Java
|
mit
|
Microsoft/ApplicationInsights-Android,tsdl2013/ApplicationInsights-Android,Microsoft/ApplicationInsights-Android,Microsoft/ApplicationInsights-Android,tsdl2013/ApplicationInsights-Android,tsdl2013/ApplicationInsights-Android
|
java
|
## Code Before:
package com.microsoft.applicationinsights.logging;
import android.util.Log;
import com.microsoft.applicationinsights.library.ApplicationInsights;
public class InternalLogging {
private static final String PREFIX = InternalLogging.class.getPackage().getName();
private InternalLogging() {
// hide default constructor
}
/**
* Inform SDK users about SDK activities. This has 3 parameters to avoid the string
* concatenation then verbose mode is disabled.
*
* @param tag the log context
* @param message the log message
* @param payload the payload for the message
*/
public static void info(String tag, String message, String payload) {
if (ApplicationInsights.isDeveloperMode()) {
Log.i(PREFIX + tag, message + ":" + payload);
}
}
/**
* Warn SDK users about non-critical SDK misuse
*
* @param tag the log context
* @param message the log message
*/
public static void warn(String tag, String message) {
if (ApplicationInsights.isDeveloperMode()) {
Log.w(PREFIX + tag, message);
}
}
/**
* Log critical SDK error
*
* @param tag the log context
* @param message the log message
*/
public static void error(String tag, String message) {
Log.e(PREFIX + tag, message);
}
}
## Instruction:
Add empty space to logging output
## Code After:
package com.microsoft.applicationinsights.logging;
import android.util.Log;
import com.microsoft.applicationinsights.library.ApplicationInsights;
public class InternalLogging {
private static final String PREFIX = InternalLogging.class.getPackage().getName();
private InternalLogging() {
// hide default constructor
}
/**
* Inform SDK users about SDK activities. This has 3 parameters to avoid the string
* concatenation then verbose mode is disabled.
*
* @param tag the log context
* @param message the log message
* @param payload the payload for the message
*/
public static void info(String tag, String message, String payload) {
if (ApplicationInsights.isDeveloperMode()) {
Log.i(PREFIX + " " + tag, message + ":" + payload);
}
}
/**
* Warn SDK users about non-critical SDK misuse
*
* @param tag the log context
* @param message the log message
*/
public static void warn(String tag, String message) {
if (ApplicationInsights.isDeveloperMode()) {
Log.w(PREFIX + " " + tag, message);
}
}
/**
* Log critical SDK error
*
* @param tag the log context
* @param message the log message
*/
public static void error(String tag, String message) {
Log.e(PREFIX + " " + tag, message);
}
}
|
// ... existing code ...
*/
public static void info(String tag, String message, String payload) {
if (ApplicationInsights.isDeveloperMode()) {
Log.i(PREFIX + " " + tag, message + ":" + payload);
}
}
// ... modified code ...
*/
public static void warn(String tag, String message) {
if (ApplicationInsights.isDeveloperMode()) {
Log.w(PREFIX + " " + tag, message);
}
}
...
* @param message the log message
*/
public static void error(String tag, String message) {
Log.e(PREFIX + " " + tag, message);
}
}
// ... rest of the code ...
|
b1963f00e5290c11654eefbd24fbce185bbcd8b4
|
packages/Preferences/define.py
|
packages/Preferences/define.py
|
import os
_CURRENTPATH = os.path.dirname(os.path.realpath(__file__))
preferencesIconPath = os.path.join(_CURRENTPATH, 'static', 'gear.svg')
preferencesUIPath = os.path.join(_CURRENTPATH, 'ui', 'preferences.ui')
version = '0.1.0'
|
import os
_CURRENTPATH = os.path.dirname(os.path.realpath(__file__))
config_name = 'mantle_config.ini'
preferencesIconPath = os.path.join(_CURRENTPATH, 'static', 'gear.svg')
preferencesUIPath = os.path.join(_CURRENTPATH, 'ui', 'preferences.ui')
version = '0.1.0'
|
Add config ini file name.
|
Add config ini file name.
|
Python
|
mit
|
takavfx/Mantle
|
python
|
## Code Before:
import os
_CURRENTPATH = os.path.dirname(os.path.realpath(__file__))
preferencesIconPath = os.path.join(_CURRENTPATH, 'static', 'gear.svg')
preferencesUIPath = os.path.join(_CURRENTPATH, 'ui', 'preferences.ui')
version = '0.1.0'
## Instruction:
Add config ini file name.
## Code After:
import os
_CURRENTPATH = os.path.dirname(os.path.realpath(__file__))
config_name = 'mantle_config.ini'
preferencesIconPath = os.path.join(_CURRENTPATH, 'static', 'gear.svg')
preferencesUIPath = os.path.join(_CURRENTPATH, 'ui', 'preferences.ui')
version = '0.1.0'
|
// ... existing code ...
import os
_CURRENTPATH = os.path.dirname(os.path.realpath(__file__))
config_name = 'mantle_config.ini'
preferencesIconPath = os.path.join(_CURRENTPATH, 'static', 'gear.svg')
preferencesUIPath = os.path.join(_CURRENTPATH, 'ui', 'preferences.ui')
// ... rest of the code ...
|
64fee3eb2a142a8c36282d091d786ce9871ad3ba
|
400-IoTGateway/src/main/java/com/ociweb/gateway/IoTApp.java
|
400-IoTGateway/src/main/java/com/ociweb/gateway/IoTApp.java
|
package com.ociweb.gateway;
import com.ociweb.iot.maker.DeviceRuntime;
import com.ociweb.iot.maker.Hardware;
import com.ociweb.iot.maker.IoTSetup;
public class IoTApp implements IoTSetup
{
private static String brokerURI;
private static String clientId;
private static String kafkaURI;
public static void main( String[] args ) {
//parse the optional command line arguments
brokerURI = DeviceRuntime.getOptArg("--brokerURI", "-br", args, "tcp://localhost:1883");;
clientId = DeviceRuntime.getOptArg("--clientId", "-id", args, "unknownGateway");
kafkaURI = DeviceRuntime.getOptArg("--kafkaURI", "-ku", args, "ec2-54-149-45-216.us-west-2.compute.amazonaws.com:9092");
DeviceRuntime.run(new IoTApp());
}
@Override
public void declareConnections(Hardware c) {
}
@Override
public void declareBehavior(DeviceRuntime runtime) {
runtime.addStartupListener(new SubscribeDataMQTT(runtime, "#", "localPub", brokerURI, clientId ));
runtime.addPubSubListener(new PublishKafka(runtime, kafkaURI)).addSubscription("localPub");
}
}
|
package com.ociweb.gateway;
import com.ociweb.iot.maker.DeviceRuntime;
import com.ociweb.iot.maker.Hardware;
import com.ociweb.iot.maker.IoTSetup;
public class IoTApp implements IoTSetup
{
private static String brokerURI;
private static String clientId;
private static String kafkaURI;
public static void main( String[] args ) {
//parse the optional command line arguments
brokerURI = DeviceRuntime.getOptArg("--brokerURI", "-br", args, "tcp://localhost:1883");;
clientId = DeviceRuntime.getOptArg("--clientId", "-id", args, "unknownGateway");
kafkaURI = DeviceRuntime.getOptArg("--kafkaURI", "-ku", args, "localhost:9092");
DeviceRuntime.run(new IoTApp());
}
@Override
public void declareConnections(Hardware c) {
}
@Override
public void declareBehavior(DeviceRuntime runtime) {
runtime.addStartupListener(new SubscribeDataMQTT(runtime, "#", "localPub", brokerURI, clientId ));
runtime.addPubSubListener(new PublishKafka(runtime, kafkaURI)).addSubscription("localPub");
}
}
|
Change default KafkaURI to localhost
|
Change default KafkaURI to localhost
|
Java
|
bsd-3-clause
|
oci-pronghorn/FogLight,oci-pronghorn/PronghornIoT,oci-pronghorn/PronghornIoT-Examples,oci-pronghorn/FogLight,oci-pronghorn/FogLight,oci-pronghorn/PronghornIoT-Examples,oci-pronghorn/PronghornIoT
|
java
|
## Code Before:
package com.ociweb.gateway;
import com.ociweb.iot.maker.DeviceRuntime;
import com.ociweb.iot.maker.Hardware;
import com.ociweb.iot.maker.IoTSetup;
public class IoTApp implements IoTSetup
{
private static String brokerURI;
private static String clientId;
private static String kafkaURI;
public static void main( String[] args ) {
//parse the optional command line arguments
brokerURI = DeviceRuntime.getOptArg("--brokerURI", "-br", args, "tcp://localhost:1883");;
clientId = DeviceRuntime.getOptArg("--clientId", "-id", args, "unknownGateway");
kafkaURI = DeviceRuntime.getOptArg("--kafkaURI", "-ku", args, "ec2-54-149-45-216.us-west-2.compute.amazonaws.com:9092");
DeviceRuntime.run(new IoTApp());
}
@Override
public void declareConnections(Hardware c) {
}
@Override
public void declareBehavior(DeviceRuntime runtime) {
runtime.addStartupListener(new SubscribeDataMQTT(runtime, "#", "localPub", brokerURI, clientId ));
runtime.addPubSubListener(new PublishKafka(runtime, kafkaURI)).addSubscription("localPub");
}
}
## Instruction:
Change default KafkaURI to localhost
## Code After:
package com.ociweb.gateway;
import com.ociweb.iot.maker.DeviceRuntime;
import com.ociweb.iot.maker.Hardware;
import com.ociweb.iot.maker.IoTSetup;
public class IoTApp implements IoTSetup
{
private static String brokerURI;
private static String clientId;
private static String kafkaURI;
public static void main( String[] args ) {
//parse the optional command line arguments
brokerURI = DeviceRuntime.getOptArg("--brokerURI", "-br", args, "tcp://localhost:1883");;
clientId = DeviceRuntime.getOptArg("--clientId", "-id", args, "unknownGateway");
kafkaURI = DeviceRuntime.getOptArg("--kafkaURI", "-ku", args, "localhost:9092");
DeviceRuntime.run(new IoTApp());
}
@Override
public void declareConnections(Hardware c) {
}
@Override
public void declareBehavior(DeviceRuntime runtime) {
runtime.addStartupListener(new SubscribeDataMQTT(runtime, "#", "localPub", brokerURI, clientId ));
runtime.addPubSubListener(new PublishKafka(runtime, kafkaURI)).addSubscription("localPub");
}
}
|
// ... existing code ...
//parse the optional command line arguments
brokerURI = DeviceRuntime.getOptArg("--brokerURI", "-br", args, "tcp://localhost:1883");;
clientId = DeviceRuntime.getOptArg("--clientId", "-id", args, "unknownGateway");
kafkaURI = DeviceRuntime.getOptArg("--kafkaURI", "-ku", args, "localhost:9092");
DeviceRuntime.run(new IoTApp());
}
// ... rest of the code ...
|
9dc90727df23e655e5c921ca84cb98b7d5ae5eb2
|
example_game.py
|
example_game.py
|
from pygametemplate import Game
class ExampleGame(Game):
def logic(self):
pass
def draw(self):
pass
def quit(self):
pass
|
from pygametemplate import Game
class ExampleGame(Game):
def logic(self):
pass
def draw(self):
pass
|
Remove now unnecessary quit() method from ExampleGame
|
Remove now unnecessary quit() method from ExampleGame
|
Python
|
mit
|
AndyDeany/pygame-template
|
python
|
## Code Before:
from pygametemplate import Game
class ExampleGame(Game):
def logic(self):
pass
def draw(self):
pass
def quit(self):
pass
## Instruction:
Remove now unnecessary quit() method from ExampleGame
## Code After:
from pygametemplate import Game
class ExampleGame(Game):
def logic(self):
pass
def draw(self):
pass
|
# ... existing code ...
def draw(self):
pass
# ... rest of the code ...
|
61e792e1c4d41d2a0e3f3433b39f364a5c1df144
|
daybed/tests/test_id_generators.py
|
daybed/tests/test_id_generators.py
|
try:
from unittest2 import TestCase
except ImportError:
from unittest import TestCase # flake8: noqa
import six
from mock import patch
from daybed.backends.id_generators import KoremutakeGenerator
class KoremutakeGeneratorTest(TestCase):
def test_it_defaults_the_max_bytes_to_4(self):
generator = KoremutakeGenerator()
self.assertEquals(generator.max_bytes, 4)
@patch('koremutake.encode')
def test_it_doesnt_reuse_a_name_twice(self, encode):
encode.side_effect = ['existing-value', 'new-value']
created = ['existing-value']
def _exists(key):
return key in created
generator = KoremutakeGenerator()
self.assertEquals(generator(key_exist=_exists), 'new-value')
def test_it_returns_a_string_with_a_max_size(self):
generator = KoremutakeGenerator()
uid = generator()
self.assertTrue(len(uid) <= 24)
self.assertIsInstance(uid, six.text_type)
|
try:
from unittest2 import TestCase
except ImportError:
from unittest import TestCase # flake8: noqa
import six
from mock import patch
from daybed.backends.id_generators import KoremutakeGenerator
class KoremutakeGeneratorTest(TestCase):
def setUp(self):
self.generator = KoremutakeGenerator()
def test_it_defaults_the_max_bytes_to_4(self):
self.assertEquals(generator.max_bytes, 4)
@patch('koremutake.encode')
def test_it_doesnt_reuse_a_name_twice(self, encode):
encode.side_effect = ['existing-value', 'new-value']
created = ['existing-value']
def _exists(key):
return key in created
self.assertEquals(self.generator(key_exist=_exists), 'new-value')
def test_it_returns_a_string_with_a_max_size(self):
uid = self.generator()
self.assertTrue(len(uid) <= 24)
self.assertIsInstance(uid, six.text_type)
|
Put the generator instanciation in the setUp
|
Put the generator instanciation in the setUp
|
Python
|
bsd-3-clause
|
spiral-project/daybed,spiral-project/daybed
|
python
|
## Code Before:
try:
from unittest2 import TestCase
except ImportError:
from unittest import TestCase # flake8: noqa
import six
from mock import patch
from daybed.backends.id_generators import KoremutakeGenerator
class KoremutakeGeneratorTest(TestCase):
def test_it_defaults_the_max_bytes_to_4(self):
generator = KoremutakeGenerator()
self.assertEquals(generator.max_bytes, 4)
@patch('koremutake.encode')
def test_it_doesnt_reuse_a_name_twice(self, encode):
encode.side_effect = ['existing-value', 'new-value']
created = ['existing-value']
def _exists(key):
return key in created
generator = KoremutakeGenerator()
self.assertEquals(generator(key_exist=_exists), 'new-value')
def test_it_returns_a_string_with_a_max_size(self):
generator = KoremutakeGenerator()
uid = generator()
self.assertTrue(len(uid) <= 24)
self.assertIsInstance(uid, six.text_type)
## Instruction:
Put the generator instanciation in the setUp
## Code After:
try:
from unittest2 import TestCase
except ImportError:
from unittest import TestCase # flake8: noqa
import six
from mock import patch
from daybed.backends.id_generators import KoremutakeGenerator
class KoremutakeGeneratorTest(TestCase):
def setUp(self):
self.generator = KoremutakeGenerator()
def test_it_defaults_the_max_bytes_to_4(self):
self.assertEquals(generator.max_bytes, 4)
@patch('koremutake.encode')
def test_it_doesnt_reuse_a_name_twice(self, encode):
encode.side_effect = ['existing-value', 'new-value']
created = ['existing-value']
def _exists(key):
return key in created
self.assertEquals(self.generator(key_exist=_exists), 'new-value')
def test_it_returns_a_string_with_a_max_size(self):
uid = self.generator()
self.assertTrue(len(uid) <= 24)
self.assertIsInstance(uid, six.text_type)
|
# ... existing code ...
class KoremutakeGeneratorTest(TestCase):
def setUp(self):
self.generator = KoremutakeGenerator()
def test_it_defaults_the_max_bytes_to_4(self):
self.assertEquals(generator.max_bytes, 4)
@patch('koremutake.encode')
def test_it_doesnt_reuse_a_name_twice(self, encode):
# ... modified code ...
def _exists(key):
return key in created
self.assertEquals(self.generator(key_exist=_exists), 'new-value')
def test_it_returns_a_string_with_a_max_size(self):
uid = self.generator()
self.assertTrue(len(uid) <= 24)
self.assertIsInstance(uid, six.text_type)
# ... rest of the code ...
|
8f86b354b3ceff46363e3121bb1f553a8ff8b301
|
setup.py
|
setup.py
|
from distutils.core import setup
import os.path
import versioneer
versioneer.versionfile_source = "circuit/_version.py"
versioneer.versionfile_build = "circuit/_version.py"
versioneer.tag_prefix = ""
versioneer.parentdir_prefix = ""
commands = versioneer.get_cmdclass().copy()
## Get long_description from index.txt:
here = os.path.dirname(os.path.abspath(__file__))
f = open(os.path.join(here, 'README.md'))
long_description = f.read().strip()
f.close()
setup(name='python-circuit',
version=versioneer.get_version(),
description='Simple implementation of the Circuit Breaker pattern',
long_description=long_description,
author='Johan Rydberg',
author_email='[email protected]',
url='https://github.com/edgeware/python-circuit',
packages=['circuit'],
cmdclass=commands)
|
from setuptools import setup
import versioneer
versioneer.versionfile_source = "circuit/_version.py"
versioneer.versionfile_build = "circuit/_version.py"
versioneer.tag_prefix = ""
versioneer.parentdir_prefix = ""
commands = versioneer.get_cmdclass().copy()
with open('README.md') as f:
long_description = f.read().strip()
setup(name='python-circuit',
version=versioneer.get_version(),
description='Simple implementation of the Circuit Breaker pattern',
long_description=long_description,
author='Edgeware',
author_email='[email protected]',
url='https://github.com/edgeware/python-circuit',
packages=['circuit'],
test_suite='circuit.test',
tests_require=[
'mockito==0.5.2',
'Twisted>=10.2'
],
cmdclass=commands)
|
Add test suit and requirements.
|
Add test suit and requirements.
|
Python
|
apache-2.0
|
edgeware/python-circuit
|
python
|
## Code Before:
from distutils.core import setup
import os.path
import versioneer
versioneer.versionfile_source = "circuit/_version.py"
versioneer.versionfile_build = "circuit/_version.py"
versioneer.tag_prefix = ""
versioneer.parentdir_prefix = ""
commands = versioneer.get_cmdclass().copy()
## Get long_description from index.txt:
here = os.path.dirname(os.path.abspath(__file__))
f = open(os.path.join(here, 'README.md'))
long_description = f.read().strip()
f.close()
setup(name='python-circuit',
version=versioneer.get_version(),
description='Simple implementation of the Circuit Breaker pattern',
long_description=long_description,
author='Johan Rydberg',
author_email='[email protected]',
url='https://github.com/edgeware/python-circuit',
packages=['circuit'],
cmdclass=commands)
## Instruction:
Add test suit and requirements.
## Code After:
from setuptools import setup
import versioneer
versioneer.versionfile_source = "circuit/_version.py"
versioneer.versionfile_build = "circuit/_version.py"
versioneer.tag_prefix = ""
versioneer.parentdir_prefix = ""
commands = versioneer.get_cmdclass().copy()
with open('README.md') as f:
long_description = f.read().strip()
setup(name='python-circuit',
version=versioneer.get_version(),
description='Simple implementation of the Circuit Breaker pattern',
long_description=long_description,
author='Edgeware',
author_email='[email protected]',
url='https://github.com/edgeware/python-circuit',
packages=['circuit'],
test_suite='circuit.test',
tests_require=[
'mockito==0.5.2',
'Twisted>=10.2'
],
cmdclass=commands)
|
# ... existing code ...
from setuptools import setup
import versioneer
versioneer.versionfile_source = "circuit/_version.py"
# ... modified code ...
versioneer.parentdir_prefix = ""
commands = versioneer.get_cmdclass().copy()
with open('README.md') as f:
long_description = f.read().strip()
setup(name='python-circuit',
version=versioneer.get_version(),
description='Simple implementation of the Circuit Breaker pattern',
long_description=long_description,
author='Edgeware',
author_email='[email protected]',
url='https://github.com/edgeware/python-circuit',
packages=['circuit'],
test_suite='circuit.test',
tests_require=[
'mockito==0.5.2',
'Twisted>=10.2'
],
cmdclass=commands)
# ... rest of the code ...
|
5b58da08a3f4c1302098d7976f1c3394e2024028
|
Simperium/src/main/java/com/simperium/client/AuthResponseHandler.java
|
Simperium/src/main/java/com/simperium/client/AuthResponseHandler.java
|
package com.simperium.client;
import com.simperium.util.AuthUtil;
import org.json.JSONException;
import org.json.JSONObject;
public class AuthResponseHandler {
private AuthResponseListener mListener;
private User mUser;
public AuthResponseHandler(User user, AuthResponseListener listener){
mUser = user;
mListener = listener;
}
public void onResponse(JSONObject response){
try {
mUser.setUserId(response.getString(AuthUtil.USERID_KEY));
mUser.setAccessToken(response.getString(AuthUtil.ACCESS_TOKEN_KEY));
} catch(JSONException error){
mListener.onFailure(mUser, AuthException.defaultException());
return;
}
mUser.setStatus(User.Status.AUTHORIZED);
mListener.onSuccess(mUser, mUser.getUserId(), mUser.getAccessToken());
}
public void onError(AuthException error){
mListener.onFailure(mUser, error);
}
}
|
package com.simperium.client;
import com.simperium.util.AuthUtil;
import org.json.JSONObject;
public class AuthResponseHandler {
private AuthResponseListener mListener;
private User mUser;
public AuthResponseHandler(User user, AuthResponseListener listener) {
mUser = user;
mListener = listener;
}
public void onResponse(JSONObject response){
if (!response.optString(AuthUtil.USERID_KEY).isEmpty() && !response.optString(AuthUtil.ACCESS_TOKEN_KEY).isEmpty()) {
mListener.onSuccess(mUser, response.optString(AuthUtil.USERID_KEY), response.optString(AuthUtil.ACCESS_TOKEN_KEY));
} else {
mListener.onFailure(mUser, AuthException.defaultException());
}
}
public void onError(AuthException error) {
mListener.onFailure(mUser, error);
}
}
|
Remove setting user id and access token from response method in auth response handler
|
Remove setting user id and access token from response method in auth response handler
|
Java
|
mit
|
Simperium/simperium-android,Simperium/simperium-android
|
java
|
## Code Before:
package com.simperium.client;
import com.simperium.util.AuthUtil;
import org.json.JSONException;
import org.json.JSONObject;
public class AuthResponseHandler {
private AuthResponseListener mListener;
private User mUser;
public AuthResponseHandler(User user, AuthResponseListener listener){
mUser = user;
mListener = listener;
}
public void onResponse(JSONObject response){
try {
mUser.setUserId(response.getString(AuthUtil.USERID_KEY));
mUser.setAccessToken(response.getString(AuthUtil.ACCESS_TOKEN_KEY));
} catch(JSONException error){
mListener.onFailure(mUser, AuthException.defaultException());
return;
}
mUser.setStatus(User.Status.AUTHORIZED);
mListener.onSuccess(mUser, mUser.getUserId(), mUser.getAccessToken());
}
public void onError(AuthException error){
mListener.onFailure(mUser, error);
}
}
## Instruction:
Remove setting user id and access token from response method in auth response handler
## Code After:
package com.simperium.client;
import com.simperium.util.AuthUtil;
import org.json.JSONObject;
public class AuthResponseHandler {
private AuthResponseListener mListener;
private User mUser;
public AuthResponseHandler(User user, AuthResponseListener listener) {
mUser = user;
mListener = listener;
}
public void onResponse(JSONObject response){
if (!response.optString(AuthUtil.USERID_KEY).isEmpty() && !response.optString(AuthUtil.ACCESS_TOKEN_KEY).isEmpty()) {
mListener.onSuccess(mUser, response.optString(AuthUtil.USERID_KEY), response.optString(AuthUtil.ACCESS_TOKEN_KEY));
} else {
mListener.onFailure(mUser, AuthException.defaultException());
}
}
public void onError(AuthException error) {
mListener.onFailure(mUser, error);
}
}
|
// ... existing code ...
import com.simperium.util.AuthUtil;
import org.json.JSONObject;
public class AuthResponseHandler {
private AuthResponseListener mListener;
private User mUser;
public AuthResponseHandler(User user, AuthResponseListener listener) {
mUser = user;
mListener = listener;
}
public void onResponse(JSONObject response){
if (!response.optString(AuthUtil.USERID_KEY).isEmpty() && !response.optString(AuthUtil.ACCESS_TOKEN_KEY).isEmpty()) {
mListener.onSuccess(mUser, response.optString(AuthUtil.USERID_KEY), response.optString(AuthUtil.ACCESS_TOKEN_KEY));
} else {
mListener.onFailure(mUser, AuthException.defaultException());
}
}
public void onError(AuthException error) {
mListener.onFailure(mUser, error);
}
}
// ... rest of the code ...
|
98c1fbe223dd5469e194a4e772b8e5b181b692ee
|
src/ui.h
|
src/ui.h
|
void draw_seconds(GContext *ctx, uint8_t seconds, Layer *layer);
void draw_minutes(GContext *ctx, uint8_t minutes, Layer *layer);
void draw_hours(GContext *ctx, uint8_t hours, Layer *layer);
|
/*
This header file declares drawing methods that are defined in rect.c or round.c,
depending on the platform being built. Since the methods share the same function
signature, they can share the same header file, even though the implementations
of the functions themselves are different.
*/
void draw_seconds(GContext *ctx, uint8_t seconds, Layer *layer);
void draw_minutes(GContext *ctx, uint8_t minutes, Layer *layer);
void draw_hours(GContext *ctx, uint8_t hours, Layer *layer);
|
Add comment to header file about change
|
Add comment to header file about change
|
C
|
mit
|
NiVZ78/concentricity,pebble-examples/concentricity,NiVZ78/concentricity,pebble-examples/concentricity,pebble-examples/concentricity
|
c
|
## Code Before:
void draw_seconds(GContext *ctx, uint8_t seconds, Layer *layer);
void draw_minutes(GContext *ctx, uint8_t minutes, Layer *layer);
void draw_hours(GContext *ctx, uint8_t hours, Layer *layer);
## Instruction:
Add comment to header file about change
## Code After:
/*
This header file declares drawing methods that are defined in rect.c or round.c,
depending on the platform being built. Since the methods share the same function
signature, they can share the same header file, even though the implementations
of the functions themselves are different.
*/
void draw_seconds(GContext *ctx, uint8_t seconds, Layer *layer);
void draw_minutes(GContext *ctx, uint8_t minutes, Layer *layer);
void draw_hours(GContext *ctx, uint8_t hours, Layer *layer);
|
# ... existing code ...
/*
This header file declares drawing methods that are defined in rect.c or round.c,
depending on the platform being built. Since the methods share the same function
signature, they can share the same header file, even though the implementations
of the functions themselves are different.
*/
void draw_seconds(GContext *ctx, uint8_t seconds, Layer *layer);
void draw_minutes(GContext *ctx, uint8_t minutes, Layer *layer);
# ... rest of the code ...
|
d1d7684edb6d687206deea75d2ba13194046e376
|
sixquiprend/models/chosen_card.py
|
sixquiprend/models/chosen_card.py
|
from sixquiprend.sixquiprend import app, db
class ChosenCard(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete="CASCADE"))
game_id = db.Column(db.Integer, db.ForeignKey('game.id', ondelete="CASCADE"))
card_id = db.Column(db.Integer, db.ForeignKey('card.id'))
################################################################################
## Serializer
################################################################################
def serialize(self):
from sixquiprend.models.card import Card
return {
'id': self.id,
'user_id': self.user_id,
'game_id': self.game_id,
'card': Card.find(self.card_id)
}
|
from sixquiprend.sixquiprend import app, db
from sixquiprend.models.card import Card
class ChosenCard(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete="CASCADE"))
game_id = db.Column(db.Integer, db.ForeignKey('game.id', ondelete="CASCADE"))
card_id = db.Column(db.Integer, db.ForeignKey('card.id'))
################################################################################
## Serializer
################################################################################
def serialize(self):
return {
'id': self.id,
'user_id': self.user_id,
'game_id': self.game_id,
'card': Card.find(self.card_id)
}
|
Move an import to top
|
Move an import to top
|
Python
|
mit
|
nyddogghr/SixQuiPrend,nyddogghr/SixQuiPrend,nyddogghr/SixQuiPrend,nyddogghr/SixQuiPrend
|
python
|
## Code Before:
from sixquiprend.sixquiprend import app, db
class ChosenCard(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete="CASCADE"))
game_id = db.Column(db.Integer, db.ForeignKey('game.id', ondelete="CASCADE"))
card_id = db.Column(db.Integer, db.ForeignKey('card.id'))
################################################################################
## Serializer
################################################################################
def serialize(self):
from sixquiprend.models.card import Card
return {
'id': self.id,
'user_id': self.user_id,
'game_id': self.game_id,
'card': Card.find(self.card_id)
}
## Instruction:
Move an import to top
## Code After:
from sixquiprend.sixquiprend import app, db
from sixquiprend.models.card import Card
class ChosenCard(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete="CASCADE"))
game_id = db.Column(db.Integer, db.ForeignKey('game.id', ondelete="CASCADE"))
card_id = db.Column(db.Integer, db.ForeignKey('card.id'))
################################################################################
## Serializer
################################################################################
def serialize(self):
return {
'id': self.id,
'user_id': self.user_id,
'game_id': self.game_id,
'card': Card.find(self.card_id)
}
|
// ... existing code ...
from sixquiprend.sixquiprend import app, db
from sixquiprend.models.card import Card
class ChosenCard(db.Model):
id = db.Column(db.Integer, primary_key=True)
// ... modified code ...
################################################################################
def serialize(self):
return {
'id': self.id,
'user_id': self.user_id,
// ... rest of the code ...
|
8851223a1576a4e164449b589f68c0420966d622
|
PythonScript/GenerateBook.py
|
PythonScript/GenerateBook.py
|
def GenerateCover():
pass
if __name__ == '__main__':
GenerateCover()
|
import subprocess
def GenerateCover():
Cover = "Cover"
BookName = "BookName"
BookCover = BookName + Cover
BookExt = "BookExt"
HTMLExt = "HTMLExt"
BookCoverHTML = BookCover + HTMLExt
CSS = "CSS_"
CSSExt = "CSSExt"
pandocCommand = "pandoc ..\\source\\" + BookCover + BookExt + " -o "
+ BookCoverHTML + " -standalone " + CSS_ + Cover + CSSExt + " --verbose"
subprocess.call(pandocCommand, stdout=FNULL, stderr=FNULL, shell=False)
if __name__ == '__main__':
GenerateCover()
|
Implement GenerateCover using fake vars
|
Implement GenerateCover using fake vars
|
Python
|
mit
|
fan-jiang/Dujing
|
python
|
## Code Before:
def GenerateCover():
pass
if __name__ == '__main__':
GenerateCover()
## Instruction:
Implement GenerateCover using fake vars
## Code After:
import subprocess
def GenerateCover():
Cover = "Cover"
BookName = "BookName"
BookCover = BookName + Cover
BookExt = "BookExt"
HTMLExt = "HTMLExt"
BookCoverHTML = BookCover + HTMLExt
CSS = "CSS_"
CSSExt = "CSSExt"
pandocCommand = "pandoc ..\\source\\" + BookCover + BookExt + " -o "
+ BookCoverHTML + " -standalone " + CSS_ + Cover + CSSExt + " --verbose"
subprocess.call(pandocCommand, stdout=FNULL, stderr=FNULL, shell=False)
if __name__ == '__main__':
GenerateCover()
|
# ... existing code ...
import subprocess
def GenerateCover():
Cover = "Cover"
BookName = "BookName"
BookCover = BookName + Cover
BookExt = "BookExt"
HTMLExt = "HTMLExt"
BookCoverHTML = BookCover + HTMLExt
CSS = "CSS_"
CSSExt = "CSSExt"
pandocCommand = "pandoc ..\\source\\" + BookCover + BookExt + " -o "
+ BookCoverHTML + " -standalone " + CSS_ + Cover + CSSExt + " --verbose"
subprocess.call(pandocCommand, stdout=FNULL, stderr=FNULL, shell=False)
if __name__ == '__main__':
GenerateCover()
# ... rest of the code ...
|
2ca6f765a3bd1eca6bd255f9c679c9fbea78484a
|
run_maya_tests.py
|
run_maya_tests.py
|
import sys
import nose
import warnings
from nose_exclude import NoseExclude
warnings.filterwarnings("ignore", category=DeprecationWarning)
if __name__ == "__main__":
from maya import standalone
standalone.initialize()
argv = sys.argv[:]
argv.extend([
# Sometimes, files from Windows accessed
# from Linux cause the executable flag to be
# set, and Nose has an aversion to these
# per default.
"--exe",
"--verbose",
"--with-doctest",
"--with-coverage",
"--cover-html",
"--cover-tests",
"--cover-erase",
"--exclude-dir=mindbender/nuke",
"--exclude-dir=mindbender/houdini",
"--exclude-dir=mindbender/schema",
"--exclude-dir=mindbender/plugins",
# We can expect any vendors to
# be well tested beforehand.
"--exclude-dir=mindbender/vendor",
])
nose.main(argv=argv,
addplugins=[NoseExclude()])
|
import sys
import nose
import logging
import warnings
from nose_exclude import NoseExclude
warnings.filterwarnings("ignore", category=DeprecationWarning)
if __name__ == "__main__":
from maya import standalone
standalone.initialize()
log = logging.getLogger()
# Discard default Maya logging handler
log.handlers[:] = []
argv = sys.argv[:]
argv.extend([
# Sometimes, files from Windows accessed
# from Linux cause the executable flag to be
# set, and Nose has an aversion to these
# per default.
"--exe",
"--verbose",
"--with-doctest",
"--with-coverage",
"--cover-html",
"--cover-tests",
"--cover-erase",
"--exclude-dir=mindbender/nuke",
"--exclude-dir=mindbender/houdini",
"--exclude-dir=mindbender/schema",
"--exclude-dir=mindbender/plugins",
# We can expect any vendors to
# be well tested beforehand.
"--exclude-dir=mindbender/vendor",
])
nose.main(argv=argv,
addplugins=[NoseExclude()])
|
Enhance readability of test output
|
Enhance readability of test output
|
Python
|
mit
|
MoonShineVFX/core,mindbender-studio/core,MoonShineVFX/core,mindbender-studio/core,getavalon/core,getavalon/core
|
python
|
## Code Before:
import sys
import nose
import warnings
from nose_exclude import NoseExclude
warnings.filterwarnings("ignore", category=DeprecationWarning)
if __name__ == "__main__":
from maya import standalone
standalone.initialize()
argv = sys.argv[:]
argv.extend([
# Sometimes, files from Windows accessed
# from Linux cause the executable flag to be
# set, and Nose has an aversion to these
# per default.
"--exe",
"--verbose",
"--with-doctest",
"--with-coverage",
"--cover-html",
"--cover-tests",
"--cover-erase",
"--exclude-dir=mindbender/nuke",
"--exclude-dir=mindbender/houdini",
"--exclude-dir=mindbender/schema",
"--exclude-dir=mindbender/plugins",
# We can expect any vendors to
# be well tested beforehand.
"--exclude-dir=mindbender/vendor",
])
nose.main(argv=argv,
addplugins=[NoseExclude()])
## Instruction:
Enhance readability of test output
## Code After:
import sys
import nose
import logging
import warnings
from nose_exclude import NoseExclude
warnings.filterwarnings("ignore", category=DeprecationWarning)
if __name__ == "__main__":
from maya import standalone
standalone.initialize()
log = logging.getLogger()
# Discard default Maya logging handler
log.handlers[:] = []
argv = sys.argv[:]
argv.extend([
# Sometimes, files from Windows accessed
# from Linux cause the executable flag to be
# set, and Nose has an aversion to these
# per default.
"--exe",
"--verbose",
"--with-doctest",
"--with-coverage",
"--cover-html",
"--cover-tests",
"--cover-erase",
"--exclude-dir=mindbender/nuke",
"--exclude-dir=mindbender/houdini",
"--exclude-dir=mindbender/schema",
"--exclude-dir=mindbender/plugins",
# We can expect any vendors to
# be well tested beforehand.
"--exclude-dir=mindbender/vendor",
])
nose.main(argv=argv,
addplugins=[NoseExclude()])
|
# ... existing code ...
import sys
import nose
import logging
import warnings
from nose_exclude import NoseExclude
# ... modified code ...
if __name__ == "__main__":
from maya import standalone
standalone.initialize()
log = logging.getLogger()
# Discard default Maya logging handler
log.handlers[:] = []
argv = sys.argv[:]
argv.extend([
# ... rest of the code ...
|
108a05b050383bca218cd02be499f1fad58065dc
|
test/test_refmanage.py
|
test/test_refmanage.py
|
import unittest
import pathlib2 as pathlib
import refmanage
class NoSpecifiedFunctionality(unittest.TestCase):
"""
Tests when no functionality has been specified on cli
"""
def test_no_args(self):
"""
`ref` without arguments should print the help text
"""
pass
def test_version(self):
"""
`ref --version` should return version string
"""
pass
class TestFunctionality(unittest.TestCase):
"""
Test "test" functionality
"""
def test_no_args(self):
"""
`ref test` without additonal arguments should print the help text
"""
pass
def test_default(self):
"""
`ref test *.bib` without flags should default to --unparseable and print list of unparseable files
"""
pass
def test_unparseable(self):
"""
`ref test -u *.bib` should print list of unparseable files
"""
pass
def test_unparseable_verbose(self):
"""
`ref test -uv *.bib` should print list of unparseable files with information about corresponding parsing message
"""
pass
def test_parseable(self):
"""
`ref test -p *.bib` should print list of parseable files
"""
pass
def test_parseable_verbose(self):
"""
`ref test -pv *.bib` should print list of parseable files and nothing more
"""
pass
def test_parseable_unparseable(self):
"""
`ref test -up *.bib` should exit with an error
"""
pass
|
import unittest
import pathlib2 as pathlib
import refmanage
class NoSpecifiedFunctionality(unittest.TestCase):
"""
Tests when no functionality has been specified on cli
"""
def test_no_args(self):
"""
`ref` without arguments should print the help text
"""
self.fail()
def test_version(self):
"""
`ref --version` should return version string
"""
self.fail()
class TestFunctionality(unittest.TestCase):
"""
Test "test" functionality
"""
def test_no_args(self):
"""
`ref test` without additonal arguments should print the help text
"""
self.fail()
def test_default(self):
"""
`ref test *.bib` without flags should default to --unparseable and print list of unparseable files
"""
self.fail()
def test_unparseable(self):
"""
`ref test -u *.bib` should print list of unparseable files
"""
self.fail()
def test_unparseable_verbose(self):
"""
`ref test -uv *.bib` should print list of unparseable files with information about corresponding parsing message
"""
self.fail()
def test_parseable(self):
"""
`ref test -p *.bib` should print list of parseable files
"""
self.fail()
def test_parseable_verbose(self):
"""
`ref test -pv *.bib` should print list of parseable files and nothing more
"""
self.fail()
def test_parseable_unparseable(self):
"""
`ref test -up *.bib` should exit with an error
"""
self.fail()
|
Replace "pass" with "self.fail()" in tests
|
Replace "pass" with "self.fail()" in tests
In this way, tests that haven't been written will run noisily instead of
silently, encouraging completion of writing tests.
|
Python
|
mit
|
jrsmith3/refmanage
|
python
|
## Code Before:
import unittest
import pathlib2 as pathlib
import refmanage
class NoSpecifiedFunctionality(unittest.TestCase):
"""
Tests when no functionality has been specified on cli
"""
def test_no_args(self):
"""
`ref` without arguments should print the help text
"""
pass
def test_version(self):
"""
`ref --version` should return version string
"""
pass
class TestFunctionality(unittest.TestCase):
"""
Test "test" functionality
"""
def test_no_args(self):
"""
`ref test` without additonal arguments should print the help text
"""
pass
def test_default(self):
"""
`ref test *.bib` without flags should default to --unparseable and print list of unparseable files
"""
pass
def test_unparseable(self):
"""
`ref test -u *.bib` should print list of unparseable files
"""
pass
def test_unparseable_verbose(self):
"""
`ref test -uv *.bib` should print list of unparseable files with information about corresponding parsing message
"""
pass
def test_parseable(self):
"""
`ref test -p *.bib` should print list of parseable files
"""
pass
def test_parseable_verbose(self):
"""
`ref test -pv *.bib` should print list of parseable files and nothing more
"""
pass
def test_parseable_unparseable(self):
"""
`ref test -up *.bib` should exit with an error
"""
pass
## Instruction:
Replace "pass" with "self.fail()" in tests
In this way, tests that haven't been written will run noisily instead of
silently, encouraging completion of writing tests.
## Code After:
import unittest
import pathlib2 as pathlib
import refmanage
class NoSpecifiedFunctionality(unittest.TestCase):
"""
Tests when no functionality has been specified on cli
"""
def test_no_args(self):
"""
`ref` without arguments should print the help text
"""
self.fail()
def test_version(self):
"""
`ref --version` should return version string
"""
self.fail()
class TestFunctionality(unittest.TestCase):
"""
Test "test" functionality
"""
def test_no_args(self):
"""
`ref test` without additonal arguments should print the help text
"""
self.fail()
def test_default(self):
"""
`ref test *.bib` without flags should default to --unparseable and print list of unparseable files
"""
self.fail()
def test_unparseable(self):
"""
`ref test -u *.bib` should print list of unparseable files
"""
self.fail()
def test_unparseable_verbose(self):
"""
`ref test -uv *.bib` should print list of unparseable files with information about corresponding parsing message
"""
self.fail()
def test_parseable(self):
"""
`ref test -p *.bib` should print list of parseable files
"""
self.fail()
def test_parseable_verbose(self):
"""
`ref test -pv *.bib` should print list of parseable files and nothing more
"""
self.fail()
def test_parseable_unparseable(self):
"""
`ref test -up *.bib` should exit with an error
"""
self.fail()
|
// ... existing code ...
"""
`ref` without arguments should print the help text
"""
self.fail()
def test_version(self):
"""
`ref --version` should return version string
"""
self.fail()
class TestFunctionality(unittest.TestCase):
"""
// ... modified code ...
"""
`ref test` without additonal arguments should print the help text
"""
self.fail()
def test_default(self):
"""
`ref test *.bib` without flags should default to --unparseable and print list of unparseable files
"""
self.fail()
def test_unparseable(self):
...
"""
`ref test -u *.bib` should print list of unparseable files
"""
self.fail()
def test_unparseable_verbose(self):
"""
`ref test -uv *.bib` should print list of unparseable files with information about corresponding parsing message
"""
self.fail()
def test_parseable(self):
"""
`ref test -p *.bib` should print list of parseable files
"""
self.fail()
def test_parseable_verbose(self):
"""
`ref test -pv *.bib` should print list of parseable files and nothing more
"""
self.fail()
def test_parseable_unparseable(self):
"""
`ref test -up *.bib` should exit with an error
"""
self.fail()
// ... rest of the code ...
|
476e0f7dc4c4e401416c92cca1d481fe2520d8f3
|
setup.py
|
setup.py
|
from setuptools import setup
import cetacean
setup(
name="Cetacean",
version=cetacean.__version__,
author="Ben Hamill",
author_email="[email protected]",
url="http://github.com/benhamill/cetacean-python#readme",
license="MIT",
description="The HAL client that does almost nothing for you.",
long_description=__doc__,
py_modules=["cetacean"],
classifiers=[],
)
|
from setuptools import setup
import cetacean
setup(
name="Cetacean",
version=cetacean.__version__,
author="Ben Hamill",
author_email="[email protected]",
url="http://github.com/benhamill/cetacean-python#readme",
license="MIT",
description="The HAL client that does almost nothing for you.",
long_description=__doc__,
py_modules=["cetacean"],
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Topic :: Internet :: WWW/HTTP",
],
)
|
Add a bunch of classifiers.
|
Add a bunch of classifiers.
|
Python
|
mit
|
nanorepublica/cetacean-python,benhamill/cetacean-python
|
python
|
## Code Before:
from setuptools import setup
import cetacean
setup(
name="Cetacean",
version=cetacean.__version__,
author="Ben Hamill",
author_email="[email protected]",
url="http://github.com/benhamill/cetacean-python#readme",
license="MIT",
description="The HAL client that does almost nothing for you.",
long_description=__doc__,
py_modules=["cetacean"],
classifiers=[],
)
## Instruction:
Add a bunch of classifiers.
## Code After:
from setuptools import setup
import cetacean
setup(
name="Cetacean",
version=cetacean.__version__,
author="Ben Hamill",
author_email="[email protected]",
url="http://github.com/benhamill/cetacean-python#readme",
license="MIT",
description="The HAL client that does almost nothing for you.",
long_description=__doc__,
py_modules=["cetacean"],
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Topic :: Internet :: WWW/HTTP",
],
)
|
// ... existing code ...
description="The HAL client that does almost nothing for you.",
long_description=__doc__,
py_modules=["cetacean"],
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Topic :: Internet :: WWW/HTTP",
],
)
// ... rest of the code ...
|
8a3eb221f51850d8a97c6d72715e644f52346c9f
|
swish/client.py
|
swish/client.py
|
import json
import requests
from .environment import Environment
class SwishClient(object):
def __init__(self, environment, payee_alias, cert):
self.environment = Environment.parse_environment(environment)
self.payee_alias = payee_alias
self.cert = cert
def post(self, endpoint, json):
url = self.environment.base_url + endpoint
return requests.post(url=url, json=json, headers={'Content-Type': 'application/json'}, cert=self.cert)
def get(self, endpoint, id):
print("Not implemented yet!")
def payment_request(self, amount, currency, callback_url, payment_reference='', message=''):
data = {
'amount': amount,
'currency': currency,
'callback_url': callback_url,
'payment_reference': payment_reference,
'message': message
}
r = self.post('paymentrequests', json.dumps(data))
return r
def get_payment_request(payment_request_id):
print("Not implemented yet!")
def refund(self, amount, currency, callback_url, original_payment_reference, payer_payment_reference=''):
data = {
'amount': amount,
'currency': currency,
'callback_url': callback_url
}
r = self.post('refunds', json.dumps(data))
return r
def get_refund(refund_id):
print("Not implemented yet!")
|
import json
import requests
from .environment import Environment
class SwishClient(object):
def __init__(self, environment, payee_alias, cert):
self.environment = Environment.parse_environment(environment)
self.payee_alias = payee_alias
self.cert = cert
def post(self, endpoint, json):
url = self.environment.base_url + endpoint
return requests.post(url=url, json=json, headers={'Content-Type': 'application/json'}, cert=self.cert)
def get(self, endpoint, id):
print("Not implemented yet!")
def payment_request(self, amount, currency, callback_url, payee_payment_reference='', message=''):
data = {
'payeeAlias': self.payee_alias,
'amount': amount,
'currency': currency,
'callbackUrl': callback_url,
'payeePaymentReference': payee_payment_reference,
'message': message
}
r = self.post('paymentrequests', json.dumps(data))
return r
def get_payment_request(payment_request_id):
print("Not implemented yet!")
def refund(self, amount, currency, callback_url, original_payment_reference, payer_payment_reference=''):
data = {
'amount': amount,
'currency': currency,
'callback_url': callback_url
}
r = self.post('refunds', json.dumps(data))
return r
def get_refund(refund_id):
print("Not implemented yet!")
|
Correct data in payment request
|
Correct data in payment request
|
Python
|
mit
|
playing-se/swish-python
|
python
|
## Code Before:
import json
import requests
from .environment import Environment
class SwishClient(object):
def __init__(self, environment, payee_alias, cert):
self.environment = Environment.parse_environment(environment)
self.payee_alias = payee_alias
self.cert = cert
def post(self, endpoint, json):
url = self.environment.base_url + endpoint
return requests.post(url=url, json=json, headers={'Content-Type': 'application/json'}, cert=self.cert)
def get(self, endpoint, id):
print("Not implemented yet!")
def payment_request(self, amount, currency, callback_url, payment_reference='', message=''):
data = {
'amount': amount,
'currency': currency,
'callback_url': callback_url,
'payment_reference': payment_reference,
'message': message
}
r = self.post('paymentrequests', json.dumps(data))
return r
def get_payment_request(payment_request_id):
print("Not implemented yet!")
def refund(self, amount, currency, callback_url, original_payment_reference, payer_payment_reference=''):
data = {
'amount': amount,
'currency': currency,
'callback_url': callback_url
}
r = self.post('refunds', json.dumps(data))
return r
def get_refund(refund_id):
print("Not implemented yet!")
## Instruction:
Correct data in payment request
## Code After:
import json
import requests
from .environment import Environment
class SwishClient(object):
def __init__(self, environment, payee_alias, cert):
self.environment = Environment.parse_environment(environment)
self.payee_alias = payee_alias
self.cert = cert
def post(self, endpoint, json):
url = self.environment.base_url + endpoint
return requests.post(url=url, json=json, headers={'Content-Type': 'application/json'}, cert=self.cert)
def get(self, endpoint, id):
print("Not implemented yet!")
def payment_request(self, amount, currency, callback_url, payee_payment_reference='', message=''):
data = {
'payeeAlias': self.payee_alias,
'amount': amount,
'currency': currency,
'callbackUrl': callback_url,
'payeePaymentReference': payee_payment_reference,
'message': message
}
r = self.post('paymentrequests', json.dumps(data))
return r
def get_payment_request(payment_request_id):
print("Not implemented yet!")
def refund(self, amount, currency, callback_url, original_payment_reference, payer_payment_reference=''):
data = {
'amount': amount,
'currency': currency,
'callback_url': callback_url
}
r = self.post('refunds', json.dumps(data))
return r
def get_refund(refund_id):
print("Not implemented yet!")
|
// ... existing code ...
def get(self, endpoint, id):
print("Not implemented yet!")
def payment_request(self, amount, currency, callback_url, payee_payment_reference='', message=''):
data = {
'payeeAlias': self.payee_alias,
'amount': amount,
'currency': currency,
'callbackUrl': callback_url,
'payeePaymentReference': payee_payment_reference,
'message': message
}
r = self.post('paymentrequests', json.dumps(data))
// ... rest of the code ...
|
5d1ed87984446fa3794db7fd975215f1184ae669
|
src/test/kotlin/khronos/Utils.kt
|
src/test/kotlin/khronos/Utils.kt
|
package khronos
import org.junit.Assert
import java.util.*
fun assertEquals(expected: Date, actual: Date) {
Assert.assertEquals(expected.toString(), actual.toString())
}
fun assertEquals(expected: Duration, actual: Duration) {
Assert.assertEquals(expected, actual)
}
|
package khronos
import org.junit.Assert
import java.text.SimpleDateFormat
import java.util.*
internal val iso8601: SimpleDateFormat by lazy {
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
}
fun assertEquals(expected: Date, actual: Date) {
Assert.assertEquals(iso8601.format(expected), iso8601.format(actual))
}
fun assertEquals(expected: Duration, actual: Duration) {
Assert.assertEquals(expected, actual)
}
|
Make assertEquals as precise as Date (precise to milliseconds)
|
Make assertEquals as precise as Date (precise to milliseconds)
|
Kotlin
|
apache-2.0
|
hotchemi/khronos
|
kotlin
|
## Code Before:
package khronos
import org.junit.Assert
import java.util.*
fun assertEquals(expected: Date, actual: Date) {
Assert.assertEquals(expected.toString(), actual.toString())
}
fun assertEquals(expected: Duration, actual: Duration) {
Assert.assertEquals(expected, actual)
}
## Instruction:
Make assertEquals as precise as Date (precise to milliseconds)
## Code After:
package khronos
import org.junit.Assert
import java.text.SimpleDateFormat
import java.util.*
internal val iso8601: SimpleDateFormat by lazy {
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
}
fun assertEquals(expected: Date, actual: Date) {
Assert.assertEquals(iso8601.format(expected), iso8601.format(actual))
}
fun assertEquals(expected: Duration, actual: Duration) {
Assert.assertEquals(expected, actual)
}
|
// ... existing code ...
package khronos
import org.junit.Assert
import java.text.SimpleDateFormat
import java.util.*
internal val iso8601: SimpleDateFormat by lazy {
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
}
fun assertEquals(expected: Date, actual: Date) {
Assert.assertEquals(iso8601.format(expected), iso8601.format(actual))
}
fun assertEquals(expected: Duration, actual: Duration) {
// ... rest of the code ...
|
abfe0538769145ac83031062ce3b22d2622f18bf
|
opwen_email_server/utils/temporary.py
|
opwen_email_server/utils/temporary.py
|
from contextlib import contextmanager
from contextlib import suppress
from os import close
from os import remove
from tempfile import mkstemp
def create_tempfilename() -> str:
file_descriptor, filename = mkstemp()
close(file_descriptor)
return filename
@contextmanager
def removing(path: str) -> str:
try:
yield path
finally:
_remove_if_exists(path)
def _remove_if_exists(path: str):
with suppress(FileNotFoundError):
remove(path)
|
from contextlib import contextmanager
from contextlib import suppress
from os import close
from os import remove
from tempfile import mkstemp
from typing import Generator
def create_tempfilename() -> str:
file_descriptor, filename = mkstemp()
close(file_descriptor)
return filename
@contextmanager
def removing(path: str) -> Generator[str, None, None]:
try:
yield path
finally:
_remove_if_exists(path)
def _remove_if_exists(path: str):
with suppress(FileNotFoundError):
remove(path)
|
Fix type annotation for context manager
|
Fix type annotation for context manager
|
Python
|
apache-2.0
|
ascoderu/opwen-cloudserver,ascoderu/opwen-cloudserver
|
python
|
## Code Before:
from contextlib import contextmanager
from contextlib import suppress
from os import close
from os import remove
from tempfile import mkstemp
def create_tempfilename() -> str:
file_descriptor, filename = mkstemp()
close(file_descriptor)
return filename
@contextmanager
def removing(path: str) -> str:
try:
yield path
finally:
_remove_if_exists(path)
def _remove_if_exists(path: str):
with suppress(FileNotFoundError):
remove(path)
## Instruction:
Fix type annotation for context manager
## Code After:
from contextlib import contextmanager
from contextlib import suppress
from os import close
from os import remove
from tempfile import mkstemp
from typing import Generator
def create_tempfilename() -> str:
file_descriptor, filename = mkstemp()
close(file_descriptor)
return filename
@contextmanager
def removing(path: str) -> Generator[str, None, None]:
try:
yield path
finally:
_remove_if_exists(path)
def _remove_if_exists(path: str):
with suppress(FileNotFoundError):
remove(path)
|
...
from os import close
from os import remove
from tempfile import mkstemp
from typing import Generator
def create_tempfilename() -> str:
...
@contextmanager
def removing(path: str) -> Generator[str, None, None]:
try:
yield path
finally:
...
|
3a77de3c7d863041bea1366c50a95293d1cd2f7a
|
tests/functional/test_warning.py
|
tests/functional/test_warning.py
|
import pytest
import textwrap
@pytest.fixture
def warnings_demo(tmpdir):
demo = tmpdir.joinpath('warnings_demo.py')
demo.write_text(textwrap.dedent('''
from logging import basicConfig
from pip._internal.utils import deprecation
deprecation.install_warning_logger()
basicConfig()
deprecation.deprecated("deprecated!", replacement=None, gone_in=None)
'''))
return demo
def test_deprecation_warnings_are_correct(script, warnings_demo):
result = script.run('python', warnings_demo, expect_stderr=True)
expected = 'WARNING:pip._internal.deprecations:DEPRECATION: deprecated!\n'
assert result.stderr == expected
# NOTE: PYTHONWARNINGS was added in 2.7
script.environ['PYTHONWARNINGS'] = 'ignore'
result = script.run('python', warnings_demo)
assert result.stderr == ''
|
import pytest
import textwrap
@pytest.fixture
def warnings_demo(tmpdir):
demo = tmpdir.joinpath('warnings_demo.py')
demo.write_text(textwrap.dedent('''
from logging import basicConfig
from pip._internal.utils import deprecation
deprecation.install_warning_logger()
basicConfig()
deprecation.deprecated("deprecated!", replacement=None, gone_in=None)
'''))
return demo
def test_deprecation_warnings_are_correct(script, warnings_demo):
result = script.run('python', warnings_demo, expect_stderr=True)
expected = 'WARNING:pip._internal.deprecations:DEPRECATION: deprecated!\n'
assert result.stderr == expected
def test_deprecation_warnings_can_be_silenced(script, warnings_demo):
script.environ['PYTHONWARNINGS'] = 'ignore'
result = script.run('python', warnings_demo)
assert result.stderr == ''
|
Split tests for different functionality
|
Split tests for different functionality
|
Python
|
mit
|
pypa/pip,pradyunsg/pip,xavfernandez/pip,rouge8/pip,pypa/pip,xavfernandez/pip,rouge8/pip,xavfernandez/pip,pfmoore/pip,sbidoul/pip,rouge8/pip,sbidoul/pip,pradyunsg/pip,pfmoore/pip
|
python
|
## Code Before:
import pytest
import textwrap
@pytest.fixture
def warnings_demo(tmpdir):
demo = tmpdir.joinpath('warnings_demo.py')
demo.write_text(textwrap.dedent('''
from logging import basicConfig
from pip._internal.utils import deprecation
deprecation.install_warning_logger()
basicConfig()
deprecation.deprecated("deprecated!", replacement=None, gone_in=None)
'''))
return demo
def test_deprecation_warnings_are_correct(script, warnings_demo):
result = script.run('python', warnings_demo, expect_stderr=True)
expected = 'WARNING:pip._internal.deprecations:DEPRECATION: deprecated!\n'
assert result.stderr == expected
# NOTE: PYTHONWARNINGS was added in 2.7
script.environ['PYTHONWARNINGS'] = 'ignore'
result = script.run('python', warnings_demo)
assert result.stderr == ''
## Instruction:
Split tests for different functionality
## Code After:
import pytest
import textwrap
@pytest.fixture
def warnings_demo(tmpdir):
demo = tmpdir.joinpath('warnings_demo.py')
demo.write_text(textwrap.dedent('''
from logging import basicConfig
from pip._internal.utils import deprecation
deprecation.install_warning_logger()
basicConfig()
deprecation.deprecated("deprecated!", replacement=None, gone_in=None)
'''))
return demo
def test_deprecation_warnings_are_correct(script, warnings_demo):
result = script.run('python', warnings_demo, expect_stderr=True)
expected = 'WARNING:pip._internal.deprecations:DEPRECATION: deprecated!\n'
assert result.stderr == expected
def test_deprecation_warnings_can_be_silenced(script, warnings_demo):
script.environ['PYTHONWARNINGS'] = 'ignore'
result = script.run('python', warnings_demo)
assert result.stderr == ''
|
# ... existing code ...
expected = 'WARNING:pip._internal.deprecations:DEPRECATION: deprecated!\n'
assert result.stderr == expected
def test_deprecation_warnings_can_be_silenced(script, warnings_demo):
script.environ['PYTHONWARNINGS'] = 'ignore'
result = script.run('python', warnings_demo)
assert result.stderr == ''
# ... rest of the code ...
|
c906df9cc8e5820d47d8e5b71a5e627e473a1ce4
|
app/src/main/java/org/openalpr/model/Results.java
|
app/src/main/java/org/openalpr/model/Results.java
|
package org.openalpr.model;
import java.util.ArrayList;
public class Results {
private final Float epoch_time;
private final Float processing_time_ms;
private final ArrayList<Result> results;
public Results(Float epoch_time, Float processing_time_ms, ArrayList<Result> results) {
this.epoch_time = epoch_time;
this.processing_time_ms = processing_time_ms;
this.results = results;
}
public Float getEpoch_time() {
return epoch_time;
}
public Float getProcessing_time_ms() {
return processing_time_ms;
}
public ArrayList<Result> getResults() {
return results;
}
}
|
package org.openalpr.model;
import java.util.ArrayList;
public class Results {
private final Double epoch_time;
private final Double processing_time_ms;
private final ArrayList<Result> results;
public Results(Double epoch_time, Double processing_time_ms, ArrayList<Result> results) {
this.epoch_time = epoch_time;
this.processing_time_ms = processing_time_ms;
this.results = results;
}
public Double getEpoch_time() {
return epoch_time;
}
public Double getProcessing_time_ms() {
return processing_time_ms;
}
public ArrayList<Result> getResults() {
return results;
}
}
|
Update result model to Double
|
Update result model to Double
|
Java
|
apache-2.0
|
SandroMachado/openalpr-android
|
java
|
## Code Before:
package org.openalpr.model;
import java.util.ArrayList;
public class Results {
private final Float epoch_time;
private final Float processing_time_ms;
private final ArrayList<Result> results;
public Results(Float epoch_time, Float processing_time_ms, ArrayList<Result> results) {
this.epoch_time = epoch_time;
this.processing_time_ms = processing_time_ms;
this.results = results;
}
public Float getEpoch_time() {
return epoch_time;
}
public Float getProcessing_time_ms() {
return processing_time_ms;
}
public ArrayList<Result> getResults() {
return results;
}
}
## Instruction:
Update result model to Double
## Code After:
package org.openalpr.model;
import java.util.ArrayList;
public class Results {
private final Double epoch_time;
private final Double processing_time_ms;
private final ArrayList<Result> results;
public Results(Double epoch_time, Double processing_time_ms, ArrayList<Result> results) {
this.epoch_time = epoch_time;
this.processing_time_ms = processing_time_ms;
this.results = results;
}
public Double getEpoch_time() {
return epoch_time;
}
public Double getProcessing_time_ms() {
return processing_time_ms;
}
public ArrayList<Result> getResults() {
return results;
}
}
|
...
public class Results {
private final Double epoch_time;
private final Double processing_time_ms;
private final ArrayList<Result> results;
public Results(Double epoch_time, Double processing_time_ms, ArrayList<Result> results) {
this.epoch_time = epoch_time;
this.processing_time_ms = processing_time_ms;
this.results = results;
}
public Double getEpoch_time() {
return epoch_time;
}
public Double getProcessing_time_ms() {
return processing_time_ms;
}
...
|
9fefa30f51f1a3c0e4586bc21c36324c6dfbbc87
|
test/tst_filepath.py
|
test/tst_filepath.py
|
import os
import unittest
import netCDF4
class test_filepath(unittest.TestCase):
def setUp(self):
self.netcdf_file = os.path.join(os.getcwd(), "netcdf_dummy_file.nc")
self.nc = netCDF4.Dataset(self.netcdf_file)
def test_filepath(self):
assert self.nc.filepath() == str(self.netcdf_file)
if __name__ == '__main__':
unittest.main()
|
import os
import unittest
import tempfile
import netCDF4
class test_filepath(unittest.TestCase):
def setUp(self):
self.netcdf_file = os.path.join(os.getcwd(), "netcdf_dummy_file.nc")
self.nc = netCDF4.Dataset(self.netcdf_file)
def test_filepath(self):
assert self.nc.filepath() == str(self.netcdf_file)
def test_filepath_with_non_ascii_characters(self):
# create nc-file in a filepath with Non-Ascii-Characters
tempdir = tempfile.mkdtemp(prefix='ÄÖÜß_')
nc_non_ascii_file = os.path.join(tempdir, "Besançonalléestraße.nc")
nc_non_ascii = netCDF4.Dataset(nc_non_ascii_file, 'w')
# test that no UnicodeDecodeError occur in the filepath() method
assert nc_non_ascii.filepath() == str(nc_non_ascii_file)
# cleanup
nc_non_ascii.close()
os.remove(nc_non_ascii_file)
os.rmdir(tempdir)
if __name__ == '__main__':
unittest.main()
|
Add test for filepath with non-ascii-chars
|
Add test for filepath with non-ascii-chars
|
Python
|
mit
|
Unidata/netcdf4-python,Unidata/netcdf4-python,Unidata/netcdf4-python
|
python
|
## Code Before:
import os
import unittest
import netCDF4
class test_filepath(unittest.TestCase):
def setUp(self):
self.netcdf_file = os.path.join(os.getcwd(), "netcdf_dummy_file.nc")
self.nc = netCDF4.Dataset(self.netcdf_file)
def test_filepath(self):
assert self.nc.filepath() == str(self.netcdf_file)
if __name__ == '__main__':
unittest.main()
## Instruction:
Add test for filepath with non-ascii-chars
## Code After:
import os
import unittest
import tempfile
import netCDF4
class test_filepath(unittest.TestCase):
def setUp(self):
self.netcdf_file = os.path.join(os.getcwd(), "netcdf_dummy_file.nc")
self.nc = netCDF4.Dataset(self.netcdf_file)
def test_filepath(self):
assert self.nc.filepath() == str(self.netcdf_file)
def test_filepath_with_non_ascii_characters(self):
# create nc-file in a filepath with Non-Ascii-Characters
tempdir = tempfile.mkdtemp(prefix='ÄÖÜß_')
nc_non_ascii_file = os.path.join(tempdir, "Besançonalléestraße.nc")
nc_non_ascii = netCDF4.Dataset(nc_non_ascii_file, 'w')
# test that no UnicodeDecodeError occur in the filepath() method
assert nc_non_ascii.filepath() == str(nc_non_ascii_file)
# cleanup
nc_non_ascii.close()
os.remove(nc_non_ascii_file)
os.rmdir(tempdir)
if __name__ == '__main__':
unittest.main()
|
// ... existing code ...
import os
import unittest
import tempfile
import netCDF4
class test_filepath(unittest.TestCase):
// ... modified code ...
def test_filepath(self):
assert self.nc.filepath() == str(self.netcdf_file)
def test_filepath_with_non_ascii_characters(self):
# create nc-file in a filepath with Non-Ascii-Characters
tempdir = tempfile.mkdtemp(prefix='ÄÖÜß_')
nc_non_ascii_file = os.path.join(tempdir, "Besançonalléestraße.nc")
nc_non_ascii = netCDF4.Dataset(nc_non_ascii_file, 'w')
# test that no UnicodeDecodeError occur in the filepath() method
assert nc_non_ascii.filepath() == str(nc_non_ascii_file)
# cleanup
nc_non_ascii.close()
os.remove(nc_non_ascii_file)
os.rmdir(tempdir)
if __name__ == '__main__':
unittest.main()
// ... rest of the code ...
|
ac5fd7394e8ed5784c3060669ea7e2935fc6d863
|
src/main/java/com/alexrnl/commons/utils/CollectionUtils.java
|
src/main/java/com/alexrnl/commons/utils/CollectionUtils.java
|
package com.alexrnl.commons.utils;
import java.util.Iterator;
import java.util.Objects;
import java.util.logging.Logger;
/**
* Utilities on collections.<br />
* @author Alex
*/
public final class CollectionUtils {
/** Logger */
private static Logger lg = Logger.getLogger(CollectionUtils.class.getName());
/**
* Constructor #1.<br />
* Default private constructor.
*/
private CollectionUtils () {
super();
}
/**
* Check if a collection is sorted.<br />
* @param collection
* the collection to check.
* @return <code>true</code> if the collection is sorted.
*/
public static <T extends Comparable<? super T>> boolean isSorted (final Iterable<T> collection) {
Objects.requireNonNull(collection);
final Iterator<T> it = collection.iterator();
while (it.hasNext()) {
final T current = it.next();
if (it.hasNext() && current.compareTo(it.next()) > 0) {
return false;
}
}
return true;
}
}
|
package com.alexrnl.commons.utils;
import java.util.Iterator;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Utilities on collections.<br />
* @author Alex
*/
public final class CollectionUtils {
/** Logger */
private static Logger lg = Logger.getLogger(CollectionUtils.class.getName());
/**
* Constructor #1.<br />
* Default private constructor.
*/
private CollectionUtils () {
super();
}
/**
* Check if a collection is sorted.<br />
* @param collection
* the collection to check.
* @return <code>true</code> if the collection is sorted.
*/
public static <T extends Comparable<? super T>> boolean isSorted (final Iterable<T> collection) {
Objects.requireNonNull(collection);
final Iterator<T> it = collection.iterator();
while (it.hasNext()) {
final T current = it.next();
if (it.hasNext() && current.compareTo(it.next()) > 0) {
if (lg.isLoggable(Level.INFO)) {
lg.info("Collection is unordered at element " + current);
}
return false;
}
}
return true;
}
}
|
Use logger is method isSorted
|
Use logger is method isSorted
|
Java
|
bsd-3-clause
|
AlexRNL/Commons
|
java
|
## Code Before:
package com.alexrnl.commons.utils;
import java.util.Iterator;
import java.util.Objects;
import java.util.logging.Logger;
/**
* Utilities on collections.<br />
* @author Alex
*/
public final class CollectionUtils {
/** Logger */
private static Logger lg = Logger.getLogger(CollectionUtils.class.getName());
/**
* Constructor #1.<br />
* Default private constructor.
*/
private CollectionUtils () {
super();
}
/**
* Check if a collection is sorted.<br />
* @param collection
* the collection to check.
* @return <code>true</code> if the collection is sorted.
*/
public static <T extends Comparable<? super T>> boolean isSorted (final Iterable<T> collection) {
Objects.requireNonNull(collection);
final Iterator<T> it = collection.iterator();
while (it.hasNext()) {
final T current = it.next();
if (it.hasNext() && current.compareTo(it.next()) > 0) {
return false;
}
}
return true;
}
}
## Instruction:
Use logger is method isSorted
## Code After:
package com.alexrnl.commons.utils;
import java.util.Iterator;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Utilities on collections.<br />
* @author Alex
*/
public final class CollectionUtils {
/** Logger */
private static Logger lg = Logger.getLogger(CollectionUtils.class.getName());
/**
* Constructor #1.<br />
* Default private constructor.
*/
private CollectionUtils () {
super();
}
/**
* Check if a collection is sorted.<br />
* @param collection
* the collection to check.
* @return <code>true</code> if the collection is sorted.
*/
public static <T extends Comparable<? super T>> boolean isSorted (final Iterable<T> collection) {
Objects.requireNonNull(collection);
final Iterator<T> it = collection.iterator();
while (it.hasNext()) {
final T current = it.next();
if (it.hasNext() && current.compareTo(it.next()) > 0) {
if (lg.isLoggable(Level.INFO)) {
lg.info("Collection is unordered at element " + current);
}
return false;
}
}
return true;
}
}
|
...
import java.util.Iterator;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
...
while (it.hasNext()) {
final T current = it.next();
if (it.hasNext() && current.compareTo(it.next()) > 0) {
if (lg.isLoggable(Level.INFO)) {
lg.info("Collection is unordered at element " + current);
}
return false;
}
}
...
|
06d210cdc811f0051a489f335cc94a604e99a35d
|
werobot/session/mongodbstorage.py
|
werobot/session/mongodbstorage.py
|
from werobot.session import SessionStorage
from werobot.utils import json_loads, json_dumps
class MongoDBStorage(SessionStorage):
"""
MongoDBStorage 会把你的 Session 数据储存在一个 MongoDB Collection 中 ::
import pymongo
import werobot
from werobot.session.mongodbstorage import MongoDBStorage
collection = pymongo.MongoClient()["wechat"]["session"]
session_storage = MongoDBStorage(collection)
robot = werobot.WeRoBot(token="token", enable_session=True,
session_storage=session_storage)
你需要安装 ``pymongo`` 才能使用 MongoDBStorage 。
:param collection: 一个 MongoDB Collection。
"""
def __init__(self, collection):
import pymongo
assert isinstance(collection,
pymongo.collection.Collection)
self.collection = collection
collection.create_index("wechat_id")
def _get_document(self, id):
return self.collection.find_one({"wechat_id": id})
def get(self, id):
document = self._get_document(id)
if document:
session_json = document["session"]
return json_loads(session_json)
return {}
def set(self, id, value):
document = self._get_document(id)
session = json_dumps(value)
if document:
document["session"] = session
self.collection.save(document)
else:
self.collection.insert({
"wechat_id": id,
"session": session
})
def delete(self, id):
document = self._get_document(id)
if document:
self.collection.remove(document["_id"])
|
from werobot.session import SessionStorage
from werobot.utils import json_loads, json_dumps
class MongoDBStorage(SessionStorage):
"""
MongoDBStorage 会把你的 Session 数据储存在一个 MongoDB Collection 中 ::
import pymongo
import werobot
from werobot.session.mongodbstorage import MongoDBStorage
collection = pymongo.MongoClient()["wechat"]["session"]
session_storage = MongoDBStorage(collection)
robot = werobot.WeRoBot(token="token", enable_session=True,
session_storage=session_storage)
你需要安装 ``pymongo`` 才能使用 MongoDBStorage 。
:param collection: 一个 MongoDB Collection。
"""
def __init__(self, collection):
self.collection = collection
collection.create_index("wechat_id")
def _get_document(self, id):
return self.collection.find_one({"wechat_id": id})
def get(self, id):
document = self._get_document(id)
if document:
session_json = document["session"]
return json_loads(session_json)
return {}
def set(self, id, value):
session = json_dumps(value)
self.collection.replace_one({
"wechat_id": id
}, {
"wechat_id": id,
"session": session
}, upsert=True)
def delete(self, id):
self.collection.delete_one({
"wechat_id": id
})
|
Use new pymongo API in MongoDBStorage
|
Use new pymongo API in MongoDBStorage
|
Python
|
mit
|
whtsky/WeRoBot,whtsky/WeRoBot,adam139/WeRobot,adam139/WeRobot,whtsky/WeRoBot,weberwang/WeRoBot,weberwang/WeRoBot
|
python
|
## Code Before:
from werobot.session import SessionStorage
from werobot.utils import json_loads, json_dumps
class MongoDBStorage(SessionStorage):
"""
MongoDBStorage 会把你的 Session 数据储存在一个 MongoDB Collection 中 ::
import pymongo
import werobot
from werobot.session.mongodbstorage import MongoDBStorage
collection = pymongo.MongoClient()["wechat"]["session"]
session_storage = MongoDBStorage(collection)
robot = werobot.WeRoBot(token="token", enable_session=True,
session_storage=session_storage)
你需要安装 ``pymongo`` 才能使用 MongoDBStorage 。
:param collection: 一个 MongoDB Collection。
"""
def __init__(self, collection):
import pymongo
assert isinstance(collection,
pymongo.collection.Collection)
self.collection = collection
collection.create_index("wechat_id")
def _get_document(self, id):
return self.collection.find_one({"wechat_id": id})
def get(self, id):
document = self._get_document(id)
if document:
session_json = document["session"]
return json_loads(session_json)
return {}
def set(self, id, value):
document = self._get_document(id)
session = json_dumps(value)
if document:
document["session"] = session
self.collection.save(document)
else:
self.collection.insert({
"wechat_id": id,
"session": session
})
def delete(self, id):
document = self._get_document(id)
if document:
self.collection.remove(document["_id"])
## Instruction:
Use new pymongo API in MongoDBStorage
## Code After:
from werobot.session import SessionStorage
from werobot.utils import json_loads, json_dumps
class MongoDBStorage(SessionStorage):
"""
MongoDBStorage 会把你的 Session 数据储存在一个 MongoDB Collection 中 ::
import pymongo
import werobot
from werobot.session.mongodbstorage import MongoDBStorage
collection = pymongo.MongoClient()["wechat"]["session"]
session_storage = MongoDBStorage(collection)
robot = werobot.WeRoBot(token="token", enable_session=True,
session_storage=session_storage)
你需要安装 ``pymongo`` 才能使用 MongoDBStorage 。
:param collection: 一个 MongoDB Collection。
"""
def __init__(self, collection):
self.collection = collection
collection.create_index("wechat_id")
def _get_document(self, id):
return self.collection.find_one({"wechat_id": id})
def get(self, id):
document = self._get_document(id)
if document:
session_json = document["session"]
return json_loads(session_json)
return {}
def set(self, id, value):
session = json_dumps(value)
self.collection.replace_one({
"wechat_id": id
}, {
"wechat_id": id,
"session": session
}, upsert=True)
def delete(self, id):
self.collection.delete_one({
"wechat_id": id
})
|
...
:param collection: 一个 MongoDB Collection。
"""
def __init__(self, collection):
self.collection = collection
collection.create_index("wechat_id")
...
return {}
def set(self, id, value):
session = json_dumps(value)
self.collection.replace_one({
"wechat_id": id
}, {
"wechat_id": id,
"session": session
}, upsert=True)
def delete(self, id):
self.collection.delete_one({
"wechat_id": id
})
...
|
a6d49059851450c7ea527941600564cb3f48cc72
|
flask_profiler/storage/base.py
|
flask_profiler/storage/base.py
|
class BaseStorage(object):
"""docstring for BaseStorage"""
def __init__(self):
super(BaseStorage, self).__init__()
def filter(self, criteria):
raise Exception("Not implemneted Error")
def getSummary(self, criteria):
raise Exception("Not implemneted Error")
def insert(self, measurement):
raise Exception("Not implemented Error")
def delete(self, measurementId):
raise Exception("Not imlemented Error")
|
class BaseStorage(object):
"""docstring for BaseStorage"""
def __init__(self):
super(BaseStorage, self).__init__()
def filter(self, criteria):
raise Exception("Not implemneted Error")
def getSummary(self, criteria):
raise Exception("Not implemneted Error")
def insert(self, measurement):
raise Exception("Not implemented Error")
def delete(self, measurementId):
raise Exception("Not imlemented Error")
def truncate(self):
raise Exception("Not imlemented Error")
|
Add tuncate method to BaseStorage class
|
Add tuncate method to BaseStorage class
This will provide an interface for supporting any new database, there by, making the code more robust.
|
Python
|
mit
|
muatik/flask-profiler
|
python
|
## Code Before:
class BaseStorage(object):
"""docstring for BaseStorage"""
def __init__(self):
super(BaseStorage, self).__init__()
def filter(self, criteria):
raise Exception("Not implemneted Error")
def getSummary(self, criteria):
raise Exception("Not implemneted Error")
def insert(self, measurement):
raise Exception("Not implemented Error")
def delete(self, measurementId):
raise Exception("Not imlemented Error")
## Instruction:
Add tuncate method to BaseStorage class
This will provide an interface for supporting any new database, there by, making the code more robust.
## Code After:
class BaseStorage(object):
"""docstring for BaseStorage"""
def __init__(self):
super(BaseStorage, self).__init__()
def filter(self, criteria):
raise Exception("Not implemneted Error")
def getSummary(self, criteria):
raise Exception("Not implemneted Error")
def insert(self, measurement):
raise Exception("Not implemented Error")
def delete(self, measurementId):
raise Exception("Not imlemented Error")
def truncate(self):
raise Exception("Not imlemented Error")
|
# ... existing code ...
def delete(self, measurementId):
raise Exception("Not imlemented Error")
def truncate(self):
raise Exception("Not imlemented Error")
# ... rest of the code ...
|
2438efb99b85fbc76cd285792c1511e7e2813a05
|
zeus/api/resources/repository_tests.py
|
zeus/api/resources/repository_tests.py
|
from datetime import timedelta
from sqlalchemy.sql import func
from zeus.config import db
from zeus.constants import Result, Status
from zeus.models import Repository, TestCase, Job
from zeus.utils import timezone
from .base_repository import BaseRepositoryResource
from ..schemas import TestCaseStatisticsSchema
testcases_schema = TestCaseStatisticsSchema(many=True)
class RepositoryTestsResource(BaseRepositoryResource):
def get(self, repo: Repository):
"""
Return a list of testcases for the given repository.
"""
runs_failed = (
func.count(TestCase.result)
.filter(TestCase.result == Result.failed)
.label("runs_failed")
)
query = (
db.session.query(
TestCase.hash,
TestCase.name,
func.count(TestCase.hash).label("runs_total"),
runs_failed,
func.avg(TestCase.duration).label("avg_duration"),
)
.join(Job, TestCase.job_id == Job.id)
.filter(
Job.repository_id == repo.id,
Job.date_finished >= timezone.now() - timedelta(days=14),
Job.status == Status.finished,
TestCase.repository_id == repo.id,
)
.group_by(TestCase.hash, TestCase.name)
.order_by(runs_failed.desc())
)
return self.paginate_with_schema(testcases_schema, query)
|
from datetime import timedelta
from sqlalchemy.sql import func
from zeus.config import db
from zeus.constants import Result, Status
from zeus.models import Repository, TestCase, Job
from zeus.utils import timezone
from .base_repository import BaseRepositoryResource
from ..schemas import TestCaseStatisticsSchema
testcases_schema = TestCaseStatisticsSchema(many=True)
class RepositoryTestsResource(BaseRepositoryResource):
def get(self, repo: Repository):
"""
Return a list of testcases for the given repository.
"""
runs_failed = (
func.count(TestCase.result)
.filter(TestCase.result == Result.failed)
.label("runs_failed")
)
query = (
db.session.query(
TestCase.hash,
TestCase.name,
func.count(TestCase.hash).label("runs_total"),
runs_failed,
func.avg(TestCase.duration).label("avg_duration"),
)
.filter(
TestCase.job_id.in_(
db.session.query(Job.id)
.filter(
Job.repository_id == repo.id,
Job.date_finished >= timezone.now() - timedelta(days=14),
Job.status == Status.finished,
)
.subquery()
)
)
.group_by(TestCase.hash, TestCase.name)
.order_by(runs_failed.desc())
)
return self.paginate_with_schema(testcases_schema, query)
|
Simplify query plan for repo tests
|
ref: Simplify query plan for repo tests
|
Python
|
apache-2.0
|
getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus
|
python
|
## Code Before:
from datetime import timedelta
from sqlalchemy.sql import func
from zeus.config import db
from zeus.constants import Result, Status
from zeus.models import Repository, TestCase, Job
from zeus.utils import timezone
from .base_repository import BaseRepositoryResource
from ..schemas import TestCaseStatisticsSchema
testcases_schema = TestCaseStatisticsSchema(many=True)
class RepositoryTestsResource(BaseRepositoryResource):
def get(self, repo: Repository):
"""
Return a list of testcases for the given repository.
"""
runs_failed = (
func.count(TestCase.result)
.filter(TestCase.result == Result.failed)
.label("runs_failed")
)
query = (
db.session.query(
TestCase.hash,
TestCase.name,
func.count(TestCase.hash).label("runs_total"),
runs_failed,
func.avg(TestCase.duration).label("avg_duration"),
)
.join(Job, TestCase.job_id == Job.id)
.filter(
Job.repository_id == repo.id,
Job.date_finished >= timezone.now() - timedelta(days=14),
Job.status == Status.finished,
TestCase.repository_id == repo.id,
)
.group_by(TestCase.hash, TestCase.name)
.order_by(runs_failed.desc())
)
return self.paginate_with_schema(testcases_schema, query)
## Instruction:
ref: Simplify query plan for repo tests
## Code After:
from datetime import timedelta
from sqlalchemy.sql import func
from zeus.config import db
from zeus.constants import Result, Status
from zeus.models import Repository, TestCase, Job
from zeus.utils import timezone
from .base_repository import BaseRepositoryResource
from ..schemas import TestCaseStatisticsSchema
testcases_schema = TestCaseStatisticsSchema(many=True)
class RepositoryTestsResource(BaseRepositoryResource):
def get(self, repo: Repository):
"""
Return a list of testcases for the given repository.
"""
runs_failed = (
func.count(TestCase.result)
.filter(TestCase.result == Result.failed)
.label("runs_failed")
)
query = (
db.session.query(
TestCase.hash,
TestCase.name,
func.count(TestCase.hash).label("runs_total"),
runs_failed,
func.avg(TestCase.duration).label("avg_duration"),
)
.filter(
TestCase.job_id.in_(
db.session.query(Job.id)
.filter(
Job.repository_id == repo.id,
Job.date_finished >= timezone.now() - timedelta(days=14),
Job.status == Status.finished,
)
.subquery()
)
)
.group_by(TestCase.hash, TestCase.name)
.order_by(runs_failed.desc())
)
return self.paginate_with_schema(testcases_schema, query)
|
...
runs_failed,
func.avg(TestCase.duration).label("avg_duration"),
)
.filter(
TestCase.job_id.in_(
db.session.query(Job.id)
.filter(
Job.repository_id == repo.id,
Job.date_finished >= timezone.now() - timedelta(days=14),
Job.status == Status.finished,
)
.subquery()
)
)
.group_by(TestCase.hash, TestCase.name)
.order_by(runs_failed.desc())
...
|
fd9584e6f2043d51f3d8feeae8ce6044056c028e
|
imagepipeline/src/main/java/com/facebook/imagepipeline/postprocessors/RoundAsCirclePostprocessor.java
|
imagepipeline/src/main/java/com/facebook/imagepipeline/postprocessors/RoundAsCirclePostprocessor.java
|
/*
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.imagepipeline.postprocessors;
import android.graphics.Bitmap;
import com.facebook.cache.common.CacheKey;
import com.facebook.cache.common.SimpleCacheKey;
import com.facebook.imagepipeline.nativecode.NativeRoundingFilter;
import com.facebook.imagepipeline.request.BasePostprocessor;
import javax.annotation.Nullable;
/** Postprocessor that rounds a given image as a circle. */
public class RoundAsCirclePostprocessor extends BasePostprocessor {
private @Nullable CacheKey mCacheKey;
@Override
public void process(Bitmap bitmap) {
NativeRoundingFilter.toCircle(bitmap);
}
@Nullable
@Override
public CacheKey getPostprocessorCacheKey() {
if (mCacheKey == null) {
mCacheKey = new SimpleCacheKey("RoundAsCirclePostprocessor");
}
return mCacheKey;
}
}
|
/*
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.imagepipeline.postprocessors;
import android.graphics.Bitmap;
import com.facebook.cache.common.CacheKey;
import com.facebook.cache.common.SimpleCacheKey;
import com.facebook.imagepipeline.nativecode.NativeRoundingFilter;
import com.facebook.imagepipeline.request.BasePostprocessor;
import javax.annotation.Nullable;
/** Postprocessor that rounds a given image as a circle. */
public class RoundAsCirclePostprocessor extends BasePostprocessor {
private static final boolean ENABLE_ANTI_ALIASING = true;
private @Nullable CacheKey mCacheKey;
private final boolean mEnableAntiAliasing;
public RoundAsCirclePostprocessor() {
this(ENABLE_ANTI_ALIASING);
}
public RoundAsCirclePostprocessor(boolean enableAntiAliasing) {
mEnableAntiAliasing = enableAntiAliasing;
}
@Override
public void process(Bitmap bitmap) {
NativeRoundingFilter.toCircle(bitmap, mEnableAntiAliasing);
}
@Nullable
@Override
public CacheKey getPostprocessorCacheKey() {
if (mCacheKey == null) {
if (mEnableAntiAliasing) {
mCacheKey = new SimpleCacheKey("RoundAsCirclePostprocessor#AntiAliased");
} else {
mCacheKey = new SimpleCacheKey("RoundAsCirclePostprocessor");
}
}
return mCacheKey;
}
}
|
Update existing native rounding post processor
|
Update existing native rounding post processor
Reviewed By: oprisnik
Differential Revision: D9607950
fbshipit-source-id: 080aa9cd339761a48e534c2fd4d3677005063e78
|
Java
|
mit
|
facebook/fresco,facebook/fresco,facebook/fresco,facebook/fresco,facebook/fresco,facebook/fresco
|
java
|
## Code Before:
/*
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.imagepipeline.postprocessors;
import android.graphics.Bitmap;
import com.facebook.cache.common.CacheKey;
import com.facebook.cache.common.SimpleCacheKey;
import com.facebook.imagepipeline.nativecode.NativeRoundingFilter;
import com.facebook.imagepipeline.request.BasePostprocessor;
import javax.annotation.Nullable;
/** Postprocessor that rounds a given image as a circle. */
public class RoundAsCirclePostprocessor extends BasePostprocessor {
private @Nullable CacheKey mCacheKey;
@Override
public void process(Bitmap bitmap) {
NativeRoundingFilter.toCircle(bitmap);
}
@Nullable
@Override
public CacheKey getPostprocessorCacheKey() {
if (mCacheKey == null) {
mCacheKey = new SimpleCacheKey("RoundAsCirclePostprocessor");
}
return mCacheKey;
}
}
## Instruction:
Update existing native rounding post processor
Reviewed By: oprisnik
Differential Revision: D9607950
fbshipit-source-id: 080aa9cd339761a48e534c2fd4d3677005063e78
## Code After:
/*
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.imagepipeline.postprocessors;
import android.graphics.Bitmap;
import com.facebook.cache.common.CacheKey;
import com.facebook.cache.common.SimpleCacheKey;
import com.facebook.imagepipeline.nativecode.NativeRoundingFilter;
import com.facebook.imagepipeline.request.BasePostprocessor;
import javax.annotation.Nullable;
/** Postprocessor that rounds a given image as a circle. */
public class RoundAsCirclePostprocessor extends BasePostprocessor {
private static final boolean ENABLE_ANTI_ALIASING = true;
private @Nullable CacheKey mCacheKey;
private final boolean mEnableAntiAliasing;
public RoundAsCirclePostprocessor() {
this(ENABLE_ANTI_ALIASING);
}
public RoundAsCirclePostprocessor(boolean enableAntiAliasing) {
mEnableAntiAliasing = enableAntiAliasing;
}
@Override
public void process(Bitmap bitmap) {
NativeRoundingFilter.toCircle(bitmap, mEnableAntiAliasing);
}
@Nullable
@Override
public CacheKey getPostprocessorCacheKey() {
if (mCacheKey == null) {
if (mEnableAntiAliasing) {
mCacheKey = new SimpleCacheKey("RoundAsCirclePostprocessor#AntiAliased");
} else {
mCacheKey = new SimpleCacheKey("RoundAsCirclePostprocessor");
}
}
return mCacheKey;
}
}
|
...
/** Postprocessor that rounds a given image as a circle. */
public class RoundAsCirclePostprocessor extends BasePostprocessor {
private static final boolean ENABLE_ANTI_ALIASING = true;
private @Nullable CacheKey mCacheKey;
private final boolean mEnableAntiAliasing;
public RoundAsCirclePostprocessor() {
this(ENABLE_ANTI_ALIASING);
}
public RoundAsCirclePostprocessor(boolean enableAntiAliasing) {
mEnableAntiAliasing = enableAntiAliasing;
}
@Override
public void process(Bitmap bitmap) {
NativeRoundingFilter.toCircle(bitmap, mEnableAntiAliasing);
}
@Nullable
...
@Override
public CacheKey getPostprocessorCacheKey() {
if (mCacheKey == null) {
if (mEnableAntiAliasing) {
mCacheKey = new SimpleCacheKey("RoundAsCirclePostprocessor#AntiAliased");
} else {
mCacheKey = new SimpleCacheKey("RoundAsCirclePostprocessor");
}
}
return mCacheKey;
}
...
|
8528beef5d10355af07f641b4987df3cd64a7b0f
|
sprockets/mixins/metrics/__init__.py
|
sprockets/mixins/metrics/__init__.py
|
from .influxdb import InfluxDBMixin
from .statsd import StatsdMixin
version_info = (1, 0, 0)
__version__ = '.'.join(str(v) for v in version_info)
__all__ = ['InfluxDBMixin', 'StatsdMixin']
|
try:
from .influxdb import InfluxDBMixin
from .statsd import StatsdMixin
except ImportError as error:
def InfluxDBMixin(*args, **kwargs):
raise error
def StatsdMixin(*args, **kwargs):
raise error
version_info = (1, 0, 0)
__version__ = '.'.join(str(v) for v in version_info)
__all__ = ['InfluxDBMixin', 'StatsdMixin']
|
Make it safe to import __version__.
|
Make it safe to import __version__.
|
Python
|
bsd-3-clause
|
sprockets/sprockets.mixins.metrics
|
python
|
## Code Before:
from .influxdb import InfluxDBMixin
from .statsd import StatsdMixin
version_info = (1, 0, 0)
__version__ = '.'.join(str(v) for v in version_info)
__all__ = ['InfluxDBMixin', 'StatsdMixin']
## Instruction:
Make it safe to import __version__.
## Code After:
try:
from .influxdb import InfluxDBMixin
from .statsd import StatsdMixin
except ImportError as error:
def InfluxDBMixin(*args, **kwargs):
raise error
def StatsdMixin(*args, **kwargs):
raise error
version_info = (1, 0, 0)
__version__ = '.'.join(str(v) for v in version_info)
__all__ = ['InfluxDBMixin', 'StatsdMixin']
|
# ... existing code ...
try:
from .influxdb import InfluxDBMixin
from .statsd import StatsdMixin
except ImportError as error:
def InfluxDBMixin(*args, **kwargs):
raise error
def StatsdMixin(*args, **kwargs):
raise error
version_info = (1, 0, 0)
__version__ = '.'.join(str(v) for v in version_info)
# ... rest of the code ...
|
33d8e9ce8be2901dab5998192559b0e1c3408807
|
kikola/core/context_processors.py
|
kikola/core/context_processors.py
|
def path(request):
"""
kikola.core.context_processors.path
===================================
Adds current path and full path variables to templates.
To enable, adds ``kikola.core.context_processors.path`` to your project's
``settings`` ``TEMPLATE_CONTEXT_PROCESSORS`` var.
**Note:** Django has ``django.core.context_processors.request`` context
processor that adding current ``HttpRequest`` object to templates.
"""
return {'REQUEST_FULL_PATH': request.get_full_path(),
'REQUEST_PATH': request.path}
|
def path(request):
"""
Adds current absolute URI, path and full path variables to templates.
To enable, adds ``kikola.core.context_processors.path`` to your project's
``settings`` ``TEMPLATE_CONTEXT_PROCESSORS`` var.
**Note:** Django has ``django.core.context_processors.request`` context
processor that adding whole ``HttpRequest`` object to templates.
"""
return {'REQUEST_ABSOLUTE_URI': request.build_absolute_uri(),
'REQUEST_FULL_PATH': request.get_full_path(),
'REQUEST_PATH': request.path}
|
Make ``path`` context processor return request absolute URI too.
|
Make ``path`` context processor return request absolute URI too.
|
Python
|
bsd-3-clause
|
playpauseandstop/kikola
|
python
|
## Code Before:
def path(request):
"""
kikola.core.context_processors.path
===================================
Adds current path and full path variables to templates.
To enable, adds ``kikola.core.context_processors.path`` to your project's
``settings`` ``TEMPLATE_CONTEXT_PROCESSORS`` var.
**Note:** Django has ``django.core.context_processors.request`` context
processor that adding current ``HttpRequest`` object to templates.
"""
return {'REQUEST_FULL_PATH': request.get_full_path(),
'REQUEST_PATH': request.path}
## Instruction:
Make ``path`` context processor return request absolute URI too.
## Code After:
def path(request):
"""
Adds current absolute URI, path and full path variables to templates.
To enable, adds ``kikola.core.context_processors.path`` to your project's
``settings`` ``TEMPLATE_CONTEXT_PROCESSORS`` var.
**Note:** Django has ``django.core.context_processors.request`` context
processor that adding whole ``HttpRequest`` object to templates.
"""
return {'REQUEST_ABSOLUTE_URI': request.build_absolute_uri(),
'REQUEST_FULL_PATH': request.get_full_path(),
'REQUEST_PATH': request.path}
|
# ... existing code ...
def path(request):
"""
Adds current absolute URI, path and full path variables to templates.
To enable, adds ``kikola.core.context_processors.path`` to your project's
``settings`` ``TEMPLATE_CONTEXT_PROCESSORS`` var.
**Note:** Django has ``django.core.context_processors.request`` context
processor that adding whole ``HttpRequest`` object to templates.
"""
return {'REQUEST_ABSOLUTE_URI': request.build_absolute_uri(),
'REQUEST_FULL_PATH': request.get_full_path(),
'REQUEST_PATH': request.path}
# ... rest of the code ...
|
b03ed6307bd1354b931cdd993361d0a40a1d6850
|
api/init/graphqlapi/proxy.py
|
api/init/graphqlapi/proxy.py
|
import graphqlapi.utils as utils
from graphql.parser import GraphQLParser
from graphqlapi.interceptor import ExecuteBatch, TestDataSource
from graphqlapi.exceptions import RequestException
interceptors = [
ExecuteBatch(),
TestDataSource()
]
def proxy_request(payload: dict):
graphql_ast = parse_query(payload['query'])
# Execute request on GraphQL API
status, data = utils.execute_graphql_request(payload['query'])
for interceptor in interceptors:
if interceptor.can_handle(graphql_ast):
data = interceptor.after_request(graphql_ast, status, data)
return 200 if status == 200 else 500, data
def parse_query(payload_query: str):
try:
return GraphQLParser().parse(payload_query)
except Exception:
raise RequestException(400, 'Invalid GraphQL query')
|
import graphqlapi.utils as utils
from graphqlapi.exceptions import RequestException
from graphqlapi.interceptor import ExecuteBatch, TestDataSource
from graphql.parser import GraphQLParser
interceptors = [
ExecuteBatch(),
TestDataSource()
]
def proxy_request(payload: dict):
graphql_ast = parse_query(payload['query'])
# Execute request on GraphQL API
status, data = utils.execute_graphql_request(payload['query'])
for interceptor in interceptors:
if interceptor.can_handle(graphql_ast):
data = interceptor.after_request(graphql_ast, status, data)
return 200 if status == 200 else 500, data
def parse_query(payload_query: str):
try:
return GraphQLParser().parse(payload_query)
except Exception:
raise RequestException(400, 'Invalid GraphQL query')
|
Reorder imports in alphabetical order
|
Reorder imports in alphabetical order
|
Python
|
apache-2.0
|
alexisrolland/data-quality,alexisrolland/data-quality,alexisrolland/data-quality,alexisrolland/data-quality
|
python
|
## Code Before:
import graphqlapi.utils as utils
from graphql.parser import GraphQLParser
from graphqlapi.interceptor import ExecuteBatch, TestDataSource
from graphqlapi.exceptions import RequestException
interceptors = [
ExecuteBatch(),
TestDataSource()
]
def proxy_request(payload: dict):
graphql_ast = parse_query(payload['query'])
# Execute request on GraphQL API
status, data = utils.execute_graphql_request(payload['query'])
for interceptor in interceptors:
if interceptor.can_handle(graphql_ast):
data = interceptor.after_request(graphql_ast, status, data)
return 200 if status == 200 else 500, data
def parse_query(payload_query: str):
try:
return GraphQLParser().parse(payload_query)
except Exception:
raise RequestException(400, 'Invalid GraphQL query')
## Instruction:
Reorder imports in alphabetical order
## Code After:
import graphqlapi.utils as utils
from graphqlapi.exceptions import RequestException
from graphqlapi.interceptor import ExecuteBatch, TestDataSource
from graphql.parser import GraphQLParser
interceptors = [
ExecuteBatch(),
TestDataSource()
]
def proxy_request(payload: dict):
graphql_ast = parse_query(payload['query'])
# Execute request on GraphQL API
status, data = utils.execute_graphql_request(payload['query'])
for interceptor in interceptors:
if interceptor.can_handle(graphql_ast):
data = interceptor.after_request(graphql_ast, status, data)
return 200 if status == 200 else 500, data
def parse_query(payload_query: str):
try:
return GraphQLParser().parse(payload_query)
except Exception:
raise RequestException(400, 'Invalid GraphQL query')
|
...
import graphqlapi.utils as utils
from graphqlapi.exceptions import RequestException
from graphqlapi.interceptor import ExecuteBatch, TestDataSource
from graphql.parser import GraphQLParser
interceptors = [
...
|
cd219d5ee0ecbd54705c5add4239cef1513b8c2a
|
dodocs/__init__.py
|
dodocs/__init__.py
|
import sys
import colorama
from dodocs.cmdline import parse
__version__ = "0.0.1"
colorama.init(autoreset=True)
def main(argv=None):
"""
Main code
Parameters
----------
argv : list of strings, optional
command line arguments
"""
args = parse(argv=argv)
if args.subparser_name == "profile":
from dodocs.profiles import main
main(args)
# elif args.subparser_name == "mkvenv":
# from dodocs.venvs import create
# create(args)
# elif args.subparser_name == "build":
# print("building")
else:
msg = colorama.Fore.RED + "Please provide a command."
msg += " Valid commands are:\n * profile" # \n * create"
sys.exit(msg)
|
import sys
import colorama
from dodocs.cmdline import parse
__version__ = "0.0.1"
colorama.init(autoreset=True)
def main(argv=None):
"""
Main code
Parameters
----------
argv : list of strings, optional
command line arguments
"""
args = parse(argv=argv)
try:
args.func(args)
except AttributeError:
# defaults profile to list
if args.subparser_name == 'profile' and args.profile_cmd is None:
main([args.subparser_name, 'list'])
# in the other cases suggest to run -h
msg = colorama.Fore.RED + "Please provide a valid command."
print(msg)
msg = "Type\n " + sys.argv[0]
if args.subparser_name is not None:
msg += " " + args.subparser_name
msg += ' -h'
print(msg)
|
Use args.func. Deal with failures, default "profile'
|
Use args.func. Deal with failures, default "profile'
|
Python
|
mit
|
montefra/dodocs
|
python
|
## Code Before:
import sys
import colorama
from dodocs.cmdline import parse
__version__ = "0.0.1"
colorama.init(autoreset=True)
def main(argv=None):
"""
Main code
Parameters
----------
argv : list of strings, optional
command line arguments
"""
args = parse(argv=argv)
if args.subparser_name == "profile":
from dodocs.profiles import main
main(args)
# elif args.subparser_name == "mkvenv":
# from dodocs.venvs import create
# create(args)
# elif args.subparser_name == "build":
# print("building")
else:
msg = colorama.Fore.RED + "Please provide a command."
msg += " Valid commands are:\n * profile" # \n * create"
sys.exit(msg)
## Instruction:
Use args.func. Deal with failures, default "profile'
## Code After:
import sys
import colorama
from dodocs.cmdline import parse
__version__ = "0.0.1"
colorama.init(autoreset=True)
def main(argv=None):
"""
Main code
Parameters
----------
argv : list of strings, optional
command line arguments
"""
args = parse(argv=argv)
try:
args.func(args)
except AttributeError:
# defaults profile to list
if args.subparser_name == 'profile' and args.profile_cmd is None:
main([args.subparser_name, 'list'])
# in the other cases suggest to run -h
msg = colorama.Fore.RED + "Please provide a valid command."
print(msg)
msg = "Type\n " + sys.argv[0]
if args.subparser_name is not None:
msg += " " + args.subparser_name
msg += ' -h'
print(msg)
|
...
"""
args = parse(argv=argv)
try:
args.func(args)
except AttributeError:
# defaults profile to list
if args.subparser_name == 'profile' and args.profile_cmd is None:
main([args.subparser_name, 'list'])
# in the other cases suggest to run -h
msg = colorama.Fore.RED + "Please provide a valid command."
print(msg)
msg = "Type\n " + sys.argv[0]
if args.subparser_name is not None:
msg += " " + args.subparser_name
msg += ' -h'
print(msg)
...
|
0235bd2ec4410a7d4e3fd7ef4fc6d2ac98730f30
|
src/adts/adts_display.h
|
src/adts/adts_display.h
|
/**
**************************************************************************
* \brief
* preprocessor conditional printf formatter output
*
* \details
* Input arguments are equivalent to printf. referrence printf man pages
* for api details
*
**************************************************************************
*/
#if defined(__ADTS_DISPLAY)
#define CDISPLAY(_format, ...) \
do { \
char _buffer[256] = {0}; \
\
sprintf(_buffer, _format, ## __VA_ARGS__); \
printf("%3d %4d %-25.25s %-30.30s %s\n", \
sched_getcpu(), __LINE__, __FILE__, __FUNCTION__, _buffer); \
\
/* Serialize console output on exit/error */ \
fflush(stdout); \
} while(0);
#else
#define CDISPLAY(_format, ...) /* compile disabled */
#endif
/**
**************************************************************************
* \details
* Count digits in decimal number
*
**************************************************************************
*/
inline size_t
adts_digits_decimal( int32_t val )
{
size_t digits = 0;
while (val) {
val /= 10;
digits++;
}
return digits;
} /* adts_digits_decimal() */
|
/**
**************************************************************************
* \brief
* preprocessor conditional printf formatter output
*
* \details
* Input arguments are equivalent to printf. referrence printf man pages
* for api details
*
**************************************************************************
*/
#if defined(__ADTS_DISPLAY)
#define CDISPLAY(_format, ...) \
do { \
char _buffer[256] = {0}; \
size_t _limit = sizeof(_buffer) - 1; \
\
snprintf(_buffer, _limit, _format, ## __VA_ARGS__); \
printf("%3d %4d %-25.25s %-30.30s %s\n", \
sched_getcpu(), __LINE__, __FILE__, __FUNCTION__, _buffer); \
\
/* Serialize console output on exit/error */ \
fflush(stdout); \
} while(0);
#else
#define CDISPLAY(_format, ...) /* compile disabled */
#endif
/**
**************************************************************************
* \details
* Count digits in decimal number
*
**************************************************************************
*/
inline size_t
adts_digits_decimal( int32_t val )
{
size_t digits = 0;
while (val) {
val /= 10;
digits++;
}
return digits;
} /* adts_digits_decimal() */
|
Add buffer overflow safety to CDISPLAY
|
Add buffer overflow safety to CDISPLAY
|
C
|
mit
|
78613/sample,78613/sample
|
c
|
## Code Before:
/**
**************************************************************************
* \brief
* preprocessor conditional printf formatter output
*
* \details
* Input arguments are equivalent to printf. referrence printf man pages
* for api details
*
**************************************************************************
*/
#if defined(__ADTS_DISPLAY)
#define CDISPLAY(_format, ...) \
do { \
char _buffer[256] = {0}; \
\
sprintf(_buffer, _format, ## __VA_ARGS__); \
printf("%3d %4d %-25.25s %-30.30s %s\n", \
sched_getcpu(), __LINE__, __FILE__, __FUNCTION__, _buffer); \
\
/* Serialize console output on exit/error */ \
fflush(stdout); \
} while(0);
#else
#define CDISPLAY(_format, ...) /* compile disabled */
#endif
/**
**************************************************************************
* \details
* Count digits in decimal number
*
**************************************************************************
*/
inline size_t
adts_digits_decimal( int32_t val )
{
size_t digits = 0;
while (val) {
val /= 10;
digits++;
}
return digits;
} /* adts_digits_decimal() */
## Instruction:
Add buffer overflow safety to CDISPLAY
## Code After:
/**
**************************************************************************
* \brief
* preprocessor conditional printf formatter output
*
* \details
* Input arguments are equivalent to printf. referrence printf man pages
* for api details
*
**************************************************************************
*/
#if defined(__ADTS_DISPLAY)
#define CDISPLAY(_format, ...) \
do { \
char _buffer[256] = {0}; \
size_t _limit = sizeof(_buffer) - 1; \
\
snprintf(_buffer, _limit, _format, ## __VA_ARGS__); \
printf("%3d %4d %-25.25s %-30.30s %s\n", \
sched_getcpu(), __LINE__, __FILE__, __FUNCTION__, _buffer); \
\
/* Serialize console output on exit/error */ \
fflush(stdout); \
} while(0);
#else
#define CDISPLAY(_format, ...) /* compile disabled */
#endif
/**
**************************************************************************
* \details
* Count digits in decimal number
*
**************************************************************************
*/
inline size_t
adts_digits_decimal( int32_t val )
{
size_t digits = 0;
while (val) {
val /= 10;
digits++;
}
return digits;
} /* adts_digits_decimal() */
|
# ... existing code ...
**************************************************************************
*/
#if defined(__ADTS_DISPLAY)
#define CDISPLAY(_format, ...) \
do { \
char _buffer[256] = {0}; \
size_t _limit = sizeof(_buffer) - 1; \
\
snprintf(_buffer, _limit, _format, ## __VA_ARGS__); \
printf("%3d %4d %-25.25s %-30.30s %s\n", \
sched_getcpu(), __LINE__, __FILE__, __FUNCTION__, _buffer); \
\
/* Serialize console output on exit/error */ \
fflush(stdout); \
} while(0);
#else
#define CDISPLAY(_format, ...) /* compile disabled */
# ... rest of the code ...
|
770f9dd75a223fb31a18af2fcb089398663f2065
|
concentration.py
|
concentration.py
|
from major import Major
class Concentration(Major):
def __init__(self, dept="NONE"):
super().__init__(dept, path="concentrations/")
if __name__ == '__main__':
tmp = [
Concentration(dept="Asian")
]
for i in tmp:
print(i)
|
from major import Major
class Concentration(Major):
def __init__(self, dept="NONE"):
super().__init__(dept, path="concentrations/")
def getConcentrationRequirement(self, string):
return self.requirements[string]
if __name__ == '__main__':
tmp = [
Concentration(dept="Asian")
]
for i in tmp:
print(i)
|
Add a getConcentrationRequirement to corrospond to getMajorRequirement
|
Add a getConcentrationRequirement to corrospond to getMajorRequirement
|
Python
|
agpl-3.0
|
hawkrives/gobbldygook,hawkrives/gobbldygook,hawkrives/gobbldygook
|
python
|
## Code Before:
from major import Major
class Concentration(Major):
def __init__(self, dept="NONE"):
super().__init__(dept, path="concentrations/")
if __name__ == '__main__':
tmp = [
Concentration(dept="Asian")
]
for i in tmp:
print(i)
## Instruction:
Add a getConcentrationRequirement to corrospond to getMajorRequirement
## Code After:
from major import Major
class Concentration(Major):
def __init__(self, dept="NONE"):
super().__init__(dept, path="concentrations/")
def getConcentrationRequirement(self, string):
return self.requirements[string]
if __name__ == '__main__':
tmp = [
Concentration(dept="Asian")
]
for i in tmp:
print(i)
|
...
class Concentration(Major):
def __init__(self, dept="NONE"):
super().__init__(dept, path="concentrations/")
def getConcentrationRequirement(self, string):
return self.requirements[string]
if __name__ == '__main__':
tmp = [
...
|
fc73dfb33f4e19d649672f19a1dc4cf09b229d29
|
echo_server.py
|
echo_server.py
|
"""Echo server in socket connection: receives and sends back a message."""
import socket
if __name__ == '__main__':
"""Run from terminal, this will recieve a messages and send them back."""
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
socket.IPPROTO_IP)
server_socket.bind(('127.0.0.1', 50000))
server_socket.listen(1)
buffsize = 32
try:
while True:
msg = ''
done = False
conn, addr = server_socket.accept()
while not done:
msg_part = conn.recv(buffsize)
msg += msg_part
if len(msg_part) < buffsize:
done = True
conn.sendall(msg)
conn.shutdown(socket.SHUT_WR)
conn.close()
except KeyboardInterrupt:
print 'I successfully stopped.'
server_socket.close()
|
"""Echo server in socket connection: receives and sends back a message."""
import socket
def response_ok():
"""Return byte string 200 ok response."""
return u"HTTP/1.1 200 OK\nContent-Type: text/plain\nContent-length: 18\n\r\neverything is okay".encode('utf-8')
def reponse_error(error_code, reason):
"""Return byte string error code."""
return u"HTTP/1.1 {} {}".format(error_code, reason).encode('utf-8')
if __name__ == '__main__':
"""Run from terminal, this will recieve a messages and send them back."""
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
socket.IPPROTO_IP)
server_socket.bind(('127.0.0.1', 50000))
server_socket.listen(1)
buffsize = 32
try:
while True:
msg = ''
done = False
conn, addr = server_socket.accept()
while not done:
msg_part = conn.recv(buffsize)
msg += msg_part
if len(msg_part) < buffsize:
done = True
conn.sendall(msg)
conn.shutdown(socket.SHUT_WR)
conn.close()
except KeyboardInterrupt:
print 'I successfully stopped.'
server_socket.close()
|
Add response_ok and response_error methods which return byte strings.
|
Add response_ok and response_error methods which return byte strings.
|
Python
|
mit
|
bm5w/network_tools
|
python
|
## Code Before:
"""Echo server in socket connection: receives and sends back a message."""
import socket
if __name__ == '__main__':
"""Run from terminal, this will recieve a messages and send them back."""
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
socket.IPPROTO_IP)
server_socket.bind(('127.0.0.1', 50000))
server_socket.listen(1)
buffsize = 32
try:
while True:
msg = ''
done = False
conn, addr = server_socket.accept()
while not done:
msg_part = conn.recv(buffsize)
msg += msg_part
if len(msg_part) < buffsize:
done = True
conn.sendall(msg)
conn.shutdown(socket.SHUT_WR)
conn.close()
except KeyboardInterrupt:
print 'I successfully stopped.'
server_socket.close()
## Instruction:
Add response_ok and response_error methods which return byte strings.
## Code After:
"""Echo server in socket connection: receives and sends back a message."""
import socket
def response_ok():
"""Return byte string 200 ok response."""
return u"HTTP/1.1 200 OK\nContent-Type: text/plain\nContent-length: 18\n\r\neverything is okay".encode('utf-8')
def reponse_error(error_code, reason):
"""Return byte string error code."""
return u"HTTP/1.1 {} {}".format(error_code, reason).encode('utf-8')
if __name__ == '__main__':
"""Run from terminal, this will recieve a messages and send them back."""
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
socket.IPPROTO_IP)
server_socket.bind(('127.0.0.1', 50000))
server_socket.listen(1)
buffsize = 32
try:
while True:
msg = ''
done = False
conn, addr = server_socket.accept()
while not done:
msg_part = conn.recv(buffsize)
msg += msg_part
if len(msg_part) < buffsize:
done = True
conn.sendall(msg)
conn.shutdown(socket.SHUT_WR)
conn.close()
except KeyboardInterrupt:
print 'I successfully stopped.'
server_socket.close()
|
...
"""Echo server in socket connection: receives and sends back a message."""
import socket
def response_ok():
"""Return byte string 200 ok response."""
return u"HTTP/1.1 200 OK\nContent-Type: text/plain\nContent-length: 18\n\r\neverything is okay".encode('utf-8')
def reponse_error(error_code, reason):
"""Return byte string error code."""
return u"HTTP/1.1 {} {}".format(error_code, reason).encode('utf-8')
if __name__ == '__main__':
...
|
ebd6d12ca16003e771a7015505be1b42d96483a3
|
roles/gvl.commandline-utilities/templates/jupyterhub_config.py
|
roles/gvl.commandline-utilities/templates/jupyterhub_config.py
|
c.JupyterHub.ip = '127.0.0.1'
# The ip for the proxy API handlers
c.JupyterHub.proxy_api_ip = '127.0.0.1'
# The public facing port of the proxy
c.JupyterHub.port = 9510
# The base URL of the entire application
c.JupyterHub.base_url = '/jupyterhub'
# The ip for this process
c.JupyterHub.hub_ip = '127.0.0.1'
# put the log file in /var/log
c.JupyterHub.extra_log_file = '/var/log/jupyterhub.log'
#------------------------------------------------------------------------------
# Spawner configuration
#------------------------------------------------------------------------------
# The IP address (or hostname) the single-user server should listen on
c.Spawner.ip = '127.0.0.1'
#------------------------------------------------------------------------------
# Authenticator configuration
#------------------------------------------------------------------------------
# A class for authentication.
#
# The API is one method, `authenticate`, a tornado gen.coroutine.
# set of usernames of admin users
#
# If unspecified, only the user that launches the server will be admin.
c.Authenticator.admin_users = {'root', 'ubuntu'}
|
c.JupyterHub.ip = '127.0.0.1'
# The ip for the proxy API handlers
c.JupyterHub.proxy_api_ip = '127.0.0.1'
# The public facing port of the proxy
c.JupyterHub.port = 9510
# The base URL of the entire application
c.JupyterHub.base_url = '/jupyterhub'
# The ip for this process
c.JupyterHub.hub_ip = '127.0.0.1'
# put the log file in /var/log
c.JupyterHub.extra_log_file = '/var/log/jupyterhub.log'
c.JupyterHub.log_level = 'WARN'
#------------------------------------------------------------------------------
# Spawner configuration
#------------------------------------------------------------------------------
# The IP address (or hostname) the single-user server should listen on
c.Spawner.ip = '127.0.0.1'
#------------------------------------------------------------------------------
# Authenticator configuration
#------------------------------------------------------------------------------
# A class for authentication.
#
# The API is one method, `authenticate`, a tornado gen.coroutine.
# set of usernames of admin users
#
# If unspecified, only the user that launches the server will be admin.
c.Authenticator.admin_users = {'root', 'ubuntu'}
|
Set log level to 'WARN'
|
Set log level to 'WARN'
|
Python
|
mit
|
gvlproject/gvl_commandline_utilities,nuwang/gvl_commandline_utilities,claresloggett/gvl_commandline_utilities,nuwang/gvl_commandline_utilities,claresloggett/gvl_commandline_utilities,gvlproject/gvl_commandline_utilities
|
python
|
## Code Before:
c.JupyterHub.ip = '127.0.0.1'
# The ip for the proxy API handlers
c.JupyterHub.proxy_api_ip = '127.0.0.1'
# The public facing port of the proxy
c.JupyterHub.port = 9510
# The base URL of the entire application
c.JupyterHub.base_url = '/jupyterhub'
# The ip for this process
c.JupyterHub.hub_ip = '127.0.0.1'
# put the log file in /var/log
c.JupyterHub.extra_log_file = '/var/log/jupyterhub.log'
#------------------------------------------------------------------------------
# Spawner configuration
#------------------------------------------------------------------------------
# The IP address (or hostname) the single-user server should listen on
c.Spawner.ip = '127.0.0.1'
#------------------------------------------------------------------------------
# Authenticator configuration
#------------------------------------------------------------------------------
# A class for authentication.
#
# The API is one method, `authenticate`, a tornado gen.coroutine.
# set of usernames of admin users
#
# If unspecified, only the user that launches the server will be admin.
c.Authenticator.admin_users = {'root', 'ubuntu'}
## Instruction:
Set log level to 'WARN'
## Code After:
c.JupyterHub.ip = '127.0.0.1'
# The ip for the proxy API handlers
c.JupyterHub.proxy_api_ip = '127.0.0.1'
# The public facing port of the proxy
c.JupyterHub.port = 9510
# The base URL of the entire application
c.JupyterHub.base_url = '/jupyterhub'
# The ip for this process
c.JupyterHub.hub_ip = '127.0.0.1'
# put the log file in /var/log
c.JupyterHub.extra_log_file = '/var/log/jupyterhub.log'
c.JupyterHub.log_level = 'WARN'
#------------------------------------------------------------------------------
# Spawner configuration
#------------------------------------------------------------------------------
# The IP address (or hostname) the single-user server should listen on
c.Spawner.ip = '127.0.0.1'
#------------------------------------------------------------------------------
# Authenticator configuration
#------------------------------------------------------------------------------
# A class for authentication.
#
# The API is one method, `authenticate`, a tornado gen.coroutine.
# set of usernames of admin users
#
# If unspecified, only the user that launches the server will be admin.
c.Authenticator.admin_users = {'root', 'ubuntu'}
|
// ... existing code ...
# put the log file in /var/log
c.JupyterHub.extra_log_file = '/var/log/jupyterhub.log'
c.JupyterHub.log_level = 'WARN'
#------------------------------------------------------------------------------
# Spawner configuration
// ... rest of the code ...
|
5394589f53072a71942a11695470d7ca97ab7a70
|
tests/testTime.c
|
tests/testTime.c
|
int main(int argc, char **argv) {
struct timeval tv;
struct timezone tz;
struct tm *tm;
gettimeofday(&tv, &tz);
tm = localtime(&tv.tv_sec);
char timestr[128];
size_t length = strftime(timestr, 128, "%F %T", tm);
snprintf(timestr+length, 128-length, ".%ld", tv.tv_usec/1000);
printf("Time string: %s\n", timestr);
}
|
int main(int argc, char **argv) {
struct timeval tv;
struct timezone tz;
struct tm *tm;
gettimeofday(&tv, &tz);
tm = localtime(&tv.tv_sec);
char timestr[128];
size_t length = strftime(timestr, 128, "%F %T", tm);
snprintf(timestr+length, 128-length, ".%ld", tv.tv_usec/1000);
printf("Time string: %s\n", timestr);
long ms = htobl(tv.tv_sec)*1000 + htobl(tv.tv_usec)/1000;
int64_t ms64 = htobl(tv.tv_sec)*1000 + htobl(tv.tv_usec)/1000;
printf("Sizeof(long) = %d, ms=%ld, ms64=%ld\n", sizeof(ms), ms, ms64);
}
|
Test long size and timeval to long conversion
|
Test long size and timeval to long conversion
|
C
|
apache-2.0
|
starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser
|
c
|
## Code Before:
int main(int argc, char **argv) {
struct timeval tv;
struct timezone tz;
struct tm *tm;
gettimeofday(&tv, &tz);
tm = localtime(&tv.tv_sec);
char timestr[128];
size_t length = strftime(timestr, 128, "%F %T", tm);
snprintf(timestr+length, 128-length, ".%ld", tv.tv_usec/1000);
printf("Time string: %s\n", timestr);
}
## Instruction:
Test long size and timeval to long conversion
## Code After:
int main(int argc, char **argv) {
struct timeval tv;
struct timezone tz;
struct tm *tm;
gettimeofday(&tv, &tz);
tm = localtime(&tv.tv_sec);
char timestr[128];
size_t length = strftime(timestr, 128, "%F %T", tm);
snprintf(timestr+length, 128-length, ".%ld", tv.tv_usec/1000);
printf("Time string: %s\n", timestr);
long ms = htobl(tv.tv_sec)*1000 + htobl(tv.tv_usec)/1000;
int64_t ms64 = htobl(tv.tv_sec)*1000 + htobl(tv.tv_usec)/1000;
printf("Sizeof(long) = %d, ms=%ld, ms64=%ld\n", sizeof(ms), ms, ms64);
}
|
...
size_t length = strftime(timestr, 128, "%F %T", tm);
snprintf(timestr+length, 128-length, ".%ld", tv.tv_usec/1000);
printf("Time string: %s\n", timestr);
long ms = htobl(tv.tv_sec)*1000 + htobl(tv.tv_usec)/1000;
int64_t ms64 = htobl(tv.tv_sec)*1000 + htobl(tv.tv_usec)/1000;
printf("Sizeof(long) = %d, ms=%ld, ms64=%ld\n", sizeof(ms), ms, ms64);
}
...
|
797da1bd335c0d8237ff4ee4785fe7aca76f0b84
|
setup.py
|
setup.py
|
from setuptools import setup
setup(
name='pusher',
version='1.2.0',
description='A Python library to interract with the Pusher API',
url='https://github.com/pusher/pusher-http-python',
author='Pusher',
author_email='[email protected]',
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Internet :: WWW/HTTP",
],
keywords='pusher rest realtime websockets service',
license='MIT',
packages=[
'pusher'
],
install_requires=['six', 'requests>=2.3.0', 'urllib3', 'pyopenssl', 'ndg-httpsclient', 'pyasn1'],
tests_require=['nose', 'mock', 'HTTPretty'],
extras_require={
'aiohttp': ["aiohttp>=0.9.0"],
'tornado': ['tornado>=4.0.0']
},
test_suite='pusher_tests',
)
|
from setuptools import setup
setup(
name='pusher',
version='1.2.0',
description='A Python library to interract with the Pusher API',
url='https://github.com/pusher/pusher-http-python',
author='Pusher',
author_email='[email protected]',
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Internet :: WWW/HTTP",
],
keywords='pusher rest realtime websockets service',
license='MIT',
packages=[
'pusher'
],
install_requires=['six', 'requests>=2.3.0', 'urllib3', 'pyopenssl', 'ndg-httpsclient', 'pyasn1'],
tests_require=['nose', 'mock', 'HTTPretty'],
extras_require={
'aiohttp': ["aiohttp>=0.9.0"],
'tornado': ['tornado>=4.0.0']
},
package_data={
'pusher': ['cacert.pem']
},
test_suite='pusher_tests',
)
|
Include cacert.pem as part of the package
|
Include cacert.pem as part of the package
|
Python
|
mit
|
hkjallbring/pusher-http-python,pusher/pusher-http-python
|
python
|
## Code Before:
from setuptools import setup
setup(
name='pusher',
version='1.2.0',
description='A Python library to interract with the Pusher API',
url='https://github.com/pusher/pusher-http-python',
author='Pusher',
author_email='[email protected]',
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Internet :: WWW/HTTP",
],
keywords='pusher rest realtime websockets service',
license='MIT',
packages=[
'pusher'
],
install_requires=['six', 'requests>=2.3.0', 'urllib3', 'pyopenssl', 'ndg-httpsclient', 'pyasn1'],
tests_require=['nose', 'mock', 'HTTPretty'],
extras_require={
'aiohttp': ["aiohttp>=0.9.0"],
'tornado': ['tornado>=4.0.0']
},
test_suite='pusher_tests',
)
## Instruction:
Include cacert.pem as part of the package
## Code After:
from setuptools import setup
setup(
name='pusher',
version='1.2.0',
description='A Python library to interract with the Pusher API',
url='https://github.com/pusher/pusher-http-python',
author='Pusher',
author_email='[email protected]',
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Internet :: WWW/HTTP",
],
keywords='pusher rest realtime websockets service',
license='MIT',
packages=[
'pusher'
],
install_requires=['six', 'requests>=2.3.0', 'urllib3', 'pyopenssl', 'ndg-httpsclient', 'pyasn1'],
tests_require=['nose', 'mock', 'HTTPretty'],
extras_require={
'aiohttp': ["aiohttp>=0.9.0"],
'tornado': ['tornado>=4.0.0']
},
package_data={
'pusher': ['cacert.pem']
},
test_suite='pusher_tests',
)
|
...
'tornado': ['tornado>=4.0.0']
},
package_data={
'pusher': ['cacert.pem']
},
test_suite='pusher_tests',
)
...
|
d8b3e511b00c9b5a8c7951e16d06173fe93d6501
|
engine/util.py
|
engine/util.py
|
import json
import threading
import Queue
from datetime import datetime,date,timedelta
import time
from tornado import gen
from tornado.ioloop import IOLoop
@gen.coroutine
def async_sleep(seconds):
yield gen.Task(IOLoop.instance().add_timeout, time.time() + seconds)
def delayed(seconds):
def f(x):
time.sleep(seconds)
return x
return f
def call_in_background(f, *args):
'''Call function in background in a separate thread / coroutine'''
result = Queue.Queue(1)
t = threading.Thread(target=lambda: result.put(f(*args)))
t.start()
return result
def get_id_from_slug(slug):
'''Remove '/' from a part of url if it is present'''
return slug if slug[-1] != '/' else slug[:-1]
def my_print(s):
'''Pretty printing with timestamp'''
print "[" + str(datetime.now()) + "] " + s
class DateTimeEncoder(json.JSONEncoder):
'''Auxuliary class that lets us encode dates in json'''
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
elif isinstance(obj, date):
return obj.isoformat()
elif isinstance(obj, timedelta):
return (datetime.min + obj).time().isoformat()
else:
return super(DateTimeEncoder, self).default(obj)
|
import json
import threading
import Queue
from datetime import datetime,date,timedelta
import time
import numpy
from tornado import gen
from tornado.ioloop import IOLoop
@gen.coroutine
def async_sleep(seconds):
yield gen.Task(IOLoop.instance().add_timeout, time.time() + seconds)
def delayed(seconds):
def f(x):
time.sleep(seconds)
return x
return f
def call_in_background(f, *args):
'''Call function in background in a separate thread / coroutine'''
result = Queue.Queue(1)
t = threading.Thread(target=lambda: result.put(f(*args)))
t.start()
return result
def get_id_from_slug(slug):
'''Remove '/' from a part of url if it is present'''
return slug if slug[-1] != '/' else slug[:-1]
def my_print(s):
'''Pretty printing with timestamp'''
print "[" + str(datetime.now()) + "] " + s
class DateTimeEncoder(json.JSONEncoder):
'''Auxuliary class that lets us encode dates in json'''
def default(self, obj):
if hasattr(obj, 'isoformat'):
return obj.isoformat()
elif isinstance(obj, datetime):
return obj.isoformat()
elif isinstance(obj, date):
return obj.isoformat()
elif isinstance(obj, timedelta):
return (datetime.min + obj).time().isoformat()
elif isinstance(obj, numpy.generic):
return numpy.asscalar(obj)
else:
return super(DateTimeEncoder, self).default(obj)
|
Fix conditions in JSON encoder
|
Fix conditions in JSON encoder
|
Python
|
apache-2.0
|
METASPACE2020/sm-engine,SpatialMetabolomics/SM_distributed,METASPACE2020/sm-engine,SpatialMetabolomics/SM_distributed,SpatialMetabolomics/SM_distributed,SpatialMetabolomics/SM_distributed
|
python
|
## Code Before:
import json
import threading
import Queue
from datetime import datetime,date,timedelta
import time
from tornado import gen
from tornado.ioloop import IOLoop
@gen.coroutine
def async_sleep(seconds):
yield gen.Task(IOLoop.instance().add_timeout, time.time() + seconds)
def delayed(seconds):
def f(x):
time.sleep(seconds)
return x
return f
def call_in_background(f, *args):
'''Call function in background in a separate thread / coroutine'''
result = Queue.Queue(1)
t = threading.Thread(target=lambda: result.put(f(*args)))
t.start()
return result
def get_id_from_slug(slug):
'''Remove '/' from a part of url if it is present'''
return slug if slug[-1] != '/' else slug[:-1]
def my_print(s):
'''Pretty printing with timestamp'''
print "[" + str(datetime.now()) + "] " + s
class DateTimeEncoder(json.JSONEncoder):
'''Auxuliary class that lets us encode dates in json'''
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
elif isinstance(obj, date):
return obj.isoformat()
elif isinstance(obj, timedelta):
return (datetime.min + obj).time().isoformat()
else:
return super(DateTimeEncoder, self).default(obj)
## Instruction:
Fix conditions in JSON encoder
## Code After:
import json
import threading
import Queue
from datetime import datetime,date,timedelta
import time
import numpy
from tornado import gen
from tornado.ioloop import IOLoop
@gen.coroutine
def async_sleep(seconds):
yield gen.Task(IOLoop.instance().add_timeout, time.time() + seconds)
def delayed(seconds):
def f(x):
time.sleep(seconds)
return x
return f
def call_in_background(f, *args):
'''Call function in background in a separate thread / coroutine'''
result = Queue.Queue(1)
t = threading.Thread(target=lambda: result.put(f(*args)))
t.start()
return result
def get_id_from_slug(slug):
'''Remove '/' from a part of url if it is present'''
return slug if slug[-1] != '/' else slug[:-1]
def my_print(s):
'''Pretty printing with timestamp'''
print "[" + str(datetime.now()) + "] " + s
class DateTimeEncoder(json.JSONEncoder):
'''Auxuliary class that lets us encode dates in json'''
def default(self, obj):
if hasattr(obj, 'isoformat'):
return obj.isoformat()
elif isinstance(obj, datetime):
return obj.isoformat()
elif isinstance(obj, date):
return obj.isoformat()
elif isinstance(obj, timedelta):
return (datetime.min + obj).time().isoformat()
elif isinstance(obj, numpy.generic):
return numpy.asscalar(obj)
else:
return super(DateTimeEncoder, self).default(obj)
|
// ... existing code ...
from datetime import datetime,date,timedelta
import time
import numpy
from tornado import gen
from tornado.ioloop import IOLoop
// ... modified code ...
class DateTimeEncoder(json.JSONEncoder):
'''Auxuliary class that lets us encode dates in json'''
def default(self, obj):
if hasattr(obj, 'isoformat'):
return obj.isoformat()
elif isinstance(obj, datetime):
return obj.isoformat()
elif isinstance(obj, date):
return obj.isoformat()
elif isinstance(obj, timedelta):
return (datetime.min + obj).time().isoformat()
elif isinstance(obj, numpy.generic):
return numpy.asscalar(obj)
else:
return super(DateTimeEncoder, self).default(obj)
// ... rest of the code ...
|
a92121cfdbb94d36d021fb8d1386031829ee86a2
|
patterns/solid.py
|
patterns/solid.py
|
import blinkypattern
class Solid(blinkypattern.BlinkyPattern):
def __init__(self, blinkytape, solid_color):
super(Solid, self).__init__(blinkytape)
self._pixels = [solid_color] * self._blinkytape.pixel_count
def setup(self):
super(Solid, self).setup()
self._blinkytape.set_pixels(self._pixels)
self._blinkytape.update()
|
class Solid(object):
def __init__(self, pixel_count, color):
self._pixels = [color] * pixel_count
@property
def pixels(self):
return self._pixels
|
Update Solid pattern for refactor
|
Update Solid pattern for refactor
|
Python
|
mit
|
jonspeicher/blinkyfun
|
python
|
## Code Before:
import blinkypattern
class Solid(blinkypattern.BlinkyPattern):
def __init__(self, blinkytape, solid_color):
super(Solid, self).__init__(blinkytape)
self._pixels = [solid_color] * self._blinkytape.pixel_count
def setup(self):
super(Solid, self).setup()
self._blinkytape.set_pixels(self._pixels)
self._blinkytape.update()
## Instruction:
Update Solid pattern for refactor
## Code After:
class Solid(object):
def __init__(self, pixel_count, color):
self._pixels = [color] * pixel_count
@property
def pixels(self):
return self._pixels
|
// ... existing code ...
class Solid(object):
def __init__(self, pixel_count, color):
self._pixels = [color] * pixel_count
@property
def pixels(self):
return self._pixels
// ... rest of the code ...
|
3566560a1d8f49394f642d000ba3d3bb7646bdf6
|
src/java/fault/LoadBalancer.java
|
src/java/fault/LoadBalancer.java
|
package fault;
import fault.concurrent.DefaultResilientPromise;
import fault.concurrent.ResilientFuture;
import fault.concurrent.ResilientPromise;
import fault.utils.ResilientPatternAction;
/**
* Created by timbrooks on 6/4/15.
*/
public class LoadBalancer<T, C> implements Pattern {
@Override
public ResilientFuture<T> submitAction(ResilientPatternAction action, long millisTimeout) {
return submitAction(action, new DefaultResilientPromise(), null, millisTimeout);
}
@Override
public ResilientFuture<T> submitAction(ResilientPatternAction action, ResilientCallback callback,
long millisTimeout) {
return null;
}
@Override
public ResilientFuture<T> submitAction(ResilientPatternAction action, ResilientPromise promise,
long millisTimeout) {
return null;
}
@Override
public ResilientFuture<T> submitAction(ResilientPatternAction action, ResilientPromise promise,
ResilientCallback callback, long millisTimeout) {
return null;
}
@Override
public ResilientPromise<T> performAction(ResilientPatternAction action) {
return null;
}
}
|
package fault;
import fault.concurrent.DefaultResilientPromise;
import fault.concurrent.ResilientFuture;
import fault.concurrent.ResilientPromise;
import fault.utils.ResilientPatternAction;
/**
* Created by timbrooks on 6/4/15.
*/
public class LoadBalancer<C> implements Pattern<C> {
@Override
public <T> ResilientFuture<T> submitAction(ResilientPatternAction<T, C> action, long millisTimeout) {
return submitAction(action, new DefaultResilientPromise<T>(), null, millisTimeout);
}
@Override
public <T> ResilientFuture<T> submitAction(ResilientPatternAction<T, C> action, ResilientCallback<T> callback,
long millisTimeout) {
return submitAction(action, new DefaultResilientPromise<T>(), callback, millisTimeout);
}
@Override
public <T> ResilientFuture<T> submitAction(ResilientPatternAction<T, C> action, ResilientPromise<T> promise,
long millisTimeout) {
return submitAction(action, promise, null, millisTimeout);
}
@Override
public <T> ResilientFuture<T> submitAction(ResilientPatternAction<T, C> action, ResilientPromise<T> promise,
ResilientCallback<T> callback, long millisTimeout) {
return submitAction(action, promise, callback, millisTimeout);
}
@Override
public <T> ResilientPromise<T> performAction(ResilientPatternAction<T, C> action) {
return null;
}
}
|
Fix type relationship. And have methods calls each other
|
Fix type relationship. And have methods calls each other
|
Java
|
apache-2.0
|
tbrooks8/Beehive
|
java
|
## Code Before:
package fault;
import fault.concurrent.DefaultResilientPromise;
import fault.concurrent.ResilientFuture;
import fault.concurrent.ResilientPromise;
import fault.utils.ResilientPatternAction;
/**
* Created by timbrooks on 6/4/15.
*/
public class LoadBalancer<T, C> implements Pattern {
@Override
public ResilientFuture<T> submitAction(ResilientPatternAction action, long millisTimeout) {
return submitAction(action, new DefaultResilientPromise(), null, millisTimeout);
}
@Override
public ResilientFuture<T> submitAction(ResilientPatternAction action, ResilientCallback callback,
long millisTimeout) {
return null;
}
@Override
public ResilientFuture<T> submitAction(ResilientPatternAction action, ResilientPromise promise,
long millisTimeout) {
return null;
}
@Override
public ResilientFuture<T> submitAction(ResilientPatternAction action, ResilientPromise promise,
ResilientCallback callback, long millisTimeout) {
return null;
}
@Override
public ResilientPromise<T> performAction(ResilientPatternAction action) {
return null;
}
}
## Instruction:
Fix type relationship. And have methods calls each other
## Code After:
package fault;
import fault.concurrent.DefaultResilientPromise;
import fault.concurrent.ResilientFuture;
import fault.concurrent.ResilientPromise;
import fault.utils.ResilientPatternAction;
/**
* Created by timbrooks on 6/4/15.
*/
public class LoadBalancer<C> implements Pattern<C> {
@Override
public <T> ResilientFuture<T> submitAction(ResilientPatternAction<T, C> action, long millisTimeout) {
return submitAction(action, new DefaultResilientPromise<T>(), null, millisTimeout);
}
@Override
public <T> ResilientFuture<T> submitAction(ResilientPatternAction<T, C> action, ResilientCallback<T> callback,
long millisTimeout) {
return submitAction(action, new DefaultResilientPromise<T>(), callback, millisTimeout);
}
@Override
public <T> ResilientFuture<T> submitAction(ResilientPatternAction<T, C> action, ResilientPromise<T> promise,
long millisTimeout) {
return submitAction(action, promise, null, millisTimeout);
}
@Override
public <T> ResilientFuture<T> submitAction(ResilientPatternAction<T, C> action, ResilientPromise<T> promise,
ResilientCallback<T> callback, long millisTimeout) {
return submitAction(action, promise, callback, millisTimeout);
}
@Override
public <T> ResilientPromise<T> performAction(ResilientPatternAction<T, C> action) {
return null;
}
}
|
// ... existing code ...
/**
* Created by timbrooks on 6/4/15.
*/
public class LoadBalancer<C> implements Pattern<C> {
@Override
public <T> ResilientFuture<T> submitAction(ResilientPatternAction<T, C> action, long millisTimeout) {
return submitAction(action, new DefaultResilientPromise<T>(), null, millisTimeout);
}
@Override
public <T> ResilientFuture<T> submitAction(ResilientPatternAction<T, C> action, ResilientCallback<T> callback,
long millisTimeout) {
return submitAction(action, new DefaultResilientPromise<T>(), callback, millisTimeout);
}
@Override
public <T> ResilientFuture<T> submitAction(ResilientPatternAction<T, C> action, ResilientPromise<T> promise,
long millisTimeout) {
return submitAction(action, promise, null, millisTimeout);
}
@Override
public <T> ResilientFuture<T> submitAction(ResilientPatternAction<T, C> action, ResilientPromise<T> promise,
ResilientCallback<T> callback, long millisTimeout) {
return submitAction(action, promise, callback, millisTimeout);
}
@Override
public <T> ResilientPromise<T> performAction(ResilientPatternAction<T, C> action) {
return null;
}
}
// ... rest of the code ...
|
e1c58062db9c107c358e3617793aaed7cdb3a133
|
jobmon/util.py
|
jobmon/util.py
|
import os
import threading
class TerminableThreadMixin:
"""
TerminableThreadMixin is useful for threads that need to be terminated
from the outside. It provides a method called 'terminate', which communicates
to the thread that it needs to die, and then waits for the death to occur.
It imposes the following rules:
1. Call it's .__init__ inside of your __init__
2. Use the .reader inside of the thread - when it has data written on it,
that is an exit request
3. Call it's .cleanup method before exiting.
"""
def __init__(self):
reader, writer = os.pipe()
self.exit_reader = os.fdopen(reader, 'rb')
self.exit_writer = os.fdopen(writer, 'wb')
def cleanup(self):
self.exit_reader.close()
self.exit_writer.close()
def terminate(self):
"""
Asynchronously terminates the thread, without waiting for it to exit.
"""
try:
self.exit_writer.write(b' ')
self.exit_writer.flush()
except ValueError:
pass
def wait_for_exit(self):
"""
Waits for the thread to exit - should be run only after terminating
the thread.
"""
self.join()
|
import logging
import os
import threading
def reset_loggers():
"""
Removes all handlers from the current loggers to allow for a new basicConfig.
"""
root = logging.getLogger()
for handler in root.handlers[:]:
root.removeHandler(handler)
class TerminableThreadMixin:
"""
TerminableThreadMixin is useful for threads that need to be terminated
from the outside. It provides a method called 'terminate', which communicates
to the thread that it needs to die, and then waits for the death to occur.
It imposes the following rules:
1. Call it's .__init__ inside of your __init__
2. Use the .reader inside of the thread - when it has data written on it,
that is an exit request
3. Call it's .cleanup method before exiting.
"""
def __init__(self):
reader, writer = os.pipe()
self.exit_reader = os.fdopen(reader, 'rb')
self.exit_writer = os.fdopen(writer, 'wb')
def cleanup(self):
self.exit_reader.close()
self.exit_writer.close()
def terminate(self):
"""
Asynchronously terminates the thread, without waiting for it to exit.
"""
try:
self.exit_writer.write(b' ')
self.exit_writer.flush()
except ValueError:
pass
def wait_for_exit(self):
"""
Waits for the thread to exit - should be run only after terminating
the thread.
"""
self.join()
|
Add way to reset loggers
|
Add way to reset loggers
logging.basicConfig doesn't reset the current logging infrastructure, which
was messing up some tests that expected logs to be one place even though
they ended up in another
|
Python
|
bsd-2-clause
|
adamnew123456/jobmon
|
python
|
## Code Before:
import os
import threading
class TerminableThreadMixin:
"""
TerminableThreadMixin is useful for threads that need to be terminated
from the outside. It provides a method called 'terminate', which communicates
to the thread that it needs to die, and then waits for the death to occur.
It imposes the following rules:
1. Call it's .__init__ inside of your __init__
2. Use the .reader inside of the thread - when it has data written on it,
that is an exit request
3. Call it's .cleanup method before exiting.
"""
def __init__(self):
reader, writer = os.pipe()
self.exit_reader = os.fdopen(reader, 'rb')
self.exit_writer = os.fdopen(writer, 'wb')
def cleanup(self):
self.exit_reader.close()
self.exit_writer.close()
def terminate(self):
"""
Asynchronously terminates the thread, without waiting for it to exit.
"""
try:
self.exit_writer.write(b' ')
self.exit_writer.flush()
except ValueError:
pass
def wait_for_exit(self):
"""
Waits for the thread to exit - should be run only after terminating
the thread.
"""
self.join()
## Instruction:
Add way to reset loggers
logging.basicConfig doesn't reset the current logging infrastructure, which
was messing up some tests that expected logs to be one place even though
they ended up in another
## Code After:
import logging
import os
import threading
def reset_loggers():
"""
Removes all handlers from the current loggers to allow for a new basicConfig.
"""
root = logging.getLogger()
for handler in root.handlers[:]:
root.removeHandler(handler)
class TerminableThreadMixin:
"""
TerminableThreadMixin is useful for threads that need to be terminated
from the outside. It provides a method called 'terminate', which communicates
to the thread that it needs to die, and then waits for the death to occur.
It imposes the following rules:
1. Call it's .__init__ inside of your __init__
2. Use the .reader inside of the thread - when it has data written on it,
that is an exit request
3. Call it's .cleanup method before exiting.
"""
def __init__(self):
reader, writer = os.pipe()
self.exit_reader = os.fdopen(reader, 'rb')
self.exit_writer = os.fdopen(writer, 'wb')
def cleanup(self):
self.exit_reader.close()
self.exit_writer.close()
def terminate(self):
"""
Asynchronously terminates the thread, without waiting for it to exit.
"""
try:
self.exit_writer.write(b' ')
self.exit_writer.flush()
except ValueError:
pass
def wait_for_exit(self):
"""
Waits for the thread to exit - should be run only after terminating
the thread.
"""
self.join()
|
...
import logging
import os
import threading
def reset_loggers():
"""
Removes all handlers from the current loggers to allow for a new basicConfig.
"""
root = logging.getLogger()
for handler in root.handlers[:]:
root.removeHandler(handler)
class TerminableThreadMixin:
"""
...
|
176c03e26f46bad73df39c11ea4a190baca6fe54
|
apps/authentication/tests.py
|
apps/authentication/tests.py
|
from django.core.urlresolvers import reverse
from django.test import TestCase
class HTTPGetRootTestCase(TestCase):
def setUp(self):
pass
def test_get_root_expect_http_200(self):
url = reverse('microauth_authentication:index')
response = self.client.get(url)
self.assertEqual(200, response.status_code, 'Expect root view to load without issues.')
|
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.utils import override_settings
class HTTPGetRootTestCase(TestCase):
def setUp(self):
pass
def test_get_root_expect_http_200(self):
pipeline_settings = settings.PIPELINE
pipeline_settings['PIPELINE_ENABLED'] = False
with override_settings(PIPELINE_SETTINGS=pipeline_settings):
url = reverse('microauth_authentication:index')
response = self.client.get(url)
self.assertEqual(200, response.status_code, 'Expect root view to load without issues.')
|
Make test not depend on django-pipeline
|
Make test not depend on django-pipeline
|
Python
|
mit
|
microserv/microauth,microserv/microauth,microserv/microauth
|
python
|
## Code Before:
from django.core.urlresolvers import reverse
from django.test import TestCase
class HTTPGetRootTestCase(TestCase):
def setUp(self):
pass
def test_get_root_expect_http_200(self):
url = reverse('microauth_authentication:index')
response = self.client.get(url)
self.assertEqual(200, response.status_code, 'Expect root view to load without issues.')
## Instruction:
Make test not depend on django-pipeline
## Code After:
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.utils import override_settings
class HTTPGetRootTestCase(TestCase):
def setUp(self):
pass
def test_get_root_expect_http_200(self):
pipeline_settings = settings.PIPELINE
pipeline_settings['PIPELINE_ENABLED'] = False
with override_settings(PIPELINE_SETTINGS=pipeline_settings):
url = reverse('microauth_authentication:index')
response = self.client.get(url)
self.assertEqual(200, response.status_code, 'Expect root view to load without issues.')
|
# ... existing code ...
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.utils import override_settings
class HTTPGetRootTestCase(TestCase):
# ... modified code ...
pass
def test_get_root_expect_http_200(self):
pipeline_settings = settings.PIPELINE
pipeline_settings['PIPELINE_ENABLED'] = False
with override_settings(PIPELINE_SETTINGS=pipeline_settings):
url = reverse('microauth_authentication:index')
response = self.client.get(url)
self.assertEqual(200, response.status_code, 'Expect root view to load without issues.')
# ... rest of the code ...
|
45542f012b3dc6d089bc991529523a4ea6401b35
|
br_rss/boilerroomtv/management/commands/scrape_all.py
|
br_rss/boilerroomtv/management/commands/scrape_all.py
|
from django.core.management.base import BaseCommand
from boilerroomtv.tasks import scrape_genres, scrape_all_recordings, scrape_channels
class Command(BaseCommand):
def handle(self, *args, **options):
scrape_genres()
scrape_all_recordings()
scrape_channels()
|
from django.core.management.base import BaseCommand
from ...tasks import scrape_genres, scrape_all_recordings, scrape_channels
class Command(BaseCommand):
def handle(self, *args, **options):
scrape_genres()
scrape_all_recordings()
scrape_channels()
|
Use relative import in command.
|
Use relative import in command.
|
Python
|
mpl-2.0
|
jeffbr13/br-rss,jeffbr13/br-rss
|
python
|
## Code Before:
from django.core.management.base import BaseCommand
from boilerroomtv.tasks import scrape_genres, scrape_all_recordings, scrape_channels
class Command(BaseCommand):
def handle(self, *args, **options):
scrape_genres()
scrape_all_recordings()
scrape_channels()
## Instruction:
Use relative import in command.
## Code After:
from django.core.management.base import BaseCommand
from ...tasks import scrape_genres, scrape_all_recordings, scrape_channels
class Command(BaseCommand):
def handle(self, *args, **options):
scrape_genres()
scrape_all_recordings()
scrape_channels()
|
...
from django.core.management.base import BaseCommand
from ...tasks import scrape_genres, scrape_all_recordings, scrape_channels
class Command(BaseCommand):
...
|
143af64f9435b3964ee618cccb89e7ad211e030a
|
db/__init__.py
|
db/__init__.py
|
from .common import session_scope
def commit_db_item(db_item):
with session_scope() as session:
session.merge(db_item)
session.commit()
|
from .common import session_scope
def commit_db_item(db_item):
with session_scope() as session:
session.merge(db_item)
session.commit()
def create_or_update_db_item(db_item, new_item):
"""
Updates an existing or creates a new database item.
"""
with session_scope() as session:
# if database item exists
if db_item is not None:
# returning if database item is unchanged
if db_item == new_item:
return
# updating database item otherwise
else:
db_item.update(new_item)
session.merge(db_item)
# creating database item otherwise
else:
session.add(new_item)
session.commit()
|
Add utility function to create or update database items
|
Add utility function to create or update database items
|
Python
|
mit
|
leaffan/pynhldb
|
python
|
## Code Before:
from .common import session_scope
def commit_db_item(db_item):
with session_scope() as session:
session.merge(db_item)
session.commit()
## Instruction:
Add utility function to create or update database items
## Code After:
from .common import session_scope
def commit_db_item(db_item):
with session_scope() as session:
session.merge(db_item)
session.commit()
def create_or_update_db_item(db_item, new_item):
"""
Updates an existing or creates a new database item.
"""
with session_scope() as session:
# if database item exists
if db_item is not None:
# returning if database item is unchanged
if db_item == new_item:
return
# updating database item otherwise
else:
db_item.update(new_item)
session.merge(db_item)
# creating database item otherwise
else:
session.add(new_item)
session.commit()
|
// ... existing code ...
with session_scope() as session:
session.merge(db_item)
session.commit()
def create_or_update_db_item(db_item, new_item):
"""
Updates an existing or creates a new database item.
"""
with session_scope() as session:
# if database item exists
if db_item is not None:
# returning if database item is unchanged
if db_item == new_item:
return
# updating database item otherwise
else:
db_item.update(new_item)
session.merge(db_item)
# creating database item otherwise
else:
session.add(new_item)
session.commit()
// ... rest of the code ...
|
517c0f2b1f8e6616cc63ec0c3990dcff2922f0e6
|
pinax/invitations/admin.py
|
pinax/invitations/admin.py
|
from django.contrib import admin
from django.contrib.auth import get_user_model
from .models import InvitationStat, JoinInvitation
User = get_user_model()
class InvitationStatAdmin(admin.ModelAdmin):
raw_id_fields = ["user"]
readonly_fields = ["invites_sent", "invites_accepted"]
list_display = [
"user",
"invites_sent",
"invites_accepted",
"invites_allocated",
"invites_remaining",
"can_send"
]
list_filter = ["invites_sent", "invites_accepted"]
admin.site.register(
JoinInvitation,
list_display=["from_user", "to_user", "sent", "status", "to_user_email"],
list_filter=["sent", "status"],
search_fields=["from_user__{}".format(User.USERNAME_FIELD)]
)
admin.site.register(InvitationStat, InvitationStatAdmin)
|
from django.contrib import admin
from django.contrib.auth import get_user_model
from .models import InvitationStat, JoinInvitation
User = get_user_model()
class InvitationStatAdmin(admin.ModelAdmin):
raw_id_fields = ["user"]
readonly_fields = ["invites_sent", "invites_accepted"]
list_display = [
"user",
"invites_sent",
"invites_accepted",
"invites_allocated",
"invites_remaining",
"can_send"
]
list_filter = ["invites_sent", "invites_accepted"]
admin.site.register(
JoinInvitation,
list_display=["from_user", "to_user", "sent", "status", "to_user_email"],
list_filter=["sent", "status"],
search_fields=[f"from_user__{User.USERNAME_FIELD}"]
)
admin.site.register(InvitationStat, InvitationStatAdmin)
|
Use f-strings in place of `str.format()`
|
Use f-strings in place of `str.format()`
|
Python
|
unknown
|
pinax/pinax-invitations,eldarion/kaleo
|
python
|
## Code Before:
from django.contrib import admin
from django.contrib.auth import get_user_model
from .models import InvitationStat, JoinInvitation
User = get_user_model()
class InvitationStatAdmin(admin.ModelAdmin):
raw_id_fields = ["user"]
readonly_fields = ["invites_sent", "invites_accepted"]
list_display = [
"user",
"invites_sent",
"invites_accepted",
"invites_allocated",
"invites_remaining",
"can_send"
]
list_filter = ["invites_sent", "invites_accepted"]
admin.site.register(
JoinInvitation,
list_display=["from_user", "to_user", "sent", "status", "to_user_email"],
list_filter=["sent", "status"],
search_fields=["from_user__{}".format(User.USERNAME_FIELD)]
)
admin.site.register(InvitationStat, InvitationStatAdmin)
## Instruction:
Use f-strings in place of `str.format()`
## Code After:
from django.contrib import admin
from django.contrib.auth import get_user_model
from .models import InvitationStat, JoinInvitation
User = get_user_model()
class InvitationStatAdmin(admin.ModelAdmin):
raw_id_fields = ["user"]
readonly_fields = ["invites_sent", "invites_accepted"]
list_display = [
"user",
"invites_sent",
"invites_accepted",
"invites_allocated",
"invites_remaining",
"can_send"
]
list_filter = ["invites_sent", "invites_accepted"]
admin.site.register(
JoinInvitation,
list_display=["from_user", "to_user", "sent", "status", "to_user_email"],
list_filter=["sent", "status"],
search_fields=[f"from_user__{User.USERNAME_FIELD}"]
)
admin.site.register(InvitationStat, InvitationStatAdmin)
|
// ... existing code ...
JoinInvitation,
list_display=["from_user", "to_user", "sent", "status", "to_user_email"],
list_filter=["sent", "status"],
search_fields=[f"from_user__{User.USERNAME_FIELD}"]
)
admin.site.register(InvitationStat, InvitationStatAdmin)
// ... rest of the code ...
|
89454b1e83e01a4d523b776f74429a81467762da
|
redis/utils.py
|
redis/utils.py
|
try:
import hiredis
HIREDIS_AVAILABLE = True
except ImportError:
HIREDIS_AVAILABLE = False
def from_url(url, db=None, **kwargs):
"""
Returns an active Redis client generated from the given database URL.
Will attempt to extract the database id from the path url fragment, if
none is provided.
"""
from redis.client import Redis
return Redis.from_url(url, db, **kwargs)
from contextlib import contextmanager
@contextmanager
def pipeline(redis_obj):
p = redis_obj.pipeline()
yield p
p.execute()
|
from contextlib import contextmanager
try:
import hiredis
HIREDIS_AVAILABLE = True
except ImportError:
HIREDIS_AVAILABLE = False
def from_url(url, db=None, **kwargs):
"""
Returns an active Redis client generated from the given database URL.
Will attempt to extract the database id from the path url fragment, if
none is provided.
"""
from redis.client import Redis
return Redis.from_url(url, db, **kwargs)
@contextmanager
def pipeline(redis_obj):
p = redis_obj.pipeline()
yield p
p.execute()
|
Move import statement on top for PEP8 compliancy.
|
Move import statement on top for PEP8 compliancy.
|
Python
|
mit
|
MegaByte875/redis-py,fengshao0907/redis-py,sigma-random/redis-py,sunminghong/redis-py,garnertb/redis-py,softliumin/redis-py,sirk390/redis-py,barseghyanartur/redis-py,zhangyancoder/redis-py,LTD-Beget/redis-py,boyxuper/redis-py,barseghyanartur/redis-py,dmugtasimov/redis-py,LTD-Beget/redis-py,yuruidong/redis-py,sigma-random/redis-py,VishvajitP/redis-py,boyxuper/redis-py,barseghyanartur/redis-py,thedrow/redis-py,siryuan525614/python_operation,ContextLogic/redis-py,andymccurdy/redis-py,Kazanz/redis-py,mozillazg/redis-py-doc,joshowen/redis-py,joshowen/redis-py,MrKiven/redis-py,rcrdclub/redis-py,ze-phyr-us/redis-py,RedisLabs/redis-py,maxikov/redis-py,dylanjw/redis-py,wfxiang08/redis-py,dmoliveira/redis-py,fengshao0907/redis-py,kaushik94/redis-py,sirk390/redis-py,siryuan525614/python_operation,RedisLabs/redis-py,JamieCressey/redispy,piperck/redis-py,kaushik94/redis-py,Kazanz/redis-py,5977862/redis-py,kouhou/redis-py,dmugtasimov/redis-py,wfxiang08/redis-py,fengsp/redis-py,ffrree/redis-py,harlowja/redis-py,mozillazg/redis-py-doc,VishvajitP/redis-py,sunminghong/redis-py,yuruidong/redis-py,alisaifee/redis-py,ferrero-zhang/redis-py,thedrow/redis-py,JamieCressey/redispy,MrKiven/redis-py,harlowja/redis-py,cvrebert/redis-py,lamby/redis-py,jparise/redis-py,fengsp/redis-py,piperck/redis-py,andymccurdy/redis-py,kouhou/redis-py,boyxuper/redis-py,ycaihua/redis-py,forblackking/redis-py,MegaByte875/redis-py,alisaifee/redis-py,yihuang/redis-py,ContextLogic/redis-py,5977862/redis-py,LTD-Beget/redis-py,softliumin/redis-py,ffrree/redis-py,kouhou/redis-py,redis/redis-py,joshowen/redis-py,nfvs/redis-py,ycaihua/redis-py,softliumin/redis-py,5977862/redis-py,andymccurdy/redis-py,pombredanne/redis-py,cvrebert/redis-py,JamieCressey/redispy,dmugtasimov/redis-py,maxikov/redis-py,nfvs/redis-py,fengshao0907/redis-py,ycaihua/redis-py,yuruidong/redis-py,cvrebert/redis-py,MegaByte875/redis-py,jparise/redis-py,ze-phyr-us/redis-py,sigma-random/redis-py,harlowja/redis-py,ContextLogic/redis-py,VishvajitP/redis-py,yihuang/redis-py,ze-phyr-us/redis-py,siryuan525614/python_operation,pombredanne/redis-py,nfvs/redis-py,fengsp/redis-py,Kazanz/redis-py,rcrdclub/redis-py,pombredanne/redis-py,MrKiven/redis-py,thedrow/redis-py,kaushik94/redis-py,ffrree/redis-py,sunminghong/redis-py,ferrero-zhang/redis-py,garnertb/redis-py,sirk390/redis-py,rcrdclub/redis-py,yihuang/redis-py,forblackking/redis-py,zhangyancoder/redis-py,dmoliveira/redis-py,redis/redis-py,garnertb/redis-py,zhangyancoder/redis-py,forblackking/redis-py,piperck/redis-py,dylanjw/redis-py,lamby/redis-py,ferrero-zhang/redis-py,jparise/redis-py,dylanjw/redis-py,dmoliveira/redis-py,wfxiang08/redis-py,maxikov/redis-py,lamby/redis-py
|
python
|
## Code Before:
try:
import hiredis
HIREDIS_AVAILABLE = True
except ImportError:
HIREDIS_AVAILABLE = False
def from_url(url, db=None, **kwargs):
"""
Returns an active Redis client generated from the given database URL.
Will attempt to extract the database id from the path url fragment, if
none is provided.
"""
from redis.client import Redis
return Redis.from_url(url, db, **kwargs)
from contextlib import contextmanager
@contextmanager
def pipeline(redis_obj):
p = redis_obj.pipeline()
yield p
p.execute()
## Instruction:
Move import statement on top for PEP8 compliancy.
## Code After:
from contextlib import contextmanager
try:
import hiredis
HIREDIS_AVAILABLE = True
except ImportError:
HIREDIS_AVAILABLE = False
def from_url(url, db=None, **kwargs):
"""
Returns an active Redis client generated from the given database URL.
Will attempt to extract the database id from the path url fragment, if
none is provided.
"""
from redis.client import Redis
return Redis.from_url(url, db, **kwargs)
@contextmanager
def pipeline(redis_obj):
p = redis_obj.pipeline()
yield p
p.execute()
|
...
from contextlib import contextmanager
try:
import hiredis
HIREDIS_AVAILABLE = True
...
return Redis.from_url(url, db, **kwargs)
@contextmanager
def pipeline(redis_obj):
p = redis_obj.pipeline()
...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.