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
3cd54dd17dbff8843f9fc98e750ad907986d6666
org.metaborg.util/src/main/java/org/metaborg/util/iterators/CompoundIterator.java
org.metaborg.util/src/main/java/org/metaborg/util/iterators/CompoundIterator.java
package org.metaborg.util.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Queue; import com.google.common.collect.Queues; public class CompoundIterator<T> implements Iterator<T> { private final Queue<? extends Iterator<T>> iterators; public CompoundIterator(Iterable<? extends Iterator<T>> iterators) { this.iterators = Queues.newArrayDeque(iterators); } @Override public boolean hasNext() { final Iterator<T> iterator = iterators.peek(); if(iterator == null) { return false; } return iterator.hasNext(); } @Override public T next() { final Iterator<T> iterator = iterators.peek(); if(iterator == null) { throw new NoSuchElementException(); } if(iterator.hasNext()) { return iterator.next(); } else { iterators.poll(); return next(); } } @Override public void remove() { throw new UnsupportedOperationException(); } }
package org.metaborg.util.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import com.google.common.collect.Iterators; public class CompoundIterator<T> implements Iterator<T> { private final Iterator<? extends Iterator<T>> iterators; private Iterator<T> iterator = Iterators.emptyIterator(); public CompoundIterator(Iterable<? extends Iterator<T>> iterators) { this.iterators = iterators.iterator(); } @Override public boolean hasNext() { if(iterator.hasNext()) { return true; } try { iterator = iterators.next(); } catch(NoSuchElementException ex) { return false; } return hasNext(); } @Override public T next() { try { return iterator.next(); } catch(NoSuchElementException ex) { iterator = iterators.next(); } return next(); } @Override public void remove() { throw new UnsupportedOperationException(); } }
Fix compound iterator for case where empty iterators appear in the list.
Fix compound iterator for case where empty iterators appear in the list.
Java
apache-2.0
metaborg/mb-exec,metaborg/mb-exec,metaborg/mb-exec
java
## Code Before: package org.metaborg.util.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Queue; import com.google.common.collect.Queues; public class CompoundIterator<T> implements Iterator<T> { private final Queue<? extends Iterator<T>> iterators; public CompoundIterator(Iterable<? extends Iterator<T>> iterators) { this.iterators = Queues.newArrayDeque(iterators); } @Override public boolean hasNext() { final Iterator<T> iterator = iterators.peek(); if(iterator == null) { return false; } return iterator.hasNext(); } @Override public T next() { final Iterator<T> iterator = iterators.peek(); if(iterator == null) { throw new NoSuchElementException(); } if(iterator.hasNext()) { return iterator.next(); } else { iterators.poll(); return next(); } } @Override public void remove() { throw new UnsupportedOperationException(); } } ## Instruction: Fix compound iterator for case where empty iterators appear in the list. ## Code After: package org.metaborg.util.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import com.google.common.collect.Iterators; public class CompoundIterator<T> implements Iterator<T> { private final Iterator<? extends Iterator<T>> iterators; private Iterator<T> iterator = Iterators.emptyIterator(); public CompoundIterator(Iterable<? extends Iterator<T>> iterators) { this.iterators = iterators.iterator(); } @Override public boolean hasNext() { if(iterator.hasNext()) { return true; } try { iterator = iterators.next(); } catch(NoSuchElementException ex) { return false; } return hasNext(); } @Override public T next() { try { return iterator.next(); } catch(NoSuchElementException ex) { iterator = iterators.next(); } return next(); } @Override public void remove() { throw new UnsupportedOperationException(); } }
# ... existing code ... import java.util.Iterator; import java.util.NoSuchElementException; import com.google.common.collect.Iterators; public class CompoundIterator<T> implements Iterator<T> { private final Iterator<? extends Iterator<T>> iterators; private Iterator<T> iterator = Iterators.emptyIterator(); public CompoundIterator(Iterable<? extends Iterator<T>> iterators) { this.iterators = iterators.iterator(); } @Override public boolean hasNext() { if(iterator.hasNext()) { return true; } try { iterator = iterators.next(); } catch(NoSuchElementException ex) { return false; } return hasNext(); } @Override public T next() { try { return iterator.next(); } catch(NoSuchElementException ex) { iterator = iterators.next(); } return next(); } @Override public void remove() { # ... rest of the code ...
c6e48c224b48e90c57d7731fc88be7703990a02a
app/chess/piece.py
app/chess/piece.py
class ChessPiece(object): def __init__(self): self.column = 0 self.row = 0 self.symbol = '' # Checks piece can attack the specified position def can_attack_position(self, column, row): pass # return the character representation of this chess piece def get_symbol(self): return self.symbol def set_column(self, column): self.column = column def get_column(self): return self.column def set_row(self, row): self.row = row def get_row(self): return self.row class King(ChessPiece): def __init__(self): self.symbol = 'K' print '>>> Buil king piece' def can_attack_position(self, column, row): return True class Queen(ChessPiece): def __init__(self): self.symbol = 'Q' print '>>> Buil Queen piece' def can_attack_position(self, column, row): return True
from math import hypot class ChessPiece(object): def __init__(self): self.x = 0 self.y = 0 self.symbol = '' # Checks piece can attack the specified position def deplace_piece(self, square): self.x = square.x self.y = square.y # return the character representation of this chess piece def get_symbol(self): return self.symbol def set_column(self, column): self.x = column def get_column(self): return self.x def set_row(self, row): self.y = row def get_row(self): return self.y def pos(self): return(self.x, self.y) def check_attack(self, p): return None class King(ChessPiece): def __init__(self): ChessPiece.__init__(self) self.symbol = 'K' print '>>> Buil king piece' def check_attack(self, pos): dist = hypot(self.x - pos.x, self.y - pos.y) if dist <= 1: return True else: return False class Queen(ChessPiece): def __init__(self): ChessPiece.__init__(self) self.symbol = 'Q' print '>>> Buil Queen piece' def check_attack(self, pos): return True
Add attack function to KING class
Add attack function to KING class
Python
mit
aymguesmi/ChessChallenge
python
## Code Before: class ChessPiece(object): def __init__(self): self.column = 0 self.row = 0 self.symbol = '' # Checks piece can attack the specified position def can_attack_position(self, column, row): pass # return the character representation of this chess piece def get_symbol(self): return self.symbol def set_column(self, column): self.column = column def get_column(self): return self.column def set_row(self, row): self.row = row def get_row(self): return self.row class King(ChessPiece): def __init__(self): self.symbol = 'K' print '>>> Buil king piece' def can_attack_position(self, column, row): return True class Queen(ChessPiece): def __init__(self): self.symbol = 'Q' print '>>> Buil Queen piece' def can_attack_position(self, column, row): return True ## Instruction: Add attack function to KING class ## Code After: from math import hypot class ChessPiece(object): def __init__(self): self.x = 0 self.y = 0 self.symbol = '' # Checks piece can attack the specified position def deplace_piece(self, square): self.x = square.x self.y = square.y # return the character representation of this chess piece def get_symbol(self): return self.symbol def set_column(self, column): self.x = column def get_column(self): return self.x def set_row(self, row): self.y = row def get_row(self): return self.y def pos(self): return(self.x, self.y) def check_attack(self, p): return None class King(ChessPiece): def __init__(self): ChessPiece.__init__(self) self.symbol = 'K' print '>>> Buil king piece' def check_attack(self, pos): dist = hypot(self.x - pos.x, self.y - pos.y) if dist <= 1: return True else: return False class Queen(ChessPiece): def __init__(self): ChessPiece.__init__(self) self.symbol = 'Q' print '>>> Buil Queen piece' def check_attack(self, pos): return True
# ... existing code ... from math import hypot class ChessPiece(object): def __init__(self): self.x = 0 self.y = 0 self.symbol = '' # Checks piece can attack the specified position def deplace_piece(self, square): self.x = square.x self.y = square.y # return the character representation of this chess piece def get_symbol(self): # ... modified code ... return self.symbol def set_column(self, column): self.x = column def get_column(self): return self.x def set_row(self, row): self.y = row def get_row(self): return self.y def pos(self): return(self.x, self.y) def check_attack(self, p): return None class King(ChessPiece): def __init__(self): ChessPiece.__init__(self) self.symbol = 'K' print '>>> Buil king piece' def check_attack(self, pos): dist = hypot(self.x - pos.x, self.y - pos.y) if dist <= 1: return True else: return False class Queen(ChessPiece): def __init__(self): ChessPiece.__init__(self) self.symbol = 'Q' print '>>> Buil Queen piece' def check_attack(self, pos): return True # ... rest of the code ...
e096343aaaa916232633543d57431b7f3022215a
awscfncli/__main__.py
awscfncli/__main__.py
__author__ = 'kotaimen' __date__ = '28-Feb-2018' """Main cli entry point, called when awscfncli is run as a package, imported in setuptools intergration. cli package stucture: Click main entry: cli/main.py Command groups: cli/group_named/__init__.py Subcommands: cli/group_name/command_name.py All commands are imported in cli/__init__.py to get registered into click. """ from .cli import cfn_cli def main(): cfn_cli() if __name__ == '__main__': main()
__author__ = 'kotaimen' __date__ = '28-Feb-2018' """Main cli entry point, called when awscfncli is run as a package, imported in setuptools intergration. cli package stucture: Click main entry: cli/main.py Command groups: cli/group_named/__init__.py Subcommands: cli/group_name/command_name.py All commands are imported in cli/__init__.py to get registered into click. """ from .cli import cfn_cli def main(): cfn_cli( auto_envvar_prefix='CFN' ) if __name__ == '__main__': main()
Add click automatic environment variable prefix.
Add click automatic environment variable prefix.
Python
mit
Kotaimen/awscfncli,Kotaimen/awscfncli
python
## Code Before: __author__ = 'kotaimen' __date__ = '28-Feb-2018' """Main cli entry point, called when awscfncli is run as a package, imported in setuptools intergration. cli package stucture: Click main entry: cli/main.py Command groups: cli/group_named/__init__.py Subcommands: cli/group_name/command_name.py All commands are imported in cli/__init__.py to get registered into click. """ from .cli import cfn_cli def main(): cfn_cli() if __name__ == '__main__': main() ## Instruction: Add click automatic environment variable prefix. ## Code After: __author__ = 'kotaimen' __date__ = '28-Feb-2018' """Main cli entry point, called when awscfncli is run as a package, imported in setuptools intergration. cli package stucture: Click main entry: cli/main.py Command groups: cli/group_named/__init__.py Subcommands: cli/group_name/command_name.py All commands are imported in cli/__init__.py to get registered into click. """ from .cli import cfn_cli def main(): cfn_cli( auto_envvar_prefix='CFN' ) if __name__ == '__main__': main()
... def main(): cfn_cli( auto_envvar_prefix='CFN' ) if __name__ == '__main__': ...
33e3e17ddba9b6420523648a5fcaf9632b24c65c
apps/web/src/main/java/uk/co/ticklethepanda/carto/apps/web/config/ProjectionConfig.java
apps/web/src/main/java/uk/co/ticklethepanda/carto/apps/web/config/ProjectionConfig.java
package uk.co.ticklethepanda.carto.apps.web.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import uk.co.ticklethepanda.carto.core.projection.Projector; @Configuration public class ProjectionConfig { @Bean(name = "projector") public Projector projector( @Value("${location.history.heatmap.projector}") String projectorName ) throws ClassNotFoundException, IllegalAccessException, InstantiationException { Class<?> projectorClass = Class.forName(projectorName); Object projector = projectorClass.newInstance(); if (!(projector instanceof Projector)) { throw new IllegalArgumentException("\"location.history.heatmap.projector\" must be a type of Projector"); } return (Projector) projector; } }
package uk.co.ticklethepanda.carto.apps.web.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import uk.co.ticklethepanda.carto.core.projection.Projector; import java.lang.reflect.InvocationTargetException; @Configuration public class ProjectionConfig { @Bean(name = "projector") public Projector projector( @Value("${location.history.heatmap.projector}") String projectorName ) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { Class<?> projectorClass = Class.forName(projectorName); Object projector = projectorClass.getDeclaredConstructor().newInstance(); if (!(projector instanceof Projector)) { throw new IllegalArgumentException("\"location.history.heatmap.projector\" must be a type of Projector"); } return (Projector) projector; } }
Use non-deprecated new instance method
Use non-deprecated new instance method
Java
mit
TickleThePanda/location-history,TickleThePanda/location-history
java
## Code Before: package uk.co.ticklethepanda.carto.apps.web.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import uk.co.ticklethepanda.carto.core.projection.Projector; @Configuration public class ProjectionConfig { @Bean(name = "projector") public Projector projector( @Value("${location.history.heatmap.projector}") String projectorName ) throws ClassNotFoundException, IllegalAccessException, InstantiationException { Class<?> projectorClass = Class.forName(projectorName); Object projector = projectorClass.newInstance(); if (!(projector instanceof Projector)) { throw new IllegalArgumentException("\"location.history.heatmap.projector\" must be a type of Projector"); } return (Projector) projector; } } ## Instruction: Use non-deprecated new instance method ## Code After: package uk.co.ticklethepanda.carto.apps.web.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import uk.co.ticklethepanda.carto.core.projection.Projector; import java.lang.reflect.InvocationTargetException; @Configuration public class ProjectionConfig { @Bean(name = "projector") public Projector projector( @Value("${location.history.heatmap.projector}") String projectorName ) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { Class<?> projectorClass = Class.forName(projectorName); Object projector = projectorClass.getDeclaredConstructor().newInstance(); if (!(projector instanceof Projector)) { throw new IllegalArgumentException("\"location.history.heatmap.projector\" must be a type of Projector"); } return (Projector) projector; } }
... import org.springframework.context.annotation.Configuration; import uk.co.ticklethepanda.carto.core.projection.Projector; import java.lang.reflect.InvocationTargetException; @Configuration public class ProjectionConfig { ... @Bean(name = "projector") public Projector projector( @Value("${location.history.heatmap.projector}") String projectorName ) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { Class<?> projectorClass = Class.forName(projectorName); Object projector = projectorClass.getDeclaredConstructor().newInstance(); if (!(projector instanceof Projector)) { throw new IllegalArgumentException("\"location.history.heatmap.projector\" must be a type of Projector"); ...
d7ebf5c6db9b73133915aabb3dbd9c5b283f9982
ooni/tests/test_trueheaders.py
ooni/tests/test_trueheaders.py
from twisted.trial import unittest from ooni.utils.txagentwithsocks import TrueHeaders dummy_headers_dict = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'] } dummy_headers_dict2 = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'], 'Header3': ['ValueA', 'ValueB'], } dummy_headers_dict3 = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'], 'Header4': ['ValueA', 'ValueB'], } class TestTrueHeaders(unittest.TestCase): def test_names_match(self): th = TrueHeaders(dummy_headers_dict) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict)), set()) def test_names_not_match(self): th = TrueHeaders(dummy_headers_dict) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3'])) th = TrueHeaders(dummy_headers_dict3) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3', 'Header4'])) def test_names_match_expect_ignore(self): th = TrueHeaders(dummy_headers_dict) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2), ignore=['Header3']), set())
from twisted.trial import unittest from ooni.utils.trueheaders import TrueHeaders dummy_headers_dict = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'] } dummy_headers_dict2 = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'], 'Header3': ['ValueA', 'ValueB'], } dummy_headers_dict3 = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'], 'Header4': ['ValueA', 'ValueB'], } class TestTrueHeaders(unittest.TestCase): def test_names_match(self): th = TrueHeaders(dummy_headers_dict) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict)), set()) def test_names_not_match(self): th = TrueHeaders(dummy_headers_dict) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3'])) th = TrueHeaders(dummy_headers_dict3) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3', 'Header4'])) def test_names_match_expect_ignore(self): th = TrueHeaders(dummy_headers_dict) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2), ignore=['Header3']), set())
Fix unittest for true headers..
Fix unittest for true headers..
Python
bsd-2-clause
kdmurray91/ooni-probe,kdmurray91/ooni-probe,kdmurray91/ooni-probe,juga0/ooni-probe,juga0/ooni-probe,lordappsec/ooni-probe,lordappsec/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,lordappsec/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,kdmurray91/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-probe,0xPoly/ooni-probe,lordappsec/ooni-probe
python
## Code Before: from twisted.trial import unittest from ooni.utils.txagentwithsocks import TrueHeaders dummy_headers_dict = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'] } dummy_headers_dict2 = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'], 'Header3': ['ValueA', 'ValueB'], } dummy_headers_dict3 = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'], 'Header4': ['ValueA', 'ValueB'], } class TestTrueHeaders(unittest.TestCase): def test_names_match(self): th = TrueHeaders(dummy_headers_dict) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict)), set()) def test_names_not_match(self): th = TrueHeaders(dummy_headers_dict) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3'])) th = TrueHeaders(dummy_headers_dict3) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3', 'Header4'])) def test_names_match_expect_ignore(self): th = TrueHeaders(dummy_headers_dict) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2), ignore=['Header3']), set()) ## Instruction: Fix unittest for true headers.. ## Code After: from twisted.trial import unittest from ooni.utils.trueheaders import TrueHeaders dummy_headers_dict = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'] } dummy_headers_dict2 = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'], 'Header3': ['ValueA', 'ValueB'], } dummy_headers_dict3 = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'], 'Header4': ['ValueA', 'ValueB'], } class TestTrueHeaders(unittest.TestCase): def test_names_match(self): th = TrueHeaders(dummy_headers_dict) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict)), set()) def test_names_not_match(self): th = TrueHeaders(dummy_headers_dict) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3'])) th = TrueHeaders(dummy_headers_dict3) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3', 'Header4'])) def test_names_match_expect_ignore(self): th = TrueHeaders(dummy_headers_dict) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2), ignore=['Header3']), set())
// ... existing code ... from twisted.trial import unittest from ooni.utils.trueheaders import TrueHeaders dummy_headers_dict = { 'Header1': ['Value1', 'Value2'], // ... rest of the code ...
c81d075dd11591e6b68f3f1444d80200db24bfad
install.py
install.py
import os import stat import config TEMPLATE_FILE = 'powerline-shell.py.template' OUTPUT_FILE = 'powerline-shell.py' SEGMENTS_DIR = 'segments' THEMES_DIR = 'themes' def load_source(srcfile): try: return ''.join(open(srcfile).readlines()) + '\n\n' except IOError: print 'Could not open', srcfile return '' if __name__ == "__main__": try: with open('config.py'): pass except IOError: print 'Please copy config.py.dist to config.py and retry.' exit(1) source = load_source(TEMPLATE_FILE) source += load_source(os.path.join(THEMES_DIR, config.THEME + '.py')) for segment in config.SEGMENTS: source += load_source(os.path.join(SEGMENTS_DIR, segment + '.py')) source += 'sys.stdout.write(powerline.draw())\n' try: open(OUTPUT_FILE, 'w').write(source) st = os.stat(OUTPUT_FILE) os.chmod(OUTPUT_FILE, st.st_mode | stat.S_IEXEC) print OUTPUT_FILE, 'saved successfully' except IOError: print 'ERROR: Could not write to powerline-shell.py. Make sure it is writable'
import os import stat import config import shutil TEMPLATE_FILE = 'powerline-shell.py.template' OUTPUT_FILE = 'powerline-shell.py' SEGMENTS_DIR = 'segments' THEMES_DIR = 'themes' def load_source(srcfile): try: return ''.join(open(srcfile).readlines()) + '\n\n' except IOError: print 'Could not open', srcfile return '' if __name__ == "__main__": try: with open('config.py'): pass except IOError: print 'Created personal config.py for your customizations' shutil.copyfile('config.py.dist', 'config.py') source = load_source(TEMPLATE_FILE) source += load_source(os.path.join(THEMES_DIR, config.THEME + '.py')) for segment in config.SEGMENTS: source += load_source(os.path.join(SEGMENTS_DIR, segment + '.py')) source += 'sys.stdout.write(powerline.draw())\n' try: open(OUTPUT_FILE, 'w').write(source) st = os.stat(OUTPUT_FILE) os.chmod(OUTPUT_FILE, st.st_mode | stat.S_IEXEC) print OUTPUT_FILE, 'saved successfully' except IOError: print 'ERROR: Could not write to powerline-shell.py. Make sure it is writable' exit(1)
Create a config.py rather than having people do it manually.
Create a config.py rather than having people do it manually.
Python
mit
banga/powerline-shell,intfrr/powerline-shell,ceholden/powerline-shell,banga/powerline-shell,bitIO/powerline-shell,paulhybryant/powerline-shell,b-ryan/powerline-shell,LeonardoGentile/powerline-shell,yc2prime/powerline-shell,dtrip/powerline-shell,fellipecastro/powerline-shell,tswsl1989/powerline-shell,paulhybryant/powerline-shell,saghul/shline,blieque/powerline-shell,MartinWetterwald/powerline-shell,iKrishneel/powerline-shell,torbjornvatn/powerline-shell,mcdope/powerline-shell,handsomecheung/powerline-shell,junix/powerline-shell,Menci/powerline-shell,wrgoldstein/powerline-shell,mart-e/powerline-shell,paol/powerline-shell,JulianVolodia/powerline-shell,rbanffy/powerline-shell,eran-stratoscale/powerline-shell,milkbikis/powerline-shell,b-ryan/powerline-shell,strycore/powerline-shell,guykr-stratoscale/powerline-shell,nicholascapo/powerline-shell
python
## Code Before: import os import stat import config TEMPLATE_FILE = 'powerline-shell.py.template' OUTPUT_FILE = 'powerline-shell.py' SEGMENTS_DIR = 'segments' THEMES_DIR = 'themes' def load_source(srcfile): try: return ''.join(open(srcfile).readlines()) + '\n\n' except IOError: print 'Could not open', srcfile return '' if __name__ == "__main__": try: with open('config.py'): pass except IOError: print 'Please copy config.py.dist to config.py and retry.' exit(1) source = load_source(TEMPLATE_FILE) source += load_source(os.path.join(THEMES_DIR, config.THEME + '.py')) for segment in config.SEGMENTS: source += load_source(os.path.join(SEGMENTS_DIR, segment + '.py')) source += 'sys.stdout.write(powerline.draw())\n' try: open(OUTPUT_FILE, 'w').write(source) st = os.stat(OUTPUT_FILE) os.chmod(OUTPUT_FILE, st.st_mode | stat.S_IEXEC) print OUTPUT_FILE, 'saved successfully' except IOError: print 'ERROR: Could not write to powerline-shell.py. Make sure it is writable' ## Instruction: Create a config.py rather than having people do it manually. ## Code After: import os import stat import config import shutil TEMPLATE_FILE = 'powerline-shell.py.template' OUTPUT_FILE = 'powerline-shell.py' SEGMENTS_DIR = 'segments' THEMES_DIR = 'themes' def load_source(srcfile): try: return ''.join(open(srcfile).readlines()) + '\n\n' except IOError: print 'Could not open', srcfile return '' if __name__ == "__main__": try: with open('config.py'): pass except IOError: print 'Created personal config.py for your customizations' shutil.copyfile('config.py.dist', 'config.py') source = load_source(TEMPLATE_FILE) source += load_source(os.path.join(THEMES_DIR, config.THEME + '.py')) for segment in config.SEGMENTS: source += load_source(os.path.join(SEGMENTS_DIR, segment + '.py')) source += 'sys.stdout.write(powerline.draw())\n' try: open(OUTPUT_FILE, 'w').write(source) st = os.stat(OUTPUT_FILE) os.chmod(OUTPUT_FILE, st.st_mode | stat.S_IEXEC) print OUTPUT_FILE, 'saved successfully' except IOError: print 'ERROR: Could not write to powerline-shell.py. Make sure it is writable' exit(1)
// ... existing code ... import os import stat import config import shutil TEMPLATE_FILE = 'powerline-shell.py.template' OUTPUT_FILE = 'powerline-shell.py' // ... modified code ... try: with open('config.py'): pass except IOError: print 'Created personal config.py for your customizations' shutil.copyfile('config.py.dist', 'config.py') source = load_source(TEMPLATE_FILE) source += load_source(os.path.join(THEMES_DIR, config.THEME + '.py')) for segment in config.SEGMENTS: ... print OUTPUT_FILE, 'saved successfully' except IOError: print 'ERROR: Could not write to powerline-shell.py. Make sure it is writable' exit(1) // ... rest of the code ...
f2a47110c9416a1efcf2a4346303377afedc2315
builders/horizons_telnet.py
builders/horizons_telnet.py
from telnetlib import Telnet def main(in_path, out_path): lines = read_lines(open(in_path)) tn = Telnet('horizons.jpl.nasa.gov', 6775) out = open(out_path, 'w') for line in lines: print(repr(line)) tn.write(line.encode('ascii') + b'\r\n') data = tn.read_until(b'DUMMY PATTERN', 5.0).decode('ascii') print(repr(data)) out.write(data) out.flush() def read_lines(f): for line in f: line = line.strip() if (not line) or line.startswith('#'): continue yield line if __name__ == '__main__': try: main('horizons_input.txt', 'horizons_output.txt') except EOFError: print print('EOF')
from telnetlib import Telnet def main(in_path, out_path): lines = read_lines(open(in_path)) tn = Telnet('horizons.jpl.nasa.gov', 6775) out = open(out_path, 'w') for line in lines: print(repr(line)) tn.write(line.encode('ascii') + b'\r\n') index, match, data1 = tn.expect([b'.'], 5.0) data2 = tn.read_until(b'DUMMY PATTERN', 1.0) data = (data1 + data2).decode('ascii') print(repr(data)) out.write(data) out.flush() def read_lines(f): for line in f: line = line.strip() if (not line) or line.startswith('#'): continue yield line if __name__ == '__main__': try: main('horizons_input.txt', 'horizons_output.txt') except EOFError: print print('EOF')
Speed up the telnet process for HORIZONS
Speed up the telnet process for HORIZONS Be very patient waiting for the other end to start its reply, but then only wait 1s for the rest of the data.
Python
mit
exoanalytic/python-skyfield,ozialien/python-skyfield,exoanalytic/python-skyfield,skyfielders/python-skyfield,ozialien/python-skyfield,GuidoBR/python-skyfield,GuidoBR/python-skyfield,skyfielders/python-skyfield
python
## Code Before: from telnetlib import Telnet def main(in_path, out_path): lines = read_lines(open(in_path)) tn = Telnet('horizons.jpl.nasa.gov', 6775) out = open(out_path, 'w') for line in lines: print(repr(line)) tn.write(line.encode('ascii') + b'\r\n') data = tn.read_until(b'DUMMY PATTERN', 5.0).decode('ascii') print(repr(data)) out.write(data) out.flush() def read_lines(f): for line in f: line = line.strip() if (not line) or line.startswith('#'): continue yield line if __name__ == '__main__': try: main('horizons_input.txt', 'horizons_output.txt') except EOFError: print print('EOF') ## Instruction: Speed up the telnet process for HORIZONS Be very patient waiting for the other end to start its reply, but then only wait 1s for the rest of the data. ## Code After: from telnetlib import Telnet def main(in_path, out_path): lines = read_lines(open(in_path)) tn = Telnet('horizons.jpl.nasa.gov', 6775) out = open(out_path, 'w') for line in lines: print(repr(line)) tn.write(line.encode('ascii') + b'\r\n') index, match, data1 = tn.expect([b'.'], 5.0) data2 = tn.read_until(b'DUMMY PATTERN', 1.0) data = (data1 + data2).decode('ascii') print(repr(data)) out.write(data) out.flush() def read_lines(f): for line in f: line = line.strip() if (not line) or line.startswith('#'): continue yield line if __name__ == '__main__': try: main('horizons_input.txt', 'horizons_output.txt') except EOFError: print print('EOF')
// ... existing code ... for line in lines: print(repr(line)) tn.write(line.encode('ascii') + b'\r\n') index, match, data1 = tn.expect([b'.'], 5.0) data2 = tn.read_until(b'DUMMY PATTERN', 1.0) data = (data1 + data2).decode('ascii') print(repr(data)) out.write(data) out.flush() // ... rest of the code ...
79450cd4313e8ce50f7cb2035bd14497e1308249
src/main/java/hackerrank/GameOfThrones1.java
src/main/java/hackerrank/GameOfThrones1.java
package hackerrank; import java.util.Scanner; public class GameOfThrones1 { private static String isPalindrome(String str) { // TODO: return "YES"; } public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.next(); System.out.println(isPalindrome(str)); } }
package hackerrank; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class GameOfThrones1 { private static String isPalindrome(String str) { Map<Character, Integer> counts = new HashMap<>(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (!counts.containsKey(c)) { counts.put(c, 1); } else { counts.put(c, counts.get(c) + 1); } } int odd = 0; for (Map.Entry<Character, Integer> e : counts.entrySet()) { if (e.getValue() % 2 != 0) { odd++; } } if (odd > 1) { return "NO"; } return "YES"; } public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.next(); System.out.println(isPalindrome(str)); } }
Solve Game of Thrones 1
Solve Game of Thrones 1
Java
mit
fredyw/hackerrank
java
## Code Before: package hackerrank; import java.util.Scanner; public class GameOfThrones1 { private static String isPalindrome(String str) { // TODO: return "YES"; } public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.next(); System.out.println(isPalindrome(str)); } } ## Instruction: Solve Game of Thrones 1 ## Code After: package hackerrank; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class GameOfThrones1 { private static String isPalindrome(String str) { Map<Character, Integer> counts = new HashMap<>(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (!counts.containsKey(c)) { counts.put(c, 1); } else { counts.put(c, counts.get(c) + 1); } } int odd = 0; for (Map.Entry<Character, Integer> e : counts.entrySet()) { if (e.getValue() % 2 != 0) { odd++; } } if (odd > 1) { return "NO"; } return "YES"; } public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.next(); System.out.println(isPalindrome(str)); } }
// ... existing code ... package hackerrank; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class GameOfThrones1 { private static String isPalindrome(String str) { Map<Character, Integer> counts = new HashMap<>(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (!counts.containsKey(c)) { counts.put(c, 1); } else { counts.put(c, counts.get(c) + 1); } } int odd = 0; for (Map.Entry<Character, Integer> e : counts.entrySet()) { if (e.getValue() % 2 != 0) { odd++; } } if (odd > 1) { return "NO"; } return "YES"; } // ... rest of the code ...
51f32076e8708c55420989b660323cdfd9fc6650
cycy/interpreter.py
cycy/interpreter.py
from cycy import compiler from cycy.parser.sourceparser import parse class CyCy(object): """ The main CyCy interpreter. """ def run(self, bytecode): pass def interpret(source): print "Hello, world!" return bytecode = compiler.Context.to_bytecode(parse(source.getContent())) CyCy().run(bytecode)
from cycy import compiler from cycy.parser.sourceparser import parse class CyCy(object): """ The main CyCy interpreter. """ def run(self, bytecode): pass def interpret(source): bytecode = compiler.Context.to_bytecode(parse(source)) CyCy().run(bytecode)
Break the tests to show us we're not writing RPython.
Break the tests to show us we're not writing RPython.
Python
mit
Magnetic/cycy,Magnetic/cycy,Magnetic/cycy
python
## Code Before: from cycy import compiler from cycy.parser.sourceparser import parse class CyCy(object): """ The main CyCy interpreter. """ def run(self, bytecode): pass def interpret(source): print "Hello, world!" return bytecode = compiler.Context.to_bytecode(parse(source.getContent())) CyCy().run(bytecode) ## Instruction: Break the tests to show us we're not writing RPython. ## Code After: from cycy import compiler from cycy.parser.sourceparser import parse class CyCy(object): """ The main CyCy interpreter. """ def run(self, bytecode): pass def interpret(source): bytecode = compiler.Context.to_bytecode(parse(source)) CyCy().run(bytecode)
# ... existing code ... def interpret(source): bytecode = compiler.Context.to_bytecode(parse(source)) CyCy().run(bytecode) # ... rest of the code ...
ce5148894cbf4a465e2bc1158e8a4f8a729f6632
test/PCH/va_arg.c
test/PCH/va_arg.c
// Test this without pch. // RUN: clang-cc -triple=x86_64-unknown-freebsd7.0 -include %S/va_arg.h %s -emit-llvm -o - && // Test with pch. // RUN: clang-cc -triple=x86_64-unknown-freebsd7.0 -o %t %S/va_arg.h && // RUN: clang-cc -triple=x86_64-unknown-freebsd7.0 -include-pch %t %s -emit-llvm -o - char *g0(char** argv, int argc) { return argv[argc]; } char *g(char **argv) { f(g0, argv, 1, 2, 3); }
// Test this without pch. // RUN: clang-cc -triple=x86_64-unknown-freebsd7.0 -include %S/va_arg.h %s -emit-llvm -o - && // Test with pch. // RUN: clang-cc -triple=x86_64-unknown-freebsd7.0 -emit-pch -o %t %S/va_arg.h && // RUN: clang-cc -triple=x86_64-unknown-freebsd7.0 -include-pch %t %s -emit-llvm -o - char *g0(char** argv, int argc) { return argv[argc]; } char *g(char **argv) { f(g0, argv, 1, 2, 3); }
Fix a problem with the RUN line of one of the PCH tests
Fix a problem with the RUN line of one of the PCH tests git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@70227 91177308-0d34-0410-b5e6-96231b3b80d8
C
apache-2.0
apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang
c
## Code Before: // Test this without pch. // RUN: clang-cc -triple=x86_64-unknown-freebsd7.0 -include %S/va_arg.h %s -emit-llvm -o - && // Test with pch. // RUN: clang-cc -triple=x86_64-unknown-freebsd7.0 -o %t %S/va_arg.h && // RUN: clang-cc -triple=x86_64-unknown-freebsd7.0 -include-pch %t %s -emit-llvm -o - char *g0(char** argv, int argc) { return argv[argc]; } char *g(char **argv) { f(g0, argv, 1, 2, 3); } ## Instruction: Fix a problem with the RUN line of one of the PCH tests git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@70227 91177308-0d34-0410-b5e6-96231b3b80d8 ## Code After: // Test this without pch. // RUN: clang-cc -triple=x86_64-unknown-freebsd7.0 -include %S/va_arg.h %s -emit-llvm -o - && // Test with pch. // RUN: clang-cc -triple=x86_64-unknown-freebsd7.0 -emit-pch -o %t %S/va_arg.h && // RUN: clang-cc -triple=x86_64-unknown-freebsd7.0 -include-pch %t %s -emit-llvm -o - char *g0(char** argv, int argc) { return argv[argc]; } char *g(char **argv) { f(g0, argv, 1, 2, 3); }
// ... existing code ... // RUN: clang-cc -triple=x86_64-unknown-freebsd7.0 -include %S/va_arg.h %s -emit-llvm -o - && // Test with pch. // RUN: clang-cc -triple=x86_64-unknown-freebsd7.0 -emit-pch -o %t %S/va_arg.h && // RUN: clang-cc -triple=x86_64-unknown-freebsd7.0 -include-pch %t %s -emit-llvm -o - char *g0(char** argv, int argc) { return argv[argc]; } // ... rest of the code ...
1f89d17a16789768c72b02415f2319150a0b9ab3
app/src/test/java/lt/vilnius/tvarkau/dagger/module/TestAnalyticsModule.kt
app/src/test/java/lt/vilnius/tvarkau/dagger/module/TestAnalyticsModule.kt
package lt.vilnius.tvarkau.dagger.module import android.app.Application import com.nhaarman.mockito_kotlin.mock import dagger.Module import dagger.Provides import lt.vilnius.tvarkau.analytics.Analytics import javax.inject.Singleton /** * @author Martynas Jurkus */ @Module class TestAnalyticsModule { @Provides @Singleton fun providesAnalytics(application: Application): Analytics = mock() }
package lt.vilnius.tvarkau.dagger.module import android.app.Application import com.mixpanel.android.mpmetrics.MixpanelAPI import com.nhaarman.mockito_kotlin.mock import dagger.Module import dagger.Provides import lt.vilnius.tvarkau.analytics.Analytics import javax.inject.Singleton /** * @author Martynas Jurkus */ @Module class TestAnalyticsModule { @Provides @Singleton internal fun providesMixpanel(application: Application): MixpanelAPI = mock() @Provides @Singleton fun providesAnalytics(application: Application): Analytics = mock() }
Add mock method for MixPanel
Add mock method for MixPanel
Kotlin
mit
vilnius/tvarkau-vilniu,vilnius/tvarkau-vilniu
kotlin
## Code Before: package lt.vilnius.tvarkau.dagger.module import android.app.Application import com.nhaarman.mockito_kotlin.mock import dagger.Module import dagger.Provides import lt.vilnius.tvarkau.analytics.Analytics import javax.inject.Singleton /** * @author Martynas Jurkus */ @Module class TestAnalyticsModule { @Provides @Singleton fun providesAnalytics(application: Application): Analytics = mock() } ## Instruction: Add mock method for MixPanel ## Code After: package lt.vilnius.tvarkau.dagger.module import android.app.Application import com.mixpanel.android.mpmetrics.MixpanelAPI import com.nhaarman.mockito_kotlin.mock import dagger.Module import dagger.Provides import lt.vilnius.tvarkau.analytics.Analytics import javax.inject.Singleton /** * @author Martynas Jurkus */ @Module class TestAnalyticsModule { @Provides @Singleton internal fun providesMixpanel(application: Application): MixpanelAPI = mock() @Provides @Singleton fun providesAnalytics(application: Application): Analytics = mock() }
// ... existing code ... package lt.vilnius.tvarkau.dagger.module import android.app.Application import com.mixpanel.android.mpmetrics.MixpanelAPI import com.nhaarman.mockito_kotlin.mock import dagger.Module import dagger.Provides // ... modified code ... @Provides @Singleton internal fun providesMixpanel(application: Application): MixpanelAPI = mock() @Provides @Singleton fun providesAnalytics(application: Application): Analytics = mock() } // ... rest of the code ...
754d2949ce0c2fa2b36615af755b3b8aaf9876b5
tests/test_resources.py
tests/test_resources.py
import pytest from micromanager.resources import Resource from micromanager.resources import BQDataset from micromanager.resources import Bucket from micromanager.resources import SQLInstance test_cases = [ ( {'resource_kind': 'storage#bucket'}, Bucket ), ( {'resource_kind': 'sql#instance'}, SQLInstance ), ( {'resource_kind': 'bigquery#dataset'}, BQDataset ) ] @pytest.mark.parametrize( "input,expected", test_cases, ids=[cls.__name__ for (_, cls) in test_cases]) def test_resource_factory(input, expected): r = Resource.factory(input) assert r.__class__ == expected def test_resource_factory_invalid(): with pytest.raises(AssertionError): r = Resource.factory({})
import pytest from .util import load_test_data from .util import discovery_cache from .mock import HttpMockSequenceEx from googleapiclient.http import HttpMockSequence from micromanager.resources import Resource from micromanager.resources.gcp import GcpBigqueryDataset from micromanager.resources.gcp import GcpComputeInstance from micromanager.resources.gcp import GcpSqlInstance from micromanager.resources.gcp import GcpStorageBucket from micromanager.resources.gcp import GcpStorageBucketIamPolicy test_cases = [ ( {'resource_type': 'bigquery.datasets', 'resource_name': '', 'project_id': ''}, GcpBigqueryDataset, 'gcp.bigquery.datasets' ), ( {'resource_type': 'compute.instances', 'resource_name': '', 'project_id': ''}, GcpComputeInstance, 'gcp.compute.instances' ), ( {'resource_type': 'sqladmin.instances', 'resource_name': '', 'project_id': ''}, GcpSqlInstance, 'gcp.sqladmin.instances' ), ( {'resource_type': 'storage.buckets', 'resource_name': '', 'project_id': ''}, GcpStorageBucket, 'gcp.storage.buckets' ), ( {'resource_type': 'storage.buckets.iam', 'resource_name': '', 'project_id': ''}, GcpStorageBucketIamPolicy, 'gcp.storage.buckets.iam' ) ] @pytest.mark.parametrize( "input,cls,rtype", test_cases, ids=[cls.__name__ for (_, cls, _) in test_cases]) def test_gcp_resource_factory(input, cls, rtype): r = Resource.factory("gcp", input) assert r.__class__ == cls assert r.type() == rtype def test_gcp_resource_factory_invalid(): with pytest.raises(AssertionError): r = Resource.factory('gcp', {})
Update tests after lots of work on Resources
Update tests after lots of work on Resources
Python
apache-2.0
forseti-security/resource-policy-evaluation-library
python
## Code Before: import pytest from micromanager.resources import Resource from micromanager.resources import BQDataset from micromanager.resources import Bucket from micromanager.resources import SQLInstance test_cases = [ ( {'resource_kind': 'storage#bucket'}, Bucket ), ( {'resource_kind': 'sql#instance'}, SQLInstance ), ( {'resource_kind': 'bigquery#dataset'}, BQDataset ) ] @pytest.mark.parametrize( "input,expected", test_cases, ids=[cls.__name__ for (_, cls) in test_cases]) def test_resource_factory(input, expected): r = Resource.factory(input) assert r.__class__ == expected def test_resource_factory_invalid(): with pytest.raises(AssertionError): r = Resource.factory({}) ## Instruction: Update tests after lots of work on Resources ## Code After: import pytest from .util import load_test_data from .util import discovery_cache from .mock import HttpMockSequenceEx from googleapiclient.http import HttpMockSequence from micromanager.resources import Resource from micromanager.resources.gcp import GcpBigqueryDataset from micromanager.resources.gcp import GcpComputeInstance from micromanager.resources.gcp import GcpSqlInstance from micromanager.resources.gcp import GcpStorageBucket from micromanager.resources.gcp import GcpStorageBucketIamPolicy test_cases = [ ( {'resource_type': 'bigquery.datasets', 'resource_name': '', 'project_id': ''}, GcpBigqueryDataset, 'gcp.bigquery.datasets' ), ( {'resource_type': 'compute.instances', 'resource_name': '', 'project_id': ''}, GcpComputeInstance, 'gcp.compute.instances' ), ( {'resource_type': 'sqladmin.instances', 'resource_name': '', 'project_id': ''}, GcpSqlInstance, 'gcp.sqladmin.instances' ), ( {'resource_type': 'storage.buckets', 'resource_name': '', 'project_id': ''}, GcpStorageBucket, 'gcp.storage.buckets' ), ( {'resource_type': 'storage.buckets.iam', 'resource_name': '', 'project_id': ''}, GcpStorageBucketIamPolicy, 'gcp.storage.buckets.iam' ) ] @pytest.mark.parametrize( "input,cls,rtype", test_cases, ids=[cls.__name__ for (_, cls, _) in test_cases]) def test_gcp_resource_factory(input, cls, rtype): r = Resource.factory("gcp", input) assert r.__class__ == cls assert r.type() == rtype def test_gcp_resource_factory_invalid(): with pytest.raises(AssertionError): r = Resource.factory('gcp', {})
// ... existing code ... import pytest from .util import load_test_data from .util import discovery_cache from .mock import HttpMockSequenceEx from googleapiclient.http import HttpMockSequence from micromanager.resources import Resource from micromanager.resources.gcp import GcpBigqueryDataset from micromanager.resources.gcp import GcpComputeInstance from micromanager.resources.gcp import GcpSqlInstance from micromanager.resources.gcp import GcpStorageBucket from micromanager.resources.gcp import GcpStorageBucketIamPolicy test_cases = [ ( {'resource_type': 'bigquery.datasets', 'resource_name': '', 'project_id': ''}, GcpBigqueryDataset, 'gcp.bigquery.datasets' ), ( {'resource_type': 'compute.instances', 'resource_name': '', 'project_id': ''}, GcpComputeInstance, 'gcp.compute.instances' ), ( {'resource_type': 'sqladmin.instances', 'resource_name': '', 'project_id': ''}, GcpSqlInstance, 'gcp.sqladmin.instances' ), ( {'resource_type': 'storage.buckets', 'resource_name': '', 'project_id': ''}, GcpStorageBucket, 'gcp.storage.buckets' ), ( {'resource_type': 'storage.buckets.iam', 'resource_name': '', 'project_id': ''}, GcpStorageBucketIamPolicy, 'gcp.storage.buckets.iam' ) ] @pytest.mark.parametrize( "input,cls,rtype", test_cases, ids=[cls.__name__ for (_, cls, _) in test_cases]) def test_gcp_resource_factory(input, cls, rtype): r = Resource.factory("gcp", input) assert r.__class__ == cls assert r.type() == rtype def test_gcp_resource_factory_invalid(): with pytest.raises(AssertionError): r = Resource.factory('gcp', {}) // ... rest of the code ...
003b18c0872f6441d5cdef3c2e0917f29513cdbe
app/src/main/java/br/ufu/renova/scraper/MockHttpClient.java
app/src/main/java/br/ufu/renova/scraper/MockHttpClient.java
package br.ufu.renova.scraper; import java.io.IOException; import java.util.*; /** * Created by yassin on 10/19/16. */ public class MockHttpClient implements IHttpClient { @Override public List<Book> getBooks() { Calendar tomorrow = Calendar.getInstance(); tomorrow.add(Calendar.DAY_OF_MONTH, 1); Book b1 = new Book(); b1.setTitle("Effective Java"); b1.setAuthors("Joshua Bloch"); b1.setBarcode("123456789"); b1.setExpiration(tomorrow.getTime()); Book b2 = new Book(); b2.setTitle("Machine Learning"); b2.setAuthors("Tom M. Mitchell"); b2.setBarcode("987654321"); b2.setExpiration(tomorrow.getTime()); Book[] books = {b1, b2}; return Arrays.asList(books); } @Override public void renew(Book b) throws RenewDateException, BookReservedException, IOException { Calendar nextWeek = Calendar.getInstance(); nextWeek.setTime(b.getExpiration()); nextWeek.add(Calendar.DAY_OF_MONTH, 7); b.setExpiration(nextWeek.getTime()); b.setState(Book.State.RENEWED); } }
package br.ufu.renova.scraper; import java.io.IOException; import java.util.*; /** * Created by yassin on 10/19/16. */ public class MockHttpClient implements IHttpClient { private Book[] books; public MockHttpClient() { Calendar tomorrow = Calendar.getInstance(); tomorrow.add(Calendar.DAY_OF_MONTH, 1); Book b1 = new Book(); b1.setTitle("Effective Java"); b1.setAuthors("Joshua Bloch"); b1.setBarcode("123456789"); b1.setExpiration(tomorrow.getTime()); Book b2 = new Book(); b2.setTitle("Machine Learning"); b2.setAuthors("Tom M. Mitchell"); b2.setBarcode("987654321"); b2.setExpiration(tomorrow.getTime()); books = new Book[]{b1, b2}; } @Override public List<Book> getBooks() { return Arrays.asList(books); } @Override public void renew(Book b) throws RenewDateException, BookReservedException, IOException { Calendar nextWeek = Calendar.getInstance(); nextWeek.setTime(b.getExpiration()); nextWeek.add(Calendar.DAY_OF_MONTH, 7); b.setExpiration(nextWeek.getTime()); b.setState(Book.State.RENEWED); try { Thread.sleep(1000l); } catch (InterruptedException e) { e.printStackTrace(); } } }
Fix bug ao criar novas instâncias no getBooks. Adicionando sleep para se poder ver as animações.
Fix bug ao criar novas instâncias no getBooks. Adicionando sleep para se poder ver as animações.
Java
apache-2.0
ynurmahomed/renova
java
## Code Before: package br.ufu.renova.scraper; import java.io.IOException; import java.util.*; /** * Created by yassin on 10/19/16. */ public class MockHttpClient implements IHttpClient { @Override public List<Book> getBooks() { Calendar tomorrow = Calendar.getInstance(); tomorrow.add(Calendar.DAY_OF_MONTH, 1); Book b1 = new Book(); b1.setTitle("Effective Java"); b1.setAuthors("Joshua Bloch"); b1.setBarcode("123456789"); b1.setExpiration(tomorrow.getTime()); Book b2 = new Book(); b2.setTitle("Machine Learning"); b2.setAuthors("Tom M. Mitchell"); b2.setBarcode("987654321"); b2.setExpiration(tomorrow.getTime()); Book[] books = {b1, b2}; return Arrays.asList(books); } @Override public void renew(Book b) throws RenewDateException, BookReservedException, IOException { Calendar nextWeek = Calendar.getInstance(); nextWeek.setTime(b.getExpiration()); nextWeek.add(Calendar.DAY_OF_MONTH, 7); b.setExpiration(nextWeek.getTime()); b.setState(Book.State.RENEWED); } } ## Instruction: Fix bug ao criar novas instâncias no getBooks. Adicionando sleep para se poder ver as animações. ## Code After: package br.ufu.renova.scraper; import java.io.IOException; import java.util.*; /** * Created by yassin on 10/19/16. */ public class MockHttpClient implements IHttpClient { private Book[] books; public MockHttpClient() { Calendar tomorrow = Calendar.getInstance(); tomorrow.add(Calendar.DAY_OF_MONTH, 1); Book b1 = new Book(); b1.setTitle("Effective Java"); b1.setAuthors("Joshua Bloch"); b1.setBarcode("123456789"); b1.setExpiration(tomorrow.getTime()); Book b2 = new Book(); b2.setTitle("Machine Learning"); b2.setAuthors("Tom M. Mitchell"); b2.setBarcode("987654321"); b2.setExpiration(tomorrow.getTime()); books = new Book[]{b1, b2}; } @Override public List<Book> getBooks() { return Arrays.asList(books); } @Override public void renew(Book b) throws RenewDateException, BookReservedException, IOException { Calendar nextWeek = Calendar.getInstance(); nextWeek.setTime(b.getExpiration()); nextWeek.add(Calendar.DAY_OF_MONTH, 7); b.setExpiration(nextWeek.getTime()); b.setState(Book.State.RENEWED); try { Thread.sleep(1000l); } catch (InterruptedException e) { e.printStackTrace(); } } }
// ... existing code ... */ public class MockHttpClient implements IHttpClient { private Book[] books; public MockHttpClient() { Calendar tomorrow = Calendar.getInstance(); tomorrow.add(Calendar.DAY_OF_MONTH, 1); // ... modified code ... b2.setBarcode("987654321"); b2.setExpiration(tomorrow.getTime()); books = new Book[]{b1, b2}; } @Override public List<Book> getBooks() { return Arrays.asList(books); } ... nextWeek.add(Calendar.DAY_OF_MONTH, 7); b.setExpiration(nextWeek.getTime()); b.setState(Book.State.RENEWED); try { Thread.sleep(1000l); } catch (InterruptedException e) { e.printStackTrace(); } } } // ... rest of the code ...
053b0ea3e6f209b611a9d64a38e2c7df2a03dd42
testsuites/org.eclipse.birt.report.tests.engine/src/org/eclipse/birt/report/tests/engine/AllTests.java
testsuites/org.eclipse.birt.report.tests.engine/src/org/eclipse/birt/report/tests/engine/AllTests.java
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. All rights reserved. This program and * the accompanying materials are made available under the terms of the Eclipse * Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: Actuate Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.birt.report.tests.engine; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.birt.report.tests.engine.api.AllApiTests; import org.eclipse.birt.report.tests.engine.regression.AllRegressionTests; import org.eclipse.birt.report.tests.engine.smoke.AllSmokeTests; public class AllTests { public static Test suite( ) { TestSuite test = new TestSuite( ); test.addTest( AllRegressionTests.suite( ) ); // test.addTest( AllCompatibilityTests.suite( ) ); test.addTest( AllSmokeTests.suite( ) ); test.addTest( AllApiTests.suite( ) ); return test; } }
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. All rights reserved. This program and * the accompanying materials are made available under the terms of the Eclipse * Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: Actuate Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.birt.report.tests.engine; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.birt.report.tests.engine.api.AllApiTests; public class AllTests { public static Test suite( ) { TestSuite test = new TestSuite( ); // test.addTest( AllRegressionTests.suite( ) ); // test.addTest( AllCompatibilityTests.suite( ) ); // test.addTest( AllSmokeTests.suite( ) ); test.addTest( AllApiTests.suite( ) ); return test; } }
Remove regression, smoke and compatibility package. They have been moved to new test framework except for compatibility which is useless.
Remove regression, smoke and compatibility package. They have been moved to new test framework except for compatibility which is useless.
Java
epl-1.0
Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,rrimmana/birt-1,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1
java
## Code Before: /******************************************************************************* * Copyright (c) 2004 Actuate Corporation. All rights reserved. This program and * the accompanying materials are made available under the terms of the Eclipse * Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: Actuate Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.birt.report.tests.engine; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.birt.report.tests.engine.api.AllApiTests; import org.eclipse.birt.report.tests.engine.regression.AllRegressionTests; import org.eclipse.birt.report.tests.engine.smoke.AllSmokeTests; public class AllTests { public static Test suite( ) { TestSuite test = new TestSuite( ); test.addTest( AllRegressionTests.suite( ) ); // test.addTest( AllCompatibilityTests.suite( ) ); test.addTest( AllSmokeTests.suite( ) ); test.addTest( AllApiTests.suite( ) ); return test; } } ## Instruction: Remove regression, smoke and compatibility package. They have been moved to new test framework except for compatibility which is useless. ## Code After: /******************************************************************************* * Copyright (c) 2004 Actuate Corporation. All rights reserved. This program and * the accompanying materials are made available under the terms of the Eclipse * Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: Actuate Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.birt.report.tests.engine; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.birt.report.tests.engine.api.AllApiTests; public class AllTests { public static Test suite( ) { TestSuite test = new TestSuite( ); // test.addTest( AllRegressionTests.suite( ) ); // test.addTest( AllCompatibilityTests.suite( ) ); // test.addTest( AllSmokeTests.suite( ) ); test.addTest( AllApiTests.suite( ) ); return test; } }
... import junit.framework.TestSuite; import org.eclipse.birt.report.tests.engine.api.AllApiTests; public class AllTests { ... public static Test suite( ) { TestSuite test = new TestSuite( ); // test.addTest( AllRegressionTests.suite( ) ); // test.addTest( AllCompatibilityTests.suite( ) ); // test.addTest( AllSmokeTests.suite( ) ); test.addTest( AllApiTests.suite( ) ); return test; } ...
fbded0e311084692052ebd0479d487f13f9e04e3
tinylog-impl/src/test/java/org/tinylog/impl/format/ClassPlaceholderTest.java
tinylog-impl/src/test/java/org/tinylog/impl/format/ClassPlaceholderTest.java
package org.tinylog.impl.format; import org.junit.jupiter.api.Test; import org.tinylog.impl.LogEntry; import org.tinylog.impl.test.LogEntryBuilder; import org.tinylog.impl.test.PlaceholderRenderer; import static org.assertj.core.api.Assertions.assertThat; class ClassPlaceholderTest { /** * Verifies that the source class name of a log entry will be output, if set. */ @Test void renderWithClassName() { PlaceholderRenderer renderer = new PlaceholderRenderer(new ClassPlaceholder()); LogEntry logEntry = new LogEntryBuilder().className("foo.MyClass").create(); assertThat(renderer.render(logEntry)).isEqualTo("foo.MyClass"); } /** * Verifies that "&lt;unknown&gt;" will be output, if the class name is not set. */ @Test void renderWithoutClassName() { PlaceholderRenderer renderer = new PlaceholderRenderer(new ClassPlaceholder()); LogEntry logEntry = new LogEntryBuilder().create(); assertThat(renderer.render(logEntry)).isEqualTo("<unknown>"); } }
package org.tinylog.impl.format; import org.junit.jupiter.api.Test; import org.tinylog.impl.LogEntry; import org.tinylog.impl.test.LogEntryBuilder; import org.tinylog.impl.test.PlaceholderRenderer; import static org.assertj.core.api.Assertions.assertThat; class ClassPlaceholderTest { /** * Verifies that the source class name of a log entry will be output, if set. */ @Test void renderWithClassName() { PlaceholderRenderer renderer = new PlaceholderRenderer(new ClassPlaceholder()); LogEntry logEntry = new LogEntryBuilder().className("foo.MyClass").create(); assertThat(renderer.render(logEntry)).isEqualTo("foo.MyClass"); } /** * Verifies that {@code <unknown>} will be output, if the class name is not set. */ @Test void renderWithoutClassName() { PlaceholderRenderer renderer = new PlaceholderRenderer(new ClassPlaceholder()); LogEntry logEntry = new LogEntryBuilder().create(); assertThat(renderer.render(logEntry)).isEqualTo("<unknown>"); } }
Update Javadoc in class placeholder test
Update Javadoc in class placeholder test
Java
apache-2.0
pmwmedia/tinylog,pmwmedia/tinylog
java
## Code Before: package org.tinylog.impl.format; import org.junit.jupiter.api.Test; import org.tinylog.impl.LogEntry; import org.tinylog.impl.test.LogEntryBuilder; import org.tinylog.impl.test.PlaceholderRenderer; import static org.assertj.core.api.Assertions.assertThat; class ClassPlaceholderTest { /** * Verifies that the source class name of a log entry will be output, if set. */ @Test void renderWithClassName() { PlaceholderRenderer renderer = new PlaceholderRenderer(new ClassPlaceholder()); LogEntry logEntry = new LogEntryBuilder().className("foo.MyClass").create(); assertThat(renderer.render(logEntry)).isEqualTo("foo.MyClass"); } /** * Verifies that "&lt;unknown&gt;" will be output, if the class name is not set. */ @Test void renderWithoutClassName() { PlaceholderRenderer renderer = new PlaceholderRenderer(new ClassPlaceholder()); LogEntry logEntry = new LogEntryBuilder().create(); assertThat(renderer.render(logEntry)).isEqualTo("<unknown>"); } } ## Instruction: Update Javadoc in class placeholder test ## Code After: package org.tinylog.impl.format; import org.junit.jupiter.api.Test; import org.tinylog.impl.LogEntry; import org.tinylog.impl.test.LogEntryBuilder; import org.tinylog.impl.test.PlaceholderRenderer; import static org.assertj.core.api.Assertions.assertThat; class ClassPlaceholderTest { /** * Verifies that the source class name of a log entry will be output, if set. */ @Test void renderWithClassName() { PlaceholderRenderer renderer = new PlaceholderRenderer(new ClassPlaceholder()); LogEntry logEntry = new LogEntryBuilder().className("foo.MyClass").create(); assertThat(renderer.render(logEntry)).isEqualTo("foo.MyClass"); } /** * Verifies that {@code <unknown>} will be output, if the class name is not set. */ @Test void renderWithoutClassName() { PlaceholderRenderer renderer = new PlaceholderRenderer(new ClassPlaceholder()); LogEntry logEntry = new LogEntryBuilder().create(); assertThat(renderer.render(logEntry)).isEqualTo("<unknown>"); } }
... } /** * Verifies that {@code <unknown>} will be output, if the class name is not set. */ @Test void renderWithoutClassName() { ...
44db9de83aad25a1302ac4c31450a525c0095583
binobj/__init__.py
binobj/__init__.py
__version_info__ = (0, 1, 0) __version__ = '.'.join(str(v) for v in __version_info__)
# pylint: disable=wildcard-import,unused-import from .errors import * from .fields import * from .serialization import * from .structures import * __version_info__ = (0, 1, 0) __version__ = '.'.join(str(v) for v in __version_info__)
Add wildcard imports at root.
Add wildcard imports at root.
Python
bsd-3-clause
dargueta/binobj
python
## Code Before: __version_info__ = (0, 1, 0) __version__ = '.'.join(str(v) for v in __version_info__) ## Instruction: Add wildcard imports at root. ## Code After: # pylint: disable=wildcard-import,unused-import from .errors import * from .fields import * from .serialization import * from .structures import * __version_info__ = (0, 1, 0) __version__ = '.'.join(str(v) for v in __version_info__)
# ... existing code ... # pylint: disable=wildcard-import,unused-import from .errors import * from .fields import * from .serialization import * from .structures import * __version_info__ = (0, 1, 0) __version__ = '.'.join(str(v) for v in __version_info__) # ... rest of the code ...
1a74d34d358940175c9e5ac50a11ac3f0f40729b
app/sense.py
app/sense.py
import threading import time class SensorThread(object): def __init__(self, notify, delay=0): self.notify = notify self.delay = delay self.interval = 0.2 self.color = -1 def start(self, control, robot): self.control = control self.robot = robot thread = threading.Thread(target=self.run, args=()) thread.daemon = True # Daemonize thread thread.start() # Start the execution def run(self): while True: color = int(self.robot.color()) touch = self.robot.touch() direction = self.robot.direction() self.control.readings(color, touch, direction) time.sleep(self.interval) def sensors(self, color, touch, direction): #print "sense: %s %s" % (touch, direction) if not self.color == color: self.notify.emit('sense', color) self.color = color print "color %s%%" % color
import threading import time class SensorThread(object): def __init__(self, notify, delay=0): self.notify = notify self.delay = delay self.interval = 0.2 self.color = -1 def start(self, control, robot): self.control = control self.robot = robot thread = threading.Thread(target=self.run, args=()) thread.daemon = True # Daemonize thread thread.start() # Start the execution def run(self): while True: color = int(self.robot.color()) touch = self.robot.touch() try: direction = self.robot.direction() except: direction = 0 self.control.readings(color, touch, direction) time.sleep(self.interval) def sensors(self, color, touch, direction): #print "sense: %s %s" % (touch, direction) if not self.color == color: self.notify.emit('sense', color) self.color = color print "color %s%%" % color
Work without the Gyro sensor for retail set compatibility.
Work without the Gyro sensor for retail set compatibility.
Python
bsd-2-clause
legorovers/legoflask,legorovers/legoflask,legorovers/legoflask
python
## Code Before: import threading import time class SensorThread(object): def __init__(self, notify, delay=0): self.notify = notify self.delay = delay self.interval = 0.2 self.color = -1 def start(self, control, robot): self.control = control self.robot = robot thread = threading.Thread(target=self.run, args=()) thread.daemon = True # Daemonize thread thread.start() # Start the execution def run(self): while True: color = int(self.robot.color()) touch = self.robot.touch() direction = self.robot.direction() self.control.readings(color, touch, direction) time.sleep(self.interval) def sensors(self, color, touch, direction): #print "sense: %s %s" % (touch, direction) if not self.color == color: self.notify.emit('sense', color) self.color = color print "color %s%%" % color ## Instruction: Work without the Gyro sensor for retail set compatibility. ## Code After: import threading import time class SensorThread(object): def __init__(self, notify, delay=0): self.notify = notify self.delay = delay self.interval = 0.2 self.color = -1 def start(self, control, robot): self.control = control self.robot = robot thread = threading.Thread(target=self.run, args=()) thread.daemon = True # Daemonize thread thread.start() # Start the execution def run(self): while True: color = int(self.robot.color()) touch = self.robot.touch() try: direction = self.robot.direction() except: direction = 0 self.control.readings(color, touch, direction) time.sleep(self.interval) def sensors(self, color, touch, direction): #print "sense: %s %s" % (touch, direction) if not self.color == color: self.notify.emit('sense', color) self.color = color print "color %s%%" % color
# ... existing code ... while True: color = int(self.robot.color()) touch = self.robot.touch() try: direction = self.robot.direction() except: direction = 0 self.control.readings(color, touch, direction) time.sleep(self.interval) # ... rest of the code ...
bcca20cecbc664422f72359ba4fba7d55e833b32
swampdragon/connections/sockjs_connection.py
swampdragon/connections/sockjs_connection.py
from sockjs.tornado import SockJSConnection from ..pubsub_providers.redis_pubsub_provider import RedisPubSubProvider from .. import route_handler import json pub_sub = RedisPubSubProvider() class ConnectionMixin(object): def to_json(self, data): if isinstance(data, dict): return data try: data = json.loads(data.replace("'", '"')) return data except: return json.dumps({'message': data}) def to_string(self, data): if isinstance(data, dict): return json.dumps(data).replace("'", '"') return data class SubscriberConnection(ConnectionMixin, SockJSConnection): def __init__(self, session): super(SubscriberConnection, self).__init__(session) def on_open(self, request): self.pub_sub = pub_sub def on_close(self): self.pub_sub.close(self) def on_message(self, data): try: data = self.to_json(data) handler = route_handler.get_route_handler(data['route']) handler(self).handle(data) except Exception as e: self.abort_connection() raise e def abort_connection(self): self.close() def send(self, message, binary=False): super(SubscriberConnection, self).send(message, binary) def broadcast(self, clients, message): super(SubscriberConnection, self).broadcast(clients, message) class DjangoSubscriberConnection(SubscriberConnection): def __init__(self, session): super(DjangoSubscriberConnection, self).__init__(session)
from sockjs.tornado import SockJSConnection from ..pubsub_providers.redis_pubsub_provider import RedisPubSubProvider from .. import route_handler import json pub_sub = RedisPubSubProvider() class ConnectionMixin(object): def to_json(self, data): if isinstance(data, dict): return data try: data = json.loads(data.replace("'", '"')) return data except: return json.dumps({'message': data}) def to_string(self, data): if isinstance(data, dict): return json.dumps(data).replace("'", '"') return data class SubscriberConnection(ConnectionMixin, SockJSConnection): channels = [] def __init__(self, session): super(SubscriberConnection, self).__init__(session) def on_open(self, request): self.pub_sub = pub_sub def on_close(self): self.pub_sub.close(self) def on_message(self, data): try: data = self.to_json(data) handler = route_handler.get_route_handler(data['route']) handler(self).handle(data) except Exception as e: self.abort_connection() raise e def abort_connection(self): self.close() def send(self, message, binary=False): super(SubscriberConnection, self).send(message, binary) def broadcast(self, clients, message): super(SubscriberConnection, self).broadcast(clients, message) class DjangoSubscriberConnection(SubscriberConnection): def __init__(self, session): super(DjangoSubscriberConnection, self).__init__(session)
Include channel list in connection
Include channel list in connection
Python
bsd-3-clause
sahlinet/swampdragon,denizs/swampdragon,michael-k/swampdragon,seclinch/swampdragon,Manuel4131/swampdragon,aexeagmbh/swampdragon,Manuel4131/swampdragon,d9pouces/swampdragon,aexeagmbh/swampdragon,michael-k/swampdragon,d9pouces/swampdragon,boris-savic/swampdragon,boris-savic/swampdragon,jonashagstedt/swampdragon,jonashagstedt/swampdragon,faulkner/swampdragon,faulkner/swampdragon,aexeagmbh/swampdragon,Manuel4131/swampdragon,michael-k/swampdragon,d9pouces/swampdragon,denizs/swampdragon,sahlinet/swampdragon,bastianh/swampdragon,h-hirokawa/swampdragon,bastianh/swampdragon,seclinch/swampdragon,faulkner/swampdragon,bastianh/swampdragon,h-hirokawa/swampdragon,sahlinet/swampdragon,seclinch/swampdragon,jonashagstedt/swampdragon,denizs/swampdragon,boris-savic/swampdragon
python
## Code Before: from sockjs.tornado import SockJSConnection from ..pubsub_providers.redis_pubsub_provider import RedisPubSubProvider from .. import route_handler import json pub_sub = RedisPubSubProvider() class ConnectionMixin(object): def to_json(self, data): if isinstance(data, dict): return data try: data = json.loads(data.replace("'", '"')) return data except: return json.dumps({'message': data}) def to_string(self, data): if isinstance(data, dict): return json.dumps(data).replace("'", '"') return data class SubscriberConnection(ConnectionMixin, SockJSConnection): def __init__(self, session): super(SubscriberConnection, self).__init__(session) def on_open(self, request): self.pub_sub = pub_sub def on_close(self): self.pub_sub.close(self) def on_message(self, data): try: data = self.to_json(data) handler = route_handler.get_route_handler(data['route']) handler(self).handle(data) except Exception as e: self.abort_connection() raise e def abort_connection(self): self.close() def send(self, message, binary=False): super(SubscriberConnection, self).send(message, binary) def broadcast(self, clients, message): super(SubscriberConnection, self).broadcast(clients, message) class DjangoSubscriberConnection(SubscriberConnection): def __init__(self, session): super(DjangoSubscriberConnection, self).__init__(session) ## Instruction: Include channel list in connection ## Code After: from sockjs.tornado import SockJSConnection from ..pubsub_providers.redis_pubsub_provider import RedisPubSubProvider from .. import route_handler import json pub_sub = RedisPubSubProvider() class ConnectionMixin(object): def to_json(self, data): if isinstance(data, dict): return data try: data = json.loads(data.replace("'", '"')) return data except: return json.dumps({'message': data}) def to_string(self, data): if isinstance(data, dict): return json.dumps(data).replace("'", '"') return data class SubscriberConnection(ConnectionMixin, SockJSConnection): channels = [] def __init__(self, session): super(SubscriberConnection, self).__init__(session) def on_open(self, request): self.pub_sub = pub_sub def on_close(self): self.pub_sub.close(self) def on_message(self, data): try: data = self.to_json(data) handler = route_handler.get_route_handler(data['route']) handler(self).handle(data) except Exception as e: self.abort_connection() raise e def abort_connection(self): self.close() def send(self, message, binary=False): super(SubscriberConnection, self).send(message, binary) def broadcast(self, clients, message): super(SubscriberConnection, self).broadcast(clients, message) class DjangoSubscriberConnection(SubscriberConnection): def __init__(self, session): super(DjangoSubscriberConnection, self).__init__(session)
// ... existing code ... class SubscriberConnection(ConnectionMixin, SockJSConnection): channels = [] def __init__(self, session): super(SubscriberConnection, self).__init__(session) // ... rest of the code ...
acab1af0e9bebeea011de1be472f298ddedd862b
src/pretix/control/views/global_settings.py
src/pretix/control/views/global_settings.py
from django.shortcuts import reverse from django.views.generic import FormView from pretix.control.forms.global_settings import GlobalSettingsForm from pretix.control.permissions import AdministratorPermissionRequiredMixin class GlobalSettingsView(AdministratorPermissionRequiredMixin, FormView): template_name = 'pretixcontrol/global_settings.html' form_class = GlobalSettingsForm def form_valid(self, form): form.save() return super().form_valid(form) def get_success_url(self): return reverse('control:global-settings')
from django.contrib import messages from django.shortcuts import reverse from django.utils.translation import ugettext_lazy as _ from django.views.generic import FormView from pretix.control.forms.global_settings import GlobalSettingsForm from pretix.control.permissions import AdministratorPermissionRequiredMixin class GlobalSettingsView(AdministratorPermissionRequiredMixin, FormView): template_name = 'pretixcontrol/global_settings.html' form_class = GlobalSettingsForm def form_valid(self, form): form.save() messages.success(self.request, _('Your changes have been saved.')) return super().form_valid(form) def form_invalid(self, form): messages.error(self.request, _('Your changes have not been saved, see below for errors.')) return super().form_invalid(form) def get_success_url(self): return reverse('control:global-settings')
Add feedback to global settings
Add feedback to global settings
Python
apache-2.0
Flamacue/pretix,Flamacue/pretix,Flamacue/pretix,Flamacue/pretix
python
## Code Before: from django.shortcuts import reverse from django.views.generic import FormView from pretix.control.forms.global_settings import GlobalSettingsForm from pretix.control.permissions import AdministratorPermissionRequiredMixin class GlobalSettingsView(AdministratorPermissionRequiredMixin, FormView): template_name = 'pretixcontrol/global_settings.html' form_class = GlobalSettingsForm def form_valid(self, form): form.save() return super().form_valid(form) def get_success_url(self): return reverse('control:global-settings') ## Instruction: Add feedback to global settings ## Code After: from django.contrib import messages from django.shortcuts import reverse from django.utils.translation import ugettext_lazy as _ from django.views.generic import FormView from pretix.control.forms.global_settings import GlobalSettingsForm from pretix.control.permissions import AdministratorPermissionRequiredMixin class GlobalSettingsView(AdministratorPermissionRequiredMixin, FormView): template_name = 'pretixcontrol/global_settings.html' form_class = GlobalSettingsForm def form_valid(self, form): form.save() messages.success(self.request, _('Your changes have been saved.')) return super().form_valid(form) def form_invalid(self, form): messages.error(self.request, _('Your changes have not been saved, see below for errors.')) return super().form_invalid(form) def get_success_url(self): return reverse('control:global-settings')
# ... existing code ... from django.contrib import messages from django.shortcuts import reverse from django.utils.translation import ugettext_lazy as _ from django.views.generic import FormView from pretix.control.forms.global_settings import GlobalSettingsForm # ... modified code ... def form_valid(self, form): form.save() messages.success(self.request, _('Your changes have been saved.')) return super().form_valid(form) def form_invalid(self, form): messages.error(self.request, _('Your changes have not been saved, see below for errors.')) return super().form_invalid(form) def get_success_url(self): return reverse('control:global-settings') # ... rest of the code ...
07ee6957d20a1c02b22ed5d91d20211506e7ca54
partner_feeds/templatetags/partner_feed_tags.py
partner_feeds/templatetags/partner_feed_tags.py
from django import template from partner_feeds.models import Partner register = template.Library() @register.assignment_tag def get_partners(*args): partners = [] for name in args: try: partner = Partner.objects.get(name=name) except Partner.DoesNotExist: continue partner.posts = partner.post_set.all().order_by('-date') partners.append(partner) return partners
from django import template from partner_feeds.models import Partner, Post register = template.Library() @register.assignment_tag def get_partners(*partner_names): """ Given a list of partner names, return those partners with posts attached to them in the order that they were passed to this function """ partners = list(Partner.objects.filter(name__in=partner_names)) for partner in partners: partner.posts = Post.objects.filter(partner=partner) partners.sort(key=lambda p: partner_names.index(p.name)) return partners
Update `get_partners` assignment tag to reduce the number of queries
Update `get_partners` assignment tag to reduce the number of queries Maintains the same interface so no other changes should be required
Python
bsd-2-clause
theatlantic/django-partner-feeds
python
## Code Before: from django import template from partner_feeds.models import Partner register = template.Library() @register.assignment_tag def get_partners(*args): partners = [] for name in args: try: partner = Partner.objects.get(name=name) except Partner.DoesNotExist: continue partner.posts = partner.post_set.all().order_by('-date') partners.append(partner) return partners ## Instruction: Update `get_partners` assignment tag to reduce the number of queries Maintains the same interface so no other changes should be required ## Code After: from django import template from partner_feeds.models import Partner, Post register = template.Library() @register.assignment_tag def get_partners(*partner_names): """ Given a list of partner names, return those partners with posts attached to them in the order that they were passed to this function """ partners = list(Partner.objects.filter(name__in=partner_names)) for partner in partners: partner.posts = Post.objects.filter(partner=partner) partners.sort(key=lambda p: partner_names.index(p.name)) return partners
... from django import template from partner_feeds.models import Partner, Post register = template.Library() @register.assignment_tag def get_partners(*partner_names): """ Given a list of partner names, return those partners with posts attached to them in the order that they were passed to this function """ partners = list(Partner.objects.filter(name__in=partner_names)) for partner in partners: partner.posts = Post.objects.filter(partner=partner) partners.sort(key=lambda p: partner_names.index(p.name)) return partners ...
f2d91d2c296e3662a1b656f0fdf5191665ff363b
skimage/transform/__init__.py
skimage/transform/__init__.py
from .hough_transform import * from .radon_transform import * from .finite_radon_transform import * from .integral import * from ._geometric import (warp, warp_coords, estimate_transform, SimilarityTransform, AffineTransform, ProjectiveTransform, PolynomialTransform, PiecewiseAffineTransform) from ._warps import swirl, homography, resize, rotate, rescale from .pyramids import (pyramid_reduce, pyramid_expand, pyramid_gaussian, pyramid_laplacian)
from .hough_transform import * from .radon_transform import * from .finite_radon_transform import * from .integral import * from ._geometric import (warp, warp_coords, estimate_transform, SimilarityTransform, AffineTransform, ProjectiveTransform, PolynomialTransform, PiecewiseAffineTransform) from ._warps import swirl, resize, rotate, rescale from .pyramids import (pyramid_reduce, pyramid_expand, pyramid_gaussian, pyramid_laplacian)
Remove deprecated import of hompgraphy
Remove deprecated import of hompgraphy
Python
bsd-3-clause
youprofit/scikit-image,almarklein/scikit-image,keflavich/scikit-image,pratapvardhan/scikit-image,vighneshbirodkar/scikit-image,almarklein/scikit-image,almarklein/scikit-image,chriscrosscutler/scikit-image,ajaybhat/scikit-image,SamHames/scikit-image,oew1v07/scikit-image,vighneshbirodkar/scikit-image,youprofit/scikit-image,SamHames/scikit-image,robintw/scikit-image,emon10005/scikit-image,emon10005/scikit-image,ClinicalGraphics/scikit-image,Midafi/scikit-image,warmspringwinds/scikit-image,vighneshbirodkar/scikit-image,ofgulban/scikit-image,michaelaye/scikit-image,ofgulban/scikit-image,Britefury/scikit-image,michaelaye/scikit-image,blink1073/scikit-image,paalge/scikit-image,Britefury/scikit-image,keflavich/scikit-image,rjeli/scikit-image,newville/scikit-image,bennlich/scikit-image,SamHames/scikit-image,ajaybhat/scikit-image,michaelpacer/scikit-image,chintak/scikit-image,jwiggins/scikit-image,warmspringwinds/scikit-image,chintak/scikit-image,oew1v07/scikit-image,ClinicalGraphics/scikit-image,dpshelio/scikit-image,SamHames/scikit-image,juliusbierk/scikit-image,Midafi/scikit-image,GaZ3ll3/scikit-image,ofgulban/scikit-image,paalge/scikit-image,chintak/scikit-image,robintw/scikit-image,bsipocz/scikit-image,bsipocz/scikit-image,rjeli/scikit-image,bennlich/scikit-image,juliusbierk/scikit-image,chriscrosscutler/scikit-image,jwiggins/scikit-image,michaelpacer/scikit-image,WarrenWeckesser/scikits-image,Hiyorimi/scikit-image,almarklein/scikit-image,pratapvardhan/scikit-image,Hiyorimi/scikit-image,WarrenWeckesser/scikits-image,chintak/scikit-image,dpshelio/scikit-image,rjeli/scikit-image,newville/scikit-image,GaZ3ll3/scikit-image,paalge/scikit-image,blink1073/scikit-image
python
## Code Before: from .hough_transform import * from .radon_transform import * from .finite_radon_transform import * from .integral import * from ._geometric import (warp, warp_coords, estimate_transform, SimilarityTransform, AffineTransform, ProjectiveTransform, PolynomialTransform, PiecewiseAffineTransform) from ._warps import swirl, homography, resize, rotate, rescale from .pyramids import (pyramid_reduce, pyramid_expand, pyramid_gaussian, pyramid_laplacian) ## Instruction: Remove deprecated import of hompgraphy ## Code After: from .hough_transform import * from .radon_transform import * from .finite_radon_transform import * from .integral import * from ._geometric import (warp, warp_coords, estimate_transform, SimilarityTransform, AffineTransform, ProjectiveTransform, PolynomialTransform, PiecewiseAffineTransform) from ._warps import swirl, resize, rotate, rescale from .pyramids import (pyramid_reduce, pyramid_expand, pyramid_gaussian, pyramid_laplacian)
// ... existing code ... SimilarityTransform, AffineTransform, ProjectiveTransform, PolynomialTransform, PiecewiseAffineTransform) from ._warps import swirl, resize, rotate, rescale from .pyramids import (pyramid_reduce, pyramid_expand, pyramid_gaussian, pyramid_laplacian) // ... rest of the code ...
e91dc26cc983f98de1efb09cbf687c70ca0f557d
transitions/extensions/locking.py
transitions/extensions/locking.py
from ..core import Machine, Transition, Event from threading import RLock import inspect class LockedMethod: def __init__(self, lock, func): self.lock = lock self.func = func def __call__(self, *args, **kwargs): with self.lock: return self.func(*args, **kwargs) class LockedEvent(Event): def trigger(self, model, *args, **kwargs): with self.machine.rlock: return super(LockedEvent, self).trigger(model, *args, **kwargs) class LockedMachine(Machine): def __init__(self, *args, **kwargs): self.rlock = RLock() super(LockedMachine, self).__init__(*args, **kwargs) def __getattribute__(self, item): f = super(LockedMachine, self).__getattribute__ tmp = f(item) if inspect.ismethod(tmp) and item not in "__getattribute__": return LockedMethod(f('rlock'), tmp) return tmp def __getattr__(self, item): try: return super(LockedMachine, self).__getattribute__(item) except AttributeError: return super(LockedMachine, self).__getattr__(item) @staticmethod def _create_event(*args, **kwargs): return LockedEvent(*args, **kwargs)
from ..core import Machine, Transition, Event, listify from threading import RLock import inspect try: from contextlib import nested # Python 2 except ImportError: from contextlib import ExitStack, contextmanager @contextmanager def nested(*contexts): """ Reimplementation of nested in python 3. """ with ExitStack() as stack: for ctx in contexts: stack.enter_context(ctx) yield contexts class LockedMethod: def __init__(self, context, func): self.context = context self.func = func def __call__(self, *args, **kwargs): with nested(*self.context): return self.func(*args, **kwargs) class LockedEvent(Event): def trigger(self, model, *args, **kwargs): with nested(*self.machine.context): return super(LockedEvent, self).trigger(model, *args, **kwargs) class LockedMachine(Machine): def __init__(self, *args, **kwargs): try: self.context = listify(kwargs.pop('context')) except KeyError: self.context = [RLock()] super(LockedMachine, self).__init__(*args, **kwargs) def __getattribute__(self, item): f = super(LockedMachine, self).__getattribute__ tmp = f(item) if inspect.ismethod(tmp) and item not in "__getattribute__": return LockedMethod(f('context'), tmp) return tmp def __getattr__(self, item): try: return super(LockedMachine, self).__getattribute__(item) except AttributeError: return super(LockedMachine, self).__getattr__(item) @staticmethod def _create_event(*args, **kwargs): return LockedEvent(*args, **kwargs)
Allow injecting a lock, or arbitrary context managers into LockedMachine
Allow injecting a lock, or arbitrary context managers into LockedMachine
Python
mit
pytransitions/transitions,tyarkoni/transitions,pytransitions/transitions
python
## Code Before: from ..core import Machine, Transition, Event from threading import RLock import inspect class LockedMethod: def __init__(self, lock, func): self.lock = lock self.func = func def __call__(self, *args, **kwargs): with self.lock: return self.func(*args, **kwargs) class LockedEvent(Event): def trigger(self, model, *args, **kwargs): with self.machine.rlock: return super(LockedEvent, self).trigger(model, *args, **kwargs) class LockedMachine(Machine): def __init__(self, *args, **kwargs): self.rlock = RLock() super(LockedMachine, self).__init__(*args, **kwargs) def __getattribute__(self, item): f = super(LockedMachine, self).__getattribute__ tmp = f(item) if inspect.ismethod(tmp) and item not in "__getattribute__": return LockedMethod(f('rlock'), tmp) return tmp def __getattr__(self, item): try: return super(LockedMachine, self).__getattribute__(item) except AttributeError: return super(LockedMachine, self).__getattr__(item) @staticmethod def _create_event(*args, **kwargs): return LockedEvent(*args, **kwargs) ## Instruction: Allow injecting a lock, or arbitrary context managers into LockedMachine ## Code After: from ..core import Machine, Transition, Event, listify from threading import RLock import inspect try: from contextlib import nested # Python 2 except ImportError: from contextlib import ExitStack, contextmanager @contextmanager def nested(*contexts): """ Reimplementation of nested in python 3. """ with ExitStack() as stack: for ctx in contexts: stack.enter_context(ctx) yield contexts class LockedMethod: def __init__(self, context, func): self.context = context self.func = func def __call__(self, *args, **kwargs): with nested(*self.context): return self.func(*args, **kwargs) class LockedEvent(Event): def trigger(self, model, *args, **kwargs): with nested(*self.machine.context): return super(LockedEvent, self).trigger(model, *args, **kwargs) class LockedMachine(Machine): def __init__(self, *args, **kwargs): try: self.context = listify(kwargs.pop('context')) except KeyError: self.context = [RLock()] super(LockedMachine, self).__init__(*args, **kwargs) def __getattribute__(self, item): f = super(LockedMachine, self).__getattribute__ tmp = f(item) if inspect.ismethod(tmp) and item not in "__getattribute__": return LockedMethod(f('context'), tmp) return tmp def __getattr__(self, item): try: return super(LockedMachine, self).__getattribute__(item) except AttributeError: return super(LockedMachine, self).__getattr__(item) @staticmethod def _create_event(*args, **kwargs): return LockedEvent(*args, **kwargs)
... from ..core import Machine, Transition, Event, listify from threading import RLock import inspect try: from contextlib import nested # Python 2 except ImportError: from contextlib import ExitStack, contextmanager @contextmanager def nested(*contexts): """ Reimplementation of nested in python 3. """ with ExitStack() as stack: for ctx in contexts: stack.enter_context(ctx) yield contexts class LockedMethod: def __init__(self, context, func): self.context = context self.func = func def __call__(self, *args, **kwargs): with nested(*self.context): return self.func(*args, **kwargs) ... class LockedEvent(Event): def trigger(self, model, *args, **kwargs): with nested(*self.machine.context): return super(LockedEvent, self).trigger(model, *args, **kwargs) ... class LockedMachine(Machine): def __init__(self, *args, **kwargs): try: self.context = listify(kwargs.pop('context')) except KeyError: self.context = [RLock()] super(LockedMachine, self).__init__(*args, **kwargs) def __getattribute__(self, item): ... f = super(LockedMachine, self).__getattribute__ tmp = f(item) if inspect.ismethod(tmp) and item not in "__getattribute__": return LockedMethod(f('context'), tmp) return tmp def __getattr__(self, item): ...
b4073cd21954c632884b284967bbe1fd781cc109
app/templates/src/main/java/package/service/_AuditEventService.java
app/templates/src/main/java/package/service/_AuditEventService.java
package <%=packageName%>.service; import <%=packageName%>.config.audit.AuditEventConverter; import <%=packageName%>.domain.PersistentAuditEvent; import <%=packageName%>.repository.PersistenceAuditEventRepository; import org.joda.time.LocalDateTime; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.inject.Inject; import java.util.List; /** * Service for managing audit event. * <p/> * <p> * This is the default implementation to support SpringBoot Actuator AuditEventRepository * </p> */ @Service @Transactional public class AuditEventService { @Inject private PersistenceAuditEventRepository persistenceAuditEventRepository; @Inject private AuditEventConverter auditEventConverter; public List<AuditEvent> findAll() { return auditEventConverter.convertToAuditEvent(persistenceAuditEventRepository.findAll()); } public List<AuditEvent> findBetweenDates(LocalDateTime fromDate, LocalDateTime toDate) { final List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findByAuditEventDateBetween(fromDate, toDate); return auditEventConverter.convertToAuditEvent(persistentAuditEvents); } }
package <%=packageName%>.service; import <%=packageName%>.config.audit.AuditEventConverter; import <%=packageName%>.domain.PersistentAuditEvent; import <%=packageName%>.repository.PersistenceAuditEventRepository; import org.joda.time.LocalDateTime; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.inject.Inject; import java.util.List; /** * Service for managing audit event. * <p/> * <p> * This is the default implementation to support SpringBoot Actuator AuditEventRepository * </p> */ @Service @Transactional public class AuditEventService { @Inject private PersistenceAuditEventRepository persistenceAuditEventRepository; @Inject private AuditEventConverter auditEventConverter; public List<AuditEvent> findAll() { return auditEventConverter.convertToAuditEvent(persistenceAuditEventRepository.findAll()); } public List<AuditEvent> findBetweenDates(LocalDateTime fromDate, LocalDateTime toDate) { final List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findByDates(fromDate, toDate); return auditEventConverter.convertToAuditEvent(persistentAuditEvents); } }
Call the new findByDates method
Call the new findByDates method
Java
apache-2.0
lrkwz/generator-jhipster,rkohel/generator-jhipster,atomfrede/generator-jhipster,siliconharborlabs/generator-jhipster,cbornet/generator-jhipster,nkolosnjaji/generator-jhipster,dalbelap/generator-jhipster,Tcharl/generator-jhipster,siliconharborlabs/generator-jhipster,xetys/generator-jhipster,rkohel/generator-jhipster,siliconharborlabs/generator-jhipster,sendilkumarn/generator-jhipster,atomfrede/generator-jhipster,dalbelap/generator-jhipster,eosimosu/generator-jhipster,ctamisier/generator-jhipster,deepu105/generator-jhipster,yongli82/generator-jhipster,pascalgrimaud/generator-jhipster,duderoot/generator-jhipster,ziogiugno/generator-jhipster,pascalgrimaud/generator-jhipster,gzsombor/generator-jhipster,hdurix/generator-jhipster,baskeboler/generator-jhipster,gzsombor/generator-jhipster,wmarques/generator-jhipster,sendilkumarn/generator-jhipster,hdurix/generator-jhipster,deepu105/generator-jhipster,wmarques/generator-jhipster,ruddell/generator-jhipster,sendilkumarn/generator-jhipster,wmarques/generator-jhipster,cbornet/generator-jhipster,robertmilowski/generator-jhipster,erikkemperman/generator-jhipster,vivekmore/generator-jhipster,maniacneron/generator-jhipster,lrkwz/generator-jhipster,nkolosnjaji/generator-jhipster,baskeboler/generator-jhipster,maniacneron/generator-jhipster,eosimosu/generator-jhipster,ziogiugno/generator-jhipster,PierreBesson/generator-jhipster,stevehouel/generator-jhipster,sendilkumarn/generator-jhipster,deepu105/generator-jhipster,liseri/generator-jhipster,ruddell/generator-jhipster,pascalgrimaud/generator-jhipster,gzsombor/generator-jhipster,rkohel/generator-jhipster,cbornet/generator-jhipster,liseri/generator-jhipster,sohibegit/generator-jhipster,cbornet/generator-jhipster,ramzimaalej/generator-jhipster,gzsombor/generator-jhipster,ruddell/generator-jhipster,dalbelap/generator-jhipster,baskeboler/generator-jhipster,baskeboler/generator-jhipster,danielpetisme/generator-jhipster,jkutner/generator-jhipster,pascalgrimaud/generator-jhipster,robertmilowski/generator-jhipster,siliconharborlabs/generator-jhipster,ctamisier/generator-jhipster,dimeros/generator-jhipster,PierreBesson/generator-jhipster,ruddell/generator-jhipster,duderoot/generator-jhipster,stevehouel/generator-jhipster,danielpetisme/generator-jhipster,mraible/generator-jhipster,mosoft521/generator-jhipster,mosoft521/generator-jhipster,lrkwz/generator-jhipster,liseri/generator-jhipster,Tcharl/generator-jhipster,gmarziou/generator-jhipster,maniacneron/generator-jhipster,sendilkumarn/generator-jhipster,hdurix/generator-jhipster,nkolosnjaji/generator-jhipster,eosimosu/generator-jhipster,stevehouel/generator-jhipster,danielpetisme/generator-jhipster,vivekmore/generator-jhipster,robertmilowski/generator-jhipster,robertmilowski/generator-jhipster,JulienMrgrd/generator-jhipster,eosimosu/generator-jhipster,mraible/generator-jhipster,liseri/generator-jhipster,dimeros/generator-jhipster,nkolosnjaji/generator-jhipster,ziogiugno/generator-jhipster,jkutner/generator-jhipster,sohibegit/generator-jhipster,atomfrede/generator-jhipster,ctamisier/generator-jhipster,PierreBesson/generator-jhipster,jhipster/generator-jhipster,duderoot/generator-jhipster,mosoft521/generator-jhipster,mraible/generator-jhipster,hdurix/generator-jhipster,PierreBesson/generator-jhipster,wmarques/generator-jhipster,rifatdover/generator-jhipster,xetys/generator-jhipster,gmarziou/generator-jhipster,dimeros/generator-jhipster,jhipster/generator-jhipster,deepu105/generator-jhipster,dimeros/generator-jhipster,robertmilowski/generator-jhipster,jkutner/generator-jhipster,gzsombor/generator-jhipster,rkohel/generator-jhipster,jkutner/generator-jhipster,duderoot/generator-jhipster,ramzimaalej/generator-jhipster,JulienMrgrd/generator-jhipster,lrkwz/generator-jhipster,ziogiugno/generator-jhipster,JulienMrgrd/generator-jhipster,dalbelap/generator-jhipster,ctamisier/generator-jhipster,eosimosu/generator-jhipster,erikkemperman/generator-jhipster,ruddell/generator-jhipster,jkutner/generator-jhipster,mraible/generator-jhipster,erikkemperman/generator-jhipster,yongli82/generator-jhipster,rifatdover/generator-jhipster,mraible/generator-jhipster,liseri/generator-jhipster,gmarziou/generator-jhipster,PierreBesson/generator-jhipster,xetys/generator-jhipster,stevehouel/generator-jhipster,dynamicguy/generator-jhipster,ramzimaalej/generator-jhipster,baskeboler/generator-jhipster,ziogiugno/generator-jhipster,dimeros/generator-jhipster,maniacneron/generator-jhipster,erikkemperman/generator-jhipster,deepu105/generator-jhipster,jhipster/generator-jhipster,pascalgrimaud/generator-jhipster,lrkwz/generator-jhipster,gmarziou/generator-jhipster,xetys/generator-jhipster,cbornet/generator-jhipster,atomfrede/generator-jhipster,siliconharborlabs/generator-jhipster,rifatdover/generator-jhipster,dynamicguy/generator-jhipster,jhipster/generator-jhipster,stevehouel/generator-jhipster,sohibegit/generator-jhipster,sohibegit/generator-jhipster,hdurix/generator-jhipster,vivekmore/generator-jhipster,erikkemperman/generator-jhipster,Tcharl/generator-jhipster,rkohel/generator-jhipster,wmarques/generator-jhipster,yongli82/generator-jhipster,ctamisier/generator-jhipster,danielpetisme/generator-jhipster,nkolosnjaji/generator-jhipster,mosoft521/generator-jhipster,yongli82/generator-jhipster,dalbelap/generator-jhipster,jhipster/generator-jhipster,JulienMrgrd/generator-jhipster,atomfrede/generator-jhipster,Tcharl/generator-jhipster,dynamicguy/generator-jhipster,vivekmore/generator-jhipster,Tcharl/generator-jhipster,dynamicguy/generator-jhipster,gmarziou/generator-jhipster,mosoft521/generator-jhipster,yongli82/generator-jhipster,sohibegit/generator-jhipster,JulienMrgrd/generator-jhipster,duderoot/generator-jhipster,vivekmore/generator-jhipster,danielpetisme/generator-jhipster,maniacneron/generator-jhipster
java
## Code Before: package <%=packageName%>.service; import <%=packageName%>.config.audit.AuditEventConverter; import <%=packageName%>.domain.PersistentAuditEvent; import <%=packageName%>.repository.PersistenceAuditEventRepository; import org.joda.time.LocalDateTime; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.inject.Inject; import java.util.List; /** * Service for managing audit event. * <p/> * <p> * This is the default implementation to support SpringBoot Actuator AuditEventRepository * </p> */ @Service @Transactional public class AuditEventService { @Inject private PersistenceAuditEventRepository persistenceAuditEventRepository; @Inject private AuditEventConverter auditEventConverter; public List<AuditEvent> findAll() { return auditEventConverter.convertToAuditEvent(persistenceAuditEventRepository.findAll()); } public List<AuditEvent> findBetweenDates(LocalDateTime fromDate, LocalDateTime toDate) { final List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findByAuditEventDateBetween(fromDate, toDate); return auditEventConverter.convertToAuditEvent(persistentAuditEvents); } } ## Instruction: Call the new findByDates method ## Code After: package <%=packageName%>.service; import <%=packageName%>.config.audit.AuditEventConverter; import <%=packageName%>.domain.PersistentAuditEvent; import <%=packageName%>.repository.PersistenceAuditEventRepository; import org.joda.time.LocalDateTime; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.inject.Inject; import java.util.List; /** * Service for managing audit event. * <p/> * <p> * This is the default implementation to support SpringBoot Actuator AuditEventRepository * </p> */ @Service @Transactional public class AuditEventService { @Inject private PersistenceAuditEventRepository persistenceAuditEventRepository; @Inject private AuditEventConverter auditEventConverter; public List<AuditEvent> findAll() { return auditEventConverter.convertToAuditEvent(persistenceAuditEventRepository.findAll()); } public List<AuditEvent> findBetweenDates(LocalDateTime fromDate, LocalDateTime toDate) { final List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findByDates(fromDate, toDate); return auditEventConverter.convertToAuditEvent(persistentAuditEvents); } }
// ... existing code ... public List<AuditEvent> findBetweenDates(LocalDateTime fromDate, LocalDateTime toDate) { final List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findByDates(fromDate, toDate); return auditEventConverter.convertToAuditEvent(persistentAuditEvents); } // ... rest of the code ...
60ae97e2060cb01ac159acc6c0c7abdf866019b0
clean_lxd.py
clean_lxd.py
from __future__ import print_function from argparse import ArgumentParser from datetime import ( datetime, timedelta, ) import json import os import subprocess import sys def list_old_juju_containers(hours): env = dict(os.environ) containers = json.loads(subprocess.check_output([ 'lxc', 'list', '--format', 'json'], env=env)) now = datetime.now() for container in containers: name = container['name'] if not name.startswith('juju-'): continue # This produces local time. lxc does not respect TZ=UTC. created_at = datetime.strptime( container['created_at'][:-6], '%Y-%m-%dT%H:%M:%S') age = now - created_at if age <= timedelta(hours=hours): continue yield name, age def main(): parser = ArgumentParser('Delete old juju containers') parser.add_argument('--dry-run', action='store_true', help='Do not actually delete.') parser.add_argument('--hours', type=int, default=1, help='Number of hours a juju container may exist.') args = parser.parse_args() for container, age in list_old_juju_containers(args.hours): print('deleting {} ({} old)'.format(container, age)) if args.dry_run: continue subprocess.check_call(('lxc', 'delete', '--verbose', '--force', container)) if __name__ == '__main__': sys.exit(main())
from __future__ import print_function from argparse import ArgumentParser from datetime import ( datetime, timedelta, ) import json import os import subprocess import sys from dateutil import ( parser as date_parser, tz, ) def list_old_juju_containers(hours): env = dict(os.environ) containers = json.loads(subprocess.check_output([ 'lxc', 'list', '--format', 'json'], env=env)) now = datetime.now(tz.gettz('UTC')) for container in containers: name = container['name'] if not name.startswith('juju-'): continue created_at = date_parser.parse(container['created_at']) age = now - created_at if age <= timedelta(hours=hours): continue yield name, age def main(): parser = ArgumentParser('Delete old juju containers') parser.add_argument('--dry-run', action='store_true', help='Do not actually delete.') parser.add_argument('--hours', type=int, default=1, help='Number of hours a juju container may exist.') args = parser.parse_args() for container, age in list_old_juju_containers(args.hours): print('deleting {} ({} old)'.format(container, age)) if args.dry_run: continue subprocess.check_call(('lxc', 'delete', '--verbose', '--force', container)) if __name__ == '__main__': sys.exit(main())
Use dateutil to calculate age of container.
Use dateutil to calculate age of container.
Python
agpl-3.0
mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju
python
## Code Before: from __future__ import print_function from argparse import ArgumentParser from datetime import ( datetime, timedelta, ) import json import os import subprocess import sys def list_old_juju_containers(hours): env = dict(os.environ) containers = json.loads(subprocess.check_output([ 'lxc', 'list', '--format', 'json'], env=env)) now = datetime.now() for container in containers: name = container['name'] if not name.startswith('juju-'): continue # This produces local time. lxc does not respect TZ=UTC. created_at = datetime.strptime( container['created_at'][:-6], '%Y-%m-%dT%H:%M:%S') age = now - created_at if age <= timedelta(hours=hours): continue yield name, age def main(): parser = ArgumentParser('Delete old juju containers') parser.add_argument('--dry-run', action='store_true', help='Do not actually delete.') parser.add_argument('--hours', type=int, default=1, help='Number of hours a juju container may exist.') args = parser.parse_args() for container, age in list_old_juju_containers(args.hours): print('deleting {} ({} old)'.format(container, age)) if args.dry_run: continue subprocess.check_call(('lxc', 'delete', '--verbose', '--force', container)) if __name__ == '__main__': sys.exit(main()) ## Instruction: Use dateutil to calculate age of container. ## Code After: from __future__ import print_function from argparse import ArgumentParser from datetime import ( datetime, timedelta, ) import json import os import subprocess import sys from dateutil import ( parser as date_parser, tz, ) def list_old_juju_containers(hours): env = dict(os.environ) containers = json.loads(subprocess.check_output([ 'lxc', 'list', '--format', 'json'], env=env)) now = datetime.now(tz.gettz('UTC')) for container in containers: name = container['name'] if not name.startswith('juju-'): continue created_at = date_parser.parse(container['created_at']) age = now - created_at if age <= timedelta(hours=hours): continue yield name, age def main(): parser = ArgumentParser('Delete old juju containers') parser.add_argument('--dry-run', action='store_true', help='Do not actually delete.') parser.add_argument('--hours', type=int, default=1, help='Number of hours a juju container may exist.') args = parser.parse_args() for container, age in list_old_juju_containers(args.hours): print('deleting {} ({} old)'.format(container, age)) if args.dry_run: continue subprocess.check_call(('lxc', 'delete', '--verbose', '--force', container)) if __name__ == '__main__': sys.exit(main())
... import subprocess import sys from dateutil import ( parser as date_parser, tz, ) def list_old_juju_containers(hours): env = dict(os.environ) containers = json.loads(subprocess.check_output([ 'lxc', 'list', '--format', 'json'], env=env)) now = datetime.now(tz.gettz('UTC')) for container in containers: name = container['name'] if not name.startswith('juju-'): continue created_at = date_parser.parse(container['created_at']) age = now - created_at if age <= timedelta(hours=hours): continue ...
7c6a128b707db738d0a89c2897b35ed7d783ade0
plugins/basic_info_plugin.py
plugins/basic_info_plugin.py
import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): name = 'BasicInfoPlugin' short_description = 'Basic info:' default = True description = textwrap.dedent(''' This plugin provides some basic info about the string such as: - Length - Presence of alpha/digits/raw bytes ''') def handle(self): result = '' for s in self.args['STRING']: if len(self.args['STRING']) > 1: result += '{0}:\n'.format(s) table = VeryPrettyTable() table.field_names = ['Length', '# Digits', '# Alpha', '# unprintable'] table.add_row((len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), sum(x in string.printable for x in s))) result += str(table) + '\n' return result
import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): name = 'BasicInfoPlugin' short_description = 'Basic info:' default = True description = textwrap.dedent(''' This plugin provides some basic info about the string such as: - Length - Presence of alpha/digits/raw bytes ''') def handle(self): result = '' for s in self.args['STRING']: if len(self.args['STRING']) > 1: result += '{0}:\n'.format(s) table = VeryPrettyTable() table.field_names = ['Length', '# Digits', '# Alpha', '# Punct.', '# Control'] table.add_row((len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), sum(x in string.punctuation for x in s), sum(x not in string.printable for x in s))) result += str(table) + '\n' return result
Add punctuation to basic info
Add punctuation to basic info
Python
mit
Sakartu/stringinfo
python
## Code Before: import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): name = 'BasicInfoPlugin' short_description = 'Basic info:' default = True description = textwrap.dedent(''' This plugin provides some basic info about the string such as: - Length - Presence of alpha/digits/raw bytes ''') def handle(self): result = '' for s in self.args['STRING']: if len(self.args['STRING']) > 1: result += '{0}:\n'.format(s) table = VeryPrettyTable() table.field_names = ['Length', '# Digits', '# Alpha', '# unprintable'] table.add_row((len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), sum(x in string.printable for x in s))) result += str(table) + '\n' return result ## Instruction: Add punctuation to basic info ## Code After: import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): name = 'BasicInfoPlugin' short_description = 'Basic info:' default = True description = textwrap.dedent(''' This plugin provides some basic info about the string such as: - Length - Presence of alpha/digits/raw bytes ''') def handle(self): result = '' for s in self.args['STRING']: if len(self.args['STRING']) > 1: result += '{0}:\n'.format(s) table = VeryPrettyTable() table.field_names = ['Length', '# Digits', '# Alpha', '# Punct.', '# Control'] table.add_row((len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), sum(x in string.punctuation for x in s), sum(x not in string.printable for x in s))) result += str(table) + '\n' return result
// ... existing code ... if len(self.args['STRING']) > 1: result += '{0}:\n'.format(s) table = VeryPrettyTable() table.field_names = ['Length', '# Digits', '# Alpha', '# Punct.', '# Control'] table.add_row((len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), sum(x in string.punctuation for x in s), sum(x not in string.printable for x in s))) result += str(table) + '\n' return result // ... rest of the code ...
b4b905333f8847be730f30fbc53ac7a172195cdc
src/sentry/api/endpoints/group_events.py
src/sentry/api/endpoints/group_events.py
from __future__ import absolute_import from sentry.api.base import DocSection from sentry.api.bases import GroupEndpoint from sentry.api.serializers import serialize from sentry.api.paginator import DateTimePaginator from sentry.models import Event, Group from sentry.utils.apidocs import scenario, attach_scenarios @scenario('ListAvailableSamples') def list_available_samples_scenario(runner): group = Group.objects.filter(project=runner.default_project).first() runner.request( method='GET', path='/issues/%s/events/' % group.id ) class GroupEventsEndpoint(GroupEndpoint): doc_section = DocSection.EVENTS @attach_scenarios([list_available_samples_scenario]) def get(self, request, group): """ List an Issue's Events `````````````````````` This endpoint lists an issue's events. :pparam string issue_id: the ID of the issue to retrieve. :auth: required """ events = Event.objects.filter( group=group ) return self.paginate( request=request, queryset=events, order_by='-datetime', on_results=lambda x: serialize(x, request.user), paginator_cls=DateTimePaginator, )
from __future__ import absolute_import from sentry.api.base import DocSection from sentry.api.bases import GroupEndpoint from sentry.api.serializers import serialize from sentry.api.paginator import DateTimePaginator from sentry.models import Event, Group from sentry.utils.apidocs import scenario, attach_scenarios @scenario('ListAvailableSamples') def list_available_samples_scenario(runner): group = Group.objects.filter(project=runner.default_project).first() runner.request( method='GET', path='/issues/%s/events/' % group.id ) class GroupEventsEndpoint(GroupEndpoint): doc_section = DocSection.EVENTS @attach_scenarios([list_available_samples_scenario]) def get(self, request, group): """ List an Issue's Events `````````````````````` This endpoint lists an issue's events. :pparam string issue_id: the ID of the issue to retrieve. :auth: required """ events = Event.objects.filter( group=group ) query = request.GET.get('query') if query: events = events.filter( message__iexact=query, ) return self.paginate( request=request, queryset=events, order_by='-datetime', on_results=lambda x: serialize(x, request.user), paginator_cls=DateTimePaginator, )
Add query param to event list
Add query param to event list
Python
bsd-3-clause
looker/sentry,BuildingLink/sentry,mvaled/sentry,fotinakis/sentry,zenefits/sentry,BuildingLink/sentry,gencer/sentry,gencer/sentry,JamesMura/sentry,zenefits/sentry,alexm92/sentry,ifduyue/sentry,BuildingLink/sentry,JamesMura/sentry,JackDanger/sentry,gencer/sentry,fotinakis/sentry,nicholasserra/sentry,JackDanger/sentry,mvaled/sentry,jean/sentry,mvaled/sentry,beeftornado/sentry,beeftornado/sentry,ifduyue/sentry,nicholasserra/sentry,jean/sentry,daevaorn/sentry,ifduyue/sentry,fotinakis/sentry,mitsuhiko/sentry,zenefits/sentry,looker/sentry,ifduyue/sentry,jean/sentry,alexm92/sentry,looker/sentry,BuildingLink/sentry,jean/sentry,alexm92/sentry,daevaorn/sentry,mitsuhiko/sentry,JamesMura/sentry,daevaorn/sentry,gencer/sentry,nicholasserra/sentry,daevaorn/sentry,ifduyue/sentry,looker/sentry,zenefits/sentry,JackDanger/sentry,mvaled/sentry,looker/sentry,JamesMura/sentry,mvaled/sentry,fotinakis/sentry,beeftornado/sentry,BuildingLink/sentry,gencer/sentry,jean/sentry,mvaled/sentry,JamesMura/sentry,zenefits/sentry
python
## Code Before: from __future__ import absolute_import from sentry.api.base import DocSection from sentry.api.bases import GroupEndpoint from sentry.api.serializers import serialize from sentry.api.paginator import DateTimePaginator from sentry.models import Event, Group from sentry.utils.apidocs import scenario, attach_scenarios @scenario('ListAvailableSamples') def list_available_samples_scenario(runner): group = Group.objects.filter(project=runner.default_project).first() runner.request( method='GET', path='/issues/%s/events/' % group.id ) class GroupEventsEndpoint(GroupEndpoint): doc_section = DocSection.EVENTS @attach_scenarios([list_available_samples_scenario]) def get(self, request, group): """ List an Issue's Events `````````````````````` This endpoint lists an issue's events. :pparam string issue_id: the ID of the issue to retrieve. :auth: required """ events = Event.objects.filter( group=group ) return self.paginate( request=request, queryset=events, order_by='-datetime', on_results=lambda x: serialize(x, request.user), paginator_cls=DateTimePaginator, ) ## Instruction: Add query param to event list ## Code After: from __future__ import absolute_import from sentry.api.base import DocSection from sentry.api.bases import GroupEndpoint from sentry.api.serializers import serialize from sentry.api.paginator import DateTimePaginator from sentry.models import Event, Group from sentry.utils.apidocs import scenario, attach_scenarios @scenario('ListAvailableSamples') def list_available_samples_scenario(runner): group = Group.objects.filter(project=runner.default_project).first() runner.request( method='GET', path='/issues/%s/events/' % group.id ) class GroupEventsEndpoint(GroupEndpoint): doc_section = DocSection.EVENTS @attach_scenarios([list_available_samples_scenario]) def get(self, request, group): """ List an Issue's Events `````````````````````` This endpoint lists an issue's events. :pparam string issue_id: the ID of the issue to retrieve. :auth: required """ events = Event.objects.filter( group=group ) query = request.GET.get('query') if query: events = events.filter( message__iexact=query, ) return self.paginate( request=request, queryset=events, order_by='-datetime', on_results=lambda x: serialize(x, request.user), paginator_cls=DateTimePaginator, )
... group=group ) query = request.GET.get('query') if query: events = events.filter( message__iexact=query, ) return self.paginate( request=request, queryset=events, ...
030a786db1c0602125bfe4093c6a5709b0202858
app/hooks/views.py
app/hooks/views.py
from __future__ import absolute_import from __future__ import unicode_literals from app import app, webhooks @webhooks.hook(app.config.get('GITLAB_HOOK'), handler='gitlab') class Gitlab: def issue(self, data): pass def push(self, data): pass def tag_push(self, data): pass def merge_request(self, data): pass def commit_comment(self, data): pass def issue_comment(self, data): pass def merge_request_comment(self, data): pass def snippet_comment(self, data): pass
from __future__ import absolute_import from __future__ import unicode_literals from app import app, webhooks @webhooks.hook( app.config.get('GITLAB_HOOK','/hooks/gitlab'), handler='gitlab') class Gitlab: def issue(self, data): pass def push(self, data): pass def tag_push(self, data): pass def merge_request(self, data): pass def commit_comment(self, data): pass def issue_comment(self, data): pass def merge_request_comment(self, data): pass def snippet_comment(self, data): pass
Add default hook url for gitlab
Add default hook url for gitlab
Python
apache-2.0
pipex/gitbot,pipex/gitbot,pipex/gitbot
python
## Code Before: from __future__ import absolute_import from __future__ import unicode_literals from app import app, webhooks @webhooks.hook(app.config.get('GITLAB_HOOK'), handler='gitlab') class Gitlab: def issue(self, data): pass def push(self, data): pass def tag_push(self, data): pass def merge_request(self, data): pass def commit_comment(self, data): pass def issue_comment(self, data): pass def merge_request_comment(self, data): pass def snippet_comment(self, data): pass ## Instruction: Add default hook url for gitlab ## Code After: from __future__ import absolute_import from __future__ import unicode_literals from app import app, webhooks @webhooks.hook( app.config.get('GITLAB_HOOK','/hooks/gitlab'), handler='gitlab') class Gitlab: def issue(self, data): pass def push(self, data): pass def tag_push(self, data): pass def merge_request(self, data): pass def commit_comment(self, data): pass def issue_comment(self, data): pass def merge_request_comment(self, data): pass def snippet_comment(self, data): pass
// ... existing code ... from app import app, webhooks @webhooks.hook( app.config.get('GITLAB_HOOK','/hooks/gitlab'), handler='gitlab') class Gitlab: def issue(self, data): pass // ... rest of the code ...
1ee41f5439f80af139e612591d48cdac5ecfda39
hiapi/hi.py
hiapi/hi.py
import argparse from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return 'Hi!\n' def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-b', '--bind-address', dest='bind', default='127.0.0.1') parser.add_argument('-p', '--port', dest='port', default=4000, type=int) return parser.parse_args() def main(): opts = parse_args() app.run(host=opts.bind, port=opts.port) # Support for uWSGI def application(env, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return [b'Hi!\n'] if __name__ == "__main__": main()
import argparse import flask RESPONSE_CODE = 200 app = flask.Flask(__name__) @app.route('/') def hello(): global RESPONSE_CODE if RESPONSE_CODE == 200: return 'Hi!\n' else: flask.abort(RESPONSE_CODE) def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-b', '--bind-address', dest='bind', default='127.0.0.1') parser.add_argument('-p', '--port', dest='port', default=4000, type=int) parser.add_argument('-c', '--response_code', dest='code', default=200, type=int) return parser.parse_args() def main(): global RESPONSE_CODE opts = parse_args() RESPONSE_CODE = opts.code app.run(host=opts.bind, port=opts.port) if __name__ == "__main__": main()
Remove uwsgi support, add support for simple alternative responses
Remove uwsgi support, add support for simple alternative responses
Python
apache-2.0
GradysGhost/pyhiapi
python
## Code Before: import argparse from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return 'Hi!\n' def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-b', '--bind-address', dest='bind', default='127.0.0.1') parser.add_argument('-p', '--port', dest='port', default=4000, type=int) return parser.parse_args() def main(): opts = parse_args() app.run(host=opts.bind, port=opts.port) # Support for uWSGI def application(env, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return [b'Hi!\n'] if __name__ == "__main__": main() ## Instruction: Remove uwsgi support, add support for simple alternative responses ## Code After: import argparse import flask RESPONSE_CODE = 200 app = flask.Flask(__name__) @app.route('/') def hello(): global RESPONSE_CODE if RESPONSE_CODE == 200: return 'Hi!\n' else: flask.abort(RESPONSE_CODE) def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-b', '--bind-address', dest='bind', default='127.0.0.1') parser.add_argument('-p', '--port', dest='port', default=4000, type=int) parser.add_argument('-c', '--response_code', dest='code', default=200, type=int) return parser.parse_args() def main(): global RESPONSE_CODE opts = parse_args() RESPONSE_CODE = opts.code app.run(host=opts.bind, port=opts.port) if __name__ == "__main__": main()
// ... existing code ... import argparse import flask RESPONSE_CODE = 200 app = flask.Flask(__name__) @app.route('/') def hello(): global RESPONSE_CODE if RESPONSE_CODE == 200: return 'Hi!\n' else: flask.abort(RESPONSE_CODE) def parse_args(): parser = argparse.ArgumentParser() // ... modified code ... parser.add_argument('-b', '--bind-address', dest='bind', default='127.0.0.1') parser.add_argument('-p', '--port', dest='port', default=4000, type=int) parser.add_argument('-c', '--response_code', dest='code', default=200, type=int) return parser.parse_args() def main(): global RESPONSE_CODE opts = parse_args() RESPONSE_CODE = opts.code app.run(host=opts.bind, port=opts.port) if __name__ == "__main__": main() // ... rest of the code ...
198b1ef1cc1c23cb15f3cc880b93b9ca2d3fd232
src/shared.c
src/shared.c
int base64_decode (char *src, bytes *dest) { BIO *bio, *b64; unsigned int max_len = strlen(src) * 0.75; dest->data = malloc(max_len); if (dest->data == NULL) return -1; b64 = BIO_new(BIO_f_base64()); bio = BIO_new_mem_buf(src, -1); bio = BIO_push(b64, bio); dest->length = (int)BIO_read(bio, dest->data, max_len); BIO_free_all(bio); return 0; } int base64_encode (char *src, int src_len, char **dest) { return -1; }
int base64_decode (char *src, bytes *dest) { BIO *bio, *b64; unsigned int max_len = strlen(src) * 3 / 4; dest->data = malloc(max_len); if (dest->data == NULL) return -1; FILE* stream = fmemopen(src, strlen(src), "r"); b64 = BIO_new(BIO_f_base64()); bio = BIO_new_fp(stream, BIO_NOCLOSE); bio = BIO_push(b64, bio); BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL); dest->length = BIO_read(bio, dest->data, max_len); BIO_free_all(bio); return 0; } int base64_encode (char *src, int src_len, char **dest) { return -1; }
Fix overflow bug in OpenSSL
Fix overflow bug in OpenSSL
C
bsd-3-clause
undesktop/libopkeychain
c
## Code Before: int base64_decode (char *src, bytes *dest) { BIO *bio, *b64; unsigned int max_len = strlen(src) * 0.75; dest->data = malloc(max_len); if (dest->data == NULL) return -1; b64 = BIO_new(BIO_f_base64()); bio = BIO_new_mem_buf(src, -1); bio = BIO_push(b64, bio); dest->length = (int)BIO_read(bio, dest->data, max_len); BIO_free_all(bio); return 0; } int base64_encode (char *src, int src_len, char **dest) { return -1; } ## Instruction: Fix overflow bug in OpenSSL ## Code After: int base64_decode (char *src, bytes *dest) { BIO *bio, *b64; unsigned int max_len = strlen(src) * 3 / 4; dest->data = malloc(max_len); if (dest->data == NULL) return -1; FILE* stream = fmemopen(src, strlen(src), "r"); b64 = BIO_new(BIO_f_base64()); bio = BIO_new_fp(stream, BIO_NOCLOSE); bio = BIO_push(b64, bio); BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL); dest->length = BIO_read(bio, dest->data, max_len); BIO_free_all(bio); return 0; } int base64_encode (char *src, int src_len, char **dest) { return -1; }
// ... existing code ... (char *src, bytes *dest) { BIO *bio, *b64; unsigned int max_len = strlen(src) * 3 / 4; dest->data = malloc(max_len); if (dest->data == NULL) return -1; FILE* stream = fmemopen(src, strlen(src), "r"); b64 = BIO_new(BIO_f_base64()); bio = BIO_new_fp(stream, BIO_NOCLOSE); bio = BIO_push(b64, bio); BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL); dest->length = BIO_read(bio, dest->data, max_len); BIO_free_all(bio); return 0; // ... rest of the code ...
e1a09de22ee6e7bf40f5e067d4632fdad56effa6
data/src/main/java/com/edreams/android/workshops/kotlin/data/venues/mapper/VenueMapper.kt
data/src/main/java/com/edreams/android/workshops/kotlin/data/venues/mapper/VenueMapper.kt
package com.edreams.android.workshops.kotlin.data.venues.mapper import com.edreams.android.workshops.kotlin.data.venues.cache.entity.VenueEntity import com.edreams.android.workshops.kotlin.data.venues.remote.response.PhotoResponse import com.edreams.android.workshops.kotlin.data.venues.remote.response.VenueResponse import com.edreams.android.workshops.kotlin.domain.mapper.Mapper import javax.inject.Inject class VenueMapper @Inject constructor() : Mapper<VenueResponse, VenueEntity> { override fun map(from: VenueResponse): VenueEntity = with(from) { return VenueEntity(id, name, rating, buildPhotoUrl(photos.groups[0].items[0]), contact.formattedPhone, location.distance, location.formattedAddress.joinToString(","), stats.checkinsCount, tips?.get(0)?.text ) } private fun buildPhotoUrl(photo: PhotoResponse): String = with(photo) { "$prefix${width}x$height$suffix" } }
package com.edreams.android.workshops.kotlin.data.venues.mapper import com.edreams.android.workshops.kotlin.data.venues.cache.entity.VenueEntity import com.edreams.android.workshops.kotlin.data.venues.remote.response.PhotoResponse import com.edreams.android.workshops.kotlin.data.venues.remote.response.VenueResponse import com.edreams.android.workshops.kotlin.domain.mapper.Mapper import javax.inject.Inject class VenueMapper @Inject constructor() : Mapper<VenueResponse, VenueEntity> { override fun map(from: VenueResponse): VenueEntity = with(from) { return VenueEntity(id, name, rating, if (photos.groups.isNotEmpty()) buildPhotoUrl(photos.groups[0].items[0]) else "", contact.formattedPhone, location.distance, location.formattedAddress.joinToString(","), stats.checkinsCount, tips?.get(0)?.text ) } private fun buildPhotoUrl(photo: PhotoResponse): String = with(photo) { "$prefix${width}x$height$suffix" } }
Fix crash with emptu images lists
Fix crash with emptu images lists
Kotlin
apache-2.0
nico-gonzalez/K-Places,nico-gonzalez/K-Places
kotlin
## Code Before: package com.edreams.android.workshops.kotlin.data.venues.mapper import com.edreams.android.workshops.kotlin.data.venues.cache.entity.VenueEntity import com.edreams.android.workshops.kotlin.data.venues.remote.response.PhotoResponse import com.edreams.android.workshops.kotlin.data.venues.remote.response.VenueResponse import com.edreams.android.workshops.kotlin.domain.mapper.Mapper import javax.inject.Inject class VenueMapper @Inject constructor() : Mapper<VenueResponse, VenueEntity> { override fun map(from: VenueResponse): VenueEntity = with(from) { return VenueEntity(id, name, rating, buildPhotoUrl(photos.groups[0].items[0]), contact.formattedPhone, location.distance, location.formattedAddress.joinToString(","), stats.checkinsCount, tips?.get(0)?.text ) } private fun buildPhotoUrl(photo: PhotoResponse): String = with(photo) { "$prefix${width}x$height$suffix" } } ## Instruction: Fix crash with emptu images lists ## Code After: package com.edreams.android.workshops.kotlin.data.venues.mapper import com.edreams.android.workshops.kotlin.data.venues.cache.entity.VenueEntity import com.edreams.android.workshops.kotlin.data.venues.remote.response.PhotoResponse import com.edreams.android.workshops.kotlin.data.venues.remote.response.VenueResponse import com.edreams.android.workshops.kotlin.domain.mapper.Mapper import javax.inject.Inject class VenueMapper @Inject constructor() : Mapper<VenueResponse, VenueEntity> { override fun map(from: VenueResponse): VenueEntity = with(from) { return VenueEntity(id, name, rating, if (photos.groups.isNotEmpty()) buildPhotoUrl(photos.groups[0].items[0]) else "", contact.formattedPhone, location.distance, location.formattedAddress.joinToString(","), stats.checkinsCount, tips?.get(0)?.text ) } private fun buildPhotoUrl(photo: PhotoResponse): String = with(photo) { "$prefix${width}x$height$suffix" } }
... return VenueEntity(id, name, rating, if (photos.groups.isNotEmpty()) buildPhotoUrl(photos.groups[0].items[0]) else "", contact.formattedPhone, location.distance, location.formattedAddress.joinToString(","), ...
5d61b4904057acbe235b74fc1122d09aa365bdeb
edx_data_research/monitor/monitor_tracking.py
edx_data_research/monitor/monitor_tracking.py
import sys import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class TrackingEventHandler(FileSystemEventHandler): def on_created(self, event): pass def on_moved(self, event): pass if __name__ == "__main__": if len(sys.argv) > 1: args = sys.argv[1] else: raise ValueError('Missing path to directory to monitor!!!') event_handler = TrackingEventHandler() observer = Observer() observer.schedule(event_handler, path, recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
import sys import time from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler class TrackingLogHandler(PatternMatchingEventHandler): def on_created(self, event): print event.__repr__() print event.event_type, event.is_directory, event.src_path if __name__ == "__main__": if len(sys.argv) > 1: path = sys.argv[1] else: raise ValueError('Missing path to directory to monitor!!!') event_handler = TrackingLogHandler(['*.log'], ['*.log-errors'], case_sensitive=True) observer = Observer() observer.schedule(event_handler, path, recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
Define handler for tracking log files
Define handler for tracking log files
Python
mit
McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research
python
## Code Before: import sys import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class TrackingEventHandler(FileSystemEventHandler): def on_created(self, event): pass def on_moved(self, event): pass if __name__ == "__main__": if len(sys.argv) > 1: args = sys.argv[1] else: raise ValueError('Missing path to directory to monitor!!!') event_handler = TrackingEventHandler() observer = Observer() observer.schedule(event_handler, path, recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() ## Instruction: Define handler for tracking log files ## Code After: import sys import time from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler class TrackingLogHandler(PatternMatchingEventHandler): def on_created(self, event): print event.__repr__() print event.event_type, event.is_directory, event.src_path if __name__ == "__main__": if len(sys.argv) > 1: path = sys.argv[1] else: raise ValueError('Missing path to directory to monitor!!!') event_handler = TrackingLogHandler(['*.log'], ['*.log-errors'], case_sensitive=True) observer = Observer() observer.schedule(event_handler, path, recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
... import sys import time from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler class TrackingLogHandler(PatternMatchingEventHandler): def on_created(self, event): print event.__repr__() print event.event_type, event.is_directory, event.src_path if __name__ == "__main__": if len(sys.argv) > 1: path = sys.argv[1] else: raise ValueError('Missing path to directory to monitor!!!') event_handler = TrackingLogHandler(['*.log'], ['*.log-errors'], case_sensitive=True) observer = Observer() observer.schedule(event_handler, path, recursive=True) observer.start() ...
1fd2299b2a0c993bd463ab88c0a7544ade2c945b
test_kasp/disk/test_disk.py
test_kasp/disk/test_disk.py
import pytest from utils.disk_utils import DiskIO class TestDisk: def __init__(self): self.WRITE_MB = 128 self.WRITE_BLOCK_KB = 1024 self.READ_BLOCK_B = 512 @staticmethod def all_free_disk_space_gb(): return reduce(lambda res, x: res+x[1], DiskIO().disks, 0) @pytest.mark.disk @pytest.mark.storage def test_disk_space_storage(self): assert self.all_free_disk_space_gb() > 3000
import pytest from utils.disk_utils import DiskIO class TestDisk: @staticmethod def all_free_disk_space_gb(): return reduce(lambda res, x: res+x[1], DiskIO().disks, 0) @pytest.mark.disk @pytest.mark.storage def test_disk_space_storage(self): assert self.all_free_disk_space_gb() > 3000
Remove init mrthod from disk test
Remove init mrthod from disk test Removed init method from test class for disk test
Python
apache-2.0
vrovachev/kaspersky-framework
python
## Code Before: import pytest from utils.disk_utils import DiskIO class TestDisk: def __init__(self): self.WRITE_MB = 128 self.WRITE_BLOCK_KB = 1024 self.READ_BLOCK_B = 512 @staticmethod def all_free_disk_space_gb(): return reduce(lambda res, x: res+x[1], DiskIO().disks, 0) @pytest.mark.disk @pytest.mark.storage def test_disk_space_storage(self): assert self.all_free_disk_space_gb() > 3000 ## Instruction: Remove init mrthod from disk test Removed init method from test class for disk test ## Code After: import pytest from utils.disk_utils import DiskIO class TestDisk: @staticmethod def all_free_disk_space_gb(): return reduce(lambda res, x: res+x[1], DiskIO().disks, 0) @pytest.mark.disk @pytest.mark.storage def test_disk_space_storage(self): assert self.all_free_disk_space_gb() > 3000
# ... existing code ... class TestDisk: @staticmethod def all_free_disk_space_gb(): # ... rest of the code ...
2b8fca2bebd3acc179ac591908256a8173408cec
setup.py
setup.py
from setuptools import setup, find_packages install_requires = [] with open("requirements.txt") as fp: for s in fp: install_requires.append(s.strip()) setup( name="luigi-td", version='0.0.0', description="Luigi integration for Treasure Data", author="Treasure Data, Inc.", author_email="[email protected]", url="http://treasuredata.com/", install_requires=install_requires, packages=find_packages(), license="Apache Software License", platforms="Posix; MacOS X; Windows", classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Topic :: Internet", ], )
from setuptools import setup, find_packages setup( name="luigi-td", version='0.0.0', description="Luigi integration for Treasure Data", author="Treasure Data, Inc.", author_email="[email protected]", url="http://treasuredata.com/", install_requires=open("requirements.txt").read().splitlines(), packages=find_packages(), license="Apache Software License", platforms="Posix; MacOS X; Windows", classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Topic :: Internet", ], )
Simplify the definision of install_requires
Simplify the definision of install_requires
Python
apache-2.0
treasure-data/luigi-td
python
## Code Before: from setuptools import setup, find_packages install_requires = [] with open("requirements.txt") as fp: for s in fp: install_requires.append(s.strip()) setup( name="luigi-td", version='0.0.0', description="Luigi integration for Treasure Data", author="Treasure Data, Inc.", author_email="[email protected]", url="http://treasuredata.com/", install_requires=install_requires, packages=find_packages(), license="Apache Software License", platforms="Posix; MacOS X; Windows", classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Topic :: Internet", ], ) ## Instruction: Simplify the definision of install_requires ## Code After: from setuptools import setup, find_packages setup( name="luigi-td", version='0.0.0', description="Luigi integration for Treasure Data", author="Treasure Data, Inc.", author_email="[email protected]", url="http://treasuredata.com/", install_requires=open("requirements.txt").read().splitlines(), packages=find_packages(), license="Apache Software License", platforms="Posix; MacOS X; Windows", classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Topic :: Internet", ], )
# ... existing code ... from setuptools import setup, find_packages setup( name="luigi-td", # ... modified code ... author="Treasure Data, Inc.", author_email="[email protected]", url="http://treasuredata.com/", install_requires=open("requirements.txt").read().splitlines(), packages=find_packages(), license="Apache Software License", platforms="Posix; MacOS X; Windows", # ... rest of the code ...
a795274811b3df67a04593b1889d9c93fed40737
examples/webhooks.py
examples/webhooks.py
from __future__ import print_function import os import stripe from flask import Flask, request stripe.api_key = os.environ.get('STRIPE_SECRET_KEY') webhook_secret = os.environ.get('WEBHOOK_SECRET') app = Flask(__name__) @app.route('/webhooks', methods=['POST']) def webhooks(): payload = request.data received_sig = request.headers.get('Stripe-Signature', None) try: event = stripe.Webhook.construct_event( payload, received_sig, webhook_secret) except ValueError: print("Error while decoding event!") return 'Bad payload', 400 except stripe.error.SignatureVerificationError: print("Invalid signature!") return 'Bad signature', 400 print("Received event: id={id}, type={type}".format( id=event.id, type=event.type)) return '', 200 if __name__ == '__main__': app.run(port=int(os.environ.get('PORT', 5000)))
from __future__ import print_function import os import stripe from flask import Flask, request stripe.api_key = os.environ.get('STRIPE_SECRET_KEY') webhook_secret = os.environ.get('WEBHOOK_SECRET') app = Flask(__name__) @app.route('/webhooks', methods=['POST']) def webhooks(): payload = request.data.decode('utf-8') received_sig = request.headers.get('Stripe-Signature', None) try: event = stripe.Webhook.construct_event( payload, received_sig, webhook_secret) except ValueError: print("Error while decoding event!") return 'Bad payload', 400 except stripe.error.SignatureVerificationError: print("Invalid signature!") return 'Bad signature', 400 print("Received event: id={id}, type={type}".format( id=event.id, type=event.type)) return '', 200 if __name__ == '__main__': app.run(port=int(os.environ.get('PORT', 5000)))
Fix example for Python 3 compatibility
Fix example for Python 3 compatibility
Python
mit
stripe/stripe-python
python
## Code Before: from __future__ import print_function import os import stripe from flask import Flask, request stripe.api_key = os.environ.get('STRIPE_SECRET_KEY') webhook_secret = os.environ.get('WEBHOOK_SECRET') app = Flask(__name__) @app.route('/webhooks', methods=['POST']) def webhooks(): payload = request.data received_sig = request.headers.get('Stripe-Signature', None) try: event = stripe.Webhook.construct_event( payload, received_sig, webhook_secret) except ValueError: print("Error while decoding event!") return 'Bad payload', 400 except stripe.error.SignatureVerificationError: print("Invalid signature!") return 'Bad signature', 400 print("Received event: id={id}, type={type}".format( id=event.id, type=event.type)) return '', 200 if __name__ == '__main__': app.run(port=int(os.environ.get('PORT', 5000))) ## Instruction: Fix example for Python 3 compatibility ## Code After: from __future__ import print_function import os import stripe from flask import Flask, request stripe.api_key = os.environ.get('STRIPE_SECRET_KEY') webhook_secret = os.environ.get('WEBHOOK_SECRET') app = Flask(__name__) @app.route('/webhooks', methods=['POST']) def webhooks(): payload = request.data.decode('utf-8') received_sig = request.headers.get('Stripe-Signature', None) try: event = stripe.Webhook.construct_event( payload, received_sig, webhook_secret) except ValueError: print("Error while decoding event!") return 'Bad payload', 400 except stripe.error.SignatureVerificationError: print("Invalid signature!") return 'Bad signature', 400 print("Received event: id={id}, type={type}".format( id=event.id, type=event.type)) return '', 200 if __name__ == '__main__': app.run(port=int(os.environ.get('PORT', 5000)))
... @app.route('/webhooks', methods=['POST']) def webhooks(): payload = request.data.decode('utf-8') received_sig = request.headers.get('Stripe-Signature', None) try: ...
fc350215a32586ac2233749924fa61078e8c780a
cosmic_ray/testing/unittest_runner.py
cosmic_ray/testing/unittest_runner.py
from itertools import chain import unittest from .test_runner import TestRunner class UnittestRunner(TestRunner): # pylint:disable=no-init, too-few-public-methods """A TestRunner using `unittest`'s discovery mechanisms. This treats the first element of `test_args` as a directory. This discovers all tests under that directory and executes them. All elements in `test_args` after the first are ignored. """ def _run(self): suite = unittest.TestLoader().discover(self.test_args[0]) result = unittest.TestResult() result.failfast = True suite.run(result) return ( result.wasSuccessful(), [(str(r[0]), r[1]) for r in chain(result.errors, result.failures)])
from itertools import chain import unittest from .test_runner import TestRunner class UnittestRunner(TestRunner): # pylint:disable=no-init, too-few-public-methods """A TestRunner using `unittest`'s discovery mechanisms. This treats the first element of `test_args` as a directory. This discovers all tests under that directory and executes them. All elements in `test_args` after the first are ignored. """ def _run(self): suite = unittest.TestLoader().discover(self.test_args[0]) result = unittest.TestResult() result.failfast = True suite.run(result) return ( result.wasSuccessful(), [r[1] for r in chain(result.errors, result.failures)])
Return a list of strings for unittest results, not list of tuples
Return a list of strings for unittest results, not list of tuples This is needed so the reporter can print a nicely formatted traceback when the job is killed.
Python
mit
sixty-north/cosmic-ray
python
## Code Before: from itertools import chain import unittest from .test_runner import TestRunner class UnittestRunner(TestRunner): # pylint:disable=no-init, too-few-public-methods """A TestRunner using `unittest`'s discovery mechanisms. This treats the first element of `test_args` as a directory. This discovers all tests under that directory and executes them. All elements in `test_args` after the first are ignored. """ def _run(self): suite = unittest.TestLoader().discover(self.test_args[0]) result = unittest.TestResult() result.failfast = True suite.run(result) return ( result.wasSuccessful(), [(str(r[0]), r[1]) for r in chain(result.errors, result.failures)]) ## Instruction: Return a list of strings for unittest results, not list of tuples This is needed so the reporter can print a nicely formatted traceback when the job is killed. ## Code After: from itertools import chain import unittest from .test_runner import TestRunner class UnittestRunner(TestRunner): # pylint:disable=no-init, too-few-public-methods """A TestRunner using `unittest`'s discovery mechanisms. This treats the first element of `test_args` as a directory. This discovers all tests under that directory and executes them. All elements in `test_args` after the first are ignored. """ def _run(self): suite = unittest.TestLoader().discover(self.test_args[0]) result = unittest.TestResult() result.failfast = True suite.run(result) return ( result.wasSuccessful(), [r[1] for r in chain(result.errors, result.failures)])
# ... existing code ... return ( result.wasSuccessful(), [r[1] for r in chain(result.errors, result.failures)]) # ... rest of the code ...
172675716f9766ad8c3d228a297c982dd6dab971
setup.py
setup.py
from setuptools import setup, find_packages PROJECT = 'overalls' VERSION = '0.1' AUTHOR = 'Simon Cross' AUTHOR_EMAIL = '[email protected]' DESC = "Coveralls coverage uploader." setup( name=PROJECT, version=VERSION, description=DESC, long_description=open('README.rst').read(), author=AUTHOR, author_email=AUTHOR_EMAIL, packages=find_packages(), scripts=[ 'scripts/overalls', ], requires=[ 'requests', ], build_requires=[ 'pytest', 'pytest-cov', 'pytest-pep8', 'mock', ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: POSIX', 'Programming Language :: Python', ], )
from setuptools import setup, find_packages PROJECT = 'overalls' VERSION = '0.1' AUTHOR = 'Simon Cross' AUTHOR_EMAIL = '[email protected]' DESC = "Coveralls coverage uploader." setup( name=PROJECT, version=VERSION, description=DESC, long_description=open('README.rst').read(), author=AUTHOR, author_email=AUTHOR_EMAIL, packages=find_packages(), scripts=[ 'scripts/overalls', ], requires=[ 'requests', ], build_requires=[ 'pep8', 'pytest', 'pytest-cov', 'pytest-pep8', 'mock', ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: POSIX', 'Programming Language :: Python', ], )
Add pep8 as a build dependency.
Add pep8 as a build dependency.
Python
bsd-3-clause
hodgestar/overalls
python
## Code Before: from setuptools import setup, find_packages PROJECT = 'overalls' VERSION = '0.1' AUTHOR = 'Simon Cross' AUTHOR_EMAIL = '[email protected]' DESC = "Coveralls coverage uploader." setup( name=PROJECT, version=VERSION, description=DESC, long_description=open('README.rst').read(), author=AUTHOR, author_email=AUTHOR_EMAIL, packages=find_packages(), scripts=[ 'scripts/overalls', ], requires=[ 'requests', ], build_requires=[ 'pytest', 'pytest-cov', 'pytest-pep8', 'mock', ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: POSIX', 'Programming Language :: Python', ], ) ## Instruction: Add pep8 as a build dependency. ## Code After: from setuptools import setup, find_packages PROJECT = 'overalls' VERSION = '0.1' AUTHOR = 'Simon Cross' AUTHOR_EMAIL = '[email protected]' DESC = "Coveralls coverage uploader." setup( name=PROJECT, version=VERSION, description=DESC, long_description=open('README.rst').read(), author=AUTHOR, author_email=AUTHOR_EMAIL, packages=find_packages(), scripts=[ 'scripts/overalls', ], requires=[ 'requests', ], build_requires=[ 'pep8', 'pytest', 'pytest-cov', 'pytest-pep8', 'mock', ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: POSIX', 'Programming Language :: Python', ], )
... 'requests', ], build_requires=[ 'pep8', 'pytest', 'pytest-cov', 'pytest-pep8', ...
73399a7cf86d20a3cda4336cb37f64bcc0508274
masters/master.client.skia/master_site_config.py
masters/master.client.skia/master_site_config.py
"""ActiveMaster definition.""" from config_bootstrap import Master class Skia(Master.Master3): project_name = 'Skia' master_port = 10115 slave_port = 10116 master_port_alt = 10117 repo_url = 'https://skia.googlesource.com/skia.git' production_host = None is_production_host = False buildbot_url = None
"""ActiveMaster definition.""" from config_bootstrap import Master class Skia(Master.Master3): project_name = 'Skia' master_port = 8053 slave_port = 8153 master_port_alt = 8253 repo_url = 'https://skia.googlesource.com/skia.git' production_host = None is_production_host = False buildbot_url = None
Change Skia master ports again
Change Skia master ports again BUG=393690 Review URL: https://codereview.chromium.org/390903004 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@283235 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
python
## Code Before: """ActiveMaster definition.""" from config_bootstrap import Master class Skia(Master.Master3): project_name = 'Skia' master_port = 10115 slave_port = 10116 master_port_alt = 10117 repo_url = 'https://skia.googlesource.com/skia.git' production_host = None is_production_host = False buildbot_url = None ## Instruction: Change Skia master ports again BUG=393690 Review URL: https://codereview.chromium.org/390903004 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@283235 0039d316-1c4b-4281-b951-d872f2087c98 ## Code After: """ActiveMaster definition.""" from config_bootstrap import Master class Skia(Master.Master3): project_name = 'Skia' master_port = 8053 slave_port = 8153 master_port_alt = 8253 repo_url = 'https://skia.googlesource.com/skia.git' production_host = None is_production_host = False buildbot_url = None
# ... existing code ... class Skia(Master.Master3): project_name = 'Skia' master_port = 8053 slave_port = 8153 master_port_alt = 8253 repo_url = 'https://skia.googlesource.com/skia.git' production_host = None is_production_host = False # ... rest of the code ...
abf2f4209f8adf06bef624e9d0a188eba39c2c7a
cinch/lexer.py
cinch/lexer.py
def lex(source): """Lex the source code. Split on spaces, strip newlines, and filter out empty strings""" return filter(lambda s: s != '', map(lambda x: x.strip(), source.split(' ')))
import re # This is the lexer. We could build a state machine which would parse # each token character by character, but the point of this project is to # be as simple as possible, so we will literally just split the string on # spaces, scrub all newlines, and filter out any empty strings def lex(source): """Lex the source code. Split on spaces, strip newlines, and filter out empty strings""" # Strip comments from source code. source = re.sub('#.*$', '', source) return filter(lambda s: s != '', map(lambda x: x.strip(), source.split(' ')))
Remove comments as part of lexing
Remove comments as part of lexing
Python
mit
iankronquist/cinch-lang,tschuy/cinch-lang
python
## Code Before: def lex(source): """Lex the source code. Split on spaces, strip newlines, and filter out empty strings""" return filter(lambda s: s != '', map(lambda x: x.strip(), source.split(' '))) ## Instruction: Remove comments as part of lexing ## Code After: import re # This is the lexer. We could build a state machine which would parse # each token character by character, but the point of this project is to # be as simple as possible, so we will literally just split the string on # spaces, scrub all newlines, and filter out any empty strings def lex(source): """Lex the source code. Split on spaces, strip newlines, and filter out empty strings""" # Strip comments from source code. source = re.sub('#.*$', '', source) return filter(lambda s: s != '', map(lambda x: x.strip(), source.split(' ')))
// ... existing code ... import re # This is the lexer. We could build a state machine which would parse # each token character by character, but the point of this project is to # be as simple as possible, so we will literally just split the string on # spaces, scrub all newlines, and filter out any empty strings def lex(source): """Lex the source code. Split on spaces, strip newlines, and filter out empty strings""" # Strip comments from source code. source = re.sub('#.*$', '', source) return filter(lambda s: s != '', map(lambda x: x.strip(), source.split(' '))) // ... rest of the code ...
83598d24c46683b7d2eb3e99d39cbd5babba5073
tests/api/views/clubs/create_test.py
tests/api/views/clubs/create_test.py
from skylines.model import Club from tests.api import basic_auth def test_create(db_session, client, test_user): headers = basic_auth(test_user.email_address, test_user.original_password) res = client.put('/clubs', headers=headers, json={ 'name': 'LV Aachen', }) assert res.status_code == 200 assert Club.get(res.json['id'])
from skylines.model import Club from tests.api import basic_auth from tests.data import add_fixtures, clubs def test_create(db_session, client, test_user): headers = basic_auth(test_user.email_address, test_user.original_password) res = client.put('/clubs', headers=headers, json={ 'name': 'LV Aachen', }) assert res.status_code == 200 club = Club.get(res.json['id']) assert club assert club.owner_id == test_user.id def test_without_authentication(db_session, client): res = client.put('/clubs', json={ 'name': 'LV Aachen', }) assert res.status_code == 401 assert res.json['error'] == 'invalid_token' def test_non_json_data(db_session, client, test_user): headers = basic_auth(test_user.email_address, test_user.original_password) res = client.put('/clubs', headers=headers, data='foobar?') assert res.status_code == 400 assert res.json['error'] == 'invalid-request' def test_invalid_data(db_session, client, test_user): headers = basic_auth(test_user.email_address, test_user.original_password) res = client.put('/clubs', headers=headers, json={ 'name': '', }) assert res.status_code == 422 assert res.json['error'] == 'validation-failed' def test_existing_club(db_session, client, test_user): lva = clubs.lva() add_fixtures(db_session, lva) headers = basic_auth(test_user.email_address, test_user.original_password) res = client.put('/clubs', headers=headers, json={ 'name': 'LV Aachen', }) assert res.status_code == 422 assert res.json['error'] == 'duplicate-club-name'
Add more "PUT /clubs" tests
tests/api: Add more "PUT /clubs" tests
Python
agpl-3.0
RBE-Avionik/skylines,Harry-R/skylines,shadowoneau/skylines,skylines-project/skylines,Harry-R/skylines,shadowoneau/skylines,Turbo87/skylines,Turbo87/skylines,RBE-Avionik/skylines,Harry-R/skylines,Turbo87/skylines,skylines-project/skylines,skylines-project/skylines,Turbo87/skylines,shadowoneau/skylines,RBE-Avionik/skylines,skylines-project/skylines,Harry-R/skylines,shadowoneau/skylines,RBE-Avionik/skylines
python
## Code Before: from skylines.model import Club from tests.api import basic_auth def test_create(db_session, client, test_user): headers = basic_auth(test_user.email_address, test_user.original_password) res = client.put('/clubs', headers=headers, json={ 'name': 'LV Aachen', }) assert res.status_code == 200 assert Club.get(res.json['id']) ## Instruction: tests/api: Add more "PUT /clubs" tests ## Code After: from skylines.model import Club from tests.api import basic_auth from tests.data import add_fixtures, clubs def test_create(db_session, client, test_user): headers = basic_auth(test_user.email_address, test_user.original_password) res = client.put('/clubs', headers=headers, json={ 'name': 'LV Aachen', }) assert res.status_code == 200 club = Club.get(res.json['id']) assert club assert club.owner_id == test_user.id def test_without_authentication(db_session, client): res = client.put('/clubs', json={ 'name': 'LV Aachen', }) assert res.status_code == 401 assert res.json['error'] == 'invalid_token' def test_non_json_data(db_session, client, test_user): headers = basic_auth(test_user.email_address, test_user.original_password) res = client.put('/clubs', headers=headers, data='foobar?') assert res.status_code == 400 assert res.json['error'] == 'invalid-request' def test_invalid_data(db_session, client, test_user): headers = basic_auth(test_user.email_address, test_user.original_password) res = client.put('/clubs', headers=headers, json={ 'name': '', }) assert res.status_code == 422 assert res.json['error'] == 'validation-failed' def test_existing_club(db_session, client, test_user): lva = clubs.lva() add_fixtures(db_session, lva) headers = basic_auth(test_user.email_address, test_user.original_password) res = client.put('/clubs', headers=headers, json={ 'name': 'LV Aachen', }) assert res.status_code == 422 assert res.json['error'] == 'duplicate-club-name'
... from skylines.model import Club from tests.api import basic_auth from tests.data import add_fixtures, clubs def test_create(db_session, client, test_user): ... 'name': 'LV Aachen', }) assert res.status_code == 200 club = Club.get(res.json['id']) assert club assert club.owner_id == test_user.id def test_without_authentication(db_session, client): res = client.put('/clubs', json={ 'name': 'LV Aachen', }) assert res.status_code == 401 assert res.json['error'] == 'invalid_token' def test_non_json_data(db_session, client, test_user): headers = basic_auth(test_user.email_address, test_user.original_password) res = client.put('/clubs', headers=headers, data='foobar?') assert res.status_code == 400 assert res.json['error'] == 'invalid-request' def test_invalid_data(db_session, client, test_user): headers = basic_auth(test_user.email_address, test_user.original_password) res = client.put('/clubs', headers=headers, json={ 'name': '', }) assert res.status_code == 422 assert res.json['error'] == 'validation-failed' def test_existing_club(db_session, client, test_user): lva = clubs.lva() add_fixtures(db_session, lva) headers = basic_auth(test_user.email_address, test_user.original_password) res = client.put('/clubs', headers=headers, json={ 'name': 'LV Aachen', }) assert res.status_code == 422 assert res.json['error'] == 'duplicate-club-name' ...
d0660abf6de458436322ae3dc285feed20408ad8
src/test/java/ca/intelliware/ihtsdo/mlds/search/AngularTranslateServiceSetup.java
src/test/java/ca/intelliware/ihtsdo/mlds/search/AngularTranslateServiceSetup.java
package ca.intelliware.ihtsdo.mlds.search; import java.io.File; import org.springframework.core.io.FileSystemResourceLoader; import org.springframework.mock.web.MockServletContext; public class AngularTranslateServiceSetup { MockServletContext mockServletContext; AngularTranslateService angularTranslateService; public void setup() { System.out.println("AngularTranslateServiceSetup - working directory is " + new File(".").getAbsolutePath()); mockServletContext = new MockServletContext("src/main/webapp", new FileSystemResourceLoader()); angularTranslateService = new AngularTranslateService(); angularTranslateService.setServletContext(mockServletContext); } }
package ca.intelliware.ihtsdo.mlds.search; import org.springframework.core.io.FileSystemResourceLoader; import org.springframework.mock.web.MockServletContext; public class AngularTranslateServiceSetup { MockServletContext mockServletContext; AngularTranslateService angularTranslateService; public void setup() { if (AngularTranslateService.getInstance() == null) { angularTranslateService = new AngularTranslateService(); } else { angularTranslateService = AngularTranslateService.getInstance(); } mockServletContext = new MockServletContext("src/main/webapp", new FileSystemResourceLoader()); angularTranslateService.setServletContext(mockServletContext); } }
Patch AngularTranslateService during test to avoid odd servlet resource location behaviour
Patch AngularTranslateService during test to avoid odd servlet resource location behaviour
Java
apache-2.0
IHTSDO/MLDS,IHTSDO/MLDS,IHTSDO/MLDS,IHTSDO/MLDS
java
## Code Before: package ca.intelliware.ihtsdo.mlds.search; import java.io.File; import org.springframework.core.io.FileSystemResourceLoader; import org.springframework.mock.web.MockServletContext; public class AngularTranslateServiceSetup { MockServletContext mockServletContext; AngularTranslateService angularTranslateService; public void setup() { System.out.println("AngularTranslateServiceSetup - working directory is " + new File(".").getAbsolutePath()); mockServletContext = new MockServletContext("src/main/webapp", new FileSystemResourceLoader()); angularTranslateService = new AngularTranslateService(); angularTranslateService.setServletContext(mockServletContext); } } ## Instruction: Patch AngularTranslateService during test to avoid odd servlet resource location behaviour ## Code After: package ca.intelliware.ihtsdo.mlds.search; import org.springframework.core.io.FileSystemResourceLoader; import org.springframework.mock.web.MockServletContext; public class AngularTranslateServiceSetup { MockServletContext mockServletContext; AngularTranslateService angularTranslateService; public void setup() { if (AngularTranslateService.getInstance() == null) { angularTranslateService = new AngularTranslateService(); } else { angularTranslateService = AngularTranslateService.getInstance(); } mockServletContext = new MockServletContext("src/main/webapp", new FileSystemResourceLoader()); angularTranslateService.setServletContext(mockServletContext); } }
... package ca.intelliware.ihtsdo.mlds.search; import org.springframework.core.io.FileSystemResourceLoader; import org.springframework.mock.web.MockServletContext; ... AngularTranslateService angularTranslateService; public void setup() { if (AngularTranslateService.getInstance() == null) { angularTranslateService = new AngularTranslateService(); } else { angularTranslateService = AngularTranslateService.getInstance(); } mockServletContext = new MockServletContext("src/main/webapp", new FileSystemResourceLoader()); angularTranslateService.setServletContext(mockServletContext); } } ...
c5b00edd9b8acbe594e43ecce093cd1c695b8b01
getalltextfromuser.py
getalltextfromuser.py
import argparse from json import loads def main(): parser = argparse.ArgumentParser( description="Extract raw text sent by a user from a json telegram chat log") parser.add_argument( 'filepath', help='the json file to analyse') parser.add_argument( 'username', help='the username of the person whose text you want') args=parser.parse_args() filepath = args.filepath username = args.username with open(filepath, 'r') as jsonfile: events = (loads(line) for line in jsonfile) for event in events: #check the event is the sort we're looking for if "from" in event and "text" in event: if "username" in event["from"]: #do i need "from" here? if event["from"]["username"] == username: print(event["text"]) if __name__ == "__main__": main()
import argparse from json import loads def main(): parser = argparse.ArgumentParser( description="Extract raw text sent by a user from a json telegram chat log") parser.add_argument( 'filepath', help='the json file to analyse') parser.add_argument( 'username', help='the username of the person whose text you want') args=parser.parse_args() filepath = args.filepath username = args.username user_id = "" #first, get the ID of the user with that username. with open(filepath, 'r') as jsonfile: events = (loads(line) for line in jsonfile) for event in events: #check the event is the sort we're looking for if "from" in event and "text" in event: if "username" in event["from"]: #do i need "from" here? if event["from"]["username"] == username: #print(event["text"]) print(event['from']['id']) user_id = event['from']['id'] break if user_id == "": print("user not found") exit() with open(filepath, 'r') as jsonfile: events = (loads(line) for line in jsonfile) for event in events: #check the event is the sort we're looking for if "from" in event and "text" in event: if user_id == event["from"]["id"]: print(event["text"]) if __name__ == "__main__": main()
Use user ID instead of username to get messages even with username changes
Use user ID instead of username to get messages even with username changes
Python
mit
expectocode/telegram-analysis,expectocode/telegramAnalysis
python
## Code Before: import argparse from json import loads def main(): parser = argparse.ArgumentParser( description="Extract raw text sent by a user from a json telegram chat log") parser.add_argument( 'filepath', help='the json file to analyse') parser.add_argument( 'username', help='the username of the person whose text you want') args=parser.parse_args() filepath = args.filepath username = args.username with open(filepath, 'r') as jsonfile: events = (loads(line) for line in jsonfile) for event in events: #check the event is the sort we're looking for if "from" in event and "text" in event: if "username" in event["from"]: #do i need "from" here? if event["from"]["username"] == username: print(event["text"]) if __name__ == "__main__": main() ## Instruction: Use user ID instead of username to get messages even with username changes ## Code After: import argparse from json import loads def main(): parser = argparse.ArgumentParser( description="Extract raw text sent by a user from a json telegram chat log") parser.add_argument( 'filepath', help='the json file to analyse') parser.add_argument( 'username', help='the username of the person whose text you want') args=parser.parse_args() filepath = args.filepath username = args.username user_id = "" #first, get the ID of the user with that username. with open(filepath, 'r') as jsonfile: events = (loads(line) for line in jsonfile) for event in events: #check the event is the sort we're looking for if "from" in event and "text" in event: if "username" in event["from"]: #do i need "from" here? if event["from"]["username"] == username: #print(event["text"]) print(event['from']['id']) user_id = event['from']['id'] break if user_id == "": print("user not found") exit() with open(filepath, 'r') as jsonfile: events = (loads(line) for line in jsonfile) for event in events: #check the event is the sort we're looking for if "from" in event and "text" in event: if user_id == event["from"]["id"]: print(event["text"]) if __name__ == "__main__": main()
# ... existing code ... filepath = args.filepath username = args.username user_id = "" #first, get the ID of the user with that username. with open(filepath, 'r') as jsonfile: events = (loads(line) for line in jsonfile) for event in events: # ... modified code ... if "username" in event["from"]: #do i need "from" here? if event["from"]["username"] == username: #print(event["text"]) print(event['from']['id']) user_id = event['from']['id'] break if user_id == "": print("user not found") exit() with open(filepath, 'r') as jsonfile: events = (loads(line) for line in jsonfile) for event in events: #check the event is the sort we're looking for if "from" in event and "text" in event: if user_id == event["from"]["id"]: print(event["text"]) if __name__ == "__main__": main() # ... rest of the code ...
928cb5c6fdfbcbd62f2d163e54f8b2f313453bd1
rxappfocus/src/main/java/com/gramboid/rxappfocus/AppFocusProvider.java
rxappfocus/src/main/java/com/gramboid/rxappfocus/AppFocusProvider.java
package com.gramboid.rxappfocus; import android.app.Activity; import android.app.Application; import android.app.Application.ActivityLifecycleCallbacks; import rx.Observable; import rx.subjects.PublishSubject; /** * Provides Observables to monitor app visibility. */ public class AppFocusProvider { private boolean changingConfig; private int foregroundCounter; private final PublishSubject<Boolean> subject = PublishSubject.create(); private final ActivityLifecycleCallbacks callbacks = new DefaultActivityLifecycleCallbacks() { @Override public void onActivityStarted(Activity activity) { if (changingConfig) { // ignore activity start, just a config change changingConfig = false; } else { incrementVisibleCounter(); } } @Override public void onActivityStopped(Activity activity) { if (activity.isChangingConfigurations()) { // ignore activity stop, just a config change changingConfig = true; } else { decrementVisibleCounter(); } } }; private void incrementVisibleCounter() { final boolean justBecomingVisible = !isVisible(); foregroundCounter++; if (justBecomingVisible) { subject.onNext(true); } } private void decrementVisibleCounter() { foregroundCounter--; if (!isVisible()) { subject.onNext(false); } } public AppFocusProvider(Application app) { app.registerActivityLifecycleCallbacks(callbacks); } public boolean isVisible() { return foregroundCounter > 0; } public Observable<Boolean> getAppFocus() { return subject; } }
package com.gramboid.rxappfocus; import android.app.Activity; import android.app.Application; import android.app.Application.ActivityLifecycleCallbacks; import rx.Observable; import rx.subjects.ReplaySubject; /** * Provides Observables to monitor app visibility. */ public class AppFocusProvider { private boolean changingConfig; private int foregroundCounter; private final ReplaySubject<Boolean> subject = ReplaySubject.createWithSize(1); private final ActivityLifecycleCallbacks callbacks = new DefaultActivityLifecycleCallbacks() { @Override public void onActivityStarted(Activity activity) { if (changingConfig) { // ignore activity start, just a config change changingConfig = false; } else { incrementVisibleCounter(); } } @Override public void onActivityStopped(Activity activity) { if (activity.isChangingConfigurations()) { // ignore activity stop, just a config change changingConfig = true; } else { decrementVisibleCounter(); } } }; private void incrementVisibleCounter() { final boolean justBecomingVisible = !isVisible(); foregroundCounter++; if (justBecomingVisible) { subject.onNext(true); } } private void decrementVisibleCounter() { foregroundCounter--; if (!isVisible()) { subject.onNext(false); } } public AppFocusProvider(Application app) { app.registerActivityLifecycleCallbacks(callbacks); } public boolean isVisible() { return foregroundCounter > 0; } public Observable<Boolean> getAppFocus() { return subject; } }
Allow late subscribers to immediately get the visibility status
Allow late subscribers to immediately get the visibility status
Java
apache-2.0
gramboid/RxAppFocus
java
## Code Before: package com.gramboid.rxappfocus; import android.app.Activity; import android.app.Application; import android.app.Application.ActivityLifecycleCallbacks; import rx.Observable; import rx.subjects.PublishSubject; /** * Provides Observables to monitor app visibility. */ public class AppFocusProvider { private boolean changingConfig; private int foregroundCounter; private final PublishSubject<Boolean> subject = PublishSubject.create(); private final ActivityLifecycleCallbacks callbacks = new DefaultActivityLifecycleCallbacks() { @Override public void onActivityStarted(Activity activity) { if (changingConfig) { // ignore activity start, just a config change changingConfig = false; } else { incrementVisibleCounter(); } } @Override public void onActivityStopped(Activity activity) { if (activity.isChangingConfigurations()) { // ignore activity stop, just a config change changingConfig = true; } else { decrementVisibleCounter(); } } }; private void incrementVisibleCounter() { final boolean justBecomingVisible = !isVisible(); foregroundCounter++; if (justBecomingVisible) { subject.onNext(true); } } private void decrementVisibleCounter() { foregroundCounter--; if (!isVisible()) { subject.onNext(false); } } public AppFocusProvider(Application app) { app.registerActivityLifecycleCallbacks(callbacks); } public boolean isVisible() { return foregroundCounter > 0; } public Observable<Boolean> getAppFocus() { return subject; } } ## Instruction: Allow late subscribers to immediately get the visibility status ## Code After: package com.gramboid.rxappfocus; import android.app.Activity; import android.app.Application; import android.app.Application.ActivityLifecycleCallbacks; import rx.Observable; import rx.subjects.ReplaySubject; /** * Provides Observables to monitor app visibility. */ public class AppFocusProvider { private boolean changingConfig; private int foregroundCounter; private final ReplaySubject<Boolean> subject = ReplaySubject.createWithSize(1); private final ActivityLifecycleCallbacks callbacks = new DefaultActivityLifecycleCallbacks() { @Override public void onActivityStarted(Activity activity) { if (changingConfig) { // ignore activity start, just a config change changingConfig = false; } else { incrementVisibleCounter(); } } @Override public void onActivityStopped(Activity activity) { if (activity.isChangingConfigurations()) { // ignore activity stop, just a config change changingConfig = true; } else { decrementVisibleCounter(); } } }; private void incrementVisibleCounter() { final boolean justBecomingVisible = !isVisible(); foregroundCounter++; if (justBecomingVisible) { subject.onNext(true); } } private void decrementVisibleCounter() { foregroundCounter--; if (!isVisible()) { subject.onNext(false); } } public AppFocusProvider(Application app) { app.registerActivityLifecycleCallbacks(callbacks); } public boolean isVisible() { return foregroundCounter > 0; } public Observable<Boolean> getAppFocus() { return subject; } }
// ... existing code ... import android.app.Application.ActivityLifecycleCallbacks; import rx.Observable; import rx.subjects.ReplaySubject; /** * Provides Observables to monitor app visibility. // ... modified code ... private boolean changingConfig; private int foregroundCounter; private final ReplaySubject<Boolean> subject = ReplaySubject.createWithSize(1); private final ActivityLifecycleCallbacks callbacks = new DefaultActivityLifecycleCallbacks() { // ... rest of the code ...
e84a06ea851a81648ba6ee54c88a61c049e913f2
gorilla/__init__.py
gorilla/__init__.py
from gorilla.decorators import apply, name, patch from gorilla.utils import get_original_attribute __version__ = '0.1.0' __all__ = [ 'decorators', 'extension', 'settings', 'utils' ]
from gorilla.decorators import apply, name, patch __version__ = '0.1.0' __all__ = [ 'decorators', 'extension', 'settings', 'utils' ]
Remove the `get_original_attribute` shortcut from the root module.
Remove the `get_original_attribute` shortcut from the root module.
Python
mit
christophercrouzet/gorilla
python
## Code Before: from gorilla.decorators import apply, name, patch from gorilla.utils import get_original_attribute __version__ = '0.1.0' __all__ = [ 'decorators', 'extension', 'settings', 'utils' ] ## Instruction: Remove the `get_original_attribute` shortcut from the root module. ## Code After: from gorilla.decorators import apply, name, patch __version__ = '0.1.0' __all__ = [ 'decorators', 'extension', 'settings', 'utils' ]
# ... existing code ... from gorilla.decorators import apply, name, patch __version__ = '0.1.0' # ... rest of the code ...
87b6f69fe53e0425dd5321fcecb613f31887c746
recipyCommon/libraryversions.py
recipyCommon/libraryversions.py
import sys import warnings def get_version(modulename): "Return a string containing the module name and the library version." version = '?' # Get the root module name (in case we have something like `recipy.open` # or `matplotlib.pyplot`) modulename = modulename.split('.')[0] if modulename in sys.modules: try: version = sys.modules[modulename].__version__ except: pass try: version = sys.modules[modulename].version except: pass try: version = sys.modules[modulename].version.version except: pass try: version = sys.modules[modulename].VERSION except: pass else: warnings.warn('requesting version of a module that has not been ' 'imported ({})'.format(modulename)) return '{} v{}'.format(modulename, version)
import sys import warnings def get_version(modulename): "Return a string containing the module name and the library version." version = '?' # Get the root module name (in case we have something like `recipy.open` # or `matplotlib.pyplot`) modulename = modulename.split('.')[0] if modulename in sys.modules: try: version = sys.modules[modulename].__version__ except (KeyError, AttributeError): pass try: version = sys.modules[modulename].version except (KeyError, AttributeError): pass try: version = sys.modules[modulename].version.version except (KeyError, AttributeError): pass try: version = sys.modules[modulename].VERSION except (KeyError, AttributeError): pass else: warnings.warn('requesting version of a module that has not been ' 'imported ({})'.format(modulename)) return '{} v{}'.format(modulename, version)
Add explicit (rather than broad/general) exceptions in get_version
Add explicit (rather than broad/general) exceptions in get_version
Python
apache-2.0
recipy/recipy,recipy/recipy
python
## Code Before: import sys import warnings def get_version(modulename): "Return a string containing the module name and the library version." version = '?' # Get the root module name (in case we have something like `recipy.open` # or `matplotlib.pyplot`) modulename = modulename.split('.')[0] if modulename in sys.modules: try: version = sys.modules[modulename].__version__ except: pass try: version = sys.modules[modulename].version except: pass try: version = sys.modules[modulename].version.version except: pass try: version = sys.modules[modulename].VERSION except: pass else: warnings.warn('requesting version of a module that has not been ' 'imported ({})'.format(modulename)) return '{} v{}'.format(modulename, version) ## Instruction: Add explicit (rather than broad/general) exceptions in get_version ## Code After: import sys import warnings def get_version(modulename): "Return a string containing the module name and the library version." version = '?' # Get the root module name (in case we have something like `recipy.open` # or `matplotlib.pyplot`) modulename = modulename.split('.')[0] if modulename in sys.modules: try: version = sys.modules[modulename].__version__ except (KeyError, AttributeError): pass try: version = sys.modules[modulename].version except (KeyError, AttributeError): pass try: version = sys.modules[modulename].version.version except (KeyError, AttributeError): pass try: version = sys.modules[modulename].VERSION except (KeyError, AttributeError): pass else: warnings.warn('requesting version of a module that has not been ' 'imported ({})'.format(modulename)) return '{} v{}'.format(modulename, version)
// ... existing code ... if modulename in sys.modules: try: version = sys.modules[modulename].__version__ except (KeyError, AttributeError): pass try: version = sys.modules[modulename].version except (KeyError, AttributeError): pass try: version = sys.modules[modulename].version.version except (KeyError, AttributeError): pass try: version = sys.modules[modulename].VERSION except (KeyError, AttributeError): pass else: warnings.warn('requesting version of a module that has not been ' // ... rest of the code ...
aa436864f53a4c77b4869baabfb1478d7fea36f0
tests/products/__init__.py
tests/products/__init__.py
import arrow import six from tilezilla.core import BoundingBox, Band MAPPING = { 'timeseries_id': str, 'acquired': arrow.Arrow, 'processed': arrow.Arrow, 'platform': str, 'instrument': str, 'bounds': BoundingBox, 'bands': [Band], 'metadata': dict, 'metadata_files': dict } def check_attributes(product): for attr, _type in six.iteritems(MAPPING): assert hasattr(product, attr) value = getattr(product, attr) if isinstance(_type, type): assert isinstance(value, _type) else: assert isinstance(value, type(_type)) for item in value: assert isinstance(item, tuple(_type))
import arrow import six from tilezilla.core import BoundingBox, Band MAPPING = { 'timeseries_id': six.string_types, 'acquired': arrow.Arrow, 'processed': arrow.Arrow, 'platform': six.string_types, 'instrument': six.string_types, 'bounds': BoundingBox, 'bands': [Band], 'metadata': dict, 'metadata_files': dict } def check_attributes(product): for attr, _type in six.iteritems(MAPPING): assert hasattr(product, attr) value = getattr(product, attr) if isinstance(_type, (type, tuple)): # Type declaration one or more types assert isinstance(value, _type) else: # Type declaration list of types assert isinstance(value, type(_type)) for item in value: assert isinstance(item, tuple(_type))
Allow str type comparison in py2/3
Allow str type comparison in py2/3
Python
bsd-3-clause
ceholden/landsat_tile,ceholden/landsat_tiles,ceholden/landsat_tiles,ceholden/tilezilla,ceholden/landsat_tile
python
## Code Before: import arrow import six from tilezilla.core import BoundingBox, Band MAPPING = { 'timeseries_id': str, 'acquired': arrow.Arrow, 'processed': arrow.Arrow, 'platform': str, 'instrument': str, 'bounds': BoundingBox, 'bands': [Band], 'metadata': dict, 'metadata_files': dict } def check_attributes(product): for attr, _type in six.iteritems(MAPPING): assert hasattr(product, attr) value = getattr(product, attr) if isinstance(_type, type): assert isinstance(value, _type) else: assert isinstance(value, type(_type)) for item in value: assert isinstance(item, tuple(_type)) ## Instruction: Allow str type comparison in py2/3 ## Code After: import arrow import six from tilezilla.core import BoundingBox, Band MAPPING = { 'timeseries_id': six.string_types, 'acquired': arrow.Arrow, 'processed': arrow.Arrow, 'platform': six.string_types, 'instrument': six.string_types, 'bounds': BoundingBox, 'bands': [Band], 'metadata': dict, 'metadata_files': dict } def check_attributes(product): for attr, _type in six.iteritems(MAPPING): assert hasattr(product, attr) value = getattr(product, attr) if isinstance(_type, (type, tuple)): # Type declaration one or more types assert isinstance(value, _type) else: # Type declaration list of types assert isinstance(value, type(_type)) for item in value: assert isinstance(item, tuple(_type))
# ... existing code ... MAPPING = { 'timeseries_id': six.string_types, 'acquired': arrow.Arrow, 'processed': arrow.Arrow, 'platform': six.string_types, 'instrument': six.string_types, 'bounds': BoundingBox, 'bands': [Band], 'metadata': dict, # ... modified code ... assert hasattr(product, attr) value = getattr(product, attr) if isinstance(_type, (type, tuple)): # Type declaration one or more types assert isinstance(value, _type) else: # Type declaration list of types assert isinstance(value, type(_type)) for item in value: assert isinstance(item, tuple(_type)) # ... rest of the code ...
e8b74cb53887da0611f686c017eb27926ad35cbb
src/main/java/com/researchspace/api/clientmodel/DocumentPost.java
src/main/java/com/researchspace/api/clientmodel/DocumentPost.java
package com.researchspace.api.clientmodel; import java.util.ArrayList; import java.util.List; import lombok.Builder; import lombok.Data; import lombok.Singular; /** * Models the request body of a /documents POST request. All content is optional. * If a form ID is set then the field content must match the field types defined by the Form * @author rspace * @since 1.1.0 * */ @Data @Builder public class DocumentPost { /** * Comma separated tags */ private String tags; /** * name of document */ private String name; @Singular private List<FieldPost> fields; private FormRef form; /** * Appends a {@link FieldPost} to the list of Fields * @param toAdd a {@link FieldPost} * @return <code>true</code> if added, <code>false</code> otherwise */ public boolean addField(FieldPost toAdd) { if(fields == null) { fields = new ArrayList<>(); } return fields.add(toAdd); } }
package com.researchspace.api.clientmodel; import java.util.ArrayList; import java.util.List; import lombok.Builder; import lombok.Data; import lombok.Singular; /** * Models the request body of a /documents POST request. All content is optional. * If a form ID is set then the field content must match the field types defined by the Form * @author rspace * @since 1.1.0 * */ @Data @Builder public class DocumentPost { /** * Comma separated tags */ private String tags; /** * name of document */ private String name; @Singular private List<FieldPost> fields; /** * Optional id of the folder to hold this document. * @since 1.3.0 */ private Long parentFolderId; private FormRef form; /** * Appends a {@link FieldPost} to the list of Fields * @param toAdd a {@link FieldPost} * @return <code>true</code> if added, <code>false</code> otherwise */ public boolean addField(FieldPost toAdd) { if(fields == null) { fields = new ArrayList<>(); } return fields.add(toAdd); } }
Add parentFolderId to document post
Add parentFolderId to document post
Java
apache-2.0
rspace-os/rspace-client-java-model
java
## Code Before: package com.researchspace.api.clientmodel; import java.util.ArrayList; import java.util.List; import lombok.Builder; import lombok.Data; import lombok.Singular; /** * Models the request body of a /documents POST request. All content is optional. * If a form ID is set then the field content must match the field types defined by the Form * @author rspace * @since 1.1.0 * */ @Data @Builder public class DocumentPost { /** * Comma separated tags */ private String tags; /** * name of document */ private String name; @Singular private List<FieldPost> fields; private FormRef form; /** * Appends a {@link FieldPost} to the list of Fields * @param toAdd a {@link FieldPost} * @return <code>true</code> if added, <code>false</code> otherwise */ public boolean addField(FieldPost toAdd) { if(fields == null) { fields = new ArrayList<>(); } return fields.add(toAdd); } } ## Instruction: Add parentFolderId to document post ## Code After: package com.researchspace.api.clientmodel; import java.util.ArrayList; import java.util.List; import lombok.Builder; import lombok.Data; import lombok.Singular; /** * Models the request body of a /documents POST request. All content is optional. * If a form ID is set then the field content must match the field types defined by the Form * @author rspace * @since 1.1.0 * */ @Data @Builder public class DocumentPost { /** * Comma separated tags */ private String tags; /** * name of document */ private String name; @Singular private List<FieldPost> fields; /** * Optional id of the folder to hold this document. * @since 1.3.0 */ private Long parentFolderId; private FormRef form; /** * Appends a {@link FieldPost} to the list of Fields * @param toAdd a {@link FieldPost} * @return <code>true</code> if added, <code>false</code> otherwise */ public boolean addField(FieldPost toAdd) { if(fields == null) { fields = new ArrayList<>(); } return fields.add(toAdd); } }
... @Singular private List<FieldPost> fields; /** * Optional id of the folder to hold this document. * @since 1.3.0 */ private Long parentFolderId; private FormRef form; /** ...
901c482f357ba3a845d40cb126667490472a6bf6
Code/divide.py
Code/divide.py
def divide(a, b): return a / b print divide(20, 2)
num1 = input('Enter first number: ') num2 = input('Enter second number: ') if num2==0: print 'Denominator cannot be 0' else: Division=float(num1)/float(num2) print Division
Divide two numbers using python code
Divide two numbers using python code
Python
mit
HarendraSingh22/Python-Guide-for-Beginners
python
## Code Before: def divide(a, b): return a / b print divide(20, 2) ## Instruction: Divide two numbers using python code ## Code After: num1 = input('Enter first number: ') num2 = input('Enter second number: ') if num2==0: print 'Denominator cannot be 0' else: Division=float(num1)/float(num2) print Division
... num1 = input('Enter first number: ') num2 = input('Enter second number: ') if num2==0: print 'Denominator cannot be 0' else: Division=float(num1)/float(num2) print Division ...
40642464aa4d21cb1710f9197bc3456467ed22a8
b2b_demo/views/basket.py
b2b_demo/views/basket.py
from django import forms from shoop.core.models import Address from shoop.front.views.basket import DefaultBasketView class AddressForm(forms.ModelForm): class Meta: model = Address fields = ( "name", "phone", "email", "street", "street2", "postal_code", "city", "region", "country" ) def __init__(self, *args, **kwargs): super(AddressForm, self).__init__(*args, **kwargs) for field_name in ("email", "postal_code"): self.fields[field_name].required = True class B2bBasketView(DefaultBasketView): shipping_address_form_class = AddressForm billing_address_form_class = AddressForm
from django import forms from shoop.front.views.basket import DefaultBasketView from shoop.core.models import MutableAddress class AddressForm(forms.ModelForm): class Meta: model = MutableAddress fields = ( "name", "phone", "email", "street", "street2", "postal_code", "city", "region", "country" ) def __init__(self, *args, **kwargs): super(AddressForm, self).__init__(*args, **kwargs) for field_name in ("email", "postal_code"): self.fields[field_name].required = True class B2bBasketView(DefaultBasketView): shipping_address_form_class = AddressForm billing_address_form_class = AddressForm
Use MutableAddress instead of Address
Use MutableAddress instead of Address
Python
agpl-3.0
shoopio/shoop-gifter-demo,shoopio/shoop-gifter-demo,shoopio/shoop-gifter-demo
python
## Code Before: from django import forms from shoop.core.models import Address from shoop.front.views.basket import DefaultBasketView class AddressForm(forms.ModelForm): class Meta: model = Address fields = ( "name", "phone", "email", "street", "street2", "postal_code", "city", "region", "country" ) def __init__(self, *args, **kwargs): super(AddressForm, self).__init__(*args, **kwargs) for field_name in ("email", "postal_code"): self.fields[field_name].required = True class B2bBasketView(DefaultBasketView): shipping_address_form_class = AddressForm billing_address_form_class = AddressForm ## Instruction: Use MutableAddress instead of Address ## Code After: from django import forms from shoop.front.views.basket import DefaultBasketView from shoop.core.models import MutableAddress class AddressForm(forms.ModelForm): class Meta: model = MutableAddress fields = ( "name", "phone", "email", "street", "street2", "postal_code", "city", "region", "country" ) def __init__(self, *args, **kwargs): super(AddressForm, self).__init__(*args, **kwargs) for field_name in ("email", "postal_code"): self.fields[field_name].required = True class B2bBasketView(DefaultBasketView): shipping_address_form_class = AddressForm billing_address_form_class = AddressForm
# ... existing code ... from django import forms from shoop.front.views.basket import DefaultBasketView from shoop.core.models import MutableAddress class AddressForm(forms.ModelForm): class Meta: model = MutableAddress fields = ( "name", "phone", "email", "street", "street2", "postal_code", "city", # ... rest of the code ...
ea3918bcde250b16baabe72bf4003ce5c16831af
app/src/ee/ioc/phon/android/arvutaja/command/CommandParser.java
app/src/ee/ioc/phon/android/arvutaja/command/CommandParser.java
package ee.ioc.phon.android.arvutaja.command; import ee.ioc.phon.android.arvutaja.R; import android.content.Context; public class CommandParser { public static Command getCommand(Context context, String command) throws CommandParseException { if (command == null) { throw new CommandParseException(); } if (Alarm.isCommand(command)) return new Alarm(command, context.getString(R.string.alarmExtraMessage)); if (Dial.isCommand(command)) return new Dial(command); if (Expr.isCommand(command)) return new Expr(command); if (Search.isCommand(command)) return new Search(command); if (Unitconv.isCommand(command)) return new Unitconv(command); if (Direction.isCommand(command)) return new Direction(command); return new DefaultCommand(command); } }
package ee.ioc.phon.android.arvutaja.command; import ee.ioc.phon.android.arvutaja.R; import android.content.Context; public class CommandParser { public static Command getCommand(Context context, String command) throws CommandParseException { if (command == null) { throw new CommandParseException(); } if (Alarm.isCommand(command)) return new Alarm(command, context.getString(R.string.alarmExtraMessage)); if (command.startsWith("weather ")) return new DefaultCommand(command); if (Dial.isCommand(command)) return new Dial(command); if (Expr.isCommand(command)) return new Expr(command); if (Search.isCommand(command)) return new Search(command); if (Unitconv.isCommand(command)) return new Unitconv(command); if (Direction.isCommand(command)) return new Direction(command); return new DefaultCommand(command); } }
Add support for weather queries
Add support for weather queries
Java
apache-2.0
Kaljurand/Arvutaja,Kaljurand/Arvutaja
java
## Code Before: package ee.ioc.phon.android.arvutaja.command; import ee.ioc.phon.android.arvutaja.R; import android.content.Context; public class CommandParser { public static Command getCommand(Context context, String command) throws CommandParseException { if (command == null) { throw new CommandParseException(); } if (Alarm.isCommand(command)) return new Alarm(command, context.getString(R.string.alarmExtraMessage)); if (Dial.isCommand(command)) return new Dial(command); if (Expr.isCommand(command)) return new Expr(command); if (Search.isCommand(command)) return new Search(command); if (Unitconv.isCommand(command)) return new Unitconv(command); if (Direction.isCommand(command)) return new Direction(command); return new DefaultCommand(command); } } ## Instruction: Add support for weather queries ## Code After: package ee.ioc.phon.android.arvutaja.command; import ee.ioc.phon.android.arvutaja.R; import android.content.Context; public class CommandParser { public static Command getCommand(Context context, String command) throws CommandParseException { if (command == null) { throw new CommandParseException(); } if (Alarm.isCommand(command)) return new Alarm(command, context.getString(R.string.alarmExtraMessage)); if (command.startsWith("weather ")) return new DefaultCommand(command); if (Dial.isCommand(command)) return new Dial(command); if (Expr.isCommand(command)) return new Expr(command); if (Search.isCommand(command)) return new Search(command); if (Unitconv.isCommand(command)) return new Unitconv(command); if (Direction.isCommand(command)) return new Direction(command); return new DefaultCommand(command); } }
// ... existing code ... if (Alarm.isCommand(command)) return new Alarm(command, context.getString(R.string.alarmExtraMessage)); if (command.startsWith("weather ")) return new DefaultCommand(command); if (Dial.isCommand(command)) return new Dial(command); // ... rest of the code ...
a38e293d76beaa71893a8f5c4be2ea562d6d3fc2
apistar/layouts/standard/project/routes.py
apistar/layouts/standard/project/routes.py
from apistar import Route, Include from apistar.docs import docs_routes from apistar.statics import static_routes from project.views import welcome routes = [ Route('/', 'GET', welcome), Include('/docs', docs_routes), Include('/static', static_routes) ]
from apistar import Include, Route from apistar.docs import docs_routes from apistar.statics import static_routes from project.views import welcome routes = [ Route('/', 'GET', welcome), Include('/docs', docs_routes), Include('/static', static_routes) ]
Fix import ordering in standard layout
Fix import ordering in standard layout
Python
bsd-3-clause
encode/apistar,rsalmaso/apistar,rsalmaso/apistar,encode/apistar,tomchristie/apistar,tomchristie/apistar,tomchristie/apistar,thimslugga/apistar,thimslugga/apistar,rsalmaso/apistar,encode/apistar,rsalmaso/apistar,encode/apistar,thimslugga/apistar,thimslugga/apistar,tomchristie/apistar
python
## Code Before: from apistar import Route, Include from apistar.docs import docs_routes from apistar.statics import static_routes from project.views import welcome routes = [ Route('/', 'GET', welcome), Include('/docs', docs_routes), Include('/static', static_routes) ] ## Instruction: Fix import ordering in standard layout ## Code After: from apistar import Include, Route from apistar.docs import docs_routes from apistar.statics import static_routes from project.views import welcome routes = [ Route('/', 'GET', welcome), Include('/docs', docs_routes), Include('/static', static_routes) ]
// ... existing code ... from apistar import Include, Route from apistar.docs import docs_routes from apistar.statics import static_routes from project.views import welcome // ... rest of the code ...
fbdf73e3e9fb5f2801ec11637caa6020095acfdf
terrabot/packets/packetE.py
terrabot/packets/packetE.py
from terrabot.util.streamer import Streamer from terrabot.events.events import Events class PacketEParser(object): def parse(self, world, player, data, ev_man): #If player is active if data[2] == 1: #Raise event with player_id ev_man.raise_event(Events.NewPlayer, data[1])
from terrabot.util.streamer import Streamer from terrabot.events.events import Events class PacketEParser(object): def parse(self, world, player, data, ev_man): #If player is active if data[2] == 1 and player.logged_in: #Raise event with player_id ev_man.raise_event(Events.NewPlayer, data[1])
Fix with 'newPlayer' event triggering on load
Fix with 'newPlayer' event triggering on load
Python
mit
flammified/terrabot
python
## Code Before: from terrabot.util.streamer import Streamer from terrabot.events.events import Events class PacketEParser(object): def parse(self, world, player, data, ev_man): #If player is active if data[2] == 1: #Raise event with player_id ev_man.raise_event(Events.NewPlayer, data[1]) ## Instruction: Fix with 'newPlayer' event triggering on load ## Code After: from terrabot.util.streamer import Streamer from terrabot.events.events import Events class PacketEParser(object): def parse(self, world, player, data, ev_man): #If player is active if data[2] == 1 and player.logged_in: #Raise event with player_id ev_man.raise_event(Events.NewPlayer, data[1])
# ... existing code ... def parse(self, world, player, data, ev_man): #If player is active if data[2] == 1 and player.logged_in: #Raise event with player_id ev_man.raise_event(Events.NewPlayer, data[1]) # ... rest of the code ...
c88969f2e4a1459e6a66da3f75f8ea41ae9cea9c
rplugin/python3/denite/source/denite_gtags/tags_base.py
rplugin/python3/denite/source/denite_gtags/tags_base.py
import re from abc import abstractmethod from denite_gtags import GtagsBase # pylint: disable=locally-disabled, wrong-import-position class TagsBase(GtagsBase): TAG_PATTERN = re.compile('([^\t]+)\t(\\d+)\t(.*)') def __init__(self, vim): super().__init__(vim) @abstractmethod def get_search_flags(self): return [] def get_search_word(self, context): if len(context['args']) > 0: return context['args'][0] return context['input'] def gather_candidates(self, context): word = self.get_search_word(context) tags = self.exec_global(self.get_search_flags() + [word], context) candidates = self._convert_to_candidates(tags) return candidates @classmethod def _convert_to_candidates(cls, tags): candidates = [] for tag in tags: path, line, text = cls._parse_tag(tag) col = text.find(text) -1 candidates.append({ 'word': tag, 'action__path': path, 'action__line': line, 'action__text': text, 'action__col': col }) return candidates @classmethod def _parse_tag(cls, tag): match = cls.TAG_PATTERN.match(tag) return match.groups()
import re from abc import abstractmethod from denite_gtags import GtagsBase # pylint: disable=locally-disabled, wrong-import-position class TagsBase(GtagsBase): TAG_PATTERN = re.compile('([^\t]+)\t(\\d+)\t(.*)') @abstractmethod def get_search_flags(self): return [] def get_search_word(self, context): args_count = len(context['args']) if args_count > 0: return context['args'][0] return context['input'] def gather_candidates(self, context): word = self.get_search_word(context) tags = self.exec_global(self.get_search_flags() + ['--', word], context) candidates = self._convert_to_candidates(tags) return candidates @classmethod def _convert_to_candidates(cls, tags): candidates = [] for tag in tags: path, line, text = cls._parse_tag(tag) col = text.find(text) -1 candidates.append({ 'word': tag, 'action__path': path, 'action__line': line, 'action__text': text, 'action__col': col }) return candidates @classmethod def _parse_tag(cls, tag): match = cls.TAG_PATTERN.match(tag) return match.groups()
Fix error on words beginning with '-'
Fix error on words beginning with '-'
Python
mit
ozelentok/denite-gtags
python
## Code Before: import re from abc import abstractmethod from denite_gtags import GtagsBase # pylint: disable=locally-disabled, wrong-import-position class TagsBase(GtagsBase): TAG_PATTERN = re.compile('([^\t]+)\t(\\d+)\t(.*)') def __init__(self, vim): super().__init__(vim) @abstractmethod def get_search_flags(self): return [] def get_search_word(self, context): if len(context['args']) > 0: return context['args'][0] return context['input'] def gather_candidates(self, context): word = self.get_search_word(context) tags = self.exec_global(self.get_search_flags() + [word], context) candidates = self._convert_to_candidates(tags) return candidates @classmethod def _convert_to_candidates(cls, tags): candidates = [] for tag in tags: path, line, text = cls._parse_tag(tag) col = text.find(text) -1 candidates.append({ 'word': tag, 'action__path': path, 'action__line': line, 'action__text': text, 'action__col': col }) return candidates @classmethod def _parse_tag(cls, tag): match = cls.TAG_PATTERN.match(tag) return match.groups() ## Instruction: Fix error on words beginning with '-' ## Code After: import re from abc import abstractmethod from denite_gtags import GtagsBase # pylint: disable=locally-disabled, wrong-import-position class TagsBase(GtagsBase): TAG_PATTERN = re.compile('([^\t]+)\t(\\d+)\t(.*)') @abstractmethod def get_search_flags(self): return [] def get_search_word(self, context): args_count = len(context['args']) if args_count > 0: return context['args'][0] return context['input'] def gather_candidates(self, context): word = self.get_search_word(context) tags = self.exec_global(self.get_search_flags() + ['--', word], context) candidates = self._convert_to_candidates(tags) return candidates @classmethod def _convert_to_candidates(cls, tags): candidates = [] for tag in tags: path, line, text = cls._parse_tag(tag) col = text.find(text) -1 candidates.append({ 'word': tag, 'action__path': path, 'action__line': line, 'action__text': text, 'action__col': col }) return candidates @classmethod def _parse_tag(cls, tag): match = cls.TAG_PATTERN.match(tag) return match.groups()
// ... existing code ... TAG_PATTERN = re.compile('([^\t]+)\t(\\d+)\t(.*)') @abstractmethod def get_search_flags(self): return [] def get_search_word(self, context): args_count = len(context['args']) if args_count > 0: return context['args'][0] return context['input'] def gather_candidates(self, context): word = self.get_search_word(context) tags = self.exec_global(self.get_search_flags() + ['--', word], context) candidates = self._convert_to_candidates(tags) return candidates // ... rest of the code ...
e28c9da712574618eb28b6ff82631462fee67c16
changes/utils/times.py
changes/utils/times.py
def duration(value): ONE_SECOND = 1000 ONE_MINUTE = ONE_SECOND * 60 if not value: return '0 s' if value < 3 * ONE_SECOND: return '%d ms' % (value,) elif value < 5 * ONE_MINUTE: return '%d s' % (value / ONE_SECOND,) else: return '%d m' % (value / ONE_MINUTE,)
def duration(value): ONE_SECOND = 1000 ONE_MINUTE = ONE_SECOND * 60 if not value: return '0 s' abs_value = abs(value) if abs_value < 3 * ONE_SECOND: return '%d ms' % (value,) elif abs_value < 5 * ONE_MINUTE: return '%d s' % (value / ONE_SECOND,) else: return '%d m' % (value / ONE_MINUTE,)
Fix for negative values in duration
Fix for negative values in duration
Python
apache-2.0
bowlofstew/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,dropbox/changes,bowlofstew/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,wfxiang08/changes
python
## Code Before: def duration(value): ONE_SECOND = 1000 ONE_MINUTE = ONE_SECOND * 60 if not value: return '0 s' if value < 3 * ONE_SECOND: return '%d ms' % (value,) elif value < 5 * ONE_MINUTE: return '%d s' % (value / ONE_SECOND,) else: return '%d m' % (value / ONE_MINUTE,) ## Instruction: Fix for negative values in duration ## Code After: def duration(value): ONE_SECOND = 1000 ONE_MINUTE = ONE_SECOND * 60 if not value: return '0 s' abs_value = abs(value) if abs_value < 3 * ONE_SECOND: return '%d ms' % (value,) elif abs_value < 5 * ONE_MINUTE: return '%d s' % (value / ONE_SECOND,) else: return '%d m' % (value / ONE_MINUTE,)
# ... existing code ... if not value: return '0 s' abs_value = abs(value) if abs_value < 3 * ONE_SECOND: return '%d ms' % (value,) elif abs_value < 5 * ONE_MINUTE: return '%d s' % (value / ONE_SECOND,) else: return '%d m' % (value / ONE_MINUTE,) # ... rest of the code ...
3471024a63f2bf55763563693f439a704291fc7d
examples/apt.py
examples/apt.py
from pyinfra import host from pyinfra.modules import apt SUDO = True code_name = host.fact.linux_distribution['release_meta'].get('DISTRIB_CODENAME') print(host.fact.linux_name, code_name) if host.fact.linux_name in ['Debian', 'Ubuntu']: apt.packages( {'Install some packages'}, ['vim-addon-manager', 'vim', 'software-properties-common', 'wget', 'curl'], update=True, ) apt.ppa( {'Add the Bitcoin ppa'}, 'ppa:bitcoin/bitcoin', ) # typically after adding a ppk, you want to update apt.update() # but you could just include the update in the apt install step # like this: apt.packages( {'Install Bitcoin'}, 'bitcoin-qt', update=True, ) apt.deb( {'Install Chrome via deb'}, 'https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb', ) apt.key( {'Install VirtualBox key'}, 'https://www.virtualbox.org/download/oracle_vbox_2016.asc', ) apt.repo( {'Install VirtualBox repo'}, 'deb https://download.virtualbox.org/virtualbox/debian {} contrib'.format(code_name), )
from pyinfra import host from pyinfra.modules import apt SUDO = True code_name = host.fact.linux_distribution['release_meta'].get('DISTRIB_CODENAME') print(host.fact.linux_name, code_name) if host.fact.linux_name in ['Debian', 'Ubuntu']: apt.packages( {'Install some packages'}, ['vim-addon-manager', 'vim', 'software-properties-common', 'wget', 'curl'], update=True, ) # NOTE: the bitcoin PPA is no longer supported # apt.ppa( # {'Add the Bitcoin ppa'}, # 'ppa:bitcoin/bitcoin', # ) # # apt.packages( # {'Install Bitcoin'}, # 'bitcoin-qt', # update=True, # ) apt.deb( {'Install Chrome via deb'}, 'https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb', ) apt.key( {'Install VirtualBox key'}, 'https://www.virtualbox.org/download/oracle_vbox_2016.asc', ) apt.repo( {'Install VirtualBox repo'}, 'deb https://download.virtualbox.org/virtualbox/debian {} contrib'.format(code_name), )
Comment out the bitcoin PPA code.
Comment out the bitcoin PPA code. The bitcoin PPA is no longer maintained/supported.
Python
mit
Fizzadar/pyinfra,Fizzadar/pyinfra
python
## Code Before: from pyinfra import host from pyinfra.modules import apt SUDO = True code_name = host.fact.linux_distribution['release_meta'].get('DISTRIB_CODENAME') print(host.fact.linux_name, code_name) if host.fact.linux_name in ['Debian', 'Ubuntu']: apt.packages( {'Install some packages'}, ['vim-addon-manager', 'vim', 'software-properties-common', 'wget', 'curl'], update=True, ) apt.ppa( {'Add the Bitcoin ppa'}, 'ppa:bitcoin/bitcoin', ) # typically after adding a ppk, you want to update apt.update() # but you could just include the update in the apt install step # like this: apt.packages( {'Install Bitcoin'}, 'bitcoin-qt', update=True, ) apt.deb( {'Install Chrome via deb'}, 'https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb', ) apt.key( {'Install VirtualBox key'}, 'https://www.virtualbox.org/download/oracle_vbox_2016.asc', ) apt.repo( {'Install VirtualBox repo'}, 'deb https://download.virtualbox.org/virtualbox/debian {} contrib'.format(code_name), ) ## Instruction: Comment out the bitcoin PPA code. The bitcoin PPA is no longer maintained/supported. ## Code After: from pyinfra import host from pyinfra.modules import apt SUDO = True code_name = host.fact.linux_distribution['release_meta'].get('DISTRIB_CODENAME') print(host.fact.linux_name, code_name) if host.fact.linux_name in ['Debian', 'Ubuntu']: apt.packages( {'Install some packages'}, ['vim-addon-manager', 'vim', 'software-properties-common', 'wget', 'curl'], update=True, ) # NOTE: the bitcoin PPA is no longer supported # apt.ppa( # {'Add the Bitcoin ppa'}, # 'ppa:bitcoin/bitcoin', # ) # # apt.packages( # {'Install Bitcoin'}, # 'bitcoin-qt', # update=True, # ) apt.deb( {'Install Chrome via deb'}, 'https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb', ) apt.key( {'Install VirtualBox key'}, 'https://www.virtualbox.org/download/oracle_vbox_2016.asc', ) apt.repo( {'Install VirtualBox repo'}, 'deb https://download.virtualbox.org/virtualbox/debian {} contrib'.format(code_name), )
... update=True, ) # NOTE: the bitcoin PPA is no longer supported # apt.ppa( # {'Add the Bitcoin ppa'}, # 'ppa:bitcoin/bitcoin', # ) # # apt.packages( # {'Install Bitcoin'}, # 'bitcoin-qt', # update=True, # ) apt.deb( {'Install Chrome via deb'}, ...
d37631451ad65588fdd8ab6cb300769deca3d043
modules/roles.py
modules/roles.py
import discord import shlex from modules.botModule import BotModule class Roles(BotModule): name = 'Roles' description = 'Allow for the assignment and removal of roles.' help_text = '' trigger_string = '!role' # String to listen for as trigger async def parse_command(self, message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg = shlex.split(message.content) role = [i for i, x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is role_to_assign = message.server.roles[role[0]] if len(msg) != 1: try: if role_to_assign in message.author.roles: await client.remove_roles(message.author, role_to_assign) msg = ":ok_hand: Removed you from " + role_to_assign.name + " ." else: await client.add_roles(message.author, role_to_assign) msg = ":ok_hand: Added you to " + role_to_assign.name + " ." except discord.DiscordException: msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." await client.send_message(message.channel, msg) else: pass
import discord import shlex from modules.botModule import BotModule class Roles(BotModule): name = 'Roles' description = 'Allow for the assignment and removal of roles.' help_text = 'Usage: `!roles "role_name"`. This will add you to that role if allowed.' ' Executing it when you already have the role assigned will remove you' ' from that role.') trigger_string = '!role' # String to listen for as trigger async def parse_command(self, message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg = shlex.split(message.content) role = [i for i, x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is role_to_assign = message.server.roles[role[0]] if len(msg) != 1: try: if role_to_assign in message.author.roles: await client.remove_roles(message.author, role_to_assign) msg = ":ok_hand: Removed you from " + role_to_assign.name + " ." else: await client.add_roles(message.author, role_to_assign) msg = ":ok_hand: Added you to " + role_to_assign.name + " ." except discord.DiscordException: msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." await client.send_message(message.channel, msg) else: pass
Add help text for Roles module.
Add help text for Roles module.
Python
mit
suclearnub/scubot
python
## Code Before: import discord import shlex from modules.botModule import BotModule class Roles(BotModule): name = 'Roles' description = 'Allow for the assignment and removal of roles.' help_text = '' trigger_string = '!role' # String to listen for as trigger async def parse_command(self, message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg = shlex.split(message.content) role = [i for i, x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is role_to_assign = message.server.roles[role[0]] if len(msg) != 1: try: if role_to_assign in message.author.roles: await client.remove_roles(message.author, role_to_assign) msg = ":ok_hand: Removed you from " + role_to_assign.name + " ." else: await client.add_roles(message.author, role_to_assign) msg = ":ok_hand: Added you to " + role_to_assign.name + " ." except discord.DiscordException: msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." await client.send_message(message.channel, msg) else: pass ## Instruction: Add help text for Roles module. ## Code After: import discord import shlex from modules.botModule import BotModule class Roles(BotModule): name = 'Roles' description = 'Allow for the assignment and removal of roles.' help_text = 'Usage: `!roles "role_name"`. This will add you to that role if allowed.' ' Executing it when you already have the role assigned will remove you' ' from that role.') trigger_string = '!role' # String to listen for as trigger async def parse_command(self, message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg = shlex.split(message.content) role = [i for i, x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is role_to_assign = message.server.roles[role[0]] if len(msg) != 1: try: if role_to_assign in message.author.roles: await client.remove_roles(message.author, role_to_assign) msg = ":ok_hand: Removed you from " + role_to_assign.name + " ." else: await client.add_roles(message.author, role_to_assign) msg = ":ok_hand: Added you to " + role_to_assign.name + " ." except discord.DiscordException: msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." await client.send_message(message.channel, msg) else: pass
# ... existing code ... description = 'Allow for the assignment and removal of roles.' help_text = 'Usage: `!roles "role_name"`. This will add you to that role if allowed.' ' Executing it when you already have the role assigned will remove you' ' from that role.') trigger_string = '!role' # String to listen for as trigger # ... rest of the code ...
d2f4766e51948a106009df83c79551b20d1e46d2
OutlawEditor/src/main/java/org/badvision/outlaweditor/data/DataUtilities.java
OutlawEditor/src/main/java/org/badvision/outlaweditor/data/DataUtilities.java
package org.badvision.outlaweditor.data; import java.util.List; import org.badvision.outlaweditor.Application; import org.badvision.outlaweditor.data.xml.Global; import org.badvision.outlaweditor.data.xml.NamedEntity; public class DataUtilities { public static void ensureGlobalExists() { if (Application.gameData.getGlobal() == null) { Application.gameData.setGlobal(new Global()); } } public static void sortNamedEntities(List<? extends NamedEntity> entities) { if (entities == null) { return; } entities.sort((a,b)->{ String nameA = a == null ? "" : nullSafe(a.getName()); String nameB = b == null ? "" : nullSafe(b.getName()); return nameA.compareTo(nameB); }); } public static String nullSafe(String str) { if (str == null) return ""; return str; } public static String uppercaseFirst(String str) { StringBuilder b = new StringBuilder(str); int i = 0; do { b.replace(i, i + 1, b.substring(i, i + 1).toUpperCase()); i = b.indexOf(" ", i) + 1; } while (i > 0 && i < b.length()); return b.toString(); } }
package org.badvision.outlaweditor.data; import java.util.List; import org.badvision.outlaweditor.Application; import org.badvision.outlaweditor.data.xml.Global; import org.badvision.outlaweditor.data.xml.NamedEntity; public class DataUtilities { public static void ensureGlobalExists() { if (Application.gameData.getGlobal() == null) { Application.gameData.setGlobal(new Global()); } } public static void sortNamedEntities(List<? extends NamedEntity> entities) { if (entities == null) { return; } entities.sort((a,b)->{ String nameA = a == null ? "" : nullSafe(a.getName()); String nameB = b == null ? "" : nullSafe(b.getName()); if (nameA.equalsIgnoreCase("init")) return -1; if (nameB.equalsIgnoreCase("init")) return 1; return nameA.compareTo(nameB); }); } public static String nullSafe(String str) { if (str == null) return ""; return str; } public static String uppercaseFirst(String str) { StringBuilder b = new StringBuilder(str); int i = 0; do { b.replace(i, i + 1, b.substring(i, i + 1).toUpperCase()); i = b.indexOf(" ", i) + 1; } while (i > 0 && i < b.length()); return b.toString(); } }
Put "init" as the topmost item in the sort again
Put "init" as the topmost item in the sort again
Java
apache-2.0
badvision/lawless-legends,badvision/lawless-legends,badvision/lawless-legends,badvision/lawless-legends,badvision/lawless-legends,badvision/lawless-legends,badvision/lawless-legends
java
## Code Before: package org.badvision.outlaweditor.data; import java.util.List; import org.badvision.outlaweditor.Application; import org.badvision.outlaweditor.data.xml.Global; import org.badvision.outlaweditor.data.xml.NamedEntity; public class DataUtilities { public static void ensureGlobalExists() { if (Application.gameData.getGlobal() == null) { Application.gameData.setGlobal(new Global()); } } public static void sortNamedEntities(List<? extends NamedEntity> entities) { if (entities == null) { return; } entities.sort((a,b)->{ String nameA = a == null ? "" : nullSafe(a.getName()); String nameB = b == null ? "" : nullSafe(b.getName()); return nameA.compareTo(nameB); }); } public static String nullSafe(String str) { if (str == null) return ""; return str; } public static String uppercaseFirst(String str) { StringBuilder b = new StringBuilder(str); int i = 0; do { b.replace(i, i + 1, b.substring(i, i + 1).toUpperCase()); i = b.indexOf(" ", i) + 1; } while (i > 0 && i < b.length()); return b.toString(); } } ## Instruction: Put "init" as the topmost item in the sort again ## Code After: package org.badvision.outlaweditor.data; import java.util.List; import org.badvision.outlaweditor.Application; import org.badvision.outlaweditor.data.xml.Global; import org.badvision.outlaweditor.data.xml.NamedEntity; public class DataUtilities { public static void ensureGlobalExists() { if (Application.gameData.getGlobal() == null) { Application.gameData.setGlobal(new Global()); } } public static void sortNamedEntities(List<? extends NamedEntity> entities) { if (entities == null) { return; } entities.sort((a,b)->{ String nameA = a == null ? "" : nullSafe(a.getName()); String nameB = b == null ? "" : nullSafe(b.getName()); if (nameA.equalsIgnoreCase("init")) return -1; if (nameB.equalsIgnoreCase("init")) return 1; return nameA.compareTo(nameB); }); } public static String nullSafe(String str) { if (str == null) return ""; return str; } public static String uppercaseFirst(String str) { StringBuilder b = new StringBuilder(str); int i = 0; do { b.replace(i, i + 1, b.substring(i, i + 1).toUpperCase()); i = b.indexOf(" ", i) + 1; } while (i > 0 && i < b.length()); return b.toString(); } }
// ... existing code ... entities.sort((a,b)->{ String nameA = a == null ? "" : nullSafe(a.getName()); String nameB = b == null ? "" : nullSafe(b.getName()); if (nameA.equalsIgnoreCase("init")) return -1; if (nameB.equalsIgnoreCase("init")) return 1; return nameA.compareTo(nameB); }); } // ... rest of the code ...
e005a5a1d10df7a5a2f6a599c3419c89bd61eeb2
mrbelvedereci/cumulusci/admin.py
mrbelvedereci/cumulusci/admin.py
from django.contrib import admin from mrbelvedereci.cumulusci.models import Org from mrbelvedereci.cumulusci.models import Service class OrgAdmin(admin.ModelAdmin): list_display = ('name','repo','scratch') list_filter = ('repo','scratch') admin.site.register(Org, OrgAdmin) class ServiceAdmin(admin.ModelAdmin): list_display = ('name',) admin.site.register(Service, ServiceAdmin)
from django.contrib import admin from mrbelvedereci.cumulusci.models import Org from mrbelvedereci.cumulusci.models import Service class OrgAdmin(admin.ModelAdmin): list_display = ('name','repo','scratch') list_filter = ('name', 'scratch', 'repo') admin.site.register(Org, OrgAdmin) class ServiceAdmin(admin.ModelAdmin): list_display = ('name',) admin.site.register(Service, ServiceAdmin)
Add filters to Org model
Add filters to Org model
Python
bsd-3-clause
SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci
python
## Code Before: from django.contrib import admin from mrbelvedereci.cumulusci.models import Org from mrbelvedereci.cumulusci.models import Service class OrgAdmin(admin.ModelAdmin): list_display = ('name','repo','scratch') list_filter = ('repo','scratch') admin.site.register(Org, OrgAdmin) class ServiceAdmin(admin.ModelAdmin): list_display = ('name',) admin.site.register(Service, ServiceAdmin) ## Instruction: Add filters to Org model ## Code After: from django.contrib import admin from mrbelvedereci.cumulusci.models import Org from mrbelvedereci.cumulusci.models import Service class OrgAdmin(admin.ModelAdmin): list_display = ('name','repo','scratch') list_filter = ('name', 'scratch', 'repo') admin.site.register(Org, OrgAdmin) class ServiceAdmin(admin.ModelAdmin): list_display = ('name',) admin.site.register(Service, ServiceAdmin)
# ... existing code ... class OrgAdmin(admin.ModelAdmin): list_display = ('name','repo','scratch') list_filter = ('name', 'scratch', 'repo') admin.site.register(Org, OrgAdmin) class ServiceAdmin(admin.ModelAdmin): # ... rest of the code ...
1c14c4ac824f2242cc8beeb14f836ee4a9e030cc
src/main/kotlin/main/main.kt
src/main/kotlin/main/main.kt
package main /** * Created by allen on 7/28/16. */ import spark.Spark.* import com.google.gson.Gson import controllers.SqliteController import models.User import spark.ModelAndView import spark.template.handlebars.HandlebarsTemplateEngine import java.util.* fun main(args : Array<String>) { port(3000) staticFiles.location("/public"); //gzip everything after({req, res -> res.header("Content-Encoding", "gzip") }) //used to parse and convert JSON val gson = Gson() val templateEngine = HandlebarsTemplateEngine() // SqliteController.selectAllAlbums() get("/", { req, res -> ModelAndView(hashMapOf(Pair("name", "Test")), "index.hbs") }, templateEngine) get("/hello/:name", { req, res -> ModelAndView(hashMapOf(Pair("name", req.params(":name"))), "index.hbs") }, templateEngine) get("/user/:first/:last/json", { req, res -> User(req.params(":first"), req.params(":last")) }, { gson.toJson(it) }) get("/api/albums", { req, res -> SqliteController.selectAllAlbums() }, { gson.toJson(it) }) get("/api/albums/:id/images", { req, res -> SqliteController.imagesForAlbum(req.params(":id")) }, { gson.toJson(it) }) }
package main /** * Created by allen on 7/28/16. */ import spark.Spark.* import com.google.gson.Gson import controllers.SqliteController import models.User import spark.ModelAndView import spark.template.handlebars.HandlebarsTemplateEngine import java.util.* fun main(args : Array<String>) { port(3000) staticFiles.location("/public") //allow routes to match with trailing slash before({ req, res -> val path = req.pathInfo() if (path.endsWith("/")){ res.redirect(path.substring(0, path.length - 1)) } }) //gzip everything after({req, res -> res.header("Content-Encoding", "gzip") }) //used to parse and convert JSON val gson = Gson() val templateEngine = HandlebarsTemplateEngine() // SqliteController.selectAllAlbums() get("/", { req, res -> ModelAndView(hashMapOf(Pair("name", "Test")), "index.hbs") }, templateEngine) get("/hello/:name", { req, res -> ModelAndView(hashMapOf(Pair("name", req.params(":name"))), "index.hbs") }, templateEngine) get("/user/:first/:last/json", { req, res -> User(req.params(":first"), req.params(":last")) }, { gson.toJson(it) }) get("/api/albums", { req, res -> SqliteController.selectAllAlbums() }, { gson.toJson(it) }) get("/api/albums/:id/images", { req, res -> SqliteController.imagesForAlbum(req.params(":id")) }, { gson.toJson(it) }) }
Edit routes to allow matches with trailing slash
Edit routes to allow matches with trailing slash
Kotlin
mit
allen-garvey/photog-spark,allen-garvey/photog-spark,allen-garvey/photog-spark
kotlin
## Code Before: package main /** * Created by allen on 7/28/16. */ import spark.Spark.* import com.google.gson.Gson import controllers.SqliteController import models.User import spark.ModelAndView import spark.template.handlebars.HandlebarsTemplateEngine import java.util.* fun main(args : Array<String>) { port(3000) staticFiles.location("/public"); //gzip everything after({req, res -> res.header("Content-Encoding", "gzip") }) //used to parse and convert JSON val gson = Gson() val templateEngine = HandlebarsTemplateEngine() // SqliteController.selectAllAlbums() get("/", { req, res -> ModelAndView(hashMapOf(Pair("name", "Test")), "index.hbs") }, templateEngine) get("/hello/:name", { req, res -> ModelAndView(hashMapOf(Pair("name", req.params(":name"))), "index.hbs") }, templateEngine) get("/user/:first/:last/json", { req, res -> User(req.params(":first"), req.params(":last")) }, { gson.toJson(it) }) get("/api/albums", { req, res -> SqliteController.selectAllAlbums() }, { gson.toJson(it) }) get("/api/albums/:id/images", { req, res -> SqliteController.imagesForAlbum(req.params(":id")) }, { gson.toJson(it) }) } ## Instruction: Edit routes to allow matches with trailing slash ## Code After: package main /** * Created by allen on 7/28/16. */ import spark.Spark.* import com.google.gson.Gson import controllers.SqliteController import models.User import spark.ModelAndView import spark.template.handlebars.HandlebarsTemplateEngine import java.util.* fun main(args : Array<String>) { port(3000) staticFiles.location("/public") //allow routes to match with trailing slash before({ req, res -> val path = req.pathInfo() if (path.endsWith("/")){ res.redirect(path.substring(0, path.length - 1)) } }) //gzip everything after({req, res -> res.header("Content-Encoding", "gzip") }) //used to parse and convert JSON val gson = Gson() val templateEngine = HandlebarsTemplateEngine() // SqliteController.selectAllAlbums() get("/", { req, res -> ModelAndView(hashMapOf(Pair("name", "Test")), "index.hbs") }, templateEngine) get("/hello/:name", { req, res -> ModelAndView(hashMapOf(Pair("name", req.params(":name"))), "index.hbs") }, templateEngine) get("/user/:first/:last/json", { req, res -> User(req.params(":first"), req.params(":last")) }, { gson.toJson(it) }) get("/api/albums", { req, res -> SqliteController.selectAllAlbums() }, { gson.toJson(it) }) get("/api/albums/:id/images", { req, res -> SqliteController.imagesForAlbum(req.params(":id")) }, { gson.toJson(it) }) }
// ... existing code ... fun main(args : Array<String>) { port(3000) staticFiles.location("/public") //allow routes to match with trailing slash before({ req, res -> val path = req.pathInfo() if (path.endsWith("/")){ res.redirect(path.substring(0, path.length - 1)) } }) //gzip everything after({req, res -> // ... rest of the code ...
8b545ee63ec695a77ba08fa5ff45b7d6dd3d94f8
cuteshop/downloaders/git.py
cuteshop/downloaders/git.py
import subprocess from ..utils import DEVNULL, change_working_directory from .base import DOWNLOAD_CONTAINER def download(source_info): url = source_info['git'] subprocess.call( ('git', 'clone', url, DOWNLOAD_CONTAINER), stdout=DEVNULL, stderr=subprocess.STDOUT, ) if 'tag' in source_info: with change_working_directory(DOWNLOAD_CONTAINER): subprocess.call( ('git', 'checkout', source_info['tag']), stdout=DEVNULL, stderr=subprocess.STDOUT, )
import subprocess from ..utils import DEVNULL, change_working_directory from .base import DOWNLOAD_CONTAINER def _checkout(name): with change_working_directory(DOWNLOAD_CONTAINER): subprocess.call( ('git', 'checkout', name), stdout=DEVNULL, stderr=subprocess.STDOUT, ) def download(source_info): url = source_info['git'] subprocess.call( ('git', 'clone', url, DOWNLOAD_CONTAINER), stdout=DEVNULL, stderr=subprocess.STDOUT, ) if 'tag' in source_info: _checkout(source_info['tag']) elif 'branch' in source_info: _checkout(source_info['branch'])
Add auto branch checkout functionality
Add auto branch checkout functionality
Python
mit
uranusjr/cuteshop
python
## Code Before: import subprocess from ..utils import DEVNULL, change_working_directory from .base import DOWNLOAD_CONTAINER def download(source_info): url = source_info['git'] subprocess.call( ('git', 'clone', url, DOWNLOAD_CONTAINER), stdout=DEVNULL, stderr=subprocess.STDOUT, ) if 'tag' in source_info: with change_working_directory(DOWNLOAD_CONTAINER): subprocess.call( ('git', 'checkout', source_info['tag']), stdout=DEVNULL, stderr=subprocess.STDOUT, ) ## Instruction: Add auto branch checkout functionality ## Code After: import subprocess from ..utils import DEVNULL, change_working_directory from .base import DOWNLOAD_CONTAINER def _checkout(name): with change_working_directory(DOWNLOAD_CONTAINER): subprocess.call( ('git', 'checkout', name), stdout=DEVNULL, stderr=subprocess.STDOUT, ) def download(source_info): url = source_info['git'] subprocess.call( ('git', 'clone', url, DOWNLOAD_CONTAINER), stdout=DEVNULL, stderr=subprocess.STDOUT, ) if 'tag' in source_info: _checkout(source_info['tag']) elif 'branch' in source_info: _checkout(source_info['branch'])
# ... existing code ... import subprocess from ..utils import DEVNULL, change_working_directory from .base import DOWNLOAD_CONTAINER def _checkout(name): with change_working_directory(DOWNLOAD_CONTAINER): subprocess.call( ('git', 'checkout', name), stdout=DEVNULL, stderr=subprocess.STDOUT, ) def download(source_info): # ... modified code ... stdout=DEVNULL, stderr=subprocess.STDOUT, ) if 'tag' in source_info: _checkout(source_info['tag']) elif 'branch' in source_info: _checkout(source_info['branch']) # ... rest of the code ...
3e913e4267fd7750516edcbed1aa687e0cbd17fe
edx_repo_tools/oep2/__init__.py
edx_repo_tools/oep2/__init__.py
import click from . import explode_repos_yaml from .report import cli def _cli(): cli(auto_envvar_prefix="OEP2") @click.group() def cli(): """ Tools for implementing and enforcing OEP-2. """ pass cli.add_command(explode_repos_yaml.explode) cli.add_command(explode_repos_yaml.implode) cli.add_command(cli.cli, 'report')
import click from . import explode_repos_yaml from .report.cli import cli as report_cli def _cli(): cli(auto_envvar_prefix="OEP2") @click.group() def cli(): """ Tools for implementing and enforcing OEP-2. """ pass cli.add_command(explode_repos_yaml.explode) cli.add_command(explode_repos_yaml.implode) cli.add_command(report_cli, 'report')
Make oep-2 checker run again
Make oep-2 checker run again
Python
apache-2.0
edx/repo-tools,edx/repo-tools
python
## Code Before: import click from . import explode_repos_yaml from .report import cli def _cli(): cli(auto_envvar_prefix="OEP2") @click.group() def cli(): """ Tools for implementing and enforcing OEP-2. """ pass cli.add_command(explode_repos_yaml.explode) cli.add_command(explode_repos_yaml.implode) cli.add_command(cli.cli, 'report') ## Instruction: Make oep-2 checker run again ## Code After: import click from . import explode_repos_yaml from .report.cli import cli as report_cli def _cli(): cli(auto_envvar_prefix="OEP2") @click.group() def cli(): """ Tools for implementing and enforcing OEP-2. """ pass cli.add_command(explode_repos_yaml.explode) cli.add_command(explode_repos_yaml.implode) cli.add_command(report_cli, 'report')
# ... existing code ... import click from . import explode_repos_yaml from .report.cli import cli as report_cli def _cli(): # ... modified code ... cli.add_command(explode_repos_yaml.explode) cli.add_command(explode_repos_yaml.implode) cli.add_command(report_cli, 'report') # ... rest of the code ...
b0e44fcca09a2d62ea0dc217d1538e03d48e2558
setup.py
setup.py
from setuptools import setup, find_packages from buildcmds.addon import addon setup( name='io_scene_previz', # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html version='0.0.7', description='Blender Previz addon', url='https://app.previz.co', author='Previz', author_email='[email protected]', license='MIT', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Multimedia :: Graphics :: 3D Modeling', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', ], keywords='previz development 3d scene exporter', packages=find_packages(exclude=['tests']), install_requires=['previz'], extras_require={}, package_data={}, data_files=[], cmdclass={ 'addon': addon } )
from setuptools import setup, find_packages from buildcmds.addon import bdist_blender_addon setup( name='io_scene_previz', # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html version='0.0.7', description='Blender Previz addon', url='https://app.previz.co', author='Previz', author_email='[email protected]', license='MIT', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Multimedia :: Graphics :: 3D Modeling', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', ], keywords='previz development 3d scene exporter', packages=find_packages(exclude=['buildcmds', 'tests']), install_requires=['previz'], extras_require={}, package_data={}, data_files=[], cmdclass={ 'bdist_blender_addon': bdist_blender_addon } )
Rename command addon to bdist_blender_addon
Rename command addon to bdist_blender_addon
Python
mit
Previz-app/io_scene_dnb_previz,Previz-app/io_scene_previz,Previz-app/io_scene_previz,Previz-app/io_scene_dnb_previz
python
## Code Before: from setuptools import setup, find_packages from buildcmds.addon import addon setup( name='io_scene_previz', # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html version='0.0.7', description='Blender Previz addon', url='https://app.previz.co', author='Previz', author_email='[email protected]', license='MIT', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Multimedia :: Graphics :: 3D Modeling', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', ], keywords='previz development 3d scene exporter', packages=find_packages(exclude=['tests']), install_requires=['previz'], extras_require={}, package_data={}, data_files=[], cmdclass={ 'addon': addon } ) ## Instruction: Rename command addon to bdist_blender_addon ## Code After: from setuptools import setup, find_packages from buildcmds.addon import bdist_blender_addon setup( name='io_scene_previz', # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html version='0.0.7', description='Blender Previz addon', url='https://app.previz.co', author='Previz', author_email='[email protected]', license='MIT', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Multimedia :: Graphics :: 3D Modeling', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', ], keywords='previz development 3d scene exporter', packages=find_packages(exclude=['buildcmds', 'tests']), install_requires=['previz'], extras_require={}, package_data={}, data_files=[], cmdclass={ 'bdist_blender_addon': bdist_blender_addon } )
// ... existing code ... from setuptools import setup, find_packages from buildcmds.addon import bdist_blender_addon setup( name='io_scene_previz', // ... modified code ... ], keywords='previz development 3d scene exporter', packages=find_packages(exclude=['buildcmds', 'tests']), install_requires=['previz'], extras_require={}, package_data={}, data_files=[], cmdclass={ 'bdist_blender_addon': bdist_blender_addon } ) // ... rest of the code ...
ebf9628a55a82daa489f2bd5e2d83f2218369f01
controllers/accounts_manager.py
controllers/accounts_manager.py
from flask_restful import Resource class AccountsManager(Resource): """docstring for AccountsManager.""" def get(self): return {"route": "login"} def post(self): return {"route": "register"}
from flask import jsonify, make_response from flask_restful import Resource, reqparse from app.models import User from app.db_instance import save from validator import validate class AccountsManager(Resource): """docstring for AccountsManager.""" def __init__(self): self.parser = reqparse.RequestParser() self.parser.add_argument('username', type=str, required=True, help="username is required") self.parser.add_argument('password', type=str, required=True, help="password is required") def post(self): args = self.parser.parse_args(strict=True) username = args.get("username") password = args.get("password") if any(arg == "" for arg in [username, password]): message = "username and password is required" status = 400 elif not username.isalpha(): message = "username should not contain special characters" status = 400 elif len(password) < 6: message = "password should be more than 6 characters" status = 400 elif User.query.filter_by(username=username).first(): message = "username already exists" status = 409 else: user = User(username, password) save(user) message = "user registered successfully" status = 201 return make_response(jsonify({ "message": message }), status)
Add Register resource to handle user registration and save user data to the database
Add Register resource to handle user registration and save user data to the database
Python
mit
brayoh/bucket-list-api
python
## Code Before: from flask_restful import Resource class AccountsManager(Resource): """docstring for AccountsManager.""" def get(self): return {"route": "login"} def post(self): return {"route": "register"} ## Instruction: Add Register resource to handle user registration and save user data to the database ## Code After: from flask import jsonify, make_response from flask_restful import Resource, reqparse from app.models import User from app.db_instance import save from validator import validate class AccountsManager(Resource): """docstring for AccountsManager.""" def __init__(self): self.parser = reqparse.RequestParser() self.parser.add_argument('username', type=str, required=True, help="username is required") self.parser.add_argument('password', type=str, required=True, help="password is required") def post(self): args = self.parser.parse_args(strict=True) username = args.get("username") password = args.get("password") if any(arg == "" for arg in [username, password]): message = "username and password is required" status = 400 elif not username.isalpha(): message = "username should not contain special characters" status = 400 elif len(password) < 6: message = "password should be more than 6 characters" status = 400 elif User.query.filter_by(username=username).first(): message = "username already exists" status = 409 else: user = User(username, password) save(user) message = "user registered successfully" status = 201 return make_response(jsonify({ "message": message }), status)
... from flask import jsonify, make_response from flask_restful import Resource, reqparse from app.models import User from app.db_instance import save from validator import validate class AccountsManager(Resource): """docstring for AccountsManager.""" def __init__(self): self.parser = reqparse.RequestParser() self.parser.add_argument('username', type=str, required=True, help="username is required") self.parser.add_argument('password', type=str, required=True, help="password is required") def post(self): args = self.parser.parse_args(strict=True) username = args.get("username") password = args.get("password") if any(arg == "" for arg in [username, password]): message = "username and password is required" status = 400 elif not username.isalpha(): message = "username should not contain special characters" status = 400 elif len(password) < 6: message = "password should be more than 6 characters" status = 400 elif User.query.filter_by(username=username).first(): message = "username already exists" status = 409 else: user = User(username, password) save(user) message = "user registered successfully" status = 201 return make_response(jsonify({ "message": message }), status) ...
e5b42db249dd94a0d7652881a8bba8ed78772d3e
examples/turnAndMove.py
examples/turnAndMove.py
import slither, pygame snakey = slither.Sprite() snakey.setCostumeByName("costume0") snakey.goto(0, 0) slither.slitherStage.setColor(40, 222, 40) slither.setup() # Begin slither def handlequit(): print("Quitting...") return True slither.registerCallback(pygame.QUIT, handlequit) # This uses the direct call form @slither.registerCallback(pygame.MOUSEBUTTONUP) # This uses the decorator form def handlemouseup(event): print("Mouseup:", event.pos, event.button) def run_a_frame(): snakey.xpos += 1 snakey.ypos += 1 snakey.direction += 1 slither.runMainLoop(run_a_frame)
import slither, pygame snakey = slither.Sprite() snakey.setCostumeByName("costume0") snakey.goto(0, 0) slither.setup() # Begin slither def handlequit(): print("Quitting...") return True slither.registerCallback(pygame.QUIT, handlequit) # This uses the direct call form @slither.registerCallback(pygame.MOUSEBUTTONUP) # This uses the decorator form def handlemouseup(event): print("Mouseup:", event.pos, event.button) def run_a_frame(): snakey.xpos += 1 snakey.ypos += 1 snakey.direction += 1 slither.runMainLoop(run_a_frame)
Fix small test problem\nBTW rotation works now, thanks @BookOwl
Fix small test problem\nBTW rotation works now, thanks @BookOwl
Python
mit
PySlither/Slither,PySlither/Slither
python
## Code Before: import slither, pygame snakey = slither.Sprite() snakey.setCostumeByName("costume0") snakey.goto(0, 0) slither.slitherStage.setColor(40, 222, 40) slither.setup() # Begin slither def handlequit(): print("Quitting...") return True slither.registerCallback(pygame.QUIT, handlequit) # This uses the direct call form @slither.registerCallback(pygame.MOUSEBUTTONUP) # This uses the decorator form def handlemouseup(event): print("Mouseup:", event.pos, event.button) def run_a_frame(): snakey.xpos += 1 snakey.ypos += 1 snakey.direction += 1 slither.runMainLoop(run_a_frame) ## Instruction: Fix small test problem\nBTW rotation works now, thanks @BookOwl ## Code After: import slither, pygame snakey = slither.Sprite() snakey.setCostumeByName("costume0") snakey.goto(0, 0) slither.setup() # Begin slither def handlequit(): print("Quitting...") return True slither.registerCallback(pygame.QUIT, handlequit) # This uses the direct call form @slither.registerCallback(pygame.MOUSEBUTTONUP) # This uses the decorator form def handlemouseup(event): print("Mouseup:", event.pos, event.button) def run_a_frame(): snakey.xpos += 1 snakey.ypos += 1 snakey.direction += 1 slither.runMainLoop(run_a_frame)
... snakey.setCostumeByName("costume0") snakey.goto(0, 0) slither.setup() # Begin slither ...
ffd917c5ace8e815b185495aec17cf47b0a7648a
storage_service/administration/tests/test_languages.py
storage_service/administration/tests/test_languages.py
from django.contrib.auth.models import User from django.test import TestCase, override_settings class TestLanguageSwitching(TestCase): @classmethod def setUpClass(cls): User.objects.create_user( username="admin", password="admin", email="[email protected]" ) super(TestLanguageSwitching, cls).setUpClass() def setUp(self): self.client.login(username="admin", password="admin") def test_displays_language_form(self): self.client.get("/administration/language/") self.assertTemplateUsed("language_form.html") @override_settings(LANGUAGE_CODE="es") def test_selects_correct_language_on_form(self): response = self.client.get("/administration/language/") assert response.context["language_selection"] == "es" @override_settings(LANGUAGE_CODE="es-es") def test_falls_back_to_generic_language(self): response = self.client.get("/administration/language/") assert response.context["language_selection"] == "es" @override_settings(LANGUAGE_CODE="en-us") def test_switch_language(self): response = self.client.post( "/i18n/setlang/", {"language": "fr", "next": "/administration/language/"}, follow=True, ) assert response.context["language_selection"] == "fr"
from django.contrib.auth.models import User from django.test import TestCase, override_settings class TestLanguageSwitching(TestCase): @classmethod def setUpClass(cls): super(TestLanguageSwitching, cls).setUpClass() User.objects.create_user( username="admin", password="admin", email="[email protected]" ) def setUp(self): self.client.login(username="admin", password="admin") def test_displays_language_form(self): self.client.get("/administration/language/") self.assertTemplateUsed("language_form.html") @override_settings(LANGUAGE_CODE="es") def test_selects_correct_language_on_form(self): response = self.client.get("/administration/language/") assert response.context["language_selection"] == "es" @override_settings(LANGUAGE_CODE="es-es") def test_falls_back_to_generic_language(self): response = self.client.get("/administration/language/") assert response.context["language_selection"] == "es" @override_settings(LANGUAGE_CODE="en-us") def test_switch_language(self): response = self.client.post( "/i18n/setlang/", {"language": "fr", "next": "/administration/language/"}, follow=True, ) assert response.context["language_selection"] == "fr"
Fix integrity error reusing db in tests
Fix integrity error reusing db in tests Base `setUpClass` needs to be called first so the transaction is initialized before we mutate the data. This solves a conflic raised when using `--reuse-db`.
Python
agpl-3.0
artefactual/archivematica-storage-service,artefactual/archivematica-storage-service,artefactual/archivematica-storage-service,artefactual/archivematica-storage-service
python
## Code Before: from django.contrib.auth.models import User from django.test import TestCase, override_settings class TestLanguageSwitching(TestCase): @classmethod def setUpClass(cls): User.objects.create_user( username="admin", password="admin", email="[email protected]" ) super(TestLanguageSwitching, cls).setUpClass() def setUp(self): self.client.login(username="admin", password="admin") def test_displays_language_form(self): self.client.get("/administration/language/") self.assertTemplateUsed("language_form.html") @override_settings(LANGUAGE_CODE="es") def test_selects_correct_language_on_form(self): response = self.client.get("/administration/language/") assert response.context["language_selection"] == "es" @override_settings(LANGUAGE_CODE="es-es") def test_falls_back_to_generic_language(self): response = self.client.get("/administration/language/") assert response.context["language_selection"] == "es" @override_settings(LANGUAGE_CODE="en-us") def test_switch_language(self): response = self.client.post( "/i18n/setlang/", {"language": "fr", "next": "/administration/language/"}, follow=True, ) assert response.context["language_selection"] == "fr" ## Instruction: Fix integrity error reusing db in tests Base `setUpClass` needs to be called first so the transaction is initialized before we mutate the data. This solves a conflic raised when using `--reuse-db`. ## Code After: from django.contrib.auth.models import User from django.test import TestCase, override_settings class TestLanguageSwitching(TestCase): @classmethod def setUpClass(cls): super(TestLanguageSwitching, cls).setUpClass() User.objects.create_user( username="admin", password="admin", email="[email protected]" ) def setUp(self): self.client.login(username="admin", password="admin") def test_displays_language_form(self): self.client.get("/administration/language/") self.assertTemplateUsed("language_form.html") @override_settings(LANGUAGE_CODE="es") def test_selects_correct_language_on_form(self): response = self.client.get("/administration/language/") assert response.context["language_selection"] == "es" @override_settings(LANGUAGE_CODE="es-es") def test_falls_back_to_generic_language(self): response = self.client.get("/administration/language/") assert response.context["language_selection"] == "es" @override_settings(LANGUAGE_CODE="en-us") def test_switch_language(self): response = self.client.post( "/i18n/setlang/", {"language": "fr", "next": "/administration/language/"}, follow=True, ) assert response.context["language_selection"] == "fr"
... class TestLanguageSwitching(TestCase): @classmethod def setUpClass(cls): super(TestLanguageSwitching, cls).setUpClass() User.objects.create_user( username="admin", password="admin", email="[email protected]" ) def setUp(self): self.client.login(username="admin", password="admin") ...
456de4b1184780b9179ee9e6572a3f62cf22550a
tests/test_tools/simple_project.py
tests/test_tools/simple_project.py
project_1_yaml = { 'common': { 'sources': ['sources/main.cpp'], 'includes': ['includes/header1.h'], 'target': ['mbed-lpc1768'] } } projects_1_yaml = { 'projects': { 'project_1' : ['test_workspace/project_1.yaml'] }, }
project_1_yaml = { 'common': { 'sources': ['sources/main.cpp'], 'includes': ['includes/header1.h'], 'target': ['mbed-lpc1768'], 'linker_file': ['linker_script'], } } projects_1_yaml = { 'projects': { 'project_1' : ['test_workspace/project_1.yaml'] }, }
Test - add linker script for tools project
Test - add linker script for tools project
Python
apache-2.0
molejar/project_generator,hwfwgrp/project_generator,0xc0170/project_generator,sarahmarshy/project_generator,ohagendorf/project_generator,project-generator/project_generator
python
## Code Before: project_1_yaml = { 'common': { 'sources': ['sources/main.cpp'], 'includes': ['includes/header1.h'], 'target': ['mbed-lpc1768'] } } projects_1_yaml = { 'projects': { 'project_1' : ['test_workspace/project_1.yaml'] }, } ## Instruction: Test - add linker script for tools project ## Code After: project_1_yaml = { 'common': { 'sources': ['sources/main.cpp'], 'includes': ['includes/header1.h'], 'target': ['mbed-lpc1768'], 'linker_file': ['linker_script'], } } projects_1_yaml = { 'projects': { 'project_1' : ['test_workspace/project_1.yaml'] }, }
# ... existing code ... 'common': { 'sources': ['sources/main.cpp'], 'includes': ['includes/header1.h'], 'target': ['mbed-lpc1768'], 'linker_file': ['linker_script'], } } # ... rest of the code ...
641bd133eb97b90bbcef8acac8bb75f8d6d79051
mage/src/main/java/mil/nga/giat/mage/form/FormState.kt
mage/src/main/java/mil/nga/giat/mage/form/FormState.kt
package mil.nga.giat.mage.form import androidx.compose.runtime.mutableStateOf import mil.nga.giat.mage.form.field.FieldState import mil.nga.giat.mage.form.field.FieldValue class FormState( val id: Long? = null, val remoteId: String? = null, val eventId: String, val definition: Form, val fields: List<FieldState<*, *>>, expanded: Boolean = false, ) { val expanded = mutableStateOf(expanded) fun isValid(): Boolean { var valid = true for (fieldState in fields) { if (!fieldState.isValid) { fieldState.isFocusedDirty = true fieldState.enableShowErrors() valid = false } } return valid } companion object { fun fromForm(id: Long? = null, remoteId: String? = null, eventId: String, form: Form, defaultForm: Form? = null): FormState { val defaultFields = defaultForm?.fields?.associateTo(mutableMapOf()) { it.name to it.value } val fields = mutableListOf<FieldState<*, out FieldValue>>() for (field in form.fields) { val fieldState = FieldState.fromFormField(field, field.value, defaultFields?.get(field.name)) fields.add(fieldState) } return FormState(id, remoteId, eventId, form, fields) } } }
package mil.nga.giat.mage.form import androidx.compose.runtime.mutableStateOf import mil.nga.giat.mage.form.field.FieldState import mil.nga.giat.mage.form.field.FieldValue class FormState( val id: Long? = null, val remoteId: String? = null, val eventId: String, val definition: Form, val fields: List<FieldState<*, *>>, expanded: Boolean = false, ) { val expanded = mutableStateOf(expanded) fun isValid(): Boolean { var valid = true for (fieldState in fields) { if (!fieldState.isValid) { fieldState.isFocusedDirty = true fieldState.enableShowErrors() valid = false } } return valid } companion object { fun fromForm(remoteId: String? = null, eventId: String, form: Form, defaultForm: Form? = null): FormState { val defaultFields = defaultForm?.fields?.associateTo(mutableMapOf()) { it.name to it.value } val fields = mutableListOf<FieldState<*, out FieldValue>>() for (field in form.fields) { val fieldState = FieldState.fromFormField(field, field.value, defaultFields?.get(field.name)) fields.add(fieldState) } return FormState(form.id, remoteId, eventId, form, fields) } } }
Fix observation create mapview update
Fix observation create mapview update
Kotlin
apache-2.0
ngageoint/mage-android,ngageoint/mage-android
kotlin
## Code Before: package mil.nga.giat.mage.form import androidx.compose.runtime.mutableStateOf import mil.nga.giat.mage.form.field.FieldState import mil.nga.giat.mage.form.field.FieldValue class FormState( val id: Long? = null, val remoteId: String? = null, val eventId: String, val definition: Form, val fields: List<FieldState<*, *>>, expanded: Boolean = false, ) { val expanded = mutableStateOf(expanded) fun isValid(): Boolean { var valid = true for (fieldState in fields) { if (!fieldState.isValid) { fieldState.isFocusedDirty = true fieldState.enableShowErrors() valid = false } } return valid } companion object { fun fromForm(id: Long? = null, remoteId: String? = null, eventId: String, form: Form, defaultForm: Form? = null): FormState { val defaultFields = defaultForm?.fields?.associateTo(mutableMapOf()) { it.name to it.value } val fields = mutableListOf<FieldState<*, out FieldValue>>() for (field in form.fields) { val fieldState = FieldState.fromFormField(field, field.value, defaultFields?.get(field.name)) fields.add(fieldState) } return FormState(id, remoteId, eventId, form, fields) } } } ## Instruction: Fix observation create mapview update ## Code After: package mil.nga.giat.mage.form import androidx.compose.runtime.mutableStateOf import mil.nga.giat.mage.form.field.FieldState import mil.nga.giat.mage.form.field.FieldValue class FormState( val id: Long? = null, val remoteId: String? = null, val eventId: String, val definition: Form, val fields: List<FieldState<*, *>>, expanded: Boolean = false, ) { val expanded = mutableStateOf(expanded) fun isValid(): Boolean { var valid = true for (fieldState in fields) { if (!fieldState.isValid) { fieldState.isFocusedDirty = true fieldState.enableShowErrors() valid = false } } return valid } companion object { fun fromForm(remoteId: String? = null, eventId: String, form: Form, defaultForm: Form? = null): FormState { val defaultFields = defaultForm?.fields?.associateTo(mutableMapOf()) { it.name to it.value } val fields = mutableListOf<FieldState<*, out FieldValue>>() for (field in form.fields) { val fieldState = FieldState.fromFormField(field, field.value, defaultFields?.get(field.name)) fields.add(fieldState) } return FormState(form.id, remoteId, eventId, form, fields) } } }
... } companion object { fun fromForm(remoteId: String? = null, eventId: String, form: Form, defaultForm: Form? = null): FormState { val defaultFields = defaultForm?.fields?.associateTo(mutableMapOf()) { it.name to it.value } ... fields.add(fieldState) } return FormState(form.id, remoteId, eventId, form, fields) } } } ...
7b2154cb6232a9d289a95ce79e70c590fee12d63
test/Frontend/optimization-remark-options.c
test/Frontend/optimization-remark-options.c
// RUN: %clang -O1 -fvectorize -Rpass-analysis=loop-vectorize -emit-llvm -S %s -o - 2>&1 | FileCheck %s // CHECK: {{.*}}:9:11: remark: loop not vectorized: vectorization requires changes in the order of operations, however IEEE 754 floating-point operations are not commutative; allow commutativity by specifying '#pragma clang loop vectorize(enable)' before the loop or by providing the compiler option '-ffast-math' double foo(int N) { double v = 0.0; for (int i = 0; i < N; i++) v = v + 1.0; return v; }
// RUN: %clang -O1 -fvectorize -target x86_64-unknown-unknown -Rpass-analysis=loop-vectorize -emit-llvm -S %s -o - 2>&1 | FileCheck %s // CHECK: {{.*}}:9:11: remark: loop not vectorized: vectorization requires changes in the order of operations, however IEEE 754 floating-point operations are not commutative; allow commutativity by specifying '#pragma clang loop vectorize(enable)' before the loop or by providing the compiler option '-ffast-math' double foo(int N) { double v = 0.0; for (int i = 0; i < N; i++) v = v + 1.0; return v; }
Make frontend floating-point commutivity test X86 specific to avoid cost-model related problems on arm-thumb and hexagon.
Make frontend floating-point commutivity test X86 specific to avoid cost-model related problems on arm-thumb and hexagon. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@244517 91177308-0d34-0410-b5e6-96231b3b80d8
C
apache-2.0
llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang
c
## Code Before: // RUN: %clang -O1 -fvectorize -Rpass-analysis=loop-vectorize -emit-llvm -S %s -o - 2>&1 | FileCheck %s // CHECK: {{.*}}:9:11: remark: loop not vectorized: vectorization requires changes in the order of operations, however IEEE 754 floating-point operations are not commutative; allow commutativity by specifying '#pragma clang loop vectorize(enable)' before the loop or by providing the compiler option '-ffast-math' double foo(int N) { double v = 0.0; for (int i = 0; i < N; i++) v = v + 1.0; return v; } ## Instruction: Make frontend floating-point commutivity test X86 specific to avoid cost-model related problems on arm-thumb and hexagon. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@244517 91177308-0d34-0410-b5e6-96231b3b80d8 ## Code After: // RUN: %clang -O1 -fvectorize -target x86_64-unknown-unknown -Rpass-analysis=loop-vectorize -emit-llvm -S %s -o - 2>&1 | FileCheck %s // CHECK: {{.*}}:9:11: remark: loop not vectorized: vectorization requires changes in the order of operations, however IEEE 754 floating-point operations are not commutative; allow commutativity by specifying '#pragma clang loop vectorize(enable)' before the loop or by providing the compiler option '-ffast-math' double foo(int N) { double v = 0.0; for (int i = 0; i < N; i++) v = v + 1.0; return v; }
... // RUN: %clang -O1 -fvectorize -target x86_64-unknown-unknown -Rpass-analysis=loop-vectorize -emit-llvm -S %s -o - 2>&1 | FileCheck %s // CHECK: {{.*}}:9:11: remark: loop not vectorized: vectorization requires changes in the order of operations, however IEEE 754 floating-point operations are not commutative; allow commutativity by specifying '#pragma clang loop vectorize(enable)' before the loop or by providing the compiler option '-ffast-math' ...
79d2e089eff2f6bcfd150d3ac6e165bfefa475cb
modeltranslation/__init__.py
modeltranslation/__init__.py
from pathlib import Path __version__ = (Path(__file__).parent / "VERSION").open().read().strip() default_app_config = 'modeltranslation.apps.ModeltranslationConfig'
from pathlib import Path from django import VERSION as _django_version __version__ = (Path(__file__).parent / "VERSION").open().read().strip() if _django_version < (3, 2): default_app_config = 'modeltranslation.apps.ModeltranslationConfig'
Add django version check for default_app_config
fix: Add django version check for default_app_config
Python
bsd-3-clause
deschler/django-modeltranslation,deschler/django-modeltranslation
python
## Code Before: from pathlib import Path __version__ = (Path(__file__).parent / "VERSION").open().read().strip() default_app_config = 'modeltranslation.apps.ModeltranslationConfig' ## Instruction: fix: Add django version check for default_app_config ## Code After: from pathlib import Path from django import VERSION as _django_version __version__ = (Path(__file__).parent / "VERSION").open().read().strip() if _django_version < (3, 2): default_app_config = 'modeltranslation.apps.ModeltranslationConfig'
// ... existing code ... from pathlib import Path from django import VERSION as _django_version __version__ = (Path(__file__).parent / "VERSION").open().read().strip() if _django_version < (3, 2): default_app_config = 'modeltranslation.apps.ModeltranslationConfig' // ... rest of the code ...
be26a931ac90f000fe36ed9334436d2ce4e9828a
src/test/java/examples/locale/LocaleNegotiationTest.java
src/test/java/examples/locale/LocaleNegotiationTest.java
package examples.locale; import com.vtence.molecule.WebServer; import com.vtence.molecule.testing.http.HttpRequest; import com.vtence.molecule.testing.http.HttpResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.Locale; import static com.vtence.molecule.testing.http.HttpResponseAssert.assertThat; import static org.hamcrest.Matchers.containsString; public class LocaleNegotiationTest { LocaleNegotiationExample example = new LocaleNegotiationExample("en", "en_US", "fr"); WebServer server = WebServer.create(9999); HttpRequest request = new HttpRequest(9999); HttpResponse response; Locale originalDefault = Locale.getDefault(); @Before public void startServer() throws IOException { Locale.setDefault(Locale.US); example.run(server); } @After public void stopServer() throws IOException { server.stop(); Locale.setDefault(originalDefault); } @Test public void selectingTheBestSupportedLanguage() throws IOException { response = request.header("Accept-Language", "en; q=0.8, fr").send(); assertThat(response).hasBodyText(containsString("The best match is: fr")); } @Test public void fallingBackToTheDefaultLanguage() throws IOException { response = request.header("Accept-Language", "es-ES").send(); assertThat(response).hasBodyText(containsString("The best match is: en_US")); } }
package examples.locale; import com.vtence.molecule.WebServer; import com.vtence.molecule.testing.http.HttpRequest; import com.vtence.molecule.testing.http.HttpResponse; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; import java.util.Locale; import static com.vtence.molecule.testing.http.HttpResponseAssert.assertThat; import static org.hamcrest.Matchers.containsString; public class LocaleNegotiationTest { LocaleNegotiationExample example = new LocaleNegotiationExample("en", "en_US", "fr"); WebServer server = WebServer.create(9999); HttpRequest request = new HttpRequest(9999); HttpResponse response; Locale originalDefault = Locale.getDefault(); @Before public void startServer() throws IOException { Locale.setDefault(Locale.US); example.run(server); } @After public void stopServer() throws IOException { server.stop(); Locale.setDefault(originalDefault); } @Test @Ignore("wip") public void selectingTheBestSupportedLanguage() throws IOException { response = request.header("Accept-Language", "en; q=0.8, fr").send(); assertThat(response).hasBodyText(containsString("The best match is: fr")); } @Test public void fallingBackToTheDefaultLanguage() throws IOException { response = request.header("Accept-Language", "es-ES").send(); assertThat(response).hasBodyText(containsString("The best match is: en_US")); } }
Mark locale negotiation acceptance in progress
Mark locale negotiation acceptance in progress
Java
mit
testinfected/molecule,testinfected/molecule,testinfected/molecule,ensonik/molecule,ensonik/molecule,ensonik/molecule,ensonik/molecule,testinfected/molecule,testinfected/molecule,ensonik/molecule
java
## Code Before: package examples.locale; import com.vtence.molecule.WebServer; import com.vtence.molecule.testing.http.HttpRequest; import com.vtence.molecule.testing.http.HttpResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.Locale; import static com.vtence.molecule.testing.http.HttpResponseAssert.assertThat; import static org.hamcrest.Matchers.containsString; public class LocaleNegotiationTest { LocaleNegotiationExample example = new LocaleNegotiationExample("en", "en_US", "fr"); WebServer server = WebServer.create(9999); HttpRequest request = new HttpRequest(9999); HttpResponse response; Locale originalDefault = Locale.getDefault(); @Before public void startServer() throws IOException { Locale.setDefault(Locale.US); example.run(server); } @After public void stopServer() throws IOException { server.stop(); Locale.setDefault(originalDefault); } @Test public void selectingTheBestSupportedLanguage() throws IOException { response = request.header("Accept-Language", "en; q=0.8, fr").send(); assertThat(response).hasBodyText(containsString("The best match is: fr")); } @Test public void fallingBackToTheDefaultLanguage() throws IOException { response = request.header("Accept-Language", "es-ES").send(); assertThat(response).hasBodyText(containsString("The best match is: en_US")); } } ## Instruction: Mark locale negotiation acceptance in progress ## Code After: package examples.locale; import com.vtence.molecule.WebServer; import com.vtence.molecule.testing.http.HttpRequest; import com.vtence.molecule.testing.http.HttpResponse; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; import java.util.Locale; import static com.vtence.molecule.testing.http.HttpResponseAssert.assertThat; import static org.hamcrest.Matchers.containsString; public class LocaleNegotiationTest { LocaleNegotiationExample example = new LocaleNegotiationExample("en", "en_US", "fr"); WebServer server = WebServer.create(9999); HttpRequest request = new HttpRequest(9999); HttpResponse response; Locale originalDefault = Locale.getDefault(); @Before public void startServer() throws IOException { Locale.setDefault(Locale.US); example.run(server); } @After public void stopServer() throws IOException { server.stop(); Locale.setDefault(originalDefault); } @Test @Ignore("wip") public void selectingTheBestSupportedLanguage() throws IOException { response = request.header("Accept-Language", "en; q=0.8, fr").send(); assertThat(response).hasBodyText(containsString("The best match is: fr")); } @Test public void fallingBackToTheDefaultLanguage() throws IOException { response = request.header("Accept-Language", "es-ES").send(); assertThat(response).hasBodyText(containsString("The best match is: en_US")); } }
# ... existing code ... import com.vtence.molecule.testing.http.HttpResponse; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; # ... modified code ... Locale.setDefault(originalDefault); } @Test @Ignore("wip") public void selectingTheBestSupportedLanguage() throws IOException { response = request.header("Accept-Language", "en; q=0.8, fr").send(); assertThat(response).hasBodyText(containsString("The best match is: fr")); # ... rest of the code ...
4446a700fcf057f83645b4861b5655773983511c
tests.py
tests.py
import unittest import os from main import generate_files class WordsTest(unittest.TestCase): def setUp(self): for fname in ["test_sequences", "test_words"]: if os.path.exists(fname): os.remove(fname) def test_files_created(self): self.assertFalse(os.path.exists("test_sequences")) self.assertFalse(os.path.exists("test_words")) generate_files([], sequences_fname="test_sequences", words_fname="test_words") self.assertTrue(os.path.exists("test_sequences")) self.assertTrue(os.path.exists("test_words")) if __name__ == '__main__': unittest.main()
import unittest import os from main import generate_files class WordsTest(unittest.TestCase): def setUp(self): # Make sure the expected files don't exist yet for fname in ["test_sequences", "test_words"]: if os.path.exists(fname): os.remove(fname) def test_files_created(self): self.assertFalse(os.path.exists("test_sequences")) self.assertFalse(os.path.exists("test_words")) generate_files([], sequences_fname="test_sequences", words_fname="test_words") self.assertTrue(os.path.exists("test_sequences")) self.assertTrue(os.path.exists("test_words")) def tearDown(self): # So as not to leave a mess for fname in ["test_sequences", "test_words"]: if os.path.exists(fname): os.remove(fname) if __name__ == '__main__': unittest.main()
Add teardown function as well
Add teardown function as well
Python
mit
orblivion/hellolabs_word_test
python
## Code Before: import unittest import os from main import generate_files class WordsTest(unittest.TestCase): def setUp(self): for fname in ["test_sequences", "test_words"]: if os.path.exists(fname): os.remove(fname) def test_files_created(self): self.assertFalse(os.path.exists("test_sequences")) self.assertFalse(os.path.exists("test_words")) generate_files([], sequences_fname="test_sequences", words_fname="test_words") self.assertTrue(os.path.exists("test_sequences")) self.assertTrue(os.path.exists("test_words")) if __name__ == '__main__': unittest.main() ## Instruction: Add teardown function as well ## Code After: import unittest import os from main import generate_files class WordsTest(unittest.TestCase): def setUp(self): # Make sure the expected files don't exist yet for fname in ["test_sequences", "test_words"]: if os.path.exists(fname): os.remove(fname) def test_files_created(self): self.assertFalse(os.path.exists("test_sequences")) self.assertFalse(os.path.exists("test_words")) generate_files([], sequences_fname="test_sequences", words_fname="test_words") self.assertTrue(os.path.exists("test_sequences")) self.assertTrue(os.path.exists("test_words")) def tearDown(self): # So as not to leave a mess for fname in ["test_sequences", "test_words"]: if os.path.exists(fname): os.remove(fname) if __name__ == '__main__': unittest.main()
# ... existing code ... class WordsTest(unittest.TestCase): def setUp(self): # Make sure the expected files don't exist yet for fname in ["test_sequences", "test_words"]: if os.path.exists(fname): os.remove(fname) # ... modified code ... self.assertTrue(os.path.exists("test_sequences")) self.assertTrue(os.path.exists("test_words")) def tearDown(self): # So as not to leave a mess for fname in ["test_sequences", "test_words"]: if os.path.exists(fname): os.remove(fname) if __name__ == '__main__': unittest.main() # ... rest of the code ...
69b816868337683a7dd90f24711e03c5eb982416
kitchen/lib/__init__.py
kitchen/lib/__init__.py
import os import json from kitchen.settings import KITCHEN_LOCATION def load_data(data_type): retval = {} nodes_dir = os.path.join(KITCHEN_LOCATION, data_type) if not os.path.isdir(nodes_dir): raise IOError('Invalid data type or kitchen location. Check your settings.') for filename in os.listdir(nodes_dir): if filename.endswith('.json'): f = open(os.path.join(nodes_dir, filename), 'r') retval[filename[:-5]] = json.load(f) f.close() return retval
import os import json from kitchen.settings import KITCHEN_LOCATION def load_data(data_type): retval = [] nodes_dir = os.path.join(KITCHEN_LOCATION, data_type) if not os.path.isdir(nodes_dir): raise IOError('Invalid data type or kitchen location. Check your settings.') for filename in os.listdir(nodes_dir): if filename.endswith('.json'): entry = {'name': filename[:-5]} f = open(os.path.join(nodes_dir, filename), 'r') entry['data'] = json.load(f) f.close() retval.append(entry) return retval
Use a sortable list instead of a dictionary of values for the return value
Use a sortable list instead of a dictionary of values for the return value
Python
apache-2.0
edelight/kitchen,edelight/kitchen,edelight/kitchen,edelight/kitchen
python
## Code Before: import os import json from kitchen.settings import KITCHEN_LOCATION def load_data(data_type): retval = {} nodes_dir = os.path.join(KITCHEN_LOCATION, data_type) if not os.path.isdir(nodes_dir): raise IOError('Invalid data type or kitchen location. Check your settings.') for filename in os.listdir(nodes_dir): if filename.endswith('.json'): f = open(os.path.join(nodes_dir, filename), 'r') retval[filename[:-5]] = json.load(f) f.close() return retval ## Instruction: Use a sortable list instead of a dictionary of values for the return value ## Code After: import os import json from kitchen.settings import KITCHEN_LOCATION def load_data(data_type): retval = [] nodes_dir = os.path.join(KITCHEN_LOCATION, data_type) if not os.path.isdir(nodes_dir): raise IOError('Invalid data type or kitchen location. Check your settings.') for filename in os.listdir(nodes_dir): if filename.endswith('.json'): entry = {'name': filename[:-5]} f = open(os.path.join(nodes_dir, filename), 'r') entry['data'] = json.load(f) f.close() retval.append(entry) return retval
# ... existing code ... from kitchen.settings import KITCHEN_LOCATION def load_data(data_type): retval = [] nodes_dir = os.path.join(KITCHEN_LOCATION, data_type) if not os.path.isdir(nodes_dir): raise IOError('Invalid data type or kitchen location. Check your settings.') for filename in os.listdir(nodes_dir): if filename.endswith('.json'): entry = {'name': filename[:-5]} f = open(os.path.join(nodes_dir, filename), 'r') entry['data'] = json.load(f) f.close() retval.append(entry) return retval # ... rest of the code ...
37d9e35c93aa983dea28d44aa662dde09a0337e7
src/test/java/com/conveyal/gtfs/util/UtilTest.java
src/test/java/com/conveyal/gtfs/util/UtilTest.java
package com.conveyal.gtfs.util; import org.junit.Test; import static com.conveyal.gtfs.util.Util.human; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /** * A test suite to verify the functionality of methods in the Util class. */ public class UtilTest { /** * Assert that the human function returns strings that are properly formatted. */ @Test public void canHumanize() { assertThat(human(123), is("123")); assertThat(human(1234), is("1k")); assertThat(human(1234567), is("1.2M")); assertThat(human(1234567890), is("1.2G")); } }
package com.conveyal.gtfs.util; import org.junit.Before; import org.junit.Test; import static com.conveyal.gtfs.util.Util.human; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /** * A test suite to verify the functionality of methods in the Util class. */ public class UtilTest { @Before // setup() public void before() throws Exception { java.util.Locale.setDefault(java.util.Locale.US); } /** * Assert that the human function returns strings that are properly formatted. */ @Test public void canHumanize() { assertThat(human(123), is("123")); assertThat(human(1234), is("1k")); assertThat(human(1234567), is("1.2M")); assertThat(human(1234567890), is("1.2G")); } }
Set locale to US on humanize test
Set locale to US on humanize test
Java
bsd-2-clause
conveyal/gtfs-lib
java
## Code Before: package com.conveyal.gtfs.util; import org.junit.Test; import static com.conveyal.gtfs.util.Util.human; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /** * A test suite to verify the functionality of methods in the Util class. */ public class UtilTest { /** * Assert that the human function returns strings that are properly formatted. */ @Test public void canHumanize() { assertThat(human(123), is("123")); assertThat(human(1234), is("1k")); assertThat(human(1234567), is("1.2M")); assertThat(human(1234567890), is("1.2G")); } } ## Instruction: Set locale to US on humanize test ## Code After: package com.conveyal.gtfs.util; import org.junit.Before; import org.junit.Test; import static com.conveyal.gtfs.util.Util.human; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /** * A test suite to verify the functionality of methods in the Util class. */ public class UtilTest { @Before // setup() public void before() throws Exception { java.util.Locale.setDefault(java.util.Locale.US); } /** * Assert that the human function returns strings that are properly formatted. */ @Test public void canHumanize() { assertThat(human(123), is("123")); assertThat(human(1234), is("1k")); assertThat(human(1234567), is("1.2M")); assertThat(human(1234567890), is("1.2G")); } }
# ... existing code ... package com.conveyal.gtfs.util; import org.junit.Before; import org.junit.Test; import static com.conveyal.gtfs.util.Util.human; # ... modified code ... * A test suite to verify the functionality of methods in the Util class. */ public class UtilTest { @Before // setup() public void before() throws Exception { java.util.Locale.setDefault(java.util.Locale.US); } /** * Assert that the human function returns strings that are properly formatted. # ... rest of the code ...
43ad157b058693fd38280a802ed4da92301ef4f1
setup.py
setup.py
import re from setuptools import setup with open('mashdown/__init__.py') as f: version = re.search( r'(?<=__version__ = \')\d\.\d\.\d(?=\')', f.read() ).group() with open('README.rst') as f: readme = f.read() setup( name=u'mashdown', version=version, description=u'Splits a youtube mashup video in a list of tagged audio files', long_description=readme, author=u'Balthazar Rouberol', author_email=u'[email protected]', license='License :: OSI Approved :: MIT License', packages=['mashdown'], install_requires=['pydub', 'pafy', 'mutagen'], entry_points={ 'console_scripts': ['mashdown=main:main'] }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: TODO', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Multimedia :: Sound/Audio :: Conversion', 'Topic :: Multimedia :: Video :: Conversion' ], zip_safe=False, )
import re from setuptools import setup with open('mashdown/__init__.py') as f: version = re.search( r'(?<=__version__ = \')\d\.\d\.\d(?=\')', f.read() ).group() with open('README.rst') as f: readme = f.read() setup( name=u'mashdown', version=version, description=u'Splits a youtube mashup video in a list of tagged audio files', long_description=readme, author=u'Balthazar Rouberol', author_email=u'[email protected]', license='License :: OSI Approved :: MIT License', packages=['mashdown'], install_requires=['pydub', 'pafy', 'mutagen'], entry_points={ 'console_scripts': ['mashdown=main:main'] }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Multimedia :: Sound/Audio :: Conversion', 'Topic :: Multimedia :: Video :: Conversion' ], zip_safe=False, )
Add a proper License PyPI classifier
Add a proper License PyPI classifier
Python
mit
brouberol/mashdown
python
## Code Before: import re from setuptools import setup with open('mashdown/__init__.py') as f: version = re.search( r'(?<=__version__ = \')\d\.\d\.\d(?=\')', f.read() ).group() with open('README.rst') as f: readme = f.read() setup( name=u'mashdown', version=version, description=u'Splits a youtube mashup video in a list of tagged audio files', long_description=readme, author=u'Balthazar Rouberol', author_email=u'[email protected]', license='License :: OSI Approved :: MIT License', packages=['mashdown'], install_requires=['pydub', 'pafy', 'mutagen'], entry_points={ 'console_scripts': ['mashdown=main:main'] }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: TODO', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Multimedia :: Sound/Audio :: Conversion', 'Topic :: Multimedia :: Video :: Conversion' ], zip_safe=False, ) ## Instruction: Add a proper License PyPI classifier ## Code After: import re from setuptools import setup with open('mashdown/__init__.py') as f: version = re.search( r'(?<=__version__ = \')\d\.\d\.\d(?=\')', f.read() ).group() with open('README.rst') as f: readme = f.read() setup( name=u'mashdown', version=version, description=u'Splits a youtube mashup video in a list of tagged audio files', long_description=readme, author=u'Balthazar Rouberol', author_email=u'[email protected]', license='License :: OSI Approved :: MIT License', packages=['mashdown'], install_requires=['pydub', 'pafy', 'mutagen'], entry_points={ 'console_scripts': ['mashdown=main:main'] }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Multimedia :: Sound/Audio :: Conversion', 'Topic :: Multimedia :: Video :: Conversion' ], zip_safe=False, )
// ... existing code ... 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', // ... rest of the code ...
1975d5391f058f85272def4435b243440b72bff6
weather/admin.py
weather/admin.py
from django.contrib.admin import ModelAdmin, register from django.contrib.gis.admin import GeoModelAdmin from weather.models import WeatherStation, Location @register(Location) class LocationAdmin(GeoModelAdmin): openlayers_url = '//static.dpaw.wa.gov.au/static/libs/openlayers/2.13.1/OpenLayers.js' list_display = ('pk', 'title', 'point', 'height') @register(WeatherStation) class WeatherStationAdmin(ModelAdmin): list_display = ( 'name', 'manufacturer', 'abbreviation', 'bom_abbreviation', 'ip_address', 'last_reading', 'connect_every', 'active', 'upload_data') list_filter = ('manufacturer', 'active', 'upload_data')
from django.contrib.admin import ModelAdmin, register from django.contrib.gis.admin import GeoModelAdmin from weather.models import WeatherStation, Location @register(Location) class LocationAdmin(GeoModelAdmin): list_display = ('pk', 'title', 'point', 'height') @register(WeatherStation) class WeatherStationAdmin(ModelAdmin): list_display = ( 'name', 'manufacturer', 'abbreviation', 'bom_abbreviation', 'ip_address', 'last_reading', 'connect_every', 'active', 'upload_data') list_filter = ('manufacturer', 'active', 'upload_data')
Remove custom OpenLayers.js from LocationAdmin.
Remove custom OpenLayers.js from LocationAdmin.
Python
bsd-3-clause
parksandwildlife/resource_tracking,parksandwildlife/resource_tracking,parksandwildlife/resource_tracking,ropable/resource_tracking,ropable/resource_tracking,ropable/resource_tracking
python
## Code Before: from django.contrib.admin import ModelAdmin, register from django.contrib.gis.admin import GeoModelAdmin from weather.models import WeatherStation, Location @register(Location) class LocationAdmin(GeoModelAdmin): openlayers_url = '//static.dpaw.wa.gov.au/static/libs/openlayers/2.13.1/OpenLayers.js' list_display = ('pk', 'title', 'point', 'height') @register(WeatherStation) class WeatherStationAdmin(ModelAdmin): list_display = ( 'name', 'manufacturer', 'abbreviation', 'bom_abbreviation', 'ip_address', 'last_reading', 'connect_every', 'active', 'upload_data') list_filter = ('manufacturer', 'active', 'upload_data') ## Instruction: Remove custom OpenLayers.js from LocationAdmin. ## Code After: from django.contrib.admin import ModelAdmin, register from django.contrib.gis.admin import GeoModelAdmin from weather.models import WeatherStation, Location @register(Location) class LocationAdmin(GeoModelAdmin): list_display = ('pk', 'title', 'point', 'height') @register(WeatherStation) class WeatherStationAdmin(ModelAdmin): list_display = ( 'name', 'manufacturer', 'abbreviation', 'bom_abbreviation', 'ip_address', 'last_reading', 'connect_every', 'active', 'upload_data') list_filter = ('manufacturer', 'active', 'upload_data')
// ... existing code ... @register(Location) class LocationAdmin(GeoModelAdmin): list_display = ('pk', 'title', 'point', 'height') // ... rest of the code ...
058021756d88d5b5f68070e2307e734fda86938d
utils/src/main/java/fr/unice/polytech/al/trafficlight/utils/enums/TrafficLightId.java
utils/src/main/java/fr/unice/polytech/al/trafficlight/utils/enums/TrafficLightId.java
package fr.unice.polytech.al.trafficlight.utils.enums; /** * Created by nathael on 27/10/16. */ public class TrafficLightId { private final String id; public TrafficLightId(String id) { this.id = id; } @Override public boolean equals(Object obj) { if(obj instanceof String) return id.equals((String) obj); else if (obj instanceof TrafficLightId) { return id.equals(((TrafficLightId) obj).id); } else return false; } @Override public String toString() { return "TL:"+id; } }
package fr.unice.polytech.al.trafficlight.utils.enums; /** * Created by nathael on 27/10/16. */ public class TrafficLightId { private final String id; public TrafficLightId(String id) { this.id = id; } public String getId() { return id; } @Override public boolean equals(Object obj) { if(obj instanceof String) return id.equals((String) obj); else if (obj instanceof TrafficLightId) { return id.equals(((TrafficLightId) obj).id); } else return false; } @Override public String toString() { return "TL:"+id; } }
Add a getter to the id
Add a getter to the id
Java
mit
Lydwen/CentralTrafficLightManagement-SmartCity,Lydwen/CentralTrafficLightManagement-SmartCity
java
## Code Before: package fr.unice.polytech.al.trafficlight.utils.enums; /** * Created by nathael on 27/10/16. */ public class TrafficLightId { private final String id; public TrafficLightId(String id) { this.id = id; } @Override public boolean equals(Object obj) { if(obj instanceof String) return id.equals((String) obj); else if (obj instanceof TrafficLightId) { return id.equals(((TrafficLightId) obj).id); } else return false; } @Override public String toString() { return "TL:"+id; } } ## Instruction: Add a getter to the id ## Code After: package fr.unice.polytech.al.trafficlight.utils.enums; /** * Created by nathael on 27/10/16. */ public class TrafficLightId { private final String id; public TrafficLightId(String id) { this.id = id; } public String getId() { return id; } @Override public boolean equals(Object obj) { if(obj instanceof String) return id.equals((String) obj); else if (obj instanceof TrafficLightId) { return id.equals(((TrafficLightId) obj).id); } else return false; } @Override public String toString() { return "TL:"+id; } }
... public TrafficLightId(String id) { this.id = id; } public String getId() { return id; } @Override ...
2cd4e6f021e576a17a3f8f40122775baee9e8889
server/run.py
server/run.py
from eve import Eve app = Eve() if __name__ == '__main__': app.run()
import json import settings from flask import request, session from requests import HTTPError from requests_oauthlib import OAuth2Session from eve import Eve from flask_login import LoginManager app = Eve() login_manager = LoginManager(app) login_manager.login_view = "login" login_manager.session_protection = "strong" app.secret_key = settings.APP_SECRET_KEY def get_google_auth(state=None, token=None): if token: return OAuth2Session(settings.OAUTH_CLIENT_ID, token=token) if state: return OAuth2Session( settings.OAUTH_CLIENT_ID, state=state, redirect_uri=settings.OAUTH_REDIRECT_URI ) return OAuth2Session( settings.OAUTH_CLIENT_ID, redirect_uri=settings.OAUTH_REDIRECT_URI, scope=settings.OAUTH_SCOPE ) @app.route('/login') def login(): google = get_google_auth() auth_url, state = google.authorization_url( settings.OAUTH_AUTH_URI, access_type='online' ) session['oauth_state'] = state return json.dumps({ "auth_url": auth_url, }) @app.route('/oauth2callback') def callback(): if 'error' in request.args: if request.args.get('error') == 'access_denied': return json.dumps({ "error": "Access denied", }) return json.dumps({ "error": "Other error", }) if 'code' not in request.args and 'state' not in request.args: return json.dumps({}) else: google = get_google_auth(state=session['oauth_state']) try: token = google.fetch_token( settings.OAUTH_TOKEN_URI, client_secret=settings.OAUTH_CLIENT_SECRET, authorization_response=request.url) except HTTPError: return json.dumps({"error": "Failed to get google login."}) google = get_google_auth(token=token) resp = google.get(settings.OAUTH_USER_INFO) if resp.status_code == 200: user_data = resp.json() # email = user_data['email'] print(user_data) return json.dumps({ "status": "ok", "user_data": user_data, }) return json.dumps({ "error": "Failed to get user data", }) if __name__ == '__main__': app.run()
Add initial views for google login.
Add initial views for google login.
Python
mit
mattiaslundberg/typer,mattiaslundberg/typer,mattiaslundberg/typer,mattiaslundberg/typer
python
## Code Before: from eve import Eve app = Eve() if __name__ == '__main__': app.run() ## Instruction: Add initial views for google login. ## Code After: import json import settings from flask import request, session from requests import HTTPError from requests_oauthlib import OAuth2Session from eve import Eve from flask_login import LoginManager app = Eve() login_manager = LoginManager(app) login_manager.login_view = "login" login_manager.session_protection = "strong" app.secret_key = settings.APP_SECRET_KEY def get_google_auth(state=None, token=None): if token: return OAuth2Session(settings.OAUTH_CLIENT_ID, token=token) if state: return OAuth2Session( settings.OAUTH_CLIENT_ID, state=state, redirect_uri=settings.OAUTH_REDIRECT_URI ) return OAuth2Session( settings.OAUTH_CLIENT_ID, redirect_uri=settings.OAUTH_REDIRECT_URI, scope=settings.OAUTH_SCOPE ) @app.route('/login') def login(): google = get_google_auth() auth_url, state = google.authorization_url( settings.OAUTH_AUTH_URI, access_type='online' ) session['oauth_state'] = state return json.dumps({ "auth_url": auth_url, }) @app.route('/oauth2callback') def callback(): if 'error' in request.args: if request.args.get('error') == 'access_denied': return json.dumps({ "error": "Access denied", }) return json.dumps({ "error": "Other error", }) if 'code' not in request.args and 'state' not in request.args: return json.dumps({}) else: google = get_google_auth(state=session['oauth_state']) try: token = google.fetch_token( settings.OAUTH_TOKEN_URI, client_secret=settings.OAUTH_CLIENT_SECRET, authorization_response=request.url) except HTTPError: return json.dumps({"error": "Failed to get google login."}) google = get_google_auth(token=token) resp = google.get(settings.OAUTH_USER_INFO) if resp.status_code == 200: user_data = resp.json() # email = user_data['email'] print(user_data) return json.dumps({ "status": "ok", "user_data": user_data, }) return json.dumps({ "error": "Failed to get user data", }) if __name__ == '__main__': app.run()
# ... existing code ... import json import settings from flask import request, session from requests import HTTPError from requests_oauthlib import OAuth2Session from eve import Eve from flask_login import LoginManager app = Eve() login_manager = LoginManager(app) login_manager.login_view = "login" login_manager.session_protection = "strong" app.secret_key = settings.APP_SECRET_KEY def get_google_auth(state=None, token=None): if token: return OAuth2Session(settings.OAUTH_CLIENT_ID, token=token) if state: return OAuth2Session( settings.OAUTH_CLIENT_ID, state=state, redirect_uri=settings.OAUTH_REDIRECT_URI ) return OAuth2Session( settings.OAUTH_CLIENT_ID, redirect_uri=settings.OAUTH_REDIRECT_URI, scope=settings.OAUTH_SCOPE ) @app.route('/login') def login(): google = get_google_auth() auth_url, state = google.authorization_url( settings.OAUTH_AUTH_URI, access_type='online' ) session['oauth_state'] = state return json.dumps({ "auth_url": auth_url, }) @app.route('/oauth2callback') def callback(): if 'error' in request.args: if request.args.get('error') == 'access_denied': return json.dumps({ "error": "Access denied", }) return json.dumps({ "error": "Other error", }) if 'code' not in request.args and 'state' not in request.args: return json.dumps({}) else: google = get_google_auth(state=session['oauth_state']) try: token = google.fetch_token( settings.OAUTH_TOKEN_URI, client_secret=settings.OAUTH_CLIENT_SECRET, authorization_response=request.url) except HTTPError: return json.dumps({"error": "Failed to get google login."}) google = get_google_auth(token=token) resp = google.get(settings.OAUTH_USER_INFO) if resp.status_code == 200: user_data = resp.json() # email = user_data['email'] print(user_data) return json.dumps({ "status": "ok", "user_data": user_data, }) return json.dumps({ "error": "Failed to get user data", }) if __name__ == '__main__': app.run() # ... rest of the code ...
649ae48e2b2c5b9e03379294fa93aa100c850e71
Paystack/Classes/PublicHeaders/Paystack.h
Paystack/Classes/PublicHeaders/Paystack.h
// // Paystack.h // Paystack // // Created by Ibrahim Lawal on 02/02/16. // Copyright (c) 2016 Paystack. All rights reserved. // // The code in this workspace was adapted from https://github.com/stripe/stripe-ios. // Stripe was replaced with Paystack - and STP with PSTCK - to avoid collisions within // apps that are using both Paystack and Stripe. #import <Paystack/PSTCKAPIClient.h> #import <Paystack/PaystackError.h> #import <Paystack/PSTCKCardBrand.h> #import <Paystack/PSTCKCardParams.h> #import <Paystack/PSTCKTransactionParams.h> #import <Paystack/PSTCKCard.h> #import <Paystack/PSTCKCardValidationState.h> #import <Paystack/PSTCKCardValidator.h> #import <Paystack/PSTCKToken.h> #import <Paystack/PSTCKRSA.h> #if TARGET_OS_IPHONE #import <Paystack/PSTCKPaymentCardTextField.h> #endif
// // Paystack.h // Paystack // // Created by Ibrahim Lawal on 02/02/16. // Copyright (c) 2016 Paystack. All rights reserved. // // The code in this workspace was adapted from https://github.com/stripe/stripe-ios. // Stripe was replaced with Paystack - and STP with PSTCK - to avoid collisions within // apps that are using both Paystack and Stripe. #import "PSTCKAPIClient.h" #import "PaystackError.h" #import "PSTCKCardBrand.h" #import "PSTCKCardParams.h" #import "PSTCKTransactionParams.h" #import "PSTCKCard.h" #import "PSTCKCardValidationState.h" #import "PSTCKCardValidator.h" #import "PSTCKToken.h" #import "PSTCKRSA.h" #if TARGET_OS_IPHONE #import "PSTCKPaymentCardTextField.h" #endif
Update umbrella header file declaration
Update umbrella header file declaration
C
mit
PaystackHQ/paystack-ios,PaystackHQ/paystack-ios,PaystackHQ/paystack-ios,PaystackHQ/paystack-ios
c
## Code Before: // // Paystack.h // Paystack // // Created by Ibrahim Lawal on 02/02/16. // Copyright (c) 2016 Paystack. All rights reserved. // // The code in this workspace was adapted from https://github.com/stripe/stripe-ios. // Stripe was replaced with Paystack - and STP with PSTCK - to avoid collisions within // apps that are using both Paystack and Stripe. #import <Paystack/PSTCKAPIClient.h> #import <Paystack/PaystackError.h> #import <Paystack/PSTCKCardBrand.h> #import <Paystack/PSTCKCardParams.h> #import <Paystack/PSTCKTransactionParams.h> #import <Paystack/PSTCKCard.h> #import <Paystack/PSTCKCardValidationState.h> #import <Paystack/PSTCKCardValidator.h> #import <Paystack/PSTCKToken.h> #import <Paystack/PSTCKRSA.h> #if TARGET_OS_IPHONE #import <Paystack/PSTCKPaymentCardTextField.h> #endif ## Instruction: Update umbrella header file declaration ## Code After: // // Paystack.h // Paystack // // Created by Ibrahim Lawal on 02/02/16. // Copyright (c) 2016 Paystack. All rights reserved. // // The code in this workspace was adapted from https://github.com/stripe/stripe-ios. // Stripe was replaced with Paystack - and STP with PSTCK - to avoid collisions within // apps that are using both Paystack and Stripe. #import "PSTCKAPIClient.h" #import "PaystackError.h" #import "PSTCKCardBrand.h" #import "PSTCKCardParams.h" #import "PSTCKTransactionParams.h" #import "PSTCKCard.h" #import "PSTCKCardValidationState.h" #import "PSTCKCardValidator.h" #import "PSTCKToken.h" #import "PSTCKRSA.h" #if TARGET_OS_IPHONE #import "PSTCKPaymentCardTextField.h" #endif
// ... existing code ... // Stripe was replaced with Paystack - and STP with PSTCK - to avoid collisions within // apps that are using both Paystack and Stripe. #import "PSTCKAPIClient.h" #import "PaystackError.h" #import "PSTCKCardBrand.h" #import "PSTCKCardParams.h" #import "PSTCKTransactionParams.h" #import "PSTCKCard.h" #import "PSTCKCardValidationState.h" #import "PSTCKCardValidator.h" #import "PSTCKToken.h" #import "PSTCKRSA.h" #if TARGET_OS_IPHONE #import "PSTCKPaymentCardTextField.h" #endif // ... rest of the code ...
92ca74258f0028bf3b12a84a7f7741f7b72ec45d
db/migrations/migration2.py
db/migrations/migration2.py
import sqlite3 from config import DATA_FOLDER def migrate(database_path): print "migrating to db version 2" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # read hashmap from db cursor.execute('''SELECT * FROM hashmap''') mappings = cursor.fetchall() for mapping in mappings: if DATA_FOLDER not in mapping[1]: raise Exception("To complete migration 2 please run openbazaard at least once using the original " "data folder location before moving it to a different location.") path = mapping[1][len(DATA_FOLDER):] cursor.execute('''INSERT OR REPLACE INTO hashmap(hash, filepath) VALUES (?,?)''', (mapping[0], path)) # update version cursor.execute('''PRAGMA user_version = 2''') conn.commit() conn.close()
import sqlite3 from config import DATA_FOLDER def migrate(database_path): print "migrating to db version 2" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # read hashmap from db cursor.execute('''SELECT * FROM hashmap''') mappings = cursor.fetchall() for mapping in mappings: if DATA_FOLDER in mapping[1]: path = mapping[1][len(DATA_FOLDER):] cursor.execute('''INSERT OR REPLACE INTO hashmap(hash, filepath) VALUES (?,?)''', (mapping[0], path)) # update version cursor.execute('''PRAGMA user_version = 2''') conn.commit() conn.close()
Remove exception in migration Some users moved their data folder despite the code not permitting it yet. This migration will fail for those users, but they will still be able to run the app.
Remove exception in migration Some users moved their data folder despite the code not permitting it yet. This migration will fail for those users, but they will still be able to run the app.
Python
mit
OpenBazaar/Network,OpenBazaar/OpenBazaar-Server,tomgalloway/OpenBazaar-Server,saltduck/OpenBazaar-Server,tomgalloway/OpenBazaar-Server,tyler-smith/OpenBazaar-Server,saltduck/OpenBazaar-Server,cpacia/OpenBazaar-Server,tyler-smith/OpenBazaar-Server,OpenBazaar/Network,OpenBazaar/OpenBazaar-Server,saltduck/OpenBazaar-Server,OpenBazaar/Network,cpacia/OpenBazaar-Server,OpenBazaar/OpenBazaar-Server,cpacia/OpenBazaar-Server,tomgalloway/OpenBazaar-Server,tyler-smith/OpenBazaar-Server
python
## Code Before: import sqlite3 from config import DATA_FOLDER def migrate(database_path): print "migrating to db version 2" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # read hashmap from db cursor.execute('''SELECT * FROM hashmap''') mappings = cursor.fetchall() for mapping in mappings: if DATA_FOLDER not in mapping[1]: raise Exception("To complete migration 2 please run openbazaard at least once using the original " "data folder location before moving it to a different location.") path = mapping[1][len(DATA_FOLDER):] cursor.execute('''INSERT OR REPLACE INTO hashmap(hash, filepath) VALUES (?,?)''', (mapping[0], path)) # update version cursor.execute('''PRAGMA user_version = 2''') conn.commit() conn.close() ## Instruction: Remove exception in migration Some users moved their data folder despite the code not permitting it yet. This migration will fail for those users, but they will still be able to run the app. ## Code After: import sqlite3 from config import DATA_FOLDER def migrate(database_path): print "migrating to db version 2" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # read hashmap from db cursor.execute('''SELECT * FROM hashmap''') mappings = cursor.fetchall() for mapping in mappings: if DATA_FOLDER in mapping[1]: path = mapping[1][len(DATA_FOLDER):] cursor.execute('''INSERT OR REPLACE INTO hashmap(hash, filepath) VALUES (?,?)''', (mapping[0], path)) # update version cursor.execute('''PRAGMA user_version = 2''') conn.commit() conn.close()
... mappings = cursor.fetchall() for mapping in mappings: if DATA_FOLDER in mapping[1]: path = mapping[1][len(DATA_FOLDER):] cursor.execute('''INSERT OR REPLACE INTO hashmap(hash, filepath) VALUES (?,?)''', (mapping[0], path)) # update version cursor.execute('''PRAGMA user_version = 2''') ...
7a1a90cbaba73da44efeaf385865519cfa078a6c
astropy/vo/samp/tests/test_hub_script.py
astropy/vo/samp/tests/test_hub_script.py
import sys from ..hub_script import hub_script from ..utils import ALLOW_INTERNET def setup_module(module): ALLOW_INTERNET.set(False) def test_hub_script(): sys.argv.append('-m') # run in multiple mode sys.argv.append('-w') # disable web profile hub_script(timeout=3)
import sys from ..hub_script import hub_script from ..utils import ALLOW_INTERNET def setup_module(module): ALLOW_INTERNET.set(False) def setup_function(function): function.sys_argv_orig = sys.argv sys.argv = ["samp_hub"] def teardown_function(function): sys.argv = function.sys_argv_orig def test_hub_script(): sys.argv.append('-m') # run in multiple mode sys.argv.append('-w') # disable web profile hub_script(timeout=3)
Fix isolation of SAMP hub script test.
Fix isolation of SAMP hub script test.
Python
bsd-3-clause
StuartLittlefair/astropy,dhomeier/astropy,saimn/astropy,funbaker/astropy,larrybradley/astropy,MSeifert04/astropy,kelle/astropy,lpsinger/astropy,bsipocz/astropy,aleksandr-bakanov/astropy,DougBurke/astropy,lpsinger/astropy,lpsinger/astropy,astropy/astropy,funbaker/astropy,AustereCuriosity/astropy,StuartLittlefair/astropy,dhomeier/astropy,aleksandr-bakanov/astropy,MSeifert04/astropy,aleksandr-bakanov/astropy,tbabej/astropy,lpsinger/astropy,pllim/astropy,tbabej/astropy,stargaser/astropy,StuartLittlefair/astropy,joergdietrich/astropy,astropy/astropy,dhomeier/astropy,stargaser/astropy,AustereCuriosity/astropy,larrybradley/astropy,bsipocz/astropy,tbabej/astropy,StuartLittlefair/astropy,kelle/astropy,astropy/astropy,larrybradley/astropy,joergdietrich/astropy,mhvk/astropy,tbabej/astropy,funbaker/astropy,mhvk/astropy,stargaser/astropy,astropy/astropy,DougBurke/astropy,DougBurke/astropy,saimn/astropy,mhvk/astropy,funbaker/astropy,astropy/astropy,MSeifert04/astropy,pllim/astropy,joergdietrich/astropy,bsipocz/astropy,larrybradley/astropy,AustereCuriosity/astropy,stargaser/astropy,saimn/astropy,bsipocz/astropy,dhomeier/astropy,aleksandr-bakanov/astropy,joergdietrich/astropy,pllim/astropy,MSeifert04/astropy,saimn/astropy,dhomeier/astropy,lpsinger/astropy,StuartLittlefair/astropy,DougBurke/astropy,tbabej/astropy,saimn/astropy,kelle/astropy,kelle/astropy,pllim/astropy,larrybradley/astropy,mhvk/astropy,pllim/astropy,AustereCuriosity/astropy,AustereCuriosity/astropy,mhvk/astropy,joergdietrich/astropy,kelle/astropy
python
## Code Before: import sys from ..hub_script import hub_script from ..utils import ALLOW_INTERNET def setup_module(module): ALLOW_INTERNET.set(False) def test_hub_script(): sys.argv.append('-m') # run in multiple mode sys.argv.append('-w') # disable web profile hub_script(timeout=3) ## Instruction: Fix isolation of SAMP hub script test. ## Code After: import sys from ..hub_script import hub_script from ..utils import ALLOW_INTERNET def setup_module(module): ALLOW_INTERNET.set(False) def setup_function(function): function.sys_argv_orig = sys.argv sys.argv = ["samp_hub"] def teardown_function(function): sys.argv = function.sys_argv_orig def test_hub_script(): sys.argv.append('-m') # run in multiple mode sys.argv.append('-w') # disable web profile hub_script(timeout=3)
# ... existing code ... from ..utils import ALLOW_INTERNET def setup_module(module): ALLOW_INTERNET.set(False) def setup_function(function): function.sys_argv_orig = sys.argv sys.argv = ["samp_hub"] def teardown_function(function): sys.argv = function.sys_argv_orig def test_hub_script(): # ... rest of the code ...
28e721fd5907dd7807f35bccc48b177afdc2b2f9
main.c
main.c
int main() { int status; Turing *turing; status = 0; turing = init_turing(); status = execute_instruction(turing, "0 110\n1 110"); if (TURING_ERROR == status) { fprintf(stderr, "Exiting\n"); return 1; } else if (TURING_HALT) { printf("Program reached halt state!\n"); } free_turing(turing); return 0; }
if (TURING_ERROR == status) {\ return 1;\ } int main() { int status; Turing *turing; status = 0; turing = init_turing(); status = execute_instruction(turing, "0 110\n1 110"); if (TURING_ERROR == status) { fprintf(stderr, "Exiting\n"); return 1; } else if (TURING_HALT) { printf("Program reached halt state!\n"); } free_turing(turing); return 0; }
Add turing_try function for handling errors
Add turing_try function for handling errors
C
mit
mindriot101/turing-machine
c
## Code Before: int main() { int status; Turing *turing; status = 0; turing = init_turing(); status = execute_instruction(turing, "0 110\n1 110"); if (TURING_ERROR == status) { fprintf(stderr, "Exiting\n"); return 1; } else if (TURING_HALT) { printf("Program reached halt state!\n"); } free_turing(turing); return 0; } ## Instruction: Add turing_try function for handling errors ## Code After: if (TURING_ERROR == status) {\ return 1;\ } int main() { int status; Turing *turing; status = 0; turing = init_turing(); status = execute_instruction(turing, "0 110\n1 110"); if (TURING_ERROR == status) { fprintf(stderr, "Exiting\n"); return 1; } else if (TURING_HALT) { printf("Program reached halt state!\n"); } free_turing(turing); return 0; }
# ... existing code ... if (TURING_ERROR == status) {\ return 1;\ } int main() { int status; # ... rest of the code ...
a006c5f13e25d36f72e0878b4245e0edb126da68
ckanext/requestdata/controllers/search.py
ckanext/requestdata/controllers/search.py
try: # CKAN 2.7 and later from ckan.common import config except ImportError: # CKAN 2.6 and earlier from pylons import config is_hdx = config.get('hdx_portal') if is_hdx: from ckanext.hdx_search.controllers.search_controller import HDXSearchController as PackageController else: from ckan.controllers.package import PackageController class SearchController(PackageController): def search_datasets(self): if is_hdx: return self.search() else: pass
try: # CKAN 2.7 and later from ckan.common import config except ImportError: # CKAN 2.6 and earlier from pylons import config from paste.deploy.converters import asbool is_hdx = asbool(config.get('hdx_portal', False)) if is_hdx: from ckanext.hdx_search.controllers.search_controller\ import HDXSearchController as PackageController else: from ckan.controllers.package import PackageController class SearchController(PackageController): def search_datasets(self): return self.search()
Convert hdx_portal to a boolean value
Convert hdx_portal to a boolean value
Python
agpl-3.0
ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata
python
## Code Before: try: # CKAN 2.7 and later from ckan.common import config except ImportError: # CKAN 2.6 and earlier from pylons import config is_hdx = config.get('hdx_portal') if is_hdx: from ckanext.hdx_search.controllers.search_controller import HDXSearchController as PackageController else: from ckan.controllers.package import PackageController class SearchController(PackageController): def search_datasets(self): if is_hdx: return self.search() else: pass ## Instruction: Convert hdx_portal to a boolean value ## Code After: try: # CKAN 2.7 and later from ckan.common import config except ImportError: # CKAN 2.6 and earlier from pylons import config from paste.deploy.converters import asbool is_hdx = asbool(config.get('hdx_portal', False)) if is_hdx: from ckanext.hdx_search.controllers.search_controller\ import HDXSearchController as PackageController else: from ckan.controllers.package import PackageController class SearchController(PackageController): def search_datasets(self): return self.search()
# ... existing code ... # CKAN 2.6 and earlier from pylons import config from paste.deploy.converters import asbool is_hdx = asbool(config.get('hdx_portal', False)) if is_hdx: from ckanext.hdx_search.controllers.search_controller\ import HDXSearchController as PackageController else: from ckan.controllers.package import PackageController # ... modified code ... class SearchController(PackageController): def search_datasets(self): return self.search() # ... rest of the code ...
9614463119c6c28626ae237f9ce7225a638d32ef
src/commands/i2c_test_command.c
src/commands/i2c_test_command.c
void I2CTestCommandHandler(uint16_t argc, char* argv[]) { UNREFERENCED_PARAMETER(argc); I2CBus* bus; if (strcmp(argv[0], "system") == 0) { bus = Main.I2C.System; } else if (strcmp(argv[0], "payload") == 0) { bus = Main.I2C.Payload; } else { TerminalPuts("Unknown bus\n"); } const uint8_t device = (uint8_t)atoi(argv[1]); const uint8_t* data = (uint8_t*)argv[2]; const size_t dataLength = strlen(argv[2]); uint8_t output[20] = {0}; size_t outputLength = dataLength; const I2CResult result = bus->WriteRead(bus, device, data, dataLength, output, outputLength); if (result == I2CResultOK) { TerminalPuts((char*)output); } else { TerminalPrintf("Error %d\n", result); } }
void I2CTestCommandHandler(uint16_t argc, char* argv[]) { UNREFERENCED_PARAMETER(argc); if (argc != 3) { TerminalPuts("i2c <system|payload> <device> <data>\n"); return; } I2CBus* bus; if (strcmp(argv[0], "system") == 0) { bus = Main.I2C.System; } else if (strcmp(argv[0], "payload") == 0) { bus = Main.I2C.Payload; } else { TerminalPuts("Unknown bus\n"); } const uint8_t device = (uint8_t)atoi(argv[1]); const uint8_t* data = (uint8_t*)argv[2]; const size_t dataLength = strlen(argv[2]); uint8_t output[20] = {0}; size_t outputLength = dataLength; const I2CResult result = bus->WriteRead(bus, device, data, dataLength, output, outputLength); if (result == I2CResultOK) { TerminalPuts((char*)output); } else { TerminalPrintf("Error %d\n", result); } }
Check args count in test i2c terminal command
Check args count in test i2c terminal command
C
agpl-3.0
PW-Sat2/PWSat2OBC,PW-Sat2/PWSat2OBC,PW-Sat2/PWSat2OBC,PW-Sat2/PWSat2OBC
c
## Code Before: void I2CTestCommandHandler(uint16_t argc, char* argv[]) { UNREFERENCED_PARAMETER(argc); I2CBus* bus; if (strcmp(argv[0], "system") == 0) { bus = Main.I2C.System; } else if (strcmp(argv[0], "payload") == 0) { bus = Main.I2C.Payload; } else { TerminalPuts("Unknown bus\n"); } const uint8_t device = (uint8_t)atoi(argv[1]); const uint8_t* data = (uint8_t*)argv[2]; const size_t dataLength = strlen(argv[2]); uint8_t output[20] = {0}; size_t outputLength = dataLength; const I2CResult result = bus->WriteRead(bus, device, data, dataLength, output, outputLength); if (result == I2CResultOK) { TerminalPuts((char*)output); } else { TerminalPrintf("Error %d\n", result); } } ## Instruction: Check args count in test i2c terminal command ## Code After: void I2CTestCommandHandler(uint16_t argc, char* argv[]) { UNREFERENCED_PARAMETER(argc); if (argc != 3) { TerminalPuts("i2c <system|payload> <device> <data>\n"); return; } I2CBus* bus; if (strcmp(argv[0], "system") == 0) { bus = Main.I2C.System; } else if (strcmp(argv[0], "payload") == 0) { bus = Main.I2C.Payload; } else { TerminalPuts("Unknown bus\n"); } const uint8_t device = (uint8_t)atoi(argv[1]); const uint8_t* data = (uint8_t*)argv[2]; const size_t dataLength = strlen(argv[2]); uint8_t output[20] = {0}; size_t outputLength = dataLength; const I2CResult result = bus->WriteRead(bus, device, data, dataLength, output, outputLength); if (result == I2CResultOK) { TerminalPuts((char*)output); } else { TerminalPrintf("Error %d\n", result); } }
# ... existing code ... void I2CTestCommandHandler(uint16_t argc, char* argv[]) { UNREFERENCED_PARAMETER(argc); if (argc != 3) { TerminalPuts("i2c <system|payload> <device> <data>\n"); return; } I2CBus* bus; # ... rest of the code ...
6c9e1c31794c866e07f7fd514c5e5a8bc798843d
src/tropicalescape/Flag.java
src/tropicalescape/Flag.java
package tropicalescape; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import tropicalescape.physics.Hitbox; public class Flag extends GameObject { static final int DESC_HEIGHT_SHIFT = 15; static final String IMG_FILE = "res/flag.png"; String m_desc; static Image m_img; static { try { m_img = new Image(IMG_FILE); } catch (SlickException e) { e.printStackTrace(); } } Flag(String desc, float x, float y) { super(new Hitbox()); m_desc = desc; getPosition().x = x; getPosition().y = y; } @Override public void render(Graphics g) { m_img.draw(); if (getPosition().y - DESC_HEIGHT_SHIFT < 0) { g.drawString(m_desc, 0, m_img.getHeight()); } else { g.drawString(m_desc, 0, -DESC_HEIGHT_SHIFT); } } @Override public void update(int delta) { } }
package tropicalescape; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import org.newdawn.slick.geom.Vector2f; import tropicalescape.physics.Hitbox; public class Flag extends GameObject { static final int DESC_HEIGHT_SHIFT = 15; static final String IMG_FILE = "res/flag.png"; String m_desc; static Image m_img; static { try { m_img = new Image(IMG_FILE); } catch (SlickException e) { e.printStackTrace(); } } Flag(String desc, float x, float y) { super(new Hitbox()); m_desc = desc; getPosition().x = x; getPosition().y = y; } @Override public void render(Graphics g) { Vector2f pos = getPosition(); m_img.draw(pos.x, pos.y); if (getPosition().y - DESC_HEIGHT_SHIFT < 0) { g.drawString(m_desc, pos.x, m_img.getHeight()); } else { g.drawString(m_desc, pos.x, pos.y - DESC_HEIGHT_SHIFT); } } @Override public void update(int delta) { } }
Fix : Render du flag
Fix : Render du flag
Java
mit
jmcomets/tropical-escape,jmcomets/tropical-escape
java
## Code Before: package tropicalescape; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import tropicalescape.physics.Hitbox; public class Flag extends GameObject { static final int DESC_HEIGHT_SHIFT = 15; static final String IMG_FILE = "res/flag.png"; String m_desc; static Image m_img; static { try { m_img = new Image(IMG_FILE); } catch (SlickException e) { e.printStackTrace(); } } Flag(String desc, float x, float y) { super(new Hitbox()); m_desc = desc; getPosition().x = x; getPosition().y = y; } @Override public void render(Graphics g) { m_img.draw(); if (getPosition().y - DESC_HEIGHT_SHIFT < 0) { g.drawString(m_desc, 0, m_img.getHeight()); } else { g.drawString(m_desc, 0, -DESC_HEIGHT_SHIFT); } } @Override public void update(int delta) { } } ## Instruction: Fix : Render du flag ## Code After: package tropicalescape; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import org.newdawn.slick.geom.Vector2f; import tropicalescape.physics.Hitbox; public class Flag extends GameObject { static final int DESC_HEIGHT_SHIFT = 15; static final String IMG_FILE = "res/flag.png"; String m_desc; static Image m_img; static { try { m_img = new Image(IMG_FILE); } catch (SlickException e) { e.printStackTrace(); } } Flag(String desc, float x, float y) { super(new Hitbox()); m_desc = desc; getPosition().x = x; getPosition().y = y; } @Override public void render(Graphics g) { Vector2f pos = getPosition(); m_img.draw(pos.x, pos.y); if (getPosition().y - DESC_HEIGHT_SHIFT < 0) { g.drawString(m_desc, pos.x, m_img.getHeight()); } else { g.drawString(m_desc, pos.x, pos.y - DESC_HEIGHT_SHIFT); } } @Override public void update(int delta) { } }
# ... existing code ... import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import org.newdawn.slick.geom.Vector2f; import tropicalescape.physics.Hitbox; # ... modified code ... @Override public void render(Graphics g) { Vector2f pos = getPosition(); m_img.draw(pos.x, pos.y); if (getPosition().y - DESC_HEIGHT_SHIFT < 0) { g.drawString(m_desc, pos.x, m_img.getHeight()); } else { g.drawString(m_desc, pos.x, pos.y - DESC_HEIGHT_SHIFT); } } # ... rest of the code ...
f127f0e9bb0b8778feafbdbc1fa68e79a923d639
whats_fresh/whats_fresh_api/tests/views/entry/test_list_products.py
whats_fresh/whats_fresh_api/tests/views/entry/test_list_products.py
from django.test import TestCase from django.core.urlresolvers import reverse from whats_fresh_api.models import * from django.contrib.gis.db import models import json class ListProductTestCase(TestCase): fixtures = ['test_fixtures'] def test_url_endpoint(self): url = reverse('entry-list-products') self.assertEqual(url, '/entry/products') def test_list_items(self): """ Tests to see if the list of products contains the proper productss and proper product data """ response = self.client.get(reverse('entry-list-products')) items = response.context['item_list'] for product in Product.objects.all(): self.assertEqual( items[product.id-1]['description'], product.description) self.assertEqual( items[product.id-1]['name'], product.name) self.assertEqual( items[product.id-1]['link'], reverse('edit-product', kwargs={'id': product.id})) self.assertEqual( items[product.id-1]['modified'], product.modified.strftime("%I:%M %P, %d %b %Y")) self.assertEqual( sort(items[product.id-1]['preparations']), sort([prep.name for prep in product.preparations.all()]))
from django.test import TestCase from django.core.urlresolvers import reverse from whats_fresh_api.models import * from django.contrib.gis.db import models import json class ListProductTestCase(TestCase): fixtures = ['test_fixtures'] def test_url_endpoint(self): url = reverse('entry-list-products') self.assertEqual(url, '/entry/products') def test_list_items(self): """ Tests to see if the list of products contains the proper products and proper product data """ response = self.client.get(reverse('entry-list-products')) items = response.context['item_list'] product_dict = {} for product in items: product_id = product['link'].split('/')[-1] product_dict[str(product_id)] = product for product in Product.objects.all(): self.assertEqual( product_dict[str(product.id)]['description'], product.description) self.assertEqual( product_dict[str(product.id)]['name'], product.name) self.assertEqual( product_dict[str(product.id)]['link'], reverse('edit-product', kwargs={'id': product.id})) self.assertEqual( product_dict[str(product.id)]['modified'], product.modified.strftime("%I:%M %P, %d %b %Y")) self.assertEqual( sort(product_dict[str(product.id)]['preparations']), sort([prep.name for prep in product.preparations.all()]))
Update product listing test to use product ids rather than index
Update product listing test to use product ids rather than index
Python
apache-2.0
osu-cass/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api
python
## Code Before: from django.test import TestCase from django.core.urlresolvers import reverse from whats_fresh_api.models import * from django.contrib.gis.db import models import json class ListProductTestCase(TestCase): fixtures = ['test_fixtures'] def test_url_endpoint(self): url = reverse('entry-list-products') self.assertEqual(url, '/entry/products') def test_list_items(self): """ Tests to see if the list of products contains the proper productss and proper product data """ response = self.client.get(reverse('entry-list-products')) items = response.context['item_list'] for product in Product.objects.all(): self.assertEqual( items[product.id-1]['description'], product.description) self.assertEqual( items[product.id-1]['name'], product.name) self.assertEqual( items[product.id-1]['link'], reverse('edit-product', kwargs={'id': product.id})) self.assertEqual( items[product.id-1]['modified'], product.modified.strftime("%I:%M %P, %d %b %Y")) self.assertEqual( sort(items[product.id-1]['preparations']), sort([prep.name for prep in product.preparations.all()])) ## Instruction: Update product listing test to use product ids rather than index ## Code After: from django.test import TestCase from django.core.urlresolvers import reverse from whats_fresh_api.models import * from django.contrib.gis.db import models import json class ListProductTestCase(TestCase): fixtures = ['test_fixtures'] def test_url_endpoint(self): url = reverse('entry-list-products') self.assertEqual(url, '/entry/products') def test_list_items(self): """ Tests to see if the list of products contains the proper products and proper product data """ response = self.client.get(reverse('entry-list-products')) items = response.context['item_list'] product_dict = {} for product in items: product_id = product['link'].split('/')[-1] product_dict[str(product_id)] = product for product in Product.objects.all(): self.assertEqual( product_dict[str(product.id)]['description'], product.description) self.assertEqual( product_dict[str(product.id)]['name'], product.name) self.assertEqual( product_dict[str(product.id)]['link'], reverse('edit-product', kwargs={'id': product.id})) self.assertEqual( product_dict[str(product.id)]['modified'], product.modified.strftime("%I:%M %P, %d %b %Y")) self.assertEqual( sort(product_dict[str(product.id)]['preparations']), sort([prep.name for prep in product.preparations.all()]))
// ... existing code ... def test_list_items(self): """ Tests to see if the list of products contains the proper products and proper product data """ response = self.client.get(reverse('entry-list-products')) items = response.context['item_list'] product_dict = {} for product in items: product_id = product['link'].split('/')[-1] product_dict[str(product_id)] = product for product in Product.objects.all(): self.assertEqual( product_dict[str(product.id)]['description'], product.description) self.assertEqual( product_dict[str(product.id)]['name'], product.name) self.assertEqual( product_dict[str(product.id)]['link'], reverse('edit-product', kwargs={'id': product.id})) self.assertEqual( product_dict[str(product.id)]['modified'], product.modified.strftime("%I:%M %P, %d %b %Y")) self.assertEqual( sort(product_dict[str(product.id)]['preparations']), sort([prep.name for prep in product.preparations.all()])) // ... rest of the code ...
b591e630340e6d3906426ec1ef62329a9e696c1a
src/main/java/com/akiban/cserver/MySQLErrorConstants.java
src/main/java/com/akiban/cserver/MySQLErrorConstants.java
package com.akiban.cserver; /** * Constants derived from MySQL include/my_base.h * Add new MySQL error codes here, as needed. * * @author peter * */ public interface MySQLErrorConstants { public final static short HA_ERR_KEY_NOT_FOUND = 120; public final static short HA_ERR_FOUND_DUPP_KEY = 121; public final static short HA_ERR_INTERNAL_ERROR = 122; public final static short HA_ERR_RECORD_CHANGED = 123; public final static short HA_ERR_RECORD_DELETED = 134; public final static short HA_ERR_NO_REFERENCED_ROW = 151; public final static short HA_ERR_ROW_IS_REFERENCED = 152; public final static short HA_ERR_NO_SUCH_TABLE = 155; }
package com.akiban.cserver; /** * Constants derived from MySQL include/my_base.h * Add new MySQL error codes here, as needed. * * @author peter * */ public interface MySQLErrorConstants { public final static short HA_ERR_KEY_NOT_FOUND = 120; public final static short HA_ERR_FOUND_DUPP_KEY = 121; public final static short HA_ERR_INTERNAL_ERROR = 122; public final static short HA_ERR_RECORD_CHANGED = 123; public final static short HA_ERR_RECORD_DELETED = 134; public final static short HA_ERR_UNSUPPORTED = 138; public final static short HA_ERR_NO_REFERENCED_ROW = 151; public final static short HA_ERR_ROW_IS_REFERENCED = 152; public final static short HA_ERR_NO_SUCH_TABLE = 155; }
Add a HA_ERR_UNSUPPORTED error to return if functionality isn't supported, rather than the generic UNSUPPORTED.
Add a HA_ERR_UNSUPPORTED error to return if functionality isn't supported, rather than the generic UNSUPPORTED.
Java
agpl-3.0
shunwang/sql-layer-1,wfxiang08/sql-layer-1,shunwang/sql-layer-1,qiuyesuifeng/sql-layer,relateiq/sql-layer,ngaut/sql-layer,ngaut/sql-layer,wfxiang08/sql-layer-1,jaytaylor/sql-layer,qiuyesuifeng/sql-layer,ngaut/sql-layer,wfxiang08/sql-layer-1,qiuyesuifeng/sql-layer,wfxiang08/sql-layer-1,shunwang/sql-layer-1,relateiq/sql-layer,ngaut/sql-layer,shunwang/sql-layer-1,relateiq/sql-layer,jaytaylor/sql-layer,jaytaylor/sql-layer,jaytaylor/sql-layer,relateiq/sql-layer,qiuyesuifeng/sql-layer
java
## Code Before: package com.akiban.cserver; /** * Constants derived from MySQL include/my_base.h * Add new MySQL error codes here, as needed. * * @author peter * */ public interface MySQLErrorConstants { public final static short HA_ERR_KEY_NOT_FOUND = 120; public final static short HA_ERR_FOUND_DUPP_KEY = 121; public final static short HA_ERR_INTERNAL_ERROR = 122; public final static short HA_ERR_RECORD_CHANGED = 123; public final static short HA_ERR_RECORD_DELETED = 134; public final static short HA_ERR_NO_REFERENCED_ROW = 151; public final static short HA_ERR_ROW_IS_REFERENCED = 152; public final static short HA_ERR_NO_SUCH_TABLE = 155; } ## Instruction: Add a HA_ERR_UNSUPPORTED error to return if functionality isn't supported, rather than the generic UNSUPPORTED. ## Code After: package com.akiban.cserver; /** * Constants derived from MySQL include/my_base.h * Add new MySQL error codes here, as needed. * * @author peter * */ public interface MySQLErrorConstants { public final static short HA_ERR_KEY_NOT_FOUND = 120; public final static short HA_ERR_FOUND_DUPP_KEY = 121; public final static short HA_ERR_INTERNAL_ERROR = 122; public final static short HA_ERR_RECORD_CHANGED = 123; public final static short HA_ERR_RECORD_DELETED = 134; public final static short HA_ERR_UNSUPPORTED = 138; public final static short HA_ERR_NO_REFERENCED_ROW = 151; public final static short HA_ERR_ROW_IS_REFERENCED = 152; public final static short HA_ERR_NO_SUCH_TABLE = 155; }
... public final static short HA_ERR_INTERNAL_ERROR = 122; public final static short HA_ERR_RECORD_CHANGED = 123; public final static short HA_ERR_RECORD_DELETED = 134; public final static short HA_ERR_UNSUPPORTED = 138; public final static short HA_ERR_NO_REFERENCED_ROW = 151; public final static short HA_ERR_ROW_IS_REFERENCED = 152; public final static short HA_ERR_NO_SUCH_TABLE = 155; ...
5e1815f094f40b527406a07ea1ce751ee0b074a6
tests/__init__.py
tests/__init__.py
tests = ( 'parse_token', 'variable_fields', 'filters', 'blockextend', 'template', )
tests = ( 'parse_token', 'variable_fields', 'filters', 'default_filters', 'blockextend', 'template', )
Add defaults filters tests into all tests list
Add defaults filters tests into all tests list
Python
bsd-3-clause
GrAndSE/lighty-template,GrAndSE/lighty
python
## Code Before: tests = ( 'parse_token', 'variable_fields', 'filters', 'blockextend', 'template', ) ## Instruction: Add defaults filters tests into all tests list ## Code After: tests = ( 'parse_token', 'variable_fields', 'filters', 'default_filters', 'blockextend', 'template', )
... 'parse_token', 'variable_fields', 'filters', 'default_filters', 'blockextend', 'template', ) ...
3e2606c9ef5aa5e389469d8414d4a7b79f1b07b5
colplus-common-dw/src/main/java/org/col/dw/jersey/filter/Null404ResponseFilter.java
colplus-common-dw/src/main/java/org/col/dw/jersey/filter/Null404ResponseFilter.java
package org.col.dw.jersey.filter; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.Response; import java.io.IOException; import java.net.HttpURLConnection; /** * Filter that returns a 404 instead of 204 for null results with GET requests. */ public class Null404ResponseFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException { if (!response.hasEntity() && request.getMethod() != null && "get".equalsIgnoreCase(request.getMethod()) && (response.getStatusInfo() == null || response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) ) { response.setStatus(HttpURLConnection.HTTP_NOT_FOUND); } } }
package org.col.dw.jersey.filter; import javax.ws.rs.NotFoundException; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.Response; import java.io.IOException; /** * Filter that returns a 404 instead of 204 for null results with GET requests. */ public class Null404ResponseFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException { if (!response.hasEntity() && request.getMethod() != null && "get".equalsIgnoreCase(request.getMethod()) && (response.getStatusInfo() == null || response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) ) { throw new NotFoundException(); } } }
Throw exception instead of returning 404 manually to get the standard json
Throw exception instead of returning 404 manually to get the standard json
Java
apache-2.0
Sp2000/colplus-backend
java
## Code Before: package org.col.dw.jersey.filter; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.Response; import java.io.IOException; import java.net.HttpURLConnection; /** * Filter that returns a 404 instead of 204 for null results with GET requests. */ public class Null404ResponseFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException { if (!response.hasEntity() && request.getMethod() != null && "get".equalsIgnoreCase(request.getMethod()) && (response.getStatusInfo() == null || response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) ) { response.setStatus(HttpURLConnection.HTTP_NOT_FOUND); } } } ## Instruction: Throw exception instead of returning 404 manually to get the standard json ## Code After: package org.col.dw.jersey.filter; import javax.ws.rs.NotFoundException; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.Response; import java.io.IOException; /** * Filter that returns a 404 instead of 204 for null results with GET requests. */ public class Null404ResponseFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException { if (!response.hasEntity() && request.getMethod() != null && "get".equalsIgnoreCase(request.getMethod()) && (response.getStatusInfo() == null || response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) ) { throw new NotFoundException(); } } }
... package org.col.dw.jersey.filter; import javax.ws.rs.NotFoundException; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.Response; import java.io.IOException; /** * Filter that returns a 404 instead of 204 for null results with GET requests. ... && request.getMethod() != null && "get".equalsIgnoreCase(request.getMethod()) && (response.getStatusInfo() == null || response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) ) { throw new NotFoundException(); } } } ...
10ec59777c0b364e05dc022ac3178d0c6d0ca916
plugin/formatters.py
plugin/formatters.py
import json from collections import OrderedDict def format_json(input, settings=None): indent = 4 if settings: indent = settings.get('tab_size', indent) try: data = json.loads(input, object_pairs_hook=OrderedDict) return json.dumps(data, indent=indent, separators=(',', ': ')), None except ValueError: return None, 'Invalid JSON'
import json from collections import OrderedDict def format_json(input, settings=None): indent = 4 if settings: indent = settings.get('tab_size', indent) try: data = json.loads(input, object_pairs_hook=OrderedDict) return True, json.dumps(data, indent=indent, separators=(',', ': ')), None except ValueError: return False, None, 'Invalid JSON'
Fix parsing of JSON formatting errors
Fix parsing of JSON formatting errors
Python
mit
Rypac/sublime-format
python
## Code Before: import json from collections import OrderedDict def format_json(input, settings=None): indent = 4 if settings: indent = settings.get('tab_size', indent) try: data = json.loads(input, object_pairs_hook=OrderedDict) return json.dumps(data, indent=indent, separators=(',', ': ')), None except ValueError: return None, 'Invalid JSON' ## Instruction: Fix parsing of JSON formatting errors ## Code After: import json from collections import OrderedDict def format_json(input, settings=None): indent = 4 if settings: indent = settings.get('tab_size', indent) try: data = json.loads(input, object_pairs_hook=OrderedDict) return True, json.dumps(data, indent=indent, separators=(',', ': ')), None except ValueError: return False, None, 'Invalid JSON'
... indent = settings.get('tab_size', indent) try: data = json.loads(input, object_pairs_hook=OrderedDict) return True, json.dumps(data, indent=indent, separators=(',', ': ')), None except ValueError: return False, None, 'Invalid JSON' ...
cdce7bd7f4d0a1114f9db3b94a62e5dd70130a09
Include/dictobject.h
Include/dictobject.h
/* Dictionary object type -- mapping from char * to object. NB: the key is given as a char *, not as a stringobject. These functions set errno for errors. Functions dictremove() and dictinsert() return nonzero for errors, getdictsize() returns -1, the others NULL. A successful call to dictinsert() calls INCREF() for the inserted item. */ extern typeobject Dicttype; #define is_dictobject(op) ((op)->ob_type == &Dicttype) extern object *newdictobject PROTO((void)); extern object *dictlookup PROTO((object *dp, char *key)); extern int dictinsert PROTO((object *dp, char *key, object *item)); extern int dictremove PROTO((object *dp, char *key)); extern int getdictsize PROTO((object *dp)); extern char *getdictkey PROTO((object *dp, int i)); /* New interface with (string)object * instead of char * arguments */ extern object *dict2lookup PROTO((object *dp, object *key)); extern int dict2insert PROTO((object *dp, object *key, object *item)); extern int dict2remove PROTO((object *dp, object *key)); extern object *getdict2key PROTO((object *dp, int i));
/* Dictionary object type -- mapping from char * to object. NB: the key is given as a char *, not as a stringobject. These functions set errno for errors. Functions dictremove() and dictinsert() return nonzero for errors, getdictsize() returns -1, the others NULL. A successful call to dictinsert() calls INCREF() for the inserted item. */ extern typeobject Dicttype; #define is_dictobject(op) ((op)->ob_type == &Dicttype) extern object *newdictobject PROTO((void)); extern object *dictlookup PROTO((object *dp, char *key)); extern int dictinsert PROTO((object *dp, char *key, object *item)); extern int dictremove PROTO((object *dp, char *key)); extern int getdictsize PROTO((object *dp)); extern char *getdictkey PROTO((object *dp, int i));
Remove dict2 interface -- it's now static.
Remove dict2 interface -- it's now static.
C
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
c
## Code Before: /* Dictionary object type -- mapping from char * to object. NB: the key is given as a char *, not as a stringobject. These functions set errno for errors. Functions dictremove() and dictinsert() return nonzero for errors, getdictsize() returns -1, the others NULL. A successful call to dictinsert() calls INCREF() for the inserted item. */ extern typeobject Dicttype; #define is_dictobject(op) ((op)->ob_type == &Dicttype) extern object *newdictobject PROTO((void)); extern object *dictlookup PROTO((object *dp, char *key)); extern int dictinsert PROTO((object *dp, char *key, object *item)); extern int dictremove PROTO((object *dp, char *key)); extern int getdictsize PROTO((object *dp)); extern char *getdictkey PROTO((object *dp, int i)); /* New interface with (string)object * instead of char * arguments */ extern object *dict2lookup PROTO((object *dp, object *key)); extern int dict2insert PROTO((object *dp, object *key, object *item)); extern int dict2remove PROTO((object *dp, object *key)); extern object *getdict2key PROTO((object *dp, int i)); ## Instruction: Remove dict2 interface -- it's now static. ## Code After: /* Dictionary object type -- mapping from char * to object. NB: the key is given as a char *, not as a stringobject. These functions set errno for errors. Functions dictremove() and dictinsert() return nonzero for errors, getdictsize() returns -1, the others NULL. A successful call to dictinsert() calls INCREF() for the inserted item. */ extern typeobject Dicttype; #define is_dictobject(op) ((op)->ob_type == &Dicttype) extern object *newdictobject PROTO((void)); extern object *dictlookup PROTO((object *dp, char *key)); extern int dictinsert PROTO((object *dp, char *key, object *item)); extern int dictremove PROTO((object *dp, char *key)); extern int getdictsize PROTO((object *dp)); extern char *getdictkey PROTO((object *dp, int i));
# ... existing code ... extern int dictremove PROTO((object *dp, char *key)); extern int getdictsize PROTO((object *dp)); extern char *getdictkey PROTO((object *dp, int i)); # ... rest of the code ...
63a7b11d3ae51a944bf2e70637dea503e455c2f5
fontdump/cli.py
fontdump/cli.py
from collections import OrderedDict import requests import cssutils USER_AGENTS = OrderedDict() USER_AGENTS['woff'] = 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome USER_AGENTS['ttf'] = 'Mozilla/5.0 (Linux; U; Android 2.1-update1;)', #Andord 2 USER_AGENTS['eot'] = 'Mozilla/4.0 (compatible; MSIE 6.0;)', # IE6 USER_AGENTS['woff'] = 'Mozilla/4.0 (iPad; CPU OS 4_0_1 ) AppleWebKit', #iOS<4.2 def main(): font_url = 'http://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800|Dosis:300,400' sheets={} for (format, ua) in USER_AGENTS.items(): headers = { 'User-Agent': ua, } r =requests.get(font_url, headers=headers) sheets[format] = cssutils.parseString(r.content) if __name__ == '__main__': main()
import requests import cssutils USER_AGENTS = { 'woff': 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome 'eot': 'Mozilla/4.0 (compatible; MSIE 6.0;)', # IE6 'ttf': 'Mozilla/5.0 (Linux; U; Android 2.1-update1;)', #Andord 2 'svg': 'Mozilla/4.0 (iPad; CPU OS 4_0_1 ) AppleWebKit', #iOS<4.2 } def main(): font_url = 'http://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800|Dosis:300,400' sheets={} for (format, ua) in USER_AGENTS.items(): headers = { 'User-Agent': ua, } r =requests.get(font_url, headers=headers) sheets[format] = cssutils.parseString(r.content) if __name__ == '__main__': main()
Revert "The order of the formats matters. Use OrderedDict instead of dict"
Revert "The order of the formats matters. Use OrderedDict instead of dict" I can't rely on the order of dict. The control flow is more complex. This reverts commit 3389ed71971ddacd185bbbf8fe667a8651108c70.
Python
mit
glasslion/fontdump
python
## Code Before: from collections import OrderedDict import requests import cssutils USER_AGENTS = OrderedDict() USER_AGENTS['woff'] = 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome USER_AGENTS['ttf'] = 'Mozilla/5.0 (Linux; U; Android 2.1-update1;)', #Andord 2 USER_AGENTS['eot'] = 'Mozilla/4.0 (compatible; MSIE 6.0;)', # IE6 USER_AGENTS['woff'] = 'Mozilla/4.0 (iPad; CPU OS 4_0_1 ) AppleWebKit', #iOS<4.2 def main(): font_url = 'http://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800|Dosis:300,400' sheets={} for (format, ua) in USER_AGENTS.items(): headers = { 'User-Agent': ua, } r =requests.get(font_url, headers=headers) sheets[format] = cssutils.parseString(r.content) if __name__ == '__main__': main() ## Instruction: Revert "The order of the formats matters. Use OrderedDict instead of dict" I can't rely on the order of dict. The control flow is more complex. This reverts commit 3389ed71971ddacd185bbbf8fe667a8651108c70. ## Code After: import requests import cssutils USER_AGENTS = { 'woff': 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome 'eot': 'Mozilla/4.0 (compatible; MSIE 6.0;)', # IE6 'ttf': 'Mozilla/5.0 (Linux; U; Android 2.1-update1;)', #Andord 2 'svg': 'Mozilla/4.0 (iPad; CPU OS 4_0_1 ) AppleWebKit', #iOS<4.2 } def main(): font_url = 'http://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800|Dosis:300,400' sheets={} for (format, ua) in USER_AGENTS.items(): headers = { 'User-Agent': ua, } r =requests.get(font_url, headers=headers) sheets[format] = cssutils.parseString(r.content) if __name__ == '__main__': main()
# ... existing code ... import requests import cssutils USER_AGENTS = { 'woff': 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome 'eot': 'Mozilla/4.0 (compatible; MSIE 6.0;)', # IE6 'ttf': 'Mozilla/5.0 (Linux; U; Android 2.1-update1;)', #Andord 2 'svg': 'Mozilla/4.0 (iPad; CPU OS 4_0_1 ) AppleWebKit', #iOS<4.2 } def main(): font_url = 'http://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800|Dosis:300,400' # ... rest of the code ...
bdb46e88fb9ee14b6c12d2b9aa5087cfe973492c
pontoon/base/__init__.py
pontoon/base/__init__.py
"""Application base, containing global templates.""" default_app_config = 'pontoon.base.apps.BaseConfig' MOZILLA_REPOS = ( 'ssh://hg.mozilla.org/users/m_owca.info/firefox-aurora/', 'ssh://hg.mozilla.org/users/m_owca.info/firefox-for-android-aurora/', 'ssh://hg.mozilla.org/users/m_owca.info/thunderbird-aurora/', 'ssh://hg.mozilla.org/users/m_owca.info/lightning-aurora/', 'ssh://hg.mozilla.org/users/m_owca.info/seamonkey-aurora/', ) class SyncError(RuntimeError): """Error class for errors relating to the project sync process."""
"""Application base, containing global templates.""" default_app_config = 'pontoon.base.apps.BaseConfig' MOZILLA_REPOS = ( 'ssh://hg.mozilla.org/users/m_owca.info/firefox-beta/', 'ssh://hg.mozilla.org/users/m_owca.info/firefox-for-android-beta/', 'ssh://hg.mozilla.org/users/m_owca.info/thunderbird-beta/', 'ssh://hg.mozilla.org/users/m_owca.info/lightning-beta/', 'ssh://hg.mozilla.org/users/m_owca.info/seamonkey-beta/', 'ssh://hg.mozilla.org/users/m_owca.info/firefox-aurora/', 'ssh://hg.mozilla.org/users/m_owca.info/firefox-for-android-aurora/', 'ssh://hg.mozilla.org/users/m_owca.info/thunderbird-aurora/', 'ssh://hg.mozilla.org/users/m_owca.info/lightning-aurora/', 'ssh://hg.mozilla.org/users/m_owca.info/seamonkey-aurora/', ) class SyncError(RuntimeError): """Error class for errors relating to the project sync process."""
Make Mozilla Beta repositories special
Make Mozilla Beta repositories special
Python
bsd-3-clause
yfdyh000/pontoon,jotes/pontoon,participedia/pontoon,m8ttyB/pontoon,m8ttyB/pontoon,mastizada/pontoon,jotes/pontoon,mathjazz/pontoon,mozilla/pontoon,jotes/pontoon,yfdyh000/pontoon,mathjazz/pontoon,mastizada/pontoon,yfdyh000/pontoon,jotes/pontoon,sudheesh001/pontoon,yfdyh000/pontoon,mastizada/pontoon,sudheesh001/pontoon,mozilla/pontoon,mathjazz/pontoon,mathjazz/pontoon,sudheesh001/pontoon,participedia/pontoon,sudheesh001/pontoon,m8ttyB/pontoon,mathjazz/pontoon,mozilla/pontoon,mozilla/pontoon,participedia/pontoon,participedia/pontoon,mozilla/pontoon,mastizada/pontoon,m8ttyB/pontoon
python
## Code Before: """Application base, containing global templates.""" default_app_config = 'pontoon.base.apps.BaseConfig' MOZILLA_REPOS = ( 'ssh://hg.mozilla.org/users/m_owca.info/firefox-aurora/', 'ssh://hg.mozilla.org/users/m_owca.info/firefox-for-android-aurora/', 'ssh://hg.mozilla.org/users/m_owca.info/thunderbird-aurora/', 'ssh://hg.mozilla.org/users/m_owca.info/lightning-aurora/', 'ssh://hg.mozilla.org/users/m_owca.info/seamonkey-aurora/', ) class SyncError(RuntimeError): """Error class for errors relating to the project sync process.""" ## Instruction: Make Mozilla Beta repositories special ## Code After: """Application base, containing global templates.""" default_app_config = 'pontoon.base.apps.BaseConfig' MOZILLA_REPOS = ( 'ssh://hg.mozilla.org/users/m_owca.info/firefox-beta/', 'ssh://hg.mozilla.org/users/m_owca.info/firefox-for-android-beta/', 'ssh://hg.mozilla.org/users/m_owca.info/thunderbird-beta/', 'ssh://hg.mozilla.org/users/m_owca.info/lightning-beta/', 'ssh://hg.mozilla.org/users/m_owca.info/seamonkey-beta/', 'ssh://hg.mozilla.org/users/m_owca.info/firefox-aurora/', 'ssh://hg.mozilla.org/users/m_owca.info/firefox-for-android-aurora/', 'ssh://hg.mozilla.org/users/m_owca.info/thunderbird-aurora/', 'ssh://hg.mozilla.org/users/m_owca.info/lightning-aurora/', 'ssh://hg.mozilla.org/users/m_owca.info/seamonkey-aurora/', ) class SyncError(RuntimeError): """Error class for errors relating to the project sync process."""
# ... existing code ... MOZILLA_REPOS = ( 'ssh://hg.mozilla.org/users/m_owca.info/firefox-beta/', 'ssh://hg.mozilla.org/users/m_owca.info/firefox-for-android-beta/', 'ssh://hg.mozilla.org/users/m_owca.info/thunderbird-beta/', 'ssh://hg.mozilla.org/users/m_owca.info/lightning-beta/', 'ssh://hg.mozilla.org/users/m_owca.info/seamonkey-beta/', 'ssh://hg.mozilla.org/users/m_owca.info/firefox-aurora/', 'ssh://hg.mozilla.org/users/m_owca.info/firefox-for-android-aurora/', 'ssh://hg.mozilla.org/users/m_owca.info/thunderbird-aurora/', # ... rest of the code ...
c79e6b16e29dc0c756bfe82d62b9e01a5702c47f
testanalyzer/pythonanalyzer.py
testanalyzer/pythonanalyzer.py
import re from fileanalyzer import FileAnalyzer class PythonAnalyzer(FileAnalyzer): def get_class_count(self, content): return len( re.findall("[^\"](class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:)+[^\"]", content)) def get_function_count(self, content): return len( re.findall("[^\"](def +[a-zA-Z0-9_]+ *\([a-zA-Z0-9_, ]*\) *:)+[^\"]", content))
import re from fileanalyzer import FileAnalyzer class PythonAnalyzer(FileAnalyzer): def get_class_count(self, content): matches = re.findall("\"*class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:\"*", content) matches = [m for m in matches if m.strip()[0] != "\"" and m.strip()[-1] != "\""] return len(matches) def get_function_count(self, content): matches = re.findall("\"*def +[a-zA-Z0-9_]+ *\([a-zA-Z0-9_, ]*\) *:\"*", content) matches = [m for m in matches if m.strip()[0] != "\"" and m.strip()[-1] != "\""] return len(matches)
Fix counter to ignore quoted lines
Fix counter to ignore quoted lines
Python
mpl-2.0
CheriPai/TestAnalyzer,CheriPai/TestAnalyzer,CheriPai/TestAnalyzer
python
## Code Before: import re from fileanalyzer import FileAnalyzer class PythonAnalyzer(FileAnalyzer): def get_class_count(self, content): return len( re.findall("[^\"](class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:)+[^\"]", content)) def get_function_count(self, content): return len( re.findall("[^\"](def +[a-zA-Z0-9_]+ *\([a-zA-Z0-9_, ]*\) *:)+[^\"]", content)) ## Instruction: Fix counter to ignore quoted lines ## Code After: import re from fileanalyzer import FileAnalyzer class PythonAnalyzer(FileAnalyzer): def get_class_count(self, content): matches = re.findall("\"*class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:\"*", content) matches = [m for m in matches if m.strip()[0] != "\"" and m.strip()[-1] != "\""] return len(matches) def get_function_count(self, content): matches = re.findall("\"*def +[a-zA-Z0-9_]+ *\([a-zA-Z0-9_, ]*\) *:\"*", content) matches = [m for m in matches if m.strip()[0] != "\"" and m.strip()[-1] != "\""] return len(matches)
... class PythonAnalyzer(FileAnalyzer): def get_class_count(self, content): matches = re.findall("\"*class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:\"*", content) matches = [m for m in matches if m.strip()[0] != "\"" and m.strip()[-1] != "\""] return len(matches) def get_function_count(self, content): matches = re.findall("\"*def +[a-zA-Z0-9_]+ *\([a-zA-Z0-9_, ]*\) *:\"*", content) matches = [m for m in matches if m.strip()[0] != "\"" and m.strip()[-1] != "\""] return len(matches) ...
b8d38bd9cf86508c1b129c756f9c6a73a1279599
src/main/java/com/blazzify/jasonium/ui/ServerTreeContextMenu.java
src/main/java/com/blazzify/jasonium/ui/ServerTreeContextMenu.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.blazzify.jasonium.ui; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; /** * * @author Azzuwan Aziz <[email protected]> */ public class ServerTreeContextMenu extends ContextMenu { MenuItem connect = new MenuItem("Connect"); MenuItem disconnect = new MenuItem("Disconnect"); MenuItem remove = new MenuItem("Remove"); public ServerTreeContextMenu() { connect.setOnAction((event) -> { Alert alert = new Alert(Alert.AlertType.INFORMATION, "Connecting!", ButtonType.OK); }); disconnect.setOnAction((event) -> { }); remove.setOnAction((event) -> { }); this.getItems().addAll(connect, disconnect, remove); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.blazzify.jasonium.ui; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; /** * * @author Azzuwan Aziz <[email protected]> */ public class ServerTreeContextMenu extends ContextMenu { MenuItem connect = new MenuItem("Connect"); MenuItem disconnect = new MenuItem("Disconnect"); MenuItem remove = new MenuItem("Remove"); public ServerTreeContextMenu() { connect.setOnAction((event) -> { Alert alert = new Alert(Alert.AlertType.INFORMATION, "Connecting!", ButtonType.OK); alert.showAndWait(); }); disconnect.setOnAction((event) -> { }); remove.setOnAction((event) -> { }); this.getItems().addAll(connect, disconnect, remove); } }
Refactor server tree context menu into it's own component
Refactor server tree context menu into it's own component
Java
mit
azzuwan/Jasonium
java
## Code Before: /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.blazzify.jasonium.ui; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; /** * * @author Azzuwan Aziz <[email protected]> */ public class ServerTreeContextMenu extends ContextMenu { MenuItem connect = new MenuItem("Connect"); MenuItem disconnect = new MenuItem("Disconnect"); MenuItem remove = new MenuItem("Remove"); public ServerTreeContextMenu() { connect.setOnAction((event) -> { Alert alert = new Alert(Alert.AlertType.INFORMATION, "Connecting!", ButtonType.OK); }); disconnect.setOnAction((event) -> { }); remove.setOnAction((event) -> { }); this.getItems().addAll(connect, disconnect, remove); } } ## Instruction: Refactor server tree context menu into it's own component ## Code After: /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.blazzify.jasonium.ui; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; /** * * @author Azzuwan Aziz <[email protected]> */ public class ServerTreeContextMenu extends ContextMenu { MenuItem connect = new MenuItem("Connect"); MenuItem disconnect = new MenuItem("Disconnect"); MenuItem remove = new MenuItem("Remove"); public ServerTreeContextMenu() { connect.setOnAction((event) -> { Alert alert = new Alert(Alert.AlertType.INFORMATION, "Connecting!", ButtonType.OK); alert.showAndWait(); }); disconnect.setOnAction((event) -> { }); remove.setOnAction((event) -> { }); this.getItems().addAll(connect, disconnect, remove); } }
# ... existing code ... public ServerTreeContextMenu() { connect.setOnAction((event) -> { Alert alert = new Alert(Alert.AlertType.INFORMATION, "Connecting!", ButtonType.OK); alert.showAndWait(); }); disconnect.setOnAction((event) -> { }); # ... rest of the code ...
83c5cc34539f68360cbab585af9465e95f3ec592
tensorbayes/__init__.py
tensorbayes/__init__.py
from . import layers from . import utils from . import nputils from . import tbutils from . import distributions from .utils import FileWriter from .tbutils import function
import sys from . import layers from . import utils from . import nputils from . import tbutils from . import distributions from .utils import FileWriter from .tbutils import function if 'ipykernel' in sys.argv[0]: from . import nbutils
Add nbutils import to base import
Add nbutils import to base import
Python
mit
RuiShu/tensorbayes
python
## Code Before: from . import layers from . import utils from . import nputils from . import tbutils from . import distributions from .utils import FileWriter from .tbutils import function ## Instruction: Add nbutils import to base import ## Code After: import sys from . import layers from . import utils from . import nputils from . import tbutils from . import distributions from .utils import FileWriter from .tbutils import function if 'ipykernel' in sys.argv[0]: from . import nbutils
... import sys from . import layers from . import utils from . import nputils ... from . import distributions from .utils import FileWriter from .tbutils import function if 'ipykernel' in sys.argv[0]: from . import nbutils ...
64086acee22cfc2dde2fec9da1ea1b7745ce3d85
tests/misc/test_base_model.py
tests/misc/test_base_model.py
from tests.base import ApiDBTestCase class BaseModelTestCase(ApiDBTestCase): def test_repr(self): self.generate_fixture_project_status() self.generate_fixture_project() self.assertEqual(str(self.project), "<Project %s>" % self.project.name) def test_query(self): pass def test_get(self): pass def test_get_by(self): pass def test_get_all_by(self): pass def test_create(self): pass def test_get_id_map(self): pass def save(self): pass def delete(self): pass def update(self): pass
from tests.base import ApiDBTestCase class BaseModelTestCase(ApiDBTestCase): def test_query(self): pass def test_get(self): pass def test_get_by(self): pass def test_get_all_by(self): pass def test_create(self): pass def test_get_id_map(self): pass def save(self): pass def delete(self): pass def update(self): pass
Remove useless test about model representation
Remove useless test about model representation
Python
agpl-3.0
cgwire/zou
python
## Code Before: from tests.base import ApiDBTestCase class BaseModelTestCase(ApiDBTestCase): def test_repr(self): self.generate_fixture_project_status() self.generate_fixture_project() self.assertEqual(str(self.project), "<Project %s>" % self.project.name) def test_query(self): pass def test_get(self): pass def test_get_by(self): pass def test_get_all_by(self): pass def test_create(self): pass def test_get_id_map(self): pass def save(self): pass def delete(self): pass def update(self): pass ## Instruction: Remove useless test about model representation ## Code After: from tests.base import ApiDBTestCase class BaseModelTestCase(ApiDBTestCase): def test_query(self): pass def test_get(self): pass def test_get_by(self): pass def test_get_all_by(self): pass def test_create(self): pass def test_get_id_map(self): pass def save(self): pass def delete(self): pass def update(self): pass
... class BaseModelTestCase(ApiDBTestCase): def test_query(self): pass ...
1642bf91ab9042fddb3fcdeb7d2d8d010979c978
disasm.py
disasm.py
import MOS6502 import instructions def disasm(memory, maxLines=0, address=-1): index = 0 lines = [] while index < len(memory): currInst = instructions.instructions[memory[index]] if address > 0: line = format(address+index, '04x') + ": " else: line = '' line += currInst.mnem + " " line += currInst.operType + " " if currInst.size > 1: if 'ABS' in currInst.operType: line += hex(memory[index+1] + (memory[index+2] << 8)) else: for i in range(1, currInst.size): line += hex(memory[index + i]) + " " lines.append(line) index += currInst.size if maxLines != 0 and len(lines) == maxLines: return lines return lines
import MOS6502 import instructions import code def disasm(memory, maxLines=0, address=-1): index = 0 lines = [] while index < len(memory): opcode = memory[index] if opcode not in instructions.instructions.keys(): print "Undefined opcode: " + hex(opcode) code.interact(local=locals()) currInst = instructions.instructions[memory[index]] if address > 0: line = format(address+index, '04x') + ": " else: line = '' line += currInst.mnem + " " line += currInst.operType + " " if currInst.size > 1: if 'ABS' in currInst.operType: line += hex(memory[index+1] + (memory[index+2] << 8)) else: for i in range(1, currInst.size): line += hex(memory[index + i]) + " " lines.append(line) index += currInst.size if maxLines != 0 and len(lines) == maxLines: return lines return lines
Add catch for undefined opcodes
Add catch for undefined opcodes
Python
bsd-2-clause
pusscat/refNes
python
## Code Before: import MOS6502 import instructions def disasm(memory, maxLines=0, address=-1): index = 0 lines = [] while index < len(memory): currInst = instructions.instructions[memory[index]] if address > 0: line = format(address+index, '04x') + ": " else: line = '' line += currInst.mnem + " " line += currInst.operType + " " if currInst.size > 1: if 'ABS' in currInst.operType: line += hex(memory[index+1] + (memory[index+2] << 8)) else: for i in range(1, currInst.size): line += hex(memory[index + i]) + " " lines.append(line) index += currInst.size if maxLines != 0 and len(lines) == maxLines: return lines return lines ## Instruction: Add catch for undefined opcodes ## Code After: import MOS6502 import instructions import code def disasm(memory, maxLines=0, address=-1): index = 0 lines = [] while index < len(memory): opcode = memory[index] if opcode not in instructions.instructions.keys(): print "Undefined opcode: " + hex(opcode) code.interact(local=locals()) currInst = instructions.instructions[memory[index]] if address > 0: line = format(address+index, '04x') + ": " else: line = '' line += currInst.mnem + " " line += currInst.operType + " " if currInst.size > 1: if 'ABS' in currInst.operType: line += hex(memory[index+1] + (memory[index+2] << 8)) else: for i in range(1, currInst.size): line += hex(memory[index + i]) + " " lines.append(line) index += currInst.size if maxLines != 0 and len(lines) == maxLines: return lines return lines
// ... existing code ... import MOS6502 import instructions import code def disasm(memory, maxLines=0, address=-1): index = 0 // ... modified code ... lines = [] while index < len(memory): opcode = memory[index] if opcode not in instructions.instructions.keys(): print "Undefined opcode: " + hex(opcode) code.interact(local=locals()) currInst = instructions.instructions[memory[index]] if address > 0: // ... rest of the code ...
cebc280640017d412058c2bf40d31a5af3d82d32
Sources/Foundation/OCAFoundation.h
Sources/Foundation/OCAFoundation.h
// // ObjectiveChain.h // Objective-Chain // // Created by Martin Kiss on 30.12.13. // Copyright © 2014 Martin Kiss. All rights reserved. // /// Producers #import "OCAProducer.h" #import "OCACommand.h" #import "OCAHub.h" #import "OCAProperty.h" #import "OCAInvoker.h" #import "OCANotificator.h" #import "OCATimer.h" /// Mediators #import "OCAMediator.h" #import "OCABridge.h" #import "OCAContext.h" #import "OCAFilter.h" /// Consumers #import "OCAConsumer.h" #import "OCASubscriber.h" #import "OCAMulticast.h" /// Transformers #import "OCATransformer.h" /// Predicates #import "OCAPredicate.h" /// Utilities #import "OCAKeyPathAccessor.h" #import "OCAStructureAccessor.h" #import "OCAQueue.h" #import "OCASemaphore.h" #import "NSValue+Boxing.h" #import "NSArray+Ordinals.h" #import "OCADecomposer.h" #import "OCAInvocationCatcher.h"
// // ObjectiveChain.h // Objective-Chain // // Created by Martin Kiss on 30.12.13. // Copyright © 2014 Martin Kiss. All rights reserved. // /// Producers #import "OCAProducer.h" #import "OCACommand.h" #import "OCAHub.h" #import "OCAProperty.h" #import "OCATimer.h" #import "OCANotificator.h" /// Mediators #import "OCAMediator.h" #import "OCABridge.h" #import "OCAContext.h" #import "OCAFilter.h" #import "OCAThrottle.h" /// Consumers #import "OCAConsumer.h" #import "OCASubscriber.h" #import "OCAMulticast.h" #import "OCAInvoker.h" /// Transformers #import "OCATransformer.h" /// Predicates #import "OCAPredicate.h" /// Utilities #import "OCAKeyPathAccessor.h" #import "OCAStructureAccessor.h" #import "OCAQueue.h" #import "OCASemaphore.h" #import "NSValue+Boxing.h" #import "NSArray+Ordinals.h" #import "OCADecomposer.h" #import "OCAInvocationCatcher.h" #import "OCAKeyValueChange.h" #import "OCAVariadic.h" #import "OCAPlaceholderObject.h"
Add missing classes to Foundation import
Add missing classes to Foundation import
C
mit
Tricertops/Objective-Chain,iMartinKiss/Objective-Chain
c
## Code Before: // // ObjectiveChain.h // Objective-Chain // // Created by Martin Kiss on 30.12.13. // Copyright © 2014 Martin Kiss. All rights reserved. // /// Producers #import "OCAProducer.h" #import "OCACommand.h" #import "OCAHub.h" #import "OCAProperty.h" #import "OCAInvoker.h" #import "OCANotificator.h" #import "OCATimer.h" /// Mediators #import "OCAMediator.h" #import "OCABridge.h" #import "OCAContext.h" #import "OCAFilter.h" /// Consumers #import "OCAConsumer.h" #import "OCASubscriber.h" #import "OCAMulticast.h" /// Transformers #import "OCATransformer.h" /// Predicates #import "OCAPredicate.h" /// Utilities #import "OCAKeyPathAccessor.h" #import "OCAStructureAccessor.h" #import "OCAQueue.h" #import "OCASemaphore.h" #import "NSValue+Boxing.h" #import "NSArray+Ordinals.h" #import "OCADecomposer.h" #import "OCAInvocationCatcher.h" ## Instruction: Add missing classes to Foundation import ## Code After: // // ObjectiveChain.h // Objective-Chain // // Created by Martin Kiss on 30.12.13. // Copyright © 2014 Martin Kiss. All rights reserved. // /// Producers #import "OCAProducer.h" #import "OCACommand.h" #import "OCAHub.h" #import "OCAProperty.h" #import "OCATimer.h" #import "OCANotificator.h" /// Mediators #import "OCAMediator.h" #import "OCABridge.h" #import "OCAContext.h" #import "OCAFilter.h" #import "OCAThrottle.h" /// Consumers #import "OCAConsumer.h" #import "OCASubscriber.h" #import "OCAMulticast.h" #import "OCAInvoker.h" /// Transformers #import "OCATransformer.h" /// Predicates #import "OCAPredicate.h" /// Utilities #import "OCAKeyPathAccessor.h" #import "OCAStructureAccessor.h" #import "OCAQueue.h" #import "OCASemaphore.h" #import "NSValue+Boxing.h" #import "NSArray+Ordinals.h" #import "OCADecomposer.h" #import "OCAInvocationCatcher.h" #import "OCAKeyValueChange.h" #import "OCAVariadic.h" #import "OCAPlaceholderObject.h"
... #import "OCACommand.h" #import "OCAHub.h" #import "OCAProperty.h" #import "OCATimer.h" #import "OCANotificator.h" /// Mediators ... #import "OCABridge.h" #import "OCAContext.h" #import "OCAFilter.h" #import "OCAThrottle.h" /// Consumers ... #import "OCAConsumer.h" #import "OCASubscriber.h" #import "OCAMulticast.h" #import "OCAInvoker.h" /// Transformers ... #import "NSArray+Ordinals.h" #import "OCADecomposer.h" #import "OCAInvocationCatcher.h" #import "OCAKeyValueChange.h" #import "OCAVariadic.h" #import "OCAPlaceholderObject.h" ...
4147e6f560889c75abbfd9c8e85ea38ffe408550
suelta/mechanisms/facebook_platform.py
suelta/mechanisms/facebook_platform.py
from suelta.util import bytes from suelta.sasl import Mechanism, register_mechanism try: import urlparse except ImportError: import urllib.parse as urlparse class X_FACEBOOK_PLATFORM(Mechanism): def __init__(self, sasl, name): super(X_FACEBOOK_PLATFORM, self).__init__(sasl, name) self.check_values(['access_token', 'api_key']) def process(self, challenge=None): if challenge is not None: values = {} for kv in challenge.split('&'): key, value = kv.split('=') values[key] = value resp_data = { 'method': values['method'], 'v': '1.0', 'call_id': '1.0', 'nonce': values['nonce'], 'access_token': self.values['access_token'], 'api_key': self.values['api_key'] } resp = '&'.join(['%s=%s' % (k, v) for k, v in resp_data.items()]) return bytes(resp) return bytes('') def okay(self): return True register_mechanism('X-FACEBOOK-PLATFORM', 40, X_FACEBOOK_PLATFORM, use_hashes=False)
from suelta.util import bytes from suelta.sasl import Mechanism, register_mechanism try: import urlparse except ImportError: import urllib.parse as urlparse class X_FACEBOOK_PLATFORM(Mechanism): def __init__(self, sasl, name): super(X_FACEBOOK_PLATFORM, self).__init__(sasl, name) self.check_values(['access_token', 'api_key']) def process(self, challenge=None): if challenge is not None: values = {} for kv in challenge.split(b'&'): key, value = kv.split(b'=') values[key] = value resp_data = { b'method': values[b'method'], b'v': b'1.0', b'call_id': b'1.0', b'nonce': values[b'nonce'], b'access_token': self.values['access_token'], b'api_key': self.values['api_key'] } resp = '&'.join(['%s=%s' % (k, v) for k, v in resp_data.items()]) return bytes(resp) return b'' def okay(self): return True register_mechanism('X-FACEBOOK-PLATFORM', 40, X_FACEBOOK_PLATFORM, use_hashes=False)
Work around Python3's byte semantics.
Work around Python3's byte semantics.
Python
mit
dwd/Suelta
python
## Code Before: from suelta.util import bytes from suelta.sasl import Mechanism, register_mechanism try: import urlparse except ImportError: import urllib.parse as urlparse class X_FACEBOOK_PLATFORM(Mechanism): def __init__(self, sasl, name): super(X_FACEBOOK_PLATFORM, self).__init__(sasl, name) self.check_values(['access_token', 'api_key']) def process(self, challenge=None): if challenge is not None: values = {} for kv in challenge.split('&'): key, value = kv.split('=') values[key] = value resp_data = { 'method': values['method'], 'v': '1.0', 'call_id': '1.0', 'nonce': values['nonce'], 'access_token': self.values['access_token'], 'api_key': self.values['api_key'] } resp = '&'.join(['%s=%s' % (k, v) for k, v in resp_data.items()]) return bytes(resp) return bytes('') def okay(self): return True register_mechanism('X-FACEBOOK-PLATFORM', 40, X_FACEBOOK_PLATFORM, use_hashes=False) ## Instruction: Work around Python3's byte semantics. ## Code After: from suelta.util import bytes from suelta.sasl import Mechanism, register_mechanism try: import urlparse except ImportError: import urllib.parse as urlparse class X_FACEBOOK_PLATFORM(Mechanism): def __init__(self, sasl, name): super(X_FACEBOOK_PLATFORM, self).__init__(sasl, name) self.check_values(['access_token', 'api_key']) def process(self, challenge=None): if challenge is not None: values = {} for kv in challenge.split(b'&'): key, value = kv.split(b'=') values[key] = value resp_data = { b'method': values[b'method'], b'v': b'1.0', b'call_id': b'1.0', b'nonce': values[b'nonce'], b'access_token': self.values['access_token'], b'api_key': self.values['api_key'] } resp = '&'.join(['%s=%s' % (k, v) for k, v in resp_data.items()]) return bytes(resp) return b'' def okay(self): return True register_mechanism('X-FACEBOOK-PLATFORM', 40, X_FACEBOOK_PLATFORM, use_hashes=False)
... def process(self, challenge=None): if challenge is not None: values = {} for kv in challenge.split(b'&'): key, value = kv.split(b'=') values[key] = value resp_data = { b'method': values[b'method'], b'v': b'1.0', b'call_id': b'1.0', b'nonce': values[b'nonce'], b'access_token': self.values['access_token'], b'api_key': self.values['api_key'] } resp = '&'.join(['%s=%s' % (k, v) for k, v in resp_data.items()]) return bytes(resp) return b'' def okay(self): return True ...
0c593e993cb8fb4ea6b3031454ac359efa6aaf5c
states-pelican.py
states-pelican.py
import salt.exceptions import subprocess def build_site(name, output="/srv/www"): # /srv/salt/_states/pelican.py # Generates static site with pelican -o $output $name # Sorry. # -- Jadon Bennett, 2015 ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} # I don't know how to make this work. But it's cool. #current_state = __salt__['pelican.current_state'](name) current_state = "cool" if __opts__['test'] == True: ret['comment'] = 'Markdown files from "{0}" will be converted to HTML and put in "{1}"'.format(name,output) ret['changes'] = { 'old': current_state, 'new': 'New!', } ret['result'] = None return ret subprocess.call(['pelican', '-o', output, name]) ret['comment'] = 'Static site generated from "{0}".'.format(name) ret['changes'] = { 'old': current_state, 'new': 'Whoopee!', } ret['result'] = True return ret
import salt.exceptions import subprocess def build_site(name, output="/srv/www"): # /srv/salt/_states/pelican.py # Generates static site with pelican -o $output $name # Sorry. # -- Jadon Bennett, 2015 ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} current_state = __salt__['pelican.current_state'](name) if __opts__['test'] == True: ret['comment'] = 'Markdown files from "{0}" will be converted to HTML and put in "{1}"'.format(name,output) ret['changes'] = { 'old': current_state, 'new': 'New!', } ret['result'] = None return ret new_state = __salt__['pelican.generate'](output,path) ret['comment'] = 'Static site generated from "{0}".'.format(name) ret['changes'] = { 'old': current_state, 'new': new_state, } ret['result'] = True return ret
Move subprocess stuff to an execution module for Pelican.
Move subprocess stuff to an execution module for Pelican.
Python
mit
lvl1/salt-formulas
python
## Code Before: import salt.exceptions import subprocess def build_site(name, output="/srv/www"): # /srv/salt/_states/pelican.py # Generates static site with pelican -o $output $name # Sorry. # -- Jadon Bennett, 2015 ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} # I don't know how to make this work. But it's cool. #current_state = __salt__['pelican.current_state'](name) current_state = "cool" if __opts__['test'] == True: ret['comment'] = 'Markdown files from "{0}" will be converted to HTML and put in "{1}"'.format(name,output) ret['changes'] = { 'old': current_state, 'new': 'New!', } ret['result'] = None return ret subprocess.call(['pelican', '-o', output, name]) ret['comment'] = 'Static site generated from "{0}".'.format(name) ret['changes'] = { 'old': current_state, 'new': 'Whoopee!', } ret['result'] = True return ret ## Instruction: Move subprocess stuff to an execution module for Pelican. ## Code After: import salt.exceptions import subprocess def build_site(name, output="/srv/www"): # /srv/salt/_states/pelican.py # Generates static site with pelican -o $output $name # Sorry. # -- Jadon Bennett, 2015 ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} current_state = __salt__['pelican.current_state'](name) if __opts__['test'] == True: ret['comment'] = 'Markdown files from "{0}" will be converted to HTML and put in "{1}"'.format(name,output) ret['changes'] = { 'old': current_state, 'new': 'New!', } ret['result'] = None return ret new_state = __salt__['pelican.generate'](output,path) ret['comment'] = 'Static site generated from "{0}".'.format(name) ret['changes'] = { 'old': current_state, 'new': new_state, } ret['result'] = True return ret
# ... existing code ... ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} current_state = __salt__['pelican.current_state'](name) if __opts__['test'] == True: ret['comment'] = 'Markdown files from "{0}" will be converted to HTML and put in "{1}"'.format(name,output) # ... modified code ... return ret new_state = __salt__['pelican.generate'](output,path) ret['comment'] = 'Static site generated from "{0}".'.format(name) ret['changes'] = { 'old': current_state, 'new': new_state, } ret['result'] = True # ... rest of the code ...
4fd6a98a887a59dabcc41361a6ba2791393d875e
test/tests/python-pip-requests-ssl/container.py
test/tests/python-pip-requests-ssl/container.py
import pip pip.main(['install', '-q', 'requests']) import requests r = requests.get('https://google.com') assert(r.status_code == 200)
import subprocess, sys subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'requests']) import requests r = requests.get('https://google.com') assert(r.status_code == 200)
Fix "python-pip-requests-ssl" test to no longer "import pip"
Fix "python-pip-requests-ssl" test to no longer "import pip" (https://blog.python.org/2018/04/pip-10-has-been-released.html) > In addition, the previously announced reorganisation of pip's internals has now taken place. Unless you are the author of code that imports the pip module (or a user of such code), this change will not affect you. If you are affected, please report the issue to the author of the offending code (refer them to https://mail.python.org/pipermail/distutils-sig/2017-October/031642.html for the details of the announcement).
Python
apache-2.0
docker-library/official-images,docker-flink/official-images,docker-library/official-images,31z4/official-images,davidl-zend/official-images,jperrin/official-images,infosiftr/stackbrew,neo-technology/docker-official-images,31z4/official-images,dinogun/official-images,docker-flink/official-images,neo-technology/docker-official-images,docker-solr/official-images,31z4/official-images,chorrell/official-images,dinogun/official-images,docker-solr/official-images,docker-library/official-images,infosiftr/stackbrew,davidl-zend/official-images,docker-library/official-images,neo-technology/docker-official-images,docker-flink/official-images,infosiftr/stackbrew,docker-solr/official-images,robfrank/official-images,docker-flink/official-images,thresheek/official-images,31z4/official-images,robfrank/official-images,robfrank/official-images,infosiftr/stackbrew,infosiftr/stackbrew,docker-flink/official-images,chorrell/official-images,chorrell/official-images,docker-solr/official-images,docker-flink/official-images,neo-technology/docker-official-images,thresheek/official-images,docker-library/official-images,docker-solr/official-images,jperrin/official-images,dinogun/official-images,thresheek/official-images,chorrell/official-images,davidl-zend/official-images,neo-technology/docker-official-images,31z4/official-images,docker-flink/official-images,davidl-zend/official-images,jperrin/official-images,thresheek/official-images,thresheek/official-images,neo-technology/docker-official-images,docker-library/official-images,chorrell/official-images,robfrank/official-images,31z4/official-images,chorrell/official-images,thresheek/official-images,docker-solr/official-images,neo-technology/docker-official-images,31z4/official-images,robfrank/official-images,robfrank/official-images,davidl-zend/official-images,neo-technology/docker-official-images,infosiftr/stackbrew,docker-library/official-images,thresheek/official-images,neo-technology/docker-official-images,jperrin/official-images,neo-technology/docker-official-images,docker-library/official-images,docker-library/official-images,docker-library/official-images,infosiftr/stackbrew,chorrell/official-images,dinogun/official-images,31z4/official-images,chorrell/official-images,robfrank/official-images,docker-flink/official-images,jperrin/official-images,thresheek/official-images,docker-solr/official-images,davidl-zend/official-images,docker-flink/official-images,docker-library/official-images,dinogun/official-images,31z4/official-images,davidl-zend/official-images,davidl-zend/official-images,docker-solr/official-images,jperrin/official-images,jperrin/official-images,davidl-zend/official-images,jperrin/official-images,robfrank/official-images,chorrell/official-images,docker-flink/official-images,thresheek/official-images,31z4/official-images,docker-flink/official-images,jperrin/official-images,neo-technology/docker-official-images,docker-library/official-images,jperrin/official-images,infosiftr/stackbrew,dinogun/official-images,robfrank/official-images,jperrin/official-images,robfrank/official-images,robfrank/official-images,dinogun/official-images,31z4/official-images,31z4/official-images,docker-flink/official-images,chorrell/official-images,docker-library/official-images,davidl-zend/official-images,dinogun/official-images,infosiftr/stackbrew,docker-solr/official-images,dinogun/official-images,thresheek/official-images,docker-flink/official-images,jperrin/official-images,robfrank/official-images,docker-solr/official-images,thresheek/official-images,docker-solr/official-images,neo-technology/docker-official-images,thresheek/official-images,docker-solr/official-images,docker-solr/official-images,docker-library/official-images,robfrank/official-images,dinogun/official-images,jperrin/official-images,chorrell/official-images,infosiftr/stackbrew,infosiftr/stackbrew,dinogun/official-images,davidl-zend/official-images,31z4/official-images,infosiftr/stackbrew,neo-technology/docker-official-images,31z4/official-images,dinogun/official-images,chorrell/official-images,infosiftr/stackbrew,neo-technology/docker-official-images,davidl-zend/official-images,docker-solr/official-images,thresheek/official-images,davidl-zend/official-images,dinogun/official-images,chorrell/official-images,thresheek/official-images,infosiftr/stackbrew
python
## Code Before: import pip pip.main(['install', '-q', 'requests']) import requests r = requests.get('https://google.com') assert(r.status_code == 200) ## Instruction: Fix "python-pip-requests-ssl" test to no longer "import pip" (https://blog.python.org/2018/04/pip-10-has-been-released.html) > In addition, the previously announced reorganisation of pip's internals has now taken place. Unless you are the author of code that imports the pip module (or a user of such code), this change will not affect you. If you are affected, please report the issue to the author of the offending code (refer them to https://mail.python.org/pipermail/distutils-sig/2017-October/031642.html for the details of the announcement). ## Code After: import subprocess, sys subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'requests']) import requests r = requests.get('https://google.com') assert(r.status_code == 200)
# ... existing code ... import subprocess, sys subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'requests']) import requests r = requests.get('https://google.com') assert(r.status_code == 200) # ... rest of the code ...