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
583a32cd1e9e77d7648978d20a5b7631a4fe2334
tests/sentry/interfaces/tests.py
tests/sentry/interfaces/tests.py
from __future__ import absolute_import import pickle from sentry.interfaces import Interface from sentry.testutils import TestCase class InterfaceTests(TestCase): def test_init_sets_attrs(self): obj = Interface(foo=1) self.assertEqual(obj.attrs, ['foo']) def test_setstate_sets_attrs(self): data = pickle.dumps(Interface(foo=1)) obj = pickle.loads(data) self.assertEqual(obj.attrs, ['foo'])
from __future__ import absolute_import import pickle from sentry.interfaces import Interface, Message, Stacktrace from sentry.models import Event from sentry.testutils import TestCase, fixture class InterfaceBase(TestCase): @fixture def event(self): return Event( id=1, ) class InterfaceTest(InterfaceBase): @fixture def interface(self): return Interface(foo=1) def test_init_sets_attrs(self): assert self.interface.attrs == ['foo'] def test_setstate_sets_attrs(self): data = pickle.dumps(self.interface) obj = pickle.loads(data) assert obj.attrs == ['foo'] def test_to_html_default(self): assert self.interface.to_html(self.event) == '' def test_to_string_default(self): assert self.interface.to_string(self.event) == '' class MessageTest(InterfaceBase): @fixture def interface(self): return Message(message='Hello there %s!', params=('world',)) def test_serialize_behavior(self): assert self.interface.serialize() == { 'message': self.interface.message, 'params': self.interface.params, } def test_get_hash_uses_message(self): assert self.interface.get_hash() == [self.interface.message] def test_get_search_context_with_params_as_list(self): interface = self.interface interface.params = ['world'] assert interface.get_search_context(self.event) == { 'text': [interface.message] + list(interface.params) } def test_get_search_context_with_params_as_tuple(self): assert self.interface.get_search_context(self.event) == { 'text': [self.interface.message] + list(self.interface.params) } def test_get_search_context_with_params_as_dict(self): interface = self.interface interface.params = {'who': 'world'} interface.message = 'Hello there %(who)s!' assert self.interface.get_search_context(self.event) == { 'text': [interface.message] + interface.params.values() }
Improve test coverage on base Interface and Message classes
Improve test coverage on base Interface and Message classes
Python
bsd-3-clause
songyi199111/sentry,JTCunning/sentry,JackDanger/sentry,fotinakis/sentry,JamesMura/sentry,kevinlondon/sentry,mitsuhiko/sentry,felixbuenemann/sentry,fotinakis/sentry,jean/sentry,drcapulet/sentry,ifduyue/sentry,alexm92/sentry,pauloschilling/sentry,fuziontech/sentry,jokey2k/sentry,fotinakis/sentry,argonemyth/sentry,zenefits/sentry,Kryz/sentry,beeftornado/sentry,boneyao/sentry,pauloschilling/sentry,hongliang5623/sentry,fuziontech/sentry,imankulov/sentry,rdio/sentry,jean/sentry,BayanGroup/sentry,songyi199111/sentry,rdio/sentry,felixbuenemann/sentry,nicholasserra/sentry,looker/sentry,gg7/sentry,jokey2k/sentry,gg7/sentry,vperron/sentry,alexm92/sentry,mvaled/sentry,SilentCircle/sentry,BayanGroup/sentry,korealerts1/sentry,alexm92/sentry,ngonzalvez/sentry,fuziontech/sentry,BuildingLink/sentry,Natim/sentry,looker/sentry,boneyao/sentry,daevaorn/sentry,Natim/sentry,rdio/sentry,llonchj/sentry,kevinastone/sentry,kevinlondon/sentry,wong2/sentry,looker/sentry,beeftornado/sentry,JTCunning/sentry,JamesMura/sentry,JTCunning/sentry,BuildingLink/sentry,wong2/sentry,camilonova/sentry,gencer/sentry,BuildingLink/sentry,mvaled/sentry,gencer/sentry,BayanGroup/sentry,imankulov/sentry,beni55/sentry,gg7/sentry,felixbuenemann/sentry,Natim/sentry,wong2/sentry,kevinastone/sentry,looker/sentry,1tush/sentry,songyi199111/sentry,nicholasserra/sentry,wujuguang/sentry,SilentCircle/sentry,ifduyue/sentry,jean/sentry,camilonova/sentry,ifduyue/sentry,BuildingLink/sentry,wujuguang/sentry,wujuguang/sentry,TedaLIEz/sentry,pauloschilling/sentry,hongliang5623/sentry,beeftornado/sentry,mvaled/sentry,zenefits/sentry,beni55/sentry,daevaorn/sentry,1tush/sentry,jokey2k/sentry,korealerts1/sentry,gencer/sentry,rdio/sentry,ngonzalvez/sentry,JackDanger/sentry,BuildingLink/sentry,looker/sentry,1tush/sentry,gencer/sentry,TedaLIEz/sentry,JamesMura/sentry,vperron/sentry,argonemyth/sentry,ewdurbin/sentry,zenefits/sentry,jean/sentry,SilentCircle/sentry,drcapulet/sentry,gencer/sentry,NickPresta/sentry,zenefits/sentry,nicholasserra/sentry,ngonzalvez/sentry,drcapulet/sentry,NickPresta/sentry,daevaorn/sentry,ewdurbin/sentry,hongliang5623/sentry,fotinakis/sentry,ifduyue/sentry,kevinlondon/sentry,llonchj/sentry,mitsuhiko/sentry,zenefits/sentry,kevinastone/sentry,mvaled/sentry,JamesMura/sentry,ifduyue/sentry,mvaled/sentry,korealerts1/sentry,jean/sentry,NickPresta/sentry,daevaorn/sentry,beni55/sentry,SilentCircle/sentry,vperron/sentry,JamesMura/sentry,TedaLIEz/sentry,argonemyth/sentry,camilonova/sentry,ewdurbin/sentry,boneyao/sentry,llonchj/sentry,imankulov/sentry,Kryz/sentry,JackDanger/sentry,Kryz/sentry,mvaled/sentry,NickPresta/sentry
python
## Code Before: from __future__ import absolute_import import pickle from sentry.interfaces import Interface from sentry.testutils import TestCase class InterfaceTests(TestCase): def test_init_sets_attrs(self): obj = Interface(foo=1) self.assertEqual(obj.attrs, ['foo']) def test_setstate_sets_attrs(self): data = pickle.dumps(Interface(foo=1)) obj = pickle.loads(data) self.assertEqual(obj.attrs, ['foo']) ## Instruction: Improve test coverage on base Interface and Message classes ## Code After: from __future__ import absolute_import import pickle from sentry.interfaces import Interface, Message, Stacktrace from sentry.models import Event from sentry.testutils import TestCase, fixture class InterfaceBase(TestCase): @fixture def event(self): return Event( id=1, ) class InterfaceTest(InterfaceBase): @fixture def interface(self): return Interface(foo=1) def test_init_sets_attrs(self): assert self.interface.attrs == ['foo'] def test_setstate_sets_attrs(self): data = pickle.dumps(self.interface) obj = pickle.loads(data) assert obj.attrs == ['foo'] def test_to_html_default(self): assert self.interface.to_html(self.event) == '' def test_to_string_default(self): assert self.interface.to_string(self.event) == '' class MessageTest(InterfaceBase): @fixture def interface(self): return Message(message='Hello there %s!', params=('world',)) def test_serialize_behavior(self): assert self.interface.serialize() == { 'message': self.interface.message, 'params': self.interface.params, } def test_get_hash_uses_message(self): assert self.interface.get_hash() == [self.interface.message] def test_get_search_context_with_params_as_list(self): interface = self.interface interface.params = ['world'] assert interface.get_search_context(self.event) == { 'text': [interface.message] + list(interface.params) } def test_get_search_context_with_params_as_tuple(self): assert self.interface.get_search_context(self.event) == { 'text': [self.interface.message] + list(self.interface.params) } def test_get_search_context_with_params_as_dict(self): interface = self.interface interface.params = {'who': 'world'} interface.message = 'Hello there %(who)s!' assert self.interface.get_search_context(self.event) == { 'text': [interface.message] + interface.params.values() }
# ... existing code ... import pickle from sentry.interfaces import Interface, Message, Stacktrace from sentry.models import Event from sentry.testutils import TestCase, fixture class InterfaceBase(TestCase): @fixture def event(self): return Event( id=1, ) class InterfaceTest(InterfaceBase): @fixture def interface(self): return Interface(foo=1) def test_init_sets_attrs(self): assert self.interface.attrs == ['foo'] def test_setstate_sets_attrs(self): data = pickle.dumps(self.interface) obj = pickle.loads(data) assert obj.attrs == ['foo'] def test_to_html_default(self): assert self.interface.to_html(self.event) == '' def test_to_string_default(self): assert self.interface.to_string(self.event) == '' class MessageTest(InterfaceBase): @fixture def interface(self): return Message(message='Hello there %s!', params=('world',)) def test_serialize_behavior(self): assert self.interface.serialize() == { 'message': self.interface.message, 'params': self.interface.params, } def test_get_hash_uses_message(self): assert self.interface.get_hash() == [self.interface.message] def test_get_search_context_with_params_as_list(self): interface = self.interface interface.params = ['world'] assert interface.get_search_context(self.event) == { 'text': [interface.message] + list(interface.params) } def test_get_search_context_with_params_as_tuple(self): assert self.interface.get_search_context(self.event) == { 'text': [self.interface.message] + list(self.interface.params) } def test_get_search_context_with_params_as_dict(self): interface = self.interface interface.params = {'who': 'world'} interface.message = 'Hello there %(who)s!' assert self.interface.get_search_context(self.event) == { 'text': [interface.message] + interface.params.values() } # ... rest of the code ...
0efa7eda72c851959fa7da2bd084cc9aec310a77
src/ai/FSMTransition.h
src/ai/FSMTransition.h
namespace ADBLib { class FSMTransition { public: FSMState* currentState; //!< The current state. int input; //!< If this input is recieved and the FSM state is the currentState, transition. FSMState* nextState; //!< The next state to transition to. }; }
namespace ADBLib { struct FSMTransition { FSMState* currentState; //!< The current state. int input; //!< If this input is received and the FSM state is the currentState, transition. FSMState* nextState; //!< The next state to transition to. }; }
Fix END_STATE_TABLE define causing bool -> ptr conversion error
Fix END_STATE_TABLE define causing bool -> ptr conversion error
C
mit
Dreadbot/ADBLib,Dreadbot/ADBLib,Sourec/ADBLib,Sourec/ADBLib
c
## Code Before: namespace ADBLib { class FSMTransition { public: FSMState* currentState; //!< The current state. int input; //!< If this input is recieved and the FSM state is the currentState, transition. FSMState* nextState; //!< The next state to transition to. }; } ## Instruction: Fix END_STATE_TABLE define causing bool -> ptr conversion error ## Code After: namespace ADBLib { struct FSMTransition { FSMState* currentState; //!< The current state. int input; //!< If this input is received and the FSM state is the currentState, transition. FSMState* nextState; //!< The next state to transition to. }; }
// ... existing code ... namespace ADBLib { struct FSMTransition { FSMState* currentState; //!< The current state. int input; //!< If this input is received and the FSM state is the currentState, transition. FSMState* nextState; //!< The next state to transition to. }; } // ... rest of the code ...
ba6ff17cadaa3a23f24c228b83b6d04b5cd1dd17
src/main/java/asteroid/nodes/MethodNodeBuilder.java
src/main/java/asteroid/nodes/MethodNodeBuilder.java
package asteroid.nodes; import asteroid.A; import java.util.List; import java.util.ArrayList; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.stmt.Statement; /** * Builder to create instance of type {@link MethodNode} * * @since 0.1.0 */ public class MethodNodeBuilder { private final String name; private int modifiers; private Statement code; private ClassNode returnType; private Parameter[] parameters; private ClassNode[] exceptions; private MethodNodeBuilder(String name) { this.name = name; } public static MethodNodeBuilder method(String name) { return new MethodNodeBuilder(name); } public MethodNodeBuilder returnType(Class returnType) { this.returnType = A.NODES.clazz(returnType).build(); return this; } public MethodNodeBuilder modifiers(int modifiers) { this.modifiers = modifiers; return this; } public MethodNodeBuilder parameters(Parameter... parameters) { this.parameters = parameters; return this; } public MethodNodeBuilder exceptions(ClassNode... exceptions) { this.exceptions = exceptions; return this; } public MethodNodeBuilder code(Statement code) { this.code = code; return this; } public MethodNode build() { MethodNode methodNode = new MethodNode(name, modifiers, returnType, parameters, exceptions, code); return methodNode; } }
package asteroid.nodes; import asteroid.A; import java.util.List; import java.util.ArrayList; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.stmt.Statement; /** * Builder to create instance of type {@link MethodNode} * * @since 0.1.0 */ public class MethodNodeBuilder { private final String name; private int modifiers; private Statement code; private ClassNode returnType; private Parameter[] parameters = new Parameter[0]; private ClassNode[] exceptions = new ClassNode[0]; private MethodNodeBuilder(String name) { this.name = name; } public static MethodNodeBuilder method(String name) { return new MethodNodeBuilder(name); } public MethodNodeBuilder returnType(Class returnType) { this.returnType = A.NODES.clazz(returnType).build(); return this; } public MethodNodeBuilder modifiers(int modifiers) { this.modifiers = modifiers; return this; } public MethodNodeBuilder parameters(Parameter... parameters) { this.parameters = parameters; return this; } public MethodNodeBuilder exceptions(ClassNode... exceptions) { this.exceptions = exceptions; return this; } public MethodNodeBuilder code(Statement code) { this.code = code; return this; } public MethodNode build() { MethodNode methodNode = new MethodNode(name, modifiers, returnType, parameters, exceptions, code); return methodNode; } }
Fix NPE when no adding parameters or exceptions
Fix NPE when no adding parameters or exceptions
Java
apache-2.0
grooviter/asteroid,januslynd/asteroid
java
## Code Before: package asteroid.nodes; import asteroid.A; import java.util.List; import java.util.ArrayList; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.stmt.Statement; /** * Builder to create instance of type {@link MethodNode} * * @since 0.1.0 */ public class MethodNodeBuilder { private final String name; private int modifiers; private Statement code; private ClassNode returnType; private Parameter[] parameters; private ClassNode[] exceptions; private MethodNodeBuilder(String name) { this.name = name; } public static MethodNodeBuilder method(String name) { return new MethodNodeBuilder(name); } public MethodNodeBuilder returnType(Class returnType) { this.returnType = A.NODES.clazz(returnType).build(); return this; } public MethodNodeBuilder modifiers(int modifiers) { this.modifiers = modifiers; return this; } public MethodNodeBuilder parameters(Parameter... parameters) { this.parameters = parameters; return this; } public MethodNodeBuilder exceptions(ClassNode... exceptions) { this.exceptions = exceptions; return this; } public MethodNodeBuilder code(Statement code) { this.code = code; return this; } public MethodNode build() { MethodNode methodNode = new MethodNode(name, modifiers, returnType, parameters, exceptions, code); return methodNode; } } ## Instruction: Fix NPE when no adding parameters or exceptions ## Code After: package asteroid.nodes; import asteroid.A; import java.util.List; import java.util.ArrayList; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.stmt.Statement; /** * Builder to create instance of type {@link MethodNode} * * @since 0.1.0 */ public class MethodNodeBuilder { private final String name; private int modifiers; private Statement code; private ClassNode returnType; private Parameter[] parameters = new Parameter[0]; private ClassNode[] exceptions = new ClassNode[0]; private MethodNodeBuilder(String name) { this.name = name; } public static MethodNodeBuilder method(String name) { return new MethodNodeBuilder(name); } public MethodNodeBuilder returnType(Class returnType) { this.returnType = A.NODES.clazz(returnType).build(); return this; } public MethodNodeBuilder modifiers(int modifiers) { this.modifiers = modifiers; return this; } public MethodNodeBuilder parameters(Parameter... parameters) { this.parameters = parameters; return this; } public MethodNodeBuilder exceptions(ClassNode... exceptions) { this.exceptions = exceptions; return this; } public MethodNodeBuilder code(Statement code) { this.code = code; return this; } public MethodNode build() { MethodNode methodNode = new MethodNode(name, modifiers, returnType, parameters, exceptions, code); return methodNode; } }
# ... existing code ... private int modifiers; private Statement code; private ClassNode returnType; private Parameter[] parameters = new Parameter[0]; private ClassNode[] exceptions = new ClassNode[0]; private MethodNodeBuilder(String name) { this.name = name; # ... rest of the code ...
7a393502b36567dce93df718d716373414e2e674
test_noise_addition.py
test_noise_addition.py
import numpy as np import matplotlib.pyplot as plt def add_noise(flux, SNR): "Using the formulation mu/sigma" mu = np.mean(flux) sigma = mu / SNR # Add normal distributed noise at the SNR level. noisey_flux = flux + np.random.normal(0, sigma, len(flux)) return noisey_flux def main(): """ Visually test the addition of Noise using add_noise function """ flux = np.ones(100) for i, snr in enumerate([50, 100, 200, 300]): plt.plot(add_noise(flux, snr) + 0.05 * i, label="snr={}".format(snr)) plt.legend() plt.show() if __name__ == "__main__": main()
import numpy as np import matplotlib.pyplot as plt def add_noise(flux, SNR): "Using the formulation mu/sigma" mu = np.mean(flux) sigma = mu / SNR # Add normal distributed noise at the SNR level. noisey_flux = flux + np.random.normal(0, sigma, len(flux)) return noisey_flux def add_noise2(flux, SNR): "Using the formulation mu/sigma" #mu = np.mean(flux) sigma = flux / SNR # Add normal distributed noise at the SNR level. noisey_flux = flux + np.random.normal(0, sigma) return noisey_flux def main(): """ Visually test the addition of Noise using add_noise function """ flux = np.ones(100) for i, snr in enumerate([50, 100, 200, 300]): # Test that the standard deviation of the noise is close to the snr level print("Applying a snr of {}".format(snr)) noisey_flux = add_noise(flux, snr) std = np.std(noisey_flux) print("Standard deviation of signal = {}".format(std)) SNR = 1 / std print("Estimated SNR from stddev = {}".format(SNR)) plt.plot(noisey_flux + 0.05 * i, label="snr={}".format(snr)) plt.legend() plt.show() if __name__ == "__main__": main()
Fix noise calculation, add printing to check SNR value of data
Fix noise calculation, add printing to check SNR value of data
Python
mit
jason-neal/companion_simulations,jason-neal/companion_simulations
python
## Code Before: import numpy as np import matplotlib.pyplot as plt def add_noise(flux, SNR): "Using the formulation mu/sigma" mu = np.mean(flux) sigma = mu / SNR # Add normal distributed noise at the SNR level. noisey_flux = flux + np.random.normal(0, sigma, len(flux)) return noisey_flux def main(): """ Visually test the addition of Noise using add_noise function """ flux = np.ones(100) for i, snr in enumerate([50, 100, 200, 300]): plt.plot(add_noise(flux, snr) + 0.05 * i, label="snr={}".format(snr)) plt.legend() plt.show() if __name__ == "__main__": main() ## Instruction: Fix noise calculation, add printing to check SNR value of data ## Code After: import numpy as np import matplotlib.pyplot as plt def add_noise(flux, SNR): "Using the formulation mu/sigma" mu = np.mean(flux) sigma = mu / SNR # Add normal distributed noise at the SNR level. noisey_flux = flux + np.random.normal(0, sigma, len(flux)) return noisey_flux def add_noise2(flux, SNR): "Using the formulation mu/sigma" #mu = np.mean(flux) sigma = flux / SNR # Add normal distributed noise at the SNR level. noisey_flux = flux + np.random.normal(0, sigma) return noisey_flux def main(): """ Visually test the addition of Noise using add_noise function """ flux = np.ones(100) for i, snr in enumerate([50, 100, 200, 300]): # Test that the standard deviation of the noise is close to the snr level print("Applying a snr of {}".format(snr)) noisey_flux = add_noise(flux, snr) std = np.std(noisey_flux) print("Standard deviation of signal = {}".format(std)) SNR = 1 / std print("Estimated SNR from stddev = {}".format(SNR)) plt.plot(noisey_flux + 0.05 * i, label="snr={}".format(snr)) plt.legend() plt.show() if __name__ == "__main__": main()
... return noisey_flux def add_noise2(flux, SNR): "Using the formulation mu/sigma" #mu = np.mean(flux) sigma = flux / SNR # Add normal distributed noise at the SNR level. noisey_flux = flux + np.random.normal(0, sigma) return noisey_flux def main(): """ Visually test the addition of Noise using add_noise function """ flux = np.ones(100) for i, snr in enumerate([50, 100, 200, 300]): # Test that the standard deviation of the noise is close to the snr level print("Applying a snr of {}".format(snr)) noisey_flux = add_noise(flux, snr) std = np.std(noisey_flux) print("Standard deviation of signal = {}".format(std)) SNR = 1 / std print("Estimated SNR from stddev = {}".format(SNR)) plt.plot(noisey_flux + 0.05 * i, label="snr={}".format(snr)) plt.legend() plt.show() if __name__ == "__main__": main() ...
528813b437d2121b2c52f51884746e4cbeeeacf8
src/main/java/leetcode/Problem714.java
src/main/java/leetcode/Problem714.java
package leetcode; /** * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/ */ public class Problem714 { public int maxProfit(int[] prices, int fee) { // TODO return 0; } public static void main(String[] args) { Problem714 prob = new Problem714(); System.out.println(prob.maxProfit(new int[]{1, 3, 2, 8, 4, 9}, 2)); // 8 System.out.println(prob.maxProfit(new int[]{1, 3, 2, 6, 8, 4, 9}, 2)); // 8 System.out.println(prob.maxProfit(new int[]{1, 4, 2, 1, 4, 8, 4, 9}, 2)); // 9 } }
package leetcode; /** * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/ */ public class Problem714 { public int maxProfit(int[] prices, int fee) { int cash = 0; int hold = -prices[0]; for (int i = 1; i < prices.length; i++) { cash = Math.max(cash, hold + prices[i] - fee); hold = Math.max(hold, cash - prices[i]); } return cash; } }
Solve problem 714 (not really)
Solve problem 714 (not really)
Java
mit
fredyw/leetcode,fredyw/leetcode,fredyw/leetcode,fredyw/leetcode
java
## Code Before: package leetcode; /** * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/ */ public class Problem714 { public int maxProfit(int[] prices, int fee) { // TODO return 0; } public static void main(String[] args) { Problem714 prob = new Problem714(); System.out.println(prob.maxProfit(new int[]{1, 3, 2, 8, 4, 9}, 2)); // 8 System.out.println(prob.maxProfit(new int[]{1, 3, 2, 6, 8, 4, 9}, 2)); // 8 System.out.println(prob.maxProfit(new int[]{1, 4, 2, 1, 4, 8, 4, 9}, 2)); // 9 } } ## Instruction: Solve problem 714 (not really) ## Code After: package leetcode; /** * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/ */ public class Problem714 { public int maxProfit(int[] prices, int fee) { int cash = 0; int hold = -prices[0]; for (int i = 1; i < prices.length; i++) { cash = Math.max(cash, hold + prices[i] - fee); hold = Math.max(hold, cash - prices[i]); } return cash; } }
# ... existing code ... */ public class Problem714 { public int maxProfit(int[] prices, int fee) { int cash = 0; int hold = -prices[0]; for (int i = 1; i < prices.length; i++) { cash = Math.max(cash, hold + prices[i] - fee); hold = Math.max(hold, cash - prices[i]); } return cash; } } # ... rest of the code ...
b36f2518666572ccd3b98dd88536533e17a39e3f
setup.py
setup.py
from distutils.core import setup setup(name='SpaceScout-Server', version='1.0', description='REST Backend for SpaceScout', install_requires=[ 'Django>=1.7,<1.8', 'mock<=1.0.1', 'oauth2<=1.5.211', 'oauth_provider', 'Pillow', 'pyproj', 'pytz', 'South', 'simplejson>=2.1', 'django-oauth-plus<=2.2.5', 'phonenumbers' ], )
from distutils.core import setup setup(name='SpaceScout-Server', version='1.0', description='REST Backend for SpaceScout', install_requires=[ 'Django>=1.7,<1.8', 'mock<=1.0.1', 'oauth2<=1.5.211', 'Pillow', 'pyproj', 'pytz', 'South', 'simplejson>=2.1', 'django-oauth-plus<=2.2.5', 'phonenumbers' ], )
Remove oauth_provider as that's the eggname for django-oauth-plus.
Remove oauth_provider as that's the eggname for django-oauth-plus.
Python
apache-2.0
uw-it-aca/spotseeker_server,uw-it-aca/spotseeker_server,uw-it-aca/spotseeker_server
python
## Code Before: from distutils.core import setup setup(name='SpaceScout-Server', version='1.0', description='REST Backend for SpaceScout', install_requires=[ 'Django>=1.7,<1.8', 'mock<=1.0.1', 'oauth2<=1.5.211', 'oauth_provider', 'Pillow', 'pyproj', 'pytz', 'South', 'simplejson>=2.1', 'django-oauth-plus<=2.2.5', 'phonenumbers' ], ) ## Instruction: Remove oauth_provider as that's the eggname for django-oauth-plus. ## Code After: from distutils.core import setup setup(name='SpaceScout-Server', version='1.0', description='REST Backend for SpaceScout', install_requires=[ 'Django>=1.7,<1.8', 'mock<=1.0.1', 'oauth2<=1.5.211', 'Pillow', 'pyproj', 'pytz', 'South', 'simplejson>=2.1', 'django-oauth-plus<=2.2.5', 'phonenumbers' ], )
// ... existing code ... 'Django>=1.7,<1.8', 'mock<=1.0.1', 'oauth2<=1.5.211', 'Pillow', 'pyproj', 'pytz', // ... rest of the code ...
4f1bbe6435f2c899915ab72d990a649d4e494553
grum/views.py
grum/views.py
from grum import app, db from grum.models import User from flask import render_template, request @app.route("/") def main(): # # Login verification code # username = request.form('username') # password = request.form('password') # # user = User.query.filter_by(username=username).first_or_404() # if user.validate_password(password): # # Logged in # # Not Logged In return render_template("index.html") @app.route("/register", methods=['GET', 'POST']) def register(): if request.method == "POST": username = request.form('username') password = request.form('password') confirm_password = request.form('confirm') if password != confirm_password: return redirect("/register") new_user = User( username=username, password=password ) db.session.add(new_user) db.session.commit() return render_template("register.html") @app.route("/mail") def mail(): return render_template('mail.html')
from grum import app, db from grum.models import User from flask import render_template, request, redirect @app.route("/", methods=['GET', 'POST']) def main(): if request.method == "POST": # Login verification code username = request.form['username'] password = request.form['password'] user = User.query.filter_by(username=username).first_or_404() if user.validate_password(password): return redirect("/mail") return render_template("index.html") @app.route("/register", methods=['GET', 'POST']) def register(): if request.method == "POST": username = request.form['username'] password = request.form['password'] confirm_password = request.form['confirm'] if password != confirm_password: return redirect("/register") new_user = User( username=username, password=password ) db.session.add(new_user) db.session.commit() return redirect("/mail") return render_template("register.html") @app.route("/mail") def mail(): return render_template('mail.html')
Fix register and login y0
Fix register and login y0
Python
mit
Grum-Hackdee/grum-web,Grum-Hackdee/grum-web,Grum-Hackdee/grum-web,Grum-Hackdee/grum-web
python
## Code Before: from grum import app, db from grum.models import User from flask import render_template, request @app.route("/") def main(): # # Login verification code # username = request.form('username') # password = request.form('password') # # user = User.query.filter_by(username=username).first_or_404() # if user.validate_password(password): # # Logged in # # Not Logged In return render_template("index.html") @app.route("/register", methods=['GET', 'POST']) def register(): if request.method == "POST": username = request.form('username') password = request.form('password') confirm_password = request.form('confirm') if password != confirm_password: return redirect("/register") new_user = User( username=username, password=password ) db.session.add(new_user) db.session.commit() return render_template("register.html") @app.route("/mail") def mail(): return render_template('mail.html') ## Instruction: Fix register and login y0 ## Code After: from grum import app, db from grum.models import User from flask import render_template, request, redirect @app.route("/", methods=['GET', 'POST']) def main(): if request.method == "POST": # Login verification code username = request.form['username'] password = request.form['password'] user = User.query.filter_by(username=username).first_or_404() if user.validate_password(password): return redirect("/mail") return render_template("index.html") @app.route("/register", methods=['GET', 'POST']) def register(): if request.method == "POST": username = request.form['username'] password = request.form['password'] confirm_password = request.form['confirm'] if password != confirm_password: return redirect("/register") new_user = User( username=username, password=password ) db.session.add(new_user) db.session.commit() return redirect("/mail") return render_template("register.html") @app.route("/mail") def mail(): return render_template('mail.html')
... from grum import app, db from grum.models import User from flask import render_template, request, redirect @app.route("/", methods=['GET', 'POST']) def main(): if request.method == "POST": # Login verification code username = request.form['username'] password = request.form['password'] user = User.query.filter_by(username=username).first_or_404() if user.validate_password(password): return redirect("/mail") return render_template("index.html") ... def register(): if request.method == "POST": username = request.form['username'] password = request.form['password'] confirm_password = request.form['confirm'] if password != confirm_password: return redirect("/register") ... db.session.add(new_user) db.session.commit() return redirect("/mail") return render_template("register.html") ...
76bda324fcd617677a3f107e6b7c162a81e88db9
tests/test_vector2_negation.py
tests/test_vector2_negation.py
import pytest from ppb_vector import Vector2 negation_data = ( (Vector2(1, 1), Vector2(-1, -1)), (Vector2(2, -3), Vector2(-2, 3)), (Vector2(-4, 18), Vector2(4, -18)) ) @pytest.mark.parametrize('test_vector, expected_result', negation_data) def test_negation(test_vector, expected_result): assert -test_vector == expected_result
from hypothesis import given from ppb_vector import Vector2 from utils import vectors @given(vector=vectors()) def test_negation_coordinates(vector: Vector2): assert - vector.x == (- vector).x assert - vector.y == (- vector).y
Replace with an Hypothesis test
tests/negation: Replace with an Hypothesis test
Python
artistic-2.0
ppb/ppb-vector,ppb/ppb-vector
python
## Code Before: import pytest from ppb_vector import Vector2 negation_data = ( (Vector2(1, 1), Vector2(-1, -1)), (Vector2(2, -3), Vector2(-2, 3)), (Vector2(-4, 18), Vector2(4, -18)) ) @pytest.mark.parametrize('test_vector, expected_result', negation_data) def test_negation(test_vector, expected_result): assert -test_vector == expected_result ## Instruction: tests/negation: Replace with an Hypothesis test ## Code After: from hypothesis import given from ppb_vector import Vector2 from utils import vectors @given(vector=vectors()) def test_negation_coordinates(vector: Vector2): assert - vector.x == (- vector).x assert - vector.y == (- vector).y
# ... existing code ... from hypothesis import given from ppb_vector import Vector2 from utils import vectors @given(vector=vectors()) def test_negation_coordinates(vector: Vector2): assert - vector.x == (- vector).x assert - vector.y == (- vector).y # ... rest of the code ...
c584028875926b3a193e480e16bfc19b1c613438
turing.h
turing.h
return TURING_ERROR typedef int bool; typedef enum { TURING_OK, TURING_HALT, TURING_ERROR } turing_status_t; typedef struct Turing { bool *tape; bool *p; } Turing; Turing *init_turing(); void free_turing(Turing *turing); turing_status_t move_head(Turing *turing, int direction); turing_status_t execute_instruction(Turing *turing, char *program); turing_status_t execute_definite_instruction(Turing *turing, char *program); #endif // TURING_H_
return TURING_ERROR #define move_head_left(t) move_head(t, 0) #define move_head_right(t) move_head(t, 1) typedef int bool; typedef enum { TURING_OK, TURING_HALT, TURING_ERROR } turing_status_t; typedef struct Turing { bool *tape; bool *p; } Turing; Turing *init_turing(); void free_turing(Turing *turing); turing_status_t move_head(Turing *turing, int direction); turing_status_t execute_instruction(Turing *turing, char *program); turing_status_t execute_definite_instruction(Turing *turing, char *program); #endif // TURING_H_
Implement left and right macros
Implement left and right macros
C
mit
mindriot101/turing-machine
c
## Code Before: return TURING_ERROR typedef int bool; typedef enum { TURING_OK, TURING_HALT, TURING_ERROR } turing_status_t; typedef struct Turing { bool *tape; bool *p; } Turing; Turing *init_turing(); void free_turing(Turing *turing); turing_status_t move_head(Turing *turing, int direction); turing_status_t execute_instruction(Turing *turing, char *program); turing_status_t execute_definite_instruction(Turing *turing, char *program); #endif // TURING_H_ ## Instruction: Implement left and right macros ## Code After: return TURING_ERROR #define move_head_left(t) move_head(t, 0) #define move_head_right(t) move_head(t, 1) typedef int bool; typedef enum { TURING_OK, TURING_HALT, TURING_ERROR } turing_status_t; typedef struct Turing { bool *tape; bool *p; } Turing; Turing *init_turing(); void free_turing(Turing *turing); turing_status_t move_head(Turing *turing, int direction); turing_status_t execute_instruction(Turing *turing, char *program); turing_status_t execute_definite_instruction(Turing *turing, char *program); #endif // TURING_H_
... return TURING_ERROR #define move_head_left(t) move_head(t, 0) #define move_head_right(t) move_head(t, 1) typedef int bool; ...
797619c24f663ca0e916e173feabd04537d80262
src/main/java/fi/csc/microarray/messaging/message/UrlMessage.java
src/main/java/fi/csc/microarray/messaging/message/UrlMessage.java
package fi.csc.microarray.messaging.message; import java.net.MalformedURLException; import java.net.URL; import javax.jms.JMSException; import javax.jms.MapMessage; public class UrlMessage extends ChipsterMessage { private final static String KEY_URL = "url"; private URL url; public UrlMessage() { super(); } public UrlMessage(URL url) { super(); this.url = url; } public URL getUrl() { return url; } public void unmarshal(MapMessage from) throws JMSException { super.unmarshal(from); try { this.url = new URL(from.getString(KEY_URL)); } catch (MalformedURLException e) { handleException(e); } } public void marshal(MapMessage mapMessage) throws JMSException { super.marshal(mapMessage); String urlString = null; if (this.url != null) { urlString = this.url.toString(); } mapMessage.setString(KEY_URL, urlString); } }
package fi.csc.microarray.messaging.message; import java.net.MalformedURLException; import java.net.URL; import javax.jms.JMSException; import javax.jms.MapMessage; public class UrlMessage extends ChipsterMessage { private final static String KEY_URL = "url"; private URL url; public UrlMessage() { super(); } public UrlMessage(URL url) { super(); this.url = url; } public URL getUrl() { return url; } public void unmarshal(MapMessage from) throws JMSException { super.unmarshal(from); String urlString = from.getString(KEY_URL); if (urlString == null) { this.url = null; } else { try { this.url = new URL(from.getString(KEY_URL)); } catch (MalformedURLException e) { handleException(e); } } } public void marshal(MapMessage mapMessage) throws JMSException { super.marshal(mapMessage); String urlString = null; if (this.url != null) { urlString = this.url.toString(); } mapMessage.setString(KEY_URL, urlString); } }
Fix filebroker response when the file wasn't found
Fix filebroker response when the file wasn't found
Java
mit
chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster
java
## Code Before: package fi.csc.microarray.messaging.message; import java.net.MalformedURLException; import java.net.URL; import javax.jms.JMSException; import javax.jms.MapMessage; public class UrlMessage extends ChipsterMessage { private final static String KEY_URL = "url"; private URL url; public UrlMessage() { super(); } public UrlMessage(URL url) { super(); this.url = url; } public URL getUrl() { return url; } public void unmarshal(MapMessage from) throws JMSException { super.unmarshal(from); try { this.url = new URL(from.getString(KEY_URL)); } catch (MalformedURLException e) { handleException(e); } } public void marshal(MapMessage mapMessage) throws JMSException { super.marshal(mapMessage); String urlString = null; if (this.url != null) { urlString = this.url.toString(); } mapMessage.setString(KEY_URL, urlString); } } ## Instruction: Fix filebroker response when the file wasn't found ## Code After: package fi.csc.microarray.messaging.message; import java.net.MalformedURLException; import java.net.URL; import javax.jms.JMSException; import javax.jms.MapMessage; public class UrlMessage extends ChipsterMessage { private final static String KEY_URL = "url"; private URL url; public UrlMessage() { super(); } public UrlMessage(URL url) { super(); this.url = url; } public URL getUrl() { return url; } public void unmarshal(MapMessage from) throws JMSException { super.unmarshal(from); String urlString = from.getString(KEY_URL); if (urlString == null) { this.url = null; } else { try { this.url = new URL(from.getString(KEY_URL)); } catch (MalformedURLException e) { handleException(e); } } } public void marshal(MapMessage mapMessage) throws JMSException { super.marshal(mapMessage); String urlString = null; if (this.url != null) { urlString = this.url.toString(); } mapMessage.setString(KEY_URL, urlString); } }
// ... existing code ... public void unmarshal(MapMessage from) throws JMSException { super.unmarshal(from); String urlString = from.getString(KEY_URL); if (urlString == null) { this.url = null; } else { try { this.url = new URL(from.getString(KEY_URL)); } catch (MalformedURLException e) { handleException(e); } } } // ... rest of the code ...
7bfefe50c00d86b55c0620207e9848c97aa28227
rml/units.py
rml/units.py
import numpy as np from scipy.interpolate import PchipInterpolator class UcPoly(): def __init__(self, coef): self.p = np.poly1d(coef) def machine_to_physics(self, machine_value): return self.p(machine_value) def physics_to_machine(self, physics_value): roots = (self.p - physics_value).roots positive_roots = [root for root in roots if root > 0] if len(positive_roots) > 0: return positive_roots[0] else: raise ValueError("No corresponding positive machine value:", roots) class UcPchip(): def __init__(self, x, y): self.x = x self.y = y self.pp = PchipInterpolator(x, y) def machine_to_physics(self, machine_value): return self.pp(machine_value) def physics_to_machine(self, physics_value): pass
import numpy as np from scipy.interpolate import PchipInterpolator class UcPoly(object): def __init__(self, coef): self.p = np.poly1d(coef) def machine_to_physics(self, machine_value): return self.p(machine_value) def physics_to_machine(self, physics_value): roots = (self.p - physics_value).roots positive_roots = [root for root in roots if root > 0] if len(positive_roots) > 0: return positive_roots[0] else: raise ValueError("No corresponding positive machine value:", roots) class UcPchip(object): def __init__(self, x, y): self.x = x self.y = y self.pp = PchipInterpolator(x, y) def machine_to_physics(self, machine_value): return self.pp(machine_value) def physics_to_machine(self, physics_value): pass
Correct the definitions of old-style classes
Correct the definitions of old-style classes
Python
apache-2.0
razvanvasile/RML,willrogers/pml,willrogers/pml
python
## Code Before: import numpy as np from scipy.interpolate import PchipInterpolator class UcPoly(): def __init__(self, coef): self.p = np.poly1d(coef) def machine_to_physics(self, machine_value): return self.p(machine_value) def physics_to_machine(self, physics_value): roots = (self.p - physics_value).roots positive_roots = [root for root in roots if root > 0] if len(positive_roots) > 0: return positive_roots[0] else: raise ValueError("No corresponding positive machine value:", roots) class UcPchip(): def __init__(self, x, y): self.x = x self.y = y self.pp = PchipInterpolator(x, y) def machine_to_physics(self, machine_value): return self.pp(machine_value) def physics_to_machine(self, physics_value): pass ## Instruction: Correct the definitions of old-style classes ## Code After: import numpy as np from scipy.interpolate import PchipInterpolator class UcPoly(object): def __init__(self, coef): self.p = np.poly1d(coef) def machine_to_physics(self, machine_value): return self.p(machine_value) def physics_to_machine(self, physics_value): roots = (self.p - physics_value).roots positive_roots = [root for root in roots if root > 0] if len(positive_roots) > 0: return positive_roots[0] else: raise ValueError("No corresponding positive machine value:", roots) class UcPchip(object): def __init__(self, x, y): self.x = x self.y = y self.pp = PchipInterpolator(x, y) def machine_to_physics(self, machine_value): return self.pp(machine_value) def physics_to_machine(self, physics_value): pass
... from scipy.interpolate import PchipInterpolator class UcPoly(object): def __init__(self, coef): self.p = np.poly1d(coef) ... raise ValueError("No corresponding positive machine value:", roots) class UcPchip(object): def __init__(self, x, y): self.x = x self.y = y ...
8c97ed12b9c3e18fe355fd2e0b65f01ae66d45b4
app/src/main/java/com/oxapps/tradenotifications/NotificationDeleteReceiver.java
app/src/main/java/com/oxapps/tradenotifications/NotificationDeleteReceiver.java
package com.oxapps.tradenotifications; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.preference.PreferenceManager; public class NotificationDeleteReceiver extends BroadcastReceiver { private static final String TRADE_OFFERS_URL = "https://steamcommunity.com/id/id/tradeoffers/"; @Override public void onReceive(Context context, Intent intent) { long newRequestTime = System.currentTimeMillis() / 1000; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = prefs.edit(); editor.putLong(BackgroundIntentService.LAST_DELETE_KEY, newRequestTime); editor.apply(); if(intent.hasExtra(BackgroundIntentService.NOTIFICATION_CLICKED)) { Intent browserIntent = new Intent(Intent.ACTION_VIEW); browserIntent.setData(Uri.parse(TRADE_OFFERS_URL)); context.getApplicationContext().startActivity(browserIntent); } } }
package com.oxapps.tradenotifications; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.preference.PreferenceManager; public class NotificationDeleteReceiver extends BroadcastReceiver { private static final String TRADE_OFFERS_URL = "https://steamcommunity.com/id/id/tradeoffers/"; @Override public void onReceive(Context context, Intent intent) { long newRequestTime = System.currentTimeMillis() / 1000; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = prefs.edit(); editor.putLong(BackgroundIntentService.LAST_DELETE_KEY, newRequestTime); editor.apply(); if(intent.hasExtra(BackgroundIntentService.NOTIFICATION_CLICKED)) { Intent browserIntent = new Intent(Intent.ACTION_VIEW); browserIntent.setData(Uri.parse(TRADE_OFFERS_URL)); browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.getApplicationContext().startActivity(browserIntent); } } }
Fix bug causing app to crash on clicking notification
Fix bug causing app to crash on clicking notification
Java
apache-2.0
Flozzo/Trade-Notifications-for-Steam
java
## Code Before: package com.oxapps.tradenotifications; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.preference.PreferenceManager; public class NotificationDeleteReceiver extends BroadcastReceiver { private static final String TRADE_OFFERS_URL = "https://steamcommunity.com/id/id/tradeoffers/"; @Override public void onReceive(Context context, Intent intent) { long newRequestTime = System.currentTimeMillis() / 1000; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = prefs.edit(); editor.putLong(BackgroundIntentService.LAST_DELETE_KEY, newRequestTime); editor.apply(); if(intent.hasExtra(BackgroundIntentService.NOTIFICATION_CLICKED)) { Intent browserIntent = new Intent(Intent.ACTION_VIEW); browserIntent.setData(Uri.parse(TRADE_OFFERS_URL)); context.getApplicationContext().startActivity(browserIntent); } } } ## Instruction: Fix bug causing app to crash on clicking notification ## Code After: package com.oxapps.tradenotifications; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.preference.PreferenceManager; public class NotificationDeleteReceiver extends BroadcastReceiver { private static final String TRADE_OFFERS_URL = "https://steamcommunity.com/id/id/tradeoffers/"; @Override public void onReceive(Context context, Intent intent) { long newRequestTime = System.currentTimeMillis() / 1000; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = prefs.edit(); editor.putLong(BackgroundIntentService.LAST_DELETE_KEY, newRequestTime); editor.apply(); if(intent.hasExtra(BackgroundIntentService.NOTIFICATION_CLICKED)) { Intent browserIntent = new Intent(Intent.ACTION_VIEW); browserIntent.setData(Uri.parse(TRADE_OFFERS_URL)); browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.getApplicationContext().startActivity(browserIntent); } } }
... if(intent.hasExtra(BackgroundIntentService.NOTIFICATION_CLICKED)) { Intent browserIntent = new Intent(Intent.ACTION_VIEW); browserIntent.setData(Uri.parse(TRADE_OFFERS_URL)); browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.getApplicationContext().startActivity(browserIntent); } } ...
a5c723b589699fdf80c42a4186c2fdc0c8d84bb4
tests/sentry/app/tests.py
tests/sentry/app/tests.py
from __future__ import absolute_import import mock from sentry import app from sentry.testutils import TestCase class AppTest(TestCase): def test_buffer_is_a_buffer(self): from sentry.buffer.base import Buffer self.assertEquals(type(app.buffer), Buffer) class GetBufferTest(TestCase): @mock.patch('sentry.app.import_string') def test_instantiates_class_with_options(self, import_string): options = {'hello': 'world'} path = 'lol.FooBar' result = app.get_instance(path, options) import_string.assert_called_once_with(path) import_string.return_value.assert_called_once_with(**options) assert result == import_string.return_value.return_value
from __future__ import absolute_import from sentry import app from sentry.testutils import TestCase class AppTest(TestCase): def test_buffer_is_a_buffer(self): from sentry.buffer.base import Buffer self.assertEquals(type(app.buffer), Buffer)
Remove test that is probably more trouble than it's worth.
Remove test that is probably more trouble than it's worth.
Python
bsd-3-clause
JackDanger/sentry,mvaled/sentry,BuildingLink/sentry,alexm92/sentry,alexm92/sentry,mvaled/sentry,gencer/sentry,JamesMura/sentry,ifduyue/sentry,zenefits/sentry,jean/sentry,fotinakis/sentry,gencer/sentry,zenefits/sentry,gencer/sentry,JamesMura/sentry,zenefits/sentry,mvaled/sentry,mvaled/sentry,BuildingLink/sentry,gencer/sentry,beeftornado/sentry,fotinakis/sentry,beeftornado/sentry,mvaled/sentry,fotinakis/sentry,ifduyue/sentry,ifduyue/sentry,alexm92/sentry,looker/sentry,gencer/sentry,looker/sentry,looker/sentry,mvaled/sentry,ifduyue/sentry,BuildingLink/sentry,zenefits/sentry,BuildingLink/sentry,JackDanger/sentry,JamesMura/sentry,jean/sentry,looker/sentry,fotinakis/sentry,BuildingLink/sentry,JackDanger/sentry,JamesMura/sentry,ifduyue/sentry,jean/sentry,JamesMura/sentry,jean/sentry,jean/sentry,looker/sentry,zenefits/sentry,beeftornado/sentry
python
## Code Before: from __future__ import absolute_import import mock from sentry import app from sentry.testutils import TestCase class AppTest(TestCase): def test_buffer_is_a_buffer(self): from sentry.buffer.base import Buffer self.assertEquals(type(app.buffer), Buffer) class GetBufferTest(TestCase): @mock.patch('sentry.app.import_string') def test_instantiates_class_with_options(self, import_string): options = {'hello': 'world'} path = 'lol.FooBar' result = app.get_instance(path, options) import_string.assert_called_once_with(path) import_string.return_value.assert_called_once_with(**options) assert result == import_string.return_value.return_value ## Instruction: Remove test that is probably more trouble than it's worth. ## Code After: from __future__ import absolute_import from sentry import app from sentry.testutils import TestCase class AppTest(TestCase): def test_buffer_is_a_buffer(self): from sentry.buffer.base import Buffer self.assertEquals(type(app.buffer), Buffer)
# ... existing code ... from __future__ import absolute_import from sentry import app from sentry.testutils import TestCase # ... modified code ... def test_buffer_is_a_buffer(self): from sentry.buffer.base import Buffer self.assertEquals(type(app.buffer), Buffer) # ... rest of the code ...
3a3adca2e5462a98c70a8624f880e35e497e5acc
server.py
server.py
import http.server PORT = 8000 HOST = "127.0.0.1" # This will display the site at `http://localhost:8000/` server_address = (HOST, PORT) # The CGIHTTPRequestHandler class allows us to run the cgi script in /cgi-bin/ # Rather than attempt to display the cgi file itself, which a 'BaseHTTPRequestHandler' or # 'SimpleHTTPRequestHandler' may do httpd = http.server.HTTPServer(server_address, http.server.CGIHTTPRequestHandler) print("Starting my web server on port {0}".format(PORT)) # Make sure the server is always serving the content # You can stop the server running using CTRL + C httpd.serve_forever()
import os import http.server PORT = int(os.environ.get("PORT", 8000)) HOST = "127.0.0.1" # This will display the site at `http://localhost:8000/` server_address = (HOST, PORT) # The CGIHTTPRequestHandler class allows us to run the cgi script in /cgi-bin/ # Rather than attempt to display the cgi file itself, which a 'BaseHTTPRequestHandler' or # 'SimpleHTTPRequestHandler' may do httpd = http.server.HTTPServer(server_address, http.server.CGIHTTPRequestHandler) print("Starting my web server on port {0}".format(PORT)) # Make sure the server is always serving the content # You can stop the server running using CTRL + C httpd.serve_forever()
Set port depending on environment
Set port depending on environment
Python
mit
Charlotteis/guestbook
python
## Code Before: import http.server PORT = 8000 HOST = "127.0.0.1" # This will display the site at `http://localhost:8000/` server_address = (HOST, PORT) # The CGIHTTPRequestHandler class allows us to run the cgi script in /cgi-bin/ # Rather than attempt to display the cgi file itself, which a 'BaseHTTPRequestHandler' or # 'SimpleHTTPRequestHandler' may do httpd = http.server.HTTPServer(server_address, http.server.CGIHTTPRequestHandler) print("Starting my web server on port {0}".format(PORT)) # Make sure the server is always serving the content # You can stop the server running using CTRL + C httpd.serve_forever() ## Instruction: Set port depending on environment ## Code After: import os import http.server PORT = int(os.environ.get("PORT", 8000)) HOST = "127.0.0.1" # This will display the site at `http://localhost:8000/` server_address = (HOST, PORT) # The CGIHTTPRequestHandler class allows us to run the cgi script in /cgi-bin/ # Rather than attempt to display the cgi file itself, which a 'BaseHTTPRequestHandler' or # 'SimpleHTTPRequestHandler' may do httpd = http.server.HTTPServer(server_address, http.server.CGIHTTPRequestHandler) print("Starting my web server on port {0}".format(PORT)) # Make sure the server is always serving the content # You can stop the server running using CTRL + C httpd.serve_forever()
// ... existing code ... import os import http.server PORT = int(os.environ.get("PORT", 8000)) HOST = "127.0.0.1" # This will display the site at `http://localhost:8000/` // ... rest of the code ...
491d2ad7cea58597e15b095b94930b6ff1dbf4d2
createdb.py
createdb.py
from chalice.extensions import db from chalice import init_app from chalice.blog.models import Tag, Post from chalice.auth.models import User if __name__ == '__main__': app = init_app() with app.test_request_context(): db.create_all() post = Post( 'This is a title', 'The classic hello world here.') post.tags = ['rant', 'programming'] db.session.add(post) user = User('andrimar', 'testpass') db.session.add(user) db.session.commit() print 'Initialized an empty db using the following connection string: %s' % app.config['SQLALCHEMY_DATABASE_URI']
from chalice.extensions import db from chalice import init_app from chalice.blog.models import Tag, Post from chalice.auth.models import User if __name__ == '__main__': app = init_app() with app.test_request_context(): db.create_all() user = User(app.config['CHALICE_USER'], app.config['CHALICE_PASS']) db.session.add(user) db.session.commit() print 'Initialized a db using the following connection string: %s' % app.config['SQLALCHEMY_DATABASE_URI']
Remove dummy post from created.py script. Initial user now taken from config.
Remove dummy post from created.py script. Initial user now taken from config.
Python
bsd-2-clause
andrimarjonsson/chalice,andrimarjonsson/chalice
python
## Code Before: from chalice.extensions import db from chalice import init_app from chalice.blog.models import Tag, Post from chalice.auth.models import User if __name__ == '__main__': app = init_app() with app.test_request_context(): db.create_all() post = Post( 'This is a title', 'The classic hello world here.') post.tags = ['rant', 'programming'] db.session.add(post) user = User('andrimar', 'testpass') db.session.add(user) db.session.commit() print 'Initialized an empty db using the following connection string: %s' % app.config['SQLALCHEMY_DATABASE_URI'] ## Instruction: Remove dummy post from created.py script. Initial user now taken from config. ## Code After: from chalice.extensions import db from chalice import init_app from chalice.blog.models import Tag, Post from chalice.auth.models import User if __name__ == '__main__': app = init_app() with app.test_request_context(): db.create_all() user = User(app.config['CHALICE_USER'], app.config['CHALICE_PASS']) db.session.add(user) db.session.commit() print 'Initialized a db using the following connection string: %s' % app.config['SQLALCHEMY_DATABASE_URI']
... app = init_app() with app.test_request_context(): db.create_all() user = User(app.config['CHALICE_USER'], app.config['CHALICE_PASS']) db.session.add(user) db.session.commit() print 'Initialized a db using the following connection string: %s' % app.config['SQLALCHEMY_DATABASE_URI'] ...
2a81e9b207fa83fa57228e930e0e618b698e97b9
app/src/main/java/com/github/vase4kin/teamcityapp/api/cache/CacheProviders.java
app/src/main/java/com/github/vase4kin/teamcityapp/api/cache/CacheProviders.java
/* * Copyright 2016 Andrey Tolpeev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.vase4kin.teamcityapp.api.cache; import com.github.vase4kin.teamcityapp.navigation.api.NavigationNode; import com.github.vase4kin.teamcityapp.runbuild.api.Branches; import java.util.concurrent.TimeUnit; import io.rx_cache.DynamicKey; import io.rx_cache.EvictDynamicKey; import io.rx_cache.LifeCache; import rx.Observable; /** * Cache providers */ public interface CacheProviders { // TODO: Increase cache to 24 hours? Good idea, huh? @LifeCache(duration = 1, timeUnit = TimeUnit.HOURS) Observable<NavigationNode> listBuildTypes(Observable<NavigationNode> navigationNodeObservable, DynamicKey dynamicKey, EvictDynamicKey evictDynamicKey); @LifeCache(duration = 1, timeUnit = TimeUnit.MINUTES) Observable<Branches> listBranches(Observable<Branches> branchesObservable, DynamicKey buildTypeId); }
/* * Copyright 2016 Andrey Tolpeev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.vase4kin.teamcityapp.api.cache; import com.github.vase4kin.teamcityapp.navigation.api.NavigationNode; import com.github.vase4kin.teamcityapp.runbuild.api.Branches; import java.util.concurrent.TimeUnit; import io.rx_cache.DynamicKey; import io.rx_cache.EvictDynamicKey; import io.rx_cache.LifeCache; import rx.Observable; /** * Cache providers */ public interface CacheProviders { @LifeCache(duration = 1, timeUnit = TimeUnit.DAYS) Observable<NavigationNode> listBuildTypes(Observable<NavigationNode> navigationNodeObservable, DynamicKey dynamicKey, EvictDynamicKey evictDynamicKey); @LifeCache(duration = 1, timeUnit = TimeUnit.MINUTES) Observable<Branches> listBranches(Observable<Branches> branchesObservable, DynamicKey buildTypeId); }
Increase build types cache life for one day
Increase build types cache life for one day
Java
apache-2.0
vase4kin/TeamCityApp,vase4kin/TeamCityApp,vase4kin/TeamCityApp
java
## Code Before: /* * Copyright 2016 Andrey Tolpeev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.vase4kin.teamcityapp.api.cache; import com.github.vase4kin.teamcityapp.navigation.api.NavigationNode; import com.github.vase4kin.teamcityapp.runbuild.api.Branches; import java.util.concurrent.TimeUnit; import io.rx_cache.DynamicKey; import io.rx_cache.EvictDynamicKey; import io.rx_cache.LifeCache; import rx.Observable; /** * Cache providers */ public interface CacheProviders { // TODO: Increase cache to 24 hours? Good idea, huh? @LifeCache(duration = 1, timeUnit = TimeUnit.HOURS) Observable<NavigationNode> listBuildTypes(Observable<NavigationNode> navigationNodeObservable, DynamicKey dynamicKey, EvictDynamicKey evictDynamicKey); @LifeCache(duration = 1, timeUnit = TimeUnit.MINUTES) Observable<Branches> listBranches(Observable<Branches> branchesObservable, DynamicKey buildTypeId); } ## Instruction: Increase build types cache life for one day ## Code After: /* * Copyright 2016 Andrey Tolpeev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.vase4kin.teamcityapp.api.cache; import com.github.vase4kin.teamcityapp.navigation.api.NavigationNode; import com.github.vase4kin.teamcityapp.runbuild.api.Branches; import java.util.concurrent.TimeUnit; import io.rx_cache.DynamicKey; import io.rx_cache.EvictDynamicKey; import io.rx_cache.LifeCache; import rx.Observable; /** * Cache providers */ public interface CacheProviders { @LifeCache(duration = 1, timeUnit = TimeUnit.DAYS) Observable<NavigationNode> listBuildTypes(Observable<NavigationNode> navigationNodeObservable, DynamicKey dynamicKey, EvictDynamicKey evictDynamicKey); @LifeCache(duration = 1, timeUnit = TimeUnit.MINUTES) Observable<Branches> listBranches(Observable<Branches> branchesObservable, DynamicKey buildTypeId); }
# ... existing code ... */ public interface CacheProviders { @LifeCache(duration = 1, timeUnit = TimeUnit.DAYS) Observable<NavigationNode> listBuildTypes(Observable<NavigationNode> navigationNodeObservable, DynamicKey dynamicKey, EvictDynamicKey evictDynamicKey); @LifeCache(duration = 1, timeUnit = TimeUnit.MINUTES) # ... rest of the code ...
79d8916aecc95919fa77ddd845fdd3e0a7e0c4d9
src/ngin.py
src/ngin.py
import argparse from string import Template """ Subclassing template class """ class NginTemplate(Template): delimiter = '#' """ Reverse Proxy Template """ reverse_proxy_template = """ server { listen 80; server_name #{server_name}; access_log /var/log/nginx/#{server_name}.access.log; error_log /var/log/nginx/#{server_name}.error.log; location / { proxy_pass #{proxy_pass}; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }""" """ Initiate argparse """ parser = argparse.ArgumentParser() """ Add arguments """ parser.add_argument("-r", "--revproxy", help="reverse proxy", action="store_true") parser.add_argument("-n", "--name", help="server name or domain name", action="store") parser.add_argument("-p", "--proxypass", help="proxy pass server", action="store") """ Parsing arguments """ args = parser.parse_args() """ Reverse proxy config generator Usage Example: ngin.py -r -n example.com -p http://localhost:9000 """ if args.revproxy: if args.name is None or args.proxypass is None: raise SystemExit('Name and Pass is required!') params = {'server_name': args.name, 'proxy_pass': args.proxypass} conf = NginTemplate(reverse_proxy_template).safe_substitute(params) print conf
import argparse from nginx_conf import server, reverse_proxy from nginx_blocks import make_location_block, make_server_block from utils import to_nginx_template, make_indent """ Initiate argparse """ parser = argparse.ArgumentParser() """ Add arguments """ parser.add_argument("-r", "--revproxy", help="reverse proxy", action="store_true") parser.add_argument("-n", "--name", help="server name or domain name", action="store") parser.add_argument("-p", "--proxypass", help="proxy pass server", action="store") """ Parsing arguments """ args = parser.parse_args() """ Reverse proxy config generator Usage Example: ngin.py -r -n example.com -p http://localhost:9000 """ if args.revproxy: if args.name is None or args.proxypass is None: raise SystemExit('Name and Pass is required!') server['server_name'] = args.name reverse_proxy['proxy_pass'] = args.proxypass location = make_location_block(to_nginx_template(reverse_proxy), '/') server = to_nginx_template(server) conf = make_server_block('{} {}'.format(server, location)) print make_indent(conf)
Remove old stuff with dynamic config generator
Remove old stuff with dynamic config generator
Python
mit
thesabbir/nginpro
python
## Code Before: import argparse from string import Template """ Subclassing template class """ class NginTemplate(Template): delimiter = '#' """ Reverse Proxy Template """ reverse_proxy_template = """ server { listen 80; server_name #{server_name}; access_log /var/log/nginx/#{server_name}.access.log; error_log /var/log/nginx/#{server_name}.error.log; location / { proxy_pass #{proxy_pass}; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }""" """ Initiate argparse """ parser = argparse.ArgumentParser() """ Add arguments """ parser.add_argument("-r", "--revproxy", help="reverse proxy", action="store_true") parser.add_argument("-n", "--name", help="server name or domain name", action="store") parser.add_argument("-p", "--proxypass", help="proxy pass server", action="store") """ Parsing arguments """ args = parser.parse_args() """ Reverse proxy config generator Usage Example: ngin.py -r -n example.com -p http://localhost:9000 """ if args.revproxy: if args.name is None or args.proxypass is None: raise SystemExit('Name and Pass is required!') params = {'server_name': args.name, 'proxy_pass': args.proxypass} conf = NginTemplate(reverse_proxy_template).safe_substitute(params) print conf ## Instruction: Remove old stuff with dynamic config generator ## Code After: import argparse from nginx_conf import server, reverse_proxy from nginx_blocks import make_location_block, make_server_block from utils import to_nginx_template, make_indent """ Initiate argparse """ parser = argparse.ArgumentParser() """ Add arguments """ parser.add_argument("-r", "--revproxy", help="reverse proxy", action="store_true") parser.add_argument("-n", "--name", help="server name or domain name", action="store") parser.add_argument("-p", "--proxypass", help="proxy pass server", action="store") """ Parsing arguments """ args = parser.parse_args() """ Reverse proxy config generator Usage Example: ngin.py -r -n example.com -p http://localhost:9000 """ if args.revproxy: if args.name is None or args.proxypass is None: raise SystemExit('Name and Pass is required!') server['server_name'] = args.name reverse_proxy['proxy_pass'] = args.proxypass location = make_location_block(to_nginx_template(reverse_proxy), '/') server = to_nginx_template(server) conf = make_server_block('{} {}'.format(server, location)) print make_indent(conf)
// ... existing code ... import argparse from nginx_conf import server, reverse_proxy from nginx_blocks import make_location_block, make_server_block from utils import to_nginx_template, make_indent """ Initiate argparse // ... modified code ... if args.revproxy: if args.name is None or args.proxypass is None: raise SystemExit('Name and Pass is required!') server['server_name'] = args.name reverse_proxy['proxy_pass'] = args.proxypass location = make_location_block(to_nginx_template(reverse_proxy), '/') server = to_nginx_template(server) conf = make_server_block('{} {}'.format(server, location)) print make_indent(conf) // ... rest of the code ...
3609489c0cfd14f9f28a46555f099adcbc29b539
generators/server/templates/src/main/java/package/web/rest/errors/_CustomParameterizedException.java
generators/server/templates/src/main/java/package/web/rest/errors/_CustomParameterizedException.java
package <%=packageName%>.web.rest.errors; import java.util.HashMap; import java.util.Map; /** * Custom, parameterized exception, which can be translated on the client side. * For example: * * <pre> * throw new CustomParameterizedException(&quot;myCustomError&quot;, &quot;hello&quot;, &quot;world&quot;); * </pre> * * Can be translated with: * * <pre> * "error.myCustomError" : "The server says {{param0}} to {{param1}}" * </pre> */ public class CustomParameterizedException extends RuntimeException { private static final long serialVersionUID = 1L; private static final String PARAM = "param"; private final String message; private Map<String, String> paramMap; public CustomParameterizedException(String message, String... params) { super(message); this.message = message; if (params != null && params.length > 0) { this.paramMap = new HashMap<>(); for (int i = 0; i < params.length; i++) { paramMap.put(PARAM + i, params[i]); } } } public CustomParameterizedException(String message, Map<String, String> paramMap) { super(message); this.message = message; this.paramMap = paramMap; } public ParameterizedErrorVM getErrorVM() { return new ParameterizedErrorVM(message, paramMap); } }
package <%=packageName%>.web.rest.errors; import java.util.HashMap; import java.util.Map; /** * Custom, parameterized exception, which can be translated on the client side. * For example: * * <pre> * throw new CustomParameterizedException(&quot;myCustomError&quot;, &quot;hello&quot;, &quot;world&quot;); * </pre> * * Can be translated with: * * <pre> * "error.myCustomError" : "The server says {{param0}} to {{param1}}" * </pre> */ public class CustomParameterizedException extends RuntimeException { private static final long serialVersionUID = 1L; private static final String PARAM = "param"; private final String message; private final Map<String, String> paramMap = new HashMap<>(); public CustomParameterizedException(String message, String... params) { super(message); this.message = message; if (params != null && params.length > 0) { for (int i = 0; i < params.length; i++) { paramMap.put(PARAM + i, params[i]); } } } public CustomParameterizedException(String message, Map<String, String> paramMap) { super(message); this.message = message; this.paramMap.putAll(paramMap); } public ParameterizedErrorVM getErrorVM() { return new ParameterizedErrorVM(message, paramMap); } }
Change code to make Sonar happy
Change code to make Sonar happy See #5489
Java
apache-2.0
cbornet/generator-jhipster,jhipster/generator-jhipster,sohibegit/generator-jhipster,PierreBesson/generator-jhipster,stevehouel/generator-jhipster,stevehouel/generator-jhipster,siliconharborlabs/generator-jhipster,gzsombor/generator-jhipster,jhipster/generator-jhipster,duderoot/generator-jhipster,mraible/generator-jhipster,dynamicguy/generator-jhipster,cbornet/generator-jhipster,danielpetisme/generator-jhipster,ziogiugno/generator-jhipster,liseri/generator-jhipster,dynamicguy/generator-jhipster,siliconharborlabs/generator-jhipster,eosimosu/generator-jhipster,danielpetisme/generator-jhipster,ziogiugno/generator-jhipster,dalbelap/generator-jhipster,gmarziou/generator-jhipster,Tcharl/generator-jhipster,sendilkumarn/generator-jhipster,yongli82/generator-jhipster,ctamisier/generator-jhipster,rkohel/generator-jhipster,gmarziou/generator-jhipster,mraible/generator-jhipster,eosimosu/generator-jhipster,sendilkumarn/generator-jhipster,JulienMrgrd/generator-jhipster,ramzimaalej/generator-jhipster,PierreBesson/generator-jhipster,stevehouel/generator-jhipster,vivekmore/generator-jhipster,dalbelap/generator-jhipster,mosoft521/generator-jhipster,duderoot/generator-jhipster,ctamisier/generator-jhipster,eosimosu/generator-jhipster,wmarques/generator-jhipster,atomfrede/generator-jhipster,nkolosnjaji/generator-jhipster,atomfrede/generator-jhipster,danielpetisme/generator-jhipster,JulienMrgrd/generator-jhipster,jkutner/generator-jhipster,liseri/generator-jhipster,dimeros/generator-jhipster,PierreBesson/generator-jhipster,JulienMrgrd/generator-jhipster,yongli82/generator-jhipster,wmarques/generator-jhipster,erikkemperman/generator-jhipster,jkutner/generator-jhipster,deepu105/generator-jhipster,jhipster/generator-jhipster,pascalgrimaud/generator-jhipster,hdurix/generator-jhipster,sendilkumarn/generator-jhipster,gmarziou/generator-jhipster,Tcharl/generator-jhipster,jkutner/generator-jhipster,eosimosu/generator-jhipster,wmarques/generator-jhipster,siliconharborlabs/generator-jhipster,hdurix/generator-jhipster,dimeros/generator-jhipster,jkutner/generator-jhipster,wmarques/generator-jhipster,rkohel/generator-jhipster,deepu105/generator-jhipster,erikkemperman/generator-jhipster,vivekmore/generator-jhipster,JulienMrgrd/generator-jhipster,mraible/generator-jhipster,hdurix/generator-jhipster,duderoot/generator-jhipster,nkolosnjaji/generator-jhipster,cbornet/generator-jhipster,sohibegit/generator-jhipster,gmarziou/generator-jhipster,robertmilowski/generator-jhipster,sohibegit/generator-jhipster,rifatdover/generator-jhipster,vivekmore/generator-jhipster,yongli82/generator-jhipster,jkutner/generator-jhipster,yongli82/generator-jhipster,Tcharl/generator-jhipster,liseri/generator-jhipster,dalbelap/generator-jhipster,mosoft521/generator-jhipster,ziogiugno/generator-jhipster,dimeros/generator-jhipster,jhipster/generator-jhipster,mraible/generator-jhipster,siliconharborlabs/generator-jhipster,Tcharl/generator-jhipster,mraible/generator-jhipster,ruddell/generator-jhipster,gzsombor/generator-jhipster,hdurix/generator-jhipster,erikkemperman/generator-jhipster,hdurix/generator-jhipster,ramzimaalej/generator-jhipster,sendilkumarn/generator-jhipster,ruddell/generator-jhipster,sohibegit/generator-jhipster,cbornet/generator-jhipster,pascalgrimaud/generator-jhipster,sendilkumarn/generator-jhipster,erikkemperman/generator-jhipster,ziogiugno/generator-jhipster,robertmilowski/generator-jhipster,ctamisier/generator-jhipster,erikkemperman/generator-jhipster,stevehouel/generator-jhipster,PierreBesson/generator-jhipster,liseri/generator-jhipster,pascalgrimaud/generator-jhipster,wmarques/generator-jhipster,vivekmore/generator-jhipster,rifatdover/generator-jhipster,ruddell/generator-jhipster,eosimosu/generator-jhipster,ctamisier/generator-jhipster,PierreBesson/generator-jhipster,robertmilowski/generator-jhipster,rkohel/generator-jhipster,rifatdover/generator-jhipster,danielpetisme/generator-jhipster,nkolosnjaji/generator-jhipster,ctamisier/generator-jhipster,nkolosnjaji/generator-jhipster,mosoft521/generator-jhipster,gzsombor/generator-jhipster,ziogiugno/generator-jhipster,deepu105/generator-jhipster,duderoot/generator-jhipster,gzsombor/generator-jhipster,cbornet/generator-jhipster,danielpetisme/generator-jhipster,nkolosnjaji/generator-jhipster,dynamicguy/generator-jhipster,dalbelap/generator-jhipster,duderoot/generator-jhipster,deepu105/generator-jhipster,siliconharborlabs/generator-jhipster,ruddell/generator-jhipster,JulienMrgrd/generator-jhipster,dimeros/generator-jhipster,pascalgrimaud/generator-jhipster,dynamicguy/generator-jhipster,gzsombor/generator-jhipster,vivekmore/generator-jhipster,ramzimaalej/generator-jhipster,atomfrede/generator-jhipster,sohibegit/generator-jhipster,Tcharl/generator-jhipster,dimeros/generator-jhipster,gmarziou/generator-jhipster,rkohel/generator-jhipster,yongli82/generator-jhipster,pascalgrimaud/generator-jhipster,robertmilowski/generator-jhipster,atomfrede/generator-jhipster,liseri/generator-jhipster,jhipster/generator-jhipster,deepu105/generator-jhipster,robertmilowski/generator-jhipster,rkohel/generator-jhipster,mosoft521/generator-jhipster,atomfrede/generator-jhipster,dalbelap/generator-jhipster,stevehouel/generator-jhipster,ruddell/generator-jhipster,mosoft521/generator-jhipster
java
## Code Before: package <%=packageName%>.web.rest.errors; import java.util.HashMap; import java.util.Map; /** * Custom, parameterized exception, which can be translated on the client side. * For example: * * <pre> * throw new CustomParameterizedException(&quot;myCustomError&quot;, &quot;hello&quot;, &quot;world&quot;); * </pre> * * Can be translated with: * * <pre> * "error.myCustomError" : "The server says {{param0}} to {{param1}}" * </pre> */ public class CustomParameterizedException extends RuntimeException { private static final long serialVersionUID = 1L; private static final String PARAM = "param"; private final String message; private Map<String, String> paramMap; public CustomParameterizedException(String message, String... params) { super(message); this.message = message; if (params != null && params.length > 0) { this.paramMap = new HashMap<>(); for (int i = 0; i < params.length; i++) { paramMap.put(PARAM + i, params[i]); } } } public CustomParameterizedException(String message, Map<String, String> paramMap) { super(message); this.message = message; this.paramMap = paramMap; } public ParameterizedErrorVM getErrorVM() { return new ParameterizedErrorVM(message, paramMap); } } ## Instruction: Change code to make Sonar happy See #5489 ## Code After: package <%=packageName%>.web.rest.errors; import java.util.HashMap; import java.util.Map; /** * Custom, parameterized exception, which can be translated on the client side. * For example: * * <pre> * throw new CustomParameterizedException(&quot;myCustomError&quot;, &quot;hello&quot;, &quot;world&quot;); * </pre> * * Can be translated with: * * <pre> * "error.myCustomError" : "The server says {{param0}} to {{param1}}" * </pre> */ public class CustomParameterizedException extends RuntimeException { private static final long serialVersionUID = 1L; private static final String PARAM = "param"; private final String message; private final Map<String, String> paramMap = new HashMap<>(); public CustomParameterizedException(String message, String... params) { super(message); this.message = message; if (params != null && params.length > 0) { for (int i = 0; i < params.length; i++) { paramMap.put(PARAM + i, params[i]); } } } public CustomParameterizedException(String message, Map<String, String> paramMap) { super(message); this.message = message; this.paramMap.putAll(paramMap); } public ParameterizedErrorVM getErrorVM() { return new ParameterizedErrorVM(message, paramMap); } }
// ... existing code ... private static final String PARAM = "param"; private final String message; private final Map<String, String> paramMap = new HashMap<>(); public CustomParameterizedException(String message, String... params) { super(message); this.message = message; if (params != null && params.length > 0) { for (int i = 0; i < params.length; i++) { paramMap.put(PARAM + i, params[i]); } // ... modified code ... public CustomParameterizedException(String message, Map<String, String> paramMap) { super(message); this.message = message; this.paramMap.putAll(paramMap); } public ParameterizedErrorVM getErrorVM() { return new ParameterizedErrorVM(message, paramMap); } } // ... rest of the code ...
d3af229c5c692fdb52c211cd8785bcb7c869090b
reobject/query.py
reobject/query.py
from reobject.utils import signed_attrgetter class QuerySet(list): def __init__(self, *args, **kwargs): super(QuerySet, self).__init__(*args, **kwargs) def count(self): return len(self) def delete(self): for item in self: item.delete() def exists(self): return bool(self) def order_by(self, *args): return type(self)( sorted(self, key=signed_attrgetter(*args)) )
from reobject.utils import signed_attrgetter class QuerySet(list): def __init__(self, *args, **kwargs): super(QuerySet, self).__init__(*args, **kwargs) def count(self): return len(self) def delete(self): for item in self: item.delete() def exists(self): return bool(self) def order_by(self, *args): return type(self)( sorted(self, key=signed_attrgetter(*args)) ) def reverse(self): return type(self)( reversed(self) )
Allow QuerySet objects to be reversed
Allow QuerySet objects to be reversed
Python
apache-2.0
onyb/reobject,onyb/reobject
python
## Code Before: from reobject.utils import signed_attrgetter class QuerySet(list): def __init__(self, *args, **kwargs): super(QuerySet, self).__init__(*args, **kwargs) def count(self): return len(self) def delete(self): for item in self: item.delete() def exists(self): return bool(self) def order_by(self, *args): return type(self)( sorted(self, key=signed_attrgetter(*args)) ) ## Instruction: Allow QuerySet objects to be reversed ## Code After: from reobject.utils import signed_attrgetter class QuerySet(list): def __init__(self, *args, **kwargs): super(QuerySet, self).__init__(*args, **kwargs) def count(self): return len(self) def delete(self): for item in self: item.delete() def exists(self): return bool(self) def order_by(self, *args): return type(self)( sorted(self, key=signed_attrgetter(*args)) ) def reverse(self): return type(self)( reversed(self) )
... return type(self)( sorted(self, key=signed_attrgetter(*args)) ) def reverse(self): return type(self)( reversed(self) ) ...
542c416be33f1cc748530f20db2025f43f490b30
content/public/common/resource_devtools_info.h
content/public/common/resource_devtools_info.h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_COMMON_RESOURCE_DEVTOOLS_INFO_H_ #define CONTENT_COMMON_RESOURCE_DEVTOOLS_INFO_H_ #include <string> #include <vector> #include "base/basictypes.h" #include "base/memory/ref_counted.h" #include "content/common/content_export.h" namespace content { struct ResourceDevToolsInfo : base::RefCounted<ResourceDevToolsInfo> { typedef std::vector<std::pair<std::string, std::string> > HeadersVector; CONTENT_EXPORT ResourceDevToolsInfo(); int32 http_status_code; std::string http_status_text; HeadersVector request_headers; HeadersVector response_headers; std::string request_headers_text; std::string response_headers_text; private: friend class base::RefCounted<ResourceDevToolsInfo>; CONTENT_EXPORT ~ResourceDevToolsInfo(); }; } // namespace content #endif // CONTENT_COMMON_RESOURCE_DEVTOOLS_INFO_H_
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_COMMON_RESOURCE_DEVTOOLS_INFO_H_ #define CONTENT_COMMON_RESOURCE_DEVTOOLS_INFO_H_ #include <string> #include <vector> #include "base/basictypes.h" #include "base/memory/ref_counted.h" #include "base/strings/string_split.h" #include "content/common/content_export.h" namespace content { struct ResourceDevToolsInfo : base::RefCounted<ResourceDevToolsInfo> { typedef base::StringPairs HeadersVector; CONTENT_EXPORT ResourceDevToolsInfo(); int32 http_status_code; std::string http_status_text; HeadersVector request_headers; HeadersVector response_headers; std::string request_headers_text; std::string response_headers_text; private: friend class base::RefCounted<ResourceDevToolsInfo>; CONTENT_EXPORT ~ResourceDevToolsInfo(); }; } // namespace content #endif // CONTENT_COMMON_RESOURCE_DEVTOOLS_INFO_H_
Use base::StringPairs where appropriate from /content
Use base::StringPairs where appropriate from /content Because base/strings/string_split.h defines: typedef std::vector<std::pair<std::string, std::string> > StringPairs; BUG=412250 Review URL: https://codereview.chromium.org/600163003 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#296649}
C
bsd-3-clause
hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,dednal/chromium.src,ltilve/chromium,dednal/chromium.src,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,dednal/chromium.src,M4sse/chromium.src,ltilve/chromium,markYoungH/chromium.src,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,Just-D/chromium-1,fujunwei/chromium-crosswalk,Jonekee/chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,Fireblend/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,markYoungH/chromium.src,markYoungH/chromium.src,markYoungH/chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,jaruba/chromium.src,Chilledheart/chromium,fujunwei/chromium-crosswalk,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk,markYoungH/chromium.src,Chilledheart/chromium,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,M4sse/chromium.src,M4sse/chromium.src,dednal/chromium.src,Just-D/chromium-1,Just-D/chromium-1,M4sse/chromium.src,Chilledheart/chromium,dushu1203/chromium.src,Jonekee/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,Jonekee/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk,M4sse/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,markYoungH/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dednal/chromium.src,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,Chilledheart/chromium,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,dednal/chromium.src,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,Chilledheart/chromium,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,Just-D/chromium-1,jaruba/chromium.src,ltilve/chromium,ltilve/chromium,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,dednal/chromium.src,jaruba/chromium.src,Fireblend/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,dushu1203/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,M4sse/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,markYoungH/chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,Just-D/chromium-1,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk
c
## Code Before: // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_COMMON_RESOURCE_DEVTOOLS_INFO_H_ #define CONTENT_COMMON_RESOURCE_DEVTOOLS_INFO_H_ #include <string> #include <vector> #include "base/basictypes.h" #include "base/memory/ref_counted.h" #include "content/common/content_export.h" namespace content { struct ResourceDevToolsInfo : base::RefCounted<ResourceDevToolsInfo> { typedef std::vector<std::pair<std::string, std::string> > HeadersVector; CONTENT_EXPORT ResourceDevToolsInfo(); int32 http_status_code; std::string http_status_text; HeadersVector request_headers; HeadersVector response_headers; std::string request_headers_text; std::string response_headers_text; private: friend class base::RefCounted<ResourceDevToolsInfo>; CONTENT_EXPORT ~ResourceDevToolsInfo(); }; } // namespace content #endif // CONTENT_COMMON_RESOURCE_DEVTOOLS_INFO_H_ ## Instruction: Use base::StringPairs where appropriate from /content Because base/strings/string_split.h defines: typedef std::vector<std::pair<std::string, std::string> > StringPairs; BUG=412250 Review URL: https://codereview.chromium.org/600163003 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#296649} ## Code After: // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_COMMON_RESOURCE_DEVTOOLS_INFO_H_ #define CONTENT_COMMON_RESOURCE_DEVTOOLS_INFO_H_ #include <string> #include <vector> #include "base/basictypes.h" #include "base/memory/ref_counted.h" #include "base/strings/string_split.h" #include "content/common/content_export.h" namespace content { struct ResourceDevToolsInfo : base::RefCounted<ResourceDevToolsInfo> { typedef base::StringPairs HeadersVector; CONTENT_EXPORT ResourceDevToolsInfo(); int32 http_status_code; std::string http_status_text; HeadersVector request_headers; HeadersVector response_headers; std::string request_headers_text; std::string response_headers_text; private: friend class base::RefCounted<ResourceDevToolsInfo>; CONTENT_EXPORT ~ResourceDevToolsInfo(); }; } // namespace content #endif // CONTENT_COMMON_RESOURCE_DEVTOOLS_INFO_H_
// ... existing code ... #include "base/basictypes.h" #include "base/memory/ref_counted.h" #include "base/strings/string_split.h" #include "content/common/content_export.h" namespace content { struct ResourceDevToolsInfo : base::RefCounted<ResourceDevToolsInfo> { typedef base::StringPairs HeadersVector; CONTENT_EXPORT ResourceDevToolsInfo(); // ... rest of the code ...
d4f21288e7ba6bdc27f0f01fd0dba394a9786aa6
open_humans/utilities.py
open_humans/utilities.py
import io import os from ConfigParser import RawConfigParser def apply_env(): """ Read the `.env` file and apply it to os.environ just like using `foreman run` would. """ env = '[root]\n' + io.open('.env', 'r').read() config = RawConfigParser(allow_no_value=True) # Use `str` instead of the regular option transform to preserve option case config.optionxform = str config.readfp(io.StringIO(env), '.env') os.environ.update(config.items('root'))
import io import os from ConfigParser import RawConfigParser def apply_env(): """ Read the `.env` file and apply it to os.environ just like using `foreman run` would. """ try: env = '[root]\n' + io.open('.env', 'r').read() except IOError: return config = RawConfigParser(allow_no_value=True) # Use `str` instead of the regular option transform to preserve option case config.optionxform = str config.readfp(io.StringIO(env), '.env') os.environ.update(config.items('root'))
Fix crash if .env does not exist
Fix crash if .env does not exist
Python
mit
PersonalGenomesOrg/open-humans,OpenHumans/open-humans,OpenHumans/open-humans,PersonalGenomesOrg/open-humans,OpenHumans/open-humans,OpenHumans/open-humans,PersonalGenomesOrg/open-humans,PersonalGenomesOrg/open-humans
python
## Code Before: import io import os from ConfigParser import RawConfigParser def apply_env(): """ Read the `.env` file and apply it to os.environ just like using `foreman run` would. """ env = '[root]\n' + io.open('.env', 'r').read() config = RawConfigParser(allow_no_value=True) # Use `str` instead of the regular option transform to preserve option case config.optionxform = str config.readfp(io.StringIO(env), '.env') os.environ.update(config.items('root')) ## Instruction: Fix crash if .env does not exist ## Code After: import io import os from ConfigParser import RawConfigParser def apply_env(): """ Read the `.env` file and apply it to os.environ just like using `foreman run` would. """ try: env = '[root]\n' + io.open('.env', 'r').read() except IOError: return config = RawConfigParser(allow_no_value=True) # Use `str` instead of the regular option transform to preserve option case config.optionxform = str config.readfp(io.StringIO(env), '.env') os.environ.update(config.items('root'))
// ... existing code ... Read the `.env` file and apply it to os.environ just like using `foreman run` would. """ try: env = '[root]\n' + io.open('.env', 'r').read() except IOError: return config = RawConfigParser(allow_no_value=True) // ... rest of the code ...
ebb0916a7c63c1aaf383c696c203199ca79f70ac
nereid/backend.py
nereid/backend.py
''' nereid.backend Backed - Tryton specific features :copyright: (c) 2010-2012 by Openlabs Technologies & Consulting (P) Ltd. :license: GPLv3, see LICENSE for more details ''' class TransactionManager(object): def __init__(self, database_name, user, context=None): self.database_name = database_name self.user = user self.context = context if context is not None else {} def __enter__(self): from trytond.transaction import Transaction Transaction().start(self.database_name, self.user, self.context.copy()) return Transaction() def __exit__(self, type, value, traceback): from trytond.transaction import Transaction Transaction().stop()
''' nereid.backend Backed - Tryton specific features :copyright: (c) 2010-2012 by Openlabs Technologies & Consulting (P) Ltd. :license: GPLv3, see LICENSE for more details ''' class TransactionManager(object): def __init__(self, database_name, user, context=None): self.database_name = database_name self.user = user self.context = context if context is not None else {} def __enter__(self): from trytond.transaction import Transaction Transaction().start( self.database_name, self.user, readonly=False, context=self.context.copy() ) return Transaction() def __exit__(self, type, value, traceback): from trytond.transaction import Transaction Transaction().stop()
Change the way transaction is initiated as readonly support was introduced in version 2.4
Change the way transaction is initiated as readonly support was introduced in version 2.4
Python
bsd-3-clause
riteshshrv/nereid,usudaysingh/nereid,usudaysingh/nereid,riteshshrv/nereid,fulfilio/nereid,fulfilio/nereid,prakashpp/nereid,prakashpp/nereid
python
## Code Before: ''' nereid.backend Backed - Tryton specific features :copyright: (c) 2010-2012 by Openlabs Technologies & Consulting (P) Ltd. :license: GPLv3, see LICENSE for more details ''' class TransactionManager(object): def __init__(self, database_name, user, context=None): self.database_name = database_name self.user = user self.context = context if context is not None else {} def __enter__(self): from trytond.transaction import Transaction Transaction().start(self.database_name, self.user, self.context.copy()) return Transaction() def __exit__(self, type, value, traceback): from trytond.transaction import Transaction Transaction().stop() ## Instruction: Change the way transaction is initiated as readonly support was introduced in version 2.4 ## Code After: ''' nereid.backend Backed - Tryton specific features :copyright: (c) 2010-2012 by Openlabs Technologies & Consulting (P) Ltd. :license: GPLv3, see LICENSE for more details ''' class TransactionManager(object): def __init__(self, database_name, user, context=None): self.database_name = database_name self.user = user self.context = context if context is not None else {} def __enter__(self): from trytond.transaction import Transaction Transaction().start( self.database_name, self.user, readonly=False, context=self.context.copy() ) return Transaction() def __exit__(self, type, value, traceback): from trytond.transaction import Transaction Transaction().stop()
... def __enter__(self): from trytond.transaction import Transaction Transaction().start( self.database_name, self.user, readonly=False, context=self.context.copy() ) return Transaction() def __exit__(self, type, value, traceback): ...
7f1a58f9faacb0bb0e95c2527a348195742eb866
tornado/test/autoreload_test.py
tornado/test/autoreload_test.py
from __future__ import absolute_import, division, print_function import os import subprocess from subprocess import Popen import sys from tempfile import mkdtemp from tornado.test.util import unittest MAIN = """\ import os import sys from tornado import autoreload # This import will fail if path is not set up correctly import testapp print('Starting') if 'TESTAPP_STARTED' not in os.environ: os.environ['TESTAPP_STARTED'] = '1' sys.stdout.flush() autoreload._reload() """ class AutoreloadTest(unittest.TestCase): def test_reload_module(self): # Create temporary test application path = mkdtemp() os.mkdir(os.path.join(path, 'testapp')) open(os.path.join(path, 'testapp/__init__.py'), 'w').close() with open(os.path.join(path, 'testapp/__main__.py'), 'w') as f: f.write(MAIN) # Make sure the tornado module under test is available to the test # application pythonpath = os.getcwd() if 'PYTHONPATH' in os.environ: pythonpath += os.pathsep + os.environ['PYTHONPATH'] p = Popen([sys.executable, '-m', 'testapp'], stdout=subprocess.PIPE, cwd=path, env=dict(os.environ, PYTHONPATH=pythonpath)) out = p.communicate()[0].decode() self.assertEqual(out, 'Starting\nStarting\n')
from __future__ import absolute_import, division, print_function import os import subprocess from subprocess import Popen import sys from tempfile import mkdtemp from tornado.test.util import unittest MAIN = """\ import os import sys from tornado import autoreload # This import will fail if path is not set up correctly import testapp print('Starting') if 'TESTAPP_STARTED' not in os.environ: os.environ['TESTAPP_STARTED'] = '1' sys.stdout.flush() autoreload._reload() """ class AutoreloadTest(unittest.TestCase): def test_reload_module(self): # Create temporary test application path = mkdtemp() os.mkdir(os.path.join(path, 'testapp')) open(os.path.join(path, 'testapp/__init__.py'), 'w').close() with open(os.path.join(path, 'testapp/__main__.py'), 'w') as f: f.write(MAIN) # Make sure the tornado module under test is available to the test # application pythonpath = os.getcwd() if 'PYTHONPATH' in os.environ: pythonpath += os.pathsep + os.environ['PYTHONPATH'] p = Popen( [sys.executable, '-m', 'testapp'], stdout=subprocess.PIPE, cwd=path, env=dict(os.environ, PYTHONPATH=pythonpath), universal_newlines=True) out = p.communicate()[0] self.assertEqual(out, 'Starting\nStarting\n')
Fix newline handling in autoreload test
Fix newline handling in autoreload test
Python
apache-2.0
SuminAndrew/tornado,mivade/tornado,legnaleurc/tornado,tornadoweb/tornado,ifduyue/tornado,bdarnell/tornado,NoyaInRain/tornado,bdarnell/tornado,ajdavis/tornado,NoyaInRain/tornado,bdarnell/tornado,eklitzke/tornado,wujuguang/tornado,allenl203/tornado,SuminAndrew/tornado,Lancher/tornado,Lancher/tornado,NoyaInRain/tornado,NoyaInRain/tornado,lilydjwg/tornado,allenl203/tornado,ajdavis/tornado,lilydjwg/tornado,hhru/tornado,SuminAndrew/tornado,ajdavis/tornado,wujuguang/tornado,wujuguang/tornado,dongpinglai/my_tornado,SuminAndrew/tornado,NoyaInRain/tornado,lilydjwg/tornado,allenl203/tornado,Lancher/tornado,mivade/tornado,dongpinglai/my_tornado,eklitzke/tornado,legnaleurc/tornado,hhru/tornado,wujuguang/tornado,bdarnell/tornado,mivade/tornado,dongpinglai/my_tornado,ifduyue/tornado,NoyaInRain/tornado,allenl203/tornado,mivade/tornado,hhru/tornado,dongpinglai/my_tornado,hhru/tornado,tornadoweb/tornado,ifduyue/tornado,mivade/tornado,lilydjwg/tornado,Lancher/tornado,dongpinglai/my_tornado,bdarnell/tornado,ifduyue/tornado,eklitzke/tornado,Lancher/tornado,allenl203/tornado,tornadoweb/tornado,eklitzke/tornado,ajdavis/tornado,ajdavis/tornado,tornadoweb/tornado,legnaleurc/tornado,legnaleurc/tornado,SuminAndrew/tornado,ifduyue/tornado,legnaleurc/tornado,hhru/tornado,eklitzke/tornado,wujuguang/tornado,dongpinglai/my_tornado
python
## Code Before: from __future__ import absolute_import, division, print_function import os import subprocess from subprocess import Popen import sys from tempfile import mkdtemp from tornado.test.util import unittest MAIN = """\ import os import sys from tornado import autoreload # This import will fail if path is not set up correctly import testapp print('Starting') if 'TESTAPP_STARTED' not in os.environ: os.environ['TESTAPP_STARTED'] = '1' sys.stdout.flush() autoreload._reload() """ class AutoreloadTest(unittest.TestCase): def test_reload_module(self): # Create temporary test application path = mkdtemp() os.mkdir(os.path.join(path, 'testapp')) open(os.path.join(path, 'testapp/__init__.py'), 'w').close() with open(os.path.join(path, 'testapp/__main__.py'), 'w') as f: f.write(MAIN) # Make sure the tornado module under test is available to the test # application pythonpath = os.getcwd() if 'PYTHONPATH' in os.environ: pythonpath += os.pathsep + os.environ['PYTHONPATH'] p = Popen([sys.executable, '-m', 'testapp'], stdout=subprocess.PIPE, cwd=path, env=dict(os.environ, PYTHONPATH=pythonpath)) out = p.communicate()[0].decode() self.assertEqual(out, 'Starting\nStarting\n') ## Instruction: Fix newline handling in autoreload test ## Code After: from __future__ import absolute_import, division, print_function import os import subprocess from subprocess import Popen import sys from tempfile import mkdtemp from tornado.test.util import unittest MAIN = """\ import os import sys from tornado import autoreload # This import will fail if path is not set up correctly import testapp print('Starting') if 'TESTAPP_STARTED' not in os.environ: os.environ['TESTAPP_STARTED'] = '1' sys.stdout.flush() autoreload._reload() """ class AutoreloadTest(unittest.TestCase): def test_reload_module(self): # Create temporary test application path = mkdtemp() os.mkdir(os.path.join(path, 'testapp')) open(os.path.join(path, 'testapp/__init__.py'), 'w').close() with open(os.path.join(path, 'testapp/__main__.py'), 'w') as f: f.write(MAIN) # Make sure the tornado module under test is available to the test # application pythonpath = os.getcwd() if 'PYTHONPATH' in os.environ: pythonpath += os.pathsep + os.environ['PYTHONPATH'] p = Popen( [sys.executable, '-m', 'testapp'], stdout=subprocess.PIPE, cwd=path, env=dict(os.environ, PYTHONPATH=pythonpath), universal_newlines=True) out = p.communicate()[0] self.assertEqual(out, 'Starting\nStarting\n')
// ... existing code ... if 'PYTHONPATH' in os.environ: pythonpath += os.pathsep + os.environ['PYTHONPATH'] p = Popen( [sys.executable, '-m', 'testapp'], stdout=subprocess.PIPE, cwd=path, env=dict(os.environ, PYTHONPATH=pythonpath), universal_newlines=True) out = p.communicate()[0] self.assertEqual(out, 'Starting\nStarting\n') // ... rest of the code ...
d3caf80485da78c8eb050ff4d9e33a2ee6c8feda
tests/rietveld/test_event_handler.py
tests/rietveld/test_event_handler.py
from __future__ import absolute_import, print_function import unittest from qtpy.QtWidgets import QApplication from addie.rietveld import event_handler class RietveldEventHandlerTests(unittest.TestCase): def setUp(self): self.main_window = QApplication([]) ''' def tearDown(self): self.main_window.quit() ''' def test_evt_change_gss_mode_exception(self): """Test we can extract a bank id from bank workspace name""" f = event_handler.evt_change_gss_mode self.assertRaises(NotImplementedError, f, None) if __name__ == '__main__': unittest.main() # pragma: no cover
from __future__ import absolute_import, print_function import pytest from addie.rietveld import event_handler @pytest.fixture def rietveld_event_handler(qtbot): return event_handler def test_evt_change_gss_mode_exception(qtbot, rietveld_event_handler): """Test we can extract a bank id from bank workspace name""" with pytest.raises(NotImplementedError) as e: rietveld_event_handler.evt_change_gss_mode(None)
Refactor rietveld.event_handler test to use pytest-qt
Refactor rietveld.event_handler test to use pytest-qt
Python
mit
neutrons/FastGR,neutrons/FastGR,neutrons/FastGR
python
## Code Before: from __future__ import absolute_import, print_function import unittest from qtpy.QtWidgets import QApplication from addie.rietveld import event_handler class RietveldEventHandlerTests(unittest.TestCase): def setUp(self): self.main_window = QApplication([]) ''' def tearDown(self): self.main_window.quit() ''' def test_evt_change_gss_mode_exception(self): """Test we can extract a bank id from bank workspace name""" f = event_handler.evt_change_gss_mode self.assertRaises(NotImplementedError, f, None) if __name__ == '__main__': unittest.main() # pragma: no cover ## Instruction: Refactor rietveld.event_handler test to use pytest-qt ## Code After: from __future__ import absolute_import, print_function import pytest from addie.rietveld import event_handler @pytest.fixture def rietveld_event_handler(qtbot): return event_handler def test_evt_change_gss_mode_exception(qtbot, rietveld_event_handler): """Test we can extract a bank id from bank workspace name""" with pytest.raises(NotImplementedError) as e: rietveld_event_handler.evt_change_gss_mode(None)
... from __future__ import absolute_import, print_function import pytest from addie.rietveld import event_handler @pytest.fixture def rietveld_event_handler(qtbot): return event_handler def test_evt_change_gss_mode_exception(qtbot, rietveld_event_handler): """Test we can extract a bank id from bank workspace name""" with pytest.raises(NotImplementedError) as e: rietveld_event_handler.evt_change_gss_mode(None) ...
131f0d3a67bc6ba995d1f45dd8c85594d8d8e79c
tests/run_tests.py
tests/run_tests.py
"""Python script to run all tests""" import pytest if __name__ == '__main__': pytest.main()
"""Python script to run all tests""" import sys import pytest if __name__ == '__main__': sys.exit(pytest.main())
Allow Jenkins to actually report build failures
Allow Jenkins to actually report build failures
Python
mit
gatkin/declxml
python
## Code Before: """Python script to run all tests""" import pytest if __name__ == '__main__': pytest.main() ## Instruction: Allow Jenkins to actually report build failures ## Code After: """Python script to run all tests""" import sys import pytest if __name__ == '__main__': sys.exit(pytest.main())
... """Python script to run all tests""" import sys import pytest if __name__ == '__main__': sys.exit(pytest.main()) ...
fa212a2628fc06b21b04d00723916d0fe68ceb93
src/main/java/jwbroek/id3/v2/ITunesPodcastFrameReader.java
src/main/java/jwbroek/id3/v2/ITunesPodcastFrameReader.java
/* * Created on Aug 31, 2009 */ package jwbroek.id3.v2; import java.io.IOException; import java.io.InputStream; import jwbroek.id3.ITunesPodcastFrame; public class ITunesPodcastFrameReader implements FrameReader { private final int headerSize; public ITunesPodcastFrameReader(final int headerSize) { this.headerSize = headerSize; } public ITunesPodcastFrame readFrameBody(final int size, final InputStream input) throws IOException, UnsupportedEncodingException, MalformedFrameException { final ITunesPodcastFrame result = new ITunesPodcastFrame(this.headerSize + size); final StringBuilder payloadBuilder = new StringBuilder(); for (int index = 0; index < 4; index++) { payloadBuilder.append(Integer.toHexString(input.read())); } result.setPayload(payloadBuilder.toString()); return result; } }
/* * Created on Aug 31, 2009 */ package jwbroek.id3.v2; import jwbroek.id3.ITunesPodcastFrame; import java.io.IOException; import java.io.InputStream; public class ITunesPodcastFrameReader implements FrameReader { private final int headerSize; public ITunesPodcastFrameReader(final int headerSize) { this.headerSize = headerSize; } public ITunesPodcastFrame readFrameBody(final int size, final InputStream input) throws IOException, UnsupportedEncodingException, MalformedFrameException { final ITunesPodcastFrame result = new ITunesPodcastFrame(this.headerSize + size); final StringBuilder payloadBuilder = new StringBuilder(); for (int index = 0; index < 4; index++) { payloadBuilder.append(Integer.toHexString(input.read())); } result.setPayload(payloadBuilder.toString()); return result; } }
Reformat code, remove hardcoded path.
Reformat code, remove hardcoded path.
Java
lgpl-2.1
RomanHargrave/cuelib
java
## Code Before: /* * Created on Aug 31, 2009 */ package jwbroek.id3.v2; import java.io.IOException; import java.io.InputStream; import jwbroek.id3.ITunesPodcastFrame; public class ITunesPodcastFrameReader implements FrameReader { private final int headerSize; public ITunesPodcastFrameReader(final int headerSize) { this.headerSize = headerSize; } public ITunesPodcastFrame readFrameBody(final int size, final InputStream input) throws IOException, UnsupportedEncodingException, MalformedFrameException { final ITunesPodcastFrame result = new ITunesPodcastFrame(this.headerSize + size); final StringBuilder payloadBuilder = new StringBuilder(); for (int index = 0; index < 4; index++) { payloadBuilder.append(Integer.toHexString(input.read())); } result.setPayload(payloadBuilder.toString()); return result; } } ## Instruction: Reformat code, remove hardcoded path. ## Code After: /* * Created on Aug 31, 2009 */ package jwbroek.id3.v2; import jwbroek.id3.ITunesPodcastFrame; import java.io.IOException; import java.io.InputStream; public class ITunesPodcastFrameReader implements FrameReader { private final int headerSize; public ITunesPodcastFrameReader(final int headerSize) { this.headerSize = headerSize; } public ITunesPodcastFrame readFrameBody(final int size, final InputStream input) throws IOException, UnsupportedEncodingException, MalformedFrameException { final ITunesPodcastFrame result = new ITunesPodcastFrame(this.headerSize + size); final StringBuilder payloadBuilder = new StringBuilder(); for (int index = 0; index < 4; index++) { payloadBuilder.append(Integer.toHexString(input.read())); } result.setPayload(payloadBuilder.toString()); return result; } }
... */ package jwbroek.id3.v2; import jwbroek.id3.ITunesPodcastFrame; import java.io.IOException; import java.io.InputStream; public class ITunesPodcastFrameReader implements FrameReader { private final int headerSize; public ITunesPodcastFrameReader(final int headerSize) { this.headerSize = headerSize; } public ITunesPodcastFrame readFrameBody(final int size, final InputStream input) throws IOException, UnsupportedEncodingException, MalformedFrameException { final ITunesPodcastFrame result = new ITunesPodcastFrame(this.headerSize + size); final StringBuilder payloadBuilder = new StringBuilder(); for (int index = 0; index < 4; index++) { payloadBuilder.append(Integer.toHexString(input.read())); } result.setPayload(payloadBuilder.toString()); return result; } } ...
892c39d588e9a16609b67177e912ac1564317838
libk/UVSE/screenTest.c
libk/UVSE/screenTest.c
void screenTest(void) { int rows, cols; rows = glob.rows; cols = glob.cols; printf("%s", CursorToTopLeft ClearScreen );fflush(stdout); printf("Top of Screen: rows = %d cols = %d\n\r", rows,cols);fflush(stdout); int count; for (count = 2; count < rows; count ++) {printf("%s", TildeReturnNewline); fflush(stdout);} printf("%s","Bottom of Screen "); fflush(stdout); // Force Cursor Position with <ESC>[{ROW};{COLUMN}f printf ("\x1b[%d;%df%s", 5,5,"Hello World"); fflush(stdout); // printf("\x1b[%d;%df",2,1); fflush(stdout); return; }
// function screenTest void screenTest(void) { // retrieve Screen rows and columns from struct glob int rows, cols; rows = glob.rows; cols = glob.cols; // Move Screen Cursor to Top Left, Then Clear Screen printf("%s", CursorToTopLeft ClearScreen );fflush(stdout); // Print the Screen Header printf("Top of Screen: rows = %d cols = %d\n\r", rows,cols);fflush(stdout); int count; // Print Left Column Tildes to Screen, leaving screen last line clear for (count = 2; count < rows; count ++) {printf("%s", TildeReturnNewline); fflush(stdout);} // Prnt Screen Last Line printf("%s","Bottom of Screen "); fflush(stdout); // Place Cursor Position with <ESC>[{ROW};{COLUMN}f printf ("\x1b[%d;%df%s", 5,5,"Hello World"); fflush(stdout); // Move Screen Cursor to Second Line, First Column printf("\x1b[%d;%df",2,1); fflush(stdout); return; }
Add comments suit for formatting with idiom
Add comments suit for formatting with idiom
C
bsd-2-clause
eingaeph/pip.imbue.hood,eingaeph/pip.imbue.hood
c
## Code Before: void screenTest(void) { int rows, cols; rows = glob.rows; cols = glob.cols; printf("%s", CursorToTopLeft ClearScreen );fflush(stdout); printf("Top of Screen: rows = %d cols = %d\n\r", rows,cols);fflush(stdout); int count; for (count = 2; count < rows; count ++) {printf("%s", TildeReturnNewline); fflush(stdout);} printf("%s","Bottom of Screen "); fflush(stdout); // Force Cursor Position with <ESC>[{ROW};{COLUMN}f printf ("\x1b[%d;%df%s", 5,5,"Hello World"); fflush(stdout); // printf("\x1b[%d;%df",2,1); fflush(stdout); return; } ## Instruction: Add comments suit for formatting with idiom ## Code After: // function screenTest void screenTest(void) { // retrieve Screen rows and columns from struct glob int rows, cols; rows = glob.rows; cols = glob.cols; // Move Screen Cursor to Top Left, Then Clear Screen printf("%s", CursorToTopLeft ClearScreen );fflush(stdout); // Print the Screen Header printf("Top of Screen: rows = %d cols = %d\n\r", rows,cols);fflush(stdout); int count; // Print Left Column Tildes to Screen, leaving screen last line clear for (count = 2; count < rows; count ++) {printf("%s", TildeReturnNewline); fflush(stdout);} // Prnt Screen Last Line printf("%s","Bottom of Screen "); fflush(stdout); // Place Cursor Position with <ESC>[{ROW};{COLUMN}f printf ("\x1b[%d;%df%s", 5,5,"Hello World"); fflush(stdout); // Move Screen Cursor to Second Line, First Column printf("\x1b[%d;%df",2,1); fflush(stdout); return; }
// ... existing code ... // function screenTest void screenTest(void) { // retrieve Screen rows and columns from struct glob int rows, cols; rows = glob.rows; cols = glob.cols; // Move Screen Cursor to Top Left, Then Clear Screen printf("%s", CursorToTopLeft ClearScreen );fflush(stdout); // Print the Screen Header printf("Top of Screen: rows = %d cols = %d\n\r", rows,cols);fflush(stdout); int count; // Print Left Column Tildes to Screen, leaving screen last line clear for (count = 2; count < rows; count ++) {printf("%s", TildeReturnNewline); fflush(stdout);} // Prnt Screen Last Line printf("%s","Bottom of Screen "); fflush(stdout); // Place Cursor Position with <ESC>[{ROW};{COLUMN}f printf ("\x1b[%d;%df%s", 5,5,"Hello World"); fflush(stdout); // Move Screen Cursor to Second Line, First Column printf("\x1b[%d;%df",2,1); fflush(stdout); return; // ... rest of the code ...
80737e5de2ca3f0f039c9d4fbbf3df4ac8b59193
run.py
run.py
import twitter_rss import time import subprocess import config # Launch web server p = subprocess.Popen(['/usr/bin/python2', config.INSTALL_DIR + 'server.py']) # Update the feeds try: while 1: print 'Updating ALL THE FEEDS!' try: with open(config.XML_DIR + 'user/user.txt', 'r') as usernames: for user in usernames: twitter_rss.UserTweetGetter(user) usernames.close() with open(config.XML_DIR + 'htag/htag.txt', 'r') as hashtags: for htag in hashtags: twitter_rss.HashtagTweetGetter(user) hashtags.close() except IOError: print 'File could not be read' time.sleep(config.TIMER) except (KeyboardInterrupt, SystemExit): p.kill() # kill the subprocess print '\nKeyboardInterrupt catched -- Finishing program.'
import twitter_rss import time import subprocess import config import sys # Launch web server p = subprocess.Popen([sys.executable, config.INSTALL_DIR + 'server.py']) # Update the feeds try: while 1: print 'Updating ALL THE FEEDS!' try: with open(config.XML_DIR + 'user/user.txt', 'r') as usernames: for user in usernames: twitter_rss.UserTweetGetter(user) usernames.close() with open(config.XML_DIR + 'htag/htag.txt', 'r') as hashtags: for htag in hashtags: twitter_rss.HashtagTweetGetter(user) hashtags.close() except IOError: print 'File could not be read' time.sleep(config.TIMER) except (KeyboardInterrupt, SystemExit): p.kill() # kill the subprocess print '\nKeyboardInterrupt catched -- Finishing program.'
Use sys.executable instead of harcoded python path
Use sys.executable instead of harcoded python path Fixes issue when running in a virtualenv and in non-standard python installations.
Python
mit
Astalaseven/twitter-rss,Astalaseven/twitter-rss
python
## Code Before: import twitter_rss import time import subprocess import config # Launch web server p = subprocess.Popen(['/usr/bin/python2', config.INSTALL_DIR + 'server.py']) # Update the feeds try: while 1: print 'Updating ALL THE FEEDS!' try: with open(config.XML_DIR + 'user/user.txt', 'r') as usernames: for user in usernames: twitter_rss.UserTweetGetter(user) usernames.close() with open(config.XML_DIR + 'htag/htag.txt', 'r') as hashtags: for htag in hashtags: twitter_rss.HashtagTweetGetter(user) hashtags.close() except IOError: print 'File could not be read' time.sleep(config.TIMER) except (KeyboardInterrupt, SystemExit): p.kill() # kill the subprocess print '\nKeyboardInterrupt catched -- Finishing program.' ## Instruction: Use sys.executable instead of harcoded python path Fixes issue when running in a virtualenv and in non-standard python installations. ## Code After: import twitter_rss import time import subprocess import config import sys # Launch web server p = subprocess.Popen([sys.executable, config.INSTALL_DIR + 'server.py']) # Update the feeds try: while 1: print 'Updating ALL THE FEEDS!' try: with open(config.XML_DIR + 'user/user.txt', 'r') as usernames: for user in usernames: twitter_rss.UserTweetGetter(user) usernames.close() with open(config.XML_DIR + 'htag/htag.txt', 'r') as hashtags: for htag in hashtags: twitter_rss.HashtagTweetGetter(user) hashtags.close() except IOError: print 'File could not be read' time.sleep(config.TIMER) except (KeyboardInterrupt, SystemExit): p.kill() # kill the subprocess print '\nKeyboardInterrupt catched -- Finishing program.'
// ... existing code ... import time import subprocess import config import sys # Launch web server p = subprocess.Popen([sys.executable, config.INSTALL_DIR + 'server.py']) # Update the feeds try: // ... rest of the code ...
2b74c8714b659ccf5faa615e9b5c4c4559f8d9c8
artbot_website/views.py
artbot_website/views.py
from django.shortcuts import render from datetime import date, datetime, timedelta from .models import Event def index(request): if date.today().isoweekday() in [5,6,7]: weekend_start = date.today() else: weekend_start = date.today() + timedelta((5 - date.today().isoweekday()) % 7 ) events = Event.objects.filter(start__lte = weekend_start, end__gte = weekend_start).order_by('-start') return render(request, 'index.html', {'events': events})
from django.shortcuts import render from datetime import date, datetime, timedelta from .models import Event def index(request): if date.today().isoweekday() in [5,6,7]: weekend_start = date.today() else: weekend_start = date.today() + timedelta((5 - date.today().isoweekday()) % 7 ) events = Event.objects.filter(start__lte = weekend_start, end__gte = weekend_start, published = True).order_by('-start') return render(request, 'index.html', {'events': events})
Index now only displays published articles.
Index now only displays published articles.
Python
mit
coreymcdermott/artbot,coreymcdermott/artbot
python
## Code Before: from django.shortcuts import render from datetime import date, datetime, timedelta from .models import Event def index(request): if date.today().isoweekday() in [5,6,7]: weekend_start = date.today() else: weekend_start = date.today() + timedelta((5 - date.today().isoweekday()) % 7 ) events = Event.objects.filter(start__lte = weekend_start, end__gte = weekend_start).order_by('-start') return render(request, 'index.html', {'events': events}) ## Instruction: Index now only displays published articles. ## Code After: from django.shortcuts import render from datetime import date, datetime, timedelta from .models import Event def index(request): if date.today().isoweekday() in [5,6,7]: weekend_start = date.today() else: weekend_start = date.today() + timedelta((5 - date.today().isoweekday()) % 7 ) events = Event.objects.filter(start__lte = weekend_start, end__gte = weekend_start, published = True).order_by('-start') return render(request, 'index.html', {'events': events})
// ... existing code ... else: weekend_start = date.today() + timedelta((5 - date.today().isoweekday()) % 7 ) events = Event.objects.filter(start__lte = weekend_start, end__gte = weekend_start, published = True).order_by('-start') return render(request, 'index.html', {'events': events}) // ... rest of the code ...
8d24a632dde955a9e4e093fe8764bc598cf65f4c
dynamic_subdomains/defaults.py
dynamic_subdomains/defaults.py
from django.core.exceptions import ImproperlyConfigured from django.utils.datastructures import SortedDict def patterns(*args): subdomains = SortedDict() for x in args: name = x['name'] if name in subdomains: raise ImproperlyConfigured("Duplicate subdomain name: %s" % name) if name == 'default': raise ImproperlyConfigured("Reserved subdomain name: %s" % name) subdomains[name] = x return subdomains class subdomain(dict): def __init__(self, regex, urlconf, name, callback=None): self.update({ 'regex': regex, 'urlconf': urlconf, 'name': name, }) if callback: self['callback'] = callback
from django.core.exceptions import ImproperlyConfigured from django.utils.datastructures import SortedDict def patterns(*args): subdomains = SortedDict() for x in args: name = x['name'] if name in subdomains: raise ImproperlyConfigured("Duplicate subdomain name: %s" % name) subdomains[name] = x return subdomains class subdomain(dict): def __init__(self, regex, urlconf, name, callback=None): self.update({ 'regex': regex, 'urlconf': urlconf, 'name': name, }) if callback: self['callback'] = callback
Remove unnecessary protection against using "default" as a subdomainconf
Remove unnecessary protection against using "default" as a subdomainconf Thanks to Jannis Leidel <[email protected]> for the pointer. Signed-off-by: Chris Lamb <[email protected]>
Python
bsd-3-clause
playfire/django-dynamic-subdomains
python
## Code Before: from django.core.exceptions import ImproperlyConfigured from django.utils.datastructures import SortedDict def patterns(*args): subdomains = SortedDict() for x in args: name = x['name'] if name in subdomains: raise ImproperlyConfigured("Duplicate subdomain name: %s" % name) if name == 'default': raise ImproperlyConfigured("Reserved subdomain name: %s" % name) subdomains[name] = x return subdomains class subdomain(dict): def __init__(self, regex, urlconf, name, callback=None): self.update({ 'regex': regex, 'urlconf': urlconf, 'name': name, }) if callback: self['callback'] = callback ## Instruction: Remove unnecessary protection against using "default" as a subdomainconf Thanks to Jannis Leidel <[email protected]> for the pointer. Signed-off-by: Chris Lamb <[email protected]> ## Code After: from django.core.exceptions import ImproperlyConfigured from django.utils.datastructures import SortedDict def patterns(*args): subdomains = SortedDict() for x in args: name = x['name'] if name in subdomains: raise ImproperlyConfigured("Duplicate subdomain name: %s" % name) subdomains[name] = x return subdomains class subdomain(dict): def __init__(self, regex, urlconf, name, callback=None): self.update({ 'regex': regex, 'urlconf': urlconf, 'name': name, }) if callback: self['callback'] = callback
# ... existing code ... if name in subdomains: raise ImproperlyConfigured("Duplicate subdomain name: %s" % name) subdomains[name] = x # ... rest of the code ...
aed959a0593558b6063e70c3b594feb6caa4bdda
tests/runner/compose/init_test.py
tests/runner/compose/init_test.py
import os import tempfile import shutil from unittest import TestCase import yaml from dusty import constants from dusty.runner.compose import _write_composefile class TestComposeRunner(TestCase): def setUp(self): self.temp_compose_dir = tempfile.mkdtemp() self.temp_compose_path = os.path.join(self.temp_compose_dir, 'docker-compose.yml') self.old_compose_dir = constants.COMPOSE_DIR constants.COMPOSE_DIR = self.temp_compose_dir self.test_spec = {'app-a': {'image': 'app/a'}} def tearDown(self): constants.COMPOSE_DIR = self.old_compose_dir shutil.rmtree(self.temp_compose_dir) def test_write_composefile(self): _write_composefile(self.test_spec) written = open(self.temp_compose_path, 'r').read() self.assertItemsEqual(yaml.load(written), self.test_spec)
import os import tempfile import shutil from unittest import TestCase from mock import patch import yaml from dusty import constants from dusty.runner.compose import _write_composefile, _get_docker_env class TestComposeRunner(TestCase): def setUp(self): self.temp_compose_dir = tempfile.mkdtemp() self.temp_compose_path = os.path.join(self.temp_compose_dir, 'docker-compose.yml') self.old_compose_dir = constants.COMPOSE_DIR constants.COMPOSE_DIR = self.temp_compose_dir self.test_spec = {'app-a': {'image': 'app/a'}} def tearDown(self): constants.COMPOSE_DIR = self.old_compose_dir shutil.rmtree(self.temp_compose_dir) def test_write_composefile(self): _write_composefile(self.test_spec) written = open(self.temp_compose_path, 'r').read() self.assertItemsEqual(yaml.load(written), self.test_spec) @patch('dusty.runner.compose._check_output_demoted') def test_get_docker_env(self, fake_check_output): fake_check_output.return_value = """ export DOCKER_TLS_VERIFY=1 export DOCKER_HOST=tcp://192.168.59.103:2376 export DOCKER_CERT_PATH=/Users/root/.boot2docker/certs/boot2docker-vm""" expected = {'DOCKER_TLS_VERIFY': '1', 'DOCKER_HOST': 'tcp://192.168.59.103:2376', 'DOCKER_CERT_PATH': '/Users/root/.boot2docker/certs/boot2docker-vm'} result = _get_docker_env() self.assertItemsEqual(result, expected)
Add a test for _get_docker_env
Add a test for _get_docker_env
Python
mit
gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty
python
## Code Before: import os import tempfile import shutil from unittest import TestCase import yaml from dusty import constants from dusty.runner.compose import _write_composefile class TestComposeRunner(TestCase): def setUp(self): self.temp_compose_dir = tempfile.mkdtemp() self.temp_compose_path = os.path.join(self.temp_compose_dir, 'docker-compose.yml') self.old_compose_dir = constants.COMPOSE_DIR constants.COMPOSE_DIR = self.temp_compose_dir self.test_spec = {'app-a': {'image': 'app/a'}} def tearDown(self): constants.COMPOSE_DIR = self.old_compose_dir shutil.rmtree(self.temp_compose_dir) def test_write_composefile(self): _write_composefile(self.test_spec) written = open(self.temp_compose_path, 'r').read() self.assertItemsEqual(yaml.load(written), self.test_spec) ## Instruction: Add a test for _get_docker_env ## Code After: import os import tempfile import shutil from unittest import TestCase from mock import patch import yaml from dusty import constants from dusty.runner.compose import _write_composefile, _get_docker_env class TestComposeRunner(TestCase): def setUp(self): self.temp_compose_dir = tempfile.mkdtemp() self.temp_compose_path = os.path.join(self.temp_compose_dir, 'docker-compose.yml') self.old_compose_dir = constants.COMPOSE_DIR constants.COMPOSE_DIR = self.temp_compose_dir self.test_spec = {'app-a': {'image': 'app/a'}} def tearDown(self): constants.COMPOSE_DIR = self.old_compose_dir shutil.rmtree(self.temp_compose_dir) def test_write_composefile(self): _write_composefile(self.test_spec) written = open(self.temp_compose_path, 'r').read() self.assertItemsEqual(yaml.load(written), self.test_spec) @patch('dusty.runner.compose._check_output_demoted') def test_get_docker_env(self, fake_check_output): fake_check_output.return_value = """ export DOCKER_TLS_VERIFY=1 export DOCKER_HOST=tcp://192.168.59.103:2376 export DOCKER_CERT_PATH=/Users/root/.boot2docker/certs/boot2docker-vm""" expected = {'DOCKER_TLS_VERIFY': '1', 'DOCKER_HOST': 'tcp://192.168.59.103:2376', 'DOCKER_CERT_PATH': '/Users/root/.boot2docker/certs/boot2docker-vm'} result = _get_docker_env() self.assertItemsEqual(result, expected)
... import shutil from unittest import TestCase from mock import patch import yaml from dusty import constants from dusty.runner.compose import _write_composefile, _get_docker_env class TestComposeRunner(TestCase): def setUp(self): ... _write_composefile(self.test_spec) written = open(self.temp_compose_path, 'r').read() self.assertItemsEqual(yaml.load(written), self.test_spec) @patch('dusty.runner.compose._check_output_demoted') def test_get_docker_env(self, fake_check_output): fake_check_output.return_value = """ export DOCKER_TLS_VERIFY=1 export DOCKER_HOST=tcp://192.168.59.103:2376 export DOCKER_CERT_PATH=/Users/root/.boot2docker/certs/boot2docker-vm""" expected = {'DOCKER_TLS_VERIFY': '1', 'DOCKER_HOST': 'tcp://192.168.59.103:2376', 'DOCKER_CERT_PATH': '/Users/root/.boot2docker/certs/boot2docker-vm'} result = _get_docker_env() self.assertItemsEqual(result, expected) ...
4d01eb0c1b11680d463d4fcb0888fac4ab6c45c8
panoptes/utils/data.py
panoptes/utils/data.py
import os import argparse from astropy.utils import data from astroplan import download_IERS_A def download_all_files(data_folder="{}/astrometry/data".format(os.getenv('PANDIR'))): download_IERS_A() for i in range(4214, 4219): fn = 'index-{}.fits'.format(i) dest = "{}/{}".format(data_folder, fn) if not os.path.exists(dest): url = "http://data.astrometry.net/4200/{}".format(fn) df = data.download_file(url) try: os.rename(df, dest) except OSError as e: print("Problem saving. (Maybe permissions?): {}".format(e)) if __name__ == '__main__': parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--folder', help='Folder to place astrometry data') args = parser.parse_args() if not os.path.exists(args.folder): print("{} does not exist.".format(args.folder)) download_all_files(data_folder=args.folder)
import os import shutil import argparse from astropy.utils import data from astroplan import download_IERS_A def download_all_files(data_folder="{}/astrometry/data".format(os.getenv('PANDIR'))): download_IERS_A() for i in range(4214, 4219): fn = 'index-{}.fits'.format(i) dest = "{}/{}".format(data_folder, fn) if not os.path.exists(dest): url = "http://data.astrometry.net/4200/{}".format(fn) df = data.download_file(url) try: shutil.move(df, dest) except OSError as e: print("Problem saving. (Maybe permissions?): {}".format(e)) if __name__ == '__main__': parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--folder', help='Folder to place astrometry data') args = parser.parse_args() if not os.path.exists(args.folder): print("{} does not exist.".format(args.folder)) download_all_files(data_folder=args.folder)
Use shutil instead of `os.rename`
Use shutil instead of `os.rename`
Python
mit
panoptes/POCS,AstroHuntsman/POCS,joshwalawender/POCS,AstroHuntsman/POCS,joshwalawender/POCS,AstroHuntsman/POCS,panoptes/POCS,AstroHuntsman/POCS,panoptes/POCS,joshwalawender/POCS,panoptes/POCS
python
## Code Before: import os import argparse from astropy.utils import data from astroplan import download_IERS_A def download_all_files(data_folder="{}/astrometry/data".format(os.getenv('PANDIR'))): download_IERS_A() for i in range(4214, 4219): fn = 'index-{}.fits'.format(i) dest = "{}/{}".format(data_folder, fn) if not os.path.exists(dest): url = "http://data.astrometry.net/4200/{}".format(fn) df = data.download_file(url) try: os.rename(df, dest) except OSError as e: print("Problem saving. (Maybe permissions?): {}".format(e)) if __name__ == '__main__': parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--folder', help='Folder to place astrometry data') args = parser.parse_args() if not os.path.exists(args.folder): print("{} does not exist.".format(args.folder)) download_all_files(data_folder=args.folder) ## Instruction: Use shutil instead of `os.rename` ## Code After: import os import shutil import argparse from astropy.utils import data from astroplan import download_IERS_A def download_all_files(data_folder="{}/astrometry/data".format(os.getenv('PANDIR'))): download_IERS_A() for i in range(4214, 4219): fn = 'index-{}.fits'.format(i) dest = "{}/{}".format(data_folder, fn) if not os.path.exists(dest): url = "http://data.astrometry.net/4200/{}".format(fn) df = data.download_file(url) try: shutil.move(df, dest) except OSError as e: print("Problem saving. (Maybe permissions?): {}".format(e)) if __name__ == '__main__': parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--folder', help='Folder to place astrometry data') args = parser.parse_args() if not os.path.exists(args.folder): print("{} does not exist.".format(args.folder)) download_all_files(data_folder=args.folder)
# ... existing code ... import os import shutil import argparse from astropy.utils import data from astroplan import download_IERS_A # ... modified code ... url = "http://data.astrometry.net/4200/{}".format(fn) df = data.download_file(url) try: shutil.move(df, dest) except OSError as e: print("Problem saving. (Maybe permissions?): {}".format(e)) # ... rest of the code ...
03c7cd2cae064652a8b322f207e2b0a9d2001ffc
src/main/java/graphql/GraphQLException.java
src/main/java/graphql/GraphQLException.java
package graphql; public class GraphQLException extends RuntimeException { public GraphQLException() { } public GraphQLException(String message) { super(message); } public GraphQLException(String message, Throwable cause) { super(message, cause); } public GraphQLException(Throwable cause) { super(cause); } }
package graphql; public class GraphQLException extends RuntimeException { public GraphQLException() { } public GraphQLException(String message) { super(message); } public GraphQLException(String message, Throwable cause) { super(message, cause); } public GraphQLException(Throwable cause) { super(cause); } @Override public String toString() { return getMessage(); } }
Make graphql exception tostring be the message
Make graphql exception tostring be the message
Java
mit
graphql-java/graphql-java,graphql-java/graphql-java
java
## Code Before: package graphql; public class GraphQLException extends RuntimeException { public GraphQLException() { } public GraphQLException(String message) { super(message); } public GraphQLException(String message, Throwable cause) { super(message, cause); } public GraphQLException(Throwable cause) { super(cause); } } ## Instruction: Make graphql exception tostring be the message ## Code After: package graphql; public class GraphQLException extends RuntimeException { public GraphQLException() { } public GraphQLException(String message) { super(message); } public GraphQLException(String message, Throwable cause) { super(message, cause); } public GraphQLException(Throwable cause) { super(cause); } @Override public String toString() { return getMessage(); } }
... super(cause); } @Override public String toString() { return getMessage(); } } ...
232212c0f0a3b1fbcc09dd0d017caa6abcd8a9ea
platform/platform-impl/src/com/intellij/remote/RemoteConnectionType.java
platform/platform-impl/src/com/intellij/remote/RemoteConnectionType.java
package com.intellij.remote; import com.intellij.openapi.diagnostic.Logger; /** * This class denotes the type of the source to obtain remote credentials. * * @author traff */ public enum RemoteConnectionType { /** * Currently selected SDK (e.g. <Project default>) */ DEFAULT_SDK, /** * Web deployment server */ DEPLOYMENT_SERVER, /** * Remote SDK */ REMOTE_SDK, /** * Current project vagrant */ CURRENT_VAGRANT, /** * No source is predefined - it would be asked on request */ NONE; private static final Logger LOG = Logger.getInstance(RemoteConnectionType.class); public static RemoteConnectionType findByName(String name) { try { return valueOf(name); } catch (Exception e) { LOG.error("Cant find RemoteConnectionType with the name " + name, e); return NONE; } } }
package com.intellij.remote; import com.intellij.openapi.diagnostic.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * This class denotes the type of the source to obtain remote credentials. * * @author traff */ public enum RemoteConnectionType { /** * Currently selected SDK (e.g. <Project default>) */ DEFAULT_SDK, /** * Web deployment server */ DEPLOYMENT_SERVER, /** * Remote SDK */ REMOTE_SDK, /** * Current project vagrant */ CURRENT_VAGRANT, /** * No source is predefined - it would be asked on request */ NONE; private static final Logger LOG = Logger.getInstance(RemoteConnectionType.class); @NotNull public static RemoteConnectionType findByName(@Nullable String name) { if (name == null) { return NONE; } try { return valueOf(name); } catch (Exception e) { LOG.error("Cant find RemoteConnectionType with the name " + name, e); return NONE; } } }
Return NONE connection type for null.
Return NONE connection type for null.
Java
apache-2.0
fitermay/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,apixandru/intellij-community,da1z/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,apixandru/intellij-community,diorcety/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,semonte/intellij-community,FHannes/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,kool79/intellij-community,signed/intellij-community,signed/intellij-community,blademainer/intellij-community,apixandru/intellij-community,slisson/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,slisson/intellij-community,holmes/intellij-community,da1z/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,ryano144/intellij-community,kdwink/intellij-community,clumsy/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,asedunov/intellij-community,ibinti/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,clumsy/intellij-community,holmes/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,signed/intellij-community,supersven/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,signed/intellij-community,samthor/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,signed/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,allotria/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,da1z/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,samthor/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,apixandru/intellij-community,supersven/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,izonder/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,robovm/robovm-studio,kool79/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,dslomov/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,fitermay/intellij-community,apixandru/intellij-community,caot/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,hurricup/intellij-community,FHannes/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,samthor/intellij-community,blademainer/intellij-community,apixandru/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,asedunov/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,caot/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,asedunov/intellij-community,slisson/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,kool79/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,fnouama/intellij-community,jagguli/intellij-community,amith01994/intellij-community,kool79/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,caot/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,amith01994/intellij-community,allotria/intellij-community,clumsy/intellij-community,fnouama/intellij-community,petteyg/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,supersven/intellij-community,FHannes/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,petteyg/intellij-community,dslomov/intellij-community,robovm/robovm-studio,fnouama/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,samthor/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,dslomov/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,izonder/intellij-community,samthor/intellij-community,petteyg/intellij-community,diorcety/intellij-community,ryano144/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,retomerz/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,jagguli/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,da1z/intellij-community,apixandru/intellij-community,signed/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,izonder/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,xfournet/intellij-community,jagguli/intellij-community,hurricup/intellij-community,slisson/intellij-community,kool79/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,hurricup/intellij-community,xfournet/intellij-community,dslomov/intellij-community,diorcety/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,Lekanich/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,izonder/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,xfournet/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,kdwink/intellij-community,allotria/intellij-community,asedunov/intellij-community,da1z/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,slisson/intellij-community,caot/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,asedunov/intellij-community,slisson/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,signed/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,slisson/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,holmes/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,holmes/intellij-community,clumsy/intellij-community,kool79/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,allotria/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,youdonghai/intellij-community,kool79/intellij-community,vladmm/intellij-community,holmes/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,izonder/intellij-community,adedayo/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,asedunov/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,supersven/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,izonder/intellij-community,supersven/intellij-community,diorcety/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,ibinti/intellij-community,supersven/intellij-community,retomerz/intellij-community,da1z/intellij-community,ryano144/intellij-community,fnouama/intellij-community,kdwink/intellij-community,vladmm/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,caot/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,holmes/intellij-community,adedayo/intellij-community,apixandru/intellij-community,slisson/intellij-community,FHannes/intellij-community,signed/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,ahb0327/intellij-community,da1z/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,tmpgit/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,petteyg/intellij-community,robovm/robovm-studio,ibinti/intellij-community,retomerz/intellij-community,supersven/intellij-community,apixandru/intellij-community,asedunov/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,kdwink/intellij-community,caot/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,hurricup/intellij-community,kool79/intellij-community,semonte/intellij-community,supersven/intellij-community,allotria/intellij-community,xfournet/intellij-community,signed/intellij-community,diorcety/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,gnuhub/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,holmes/intellij-community,semonte/intellij-community,allotria/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,ibinti/intellij-community,robovm/robovm-studio,robovm/robovm-studio,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,hurricup/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,vladmm/intellij-community,samthor/intellij-community,vladmm/intellij-community,semonte/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,ryano144/intellij-community,kool79/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,xfournet/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,da1z/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,caot/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community
java
## Code Before: package com.intellij.remote; import com.intellij.openapi.diagnostic.Logger; /** * This class denotes the type of the source to obtain remote credentials. * * @author traff */ public enum RemoteConnectionType { /** * Currently selected SDK (e.g. <Project default>) */ DEFAULT_SDK, /** * Web deployment server */ DEPLOYMENT_SERVER, /** * Remote SDK */ REMOTE_SDK, /** * Current project vagrant */ CURRENT_VAGRANT, /** * No source is predefined - it would be asked on request */ NONE; private static final Logger LOG = Logger.getInstance(RemoteConnectionType.class); public static RemoteConnectionType findByName(String name) { try { return valueOf(name); } catch (Exception e) { LOG.error("Cant find RemoteConnectionType with the name " + name, e); return NONE; } } } ## Instruction: Return NONE connection type for null. ## Code After: package com.intellij.remote; import com.intellij.openapi.diagnostic.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * This class denotes the type of the source to obtain remote credentials. * * @author traff */ public enum RemoteConnectionType { /** * Currently selected SDK (e.g. <Project default>) */ DEFAULT_SDK, /** * Web deployment server */ DEPLOYMENT_SERVER, /** * Remote SDK */ REMOTE_SDK, /** * Current project vagrant */ CURRENT_VAGRANT, /** * No source is predefined - it would be asked on request */ NONE; private static final Logger LOG = Logger.getInstance(RemoteConnectionType.class); @NotNull public static RemoteConnectionType findByName(@Nullable String name) { if (name == null) { return NONE; } try { return valueOf(name); } catch (Exception e) { LOG.error("Cant find RemoteConnectionType with the name " + name, e); return NONE; } } }
... package com.intellij.remote; import com.intellij.openapi.diagnostic.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * This class denotes the type of the source to obtain remote credentials. ... private static final Logger LOG = Logger.getInstance(RemoteConnectionType.class); @NotNull public static RemoteConnectionType findByName(@Nullable String name) { if (name == null) { return NONE; } try { return valueOf(name); } ...
abebc8a1153a9529a0f805207492cf2f5edece62
cbor2/__init__.py
cbor2/__init__.py
from .decoder import load, loads, CBORDecoder, CBORDecodeError # noqa from .encoder import dump, dumps, CBOREncoder, CBOREncodeError, shareable_encoder # noqa from .types import CBORTag, CBORSimpleValue, undefined # noqa
from .decoder import load, loads, CBORDecoder # noqa from .encoder import dump, dumps, CBOREncoder, shareable_encoder # noqa from .types import ( # noqa CBORError, CBOREncodeError, CBORDecodeError, CBORTag, CBORSimpleValue, undefined ) try: from _cbor2 import * # noqa except ImportError: # Couldn't import the optimized C version; ignore the failure and leave the # pure Python implementations in place. pass else: # The pure Python implementations are replaced with the optimized C # variants, but we still need to create the encoder dictionaries for the C # variant here (this is much simpler than doing so in C, and doesn't affect # overall performance as it's a one-off initialization cost). def _init_cbor2(): from collections import OrderedDict from .encoder import default_encoders, canonical_encoders from .types import CBORTag, CBORSimpleValue, undefined # noqa import _cbor2 _cbor2.default_encoders = OrderedDict([ (( _cbor2.CBORSimpleValue if type_ is CBORSimpleValue else _cbor2.CBORTag if type_ is CBORTag else type(_cbor2.undefined) if type_ is type(undefined) else type_ ), getattr(_cbor2.CBOREncoder, method.__name__)) for type_, method in default_encoders.items() ]) _cbor2.canonical_encoders = OrderedDict([ (( _cbor2.CBORSimpleValue if type_ is CBORSimpleValue else _cbor2.CBORTag if type_ is CBORTag else type(_cbor2.undefined) if type_ is type(undefined) else type_ ), getattr(_cbor2.CBOREncoder, method.__name__)) for type_, method in canonical_encoders.items() ]) _init_cbor2() del _init_cbor2
Make the package import both variants
Make the package import both variants Favouring the C variant where it successfully imports. This commit also handles generating the encoding dictionaries for the C variant from those defined for the Python variant (this is much simpler than doing this in C).
Python
mit
agronholm/cbor2,agronholm/cbor2,agronholm/cbor2
python
## Code Before: from .decoder import load, loads, CBORDecoder, CBORDecodeError # noqa from .encoder import dump, dumps, CBOREncoder, CBOREncodeError, shareable_encoder # noqa from .types import CBORTag, CBORSimpleValue, undefined # noqa ## Instruction: Make the package import both variants Favouring the C variant where it successfully imports. This commit also handles generating the encoding dictionaries for the C variant from those defined for the Python variant (this is much simpler than doing this in C). ## Code After: from .decoder import load, loads, CBORDecoder # noqa from .encoder import dump, dumps, CBOREncoder, shareable_encoder # noqa from .types import ( # noqa CBORError, CBOREncodeError, CBORDecodeError, CBORTag, CBORSimpleValue, undefined ) try: from _cbor2 import * # noqa except ImportError: # Couldn't import the optimized C version; ignore the failure and leave the # pure Python implementations in place. pass else: # The pure Python implementations are replaced with the optimized C # variants, but we still need to create the encoder dictionaries for the C # variant here (this is much simpler than doing so in C, and doesn't affect # overall performance as it's a one-off initialization cost). def _init_cbor2(): from collections import OrderedDict from .encoder import default_encoders, canonical_encoders from .types import CBORTag, CBORSimpleValue, undefined # noqa import _cbor2 _cbor2.default_encoders = OrderedDict([ (( _cbor2.CBORSimpleValue if type_ is CBORSimpleValue else _cbor2.CBORTag if type_ is CBORTag else type(_cbor2.undefined) if type_ is type(undefined) else type_ ), getattr(_cbor2.CBOREncoder, method.__name__)) for type_, method in default_encoders.items() ]) _cbor2.canonical_encoders = OrderedDict([ (( _cbor2.CBORSimpleValue if type_ is CBORSimpleValue else _cbor2.CBORTag if type_ is CBORTag else type(_cbor2.undefined) if type_ is type(undefined) else type_ ), getattr(_cbor2.CBOREncoder, method.__name__)) for type_, method in canonical_encoders.items() ]) _init_cbor2() del _init_cbor2
... from .decoder import load, loads, CBORDecoder # noqa from .encoder import dump, dumps, CBOREncoder, shareable_encoder # noqa from .types import ( # noqa CBORError, CBOREncodeError, CBORDecodeError, CBORTag, CBORSimpleValue, undefined ) try: from _cbor2 import * # noqa except ImportError: # Couldn't import the optimized C version; ignore the failure and leave the # pure Python implementations in place. pass else: # The pure Python implementations are replaced with the optimized C # variants, but we still need to create the encoder dictionaries for the C # variant here (this is much simpler than doing so in C, and doesn't affect # overall performance as it's a one-off initialization cost). def _init_cbor2(): from collections import OrderedDict from .encoder import default_encoders, canonical_encoders from .types import CBORTag, CBORSimpleValue, undefined # noqa import _cbor2 _cbor2.default_encoders = OrderedDict([ (( _cbor2.CBORSimpleValue if type_ is CBORSimpleValue else _cbor2.CBORTag if type_ is CBORTag else type(_cbor2.undefined) if type_ is type(undefined) else type_ ), getattr(_cbor2.CBOREncoder, method.__name__)) for type_, method in default_encoders.items() ]) _cbor2.canonical_encoders = OrderedDict([ (( _cbor2.CBORSimpleValue if type_ is CBORSimpleValue else _cbor2.CBORTag if type_ is CBORTag else type(_cbor2.undefined) if type_ is type(undefined) else type_ ), getattr(_cbor2.CBOREncoder, method.__name__)) for type_, method in canonical_encoders.items() ]) _init_cbor2() del _init_cbor2 ...
2db6e8e294059847251feb9610c42180ae44e05b
fbone/appointment/views.py
fbone/appointment/views.py
from flask import (Blueprint, render_template, request, flash, url_for, redirect, session) from flask.ext.mail import Message from ..extensions import db, mail from .forms import MakeAppointmentForm from .models import Appointment appointment = Blueprint('appointment', __name__, url_prefix='/appointment') @appointment.route('/create', methods=['GET', 'POST']) def create(): form = MakeAppointmentForm(formdata=request.args, next=request.args.get('next')) # Dump all available data from request or session object to form fields. for key in form.data.keys(): setattr(getattr(form, key), 'data', request.args.get(key) or session.get(key)) if form.validate_on_submit(): appointment = Appointment() form.populate_obj(appointment) db.session.add(appointment) db.session.commit() flash_message = """ Congratulations! You've just made an appointment on WPIC Web Calendar system, please check your email for details. """ flash(flash_message) return redirect(url_for('appointment.create')) return render_template('appointment/create.html', form=form)
from datetime import datetime from flask import (Blueprint, render_template, request, abort, flash, url_for, redirect, session) from flask.ext.mail import Message from ..extensions import db, mail from .forms import MakeAppointmentForm from .models import Appointment appointment = Blueprint('appointment', __name__, url_prefix='/appointment') @appointment.route('/create', methods=['GET', 'POST']) def create(): if request.method == 'POST': form = MakeAppointmentForm(next=request.args.get('next')) if form.validate_on_submit(): appointment = Appointment() form.populate_obj(appointment) db.session.add(appointment) db.session.commit() flash_message = """ Congratulations! You've just made an appointment on WPIC Web Calendar system, please check your email for details. """ flash(flash_message) return redirect(url_for('appointment.create')) elif request.method == 'GET': form = MakeAppointmentForm(formdata=request.args, next=request.args.get('next')) # Dump all available data from request or session object to form # fields. for key in form.data.keys(): if key == "date": setattr(getattr(form, key), 'data', datetime.strptime(request.args.get(key) or session.get(key) or datetime.today().strftime('%Y-%m-%d'), "%Y-%m-%d")) else: setattr(getattr(form, key), 'data', request.args.get(key) or session.get(key)) return render_template('appointment/create.html', form=form) else: abort(405)
Fix some error about session.
Fix some error about session.
Python
bsd-3-clause
wpic/flask-appointment-calendar,wpic/flask-appointment-calendar
python
## Code Before: from flask import (Blueprint, render_template, request, flash, url_for, redirect, session) from flask.ext.mail import Message from ..extensions import db, mail from .forms import MakeAppointmentForm from .models import Appointment appointment = Blueprint('appointment', __name__, url_prefix='/appointment') @appointment.route('/create', methods=['GET', 'POST']) def create(): form = MakeAppointmentForm(formdata=request.args, next=request.args.get('next')) # Dump all available data from request or session object to form fields. for key in form.data.keys(): setattr(getattr(form, key), 'data', request.args.get(key) or session.get(key)) if form.validate_on_submit(): appointment = Appointment() form.populate_obj(appointment) db.session.add(appointment) db.session.commit() flash_message = """ Congratulations! You've just made an appointment on WPIC Web Calendar system, please check your email for details. """ flash(flash_message) return redirect(url_for('appointment.create')) return render_template('appointment/create.html', form=form) ## Instruction: Fix some error about session. ## Code After: from datetime import datetime from flask import (Blueprint, render_template, request, abort, flash, url_for, redirect, session) from flask.ext.mail import Message from ..extensions import db, mail from .forms import MakeAppointmentForm from .models import Appointment appointment = Blueprint('appointment', __name__, url_prefix='/appointment') @appointment.route('/create', methods=['GET', 'POST']) def create(): if request.method == 'POST': form = MakeAppointmentForm(next=request.args.get('next')) if form.validate_on_submit(): appointment = Appointment() form.populate_obj(appointment) db.session.add(appointment) db.session.commit() flash_message = """ Congratulations! You've just made an appointment on WPIC Web Calendar system, please check your email for details. """ flash(flash_message) return redirect(url_for('appointment.create')) elif request.method == 'GET': form = MakeAppointmentForm(formdata=request.args, next=request.args.get('next')) # Dump all available data from request or session object to form # fields. for key in form.data.keys(): if key == "date": setattr(getattr(form, key), 'data', datetime.strptime(request.args.get(key) or session.get(key) or datetime.today().strftime('%Y-%m-%d'), "%Y-%m-%d")) else: setattr(getattr(form, key), 'data', request.args.get(key) or session.get(key)) return render_template('appointment/create.html', form=form) else: abort(405)
# ... existing code ... from datetime import datetime from flask import (Blueprint, render_template, request, abort, flash, url_for, redirect, session) from flask.ext.mail import Message # ... modified code ... @appointment.route('/create', methods=['GET', 'POST']) def create(): if request.method == 'POST': form = MakeAppointmentForm(next=request.args.get('next')) if form.validate_on_submit(): appointment = Appointment() form.populate_obj(appointment) db.session.add(appointment) db.session.commit() flash_message = """ Congratulations! You've just made an appointment on WPIC Web Calendar system, please check your email for details. """ flash(flash_message) return redirect(url_for('appointment.create')) elif request.method == 'GET': form = MakeAppointmentForm(formdata=request.args, next=request.args.get('next')) # Dump all available data from request or session object to form # fields. for key in form.data.keys(): if key == "date": setattr(getattr(form, key), 'data', datetime.strptime(request.args.get(key) or session.get(key) or datetime.today().strftime('%Y-%m-%d'), "%Y-%m-%d")) else: setattr(getattr(form, key), 'data', request.args.get(key) or session.get(key)) return render_template('appointment/create.html', form=form) else: abort(405) # ... rest of the code ...
592d7223f28ff5b01e8538317f39c156c3ae9a97
src/main/java/ljfa/tntutils/gui/TntuConfigGui.java
src/main/java/ljfa/tntutils/gui/TntuConfigGui.java
package ljfa.tntutils.gui; import java.util.ArrayList; import java.util.List; import ljfa.tntutils.Config; import ljfa.tntutils.Reference; import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.ConfigElement; import cpw.mods.fml.client.config.DummyConfigElement; import cpw.mods.fml.client.config.GuiConfig; import cpw.mods.fml.client.config.IConfigElement; public class TntuConfigGui extends GuiConfig { public TntuConfigGui(GuiScreen parent) { super(parent, getConfigElements(), Reference.MODID, false, false, "TNTUtils configuration"); } /** Compiles a list of config elements */ private static List<IConfigElement> getConfigElements() { List<IConfigElement> list = new ArrayList<IConfigElement>(); //Add categories to config GUI list.add(new ConfigElement<ConfigCategory>(Config.conf.getCategory(Config.CATEGORY_GENERAL))); return list; } }
package ljfa.tntutils.gui; import java.util.ArrayList; import java.util.List; import ljfa.tntutils.Config; import ljfa.tntutils.Reference; import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.ConfigElement; import cpw.mods.fml.client.config.DummyConfigElement; import cpw.mods.fml.client.config.GuiConfig; import cpw.mods.fml.client.config.IConfigElement; public class TntuConfigGui extends GuiConfig { public TntuConfigGui(GuiScreen parent) { super(parent, getConfigElements(), Reference.MODID, false, false, "TNTUtils configuration"); } /** Compiles a list of config elements * Borrowed from EnderIO's implementation */ private static List<IConfigElement> getConfigElements() { List<IConfigElement> list = new ArrayList<IConfigElement>(); for(String name: Config.conf.getCategoryNames()) list.add(new ConfigElement<ConfigCategory>(Config.conf.getCategory(name))); return list; } }
Make Config GUIs easier to work with
Make Config GUIs easier to work with
Java
mit
ljfa-ag/TNTUtils
java
## Code Before: package ljfa.tntutils.gui; import java.util.ArrayList; import java.util.List; import ljfa.tntutils.Config; import ljfa.tntutils.Reference; import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.ConfigElement; import cpw.mods.fml.client.config.DummyConfigElement; import cpw.mods.fml.client.config.GuiConfig; import cpw.mods.fml.client.config.IConfigElement; public class TntuConfigGui extends GuiConfig { public TntuConfigGui(GuiScreen parent) { super(parent, getConfigElements(), Reference.MODID, false, false, "TNTUtils configuration"); } /** Compiles a list of config elements */ private static List<IConfigElement> getConfigElements() { List<IConfigElement> list = new ArrayList<IConfigElement>(); //Add categories to config GUI list.add(new ConfigElement<ConfigCategory>(Config.conf.getCategory(Config.CATEGORY_GENERAL))); return list; } } ## Instruction: Make Config GUIs easier to work with ## Code After: package ljfa.tntutils.gui; import java.util.ArrayList; import java.util.List; import ljfa.tntutils.Config; import ljfa.tntutils.Reference; import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.ConfigElement; import cpw.mods.fml.client.config.DummyConfigElement; import cpw.mods.fml.client.config.GuiConfig; import cpw.mods.fml.client.config.IConfigElement; public class TntuConfigGui extends GuiConfig { public TntuConfigGui(GuiScreen parent) { super(parent, getConfigElements(), Reference.MODID, false, false, "TNTUtils configuration"); } /** Compiles a list of config elements * Borrowed from EnderIO's implementation */ private static List<IConfigElement> getConfigElements() { List<IConfigElement> list = new ArrayList<IConfigElement>(); for(String name: Config.conf.getCategoryNames()) list.add(new ConfigElement<ConfigCategory>(Config.conf.getCategory(name))); return list; } }
# ... existing code ... super(parent, getConfigElements(), Reference.MODID, false, false, "TNTUtils configuration"); } /** Compiles a list of config elements * Borrowed from EnderIO's implementation */ private static List<IConfigElement> getConfigElements() { List<IConfigElement> list = new ArrayList<IConfigElement>(); for(String name: Config.conf.getCategoryNames()) list.add(new ConfigElement<ConfigCategory>(Config.conf.getCategory(name))); return list; } } # ... rest of the code ...
74ba99eab5d87b36e1c7809b395725d83d0ab1d6
src/scan.c
src/scan.c
/* scan: Esitmate length of a mpeg file and compare to length from exact scan. copyright 2007 by the mpg123 project - free software under the terms of the LGPL 2.1 see COPYING and AUTHORS files in distribution or http://mpg123.org initially written by Thomas Orgis */ #include "mpg123.h" int main(int argc, char **argv) { mpg123_handle *m; int i; mpg123_init(); m = mpg123_new(NULL, NULL); for(i = 1; i < argc; ++i) { off_t a, b; mpg123_open(m, argv[i]); a = mpg123_length(m); mpg123_scan(m); b = mpg123_length(m); printf("File %i: estimated %li vs. scanned %li\n", i, (long)a, (long)b); } mpg123_delete(m); mpg123_exit(); return 0; }
/* scan: Estimate length (sample count) of a mpeg file and compare to length from exact scan. copyright 2007 by the mpg123 project - free software under the terms of the LGPL 2.1 see COPYING and AUTHORS files in distribution or http://mpg123.org initially written by Thomas Orgis */ /* Note the lack of error checking here. While it would be nicer to inform the user about troubles, libmpg123 is designed _not_ to bite you on operations with invalid handles , etc. You just jet invalid results on invalid operations... */ #include <stdio.h> #include "mpg123.h" int main(int argc, char **argv) { mpg123_handle *m; int i; mpg123_init(); m = mpg123_new(NULL, NULL); for(i = 1; i < argc; ++i) { off_t a, b; mpg123_open(m, argv[i]); a = mpg123_length(m); mpg123_scan(m); b = mpg123_length(m); printf("File %i: estimated %li vs. scanned %li\n", i, (long)a, (long)b); } mpg123_delete(m); mpg123_exit(); return 0; }
Add a note about error checking, fix description and include stdio.h .
Add a note about error checking, fix description and include stdio.h . git-svn-id: 793bb72743a407948e3701719c462b6a765bc435@1145 35dc7657-300d-0410-a2e5-dc2837fedb53
C
lgpl-2.1
Distrotech/mpg123,Distrotech/mpg123,Distrotech/mpg123,Distrotech/mpg123,Distrotech/mpg123,Distrotech/mpg123,Distrotech/mpg123
c
## Code Before: /* scan: Esitmate length of a mpeg file and compare to length from exact scan. copyright 2007 by the mpg123 project - free software under the terms of the LGPL 2.1 see COPYING and AUTHORS files in distribution or http://mpg123.org initially written by Thomas Orgis */ #include "mpg123.h" int main(int argc, char **argv) { mpg123_handle *m; int i; mpg123_init(); m = mpg123_new(NULL, NULL); for(i = 1; i < argc; ++i) { off_t a, b; mpg123_open(m, argv[i]); a = mpg123_length(m); mpg123_scan(m); b = mpg123_length(m); printf("File %i: estimated %li vs. scanned %li\n", i, (long)a, (long)b); } mpg123_delete(m); mpg123_exit(); return 0; } ## Instruction: Add a note about error checking, fix description and include stdio.h . git-svn-id: 793bb72743a407948e3701719c462b6a765bc435@1145 35dc7657-300d-0410-a2e5-dc2837fedb53 ## Code After: /* scan: Estimate length (sample count) of a mpeg file and compare to length from exact scan. copyright 2007 by the mpg123 project - free software under the terms of the LGPL 2.1 see COPYING and AUTHORS files in distribution or http://mpg123.org initially written by Thomas Orgis */ /* Note the lack of error checking here. While it would be nicer to inform the user about troubles, libmpg123 is designed _not_ to bite you on operations with invalid handles , etc. You just jet invalid results on invalid operations... */ #include <stdio.h> #include "mpg123.h" int main(int argc, char **argv) { mpg123_handle *m; int i; mpg123_init(); m = mpg123_new(NULL, NULL); for(i = 1; i < argc; ++i) { off_t a, b; mpg123_open(m, argv[i]); a = mpg123_length(m); mpg123_scan(m); b = mpg123_length(m); printf("File %i: estimated %li vs. scanned %li\n", i, (long)a, (long)b); } mpg123_delete(m); mpg123_exit(); return 0; }
# ... existing code ... /* scan: Estimate length (sample count) of a mpeg file and compare to length from exact scan. copyright 2007 by the mpg123 project - free software under the terms of the LGPL 2.1 see COPYING and AUTHORS files in distribution or http://mpg123.org # ... modified code ... initially written by Thomas Orgis */ /* Note the lack of error checking here. While it would be nicer to inform the user about troubles, libmpg123 is designed _not_ to bite you on operations with invalid handles , etc. You just jet invalid results on invalid operations... */ #include <stdio.h> #include "mpg123.h" int main(int argc, char **argv) # ... rest of the code ...
99412f8b3394abdab900755095c788604669853d
ankieta/ankieta/petition/views.py
ankieta/ankieta/petition/views.py
from django.views.generic import ListView, CreateView, DetailView, TemplateView from django.core.urlresolvers import reverse from braces.views import SetHeadlineMixin from braces.views import OrderableListMixin from .models import Signature from .forms import SignatureForm class SignatureList(OrderableListMixin, ListView): model = Signature orderable_columns = ("pk", "name", "city") orderable_columns_default = "created_on" ordering = 'desc' paginate_by = 10 def get_context_data(self, **kwargs): context = super(SignatureList, self).get_context_data(**kwargs) context['count'] = Signature.objects.visible().count() context['form'] = SignatureForm() return context def get_queryset(self, *args, **kwargs): qs = super(SignatureList, self).get_queryset(*args, **kwargs) return qs.visible() class SignatureCreate(SetHeadlineMixin, CreateView): model = Signature form_class = SignatureForm def get_success_url(self): return reverse('petition:thank-you') class SignatureDetail(DetailView): model = Signature class SignatureCreateDone(TemplateView): template_name = 'petition/signature_thank_you.html'
from django.views.generic import ListView, CreateView, DetailView, TemplateView from django.core.urlresolvers import reverse from braces.views import OrderableListMixin from .models import Signature from .forms import SignatureForm class SignatureList(OrderableListMixin, ListView): model = Signature orderable_columns = ("pk", "name", "city") orderable_columns_default = "created_on" ordering = 'desc' paginate_by = 10 def get_context_data(self, **kwargs): context = super(SignatureList, self).get_context_data(**kwargs) context['count'] = Signature.objects.visible().count() context['form'] = SignatureForm() return context def get_queryset(self, *args, **kwargs): qs = super(SignatureList, self).get_queryset(*args, **kwargs) return qs.visible() class SignatureCreate(CreateView): model = Signature form_class = SignatureForm def get_success_url(self): return reverse('petition:thank-you') class SignatureDetail(DetailView): model = Signature class SignatureCreateDone(TemplateView): template_name = 'petition/signature_thank_you.html'
Remove headline from create view
Remove headline from create view
Python
bsd-3-clause
watchdogpolska/prezydent.siecobywatelska.pl,watchdogpolska/prezydent.siecobywatelska.pl,watchdogpolska/prezydent.siecobywatelska.pl
python
## Code Before: from django.views.generic import ListView, CreateView, DetailView, TemplateView from django.core.urlresolvers import reverse from braces.views import SetHeadlineMixin from braces.views import OrderableListMixin from .models import Signature from .forms import SignatureForm class SignatureList(OrderableListMixin, ListView): model = Signature orderable_columns = ("pk", "name", "city") orderable_columns_default = "created_on" ordering = 'desc' paginate_by = 10 def get_context_data(self, **kwargs): context = super(SignatureList, self).get_context_data(**kwargs) context['count'] = Signature.objects.visible().count() context['form'] = SignatureForm() return context def get_queryset(self, *args, **kwargs): qs = super(SignatureList, self).get_queryset(*args, **kwargs) return qs.visible() class SignatureCreate(SetHeadlineMixin, CreateView): model = Signature form_class = SignatureForm def get_success_url(self): return reverse('petition:thank-you') class SignatureDetail(DetailView): model = Signature class SignatureCreateDone(TemplateView): template_name = 'petition/signature_thank_you.html' ## Instruction: Remove headline from create view ## Code After: from django.views.generic import ListView, CreateView, DetailView, TemplateView from django.core.urlresolvers import reverse from braces.views import OrderableListMixin from .models import Signature from .forms import SignatureForm class SignatureList(OrderableListMixin, ListView): model = Signature orderable_columns = ("pk", "name", "city") orderable_columns_default = "created_on" ordering = 'desc' paginate_by = 10 def get_context_data(self, **kwargs): context = super(SignatureList, self).get_context_data(**kwargs) context['count'] = Signature.objects.visible().count() context['form'] = SignatureForm() return context def get_queryset(self, *args, **kwargs): qs = super(SignatureList, self).get_queryset(*args, **kwargs) return qs.visible() class SignatureCreate(CreateView): model = Signature form_class = SignatureForm def get_success_url(self): return reverse('petition:thank-you') class SignatureDetail(DetailView): model = Signature class SignatureCreateDone(TemplateView): template_name = 'petition/signature_thank_you.html'
// ... existing code ... from django.views.generic import ListView, CreateView, DetailView, TemplateView from django.core.urlresolvers import reverse from braces.views import OrderableListMixin from .models import Signature from .forms import SignatureForm // ... modified code ... return qs.visible() class SignatureCreate(CreateView): model = Signature form_class = SignatureForm // ... rest of the code ...
cd6ab8cc43ee0171d90bf6a0b94b19e12fb831c5
test/CodeGen/2004-02-13-Memset.c
test/CodeGen/2004-02-13-Memset.c
// RUN: %clang_cc1 %s -emit-llvm -o - | grep llvm.memset | count 3 #ifndef memset void *memset(void*, int, unsigned long); #endif #ifndef bzero void bzero(void*, unsigned long); #endif void test(int* X, char *Y) { // CHECK: call i8* llvm.memset memset(X, 4, 1000); // CHECK: call void bzero bzero(Y, 100); }
// RUN: %clang_cc1 %s -emit-llvm -o - | grep llvm.memset | count 3 typedef __SIZE_TYPE__ size_t; void *memset(void*, int, size_t); void bzero(void*, size_t); void test(int* X, char *Y) { // CHECK: call i8* llvm.memset memset(X, 4, 1000); // CHECK: call void bzero bzero(Y, 100); }
Use the correct definition for memset.
Use the correct definition for memset. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@136188 91177308-0d34-0410-b5e6-96231b3b80d8
C
apache-2.0
apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang
c
## Code Before: // RUN: %clang_cc1 %s -emit-llvm -o - | grep llvm.memset | count 3 #ifndef memset void *memset(void*, int, unsigned long); #endif #ifndef bzero void bzero(void*, unsigned long); #endif void test(int* X, char *Y) { // CHECK: call i8* llvm.memset memset(X, 4, 1000); // CHECK: call void bzero bzero(Y, 100); } ## Instruction: Use the correct definition for memset. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@136188 91177308-0d34-0410-b5e6-96231b3b80d8 ## Code After: // RUN: %clang_cc1 %s -emit-llvm -o - | grep llvm.memset | count 3 typedef __SIZE_TYPE__ size_t; void *memset(void*, int, size_t); void bzero(void*, size_t); void test(int* X, char *Y) { // CHECK: call i8* llvm.memset memset(X, 4, 1000); // CHECK: call void bzero bzero(Y, 100); }
// ... existing code ... // RUN: %clang_cc1 %s -emit-llvm -o - | grep llvm.memset | count 3 typedef __SIZE_TYPE__ size_t; void *memset(void*, int, size_t); void bzero(void*, size_t); void test(int* X, char *Y) { // CHECK: call i8* llvm.memset // ... rest of the code ...
90d8411412b79513338b014da63b18d0d29396d9
snmpy/log_processor.py
snmpy/log_processor.py
import re, snmpy_plugins class log_processor: def __init__(self, conf): self.data = [{'value':0, 'label': conf['objects'][item]['label'], 'regex': re.compile(conf['objects'][item]['regex'])} for item in sorted(conf['objects'])] self.proc(conf['logfile']) def len(self): return len(self.data) def key(self, idx): return 'string', self.data[idx - 1]['label'] def val(self, idx): return 'integer', self.data[idx - 1]['value'] @snmpy_plugins.task def proc(self, file): for line in snmpy_plugins.tail(file): for item in xrange(len(self.data)): find = self.data[item]['regex'].search(line) if find: self.data[item]['value'] += 1 break
import re import snmpy class log_processor(snmpy.plugin): def __init__(self, conf, script=False): snmpy.plugin.__init__(self, conf, script) def key(self, idx): return 'string', self.data[idx - 1]['label'] def val(self, idx): return 'integer', self.data[idx - 1]['value'] def worker(self): self.data = [{'value':0, 'label': self.conf['objects'][item]['label'], 'regex': re.compile(self.conf['objects'][item]['regex'])} for item in sorted(self.conf['objects'])] self.tail() @snmpy.task def tail(self): for line in snmpy.tail(self.conf['logfile']): for item in xrange(len(self.data)): find = self.data[item]['regex'].search(line) if find: self.data[item]['value'] += 1 break
Convert to use the base class and update for new plugin path.
Convert to use the base class and update for new plugin path.
Python
mit
mk23/snmpy,mk23/snmpy
python
## Code Before: import re, snmpy_plugins class log_processor: def __init__(self, conf): self.data = [{'value':0, 'label': conf['objects'][item]['label'], 'regex': re.compile(conf['objects'][item]['regex'])} for item in sorted(conf['objects'])] self.proc(conf['logfile']) def len(self): return len(self.data) def key(self, idx): return 'string', self.data[idx - 1]['label'] def val(self, idx): return 'integer', self.data[idx - 1]['value'] @snmpy_plugins.task def proc(self, file): for line in snmpy_plugins.tail(file): for item in xrange(len(self.data)): find = self.data[item]['regex'].search(line) if find: self.data[item]['value'] += 1 break ## Instruction: Convert to use the base class and update for new plugin path. ## Code After: import re import snmpy class log_processor(snmpy.plugin): def __init__(self, conf, script=False): snmpy.plugin.__init__(self, conf, script) def key(self, idx): return 'string', self.data[idx - 1]['label'] def val(self, idx): return 'integer', self.data[idx - 1]['value'] def worker(self): self.data = [{'value':0, 'label': self.conf['objects'][item]['label'], 'regex': re.compile(self.conf['objects'][item]['regex'])} for item in sorted(self.conf['objects'])] self.tail() @snmpy.task def tail(self): for line in snmpy.tail(self.conf['logfile']): for item in xrange(len(self.data)): find = self.data[item]['regex'].search(line) if find: self.data[item]['value'] += 1 break
# ... existing code ... import re import snmpy class log_processor(snmpy.plugin): def __init__(self, conf, script=False): snmpy.plugin.__init__(self, conf, script) def key(self, idx): return 'string', self.data[idx - 1]['label'] # ... modified code ... def val(self, idx): return 'integer', self.data[idx - 1]['value'] def worker(self): self.data = [{'value':0, 'label': self.conf['objects'][item]['label'], 'regex': re.compile(self.conf['objects'][item]['regex'])} for item in sorted(self.conf['objects'])] self.tail() @snmpy.task def tail(self): for line in snmpy.tail(self.conf['logfile']): for item in xrange(len(self.data)): find = self.data[item]['regex'].search(line) if find: # ... rest of the code ...
c11f4384335288a1f95c919c153ca523907850d1
src/test/java/org/inferred/cjp39/j8stages/ExceptionClonerTest.java
src/test/java/org/inferred/cjp39/j8stages/ExceptionClonerTest.java
package org.inferred.cjp39.j8stages; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import org.junit.Test; public class ExceptionClonerTest { private static final class MyUnfriendlyException extends Exception { private MyUnfriendlyException(String message, Throwable cause) { super(message, cause); } } @Test public void clone_matches_original() { MyUnfriendlyException x = new MyUnfriendlyException("Clone this, baby!", new RuntimeException("cause")); MyUnfriendlyException clone = ExceptionCloner.clone(x); assertEquals(x.getMessage(), clone.getMessage()); assertSame(x.getCause(), clone.getCause()); } @Test public void modifying_clone_does_not_modify_original() { MyUnfriendlyException x = new MyUnfriendlyException("Clone this, baby!", new RuntimeException("cause")); MyUnfriendlyException clone = ExceptionCloner.clone(x); clone.addSuppressed(new RuntimeException("dormouse")); assertEquals(0, x.getSuppressed().length); } }
package org.inferred.cjp39.j8stages; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import org.junit.Test; public class ExceptionClonerTest { private static final class MyUnfriendlyException extends Exception { private MyUnfriendlyException(String message, Throwable cause) { super(message, cause); } } @Test public void clone_matches_original() { MyUnfriendlyException x = new MyUnfriendlyException("Clone this, baby!", new RuntimeException("cause")); MyUnfriendlyException clone = ExceptionCloner.clone(x); assertEquals(x.getMessage(), clone.getMessage()); assertSame(x.getCause(), clone.getCause()); } @Test public void modifying_clone_does_not_modify_original() { MyUnfriendlyException x = new MyUnfriendlyException("Clone this, baby!", new RuntimeException("cause")); MyUnfriendlyException clone = ExceptionCloner.clone(x); clone.addSuppressed(new RuntimeException("dormouse")); assertEquals(0, x.getSuppressed().length); } @Test public void suppressed_array_not_aliased() { MyUnfriendlyException x = new MyUnfriendlyException("Clone this, baby!", new RuntimeException("cause")); x.addSuppressed(new RuntimeException("Help, help, I'm being repressed!")); MyUnfriendlyException clone = ExceptionCloner.clone(x); clone.addSuppressed(new RuntimeException("dormouse")); MyUnfriendlyException clone2 = ExceptionCloner.clone(clone); clone2.addSuppressed(new RuntimeException("in a teapot")); assertEquals(3, clone2.getSuppressed().length); assertEquals(2, clone.getSuppressed().length); assertEquals(1, x.getSuppressed().length); } }
Add a test to ensure the list of suppressed exceptions in a Throwable is not accidentally aliased during the shallow copy.
Add a test to ensure the list of suppressed exceptions in a Throwable is not accidentally aliased during the shallow copy.
Java
mit
cjp39/j8stages
java
## Code Before: package org.inferred.cjp39.j8stages; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import org.junit.Test; public class ExceptionClonerTest { private static final class MyUnfriendlyException extends Exception { private MyUnfriendlyException(String message, Throwable cause) { super(message, cause); } } @Test public void clone_matches_original() { MyUnfriendlyException x = new MyUnfriendlyException("Clone this, baby!", new RuntimeException("cause")); MyUnfriendlyException clone = ExceptionCloner.clone(x); assertEquals(x.getMessage(), clone.getMessage()); assertSame(x.getCause(), clone.getCause()); } @Test public void modifying_clone_does_not_modify_original() { MyUnfriendlyException x = new MyUnfriendlyException("Clone this, baby!", new RuntimeException("cause")); MyUnfriendlyException clone = ExceptionCloner.clone(x); clone.addSuppressed(new RuntimeException("dormouse")); assertEquals(0, x.getSuppressed().length); } } ## Instruction: Add a test to ensure the list of suppressed exceptions in a Throwable is not accidentally aliased during the shallow copy. ## Code After: package org.inferred.cjp39.j8stages; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import org.junit.Test; public class ExceptionClonerTest { private static final class MyUnfriendlyException extends Exception { private MyUnfriendlyException(String message, Throwable cause) { super(message, cause); } } @Test public void clone_matches_original() { MyUnfriendlyException x = new MyUnfriendlyException("Clone this, baby!", new RuntimeException("cause")); MyUnfriendlyException clone = ExceptionCloner.clone(x); assertEquals(x.getMessage(), clone.getMessage()); assertSame(x.getCause(), clone.getCause()); } @Test public void modifying_clone_does_not_modify_original() { MyUnfriendlyException x = new MyUnfriendlyException("Clone this, baby!", new RuntimeException("cause")); MyUnfriendlyException clone = ExceptionCloner.clone(x); clone.addSuppressed(new RuntimeException("dormouse")); assertEquals(0, x.getSuppressed().length); } @Test public void suppressed_array_not_aliased() { MyUnfriendlyException x = new MyUnfriendlyException("Clone this, baby!", new RuntimeException("cause")); x.addSuppressed(new RuntimeException("Help, help, I'm being repressed!")); MyUnfriendlyException clone = ExceptionCloner.clone(x); clone.addSuppressed(new RuntimeException("dormouse")); MyUnfriendlyException clone2 = ExceptionCloner.clone(clone); clone2.addSuppressed(new RuntimeException("in a teapot")); assertEquals(3, clone2.getSuppressed().length); assertEquals(2, clone.getSuppressed().length); assertEquals(1, x.getSuppressed().length); } }
... clone.addSuppressed(new RuntimeException("dormouse")); assertEquals(0, x.getSuppressed().length); } @Test public void suppressed_array_not_aliased() { MyUnfriendlyException x = new MyUnfriendlyException("Clone this, baby!", new RuntimeException("cause")); x.addSuppressed(new RuntimeException("Help, help, I'm being repressed!")); MyUnfriendlyException clone = ExceptionCloner.clone(x); clone.addSuppressed(new RuntimeException("dormouse")); MyUnfriendlyException clone2 = ExceptionCloner.clone(clone); clone2.addSuppressed(new RuntimeException("in a teapot")); assertEquals(3, clone2.getSuppressed().length); assertEquals(2, clone.getSuppressed().length); assertEquals(1, x.getSuppressed().length); } } ...
431357bc5ced7c1ffd6616f681c195ce45c61462
scriptobject.h
scriptobject.h
class EmacsInstance; class ScriptObject : public NPObject { public: static ScriptObject* create(NPP npp); void invalidate(); bool hasMethod(NPIdentifier name); bool invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result); bool enumerate(NPIdentifier **identifiers, uint32_t *identifierCount); static NPObject* allocateThunk(NPP npp, NPClass *aClass); static void deallocateThunk(NPObject *npobj); static void invalidateThunk(NPObject *npobj); static bool hasMethodThunk(NPObject *npobj, NPIdentifier name); static bool invokeThunk(NPObject *npobj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result); static bool enumerateThunk(NPObject *npobj, NPIdentifier **identifiers, uint32_t *identifierCount); private: ScriptObject(NPP npp); ~ScriptObject(); EmacsInstance* emacsInstance(); NPP npp_; }; #endif // INCLUDED_SCRIPT_OBJECT_H_
class EmacsInstance; class ScriptObject : public NPObject { public: static ScriptObject* create(NPP npp); void invalidate(); bool hasMethod(NPIdentifier name); bool invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result); bool enumerate(NPIdentifier **identifiers, uint32_t *identifierCount); static NPObject* allocateThunk(NPP npp, NPClass *aClass); static void deallocateThunk(NPObject *npobj); static void invalidateThunk(NPObject *npobj); static bool hasMethodThunk(NPObject *npobj, NPIdentifier name); static bool invokeThunk(NPObject *npobj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result); static bool enumerateThunk(NPObject *npobj, NPIdentifier **identifiers, uint32_t *identifierCount); private: ScriptObject(NPP npp); ~ScriptObject(); EmacsInstance* emacsInstance(); NPP npp_; DISALLOW_COPY_AND_ASSIGN(ScriptObject); }; #endif // INCLUDED_SCRIPT_OBJECT_H_
Disable copy and assign on ScriptObject
Disable copy and assign on ScriptObject
C
mit
davidben/embedded-emacs,davidben/embedded-emacs,davidben/embedded-emacs
c
## Code Before: class EmacsInstance; class ScriptObject : public NPObject { public: static ScriptObject* create(NPP npp); void invalidate(); bool hasMethod(NPIdentifier name); bool invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result); bool enumerate(NPIdentifier **identifiers, uint32_t *identifierCount); static NPObject* allocateThunk(NPP npp, NPClass *aClass); static void deallocateThunk(NPObject *npobj); static void invalidateThunk(NPObject *npobj); static bool hasMethodThunk(NPObject *npobj, NPIdentifier name); static bool invokeThunk(NPObject *npobj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result); static bool enumerateThunk(NPObject *npobj, NPIdentifier **identifiers, uint32_t *identifierCount); private: ScriptObject(NPP npp); ~ScriptObject(); EmacsInstance* emacsInstance(); NPP npp_; }; #endif // INCLUDED_SCRIPT_OBJECT_H_ ## Instruction: Disable copy and assign on ScriptObject ## Code After: class EmacsInstance; class ScriptObject : public NPObject { public: static ScriptObject* create(NPP npp); void invalidate(); bool hasMethod(NPIdentifier name); bool invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result); bool enumerate(NPIdentifier **identifiers, uint32_t *identifierCount); static NPObject* allocateThunk(NPP npp, NPClass *aClass); static void deallocateThunk(NPObject *npobj); static void invalidateThunk(NPObject *npobj); static bool hasMethodThunk(NPObject *npobj, NPIdentifier name); static bool invokeThunk(NPObject *npobj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result); static bool enumerateThunk(NPObject *npobj, NPIdentifier **identifiers, uint32_t *identifierCount); private: ScriptObject(NPP npp); ~ScriptObject(); EmacsInstance* emacsInstance(); NPP npp_; DISALLOW_COPY_AND_ASSIGN(ScriptObject); }; #endif // INCLUDED_SCRIPT_OBJECT_H_
// ... existing code ... EmacsInstance* emacsInstance(); NPP npp_; DISALLOW_COPY_AND_ASSIGN(ScriptObject); }; #endif // INCLUDED_SCRIPT_OBJECT_H_ // ... rest of the code ...
c711d5e2dbca4b95bebc0eed4d48a35eb3c7a998
website/addons/dropbox/settings/local-dist.py
website/addons/dropbox/settings/local-dist.py
# Get an app key and secret at https://www.dropbox.com/developers/apps DROPBOX_KEY = 'changeme' DROPBOX_SECRET = 'changeme'
# Get an app key and secret at https://www.dropbox.com/developers/apps DROPBOX_KEY = 'jnpncg5s2fc7cj8' DROPBOX_SECRET = 'sjqv1hrk7sonhu1'
Add dropbox credentials for testing.
Add dropbox credentials for testing.
Python
apache-2.0
crcresearch/osf.io,acshi/osf.io,felliott/osf.io,TomHeatwole/osf.io,RomanZWang/osf.io,jnayak1/osf.io,baylee-d/osf.io,TomBaxter/osf.io,mluke93/osf.io,mluo613/osf.io,pattisdr/osf.io,samchrisinger/osf.io,wearpants/osf.io,mfraezz/osf.io,kch8qx/osf.io,Nesiehr/osf.io,adlius/osf.io,RomanZWang/osf.io,abought/osf.io,felliott/osf.io,jnayak1/osf.io,caseyrollins/osf.io,doublebits/osf.io,cslzchen/osf.io,kwierman/osf.io,monikagrabowska/osf.io,rdhyee/osf.io,laurenrevere/osf.io,Nesiehr/osf.io,HalcyonChimera/osf.io,icereval/osf.io,zamattiac/osf.io,CenterForOpenScience/osf.io,jnayak1/osf.io,cwisecarver/osf.io,SSJohns/osf.io,icereval/osf.io,monikagrabowska/osf.io,wearpants/osf.io,chrisseto/osf.io,binoculars/osf.io,monikagrabowska/osf.io,mluo613/osf.io,adlius/osf.io,aaxelb/osf.io,monikagrabowska/osf.io,asanfilippo7/osf.io,icereval/osf.io,brianjgeiger/osf.io,amyshi188/osf.io,cwisecarver/osf.io,DanielSBrown/osf.io,crcresearch/osf.io,kch8qx/osf.io,SSJohns/osf.io,abought/osf.io,crcresearch/osf.io,laurenrevere/osf.io,mluo613/osf.io,baylee-d/osf.io,alexschiller/osf.io,zachjanicki/osf.io,aaxelb/osf.io,rdhyee/osf.io,doublebits/osf.io,amyshi188/osf.io,Nesiehr/osf.io,sloria/osf.io,hmoco/osf.io,HalcyonChimera/osf.io,aaxelb/osf.io,RomanZWang/osf.io,TomHeatwole/osf.io,kch8qx/osf.io,chrisseto/osf.io,TomBaxter/osf.io,aaxelb/osf.io,DanielSBrown/osf.io,mattclark/osf.io,emetsger/osf.io,emetsger/osf.io,binoculars/osf.io,zachjanicki/osf.io,kwierman/osf.io,kwierman/osf.io,kwierman/osf.io,sloria/osf.io,mfraezz/osf.io,kch8qx/osf.io,acshi/osf.io,chennan47/osf.io,caneruguz/osf.io,doublebits/osf.io,mluke93/osf.io,erinspace/osf.io,alexschiller/osf.io,mluo613/osf.io,zamattiac/osf.io,alexschiller/osf.io,caseyrollins/osf.io,zachjanicki/osf.io,cwisecarver/osf.io,samchrisinger/osf.io,TomBaxter/osf.io,wearpants/osf.io,amyshi188/osf.io,Johnetordoff/osf.io,HalcyonChimera/osf.io,laurenrevere/osf.io,cslzchen/osf.io,SSJohns/osf.io,monikagrabowska/osf.io,Johnetordoff/osf.io,asanfilippo7/osf.io,zamattiac/osf.io,CenterForOpenScience/osf.io,abought/osf.io,jnayak1/osf.io,Johnetordoff/osf.io,mfraezz/osf.io,samchrisinger/osf.io,DanielSBrown/osf.io,rdhyee/osf.io,leb2dg/osf.io,acshi/osf.io,mattclark/osf.io,chrisseto/osf.io,leb2dg/osf.io,brianjgeiger/osf.io,zachjanicki/osf.io,mluke93/osf.io,binoculars/osf.io,asanfilippo7/osf.io,felliott/osf.io,DanielSBrown/osf.io,TomHeatwole/osf.io,hmoco/osf.io,kch8qx/osf.io,caneruguz/osf.io,saradbowman/osf.io,felliott/osf.io,adlius/osf.io,doublebits/osf.io,caneruguz/osf.io,samchrisinger/osf.io,HalcyonChimera/osf.io,RomanZWang/osf.io,emetsger/osf.io,mluo613/osf.io,hmoco/osf.io,hmoco/osf.io,RomanZWang/osf.io,emetsger/osf.io,rdhyee/osf.io,mluke93/osf.io,acshi/osf.io,leb2dg/osf.io,zamattiac/osf.io,saradbowman/osf.io,leb2dg/osf.io,pattisdr/osf.io,chennan47/osf.io,acshi/osf.io,cslzchen/osf.io,alexschiller/osf.io,SSJohns/osf.io,chennan47/osf.io,erinspace/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,chrisseto/osf.io,brianjgeiger/osf.io,caseyrollins/osf.io,brianjgeiger/osf.io,alexschiller/osf.io,Nesiehr/osf.io,amyshi188/osf.io,baylee-d/osf.io,CenterForOpenScience/osf.io,erinspace/osf.io,abought/osf.io,wearpants/osf.io,asanfilippo7/osf.io,cslzchen/osf.io,adlius/osf.io,TomHeatwole/osf.io,pattisdr/osf.io,cwisecarver/osf.io,mfraezz/osf.io,caneruguz/osf.io,Johnetordoff/osf.io,doublebits/osf.io,sloria/osf.io
python
## Code Before: # Get an app key and secret at https://www.dropbox.com/developers/apps DROPBOX_KEY = 'changeme' DROPBOX_SECRET = 'changeme' ## Instruction: Add dropbox credentials for testing. ## Code After: # Get an app key and secret at https://www.dropbox.com/developers/apps DROPBOX_KEY = 'jnpncg5s2fc7cj8' DROPBOX_SECRET = 'sjqv1hrk7sonhu1'
# ... existing code ... # Get an app key and secret at https://www.dropbox.com/developers/apps DROPBOX_KEY = 'jnpncg5s2fc7cj8' DROPBOX_SECRET = 'sjqv1hrk7sonhu1' # ... rest of the code ...
aefd972c7fb423396f59da03a1d460cd3559d1e1
duplicate_questions/data/tokenizers/word_tokenizers.py
duplicate_questions/data/tokenizers/word_tokenizers.py
class SpacyWordTokenizer(): """ A Tokenizer splits strings into word tokens. """ def __init__(self): # Import is here it's slow, and can be unnecessary. import spacy self.en_nlp = spacy.load('en') # def tokenize(self, sentence: str) -> List[str]: def tokenize(self, sentence): return [str(token.lower_) for token in self.en_nlp.tokenizer(sentence)] # def get_words_for_indexer(self, text: str) -> List[str]: def get_words_for_indexer(self, text): return self.tokenize(text) # def index_text(self, text: str, data_indexer: DataIndexer) -> List: def index_text(self, text, data_indexer): return [data_indexer.get_word_index(word) for word in self.get_words_for_indexer(text)]
class SpacyWordTokenizer(): """ A Tokenizer splits strings into word tokens. """ def __init__(self): # Import is here it's slow, and can be unnecessary. import spacy self.en_nlp = spacy.load('en') def tokenize(self, sentence): return [str(token.lower_) for token in self.en_nlp.tokenizer(sentence)] def get_words_for_indexer(self, text): return self.tokenize(text) def index_text(self, text, data_indexer): return [data_indexer.get_word_index(word) for word in self.get_words_for_indexer(text)]
Remove unnecesssary comments of old function signatures
Remove unnecesssary comments of old function signatures
Python
mit
nelson-liu/paraphrase-id-tensorflow,nelson-liu/paraphrase-id-tensorflow
python
## Code Before: class SpacyWordTokenizer(): """ A Tokenizer splits strings into word tokens. """ def __init__(self): # Import is here it's slow, and can be unnecessary. import spacy self.en_nlp = spacy.load('en') # def tokenize(self, sentence: str) -> List[str]: def tokenize(self, sentence): return [str(token.lower_) for token in self.en_nlp.tokenizer(sentence)] # def get_words_for_indexer(self, text: str) -> List[str]: def get_words_for_indexer(self, text): return self.tokenize(text) # def index_text(self, text: str, data_indexer: DataIndexer) -> List: def index_text(self, text, data_indexer): return [data_indexer.get_word_index(word) for word in self.get_words_for_indexer(text)] ## Instruction: Remove unnecesssary comments of old function signatures ## Code After: class SpacyWordTokenizer(): """ A Tokenizer splits strings into word tokens. """ def __init__(self): # Import is here it's slow, and can be unnecessary. import spacy self.en_nlp = spacy.load('en') def tokenize(self, sentence): return [str(token.lower_) for token in self.en_nlp.tokenizer(sentence)] def get_words_for_indexer(self, text): return self.tokenize(text) def index_text(self, text, data_indexer): return [data_indexer.get_word_index(word) for word in self.get_words_for_indexer(text)]
... import spacy self.en_nlp = spacy.load('en') def tokenize(self, sentence): return [str(token.lower_) for token in self.en_nlp.tokenizer(sentence)] def get_words_for_indexer(self, text): return self.tokenize(text) def index_text(self, text, data_indexer): return [data_indexer.get_word_index(word) for word in self.get_words_for_indexer(text)] ...
99a1ce2ecee6dd761113515da5c89b8c7da5537f
Python/Algorithm.py
Python/Algorithm.py
class Algorithm: """ Algorithm Class Base class for the page substitution algorithms. """ def __init__(self, input = []): """ Algorithm Constructor. Parameters ---------- input : list A list containing the the input page swap. """ if not input: #If the list is empty throw an exception. raise ValueError("The list must not be empty") #throws the exception. self.blocks = input[0] #Store the page frames size. self.pages = input[1:] #Store the pages to swap. self.missingPages = self.blocks #Count the lack of pages. def removeChuncks(self, list, start, stop): """ Remove a piece of a list. Parameters ---------- list : list The list to delete the elements start : int start point. stop : int stop point. """ del list[start:stop] #Delete range def preparePageFrame(self): """ Prepare the page frames. Returns ------- list The list with initialized Page frames """ pageFrame = [self.pages[x] for x in range(0, self.blocks)] #Create the page frame with elements passed by the user. self.removeChuncks(self.pages, 0, self.blocks) #Remove part of the list that is on the page frame return pageFrame #Return the list
class Algorithm: """ Algorithm Class Base class for the page substitution algorithms. """ def __init__(self, input = []): """ Algorithm Constructor. Parameters ---------- input : list A list containing the the input page swap. """ if not input: #If the list is empty throw an exception. raise ValueError("The list must not be empty") #throws the exception. self.blocks = input[0] #Store the page frames size. self.pages = input[1:] #Store the pages to swap. self.missingPages = self.blocks #Count the lack of pages. def removeChuncks(self, list, start, stop): """ Remove a piece of a list. Parameters ---------- list : list The list to delete the elements start : int start point. stop : int stop point. """ del list[start:stop] #Delete range def preparePageFrame(self): """ Prepare the page frames. Returns ------- list The list with initialized Page frames """ pageFrame = [None] * self.blocks #Create the page frame with elements passed by the user. iterator = 0 for i in range(0, len(self.pages)): if self.pages[i] not in pageFrame: pageFrame[iterator] = self.pages[i] iterator = iterator + 1 if iterator == self.blocks: self.removeChuncks(self.pages, 0, i) #Remove part of the list that is on the page frame break return pageFrame #Return the list
Fix logic error under preparePageFrames
Fix logic error under preparePageFrames
Python
mit
caiomcg/OS-PageSubstitution
python
## Code Before: class Algorithm: """ Algorithm Class Base class for the page substitution algorithms. """ def __init__(self, input = []): """ Algorithm Constructor. Parameters ---------- input : list A list containing the the input page swap. """ if not input: #If the list is empty throw an exception. raise ValueError("The list must not be empty") #throws the exception. self.blocks = input[0] #Store the page frames size. self.pages = input[1:] #Store the pages to swap. self.missingPages = self.blocks #Count the lack of pages. def removeChuncks(self, list, start, stop): """ Remove a piece of a list. Parameters ---------- list : list The list to delete the elements start : int start point. stop : int stop point. """ del list[start:stop] #Delete range def preparePageFrame(self): """ Prepare the page frames. Returns ------- list The list with initialized Page frames """ pageFrame = [self.pages[x] for x in range(0, self.blocks)] #Create the page frame with elements passed by the user. self.removeChuncks(self.pages, 0, self.blocks) #Remove part of the list that is on the page frame return pageFrame #Return the list ## Instruction: Fix logic error under preparePageFrames ## Code After: class Algorithm: """ Algorithm Class Base class for the page substitution algorithms. """ def __init__(self, input = []): """ Algorithm Constructor. Parameters ---------- input : list A list containing the the input page swap. """ if not input: #If the list is empty throw an exception. raise ValueError("The list must not be empty") #throws the exception. self.blocks = input[0] #Store the page frames size. self.pages = input[1:] #Store the pages to swap. self.missingPages = self.blocks #Count the lack of pages. def removeChuncks(self, list, start, stop): """ Remove a piece of a list. Parameters ---------- list : list The list to delete the elements start : int start point. stop : int stop point. """ del list[start:stop] #Delete range def preparePageFrame(self): """ Prepare the page frames. Returns ------- list The list with initialized Page frames """ pageFrame = [None] * self.blocks #Create the page frame with elements passed by the user. iterator = 0 for i in range(0, len(self.pages)): if self.pages[i] not in pageFrame: pageFrame[iterator] = self.pages[i] iterator = iterator + 1 if iterator == self.blocks: self.removeChuncks(self.pages, 0, i) #Remove part of the list that is on the page frame break return pageFrame #Return the list
... list The list with initialized Page frames """ pageFrame = [None] * self.blocks #Create the page frame with elements passed by the user. iterator = 0 for i in range(0, len(self.pages)): if self.pages[i] not in pageFrame: pageFrame[iterator] = self.pages[i] iterator = iterator + 1 if iterator == self.blocks: self.removeChuncks(self.pages, 0, i) #Remove part of the list that is on the page frame break return pageFrame #Return the list ...
d5ad324355e0abdf0a6bdcb41e1f07224742b537
src/main.py
src/main.py
import sys import game import menu menu.init() menu.chooseOption()
import game import menu menu.init() menu.chooseOption()
Remove needless import of sys module
Remove needless import of sys module
Python
mit
TheUnderscores/card-fight-thingy
python
## Code Before: import sys import game import menu menu.init() menu.chooseOption() ## Instruction: Remove needless import of sys module ## Code After: import game import menu menu.init() menu.chooseOption()
... import game import menu ...
546140bee689fc63361977dafa600022396606e7
audio_train.py
audio_train.py
import numpy as np import scipy.io.wavfile from keras.utils.visualize_util import plot from keras.callbacks import TensorBoard, ModelCheckpoint from keras.utils import np_utils from eva.models.wavenet import Wavenet, compute_receptive_field from eva.util.mutil import sparse_labels #%% Data RATE, DATA = scipy.io.wavfile.read('./data/undertale/undertale_001_once_upon_a_time.comp.wav') #%% Model Config. MODEL = Wavenet FILTERS = 256 DEPTH = 7 STACKS = 4 LENGTH = 1 + compute_receptive_field(RATE, DEPTH, STACKS)[0] BINS = 256 LOAD = False #%% Model. INPUT = (LENGTH, BINS) ARGS = (INPUT, FILTERS, DEPTH, STACKS) M = MODEL(*ARGS) if LOAD: M.load_weights('model.h5') M.summary() plot(M) #%% Train. TRAIN = np_utils.to_categorical(DATA, BINS) TRAIN = TRAIN[:TRAIN.shape[0]//LENGTH*LENGTH].reshape(TRAIN.shape[0]//LENGTH, LENGTH, BINS) M.fit(TRAIN, sparse_labels(TRAIN), nb_epoch=2000, batch_size=8, callbacks=[TensorBoard(), ModelCheckpoint('model.h5')])
import numpy as np import scipy.io.wavfile from keras.utils.visualize_util import plot from keras.callbacks import TensorBoard, ModelCheckpoint from keras.utils import np_utils from eva.models.wavenet import Wavenet, compute_receptive_field from eva.util.mutil import sparse_labels #%% Data RATE, DATA = scipy.io.wavfile.read('./data/undertale/undertale_001_once_upon_a_time.comp.wav') #%% Model Config. MODEL = Wavenet FILTERS = 256 DEPTH = 7 STACKS = 4 LENGTH = DATA.shape[0] BINS = 256 LOAD = False #%% Train Config. BATCH_SIZE = 5 EPOCHS = 2000 #%% Model. INPUT = (LENGTH, BINS) ARGS = (INPUT, FILTERS, DEPTH, STACKS) M = MODEL(*ARGS) if LOAD: M.load_weights('model.h5') M.summary() plot(M) #%% Train. TRAIN = np_utils.to_categorical(DATA, BINS) TRAIN = TRAIN.reshape(BATCH_SIZE, TRAIN.shape[0]//BATCH_SIZE, TRAIN.shape[1]) M.fit(TRAIN, sparse_labels(TRAIN), nb_epoch=EPOCHS, batch_size=BATCH_SIZE, callbacks=[TensorBoard(), ModelCheckpoint('model.h5')])
Add train config to audio train
Add train config to audio train
Python
apache-2.0
israelg99/eva
python
## Code Before: import numpy as np import scipy.io.wavfile from keras.utils.visualize_util import plot from keras.callbacks import TensorBoard, ModelCheckpoint from keras.utils import np_utils from eva.models.wavenet import Wavenet, compute_receptive_field from eva.util.mutil import sparse_labels #%% Data RATE, DATA = scipy.io.wavfile.read('./data/undertale/undertale_001_once_upon_a_time.comp.wav') #%% Model Config. MODEL = Wavenet FILTERS = 256 DEPTH = 7 STACKS = 4 LENGTH = 1 + compute_receptive_field(RATE, DEPTH, STACKS)[0] BINS = 256 LOAD = False #%% Model. INPUT = (LENGTH, BINS) ARGS = (INPUT, FILTERS, DEPTH, STACKS) M = MODEL(*ARGS) if LOAD: M.load_weights('model.h5') M.summary() plot(M) #%% Train. TRAIN = np_utils.to_categorical(DATA, BINS) TRAIN = TRAIN[:TRAIN.shape[0]//LENGTH*LENGTH].reshape(TRAIN.shape[0]//LENGTH, LENGTH, BINS) M.fit(TRAIN, sparse_labels(TRAIN), nb_epoch=2000, batch_size=8, callbacks=[TensorBoard(), ModelCheckpoint('model.h5')]) ## Instruction: Add train config to audio train ## Code After: import numpy as np import scipy.io.wavfile from keras.utils.visualize_util import plot from keras.callbacks import TensorBoard, ModelCheckpoint from keras.utils import np_utils from eva.models.wavenet import Wavenet, compute_receptive_field from eva.util.mutil import sparse_labels #%% Data RATE, DATA = scipy.io.wavfile.read('./data/undertale/undertale_001_once_upon_a_time.comp.wav') #%% Model Config. MODEL = Wavenet FILTERS = 256 DEPTH = 7 STACKS = 4 LENGTH = DATA.shape[0] BINS = 256 LOAD = False #%% Train Config. BATCH_SIZE = 5 EPOCHS = 2000 #%% Model. INPUT = (LENGTH, BINS) ARGS = (INPUT, FILTERS, DEPTH, STACKS) M = MODEL(*ARGS) if LOAD: M.load_weights('model.h5') M.summary() plot(M) #%% Train. TRAIN = np_utils.to_categorical(DATA, BINS) TRAIN = TRAIN.reshape(BATCH_SIZE, TRAIN.shape[0]//BATCH_SIZE, TRAIN.shape[1]) M.fit(TRAIN, sparse_labels(TRAIN), nb_epoch=EPOCHS, batch_size=BATCH_SIZE, callbacks=[TensorBoard(), ModelCheckpoint('model.h5')])
# ... existing code ... FILTERS = 256 DEPTH = 7 STACKS = 4 LENGTH = DATA.shape[0] BINS = 256 LOAD = False #%% Train Config. BATCH_SIZE = 5 EPOCHS = 2000 #%% Model. INPUT = (LENGTH, BINS) # ... modified code ... #%% Train. TRAIN = np_utils.to_categorical(DATA, BINS) TRAIN = TRAIN.reshape(BATCH_SIZE, TRAIN.shape[0]//BATCH_SIZE, TRAIN.shape[1]) M.fit(TRAIN, sparse_labels(TRAIN), nb_epoch=EPOCHS, batch_size=BATCH_SIZE, callbacks=[TensorBoard(), ModelCheckpoint('model.h5')]) # ... rest of the code ...
48f23ec383a8a7a26ad7d12abd136d0d00813d89
src/main/kotlin/com/kotlinnlp/simplednn/core/layers/LayerConfiguration.kt
src/main/kotlin/com/kotlinnlp/simplednn/core/layers/LayerConfiguration.kt
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.layers import java.io.Serializable import com.kotlinnlp.simplednn.core.functionalities.activations.ActivationFunction /** * @property meProp whether to use the 'meProp' errors propagation algorithm (params errors are sparse) */ data class LayerConfiguration( val size: Int, val inputType: LayerType.Input = LayerType.Input.Dense, val connectionType: LayerType.Connection? = null, val activationFunction: ActivationFunction? = null, val meProp: Boolean = false, val dropout: Double = 0.0 ) : Serializable { companion object { /** * Private val used to serialize the class (needed from Serializable) */ @Suppress("unused") private const val serialVersionUID: Long = 1L } }
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.layers import java.io.Serializable import com.kotlinnlp.simplednn.core.functionalities.activations.ActivationFunction /** * The configuration of a Layer. * * @param size size of the unique array of this layer (meaningless if this is the input of a Merge layer) * @param sizes the list of sizes of the arrays in this layer * @param inputType the type of the arrays in this layer * @param connectionType the type of connection with the layer before (meaningless in case of first layer) * @param activationFunction the activation function * @param dropout the probability of dropout (default 0.0). If applying it, the usual value is 0.5 (better 0.25 if * it's the first layer). * @property meProp whether to use the 'meProp' errors propagation algorithm (params errors are sparse) */ data class LayerConfiguration( val size: Int = -1, val sizes: List<Int> = listOf(size), val inputType: LayerType.Input = LayerType.Input.Dense, val connectionType: LayerType.Connection? = null, val activationFunction: ActivationFunction? = null, val meProp: Boolean = false, val dropout: Double = 0.0 ) : Serializable { companion object { /** * Private val used to serialize the class (needed by Serializable). */ @Suppress("unused") private const val serialVersionUID: Long = 1L } }
Add 'sizes' property, in case of Merge layers
Add 'sizes' property, in case of Merge layers
Kotlin
mpl-2.0
KotlinNLP/SimpleDNN
kotlin
## Code Before: /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.layers import java.io.Serializable import com.kotlinnlp.simplednn.core.functionalities.activations.ActivationFunction /** * @property meProp whether to use the 'meProp' errors propagation algorithm (params errors are sparse) */ data class LayerConfiguration( val size: Int, val inputType: LayerType.Input = LayerType.Input.Dense, val connectionType: LayerType.Connection? = null, val activationFunction: ActivationFunction? = null, val meProp: Boolean = false, val dropout: Double = 0.0 ) : Serializable { companion object { /** * Private val used to serialize the class (needed from Serializable) */ @Suppress("unused") private const val serialVersionUID: Long = 1L } } ## Instruction: Add 'sizes' property, in case of Merge layers ## Code After: /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.layers import java.io.Serializable import com.kotlinnlp.simplednn.core.functionalities.activations.ActivationFunction /** * The configuration of a Layer. * * @param size size of the unique array of this layer (meaningless if this is the input of a Merge layer) * @param sizes the list of sizes of the arrays in this layer * @param inputType the type of the arrays in this layer * @param connectionType the type of connection with the layer before (meaningless in case of first layer) * @param activationFunction the activation function * @param dropout the probability of dropout (default 0.0). If applying it, the usual value is 0.5 (better 0.25 if * it's the first layer). * @property meProp whether to use the 'meProp' errors propagation algorithm (params errors are sparse) */ data class LayerConfiguration( val size: Int = -1, val sizes: List<Int> = listOf(size), val inputType: LayerType.Input = LayerType.Input.Dense, val connectionType: LayerType.Connection? = null, val activationFunction: ActivationFunction? = null, val meProp: Boolean = false, val dropout: Double = 0.0 ) : Serializable { companion object { /** * Private val used to serialize the class (needed by Serializable). */ @Suppress("unused") private const val serialVersionUID: Long = 1L } }
... import com.kotlinnlp.simplednn.core.functionalities.activations.ActivationFunction /** * The configuration of a Layer. * * @param size size of the unique array of this layer (meaningless if this is the input of a Merge layer) * @param sizes the list of sizes of the arrays in this layer * @param inputType the type of the arrays in this layer * @param connectionType the type of connection with the layer before (meaningless in case of first layer) * @param activationFunction the activation function * @param dropout the probability of dropout (default 0.0). If applying it, the usual value is 0.5 (better 0.25 if * it's the first layer). * @property meProp whether to use the 'meProp' errors propagation algorithm (params errors are sparse) */ data class LayerConfiguration( val size: Int = -1, val sizes: List<Int> = listOf(size), val inputType: LayerType.Input = LayerType.Input.Dense, val connectionType: LayerType.Connection? = null, val activationFunction: ActivationFunction? = null, ... companion object { /** * Private val used to serialize the class (needed by Serializable). */ @Suppress("unused") private const val serialVersionUID: Long = 1L ...
1b5fc874924958664797ba2f1e73835b4cbcef57
mfr/__init__.py
mfr/__init__.py
"""The mfr core module.""" # -*- coding: utf-8 -*- import os __version__ = '0.1.0-alpha' __author__ = 'Center for Open Science' from mfr.core import (render, detect, FileHandler, get_file_extension, register_filehandler, export, get_file_exporters, config, collect_static ) from mfr._config import Config PACKAGE_DIR = os.path.abspath(os.path.dirname(__file__))
"""The mfr core module.""" # -*- coding: utf-8 -*- import os __version__ = '0.1.0-alpha' __author__ = 'Center for Open Science' from mfr.core import ( render, detect, FileHandler, get_file_extension, register_filehandler, export, get_file_exporters, config, collect_static, RenderResult, ) from mfr._config import Config PACKAGE_DIR = os.path.abspath(os.path.dirname(__file__))
Add RenderResult to mfr namespace
Add RenderResult to mfr namespace
Python
apache-2.0
TomBaxter/modular-file-renderer,chrisseto/modular-file-renderer,mfraezz/modular-file-renderer,haoyuchen1992/modular-file-renderer,haoyuchen1992/modular-file-renderer,erinspace/modular-file-renderer,rdhyee/modular-file-renderer,CenterForOpenScience/modular-file-renderer,icereval/modular-file-renderer,TomBaxter/modular-file-renderer,erinspace/modular-file-renderer,Johnetordoff/modular-file-renderer,TomBaxter/modular-file-renderer,AddisonSchiller/modular-file-renderer,AddisonSchiller/modular-file-renderer,icereval/modular-file-renderer,Johnetordoff/modular-file-renderer,haoyuchen1992/modular-file-renderer,felliott/modular-file-renderer,Johnetordoff/modular-file-renderer,chrisseto/modular-file-renderer,felliott/modular-file-renderer,icereval/modular-file-renderer,CenterForOpenScience/modular-file-renderer,felliott/modular-file-renderer,haoyuchen1992/modular-file-renderer,mfraezz/modular-file-renderer,mfraezz/modular-file-renderer,mfraezz/modular-file-renderer,chrisseto/modular-file-renderer,AddisonSchiller/modular-file-renderer,rdhyee/modular-file-renderer,AddisonSchiller/modular-file-renderer,CenterForOpenScience/modular-file-renderer,erinspace/modular-file-renderer,rdhyee/modular-file-renderer,CenterForOpenScience/modular-file-renderer,Johnetordoff/modular-file-renderer,felliott/modular-file-renderer,TomBaxter/modular-file-renderer,rdhyee/modular-file-renderer
python
## Code Before: """The mfr core module.""" # -*- coding: utf-8 -*- import os __version__ = '0.1.0-alpha' __author__ = 'Center for Open Science' from mfr.core import (render, detect, FileHandler, get_file_extension, register_filehandler, export, get_file_exporters, config, collect_static ) from mfr._config import Config PACKAGE_DIR = os.path.abspath(os.path.dirname(__file__)) ## Instruction: Add RenderResult to mfr namespace ## Code After: """The mfr core module.""" # -*- coding: utf-8 -*- import os __version__ = '0.1.0-alpha' __author__ = 'Center for Open Science' from mfr.core import ( render, detect, FileHandler, get_file_extension, register_filehandler, export, get_file_exporters, config, collect_static, RenderResult, ) from mfr._config import Config PACKAGE_DIR = os.path.abspath(os.path.dirname(__file__))
# ... existing code ... __author__ = 'Center for Open Science' from mfr.core import ( render, detect, FileHandler, get_file_extension, register_filehandler, export, get_file_exporters, config, collect_static, RenderResult, ) from mfr._config import Config # ... rest of the code ...
6b0167514bb41f877945b408638fab72873f2da8
postgres_copy/__init__.py
postgres_copy/__init__.py
from django.db import models from django.db import connection from .copy_from import CopyMapping from .copy_to import SQLCopyToCompiler, CopyToQuery __version__ = '2.0.0' class CopyQuerySet(models.QuerySet): """ Subclass of QuerySet that adds from_csv and to_csv methods. """ def from_csv(self, csv_path, mapping, **kwargs): """ Copy CSV file from the provided path to the current model using the provided mapping. """ mapping = CopyMapping(self.model, csv_path, mapping, **kwargs) mapping.save(silent=True) def to_csv(self, csv_path, *fields): """ Copy current QuerySet to CSV at provided path. """ query = self.query.clone(CopyToQuery) query.copy_to_fields = fields compiler = query.get_compiler(self.db, connection=connection) compiler.execute_sql(csv_path) CopyManager = models.Manager.from_queryset(CopyQuerySet) __all__ = ( 'CopyMapping', 'SQLCopyToCompiler', 'CopyToQuery', 'CopyManager', )
from django.db import models from django.db import connection from .copy_from import CopyMapping from .copy_to import SQLCopyToCompiler, CopyToQuery __version__ = '2.0.0' class CopyQuerySet(models.QuerySet): """ Subclass of QuerySet that adds from_csv and to_csv methods. """ def from_csv(self, csv_path, mapping, **kwargs): """ Copy CSV file from the provided path to the current model using the provided mapping. """ mapping = CopyMapping(self.model, csv_path, mapping, **kwargs) mapping.save(silent=True) def to_csv(self, csv_path, *fields): """ Copy current QuerySet to CSV at provided path. """ query = self.query.clone(CopyToQuery) query.copy_to_fields = fields compiler = query.get_compiler(self.db, connection=connection) compiler.execute_sql(csv_path) CopyManager = models.Manager.from_queryset(CopyQuerySet) __all__ = ( 'CopyManager', 'CopyMapping', 'CopyToQuery', 'CopyToQuerySet', 'SQLCopyToCompiler', )
Add CopyToQuerySet to available imports
Add CopyToQuerySet to available imports
Python
mit
california-civic-data-coalition/django-postgres-copy
python
## Code Before: from django.db import models from django.db import connection from .copy_from import CopyMapping from .copy_to import SQLCopyToCompiler, CopyToQuery __version__ = '2.0.0' class CopyQuerySet(models.QuerySet): """ Subclass of QuerySet that adds from_csv and to_csv methods. """ def from_csv(self, csv_path, mapping, **kwargs): """ Copy CSV file from the provided path to the current model using the provided mapping. """ mapping = CopyMapping(self.model, csv_path, mapping, **kwargs) mapping.save(silent=True) def to_csv(self, csv_path, *fields): """ Copy current QuerySet to CSV at provided path. """ query = self.query.clone(CopyToQuery) query.copy_to_fields = fields compiler = query.get_compiler(self.db, connection=connection) compiler.execute_sql(csv_path) CopyManager = models.Manager.from_queryset(CopyQuerySet) __all__ = ( 'CopyMapping', 'SQLCopyToCompiler', 'CopyToQuery', 'CopyManager', ) ## Instruction: Add CopyToQuerySet to available imports ## Code After: from django.db import models from django.db import connection from .copy_from import CopyMapping from .copy_to import SQLCopyToCompiler, CopyToQuery __version__ = '2.0.0' class CopyQuerySet(models.QuerySet): """ Subclass of QuerySet that adds from_csv and to_csv methods. """ def from_csv(self, csv_path, mapping, **kwargs): """ Copy CSV file from the provided path to the current model using the provided mapping. """ mapping = CopyMapping(self.model, csv_path, mapping, **kwargs) mapping.save(silent=True) def to_csv(self, csv_path, *fields): """ Copy current QuerySet to CSV at provided path. """ query = self.query.clone(CopyToQuery) query.copy_to_fields = fields compiler = query.get_compiler(self.db, connection=connection) compiler.execute_sql(csv_path) CopyManager = models.Manager.from_queryset(CopyQuerySet) __all__ = ( 'CopyManager', 'CopyMapping', 'CopyToQuery', 'CopyToQuerySet', 'SQLCopyToCompiler', )
... __all__ = ( 'CopyManager', 'CopyMapping', 'CopyToQuery', 'CopyToQuerySet', 'SQLCopyToCompiler', ) ...
b88d2ed943228647065ff6ac8154cc35099ab9ea
src/main/java/li/l1t/tingo/TingoErrorController.java
src/main/java/li/l1t/tingo/TingoErrorController.java
package li.l1t.tingo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.web.ErrorAttributes; import org.springframework.boot.autoconfigure.web.ErrorController; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; /** * Controls displaying of error messages. * * @author <a href="http://xxyy.github.io/">xxyy</a> * @since 7.4.16 */ @Controller public class TingoErrorController implements ErrorController { private static final String ERROR_PATH = "/error"; @Autowired private ErrorAttributes errorAttributes; @Override public String getErrorPath() { return ERROR_PATH; } @RequestMapping(value = ERROR_PATH) public String errorHtml(HttpServletRequest request, Model model) { Object errCodeObj = request.getAttribute("javax.servlet.error.status_code"); int errorCode = errCodeObj == null ? 0 : (int) errCodeObj; model.addAttribute("errorCode", errCodeObj); model.addAttribute("errorType", request.getAttribute("javax.servlet.error.exception")); switch(errorCode) { case 401: return "error/401.html"; case 0: default: return "error/generic.html"; } } }
package li.l1t.tingo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.web.ErrorAttributes; import org.springframework.boot.autoconfigure.web.ErrorController; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; /** * Controls displaying of error messages. * * @author <a href="http://xxyy.github.io/">xxyy</a> * @since 7.4.16 */ @Controller public class TingoErrorController implements ErrorController { private static final String ERROR_PATH = "/error"; @Autowired private ErrorAttributes errorAttributes; @Override public String getErrorPath() { return ERROR_PATH; } @RequestMapping(value = ERROR_PATH) public String errorHtml(HttpServletRequest request, Model model) { Object errCodeObj = request.getAttribute("javax.servlet.error.status_code"); int errorCode = errCodeObj == null ? 0 : (int) errCodeObj; model.addAttribute("errorCode", errCodeObj); model.addAttribute("errorType", request.getAttribute("javax.servlet.error.exception")); switch(errorCode) { case 401: return "error/401"; case 0: default: return "error/generic"; } } }
Fix wrong template usage in error pages
Fix wrong template usage in error pages
Java
apache-2.0
xxyy/tingo,xxyy/sic,xxyy/sic,xxyy/sic,xxyy/tingo,xxyy/tingo
java
## Code Before: package li.l1t.tingo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.web.ErrorAttributes; import org.springframework.boot.autoconfigure.web.ErrorController; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; /** * Controls displaying of error messages. * * @author <a href="http://xxyy.github.io/">xxyy</a> * @since 7.4.16 */ @Controller public class TingoErrorController implements ErrorController { private static final String ERROR_PATH = "/error"; @Autowired private ErrorAttributes errorAttributes; @Override public String getErrorPath() { return ERROR_PATH; } @RequestMapping(value = ERROR_PATH) public String errorHtml(HttpServletRequest request, Model model) { Object errCodeObj = request.getAttribute("javax.servlet.error.status_code"); int errorCode = errCodeObj == null ? 0 : (int) errCodeObj; model.addAttribute("errorCode", errCodeObj); model.addAttribute("errorType", request.getAttribute("javax.servlet.error.exception")); switch(errorCode) { case 401: return "error/401.html"; case 0: default: return "error/generic.html"; } } } ## Instruction: Fix wrong template usage in error pages ## Code After: package li.l1t.tingo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.web.ErrorAttributes; import org.springframework.boot.autoconfigure.web.ErrorController; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; /** * Controls displaying of error messages. * * @author <a href="http://xxyy.github.io/">xxyy</a> * @since 7.4.16 */ @Controller public class TingoErrorController implements ErrorController { private static final String ERROR_PATH = "/error"; @Autowired private ErrorAttributes errorAttributes; @Override public String getErrorPath() { return ERROR_PATH; } @RequestMapping(value = ERROR_PATH) public String errorHtml(HttpServletRequest request, Model model) { Object errCodeObj = request.getAttribute("javax.servlet.error.status_code"); int errorCode = errCodeObj == null ? 0 : (int) errCodeObj; model.addAttribute("errorCode", errCodeObj); model.addAttribute("errorType", request.getAttribute("javax.servlet.error.exception")); switch(errorCode) { case 401: return "error/401"; case 0: default: return "error/generic"; } } }
// ... existing code ... switch(errorCode) { case 401: return "error/401"; case 0: default: return "error/generic"; } } } // ... rest of the code ...
ac00ef4ac08c6e47de80c33a6781d00c7b2bc943
flask_sockets.py
flask_sockets.py
def log_request(self): log = self.server.log if log: if hasattr(log, 'info'): log.info(self.format_request() + '\n') else: log.write(self.format_request() + '\n') # Monkeys are made for freedom. try: import gevent from geventwebsocket.gunicorn.workers import GeventWebSocketWorker as Worker except ImportError: pass if 'gevent' in locals(): # Freedom-Patch logger for Gunicorn. if hasattr(gevent, 'pywsgi'): gevent.pywsgi.WSGIHandler.log_request = log_request class SocketMiddleware(object): def __init__(self, wsgi_app, socket): self.ws = socket self.app = wsgi_app def __call__(self, environ, start_response): path = environ['PATH_INFO'] if path in self.ws.url_map: handler = self.ws.url_map[path] environment = environ['wsgi.websocket'] handler(environment) else: return self.app(environ, start_response) class Sockets(object): def __init__(self, app=None): self.url_map = {} if app: self.init_app(app) def init_app(self, app): app.wsgi_app = SocketMiddleware(app.wsgi_app, self) def route(self, rule, **options): def decorator(f): endpoint = options.pop('endpoint', None) self.add_url_rule(rule, endpoint, f, **options) return f return decorator def add_url_rule(self, rule, _, f, **options): self.url_map[rule] = f # CLI sugar. if 'Worker' in locals(): worker = Worker
from functools import wraps from flask import request def log_request(self): log = self.server.log if log: if hasattr(log, 'info'): log.info(self.format_request() + '\n') else: log.write(self.format_request() + '\n') # Monkeys are made for freedom. try: import gevent from geventwebsocket.gunicorn.workers import GeventWebSocketWorker as Worker except ImportError: pass if 'gevent' in locals(): # Freedom-Patch logger for Gunicorn. if hasattr(gevent, 'pywsgi'): gevent.pywsgi.WSGIHandler.log_request = log_request class Sockets(object): def __init__(self, app=None): self.app = app def route(self, rule, **options): def decorator(f): @wraps(f) def inner(*args, **kwargs): return f(request.environ['wsgi.websocket'], *args, **kwargs) if self.app: endpoint = options.pop('endpoint', None) self.app.add_url_rule(rule, endpoint, inner, **options) return inner return decorator # CLI sugar. if 'Worker' in locals(): worker = Worker
Use Flask routing to allow for variables in URL
Use Flask routing to allow for variables in URL
Python
mit
clarkduvall/flask-sockets
python
## Code Before: def log_request(self): log = self.server.log if log: if hasattr(log, 'info'): log.info(self.format_request() + '\n') else: log.write(self.format_request() + '\n') # Monkeys are made for freedom. try: import gevent from geventwebsocket.gunicorn.workers import GeventWebSocketWorker as Worker except ImportError: pass if 'gevent' in locals(): # Freedom-Patch logger for Gunicorn. if hasattr(gevent, 'pywsgi'): gevent.pywsgi.WSGIHandler.log_request = log_request class SocketMiddleware(object): def __init__(self, wsgi_app, socket): self.ws = socket self.app = wsgi_app def __call__(self, environ, start_response): path = environ['PATH_INFO'] if path in self.ws.url_map: handler = self.ws.url_map[path] environment = environ['wsgi.websocket'] handler(environment) else: return self.app(environ, start_response) class Sockets(object): def __init__(self, app=None): self.url_map = {} if app: self.init_app(app) def init_app(self, app): app.wsgi_app = SocketMiddleware(app.wsgi_app, self) def route(self, rule, **options): def decorator(f): endpoint = options.pop('endpoint', None) self.add_url_rule(rule, endpoint, f, **options) return f return decorator def add_url_rule(self, rule, _, f, **options): self.url_map[rule] = f # CLI sugar. if 'Worker' in locals(): worker = Worker ## Instruction: Use Flask routing to allow for variables in URL ## Code After: from functools import wraps from flask import request def log_request(self): log = self.server.log if log: if hasattr(log, 'info'): log.info(self.format_request() + '\n') else: log.write(self.format_request() + '\n') # Monkeys are made for freedom. try: import gevent from geventwebsocket.gunicorn.workers import GeventWebSocketWorker as Worker except ImportError: pass if 'gevent' in locals(): # Freedom-Patch logger for Gunicorn. if hasattr(gevent, 'pywsgi'): gevent.pywsgi.WSGIHandler.log_request = log_request class Sockets(object): def __init__(self, app=None): self.app = app def route(self, rule, **options): def decorator(f): @wraps(f) def inner(*args, **kwargs): return f(request.environ['wsgi.websocket'], *args, **kwargs) if self.app: endpoint = options.pop('endpoint', None) self.app.add_url_rule(rule, endpoint, inner, **options) return inner return decorator # CLI sugar. if 'Worker' in locals(): worker = Worker
// ... existing code ... from functools import wraps from flask import request def log_request(self): log = self.server.log // ... modified code ... if hasattr(gevent, 'pywsgi'): gevent.pywsgi.WSGIHandler.log_request = log_request class Sockets(object): def __init__(self, app=None): self.app = app def route(self, rule, **options): def decorator(f): @wraps(f) def inner(*args, **kwargs): return f(request.environ['wsgi.websocket'], *args, **kwargs) if self.app: endpoint = options.pop('endpoint', None) self.app.add_url_rule(rule, endpoint, inner, **options) return inner return decorator # CLI sugar. if 'Worker' in locals(): // ... rest of the code ...
4b354f806d28c663646b3201414158a3c822bde0
src/main/java/us/myles/ViaVersion/protocols/protocol1_9to1_8/listeners/BlockListener.java
src/main/java/us/myles/ViaVersion/protocols/protocol1_9to1_8/listeners/BlockListener.java
package us.myles.ViaVersion.protocols.protocol1_9to1_8.listeners; import lombok.RequiredArgsConstructor; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockPlaceEvent; import us.myles.ViaVersion.ViaVersionPlugin; import us.myles.ViaVersion.api.minecraft.Position; import us.myles.ViaVersion.protocols.protocol1_9to1_8.storage.EntityTracker; @RequiredArgsConstructor public class BlockListener implements Listener{ private final ViaVersionPlugin plugin; @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void placeBlock(BlockPlaceEvent e) { if(plugin.isPorted(e.getPlayer())) { Block b = e.getBlockPlaced(); plugin.getConnection(e.getPlayer()).get(EntityTracker.class).addBlockInteraction(new Position((long)b.getX(), (long)b.getY(), (long)b.getZ())); } } }
package us.myles.ViaVersion.protocols.protocol1_9to1_8.listeners; import lombok.RequiredArgsConstructor; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockPlaceEvent; import us.myles.ViaVersion.ViaVersionPlugin; import us.myles.ViaVersion.api.data.UserConnection; import us.myles.ViaVersion.api.minecraft.Position; import us.myles.ViaVersion.protocols.base.ProtocolInfo; import us.myles.ViaVersion.protocols.protocol1_9to1_8.Protocol1_9TO1_8; import us.myles.ViaVersion.protocols.protocol1_9to1_8.storage.EntityTracker; @RequiredArgsConstructor public class BlockListener implements Listener { private final ViaVersionPlugin plugin; @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void placeBlock(BlockPlaceEvent e) { if(plugin.isPorted(e.getPlayer())) { UserConnection c = plugin.getConnection(e.getPlayer()); if (!c.get(ProtocolInfo.class).getPipeline().contains(Protocol1_9TO1_8.class)) return; Block b = e.getBlockPlaced(); plugin.getConnection(e.getPlayer()).get(EntityTracker.class).addBlockInteraction(new Position((long) b.getX(), (long) b.getY(), (long) b.getZ())); } } }
Check if user is indeed using 1.9 to 1.8 protocol conversion
Check if user is indeed using 1.9 to 1.8 protocol conversion
Java
mit
MylesIsCool/ViaVersion,Matsv/ViaVersion
java
## Code Before: package us.myles.ViaVersion.protocols.protocol1_9to1_8.listeners; import lombok.RequiredArgsConstructor; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockPlaceEvent; import us.myles.ViaVersion.ViaVersionPlugin; import us.myles.ViaVersion.api.minecraft.Position; import us.myles.ViaVersion.protocols.protocol1_9to1_8.storage.EntityTracker; @RequiredArgsConstructor public class BlockListener implements Listener{ private final ViaVersionPlugin plugin; @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void placeBlock(BlockPlaceEvent e) { if(plugin.isPorted(e.getPlayer())) { Block b = e.getBlockPlaced(); plugin.getConnection(e.getPlayer()).get(EntityTracker.class).addBlockInteraction(new Position((long)b.getX(), (long)b.getY(), (long)b.getZ())); } } } ## Instruction: Check if user is indeed using 1.9 to 1.8 protocol conversion ## Code After: package us.myles.ViaVersion.protocols.protocol1_9to1_8.listeners; import lombok.RequiredArgsConstructor; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockPlaceEvent; import us.myles.ViaVersion.ViaVersionPlugin; import us.myles.ViaVersion.api.data.UserConnection; import us.myles.ViaVersion.api.minecraft.Position; import us.myles.ViaVersion.protocols.base.ProtocolInfo; import us.myles.ViaVersion.protocols.protocol1_9to1_8.Protocol1_9TO1_8; import us.myles.ViaVersion.protocols.protocol1_9to1_8.storage.EntityTracker; @RequiredArgsConstructor public class BlockListener implements Listener { private final ViaVersionPlugin plugin; @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void placeBlock(BlockPlaceEvent e) { if(plugin.isPorted(e.getPlayer())) { UserConnection c = plugin.getConnection(e.getPlayer()); if (!c.get(ProtocolInfo.class).getPipeline().contains(Protocol1_9TO1_8.class)) return; Block b = e.getBlockPlaced(); plugin.getConnection(e.getPlayer()).get(EntityTracker.class).addBlockInteraction(new Position((long) b.getX(), (long) b.getY(), (long) b.getZ())); } } }
// ... existing code ... import org.bukkit.event.Listener; import org.bukkit.event.block.BlockPlaceEvent; import us.myles.ViaVersion.ViaVersionPlugin; import us.myles.ViaVersion.api.data.UserConnection; import us.myles.ViaVersion.api.minecraft.Position; import us.myles.ViaVersion.protocols.base.ProtocolInfo; import us.myles.ViaVersion.protocols.protocol1_9to1_8.Protocol1_9TO1_8; import us.myles.ViaVersion.protocols.protocol1_9to1_8.storage.EntityTracker; @RequiredArgsConstructor public class BlockListener implements Listener { private final ViaVersionPlugin plugin; // ... modified code ... @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void placeBlock(BlockPlaceEvent e) { if(plugin.isPorted(e.getPlayer())) { UserConnection c = plugin.getConnection(e.getPlayer()); if (!c.get(ProtocolInfo.class).getPipeline().contains(Protocol1_9TO1_8.class)) return; Block b = e.getBlockPlaced(); plugin.getConnection(e.getPlayer()).get(EntityTracker.class).addBlockInteraction(new Position((long) b.getX(), (long) b.getY(), (long) b.getZ())); } } } // ... rest of the code ...
3f635db216c292c0eec720d28ecfbec3e23f1ca5
ynr/s3_storage.py
ynr/s3_storage.py
from storages.backends.s3boto3 import S3Boto3Storage from django.contrib.staticfiles.storage import ManifestFilesMixin from pipeline.storage import PipelineMixin from django.conf import settings class StaticStorage(PipelineMixin, ManifestFilesMixin, S3Boto3Storage): """ Store static files on S3 at STATICFILES_LOCATION, post-process with pipeline and then create manifest files for them. """ location = settings.STATICFILES_LOCATION class MediaStorage(S3Boto3Storage): """ Store media files on S3 at MEDIAFILES_LOCATION """ location = settings.MEDIAFILES_LOCATION @property def base_url(self): """ This is a small hack around the fact that Django Storages dosn't provide the same methods as FileSystemStorage. `base_url` is missing from their implementation of the storage class, so we emulate it here by calling URL with an empty key name. """ return self.url("")
import os from storages.backends.s3boto3 import S3Boto3Storage, SpooledTemporaryFile from django.contrib.staticfiles.storage import ManifestFilesMixin from pipeline.storage import PipelineMixin from django.conf import settings class PatchedS3Boto3Storage(S3Boto3Storage): def _save_content(self, obj, content, parameters): """ We create a clone of the content file as when this is passed to boto3 it wrongly closes the file upon upload where as the storage backend expects it to still be open """ # Seek our content back to the start content.seek(0, os.SEEK_SET) # Create a temporary file that will write to disk after a specified # size content_autoclose = SpooledTemporaryFile() # Write our original content into our copy that will be closed by boto3 content_autoclose.write(content.read()) # Upload the object which will auto close the content_autoclose # instance super()._save_content(obj, content_autoclose, parameters) # Cleanup if this is fixed upstream our duplicate should always close if not content_autoclose.closed: content_autoclose.close() class StaticStorage(PipelineMixin, ManifestFilesMixin, PatchedS3Boto3Storage): """ Store static files on S3 at STATICFILES_LOCATION, post-process with pipeline and then create manifest files for them. """ location = settings.STATICFILES_LOCATION class MediaStorage(PatchedS3Boto3Storage): """ Store media files on S3 at MEDIAFILES_LOCATION """ location = settings.MEDIAFILES_LOCATION @property def base_url(self): """ This is a small hack around the fact that Django Storages dosn't provide the same methods as FileSystemStorage. `base_url` is missing from their implementation of the storage class, so we emulate it here by calling URL with an empty key name. """ return self.url("")
Patch S3Boto3Storage to prevent closed file error when collectin static
Patch S3Boto3Storage to prevent closed file error when collectin static This is copied from the aggregator API and prevents a bug where the storage closes the files too early, raising a boto exception.
Python
agpl-3.0
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
python
## Code Before: from storages.backends.s3boto3 import S3Boto3Storage from django.contrib.staticfiles.storage import ManifestFilesMixin from pipeline.storage import PipelineMixin from django.conf import settings class StaticStorage(PipelineMixin, ManifestFilesMixin, S3Boto3Storage): """ Store static files on S3 at STATICFILES_LOCATION, post-process with pipeline and then create manifest files for them. """ location = settings.STATICFILES_LOCATION class MediaStorage(S3Boto3Storage): """ Store media files on S3 at MEDIAFILES_LOCATION """ location = settings.MEDIAFILES_LOCATION @property def base_url(self): """ This is a small hack around the fact that Django Storages dosn't provide the same methods as FileSystemStorage. `base_url` is missing from their implementation of the storage class, so we emulate it here by calling URL with an empty key name. """ return self.url("") ## Instruction: Patch S3Boto3Storage to prevent closed file error when collectin static This is copied from the aggregator API and prevents a bug where the storage closes the files too early, raising a boto exception. ## Code After: import os from storages.backends.s3boto3 import S3Boto3Storage, SpooledTemporaryFile from django.contrib.staticfiles.storage import ManifestFilesMixin from pipeline.storage import PipelineMixin from django.conf import settings class PatchedS3Boto3Storage(S3Boto3Storage): def _save_content(self, obj, content, parameters): """ We create a clone of the content file as when this is passed to boto3 it wrongly closes the file upon upload where as the storage backend expects it to still be open """ # Seek our content back to the start content.seek(0, os.SEEK_SET) # Create a temporary file that will write to disk after a specified # size content_autoclose = SpooledTemporaryFile() # Write our original content into our copy that will be closed by boto3 content_autoclose.write(content.read()) # Upload the object which will auto close the content_autoclose # instance super()._save_content(obj, content_autoclose, parameters) # Cleanup if this is fixed upstream our duplicate should always close if not content_autoclose.closed: content_autoclose.close() class StaticStorage(PipelineMixin, ManifestFilesMixin, PatchedS3Boto3Storage): """ Store static files on S3 at STATICFILES_LOCATION, post-process with pipeline and then create manifest files for them. """ location = settings.STATICFILES_LOCATION class MediaStorage(PatchedS3Boto3Storage): """ Store media files on S3 at MEDIAFILES_LOCATION """ location = settings.MEDIAFILES_LOCATION @property def base_url(self): """ This is a small hack around the fact that Django Storages dosn't provide the same methods as FileSystemStorage. `base_url` is missing from their implementation of the storage class, so we emulate it here by calling URL with an empty key name. """ return self.url("")
# ... existing code ... import os from storages.backends.s3boto3 import S3Boto3Storage, SpooledTemporaryFile from django.contrib.staticfiles.storage import ManifestFilesMixin from pipeline.storage import PipelineMixin # ... modified code ... from django.conf import settings class PatchedS3Boto3Storage(S3Boto3Storage): def _save_content(self, obj, content, parameters): """ We create a clone of the content file as when this is passed to boto3 it wrongly closes the file upon upload where as the storage backend expects it to still be open """ # Seek our content back to the start content.seek(0, os.SEEK_SET) # Create a temporary file that will write to disk after a specified # size content_autoclose = SpooledTemporaryFile() # Write our original content into our copy that will be closed by boto3 content_autoclose.write(content.read()) # Upload the object which will auto close the content_autoclose # instance super()._save_content(obj, content_autoclose, parameters) # Cleanup if this is fixed upstream our duplicate should always close if not content_autoclose.closed: content_autoclose.close() class StaticStorage(PipelineMixin, ManifestFilesMixin, PatchedS3Boto3Storage): """ Store static files on S3 at STATICFILES_LOCATION, post-process with pipeline and then create manifest files for them. ... location = settings.STATICFILES_LOCATION class MediaStorage(PatchedS3Boto3Storage): """ Store media files on S3 at MEDIAFILES_LOCATION """ # ... rest of the code ...
e170666cbbc1f2a61c0ffa077c66da4556a6c5bb
app/packages/views.py
app/packages/views.py
import requests from . import packages from models import Package, Downloads from flask import jsonify from datetime import timedelta from app import cache from utils import cache_timeout @packages.route('/stats', methods=['GET']) @cache_timeout @cache.cached() def stats(): resp = dict() resp["count"] = Package.get_count() resp["day"] = Downloads.get_overall_downloads_count(timedelta(days=1)) resp["week"] = Downloads.get_overall_downloads_count(timedelta(days=7)) resp["month"] = Downloads.get_overall_downloads_count(timedelta(days=30)) return jsonify(resp) @packages.route('/featured', methods=['GET']) @cache_timeout @cache.cached() def featured(): package_list = requests.get("https://atom.io/api/packages/featured") theme_list = requests.get("https://atom.io/api/themes/featured") featured_list = package_list.json() + theme_list.json() # limit data to multiples of three length = (len(featured_list) / 3) * 3 featured_list = featured_list[:length] json_data = [] for item in featured_list: obj = Package.get_package(item['name']) if obj is not None: json_data.append(obj.get_json()) return jsonify(results=json_data)
import requests from . import packages from models import Package, Downloads from flask import jsonify from datetime import timedelta from app import cache from utils import cache_timeout @packages.route('/stats', methods=['GET']) @cache_timeout @cache.cached() def stats(): resp = dict() resp["count"] = Package.get_count() resp["day"] = Downloads.get_overall_downloads_count(timedelta(days=1)) resp["week"] = Downloads.get_overall_downloads_count(timedelta(days=7)) resp["month"] = Downloads.get_overall_downloads_count(timedelta(days=30)) return jsonify(resp) @packages.route('/featured', methods=['GET']) @cache_timeout @cache.cached() def featured(): package_list = requests.get("https://atom.io/api/packages/featured") theme_list = requests.get("https://atom.io/api/themes/featured") featured_list = package_list.json() + theme_list.json() # limit data to multiples of three length = ((len(featured_list) + 2) / 3) * 3 featured_list = featured_list[:(length - 2)] json_data = [] for item in featured_list: obj = Package.get_package(item['name']) if obj is not None: json_data.append(obj.get_json()) for item in ["docblockr", "git-log"]: obj = Package.get_package(item) json_data.append(obj.get_json()) return jsonify(results=json_data)
Add my packages to featured list
Add my packages to featured list
Python
bsd-2-clause
NikhilKalige/atom-website,NikhilKalige/atom-website,NikhilKalige/atom-website
python
## Code Before: import requests from . import packages from models import Package, Downloads from flask import jsonify from datetime import timedelta from app import cache from utils import cache_timeout @packages.route('/stats', methods=['GET']) @cache_timeout @cache.cached() def stats(): resp = dict() resp["count"] = Package.get_count() resp["day"] = Downloads.get_overall_downloads_count(timedelta(days=1)) resp["week"] = Downloads.get_overall_downloads_count(timedelta(days=7)) resp["month"] = Downloads.get_overall_downloads_count(timedelta(days=30)) return jsonify(resp) @packages.route('/featured', methods=['GET']) @cache_timeout @cache.cached() def featured(): package_list = requests.get("https://atom.io/api/packages/featured") theme_list = requests.get("https://atom.io/api/themes/featured") featured_list = package_list.json() + theme_list.json() # limit data to multiples of three length = (len(featured_list) / 3) * 3 featured_list = featured_list[:length] json_data = [] for item in featured_list: obj = Package.get_package(item['name']) if obj is not None: json_data.append(obj.get_json()) return jsonify(results=json_data) ## Instruction: Add my packages to featured list ## Code After: import requests from . import packages from models import Package, Downloads from flask import jsonify from datetime import timedelta from app import cache from utils import cache_timeout @packages.route('/stats', methods=['GET']) @cache_timeout @cache.cached() def stats(): resp = dict() resp["count"] = Package.get_count() resp["day"] = Downloads.get_overall_downloads_count(timedelta(days=1)) resp["week"] = Downloads.get_overall_downloads_count(timedelta(days=7)) resp["month"] = Downloads.get_overall_downloads_count(timedelta(days=30)) return jsonify(resp) @packages.route('/featured', methods=['GET']) @cache_timeout @cache.cached() def featured(): package_list = requests.get("https://atom.io/api/packages/featured") theme_list = requests.get("https://atom.io/api/themes/featured") featured_list = package_list.json() + theme_list.json() # limit data to multiples of three length = ((len(featured_list) + 2) / 3) * 3 featured_list = featured_list[:(length - 2)] json_data = [] for item in featured_list: obj = Package.get_package(item['name']) if obj is not None: json_data.append(obj.get_json()) for item in ["docblockr", "git-log"]: obj = Package.get_package(item) json_data.append(obj.get_json()) return jsonify(results=json_data)
# ... existing code ... theme_list = requests.get("https://atom.io/api/themes/featured") featured_list = package_list.json() + theme_list.json() # limit data to multiples of three length = ((len(featured_list) + 2) / 3) * 3 featured_list = featured_list[:(length - 2)] json_data = [] for item in featured_list: # ... modified code ... if obj is not None: json_data.append(obj.get_json()) for item in ["docblockr", "git-log"]: obj = Package.get_package(item) json_data.append(obj.get_json()) return jsonify(results=json_data) # ... rest of the code ...
0c746fc3c3b99b09d0a437f434bbade0640dc9c2
src/dict_example.c
src/dict_example.c
// cc dict_example.c dict.c #include <assert.h> #include <stdio.h> #include <string.h> #include "bool.h" #include "dict.h" int main(int argc, const char *argv[]) { /* allocate a new dict */ struct dict *dict = dict(); /* set key and values to dict */ char *key1 = "key1"; char *key2 = "key2"; char *val1 = "val1"; char *val2 = "val2"; assert(dict_set(dict, key1, strlen(key1), val1) == DICT_OK); assert(dict_set(dict, key2, strlen(key2), val2) == DICT_OK); /* get dict length */ assert(dict_len(dict) == 2); /* get data by key */ assert(dict_get(dict, key1, strlen(key1)) == val1); assert(dict_get(dict, key2, strlen(key2)) == val2); /* iterate dict */ struct dict_iter *iter = dict_iter(dict); struct dict_node *node = NULL; while ((node = dict_iter_next(iter)) != NULL) { printf("%.*s => %s\n", (int)node->len, node->key, node->val); } /* free dict iterator */ dict_iter_free(iter); /* free the dict */ dict_free(dict); return 0; }
// cc dict_example.c dict.c md5.c #include <assert.h> #include <stdio.h> #include <string.h> #include "bool.h" #include "dict.h" int main(int argc, const char *argv[]) { /* allocate a new dict */ struct dict *dict = dict(); /* set key and values to dict */ char *key1 = "key1"; char *key2 = "key2"; char *val1 = "val1"; char *val2 = "val2"; assert(dict_set(dict, key1, strlen(key1), val1) == DICT_OK); assert(dict_set(dict, key2, strlen(key2), val2) == DICT_OK); /* get dict length */ assert(dict_len(dict) == 2); /* get data by key */ assert(dict_get(dict, key1, strlen(key1)) == val1); assert(dict_get(dict, key2, strlen(key2)) == val2); /* iterate dict */ struct dict_iter *iter = dict_iter(dict); struct dict_node *node = NULL; while ((node = dict_iter_next(iter)) != NULL) { printf("%.*s => %s\n", (int)node->len, node->key, (char *)node->val); } /* free dict iterator */ dict_iter_free(iter); /* free the dict */ dict_free(dict); return 0; }
Fix void * casting to char * warning
Fix void * casting to char * warning
C
bsd-2-clause
hit9/C-Snip,hit9/C-Snip
c
## Code Before: // cc dict_example.c dict.c #include <assert.h> #include <stdio.h> #include <string.h> #include "bool.h" #include "dict.h" int main(int argc, const char *argv[]) { /* allocate a new dict */ struct dict *dict = dict(); /* set key and values to dict */ char *key1 = "key1"; char *key2 = "key2"; char *val1 = "val1"; char *val2 = "val2"; assert(dict_set(dict, key1, strlen(key1), val1) == DICT_OK); assert(dict_set(dict, key2, strlen(key2), val2) == DICT_OK); /* get dict length */ assert(dict_len(dict) == 2); /* get data by key */ assert(dict_get(dict, key1, strlen(key1)) == val1); assert(dict_get(dict, key2, strlen(key2)) == val2); /* iterate dict */ struct dict_iter *iter = dict_iter(dict); struct dict_node *node = NULL; while ((node = dict_iter_next(iter)) != NULL) { printf("%.*s => %s\n", (int)node->len, node->key, node->val); } /* free dict iterator */ dict_iter_free(iter); /* free the dict */ dict_free(dict); return 0; } ## Instruction: Fix void * casting to char * warning ## Code After: // cc dict_example.c dict.c md5.c #include <assert.h> #include <stdio.h> #include <string.h> #include "bool.h" #include "dict.h" int main(int argc, const char *argv[]) { /* allocate a new dict */ struct dict *dict = dict(); /* set key and values to dict */ char *key1 = "key1"; char *key2 = "key2"; char *val1 = "val1"; char *val2 = "val2"; assert(dict_set(dict, key1, strlen(key1), val1) == DICT_OK); assert(dict_set(dict, key2, strlen(key2), val2) == DICT_OK); /* get dict length */ assert(dict_len(dict) == 2); /* get data by key */ assert(dict_get(dict, key1, strlen(key1)) == val1); assert(dict_get(dict, key2, strlen(key2)) == val2); /* iterate dict */ struct dict_iter *iter = dict_iter(dict); struct dict_node *node = NULL; while ((node = dict_iter_next(iter)) != NULL) { printf("%.*s => %s\n", (int)node->len, node->key, (char *)node->val); } /* free dict iterator */ dict_iter_free(iter); /* free the dict */ dict_free(dict); return 0; }
# ... existing code ... // cc dict_example.c dict.c md5.c #include <assert.h> #include <stdio.h> # ... modified code ... struct dict_iter *iter = dict_iter(dict); struct dict_node *node = NULL; while ((node = dict_iter_next(iter)) != NULL) { printf("%.*s => %s\n", (int)node->len, node->key, (char *)node->val); } /* free dict iterator */ dict_iter_free(iter); # ... rest of the code ...
07e780a27253c4108c96e232ffbb975e88d23f8d
src/pygrapes/serializer/__init__.py
src/pygrapes/serializer/__init__.py
from abstract import Abstract __all__ = ['Abstract']
from abstract import Abstract from json import Json __all__ = ['Abstract', 'Json']
Load pygrapes.serializer.json.Json right inside pygrapes.serializer
Load pygrapes.serializer.json.Json right inside pygrapes.serializer
Python
bsd-3-clause
michalbachowski/pygrapes,michalbachowski/pygrapes,michalbachowski/pygrapes
python
## Code Before: from abstract import Abstract __all__ = ['Abstract'] ## Instruction: Load pygrapes.serializer.json.Json right inside pygrapes.serializer ## Code After: from abstract import Abstract from json import Json __all__ = ['Abstract', 'Json']
// ... existing code ... from abstract import Abstract from json import Json __all__ = ['Abstract', 'Json'] // ... rest of the code ...
e00ad93c1a769a920c7f61eeccec582272766b26
badgify/templatetags/badgify_tags.py
badgify/templatetags/badgify_tags.py
from django import template from ..models import Badge, Award from ..compat import get_user_model register = template.Library() @register.assignment_tag def badgify_badges(**kwargs): """ Returns all badges or only awarded badges for the given user. """ User = get_user_model() user = kwargs.get('user', None) username = kwargs.get('username', None) if username: try: user = User.objects.get(username=username) except User.DoesNotExist: pass if user: awards = Award.objects.filter(user=user) badges = [award.badge for award in awards] return badges return Badge.objects.all()
from django import template from ..models import Badge, Award from ..compat import get_user_model register = template.Library() @register.assignment_tag def badgify_badges(**kwargs): """ Returns all badges or only awarded badges for the given user. """ User = get_user_model() user = kwargs.get('user', None) username = kwargs.get('username', None) if username: try: user = User.objects.get(username=username) except User.DoesNotExist: pass if user: awards = Award.objects.filter(user=user).select_related('badge') badges = [award.badge for award in awards] return badges return Badge.objects.all()
Add missing select_related to badgify_badges
Add missing select_related to badgify_badges
Python
mit
ulule/django-badgify,ulule/django-badgify
python
## Code Before: from django import template from ..models import Badge, Award from ..compat import get_user_model register = template.Library() @register.assignment_tag def badgify_badges(**kwargs): """ Returns all badges or only awarded badges for the given user. """ User = get_user_model() user = kwargs.get('user', None) username = kwargs.get('username', None) if username: try: user = User.objects.get(username=username) except User.DoesNotExist: pass if user: awards = Award.objects.filter(user=user) badges = [award.badge for award in awards] return badges return Badge.objects.all() ## Instruction: Add missing select_related to badgify_badges ## Code After: from django import template from ..models import Badge, Award from ..compat import get_user_model register = template.Library() @register.assignment_tag def badgify_badges(**kwargs): """ Returns all badges or only awarded badges for the given user. """ User = get_user_model() user = kwargs.get('user', None) username = kwargs.get('username', None) if username: try: user = User.objects.get(username=username) except User.DoesNotExist: pass if user: awards = Award.objects.filter(user=user).select_related('badge') badges = [award.badge for award in awards] return badges return Badge.objects.all()
# ... existing code ... except User.DoesNotExist: pass if user: awards = Award.objects.filter(user=user).select_related('badge') badges = [award.badge for award in awards] return badges return Badge.objects.all() # ... rest of the code ...
82966f5e7280fc3414b8ea43e0a43f65c97106c0
src/no/tornado/tornadofx/idea/configurations/TornadoFXRunLineMarkerContributor.kt
src/no/tornado/tornadofx/idea/configurations/TornadoFXRunLineMarkerContributor.kt
package no.tornado.tornadofx.idea.configurations import com.intellij.execution.lineMarker.ExecutorAction import com.intellij.execution.lineMarker.RunLineMarkerContributor import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiElement import com.intellij.util.Function import no.tornado.tornadofx.idea.FXTools import no.tornado.tornadofx.idea.PluginIcons import org.jetbrains.kotlin.idea.search.allScope import org.jetbrains.kotlin.psi.KtClass class TornadoFXRunLineMarkerContributor : RunLineMarkerContributor() { override fun getInfo(element: PsiElement?): Info? { if (element is KtClass) { val psiFacade = JavaPsiFacade.getInstance(element.project) val psiClass = psiFacade?.findClass(element.fqName.toString(), element.project.allScope()) ?: return null val isApp = FXTools.isApp(psiClass) val isView = FXTools.isView(psiClass) if (isApp || isView) { return Info( PluginIcons.ACTION, Function<PsiElement, String> { "Run TornadoFX ${if (isApp) "Application" else "View"}" }, *ExecutorAction.getActions(0) ) } } return null } }
package no.tornado.tornadofx.idea.configurations import com.intellij.execution.lineMarker.ExecutorAction import com.intellij.execution.lineMarker.RunLineMarkerContributor import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiElement import com.intellij.util.Function import no.tornado.tornadofx.idea.FXTools import no.tornado.tornadofx.idea.PluginIcons import org.jetbrains.kotlin.idea.search.allScope import org.jetbrains.kotlin.psi.KtClass class TornadoFXRunLineMarkerContributor : RunLineMarkerContributor() { override fun getInfo(element: PsiElement?): Info? { if (element is KtClass) { val psiFacade = JavaPsiFacade.getInstance(element.project) val psiClass = psiFacade?.findClass(element.fqName.toString(), element.project.allScope()) ?: return null val isApp = FXTools.isApp(psiClass) val isView = FXTools.isUIComponent(psiClass) if (isApp || isView) { return Info( PluginIcons.ACTION, Function<PsiElement, String> { "Run TornadoFX ${if (isApp) "Application" else "View"}" }, *ExecutorAction.getActions(0) ) } } return null } }
Support for running Fragment directly
Support for running Fragment directly
Kotlin
apache-2.0
edvin/tornadofx-idea-plugin,edvin/tornadofx-idea-plugin,edvin/tornadofx-idea-plugin,edvin/tornadofx-idea-plugin
kotlin
## Code Before: package no.tornado.tornadofx.idea.configurations import com.intellij.execution.lineMarker.ExecutorAction import com.intellij.execution.lineMarker.RunLineMarkerContributor import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiElement import com.intellij.util.Function import no.tornado.tornadofx.idea.FXTools import no.tornado.tornadofx.idea.PluginIcons import org.jetbrains.kotlin.idea.search.allScope import org.jetbrains.kotlin.psi.KtClass class TornadoFXRunLineMarkerContributor : RunLineMarkerContributor() { override fun getInfo(element: PsiElement?): Info? { if (element is KtClass) { val psiFacade = JavaPsiFacade.getInstance(element.project) val psiClass = psiFacade?.findClass(element.fqName.toString(), element.project.allScope()) ?: return null val isApp = FXTools.isApp(psiClass) val isView = FXTools.isView(psiClass) if (isApp || isView) { return Info( PluginIcons.ACTION, Function<PsiElement, String> { "Run TornadoFX ${if (isApp) "Application" else "View"}" }, *ExecutorAction.getActions(0) ) } } return null } } ## Instruction: Support for running Fragment directly ## Code After: package no.tornado.tornadofx.idea.configurations import com.intellij.execution.lineMarker.ExecutorAction import com.intellij.execution.lineMarker.RunLineMarkerContributor import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiElement import com.intellij.util.Function import no.tornado.tornadofx.idea.FXTools import no.tornado.tornadofx.idea.PluginIcons import org.jetbrains.kotlin.idea.search.allScope import org.jetbrains.kotlin.psi.KtClass class TornadoFXRunLineMarkerContributor : RunLineMarkerContributor() { override fun getInfo(element: PsiElement?): Info? { if (element is KtClass) { val psiFacade = JavaPsiFacade.getInstance(element.project) val psiClass = psiFacade?.findClass(element.fqName.toString(), element.project.allScope()) ?: return null val isApp = FXTools.isApp(psiClass) val isView = FXTools.isUIComponent(psiClass) if (isApp || isView) { return Info( PluginIcons.ACTION, Function<PsiElement, String> { "Run TornadoFX ${if (isApp) "Application" else "View"}" }, *ExecutorAction.getActions(0) ) } } return null } }
... val psiClass = psiFacade?.findClass(element.fqName.toString(), element.project.allScope()) ?: return null val isApp = FXTools.isApp(psiClass) val isView = FXTools.isUIComponent(psiClass) if (isApp || isView) { return Info( ...
e2e6cdac88ee03f78713ac4a50d0003a471a0027
setup.py
setup.py
from setuptools import setup long_description = open('README.rst').read() setup( name="celery-redbeat", description="A Celery Beat Scheduler using Redis for persistent storage", long_description=long_description, version="2.0.0", url="https://github.com/sibson/redbeat", license="Apache License, Version 2.0", author="Marc Sibson", author_email="[email protected]", keywords="python celery beat redis".split(), packages=["redbeat"], classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Topic :: System :: Distributed Computing', 'Topic :: Software Development :: Object Brokering', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Operating System :: OS Independent', ], install_requires=['redis>=3.2', 'celery>=4.2', 'python-dateutil', 'tenacity'], tests_require=['pytest'], )
from setuptools import setup long_description = open('README.rst').read() setup( name="celery-redbeat", description="A Celery Beat Scheduler using Redis for persistent storage", long_description=long_description, version="2.0.0", url="https://github.com/sibson/redbeat", license="Apache License, Version 2.0", author="Marc Sibson", author_email="[email protected]", keywords="python celery beat redis".split(), packages=["redbeat"], classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Topic :: System :: Distributed Computing', 'Topic :: Software Development :: Object Brokering', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: Implementation :: CPython', 'Operating System :: OS Independent', ], install_requires=['redis>=3.2', 'celery>=4.2', 'python-dateutil', 'tenacity'], tests_require=['pytest'], )
Add Python 3.9 to the list of supported versions.
Add Python 3.9 to the list of supported versions.
Python
apache-2.0
sibson/redbeat
python
## Code Before: from setuptools import setup long_description = open('README.rst').read() setup( name="celery-redbeat", description="A Celery Beat Scheduler using Redis for persistent storage", long_description=long_description, version="2.0.0", url="https://github.com/sibson/redbeat", license="Apache License, Version 2.0", author="Marc Sibson", author_email="[email protected]", keywords="python celery beat redis".split(), packages=["redbeat"], classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Topic :: System :: Distributed Computing', 'Topic :: Software Development :: Object Brokering', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Operating System :: OS Independent', ], install_requires=['redis>=3.2', 'celery>=4.2', 'python-dateutil', 'tenacity'], tests_require=['pytest'], ) ## Instruction: Add Python 3.9 to the list of supported versions. ## Code After: from setuptools import setup long_description = open('README.rst').read() setup( name="celery-redbeat", description="A Celery Beat Scheduler using Redis for persistent storage", long_description=long_description, version="2.0.0", url="https://github.com/sibson/redbeat", license="Apache License, Version 2.0", author="Marc Sibson", author_email="[email protected]", keywords="python celery beat redis".split(), packages=["redbeat"], classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Topic :: System :: Distributed Computing', 'Topic :: Software Development :: Object Brokering', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: Implementation :: CPython', 'Operating System :: OS Independent', ], install_requires=['redis>=3.2', 'celery>=4.2', 'python-dateutil', 'tenacity'], tests_require=['pytest'], )
# ... existing code ... 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: Implementation :: CPython', 'Operating System :: OS Independent', ], # ... rest of the code ...
58cbb8b3dbe8d1275743c3fd5d043cfa12914cb3
data_structures/bitorrent/client.py
data_structures/bitorrent/client.py
from urlparse import urlparse from torrent import Torrent from trackers.udp import UDPTracker class Client(object): __TORRENTS = {} @property def torrents(self): return self.__TORRENTS @torrents.setter def torrents(self, new_torrent): self.__TORRENTS[new_torrent] = Torrent(new_torrent) def download(self, torrent): if not torrent in self.__TORRENTS: raise ValueError('%s not here' % torrent) torrent = self.__TORRENTS[torrent] for url in torrent.urls: parsed = urlparse(url) if parsed.scheme == 'udp': _, url, port = url.split(":") tracker = UDPTracker(url[2:], int(port), torrent) print tracker.peers
import urllib from random import randint from urlparse import urlparse from torrent import Torrent from trackers.udp import UDPTracker class Client(object): __TORRENTS = {} def __init__(self): self.peer_id = urllib.quote("-AZ2470-" + "".join([str(randint(0, 9)) for i in xrange(12)])) @property def torrents(self): return self.__TORRENTS @torrents.setter def torrents(self, new_torrent): self.__TORRENTS[new_torrent] = Torrent(new_torrent) def _get_peers(self, torrent): peers = {} for url in torrent.urls: parsed = urlparse(url) if parsed.scheme == 'udp': _, url, port = url.split(":") tracker = UDPTracker(url[2:], int(port), torrent, self.peer_id) peers.update({ip: port for ip, port in tracker.peers}) return peers def download(self, torrent): if not torrent in self.__TORRENTS: raise ValueError('%s not here' % torrent) torrent = self.__TORRENTS[torrent] peers = self._get_peers(torrent) print peers
Use a separate method to get all peers of a torrent
Use a separate method to get all peers of a torrent
Python
apache-2.0
vtemian/university_projects,vtemian/university_projects,vtemian/university_projects
python
## Code Before: from urlparse import urlparse from torrent import Torrent from trackers.udp import UDPTracker class Client(object): __TORRENTS = {} @property def torrents(self): return self.__TORRENTS @torrents.setter def torrents(self, new_torrent): self.__TORRENTS[new_torrent] = Torrent(new_torrent) def download(self, torrent): if not torrent in self.__TORRENTS: raise ValueError('%s not here' % torrent) torrent = self.__TORRENTS[torrent] for url in torrent.urls: parsed = urlparse(url) if parsed.scheme == 'udp': _, url, port = url.split(":") tracker = UDPTracker(url[2:], int(port), torrent) print tracker.peers ## Instruction: Use a separate method to get all peers of a torrent ## Code After: import urllib from random import randint from urlparse import urlparse from torrent import Torrent from trackers.udp import UDPTracker class Client(object): __TORRENTS = {} def __init__(self): self.peer_id = urllib.quote("-AZ2470-" + "".join([str(randint(0, 9)) for i in xrange(12)])) @property def torrents(self): return self.__TORRENTS @torrents.setter def torrents(self, new_torrent): self.__TORRENTS[new_torrent] = Torrent(new_torrent) def _get_peers(self, torrent): peers = {} for url in torrent.urls: parsed = urlparse(url) if parsed.scheme == 'udp': _, url, port = url.split(":") tracker = UDPTracker(url[2:], int(port), torrent, self.peer_id) peers.update({ip: port for ip, port in tracker.peers}) return peers def download(self, torrent): if not torrent in self.__TORRENTS: raise ValueError('%s not here' % torrent) torrent = self.__TORRENTS[torrent] peers = self._get_peers(torrent) print peers
// ... existing code ... import urllib from random import randint from urlparse import urlparse from torrent import Torrent // ... modified code ... class Client(object): __TORRENTS = {} def __init__(self): self.peer_id = urllib.quote("-AZ2470-" + "".join([str(randint(0, 9)) for i in xrange(12)])) @property def torrents(self): return self.__TORRENTS ... def torrents(self, new_torrent): self.__TORRENTS[new_torrent] = Torrent(new_torrent) def _get_peers(self, torrent): peers = {} for url in torrent.urls: parsed = urlparse(url) if parsed.scheme == 'udp': _, url, port = url.split(":") tracker = UDPTracker(url[2:], int(port), torrent, self.peer_id) peers.update({ip: port for ip, port in tracker.peers}) return peers def download(self, torrent): if not torrent in self.__TORRENTS: raise ValueError('%s not here' % torrent) torrent = self.__TORRENTS[torrent] peers = self._get_peers(torrent) print peers // ... rest of the code ...
071d8df8a985c77397c5b2caf27722101aaefea1
setup.py
setup.py
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='gorynych', version='0.0.1', description='Automatic data collecting and refining system', long_description=long_description, url='https://github.com/vurmux/gorynych', author='Andrey Voronov', author_email='[email protected]', license='Apache', classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Information Technology', 'Topic :: Internet', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3 :: Only', ], keywords='scraping nlp', packages=find_packages(exclude=['docs', 'img']), install_requires=['beautifulsoup4', 'requests', 'nltk'], extras_require={ 'dev': [], 'test': ['coverage'], }, package_data={ 'gorynych': ['*.txt', '*.json'], }, entry_points={ 'console_scripts': [ 'gorynych-daemon=gorynych.gorynych_daemon:main', ], }, )
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='gorynych', version='0.0.1', description='Automatic data collecting and refining system', long_description=long_description, url='https://github.com/vurmux/gorynych', author='Andrey Voronov', author_email='[email protected]', license='Apache', classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Information Technology', 'Topic :: Internet', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3 :: Only', ], keywords='scraping nlp', packages=find_packages(exclude=['docs', 'img']), install_requires=['beautifulsoup4', 'requests', 'nltk', 'schedule'], extras_require={ 'dev': [], 'test': ['coverage'], }, package_data={ 'gorynych': ['*.txt', '*.json'], }, entry_points={ 'console_scripts': [ 'gorynych-daemon=gorynych.gorynych_daemon:main', ], }, )
Add missed 'schedule' package to install_requires
Add missed 'schedule' package to install_requires
Python
apache-2.0
vurmux/gorynych
python
## Code Before: from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='gorynych', version='0.0.1', description='Automatic data collecting and refining system', long_description=long_description, url='https://github.com/vurmux/gorynych', author='Andrey Voronov', author_email='[email protected]', license='Apache', classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Information Technology', 'Topic :: Internet', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3 :: Only', ], keywords='scraping nlp', packages=find_packages(exclude=['docs', 'img']), install_requires=['beautifulsoup4', 'requests', 'nltk'], extras_require={ 'dev': [], 'test': ['coverage'], }, package_data={ 'gorynych': ['*.txt', '*.json'], }, entry_points={ 'console_scripts': [ 'gorynych-daemon=gorynych.gorynych_daemon:main', ], }, ) ## Instruction: Add missed 'schedule' package to install_requires ## Code After: from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='gorynych', version='0.0.1', description='Automatic data collecting and refining system', long_description=long_description, url='https://github.com/vurmux/gorynych', author='Andrey Voronov', author_email='[email protected]', license='Apache', classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Information Technology', 'Topic :: Internet', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3 :: Only', ], keywords='scraping nlp', packages=find_packages(exclude=['docs', 'img']), install_requires=['beautifulsoup4', 'requests', 'nltk', 'schedule'], extras_require={ 'dev': [], 'test': ['coverage'], }, package_data={ 'gorynych': ['*.txt', '*.json'], }, entry_points={ 'console_scripts': [ 'gorynych-daemon=gorynych.gorynych_daemon:main', ], }, )
# ... existing code ... ], keywords='scraping nlp', packages=find_packages(exclude=['docs', 'img']), install_requires=['beautifulsoup4', 'requests', 'nltk', 'schedule'], extras_require={ 'dev': [], 'test': ['coverage'], # ... rest of the code ...
523a25d30241ecdd0abdb7545b1454714b003edc
astrospam/pyastro16.py
astrospam/pyastro16.py
import numpy as np def times(a, b): """ Multiply a by b. Parameters ---------- a : `numpy.ndarray` Array one. b : `numpy.ndarray` Array two Returns ------- result : `numpy.ndarray` ``a`` multiplied by ``b`` """ return np.multipy(a, b) class PyAstro(object): """ This is a class docstring, here you must describe the parameters for the creation of the class, which is normally the signature of the ``__init__`` method. Parameters ---------- awesomeness_level : `int` How awesome is pyastro16??! day : `int` Day of the conference. Defaults to 1. Attributes ---------- awesomeness_level: `int` How awesome is this class attributes?! You can document attributes that are not properties here. """ def __init__(self, awesomeness_level, day=1): """ This docstring is not used, because it is for a hidden method. """ self.awesomeness_level = awesomeness_level self._day = day @property def day(self): """ Day of the conference. Properties are automatically documented as attributes """ return self._day
import numpy as np def times(a, b): """ Multiply a by b. Parameters ---------- a : `numpy.ndarray` Array one. b : `numpy.ndarray` Array two Returns ------- result : `numpy.ndarray` ``a`` multiplied by ``b`` """ return np.multipy(a, b) class PyAstro(object): """ This is a class docstring, here you must describe the parameters for the creation of the class, which is normally the signature of the ``__init__`` method. Parameters ---------- awesomeness_level : `int` How awesome is pyastro16??! day : `int` Day of the conference. Defaults to 1. Attributes ---------- awesomeness_level: `int` How awesome is this class attributes?! You can document attributes that are not properties here. """ def __init__(self, awesomeness_level, day=1): """ This docstring is not used, because it is for a hidden method. """ self.awesomeness_level = awesomeness_level self._day = day @property def day(self): """ Day of the conference. Properties are automatically documented as attributes """ return self._day class PyAstro16(PyAstro): """ The 2016 edition of the python in astronomy conference. """ __doc__ += PyAstro.__doc__
Add a subclass for the dot graph
Add a subclass for the dot graph
Python
mit
cdeil/sphinx-tutorial
python
## Code Before: import numpy as np def times(a, b): """ Multiply a by b. Parameters ---------- a : `numpy.ndarray` Array one. b : `numpy.ndarray` Array two Returns ------- result : `numpy.ndarray` ``a`` multiplied by ``b`` """ return np.multipy(a, b) class PyAstro(object): """ This is a class docstring, here you must describe the parameters for the creation of the class, which is normally the signature of the ``__init__`` method. Parameters ---------- awesomeness_level : `int` How awesome is pyastro16??! day : `int` Day of the conference. Defaults to 1. Attributes ---------- awesomeness_level: `int` How awesome is this class attributes?! You can document attributes that are not properties here. """ def __init__(self, awesomeness_level, day=1): """ This docstring is not used, because it is for a hidden method. """ self.awesomeness_level = awesomeness_level self._day = day @property def day(self): """ Day of the conference. Properties are automatically documented as attributes """ return self._day ## Instruction: Add a subclass for the dot graph ## Code After: import numpy as np def times(a, b): """ Multiply a by b. Parameters ---------- a : `numpy.ndarray` Array one. b : `numpy.ndarray` Array two Returns ------- result : `numpy.ndarray` ``a`` multiplied by ``b`` """ return np.multipy(a, b) class PyAstro(object): """ This is a class docstring, here you must describe the parameters for the creation of the class, which is normally the signature of the ``__init__`` method. Parameters ---------- awesomeness_level : `int` How awesome is pyastro16??! day : `int` Day of the conference. Defaults to 1. Attributes ---------- awesomeness_level: `int` How awesome is this class attributes?! You can document attributes that are not properties here. """ def __init__(self, awesomeness_level, day=1): """ This docstring is not used, because it is for a hidden method. """ self.awesomeness_level = awesomeness_level self._day = day @property def day(self): """ Day of the conference. Properties are automatically documented as attributes """ return self._day class PyAstro16(PyAstro): """ The 2016 edition of the python in astronomy conference. """ __doc__ += PyAstro.__doc__
... Properties are automatically documented as attributes """ return self._day class PyAstro16(PyAstro): """ The 2016 edition of the python in astronomy conference. """ __doc__ += PyAstro.__doc__ ...
54c81494cbbe9a20db50596e68c57e1caa624043
src-django/authentication/signals/user_post_save.py
src-django/authentication/signals/user_post_save.py
from django.contrib.auth.models import User, Group from django.dispatch import receiver from django.db.models.signals import post_save from django.conf import settings from rest_framework.authtoken.models import Token @receiver(post_save, sender=User) def on_user_post_save(sender, instance=None, created=False, **kwargs): # Normally, users automatically get a Token created for them (if they do not # already have one) when they hit # # rest_framework.authtoken.views.obtain_auth_token view # # This will create an authentication token for newly created users so the # user registration endpoint can return a token back to Ember # (thus avoiding the need to hit login endpoint) if created: Token.objects.create(user=instance) # Add new user to the proper user group normal_users_group, created = Group.objects.get_or_create(name=settings.NORMAL_USER_GROUP) instance.groups.add(normal_users_group)
from authentication.models import UserProfile from django.contrib.auth.models import User, Group from django.dispatch import receiver from django.db.models.signals import post_save from django.conf import settings from rest_framework.authtoken.models import Token @receiver(post_save, sender=User) def on_user_post_save(sender, instance=None, created=False, **kwargs): # Normally, users automatically get a Token created for them (if they do not # already have one) when they hit # # rest_framework.authtoken.views.obtain_auth_token view # # This will create an authentication token for newly created users so the # user registration endpoint can return a token back to Ember # (thus avoiding the need to hit login endpoint) if created: user_profile = UserProfile.objects.create(user=instance, is_email_confirmed=False) user_profile.save() Token.objects.create(user=instance) # Add new user to the proper user group normal_users_group, created = Group.objects.get_or_create(name=settings.NORMAL_USER_GROUP) instance.groups.add(normal_users_group)
Add a User post_save hook for creating user profiles
Add a User post_save hook for creating user profiles
Python
bsd-3-clause
SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder
python
## Code Before: from django.contrib.auth.models import User, Group from django.dispatch import receiver from django.db.models.signals import post_save from django.conf import settings from rest_framework.authtoken.models import Token @receiver(post_save, sender=User) def on_user_post_save(sender, instance=None, created=False, **kwargs): # Normally, users automatically get a Token created for them (if they do not # already have one) when they hit # # rest_framework.authtoken.views.obtain_auth_token view # # This will create an authentication token for newly created users so the # user registration endpoint can return a token back to Ember # (thus avoiding the need to hit login endpoint) if created: Token.objects.create(user=instance) # Add new user to the proper user group normal_users_group, created = Group.objects.get_or_create(name=settings.NORMAL_USER_GROUP) instance.groups.add(normal_users_group) ## Instruction: Add a User post_save hook for creating user profiles ## Code After: from authentication.models import UserProfile from django.contrib.auth.models import User, Group from django.dispatch import receiver from django.db.models.signals import post_save from django.conf import settings from rest_framework.authtoken.models import Token @receiver(post_save, sender=User) def on_user_post_save(sender, instance=None, created=False, **kwargs): # Normally, users automatically get a Token created for them (if they do not # already have one) when they hit # # rest_framework.authtoken.views.obtain_auth_token view # # This will create an authentication token for newly created users so the # user registration endpoint can return a token back to Ember # (thus avoiding the need to hit login endpoint) if created: user_profile = UserProfile.objects.create(user=instance, is_email_confirmed=False) user_profile.save() Token.objects.create(user=instance) # Add new user to the proper user group normal_users_group, created = Group.objects.get_or_create(name=settings.NORMAL_USER_GROUP) instance.groups.add(normal_users_group)
# ... existing code ... from authentication.models import UserProfile from django.contrib.auth.models import User, Group from django.dispatch import receiver from django.db.models.signals import post_save # ... modified code ... # user registration endpoint can return a token back to Ember # (thus avoiding the need to hit login endpoint) if created: user_profile = UserProfile.objects.create(user=instance, is_email_confirmed=False) user_profile.save() Token.objects.create(user=instance) # Add new user to the proper user group # ... rest of the code ...
2d6a5a494b42519a1ec849e1fa508f93653e5d33
rango/forms.py
rango/forms.py
from django import forms from rango.models import Category, Page class CategoryForm(forms.ModelForm): name = forms.CharField(max_length=128, help_text="Please enter a category name") views = forms.IntegerField(widget=forms.HiddenInput(), initial = 0) likes = forms.IntegerField(widget=forms.HiddenInput(), initial = 0) slug = forms.CharField(widget=forms.HiddenInput(), required=False) class Meta: model = Category # tuple specifying the classes we want to use fields = ('name', ) class PageForm(forms.ModelForm): title = forms.CharField(max_length=128, help_text="Please enter the title of the page.") url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.") views = forms.IntegerField(widget=forms.HiddenInput(), initial=0) class Meta: model = Page # excluding the category foreign key field from the form exclude = ('category', 'slug')
from django import forms from django.contrib.auth.models import User from rango.models import Category, Page, UserProfile class CategoryForm(forms.ModelForm): name = forms.CharField(max_length=128, help_text="Please enter a category name") views = forms.IntegerField(widget=forms.HiddenInput(), initial = 0) likes = forms.IntegerField(widget=forms.HiddenInput(), initial = 0) slug = forms.CharField(widget=forms.HiddenInput(), required=False) class Meta: model = Category # tuple specifying the classes we want to use fields = ('name', ) class PageForm(forms.ModelForm): title = forms.CharField(max_length=128, help_text="Please enter the title of the page.") url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.") views = forms.IntegerField(widget=forms.HiddenInput(), initial=0) class Meta: model = Page # excluding the category foreign key field from the form exclude = ('category', 'slug') class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput(), help_text="Enter your password") class Meta: model = User fields = ('username', 'email', 'password') class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('website', 'picture')
Add form classes for User and UserProfile
Add form classes for User and UserProfile
Python
mit
dnestoff/Tango-With-Django,dnestoff/Tango-With-Django
python
## Code Before: from django import forms from rango.models import Category, Page class CategoryForm(forms.ModelForm): name = forms.CharField(max_length=128, help_text="Please enter a category name") views = forms.IntegerField(widget=forms.HiddenInput(), initial = 0) likes = forms.IntegerField(widget=forms.HiddenInput(), initial = 0) slug = forms.CharField(widget=forms.HiddenInput(), required=False) class Meta: model = Category # tuple specifying the classes we want to use fields = ('name', ) class PageForm(forms.ModelForm): title = forms.CharField(max_length=128, help_text="Please enter the title of the page.") url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.") views = forms.IntegerField(widget=forms.HiddenInput(), initial=0) class Meta: model = Page # excluding the category foreign key field from the form exclude = ('category', 'slug') ## Instruction: Add form classes for User and UserProfile ## Code After: from django import forms from django.contrib.auth.models import User from rango.models import Category, Page, UserProfile class CategoryForm(forms.ModelForm): name = forms.CharField(max_length=128, help_text="Please enter a category name") views = forms.IntegerField(widget=forms.HiddenInput(), initial = 0) likes = forms.IntegerField(widget=forms.HiddenInput(), initial = 0) slug = forms.CharField(widget=forms.HiddenInput(), required=False) class Meta: model = Category # tuple specifying the classes we want to use fields = ('name', ) class PageForm(forms.ModelForm): title = forms.CharField(max_length=128, help_text="Please enter the title of the page.") url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.") views = forms.IntegerField(widget=forms.HiddenInput(), initial=0) class Meta: model = Page # excluding the category foreign key field from the form exclude = ('category', 'slug') class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput(), help_text="Enter your password") class Meta: model = User fields = ('username', 'email', 'password') class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('website', 'picture')
... from django import forms from django.contrib.auth.models import User from rango.models import Category, Page, UserProfile class CategoryForm(forms.ModelForm): name = forms.CharField(max_length=128, help_text="Please enter a category name") ... model = Page # excluding the category foreign key field from the form exclude = ('category', 'slug') class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput(), help_text="Enter your password") class Meta: model = User fields = ('username', 'email', 'password') class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('website', 'picture') ...
853d9041790c833bbf6c8c06d3272c759926e531
ext/ruby/src/java/org/yecht/ruby/RubyErrHandler.java
ext/ruby/src/java/org/yecht/ruby/RubyErrHandler.java
package org.yecht.ruby; import org.yecht.Parser; import org.yecht.ErrorHandler; import org.jruby.Ruby; import org.jruby.anno.JRubyMethod; import org.jruby.runtime.builtin.IRubyObject; public class RubyErrHandler implements ErrorHandler { private Ruby runtime; public RubyErrHandler(Ruby runtime) { this.runtime = runtime; } // rb_syck_err_handler public void handle(Parser p, String msg) { int endl = p.cursor; while(p.buffer.buffer[endl] != 0 && p.buffer.buffer[endl] != '\n') { endl++; } try { int lp = p.lineptr; if(lp < 0) { lp = 0; } String line = new String(p.buffer.buffer, lp, endl-lp, "ISO-8859-1"); String m1 = msg + " on line " + p.linect + ", col " + (p.cursor-lp) + ": `" + line + "'"; throw runtime.newArgumentError(m1); } catch(java.io.UnsupportedEncodingException e) { } } }
package org.yecht.ruby; import org.yecht.Parser; import org.yecht.ErrorHandler; import org.jruby.Ruby; import org.jruby.anno.JRubyMethod; import org.jruby.runtime.builtin.IRubyObject; public class RubyErrHandler implements ErrorHandler { private Ruby runtime; public RubyErrHandler(Ruby runtime) { this.runtime = runtime; } // rb_syck_err_handler public void handle(Parser p, String msg) { int endl = p.cursor; while(p.buffer.buffer[endl] != 0 && p.buffer.buffer[endl] != '\n') { endl++; } try { int lp = p.lineptr; if(lp < 0) { lp = 0; } int len = endl-lp; if(len < 0) { len = 0; } String line = new String(p.buffer.buffer, lp, len, "ISO-8859-1"); String m1 = msg + " on line " + p.linect + ", col " + (p.cursor-lp) + ": `" + line + "'"; throw runtime.newArgumentError(m1); } catch(java.io.UnsupportedEncodingException e) { } } }
Fix an IOOBE - JRUBY-4254
Fix an IOOBE - JRUBY-4254
Java
mit
jruby/yecht,olabini/yecht,jruby/yecht,olabini/yecht
java
## Code Before: package org.yecht.ruby; import org.yecht.Parser; import org.yecht.ErrorHandler; import org.jruby.Ruby; import org.jruby.anno.JRubyMethod; import org.jruby.runtime.builtin.IRubyObject; public class RubyErrHandler implements ErrorHandler { private Ruby runtime; public RubyErrHandler(Ruby runtime) { this.runtime = runtime; } // rb_syck_err_handler public void handle(Parser p, String msg) { int endl = p.cursor; while(p.buffer.buffer[endl] != 0 && p.buffer.buffer[endl] != '\n') { endl++; } try { int lp = p.lineptr; if(lp < 0) { lp = 0; } String line = new String(p.buffer.buffer, lp, endl-lp, "ISO-8859-1"); String m1 = msg + " on line " + p.linect + ", col " + (p.cursor-lp) + ": `" + line + "'"; throw runtime.newArgumentError(m1); } catch(java.io.UnsupportedEncodingException e) { } } } ## Instruction: Fix an IOOBE - JRUBY-4254 ## Code After: package org.yecht.ruby; import org.yecht.Parser; import org.yecht.ErrorHandler; import org.jruby.Ruby; import org.jruby.anno.JRubyMethod; import org.jruby.runtime.builtin.IRubyObject; public class RubyErrHandler implements ErrorHandler { private Ruby runtime; public RubyErrHandler(Ruby runtime) { this.runtime = runtime; } // rb_syck_err_handler public void handle(Parser p, String msg) { int endl = p.cursor; while(p.buffer.buffer[endl] != 0 && p.buffer.buffer[endl] != '\n') { endl++; } try { int lp = p.lineptr; if(lp < 0) { lp = 0; } int len = endl-lp; if(len < 0) { len = 0; } String line = new String(p.buffer.buffer, lp, len, "ISO-8859-1"); String m1 = msg + " on line " + p.linect + ", col " + (p.cursor-lp) + ": `" + line + "'"; throw runtime.newArgumentError(m1); } catch(java.io.UnsupportedEncodingException e) { } } }
... if(lp < 0) { lp = 0; } int len = endl-lp; if(len < 0) { len = 0; } String line = new String(p.buffer.buffer, lp, len, "ISO-8859-1"); String m1 = msg + " on line " + p.linect + ", col " + (p.cursor-lp) + ": `" + line + "'"; throw runtime.newArgumentError(m1); } catch(java.io.UnsupportedEncodingException e) { ...
1e980277f53d12686264b8ce816e65ffea16a2dd
examples/basic.py
examples/basic.py
from simpleflow import ( activity, Workflow, ) @activity.with_attributes(task_list='quickstart') def increment(x): return x + 1 @activity.with_attributes(task_list='quickstart') def double(x): return x * 2 class BasicWorkflow(Workflow): name = 'basic' version = 'example' def run(self, x): y = self.submit(increment, x) z = self.submit(double, y) print '({x} + 1) * 2 = {result}'.format( x=x, result=z.result) return z.result
import time from simpleflow import ( activity, Workflow, ) @activity.with_attributes(task_list='quickstart') def increment(x): return x + 1 @activity.with_attributes(task_list='quickstart') def double(x): return x * 2 @activity.with_attributes(task_list='quickstart', version='example') def delay(t, x): time.sleep(t) return x class BasicWorkflow(Workflow): name = 'basic' version = 'example' def run(self, x, t=30): y = self.submit(increment, x) yy = self.submit(delay, t, y) z = self.submit(double, yy) print '({x} + 1) * 2 = {result}'.format( x=x, result=z.result) return z.result
Update example: add a delay task
Update example: add a delay task
Python
mit
botify-labs/simpleflow,botify-labs/simpleflow
python
## Code Before: from simpleflow import ( activity, Workflow, ) @activity.with_attributes(task_list='quickstart') def increment(x): return x + 1 @activity.with_attributes(task_list='quickstart') def double(x): return x * 2 class BasicWorkflow(Workflow): name = 'basic' version = 'example' def run(self, x): y = self.submit(increment, x) z = self.submit(double, y) print '({x} + 1) * 2 = {result}'.format( x=x, result=z.result) return z.result ## Instruction: Update example: add a delay task ## Code After: import time from simpleflow import ( activity, Workflow, ) @activity.with_attributes(task_list='quickstart') def increment(x): return x + 1 @activity.with_attributes(task_list='quickstart') def double(x): return x * 2 @activity.with_attributes(task_list='quickstart', version='example') def delay(t, x): time.sleep(t) return x class BasicWorkflow(Workflow): name = 'basic' version = 'example' def run(self, x, t=30): y = self.submit(increment, x) yy = self.submit(delay, t, y) z = self.submit(double, yy) print '({x} + 1) * 2 = {result}'.format( x=x, result=z.result) return z.result
// ... existing code ... import time from simpleflow import ( activity, Workflow, // ... modified code ... return x * 2 @activity.with_attributes(task_list='quickstart', version='example') def delay(t, x): time.sleep(t) return x class BasicWorkflow(Workflow): name = 'basic' version = 'example' def run(self, x, t=30): y = self.submit(increment, x) yy = self.submit(delay, t, y) z = self.submit(double, yy) print '({x} + 1) * 2 = {result}'.format( x=x, // ... rest of the code ...
f32a4239735987e4f160b4401ec93bf702e8e131
agents/neo4j/src/main/java/uk/ac/ebi/biosamples/neo/NeoMessageBuffer.java
agents/neo4j/src/main/java/uk/ac/ebi/biosamples/neo/NeoMessageBuffer.java
package uk.ac.ebi.biosamples.neo; import java.util.Collection; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.stereotype.Component; import uk.ac.ebi.biosamples.messages.threaded.MessageBuffer; import uk.ac.ebi.biosamples.neo.model.NeoSample; import uk.ac.ebi.biosamples.neo.repo.NeoSampleRepository; @Component public class NeoMessageBuffer extends MessageBuffer<NeoSample, NeoSampleRepository> { private Logger log = LoggerFactory.getLogger(this.getClass()); private Random random = new Random(); public NeoMessageBuffer(NeoSampleRepository repository) { super(repository); } @Override protected void save(NeoSampleRepository repository, Collection<NeoSample> samples) { int retryCount = 0; while (retryCount < 100) { try { //this will have its own transaction repository.save(samples); return; } catch (ConcurrencyFailureException e) { retryCount += 1 ; log.info("Retrying due to transient exception. Attempt number "+retryCount); try { Thread.sleep(random.nextInt(400)+100); } catch (InterruptedException e1) { //do nothing } } } log.warn("Unable to save within "+retryCount+" retries"); } }
package uk.ac.ebi.biosamples.neo; import java.util.Collection; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.stereotype.Component; import uk.ac.ebi.biosamples.messages.threaded.MessageBuffer; import uk.ac.ebi.biosamples.neo.model.NeoSample; import uk.ac.ebi.biosamples.neo.repo.NeoSampleRepository; @Component public class NeoMessageBuffer extends MessageBuffer<NeoSample, NeoSampleRepository> { private Logger log = LoggerFactory.getLogger(this.getClass()); private Random random = new Random(); public NeoMessageBuffer(NeoSampleRepository repository) { super(repository); } @Override protected void save(NeoSampleRepository repository, Collection<NeoSample> samples) { int retryCount = 0; while (retryCount < 100) { try { //this will have its own transaction repository.save(samples); return; } catch (ConcurrencyFailureException e) { retryCount += 1 ; log.warn("Retrying due to transient exception. Attempt number "+retryCount); try { Thread.sleep(random.nextInt(400)+100); } catch (InterruptedException e1) { //do nothing } } } throw new RuntimeException("Unable to save within "+retryCount+" retries"); } }
Tweak to error message propagation
Tweak to error message propagation
Java
apache-2.0
EBIBioSamples/biosamples-v4,EBIBioSamples/biosamples-v4,EBIBioSamples/biosamples-v4,EBIBioSamples/biosamples-v4
java
## Code Before: package uk.ac.ebi.biosamples.neo; import java.util.Collection; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.stereotype.Component; import uk.ac.ebi.biosamples.messages.threaded.MessageBuffer; import uk.ac.ebi.biosamples.neo.model.NeoSample; import uk.ac.ebi.biosamples.neo.repo.NeoSampleRepository; @Component public class NeoMessageBuffer extends MessageBuffer<NeoSample, NeoSampleRepository> { private Logger log = LoggerFactory.getLogger(this.getClass()); private Random random = new Random(); public NeoMessageBuffer(NeoSampleRepository repository) { super(repository); } @Override protected void save(NeoSampleRepository repository, Collection<NeoSample> samples) { int retryCount = 0; while (retryCount < 100) { try { //this will have its own transaction repository.save(samples); return; } catch (ConcurrencyFailureException e) { retryCount += 1 ; log.info("Retrying due to transient exception. Attempt number "+retryCount); try { Thread.sleep(random.nextInt(400)+100); } catch (InterruptedException e1) { //do nothing } } } log.warn("Unable to save within "+retryCount+" retries"); } } ## Instruction: Tweak to error message propagation ## Code After: package uk.ac.ebi.biosamples.neo; import java.util.Collection; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.stereotype.Component; import uk.ac.ebi.biosamples.messages.threaded.MessageBuffer; import uk.ac.ebi.biosamples.neo.model.NeoSample; import uk.ac.ebi.biosamples.neo.repo.NeoSampleRepository; @Component public class NeoMessageBuffer extends MessageBuffer<NeoSample, NeoSampleRepository> { private Logger log = LoggerFactory.getLogger(this.getClass()); private Random random = new Random(); public NeoMessageBuffer(NeoSampleRepository repository) { super(repository); } @Override protected void save(NeoSampleRepository repository, Collection<NeoSample> samples) { int retryCount = 0; while (retryCount < 100) { try { //this will have its own transaction repository.save(samples); return; } catch (ConcurrencyFailureException e) { retryCount += 1 ; log.warn("Retrying due to transient exception. Attempt number "+retryCount); try { Thread.sleep(random.nextInt(400)+100); } catch (InterruptedException e1) { //do nothing } } } throw new RuntimeException("Unable to save within "+retryCount+" retries"); } }
# ... existing code ... return; } catch (ConcurrencyFailureException e) { retryCount += 1 ; log.warn("Retrying due to transient exception. Attempt number "+retryCount); try { Thread.sleep(random.nextInt(400)+100); } catch (InterruptedException e1) { # ... modified code ... } } } throw new RuntimeException("Unable to save within "+retryCount+" retries"); } } # ... rest of the code ...
c72764fde63e14f378a9e31dd89ea4180655d379
nightreads/emails/management/commands/send_email.py
nightreads/emails/management/commands/send_email.py
from django.core.management.base import BaseCommand from nightreads.emails.models import Email from nightreads.emails.email_service import send_email_obj from nightreads.emails.views import get_subscriber_emails class Command(BaseCommand): help = 'Send the email to susbcribers' def handle(self, *args, **options): email_obj = Email.objects.filter(is_sent=False).first() if not email_obj: return email_obj.recipients = get_subscriber_emails(email_obj=email_obj) send_email_obj(email_obj=email_obj) email_obj.is_sent = True email_obj.targetted_users = len(email_obj.recipients) email_obj.save() self.stdout.write( self.style.SUCCESS('Successfully sent email {}'.format(email_obj)))
from django.core.management.base import BaseCommand from nightreads.emails.models import Email from nightreads.emails.email_service import send_email_obj from nightreads.emails.views import get_subscriber_emails class Command(BaseCommand): help = 'Send the email to susbcribers' def handle(self, *args, **options): email_obj = Email.objects.filter(is_sent=False).first() if not email_obj: self.stdout.write( self.style.SUCCESS('No emails available to send')) return email_obj.recipients = get_subscriber_emails(email_obj=email_obj) send_email_obj(email_obj=email_obj) email_obj.is_sent = True email_obj.targetted_users = len(email_obj.recipients) email_obj.save() self.stdout.write( self.style.SUCCESS('Successfully sent email {}'.format(email_obj)))
Add a note if no emails are available to send
Add a note if no emails are available to send
Python
mit
avinassh/nightreads,avinassh/nightreads
python
## Code Before: from django.core.management.base import BaseCommand from nightreads.emails.models import Email from nightreads.emails.email_service import send_email_obj from nightreads.emails.views import get_subscriber_emails class Command(BaseCommand): help = 'Send the email to susbcribers' def handle(self, *args, **options): email_obj = Email.objects.filter(is_sent=False).first() if not email_obj: return email_obj.recipients = get_subscriber_emails(email_obj=email_obj) send_email_obj(email_obj=email_obj) email_obj.is_sent = True email_obj.targetted_users = len(email_obj.recipients) email_obj.save() self.stdout.write( self.style.SUCCESS('Successfully sent email {}'.format(email_obj))) ## Instruction: Add a note if no emails are available to send ## Code After: from django.core.management.base import BaseCommand from nightreads.emails.models import Email from nightreads.emails.email_service import send_email_obj from nightreads.emails.views import get_subscriber_emails class Command(BaseCommand): help = 'Send the email to susbcribers' def handle(self, *args, **options): email_obj = Email.objects.filter(is_sent=False).first() if not email_obj: self.stdout.write( self.style.SUCCESS('No emails available to send')) return email_obj.recipients = get_subscriber_emails(email_obj=email_obj) send_email_obj(email_obj=email_obj) email_obj.is_sent = True email_obj.targetted_users = len(email_obj.recipients) email_obj.save() self.stdout.write( self.style.SUCCESS('Successfully sent email {}'.format(email_obj)))
// ... existing code ... def handle(self, *args, **options): email_obj = Email.objects.filter(is_sent=False).first() if not email_obj: self.stdout.write( self.style.SUCCESS('No emails available to send')) return email_obj.recipients = get_subscriber_emails(email_obj=email_obj) send_email_obj(email_obj=email_obj) // ... rest of the code ...
bc3032593b4e32d4487df926f77536920b61f393
src/test/java/io/github/bonigarcia/wdm/test/docker/DockerSafariTest.java
src/test/java/io/github/bonigarcia/wdm/test/docker/DockerSafariTest.java
/* * (C) Copyright 2021 Boni Garcia (https://bonigarcia.github.io/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.github.bonigarcia.wdm.test.docker; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.openqa.selenium.WebDriver; import io.github.bonigarcia.wdm.WebDriverManager; class DockerSafariTest { WebDriver driver; WebDriverManager wdm = WebDriverManager.safaridriver().browserInDocker(); @BeforeEach void setupTest() { driver = wdm.create(); } @AfterEach void teardown() { wdm.quit(); } @Test void test() { driver.get("https://bonigarcia.dev/selenium-webdriver-java/"); assertThat(driver.getTitle()).contains("Selenium WebDriver"); } }
/* * (C) Copyright 2021 Boni Garcia (https://bonigarcia.github.io/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.github.bonigarcia.wdm.test.docker; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.openqa.selenium.WebDriver; import io.github.bonigarcia.wdm.WebDriverManager; class DockerSafariTest { WebDriver driver; WebDriverManager wdm = WebDriverManager.safaridriver().browserInDocker(); @BeforeEach void setupTest() { driver = wdm.create(); } @AfterEach void teardown() { wdm.quit(); } @Test void test() { driver.get("https://github.com/bonigarcia/selenium-webdriver-java"); assertThat(driver.getTitle()).contains("Selenium WebDriver"); } }
Change SUT URL in Docker Safari test (due to DST Root CA X3 Expiration)
Change SUT URL in Docker Safari test (due to DST Root CA X3 Expiration)
Java
apache-2.0
bonigarcia/webdrivermanager,bonigarcia/webdrivermanager,bonigarcia/webdrivermanager
java
## Code Before: /* * (C) Copyright 2021 Boni Garcia (https://bonigarcia.github.io/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.github.bonigarcia.wdm.test.docker; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.openqa.selenium.WebDriver; import io.github.bonigarcia.wdm.WebDriverManager; class DockerSafariTest { WebDriver driver; WebDriverManager wdm = WebDriverManager.safaridriver().browserInDocker(); @BeforeEach void setupTest() { driver = wdm.create(); } @AfterEach void teardown() { wdm.quit(); } @Test void test() { driver.get("https://bonigarcia.dev/selenium-webdriver-java/"); assertThat(driver.getTitle()).contains("Selenium WebDriver"); } } ## Instruction: Change SUT URL in Docker Safari test (due to DST Root CA X3 Expiration) ## Code After: /* * (C) Copyright 2021 Boni Garcia (https://bonigarcia.github.io/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.github.bonigarcia.wdm.test.docker; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.openqa.selenium.WebDriver; import io.github.bonigarcia.wdm.WebDriverManager; class DockerSafariTest { WebDriver driver; WebDriverManager wdm = WebDriverManager.safaridriver().browserInDocker(); @BeforeEach void setupTest() { driver = wdm.create(); } @AfterEach void teardown() { wdm.quit(); } @Test void test() { driver.get("https://github.com/bonigarcia/selenium-webdriver-java"); assertThat(driver.getTitle()).contains("Selenium WebDriver"); } }
... @Test void test() { driver.get("https://github.com/bonigarcia/selenium-webdriver-java"); assertThat(driver.getTitle()).contains("Selenium WebDriver"); } ...
19cc42cbaa39854131c907115548abdd2cfdfc1b
todoist/managers/generic.py
todoist/managers/generic.py
class Manager(object): # should be re-defined in a subclass state_name = None object_type = None def __init__(self, api): self.api = api # shortcuts @property def state(self): return self.api.state @property def queue(self): return self.api.queue @property def token(self): return self.api.token class AllMixin(object): def all(self, filt=None): return list(filter(filt, self.state[self.state_name])) class GetByIdMixin(object): def get_by_id(self, obj_id, only_local=False): """ Finds and returns the object based on its id. """ for obj in self.state[self.state_name]: if obj['id'] == obj_id or obj.temp_id == str(obj_id): return obj if not only_local and self.object_type is not None: getter = getattr(self.api, '%s/get' % self.object_type) return getter(obj_id) return None class SyncMixin(object): """ Syncs this specific type of objects. """ def sync(self): return self.api.sync()
class Manager(object): # should be re-defined in a subclass state_name = None object_type = None def __init__(self, api): self.api = api # shortcuts @property def state(self): return self.api.state @property def queue(self): return self.api.queue @property def token(self): return self.api.token class AllMixin(object): def all(self, filt=None): return list(filter(filt, self.state[self.state_name])) class GetByIdMixin(object): def get_by_id(self, obj_id, only_local=False): """ Finds and returns the object based on its id. """ for obj in self.state[self.state_name]: if obj['id'] == obj_id or obj.temp_id == str(obj_id): return obj if not only_local and self.object_type is not None: getter = getattr(eval('self.api.%ss' % self.object_type) , 'get') return getter(obj_id) return None class SyncMixin(object): """ Syncs this specific type of objects. """ def sync(self): return self.api.sync()
Fix gettatr object and name.
Fix gettatr object and name.
Python
mit
Doist/todoist-python
python
## Code Before: class Manager(object): # should be re-defined in a subclass state_name = None object_type = None def __init__(self, api): self.api = api # shortcuts @property def state(self): return self.api.state @property def queue(self): return self.api.queue @property def token(self): return self.api.token class AllMixin(object): def all(self, filt=None): return list(filter(filt, self.state[self.state_name])) class GetByIdMixin(object): def get_by_id(self, obj_id, only_local=False): """ Finds and returns the object based on its id. """ for obj in self.state[self.state_name]: if obj['id'] == obj_id or obj.temp_id == str(obj_id): return obj if not only_local and self.object_type is not None: getter = getattr(self.api, '%s/get' % self.object_type) return getter(obj_id) return None class SyncMixin(object): """ Syncs this specific type of objects. """ def sync(self): return self.api.sync() ## Instruction: Fix gettatr object and name. ## Code After: class Manager(object): # should be re-defined in a subclass state_name = None object_type = None def __init__(self, api): self.api = api # shortcuts @property def state(self): return self.api.state @property def queue(self): return self.api.queue @property def token(self): return self.api.token class AllMixin(object): def all(self, filt=None): return list(filter(filt, self.state[self.state_name])) class GetByIdMixin(object): def get_by_id(self, obj_id, only_local=False): """ Finds and returns the object based on its id. """ for obj in self.state[self.state_name]: if obj['id'] == obj_id or obj.temp_id == str(obj_id): return obj if not only_local and self.object_type is not None: getter = getattr(eval('self.api.%ss' % self.object_type) , 'get') return getter(obj_id) return None class SyncMixin(object): """ Syncs this specific type of objects. """ def sync(self): return self.api.sync()
... return obj if not only_local and self.object_type is not None: getter = getattr(eval('self.api.%ss' % self.object_type) , 'get') return getter(obj_id) return None ...
edc830bcd8fb594406e314b5c93062b0ec347bba
cref/structure/__init__.py
cref/structure/__init__.py
from peptide import PeptideBuilder import Bio.PDB def write_pdb(aa_sequence, fragment_angles, gap_length, filepath): """ Generate pdb file with results :param aa_sequence: Amino acid sequence :param fragment_angles: Backbone torsion angles :param gap_length: Length of the gap at the sequence start and end :param filepath: Path to the file to save the pdb """ phi, psi = zip(*fragment_angles) structure = PeptideBuilder.make_structure(aa_sequence, phi, psi) out = Bio.PDB.PDBIO() out.set_structure(structure) out.save(filepath) def rmsd(source, target): source = Bio.PDB.parser.get_structure('source', source) target = Bio.PDB.parser.get_structure('target', target) superimposer = Bio.PDB.Superimposer() source_atoms = list(source.get_atoms()) target_atoms = list(target.get_atoms())[:len(source_atoms)] superimposer.set_atoms(source_atoms, target_atoms) return superimposer.rms
from peptide import PeptideBuilder import Bio.PDB def write_pdb(aa_sequence, fragment_angles, gap_length, filepath): """ Generate pdb file with results :param aa_sequence: Amino acid sequence :param fragment_angles: Backbone torsion angles :param gap_length: Length of the gap at the sequence start and end :param filepath: Path to the file to save the pdb """ phi, psi = zip(*fragment_angles) structure = PeptideBuilder.make_structure(aa_sequence, phi, psi) out = Bio.PDB.PDBIO() out.set_structure(structure) out.save(filepath) def rmsd(source, target): parser = Bio.PDB.PDBParser() source = parser.get_structure('source', source) target = parser.get_structure('target', target) superimposer = Bio.PDB.Superimposer() source_atoms = list(source.get_atoms()) target_atoms = list(target.get_atoms())[:len(source_atoms)] superimposer.set_atoms(source_atoms, target_atoms) return superimposer.rms
Fix wrong pdb parser invocation
Fix wrong pdb parser invocation
Python
mit
mchelem/cref2,mchelem/cref2,mchelem/cref2
python
## Code Before: from peptide import PeptideBuilder import Bio.PDB def write_pdb(aa_sequence, fragment_angles, gap_length, filepath): """ Generate pdb file with results :param aa_sequence: Amino acid sequence :param fragment_angles: Backbone torsion angles :param gap_length: Length of the gap at the sequence start and end :param filepath: Path to the file to save the pdb """ phi, psi = zip(*fragment_angles) structure = PeptideBuilder.make_structure(aa_sequence, phi, psi) out = Bio.PDB.PDBIO() out.set_structure(structure) out.save(filepath) def rmsd(source, target): source = Bio.PDB.parser.get_structure('source', source) target = Bio.PDB.parser.get_structure('target', target) superimposer = Bio.PDB.Superimposer() source_atoms = list(source.get_atoms()) target_atoms = list(target.get_atoms())[:len(source_atoms)] superimposer.set_atoms(source_atoms, target_atoms) return superimposer.rms ## Instruction: Fix wrong pdb parser invocation ## Code After: from peptide import PeptideBuilder import Bio.PDB def write_pdb(aa_sequence, fragment_angles, gap_length, filepath): """ Generate pdb file with results :param aa_sequence: Amino acid sequence :param fragment_angles: Backbone torsion angles :param gap_length: Length of the gap at the sequence start and end :param filepath: Path to the file to save the pdb """ phi, psi = zip(*fragment_angles) structure = PeptideBuilder.make_structure(aa_sequence, phi, psi) out = Bio.PDB.PDBIO() out.set_structure(structure) out.save(filepath) def rmsd(source, target): parser = Bio.PDB.PDBParser() source = parser.get_structure('source', source) target = parser.get_structure('target', target) superimposer = Bio.PDB.Superimposer() source_atoms = list(source.get_atoms()) target_atoms = list(target.get_atoms())[:len(source_atoms)] superimposer.set_atoms(source_atoms, target_atoms) return superimposer.rms
# ... existing code ... def rmsd(source, target): parser = Bio.PDB.PDBParser() source = parser.get_structure('source', source) target = parser.get_structure('target', target) superimposer = Bio.PDB.Superimposer() source_atoms = list(source.get_atoms()) # ... rest of the code ...
c7761a3b8a090e24b68b1318f1451752e34078e9
alexandria/decorators.py
alexandria/decorators.py
from functools import wraps from flask import session, redirect, url_for, request, abort from alexandria import mongo def not_even_one(f): @wraps(f) def decorated_function(*args, **kwargs): if mongo.Books.find_one() is None: return redirect(url_for('upload')) return f(*args, **kwargs) return decorated_function def authenticated(f): @wraps(f) def decorated_function(*args, **kwargs): print request.method if request.method == 'GET': token = request.args.get('token') user = mongo.Users.find_one({'tokens.token': token}) if not (token and user): #abort(403) pass elif request.method == 'POST': token = request.form.get('token') user = mongo.Users.find_one({'tokens.token': token}) if not (token and user): #abort(403) pass else: #abort(405) pass return f(*args, **kwargs) return decorated_function def administrator(f): @wraps(f) def decorated_function(*args, **kwargs): user = mongo.Users.find_one({'username': session.get('username')}) if user['role'] != 0: return redirect(url_for('index')) return f(*args, **kwargs) return decorated_function
from functools import wraps from flask import session, redirect, url_for, request, abort from alexandria import mongo def not_even_one(f): @wraps(f) def decorated_function(*args, **kwargs): if mongo.Books.find_one() is None: return redirect(url_for('upload')) return f(*args, **kwargs) return decorated_function def authenticated(f): @wraps(f) def decorated_function(*args, **kwargs): print request.method if request.method == 'GET': token = request.args.get('token') user = mongo.Users.find_one({'tokens.token': token}) if not (token and user): abort(403) elif request.method == 'POST': token = request.form.get('token') user = mongo.Users.find_one({'tokens.token': token}) if not (token and user): abort(403) else: abort(405) return f(*args, **kwargs) return decorated_function def administrator(f): @wraps(f) def decorated_function(*args, **kwargs): user = mongo.Users.find_one({'username': session.get('username')}) if user['role'] != 0: return redirect(url_for('index')) return f(*args, **kwargs) return decorated_function
Abort with appropriate status codes in the decorator
Abort with appropriate status codes in the decorator
Python
mit
citruspi/Alexandria,citruspi/Alexandria
python
## Code Before: from functools import wraps from flask import session, redirect, url_for, request, abort from alexandria import mongo def not_even_one(f): @wraps(f) def decorated_function(*args, **kwargs): if mongo.Books.find_one() is None: return redirect(url_for('upload')) return f(*args, **kwargs) return decorated_function def authenticated(f): @wraps(f) def decorated_function(*args, **kwargs): print request.method if request.method == 'GET': token = request.args.get('token') user = mongo.Users.find_one({'tokens.token': token}) if not (token and user): #abort(403) pass elif request.method == 'POST': token = request.form.get('token') user = mongo.Users.find_one({'tokens.token': token}) if not (token and user): #abort(403) pass else: #abort(405) pass return f(*args, **kwargs) return decorated_function def administrator(f): @wraps(f) def decorated_function(*args, **kwargs): user = mongo.Users.find_one({'username': session.get('username')}) if user['role'] != 0: return redirect(url_for('index')) return f(*args, **kwargs) return decorated_function ## Instruction: Abort with appropriate status codes in the decorator ## Code After: from functools import wraps from flask import session, redirect, url_for, request, abort from alexandria import mongo def not_even_one(f): @wraps(f) def decorated_function(*args, **kwargs): if mongo.Books.find_one() is None: return redirect(url_for('upload')) return f(*args, **kwargs) return decorated_function def authenticated(f): @wraps(f) def decorated_function(*args, **kwargs): print request.method if request.method == 'GET': token = request.args.get('token') user = mongo.Users.find_one({'tokens.token': token}) if not (token and user): abort(403) elif request.method == 'POST': token = request.form.get('token') user = mongo.Users.find_one({'tokens.token': token}) if not (token and user): abort(403) else: abort(405) return f(*args, **kwargs) return decorated_function def administrator(f): @wraps(f) def decorated_function(*args, **kwargs): user = mongo.Users.find_one({'username': session.get('username')}) if user['role'] != 0: return redirect(url_for('index')) return f(*args, **kwargs) return decorated_function
// ... existing code ... if not (token and user): abort(403) elif request.method == 'POST': // ... modified code ... if not (token and user): abort(403) else: abort(405) return f(*args, **kwargs) return decorated_function // ... rest of the code ...
816c6239c4bab98562198b2dd4f87d1b2f7f7df6
Atarashii/src/net/somethingdreadful/MAL/LogoutConfirmationDialogFragment.java
Atarashii/src/net/somethingdreadful/MAL/LogoutConfirmationDialogFragment.java
package net.somethingdreadful.MAL; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.ContextThemeWrapper; import com.actionbarsherlock.app.SherlockDialogFragment; public class LogoutConfirmationDialogFragment extends SherlockDialogFragment { public LogoutConfirmationDialogFragment() {} public interface LogoutConfirmationDialogListener { void onLogoutConfirmed(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), R.style.AlertDialog)); builder.setPositiveButton(R.string.dialog_logout_label_confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { ((Home) getActivity()).onLogoutConfirmed(); dismiss(); } }) .setNegativeButton(R.string.dialog_label_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismiss(); } }) .setTitle(R.string.dialog_logout_title).setMessage(R.string.dialog_logout_message); return builder.create(); } @Override public void onDismiss(DialogInterface dialog) {} @Override public void onCancel(DialogInterface dialog) { startActivity(new Intent(getActivity(), Home.class)); this.dismiss(); } }
package net.somethingdreadful.MAL; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.ContextThemeWrapper; import com.actionbarsherlock.app.SherlockDialogFragment; public class LogoutConfirmationDialogFragment extends SherlockDialogFragment { public LogoutConfirmationDialogFragment() {} public interface LogoutConfirmationDialogListener { void onLogoutConfirmed(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), R.style.AlertDialog)); builder.setPositiveButton(R.string.dialog_logout_label_confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { ((Home) getActivity()).onLogoutConfirmed(); dismiss(); } }) .setNegativeButton(R.string.dialog_label_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismiss(); } }) .setTitle(R.string.dialog_logout_title).setMessage(R.string.dialog_logout_message); return builder.create(); } @Override public void onDismiss(DialogInterface dialog) {} @Override public void onCancel(DialogInterface dialog) { // startActivity(new Intent(getActivity(), Home.class)); //Relaunching Home without needing to, causes bad things this.dismiss(); } }
Fix Logout Dialog Recreating Home
Fix Logout Dialog Recreating Home The logout dialog was launching a new instance of the home activity every time it was dismissed by touching outside the dialog instead of through the proper Cancel button. This commit is just a quick fix to fix that.
Java
bsd-2-clause
ratan12/Atarashii,AnimeNeko/Atarashii,AnimeNeko/Atarashii,ratan12/Atarashii
java
## Code Before: package net.somethingdreadful.MAL; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.ContextThemeWrapper; import com.actionbarsherlock.app.SherlockDialogFragment; public class LogoutConfirmationDialogFragment extends SherlockDialogFragment { public LogoutConfirmationDialogFragment() {} public interface LogoutConfirmationDialogListener { void onLogoutConfirmed(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), R.style.AlertDialog)); builder.setPositiveButton(R.string.dialog_logout_label_confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { ((Home) getActivity()).onLogoutConfirmed(); dismiss(); } }) .setNegativeButton(R.string.dialog_label_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismiss(); } }) .setTitle(R.string.dialog_logout_title).setMessage(R.string.dialog_logout_message); return builder.create(); } @Override public void onDismiss(DialogInterface dialog) {} @Override public void onCancel(DialogInterface dialog) { startActivity(new Intent(getActivity(), Home.class)); this.dismiss(); } } ## Instruction: Fix Logout Dialog Recreating Home The logout dialog was launching a new instance of the home activity every time it was dismissed by touching outside the dialog instead of through the proper Cancel button. This commit is just a quick fix to fix that. ## Code After: package net.somethingdreadful.MAL; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.ContextThemeWrapper; import com.actionbarsherlock.app.SherlockDialogFragment; public class LogoutConfirmationDialogFragment extends SherlockDialogFragment { public LogoutConfirmationDialogFragment() {} public interface LogoutConfirmationDialogListener { void onLogoutConfirmed(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), R.style.AlertDialog)); builder.setPositiveButton(R.string.dialog_logout_label_confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { ((Home) getActivity()).onLogoutConfirmed(); dismiss(); } }) .setNegativeButton(R.string.dialog_label_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismiss(); } }) .setTitle(R.string.dialog_logout_title).setMessage(R.string.dialog_logout_message); return builder.create(); } @Override public void onDismiss(DialogInterface dialog) {} @Override public void onCancel(DialogInterface dialog) { // startActivity(new Intent(getActivity(), Home.class)); //Relaunching Home without needing to, causes bad things this.dismiss(); } }
# ... existing code ... import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.ContextThemeWrapper; # ... modified code ... @Override public void onCancel(DialogInterface dialog) { // startActivity(new Intent(getActivity(), Home.class)); //Relaunching Home without needing to, causes bad things this.dismiss(); } # ... rest of the code ...
502e01be7fdf427e3fbbf03887bbb323d8c74d43
src/pi/pushrpc.py
src/pi/pushrpc.py
"""Pusher intergration for messages from the cloud.""" import json import logging import Queue import sys from common import creds from pusherclient import Pusher class PushRPC(object): """Wrapper for pusher integration.""" def __init__(self): self._queue = Queue.Queue() self._pusher = Pusher(creds.pusher_key) self._pusher.connection.bind('pusher:connection_established', self._connect_handler) self._pusher.connect() def _connect_handler(self, _): channel = self._pusher.subscribe('test') channel.bind('event', self._callback_handler) def _callback_handler(self, data): """Callback for when messages are recieved from pusher.""" try: data = json.loads(data) except ValueError: logging.error('Error parsing message', exc_info=sys.exc_info()) return self._queue.put(data) def events(self): while True: yield self._queue.get(block=True)
"""Pusher intergration for messages from the cloud.""" import json import logging import Queue import sys from common import creds from pusherclient import Pusher class PushRPC(object): """Wrapper for pusher integration.""" def __init__(self): self._queue = Queue.Queue() self._pusher = Pusher(creds.pusher_key) self._pusher.connection.bind('pusher:connection_established', self._connect_handler) self._pusher.connect() def _connect_handler(self, _): channel = self._pusher.subscribe('test') channel.bind('event', self._callback_handler) def _callback_handler(self, data): """Callback for when messages are recieved from pusher.""" try: data = json.loads(data) except ValueError: logging.error('Error parsing message', exc_info=sys.exc_info()) return self._queue.put(data) def events(self): while True: # if we specify a timeout, queues become keyboard interruptable try: yield self._queue.get(block=True, timeout=1000) except Queue.Empty: pass
Make the script respond to ctrl-c
Make the script respond to ctrl-c
Python
mit
tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation
python
## Code Before: """Pusher intergration for messages from the cloud.""" import json import logging import Queue import sys from common import creds from pusherclient import Pusher class PushRPC(object): """Wrapper for pusher integration.""" def __init__(self): self._queue = Queue.Queue() self._pusher = Pusher(creds.pusher_key) self._pusher.connection.bind('pusher:connection_established', self._connect_handler) self._pusher.connect() def _connect_handler(self, _): channel = self._pusher.subscribe('test') channel.bind('event', self._callback_handler) def _callback_handler(self, data): """Callback for when messages are recieved from pusher.""" try: data = json.loads(data) except ValueError: logging.error('Error parsing message', exc_info=sys.exc_info()) return self._queue.put(data) def events(self): while True: yield self._queue.get(block=True) ## Instruction: Make the script respond to ctrl-c ## Code After: """Pusher intergration for messages from the cloud.""" import json import logging import Queue import sys from common import creds from pusherclient import Pusher class PushRPC(object): """Wrapper for pusher integration.""" def __init__(self): self._queue = Queue.Queue() self._pusher = Pusher(creds.pusher_key) self._pusher.connection.bind('pusher:connection_established', self._connect_handler) self._pusher.connect() def _connect_handler(self, _): channel = self._pusher.subscribe('test') channel.bind('event', self._callback_handler) def _callback_handler(self, data): """Callback for when messages are recieved from pusher.""" try: data = json.loads(data) except ValueError: logging.error('Error parsing message', exc_info=sys.exc_info()) return self._queue.put(data) def events(self): while True: # if we specify a timeout, queues become keyboard interruptable try: yield self._queue.get(block=True, timeout=1000) except Queue.Empty: pass
# ... existing code ... def events(self): while True: # if we specify a timeout, queues become keyboard interruptable try: yield self._queue.get(block=True, timeout=1000) except Queue.Empty: pass # ... rest of the code ...
054e38ffb08216634befba3f5bf6f5a3684fdfc8
dev/plugins/hu.elte.txtuml.validation/src/hu/elte/txtuml/validation/model/ModelValidationError.java
dev/plugins/hu.elte.txtuml.validation/src/hu/elte/txtuml/validation/model/ModelValidationError.java
package hu.elte.txtuml.validation.model; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.TypeDeclaration; import hu.elte.txtuml.validation.common.AbstractValidationError; import hu.elte.txtuml.validation.common.SourceInfo; /** * Base class for all JtxtUML model validation errors. */ public abstract class ModelValidationError extends AbstractValidationError { public ModelValidationError(SourceInfo sourceInfo, ASTNode node) { super(sourceInfo, node); Class<?> c = ASTNode.nodeClassForType(node.getNodeType()); if (c == MethodDeclaration.class || c == TypeDeclaration.class) { SimpleName name; if (c == MethodDeclaration.class) { name = ((MethodDeclaration) node).getName(); } else { name = ((TypeDeclaration) node).getName(); } this.sourceStart = name.getStartPosition(); this.sourceEnd = name.getStartPosition() + name.getLength(); } } @Override public String getMarkerType() { return JtxtUMLModelCompilationParticipant.JTXTUML_MODEL_MARKER_TYPE; } @Override public String toString() { return getType() + " (" + getMessage() + ")"; } }
package hu.elte.txtuml.validation.model; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.TypeDeclaration; import hu.elte.txtuml.validation.common.AbstractValidationError; import hu.elte.txtuml.validation.common.SourceInfo; /** * Base class for all JtxtUML model validation errors. */ public abstract class ModelValidationError extends AbstractValidationError { public ModelValidationError(SourceInfo sourceInfo, ASTNode node) { super(sourceInfo, node); if (node instanceof MethodDeclaration || node instanceof TypeDeclaration) { SimpleName name; if (node instanceof MethodDeclaration) { name = ((MethodDeclaration) node).getName(); } else { name = ((TypeDeclaration) node).getName(); } this.sourceStart = name.getStartPosition(); this.sourceEnd = name.getStartPosition() + name.getLength(); } } @Override public String getMarkerType() { return JtxtUMLModelCompilationParticipant.JTXTUML_MODEL_MARKER_TYPE; } @Override public String toString() { return getType() + " (" + getMessage() + ")"; } }
Replace class equality test with instanceof
Replace class equality test with instanceof
Java
epl-1.0
ELTE-Soft/txtUML,ELTE-Soft/txtUML,ELTE-Soft/txtUML,ELTE-Soft/txtUML
java
## Code Before: package hu.elte.txtuml.validation.model; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.TypeDeclaration; import hu.elte.txtuml.validation.common.AbstractValidationError; import hu.elte.txtuml.validation.common.SourceInfo; /** * Base class for all JtxtUML model validation errors. */ public abstract class ModelValidationError extends AbstractValidationError { public ModelValidationError(SourceInfo sourceInfo, ASTNode node) { super(sourceInfo, node); Class<?> c = ASTNode.nodeClassForType(node.getNodeType()); if (c == MethodDeclaration.class || c == TypeDeclaration.class) { SimpleName name; if (c == MethodDeclaration.class) { name = ((MethodDeclaration) node).getName(); } else { name = ((TypeDeclaration) node).getName(); } this.sourceStart = name.getStartPosition(); this.sourceEnd = name.getStartPosition() + name.getLength(); } } @Override public String getMarkerType() { return JtxtUMLModelCompilationParticipant.JTXTUML_MODEL_MARKER_TYPE; } @Override public String toString() { return getType() + " (" + getMessage() + ")"; } } ## Instruction: Replace class equality test with instanceof ## Code After: package hu.elte.txtuml.validation.model; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.TypeDeclaration; import hu.elte.txtuml.validation.common.AbstractValidationError; import hu.elte.txtuml.validation.common.SourceInfo; /** * Base class for all JtxtUML model validation errors. */ public abstract class ModelValidationError extends AbstractValidationError { public ModelValidationError(SourceInfo sourceInfo, ASTNode node) { super(sourceInfo, node); if (node instanceof MethodDeclaration || node instanceof TypeDeclaration) { SimpleName name; if (node instanceof MethodDeclaration) { name = ((MethodDeclaration) node).getName(); } else { name = ((TypeDeclaration) node).getName(); } this.sourceStart = name.getStartPosition(); this.sourceEnd = name.getStartPosition() + name.getLength(); } } @Override public String getMarkerType() { return JtxtUMLModelCompilationParticipant.JTXTUML_MODEL_MARKER_TYPE; } @Override public String toString() { return getType() + " (" + getMessage() + ")"; } }
... public ModelValidationError(SourceInfo sourceInfo, ASTNode node) { super(sourceInfo, node); if (node instanceof MethodDeclaration || node instanceof TypeDeclaration) { SimpleName name; if (node instanceof MethodDeclaration) { name = ((MethodDeclaration) node).getName(); } else { name = ((TypeDeclaration) node).getName(); ...
a2d4381de5dc50110a0e57d7e56a668edbee2ccf
bot/utils.py
bot/utils.py
from discord import Embed def build_embed(ctx, desc: str, title: str = ''): name = ctx.message.server.me.nick if ctx.message.server.me.nick is not None else ctx.bot.user.name embed = Embed( title=title, description=desc ) embed.set_author(name=name, icon_url=ctx.bot.user.avatar_url) return embed
from enum import IntEnum from discord import Embed class OpStatus(IntEnum): SUCCESS = 0x2ECC71, FAILURE = 0xc0392B, WARNING = 0xf39C12 def build_embed(ctx, desc: str, title: str = '', status: OpStatus = OpStatus.SUCCESS) -> Embed: name = ctx.message.server.me.nick if ctx.message.server.me.nick is not None else ctx.bot.user.name embed = Embed( title=title, description=desc, color=status.value if status is not None else OpStatus.WARNING ) embed.set_author(name=name, icon_url=ctx.bot.user.avatar_url) return embed
Add support for colored output in embeds
Add support for colored output in embeds
Python
apache-2.0
HellPie/discord-reply-bot
python
## Code Before: from discord import Embed def build_embed(ctx, desc: str, title: str = ''): name = ctx.message.server.me.nick if ctx.message.server.me.nick is not None else ctx.bot.user.name embed = Embed( title=title, description=desc ) embed.set_author(name=name, icon_url=ctx.bot.user.avatar_url) return embed ## Instruction: Add support for colored output in embeds ## Code After: from enum import IntEnum from discord import Embed class OpStatus(IntEnum): SUCCESS = 0x2ECC71, FAILURE = 0xc0392B, WARNING = 0xf39C12 def build_embed(ctx, desc: str, title: str = '', status: OpStatus = OpStatus.SUCCESS) -> Embed: name = ctx.message.server.me.nick if ctx.message.server.me.nick is not None else ctx.bot.user.name embed = Embed( title=title, description=desc, color=status.value if status is not None else OpStatus.WARNING ) embed.set_author(name=name, icon_url=ctx.bot.user.avatar_url) return embed
# ... existing code ... from enum import IntEnum from discord import Embed class OpStatus(IntEnum): SUCCESS = 0x2ECC71, FAILURE = 0xc0392B, WARNING = 0xf39C12 def build_embed(ctx, desc: str, title: str = '', status: OpStatus = OpStatus.SUCCESS) -> Embed: name = ctx.message.server.me.nick if ctx.message.server.me.nick is not None else ctx.bot.user.name embed = Embed( title=title, description=desc, color=status.value if status is not None else OpStatus.WARNING ) embed.set_author(name=name, icon_url=ctx.bot.user.avatar_url) return embed # ... rest of the code ...
3e4707a3f25f3a2f84f811394d738cebc1ca9f19
mygpo/search/models.py
mygpo/search/models.py
""" Wrappers for the results of a search """ class PodcastResult(object): """ Wrapper for a Podcast search result """ @classmethod def from_doc(cls, doc): """ Construct a PodcastResult from a search result """ obj = cls() for key, val in doc['_source'].items(): setattr(obj, key, val) obj.id = doc['_id'] return obj @property def slug(self): return next(iter(self.slugs), None) @property def url(self): return next(iter(self.urls), None) def get_id(self): return self.id @property def display_title(self): return self.title
""" Wrappers for the results of a search """ import uuid class PodcastResult(object): """ Wrapper for a Podcast search result """ @classmethod def from_doc(cls, doc): """ Construct a PodcastResult from a search result """ obj = cls() for key, val in doc['_source'].items(): setattr(obj, key, val) obj.id = uuid.UUID(doc['_id']).hex return obj @property def slug(self): return next(iter(self.slugs), None) @property def url(self): return next(iter(self.urls), None) def get_id(self): return self.id @property def display_title(self): return self.title
Fix parsing UUID in search results
Fix parsing UUID in search results
Python
agpl-3.0
gpodder/mygpo,gpodder/mygpo,gpodder/mygpo,gpodder/mygpo
python
## Code Before: """ Wrappers for the results of a search """ class PodcastResult(object): """ Wrapper for a Podcast search result """ @classmethod def from_doc(cls, doc): """ Construct a PodcastResult from a search result """ obj = cls() for key, val in doc['_source'].items(): setattr(obj, key, val) obj.id = doc['_id'] return obj @property def slug(self): return next(iter(self.slugs), None) @property def url(self): return next(iter(self.urls), None) def get_id(self): return self.id @property def display_title(self): return self.title ## Instruction: Fix parsing UUID in search results ## Code After: """ Wrappers for the results of a search """ import uuid class PodcastResult(object): """ Wrapper for a Podcast search result """ @classmethod def from_doc(cls, doc): """ Construct a PodcastResult from a search result """ obj = cls() for key, val in doc['_source'].items(): setattr(obj, key, val) obj.id = uuid.UUID(doc['_id']).hex return obj @property def slug(self): return next(iter(self.slugs), None) @property def url(self): return next(iter(self.urls), None) def get_id(self): return self.id @property def display_title(self): return self.title
# ... existing code ... """ Wrappers for the results of a search """ import uuid class PodcastResult(object): # ... modified code ... for key, val in doc['_source'].items(): setattr(obj, key, val) obj.id = uuid.UUID(doc['_id']).hex return obj @property # ... rest of the code ...
a800bacf217ef903fd266e1fbf8103365ab64c94
source/segue/frontend/exporter.py
source/segue/frontend/exporter.py
from PySide import QtGui from .selector import SelectorWidget from .options import OptionsWidget class ExporterWidget(QtGui.QWidget): '''Manage exporting.''' def __init__(self, host, parent=None): '''Initialise with *host* application and *parent*.''' super(ExporterWidget, self).__init__(parent=parent) self.host = host self.build() self.post_build() def build(self): '''Build and layout the interface.''' self.setLayout(QtGui.QVBoxLayout()) self.selector_widget = SelectorWidget(host=self.host) self.selector_widget.setFrameStyle( QtGui.QFrame.StyledPanel ) self.layout().addWidget(self.selector_widget) self.options_widget = OptionsWidget(host=self.host) self.options_widget.setFrameStyle( QtGui.QFrame.StyledPanel ) self.layout().addWidget(self.options_widget) self.export_button = QtGui.QPushButton('Export') self.layout().addWidget(self.export_button) def post_build(self): '''Perform post-build operations.''' self.setWindowTitle('Segue Exporter')
from PySide import QtGui from .selector import SelectorWidget from .options import OptionsWidget class ExporterWidget(QtGui.QWidget): '''Manage exporting.''' def __init__(self, host, parent=None): '''Initialise with *host* application and *parent*.''' super(ExporterWidget, self).__init__(parent=parent) self.host = host self.build() self.post_build() def build(self): '''Build and layout the interface.''' self.setLayout(QtGui.QVBoxLayout()) self.selector_widget = SelectorWidget(host=self.host) self.selector_widget.setFrameStyle( QtGui.QFrame.StyledPanel ) self.layout().addWidget(self.selector_widget) self.options_widget = OptionsWidget(host=self.host) self.options_widget.setFrameStyle( QtGui.QFrame.StyledPanel ) self.layout().addWidget(self.options_widget) self.export_button = QtGui.QPushButton('Export') self.layout().addWidget(self.export_button) def post_build(self): '''Perform post-build operations.''' self.setWindowTitle('Segue Exporter') self.selector_widget.added.connect(self.on_selection_changed) self.selector_widget.removed.connect(self.on_selection_changed) self.validate() def on_selection_changed(self, items): '''Handle selection change.''' self.validate() def validate(self): '''Validate options and update UI state.''' self.export_button.setEnabled(False) if not self.selector_widget.items(): return self.export_button.setEnabled(True)
Add basic validation of ui state.
Add basic validation of ui state.
Python
apache-2.0
4degrees/segue
python
## Code Before: from PySide import QtGui from .selector import SelectorWidget from .options import OptionsWidget class ExporterWidget(QtGui.QWidget): '''Manage exporting.''' def __init__(self, host, parent=None): '''Initialise with *host* application and *parent*.''' super(ExporterWidget, self).__init__(parent=parent) self.host = host self.build() self.post_build() def build(self): '''Build and layout the interface.''' self.setLayout(QtGui.QVBoxLayout()) self.selector_widget = SelectorWidget(host=self.host) self.selector_widget.setFrameStyle( QtGui.QFrame.StyledPanel ) self.layout().addWidget(self.selector_widget) self.options_widget = OptionsWidget(host=self.host) self.options_widget.setFrameStyle( QtGui.QFrame.StyledPanel ) self.layout().addWidget(self.options_widget) self.export_button = QtGui.QPushButton('Export') self.layout().addWidget(self.export_button) def post_build(self): '''Perform post-build operations.''' self.setWindowTitle('Segue Exporter') ## Instruction: Add basic validation of ui state. ## Code After: from PySide import QtGui from .selector import SelectorWidget from .options import OptionsWidget class ExporterWidget(QtGui.QWidget): '''Manage exporting.''' def __init__(self, host, parent=None): '''Initialise with *host* application and *parent*.''' super(ExporterWidget, self).__init__(parent=parent) self.host = host self.build() self.post_build() def build(self): '''Build and layout the interface.''' self.setLayout(QtGui.QVBoxLayout()) self.selector_widget = SelectorWidget(host=self.host) self.selector_widget.setFrameStyle( QtGui.QFrame.StyledPanel ) self.layout().addWidget(self.selector_widget) self.options_widget = OptionsWidget(host=self.host) self.options_widget.setFrameStyle( QtGui.QFrame.StyledPanel ) self.layout().addWidget(self.options_widget) self.export_button = QtGui.QPushButton('Export') self.layout().addWidget(self.export_button) def post_build(self): '''Perform post-build operations.''' self.setWindowTitle('Segue Exporter') self.selector_widget.added.connect(self.on_selection_changed) self.selector_widget.removed.connect(self.on_selection_changed) self.validate() def on_selection_changed(self, items): '''Handle selection change.''' self.validate() def validate(self): '''Validate options and update UI state.''' self.export_button.setEnabled(False) if not self.selector_widget.items(): return self.export_button.setEnabled(True)
... '''Perform post-build operations.''' self.setWindowTitle('Segue Exporter') self.selector_widget.added.connect(self.on_selection_changed) self.selector_widget.removed.connect(self.on_selection_changed) self.validate() def on_selection_changed(self, items): '''Handle selection change.''' self.validate() def validate(self): '''Validate options and update UI state.''' self.export_button.setEnabled(False) if not self.selector_widget.items(): return self.export_button.setEnabled(True) ...
7c5cf5eb9b59a499ab480ea571cbb9d8203c1a79
tests/test_gdal.py
tests/test_gdal.py
import pytest from imageio.testing import run_tests_if_main, get_test_dir import imageio from imageio.core import get_remote_file test_dir = get_test_dir() try: from osgeo import gdal except ImportError: gdal = None @pytest.mark.skipif('gdal is None') def test_gdal_reading(): """ Test reading gdal""" filename = get_remote_file('images/geotiff.tif') im = imageio.imread(filename, 'gdal') assert im.shape == (929, 699) R = imageio.read(filename, 'gdal') assert R.format.name == 'GDAL' meta_data = R.get_meta_data() assert 'TIFFTAG_XRESOLUTION' in meta_data # Fail raises = pytest.raises raises(IndexError, R.get_data, -1) raises(IndexError, R.get_data, 3) run_tests_if_main()
import pytest from imageio.testing import run_tests_if_main, get_test_dir, need_internet import imageio from imageio.core import get_remote_file test_dir = get_test_dir() try: from osgeo import gdal except ImportError: gdal = None @pytest.mark.skipif('gdal is None') def test_gdal_reading(): """ Test reading gdal""" need_internet() filename = get_remote_file('images/geotiff.tif') im = imageio.imread(filename, 'gdal') assert im.shape == (929, 699) R = imageio.read(filename, 'gdal') assert R.format.name == 'GDAL' meta_data = R.get_meta_data() assert 'TIFFTAG_XRESOLUTION' in meta_data # Fail raises = pytest.raises raises(IndexError, R.get_data, -1) raises(IndexError, R.get_data, 3) run_tests_if_main()
Mark gdal tests as requiring internet
Mark gdal tests as requiring internet
Python
bsd-2-clause
imageio/imageio
python
## Code Before: import pytest from imageio.testing import run_tests_if_main, get_test_dir import imageio from imageio.core import get_remote_file test_dir = get_test_dir() try: from osgeo import gdal except ImportError: gdal = None @pytest.mark.skipif('gdal is None') def test_gdal_reading(): """ Test reading gdal""" filename = get_remote_file('images/geotiff.tif') im = imageio.imread(filename, 'gdal') assert im.shape == (929, 699) R = imageio.read(filename, 'gdal') assert R.format.name == 'GDAL' meta_data = R.get_meta_data() assert 'TIFFTAG_XRESOLUTION' in meta_data # Fail raises = pytest.raises raises(IndexError, R.get_data, -1) raises(IndexError, R.get_data, 3) run_tests_if_main() ## Instruction: Mark gdal tests as requiring internet ## Code After: import pytest from imageio.testing import run_tests_if_main, get_test_dir, need_internet import imageio from imageio.core import get_remote_file test_dir = get_test_dir() try: from osgeo import gdal except ImportError: gdal = None @pytest.mark.skipif('gdal is None') def test_gdal_reading(): """ Test reading gdal""" need_internet() filename = get_remote_file('images/geotiff.tif') im = imageio.imread(filename, 'gdal') assert im.shape == (929, 699) R = imageio.read(filename, 'gdal') assert R.format.name == 'GDAL' meta_data = R.get_meta_data() assert 'TIFFTAG_XRESOLUTION' in meta_data # Fail raises = pytest.raises raises(IndexError, R.get_data, -1) raises(IndexError, R.get_data, 3) run_tests_if_main()
// ... existing code ... import pytest from imageio.testing import run_tests_if_main, get_test_dir, need_internet import imageio from imageio.core import get_remote_file // ... modified code ... @pytest.mark.skipif('gdal is None') def test_gdal_reading(): """ Test reading gdal""" need_internet() filename = get_remote_file('images/geotiff.tif') im = imageio.imread(filename, 'gdal') // ... rest of the code ...
533194b5b8e044bca2aaeccff4d550731922b3b8
genome_designer/conf/demo_settings.py
genome_designer/conf/demo_settings.py
# Views that are visible in demo mode. DEMO_SAFE_VIEWS = [ 'main.views.home_view', 'main.views.project_list_view', 'main.views.project_view', 'main.views.tab_root_analyze', 'main.views.reference_genome_list_view', 'main.views.reference_genome_view', 'main.views.sample_list_view', 'main.views.alignment_list_view', 'main.views.alignment_view', 'main.views.sample_alignment_error_view', 'main.views.variant_set_list_view', 'main.views.variant_set_view', 'main.views.single_variant_view', 'main.xhr_handlers.get_variant_list', 'main.xhr_handlers.get_variant_set_list', 'main.xhr_handlers.get_gene_list', 'main.xhr_handlers.get_alignment_groups', 'main.xhr_handlers.is_materialized_view_valid', 'main.xhr_handlers.get_ref_genomes', 'main.xhr_handlers.compile_jbrowse_and_redirect', 'main.template_xhrs.variant_filter_controls', ]
# Views that are visible in demo mode. DEMO_SAFE_VIEWS = [ 'main.views.home_view', 'main.views.project_list_view', 'main.views.project_view', 'main.views.tab_root_analyze', 'main.views.reference_genome_list_view', 'main.views.reference_genome_view', 'main.views.sample_list_view', 'main.views.alignment_list_view', 'main.views.alignment_view', 'main.views.sample_alignment_error_view', 'main.views.variant_set_list_view', 'main.views.variant_set_view', 'main.views.single_variant_view', 'main.xhr_handlers.get_variant_list', 'main.xhr_handlers.get_variant_set_list', 'main.xhr_handlers.get_gene_list', 'main.xhr_handlers.get_alignment_groups', 'main.xhr_handlers.is_materialized_view_valid', 'main.xhr_handlers.get_ref_genomes', 'main.xhr_handlers.compile_jbrowse_and_redirect', 'main.template_xhrs.variant_filter_controls', 'main.demo_view_overrides.login_demo_account', 'django.contrib.auth.views.logout' ]
Add login and logout to allowed views in DEMO_MODE.
Add login and logout to allowed views in DEMO_MODE.
Python
mit
woodymit/millstone,churchlab/millstone,churchlab/millstone,woodymit/millstone_accidental_source,woodymit/millstone,woodymit/millstone,woodymit/millstone,woodymit/millstone_accidental_source,churchlab/millstone,woodymit/millstone_accidental_source,churchlab/millstone,woodymit/millstone_accidental_source
python
## Code Before: # Views that are visible in demo mode. DEMO_SAFE_VIEWS = [ 'main.views.home_view', 'main.views.project_list_view', 'main.views.project_view', 'main.views.tab_root_analyze', 'main.views.reference_genome_list_view', 'main.views.reference_genome_view', 'main.views.sample_list_view', 'main.views.alignment_list_view', 'main.views.alignment_view', 'main.views.sample_alignment_error_view', 'main.views.variant_set_list_view', 'main.views.variant_set_view', 'main.views.single_variant_view', 'main.xhr_handlers.get_variant_list', 'main.xhr_handlers.get_variant_set_list', 'main.xhr_handlers.get_gene_list', 'main.xhr_handlers.get_alignment_groups', 'main.xhr_handlers.is_materialized_view_valid', 'main.xhr_handlers.get_ref_genomes', 'main.xhr_handlers.compile_jbrowse_and_redirect', 'main.template_xhrs.variant_filter_controls', ] ## Instruction: Add login and logout to allowed views in DEMO_MODE. ## Code After: # Views that are visible in demo mode. DEMO_SAFE_VIEWS = [ 'main.views.home_view', 'main.views.project_list_view', 'main.views.project_view', 'main.views.tab_root_analyze', 'main.views.reference_genome_list_view', 'main.views.reference_genome_view', 'main.views.sample_list_view', 'main.views.alignment_list_view', 'main.views.alignment_view', 'main.views.sample_alignment_error_view', 'main.views.variant_set_list_view', 'main.views.variant_set_view', 'main.views.single_variant_view', 'main.xhr_handlers.get_variant_list', 'main.xhr_handlers.get_variant_set_list', 'main.xhr_handlers.get_gene_list', 'main.xhr_handlers.get_alignment_groups', 'main.xhr_handlers.is_materialized_view_valid', 'main.xhr_handlers.get_ref_genomes', 'main.xhr_handlers.compile_jbrowse_and_redirect', 'main.template_xhrs.variant_filter_controls', 'main.demo_view_overrides.login_demo_account', 'django.contrib.auth.views.logout' ]
... 'main.xhr_handlers.get_ref_genomes', 'main.xhr_handlers.compile_jbrowse_and_redirect', 'main.template_xhrs.variant_filter_controls', 'main.demo_view_overrides.login_demo_account', 'django.contrib.auth.views.logout' ] ...
92ef198213e7e5881877be5d79516046cc1e59b5
example1/Example1.h
example1/Example1.h
/* * Copyright (C) Sometrik oy 2015 * */ #include <FWContextBase.h> #include <AndroidPlatform.h> class Example1 : public FWContextBase { public: Example1(AndroidPlatform * _platform) : FWContextBase(_platform), platform(_platform) { } bool Init(); void onDraw(); void onShutdown(); private: AndroidPlatform * platform; };
/* * Copyright (C) Sometrik oy 2015 * */ #include <FWContextBase.h> #include <FWPlatformBase.h> class Example1 : public FWContextBase { public: Example1(FWPlatformBase * _platform) : FWContextBase(_platform), platform(_platform) { } bool Init(); void onDraw(); void onShutdown(); private: FWPlatformBase * platform; };
Change AndroidPlatform variables to FWPlatformBase, switch include
Change AndroidPlatform variables to FWPlatformBase, switch include
C
mit
Sometrik/framework,Sometrik/framework,Sometrik/framework
c
## Code Before: /* * Copyright (C) Sometrik oy 2015 * */ #include <FWContextBase.h> #include <AndroidPlatform.h> class Example1 : public FWContextBase { public: Example1(AndroidPlatform * _platform) : FWContextBase(_platform), platform(_platform) { } bool Init(); void onDraw(); void onShutdown(); private: AndroidPlatform * platform; }; ## Instruction: Change AndroidPlatform variables to FWPlatformBase, switch include ## Code After: /* * Copyright (C) Sometrik oy 2015 * */ #include <FWContextBase.h> #include <FWPlatformBase.h> class Example1 : public FWContextBase { public: Example1(FWPlatformBase * _platform) : FWContextBase(_platform), platform(_platform) { } bool Init(); void onDraw(); void onShutdown(); private: FWPlatformBase * platform; };
// ... existing code ... */ #include <FWContextBase.h> #include <FWPlatformBase.h> class Example1 : public FWContextBase { public: Example1(FWPlatformBase * _platform) : FWContextBase(_platform), platform(_platform) { } bool Init(); void onDraw(); // ... modified code ... void onShutdown(); private: FWPlatformBase * platform; }; // ... rest of the code ...
aae36c00e6dbea1ed68d2a921021d586d5ff723e
openquake/baselib/safeprint.py
openquake/baselib/safeprint.py
from __future__ import print_function import sys try: import __builtin__ except ImportError: # Python 3 import builtins as __builtin__ def print(*args, **kwargs): conv_str = () for s in args: conv_str = s.encode('utf-8').decode(sys.stdout.encoding, 'ignore') return __builtin__.print(conv_str, **kwargs)
from __future__ import print_function from sys import stdout try: import __builtin__ except ImportError: # Python 3 import builtins as __builtin__ def print(*args, **kwargs): ret_str = () # when stdout is redirected to a file, python 2 uses ascii for the writer; # python 3 uses what is configured in the system (i.e. 'utf-8') str_encoding = stdout.encoding if stdout.encoding is not None else 'ascii' for s in args: ret_str = s.encode('utf-8').decode(str_encoding, 'ignore') return __builtin__.print(ret_str, **kwargs)
Fix out redirection in python2
Fix out redirection in python2
Python
agpl-3.0
gem/oq-engine,gem/oq-engine,gem/oq-hazardlib,gem/oq-hazardlib,gem/oq-hazardlib,gem/oq-engine,gem/oq-engine,gem/oq-engine
python
## Code Before: from __future__ import print_function import sys try: import __builtin__ except ImportError: # Python 3 import builtins as __builtin__ def print(*args, **kwargs): conv_str = () for s in args: conv_str = s.encode('utf-8').decode(sys.stdout.encoding, 'ignore') return __builtin__.print(conv_str, **kwargs) ## Instruction: Fix out redirection in python2 ## Code After: from __future__ import print_function from sys import stdout try: import __builtin__ except ImportError: # Python 3 import builtins as __builtin__ def print(*args, **kwargs): ret_str = () # when stdout is redirected to a file, python 2 uses ascii for the writer; # python 3 uses what is configured in the system (i.e. 'utf-8') str_encoding = stdout.encoding if stdout.encoding is not None else 'ascii' for s in args: ret_str = s.encode('utf-8').decode(str_encoding, 'ignore') return __builtin__.print(ret_str, **kwargs)
... from __future__ import print_function from sys import stdout try: import __builtin__ ... def print(*args, **kwargs): ret_str = () # when stdout is redirected to a file, python 2 uses ascii for the writer; # python 3 uses what is configured in the system (i.e. 'utf-8') str_encoding = stdout.encoding if stdout.encoding is not None else 'ascii' for s in args: ret_str = s.encode('utf-8').decode(str_encoding, 'ignore') return __builtin__.print(ret_str, **kwargs) ...
d116a2ae5a4d55fc42eb68c8cf667267b302a89a
core/src/com/ychstudio/screens/transitions/SlideLeftTransition.java
core/src/com/ychstudio/screens/transitions/SlideLeftTransition.java
package com.ychstudio.screens.transitions; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Interpolation; public class SlideLeftTransition implements ScreenTransition { private float duration; public SlideLeftTransition(float duration) { this.duration = duration; } @Override public float getDuration() { return duration; } @Override public void rander(SpriteBatch batch, Texture currentScreenTexture, Texture nextScreenTexture, float alpha) { float w = Gdx.graphics.getWidth(); alpha = Interpolation.fade.apply(alpha); Sprite currentSprite = new Sprite(currentScreenTexture); currentSprite.flip(false, true); currentSprite.setPosition(w * alpha, 0); Sprite nextSprite = new Sprite(nextScreenTexture); nextSprite.flip(false, true); nextSprite.setPosition(-w + w * alpha, 0); batch.begin(); currentSprite.draw(batch); nextSprite.draw(batch); batch.end(); } }
package com.ychstudio.screens.transitions; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Interpolation; public class SlideLeftTransition implements ScreenTransition { private float duration; public SlideLeftTransition(float duration) { this.duration = duration; } @Override public float getDuration() { return duration; } @Override public void rander(SpriteBatch batch, Texture currentScreenTexture, Texture nextScreenTexture, float alpha) { float w = Gdx.graphics.getWidth(); alpha = Interpolation.fade.apply(alpha); batch.begin(); batch.draw(currentScreenTexture, w * alpha, 0, w, currentScreenTexture.getHeight(), 0, 0, (int)w, currentScreenTexture.getHeight(), false, true); batch.draw(nextScreenTexture, -w + w * alpha, 0, w, nextScreenTexture.getHeight(), 0, 0, (int)w, nextScreenTexture.getHeight(), false, true); batch.end(); } }
Improve transition by using batch.draw directly without creating Sprites
Improve transition by using batch.draw directly without creating Sprites
Java
mit
yichen0831/SpaceMission,yichen0831/SpaceMission
java
## Code Before: package com.ychstudio.screens.transitions; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Interpolation; public class SlideLeftTransition implements ScreenTransition { private float duration; public SlideLeftTransition(float duration) { this.duration = duration; } @Override public float getDuration() { return duration; } @Override public void rander(SpriteBatch batch, Texture currentScreenTexture, Texture nextScreenTexture, float alpha) { float w = Gdx.graphics.getWidth(); alpha = Interpolation.fade.apply(alpha); Sprite currentSprite = new Sprite(currentScreenTexture); currentSprite.flip(false, true); currentSprite.setPosition(w * alpha, 0); Sprite nextSprite = new Sprite(nextScreenTexture); nextSprite.flip(false, true); nextSprite.setPosition(-w + w * alpha, 0); batch.begin(); currentSprite.draw(batch); nextSprite.draw(batch); batch.end(); } } ## Instruction: Improve transition by using batch.draw directly without creating Sprites ## Code After: package com.ychstudio.screens.transitions; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Interpolation; public class SlideLeftTransition implements ScreenTransition { private float duration; public SlideLeftTransition(float duration) { this.duration = duration; } @Override public float getDuration() { return duration; } @Override public void rander(SpriteBatch batch, Texture currentScreenTexture, Texture nextScreenTexture, float alpha) { float w = Gdx.graphics.getWidth(); alpha = Interpolation.fade.apply(alpha); batch.begin(); batch.draw(currentScreenTexture, w * alpha, 0, w, currentScreenTexture.getHeight(), 0, 0, (int)w, currentScreenTexture.getHeight(), false, true); batch.draw(nextScreenTexture, -w + w * alpha, 0, w, nextScreenTexture.getHeight(), 0, 0, (int)w, nextScreenTexture.getHeight(), false, true); batch.end(); } }
// ... existing code ... import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Interpolation; // ... modified code ... float w = Gdx.graphics.getWidth(); alpha = Interpolation.fade.apply(alpha); batch.begin(); batch.draw(currentScreenTexture, w * alpha, 0, w, currentScreenTexture.getHeight(), 0, 0, (int)w, currentScreenTexture.getHeight(), false, true); batch.draw(nextScreenTexture, -w + w * alpha, 0, w, nextScreenTexture.getHeight(), 0, 0, (int)w, nextScreenTexture.getHeight(), false, true); batch.end(); } // ... rest of the code ...
29c68602396f04f57de587231b87c9e137d51412
celery/discovery.py
celery/discovery.py
import imp from django.conf import settings from django.core import exceptions __all__ = ["autodiscover", "tasks_for_app", "find_related_module"] def autodiscover(): """Include tasks for all applications in settings.INSTALLED_APPS.""" return filter(None, [tasks_for_app(app) for app in settings.INSTALLED_APPS]) def tasks_for_app(app): """Given an application name, imports any tasks.py file for that app.""" def found_tasks_module_handler(app_path, app_basename): return __import__("%s.tasks" % app) return find_related_module(app, "tasks", found_tasks_module_handler) def find_related_module(app, related_name, handler): """Given an application name and a module name, tries to find that module in the application, and running handler' if it finds it. """ # See django.contrib.admin.autodiscover for an explanation of this code. try: app_basename = app.split('.')[-1] app_path = __import__(app, {}, {}, app_basename).__path__ except AttributeError: return None try: imp.find_module(related_name, app_path) except ImportError: return None return handler(app_path, app_basename)
from django.conf import settings __all__ = ["autodiscover", "find_related_module"] def autodiscover(): """Include tasks for all applications in settings.INSTALLED_APPS.""" return filter(None, [find_related_module(app, "tasks") for app in settings.INSTALLED_APPS]) def find_related_module(app, related_name): """Given an application name and a module name, tries to find that module in the application, and running handler' if it finds it. """ try: module = __import__(app, {}, {}, [related_name]) except ImportError: return None try: related_module = getattr(module, related_name) except AttributeError: return None return related_module
Make autodiscover() work with zipped eggs.
Make autodiscover() work with zipped eggs.
Python
bsd-3-clause
ask/celery,mitsuhiko/celery,ask/celery,WoLpH/celery,frac/celery,mitsuhiko/celery,frac/celery,cbrepo/celery,cbrepo/celery,WoLpH/celery
python
## Code Before: import imp from django.conf import settings from django.core import exceptions __all__ = ["autodiscover", "tasks_for_app", "find_related_module"] def autodiscover(): """Include tasks for all applications in settings.INSTALLED_APPS.""" return filter(None, [tasks_for_app(app) for app in settings.INSTALLED_APPS]) def tasks_for_app(app): """Given an application name, imports any tasks.py file for that app.""" def found_tasks_module_handler(app_path, app_basename): return __import__("%s.tasks" % app) return find_related_module(app, "tasks", found_tasks_module_handler) def find_related_module(app, related_name, handler): """Given an application name and a module name, tries to find that module in the application, and running handler' if it finds it. """ # See django.contrib.admin.autodiscover for an explanation of this code. try: app_basename = app.split('.')[-1] app_path = __import__(app, {}, {}, app_basename).__path__ except AttributeError: return None try: imp.find_module(related_name, app_path) except ImportError: return None return handler(app_path, app_basename) ## Instruction: Make autodiscover() work with zipped eggs. ## Code After: from django.conf import settings __all__ = ["autodiscover", "find_related_module"] def autodiscover(): """Include tasks for all applications in settings.INSTALLED_APPS.""" return filter(None, [find_related_module(app, "tasks") for app in settings.INSTALLED_APPS]) def find_related_module(app, related_name): """Given an application name and a module name, tries to find that module in the application, and running handler' if it finds it. """ try: module = __import__(app, {}, {}, [related_name]) except ImportError: return None try: related_module = getattr(module, related_name) except AttributeError: return None return related_module
// ... existing code ... from django.conf import settings __all__ = ["autodiscover", "find_related_module"] def autodiscover(): """Include tasks for all applications in settings.INSTALLED_APPS.""" return filter(None, [find_related_module(app, "tasks") for app in settings.INSTALLED_APPS]) def find_related_module(app, related_name): """Given an application name and a module name, tries to find that module in the application, and running handler' if it finds it. """ try: module = __import__(app, {}, {}, [related_name]) except ImportError: return None try: related_module = getattr(module, related_name) except AttributeError: return None return related_module // ... rest of the code ...
5ba9888d267d663fb0ab0dfbfd9346dc20f4c0c1
test/test_turtle_serialize.py
test/test_turtle_serialize.py
import rdflib from rdflib.py3compat import b def testTurtleFinalDot(): """ https://github.com/RDFLib/rdflib/issues/282 """ g = rdflib.Graph() u = rdflib.URIRef("http://ex.org/bob.") g.bind("ns", "http://ex.org/") g.add( (u, u, u) ) s=g.serialize(format='turtle') assert b("ns:bob.") not in s if __name__ == "__main__": import nose, sys nose.main(defaultTest=sys.argv[0])
from rdflib import Graph, URIRef, BNode, RDF, Literal from rdflib.collection import Collection from rdflib.py3compat import b def testTurtleFinalDot(): """ https://github.com/RDFLib/rdflib/issues/282 """ g = Graph() u = URIRef("http://ex.org/bob.") g.bind("ns", "http://ex.org/") g.add( (u, u, u) ) s=g.serialize(format='turtle') assert b("ns:bob.") not in s def testTurtleBoolList(): subject = URIRef("http://localhost/user") predicate = URIRef("http://localhost/vocab#hasList") g1 = Graph() list_item1 = BNode() list_item2 = BNode() list_item3 = BNode() g1.add((subject, predicate, list_item1)) g1.add((list_item1, RDF.first, Literal(True))) g1.add((list_item1, RDF.rest, list_item2)) g1.add((list_item2, RDF.first, Literal(False))) g1.add((list_item2, RDF.rest, list_item3)) g1.add((list_item3, RDF.first, Literal(True))) g1.add((list_item3, RDF.rest, RDF.nil)) ttl_dump = g1.serialize(format="turtle") g2 = Graph() g2.parse(data=ttl_dump, format="turtle") list_id = g2.value(subject, predicate) bool_list = [i.toPython() for i in Collection(g2, list_id)] assert bool_list == [True, False, True] if __name__ == "__main__": import nose, sys nose.main(defaultTest=sys.argv[0])
Test boolean list serialization in Turtle
Test boolean list serialization in Turtle
Python
bsd-3-clause
RDFLib/rdflib,ssssam/rdflib,armandobs14/rdflib,yingerj/rdflib,RDFLib/rdflib,ssssam/rdflib,ssssam/rdflib,avorio/rdflib,marma/rdflib,marma/rdflib,RDFLib/rdflib,ssssam/rdflib,dbs/rdflib,armandobs14/rdflib,dbs/rdflib,dbs/rdflib,marma/rdflib,avorio/rdflib,marma/rdflib,yingerj/rdflib,RDFLib/rdflib,yingerj/rdflib,dbs/rdflib,armandobs14/rdflib,avorio/rdflib,armandobs14/rdflib,yingerj/rdflib,avorio/rdflib
python
## Code Before: import rdflib from rdflib.py3compat import b def testTurtleFinalDot(): """ https://github.com/RDFLib/rdflib/issues/282 """ g = rdflib.Graph() u = rdflib.URIRef("http://ex.org/bob.") g.bind("ns", "http://ex.org/") g.add( (u, u, u) ) s=g.serialize(format='turtle') assert b("ns:bob.") not in s if __name__ == "__main__": import nose, sys nose.main(defaultTest=sys.argv[0]) ## Instruction: Test boolean list serialization in Turtle ## Code After: from rdflib import Graph, URIRef, BNode, RDF, Literal from rdflib.collection import Collection from rdflib.py3compat import b def testTurtleFinalDot(): """ https://github.com/RDFLib/rdflib/issues/282 """ g = Graph() u = URIRef("http://ex.org/bob.") g.bind("ns", "http://ex.org/") g.add( (u, u, u) ) s=g.serialize(format='turtle') assert b("ns:bob.") not in s def testTurtleBoolList(): subject = URIRef("http://localhost/user") predicate = URIRef("http://localhost/vocab#hasList") g1 = Graph() list_item1 = BNode() list_item2 = BNode() list_item3 = BNode() g1.add((subject, predicate, list_item1)) g1.add((list_item1, RDF.first, Literal(True))) g1.add((list_item1, RDF.rest, list_item2)) g1.add((list_item2, RDF.first, Literal(False))) g1.add((list_item2, RDF.rest, list_item3)) g1.add((list_item3, RDF.first, Literal(True))) g1.add((list_item3, RDF.rest, RDF.nil)) ttl_dump = g1.serialize(format="turtle") g2 = Graph() g2.parse(data=ttl_dump, format="turtle") list_id = g2.value(subject, predicate) bool_list = [i.toPython() for i in Collection(g2, list_id)] assert bool_list == [True, False, True] if __name__ == "__main__": import nose, sys nose.main(defaultTest=sys.argv[0])
# ... existing code ... from rdflib import Graph, URIRef, BNode, RDF, Literal from rdflib.collection import Collection from rdflib.py3compat import b def testTurtleFinalDot(): """ # ... modified code ... https://github.com/RDFLib/rdflib/issues/282 """ g = Graph() u = URIRef("http://ex.org/bob.") g.bind("ns", "http://ex.org/") g.add( (u, u, u) ) s=g.serialize(format='turtle') ... assert b("ns:bob.") not in s def testTurtleBoolList(): subject = URIRef("http://localhost/user") predicate = URIRef("http://localhost/vocab#hasList") g1 = Graph() list_item1 = BNode() list_item2 = BNode() list_item3 = BNode() g1.add((subject, predicate, list_item1)) g1.add((list_item1, RDF.first, Literal(True))) g1.add((list_item1, RDF.rest, list_item2)) g1.add((list_item2, RDF.first, Literal(False))) g1.add((list_item2, RDF.rest, list_item3)) g1.add((list_item3, RDF.first, Literal(True))) g1.add((list_item3, RDF.rest, RDF.nil)) ttl_dump = g1.serialize(format="turtle") g2 = Graph() g2.parse(data=ttl_dump, format="turtle") list_id = g2.value(subject, predicate) bool_list = [i.toPython() for i in Collection(g2, list_id)] assert bool_list == [True, False, True] if __name__ == "__main__": import nose, sys nose.main(defaultTest=sys.argv[0]) # ... rest of the code ...
45f30b4b1da110e79787b85c054796a671718910
tests/__main__.py
tests/__main__.py
import unittest import os.path if __name__ == '__main__': HERE = os.path.dirname(__file__) loader = unittest.loader.TestLoader() suite = loader.discover(HERE) result = unittest.result.TestResult() suite.run(result) print('Ran {} tests.'.format(result.testsRun)) print('{} errors, {} failed, {} skipped'.format( len(result.errors), len(result.failures), len(result.skipped), )) if not result.wasSuccessful(): for module, traceback in result.errors: print('[{}]\n{}\n\n'.format(module, traceback))
import unittest import os.path if __name__ == '__main__': HERE = os.path.dirname(__file__) loader = unittest.loader.TestLoader() suite = loader.discover(HERE) result = unittest.result.TestResult() suite.run(result) print('Ran {} tests.'.format(result.testsRun)) print('{} errors, {} failed, {} skipped'.format( len(result.errors), len(result.failures), len(result.skipped), )) if not result.wasSuccessful(): if result.errors: print('\nErrors:') for module, traceback in result.errors: print('[{}]\n{}\n\n'.format(module, traceback)) if result.failures: print('\nFailures:') for module, traceback in result.failures: print('[{}]\n{}\n\n'.format(module, traceback))
Print failures and errors in test run
Print failures and errors in test run
Python
mit
funkybob/antfarm
python
## Code Before: import unittest import os.path if __name__ == '__main__': HERE = os.path.dirname(__file__) loader = unittest.loader.TestLoader() suite = loader.discover(HERE) result = unittest.result.TestResult() suite.run(result) print('Ran {} tests.'.format(result.testsRun)) print('{} errors, {} failed, {} skipped'.format( len(result.errors), len(result.failures), len(result.skipped), )) if not result.wasSuccessful(): for module, traceback in result.errors: print('[{}]\n{}\n\n'.format(module, traceback)) ## Instruction: Print failures and errors in test run ## Code After: import unittest import os.path if __name__ == '__main__': HERE = os.path.dirname(__file__) loader = unittest.loader.TestLoader() suite = loader.discover(HERE) result = unittest.result.TestResult() suite.run(result) print('Ran {} tests.'.format(result.testsRun)) print('{} errors, {} failed, {} skipped'.format( len(result.errors), len(result.failures), len(result.skipped), )) if not result.wasSuccessful(): if result.errors: print('\nErrors:') for module, traceback in result.errors: print('[{}]\n{}\n\n'.format(module, traceback)) if result.failures: print('\nFailures:') for module, traceback in result.failures: print('[{}]\n{}\n\n'.format(module, traceback))
// ... existing code ... len(result.skipped), )) if not result.wasSuccessful(): if result.errors: print('\nErrors:') for module, traceback in result.errors: print('[{}]\n{}\n\n'.format(module, traceback)) if result.failures: print('\nFailures:') for module, traceback in result.failures: print('[{}]\n{}\n\n'.format(module, traceback)) // ... rest of the code ...
f3e8e94267eefac6dead48d1b5d3259aca125d5c
src/main/java/io/katharsis/rs/parameterProvider/provider/QueryParamProvider.java
src/main/java/io/katharsis/rs/parameterProvider/provider/QueryParamProvider.java
package io.katharsis.rs.parameterProvider.provider; import java.io.IOException; import java.util.List; import javax.ws.rs.QueryParam; import javax.ws.rs.container.ContainerRequestContext; import com.fasterxml.jackson.databind.ObjectMapper; public class QueryParamProvider implements RequestContextParameterProvider { @Override public Object provideValue(Parameter parameter, ContainerRequestContext requestContext, ObjectMapper objectMapper) { Object returnValue; List<String> value = requestContext.getUriInfo().getQueryParameters().get(parameter.getAnnotation(QueryParam.class).value()); if (value == null || value.isEmpty()) { return null; } else { if (String.class.isAssignableFrom(parameter.getType())) { // Given a query string: ?x=y&x=z, JAX-RS will return a value of y. returnValue = value.get(0); } else { try { returnValue = objectMapper.readValue(value.get(0), parameter.getType()); } catch (IOException e) { throw new RuntimeException(e); } } } return returnValue; } @Override public boolean provides(Parameter parameter) { return parameter.isAnnotationPresent(QueryParam.class); } }
package io.katharsis.rs.parameterProvider.provider; import java.io.IOException; import java.util.List; import javax.ws.rs.QueryParam; import javax.ws.rs.container.ContainerRequestContext; import com.fasterxml.jackson.databind.ObjectMapper; public class QueryParamProvider implements RequestContextParameterProvider { @Override public Object provideValue(Parameter parameter, ContainerRequestContext requestContext, ObjectMapper objectMapper) { Object returnValue; List<String> value = requestContext.getUriInfo().getQueryParameters().get(parameter.getAnnotation(QueryParam.class).value()); if (value == null || value.isEmpty()) { return null; } else { if (String.class.isAssignableFrom(parameter.getType())) { // Given a query string: ?x=y&x=z, JAX-RS will return a value of y. returnValue = value.get(0); } else if (Iterable.class.isAssignableFrom(parameter.getType())) { returnValue = value; } else { try { returnValue = objectMapper.readValue(value.get(0), parameter.getType()); } catch (IOException e) { throw new RuntimeException(e); } } } return returnValue; } @Override public boolean provides(Parameter parameter) { return parameter.isAnnotationPresent(QueryParam.class); } }
Fix support for multiple values for a single parameter.
Fix support for multiple values for a single parameter.
Java
apache-2.0
apetrucci/katharsis-framework,katharsis-project/katharsis-framework,apetrucci/katharsis-framework,adnovum/katharsis-framework,katharsis-project/katharsis-framework,adnovum/katharsis-framework,dustinstanley/katharsis-framework,apetrucci/katharsis-framework,katharsis-project/katharsis-framework,dustinstanley/katharsis-framework,katharsis-project/katharsis-framework,adnovum/katharsis-framework,iMDT/katharsis-framework-j6,iMDT/katharsis-framework-j6,katharsis-project/katharsis-framework,apetrucci/katharsis-framework,iMDT/katharsis-framework-j6,iMDT/katharsis-framework-j6,adnovum/katharsis-framework,apetrucci/katharsis-framework
java
## Code Before: package io.katharsis.rs.parameterProvider.provider; import java.io.IOException; import java.util.List; import javax.ws.rs.QueryParam; import javax.ws.rs.container.ContainerRequestContext; import com.fasterxml.jackson.databind.ObjectMapper; public class QueryParamProvider implements RequestContextParameterProvider { @Override public Object provideValue(Parameter parameter, ContainerRequestContext requestContext, ObjectMapper objectMapper) { Object returnValue; List<String> value = requestContext.getUriInfo().getQueryParameters().get(parameter.getAnnotation(QueryParam.class).value()); if (value == null || value.isEmpty()) { return null; } else { if (String.class.isAssignableFrom(parameter.getType())) { // Given a query string: ?x=y&x=z, JAX-RS will return a value of y. returnValue = value.get(0); } else { try { returnValue = objectMapper.readValue(value.get(0), parameter.getType()); } catch (IOException e) { throw new RuntimeException(e); } } } return returnValue; } @Override public boolean provides(Parameter parameter) { return parameter.isAnnotationPresent(QueryParam.class); } } ## Instruction: Fix support for multiple values for a single parameter. ## Code After: package io.katharsis.rs.parameterProvider.provider; import java.io.IOException; import java.util.List; import javax.ws.rs.QueryParam; import javax.ws.rs.container.ContainerRequestContext; import com.fasterxml.jackson.databind.ObjectMapper; public class QueryParamProvider implements RequestContextParameterProvider { @Override public Object provideValue(Parameter parameter, ContainerRequestContext requestContext, ObjectMapper objectMapper) { Object returnValue; List<String> value = requestContext.getUriInfo().getQueryParameters().get(parameter.getAnnotation(QueryParam.class).value()); if (value == null || value.isEmpty()) { return null; } else { if (String.class.isAssignableFrom(parameter.getType())) { // Given a query string: ?x=y&x=z, JAX-RS will return a value of y. returnValue = value.get(0); } else if (Iterable.class.isAssignableFrom(parameter.getType())) { returnValue = value; } else { try { returnValue = objectMapper.readValue(value.get(0), parameter.getType()); } catch (IOException e) { throw new RuntimeException(e); } } } return returnValue; } @Override public boolean provides(Parameter parameter) { return parameter.isAnnotationPresent(QueryParam.class); } }
// ... existing code ... if (String.class.isAssignableFrom(parameter.getType())) { // Given a query string: ?x=y&x=z, JAX-RS will return a value of y. returnValue = value.get(0); } else if (Iterable.class.isAssignableFrom(parameter.getType())) { returnValue = value; } else { try { returnValue = objectMapper.readValue(value.get(0), parameter.getType()); // ... rest of the code ...
ad902e3138ff67a76e7c3d8d6bf7d7d4f76fc479
HTMLKit/CSSAttributeSelector.h
HTMLKit/CSSAttributeSelector.h
// // CSSAttributeSelector.h // HTMLKit // // Created by Iska on 14/05/15. // Copyright (c) 2015 BrainCookie. All rights reserved. // #import <Foundation/Foundation.h> #import "CSSSelector.h" #import "CSSSimpleSelector.h" typedef NS_ENUM(NSUInteger, CSSAttributeSelectorType) { CSSAttributeSelectorExists, CSSAttributeSelectorExactMatch, CSSAttributeSelectorIncludes, CSSAttributeSelectorBegins, CSSAttributeSelectorEnds, CSSAttributeSelectorContains, CSSAttributeSelectorHyphen }; @interface CSSAttributeSelector : CSSSelector <CSSSimpleSelector> @property (nonatomic, assign) CSSAttributeSelectorType type; @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *value; + (instancetype)selectorForClass:(NSString *)className; + (instancetype)selectorForId:(NSString *)elementId; - (instancetype)initWithType:(CSSAttributeSelectorType)type attributeName:(NSString *)name attrbiuteValue:(NSString *)value; @end
// // CSSAttributeSelector.h // HTMLKit // // Created by Iska on 14/05/15. // Copyright (c) 2015 BrainCookie. All rights reserved. // #import <Foundation/Foundation.h> #import "CSSSelector.h" #import "CSSSimpleSelector.h" typedef NS_ENUM(NSUInteger, CSSAttributeSelectorType) { CSSAttributeSelectorExists, CSSAttributeSelectorExactMatch, CSSAttributeSelectorIncludes, CSSAttributeSelectorBegins, CSSAttributeSelectorEnds, CSSAttributeSelectorContains, CSSAttributeSelectorHyphen, CSSAttributeSelectorNot }; @interface CSSAttributeSelector : CSSSelector <CSSSimpleSelector> @property (nonatomic, assign) CSSAttributeSelectorType type; @property (nonatomic, copy) NSString * _Nonnull name; @property (nonatomic, copy) NSString * _Nonnull value; + (nullable instancetype)selectorForClass:(nonnull NSString *)className; + (nullable instancetype)selectorForId:(nonnull NSString *)elementId; - (nullable instancetype)initWithType:(CSSAttributeSelectorType)type attributeName:(nonnull NSString *)name attrbiuteValue:(nullable NSString *)value; @end
Add nullability specifiers to attribute selector
Add nullability specifiers to attribute selector
C
mit
iabudiab/HTMLKit,iabudiab/HTMLKit,iabudiab/HTMLKit,iabudiab/HTMLKit,iabudiab/HTMLKit
c
## Code Before: // // CSSAttributeSelector.h // HTMLKit // // Created by Iska on 14/05/15. // Copyright (c) 2015 BrainCookie. All rights reserved. // #import <Foundation/Foundation.h> #import "CSSSelector.h" #import "CSSSimpleSelector.h" typedef NS_ENUM(NSUInteger, CSSAttributeSelectorType) { CSSAttributeSelectorExists, CSSAttributeSelectorExactMatch, CSSAttributeSelectorIncludes, CSSAttributeSelectorBegins, CSSAttributeSelectorEnds, CSSAttributeSelectorContains, CSSAttributeSelectorHyphen }; @interface CSSAttributeSelector : CSSSelector <CSSSimpleSelector> @property (nonatomic, assign) CSSAttributeSelectorType type; @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *value; + (instancetype)selectorForClass:(NSString *)className; + (instancetype)selectorForId:(NSString *)elementId; - (instancetype)initWithType:(CSSAttributeSelectorType)type attributeName:(NSString *)name attrbiuteValue:(NSString *)value; @end ## Instruction: Add nullability specifiers to attribute selector ## Code After: // // CSSAttributeSelector.h // HTMLKit // // Created by Iska on 14/05/15. // Copyright (c) 2015 BrainCookie. All rights reserved. // #import <Foundation/Foundation.h> #import "CSSSelector.h" #import "CSSSimpleSelector.h" typedef NS_ENUM(NSUInteger, CSSAttributeSelectorType) { CSSAttributeSelectorExists, CSSAttributeSelectorExactMatch, CSSAttributeSelectorIncludes, CSSAttributeSelectorBegins, CSSAttributeSelectorEnds, CSSAttributeSelectorContains, CSSAttributeSelectorHyphen, CSSAttributeSelectorNot }; @interface CSSAttributeSelector : CSSSelector <CSSSimpleSelector> @property (nonatomic, assign) CSSAttributeSelectorType type; @property (nonatomic, copy) NSString * _Nonnull name; @property (nonatomic, copy) NSString * _Nonnull value; + (nullable instancetype)selectorForClass:(nonnull NSString *)className; + (nullable instancetype)selectorForId:(nonnull NSString *)elementId; - (nullable instancetype)initWithType:(CSSAttributeSelectorType)type attributeName:(nonnull NSString *)name attrbiuteValue:(nullable NSString *)value; @end
... CSSAttributeSelectorBegins, CSSAttributeSelectorEnds, CSSAttributeSelectorContains, CSSAttributeSelectorHyphen, CSSAttributeSelectorNot }; @interface CSSAttributeSelector : CSSSelector <CSSSimpleSelector> @property (nonatomic, assign) CSSAttributeSelectorType type; @property (nonatomic, copy) NSString * _Nonnull name; @property (nonatomic, copy) NSString * _Nonnull value; + (nullable instancetype)selectorForClass:(nonnull NSString *)className; + (nullable instancetype)selectorForId:(nonnull NSString *)elementId; - (nullable instancetype)initWithType:(CSSAttributeSelectorType)type attributeName:(nonnull NSString *)name attrbiuteValue:(nullable NSString *)value; @end ...
1424ce565ee8b47e6a9a3bc143589c7e7e0c3e53
cloudenvy/commands/envy_scp.py
cloudenvy/commands/envy_scp.py
import logging import fabric.api import fabric.operations from cloudenvy.envy import Envy class EnvySCP(object): """SCP Files to your ENVy""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('scp', help='scp help') subparser.set_defaults(func=self.run) subparser.add_argument('source') subparser.add_argument('target') subparser.add_argument('-n', '--name', action='store', default='', help='specify custom name for an ENVy') return subparser def run(self, config, args): envy = Envy(config) if envy.ip(): host_string = '%s@%s' % (envy.remote_user, envy.ip()) with fabric.api.settings(host_string=host_string): fabric.operations.put(args.source, args.target) else: logging.error('Could not find IP to upload file to.')
import logging import fabric.api import fabric.operations from cloudenvy.envy import Envy class EnvySCP(object): """SCP Files to your ENVy""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('scp', help='scp help') subparser.set_defaults(func=self.run) subparser.add_argument('source', help='Local path to copy into your ENVy.') subparser.add_argument('target', help='Location in your ENVy to place file(s). Non-absolute ' 'paths are interpreted relative to remote_user homedir.') subparser.add_argument('-n', '--name', action='store', default='', help='specify custom name for an ENVy') return subparser def run(self, config, args): envy = Envy(config) if envy.ip(): host_string = '%s@%s' % (envy.remote_user, envy.ip()) with fabric.api.settings(host_string=host_string): fabric.operations.put(args.source, args.target) else: logging.error('Could not find IP to upload file to.')
Document source and target arguments of envy scp
Document source and target arguments of envy scp Fix issue #67
Python
apache-2.0
cloudenvy/cloudenvy
python
## Code Before: import logging import fabric.api import fabric.operations from cloudenvy.envy import Envy class EnvySCP(object): """SCP Files to your ENVy""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('scp', help='scp help') subparser.set_defaults(func=self.run) subparser.add_argument('source') subparser.add_argument('target') subparser.add_argument('-n', '--name', action='store', default='', help='specify custom name for an ENVy') return subparser def run(self, config, args): envy = Envy(config) if envy.ip(): host_string = '%s@%s' % (envy.remote_user, envy.ip()) with fabric.api.settings(host_string=host_string): fabric.operations.put(args.source, args.target) else: logging.error('Could not find IP to upload file to.') ## Instruction: Document source and target arguments of envy scp Fix issue #67 ## Code After: import logging import fabric.api import fabric.operations from cloudenvy.envy import Envy class EnvySCP(object): """SCP Files to your ENVy""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('scp', help='scp help') subparser.set_defaults(func=self.run) subparser.add_argument('source', help='Local path to copy into your ENVy.') subparser.add_argument('target', help='Location in your ENVy to place file(s). Non-absolute ' 'paths are interpreted relative to remote_user homedir.') subparser.add_argument('-n', '--name', action='store', default='', help='specify custom name for an ENVy') return subparser def run(self, config, args): envy = Envy(config) if envy.ip(): host_string = '%s@%s' % (envy.remote_user, envy.ip()) with fabric.api.settings(host_string=host_string): fabric.operations.put(args.source, args.target) else: logging.error('Could not find IP to upload file to.')
// ... existing code ... subparser = subparsers.add_parser('scp', help='scp help') subparser.set_defaults(func=self.run) subparser.add_argument('source', help='Local path to copy into your ENVy.') subparser.add_argument('target', help='Location in your ENVy to place file(s). Non-absolute ' 'paths are interpreted relative to remote_user homedir.') subparser.add_argument('-n', '--name', action='store', default='', help='specify custom name for an ENVy') return subparser // ... rest of the code ...
7d79e6f0404b04ababaca3d8c50b1e682fd64222
chainer/initializer.py
chainer/initializer.py
import typing as tp # NOQA from chainer import types # NOQA from chainer import utils class Initializer(object): """Initializes array. It initializes the given array. Attributes: dtype: Data type specifier. It is for type check in ``__call__`` function. """ def __init__(self, dtype=None): # type: (tp.Optional[types.DTypeSpec]) -> None self.dtype = dtype # type: types.DTypeSpec def __call__(self, array): # type: (types.NdArray) -> None """Initializes given array. This method destructively changes the value of array. The derived class is required to implement this method. The algorithms used to make the new values depend on the concrete derived classes. Args: array (:ref:`ndarray`): An array to be initialized by this initializer. """ raise NotImplementedError() # Original code forked from MIT licensed keras project # https://github.com/fchollet/keras/blob/master/keras/initializations.py def get_fans(shape): if not isinstance(shape, tuple): raise ValueError('shape must be tuple') if len(shape) < 2: raise ValueError('shape must be of length >= 2: shape={}', shape) receptive_field_size = utils.size_of_shape(shape[2:]) fan_in = shape[1] * receptive_field_size fan_out = shape[0] * receptive_field_size return fan_in, fan_out
import typing as tp # NOQA from chainer import types # NOQA from chainer import utils class Initializer(object): """Initializes array. It initializes the given array. Attributes: dtype: Data type specifier. It is for type check in ``__call__`` function. """ def __init__(self, dtype=None): # type: (tp.Optional[types.DTypeSpec]) -> None self.dtype = dtype # type: types.DTypeSpec def __call__(self, array): # type: (types.NdArray) -> None """Initializes given array. This method destructively changes the value of array. The derived class is required to implement this method. The algorithms used to make the new values depend on the concrete derived classes. Args: array (:ref:`ndarray`): An array to be initialized by this initializer. """ raise NotImplementedError() # Original code forked from MIT licensed keras project # https://github.com/fchollet/keras/blob/master/keras/initializations.py def get_fans(shape): if not isinstance(shape, tuple): raise ValueError( 'shape must be tuple. Actual type: {}'.format(type(shape))) if len(shape) < 2: raise ValueError( 'shape must be of length >= 2. Actual shape: {}'.format(shape)) receptive_field_size = utils.size_of_shape(shape[2:]) fan_in = shape[1] * receptive_field_size fan_out = shape[0] * receptive_field_size return fan_in, fan_out
Fix error messages in get_fans
Fix error messages in get_fans
Python
mit
niboshi/chainer,tkerola/chainer,niboshi/chainer,keisuke-umezawa/chainer,okuta/chainer,chainer/chainer,wkentaro/chainer,niboshi/chainer,okuta/chainer,okuta/chainer,wkentaro/chainer,pfnet/chainer,okuta/chainer,hvy/chainer,wkentaro/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,chainer/chainer,chainer/chainer,hvy/chainer,wkentaro/chainer,chainer/chainer,niboshi/chainer,hvy/chainer,hvy/chainer
python
## Code Before: import typing as tp # NOQA from chainer import types # NOQA from chainer import utils class Initializer(object): """Initializes array. It initializes the given array. Attributes: dtype: Data type specifier. It is for type check in ``__call__`` function. """ def __init__(self, dtype=None): # type: (tp.Optional[types.DTypeSpec]) -> None self.dtype = dtype # type: types.DTypeSpec def __call__(self, array): # type: (types.NdArray) -> None """Initializes given array. This method destructively changes the value of array. The derived class is required to implement this method. The algorithms used to make the new values depend on the concrete derived classes. Args: array (:ref:`ndarray`): An array to be initialized by this initializer. """ raise NotImplementedError() # Original code forked from MIT licensed keras project # https://github.com/fchollet/keras/blob/master/keras/initializations.py def get_fans(shape): if not isinstance(shape, tuple): raise ValueError('shape must be tuple') if len(shape) < 2: raise ValueError('shape must be of length >= 2: shape={}', shape) receptive_field_size = utils.size_of_shape(shape[2:]) fan_in = shape[1] * receptive_field_size fan_out = shape[0] * receptive_field_size return fan_in, fan_out ## Instruction: Fix error messages in get_fans ## Code After: import typing as tp # NOQA from chainer import types # NOQA from chainer import utils class Initializer(object): """Initializes array. It initializes the given array. Attributes: dtype: Data type specifier. It is for type check in ``__call__`` function. """ def __init__(self, dtype=None): # type: (tp.Optional[types.DTypeSpec]) -> None self.dtype = dtype # type: types.DTypeSpec def __call__(self, array): # type: (types.NdArray) -> None """Initializes given array. This method destructively changes the value of array. The derived class is required to implement this method. The algorithms used to make the new values depend on the concrete derived classes. Args: array (:ref:`ndarray`): An array to be initialized by this initializer. """ raise NotImplementedError() # Original code forked from MIT licensed keras project # https://github.com/fchollet/keras/blob/master/keras/initializations.py def get_fans(shape): if not isinstance(shape, tuple): raise ValueError( 'shape must be tuple. Actual type: {}'.format(type(shape))) if len(shape) < 2: raise ValueError( 'shape must be of length >= 2. Actual shape: {}'.format(shape)) receptive_field_size = utils.size_of_shape(shape[2:]) fan_in = shape[1] * receptive_field_size fan_out = shape[0] * receptive_field_size return fan_in, fan_out
// ... existing code ... def get_fans(shape): if not isinstance(shape, tuple): raise ValueError( 'shape must be tuple. Actual type: {}'.format(type(shape))) if len(shape) < 2: raise ValueError( 'shape must be of length >= 2. Actual shape: {}'.format(shape)) receptive_field_size = utils.size_of_shape(shape[2:]) fan_in = shape[1] * receptive_field_size // ... rest of the code ...
6bbafa2e9102840768ee875407be1878f2aa05ca
tests/pytests/unit/engines/test_script.py
tests/pytests/unit/engines/test_script.py
import pytest import salt.config import salt.engines.script as script from salt.exceptions import CommandExecutionError from tests.support.mock import patch @pytest.fixture def configure_loader_modules(): opts = salt.config.DEFAULT_MASTER_OPTS return {script: {"__opts__": opts}} def test__get_serializer(): """ Test known serializer is returned or exception is raised if unknown serializer """ for serializers in ("json", "yaml", "msgpack"): assert script._get_serializer(serializers) with pytest.raises(CommandExecutionError): script._get_serializer("bad") def test__read_stdout(): """ Test we can yield stdout """ with patch("subprocess.Popen") as popen_mock: popen_mock.stdout.readline.return_value = "test" assert next(script._read_stdout(popen_mock)) == "test"
import pytest import salt.config import salt.engines.script as script from salt.exceptions import CommandExecutionError from tests.support.mock import patch @pytest.fixture def configure_loader_modules(): opts = salt.config.DEFAULT_MASTER_OPTS return {script: {"__opts__": opts}} def test__get_serializer(): """ Test known serializer is returned or exception is raised if unknown serializer """ for serializers in ("json", "yaml", "msgpack"): assert script._get_serializer(serializers) with pytest.raises(CommandExecutionError): script._get_serializer("bad") def test__read_stdout(): """ Test we can yield stdout """ with patch("subprocess.Popen") as popen_mock: popen_mock.stdout.readline.return_value = "test" assert next(script._read_stdout(popen_mock)) == "test" def test__read_stdout_terminates_properly(): """ Test that _read_stdout terminates with the sentinel """ with patch("subprocess.Popen", autospec=True) as popen_mock: popen_mock.stdout.readline.return_value = b"" with pytest.raises(StopIteration): next(script._read_stdout(popen_mock))
Test iteration stops at empty bytes
Test iteration stops at empty bytes
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
python
## Code Before: import pytest import salt.config import salt.engines.script as script from salt.exceptions import CommandExecutionError from tests.support.mock import patch @pytest.fixture def configure_loader_modules(): opts = salt.config.DEFAULT_MASTER_OPTS return {script: {"__opts__": opts}} def test__get_serializer(): """ Test known serializer is returned or exception is raised if unknown serializer """ for serializers in ("json", "yaml", "msgpack"): assert script._get_serializer(serializers) with pytest.raises(CommandExecutionError): script._get_serializer("bad") def test__read_stdout(): """ Test we can yield stdout """ with patch("subprocess.Popen") as popen_mock: popen_mock.stdout.readline.return_value = "test" assert next(script._read_stdout(popen_mock)) == "test" ## Instruction: Test iteration stops at empty bytes ## Code After: import pytest import salt.config import salt.engines.script as script from salt.exceptions import CommandExecutionError from tests.support.mock import patch @pytest.fixture def configure_loader_modules(): opts = salt.config.DEFAULT_MASTER_OPTS return {script: {"__opts__": opts}} def test__get_serializer(): """ Test known serializer is returned or exception is raised if unknown serializer """ for serializers in ("json", "yaml", "msgpack"): assert script._get_serializer(serializers) with pytest.raises(CommandExecutionError): script._get_serializer("bad") def test__read_stdout(): """ Test we can yield stdout """ with patch("subprocess.Popen") as popen_mock: popen_mock.stdout.readline.return_value = "test" assert next(script._read_stdout(popen_mock)) == "test" def test__read_stdout_terminates_properly(): """ Test that _read_stdout terminates with the sentinel """ with patch("subprocess.Popen", autospec=True) as popen_mock: popen_mock.stdout.readline.return_value = b"" with pytest.raises(StopIteration): next(script._read_stdout(popen_mock))
# ... existing code ... with patch("subprocess.Popen") as popen_mock: popen_mock.stdout.readline.return_value = "test" assert next(script._read_stdout(popen_mock)) == "test" def test__read_stdout_terminates_properly(): """ Test that _read_stdout terminates with the sentinel """ with patch("subprocess.Popen", autospec=True) as popen_mock: popen_mock.stdout.readline.return_value = b"" with pytest.raises(StopIteration): next(script._read_stdout(popen_mock)) # ... rest of the code ...
267c17ce984952d16623b0305975626397529ca8
tests/config_test.py
tests/config_test.py
import pytest from timewreport.config import TimeWarriorConfig def test_get_value_should_return_value_if_key_available(): config = TimeWarriorConfig({'FOO': 'foo'}) assert config.get_value('FOO', 'bar') == 'foo' def test_get_value_should_return_default_if_key_not_available(): config = TimeWarriorConfig({'BAR': 'foo'}) assert config.get_value('FOO', 'bar') == 'bar' @pytest.fixture(scope='function', params=['on', 1, 'yes', 'y', 'true']) def trueish_value(request): return request.param def test_get_boolean_should_return_true_on_trueish_values(trueish_value): config = TimeWarriorConfig({'KEY': trueish_value}) assert config.get_boolean('KEY', False) is True def test_get_boolean_should_return_false_on_falseish_values(): config = TimeWarriorConfig({'KEY': 'foo'}) assert config.get_boolean('KEY', True) is False
import pytest from timewreport.config import TimeWarriorConfig def test_get_value_should_return_value_if_key_available(): config = TimeWarriorConfig({'FOO': 'foo'}) assert config.get_value('FOO', 'bar') == 'foo' def test_get_value_should_return_default_if_key_not_available(): config = TimeWarriorConfig({'BAR': 'foo'}) assert config.get_value('FOO', 'bar') == 'bar' @pytest.fixture(scope='function', params=['on', 1, 'yes', 'y', 'true']) def trueish_value(request): return request.param def test_get_boolean_should_return_true_on_trueish_values(trueish_value): config = TimeWarriorConfig({'KEY': trueish_value}) assert config.get_boolean('KEY', False) is True @pytest.fixture(scope='function', params=['off', 0, 'no', 'n', 'false']) def falseish_value(request): return request.param def test_get_boolean_should_return_false_on_falseish_values(falseish_value): config = TimeWarriorConfig({'KEY': falseish_value}) assert config.get_boolean('KEY', True) is False
Add tests for falseish config values
Add tests for falseish config values
Python
mit
lauft/timew-report
python
## Code Before: import pytest from timewreport.config import TimeWarriorConfig def test_get_value_should_return_value_if_key_available(): config = TimeWarriorConfig({'FOO': 'foo'}) assert config.get_value('FOO', 'bar') == 'foo' def test_get_value_should_return_default_if_key_not_available(): config = TimeWarriorConfig({'BAR': 'foo'}) assert config.get_value('FOO', 'bar') == 'bar' @pytest.fixture(scope='function', params=['on', 1, 'yes', 'y', 'true']) def trueish_value(request): return request.param def test_get_boolean_should_return_true_on_trueish_values(trueish_value): config = TimeWarriorConfig({'KEY': trueish_value}) assert config.get_boolean('KEY', False) is True def test_get_boolean_should_return_false_on_falseish_values(): config = TimeWarriorConfig({'KEY': 'foo'}) assert config.get_boolean('KEY', True) is False ## Instruction: Add tests for falseish config values ## Code After: import pytest from timewreport.config import TimeWarriorConfig def test_get_value_should_return_value_if_key_available(): config = TimeWarriorConfig({'FOO': 'foo'}) assert config.get_value('FOO', 'bar') == 'foo' def test_get_value_should_return_default_if_key_not_available(): config = TimeWarriorConfig({'BAR': 'foo'}) assert config.get_value('FOO', 'bar') == 'bar' @pytest.fixture(scope='function', params=['on', 1, 'yes', 'y', 'true']) def trueish_value(request): return request.param def test_get_boolean_should_return_true_on_trueish_values(trueish_value): config = TimeWarriorConfig({'KEY': trueish_value}) assert config.get_boolean('KEY', False) is True @pytest.fixture(scope='function', params=['off', 0, 'no', 'n', 'false']) def falseish_value(request): return request.param def test_get_boolean_should_return_false_on_falseish_values(falseish_value): config = TimeWarriorConfig({'KEY': falseish_value}) assert config.get_boolean('KEY', True) is False
# ... existing code ... assert config.get_boolean('KEY', False) is True @pytest.fixture(scope='function', params=['off', 0, 'no', 'n', 'false']) def falseish_value(request): return request.param def test_get_boolean_should_return_false_on_falseish_values(falseish_value): config = TimeWarriorConfig({'KEY': falseish_value}) assert config.get_boolean('KEY', True) is False # ... rest of the code ...
d05b9effc6d230aeb2a13759a67df644d75140ca
cts/views.py
cts/views.py
from django.http import HttpResponse def health_view(request): return HttpResponse()
from django.http import HttpResponse def health_view(request): return HttpResponse("I am okay.", content_type="text/plain")
Return some text on a health check
Return some text on a health check
Python
bsd-3-clause
theirc/CTS,theirc/CTS,theirc/CTS,stbenjam/CTS,stbenjam/CTS,stbenjam/CTS,stbenjam/CTS,theirc/CTS
python
## Code Before: from django.http import HttpResponse def health_view(request): return HttpResponse() ## Instruction: Return some text on a health check ## Code After: from django.http import HttpResponse def health_view(request): return HttpResponse("I am okay.", content_type="text/plain")
// ... existing code ... def health_view(request): return HttpResponse("I am okay.", content_type="text/plain") // ... rest of the code ...
e1bdfbb226795f4dd15fefb109ece2aa9659f421
tests/test_ssl.py
tests/test_ssl.py
from nose.tools import assert_true, assert_false, assert_equal, \ assert_list_equal, raises import datajoint as dj from . import CONN_INFO from pymysql.err import OperationalError class TestSSL: @staticmethod def test_secure_connection(): result = dj.conn(**CONN_INFO, reset=True).query( "SHOW STATUS LIKE 'Ssl_cipher';").fetchone()[1] assert_true(len(result) > 0) @staticmethod def test_insecure_connection(): result = dj.conn(**CONN_INFO, ssl=False, reset=True).query( "SHOW STATUS LIKE 'Ssl_cipher';").fetchone()[1] assert_equal(result, '') @staticmethod @raises(OperationalError) def test_reject_insecure(): result = dj.conn( CONN_INFO['host'], user='djssl', password='djssl', ssl=False, reset=True ).query("SHOW STATUS LIKE 'Ssl_cipher';").fetchone()[1]
from nose.tools import assert_true, assert_false, assert_equal, \ assert_list_equal, raises import datajoint as dj from . import CONN_INFO from pymysql.err import OperationalError class TestSSL: # @staticmethod # def test_secure_connection(): # result = dj.conn(**CONN_INFO, reset=True).query( # "SHOW STATUS LIKE 'Ssl_cipher';").fetchone()[1] # assert_true(len(result) > 0) @staticmethod def test_insecure_connection(): result = dj.conn(**CONN_INFO, ssl=False, reset=True).query( "SHOW STATUS LIKE 'Ssl_cipher';").fetchone()[1] assert_equal(result, '') @staticmethod @raises(OperationalError) def test_reject_insecure(): result = dj.conn( CONN_INFO['host'], user='djssl', password='djssl', ssl=False, reset=True ).query("SHOW STATUS LIKE 'Ssl_cipher';").fetchone()[1]
Disable secure test until new test rig complete.
Disable secure test until new test rig complete.
Python
lgpl-2.1
eywalker/datajoint-python,datajoint/datajoint-python,dimitri-yatsenko/datajoint-python
python
## Code Before: from nose.tools import assert_true, assert_false, assert_equal, \ assert_list_equal, raises import datajoint as dj from . import CONN_INFO from pymysql.err import OperationalError class TestSSL: @staticmethod def test_secure_connection(): result = dj.conn(**CONN_INFO, reset=True).query( "SHOW STATUS LIKE 'Ssl_cipher';").fetchone()[1] assert_true(len(result) > 0) @staticmethod def test_insecure_connection(): result = dj.conn(**CONN_INFO, ssl=False, reset=True).query( "SHOW STATUS LIKE 'Ssl_cipher';").fetchone()[1] assert_equal(result, '') @staticmethod @raises(OperationalError) def test_reject_insecure(): result = dj.conn( CONN_INFO['host'], user='djssl', password='djssl', ssl=False, reset=True ).query("SHOW STATUS LIKE 'Ssl_cipher';").fetchone()[1] ## Instruction: Disable secure test until new test rig complete. ## Code After: from nose.tools import assert_true, assert_false, assert_equal, \ assert_list_equal, raises import datajoint as dj from . import CONN_INFO from pymysql.err import OperationalError class TestSSL: # @staticmethod # def test_secure_connection(): # result = dj.conn(**CONN_INFO, reset=True).query( # "SHOW STATUS LIKE 'Ssl_cipher';").fetchone()[1] # assert_true(len(result) > 0) @staticmethod def test_insecure_connection(): result = dj.conn(**CONN_INFO, ssl=False, reset=True).query( "SHOW STATUS LIKE 'Ssl_cipher';").fetchone()[1] assert_equal(result, '') @staticmethod @raises(OperationalError) def test_reject_insecure(): result = dj.conn( CONN_INFO['host'], user='djssl', password='djssl', ssl=False, reset=True ).query("SHOW STATUS LIKE 'Ssl_cipher';").fetchone()[1]
# ... existing code ... class TestSSL: # @staticmethod # def test_secure_connection(): # result = dj.conn(**CONN_INFO, reset=True).query( # "SHOW STATUS LIKE 'Ssl_cipher';").fetchone()[1] # assert_true(len(result) > 0) @staticmethod def test_insecure_connection(): # ... rest of the code ...
58d7592c603509f2bb625e4e2e5cb31ada4a8194
astropy/nddata/convolution/tests/test_make_kernel.py
astropy/nddata/convolution/tests/test_make_kernel.py
import numpy as np from numpy.testing import assert_allclose, assert_equal from ....tests.helper import pytest from ..make_kernel import make_kernel try: import scipy HAS_SCIPY = True except ImportError: HAS_SCIPY = False class TestMakeKernel(object): """ Test the make_kernel function """ @pytest.mark.skipif('not HAS_SCIPY') def test_airy(self): """ Test kerneltype airy, a.k.a. brickwall Checks https://github.com/astropy/astropy/pull/939 """ k1 = make_kernel([3, 3], kernelwidth=0.5, kerneltype='airy') k2 = make_kernel([3, 3], kernelwidth=0.5, kerneltype='brickwall') ref = np.array([[ 0.06375119, 0.12992753, 0.06375119], [ 0.12992753, 0.22528514, 0.12992753], [ 0.06375119, 0.12992753, 0.06375119]]) assert_allclose(k1, ref, rtol=0, atol=1e-7) assert_equal(k1, k2)
import numpy as np from numpy.testing import assert_allclose from ....tests.helper import pytest from ..make_kernel import make_kernel try: import scipy HAS_SCIPY = True except ImportError: HAS_SCIPY = False @pytest.mark.skipif('not HAS_SCIPY') def test_airy(): """ Test kerneltype airy, a.k.a. brickwall Checks https://github.com/astropy/astropy/pull/939 """ k1 = make_kernel([3, 3], kernelwidth=0.5, kerneltype='airy') ref = np.array([[ 0.06375119, 0.12992753, 0.06375119], [ 0.12992753, 0.22528514, 0.12992753], [ 0.06375119, 0.12992753, 0.06375119]]) assert_allclose(k1, ref, rtol=0, atol=1e-7)
Change test for make_kernel(kerneltype='airy') from class to function
Change test for make_kernel(kerneltype='airy') from class to function
Python
bsd-3-clause
AustereCuriosity/astropy,astropy/astropy,lpsinger/astropy,MSeifert04/astropy,larrybradley/astropy,StuartLittlefair/astropy,dhomeier/astropy,kelle/astropy,joergdietrich/astropy,mhvk/astropy,kelle/astropy,joergdietrich/astropy,StuartLittlefair/astropy,tbabej/astropy,dhomeier/astropy,StuartLittlefair/astropy,mhvk/astropy,DougBurke/astropy,MSeifert04/astropy,AustereCuriosity/astropy,AustereCuriosity/astropy,astropy/astropy,funbaker/astropy,astropy/astropy,stargaser/astropy,stargaser/astropy,DougBurke/astropy,pllim/astropy,tbabej/astropy,pllim/astropy,aleksandr-bakanov/astropy,StuartLittlefair/astropy,funbaker/astropy,larrybradley/astropy,StuartLittlefair/astropy,larrybradley/astropy,larrybradley/astropy,saimn/astropy,bsipocz/astropy,saimn/astropy,stargaser/astropy,joergdietrich/astropy,tbabej/astropy,aleksandr-bakanov/astropy,pllim/astropy,saimn/astropy,lpsinger/astropy,AustereCuriosity/astropy,DougBurke/astropy,pllim/astropy,dhomeier/astropy,funbaker/astropy,pllim/astropy,tbabej/astropy,lpsinger/astropy,astropy/astropy,kelle/astropy,kelle/astropy,aleksandr-bakanov/astropy,astropy/astropy,joergdietrich/astropy,DougBurke/astropy,AustereCuriosity/astropy,funbaker/astropy,saimn/astropy,bsipocz/astropy,MSeifert04/astropy,mhvk/astropy,bsipocz/astropy,mhvk/astropy,larrybradley/astropy,MSeifert04/astropy,aleksandr-bakanov/astropy,lpsinger/astropy,saimn/astropy,tbabej/astropy,dhomeier/astropy,kelle/astropy,dhomeier/astropy,bsipocz/astropy,lpsinger/astropy,stargaser/astropy,joergdietrich/astropy,mhvk/astropy
python
## Code Before: import numpy as np from numpy.testing import assert_allclose, assert_equal from ....tests.helper import pytest from ..make_kernel import make_kernel try: import scipy HAS_SCIPY = True except ImportError: HAS_SCIPY = False class TestMakeKernel(object): """ Test the make_kernel function """ @pytest.mark.skipif('not HAS_SCIPY') def test_airy(self): """ Test kerneltype airy, a.k.a. brickwall Checks https://github.com/astropy/astropy/pull/939 """ k1 = make_kernel([3, 3], kernelwidth=0.5, kerneltype='airy') k2 = make_kernel([3, 3], kernelwidth=0.5, kerneltype='brickwall') ref = np.array([[ 0.06375119, 0.12992753, 0.06375119], [ 0.12992753, 0.22528514, 0.12992753], [ 0.06375119, 0.12992753, 0.06375119]]) assert_allclose(k1, ref, rtol=0, atol=1e-7) assert_equal(k1, k2) ## Instruction: Change test for make_kernel(kerneltype='airy') from class to function ## Code After: import numpy as np from numpy.testing import assert_allclose from ....tests.helper import pytest from ..make_kernel import make_kernel try: import scipy HAS_SCIPY = True except ImportError: HAS_SCIPY = False @pytest.mark.skipif('not HAS_SCIPY') def test_airy(): """ Test kerneltype airy, a.k.a. brickwall Checks https://github.com/astropy/astropy/pull/939 """ k1 = make_kernel([3, 3], kernelwidth=0.5, kerneltype='airy') ref = np.array([[ 0.06375119, 0.12992753, 0.06375119], [ 0.12992753, 0.22528514, 0.12992753], [ 0.06375119, 0.12992753, 0.06375119]]) assert_allclose(k1, ref, rtol=0, atol=1e-7)
# ... existing code ... import numpy as np from numpy.testing import assert_allclose from ....tests.helper import pytest # ... modified code ... except ImportError: HAS_SCIPY = False @pytest.mark.skipif('not HAS_SCIPY') def test_airy(): """ Test kerneltype airy, a.k.a. brickwall Checks https://github.com/astropy/astropy/pull/939 """ k1 = make_kernel([3, 3], kernelwidth=0.5, kerneltype='airy') ref = np.array([[ 0.06375119, 0.12992753, 0.06375119], [ 0.12992753, 0.22528514, 0.12992753], [ 0.06375119, 0.12992753, 0.06375119]]) assert_allclose(k1, ref, rtol=0, atol=1e-7) # ... rest of the code ...
751b246b70a86733886159954e60dc7dd706917b
presto-product-tests/src/main/java/io/prestosql/tests/hive/HiveProductTest.java
presto-product-tests/src/main/java/io/prestosql/tests/hive/HiveProductTest.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.tests.hive; import com.google.inject.Inject; import com.google.inject.name.Named; import io.prestosql.tempto.ProductTest; import static com.google.common.base.Preconditions.checkState; public class HiveProductTest extends ProductTest { @Inject @Named("databases.hive.major_version") private int hiveVersionMajor; protected int getHiveVersionMajor() { checkState(hiveVersionMajor > 0, "hiveVersionMajor not set"); return hiveVersionMajor; } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.tests.hive; import com.google.inject.Inject; import com.google.inject.name.Named; import io.prestosql.tempto.ProductTest; import java.sql.SQLException; import static com.google.common.base.Preconditions.checkState; import static io.prestosql.tests.utils.QueryExecutors.onHive; public class HiveProductTest extends ProductTest { @Inject @Named("databases.hive.major_version") private int hiveVersionMajor; private boolean hiveVersionMajorVerified; protected int getHiveVersionMajor() { checkState(hiveVersionMajor > 0, "hiveVersionMajor not set"); if (!hiveVersionMajorVerified) { int detected = detectHiveVersionMajor(); checkState(hiveVersionMajor == detected, "Hive version major expected: %s, but was detected as: %s", hiveVersionMajor, detected); hiveVersionMajorVerified = true; } return hiveVersionMajor; } private static int detectHiveVersionMajor() { try { return onHive().getConnection().getMetaData().getDatabaseMajorVersion(); } catch (SQLException e) { throw new RuntimeException(e); } } }
Verify Hive version major in product tests
Verify Hive version major in product tests
Java
apache-2.0
treasure-data/presto,losipiuk/presto,11xor6/presto,ebyhr/presto,smartnews/presto,dain/presto,dain/presto,treasure-data/presto,treasure-data/presto,Praveen2112/presto,martint/presto,ebyhr/presto,hgschmie/presto,losipiuk/presto,treasure-data/presto,hgschmie/presto,electrum/presto,losipiuk/presto,Praveen2112/presto,Praveen2112/presto,treasure-data/presto,Praveen2112/presto,11xor6/presto,11xor6/presto,hgschmie/presto,dain/presto,electrum/presto,losipiuk/presto,hgschmie/presto,ebyhr/presto,erichwang/presto,erichwang/presto,electrum/presto,Praveen2112/presto,losipiuk/presto,ebyhr/presto,smartnews/presto,electrum/presto,hgschmie/presto,erichwang/presto,dain/presto,smartnews/presto,11xor6/presto,smartnews/presto,erichwang/presto,smartnews/presto,martint/presto,martint/presto,erichwang/presto,dain/presto,treasure-data/presto,martint/presto,ebyhr/presto,electrum/presto,11xor6/presto,martint/presto
java
## Code Before: /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.tests.hive; import com.google.inject.Inject; import com.google.inject.name.Named; import io.prestosql.tempto.ProductTest; import static com.google.common.base.Preconditions.checkState; public class HiveProductTest extends ProductTest { @Inject @Named("databases.hive.major_version") private int hiveVersionMajor; protected int getHiveVersionMajor() { checkState(hiveVersionMajor > 0, "hiveVersionMajor not set"); return hiveVersionMajor; } } ## Instruction: Verify Hive version major in product tests ## Code After: /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.tests.hive; import com.google.inject.Inject; import com.google.inject.name.Named; import io.prestosql.tempto.ProductTest; import java.sql.SQLException; import static com.google.common.base.Preconditions.checkState; import static io.prestosql.tests.utils.QueryExecutors.onHive; public class HiveProductTest extends ProductTest { @Inject @Named("databases.hive.major_version") private int hiveVersionMajor; private boolean hiveVersionMajorVerified; protected int getHiveVersionMajor() { checkState(hiveVersionMajor > 0, "hiveVersionMajor not set"); if (!hiveVersionMajorVerified) { int detected = detectHiveVersionMajor(); checkState(hiveVersionMajor == detected, "Hive version major expected: %s, but was detected as: %s", hiveVersionMajor, detected); hiveVersionMajorVerified = true; } return hiveVersionMajor; } private static int detectHiveVersionMajor() { try { return onHive().getConnection().getMetaData().getDatabaseMajorVersion(); } catch (SQLException e) { throw new RuntimeException(e); } } }
// ... existing code ... import com.google.inject.name.Named; import io.prestosql.tempto.ProductTest; import java.sql.SQLException; import static com.google.common.base.Preconditions.checkState; import static io.prestosql.tests.utils.QueryExecutors.onHive; public class HiveProductTest extends ProductTest // ... modified code ... @Inject @Named("databases.hive.major_version") private int hiveVersionMajor; private boolean hiveVersionMajorVerified; protected int getHiveVersionMajor() { checkState(hiveVersionMajor > 0, "hiveVersionMajor not set"); if (!hiveVersionMajorVerified) { int detected = detectHiveVersionMajor(); checkState(hiveVersionMajor == detected, "Hive version major expected: %s, but was detected as: %s", hiveVersionMajor, detected); hiveVersionMajorVerified = true; } return hiveVersionMajor; } private static int detectHiveVersionMajor() { try { return onHive().getConnection().getMetaData().getDatabaseMajorVersion(); } catch (SQLException e) { throw new RuntimeException(e); } } } // ... rest of the code ...
d4f63bb099db886f50b6e54838ec9200dbc3ca1f
echo_client.py
echo_client.py
import socket import sys def main(): message = sys.argv[1] port = 50000 address = '127.0.0.1' client_socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) client_socket.connect((address, port)) client_socket.sendall(message) client_socket.shutdown(socket.SHUT_WR) return client_socket.recv(1024) if __name__ == '__main__': print main()
import socket import sys import echo_server from threading import Thread def main(): message = sys.argv[1] port = 50000 address = '127.0.0.1' client_socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) client_socket.connect((address, port)) client_socket.sendall(message) client_socket.shutdown(socket.SHUT_WR) return client_socket.recv(1024) if __name__ == '__main__': t = Thread(target=echo_server.main) t.start() print main()
Add threading to allow for client and server to be run from a single script
Add threading to allow for client and server to be run from a single script
Python
mit
charlieRode/network_tools
python
## Code Before: import socket import sys def main(): message = sys.argv[1] port = 50000 address = '127.0.0.1' client_socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) client_socket.connect((address, port)) client_socket.sendall(message) client_socket.shutdown(socket.SHUT_WR) return client_socket.recv(1024) if __name__ == '__main__': print main() ## Instruction: Add threading to allow for client and server to be run from a single script ## Code After: import socket import sys import echo_server from threading import Thread def main(): message = sys.argv[1] port = 50000 address = '127.0.0.1' client_socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) client_socket.connect((address, port)) client_socket.sendall(message) client_socket.shutdown(socket.SHUT_WR) return client_socket.recv(1024) if __name__ == '__main__': t = Thread(target=echo_server.main) t.start() print main()
# ... existing code ... import socket import sys import echo_server from threading import Thread def main(): # ... modified code ... return client_socket.recv(1024) if __name__ == '__main__': t = Thread(target=echo_server.main) t.start() print main() # ... rest of the code ...
e8da237a6c1542b997b061db43cc993942983b10
django_local_apps/management/commands/local_app_utils/db_clean_utils.py
django_local_apps/management/commands/local_app_utils/db_clean_utils.py
from django.db.models import Q from django.utils import timezone def remove_expired_record(expire_days, query_set, time_attr_name="timestamp"): expired_record_filter = {"%s__lt" % time_attr_name: timezone.now() - timezone.timedelta(days=expire_days)} q = Q(**expired_record_filter) final_q = query_set.filter(q) # cnt = 0 # for i in final_q: # i.delete() # cnt += 1 # if cnt % 1000 == 0: # print "%d deleted" % cnt final_q.delete()
from django.db.models import Q from django.utils import timezone def remove_expired_record(expire_days, query_set, time_attr_name="timestamp"): expired_record_filter = {"%s__lt" % time_attr_name: timezone.now() - timezone.timedelta(days=expire_days)} q = Q(**expired_record_filter) final_q = query_set.filter(q) if final_q.count() > 1000: final_q = final_q[:999] # cnt = 0 # for i in final_q: # i.delete() # cnt += 1 # if cnt % 1000 == 0: # print "%d deleted" % cnt final_q.delete()
Delete item with limited size.
Delete item with limited size.
Python
bsd-3-clause
weijia/django-local-apps,weijia/django-local-apps
python
## Code Before: from django.db.models import Q from django.utils import timezone def remove_expired_record(expire_days, query_set, time_attr_name="timestamp"): expired_record_filter = {"%s__lt" % time_attr_name: timezone.now() - timezone.timedelta(days=expire_days)} q = Q(**expired_record_filter) final_q = query_set.filter(q) # cnt = 0 # for i in final_q: # i.delete() # cnt += 1 # if cnt % 1000 == 0: # print "%d deleted" % cnt final_q.delete() ## Instruction: Delete item with limited size. ## Code After: from django.db.models import Q from django.utils import timezone def remove_expired_record(expire_days, query_set, time_attr_name="timestamp"): expired_record_filter = {"%s__lt" % time_attr_name: timezone.now() - timezone.timedelta(days=expire_days)} q = Q(**expired_record_filter) final_q = query_set.filter(q) if final_q.count() > 1000: final_q = final_q[:999] # cnt = 0 # for i in final_q: # i.delete() # cnt += 1 # if cnt % 1000 == 0: # print "%d deleted" % cnt final_q.delete()
# ... existing code ... expired_record_filter = {"%s__lt" % time_attr_name: timezone.now() - timezone.timedelta(days=expire_days)} q = Q(**expired_record_filter) final_q = query_set.filter(q) if final_q.count() > 1000: final_q = final_q[:999] # cnt = 0 # for i in final_q: # i.delete() # ... rest of the code ...