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
fcf57f6698166e3a1851d45b5458191987435c5a
engine/src/main/java/uk/org/sappho/code/change/management/data/ChangedFile.java
engine/src/main/java/uk/org/sappho/code/change/management/data/ChangedFile.java
package uk.org.sappho.code.change.management.data; import net.sf.oval.constraint.NotEmpty; import net.sf.oval.constraint.NotNull; public class ChangedFile { @NotNull @NotEmpty private final String filename; @NotNull @NotEmpty private final Boolean isCreate; public ChangedFile(String filename, Boolean isCreate) { this.filename = filename; this.isCreate = isCreate; } public String getFilename() { return filename; } public boolean isCreate() { return isCreate; } }
package uk.org.sappho.code.change.management.data; import net.sf.oval.constraint.NotEmpty; import net.sf.oval.constraint.NotNull; public class ChangedFile { @NotNull @NotEmpty private String filename; @NotNull @NotEmpty private Boolean isCreate; public ChangedFile() { } public ChangedFile(String filename, Boolean isCreate) { this.filename = filename; this.isCreate = isCreate; } public String getFilename() { return filename; } public boolean isCreate() { return isCreate; } }
Add no-params constructor to fix data file read issue.
CHM-57: Add no-params constructor to fix data file read issue.
Java
agpl-3.0
sappho/code-heatmap
java
## Code Before: package uk.org.sappho.code.change.management.data; import net.sf.oval.constraint.NotEmpty; import net.sf.oval.constraint.NotNull; public class ChangedFile { @NotNull @NotEmpty private final String filename; @NotNull @NotEmpty private final Boolean isCreate; public ChangedFile(String filename, Boolean isCreate) { this.filename = filename; this.isCreate = isCreate; } public String getFilename() { return filename; } public boolean isCreate() { return isCreate; } } ## Instruction: CHM-57: Add no-params constructor to fix data file read issue. ## Code After: package uk.org.sappho.code.change.management.data; import net.sf.oval.constraint.NotEmpty; import net.sf.oval.constraint.NotNull; public class ChangedFile { @NotNull @NotEmpty private String filename; @NotNull @NotEmpty private Boolean isCreate; public ChangedFile() { } public ChangedFile(String filename, Boolean isCreate) { this.filename = filename; this.isCreate = isCreate; } public String getFilename() { return filename; } public boolean isCreate() { return isCreate; } }
# ... existing code ... @NotNull @NotEmpty private String filename; @NotNull @NotEmpty private Boolean isCreate; public ChangedFile() { } public ChangedFile(String filename, Boolean isCreate) { # ... rest of the code ...
ff2d9b276928d2bf06ae81b1fa243ee2816cd694
seawater/__init__.py
seawater/__init__.py
__all__ = ["csiro", "extras"] __authors__ = 'Filipe Fernandes' __created_ = "14-Jan-2010" __email__ = "[email protected]" __license__ = "MIT" __maintainer__ = "Filipe Fernandes" __modified__ = "16-Mar-2013" __status__ = "Production" __version__ = "2.0.0" import csiro import extras
from csiro import *
Update to reflect some small re-factoring.
Update to reflect some small re-factoring.
Python
mit
ocefpaf/python-seawater,pyoceans/python-seawater,pyoceans/python-seawater,ocefpaf/python-seawater
python
## Code Before: __all__ = ["csiro", "extras"] __authors__ = 'Filipe Fernandes' __created_ = "14-Jan-2010" __email__ = "[email protected]" __license__ = "MIT" __maintainer__ = "Filipe Fernandes" __modified__ = "16-Mar-2013" __status__ = "Production" __version__ = "2.0.0" import csiro import extras ## Instruction: Update to reflect some small re-factoring. ## Code After: from csiro import *
# ... existing code ... from csiro import * # ... rest of the code ...
c792cfc75cddbd77f7de3257fad4a6cec50bd152
src/main/java/com/woinject/Interceptor.java
src/main/java/com/woinject/Interceptor.java
package com.woinject; import com.google.inject.Injector; /** * @author <a href="mailto:[email protected]">Henrique Prange</a> */ public class Interceptor { public static Object injectMembers(Object object) { Injector injector = InjectableApplication.application().injector(); if (injector == null) { return object; } injector.injectMembers(object); return object; } // public static Object intercept(Class<?> clazz, Object[] parameters) { // System.out.println("\tClass: " + clazz + " Parameters: " + // java.util.Arrays.toString(parameters)); // // if (WOSession.class.isAssignableFrom(clazz)) { // System.out.println("Creating an instace of " + clazz.getName()); // // Object instance = injector().getInstance(clazz); // // return instance; // } // // if (EOEnterpriseObject.class.isAssignableFrom(clazz)) { // System.out.println("Creating an instace of " + clazz.getName()); // // Object instance = injector().getInstance(clazz); // // return instance; // } // // return null; // } }
/** * Copyright (C) 2010 hprange <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.woinject; import com.google.inject.Injector; /** * @author <a href="mailto:[email protected]">Henrique Prange</a> */ public class Interceptor { public static Object injectMembers(Object object) { Injector injector = InjectableApplication.application().injector(); if (injector == null) { return object; } injector.injectMembers(object); return object; } // public static Object intercept(Class<?> clazz, Object[] parameters) { // System.out.println("\tClass: " + clazz + " Parameters: " + // java.util.Arrays.toString(parameters)); // // if (WOSession.class.isAssignableFrom(clazz)) { // System.out.println("Creating an instace of " + clazz.getName()); // // Object instance = injector().getInstance(clazz); // // return instance; // } // // if (EOEnterpriseObject.class.isAssignableFrom(clazz)) { // System.out.println("Creating an instace of " + clazz.getName()); // // Object instance = injector().getInstance(clazz); // // return instance; // } // // return null; // } }
Add the missing license header
Add the missing license header
Java
apache-2.0
hprange/woinject
java
## Code Before: package com.woinject; import com.google.inject.Injector; /** * @author <a href="mailto:[email protected]">Henrique Prange</a> */ public class Interceptor { public static Object injectMembers(Object object) { Injector injector = InjectableApplication.application().injector(); if (injector == null) { return object; } injector.injectMembers(object); return object; } // public static Object intercept(Class<?> clazz, Object[] parameters) { // System.out.println("\tClass: " + clazz + " Parameters: " + // java.util.Arrays.toString(parameters)); // // if (WOSession.class.isAssignableFrom(clazz)) { // System.out.println("Creating an instace of " + clazz.getName()); // // Object instance = injector().getInstance(clazz); // // return instance; // } // // if (EOEnterpriseObject.class.isAssignableFrom(clazz)) { // System.out.println("Creating an instace of " + clazz.getName()); // // Object instance = injector().getInstance(clazz); // // return instance; // } // // return null; // } } ## Instruction: Add the missing license header ## Code After: /** * Copyright (C) 2010 hprange <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.woinject; import com.google.inject.Injector; /** * @author <a href="mailto:[email protected]">Henrique Prange</a> */ public class Interceptor { public static Object injectMembers(Object object) { Injector injector = InjectableApplication.application().injector(); if (injector == null) { return object; } injector.injectMembers(object); return object; } // public static Object intercept(Class<?> clazz, Object[] parameters) { // System.out.println("\tClass: " + clazz + " Parameters: " + // java.util.Arrays.toString(parameters)); // // if (WOSession.class.isAssignableFrom(clazz)) { // System.out.println("Creating an instace of " + clazz.getName()); // // Object instance = injector().getInstance(clazz); // // return instance; // } // // if (EOEnterpriseObject.class.isAssignableFrom(clazz)) { // System.out.println("Creating an instace of " + clazz.getName()); // // Object instance = injector().getInstance(clazz); // // return instance; // } // // return null; // } }
# ... existing code ... /** * Copyright (C) 2010 hprange <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.woinject; import com.google.inject.Injector; # ... rest of the code ...
05c31095ee828bfe455ad93befc5d189b9d0edc5
wallace/__init__.py
wallace/__init__.py
from . import models, information, agents, networks, processes __all__ = ['models', 'information', 'agents', 'sources', 'networks', 'processes']
from . import models, information, agents, networks, processes __all__ = ['models', 'information', 'agents', 'sources', 'networks', 'processes', 'transformations']
Add transformations to Wallace init
Add transformations to Wallace init
Python
mit
Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,berkeley-cocosci/Wallace,berkeley-cocosci/Wallace,suchow/Wallace,Dallinger/Dallinger,Dallinger/Dallinger,suchow/Wallace,Dallinger/Dallinger,berkeley-cocosci/Wallace,jcpeterson/Dallinger,suchow/Wallace,Dallinger/Dallinger
python
## Code Before: from . import models, information, agents, networks, processes __all__ = ['models', 'information', 'agents', 'sources', 'networks', 'processes'] ## Instruction: Add transformations to Wallace init ## Code After: from . import models, information, agents, networks, processes __all__ = ['models', 'information', 'agents', 'sources', 'networks', 'processes', 'transformations']
// ... existing code ... from . import models, information, agents, networks, processes __all__ = ['models', 'information', 'agents', 'sources', 'networks', 'processes', 'transformations'] // ... rest of the code ...
c31bc6f1b0782a7d9c409e233a363be651594006
exporters/decompressors.py
exporters/decompressors.py
from exporters.pipeline.base_pipeline_item import BasePipelineItem import logging import zlib __all__ = ['BaseDecompressor', 'ZLibDecompressor', 'NoDecompressor'] class BaseDecompressor(BasePipelineItem): def decompress(self): raise NotImplementedError() def create_decompressor(): # create zlib decompressor enabling automatic header detection: # See: http://stackoverflow.com/a/22310760/149872 AUTOMATIC_HEADER_DETECTION_MASK = 32 return zlib.decompressobj(AUTOMATIC_HEADER_DETECTION_MASK | zlib.MAX_WBITS) class ZLibDecompressor(BaseDecompressor): def decompress(self, stream): try: dec = create_decompressor() for chunk in stream: rv = dec.decompress(chunk) if rv: yield rv if dec.unused_data: stream.unshift(dec.unused_data) dec = create_decompressor() except zlib.error as e: logging.error('Error decoding stream using ZlibDecompressor') if str(e).startswith('Error -3 '): logging.error("Use NoDecompressor if you're using uncompressed input") raise class NoDecompressor(BaseDecompressor): def decompress(self, stream): return stream # Input already uncompressed
from exporters.pipeline.base_pipeline_item import BasePipelineItem import sys import zlib import six __all__ = ['BaseDecompressor', 'ZLibDecompressor', 'NoDecompressor'] class BaseDecompressor(BasePipelineItem): def decompress(self): raise NotImplementedError() def create_decompressor(): # create zlib decompressor enabling automatic header detection: # See: http://stackoverflow.com/a/22310760/149872 AUTOMATIC_HEADER_DETECTION_MASK = 32 return zlib.decompressobj(AUTOMATIC_HEADER_DETECTION_MASK | zlib.MAX_WBITS) class ZLibDecompressor(BaseDecompressor): def decompress(self, stream): try: dec = create_decompressor() for chunk in stream: rv = dec.decompress(chunk) if rv: yield rv if dec.unused_data: stream.unshift(dec.unused_data) dec = create_decompressor() except zlib.error as e: msg = str(e) if msg.startswith('Error -3 '): msg += ". Use NoDecompressor if you're using uncompressed input." six.reraise(zlib.error, zlib.error(msg), sys.exc_info()[2]) class NoDecompressor(BaseDecompressor): def decompress(self, stream): return stream # Input already uncompressed
Append information to the zlib error
Append information to the zlib error
Python
bsd-3-clause
scrapinghub/exporters
python
## Code Before: from exporters.pipeline.base_pipeline_item import BasePipelineItem import logging import zlib __all__ = ['BaseDecompressor', 'ZLibDecompressor', 'NoDecompressor'] class BaseDecompressor(BasePipelineItem): def decompress(self): raise NotImplementedError() def create_decompressor(): # create zlib decompressor enabling automatic header detection: # See: http://stackoverflow.com/a/22310760/149872 AUTOMATIC_HEADER_DETECTION_MASK = 32 return zlib.decompressobj(AUTOMATIC_HEADER_DETECTION_MASK | zlib.MAX_WBITS) class ZLibDecompressor(BaseDecompressor): def decompress(self, stream): try: dec = create_decompressor() for chunk in stream: rv = dec.decompress(chunk) if rv: yield rv if dec.unused_data: stream.unshift(dec.unused_data) dec = create_decompressor() except zlib.error as e: logging.error('Error decoding stream using ZlibDecompressor') if str(e).startswith('Error -3 '): logging.error("Use NoDecompressor if you're using uncompressed input") raise class NoDecompressor(BaseDecompressor): def decompress(self, stream): return stream # Input already uncompressed ## Instruction: Append information to the zlib error ## Code After: from exporters.pipeline.base_pipeline_item import BasePipelineItem import sys import zlib import six __all__ = ['BaseDecompressor', 'ZLibDecompressor', 'NoDecompressor'] class BaseDecompressor(BasePipelineItem): def decompress(self): raise NotImplementedError() def create_decompressor(): # create zlib decompressor enabling automatic header detection: # See: http://stackoverflow.com/a/22310760/149872 AUTOMATIC_HEADER_DETECTION_MASK = 32 return zlib.decompressobj(AUTOMATIC_HEADER_DETECTION_MASK | zlib.MAX_WBITS) class ZLibDecompressor(BaseDecompressor): def decompress(self, stream): try: dec = create_decompressor() for chunk in stream: rv = dec.decompress(chunk) if rv: yield rv if dec.unused_data: stream.unshift(dec.unused_data) dec = create_decompressor() except zlib.error as e: msg = str(e) if msg.startswith('Error -3 '): msg += ". Use NoDecompressor if you're using uncompressed input." six.reraise(zlib.error, zlib.error(msg), sys.exc_info()[2]) class NoDecompressor(BaseDecompressor): def decompress(self, stream): return stream # Input already uncompressed
// ... existing code ... from exporters.pipeline.base_pipeline_item import BasePipelineItem import sys import zlib import six __all__ = ['BaseDecompressor', 'ZLibDecompressor', 'NoDecompressor'] // ... modified code ... stream.unshift(dec.unused_data) dec = create_decompressor() except zlib.error as e: msg = str(e) if msg.startswith('Error -3 '): msg += ". Use NoDecompressor if you're using uncompressed input." six.reraise(zlib.error, zlib.error(msg), sys.exc_info()[2]) class NoDecompressor(BaseDecompressor): // ... rest of the code ...
35b8dd77be54872bcf17b62e288cd4a2b5a37e5a
viper.py
viper.py
from viper.interactive import * from viper.lexer import lex_file from viper.grammar import GRAMMAR if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('-L', '--interactive-lexer', action='store_true', help='lexes input') parser.add_argument('-S', '--interactive-sppf', action='store_true', help='lexes input and produces SPPF') parser.add_argument('-s', '--file-sppf', help='produces SPPF for given input') parser.add_argument('-r', '--grammar-rule', default='single_line', help='grammar rule from which to start parsing') args = parser.parse_args() if args.interactive_lexer: InteractiveLexer().cmdloop() elif args.interactive_sppf: InteractiveSPPF(args.grammar_rule).cmdloop() elif args.file_sppf: lexemes = lex_file(args.file_sppf) sppf = GRAMMAR.parse_multiple(lexemes) print(sppf)
from viper.interactive import * from viper.lexer import lex_file, NewLine from viper.grammar import GRAMMAR if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('-L', '--interactive-lexer', action='store_true', help='lexes input') parser.add_argument('-l', '--file-lexer', help='produces lexemes for given file input') parser.add_argument('-S', '--interactive-sppf', action='store_true', help='lexes input and produces SPPF') parser.add_argument('-s', '--file-sppf', help='produces SPPF for given input') parser.add_argument('-r', '--grammar-rule', default='single_line', help='grammar rule from which to start parsing') args = parser.parse_args() if args.interactive_lexer: InteractiveLexer().cmdloop() elif args.file_lexer: lexemes = lex_file(args.file_lexer) outputs = [] curr_line = [] for lexeme in lexemes: if isinstance(lexeme, NewLine): outputs.append(' '.join(map(repr, curr_line))) curr_line = [] curr_line.append(lexeme) outputs.append(' '.join(map(repr, curr_line))) print('\n'.join(outputs)) elif args.interactive_sppf: InteractiveSPPF(args.grammar_rule).cmdloop() elif args.file_sppf: lexemes = lex_file(args.file_sppf) sppf = GRAMMAR.parse_file(lexemes) print(sppf)
Add CLI option for outputting lexed files
Add CLI option for outputting lexed files
Python
apache-2.0
pdarragh/Viper
python
## Code Before: from viper.interactive import * from viper.lexer import lex_file from viper.grammar import GRAMMAR if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('-L', '--interactive-lexer', action='store_true', help='lexes input') parser.add_argument('-S', '--interactive-sppf', action='store_true', help='lexes input and produces SPPF') parser.add_argument('-s', '--file-sppf', help='produces SPPF for given input') parser.add_argument('-r', '--grammar-rule', default='single_line', help='grammar rule from which to start parsing') args = parser.parse_args() if args.interactive_lexer: InteractiveLexer().cmdloop() elif args.interactive_sppf: InteractiveSPPF(args.grammar_rule).cmdloop() elif args.file_sppf: lexemes = lex_file(args.file_sppf) sppf = GRAMMAR.parse_multiple(lexemes) print(sppf) ## Instruction: Add CLI option for outputting lexed files ## Code After: from viper.interactive import * from viper.lexer import lex_file, NewLine from viper.grammar import GRAMMAR if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('-L', '--interactive-lexer', action='store_true', help='lexes input') parser.add_argument('-l', '--file-lexer', help='produces lexemes for given file input') parser.add_argument('-S', '--interactive-sppf', action='store_true', help='lexes input and produces SPPF') parser.add_argument('-s', '--file-sppf', help='produces SPPF for given input') parser.add_argument('-r', '--grammar-rule', default='single_line', help='grammar rule from which to start parsing') args = parser.parse_args() if args.interactive_lexer: InteractiveLexer().cmdloop() elif args.file_lexer: lexemes = lex_file(args.file_lexer) outputs = [] curr_line = [] for lexeme in lexemes: if isinstance(lexeme, NewLine): outputs.append(' '.join(map(repr, curr_line))) curr_line = [] curr_line.append(lexeme) outputs.append(' '.join(map(repr, curr_line))) print('\n'.join(outputs)) elif args.interactive_sppf: InteractiveSPPF(args.grammar_rule).cmdloop() elif args.file_sppf: lexemes = lex_file(args.file_sppf) sppf = GRAMMAR.parse_file(lexemes) print(sppf)
# ... existing code ... from viper.interactive import * from viper.lexer import lex_file, NewLine from viper.grammar import GRAMMAR # ... modified code ... import argparse parser = argparse.ArgumentParser() parser.add_argument('-L', '--interactive-lexer', action='store_true', help='lexes input') parser.add_argument('-l', '--file-lexer', help='produces lexemes for given file input') parser.add_argument('-S', '--interactive-sppf', action='store_true', help='lexes input and produces SPPF') parser.add_argument('-s', '--file-sppf', help='produces SPPF for given input') parser.add_argument('-r', '--grammar-rule', default='single_line', help='grammar rule from which to start parsing') ... if args.interactive_lexer: InteractiveLexer().cmdloop() elif args.file_lexer: lexemes = lex_file(args.file_lexer) outputs = [] curr_line = [] for lexeme in lexemes: if isinstance(lexeme, NewLine): outputs.append(' '.join(map(repr, curr_line))) curr_line = [] curr_line.append(lexeme) outputs.append(' '.join(map(repr, curr_line))) print('\n'.join(outputs)) elif args.interactive_sppf: InteractiveSPPF(args.grammar_rule).cmdloop() elif args.file_sppf: lexemes = lex_file(args.file_sppf) sppf = GRAMMAR.parse_file(lexemes) print(sppf) # ... rest of the code ...
5c020deef2ee09fe0abe00ad533fba9a2411dd4a
include/siri/grammar/gramp.h
include/siri/grammar/gramp.h
/* * gramp.h - SiriDB Grammar Properties. * * Note: we need this file up-to-date with the grammar. The grammar has * keywords starting with K_ so the will all be sorted. * KW_OFFSET should be set to the first keyword and KW_COUNT needs the * last keyword in the grammar. * */ #ifndef SIRI_GRAMP_H_ #define SIRI_GRAMP_H_ #include <siri/grammar/grammar.h> /* keywords */ #define KW_OFFSET CLERI_GID_K_ACCESS #define KW_COUNT CLERI_GID_K_WRITE + 1 - KW_OFFSET /* aggregation functions */ #define F_OFFSET CLERI_GID_F_COUNT /* help statements */ #define HELP_OFFSET CLERI_GID_HELP_ACCESS #define HELP_COUNT CLERI_GID_HELP_TIMEZONES + 1 - HELP_OFFSET #if CLERI_VERSION_MINOR >= 12 #define CLERI_NODE_DATA(__node) ((intptr_t)(__node)->data) #define CLERI_NODE_DATA_ADDR(__node) ((intptr_t *) &(__node)->data) #else #define CLERI_NODE_DATA(__node) ((intptr_t)(__node)->result) #define CLERI_NODE_DATA_ADDR(__node) ((intptr_t *) &(__node)->result) #endif #endif /* SIRI_GRAMP_H_ */
/* * gramp.h - SiriDB Grammar Properties. * * Note: we need this file up-to-date with the grammar. The grammar has * keywords starting with K_ so the will all be sorted. * KW_OFFSET should be set to the first keyword and KW_COUNT needs the * last keyword in the grammar. * */ #ifndef SIRI_GRAMP_H_ #define SIRI_GRAMP_H_ #include <siri/grammar/grammar.h> /* keywords */ #define KW_OFFSET CLERI_GID_K_ACCESS #define KW_COUNT CLERI_GID_K_WRITE + 1 - KW_OFFSET /* aggregation functions */ #define F_OFFSET CLERI_GID_F_COUNT /* help statements */ #define HELP_OFFSET CLERI_GID_HELP_ACCESS #define HELP_COUNT CLERI_GID_HELP_TIMEZONES + 1 - HELP_OFFSET #if CLERI_VERSION_MINOR >= 12 #define CLERI_NODE_DATA(__node) ((intptr_t)(__node)->data) #define CLERI_NODE_DATA_ADDR(__node) ((intptr_t *) &(__node)->data) #else #define CLERI_NODE_DATA(__node) (__node)->result #define CLERI_NODE_DATA_ADDR(__node) &(__node)->result #endif #endif /* SIRI_GRAMP_H_ */
Update compat with old libcleri
Update compat with old libcleri
C
mit
transceptor-technology/siridb-server,transceptor-technology/siridb-server,transceptor-technology/siridb-server,transceptor-technology/siridb-server
c
## Code Before: /* * gramp.h - SiriDB Grammar Properties. * * Note: we need this file up-to-date with the grammar. The grammar has * keywords starting with K_ so the will all be sorted. * KW_OFFSET should be set to the first keyword and KW_COUNT needs the * last keyword in the grammar. * */ #ifndef SIRI_GRAMP_H_ #define SIRI_GRAMP_H_ #include <siri/grammar/grammar.h> /* keywords */ #define KW_OFFSET CLERI_GID_K_ACCESS #define KW_COUNT CLERI_GID_K_WRITE + 1 - KW_OFFSET /* aggregation functions */ #define F_OFFSET CLERI_GID_F_COUNT /* help statements */ #define HELP_OFFSET CLERI_GID_HELP_ACCESS #define HELP_COUNT CLERI_GID_HELP_TIMEZONES + 1 - HELP_OFFSET #if CLERI_VERSION_MINOR >= 12 #define CLERI_NODE_DATA(__node) ((intptr_t)(__node)->data) #define CLERI_NODE_DATA_ADDR(__node) ((intptr_t *) &(__node)->data) #else #define CLERI_NODE_DATA(__node) ((intptr_t)(__node)->result) #define CLERI_NODE_DATA_ADDR(__node) ((intptr_t *) &(__node)->result) #endif #endif /* SIRI_GRAMP_H_ */ ## Instruction: Update compat with old libcleri ## Code After: /* * gramp.h - SiriDB Grammar Properties. * * Note: we need this file up-to-date with the grammar. The grammar has * keywords starting with K_ so the will all be sorted. * KW_OFFSET should be set to the first keyword and KW_COUNT needs the * last keyword in the grammar. * */ #ifndef SIRI_GRAMP_H_ #define SIRI_GRAMP_H_ #include <siri/grammar/grammar.h> /* keywords */ #define KW_OFFSET CLERI_GID_K_ACCESS #define KW_COUNT CLERI_GID_K_WRITE + 1 - KW_OFFSET /* aggregation functions */ #define F_OFFSET CLERI_GID_F_COUNT /* help statements */ #define HELP_OFFSET CLERI_GID_HELP_ACCESS #define HELP_COUNT CLERI_GID_HELP_TIMEZONES + 1 - HELP_OFFSET #if CLERI_VERSION_MINOR >= 12 #define CLERI_NODE_DATA(__node) ((intptr_t)(__node)->data) #define CLERI_NODE_DATA_ADDR(__node) ((intptr_t *) &(__node)->data) #else #define CLERI_NODE_DATA(__node) (__node)->result #define CLERI_NODE_DATA_ADDR(__node) &(__node)->result #endif #endif /* SIRI_GRAMP_H_ */
# ... existing code ... #define CLERI_NODE_DATA(__node) ((intptr_t)(__node)->data) #define CLERI_NODE_DATA_ADDR(__node) ((intptr_t *) &(__node)->data) #else #define CLERI_NODE_DATA(__node) (__node)->result #define CLERI_NODE_DATA_ADDR(__node) &(__node)->result #endif #endif /* SIRI_GRAMP_H_ */ # ... rest of the code ...
31a6e50a5f20b77c82cf2024ef8f0c8f586973b9
TesseractOCR/Tesseract.h
TesseractOCR/Tesseract.h
// // Tesseract.h // Tesseract // // Created by Loïs Di Qual on 24/09/12. // Copyright (c) 2012 Loïs Di Qual. // Under MIT License. See 'LICENCE' for more informations. // #import <UIKit/UIKit.h> @class Tesseract; @protocol TesseractDelegate <NSObject> @optional - (BOOL)shouldCancelImageRecognitionForTesseract:(Tesseract*)tesseract; @end @interface Tesseract : NSObject + (NSString *)version; @property (nonatomic, strong) NSString* language; @property (nonatomic, strong) UIImage *image; @property (nonatomic, assign) CGRect rect; @property (nonatomic, readonly) short progress; // from 0 to 100 @property (nonatomic, readonly) NSString *recognizedText; @property (nonatomic, weak) id<TesseractDelegate> delegate; /// /// @warning deprecated method! /// @deprecated - (id)initWithDataPath:(NSString *)dataPath language:(NSString *)language is deprecated. Please use - (id)initWithLanguage:(NSString*)language; /// - (id)initWithDataPath:(NSString *)dataPath language:(NSString *)language DEPRECATED_ATTRIBUTE; - (id)initWithLanguage:(NSString*)language; - (void)setVariableValue:(NSString *)value forKey:(NSString *)key; - (BOOL)recognize; - (void)clear; @end
// // Tesseract.h // Tesseract // // Created by Loïs Di Qual on 24/09/12. // Copyright (c) 2012 Loïs Di Qual. // Under MIT License. See 'LICENCE' for more informations. // #import <UIKit/UIKit.h> @class Tesseract; @protocol TesseractDelegate <NSObject> @optional - (BOOL)shouldCancelImageRecognitionForTesseract:(Tesseract*)tesseract; @end @interface Tesseract : NSObject + (NSString *)version; @property (nonatomic, strong) NSString* language; @property (nonatomic, strong) UIImage *image; @property (nonatomic, assign) CGRect rect; @property (nonatomic, readonly) short progress; // from 0 to 100 @property (nonatomic, readonly) NSString *recognizedText; @property (nonatomic, weak) id<TesseractDelegate> delegate; /// /// @warning deprecated method! /// @deprecated - (id)initWithDataPath:(NSString *)dataPath language:(NSString *)language is deprecated. Please use - (id)initWithLanguage:(NSString*)language; /// - (id)initWithDataPath:(NSString *)dataPath language:(NSString *)language DEPRECATED_ATTRIBUTE; - (id)initWithLanguage:(NSString*)language; - (void)setVariableValue:(NSString *)value forKey:(NSString *)key; - (BOOL)recognize; /// /// @warning deprecated method! /// @deprecated - (void)clear is deprecated. The memory will be freed in dealloc added by ARC; /// - (void)clear DEPRECATED_ATTRIBUTE; @end
Add a deprecated warning for - (void)clear.
Add a deprecated warning for - (void)clear.
C
mit
gank0326/Tesseract,lampkicking/Tesseract-OCR-iOS,zyggit/Tesseract-OCR-iOS,hejunbinlan/Tesseract-OCR-iOS,DanielShum/Tesseract-OCR-iOS,doo/Tesseract-OCR-iOS,StratAguilar/Tesseract-OCR-iOS,gank0326/Tesseract,lampkicking/Tesseract-OCR-iOS,ws233/Tesseract-OCR-iOS,Jaelene/Tesseract-OCR-iOS,gali8/Tesseract-OCR-iOS,cotsog/Tesseract-OCR-iOS,zilaiyedaren/Tesseract-OCR-iOS,jonesgithub/Tesseract-OCR-iOS,Richardlihui/Tesseract-OCR-iOS,amikey/Tesseract-OCR-iOS,ws233/Tesseract-OCR-iOS,zyggit/Tesseract-OCR-iOS,DanielShum/Tesseract-OCR-iOS,StratAguilar/Tesseract-OCR-iOS,cotsog/Tesseract-OCR-iOS,zilaiyedaren/Tesseract-OCR-iOS,zilaiyedaren/Tesseract-OCR-iOS,Jaelene/Tesseract-OCR-iOS,cookov/Tesseract-OCR-iOS,ryhor/Tesseract-OCR-iOS,lioonline/Tesseract-OCR-iOS,ninguchi/Tesseract-OCR-iOS,gali8/Tesseract-OCR-iOS,hoanganh6491/Tesseract-OCR-iOS,DanielShum/Tesseract-OCR-iOS,amikey/Tesseract-OCR-iOS,gali8/Tesseract-OCR-iOS,yangboz/Tesseract-OCR-iOS,lioonline/Tesseract-OCR-iOS,jeremiahyan/Tesseract-OCR-iOS,lioonline/Tesseract-OCR-iOS,zilaiyedaren/Tesseract-OCR-iOS,wenbo001/Tesseract-OCR-iOS,ChandlerNguyen/Tesseract-OCR-iOS,ryhor/Tesseract-OCR-iOS,cookov/Tesseract-OCR-iOS,lioonline/Tesseract-OCR-iOS,lioonline/Tesseract-OCR-iOS,IncredibleDucky/Tesseract-OCR-iOS,StratAguilar/Tesseract-OCR-iOS,hejunbinlan/Tesseract-OCR-iOS,zilaiyedaren/Tesseract-OCR-iOS,hejunbinlan/Tesseract-OCR-iOS,ChandlerNguyen/Tesseract-OCR-iOS,cookov/Tesseract-OCR-iOS,hoanganh6491/Tesseract-OCR-iOS,DanielShum/Tesseract-OCR-iOS,StratAguilar/Tesseract-OCR-iOS,doo/Tesseract-OCR-iOS,amikey/Tesseract-OCR-iOS,jeremiahyan/Tesseract-OCR-iOS,ChandlerNguyen/Tesseract-OCR-iOS,hoanganh6491/Tesseract-OCR-iOS,lampkicking/Tesseract-OCR-iOS,Richardlihui/Tesseract-OCR-iOS,jonesgithub/Tesseract-OCR-iOS,ChandlerNguyen/Tesseract-OCR-iOS,ryhor/Tesseract-OCR-iOS,Jaelene/Tesseract-OCR-iOS,hoanganh6491/Tesseract-OCR-iOS,jonesgithub/Tesseract-OCR-iOS,ChandlerNguyen/Tesseract-OCR-iOS,cookov/Tesseract-OCR-iOS,yangboz/Tesseract-OCR-iOS,zyggit/Tesseract-OCR-iOS,yangboz/Tesseract-OCR-iOS,hoanganh6491/Tesseract-OCR-iOS,gali8/Tesseract-OCR-iOS,zyggit/Tesseract-OCR-iOS,jonesgithub/Tesseract-OCR-iOS,lampkicking/Tesseract-OCR-iOS,ws233/Tesseract-OCR-iOS,cotsog/Tesseract-OCR-iOS,jonesgithub/Tesseract-OCR-iOS,jeremiahyan/Tesseract-OCR-iOS,IncredibleDucky/Tesseract-OCR-iOS,Jaelene/Tesseract-OCR-iOS,Jaelene/Tesseract-OCR-iOS,IncredibleDucky/Tesseract-OCR-iOS,gank0326/Tesseract,DanielShum/Tesseract-OCR-iOS,ninguchi/Tesseract-OCR-iOS,gank0326/Tesseract,doo/Tesseract-OCR-iOS,doo/Tesseract-OCR-iOS,ws233/Tesseract-OCR-iOS,doo/Tesseract-OCR-iOS,wenbo001/Tesseract-OCR-iOS,cookov/Tesseract-OCR-iOS,ninguchi/Tesseract-OCR-iOS,jeremiahyan/Tesseract-OCR-iOS,wenbo001/Tesseract-OCR-iOS,ws233/Tesseract-OCR-iOS,yangboz/Tesseract-OCR-iOS,yangboz/Tesseract-OCR-iOS,jeremiahyan/Tesseract-OCR-iOS,ninguchi/Tesseract-OCR-iOS,IncredibleDucky/Tesseract-OCR-iOS,amikey/Tesseract-OCR-iOS,StratAguilar/Tesseract-OCR-iOS,lampkicking/Tesseract-OCR-iOS,IncredibleDucky/Tesseract-OCR-iOS,cotsog/Tesseract-OCR-iOS,hejunbinlan/Tesseract-OCR-iOS,ninguchi/Tesseract-OCR-iOS,cotsog/Tesseract-OCR-iOS,wenbo001/Tesseract-OCR-iOS,doo/Tesseract-OCR-iOS,amikey/Tesseract-OCR-iOS,zyggit/Tesseract-OCR-iOS,wenbo001/Tesseract-OCR-iOS,Richardlihui/Tesseract-OCR-iOS,gank0326/Tesseract,ryhor/Tesseract-OCR-iOS,hejunbinlan/Tesseract-OCR-iOS,Richardlihui/Tesseract-OCR-iOS,gali8/Tesseract-OCR-iOS,Richardlihui/Tesseract-OCR-iOS,doo/Tesseract-OCR-iOS,ryhor/Tesseract-OCR-iOS
c
## Code Before: // // Tesseract.h // Tesseract // // Created by Loïs Di Qual on 24/09/12. // Copyright (c) 2012 Loïs Di Qual. // Under MIT License. See 'LICENCE' for more informations. // #import <UIKit/UIKit.h> @class Tesseract; @protocol TesseractDelegate <NSObject> @optional - (BOOL)shouldCancelImageRecognitionForTesseract:(Tesseract*)tesseract; @end @interface Tesseract : NSObject + (NSString *)version; @property (nonatomic, strong) NSString* language; @property (nonatomic, strong) UIImage *image; @property (nonatomic, assign) CGRect rect; @property (nonatomic, readonly) short progress; // from 0 to 100 @property (nonatomic, readonly) NSString *recognizedText; @property (nonatomic, weak) id<TesseractDelegate> delegate; /// /// @warning deprecated method! /// @deprecated - (id)initWithDataPath:(NSString *)dataPath language:(NSString *)language is deprecated. Please use - (id)initWithLanguage:(NSString*)language; /// - (id)initWithDataPath:(NSString *)dataPath language:(NSString *)language DEPRECATED_ATTRIBUTE; - (id)initWithLanguage:(NSString*)language; - (void)setVariableValue:(NSString *)value forKey:(NSString *)key; - (BOOL)recognize; - (void)clear; @end ## Instruction: Add a deprecated warning for - (void)clear. ## Code After: // // Tesseract.h // Tesseract // // Created by Loïs Di Qual on 24/09/12. // Copyright (c) 2012 Loïs Di Qual. // Under MIT License. See 'LICENCE' for more informations. // #import <UIKit/UIKit.h> @class Tesseract; @protocol TesseractDelegate <NSObject> @optional - (BOOL)shouldCancelImageRecognitionForTesseract:(Tesseract*)tesseract; @end @interface Tesseract : NSObject + (NSString *)version; @property (nonatomic, strong) NSString* language; @property (nonatomic, strong) UIImage *image; @property (nonatomic, assign) CGRect rect; @property (nonatomic, readonly) short progress; // from 0 to 100 @property (nonatomic, readonly) NSString *recognizedText; @property (nonatomic, weak) id<TesseractDelegate> delegate; /// /// @warning deprecated method! /// @deprecated - (id)initWithDataPath:(NSString *)dataPath language:(NSString *)language is deprecated. Please use - (id)initWithLanguage:(NSString*)language; /// - (id)initWithDataPath:(NSString *)dataPath language:(NSString *)language DEPRECATED_ATTRIBUTE; - (id)initWithLanguage:(NSString*)language; - (void)setVariableValue:(NSString *)value forKey:(NSString *)key; - (BOOL)recognize; /// /// @warning deprecated method! /// @deprecated - (void)clear is deprecated. The memory will be freed in dealloc added by ARC; /// - (void)clear DEPRECATED_ATTRIBUTE; @end
# ... existing code ... - (void)setVariableValue:(NSString *)value forKey:(NSString *)key; - (BOOL)recognize; /// /// @warning deprecated method! /// @deprecated - (void)clear is deprecated. The memory will be freed in dealloc added by ARC; /// - (void)clear DEPRECATED_ATTRIBUTE; @end # ... rest of the code ...
6e540d7125e76c2d4d7d06662ab283a5d698c86b
setup.py
setup.py
from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand import sys requirements = [line.strip() for line in open('requirements.txt').readlines()] class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest errcode = pytest.main(['linear_solver']) sys.exit(errcode) setup(name='linear_solver', version='0.0', description='', url='http://github.com/tcmoore3/linear_solver', author='Timothy C. Moore', author_email='[email protected]', license='MIT', packages=find_packages(), package_data={'linear_solver.testing': ['reference/*']}, install_requires=requirements, zip_safe=False, test_suite='linear_solver', cmdclass={'test': PyTest}, extras_require={'utils': ['pytest']}, )
from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand import sys requirements = [line.strip() for line in open('requirements.txt').readlines()] class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest errcode = pytest.main(['linear_solver/tests/tests.py']) sys.exit(errcode) setup(name='linear_solver', version='0.0', description='', url='http://github.com/tcmoore3/linear_solver', author='Timothy C. Moore', author_email='[email protected]', license='MIT', packages=find_packages(), package_data={'linear_solver.testing': ['reference/*']}, install_requires=requirements, zip_safe=False, test_suite='linear_solver', cmdclass={'test': PyTest}, extras_require={'utils': ['pytest']}, )
Add correct path to tests
Add correct path to tests
Python
mit
tcmoore3/linear_solver
python
## Code Before: from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand import sys requirements = [line.strip() for line in open('requirements.txt').readlines()] class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest errcode = pytest.main(['linear_solver']) sys.exit(errcode) setup(name='linear_solver', version='0.0', description='', url='http://github.com/tcmoore3/linear_solver', author='Timothy C. Moore', author_email='[email protected]', license='MIT', packages=find_packages(), package_data={'linear_solver.testing': ['reference/*']}, install_requires=requirements, zip_safe=False, test_suite='linear_solver', cmdclass={'test': PyTest}, extras_require={'utils': ['pytest']}, ) ## Instruction: Add correct path to tests ## Code After: from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand import sys requirements = [line.strip() for line in open('requirements.txt').readlines()] class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest errcode = pytest.main(['linear_solver/tests/tests.py']) sys.exit(errcode) setup(name='linear_solver', version='0.0', description='', url='http://github.com/tcmoore3/linear_solver', author='Timothy C. Moore', author_email='[email protected]', license='MIT', packages=find_packages(), package_data={'linear_solver.testing': ['reference/*']}, install_requires=requirements, zip_safe=False, test_suite='linear_solver', cmdclass={'test': PyTest}, extras_require={'utils': ['pytest']}, )
# ... existing code ... def run_tests(self): import pytest errcode = pytest.main(['linear_solver/tests/tests.py']) sys.exit(errcode) # ... rest of the code ...
e6457c384eaa13eff82217ef4eb15f580efd8121
setup.py
setup.py
import re from setuptools import setup init_py = open('wikipediabase/__init__.py').read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", init_py)) metadata['doc'] = re.findall('"""(.+)"""', init_py)[0] setup( name='wikipediabase', version=metadata['version'], description=metadata['doc'], author=metadata['author'], author_email=metadata['email'], url=metadata['url'], packages=[ 'wikipediabase', 'wikipediabase.resolvers', 'wikipediabase.adhoc', 'tests', ], include_package_data=True, install_requires=[ 'edn_format', 'docopt', 'flake8 < 3.0.0', 'unittest2 < 1.0.0', 'overlay-parse', 'lxml', 'sqlitedict', 'requests', 'beautifulsoup4', 'redis', 'redis', 'hiredis', ], dependency_links=[ 'git+https://github.com/fakedrake/overlay_parse#egg=overlay-parse', ], tests_require=[ 'nose>=1.0', 'sqlitedict', ], entry_points={ 'console_scripts': [ 'wikipediabase = wikipediabase.cli:main', ], }, test_suite='nose.collector', license=open('LICENSE').read(), )
import re from setuptools import setup init_py = open('wikipediabase/__init__.py').read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", init_py)) metadata['doc'] = re.findall('"""(.+)"""', init_py)[0] setup( name='wikipediabase', version=metadata['version'], description=metadata['doc'], author=metadata['author'], author_email=metadata['email'], url=metadata['url'], packages=[ 'wikipediabase', 'wikipediabase.resolvers', 'wikipediabase.adhoc', 'tests', ], include_package_data=True, install_requires=[ 'edn_format', 'docopt', 'flake8 < 3.0.0', 'unittest2 < 1.0.0', 'overlay-parse', 'lxml', 'sqlitedict', 'requests', 'beautifulsoup4', 'redis', 'redis', 'hiredis', 'unidecode', ], dependency_links=[ 'git+https://github.com/fakedrake/overlay_parse#egg=overlay-parse', ], tests_require=[ 'nose>=1.0', 'sqlitedict', ], entry_points={ 'console_scripts': [ 'wikipediabase = wikipediabase.cli:main', ], }, test_suite='nose.collector', license=open('LICENSE').read(), )
Add unidecode as a dependency
Add unidecode as a dependency
Python
apache-2.0
fakedrake/WikipediaBase
python
## Code Before: import re from setuptools import setup init_py = open('wikipediabase/__init__.py').read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", init_py)) metadata['doc'] = re.findall('"""(.+)"""', init_py)[0] setup( name='wikipediabase', version=metadata['version'], description=metadata['doc'], author=metadata['author'], author_email=metadata['email'], url=metadata['url'], packages=[ 'wikipediabase', 'wikipediabase.resolvers', 'wikipediabase.adhoc', 'tests', ], include_package_data=True, install_requires=[ 'edn_format', 'docopt', 'flake8 < 3.0.0', 'unittest2 < 1.0.0', 'overlay-parse', 'lxml', 'sqlitedict', 'requests', 'beautifulsoup4', 'redis', 'redis', 'hiredis', ], dependency_links=[ 'git+https://github.com/fakedrake/overlay_parse#egg=overlay-parse', ], tests_require=[ 'nose>=1.0', 'sqlitedict', ], entry_points={ 'console_scripts': [ 'wikipediabase = wikipediabase.cli:main', ], }, test_suite='nose.collector', license=open('LICENSE').read(), ) ## Instruction: Add unidecode as a dependency ## Code After: import re from setuptools import setup init_py = open('wikipediabase/__init__.py').read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", init_py)) metadata['doc'] = re.findall('"""(.+)"""', init_py)[0] setup( name='wikipediabase', version=metadata['version'], description=metadata['doc'], author=metadata['author'], author_email=metadata['email'], url=metadata['url'], packages=[ 'wikipediabase', 'wikipediabase.resolvers', 'wikipediabase.adhoc', 'tests', ], include_package_data=True, install_requires=[ 'edn_format', 'docopt', 'flake8 < 3.0.0', 'unittest2 < 1.0.0', 'overlay-parse', 'lxml', 'sqlitedict', 'requests', 'beautifulsoup4', 'redis', 'redis', 'hiredis', 'unidecode', ], dependency_links=[ 'git+https://github.com/fakedrake/overlay_parse#egg=overlay-parse', ], tests_require=[ 'nose>=1.0', 'sqlitedict', ], entry_points={ 'console_scripts': [ 'wikipediabase = wikipediabase.cli:main', ], }, test_suite='nose.collector', license=open('LICENSE').read(), )
... 'redis', 'redis', 'hiredis', 'unidecode', ], dependency_links=[ 'git+https://github.com/fakedrake/overlay_parse#egg=overlay-parse', ...
9a5fa9b32d822848dd8fcbdbf9627c8c89bcf66a
deen/main.py
deen/main.py
import sys import logging import pathlib from PyQt5.QtWidgets import QApplication from PyQt5.QtGui import QIcon from deen.widgets.core import Deen ICON = str(pathlib.PurePath(__file__).parent / 'icon.png') LOGGER = logging.getLogger() logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s') def main(): app = QApplication(sys.argv) ex = Deen() ex.setWindowIcon(QIcon(ICON)) LOGGER.addHandler(ex.log) return app.exec_()
import sys import logging import os.path from PyQt5.QtWidgets import QApplication from PyQt5.QtGui import QIcon from deen.widgets.core import Deen ICON = os.path.dirname(os.path.abspath(__file__)) + '/icon.png' LOGGER = logging.getLogger() logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s') def main(): app = QApplication(sys.argv) ex = Deen() ex.setWindowIcon(QIcon(ICON)) LOGGER.addHandler(ex.log) return app.exec_()
Use os.path instead of pathlib
Use os.path instead of pathlib
Python
apache-2.0
takeshixx/deen,takeshixx/deen
python
## Code Before: import sys import logging import pathlib from PyQt5.QtWidgets import QApplication from PyQt5.QtGui import QIcon from deen.widgets.core import Deen ICON = str(pathlib.PurePath(__file__).parent / 'icon.png') LOGGER = logging.getLogger() logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s') def main(): app = QApplication(sys.argv) ex = Deen() ex.setWindowIcon(QIcon(ICON)) LOGGER.addHandler(ex.log) return app.exec_() ## Instruction: Use os.path instead of pathlib ## Code After: import sys import logging import os.path from PyQt5.QtWidgets import QApplication from PyQt5.QtGui import QIcon from deen.widgets.core import Deen ICON = os.path.dirname(os.path.abspath(__file__)) + '/icon.png' LOGGER = logging.getLogger() logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s') def main(): app = QApplication(sys.argv) ex = Deen() ex.setWindowIcon(QIcon(ICON)) LOGGER.addHandler(ex.log) return app.exec_()
... import sys import logging import os.path from PyQt5.QtWidgets import QApplication from PyQt5.QtGui import QIcon ... from deen.widgets.core import Deen ICON = os.path.dirname(os.path.abspath(__file__)) + '/icon.png' LOGGER = logging.getLogger() logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s') ...
02f77babc6195426fdb5c495d44ede6af6fbec8f
mangopaysdk/entities/userlegal.py
mangopaysdk/entities/userlegal.py
from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.entities.user import User from mangopaysdk.tools.enums import PersonType from mangopaysdk.tools.enums import KYCLevel class UserLegal (User): def __init__(self, id = None): super(UserLegal, self).__init__(id) self._setPersonType(PersonType.Legal) self.Name = None # Required LegalPersonType: BUSINESS, ORGANIZATION self.LegalPersonType = None self.HeadquartersAddress = None # Required self.LegalRepresentativeFirstName = None # Required self.LegalRepresentativeLastName = None self.LegalRepresentativeAddress = None self.LegalRepresentativeEmail = None # Required self.LegalRepresentativeBirthday = None # Required self.LegalRepresentativeNationality = None # Required self.LegalRepresentativeCountryOfResidence = None self._statute = None self._proofOfRegistration = None self._shareholderDeclaration = None def GetReadOnlyProperties(self): properties = super(UserLegal, self).GetReadOnlyProperties() properties.append('Statute' ) properties.append('ProofOfRegistration' ) properties.append('ShareholderDeclaration' ) return properties
from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.entities.user import User from mangopaysdk.tools.enums import PersonType from mangopaysdk.tools.enums import KYCLevel class UserLegal (User): def __init__(self, id = None): super(UserLegal, self).__init__(id) self._setPersonType(PersonType.Legal) self.Name = None # Required LegalPersonType: BUSINESS, ORGANIZATION self.LegalPersonType = None self.HeadquartersAddress = None # Required self.LegalRepresentativeFirstName = None # Required self.LegalRepresentativeLastName = None self.LegalRepresentativeAddress = None self.LegalRepresentativeEmail = None # Required self.LegalRepresentativeBirthday = None # Required self.LegalRepresentativeNationality = None # Required self.LegalRepresentativeCountryOfResidence = None self._statute = None self._proofOfRegistration = None self._shareholderDeclaration = None self._legalRepresentativeProofOfIdentity = None def GetReadOnlyProperties(self): properties = super(UserLegal, self).GetReadOnlyProperties() properties.append('Statute' ) properties.append('ProofOfRegistration' ) properties.append('ShareholderDeclaration' ) properties.append('LegalRepresentativeProofOfIdentity' ) return properties
Add LegalRepresentativeProofOfIdentity to legal user
Add LegalRepresentativeProofOfIdentity to legal user
Python
mit
chocopoche/mangopay2-python-sdk,Mangopay/mangopay2-python-sdk
python
## Code Before: from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.entities.user import User from mangopaysdk.tools.enums import PersonType from mangopaysdk.tools.enums import KYCLevel class UserLegal (User): def __init__(self, id = None): super(UserLegal, self).__init__(id) self._setPersonType(PersonType.Legal) self.Name = None # Required LegalPersonType: BUSINESS, ORGANIZATION self.LegalPersonType = None self.HeadquartersAddress = None # Required self.LegalRepresentativeFirstName = None # Required self.LegalRepresentativeLastName = None self.LegalRepresentativeAddress = None self.LegalRepresentativeEmail = None # Required self.LegalRepresentativeBirthday = None # Required self.LegalRepresentativeNationality = None # Required self.LegalRepresentativeCountryOfResidence = None self._statute = None self._proofOfRegistration = None self._shareholderDeclaration = None def GetReadOnlyProperties(self): properties = super(UserLegal, self).GetReadOnlyProperties() properties.append('Statute' ) properties.append('ProofOfRegistration' ) properties.append('ShareholderDeclaration' ) return properties ## Instruction: Add LegalRepresentativeProofOfIdentity to legal user ## Code After: from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.entities.user import User from mangopaysdk.tools.enums import PersonType from mangopaysdk.tools.enums import KYCLevel class UserLegal (User): def __init__(self, id = None): super(UserLegal, self).__init__(id) self._setPersonType(PersonType.Legal) self.Name = None # Required LegalPersonType: BUSINESS, ORGANIZATION self.LegalPersonType = None self.HeadquartersAddress = None # Required self.LegalRepresentativeFirstName = None # Required self.LegalRepresentativeLastName = None self.LegalRepresentativeAddress = None self.LegalRepresentativeEmail = None # Required self.LegalRepresentativeBirthday = None # Required self.LegalRepresentativeNationality = None # Required self.LegalRepresentativeCountryOfResidence = None self._statute = None self._proofOfRegistration = None self._shareholderDeclaration = None self._legalRepresentativeProofOfIdentity = None def GetReadOnlyProperties(self): properties = super(UserLegal, self).GetReadOnlyProperties() properties.append('Statute' ) properties.append('ProofOfRegistration' ) properties.append('ShareholderDeclaration' ) properties.append('LegalRepresentativeProofOfIdentity' ) return properties
// ... existing code ... self._statute = None self._proofOfRegistration = None self._shareholderDeclaration = None self._legalRepresentativeProofOfIdentity = None def GetReadOnlyProperties(self): properties = super(UserLegal, self).GetReadOnlyProperties() properties.append('Statute' ) properties.append('ProofOfRegistration' ) properties.append('ShareholderDeclaration' ) properties.append('LegalRepresentativeProofOfIdentity' ) return properties // ... rest of the code ...
646a248d59f835264729b48a0116d51089f6113e
oscar/templatetags/currency_filters.py
oscar/templatetags/currency_filters.py
from decimal import Decimal as D, InvalidOperation from django import template from django.conf import settings from babel.numbers import format_currency register = template.Library() @register.filter(name='currency') def currency(value): """ Format decimal value as currency """ try: value = D(value) except (TypeError, InvalidOperation): return u"" # Using Babel's currency formatting # http://packages.python.org/Babel/api/babel.numbers-module.html#format_currency kwargs = { 'currency': settings.OSCAR_DEFAULT_CURRENCY, 'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None)} locale = getattr(settings, 'OSCAR_CURRENCY_LOCALE', None) if locale: kwargs['locale'] = locale return format_currency(value, **kwargs)
from decimal import Decimal as D, InvalidOperation from django import template from django.conf import settings from babel.numbers import format_currency register = template.Library() @register.filter(name='currency') def currency(value): """ Format decimal value as currency """ try: value = D(value) except (TypeError, InvalidOperation): return u"" # Using Babel's currency formatting # http://babel.pocoo.org/docs/api/numbers/#babel.numbers.format_currency kwargs = { 'currency': settings.OSCAR_DEFAULT_CURRENCY, 'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None)} locale = getattr(settings, 'OSCAR_CURRENCY_LOCALE', None) if locale: kwargs['locale'] = locale return format_currency(value, **kwargs)
Replace broken babel documentation link
Replace broken babel documentation link According to Babel's PyPI package page, http://babel.pocoo.org/docs/ is the official documentation website.
Python
bsd-3-clause
lijoantony/django-oscar,faratro/django-oscar,michaelkuty/django-oscar,MatthewWilkes/django-oscar,django-oscar/django-oscar,dongguangming/django-oscar,taedori81/django-oscar,pasqualguerrero/django-oscar,marcoantoniooliveira/labweb,faratro/django-oscar,Jannes123/django-oscar,binarydud/django-oscar,Jannes123/django-oscar,solarissmoke/django-oscar,faratro/django-oscar,pdonadeo/django-oscar,ademuk/django-oscar,vovanbo/django-oscar,michaelkuty/django-oscar,okfish/django-oscar,thechampanurag/django-oscar,sasha0/django-oscar,rocopartners/django-oscar,binarydud/django-oscar,pdonadeo/django-oscar,elliotthill/django-oscar,john-parton/django-oscar,adamend/django-oscar,ahmetdaglarbas/e-commerce,mexeniz/django-oscar,Jannes123/django-oscar,monikasulik/django-oscar,rocopartners/django-oscar,josesanch/django-oscar,QLGu/django-oscar,Bogh/django-oscar,dongguangming/django-oscar,spartonia/django-oscar,bschuon/django-oscar,vovanbo/django-oscar,marcoantoniooliveira/labweb,WadeYuChen/django-oscar,manevant/django-oscar,anentropic/django-oscar,django-oscar/django-oscar,thechampanurag/django-oscar,Jannes123/django-oscar,solarissmoke/django-oscar,marcoantoniooliveira/labweb,jinnykoo/wuyisj,monikasulik/django-oscar,Bogh/django-oscar,bnprk/django-oscar,lijoantony/django-oscar,adamend/django-oscar,okfish/django-oscar,itbabu/django-oscar,jinnykoo/wuyisj,kapt/django-oscar,jinnykoo/wuyisj.com,pasqualguerrero/django-oscar,MatthewWilkes/django-oscar,anentropic/django-oscar,DrOctogon/unwash_ecom,josesanch/django-oscar,WadeYuChen/django-oscar,makielab/django-oscar,WillisXChen/django-oscar,manevant/django-oscar,faratro/django-oscar,john-parton/django-oscar,itbabu/django-oscar,spartonia/django-oscar,kapari/django-oscar,WillisXChen/django-oscar,ademuk/django-oscar,thechampanurag/django-oscar,kapari/django-oscar,saadatqadri/django-oscar,machtfit/django-oscar,makielab/django-oscar,sonofatailor/django-oscar,jinnykoo/christmas,michaelkuty/django-oscar,makielab/django-oscar,okfish/django-oscar,manevant/django-oscar,DrOctogon/unwash_ecom,taedori81/django-oscar,Idematica/django-oscar,Idematica/django-oscar,nickpack/django-oscar,jinnykoo/christmas,ahmetdaglarbas/e-commerce,mexeniz/django-oscar,vovanbo/django-oscar,jinnykoo/wuyisj.com,okfish/django-oscar,mexeniz/django-oscar,jinnykoo/wuyisj.com,machtfit/django-oscar,itbabu/django-oscar,bschuon/django-oscar,dongguangming/django-oscar,MatthewWilkes/django-oscar,anentropic/django-oscar,machtfit/django-oscar,Idematica/django-oscar,michaelkuty/django-oscar,jinnykoo/wuyisj.com,sasha0/django-oscar,amirrpp/django-oscar,monikasulik/django-oscar,bnprk/django-oscar,elliotthill/django-oscar,spartonia/django-oscar,lijoantony/django-oscar,jinnykoo/wuyisj,nickpack/django-oscar,sonofatailor/django-oscar,nfletton/django-oscar,jmt4/django-oscar,ka7eh/django-oscar,WadeYuChen/django-oscar,WillisXChen/django-oscar,eddiep1101/django-oscar,rocopartners/django-oscar,saadatqadri/django-oscar,binarydud/django-oscar,jlmadurga/django-oscar,django-oscar/django-oscar,itbabu/django-oscar,ademuk/django-oscar,jmt4/django-oscar,sasha0/django-oscar,nfletton/django-oscar,DrOctogon/unwash_ecom,taedori81/django-oscar,Bogh/django-oscar,ahmetdaglarbas/e-commerce,anentropic/django-oscar,binarydud/django-oscar,WadeYuChen/django-oscar,jlmadurga/django-oscar,makielab/django-oscar,marcoantoniooliveira/labweb,nfletton/django-oscar,manevant/django-oscar,nickpack/django-oscar,lijoantony/django-oscar,taedori81/django-oscar,sonofatailor/django-oscar,ahmetdaglarbas/e-commerce,kapari/django-oscar,ka7eh/django-oscar,saadatqadri/django-oscar,bnprk/django-oscar,solarissmoke/django-oscar,john-parton/django-oscar,solarissmoke/django-oscar,QLGu/django-oscar,kapt/django-oscar,john-parton/django-oscar,WillisXChen/django-oscar,jlmadurga/django-oscar,elliotthill/django-oscar,pdonadeo/django-oscar,pasqualguerrero/django-oscar,amirrpp/django-oscar,nickpack/django-oscar,bschuon/django-oscar,kapari/django-oscar,sasha0/django-oscar,MatthewWilkes/django-oscar,Bogh/django-oscar,nfletton/django-oscar,pasqualguerrero/django-oscar,dongguangming/django-oscar,amirrpp/django-oscar,saadatqadri/django-oscar,josesanch/django-oscar,QLGu/django-oscar,monikasulik/django-oscar,ademuk/django-oscar,spartonia/django-oscar,jlmadurga/django-oscar,jinnykoo/christmas,ka7eh/django-oscar,rocopartners/django-oscar,sonofatailor/django-oscar,eddiep1101/django-oscar,QLGu/django-oscar,jmt4/django-oscar,adamend/django-oscar,adamend/django-oscar,eddiep1101/django-oscar,bnprk/django-oscar,jinnykoo/wuyisj,WillisXChen/django-oscar,amirrpp/django-oscar,eddiep1101/django-oscar,vovanbo/django-oscar,bschuon/django-oscar,kapt/django-oscar,mexeniz/django-oscar,WillisXChen/django-oscar,ka7eh/django-oscar,thechampanurag/django-oscar,pdonadeo/django-oscar,jmt4/django-oscar,django-oscar/django-oscar
python
## Code Before: from decimal import Decimal as D, InvalidOperation from django import template from django.conf import settings from babel.numbers import format_currency register = template.Library() @register.filter(name='currency') def currency(value): """ Format decimal value as currency """ try: value = D(value) except (TypeError, InvalidOperation): return u"" # Using Babel's currency formatting # http://packages.python.org/Babel/api/babel.numbers-module.html#format_currency kwargs = { 'currency': settings.OSCAR_DEFAULT_CURRENCY, 'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None)} locale = getattr(settings, 'OSCAR_CURRENCY_LOCALE', None) if locale: kwargs['locale'] = locale return format_currency(value, **kwargs) ## Instruction: Replace broken babel documentation link According to Babel's PyPI package page, http://babel.pocoo.org/docs/ is the official documentation website. ## Code After: from decimal import Decimal as D, InvalidOperation from django import template from django.conf import settings from babel.numbers import format_currency register = template.Library() @register.filter(name='currency') def currency(value): """ Format decimal value as currency """ try: value = D(value) except (TypeError, InvalidOperation): return u"" # Using Babel's currency formatting # http://babel.pocoo.org/docs/api/numbers/#babel.numbers.format_currency kwargs = { 'currency': settings.OSCAR_DEFAULT_CURRENCY, 'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None)} locale = getattr(settings, 'OSCAR_CURRENCY_LOCALE', None) if locale: kwargs['locale'] = locale return format_currency(value, **kwargs)
# ... existing code ... except (TypeError, InvalidOperation): return u"" # Using Babel's currency formatting # http://babel.pocoo.org/docs/api/numbers/#babel.numbers.format_currency kwargs = { 'currency': settings.OSCAR_DEFAULT_CURRENCY, 'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None)} # ... rest of the code ...
19a58255f247199d0e60408cab8220a8c2a1ff3b
qxlc/minifier.py
qxlc/minifier.py
import htmlmin from markupsafe import Markup from qxlc import app @app.template_filter("minify") def minify_filter(text): return Markup(htmlmin.minify(text.unescape(), remove_comments=True, remove_empty_space=True))
import htmlmin from markupsafe import Markup from qxlc import app @app.template_filter("minify") def minify_filter(s): return Markup(htmlmin.minify(str(s), remove_comments=True, remove_empty_space=True))
Use str(s) instead of s.unescape() to add support for escaping things inside. (took me a while to find that str() worked)
Use str(s) instead of s.unescape() to add support for escaping things inside. (took me a while to find that str() worked)
Python
apache-2.0
daboross/qxlc,daboross/qxlc
python
## Code Before: import htmlmin from markupsafe import Markup from qxlc import app @app.template_filter("minify") def minify_filter(text): return Markup(htmlmin.minify(text.unescape(), remove_comments=True, remove_empty_space=True)) ## Instruction: Use str(s) instead of s.unescape() to add support for escaping things inside. (took me a while to find that str() worked) ## Code After: import htmlmin from markupsafe import Markup from qxlc import app @app.template_filter("minify") def minify_filter(s): return Markup(htmlmin.minify(str(s), remove_comments=True, remove_empty_space=True))
// ... existing code ... @app.template_filter("minify") def minify_filter(s): return Markup(htmlmin.minify(str(s), remove_comments=True, remove_empty_space=True)) // ... rest of the code ...
25f2692d5865a76533f8087c2f566299ae777c8e
conman/redirects/views.py
conman/redirects/views.py
from django.views.generic import RedirectView class RouteRedirectView(RedirectView): """Redirect to the target Route.""" def get_redirect_url(self, *args, **kwargs): """ Return the route's target url. Save the route's redirect type for use by RedirectView. """ redirect = kwargs['route'] self.permanent = redirect.permanent return redirect.target.url
from django.views.generic import RedirectView class RouteRedirectView(RedirectView): """Redirect to the target Route.""" permanent = True # Set to django 1.9's default to avoid RemovedInDjango19Warning def get_redirect_url(self, *args, **kwargs): """ Return the route's target url. Save the route's redirect type for use by RedirectView. """ redirect = kwargs['route'] self.permanent = redirect.permanent return redirect.target.url
Set variable to future default
Set variable to future default Deprecation warning was: RemovedInDjango19Warning: Default value of 'RedirectView.permanent' will change from True to False in Django 1.9. Set an explicit value to silence this warning.
Python
bsd-2-clause
meshy/django-conman,meshy/django-conman,Ian-Foote/django-conman
python
## Code Before: from django.views.generic import RedirectView class RouteRedirectView(RedirectView): """Redirect to the target Route.""" def get_redirect_url(self, *args, **kwargs): """ Return the route's target url. Save the route's redirect type for use by RedirectView. """ redirect = kwargs['route'] self.permanent = redirect.permanent return redirect.target.url ## Instruction: Set variable to future default Deprecation warning was: RemovedInDjango19Warning: Default value of 'RedirectView.permanent' will change from True to False in Django 1.9. Set an explicit value to silence this warning. ## Code After: from django.views.generic import RedirectView class RouteRedirectView(RedirectView): """Redirect to the target Route.""" permanent = True # Set to django 1.9's default to avoid RemovedInDjango19Warning def get_redirect_url(self, *args, **kwargs): """ Return the route's target url. Save the route's redirect type for use by RedirectView. """ redirect = kwargs['route'] self.permanent = redirect.permanent return redirect.target.url
# ... existing code ... class RouteRedirectView(RedirectView): """Redirect to the target Route.""" permanent = True # Set to django 1.9's default to avoid RemovedInDjango19Warning def get_redirect_url(self, *args, **kwargs): """ Return the route's target url. # ... rest of the code ...
bf94028e883779ee7ee9da58a970796ab8b0be25
program2.c
program2.c
/* * CIS 314 Fall 2015 Lab 1 * Assigned project * * This program reads a sorted array from a file and finds a requested number * using recursive or iterative binary search. The array is read from a file * defined by FILE_NAME, which should be written as the number of elements * followed by the elements themselses. each number can be deliniated with * any whitepace character. Also, the maximum size of the array is defined * as MAX_SIZE. * * NOTE: The array must be sorted!! * */ #include <stdio.h> #include <stdlib.h> #include <time.h> #define MAX_SIZE 150 #define FILE_NAME "array.dat" //must include quotes // Implement the rest of the program int main(void) { FILE *in_file; int array[MAX_SIZE]; int size; char in_file_name[] = FILE_NAME; printf("\n\n=== CIS314 Fall 2014 - Lab 1: Part 2: Program 2 ===\n\n"); printf("\n\n"); return 0; } int recursiveBinarySearch(int list_of_numbers[], int desired_number, int low_number, int high_number) { } int iterativeBinarySearch(int list_of_numbers[], int desired_number) { }
/* * CIS 314 Fall 2015 Lab 1 * Assigned project * * This program reads a sorted array from a file and finds a requested number * using recursive or iterative binary search. The array is read from a file * defined by FILE_NAME, which should be written as the number of elements * followed by the elements themselses. each number can be deliniated with * any whitepace character. Also, the maximum size of the array is defined * as MAX_SIZE. * * NOTE: The array must be sorted!! * */ #include <stdio.h> #include <stdlib.h> #include <time.h> #define MAX_SIZE 150 #define FILE_NAME "array.dat" //must include quotes // Implement the rest of the program int main(void) { FILE *in_file; int array[MAX_SIZE]; int size; char in_file_name[] = FILE_NAME; printf("\n\n=== CIS314 Fall 2014 - Lab 1: Part 2: Program 2 ===\n\n"); printf("\n\n"); return 0; } int recursiveBinarySearch(int list_of_numbers[], int desired_number, int low_number, int high_number) { } int iterativeBinarySearch(int list_of_numbers[], int desired_number) { int low = 0; int high = (sizeof(list_of_numbers)/sizeof(list_of_numbers[0])) - 1 }
Add high and low in iterative
Add high and low in iterative
C
mit
jacobbieker/CIS314_Lab_1
c
## Code Before: /* * CIS 314 Fall 2015 Lab 1 * Assigned project * * This program reads a sorted array from a file and finds a requested number * using recursive or iterative binary search. The array is read from a file * defined by FILE_NAME, which should be written as the number of elements * followed by the elements themselses. each number can be deliniated with * any whitepace character. Also, the maximum size of the array is defined * as MAX_SIZE. * * NOTE: The array must be sorted!! * */ #include <stdio.h> #include <stdlib.h> #include <time.h> #define MAX_SIZE 150 #define FILE_NAME "array.dat" //must include quotes // Implement the rest of the program int main(void) { FILE *in_file; int array[MAX_SIZE]; int size; char in_file_name[] = FILE_NAME; printf("\n\n=== CIS314 Fall 2014 - Lab 1: Part 2: Program 2 ===\n\n"); printf("\n\n"); return 0; } int recursiveBinarySearch(int list_of_numbers[], int desired_number, int low_number, int high_number) { } int iterativeBinarySearch(int list_of_numbers[], int desired_number) { } ## Instruction: Add high and low in iterative ## Code After: /* * CIS 314 Fall 2015 Lab 1 * Assigned project * * This program reads a sorted array from a file and finds a requested number * using recursive or iterative binary search. The array is read from a file * defined by FILE_NAME, which should be written as the number of elements * followed by the elements themselses. each number can be deliniated with * any whitepace character. Also, the maximum size of the array is defined * as MAX_SIZE. * * NOTE: The array must be sorted!! * */ #include <stdio.h> #include <stdlib.h> #include <time.h> #define MAX_SIZE 150 #define FILE_NAME "array.dat" //must include quotes // Implement the rest of the program int main(void) { FILE *in_file; int array[MAX_SIZE]; int size; char in_file_name[] = FILE_NAME; printf("\n\n=== CIS314 Fall 2014 - Lab 1: Part 2: Program 2 ===\n\n"); printf("\n\n"); return 0; } int recursiveBinarySearch(int list_of_numbers[], int desired_number, int low_number, int high_number) { } int iterativeBinarySearch(int list_of_numbers[], int desired_number) { int low = 0; int high = (sizeof(list_of_numbers)/sizeof(list_of_numbers[0])) - 1 }
# ... existing code ... } int iterativeBinarySearch(int list_of_numbers[], int desired_number) { int low = 0; int high = (sizeof(list_of_numbers)/sizeof(list_of_numbers[0])) - 1 } # ... rest of the code ...
754cc91b0bbd3f0b01cb67fdf45bbb2ec0377222
guice/common/src/main/java/com/peterphi/std/guice/common/serviceprops/net/NetworkConfigReloadModule.java
guice/common/src/main/java/com/peterphi/std/guice/common/serviceprops/net/NetworkConfigReloadModule.java
package com.peterphi.std.guice.common.serviceprops.net; import com.google.inject.AbstractModule; public class NetworkConfigReloadModule extends AbstractModule { @Override protected void configure() { bind(NetworkConfigReloadDaemon.class).asEagerSingleton(); } }
package com.peterphi.std.guice.common.serviceprops.net; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Singleton; import com.peterphi.std.guice.config.rest.iface.ConfigRestService; import com.peterphi.std.guice.restclient.JAXRSProxyClientFactory; public class NetworkConfigReloadModule extends AbstractModule { @Override protected void configure() { bind(NetworkConfigReloadDaemon.class).asEagerSingleton(); } @Provides @Singleton public ConfigRestService getConfigService(JAXRSProxyClientFactory factory) { return factory.getClient(ConfigRestService.class); } }
Add explicit jax-rs client provider for ConfigRestService so that scan.packages doesn't have to include ConfigRestService
Add explicit jax-rs client provider for ConfigRestService so that scan.packages doesn't have to include ConfigRestService
Java
mit
petergeneric/stdlib,petergeneric/stdlib,petergeneric/stdlib
java
## Code Before: package com.peterphi.std.guice.common.serviceprops.net; import com.google.inject.AbstractModule; public class NetworkConfigReloadModule extends AbstractModule { @Override protected void configure() { bind(NetworkConfigReloadDaemon.class).asEagerSingleton(); } } ## Instruction: Add explicit jax-rs client provider for ConfigRestService so that scan.packages doesn't have to include ConfigRestService ## Code After: package com.peterphi.std.guice.common.serviceprops.net; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Singleton; import com.peterphi.std.guice.config.rest.iface.ConfigRestService; import com.peterphi.std.guice.restclient.JAXRSProxyClientFactory; public class NetworkConfigReloadModule extends AbstractModule { @Override protected void configure() { bind(NetworkConfigReloadDaemon.class).asEagerSingleton(); } @Provides @Singleton public ConfigRestService getConfigService(JAXRSProxyClientFactory factory) { return factory.getClient(ConfigRestService.class); } }
# ... existing code ... package com.peterphi.std.guice.common.serviceprops.net; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Singleton; import com.peterphi.std.guice.config.rest.iface.ConfigRestService; import com.peterphi.std.guice.restclient.JAXRSProxyClientFactory; public class NetworkConfigReloadModule extends AbstractModule { # ... modified code ... { bind(NetworkConfigReloadDaemon.class).asEagerSingleton(); } @Provides @Singleton public ConfigRestService getConfigService(JAXRSProxyClientFactory factory) { return factory.getClient(ConfigRestService.class); } } # ... rest of the code ...
1d2d8727f421cde5e869a9bbfb00c06df5163fac
core/src/main/java/pw/scho/battleship/persistence/configuration/MongoConfiguration.java
core/src/main/java/pw/scho/battleship/persistence/configuration/MongoConfiguration.java
package pw.scho.battleship.persistence.configuration; import com.mongodb.ServerAddress; import org.mongolink.MongoSession; import org.mongolink.MongoSessionManager; import org.mongolink.Settings; import org.mongolink.UpdateStrategies; import org.mongolink.domain.mapper.ContextBuilder; import java.net.UnknownHostException; import java.util.Arrays; public class MongoConfiguration { public static void stop() { Singleton.INSTANCE.mongoSessionManager.close(); } public static MongoSession createSession() { return Singleton.INSTANCE.mongoSessionManager.createSession(); } private enum Singleton { INSTANCE; private final MongoSessionManager mongoSessionManager; private Singleton() { ContextBuilder builder = new ContextBuilder("pw.scho.battleship.persistence.mongo.mapping"); Settings settings = null; try { settings = Settings.defaultInstance() .withDefaultUpdateStrategy(UpdateStrategies.DIFF) .withDbName("battleship") .withAddresses(Arrays.asList(new ServerAddress("localhost", 27017))); } catch (UnknownHostException e) { } mongoSessionManager = MongoSessionManager.create(builder, settings); } } }
package pw.scho.battleship.persistence.configuration; import com.mongodb.DB; import com.mongodb.MongoURI; import com.mongodb.ServerAddress; import org.mongolink.MongoSession; import org.mongolink.MongoSessionManager; import org.mongolink.Settings; import org.mongolink.UpdateStrategies; import org.mongolink.domain.mapper.ContextBuilder; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MongoConfiguration { public static void stop() { Singleton.INSTANCE.mongoSessionManager.close(); } public static MongoSession createSession() { return Singleton.INSTANCE.mongoSessionManager.createSession(); } private enum Singleton { INSTANCE; private final MongoSessionManager mongoSessionManager; private Singleton() { ContextBuilder builder = new ContextBuilder("pw.scho.battleship.persistence.mongo.mapping"); Settings settings = null; try { settings = Settings.defaultInstance() .withDefaultUpdateStrategy(UpdateStrategies.DIFF) .withDbName("battleship"); String mongoHqUrl = System.getenv("MONGOHQ_URL"); if(mongoHqUrl!= null){ MongoURI mongoURI = new MongoURI(mongoHqUrl); List<ServerAddress> serverAdresses = new ArrayList<>(); for(String host : mongoURI.getHosts()){ serverAdresses.add(new ServerAddress(host, 27017)); } settings = settings.withAddresses(serverAdresses) .withAuthentication(mongoURI.getUsername(), mongoURI.getPassword().toString()); } else { settings = settings.withAddresses(Arrays.asList(new ServerAddress("localhost", 27017))); } } catch (UnknownHostException e) { } mongoSessionManager = MongoSessionManager.create(builder, settings); } } }
Add mongo hq authentication for heroku
Add mongo hq authentication for heroku
Java
mit
scho/battleship,scho/battleship
java
## Code Before: package pw.scho.battleship.persistence.configuration; import com.mongodb.ServerAddress; import org.mongolink.MongoSession; import org.mongolink.MongoSessionManager; import org.mongolink.Settings; import org.mongolink.UpdateStrategies; import org.mongolink.domain.mapper.ContextBuilder; import java.net.UnknownHostException; import java.util.Arrays; public class MongoConfiguration { public static void stop() { Singleton.INSTANCE.mongoSessionManager.close(); } public static MongoSession createSession() { return Singleton.INSTANCE.mongoSessionManager.createSession(); } private enum Singleton { INSTANCE; private final MongoSessionManager mongoSessionManager; private Singleton() { ContextBuilder builder = new ContextBuilder("pw.scho.battleship.persistence.mongo.mapping"); Settings settings = null; try { settings = Settings.defaultInstance() .withDefaultUpdateStrategy(UpdateStrategies.DIFF) .withDbName("battleship") .withAddresses(Arrays.asList(new ServerAddress("localhost", 27017))); } catch (UnknownHostException e) { } mongoSessionManager = MongoSessionManager.create(builder, settings); } } } ## Instruction: Add mongo hq authentication for heroku ## Code After: package pw.scho.battleship.persistence.configuration; import com.mongodb.DB; import com.mongodb.MongoURI; import com.mongodb.ServerAddress; import org.mongolink.MongoSession; import org.mongolink.MongoSessionManager; import org.mongolink.Settings; import org.mongolink.UpdateStrategies; import org.mongolink.domain.mapper.ContextBuilder; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MongoConfiguration { public static void stop() { Singleton.INSTANCE.mongoSessionManager.close(); } public static MongoSession createSession() { return Singleton.INSTANCE.mongoSessionManager.createSession(); } private enum Singleton { INSTANCE; private final MongoSessionManager mongoSessionManager; private Singleton() { ContextBuilder builder = new ContextBuilder("pw.scho.battleship.persistence.mongo.mapping"); Settings settings = null; try { settings = Settings.defaultInstance() .withDefaultUpdateStrategy(UpdateStrategies.DIFF) .withDbName("battleship"); String mongoHqUrl = System.getenv("MONGOHQ_URL"); if(mongoHqUrl!= null){ MongoURI mongoURI = new MongoURI(mongoHqUrl); List<ServerAddress> serverAdresses = new ArrayList<>(); for(String host : mongoURI.getHosts()){ serverAdresses.add(new ServerAddress(host, 27017)); } settings = settings.withAddresses(serverAdresses) .withAuthentication(mongoURI.getUsername(), mongoURI.getPassword().toString()); } else { settings = settings.withAddresses(Arrays.asList(new ServerAddress("localhost", 27017))); } } catch (UnknownHostException e) { } mongoSessionManager = MongoSessionManager.create(builder, settings); } } }
... package pw.scho.battleship.persistence.configuration; import com.mongodb.DB; import com.mongodb.MongoURI; import com.mongodb.ServerAddress; import org.mongolink.MongoSession; import org.mongolink.MongoSessionManager; ... import org.mongolink.UpdateStrategies; import org.mongolink.domain.mapper.ContextBuilder; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MongoConfiguration { ... try { settings = Settings.defaultInstance() .withDefaultUpdateStrategy(UpdateStrategies.DIFF) .withDbName("battleship"); String mongoHqUrl = System.getenv("MONGOHQ_URL"); if(mongoHqUrl!= null){ MongoURI mongoURI = new MongoURI(mongoHqUrl); List<ServerAddress> serverAdresses = new ArrayList<>(); for(String host : mongoURI.getHosts()){ serverAdresses.add(new ServerAddress(host, 27017)); } settings = settings.withAddresses(serverAdresses) .withAuthentication(mongoURI.getUsername(), mongoURI.getPassword().toString()); } else { settings = settings.withAddresses(Arrays.asList(new ServerAddress("localhost", 27017))); } } catch (UnknownHostException e) { } mongoSessionManager = MongoSessionManager.create(builder, settings); ...
8cf6f2c0d3ea09369fcf3cf871ea679ab791f6e2
devhub-server/web/src/main/java/nl/tudelft/ewi/dea/jaxrs/api/ExceptionAASResource.java
devhub-server/web/src/main/java/nl/tudelft/ewi/dea/jaxrs/api/ExceptionAASResource.java
package nl.tudelft.ewi.dea.jaxrs.api; import javax.ws.rs.GET; import javax.ws.rs.Path; import com.google.inject.servlet.RequestScoped; @RequestScoped @Path("api/exception") public class ExceptionAASResource { @GET public void throwException() { throw new RuntimeException("Your Exception-As-A-Service is served!"); } }
package nl.tudelft.ewi.dea.jaxrs.api; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; import com.google.inject.servlet.RequestScoped; @RequestScoped @Path("api/exception") public class ExceptionAASResource { @GET public Response throwException() { throw new RuntimeException("Your Exception-As-A-Service is served!"); } }
Return Response instead of void as per the spec.
Return Response instead of void as per the spec.
Java
apache-2.0
devhub-tud/devhub-prototype,devhub-tud/devhub-prototype,devhub-tud/devhub-prototype
java
## Code Before: package nl.tudelft.ewi.dea.jaxrs.api; import javax.ws.rs.GET; import javax.ws.rs.Path; import com.google.inject.servlet.RequestScoped; @RequestScoped @Path("api/exception") public class ExceptionAASResource { @GET public void throwException() { throw new RuntimeException("Your Exception-As-A-Service is served!"); } } ## Instruction: Return Response instead of void as per the spec. ## Code After: package nl.tudelft.ewi.dea.jaxrs.api; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; import com.google.inject.servlet.RequestScoped; @RequestScoped @Path("api/exception") public class ExceptionAASResource { @GET public Response throwException() { throw new RuntimeException("Your Exception-As-A-Service is served!"); } }
// ... existing code ... import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; import com.google.inject.servlet.RequestScoped; // ... modified code ... public class ExceptionAASResource { @GET public Response throwException() { throw new RuntimeException("Your Exception-As-A-Service is served!"); } // ... rest of the code ...
c2ca03ba94349340447a316ff21bcb26631e308f
lms/djangoapps/discussion/settings/common.py
lms/djangoapps/discussion/settings/common.py
"""Common environment variables unique to the discussion plugin.""" def plugin_settings(settings): """Settings for the discussions plugin. """ settings.FEATURES['ALLOW_HIDING_DISCUSSION_TAB'] = False settings.DISCUSSION_SETTINGS = { 'MAX_COMMENT_DEPTH': 2, 'COURSE_PUBLISH_TASK_DELAY': 30, }
"""Common environment variables unique to the discussion plugin.""" def plugin_settings(settings): """Settings for the discussions plugin. """ # .. toggle_name: ALLOW_HIDING_DISCUSSION_TAB # .. toggle_implementation: DjangoSetting # .. toggle_default: False # .. toggle_description: If True, it adds an option to show/hide the discussions tab. # .. toggle_use_cases: open_edx # .. toggle_creation_date: 2015-06-15 # .. toggle_target_removal_date: None # .. toggle_warnings: None # .. toggle_tickets: https://github.com/edx/edx-platform/pull/8474 settings.FEATURES['ALLOW_HIDING_DISCUSSION_TAB'] = False settings.DISCUSSION_SETTINGS = { 'MAX_COMMENT_DEPTH': 2, 'COURSE_PUBLISH_TASK_DELAY': 30, }
Add annotation for ALLOW_HIDING_DISCUSSION_TAB feature flag
Add annotation for ALLOW_HIDING_DISCUSSION_TAB feature flag
Python
agpl-3.0
EDUlib/edx-platform,eduNEXT/edx-platform,EDUlib/edx-platform,eduNEXT/edunext-platform,edx/edx-platform,eduNEXT/edx-platform,angelapper/edx-platform,eduNEXT/edx-platform,eduNEXT/edx-platform,arbrandes/edx-platform,arbrandes/edx-platform,eduNEXT/edunext-platform,EDUlib/edx-platform,edx/edx-platform,angelapper/edx-platform,edx/edx-platform,angelapper/edx-platform,eduNEXT/edunext-platform,arbrandes/edx-platform,edx/edx-platform,EDUlib/edx-platform,angelapper/edx-platform,arbrandes/edx-platform,eduNEXT/edunext-platform
python
## Code Before: """Common environment variables unique to the discussion plugin.""" def plugin_settings(settings): """Settings for the discussions plugin. """ settings.FEATURES['ALLOW_HIDING_DISCUSSION_TAB'] = False settings.DISCUSSION_SETTINGS = { 'MAX_COMMENT_DEPTH': 2, 'COURSE_PUBLISH_TASK_DELAY': 30, } ## Instruction: Add annotation for ALLOW_HIDING_DISCUSSION_TAB feature flag ## Code After: """Common environment variables unique to the discussion plugin.""" def plugin_settings(settings): """Settings for the discussions plugin. """ # .. toggle_name: ALLOW_HIDING_DISCUSSION_TAB # .. toggle_implementation: DjangoSetting # .. toggle_default: False # .. toggle_description: If True, it adds an option to show/hide the discussions tab. # .. toggle_use_cases: open_edx # .. toggle_creation_date: 2015-06-15 # .. toggle_target_removal_date: None # .. toggle_warnings: None # .. toggle_tickets: https://github.com/edx/edx-platform/pull/8474 settings.FEATURES['ALLOW_HIDING_DISCUSSION_TAB'] = False settings.DISCUSSION_SETTINGS = { 'MAX_COMMENT_DEPTH': 2, 'COURSE_PUBLISH_TASK_DELAY': 30, }
# ... existing code ... def plugin_settings(settings): """Settings for the discussions plugin. """ # .. toggle_name: ALLOW_HIDING_DISCUSSION_TAB # .. toggle_implementation: DjangoSetting # .. toggle_default: False # .. toggle_description: If True, it adds an option to show/hide the discussions tab. # .. toggle_use_cases: open_edx # .. toggle_creation_date: 2015-06-15 # .. toggle_target_removal_date: None # .. toggle_warnings: None # .. toggle_tickets: https://github.com/edx/edx-platform/pull/8474 settings.FEATURES['ALLOW_HIDING_DISCUSSION_TAB'] = False settings.DISCUSSION_SETTINGS = { 'MAX_COMMENT_DEPTH': 2, # ... rest of the code ...
07b0b608a948e1058aeb40fdfbf5a0425933562d
mcavatar/__init__.py
mcavatar/__init__.py
from redis import Redis from flask import Flask, g app = Flask(__name__) app.config.from_pyfile('config.py') _redis = Redis( host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT'], db=app.config['REDIS_DB'] ) from mcavatar.views.public import public from mcavatar.views.img import img app.register_blueprint(public) app.register_blueprint(img, subdomain='i') @app.before_request def set_db(): g.redis = _redis
from redis import Redis from flask import Flask, g app = Flask(__name__) app.config.from_pyfile('config.py') _redis = Redis( host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT'], db=app.config['REDIS_DB'] ) from mcavatar.views.public import public from mcavatar.views.img import img app.register_blueprint(public) app.register_blueprint(img, subdomain='i') @app.before_request def set_db(): g.redis = _redis @app.teardown_request def incr_requests(ex): g.redis.incr('total_requests')
Increment total_requests key in redis after each request
Increment total_requests key in redis after each request
Python
mit
joealcorn/MCAvatar
python
## Code Before: from redis import Redis from flask import Flask, g app = Flask(__name__) app.config.from_pyfile('config.py') _redis = Redis( host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT'], db=app.config['REDIS_DB'] ) from mcavatar.views.public import public from mcavatar.views.img import img app.register_blueprint(public) app.register_blueprint(img, subdomain='i') @app.before_request def set_db(): g.redis = _redis ## Instruction: Increment total_requests key in redis after each request ## Code After: from redis import Redis from flask import Flask, g app = Flask(__name__) app.config.from_pyfile('config.py') _redis = Redis( host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT'], db=app.config['REDIS_DB'] ) from mcavatar.views.public import public from mcavatar.views.img import img app.register_blueprint(public) app.register_blueprint(img, subdomain='i') @app.before_request def set_db(): g.redis = _redis @app.teardown_request def incr_requests(ex): g.redis.incr('total_requests')
// ... existing code ... @app.before_request def set_db(): g.redis = _redis @app.teardown_request def incr_requests(ex): g.redis.incr('total_requests') // ... rest of the code ...
917cd9330f572bc2ec601a7555122b59507f6429
payments/management/commands/init_plans.py
payments/management/commands/init_plans.py
from django.conf import settings from django.core.management.base import BaseCommand import stripe class Command(BaseCommand): help = "Make sure your Stripe account has the plans" def handle(self, *args, **options): stripe.api_key = settings.STRIPE_SECRET_KEY for plan in settings.PAYMENTS_PLANS: if settings.PAYMENTS_PLANS[plan].get("stripe_plan_id"): stripe.Plan.create( amount=100 * settings.PAYMENTS_PLANS[plan]["price"], interval=settings.PAYMENTS_PLANS[plan]["interval"], name=settings.PAYMENTS_PLANS[plan]["description"], currency="usd", id=settings.PAYMENTS_PLANS[plan].get("stripe_plan_id") ) print "Plan created for %s" % plan
from django.conf import settings from django.core.management.base import BaseCommand import stripe class Command(BaseCommand): help = "Make sure your Stripe account has the plans" def handle(self, *args, **options): stripe.api_key = settings.STRIPE_SECRET_KEY for plan in settings.PAYMENTS_PLANS: if settings.PAYMENTS_PLANS[plan].get("stripe_plan_id"): stripe.Plan.create( amount=100 * settings.PAYMENTS_PLANS[plan]["price"], interval=settings.PAYMENTS_PLANS[plan]["interval"], name=settings.PAYMENTS_PLANS[plan]["name"], currency="usd", id=settings.PAYMENTS_PLANS[plan].get("stripe_plan_id") ) print "Plan created for %s" % plan
Use plan name instead of description
Use plan name instead of description
Python
mit
aibon/django-stripe-payments,crehana/django-stripe-payments,crehana/django-stripe-payments,jamespacileo/django-stripe-payments,alexhayes/django-stripe-payments,ZeevG/django-stripe-payments,jamespacileo/django-stripe-payments,grue/django-stripe-payments,wahuneke/django-stripe-payments,adi-li/django-stripe-payments,alexhayes/django-stripe-payments,wahuneke/django-stripe-payments,jawed123/django-stripe-payments,pinax/django-stripe-payments,jawed123/django-stripe-payments,wahuneke/django-stripe-payments,aibon/django-stripe-payments,boxysean/django-stripe-payments,adi-li/django-stripe-payments,boxysean/django-stripe-payments,ZeevG/django-stripe-payments,grue/django-stripe-payments
python
## Code Before: from django.conf import settings from django.core.management.base import BaseCommand import stripe class Command(BaseCommand): help = "Make sure your Stripe account has the plans" def handle(self, *args, **options): stripe.api_key = settings.STRIPE_SECRET_KEY for plan in settings.PAYMENTS_PLANS: if settings.PAYMENTS_PLANS[plan].get("stripe_plan_id"): stripe.Plan.create( amount=100 * settings.PAYMENTS_PLANS[plan]["price"], interval=settings.PAYMENTS_PLANS[plan]["interval"], name=settings.PAYMENTS_PLANS[plan]["description"], currency="usd", id=settings.PAYMENTS_PLANS[plan].get("stripe_plan_id") ) print "Plan created for %s" % plan ## Instruction: Use plan name instead of description ## Code After: from django.conf import settings from django.core.management.base import BaseCommand import stripe class Command(BaseCommand): help = "Make sure your Stripe account has the plans" def handle(self, *args, **options): stripe.api_key = settings.STRIPE_SECRET_KEY for plan in settings.PAYMENTS_PLANS: if settings.PAYMENTS_PLANS[plan].get("stripe_plan_id"): stripe.Plan.create( amount=100 * settings.PAYMENTS_PLANS[plan]["price"], interval=settings.PAYMENTS_PLANS[plan]["interval"], name=settings.PAYMENTS_PLANS[plan]["name"], currency="usd", id=settings.PAYMENTS_PLANS[plan].get("stripe_plan_id") ) print "Plan created for %s" % plan
... stripe.Plan.create( amount=100 * settings.PAYMENTS_PLANS[plan]["price"], interval=settings.PAYMENTS_PLANS[plan]["interval"], name=settings.PAYMENTS_PLANS[plan]["name"], currency="usd", id=settings.PAYMENTS_PLANS[plan].get("stripe_plan_id") ) ...
aa3a79f3e733e65e354e0c1c63bf3efe0f128fc1
contentcuration/contentcuration/views/json_dump.py
contentcuration/contentcuration/views/json_dump.py
import json from rest_framework.renderers import JSONRenderer """ Format data such that it can be safely loaded by JSON.parse in javascript 1. create a JSON string 2. second, correctly wrap the JSON in quotes for inclusion in JS Ref: https://github.com/learningequality/kolibri/issues/6044 """ def _json_dumps(value): """ json.dumps parameters for dumping unicode into JS """ return json.dumps(value, separators=(",", ":"), ensure_ascii=False) def json_for_parse_from_data(data): return _json_dumps(_json_dumps(data)) def json_for_parse_from_serializer(serializer): return _json_dumps(JSONRenderer().render(serializer.data))
import json from rest_framework.renderers import JSONRenderer """ Format data such that it can be safely loaded by JSON.parse in javascript 1. create a JSON string 2. second, correctly wrap the JSON in quotes for inclusion in JS Ref: https://github.com/learningequality/kolibri/issues/6044 """ def _json_dumps(value): """ json.dumps parameters for dumping unicode into JS """ return json.dumps(value, separators=(",", ":"), ensure_ascii=False) def json_for_parse_from_data(data): return _json_dumps(_json_dumps(data)) def json_for_parse_from_serializer(serializer): return _json_dumps(JSONRenderer().render(serializer.data).decode("utf-8"))
Update json bootstrapping code for Py3.
Update json bootstrapping code for Py3.
Python
mit
DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation
python
## Code Before: import json from rest_framework.renderers import JSONRenderer """ Format data such that it can be safely loaded by JSON.parse in javascript 1. create a JSON string 2. second, correctly wrap the JSON in quotes for inclusion in JS Ref: https://github.com/learningequality/kolibri/issues/6044 """ def _json_dumps(value): """ json.dumps parameters for dumping unicode into JS """ return json.dumps(value, separators=(",", ":"), ensure_ascii=False) def json_for_parse_from_data(data): return _json_dumps(_json_dumps(data)) def json_for_parse_from_serializer(serializer): return _json_dumps(JSONRenderer().render(serializer.data)) ## Instruction: Update json bootstrapping code for Py3. ## Code After: import json from rest_framework.renderers import JSONRenderer """ Format data such that it can be safely loaded by JSON.parse in javascript 1. create a JSON string 2. second, correctly wrap the JSON in quotes for inclusion in JS Ref: https://github.com/learningequality/kolibri/issues/6044 """ def _json_dumps(value): """ json.dumps parameters for dumping unicode into JS """ return json.dumps(value, separators=(",", ":"), ensure_ascii=False) def json_for_parse_from_data(data): return _json_dumps(_json_dumps(data)) def json_for_parse_from_serializer(serializer): return _json_dumps(JSONRenderer().render(serializer.data).decode("utf-8"))
... def json_for_parse_from_serializer(serializer): return _json_dumps(JSONRenderer().render(serializer.data).decode("utf-8")) ...
670eaa5836635d6242bf6d4f0ef8ef07c2e82498
src/main/java/mcjty/xnet/api/keys/SidedPos.java
src/main/java/mcjty/xnet/api/keys/SidedPos.java
package mcjty.xnet.api.keys; import mcjty.lib.varia.BlockPosTools; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import javax.annotation.Nonnull; public class SidedPos { private final BlockPos pos; private final EnumFacing side; /** * A position of a connected block and the side relative * from this block where the connection is. Basically * pos.offset(side) will be the consumer/connector */ public SidedPos(@Nonnull BlockPos pos, @Nonnull EnumFacing side) { this.pos = pos; this.side = side; } @Nonnull public BlockPos getPos() { return pos; } /** * Get the side relative to this position for the connector. */ @Nonnull public EnumFacing getSide() { return side; } @Override public String toString() { return "SidedPos{" + BlockPosTools.toString(pos) + "/" + side.getName() + "}"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SidedPos sidedPos = (SidedPos) o; if (pos != null ? !pos.equals(sidedPos.pos) : sidedPos.pos != null) return false; if (side != sidedPos.side) return false; return true; } @Override public int hashCode() { int result = pos != null ? pos.hashCode() : 0; result = 31 * result + (side != null ? side.hashCode() : 0); return result; } }
package mcjty.xnet.api.keys; import mcjty.lib.varia.BlockPosTools; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import javax.annotation.Nonnull; public class SidedPos { private final BlockPos pos; private final EnumFacing side; /** * A position of a connected block and the side relative * from this block where the connection is. Basically * pos.offset(side) will be the consumer/connector */ public SidedPos(@Nonnull BlockPos pos, @Nonnull EnumFacing side) { this.pos = pos; this.side = side; } @Nonnull public BlockPos getPos() { return pos; } /** * Get the side relative to this position for the connector. */ @Nonnull public EnumFacing getSide() { return side; } @Override public String toString() { return "SidedPos{" + BlockPosTools.toString(pos) + "/" + side.getName() + "}"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SidedPos sidedPos = (SidedPos) o; return side == sidedPos.side && pos.equals(sidedPos.pos); } @Override public int hashCode() { return 31 * pos.hashCode() + side.hashCode(); } }
Simplify equals and hashCode given @NonNull
Simplify equals and hashCode given @NonNull
Java
mit
McJty/XNet
java
## Code Before: package mcjty.xnet.api.keys; import mcjty.lib.varia.BlockPosTools; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import javax.annotation.Nonnull; public class SidedPos { private final BlockPos pos; private final EnumFacing side; /** * A position of a connected block and the side relative * from this block where the connection is. Basically * pos.offset(side) will be the consumer/connector */ public SidedPos(@Nonnull BlockPos pos, @Nonnull EnumFacing side) { this.pos = pos; this.side = side; } @Nonnull public BlockPos getPos() { return pos; } /** * Get the side relative to this position for the connector. */ @Nonnull public EnumFacing getSide() { return side; } @Override public String toString() { return "SidedPos{" + BlockPosTools.toString(pos) + "/" + side.getName() + "}"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SidedPos sidedPos = (SidedPos) o; if (pos != null ? !pos.equals(sidedPos.pos) : sidedPos.pos != null) return false; if (side != sidedPos.side) return false; return true; } @Override public int hashCode() { int result = pos != null ? pos.hashCode() : 0; result = 31 * result + (side != null ? side.hashCode() : 0); return result; } } ## Instruction: Simplify equals and hashCode given @NonNull ## Code After: package mcjty.xnet.api.keys; import mcjty.lib.varia.BlockPosTools; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import javax.annotation.Nonnull; public class SidedPos { private final BlockPos pos; private final EnumFacing side; /** * A position of a connected block and the side relative * from this block where the connection is. Basically * pos.offset(side) will be the consumer/connector */ public SidedPos(@Nonnull BlockPos pos, @Nonnull EnumFacing side) { this.pos = pos; this.side = side; } @Nonnull public BlockPos getPos() { return pos; } /** * Get the side relative to this position for the connector. */ @Nonnull public EnumFacing getSide() { return side; } @Override public String toString() { return "SidedPos{" + BlockPosTools.toString(pos) + "/" + side.getName() + "}"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SidedPos sidedPos = (SidedPos) o; return side == sidedPos.side && pos.equals(sidedPos.pos); } @Override public int hashCode() { return 31 * pos.hashCode() + side.hashCode(); } }
... SidedPos sidedPos = (SidedPos) o; return side == sidedPos.side && pos.equals(sidedPos.pos); } @Override public int hashCode() { return 31 * pos.hashCode() + side.hashCode(); } } ...
663d0674ebdfd2f4ea5483479890e3a762d57755
l10n_ar_aeroo_sale/__openerp__.py
l10n_ar_aeroo_sale/__openerp__.py
{ 'name': 'Argentinian Like Sale Order Aeroo Report', 'version': '1.0', 'category': 'Localization/Argentina', 'sequence': 14, 'summary': '', 'description': """ Argentinian Like Sale Order / Quotation Aeroo Report ==================================================== """, 'author': 'Ingenieria ADHOC', 'website': 'www.ingadhoc.com', 'images': [ ], 'depends': [ 'report_extended_sale', 'l10n_ar_aeroo_base', 'portal_sale', ], 'data': [ 'report_configuration_defaults_data.xml', 'sale_order_report.xml', 'sale_order_template.xml', ], 'demo': [ ], 'test': [ ], 'installable': True, 'auto_install': False, 'application': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
{ 'name': 'Argentinian Like Sale Order Aeroo Report', 'version': '1.0', 'category': 'Localization/Argentina', 'sequence': 14, 'summary': '', 'description': """ Argentinian Like Sale Order / Quotation Aeroo Report ==================================================== """, 'author': 'Ingenieria ADHOC', 'website': 'www.ingadhoc.com', 'images': [ ], 'depends': [ 'report_extended_sale', 'l10n_ar_aeroo_base', 'l10n_ar_aeroo_invoice', #esta dependencia es porque actualizamos algo que crea portal_sale con un valor de las invoice 'portal_sale', ], 'data': [ 'report_configuration_defaults_data.xml', 'sale_order_report.xml', 'sale_order_template.xml', ], 'demo': [ ], 'test': [ ], 'installable': True, 'auto_install': False, 'application': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
FIX dependency on aeroo rpoert
FIX dependency on aeroo rpoert
Python
agpl-3.0
bmya/odoo-argentina,ingadhoc/odoo-argentina,jobiols/odoo-argentina,bmya/odoo-argentina,adhoc-dev/odoo-argentina,adrianpaesani/odoo-argentina,jobiols/odoo-argentina,adrianpaesani/odoo-argentina,adhoc-dev/odoo-argentina
python
## Code Before: { 'name': 'Argentinian Like Sale Order Aeroo Report', 'version': '1.0', 'category': 'Localization/Argentina', 'sequence': 14, 'summary': '', 'description': """ Argentinian Like Sale Order / Quotation Aeroo Report ==================================================== """, 'author': 'Ingenieria ADHOC', 'website': 'www.ingadhoc.com', 'images': [ ], 'depends': [ 'report_extended_sale', 'l10n_ar_aeroo_base', 'portal_sale', ], 'data': [ 'report_configuration_defaults_data.xml', 'sale_order_report.xml', 'sale_order_template.xml', ], 'demo': [ ], 'test': [ ], 'installable': True, 'auto_install': False, 'application': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: ## Instruction: FIX dependency on aeroo rpoert ## Code After: { 'name': 'Argentinian Like Sale Order Aeroo Report', 'version': '1.0', 'category': 'Localization/Argentina', 'sequence': 14, 'summary': '', 'description': """ Argentinian Like Sale Order / Quotation Aeroo Report ==================================================== """, 'author': 'Ingenieria ADHOC', 'website': 'www.ingadhoc.com', 'images': [ ], 'depends': [ 'report_extended_sale', 'l10n_ar_aeroo_base', 'l10n_ar_aeroo_invoice', #esta dependencia es porque actualizamos algo que crea portal_sale con un valor de las invoice 'portal_sale', ], 'data': [ 'report_configuration_defaults_data.xml', 'sale_order_report.xml', 'sale_order_template.xml', ], 'demo': [ ], 'test': [ ], 'installable': True, 'auto_install': False, 'application': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# ... existing code ... 'depends': [ 'report_extended_sale', 'l10n_ar_aeroo_base', 'l10n_ar_aeroo_invoice', #esta dependencia es porque actualizamos algo que crea portal_sale con un valor de las invoice 'portal_sale', ], 'data': [ # ... rest of the code ...
0cb807470ee56207251f36ad78d35c48f6e9361b
example_project/urls.py
example_project/urls.py
from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^selectable/', include('selectable.urls')), url(r'', include('timepiece.urls')), # authentication views url(r'^accounts/login/$', 'django.contrib.auth.views.login', name='auth_login'), url(r'^accounts/logout/$', 'django.contrib.auth.views.logout_then_login', name='auth_logout'), url(r'^accounts/password-change/$', 'django.contrib.auth.views.password_change', name='change_password'), url(r'^accounts/password-change/done/$', 'django.contrib.auth.views.password_change_done'), url(r'^accounts/password-reset/$', 'django.contrib.auth.views.password_reset', name='reset_password'), url(r'^accounts/password-reset/done/$', 'django.contrib.auth.views.password_reset_done'), url(r'^accounts/reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'django.contrib.auth.views.password_reset_confirm'), url(r'^accounts/reset/done/$', 'django.contrib.auth.views.password_reset_complete'), ]
from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() # For Django 1.6 urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^selectable/', include('selectable.urls')), url(r'', include('timepiece.urls')), # authentication views url(r'^accounts/login/$', 'django.contrib.auth.views.login', name='auth_login'), url(r'^accounts/logout/$', 'django.contrib.auth.views.logout_then_login', name='auth_logout'), url(r'^accounts/password-change/$', 'django.contrib.auth.views.password_change', name='change_password'), url(r'^accounts/password-change/done/$', 'django.contrib.auth.views.password_change_done'), url(r'^accounts/password-reset/$', 'django.contrib.auth.views.password_reset', name='reset_password'), url(r'^accounts/password-reset/done/$', 'django.contrib.auth.views.password_reset_done'), url(r'^accounts/reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'django.contrib.auth.views.password_reset_confirm'), url(r'^accounts/reset/done/$', 'django.contrib.auth.views.password_reset_complete'), ]
Update Python/Django: Restore admin.autodiscover() for Django 1.6 compatibility
Update Python/Django: Restore admin.autodiscover() for Django 1.6 compatibility
Python
mit
BocuStudio/django-timepiece,caktus/django-timepiece,arbitrahj/django-timepiece,BocuStudio/django-timepiece,caktus/django-timepiece,arbitrahj/django-timepiece,caktus/django-timepiece,arbitrahj/django-timepiece,BocuStudio/django-timepiece
python
## Code Before: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^selectable/', include('selectable.urls')), url(r'', include('timepiece.urls')), # authentication views url(r'^accounts/login/$', 'django.contrib.auth.views.login', name='auth_login'), url(r'^accounts/logout/$', 'django.contrib.auth.views.logout_then_login', name='auth_logout'), url(r'^accounts/password-change/$', 'django.contrib.auth.views.password_change', name='change_password'), url(r'^accounts/password-change/done/$', 'django.contrib.auth.views.password_change_done'), url(r'^accounts/password-reset/$', 'django.contrib.auth.views.password_reset', name='reset_password'), url(r'^accounts/password-reset/done/$', 'django.contrib.auth.views.password_reset_done'), url(r'^accounts/reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'django.contrib.auth.views.password_reset_confirm'), url(r'^accounts/reset/done/$', 'django.contrib.auth.views.password_reset_complete'), ] ## Instruction: Update Python/Django: Restore admin.autodiscover() for Django 1.6 compatibility ## Code After: from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() # For Django 1.6 urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^selectable/', include('selectable.urls')), url(r'', include('timepiece.urls')), # authentication views url(r'^accounts/login/$', 'django.contrib.auth.views.login', name='auth_login'), url(r'^accounts/logout/$', 'django.contrib.auth.views.logout_then_login', name='auth_logout'), url(r'^accounts/password-change/$', 'django.contrib.auth.views.password_change', name='change_password'), url(r'^accounts/password-change/done/$', 'django.contrib.auth.views.password_change_done'), url(r'^accounts/password-reset/$', 'django.contrib.auth.views.password_reset', name='reset_password'), url(r'^accounts/password-reset/done/$', 'django.contrib.auth.views.password_reset_done'), url(r'^accounts/reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'django.contrib.auth.views.password_reset_confirm'), url(r'^accounts/reset/done/$', 'django.contrib.auth.views.password_reset_complete'), ]
// ... existing code ... from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() # For Django 1.6 urlpatterns = [ // ... rest of the code ...
3bd116a301ce8de9d3ea1b0dd4c0a969c278455a
wsgi.py
wsgi.py
from shale import app if __name__ == '__main__': app.run( host='127.0.0.1', )
from shale import app if __name__ == '__main__': app.run()
Revert "bind flask to 127.0.0.1"
Revert "bind flask to 127.0.0.1" This reverts commit 097b126e511d3d7bf5f431cc6df552843fad4477. I guess I was way wrong about that.
Python
mit
mhluongo/shale,mhluongo/shale,cardforcoin/shale,cardforcoin/shale
python
## Code Before: from shale import app if __name__ == '__main__': app.run( host='127.0.0.1', ) ## Instruction: Revert "bind flask to 127.0.0.1" This reverts commit 097b126e511d3d7bf5f431cc6df552843fad4477. I guess I was way wrong about that. ## Code After: from shale import app if __name__ == '__main__': app.run()
# ... existing code ... from shale import app if __name__ == '__main__': app.run() # ... rest of the code ...
4ecd060c9354e09d27eb6a404a0f62d41463ecb5
services/repository-managers/src/main/java/org/sagebionetworks/repo/manager/table/TableUpdateRequestManagerProviderImpl.java
services/repository-managers/src/main/java/org/sagebionetworks/repo/manager/table/TableUpdateRequestManagerProviderImpl.java
package org.sagebionetworks.repo.manager.table; import java.util.HashMap; import java.util.Map; import org.sagebionetworks.repo.model.EntityType; import org.sagebionetworks.util.ValidateArgument; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Simple mapping of entity types to transaction managers. * */ @Service public class TableUpdateRequestManagerProviderImpl implements TableUpdateRequestManagerProvider { private Map<EntityType, TableUpdateRequestManager> managerMap; @Autowired public void configureMapping(TableEntityUpdateRequestManager tableEntityUpdateManager, TableViewUpdateRequestManager tableViewUpdateManager) { managerMap = new HashMap<>(); managerMap.put(EntityType.table, tableEntityUpdateManager); managerMap.put(EntityType.entityview, tableViewUpdateManager); managerMap.put(EntityType.submissionview, tableViewUpdateManager); managerMap.put(EntityType.dataset, tableViewUpdateManager); } @Override public TableUpdateRequestManager getUpdateRequestManagerForType(EntityType type) { ValidateArgument.required(type, "type"); TableUpdateRequestManager manager = managerMap.get(type); if (manager == null){ throw new IllegalArgumentException("Unknown type: "+type); } return manager; } }
package org.sagebionetworks.repo.manager.table; import java.util.HashMap; import java.util.Map; import org.sagebionetworks.repo.model.EntityType; import org.sagebionetworks.util.ValidateArgument; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Simple mapping of entity types to transaction managers. * */ @Service public class TableUpdateRequestManagerProviderImpl implements TableUpdateRequestManagerProvider { private Map<EntityType, TableUpdateRequestManager> managerMap; @Autowired public void configureMapping(TableEntityUpdateRequestManager tableEntityUpdateManager, TableViewUpdateRequestManager tableViewUpdateManager) { managerMap = new HashMap<>(); managerMap.put(EntityType.table, tableEntityUpdateManager); managerMap.put(EntityType.entityview, tableViewUpdateManager); managerMap.put(EntityType.submissionview, tableViewUpdateManager); managerMap.put(EntityType.dataset, tableViewUpdateManager); managerMap.put(EntityType.datasetcollection, tableViewUpdateManager); } @Override public TableUpdateRequestManager getUpdateRequestManagerForType(EntityType type) { ValidateArgument.required(type, "type"); TableUpdateRequestManager manager = managerMap.get(type); if (manager == null){ throw new IllegalArgumentException("Unknown type: "+type); } return manager; } }
Add missing mapping for datasetcollection updates
PLFM-7403: Add missing mapping for datasetcollection updates
Java
apache-2.0
Sage-Bionetworks/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services
java
## Code Before: package org.sagebionetworks.repo.manager.table; import java.util.HashMap; import java.util.Map; import org.sagebionetworks.repo.model.EntityType; import org.sagebionetworks.util.ValidateArgument; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Simple mapping of entity types to transaction managers. * */ @Service public class TableUpdateRequestManagerProviderImpl implements TableUpdateRequestManagerProvider { private Map<EntityType, TableUpdateRequestManager> managerMap; @Autowired public void configureMapping(TableEntityUpdateRequestManager tableEntityUpdateManager, TableViewUpdateRequestManager tableViewUpdateManager) { managerMap = new HashMap<>(); managerMap.put(EntityType.table, tableEntityUpdateManager); managerMap.put(EntityType.entityview, tableViewUpdateManager); managerMap.put(EntityType.submissionview, tableViewUpdateManager); managerMap.put(EntityType.dataset, tableViewUpdateManager); } @Override public TableUpdateRequestManager getUpdateRequestManagerForType(EntityType type) { ValidateArgument.required(type, "type"); TableUpdateRequestManager manager = managerMap.get(type); if (manager == null){ throw new IllegalArgumentException("Unknown type: "+type); } return manager; } } ## Instruction: PLFM-7403: Add missing mapping for datasetcollection updates ## Code After: package org.sagebionetworks.repo.manager.table; import java.util.HashMap; import java.util.Map; import org.sagebionetworks.repo.model.EntityType; import org.sagebionetworks.util.ValidateArgument; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Simple mapping of entity types to transaction managers. * */ @Service public class TableUpdateRequestManagerProviderImpl implements TableUpdateRequestManagerProvider { private Map<EntityType, TableUpdateRequestManager> managerMap; @Autowired public void configureMapping(TableEntityUpdateRequestManager tableEntityUpdateManager, TableViewUpdateRequestManager tableViewUpdateManager) { managerMap = new HashMap<>(); managerMap.put(EntityType.table, tableEntityUpdateManager); managerMap.put(EntityType.entityview, tableViewUpdateManager); managerMap.put(EntityType.submissionview, tableViewUpdateManager); managerMap.put(EntityType.dataset, tableViewUpdateManager); managerMap.put(EntityType.datasetcollection, tableViewUpdateManager); } @Override public TableUpdateRequestManager getUpdateRequestManagerForType(EntityType type) { ValidateArgument.required(type, "type"); TableUpdateRequestManager manager = managerMap.get(type); if (manager == null){ throw new IllegalArgumentException("Unknown type: "+type); } return manager; } }
// ... existing code ... managerMap.put(EntityType.entityview, tableViewUpdateManager); managerMap.put(EntityType.submissionview, tableViewUpdateManager); managerMap.put(EntityType.dataset, tableViewUpdateManager); managerMap.put(EntityType.datasetcollection, tableViewUpdateManager); } @Override // ... rest of the code ...
21144972d185d3dfd47cd9641901ba8d34921e84
src/lib/eina_main.c
src/lib/eina_main.c
/* EINA - EFL data type library * Copyright (C) 2008 Cedric Bail * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; * if not, see <http://www.gnu.org/licenses/>. */ #include "Eina.h" EAPI int eina_init(void) { int r; r = eina_error_init(); r += eina_hash_init(); r += eina_stringshare_init(); r += eina_list_init(); r += eina_array_init(); return r; } EAPI int eina_shutdown(void) { int r; eina_array_shutdown(); eina_list_shutdown(); r = eina_stringshare_shutdown(); r += eina_hash_shutdown(); r += eina_error_shutdown(); return r; }
/* EINA - EFL data type library * Copyright (C) 2008 Cedric Bail * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; * if not, see <http://www.gnu.org/licenses/>. */ #include "eina_error.h" #include "eina_hash.h" #include "eina_stringshare.h" #include "eina_list.h" #include "eina_array.h" EAPI int eina_init(void) { int r; r = eina_error_init(); r += eina_hash_init(); r += eina_stringshare_init(); r += eina_list_init(); r += eina_array_init(); return r; } EAPI int eina_shutdown(void) { int r; eina_array_shutdown(); eina_list_shutdown(); r = eina_stringshare_shutdown(); r += eina_hash_shutdown(); r += eina_error_shutdown(); return r; }
Remove warning and only include needed stuff.
Remove warning and only include needed stuff. git-svn-id: b99a075ee42e317ef7d0e499fd315684e5f6d838@35456 7cbeb6ba-43b4-40fd-8cce-4c39aea84d33
C
lgpl-2.1
OpenInkpot-archive/iplinux-eina,jordemort/eina,OpenInkpot-archive/iplinux-eina,jordemort/eina,OpenInkpot-archive/iplinux-eina,jordemort/eina
c
## Code Before: /* EINA - EFL data type library * Copyright (C) 2008 Cedric Bail * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; * if not, see <http://www.gnu.org/licenses/>. */ #include "Eina.h" EAPI int eina_init(void) { int r; r = eina_error_init(); r += eina_hash_init(); r += eina_stringshare_init(); r += eina_list_init(); r += eina_array_init(); return r; } EAPI int eina_shutdown(void) { int r; eina_array_shutdown(); eina_list_shutdown(); r = eina_stringshare_shutdown(); r += eina_hash_shutdown(); r += eina_error_shutdown(); return r; } ## Instruction: Remove warning and only include needed stuff. git-svn-id: b99a075ee42e317ef7d0e499fd315684e5f6d838@35456 7cbeb6ba-43b4-40fd-8cce-4c39aea84d33 ## Code After: /* EINA - EFL data type library * Copyright (C) 2008 Cedric Bail * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; * if not, see <http://www.gnu.org/licenses/>. */ #include "eina_error.h" #include "eina_hash.h" #include "eina_stringshare.h" #include "eina_list.h" #include "eina_array.h" EAPI int eina_init(void) { int r; r = eina_error_init(); r += eina_hash_init(); r += eina_stringshare_init(); r += eina_list_init(); r += eina_array_init(); return r; } EAPI int eina_shutdown(void) { int r; eina_array_shutdown(); eina_list_shutdown(); r = eina_stringshare_shutdown(); r += eina_hash_shutdown(); r += eina_error_shutdown(); return r; }
... * if not, see <http://www.gnu.org/licenses/>. */ #include "eina_error.h" #include "eina_hash.h" #include "eina_stringshare.h" #include "eina_list.h" #include "eina_array.h" EAPI int eina_init(void) ...
b07ec29109a2ca1603d3a4c199132f4c510ef763
third_party/lua-5.2.3/src/floating_temple.c
third_party/lua-5.2.3/src/floating_temple.c
/* ** Hook functions for integration with the Floating Temple distributed ** interpreter */ #include <stddef.h> #define floating_temple_c #define LUA_CORE #include "lua.h" #include "floating_temple.h" #include "lobject.h" #include "luaconf.h" static int ft_defaultnewstringhook (lua_State *L, StkId obj, const char *str, size_t len) { return 0; } static int ft_defaultnewtablehook (lua_State *L, StkId obj, int b, int c) { return 0; } #define FT_DEFINE_HOOK_FUNC(install_func, hook_type, hook_var, \ default_hook_func) \ LUAI_DDEF hook_type hook_var = &default_hook_func; \ \ LUA_API hook_type install_func (hook_type hook) { \ hook_type old_hook = hook_var; \ hook_var = hook; \ return old_hook; \ } FT_DEFINE_HOOK_FUNC(ft_installnewstringhook, ft_NewStringHook, ft_newstringhook, ft_defaultnewstringhook) FT_DEFINE_HOOK_FUNC(ft_installnewtablehook, ft_NewTableHook, ft_newtablehook, ft_defaultnewtablehook) #undef FT_DEFINE_HOOK_FUNC
/* ** Hook functions for integration with the Floating Temple distributed ** interpreter */ #include <stddef.h> #define floating_temple_c #define LUA_CORE #include "lua.h" #include "floating_temple.h" #include "lobject.h" #include "luaconf.h" #define FT_DEFINE_HOOK_FUNC(install_func, hook_type, hook_var, hook_params, \ default_hook_func) \ static int default_hook_func hook_params { \ return 0; \ } \ \ LUAI_DDEF hook_type hook_var = &default_hook_func; \ \ LUA_API hook_type install_func (hook_type hook) { \ hook_type old_hook = hook_var; \ hook_var = hook; \ return old_hook; \ } FT_DEFINE_HOOK_FUNC(ft_installnewstringhook, ft_NewStringHook, ft_newstringhook, (lua_State *L, StkId obj, const char *str, size_t len), ft_defaultnewstringhook) FT_DEFINE_HOOK_FUNC(ft_installnewtablehook, ft_NewTableHook, ft_newtablehook, (lua_State *L, StkId obj, int b, int c), ft_defaultnewtablehook) #undef FT_DEFINE_HOOK_FUNC
Add the definition of the default hook function to the FT_DEFINE_HOOK_FUNCTION macro.
Add the definition of the default hook function to the FT_DEFINE_HOOK_FUNCTION macro.
C
apache-2.0
snyderek/floating_temple,snyderek/floating_temple,snyderek/floating_temple
c
## Code Before: /* ** Hook functions for integration with the Floating Temple distributed ** interpreter */ #include <stddef.h> #define floating_temple_c #define LUA_CORE #include "lua.h" #include "floating_temple.h" #include "lobject.h" #include "luaconf.h" static int ft_defaultnewstringhook (lua_State *L, StkId obj, const char *str, size_t len) { return 0; } static int ft_defaultnewtablehook (lua_State *L, StkId obj, int b, int c) { return 0; } #define FT_DEFINE_HOOK_FUNC(install_func, hook_type, hook_var, \ default_hook_func) \ LUAI_DDEF hook_type hook_var = &default_hook_func; \ \ LUA_API hook_type install_func (hook_type hook) { \ hook_type old_hook = hook_var; \ hook_var = hook; \ return old_hook; \ } FT_DEFINE_HOOK_FUNC(ft_installnewstringhook, ft_NewStringHook, ft_newstringhook, ft_defaultnewstringhook) FT_DEFINE_HOOK_FUNC(ft_installnewtablehook, ft_NewTableHook, ft_newtablehook, ft_defaultnewtablehook) #undef FT_DEFINE_HOOK_FUNC ## Instruction: Add the definition of the default hook function to the FT_DEFINE_HOOK_FUNCTION macro. ## Code After: /* ** Hook functions for integration with the Floating Temple distributed ** interpreter */ #include <stddef.h> #define floating_temple_c #define LUA_CORE #include "lua.h" #include "floating_temple.h" #include "lobject.h" #include "luaconf.h" #define FT_DEFINE_HOOK_FUNC(install_func, hook_type, hook_var, hook_params, \ default_hook_func) \ static int default_hook_func hook_params { \ return 0; \ } \ \ LUAI_DDEF hook_type hook_var = &default_hook_func; \ \ LUA_API hook_type install_func (hook_type hook) { \ hook_type old_hook = hook_var; \ hook_var = hook; \ return old_hook; \ } FT_DEFINE_HOOK_FUNC(ft_installnewstringhook, ft_NewStringHook, ft_newstringhook, (lua_State *L, StkId obj, const char *str, size_t len), ft_defaultnewstringhook) FT_DEFINE_HOOK_FUNC(ft_installnewtablehook, ft_NewTableHook, ft_newtablehook, (lua_State *L, StkId obj, int b, int c), ft_defaultnewtablehook) #undef FT_DEFINE_HOOK_FUNC
// ... existing code ... #include "luaconf.h" #define FT_DEFINE_HOOK_FUNC(install_func, hook_type, hook_var, hook_params, \ default_hook_func) \ static int default_hook_func hook_params { \ return 0; \ } \ \ LUAI_DDEF hook_type hook_var = &default_hook_func; \ \ LUA_API hook_type install_func (hook_type hook) { \ // ... modified code ... FT_DEFINE_HOOK_FUNC(ft_installnewstringhook, ft_NewStringHook, ft_newstringhook, (lua_State *L, StkId obj, const char *str, size_t len), ft_defaultnewstringhook) FT_DEFINE_HOOK_FUNC(ft_installnewtablehook, ft_NewTableHook, ft_newtablehook, (lua_State *L, StkId obj, int b, int c), ft_defaultnewtablehook) // ... rest of the code ...
6bfb23294c2cc445479f4c8098b8e62647cf01bd
test/test_notification_integration.py
test/test_notification_integration.py
import os import select import groundstation.fs_watcher as fs_watcher from groundstation.peer_socket import PeerSocket from integration_fixture import StationIntegrationFixture, \ TestListener, \ TestClient class StationFSWatcherIntegration(StationIntegrationFixture): def test_notifies_peer(self): read_sockets = [] write_sockets = [] def tick(): return select.select(read_sockets, write_sockets, [], 1) addr = os.path.join(self.dir, "listener") listener = TestListener(addr) client = TestClient(addr) peer = listener.accept(PeerSocket) watcher = fs_watcher.FSWatcher(self.stations[0].store.object_root) read_sockets.append(client) read_sockets.append(watcher) self.stations[0].write("trolololol") (sread, _, _) = tick() self.assertIn(watcher, sread) obj_name = watcher.read() client.notify_new_object(self.stations[0], obj_name) client.send() peer.recv() data = peer.packet_queue.pop() gizmo = self.stations[1].gizmo_factory.hydrate(data, peer) assert gizmo is not None, "gizmo_factory returned None" gizmo.process() watcher.kill()
import os import select import groundstation.fs_watcher as fs_watcher from groundstation.peer_socket import PeerSocket from groundstation.utils import path2id from integration_fixture import StationIntegrationFixture, \ TestListener, \ TestClient class StationFSWatcherIntegration(StationIntegrationFixture): def test_notifies_peer(self): read_sockets = [] write_sockets = [] def tick(): return select.select(read_sockets, write_sockets, [], 1) addr = os.path.join(self.dir, "listener") listener = TestListener(addr) client = TestClient(addr) peer = listener.accept(PeerSocket) watcher = fs_watcher.FSWatcher(self.stations[0].store.object_root) read_sockets.append(client) read_sockets.append(watcher) self.stations[0].write("trolololol") (sread, _, _) = tick() self.assertIn(watcher, sread) obj_name = path2id(watcher.read()) client.notify_new_object(self.stations[0], obj_name) client.send() peer.recv() data = peer.packet_queue.pop() gizmo = self.stations[1].gizmo_factory.hydrate(data, peer) assert gizmo is not None, "gizmo_factory returned None" gizmo.process() peer.send() client.recv() data = client.packet_queue.pop() gizmo = self.stations[0].gizmo_factory.hydrate(data, peer) assert gizmo is not None, "gizmo_factory returned None" self.assertEqual(gizmo.verb, "FETCHOBJECT") self.assertEqual(gizmo.payload, obj_name) gizmo.process() watcher.kill()
Validate that we can translate a NEWOBJECT into a FETCHOBJECT
Validate that we can translate a NEWOBJECT into a FETCHOBJECT
Python
mit
richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation
python
## Code Before: import os import select import groundstation.fs_watcher as fs_watcher from groundstation.peer_socket import PeerSocket from integration_fixture import StationIntegrationFixture, \ TestListener, \ TestClient class StationFSWatcherIntegration(StationIntegrationFixture): def test_notifies_peer(self): read_sockets = [] write_sockets = [] def tick(): return select.select(read_sockets, write_sockets, [], 1) addr = os.path.join(self.dir, "listener") listener = TestListener(addr) client = TestClient(addr) peer = listener.accept(PeerSocket) watcher = fs_watcher.FSWatcher(self.stations[0].store.object_root) read_sockets.append(client) read_sockets.append(watcher) self.stations[0].write("trolololol") (sread, _, _) = tick() self.assertIn(watcher, sread) obj_name = watcher.read() client.notify_new_object(self.stations[0], obj_name) client.send() peer.recv() data = peer.packet_queue.pop() gizmo = self.stations[1].gizmo_factory.hydrate(data, peer) assert gizmo is not None, "gizmo_factory returned None" gizmo.process() watcher.kill() ## Instruction: Validate that we can translate a NEWOBJECT into a FETCHOBJECT ## Code After: import os import select import groundstation.fs_watcher as fs_watcher from groundstation.peer_socket import PeerSocket from groundstation.utils import path2id from integration_fixture import StationIntegrationFixture, \ TestListener, \ TestClient class StationFSWatcherIntegration(StationIntegrationFixture): def test_notifies_peer(self): read_sockets = [] write_sockets = [] def tick(): return select.select(read_sockets, write_sockets, [], 1) addr = os.path.join(self.dir, "listener") listener = TestListener(addr) client = TestClient(addr) peer = listener.accept(PeerSocket) watcher = fs_watcher.FSWatcher(self.stations[0].store.object_root) read_sockets.append(client) read_sockets.append(watcher) self.stations[0].write("trolololol") (sread, _, _) = tick() self.assertIn(watcher, sread) obj_name = path2id(watcher.read()) client.notify_new_object(self.stations[0], obj_name) client.send() peer.recv() data = peer.packet_queue.pop() gizmo = self.stations[1].gizmo_factory.hydrate(data, peer) assert gizmo is not None, "gizmo_factory returned None" gizmo.process() peer.send() client.recv() data = client.packet_queue.pop() gizmo = self.stations[0].gizmo_factory.hydrate(data, peer) assert gizmo is not None, "gizmo_factory returned None" self.assertEqual(gizmo.verb, "FETCHOBJECT") self.assertEqual(gizmo.payload, obj_name) gizmo.process() watcher.kill()
... import groundstation.fs_watcher as fs_watcher from groundstation.peer_socket import PeerSocket from groundstation.utils import path2id from integration_fixture import StationIntegrationFixture, \ TestListener, \ ... (sread, _, _) = tick() self.assertIn(watcher, sread) obj_name = path2id(watcher.read()) client.notify_new_object(self.stations[0], obj_name) client.send() ... gizmo = self.stations[1].gizmo_factory.hydrate(data, peer) assert gizmo is not None, "gizmo_factory returned None" gizmo.process() peer.send() client.recv() data = client.packet_queue.pop() gizmo = self.stations[0].gizmo_factory.hydrate(data, peer) assert gizmo is not None, "gizmo_factory returned None" self.assertEqual(gizmo.verb, "FETCHOBJECT") self.assertEqual(gizmo.payload, obj_name) gizmo.process() watcher.kill() ...
e5a056deffa31ef107a085fdf01ac89de50c1390
setup.py
setup.py
from setuptools import setup setup(name='xml_models2', version='0.7.0', description='XML backed models queried from external REST apis', author='Geoff Ford and Chris Tarttelin and Cam McHugh', author_email='[email protected]', url='http://github.com/alephnullplex/xml_models', packages=['xml_models'], install_requires=['lxml', 'python-dateutil', 'pytz', 'future', 'requests'], tests_require=['mock', 'nose', 'coverage'], test_suite="nose.collector" )
from setuptools import setup try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except(IOError, ImportError): long_description = open('README.md').read() setup( name='xml_models2', version='0.7.0', description='XML backed models queried from external REST apis', long_description=long_description, author='Geoff Ford and Chris Tarttelin and Cam McHugh', author_email='[email protected]', url='http://github.com/alephnullplex/xml_models', packages=['xml_models'], install_requires=['lxml', 'python-dateutil', 'pytz', 'future', 'requests'], tests_require=['mock', 'nose', 'coverage'], test_suite="nose.collector" )
Convert MD to reST for pypi
Convert MD to reST for pypi
Python
bsd-2-clause
iamwucheng/xml_models2,alephnullplex/xml_models2
python
## Code Before: from setuptools import setup setup(name='xml_models2', version='0.7.0', description='XML backed models queried from external REST apis', author='Geoff Ford and Chris Tarttelin and Cam McHugh', author_email='[email protected]', url='http://github.com/alephnullplex/xml_models', packages=['xml_models'], install_requires=['lxml', 'python-dateutil', 'pytz', 'future', 'requests'], tests_require=['mock', 'nose', 'coverage'], test_suite="nose.collector" ) ## Instruction: Convert MD to reST for pypi ## Code After: from setuptools import setup try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except(IOError, ImportError): long_description = open('README.md').read() setup( name='xml_models2', version='0.7.0', description='XML backed models queried from external REST apis', long_description=long_description, author='Geoff Ford and Chris Tarttelin and Cam McHugh', author_email='[email protected]', url='http://github.com/alephnullplex/xml_models', packages=['xml_models'], install_requires=['lxml', 'python-dateutil', 'pytz', 'future', 'requests'], tests_require=['mock', 'nose', 'coverage'], test_suite="nose.collector" )
... from setuptools import setup try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except(IOError, ImportError): long_description = open('README.md').read() setup( name='xml_models2', version='0.7.0', description='XML backed models queried from external REST apis', long_description=long_description, author='Geoff Ford and Chris Tarttelin and Cam McHugh', author_email='[email protected]', url='http://github.com/alephnullplex/xml_models', packages=['xml_models'], install_requires=['lxml', 'python-dateutil', 'pytz', 'future', 'requests'], tests_require=['mock', 'nose', 'coverage'], test_suite="nose.collector" ) ...
f9fcdb1670971781c356be0d6d8fa3699459e333
library/src/main/java/com/github/javiersantos/piracychecker/enums/InstallerID.kt
library/src/main/java/com/github/javiersantos/piracychecker/enums/InstallerID.kt
package com.github.javiersantos.piracychecker.enums import java.util.ArrayList import java.util.Arrays enum class InstallerID(private val text: String) { GOOGLE_PLAY("com.android.vending|com.google.android.feedback"), AMAZON_APP_STORE("com.amazon.venezia"), GALAXY_APPS("com.sec.android.app.samsungapps"); /* (non-Javadoc) * @see java.lang.Enum#toString() */ override fun toString(): String { return text } fun toIDs(): List<String> = if (text.contains("|")) { val split = text.split("\\|".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() ArrayList(Arrays.asList(*split)) } else { ArrayList(listOf(text)) } }
package com.github.javiersantos.piracychecker.enums import java.util.ArrayList import java.util.Arrays enum class InstallerID(private val text: String) { GOOGLE_PLAY("com.android.vending|com.google.android.feedback"), AMAZON_APP_STORE("com.amazon.venezia"), GALAXY_APPS("com.sec.android.app.samsungapps"); HUAWEI_APPGALLERY("com.huawei.appmarket"); /* (non-Javadoc) * @see java.lang.Enum#toString() */ override fun toString(): String { return text } fun toIDs(): List<String> = if (text.contains("|")) { val split = text.split("\\|".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() ArrayList(Arrays.asList(*split)) } else { ArrayList(listOf(text)) } }
Add Huawei AppGallery Installer ID enum
Add Huawei AppGallery Installer ID enum Implements #77
Kotlin
apache-2.0
javiersantos/PiracyChecker,javiersantos/PiracyChecker
kotlin
## Code Before: package com.github.javiersantos.piracychecker.enums import java.util.ArrayList import java.util.Arrays enum class InstallerID(private val text: String) { GOOGLE_PLAY("com.android.vending|com.google.android.feedback"), AMAZON_APP_STORE("com.amazon.venezia"), GALAXY_APPS("com.sec.android.app.samsungapps"); /* (non-Javadoc) * @see java.lang.Enum#toString() */ override fun toString(): String { return text } fun toIDs(): List<String> = if (text.contains("|")) { val split = text.split("\\|".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() ArrayList(Arrays.asList(*split)) } else { ArrayList(listOf(text)) } } ## Instruction: Add Huawei AppGallery Installer ID enum Implements #77 ## Code After: package com.github.javiersantos.piracychecker.enums import java.util.ArrayList import java.util.Arrays enum class InstallerID(private val text: String) { GOOGLE_PLAY("com.android.vending|com.google.android.feedback"), AMAZON_APP_STORE("com.amazon.venezia"), GALAXY_APPS("com.sec.android.app.samsungapps"); HUAWEI_APPGALLERY("com.huawei.appmarket"); /* (non-Javadoc) * @see java.lang.Enum#toString() */ override fun toString(): String { return text } fun toIDs(): List<String> = if (text.contains("|")) { val split = text.split("\\|".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() ArrayList(Arrays.asList(*split)) } else { ArrayList(listOf(text)) } }
... GOOGLE_PLAY("com.android.vending|com.google.android.feedback"), AMAZON_APP_STORE("com.amazon.venezia"), GALAXY_APPS("com.sec.android.app.samsungapps"); HUAWEI_APPGALLERY("com.huawei.appmarket"); /* (non-Javadoc) * @see java.lang.Enum#toString() ...
452955ca8b7ba2ef01fc97800e5f350fee3e3a6e
tvnamer/renamer.py
tvnamer/renamer.py
import re import os import pytvdbapi.api as tvdb class Renamer: def __init__(self, api_key): self.tvdb = tvdb.TVDB(api_key) @staticmethod def flat_file_list(directory): directory = os.path.normpath(directory) for dirpath, dirnames, filenames in os.walk(directory): for filename in filenames: full_path = os.path.join(dirpath, filename) # remove directory from the start of the full path full_path = full_path[len(directory)+1:] yield full_path def rename_table(self, directory, input_regex, output_format): input_pattern = re.compile(input_regex) filenames = self.flat_file_list(directory) for filename in filenames: thing = input_pattern.search(filename) if thing is not None: params = thing.groupdict() output_filename = output_format.format(**params) yield filename, output_filename
import re import os import pytvdbapi.api as tvdb class Renamer: def __init__(self, api_key): self.tvdb = tvdb.TVDB(api_key) @staticmethod def flat_file_list(directory): directory = os.path.normpath(directory) for dirpath, dirnames, filenames in os.walk(directory): for filename in filenames: full_path = os.path.join(dirpath, filename) # remove directory from the start of the full path full_path = full_path[len(directory)+1:] yield full_path @staticmethod def normalise_params(params): def normalise(key, value): if key == "show": return str(value) elif key in ["episode", "season"]: return int(value) else: raise ValueError("Unknown parameter: '{}'".format(key)) return {key: normalise(key, value) for key, value in params.items()} def rename_table(self, directory, input_regex, output_format): input_pattern = re.compile(input_regex) filenames = self.flat_file_list(directory) for filename in filenames: thing = input_pattern.search(filename) if thing is not None: params = self.normalise_params(thing.groupdict()) output_filename = output_format.format(**params) yield filename, output_filename
Add normalising params from the regex input
Add normalising params from the regex input
Python
mit
tomleese/tvnamer,thomasleese/tvnamer
python
## Code Before: import re import os import pytvdbapi.api as tvdb class Renamer: def __init__(self, api_key): self.tvdb = tvdb.TVDB(api_key) @staticmethod def flat_file_list(directory): directory = os.path.normpath(directory) for dirpath, dirnames, filenames in os.walk(directory): for filename in filenames: full_path = os.path.join(dirpath, filename) # remove directory from the start of the full path full_path = full_path[len(directory)+1:] yield full_path def rename_table(self, directory, input_regex, output_format): input_pattern = re.compile(input_regex) filenames = self.flat_file_list(directory) for filename in filenames: thing = input_pattern.search(filename) if thing is not None: params = thing.groupdict() output_filename = output_format.format(**params) yield filename, output_filename ## Instruction: Add normalising params from the regex input ## Code After: import re import os import pytvdbapi.api as tvdb class Renamer: def __init__(self, api_key): self.tvdb = tvdb.TVDB(api_key) @staticmethod def flat_file_list(directory): directory = os.path.normpath(directory) for dirpath, dirnames, filenames in os.walk(directory): for filename in filenames: full_path = os.path.join(dirpath, filename) # remove directory from the start of the full path full_path = full_path[len(directory)+1:] yield full_path @staticmethod def normalise_params(params): def normalise(key, value): if key == "show": return str(value) elif key in ["episode", "season"]: return int(value) else: raise ValueError("Unknown parameter: '{}'".format(key)) return {key: normalise(key, value) for key, value in params.items()} def rename_table(self, directory, input_regex, output_format): input_pattern = re.compile(input_regex) filenames = self.flat_file_list(directory) for filename in filenames: thing = input_pattern.search(filename) if thing is not None: params = self.normalise_params(thing.groupdict()) output_filename = output_format.format(**params) yield filename, output_filename
// ... existing code ... full_path = full_path[len(directory)+1:] yield full_path @staticmethod def normalise_params(params): def normalise(key, value): if key == "show": return str(value) elif key in ["episode", "season"]: return int(value) else: raise ValueError("Unknown parameter: '{}'".format(key)) return {key: normalise(key, value) for key, value in params.items()} def rename_table(self, directory, input_regex, output_format): input_pattern = re.compile(input_regex) // ... modified code ... for filename in filenames: thing = input_pattern.search(filename) if thing is not None: params = self.normalise_params(thing.groupdict()) output_filename = output_format.format(**params) yield filename, output_filename // ... rest of the code ...
f5e36391c253a52fe2bd434caf59c0f5c389cc64
tests/base.py
tests/base.py
import unittest import os os.environ['OGN_CONFIG_MODULE'] = 'config/test.py' from ogn_python import db # noqa: E402 class TestBaseDB(unittest.TestCase): @classmethod def setUpClass(cls): db.session.execute('CREATE EXTENSION IF NOT EXISTS postgis;') db.session.commit() db.create_all() def setUp(self): pass def tearDown(self): db.session.execute(""" DELETE FROM aircraft_beacons; DELETE FROM receiver_beacons; DELETE FROM takeoff_landings; DELETE FROM logbook; DELETE FROM receiver_coverages; DELETE FROM device_stats; DELETE FROM receiver_stats; DELETE FROM receivers; DELETE FROM devices; """) if __name__ == '__main__': unittest.main()
import unittest import os os.environ['OGN_CONFIG_MODULE'] = 'config/test.py' from ogn_python import db # noqa: E402 class TestBaseDB(unittest.TestCase): @classmethod def setUpClass(cls): db.drop_all() db.session.execute('CREATE EXTENSION IF NOT EXISTS postgis;') db.session.commit() db.create_all() def setUp(self): pass def tearDown(self): db.session.execute(""" DELETE FROM aircraft_beacons; DELETE FROM receiver_beacons; DELETE FROM takeoff_landings; DELETE FROM logbook; DELETE FROM receiver_coverages; DELETE FROM device_stats; DELETE FROM receiver_stats; DELETE FROM receivers; DELETE FROM devices; """) if __name__ == '__main__': unittest.main()
Drop db before each test
Drop db before each test
Python
agpl-3.0
Meisterschueler/ogn-python,glidernet/ogn-python,glidernet/ogn-python,Meisterschueler/ogn-python,glidernet/ogn-python,glidernet/ogn-python,Meisterschueler/ogn-python,Meisterschueler/ogn-python
python
## Code Before: import unittest import os os.environ['OGN_CONFIG_MODULE'] = 'config/test.py' from ogn_python import db # noqa: E402 class TestBaseDB(unittest.TestCase): @classmethod def setUpClass(cls): db.session.execute('CREATE EXTENSION IF NOT EXISTS postgis;') db.session.commit() db.create_all() def setUp(self): pass def tearDown(self): db.session.execute(""" DELETE FROM aircraft_beacons; DELETE FROM receiver_beacons; DELETE FROM takeoff_landings; DELETE FROM logbook; DELETE FROM receiver_coverages; DELETE FROM device_stats; DELETE FROM receiver_stats; DELETE FROM receivers; DELETE FROM devices; """) if __name__ == '__main__': unittest.main() ## Instruction: Drop db before each test ## Code After: import unittest import os os.environ['OGN_CONFIG_MODULE'] = 'config/test.py' from ogn_python import db # noqa: E402 class TestBaseDB(unittest.TestCase): @classmethod def setUpClass(cls): db.drop_all() db.session.execute('CREATE EXTENSION IF NOT EXISTS postgis;') db.session.commit() db.create_all() def setUp(self): pass def tearDown(self): db.session.execute(""" DELETE FROM aircraft_beacons; DELETE FROM receiver_beacons; DELETE FROM takeoff_landings; DELETE FROM logbook; DELETE FROM receiver_coverages; DELETE FROM device_stats; DELETE FROM receiver_stats; DELETE FROM receivers; DELETE FROM devices; """) if __name__ == '__main__': unittest.main()
... class TestBaseDB(unittest.TestCase): @classmethod def setUpClass(cls): db.drop_all() db.session.execute('CREATE EXTENSION IF NOT EXISTS postgis;') db.session.commit() db.create_all() ...
4d4805a99d61365bff3c379d149561617537d4cd
plugin/src/main/groovy/com/btkelly/gnag/utils/StringUtils.java
plugin/src/main/groovy/com/btkelly/gnag/utils/StringUtils.java
/** * Copyright 2016 Bryan Kelly * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.btkelly.gnag.utils; import org.jetbrains.annotations.Nullable; public final class StringUtils { /** * Removes leading/trailing whitespace and newlines. */ public static String sanitize(@Nullable final String string) { if (string == null) { return null; } return string .trim() .replaceAll("^\\r|^\\n|\\r$\\n$", ""); } private StringUtils() { // This constructor intentionally left blank. } }
/** * Copyright 2016 Bryan Kelly * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.btkelly.gnag.utils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public final class StringUtils { /** * Removes leading/trailing whitespace and newlines. */ @NotNull public static String sanitize(@Nullable final String string) { if (string == null) { return ""; } return string .trim() .replaceAll("^\\r|^\\n|\\r$\\n$", ""); } private StringUtils() { // This constructor intentionally left blank. } }
Make sanitization method more safe
Make sanitization method more safe
Java
apache-2.0
btkelly/gnag,btkelly/gnag,btkelly/gnag
java
## Code Before: /** * Copyright 2016 Bryan Kelly * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.btkelly.gnag.utils; import org.jetbrains.annotations.Nullable; public final class StringUtils { /** * Removes leading/trailing whitespace and newlines. */ public static String sanitize(@Nullable final String string) { if (string == null) { return null; } return string .trim() .replaceAll("^\\r|^\\n|\\r$\\n$", ""); } private StringUtils() { // This constructor intentionally left blank. } } ## Instruction: Make sanitization method more safe ## Code After: /** * Copyright 2016 Bryan Kelly * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.btkelly.gnag.utils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public final class StringUtils { /** * Removes leading/trailing whitespace and newlines. */ @NotNull public static String sanitize(@Nullable final String string) { if (string == null) { return ""; } return string .trim() .replaceAll("^\\r|^\\n|\\r$\\n$", ""); } private StringUtils() { // This constructor intentionally left blank. } }
# ... existing code ... */ package com.btkelly.gnag.utils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public final class StringUtils { # ... modified code ... /** * Removes leading/trailing whitespace and newlines. */ @NotNull public static String sanitize(@Nullable final String string) { if (string == null) { return ""; } return string # ... rest of the code ...
e1f15a29bb947666740ec250120e3bdf451f0477
pythonwarrior/towers/beginner/level_006.py
pythonwarrior/towers/beginner/level_006.py
level.description("The wall behind you feels a bit further away in this room. And you hear more cries for help.") level.tip("You can walk backward by passing 'backward' as an argument to walk_. Same goes for feel, rescue_ and attack_. Archers have a limited attack distance.") level.clue("Walk backward if you are taking damage from afar and do not have enough health to attack. You may also want to consider walking backward until warrior.feel('backward').is_wall().") level.time_bonus(55) level.ace_score(105) level.size(8, 1) level.stairs(7, 0) level.warrior(2, 0, 'east') level.unit('captive', 0, 0, 'east') level.unit('thick_sludge', 4, 0, 'west') level.unit('archer', 6, 0, 'west') level.unit('archer', 7, 0, 'west')
level.description("The wall behind you feels a bit further away in this room. And you hear more cries for help.") level.tip("You can walk backward by passing 'backward' as an argument to warrior.walk_. Same goes for warrior.feel, warrior.rescue_ and warrior.attack_. Archers have a limited attack distance.") level.clue("Walk backward if you are taking damage from afar and do not have enough health to attack. You may also want to consider walking backward until warrior.feel('backward').is_wall().") level.time_bonus(55) level.ace_score(105) level.size(8, 1) level.stairs(7, 0) level.warrior(2, 0, 'east') level.unit('captive', 0, 0, 'east') level.unit('thick_sludge', 4, 0, 'west') level.unit('archer', 6, 0, 'west') level.unit('archer', 7, 0, 'west')
Update description of the level 06
Update description of the level 06
Python
mit
arbylee/python-warrior
python
## Code Before: level.description("The wall behind you feels a bit further away in this room. And you hear more cries for help.") level.tip("You can walk backward by passing 'backward' as an argument to walk_. Same goes for feel, rescue_ and attack_. Archers have a limited attack distance.") level.clue("Walk backward if you are taking damage from afar and do not have enough health to attack. You may also want to consider walking backward until warrior.feel('backward').is_wall().") level.time_bonus(55) level.ace_score(105) level.size(8, 1) level.stairs(7, 0) level.warrior(2, 0, 'east') level.unit('captive', 0, 0, 'east') level.unit('thick_sludge', 4, 0, 'west') level.unit('archer', 6, 0, 'west') level.unit('archer', 7, 0, 'west') ## Instruction: Update description of the level 06 ## Code After: level.description("The wall behind you feels a bit further away in this room. And you hear more cries for help.") level.tip("You can walk backward by passing 'backward' as an argument to warrior.walk_. Same goes for warrior.feel, warrior.rescue_ and warrior.attack_. Archers have a limited attack distance.") level.clue("Walk backward if you are taking damage from afar and do not have enough health to attack. You may also want to consider walking backward until warrior.feel('backward').is_wall().") level.time_bonus(55) level.ace_score(105) level.size(8, 1) level.stairs(7, 0) level.warrior(2, 0, 'east') level.unit('captive', 0, 0, 'east') level.unit('thick_sludge', 4, 0, 'west') level.unit('archer', 6, 0, 'west') level.unit('archer', 7, 0, 'west')
# ... existing code ... level.description("The wall behind you feels a bit further away in this room. And you hear more cries for help.") level.tip("You can walk backward by passing 'backward' as an argument to warrior.walk_. Same goes for warrior.feel, warrior.rescue_ and warrior.attack_. Archers have a limited attack distance.") level.clue("Walk backward if you are taking damage from afar and do not have enough health to attack. You may also want to consider walking backward until warrior.feel('backward').is_wall().") level.time_bonus(55) # ... rest of the code ...
b21d63d8df7d17e150702c531ef449f409100eff
wot_clan_battles/views_auth.py
wot_clan_battles/views_auth.py
import six from django.http import HttpResponseRedirect from django.shortcuts import reverse from django.conf import settings from openid.consumer import consumer import wargaming wot = wargaming.WoT(settings.WARGAMING_KEY, language='ru', region='ru') def auth_callback(request): oidconsumer = consumer.Consumer(request.session, None) url = 'http://%s%s' % (request.META['HTTP_HOST'], reverse('auth_callback')) result = oidconsumer.complete(request.GET, url) if result.status == consumer.SUCCESS: identifier = result.getDisplayIdentifier() print identifier user_id, username = six.moves.urllib_parse.urlparse(identifier).path.split('/')[2].split('-') request.session['user_id'] = user_id request.session['username'] = username request.session['user_clan_id'] = wot.account.info(account_id=user_id)[str(user_id)]['clan_id'] return HttpResponseRedirect('/') def auth_login(request): oidconsumer = consumer.Consumer(dict(request.session), None) openid_request = oidconsumer.begin(u'http://ru.wargaming.net/id/openid/') trust_root = 'http://%s' % request.META['HTTP_HOST'] return_to = '%s%s' % (trust_root, reverse('auth_callback')) redirect_to = openid_request.redirectURL(trust_root, return_to, immediate=False) return HttpResponseRedirect(redirect_to)
import six from django.http import HttpResponseRedirect from django.shortcuts import reverse from django.conf import settings from openid.consumer import consumer import wargaming wot = wargaming.WoT(settings.WARGAMING_KEY, language='ru', region='ru') def auth_callback(request): oidconsumer = consumer.Consumer(request.session, None) url = 'http://%s%s' % (request.META['HTTP_HOST'], reverse('auth_callback')) result = oidconsumer.complete(request.GET, url) if result.status == consumer.SUCCESS: identifier = result.getDisplayIdentifier() user_id, username = six.moves.urllib_parse.urlparse(identifier).path.split('/')[2].split('-') request.session['user_id'] = user_id request.session['username'] = username request.session['user_clan_id'] = wot.account.info(account_id=user_id)[str(user_id)]['clan_id'] return HttpResponseRedirect('/') def auth_login(request): oidconsumer = consumer.Consumer(dict(request.session), None) openid_request = oidconsumer.begin(u'http://ru.wargaming.net/id/openid/') trust_root = 'http://%s' % request.META['HTTP_HOST'] return_to = '%s%s' % (trust_root, reverse('auth_callback')) redirect_to = openid_request.redirectURL(trust_root, return_to, immediate=False) return HttpResponseRedirect(redirect_to)
Remove debug print from view
Remove debug print from view
Python
mit
monester/wot-battles,monester/wot-battles,monester/wot-battles,monester/wot-battles
python
## Code Before: import six from django.http import HttpResponseRedirect from django.shortcuts import reverse from django.conf import settings from openid.consumer import consumer import wargaming wot = wargaming.WoT(settings.WARGAMING_KEY, language='ru', region='ru') def auth_callback(request): oidconsumer = consumer.Consumer(request.session, None) url = 'http://%s%s' % (request.META['HTTP_HOST'], reverse('auth_callback')) result = oidconsumer.complete(request.GET, url) if result.status == consumer.SUCCESS: identifier = result.getDisplayIdentifier() print identifier user_id, username = six.moves.urllib_parse.urlparse(identifier).path.split('/')[2].split('-') request.session['user_id'] = user_id request.session['username'] = username request.session['user_clan_id'] = wot.account.info(account_id=user_id)[str(user_id)]['clan_id'] return HttpResponseRedirect('/') def auth_login(request): oidconsumer = consumer.Consumer(dict(request.session), None) openid_request = oidconsumer.begin(u'http://ru.wargaming.net/id/openid/') trust_root = 'http://%s' % request.META['HTTP_HOST'] return_to = '%s%s' % (trust_root, reverse('auth_callback')) redirect_to = openid_request.redirectURL(trust_root, return_to, immediate=False) return HttpResponseRedirect(redirect_to) ## Instruction: Remove debug print from view ## Code After: import six from django.http import HttpResponseRedirect from django.shortcuts import reverse from django.conf import settings from openid.consumer import consumer import wargaming wot = wargaming.WoT(settings.WARGAMING_KEY, language='ru', region='ru') def auth_callback(request): oidconsumer = consumer.Consumer(request.session, None) url = 'http://%s%s' % (request.META['HTTP_HOST'], reverse('auth_callback')) result = oidconsumer.complete(request.GET, url) if result.status == consumer.SUCCESS: identifier = result.getDisplayIdentifier() user_id, username = six.moves.urllib_parse.urlparse(identifier).path.split('/')[2].split('-') request.session['user_id'] = user_id request.session['username'] = username request.session['user_clan_id'] = wot.account.info(account_id=user_id)[str(user_id)]['clan_id'] return HttpResponseRedirect('/') def auth_login(request): oidconsumer = consumer.Consumer(dict(request.session), None) openid_request = oidconsumer.begin(u'http://ru.wargaming.net/id/openid/') trust_root = 'http://%s' % request.META['HTTP_HOST'] return_to = '%s%s' % (trust_root, reverse('auth_callback')) redirect_to = openid_request.redirectURL(trust_root, return_to, immediate=False) return HttpResponseRedirect(redirect_to)
... result = oidconsumer.complete(request.GET, url) if result.status == consumer.SUCCESS: identifier = result.getDisplayIdentifier() user_id, username = six.moves.urllib_parse.urlparse(identifier).path.split('/')[2].split('-') request.session['user_id'] = user_id request.session['username'] = username ...
b8478f65643172a3b56adffe452cc625b2aac022
src/main/java/com/techern/minecraft/melonblockdrop/MelonBlockHarvestEventHandler.java
src/main/java/com/techern/minecraft/melonblockdrop/MelonBlockHarvestEventHandler.java
package com.techern.minecraft.melonblockdrop; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; /** * An event handler for when breaking {@link net.minecraft.block.BlockMelon}s * * @since 1.0.0 */ public class MelonBlockHarvestEventHandler { /** * Called when harvesting any block * * @param event The {@link net.minecraftforge.event.world.BlockEvent.HarvestDropsEvent} * * @since 1.0.0 */ @SubscribeEvent public void harvest(BlockEvent.HarvestDropsEvent event) { if (event.state.getBlock().equals(Blocks.melon_block)) { //We're doing a melon block //First reset the drop list event.drops.clear(); //Then add the new drop event.drops.add(new ItemStack(Blocks.melon_block, 1)); } //Do nothing if not } }
package com.techern.minecraft.melonblockdrop; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; /** * An event handler for when breaking {@link net.minecraft.block.BlockMelon}s * * @since 1.0.0 */ public class MelonBlockHarvestEventHandler { /** * Called when harvesting any block * * @param event The {@link net.minecraftforge.event.world.BlockEvent.HarvestDropsEvent} * * @since 1.0.0 */ @SubscribeEvent public void harvest(BlockEvent.HarvestDropsEvent event) { if (event.getState().getBlock().equals(Blocks.melon_block)) { //We're doing a melon block //First reset the drop list event.getDrops().clear(); //Then add the new drop event.getDrops().add(new ItemStack(Blocks.melon_block, 1)); } //Do nothing if not } }
Fix the drop harvest event
Fix the drop harvest event
Java
mit
Techern/Melon-block-drops
java
## Code Before: package com.techern.minecraft.melonblockdrop; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; /** * An event handler for when breaking {@link net.minecraft.block.BlockMelon}s * * @since 1.0.0 */ public class MelonBlockHarvestEventHandler { /** * Called when harvesting any block * * @param event The {@link net.minecraftforge.event.world.BlockEvent.HarvestDropsEvent} * * @since 1.0.0 */ @SubscribeEvent public void harvest(BlockEvent.HarvestDropsEvent event) { if (event.state.getBlock().equals(Blocks.melon_block)) { //We're doing a melon block //First reset the drop list event.drops.clear(); //Then add the new drop event.drops.add(new ItemStack(Blocks.melon_block, 1)); } //Do nothing if not } } ## Instruction: Fix the drop harvest event ## Code After: package com.techern.minecraft.melonblockdrop; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; /** * An event handler for when breaking {@link net.minecraft.block.BlockMelon}s * * @since 1.0.0 */ public class MelonBlockHarvestEventHandler { /** * Called when harvesting any block * * @param event The {@link net.minecraftforge.event.world.BlockEvent.HarvestDropsEvent} * * @since 1.0.0 */ @SubscribeEvent public void harvest(BlockEvent.HarvestDropsEvent event) { if (event.getState().getBlock().equals(Blocks.melon_block)) { //We're doing a melon block //First reset the drop list event.getDrops().clear(); //Then add the new drop event.getDrops().add(new ItemStack(Blocks.melon_block, 1)); } //Do nothing if not } }
# ... existing code ... @SubscribeEvent public void harvest(BlockEvent.HarvestDropsEvent event) { if (event.getState().getBlock().equals(Blocks.melon_block)) { //We're doing a melon block //First reset the drop list event.getDrops().clear(); //Then add the new drop event.getDrops().add(new ItemStack(Blocks.melon_block, 1)); } //Do nothing if not # ... rest of the code ...
3b8282703a468631d3e96242d80cdc3268ed26f1
src/test/java/seedu/doist/testutil/TaskBuilder.java
src/test/java/seedu/doist/testutil/TaskBuilder.java
package seedu.doist.testutil; import java.util.Date; import seedu.doist.commons.exceptions.IllegalValueException; import seedu.doist.model.tag.Tag; import seedu.doist.model.tag.UniqueTagList; import seedu.doist.model.task.Description; import seedu.doist.model.task.Priority; /** * */ public class TaskBuilder { private TestTask task; public TaskBuilder() { this.task = new TestTask(); } /** * Initializes the TaskBuilder with the data of {@code personToCopy}. */ public TaskBuilder(TestTask taskToCopy) { this.task = new TestTask(taskToCopy); } public TaskBuilder withName(String name) throws IllegalValueException { this.task.setName(new Description(name)); return this; } public TaskBuilder withPriority(String priority) throws IllegalValueException { this.task.setPriority(new Priority(priority)); return this; } public TaskBuilder withTags(String ... tags) throws IllegalValueException { task.setTags(new UniqueTagList()); for (String tag: tags) { task.getTags().add(new Tag(tag)); } return this; } public TaskBuilder withDates(Date startDate, Date endDate) throws IllegalValueException { this.task.setStartDate(startDate); this.task.setEndDate(endDate); return this; } public TestTask build() { return this.task; } }
package seedu.doist.testutil; import java.util.Date; import seedu.doist.commons.exceptions.IllegalValueException; import seedu.doist.model.tag.Tag; import seedu.doist.model.tag.UniqueTagList; import seedu.doist.model.task.Description; import seedu.doist.model.task.Priority; /** * */ public class TaskBuilder { private TestTask task; public TaskBuilder() { this.task = new TestTask(); } /** * Initializes the TaskBuilder with the data of {@code personToCopy}. */ public TaskBuilder(TestTask taskToCopy) { this.task = new TestTask(taskToCopy); } public TaskBuilder withName(String name) throws IllegalValueException { this.task.setName(new Description(name)); return this; } public TaskBuilder withPriority(String priority) throws IllegalValueException { this.task.setPriority(new Priority(priority)); return this; } public TaskBuilder withTags(String ... tags) throws IllegalValueException { task.setTags(new UniqueTagList()); for (String tag: tags) { task.getTags().add(new Tag(tag)); } return this; } public TaskBuilder withDates(Date startDate, Date endDate) throws IllegalValueException { this.task.getDates().setStartDate(startDate); this.task.getDates().setEndDate(endDate); return this; } public TestTask build() { return this.task; } }
Change class to use new TaskDate
Change class to use new TaskDate
Java
mit
CS2103JAN2017-W13-B4/main,CS2103JAN2017-W13-B4/main
java
## Code Before: package seedu.doist.testutil; import java.util.Date; import seedu.doist.commons.exceptions.IllegalValueException; import seedu.doist.model.tag.Tag; import seedu.doist.model.tag.UniqueTagList; import seedu.doist.model.task.Description; import seedu.doist.model.task.Priority; /** * */ public class TaskBuilder { private TestTask task; public TaskBuilder() { this.task = new TestTask(); } /** * Initializes the TaskBuilder with the data of {@code personToCopy}. */ public TaskBuilder(TestTask taskToCopy) { this.task = new TestTask(taskToCopy); } public TaskBuilder withName(String name) throws IllegalValueException { this.task.setName(new Description(name)); return this; } public TaskBuilder withPriority(String priority) throws IllegalValueException { this.task.setPriority(new Priority(priority)); return this; } public TaskBuilder withTags(String ... tags) throws IllegalValueException { task.setTags(new UniqueTagList()); for (String tag: tags) { task.getTags().add(new Tag(tag)); } return this; } public TaskBuilder withDates(Date startDate, Date endDate) throws IllegalValueException { this.task.setStartDate(startDate); this.task.setEndDate(endDate); return this; } public TestTask build() { return this.task; } } ## Instruction: Change class to use new TaskDate ## Code After: package seedu.doist.testutil; import java.util.Date; import seedu.doist.commons.exceptions.IllegalValueException; import seedu.doist.model.tag.Tag; import seedu.doist.model.tag.UniqueTagList; import seedu.doist.model.task.Description; import seedu.doist.model.task.Priority; /** * */ public class TaskBuilder { private TestTask task; public TaskBuilder() { this.task = new TestTask(); } /** * Initializes the TaskBuilder with the data of {@code personToCopy}. */ public TaskBuilder(TestTask taskToCopy) { this.task = new TestTask(taskToCopy); } public TaskBuilder withName(String name) throws IllegalValueException { this.task.setName(new Description(name)); return this; } public TaskBuilder withPriority(String priority) throws IllegalValueException { this.task.setPriority(new Priority(priority)); return this; } public TaskBuilder withTags(String ... tags) throws IllegalValueException { task.setTags(new UniqueTagList()); for (String tag: tags) { task.getTags().add(new Tag(tag)); } return this; } public TaskBuilder withDates(Date startDate, Date endDate) throws IllegalValueException { this.task.getDates().setStartDate(startDate); this.task.getDates().setEndDate(endDate); return this; } public TestTask build() { return this.task; } }
# ... existing code ... } public TaskBuilder withDates(Date startDate, Date endDate) throws IllegalValueException { this.task.getDates().setStartDate(startDate); this.task.getDates().setEndDate(endDate); return this; } # ... rest of the code ...
f2e3ae3e82b622500a6c85ba7aa284babb7ba22a
microsoft-azure-api/src/test/java/com/microsoft/azure/services/blob/IntegrationTestBase.java
microsoft-azure-api/src/test/java/com/microsoft/azure/services/blob/IntegrationTestBase.java
package com.microsoft.azure.services.blob; import org.junit.Before; import org.junit.BeforeClass; import com.microsoft.azure.configuration.Configuration; public abstract class IntegrationTestBase { protected Configuration createConfiguration() { Configuration config = new Configuration(); config.setProperty(BlobConfiguration.ACCOUNT_NAME, "xxx"); config.setProperty(BlobConfiguration.ACCOUNT_KEY, "xxx"); config.setProperty(BlobConfiguration.URL, "http://xxx.blob.core.windows.net"); // when mock running // config.setProperty("serviceBus.uri", "http://localhost:8086"); // config.setProperty("wrapClient.uri", // "http://localhost:8081/WRAPv0.9"); return config; } @BeforeClass public static void initializeSystem() { System.out.println("initialize"); // System.setProperty("http.proxyHost", "itgproxy"); // System.setProperty("http.proxyPort", "80"); // System.setProperty("http.keepAlive", "false"); } @Before public void initialize() throws Exception { System.out.println("initialize"); // System.setProperty("http.proxyHost", "itgproxy"); // System.setProperty("http.proxyPort", "80"); // System.setProperty("http.keepAlive", "false"); } }
package com.microsoft.azure.services.blob; import java.util.Map; import org.junit.Before; import org.junit.BeforeClass; import com.microsoft.azure.configuration.Configuration; public abstract class IntegrationTestBase { protected Configuration createConfiguration() { Configuration config = new Configuration(); Map<String, String> env = System.getenv(); setConfigValue(config, env, BlobConfiguration.ACCOUNT_NAME, "xxx"); setConfigValue(config, env, BlobConfiguration.ACCOUNT_KEY, "xxx"); setConfigValue(config, env, BlobConfiguration.URL, "http://xxx.blob.core.windows.net"); // when mock running // config.setProperty("serviceBus.uri", "http://localhost:8086"); // config.setProperty("wrapClient.uri", // "http://localhost:8081/WRAPv0.9"); return config; } private void setConfigValue(Configuration config, Map<String, String> props, String key, String defaultValue) { String value = props.get(key); if (value == null) value = defaultValue; config.setProperty(key, value); } @BeforeClass public static void initializeSystem() { System.out.println("initialize"); // System.setProperty("http.proxyHost", "itgproxy"); // System.setProperty("http.proxyPort", "80"); // System.setProperty("http.keepAlive", "false"); } @Before public void initialize() throws Exception { System.out.println("initialize"); // System.setProperty("http.proxyHost", "itgproxy"); // System.setProperty("http.proxyPort", "80"); // System.setProperty("http.keepAlive", "false"); } }
Support configuring integration tests with env. variables
Support configuring integration tests with env. variables
Java
mit
manikandan-palaniappan/azure-sdk-for-java,selvasingh/azure-sdk-for-java,hovsepm/azure-sdk-for-java,navalev/azure-sdk-for-java,jianghaolu/azure-sdk-for-java,oaastest/azure-sdk-for-java,Azure/azure-sdk-for-java,Azure/azure-sdk-for-java,selvasingh/azure-sdk-for-java,southworkscom/azure-sdk-for-java,herveyw/azure-sdk-for-java,jianghaolu/azure-sdk-for-java,jianghaolu/azure-sdk-for-java,Azure/azure-sdk-for-java,Azure/azure-sdk-for-java,jingleheimerschmidt/azure-sdk-for-java,jmspring/azure-sdk-for-java,jmspring/azure-sdk-for-java,devigned/azure-sdk-for-java,jingleheimerschmidt/azure-sdk-for-java,navalev/azure-sdk-for-java,ElliottMiller/azure-sdk-for-java,selvasingh/azure-sdk-for-java,pomortaz/azure-sdk-for-java,jalves94/azure-sdk-for-java,jalves94/azure-sdk-for-java,hovsepm/azure-sdk-for-java,martinsawicki/azure-sdk-for-java,pomortaz/azure-sdk-for-java,avranju/azure-sdk-for-java,navalev/azure-sdk-for-java,navalev/azure-sdk-for-java,ljhljh235/azure-sdk-for-java,martinsawicki/azure-sdk-for-java,Azure/azure-sdk-for-java,devigned/azure-sdk-for-java,southworkscom/azure-sdk-for-java,jalves94/azure-sdk-for-java,martinsawicki/azure-sdk-for-java,oaastest/azure-sdk-for-java,navalev/azure-sdk-for-java,pomortaz/azure-sdk-for-java,manikandan-palaniappan/azure-sdk-for-java,avranju/azure-sdk-for-java,herveyw/azure-sdk-for-java,jalves94/azure-sdk-for-java,anudeepsharma/azure-sdk-for-java,hovsepm/azure-sdk-for-java,anudeepsharma/azure-sdk-for-java,herveyw/azure-sdk-for-java,herveyw/azure-sdk-for-java,anudeepsharma/azure-sdk-for-java,hovsepm/azure-sdk-for-java,flydream2046/azure-sdk-for-java,hovsepm/azure-sdk-for-java,ElliottMiller/azure-sdk-for-java,flydream2046/azure-sdk-for-java,anudeepsharma/azure-sdk-for-java,ljhljh235/azure-sdk-for-java,pomortaz/azure-sdk-for-java,anudeepsharma/azure-sdk-for-java
java
## Code Before: package com.microsoft.azure.services.blob; import org.junit.Before; import org.junit.BeforeClass; import com.microsoft.azure.configuration.Configuration; public abstract class IntegrationTestBase { protected Configuration createConfiguration() { Configuration config = new Configuration(); config.setProperty(BlobConfiguration.ACCOUNT_NAME, "xxx"); config.setProperty(BlobConfiguration.ACCOUNT_KEY, "xxx"); config.setProperty(BlobConfiguration.URL, "http://xxx.blob.core.windows.net"); // when mock running // config.setProperty("serviceBus.uri", "http://localhost:8086"); // config.setProperty("wrapClient.uri", // "http://localhost:8081/WRAPv0.9"); return config; } @BeforeClass public static void initializeSystem() { System.out.println("initialize"); // System.setProperty("http.proxyHost", "itgproxy"); // System.setProperty("http.proxyPort", "80"); // System.setProperty("http.keepAlive", "false"); } @Before public void initialize() throws Exception { System.out.println("initialize"); // System.setProperty("http.proxyHost", "itgproxy"); // System.setProperty("http.proxyPort", "80"); // System.setProperty("http.keepAlive", "false"); } } ## Instruction: Support configuring integration tests with env. variables ## Code After: package com.microsoft.azure.services.blob; import java.util.Map; import org.junit.Before; import org.junit.BeforeClass; import com.microsoft.azure.configuration.Configuration; public abstract class IntegrationTestBase { protected Configuration createConfiguration() { Configuration config = new Configuration(); Map<String, String> env = System.getenv(); setConfigValue(config, env, BlobConfiguration.ACCOUNT_NAME, "xxx"); setConfigValue(config, env, BlobConfiguration.ACCOUNT_KEY, "xxx"); setConfigValue(config, env, BlobConfiguration.URL, "http://xxx.blob.core.windows.net"); // when mock running // config.setProperty("serviceBus.uri", "http://localhost:8086"); // config.setProperty("wrapClient.uri", // "http://localhost:8081/WRAPv0.9"); return config; } private void setConfigValue(Configuration config, Map<String, String> props, String key, String defaultValue) { String value = props.get(key); if (value == null) value = defaultValue; config.setProperty(key, value); } @BeforeClass public static void initializeSystem() { System.out.println("initialize"); // System.setProperty("http.proxyHost", "itgproxy"); // System.setProperty("http.proxyPort", "80"); // System.setProperty("http.keepAlive", "false"); } @Before public void initialize() throws Exception { System.out.println("initialize"); // System.setProperty("http.proxyHost", "itgproxy"); // System.setProperty("http.proxyPort", "80"); // System.setProperty("http.keepAlive", "false"); } }
// ... existing code ... package com.microsoft.azure.services.blob; import java.util.Map; import org.junit.Before; import org.junit.BeforeClass; // ... modified code ... public abstract class IntegrationTestBase { protected Configuration createConfiguration() { Configuration config = new Configuration(); Map<String, String> env = System.getenv(); setConfigValue(config, env, BlobConfiguration.ACCOUNT_NAME, "xxx"); setConfigValue(config, env, BlobConfiguration.ACCOUNT_KEY, "xxx"); setConfigValue(config, env, BlobConfiguration.URL, "http://xxx.blob.core.windows.net"); // when mock running // config.setProperty("serviceBus.uri", "http://localhost:8086"); ... // "http://localhost:8081/WRAPv0.9"); return config; } private void setConfigValue(Configuration config, Map<String, String> props, String key, String defaultValue) { String value = props.get(key); if (value == null) value = defaultValue; config.setProperty(key, value); } @BeforeClass // ... rest of the code ...
46fc77ccebf152d2a7825e21a3bc323dd68a6ef9
backend/src/main/java/awesomefb/Post.java
backend/src/main/java/awesomefb/Post.java
package awesomefb; import com.mongodb.BasicDBObject; import org.json.JSONObject; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by earl on 5/25/2015. */ public class Post { private String mMessage; private User mCreator; private Date mCreatedTime; private CommentsList mCommentsList; public Post(JSONObject post) { mMessage = post.getString("message"); mCreator = new User(post.getJSONObject("from")); DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); try { mCreatedTime = format.parse(post.getString("created_time")); } catch (ParseException e) { System.out.println(e.toString()); } mCommentsList = new CommentsList(post.getJSONObject("comments").getJSONArray("data")); } public BasicDBObject toDBObject() { BasicDBObject doc = new BasicDBObject("message", mMessage) .append("creator", mCreator.toDBObject()) .append("time", mCreatedTime) .append("comments", mCommentsList.toDBObject()); return doc; } }
package awesomefb; import com.mongodb.BasicDBObject; import org.json.JSONObject; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by earl on 5/25/2015. */ public class Post { private String mMessage; private User mCreator; private Date mCreatedTime; private CommentsList mCommentsList; public Post(JSONObject post) { mMessage = post.getString("message"); mCreator = new User(post.getJSONObject("from")); mCreatedTime = parseTime(post.getString("created_time")); mCommentsList = new CommentsList(post.getJSONObject("comments").getJSONArray("data")); } private Date parseTime(String dateString) { DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); try { Date time = format.parse(dateString); return time; } catch (ParseException e) { System.out.println(e.toString()); } return null; } public BasicDBObject toDBObject() { BasicDBObject doc = new BasicDBObject("message", mMessage) .append("creator", mCreator.toDBObject()) .append("time", mCreatedTime) .append("comments", mCommentsList.toDBObject()); return doc; } }
Move statements to parseTime method
Move statements to parseTime method
Java
mit
earlwlkr/awesomeFb,earlwlkr/awesomeFb,earlwlkr/awesomeFb
java
## Code Before: package awesomefb; import com.mongodb.BasicDBObject; import org.json.JSONObject; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by earl on 5/25/2015. */ public class Post { private String mMessage; private User mCreator; private Date mCreatedTime; private CommentsList mCommentsList; public Post(JSONObject post) { mMessage = post.getString("message"); mCreator = new User(post.getJSONObject("from")); DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); try { mCreatedTime = format.parse(post.getString("created_time")); } catch (ParseException e) { System.out.println(e.toString()); } mCommentsList = new CommentsList(post.getJSONObject("comments").getJSONArray("data")); } public BasicDBObject toDBObject() { BasicDBObject doc = new BasicDBObject("message", mMessage) .append("creator", mCreator.toDBObject()) .append("time", mCreatedTime) .append("comments", mCommentsList.toDBObject()); return doc; } } ## Instruction: Move statements to parseTime method ## Code After: package awesomefb; import com.mongodb.BasicDBObject; import org.json.JSONObject; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by earl on 5/25/2015. */ public class Post { private String mMessage; private User mCreator; private Date mCreatedTime; private CommentsList mCommentsList; public Post(JSONObject post) { mMessage = post.getString("message"); mCreator = new User(post.getJSONObject("from")); mCreatedTime = parseTime(post.getString("created_time")); mCommentsList = new CommentsList(post.getJSONObject("comments").getJSONArray("data")); } private Date parseTime(String dateString) { DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); try { Date time = format.parse(dateString); return time; } catch (ParseException e) { System.out.println(e.toString()); } return null; } public BasicDBObject toDBObject() { BasicDBObject doc = new BasicDBObject("message", mMessage) .append("creator", mCreator.toDBObject()) .append("time", mCreatedTime) .append("comments", mCommentsList.toDBObject()); return doc; } }
# ... existing code ... public Post(JSONObject post) { mMessage = post.getString("message"); mCreator = new User(post.getJSONObject("from")); mCreatedTime = parseTime(post.getString("created_time")); mCommentsList = new CommentsList(post.getJSONObject("comments").getJSONArray("data")); } private Date parseTime(String dateString) { DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); try { Date time = format.parse(dateString); return time; } catch (ParseException e) { System.out.println(e.toString()); } return null; } public BasicDBObject toDBObject() { # ... rest of the code ...
d7c9bcbf25a6b45a462216f426608474aa66ceb0
mysite/missions/models.py
mysite/missions/models.py
from django.db import models class MissionStep(models.Model): pass class MissionStepCompletion(models.Model): person = models.ForeignKey('profile.Person') step = models.ForeignKey('MissionStep') class Meta: unique_together = ('person', 'step')
from django.db import models class Step(models.Model): pass class StepCompletion(models.Model): person = models.ForeignKey('profile.Person') step = models.ForeignKey('Step') class Meta: unique_together = ('person', 'step')
Remove the redundant "Mission" prefix from the mission model names.
Remove the redundant "Mission" prefix from the mission model names.
Python
agpl-3.0
heeraj123/oh-mainline,vipul-sharma20/oh-mainline,sudheesh001/oh-mainline,willingc/oh-mainline,jledbetter/openhatch,jledbetter/openhatch,moijes12/oh-mainline,openhatch/oh-mainline,mzdaniel/oh-mainline,openhatch/oh-mainline,jledbetter/openhatch,waseem18/oh-mainline,waseem18/oh-mainline,SnappleCap/oh-mainline,Changaco/oh-mainline,eeshangarg/oh-mainline,ehashman/oh-mainline,mzdaniel/oh-mainline,mzdaniel/oh-mainline,Changaco/oh-mainline,Changaco/oh-mainline,SnappleCap/oh-mainline,jledbetter/openhatch,onceuponatimeforever/oh-mainline,nirmeshk/oh-mainline,mzdaniel/oh-mainline,ojengwa/oh-mainline,ehashman/oh-mainline,openhatch/oh-mainline,eeshangarg/oh-mainline,nirmeshk/oh-mainline,nirmeshk/oh-mainline,campbe13/openhatch,heeraj123/oh-mainline,waseem18/oh-mainline,sudheesh001/oh-mainline,waseem18/oh-mainline,heeraj123/oh-mainline,vipul-sharma20/oh-mainline,campbe13/openhatch,willingc/oh-mainline,SnappleCap/oh-mainline,campbe13/openhatch,vipul-sharma20/oh-mainline,campbe13/openhatch,moijes12/oh-mainline,eeshangarg/oh-mainline,onceuponatimeforever/oh-mainline,moijes12/oh-mainline,SnappleCap/oh-mainline,willingc/oh-mainline,heeraj123/oh-mainline,mzdaniel/oh-mainline,mzdaniel/oh-mainline,moijes12/oh-mainline,ehashman/oh-mainline,moijes12/oh-mainline,Changaco/oh-mainline,vipul-sharma20/oh-mainline,Changaco/oh-mainline,onceuponatimeforever/oh-mainline,ojengwa/oh-mainline,onceuponatimeforever/oh-mainline,onceuponatimeforever/oh-mainline,sudheesh001/oh-mainline,heeraj123/oh-mainline,willingc/oh-mainline,SnappleCap/oh-mainline,sudheesh001/oh-mainline,jledbetter/openhatch,ehashman/oh-mainline,eeshangarg/oh-mainline,openhatch/oh-mainline,sudheesh001/oh-mainline,waseem18/oh-mainline,mzdaniel/oh-mainline,eeshangarg/oh-mainline,willingc/oh-mainline,nirmeshk/oh-mainline,campbe13/openhatch,vipul-sharma20/oh-mainline,ojengwa/oh-mainline,ojengwa/oh-mainline,ehashman/oh-mainline,ojengwa/oh-mainline,nirmeshk/oh-mainline,openhatch/oh-mainline
python
## Code Before: from django.db import models class MissionStep(models.Model): pass class MissionStepCompletion(models.Model): person = models.ForeignKey('profile.Person') step = models.ForeignKey('MissionStep') class Meta: unique_together = ('person', 'step') ## Instruction: Remove the redundant "Mission" prefix from the mission model names. ## Code After: from django.db import models class Step(models.Model): pass class StepCompletion(models.Model): person = models.ForeignKey('profile.Person') step = models.ForeignKey('Step') class Meta: unique_together = ('person', 'step')
... from django.db import models class Step(models.Model): pass class StepCompletion(models.Model): person = models.ForeignKey('profile.Person') step = models.ForeignKey('Step') class Meta: unique_together = ('person', 'step') ...
3a89181d0adb53a2a3d428485d5e3deaeb950a02
fixedwidthwriter/__init__.py
fixedwidthwriter/__init__.py
from decimal import Decimal class FixedWidthWriter(): def __init__(self, fd, fields, line_ending='linux'): self.fd = fd self.fields = fields if line_ending == 'linux': self.line_ending = '\n' elif line_ending == 'windows': self.line_ending = '\r\n' else: raise ValueError('Only windows or linux line endings supported') def writerow(self, rowdict): _row = [] for field in self.fields: try: _key, _width, _options = field except ValueError: _key, _width = field _options = {} _value = rowdict[_key] _decimal_spaces = _options.get('decimal_spaces', 0) if _decimal_spaces: _value = unicode(Decimal(_value) .quantize(Decimal(10)**-_decimal_spaces)) _part = '{0: {1}{2}}' \ .format(_value, _options.get('direction', '<'), _width) _row.append(_part) _row = ''.join(_row) self.fd.write(_row + self.line_ending) def writerows(self, rowdicts): for rowdict in rowdicts: self.writerow(rowdict)
from decimal import Decimal class FixedWidthWriter(): def __init__(self, fd, fields, line_ending='linux'): self.fd = fd self.fields = fields if line_ending == 'linux': self.line_ending = '\n' elif line_ending == 'windows': self.line_ending = '\r\n' else: raise ValueError('Only windows or linux line endings supported') def writerow(self, rowdict): row = [] for field in self.fields: try: key, width, options = field except ValueError: key, width = field options = {} value = rowdict[key] decimal_spaces = options.get('decimal_spaces', 0) if decimal_spaces: value = unicode(Decimal(value) .quantize(Decimal(10)**-decimal_spaces)) part = '{0: {1}{2}}' \ .format(value, options.get('direction', '<'), width) row.append(part) row = ''.join(row) self.fd.write(row + self.line_ending) def writerows(self, rowdicts): for rowdict in rowdicts: self.writerow(rowdict)
Remove leading underscores from variables.
Remove leading underscores from variables.
Python
mit
ArthurPBressan/py-fixedwidthwriter,HardDiskD/py-fixedwidthwriter
python
## Code Before: from decimal import Decimal class FixedWidthWriter(): def __init__(self, fd, fields, line_ending='linux'): self.fd = fd self.fields = fields if line_ending == 'linux': self.line_ending = '\n' elif line_ending == 'windows': self.line_ending = '\r\n' else: raise ValueError('Only windows or linux line endings supported') def writerow(self, rowdict): _row = [] for field in self.fields: try: _key, _width, _options = field except ValueError: _key, _width = field _options = {} _value = rowdict[_key] _decimal_spaces = _options.get('decimal_spaces', 0) if _decimal_spaces: _value = unicode(Decimal(_value) .quantize(Decimal(10)**-_decimal_spaces)) _part = '{0: {1}{2}}' \ .format(_value, _options.get('direction', '<'), _width) _row.append(_part) _row = ''.join(_row) self.fd.write(_row + self.line_ending) def writerows(self, rowdicts): for rowdict in rowdicts: self.writerow(rowdict) ## Instruction: Remove leading underscores from variables. ## Code After: from decimal import Decimal class FixedWidthWriter(): def __init__(self, fd, fields, line_ending='linux'): self.fd = fd self.fields = fields if line_ending == 'linux': self.line_ending = '\n' elif line_ending == 'windows': self.line_ending = '\r\n' else: raise ValueError('Only windows or linux line endings supported') def writerow(self, rowdict): row = [] for field in self.fields: try: key, width, options = field except ValueError: key, width = field options = {} value = rowdict[key] decimal_spaces = options.get('decimal_spaces', 0) if decimal_spaces: value = unicode(Decimal(value) .quantize(Decimal(10)**-decimal_spaces)) part = '{0: {1}{2}}' \ .format(value, options.get('direction', '<'), width) row.append(part) row = ''.join(row) self.fd.write(row + self.line_ending) def writerows(self, rowdicts): for rowdict in rowdicts: self.writerow(rowdict)
# ... existing code ... raise ValueError('Only windows or linux line endings supported') def writerow(self, rowdict): row = [] for field in self.fields: try: key, width, options = field except ValueError: key, width = field options = {} value = rowdict[key] decimal_spaces = options.get('decimal_spaces', 0) if decimal_spaces: value = unicode(Decimal(value) .quantize(Decimal(10)**-decimal_spaces)) part = '{0: {1}{2}}' \ .format(value, options.get('direction', '<'), width) row.append(part) row = ''.join(row) self.fd.write(row + self.line_ending) def writerows(self, rowdicts): for rowdict in rowdicts: # ... rest of the code ...
f87a923678f5d7e9f6390ffcb42eae6b2a0f9cc2
services/views.py
services/views.py
import json import requests from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseNotFound from django.conf import settings from django.views.decorators.csrf import csrf_exempt from .patch_ssl import get_session @csrf_exempt def post_service_request(request): if request.method != 'POST': return HttpResponseNotAllowed(['POST']) payload = request.POST.copy() outgoing = payload.dict() outgoing['api_key'] = settings.OPEN311['API_KEY'] url = settings.OPEN311['URL_BASE'] session = get_session() r = session.post(url, data=outgoing) if r.status_code != 200: return HttpResponseBadRequest() return HttpResponse(r.content, content_type="application/json")
import json import requests from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseNotFound from django.conf import settings from django.views.decorators.csrf import csrf_exempt from .patch_ssl import get_session @csrf_exempt def post_service_request(request): if request.method != 'POST': return HttpResponseNotAllowed(['POST']) payload = request.POST.copy() outgoing = payload.dict() if outgoing.get('internal_feedback', False): if 'internal_feedback' in outgoing: del outgoing['internal_feedback'] api_key = settings.OPEN311['INTERNAL_FEEDBACK_API_KEY'] else: api_key = settings.OPEN311['API_KEY'] outgoing['api_key'] = api_key url = settings.OPEN311['URL_BASE'] session = get_session() r = session.post(url, data=outgoing) if r.status_code != 200: return HttpResponseBadRequest() return HttpResponse(r.content, content_type="application/json")
Use separate API key for feedback about app.
Use separate API key for feedback about app.
Python
agpl-3.0
City-of-Helsinki/smbackend,City-of-Helsinki/smbackend
python
## Code Before: import json import requests from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseNotFound from django.conf import settings from django.views.decorators.csrf import csrf_exempt from .patch_ssl import get_session @csrf_exempt def post_service_request(request): if request.method != 'POST': return HttpResponseNotAllowed(['POST']) payload = request.POST.copy() outgoing = payload.dict() outgoing['api_key'] = settings.OPEN311['API_KEY'] url = settings.OPEN311['URL_BASE'] session = get_session() r = session.post(url, data=outgoing) if r.status_code != 200: return HttpResponseBadRequest() return HttpResponse(r.content, content_type="application/json") ## Instruction: Use separate API key for feedback about app. ## Code After: import json import requests from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseNotFound from django.conf import settings from django.views.decorators.csrf import csrf_exempt from .patch_ssl import get_session @csrf_exempt def post_service_request(request): if request.method != 'POST': return HttpResponseNotAllowed(['POST']) payload = request.POST.copy() outgoing = payload.dict() if outgoing.get('internal_feedback', False): if 'internal_feedback' in outgoing: del outgoing['internal_feedback'] api_key = settings.OPEN311['INTERNAL_FEEDBACK_API_KEY'] else: api_key = settings.OPEN311['API_KEY'] outgoing['api_key'] = api_key url = settings.OPEN311['URL_BASE'] session = get_session() r = session.post(url, data=outgoing) if r.status_code != 200: return HttpResponseBadRequest() return HttpResponse(r.content, content_type="application/json")
... return HttpResponseNotAllowed(['POST']) payload = request.POST.copy() outgoing = payload.dict() if outgoing.get('internal_feedback', False): if 'internal_feedback' in outgoing: del outgoing['internal_feedback'] api_key = settings.OPEN311['INTERNAL_FEEDBACK_API_KEY'] else: api_key = settings.OPEN311['API_KEY'] outgoing['api_key'] = api_key url = settings.OPEN311['URL_BASE'] session = get_session() r = session.post(url, data=outgoing) ...
47ea7ebce827727bef5ad49e5df84fa0e5f6e4b9
pycloudflare/services.py
pycloudflare/services.py
from itertools import count from demands import HTTPServiceClient from yoconfig import get_config class CloudFlareService(HTTPServiceClient): def __init__(self, **kwargs): config = get_config('cloudflare') headers = { 'Content-Type': 'application/json', 'X-Auth-Key': config['api_key'], 'X-Auth-Email': config['email'] } super(CloudFlareService, self).__init__(config['url'], headers=headers) def get_zones(self): zones = [] for page in count(): batch = self.get( 'zones?page=%s&per_page=50' % page).json()['result'] if batch: zones.extend(batch) else: break return zones def get_zone(self, zone_id): return self.get('zones/%s' % zone_id).json()['result']
from itertools import count from demands import HTTPServiceClient from yoconfig import get_config class CloudFlareService(HTTPServiceClient): def __init__(self, **kwargs): config = get_config('cloudflare') headers = { 'Content-Type': 'application/json', 'X-Auth-Key': config['api_key'], 'X-Auth-Email': config['email'] } super(CloudFlareService, self).__init__(config['url'], headers=headers) def iter_zones(self): for page in count(): batch = self.get('zones?page=%i&per_page=50' % page).json()['result'] if not batch: return for result in batch: yield result def get_zones(self): return list(self.iter_zones()) def get_zone(self, zone_id): return self.get('zones/%s' % zone_id).json()['result']
Use an iterator to get pages
Use an iterator to get pages
Python
mit
gnowxilef/pycloudflare,yola/pycloudflare
python
## Code Before: from itertools import count from demands import HTTPServiceClient from yoconfig import get_config class CloudFlareService(HTTPServiceClient): def __init__(self, **kwargs): config = get_config('cloudflare') headers = { 'Content-Type': 'application/json', 'X-Auth-Key': config['api_key'], 'X-Auth-Email': config['email'] } super(CloudFlareService, self).__init__(config['url'], headers=headers) def get_zones(self): zones = [] for page in count(): batch = self.get( 'zones?page=%s&per_page=50' % page).json()['result'] if batch: zones.extend(batch) else: break return zones def get_zone(self, zone_id): return self.get('zones/%s' % zone_id).json()['result'] ## Instruction: Use an iterator to get pages ## Code After: from itertools import count from demands import HTTPServiceClient from yoconfig import get_config class CloudFlareService(HTTPServiceClient): def __init__(self, **kwargs): config = get_config('cloudflare') headers = { 'Content-Type': 'application/json', 'X-Auth-Key': config['api_key'], 'X-Auth-Email': config['email'] } super(CloudFlareService, self).__init__(config['url'], headers=headers) def iter_zones(self): for page in count(): batch = self.get('zones?page=%i&per_page=50' % page).json()['result'] if not batch: return for result in batch: yield result def get_zones(self): return list(self.iter_zones()) def get_zone(self, zone_id): return self.get('zones/%s' % zone_id).json()['result']
// ... existing code ... } super(CloudFlareService, self).__init__(config['url'], headers=headers) def iter_zones(self): for page in count(): batch = self.get('zones?page=%i&per_page=50' % page).json()['result'] if not batch: return for result in batch: yield result def get_zones(self): return list(self.iter_zones()) def get_zone(self, zone_id): return self.get('zones/%s' % zone_id).json()['result'] // ... rest of the code ...
3c1853a1bd64adb3e6b4a175bbac926089acac66
app/src/main/java/com/paperfly/instantjio/contacts/Contact.java
app/src/main/java/com/paperfly/instantjio/contacts/Contact.java
package com.paperfly.instantjio.contacts; import android.net.Uri; /** * Entity model that represents a contact */ final public class Contact { final private String photoUri; final private String displayName; final private Uri contactUri; public Contact(String photoUri, String displayName, Uri contactUri) { this.photoUri = photoUri; this.displayName = displayName; this.contactUri = contactUri; } public String getPhotoUri() { return photoUri; } public String getDisplayName() { return displayName; } public Uri getContactUri() { return contactUri; } }
package com.paperfly.instantjio.contacts; import android.net.Uri; /** * Entity model that represents a contact */ public class Contact { String photoUri; String displayName; Uri contactUri; public Contact() { } public Contact(String photoUri, String displayName, Uri contactUri) { this.photoUri = photoUri; this.displayName = displayName; this.contactUri = contactUri; } public String getPhotoUri() { return photoUri; } public String getDisplayName() { return displayName; } public Uri getContactUri() { return contactUri; } }
Change to fit Firebase model class style
Change to fit Firebase model class style
Java
mit
paperfly/InstantJio
java
## Code Before: package com.paperfly.instantjio.contacts; import android.net.Uri; /** * Entity model that represents a contact */ final public class Contact { final private String photoUri; final private String displayName; final private Uri contactUri; public Contact(String photoUri, String displayName, Uri contactUri) { this.photoUri = photoUri; this.displayName = displayName; this.contactUri = contactUri; } public String getPhotoUri() { return photoUri; } public String getDisplayName() { return displayName; } public Uri getContactUri() { return contactUri; } } ## Instruction: Change to fit Firebase model class style ## Code After: package com.paperfly.instantjio.contacts; import android.net.Uri; /** * Entity model that represents a contact */ public class Contact { String photoUri; String displayName; Uri contactUri; public Contact() { } public Contact(String photoUri, String displayName, Uri contactUri) { this.photoUri = photoUri; this.displayName = displayName; this.contactUri = contactUri; } public String getPhotoUri() { return photoUri; } public String getDisplayName() { return displayName; } public Uri getContactUri() { return contactUri; } }
# ... existing code ... /** * Entity model that represents a contact */ public class Contact { String photoUri; String displayName; Uri contactUri; public Contact() { } public Contact(String photoUri, String displayName, Uri contactUri) { this.photoUri = photoUri; # ... rest of the code ...
3e4360e831d98dadca3f9346f324f3d17769257f
alg_selection_sort.py
alg_selection_sort.py
from __future__ import absolute_import from __future__ import print_function from __future__ import division def selection_sort(a_list): """Selection Sort algortihm. Time complexity: O(n^2). """ for max_slot in reversed(range(len(a_list))): select_slot = 0 for slot in range(1, max_slot + 1): if a_list[slot] > a_list[select_slot]: select_slot = slot a_list[select_slot], a_list[max_slot] = ( a_list[max_slot], a_list[select_slot]) def main(): a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] print('a_list: {}'.format(a_list)) print('By selection sort: ') selection_sort(a_list) print(a_list) if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import print_function from __future__ import division def selection_sort(ls): """Selection Sort algortihm. Time complexity: O(n^2). Space complexity: O(1). """ # Start from the last elemenet reversely: len(ls) - 1, ..., 0. for i_max in reversed(range(len(ls))): # Select the next max, and interchange it with corresponding element. s = 0 for i in range(1, i_max + 1): if ls[i] > ls[s]: s = i ls[s], ls[i_max] = ls[i_max], ls[s] def main(): ls = [54, 26, 93, 17, 77, 31, 44, 55, 20] print('List: {}'.format(ls)) print('By selection sort: ') selection_sort(ls) print(ls) if __name__ == '__main__': main()
Refactor selection sort w/ adding comments
Refactor selection sort w/ adding comments
Python
bsd-2-clause
bowen0701/algorithms_data_structures
python
## Code Before: from __future__ import absolute_import from __future__ import print_function from __future__ import division def selection_sort(a_list): """Selection Sort algortihm. Time complexity: O(n^2). """ for max_slot in reversed(range(len(a_list))): select_slot = 0 for slot in range(1, max_slot + 1): if a_list[slot] > a_list[select_slot]: select_slot = slot a_list[select_slot], a_list[max_slot] = ( a_list[max_slot], a_list[select_slot]) def main(): a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] print('a_list: {}'.format(a_list)) print('By selection sort: ') selection_sort(a_list) print(a_list) if __name__ == '__main__': main() ## Instruction: Refactor selection sort w/ adding comments ## Code After: from __future__ import absolute_import from __future__ import print_function from __future__ import division def selection_sort(ls): """Selection Sort algortihm. Time complexity: O(n^2). Space complexity: O(1). """ # Start from the last elemenet reversely: len(ls) - 1, ..., 0. for i_max in reversed(range(len(ls))): # Select the next max, and interchange it with corresponding element. s = 0 for i in range(1, i_max + 1): if ls[i] > ls[s]: s = i ls[s], ls[i_max] = ls[i_max], ls[s] def main(): ls = [54, 26, 93, 17, 77, 31, 44, 55, 20] print('List: {}'.format(ls)) print('By selection sort: ') selection_sort(ls) print(ls) if __name__ == '__main__': main()
// ... existing code ... from __future__ import division def selection_sort(ls): """Selection Sort algortihm. Time complexity: O(n^2). Space complexity: O(1). """ # Start from the last elemenet reversely: len(ls) - 1, ..., 0. for i_max in reversed(range(len(ls))): # Select the next max, and interchange it with corresponding element. s = 0 for i in range(1, i_max + 1): if ls[i] > ls[s]: s = i ls[s], ls[i_max] = ls[i_max], ls[s] def main(): ls = [54, 26, 93, 17, 77, 31, 44, 55, 20] print('List: {}'.format(ls)) print('By selection sort: ') selection_sort(ls) print(ls) if __name__ == '__main__': // ... rest of the code ...
159239da12101124ee261e8edd47ba7e4e5a8419
TachiServer/DesktopUI/src/main/java/xyz/nulldev/ts/dui/DUIView.kt
TachiServer/DesktopUI/src/main/java/xyz/nulldev/ts/dui/DUIView.kt
package xyz.nulldev.ts.dui import com.github.salomonbrys.kodein.conf.KodeinGlobalAware import com.github.salomonbrys.kodein.instance import com.sun.javafx.webkit.WebConsoleListener import tornadofx.View import tornadofx.stackpane import tornadofx.webview import xyz.nulldev.ts.config.ConfigManager import xyz.nulldev.ts.config.ServerConfig class DUIView : View(), KodeinGlobalAware { val serverConfig by lazy { instance<ConfigManager>().module<ServerConfig>() } override val root = stackpane { webview { engine.load("http://${serverConfig.ip}:${serverConfig.port}") WebConsoleListener.setDefaultListener { webView, message, lineNumber, sourceId -> println("Console: [$sourceId:$lineNumber] $message") } } } }
package xyz.nulldev.ts.dui import com.github.salomonbrys.kodein.conf.KodeinGlobalAware import com.github.salomonbrys.kodein.instance import tornadofx.View import tornadofx.stackpane import tornadofx.webview import xyz.nulldev.ts.config.ConfigManager import xyz.nulldev.ts.config.ServerConfig class DUIView : View(), KodeinGlobalAware { val serverConfig by lazy { instance<ConfigManager>().module<ServerConfig>() } override val root = stackpane { webview { engine.load("http://${serverConfig.ip}:${serverConfig.port}") // WebConsoleListener.setDefaultListener { webView, message, lineNumber, sourceId -> // println("Console: [$sourceId:$lineNumber] $message") // } } } }
Remove invalid module access in webview test Fix line endings in gradlew.bat
Remove invalid module access in webview test Fix line endings in gradlew.bat
Kotlin
apache-2.0
TachiWeb/TachiWeb-Server,TachiWeb/TachiWeb-Server,TachiWeb/TachiWeb-Server,TachiWeb/TachiWeb-Server,TachiWeb/TachiWeb-Server
kotlin
## Code Before: package xyz.nulldev.ts.dui import com.github.salomonbrys.kodein.conf.KodeinGlobalAware import com.github.salomonbrys.kodein.instance import com.sun.javafx.webkit.WebConsoleListener import tornadofx.View import tornadofx.stackpane import tornadofx.webview import xyz.nulldev.ts.config.ConfigManager import xyz.nulldev.ts.config.ServerConfig class DUIView : View(), KodeinGlobalAware { val serverConfig by lazy { instance<ConfigManager>().module<ServerConfig>() } override val root = stackpane { webview { engine.load("http://${serverConfig.ip}:${serverConfig.port}") WebConsoleListener.setDefaultListener { webView, message, lineNumber, sourceId -> println("Console: [$sourceId:$lineNumber] $message") } } } } ## Instruction: Remove invalid module access in webview test Fix line endings in gradlew.bat ## Code After: package xyz.nulldev.ts.dui import com.github.salomonbrys.kodein.conf.KodeinGlobalAware import com.github.salomonbrys.kodein.instance import tornadofx.View import tornadofx.stackpane import tornadofx.webview import xyz.nulldev.ts.config.ConfigManager import xyz.nulldev.ts.config.ServerConfig class DUIView : View(), KodeinGlobalAware { val serverConfig by lazy { instance<ConfigManager>().module<ServerConfig>() } override val root = stackpane { webview { engine.load("http://${serverConfig.ip}:${serverConfig.port}") // WebConsoleListener.setDefaultListener { webView, message, lineNumber, sourceId -> // println("Console: [$sourceId:$lineNumber] $message") // } } } }
... import com.github.salomonbrys.kodein.conf.KodeinGlobalAware import com.github.salomonbrys.kodein.instance import tornadofx.View import tornadofx.stackpane import tornadofx.webview ... webview { engine.load("http://${serverConfig.ip}:${serverConfig.port}") // WebConsoleListener.setDefaultListener { webView, message, lineNumber, sourceId -> // println("Console: [$sourceId:$lineNumber] $message") // } } } } ...
7654d9dcebb0ad1e862e376b5b694234173289ed
twitter_helper/util.py
twitter_helper/util.py
import random def random_line(afile, max_chars = 123, min_chars = 5): line = next(afile) for num, aline in enumerate(afile): aline = aline.strip() if (len(aline) < min_chars or aline[0].islower() or len(aline) > max_chars) or random.randrange(num + 2): continue line = aline return line def prepare_quote(text_file, signature=" -- Hamlet", max_chars = 123, min_chars = 5,): line = random_line(text_file, max_chars, min_chars) number = random.randrange(1,1000,2) line = "{0}] " + line + signature line = line.format(number) return line
import random def random_line(afile, max_chars = 123, min_chars = 5): line = next(afile) for num, aline in enumerate(afile): aline = aline.strip() if (len(aline) < min_chars or aline[0].islower() or len(aline) > max_chars) or random.randrange(num + 2): continue line = aline #Be polite, put things back in the place you found them afile.seek(0) return line def prepare_quote(text_file, signature=" -- Hamlet", max_chars = 123, min_chars = 5,): line = random_line(text_file, max_chars, min_chars) number = random.randrange(1,1000,2) line = "{0}] " + line + signature line = line.format(number) return line
Reset pointer to the beginning of file once read it
Reset pointer to the beginning of file once read it Be polite, put things back in the place you found them
Python
mit
kuzeko/Twitter-Importer,kuzeko/Twitter-Importer
python
## Code Before: import random def random_line(afile, max_chars = 123, min_chars = 5): line = next(afile) for num, aline in enumerate(afile): aline = aline.strip() if (len(aline) < min_chars or aline[0].islower() or len(aline) > max_chars) or random.randrange(num + 2): continue line = aline return line def prepare_quote(text_file, signature=" -- Hamlet", max_chars = 123, min_chars = 5,): line = random_line(text_file, max_chars, min_chars) number = random.randrange(1,1000,2) line = "{0}] " + line + signature line = line.format(number) return line ## Instruction: Reset pointer to the beginning of file once read it Be polite, put things back in the place you found them ## Code After: import random def random_line(afile, max_chars = 123, min_chars = 5): line = next(afile) for num, aline in enumerate(afile): aline = aline.strip() if (len(aline) < min_chars or aline[0].islower() or len(aline) > max_chars) or random.randrange(num + 2): continue line = aline #Be polite, put things back in the place you found them afile.seek(0) return line def prepare_quote(text_file, signature=" -- Hamlet", max_chars = 123, min_chars = 5,): line = random_line(text_file, max_chars, min_chars) number = random.randrange(1,1000,2) line = "{0}] " + line + signature line = line.format(number) return line
# ... existing code ... if (len(aline) < min_chars or aline[0].islower() or len(aline) > max_chars) or random.randrange(num + 2): continue line = aline #Be polite, put things back in the place you found them afile.seek(0) return line def prepare_quote(text_file, signature=" -- Hamlet", max_chars = 123, min_chars = 5,): # ... rest of the code ...
bccfc6d3c0035e2a5668607ebb7dd6047ee1942f
kokki/cookbooks/mdadm/recipes/default.py
kokki/cookbooks/mdadm/recipes/default.py
from kokki import * if env.config.mdadm.arrays: Package("mdadm") Execute("mdadm-update-conf", action = "nothing", command = ("(" "echo DEVICE partitions > /etc/mdadm/mdadm.conf" "; mdadm --detail --scan >> /etc/mdadm/mdadm.conf" ")" )) for array in env.config.mdadm.arrays: env.cookbooks.mdadm.Array(**array) if array.get('fstype'): if array['fstype'] == "xfs": Package("xfsprogs") Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=array['fstype'], device=array['name']), not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % dict(device=array['name'])) if array.get('mount_point'): Mount(array['mount_point'], device = array['name'], fstype = array['fstype'], options = array['fsoptions'] if array.get('fsoptions') is not None else ["noatime"], action = ["mount", "enable"])
from kokki import * if env.config.mdadm.arrays: Package("mdadm") Execute("mdadm-update-conf", action = "nothing", command = ("(" "echo DEVICE partitions > /etc/mdadm/mdadm.conf" "; mdadm --detail --scan >> /etc/mdadm/mdadm.conf" ")" )) for array in env.config.mdadm.arrays: fstype = array.pop('fstype', None) fsoptions = array.pop('fsoptions', None) mount_point = array.pop('mount_point', None) env.cookbooks.mdadm.Array(**array) if fstype: if fstype == "xfs": Package("xfsprogs") Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=fstype, device=array['name']), not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % dict(device=array['name'])) if mount_point: Mount(mount_point, device = array['name'], fstype = fstype, options = fsoptions if fsoptions is not None else ["noatime"], action = ["mount", "enable"])
Fix to mounting mdadm raid arrays
Fix to mounting mdadm raid arrays
Python
bsd-3-clause
samuel/kokki
python
## Code Before: from kokki import * if env.config.mdadm.arrays: Package("mdadm") Execute("mdadm-update-conf", action = "nothing", command = ("(" "echo DEVICE partitions > /etc/mdadm/mdadm.conf" "; mdadm --detail --scan >> /etc/mdadm/mdadm.conf" ")" )) for array in env.config.mdadm.arrays: env.cookbooks.mdadm.Array(**array) if array.get('fstype'): if array['fstype'] == "xfs": Package("xfsprogs") Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=array['fstype'], device=array['name']), not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % dict(device=array['name'])) if array.get('mount_point'): Mount(array['mount_point'], device = array['name'], fstype = array['fstype'], options = array['fsoptions'] if array.get('fsoptions') is not None else ["noatime"], action = ["mount", "enable"]) ## Instruction: Fix to mounting mdadm raid arrays ## Code After: from kokki import * if env.config.mdadm.arrays: Package("mdadm") Execute("mdadm-update-conf", action = "nothing", command = ("(" "echo DEVICE partitions > /etc/mdadm/mdadm.conf" "; mdadm --detail --scan >> /etc/mdadm/mdadm.conf" ")" )) for array in env.config.mdadm.arrays: fstype = array.pop('fstype', None) fsoptions = array.pop('fsoptions', None) mount_point = array.pop('mount_point', None) env.cookbooks.mdadm.Array(**array) if fstype: if fstype == "xfs": Package("xfsprogs") Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=fstype, device=array['name']), not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % dict(device=array['name'])) if mount_point: Mount(mount_point, device = array['name'], fstype = fstype, options = fsoptions if fsoptions is not None else ["noatime"], action = ["mount", "enable"])
// ... existing code ... )) for array in env.config.mdadm.arrays: fstype = array.pop('fstype', None) fsoptions = array.pop('fsoptions', None) mount_point = array.pop('mount_point', None) env.cookbooks.mdadm.Array(**array) if fstype: if fstype == "xfs": Package("xfsprogs") Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=fstype, device=array['name']), not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % dict(device=array['name'])) if mount_point: Mount(mount_point, device = array['name'], fstype = fstype, options = fsoptions if fsoptions is not None else ["noatime"], action = ["mount", "enable"]) // ... rest of the code ...
b702569c800953eb3476c927fbc1085e67c88dbd
ghettoq/messaging.py
ghettoq/messaging.py
from Queue import Empty from itertools import cycle class Queue(object): def __init__(self, backend, name): self.name = name self.backend = backend def put(self, payload): self.backend.put(self.name, payload) def get(self): payload = self.backend.get(self.name) if payload is not None: return payload raise Empty class QueueSet(object): def __init__(self, backend, queues): self.backend = backend self.queues = map(self.backend.Queue, queues) self.cycle = cycle(self.queues) def get(self): while True: try: return self.cycle.next().get() except QueueEmpty: pass
from Queue import Empty from itertools import cycle class Queue(object): def __init__(self, backend, name): self.name = name self.backend = backend def put(self, payload): self.backend.put(self.name, payload) def get(self): payload = self.backend.get(self.name) if payload is not None: return payload raise Empty class QueueSet(object): def __init__(self, backend, queues): self.backend = backend self.queue_names = queues self.queues = map(self.backend.Queue, self.queue_names) self.cycle = cycle(self.queues) self.all = frozenset(self.queue_names) def get(self): tried = set() while True: queue = self.cycle.next() try: return queue.get() except QueueEmpty: tried.add(queue) if tried == self.all: raise
Raise QueueEmpty when all queues has been tried.
QueueSet: Raise QueueEmpty when all queues has been tried.
Python
bsd-3-clause
ask/ghettoq
python
## Code Before: from Queue import Empty from itertools import cycle class Queue(object): def __init__(self, backend, name): self.name = name self.backend = backend def put(self, payload): self.backend.put(self.name, payload) def get(self): payload = self.backend.get(self.name) if payload is not None: return payload raise Empty class QueueSet(object): def __init__(self, backend, queues): self.backend = backend self.queues = map(self.backend.Queue, queues) self.cycle = cycle(self.queues) def get(self): while True: try: return self.cycle.next().get() except QueueEmpty: pass ## Instruction: QueueSet: Raise QueueEmpty when all queues has been tried. ## Code After: from Queue import Empty from itertools import cycle class Queue(object): def __init__(self, backend, name): self.name = name self.backend = backend def put(self, payload): self.backend.put(self.name, payload) def get(self): payload = self.backend.get(self.name) if payload is not None: return payload raise Empty class QueueSet(object): def __init__(self, backend, queues): self.backend = backend self.queue_names = queues self.queues = map(self.backend.Queue, self.queue_names) self.cycle = cycle(self.queues) self.all = frozenset(self.queue_names) def get(self): tried = set() while True: queue = self.cycle.next() try: return queue.get() except QueueEmpty: tried.add(queue) if tried == self.all: raise
# ... existing code ... def __init__(self, backend, queues): self.backend = backend self.queue_names = queues self.queues = map(self.backend.Queue, self.queue_names) self.cycle = cycle(self.queues) self.all = frozenset(self.queue_names) def get(self): tried = set() while True: queue = self.cycle.next() try: return queue.get() except QueueEmpty: tried.add(queue) if tried == self.all: raise # ... rest of the code ...
678e872de192b09c1bafc7a26dc67d7737a14e20
altair/examples/us_population_over_time.py
altair/examples/us_population_over_time.py
# category: case studies import altair as alt from vega_datasets import data source = data.population.url pink_blue = alt.Scale(domain=('Male', 'Female'), range=["steelblue", "salmon"]) slider = alt.binding_range(min=1900, max=2000, step=10) select_year = alt.selection_single(name="year", fields=['year'], bind=slider, init={'year': 2000}) alt.Chart(source).mark_bar().encode( x=alt.X('sex:N', title=None), y=alt.Y('people:Q', scale=alt.Scale(domain=(0, 12000000))), color=alt.Color('sex:N', scale=pink_blue), column='age:O' ).properties( width=20 ).add_selection( select_year ).transform_calculate( "sex", alt.expr.if_(alt.datum.sex == 1, "Male", "Female") ).transform_filter( select_year ).configure_facet( spacing=8 )
# category: case studies import altair as alt from vega_datasets import data source = data.population.url select_year = alt.selection_single( name="Year", fields=["year"], bind=alt.binding_range(min=1900, max=2000, step=10, name="Year"), init={"year": 2000}, ) alt.Chart(source).mark_bar().encode( x=alt.X("sex:N", axis=alt.Axis(labels=False, title=None, ticks=False)), y=alt.Y("people:Q", scale=alt.Scale(domain=(0, 12000000)), title="Population"), color=alt.Color( "sex:N", scale=alt.Scale(domain=("Male", "Female"), range=["steelblue", "salmon"]), title="Sex", ), column=alt.Column("age:O", title="Age"), ).properties(width=20, title="U.S. Population by Age and Sex").add_selection( select_year ).transform_calculate( "sex", alt.expr.if_(alt.datum.sex == 1, "Male", "Female") ).transform_filter( select_year ).configure_facet( spacing=8 )
Tidy up U.S. Population by Age and Sex
Tidy up U.S. Population by Age and Sex
Python
bsd-3-clause
altair-viz/altair
python
## Code Before: # category: case studies import altair as alt from vega_datasets import data source = data.population.url pink_blue = alt.Scale(domain=('Male', 'Female'), range=["steelblue", "salmon"]) slider = alt.binding_range(min=1900, max=2000, step=10) select_year = alt.selection_single(name="year", fields=['year'], bind=slider, init={'year': 2000}) alt.Chart(source).mark_bar().encode( x=alt.X('sex:N', title=None), y=alt.Y('people:Q', scale=alt.Scale(domain=(0, 12000000))), color=alt.Color('sex:N', scale=pink_blue), column='age:O' ).properties( width=20 ).add_selection( select_year ).transform_calculate( "sex", alt.expr.if_(alt.datum.sex == 1, "Male", "Female") ).transform_filter( select_year ).configure_facet( spacing=8 ) ## Instruction: Tidy up U.S. Population by Age and Sex ## Code After: # category: case studies import altair as alt from vega_datasets import data source = data.population.url select_year = alt.selection_single( name="Year", fields=["year"], bind=alt.binding_range(min=1900, max=2000, step=10, name="Year"), init={"year": 2000}, ) alt.Chart(source).mark_bar().encode( x=alt.X("sex:N", axis=alt.Axis(labels=False, title=None, ticks=False)), y=alt.Y("people:Q", scale=alt.Scale(domain=(0, 12000000)), title="Population"), color=alt.Color( "sex:N", scale=alt.Scale(domain=("Male", "Female"), range=["steelblue", "salmon"]), title="Sex", ), column=alt.Column("age:O", title="Age"), ).properties(width=20, title="U.S. Population by Age and Sex").add_selection( select_year ).transform_calculate( "sex", alt.expr.if_(alt.datum.sex == 1, "Male", "Female") ).transform_filter( select_year ).configure_facet( spacing=8 )
# ... existing code ... source = data.population.url select_year = alt.selection_single( name="Year", fields=["year"], bind=alt.binding_range(min=1900, max=2000, step=10, name="Year"), init={"year": 2000}, ) alt.Chart(source).mark_bar().encode( x=alt.X("sex:N", axis=alt.Axis(labels=False, title=None, ticks=False)), y=alt.Y("people:Q", scale=alt.Scale(domain=(0, 12000000)), title="Population"), color=alt.Color( "sex:N", scale=alt.Scale(domain=("Male", "Female"), range=["steelblue", "salmon"]), title="Sex", ), column=alt.Column("age:O", title="Age"), ).properties(width=20, title="U.S. Population by Age and Sex").add_selection( select_year ).transform_calculate( "sex", alt.expr.if_(alt.datum.sex == 1, "Male", "Female") # ... rest of the code ...
577e2a03c15e4e489d0df4c3c2a2bea8b9aa54b6
fluent_utils/softdeps/any_urlfield.py
fluent_utils/softdeps/any_urlfield.py
from __future__ import absolute_import from django.db import models from fluent_utils.django_compat import is_installed if is_installed('any_urlfield'): from any_urlfield.models import AnyUrlField as BaseUrlField else: BaseUrlField = models.URLField # subclassing here so South or Django migrations detect a single class. class AnyUrlField(BaseUrlField): """ A CharField that can either refer to a CMS page ID, or external URL. If *django-any-urlfield* is not installed, only regular URLs can be used. """ def __init__(self, *args, **kwargs): if 'max_length' not in kwargs: kwargs['max_length'] = 300 # Standardize super(AnyUrlField, self).__init__(*args, **kwargs) def south_field_triple(self): # Masquerade as normal URLField, so the soft-dependency also exists in the migrations. from south.modelsinspector import introspector path = "{0}.{1}".format(models.URLField.__module__, models.URLField.__name__) args, kwargs = introspector(self) return (path, args, kwargs) def deconstruct(self): # For Django 1.7 migrations, masquerade as normal URLField too name, path, args, kwargs = super(AnyUrlField, self).deconstruct() path = "{0}.{1}".format(models.URLField.__module__, models.URLField.__name__) return name, path, args, kwargs
from __future__ import absolute_import from django.db import models from fluent_utils.django_compat import is_installed if is_installed('any_urlfield'): from any_urlfield.models import AnyUrlField as BaseUrlField else: BaseUrlField = models.URLField # subclassing here so South or Django migrations detect a single class. class AnyUrlField(BaseUrlField): """ A CharField that can either refer to a CMS page ID, or external URL. If *django-any-urlfield* is not installed, only regular URLs can be used. """ def __init__(self, *args, **kwargs): if 'max_length' not in kwargs: kwargs['max_length'] = 300 # Standardize super(AnyUrlField, self).__init__(*args, **kwargs) def south_field_triple(self): # Masquerade as normal URLField, so the soft-dependency also exists in the migrations. from south.modelsinspector import introspector path = "{0}.{1}".format(models.URLField.__module__, models.URLField.__name__) args, kwargs = introspector(self) return (path, args, kwargs) def deconstruct(self): # For Django 1.7 migrations, masquerade as normal URLField too name, path, args, kwargs = super(AnyUrlField, self).deconstruct() path = "django.db.models.{}".format(models.URLField.__name__) return name, path, args, kwargs
Fix AnyUrlField migration issue on Django 1.11.
Fix AnyUrlField migration issue on Django 1.11.
Python
apache-2.0
edoburu/django-fluent-utils
python
## Code Before: from __future__ import absolute_import from django.db import models from fluent_utils.django_compat import is_installed if is_installed('any_urlfield'): from any_urlfield.models import AnyUrlField as BaseUrlField else: BaseUrlField = models.URLField # subclassing here so South or Django migrations detect a single class. class AnyUrlField(BaseUrlField): """ A CharField that can either refer to a CMS page ID, or external URL. If *django-any-urlfield* is not installed, only regular URLs can be used. """ def __init__(self, *args, **kwargs): if 'max_length' not in kwargs: kwargs['max_length'] = 300 # Standardize super(AnyUrlField, self).__init__(*args, **kwargs) def south_field_triple(self): # Masquerade as normal URLField, so the soft-dependency also exists in the migrations. from south.modelsinspector import introspector path = "{0}.{1}".format(models.URLField.__module__, models.URLField.__name__) args, kwargs = introspector(self) return (path, args, kwargs) def deconstruct(self): # For Django 1.7 migrations, masquerade as normal URLField too name, path, args, kwargs = super(AnyUrlField, self).deconstruct() path = "{0}.{1}".format(models.URLField.__module__, models.URLField.__name__) return name, path, args, kwargs ## Instruction: Fix AnyUrlField migration issue on Django 1.11. ## Code After: from __future__ import absolute_import from django.db import models from fluent_utils.django_compat import is_installed if is_installed('any_urlfield'): from any_urlfield.models import AnyUrlField as BaseUrlField else: BaseUrlField = models.URLField # subclassing here so South or Django migrations detect a single class. class AnyUrlField(BaseUrlField): """ A CharField that can either refer to a CMS page ID, or external URL. If *django-any-urlfield* is not installed, only regular URLs can be used. """ def __init__(self, *args, **kwargs): if 'max_length' not in kwargs: kwargs['max_length'] = 300 # Standardize super(AnyUrlField, self).__init__(*args, **kwargs) def south_field_triple(self): # Masquerade as normal URLField, so the soft-dependency also exists in the migrations. from south.modelsinspector import introspector path = "{0}.{1}".format(models.URLField.__module__, models.URLField.__name__) args, kwargs = introspector(self) return (path, args, kwargs) def deconstruct(self): # For Django 1.7 migrations, masquerade as normal URLField too name, path, args, kwargs = super(AnyUrlField, self).deconstruct() path = "django.db.models.{}".format(models.URLField.__name__) return name, path, args, kwargs
// ... existing code ... def deconstruct(self): # For Django 1.7 migrations, masquerade as normal URLField too name, path, args, kwargs = super(AnyUrlField, self).deconstruct() path = "django.db.models.{}".format(models.URLField.__name__) return name, path, args, kwargs // ... rest of the code ...
9704602f26b4a9aab15caf00795d283c5f6e4ae4
src/fiona/tool.py
src/fiona/tool.py
if __name__ == '__main__': import argparse import fiona import json import pprint import sys parser = argparse.ArgumentParser( description="Serialize a file to GeoJSON or view its description") parser.add_argument('-i', '--info', action='store_true', help='View pretty printed description information only') parser.add_argument('-j', '--json', action='store_true', help='Output description as indented JSON') parser.add_argument('filename', help="data file name") args = parser.parse_args() with fiona.open(args.filename, 'r') as col: if args.info: if args.json: meta = col.meta.copy() meta.update(name=args.filename) print(json.dumps(meta, indent=2)) else: print("\nDescription of: %r" % col) print("\nCoordinate reference system (col.crs):") pprint.pprint(meta['crs']) print("\nFormat driver (col.driver):") pprint.pprint(meta['driver']) print("\nData description (col.schema):") pprint.pprint(meta['schema']) else: print(json.dumps(list(col), indent=2))
if __name__ == '__main__': import argparse import fiona import json import pprint import sys parser = argparse.ArgumentParser( description="Serialize a file to GeoJSON or view its description") parser.add_argument('-i', '--info', action='store_true', help='View pretty printed description information only') parser.add_argument('-j', '--json', action='store_true', help='Output description as indented JSON') parser.add_argument('filename', help="data file name") args = parser.parse_args() with fiona.open(args.filename, 'r') as col: if args.info: if args.json: meta = col.meta.copy() meta.update(name=args.filename) print(json.dumps(meta, indent=2)) else: print("\nDescription of: %r" % col) print("\nCoordinate reference system (col.crs):") pprint.pprint(meta['crs']) print("\nFormat driver (col.driver):") pprint.pprint(meta['driver']) print("\nData description (col.schema):") pprint.pprint(meta['schema']) else: collection = {'type': 'FeatureCollection'} collection['features'] = list(col) print(json.dumps(collection, indent=2))
Change record output to strict GeoJSON.
Change record output to strict GeoJSON. Meaning features in a FeatureCollection.
Python
bsd-3-clause
rbuffat/Fiona,Toblerity/Fiona,sgillies/Fiona,johanvdw/Fiona,perrygeo/Fiona,Toblerity/Fiona,perrygeo/Fiona,rbuffat/Fiona
python
## Code Before: if __name__ == '__main__': import argparse import fiona import json import pprint import sys parser = argparse.ArgumentParser( description="Serialize a file to GeoJSON or view its description") parser.add_argument('-i', '--info', action='store_true', help='View pretty printed description information only') parser.add_argument('-j', '--json', action='store_true', help='Output description as indented JSON') parser.add_argument('filename', help="data file name") args = parser.parse_args() with fiona.open(args.filename, 'r') as col: if args.info: if args.json: meta = col.meta.copy() meta.update(name=args.filename) print(json.dumps(meta, indent=2)) else: print("\nDescription of: %r" % col) print("\nCoordinate reference system (col.crs):") pprint.pprint(meta['crs']) print("\nFormat driver (col.driver):") pprint.pprint(meta['driver']) print("\nData description (col.schema):") pprint.pprint(meta['schema']) else: print(json.dumps(list(col), indent=2)) ## Instruction: Change record output to strict GeoJSON. Meaning features in a FeatureCollection. ## Code After: if __name__ == '__main__': import argparse import fiona import json import pprint import sys parser = argparse.ArgumentParser( description="Serialize a file to GeoJSON or view its description") parser.add_argument('-i', '--info', action='store_true', help='View pretty printed description information only') parser.add_argument('-j', '--json', action='store_true', help='Output description as indented JSON') parser.add_argument('filename', help="data file name") args = parser.parse_args() with fiona.open(args.filename, 'r') as col: if args.info: if args.json: meta = col.meta.copy() meta.update(name=args.filename) print(json.dumps(meta, indent=2)) else: print("\nDescription of: %r" % col) print("\nCoordinate reference system (col.crs):") pprint.pprint(meta['crs']) print("\nFormat driver (col.driver):") pprint.pprint(meta['driver']) print("\nData description (col.schema):") pprint.pprint(meta['schema']) else: collection = {'type': 'FeatureCollection'} collection['features'] = list(col) print(json.dumps(collection, indent=2))
... print("\nData description (col.schema):") pprint.pprint(meta['schema']) else: collection = {'type': 'FeatureCollection'} collection['features'] = list(col) print(json.dumps(collection, indent=2)) ...
24187524c3db0287e40de4f057ff7fdea5595f34
src/main/kotlin/cn/yiiguxing/plugin/translate/action/ShowWordOfTheDayAction.kt
src/main/kotlin/cn/yiiguxing/plugin/translate/action/ShowWordOfTheDayAction.kt
@file:Suppress("InvalidBundleOrProperty") package cn.yiiguxing.plugin.translate.action import cn.yiiguxing.plugin.translate.message import cn.yiiguxing.plugin.translate.util.* import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAware import com.intellij.openapi.ui.MessageType /** * Show word of the day action. * * Created by Yii.Guxing on 2019/08/23. */ class ShowWordOfTheDayAction : AnAction(), DumbAware { private var isLoading: Boolean = false init { templatePresentation.description = message("word.of.the.day.title") } override fun actionPerformed(e: AnActionEvent) { if (Application.isUnitTestMode || isLoading) { return } isLoading = true val project = e.project executeOnPooledThread { if (project?.isDisposed == true) { return@executeOnPooledThread } val words = WordBookService.getWords() invokeLater { if (project?.isDisposed != true) { if (words.isNotEmpty()) { TranslationUIManager.showWordDialog(project, words) } else { val message = message("word.of.the.day.no.words") Popups.showBalloonForActiveFrame(message, MessageType.INFO) } } isLoading = false } } } }
@file:Suppress("InvalidBundleOrProperty") package cn.yiiguxing.plugin.translate.action import cn.yiiguxing.plugin.translate.message import cn.yiiguxing.plugin.translate.util.* import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAware import com.intellij.openapi.ui.MessageType /** * Show word of the day action. * * Created by Yii.Guxing on 2019/08/23. */ class ShowWordOfTheDayAction : AnAction(), DumbAware { init { templatePresentation.description = message("word.of.the.day.title") } override fun actionPerformed(e: AnActionEvent) { if (Application.isUnitTestMode) { return } val project = e.project executeOnPooledThread { if (project?.isDisposed == true) { return@executeOnPooledThread } val words = WordBookService.getWords() invokeLater { if (project?.isDisposed != true) { if (words.isNotEmpty()) { TranslationUIManager.showWordDialog(project, words) } else { val message = message("word.of.the.day.no.words") Popups.showBalloonForActiveFrame(message, MessageType.INFO) } } } } } }
Optimize show word of the day action
Optimize show word of the day action
Kotlin
mit
YiiGuxing/TranslationPlugin,YiiGuxing/TranslationPlugin
kotlin
## Code Before: @file:Suppress("InvalidBundleOrProperty") package cn.yiiguxing.plugin.translate.action import cn.yiiguxing.plugin.translate.message import cn.yiiguxing.plugin.translate.util.* import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAware import com.intellij.openapi.ui.MessageType /** * Show word of the day action. * * Created by Yii.Guxing on 2019/08/23. */ class ShowWordOfTheDayAction : AnAction(), DumbAware { private var isLoading: Boolean = false init { templatePresentation.description = message("word.of.the.day.title") } override fun actionPerformed(e: AnActionEvent) { if (Application.isUnitTestMode || isLoading) { return } isLoading = true val project = e.project executeOnPooledThread { if (project?.isDisposed == true) { return@executeOnPooledThread } val words = WordBookService.getWords() invokeLater { if (project?.isDisposed != true) { if (words.isNotEmpty()) { TranslationUIManager.showWordDialog(project, words) } else { val message = message("word.of.the.day.no.words") Popups.showBalloonForActiveFrame(message, MessageType.INFO) } } isLoading = false } } } } ## Instruction: Optimize show word of the day action ## Code After: @file:Suppress("InvalidBundleOrProperty") package cn.yiiguxing.plugin.translate.action import cn.yiiguxing.plugin.translate.message import cn.yiiguxing.plugin.translate.util.* import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAware import com.intellij.openapi.ui.MessageType /** * Show word of the day action. * * Created by Yii.Guxing on 2019/08/23. */ class ShowWordOfTheDayAction : AnAction(), DumbAware { init { templatePresentation.description = message("word.of.the.day.title") } override fun actionPerformed(e: AnActionEvent) { if (Application.isUnitTestMode) { return } val project = e.project executeOnPooledThread { if (project?.isDisposed == true) { return@executeOnPooledThread } val words = WordBookService.getWords() invokeLater { if (project?.isDisposed != true) { if (words.isNotEmpty()) { TranslationUIManager.showWordDialog(project, words) } else { val message = message("word.of.the.day.no.words") Popups.showBalloonForActiveFrame(message, MessageType.INFO) } } } } } }
... */ class ShowWordOfTheDayAction : AnAction(), DumbAware { init { templatePresentation.description = message("word.of.the.day.title") } override fun actionPerformed(e: AnActionEvent) { if (Application.isUnitTestMode) { return } val project = e.project executeOnPooledThread { if (project?.isDisposed == true) { ... Popups.showBalloonForActiveFrame(message, MessageType.INFO) } } } } } ...
22f94c5bb08ee6ae816109bdc06eab9e1974884a
app/models/cnes_professional.py
app/models/cnes_professional.py
from sqlalchemy import Column, Integer, String, func from app import db class CnesProfessional(db.Model): __tablename__ = 'cnes_professional' year = Column(Integer, primary_key=True) region = Column(String(1), primary_key=True) mesoregion = Column(String(4), primary_key=True) microregion = Column(String(5), primary_key=True) state = Column(String(2), primary_key=True) municipality = Column(String(7), primary_key=True) cnes = Column(String(7), primary_key=True) @classmethod def dimensions(cls): return [ 'year', 'region', 'mesoregion', 'microregion', 'state', 'municipality', ] @classmethod def aggregate(cls, value): return { 'professionals': func.count(cls.cnes) }[value] @classmethod def values(cls): return ['professionals']
from sqlalchemy import Column, Integer, String, func from app import db class CnesProfessional(db.Model): __tablename__ = 'cnes_professional' year = Column(Integer, primary_key=True) region = Column(String(1), primary_key=True) mesoregion = Column(String(4), primary_key=True) microregion = Column(String(5), primary_key=True) state = Column(String(2), primary_key=True) municipality = Column(String(7), primary_key=True) cnes = Column(String(7), primary_key=True) cbo = Column(String(2), primary_key=True) @classmethod def dimensions(cls): return [ 'year', 'region', 'mesoregion', 'microregion', 'state', 'municipality', 'cbo', ] @classmethod def aggregate(cls, value): return { 'professionals': func.count(cls.cnes) }[value] @classmethod def values(cls): return ['professionals']
Add CBO column to cnes professional
Add CBO column to cnes professional
Python
mit
daniel1409/dataviva-api,DataViva/dataviva-api
python
## Code Before: from sqlalchemy import Column, Integer, String, func from app import db class CnesProfessional(db.Model): __tablename__ = 'cnes_professional' year = Column(Integer, primary_key=True) region = Column(String(1), primary_key=True) mesoregion = Column(String(4), primary_key=True) microregion = Column(String(5), primary_key=True) state = Column(String(2), primary_key=True) municipality = Column(String(7), primary_key=True) cnes = Column(String(7), primary_key=True) @classmethod def dimensions(cls): return [ 'year', 'region', 'mesoregion', 'microregion', 'state', 'municipality', ] @classmethod def aggregate(cls, value): return { 'professionals': func.count(cls.cnes) }[value] @classmethod def values(cls): return ['professionals'] ## Instruction: Add CBO column to cnes professional ## Code After: from sqlalchemy import Column, Integer, String, func from app import db class CnesProfessional(db.Model): __tablename__ = 'cnes_professional' year = Column(Integer, primary_key=True) region = Column(String(1), primary_key=True) mesoregion = Column(String(4), primary_key=True) microregion = Column(String(5), primary_key=True) state = Column(String(2), primary_key=True) municipality = Column(String(7), primary_key=True) cnes = Column(String(7), primary_key=True) cbo = Column(String(2), primary_key=True) @classmethod def dimensions(cls): return [ 'year', 'region', 'mesoregion', 'microregion', 'state', 'municipality', 'cbo', ] @classmethod def aggregate(cls, value): return { 'professionals': func.count(cls.cnes) }[value] @classmethod def values(cls): return ['professionals']
... state = Column(String(2), primary_key=True) municipality = Column(String(7), primary_key=True) cnes = Column(String(7), primary_key=True) cbo = Column(String(2), primary_key=True) @classmethod def dimensions(cls): ... 'microregion', 'state', 'municipality', 'cbo', ] @classmethod ...
0f276a2da28b87e7e86d3becbf7f757f37f7f4ae
core/src/main/java/de/cdietze/ld37/core/MathUtils.java
core/src/main/java/de/cdietze/ld37/core/MathUtils.java
package de.cdietze.ld37.core; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class MathUtils { public static List<Integer> shuffledRange(int size, Random random) { ArrayList<Integer> list = new ArrayList<>(size); for (int i = 0; i < size; ++i) list.add(i); Collections.shuffle(list, random); return list; } }
package de.cdietze.ld37.core; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class MathUtils { public static List<Integer> shuffledRange(int size, Random random) { ArrayList<Integer> list = new ArrayList<>(size); for (int i = 0; i < size; ++i) list.add(i); shuffle(list, random); return list; } /** GWT does not emulate {@link java.util.Collections#shuffle(List, Random)} */ public static void shuffle(List<?> list, Random random) { for (int index = 0; index < list.size(); index += 1) { Collections.swap(list, index, index + random.nextInt(list.size() - index)); } } }
Fix for GWT’s missing collections.shuffle
Fix for GWT’s missing collections.shuffle
Java
apache-2.0
cdietze/ld37,cdietze/ld37
java
## Code Before: package de.cdietze.ld37.core; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class MathUtils { public static List<Integer> shuffledRange(int size, Random random) { ArrayList<Integer> list = new ArrayList<>(size); for (int i = 0; i < size; ++i) list.add(i); Collections.shuffle(list, random); return list; } } ## Instruction: Fix for GWT’s missing collections.shuffle ## Code After: package de.cdietze.ld37.core; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class MathUtils { public static List<Integer> shuffledRange(int size, Random random) { ArrayList<Integer> list = new ArrayList<>(size); for (int i = 0; i < size; ++i) list.add(i); shuffle(list, random); return list; } /** GWT does not emulate {@link java.util.Collections#shuffle(List, Random)} */ public static void shuffle(List<?> list, Random random) { for (int index = 0; index < list.size(); index += 1) { Collections.swap(list, index, index + random.nextInt(list.size() - index)); } } }
... public static List<Integer> shuffledRange(int size, Random random) { ArrayList<Integer> list = new ArrayList<>(size); for (int i = 0; i < size; ++i) list.add(i); shuffle(list, random); return list; } /** GWT does not emulate {@link java.util.Collections#shuffle(List, Random)} */ public static void shuffle(List<?> list, Random random) { for (int index = 0; index < list.size(); index += 1) { Collections.swap(list, index, index + random.nextInt(list.size() - index)); } } } ...
2aa415cae1cb7ed0bb2b7fdaf51d9d5eaceaa768
sweettooth/extensions/admin.py
sweettooth/extensions/admin.py
from django.contrib import admin from extensions.models import Extension, ExtensionVersion from extensions.models import STATUS_ACTIVE, STATUS_REJECTED from review.models import CodeReview class CodeReviewAdmin(admin.TabularInline): model = CodeReview fields = 'reviewer', 'comments', class ExtensionVersionAdmin(admin.ModelAdmin): list_display = 'title', 'status', list_display_links = 'title', actions = 'approve', 'reject', def title(self, ver): return "%s (%d)" % (ver.extension.uuid, ver.version) title.short_description = "Extension (version)" inlines = [CodeReviewAdmin] def approve(self, request, queryset): queryset.update(status=STATUS_ACTIVE) def reject(self, request, queryset): queryset.update(status=STATUS_REJECTED) admin.site.register(ExtensionVersion, ExtensionVersionAdmin) class ExtensionVersionInline(admin.TabularInline): model = ExtensionVersion fields = 'version', 'status', extra = 0 class ExtensionAdmin(admin.ModelAdmin): list_display = 'name', 'uuid', 'num_versions', 'creator', list_display_links = 'name', 'uuid', search_fields = ('uuid', 'name') def num_versions(self, ext): return ext.versions.count() num_versions.short_description = "#V" inlines = [ExtensionVersionInline] admin.site.register(Extension, ExtensionAdmin)
from django.contrib import admin from extensions.models import Extension, ExtensionVersion from extensions.models import STATUS_ACTIVE, STATUS_REJECTED from review.models import CodeReview class CodeReviewAdmin(admin.TabularInline): model = CodeReview fields = 'reviewer', 'comments', class ExtensionVersionAdmin(admin.ModelAdmin): list_display = 'title', 'status', list_display_links = 'title', actions = 'approve', 'reject', def title(self, ver): return "%s (%d)" % (ver.extension.uuid, ver.version) title.short_description = "Extension (version)" inlines = [CodeReviewAdmin] def approve(self, request, queryset): queryset.update(status=STATUS_ACTIVE) def reject(self, request, queryset): queryset.update(status=STATUS_REJECTED) admin.site.register(ExtensionVersion, ExtensionVersionAdmin) class ExtensionVersionInline(admin.TabularInline): model = ExtensionVersion fields = 'version', 'status', extra = 0 class ExtensionAdmin(admin.ModelAdmin): list_display = 'name', 'uuid', 'num_versions', 'creator', list_display_links = 'name', 'uuid', search_fields = ('uuid', 'name') raw_id_fields = ('user',) def num_versions(self, ext): return ext.versions.count() num_versions.short_description = "#V" inlines = [ExtensionVersionInline] admin.site.register(Extension, ExtensionAdmin)
Make the user field into a raw field
extensions: Make the user field into a raw field It's a bit annoying having to navigate through a 20,000 line combobox.
Python
agpl-3.0
GNOME/extensions-web,GNOME/extensions-web,GNOME/extensions-web,GNOME/extensions-web,magcius/sweettooth,magcius/sweettooth
python
## Code Before: from django.contrib import admin from extensions.models import Extension, ExtensionVersion from extensions.models import STATUS_ACTIVE, STATUS_REJECTED from review.models import CodeReview class CodeReviewAdmin(admin.TabularInline): model = CodeReview fields = 'reviewer', 'comments', class ExtensionVersionAdmin(admin.ModelAdmin): list_display = 'title', 'status', list_display_links = 'title', actions = 'approve', 'reject', def title(self, ver): return "%s (%d)" % (ver.extension.uuid, ver.version) title.short_description = "Extension (version)" inlines = [CodeReviewAdmin] def approve(self, request, queryset): queryset.update(status=STATUS_ACTIVE) def reject(self, request, queryset): queryset.update(status=STATUS_REJECTED) admin.site.register(ExtensionVersion, ExtensionVersionAdmin) class ExtensionVersionInline(admin.TabularInline): model = ExtensionVersion fields = 'version', 'status', extra = 0 class ExtensionAdmin(admin.ModelAdmin): list_display = 'name', 'uuid', 'num_versions', 'creator', list_display_links = 'name', 'uuid', search_fields = ('uuid', 'name') def num_versions(self, ext): return ext.versions.count() num_versions.short_description = "#V" inlines = [ExtensionVersionInline] admin.site.register(Extension, ExtensionAdmin) ## Instruction: extensions: Make the user field into a raw field It's a bit annoying having to navigate through a 20,000 line combobox. ## Code After: from django.contrib import admin from extensions.models import Extension, ExtensionVersion from extensions.models import STATUS_ACTIVE, STATUS_REJECTED from review.models import CodeReview class CodeReviewAdmin(admin.TabularInline): model = CodeReview fields = 'reviewer', 'comments', class ExtensionVersionAdmin(admin.ModelAdmin): list_display = 'title', 'status', list_display_links = 'title', actions = 'approve', 'reject', def title(self, ver): return "%s (%d)" % (ver.extension.uuid, ver.version) title.short_description = "Extension (version)" inlines = [CodeReviewAdmin] def approve(self, request, queryset): queryset.update(status=STATUS_ACTIVE) def reject(self, request, queryset): queryset.update(status=STATUS_REJECTED) admin.site.register(ExtensionVersion, ExtensionVersionAdmin) class ExtensionVersionInline(admin.TabularInline): model = ExtensionVersion fields = 'version', 'status', extra = 0 class ExtensionAdmin(admin.ModelAdmin): list_display = 'name', 'uuid', 'num_versions', 'creator', list_display_links = 'name', 'uuid', search_fields = ('uuid', 'name') raw_id_fields = ('user',) def num_versions(self, ext): return ext.versions.count() num_versions.short_description = "#V" inlines = [ExtensionVersionInline] admin.site.register(Extension, ExtensionAdmin)
# ... existing code ... list_display = 'name', 'uuid', 'num_versions', 'creator', list_display_links = 'name', 'uuid', search_fields = ('uuid', 'name') raw_id_fields = ('user',) def num_versions(self, ext): return ext.versions.count() # ... rest of the code ...
e383c0a6895e34e6fab255f236abbc1401015d4f
application/confagrid-webapp/src/main/java/com/aleggeup/confagrid/config/SecurityConfig.java
application/confagrid-webapp/src/main/java/com/aleggeup/confagrid/config/SecurityConfig.java
/* * SecurityConfig.java * * Copyright (C) 2017 [ A Legge Up ] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package com.aleggeup.confagrid.config; import java.security.SecureRandom; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.aleggeup.confagrid.filter.JwtFilter; @Configuration public class SecurityConfig { @Bean public FilterRegistrationBean jwtFilter() { final FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setFilter(new JwtFilter()); registrationBean.addUrlPatterns("/api/*"); return registrationBean; } @Bean public SecureRandom secureRandom() { return new SecureRandom(); } }
/* * SecurityConfig.java * * Copyright (C) 2017 [ A Legge Up ] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package com.aleggeup.confagrid.config; import java.security.SecureRandom; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.aleggeup.confagrid.filter.JwtFilter; @Configuration public class SecurityConfig { @Bean public FilterRegistrationBean jwtFilter() { final FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setFilter(new JwtFilter()); return registrationBean; } @Bean public SecureRandom secureRandom() { return new SecureRandom(); } }
Remove url pattern from filter so that it will filter all paths
Remove url pattern from filter so that it will filter all paths
Java
mit
ALeggeUp/confagrid,ALeggeUp/confagrid,ALeggeUp/confagrid,ALeggeUp/confagrid,ALeggeUp/confagrid
java
## Code Before: /* * SecurityConfig.java * * Copyright (C) 2017 [ A Legge Up ] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package com.aleggeup.confagrid.config; import java.security.SecureRandom; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.aleggeup.confagrid.filter.JwtFilter; @Configuration public class SecurityConfig { @Bean public FilterRegistrationBean jwtFilter() { final FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setFilter(new JwtFilter()); registrationBean.addUrlPatterns("/api/*"); return registrationBean; } @Bean public SecureRandom secureRandom() { return new SecureRandom(); } } ## Instruction: Remove url pattern from filter so that it will filter all paths ## Code After: /* * SecurityConfig.java * * Copyright (C) 2017 [ A Legge Up ] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package com.aleggeup.confagrid.config; import java.security.SecureRandom; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.aleggeup.confagrid.filter.JwtFilter; @Configuration public class SecurityConfig { @Bean public FilterRegistrationBean jwtFilter() { final FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setFilter(new JwtFilter()); return registrationBean; } @Bean public SecureRandom secureRandom() { return new SecureRandom(); } }
... public FilterRegistrationBean jwtFilter() { final FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setFilter(new JwtFilter()); return registrationBean; } ...
72dcc89d96935ba4336ebafed5252628ecf92ed4
stables/views.py
stables/views.py
from django.shortcuts import render from django.shortcuts import get_object_or_404 from django.views.generic.base import RedirectView from urllib.parse import quote from . import models class BadgeView(RedirectView): permanent = False def get_redirect_url(self, *args, **kwargs): status = get_object_or_404( models.PackageVersion, package__name=kwargs['package_name'], version=kwargs['package_version'], **{ 'result__installed_packages__%(factor_name)s' % kwargs: kwargs['factor_version'], } ) return quote( 'https://img.shields.io/badge/ 🐴 {} - {} -{}.svg'.format( *args ), )
from django.db.models import Q from django.shortcuts import render from django.shortcuts import get_object_or_404 from django.views.generic.base import RedirectView from urllib.parse import quote from . import models def badge_escape(val): return quote(val.replace('-', '--')) class BadgeView(RedirectView): permanent = False def get_redirect_url(self, *args, **kwargs): filter_arg = Q( package__name=kwargs['package_name'], ) try: filter_arg &= Q( version=kwargs['package_version'], ) except KeyError: pass try: filter_arg &= Q( result__installed_packages__contains={ kwargs['factor_name']: kwargs['factor_version'], }, ) except KeyError: try: filter_arg &= Q result__installed_packages__has_key=kwargs['factor_name'], ) status = get_object_or_404(models.PackageVersion, filter_arg) for result in status.result_set.objects.filter( color = { 'passed': 'green', }[kwargs['result'] return quote( u'https://img.shields.io/badge/ 🐴 Supports %s - %s -%s.svg' % ( badge_escape(kwargs['package_name']), badge_escape(kwargs['factor_name']), color, ), )
Update badge view with new model schema.
Update badge view with new model schema.
Python
mit
django-stables/django-stables,django-stables/django-stables
python
## Code Before: from django.shortcuts import render from django.shortcuts import get_object_or_404 from django.views.generic.base import RedirectView from urllib.parse import quote from . import models class BadgeView(RedirectView): permanent = False def get_redirect_url(self, *args, **kwargs): status = get_object_or_404( models.PackageVersion, package__name=kwargs['package_name'], version=kwargs['package_version'], **{ 'result__installed_packages__%(factor_name)s' % kwargs: kwargs['factor_version'], } ) return quote( 'https://img.shields.io/badge/ 🐴 {} - {} -{}.svg'.format( *args ), ) ## Instruction: Update badge view with new model schema. ## Code After: from django.db.models import Q from django.shortcuts import render from django.shortcuts import get_object_or_404 from django.views.generic.base import RedirectView from urllib.parse import quote from . import models def badge_escape(val): return quote(val.replace('-', '--')) class BadgeView(RedirectView): permanent = False def get_redirect_url(self, *args, **kwargs): filter_arg = Q( package__name=kwargs['package_name'], ) try: filter_arg &= Q( version=kwargs['package_version'], ) except KeyError: pass try: filter_arg &= Q( result__installed_packages__contains={ kwargs['factor_name']: kwargs['factor_version'], }, ) except KeyError: try: filter_arg &= Q result__installed_packages__has_key=kwargs['factor_name'], ) status = get_object_or_404(models.PackageVersion, filter_arg) for result in status.result_set.objects.filter( color = { 'passed': 'green', }[kwargs['result'] return quote( u'https://img.shields.io/badge/ 🐴 Supports %s - %s -%s.svg' % ( badge_escape(kwargs['package_name']), badge_escape(kwargs['factor_name']), color, ), )
# ... existing code ... from django.db.models import Q from django.shortcuts import render from django.shortcuts import get_object_or_404 from django.views.generic.base import RedirectView # ... modified code ... from . import models def badge_escape(val): return quote(val.replace('-', '--')) class BadgeView(RedirectView): permanent = False def get_redirect_url(self, *args, **kwargs): filter_arg = Q( package__name=kwargs['package_name'], ) try: filter_arg &= Q( version=kwargs['package_version'], ) except KeyError: pass try: filter_arg &= Q( result__installed_packages__contains={ kwargs['factor_name']: kwargs['factor_version'], }, ) except KeyError: try: filter_arg &= Q result__installed_packages__has_key=kwargs['factor_name'], ) status = get_object_or_404(models.PackageVersion, filter_arg) for result in status.result_set.objects.filter( color = { 'passed': 'green', }[kwargs['result'] return quote( u'https://img.shields.io/badge/ 🐴 Supports %s - %s -%s.svg' % ( badge_escape(kwargs['package_name']), badge_escape(kwargs['factor_name']), color, ), ) # ... rest of the code ...
03bbf925ab380044d24a9832da8ddd727b475cf6
src/main/kotlin/com/nkming/utils/unit/DimensionUtils.kt
src/main/kotlin/com/nkming/utils/unit/DimensionUtils.kt
package com.nkming.utils.unit; import android.content.Context; import android.util.DisplayMetrics; import android.util.TypedValue; class DimensionUtils { companion object { @JvmStatic fun dpToPx(context: Context, dp: Float): Float { val dm = context.resources.displayMetrics return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, dm) } @JvmStatic fun spToPx(context: Context, sp: Float): Float { val dm = context.resources.displayMetrics return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, dm) } @JvmStatic fun pxToDp(context: Context, px: Float): Float { val dm = context.resources.displayMetrics return px * (DisplayMetrics.DENSITY_DEFAULT / dm.densityDpi.toFloat()) } } }
package com.nkming.utils.unit; import android.content.Context import android.util.TypedValue class DimensionUtils { companion object { @JvmStatic fun dpToPx(context: Context, dp: Float): Float { val dm = context.resources.displayMetrics return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, dm) } @JvmStatic fun spToPx(context: Context, sp: Float): Float { val dm = context.resources.displayMetrics return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, dm) } @JvmStatic fun pxToDp(context: Context, px: Float): Float { val dm = context.resources.displayMetrics return px / dm.density } } } }
Use pre-calced density value instead
Use pre-calced density value instead
Kotlin
mit
nkming2/libutils-android,nkming2/libutils-android
kotlin
## Code Before: package com.nkming.utils.unit; import android.content.Context; import android.util.DisplayMetrics; import android.util.TypedValue; class DimensionUtils { companion object { @JvmStatic fun dpToPx(context: Context, dp: Float): Float { val dm = context.resources.displayMetrics return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, dm) } @JvmStatic fun spToPx(context: Context, sp: Float): Float { val dm = context.resources.displayMetrics return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, dm) } @JvmStatic fun pxToDp(context: Context, px: Float): Float { val dm = context.resources.displayMetrics return px * (DisplayMetrics.DENSITY_DEFAULT / dm.densityDpi.toFloat()) } } } ## Instruction: Use pre-calced density value instead ## Code After: package com.nkming.utils.unit; import android.content.Context import android.util.TypedValue class DimensionUtils { companion object { @JvmStatic fun dpToPx(context: Context, dp: Float): Float { val dm = context.resources.displayMetrics return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, dm) } @JvmStatic fun spToPx(context: Context, sp: Float): Float { val dm = context.resources.displayMetrics return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, dm) } @JvmStatic fun pxToDp(context: Context, px: Float): Float { val dm = context.resources.displayMetrics return px / dm.density } } } }
// ... existing code ... package com.nkming.utils.unit; import android.content.Context import android.util.TypedValue class DimensionUtils { // ... modified code ... fun pxToDp(context: Context, px: Float): Float { val dm = context.resources.displayMetrics return px / dm.density } } } } // ... rest of the code ...
f26e3716c848bf548d99015da6fb1a26bd975823
lambda-selenium-java/src/main/java/com/blackboard/testing/common/LambdaBaseTest.java
lambda-selenium-java/src/main/java/com/blackboard/testing/common/LambdaBaseTest.java
package com.blackboard.testing.common; import com.blackboard.testing.driver.LambdaWebDriverThreadLocalContainer; import com.blackboard.testing.testcontext.EnvironmentDetector; import com.codeborne.selenide.Configuration; import com.codeborne.selenide.WebDriverRunner; import com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName; import org.junit.BeforeClass; public abstract class LambdaBaseTest { @BeforeClass public static void baseTestBeforeClass() { Configuration.browser = BrowserName.CHROME.toString(); Configuration.reopenBrowserOnFail = false; if (EnvironmentDetector.inLambda()) { Configuration.reportsFolder = "/tmp/selenidereports"; WebDriverRunner.webdriverContainer = new LambdaWebDriverThreadLocalContainer(); } } }
package com.blackboard.testing.common; import com.blackboard.testing.driver.LambdaWebDriverThreadLocalContainer; import com.blackboard.testing.lambda.LambdaTestHandler; import com.blackboard.testing.testcontext.EnvironmentDetector; import com.codeborne.selenide.Configuration; import com.codeborne.selenide.Selenide; import com.codeborne.selenide.WebDriverRunner; import org.junit.BeforeClass; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; public abstract class LambdaBaseTest { @BeforeClass public static void baseTestBeforeClass() { Configuration.browser = "chrome"; Configuration.reopenBrowserOnFail = false; if (EnvironmentDetector.inLambda()) { WebDriverRunner.webdriverContainer = new LambdaWebDriverThreadLocalContainer(); } } protected void screenshot(String description) { if (EnvironmentDetector.inLambda()) { LambdaTestHandler.addAttachment(description + ".png", ((TakesScreenshot) WebDriverRunner.getWebDriver()) .getScreenshotAs(OutputType.BYTES)); } else { Selenide.screenshot(description); } } }
Add screenshot capability to base test
Add screenshot capability to base test
Java
mit
blackboard/lambda-selenium,blackboard/lambda-selenium
java
## Code Before: package com.blackboard.testing.common; import com.blackboard.testing.driver.LambdaWebDriverThreadLocalContainer; import com.blackboard.testing.testcontext.EnvironmentDetector; import com.codeborne.selenide.Configuration; import com.codeborne.selenide.WebDriverRunner; import com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName; import org.junit.BeforeClass; public abstract class LambdaBaseTest { @BeforeClass public static void baseTestBeforeClass() { Configuration.browser = BrowserName.CHROME.toString(); Configuration.reopenBrowserOnFail = false; if (EnvironmentDetector.inLambda()) { Configuration.reportsFolder = "/tmp/selenidereports"; WebDriverRunner.webdriverContainer = new LambdaWebDriverThreadLocalContainer(); } } } ## Instruction: Add screenshot capability to base test ## Code After: package com.blackboard.testing.common; import com.blackboard.testing.driver.LambdaWebDriverThreadLocalContainer; import com.blackboard.testing.lambda.LambdaTestHandler; import com.blackboard.testing.testcontext.EnvironmentDetector; import com.codeborne.selenide.Configuration; import com.codeborne.selenide.Selenide; import com.codeborne.selenide.WebDriverRunner; import org.junit.BeforeClass; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; public abstract class LambdaBaseTest { @BeforeClass public static void baseTestBeforeClass() { Configuration.browser = "chrome"; Configuration.reopenBrowserOnFail = false; if (EnvironmentDetector.inLambda()) { WebDriverRunner.webdriverContainer = new LambdaWebDriverThreadLocalContainer(); } } protected void screenshot(String description) { if (EnvironmentDetector.inLambda()) { LambdaTestHandler.addAttachment(description + ".png", ((TakesScreenshot) WebDriverRunner.getWebDriver()) .getScreenshotAs(OutputType.BYTES)); } else { Selenide.screenshot(description); } } }
# ... existing code ... package com.blackboard.testing.common; import com.blackboard.testing.driver.LambdaWebDriverThreadLocalContainer; import com.blackboard.testing.lambda.LambdaTestHandler; import com.blackboard.testing.testcontext.EnvironmentDetector; import com.codeborne.selenide.Configuration; import com.codeborne.selenide.Selenide; import com.codeborne.selenide.WebDriverRunner; import org.junit.BeforeClass; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; public abstract class LambdaBaseTest { @BeforeClass public static void baseTestBeforeClass() { Configuration.browser = "chrome"; Configuration.reopenBrowserOnFail = false; if (EnvironmentDetector.inLambda()) { WebDriverRunner.webdriverContainer = new LambdaWebDriverThreadLocalContainer(); } } protected void screenshot(String description) { if (EnvironmentDetector.inLambda()) { LambdaTestHandler.addAttachment(description + ".png", ((TakesScreenshot) WebDriverRunner.getWebDriver()) .getScreenshotAs(OutputType.BYTES)); } else { Selenide.screenshot(description); } } } # ... rest of the code ...
a03fe14d4dba7b9a54efdebeb768551bda53e3c1
admin/common_auth/models.py
admin/common_auth/models.py
from django.db import models class AdminProfile(models.Model): user = models.OneToOneField('osf.OSFUser', related_name='admin_profile') desk_token = models.CharField(max_length=45, blank=True) desk_token_secret = models.CharField(max_length=45, blank=True) class Meta: # custom permissions for use in the OSF Admin App permissions = ( ('mark_spam', 'Can mark comments, projects and registrations as spam'), ('view_spam', 'Can view nodes, comments, and projects marked as spam'), ('view_metrics', 'Can view metrics on the OSF Admin app'), ('view_prereg', 'Can view entries for the preregistration chellenge on the admin'), ('administer_prereg', 'Can update, comment on, and approve entries to the prereg challenge'), ('view_desk', 'Can view details about Desk users'), )
from django.db import models class AdminProfile(models.Model): user = models.OneToOneField('osf.OSFUser', related_name='admin_profile') desk_token = models.CharField(max_length=45, blank=True) desk_token_secret = models.CharField(max_length=45, blank=True) def __unicode__(self): return self.user.username class Meta: # custom permissions for use in the OSF Admin App permissions = ( ('mark_spam', 'Can mark comments, projects and registrations as spam'), ('view_spam', 'Can view nodes, comments, and projects marked as spam'), ('view_metrics', 'Can view metrics on the OSF Admin app'), ('view_prereg', 'Can view entries for the preregistration chellenge on the admin'), ('administer_prereg', 'Can update, comment on, and approve entries to the prereg challenge'), ('view_desk', 'Can view details about Desk users'), )
Fix the display name of admin profile in the admin admin
Fix the display name of admin profile in the admin admin
Python
apache-2.0
HalcyonChimera/osf.io,sloria/osf.io,CenterForOpenScience/osf.io,hmoco/osf.io,sloria/osf.io,chrisseto/osf.io,caneruguz/osf.io,monikagrabowska/osf.io,CenterForOpenScience/osf.io,icereval/osf.io,icereval/osf.io,TomBaxter/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,cslzchen/osf.io,felliott/osf.io,chennan47/osf.io,binoculars/osf.io,monikagrabowska/osf.io,binoculars/osf.io,crcresearch/osf.io,brianjgeiger/osf.io,Nesiehr/osf.io,leb2dg/osf.io,icereval/osf.io,HalcyonChimera/osf.io,Johnetordoff/osf.io,adlius/osf.io,Nesiehr/osf.io,leb2dg/osf.io,caseyrollins/osf.io,Johnetordoff/osf.io,cwisecarver/osf.io,pattisdr/osf.io,saradbowman/osf.io,baylee-d/osf.io,Johnetordoff/osf.io,adlius/osf.io,leb2dg/osf.io,chennan47/osf.io,monikagrabowska/osf.io,laurenrevere/osf.io,acshi/osf.io,aaxelb/osf.io,cslzchen/osf.io,caneruguz/osf.io,sloria/osf.io,laurenrevere/osf.io,adlius/osf.io,Nesiehr/osf.io,CenterForOpenScience/osf.io,caneruguz/osf.io,chrisseto/osf.io,pattisdr/osf.io,cslzchen/osf.io,brianjgeiger/osf.io,mfraezz/osf.io,acshi/osf.io,erinspace/osf.io,mattclark/osf.io,baylee-d/osf.io,chennan47/osf.io,acshi/osf.io,crcresearch/osf.io,monikagrabowska/osf.io,hmoco/osf.io,hmoco/osf.io,aaxelb/osf.io,cwisecarver/osf.io,aaxelb/osf.io,TomBaxter/osf.io,binoculars/osf.io,adlius/osf.io,felliott/osf.io,leb2dg/osf.io,HalcyonChimera/osf.io,pattisdr/osf.io,felliott/osf.io,saradbowman/osf.io,felliott/osf.io,laurenrevere/osf.io,caneruguz/osf.io,cwisecarver/osf.io,chrisseto/osf.io,acshi/osf.io,chrisseto/osf.io,acshi/osf.io,baylee-d/osf.io,mfraezz/osf.io,monikagrabowska/osf.io,cslzchen/osf.io,mfraezz/osf.io,caseyrollins/osf.io,brianjgeiger/osf.io,hmoco/osf.io,caseyrollins/osf.io,mattclark/osf.io,mfraezz/osf.io,CenterForOpenScience/osf.io,erinspace/osf.io,HalcyonChimera/osf.io,Nesiehr/osf.io,crcresearch/osf.io,mattclark/osf.io,cwisecarver/osf.io,TomBaxter/osf.io,erinspace/osf.io,Johnetordoff/osf.io
python
## Code Before: from django.db import models class AdminProfile(models.Model): user = models.OneToOneField('osf.OSFUser', related_name='admin_profile') desk_token = models.CharField(max_length=45, blank=True) desk_token_secret = models.CharField(max_length=45, blank=True) class Meta: # custom permissions for use in the OSF Admin App permissions = ( ('mark_spam', 'Can mark comments, projects and registrations as spam'), ('view_spam', 'Can view nodes, comments, and projects marked as spam'), ('view_metrics', 'Can view metrics on the OSF Admin app'), ('view_prereg', 'Can view entries for the preregistration chellenge on the admin'), ('administer_prereg', 'Can update, comment on, and approve entries to the prereg challenge'), ('view_desk', 'Can view details about Desk users'), ) ## Instruction: Fix the display name of admin profile in the admin admin ## Code After: from django.db import models class AdminProfile(models.Model): user = models.OneToOneField('osf.OSFUser', related_name='admin_profile') desk_token = models.CharField(max_length=45, blank=True) desk_token_secret = models.CharField(max_length=45, blank=True) def __unicode__(self): return self.user.username class Meta: # custom permissions for use in the OSF Admin App permissions = ( ('mark_spam', 'Can mark comments, projects and registrations as spam'), ('view_spam', 'Can view nodes, comments, and projects marked as spam'), ('view_metrics', 'Can view metrics on the OSF Admin app'), ('view_prereg', 'Can view entries for the preregistration chellenge on the admin'), ('administer_prereg', 'Can update, comment on, and approve entries to the prereg challenge'), ('view_desk', 'Can view details about Desk users'), )
# ... existing code ... desk_token = models.CharField(max_length=45, blank=True) desk_token_secret = models.CharField(max_length=45, blank=True) def __unicode__(self): return self.user.username class Meta: # custom permissions for use in the OSF Admin App # ... rest of the code ...
5eaca14a3ddf7515f5b855aee4b58d21048ca9a9
avena/utils.py
avena/utils.py
from os.path import exists, splitext from random import randint _depth = lambda x, y, z=1: z _invert_dict = lambda d: dict((v, k) for k, v in list(d.items())) _PREFERRED_RGB = { 'R': 0, 'G': 1, 'B': 2, } def depth(array): '''Return the depth (the third dimension) of an array.''' return _depth(*array.shape) def rand_filename(filename, ext=None): '''Return a unique file name based on the given file name.''' file_name, file_ext = splitext(filename) if ext is None: ext = file_ext while True: rand_file_name = file_name rand_file_name += '-' rand_file_name += str(randint(0, 10000)) rand_file_name += ext if not exists(rand_file_name): break return rand_file_name def swap_rgb(img, current, to): '''Swap the RBG channels of an image array.''' if depth(img) == 3 and not current == to: current_indices = list(map(current.get, ('R', 'G', 'B'))) to_indices = list(map(to.get, ('R', 'G', 'B'))) img[:, :, current_indices] = img[:, :, to_indices] if __name__ == '__main__': pass
from os.path import exists, splitext from random import randint def _depth(x, y, z=1): return z _invert_dict = lambda d: dict((v, k) for k, v in list(d.items())) _PREFERRED_RGB = { 'R': 0, 'G': 1, 'B': 2, } def depth(array): '''Return the depth (the third dimension) of an array.''' return _depth(*array.shape) def rand_filename(filename, ext=None): '''Return a unique file name based on the given file name.''' file_name, file_ext = splitext(filename) if ext is None: ext = file_ext while True: rand_file_name = file_name rand_file_name += '-' rand_file_name += str(randint(0, 10000)) rand_file_name += ext if not exists(rand_file_name): break return rand_file_name def swap_rgb(img, current, to): '''Swap the RBG channels of an image array.''' if depth(img) == 3 and not current == to: current_indices = list(map(current.get, ('R', 'G', 'B'))) to_indices = list(map(to.get, ('R', 'G', 'B'))) img[:, :, current_indices] = img[:, :, to_indices] if __name__ == '__main__': pass
Use a function instead of a lambda expression.
Use a function instead of a lambda expression.
Python
isc
eliteraspberries/avena
python
## Code Before: from os.path import exists, splitext from random import randint _depth = lambda x, y, z=1: z _invert_dict = lambda d: dict((v, k) for k, v in list(d.items())) _PREFERRED_RGB = { 'R': 0, 'G': 1, 'B': 2, } def depth(array): '''Return the depth (the third dimension) of an array.''' return _depth(*array.shape) def rand_filename(filename, ext=None): '''Return a unique file name based on the given file name.''' file_name, file_ext = splitext(filename) if ext is None: ext = file_ext while True: rand_file_name = file_name rand_file_name += '-' rand_file_name += str(randint(0, 10000)) rand_file_name += ext if not exists(rand_file_name): break return rand_file_name def swap_rgb(img, current, to): '''Swap the RBG channels of an image array.''' if depth(img) == 3 and not current == to: current_indices = list(map(current.get, ('R', 'G', 'B'))) to_indices = list(map(to.get, ('R', 'G', 'B'))) img[:, :, current_indices] = img[:, :, to_indices] if __name__ == '__main__': pass ## Instruction: Use a function instead of a lambda expression. ## Code After: from os.path import exists, splitext from random import randint def _depth(x, y, z=1): return z _invert_dict = lambda d: dict((v, k) for k, v in list(d.items())) _PREFERRED_RGB = { 'R': 0, 'G': 1, 'B': 2, } def depth(array): '''Return the depth (the third dimension) of an array.''' return _depth(*array.shape) def rand_filename(filename, ext=None): '''Return a unique file name based on the given file name.''' file_name, file_ext = splitext(filename) if ext is None: ext = file_ext while True: rand_file_name = file_name rand_file_name += '-' rand_file_name += str(randint(0, 10000)) rand_file_name += ext if not exists(rand_file_name): break return rand_file_name def swap_rgb(img, current, to): '''Swap the RBG channels of an image array.''' if depth(img) == 3 and not current == to: current_indices = list(map(current.get, ('R', 'G', 'B'))) to_indices = list(map(to.get, ('R', 'G', 'B'))) img[:, :, current_indices] = img[:, :, to_indices] if __name__ == '__main__': pass
// ... existing code ... from random import randint def _depth(x, y, z=1): return z _invert_dict = lambda d: dict((v, k) for k, v in list(d.items())) // ... rest of the code ...
4f6976449ce55089a823edf14365587da25c6a68
src/main/java/com/maddenabbott/jenny/Application.java
src/main/java/com/maddenabbott/jenny/Application.java
package com.maddenabbott.jenny; /** * The main entry point for Jenny. */ public class Application { private static final String defaultCommand = "help"; public static void main(String[] args) { String commandName = getCommandName(args, defaultCommand); } private static String getCommandName(final String[] args, final String defaultCommandName) { if (args.length > 0 && args[0] != null) { return args[0]; } else { return defaultCommandName; } } }
package com.maddenabbott.jenny; import java.util.Arrays; /** * The main entry point for Jenny. */ public class Application { private static final String defaultCommand = "help"; public static void main(String[] args) { String commandName = getCommandName(args, defaultCommand); String[] parameters = getParameters(args); } private static String getCommandName(final String[] args, final String defaultCommandName) { if (args.length > 0 && args[0] != null) { return args[0]; } else { return defaultCommandName; } } private static String[] getParameters(final String[] args) { if (args.length > 1) { return Arrays.copyOfRange(args, 1, args.length); } return new String[]{ }; } }
Add method to extract parameters from command line args.
Add method to extract parameters from command line args.
Java
mit
jenny-the-generator/jenny,jenny-the-generator/jenny
java
## Code Before: package com.maddenabbott.jenny; /** * The main entry point for Jenny. */ public class Application { private static final String defaultCommand = "help"; public static void main(String[] args) { String commandName = getCommandName(args, defaultCommand); } private static String getCommandName(final String[] args, final String defaultCommandName) { if (args.length > 0 && args[0] != null) { return args[0]; } else { return defaultCommandName; } } } ## Instruction: Add method to extract parameters from command line args. ## Code After: package com.maddenabbott.jenny; import java.util.Arrays; /** * The main entry point for Jenny. */ public class Application { private static final String defaultCommand = "help"; public static void main(String[] args) { String commandName = getCommandName(args, defaultCommand); String[] parameters = getParameters(args); } private static String getCommandName(final String[] args, final String defaultCommandName) { if (args.length > 0 && args[0] != null) { return args[0]; } else { return defaultCommandName; } } private static String[] getParameters(final String[] args) { if (args.length > 1) { return Arrays.copyOfRange(args, 1, args.length); } return new String[]{ }; } }
// ... existing code ... package com.maddenabbott.jenny; import java.util.Arrays; /** * The main entry point for Jenny. // ... modified code ... public static void main(String[] args) { String commandName = getCommandName(args, defaultCommand); String[] parameters = getParameters(args); } private static String getCommandName(final String[] args, final String defaultCommandName) { ... return defaultCommandName; } } private static String[] getParameters(final String[] args) { if (args.length > 1) { return Arrays.copyOfRange(args, 1, args.length); } return new String[]{ }; } } // ... rest of the code ...
628ab56107783841d1e64b11c4b82eac4806c019
selenium_testcase/testcases/content.py
selenium_testcase/testcases/content.py
from __future__ import absolute_import from .utils import dom_contains, wait_for class ContentTestMixin: # Assert that the DOM contains the given text def should_see_immediately(self, text): self.assertTrue(dom_contains(self.browser, text)) # Repeatedly look for the given text until it appears (or we give up) @wait_for def should_see(self, text): """ Wait for text to appear before raising assertion. """ return self.should_see_immediately(text) @wait_for def has_title(self, title): """ Assert when page title does not match. """ self.assertEqual(self.browser.title, title)
from __future__ import absolute_import from .utils import dom_contains, wait_for class ContentTestMixin: def should_see_immediately(self, text): """ Assert that DOM contains the given text. """ self.assertTrue(dom_contains(self.browser, text)) @wait_for def should_see(self, text): """ Wait for text to appear before testing assertion. """ return self.should_see_immediately(text) def should_not_see(self, text): """ Wait for text to not appear before testing assertion. """ self.assertRaises(AssertionError, self.should_see, text) @wait_for def has_title(self, title): """ Assert that page title matches. """ self.assertEqual(self.browser.title, title) def has_not_title(self, title): """ Assert when page title does not match. """ self.assertRaises(AssertionError, self.has_title, title) @wait_for def title_contains(self, text): """ Assert that page title contains text. """ self.assertIn(text, self.browser.title) def title_does_not_contain(self, text): """ Assert that page title does not contain text. """ self.assertRaises(AssertionError, self.title_contains, text)
Add should_not_see, has_not_title, title_does_not_contain to ContentTestMixin.
Add should_not_see, has_not_title, title_does_not_contain to ContentTestMixin. These methods cause a wait for the full duration of the @wait_for timeout when the assertion test is successful (and the given text is missing). It will fail fast, but success is slow. These negative information tests should be used sparingly.
Python
bsd-3-clause
nimbis/django-selenium-testcase,nimbis/django-selenium-testcase
python
## Code Before: from __future__ import absolute_import from .utils import dom_contains, wait_for class ContentTestMixin: # Assert that the DOM contains the given text def should_see_immediately(self, text): self.assertTrue(dom_contains(self.browser, text)) # Repeatedly look for the given text until it appears (or we give up) @wait_for def should_see(self, text): """ Wait for text to appear before raising assertion. """ return self.should_see_immediately(text) @wait_for def has_title(self, title): """ Assert when page title does not match. """ self.assertEqual(self.browser.title, title) ## Instruction: Add should_not_see, has_not_title, title_does_not_contain to ContentTestMixin. These methods cause a wait for the full duration of the @wait_for timeout when the assertion test is successful (and the given text is missing). It will fail fast, but success is slow. These negative information tests should be used sparingly. ## Code After: from __future__ import absolute_import from .utils import dom_contains, wait_for class ContentTestMixin: def should_see_immediately(self, text): """ Assert that DOM contains the given text. """ self.assertTrue(dom_contains(self.browser, text)) @wait_for def should_see(self, text): """ Wait for text to appear before testing assertion. """ return self.should_see_immediately(text) def should_not_see(self, text): """ Wait for text to not appear before testing assertion. """ self.assertRaises(AssertionError, self.should_see, text) @wait_for def has_title(self, title): """ Assert that page title matches. """ self.assertEqual(self.browser.title, title) def has_not_title(self, title): """ Assert when page title does not match. """ self.assertRaises(AssertionError, self.has_title, title) @wait_for def title_contains(self, text): """ Assert that page title contains text. """ self.assertIn(text, self.browser.title) def title_does_not_contain(self, text): """ Assert that page title does not contain text. """ self.assertRaises(AssertionError, self.title_contains, text)
... class ContentTestMixin: def should_see_immediately(self, text): """ Assert that DOM contains the given text. """ self.assertTrue(dom_contains(self.browser, text)) @wait_for def should_see(self, text): """ Wait for text to appear before testing assertion. """ return self.should_see_immediately(text) def should_not_see(self, text): """ Wait for text to not appear before testing assertion. """ self.assertRaises(AssertionError, self.should_see, text) @wait_for def has_title(self, title): """ Assert that page title matches. """ self.assertEqual(self.browser.title, title) def has_not_title(self, title): """ Assert when page title does not match. """ self.assertRaises(AssertionError, self.has_title, title) @wait_for def title_contains(self, text): """ Assert that page title contains text. """ self.assertIn(text, self.browser.title) def title_does_not_contain(self, text): """ Assert that page title does not contain text. """ self.assertRaises(AssertionError, self.title_contains, text) ...
5f7ed2e836e566559ac8d382f4a651c4454d8267
strongbox-storage/strongbox-storage-api/src/main/java/org/carlspring/strongbox/dependency/snippet/CodeSnippet.java
strongbox-storage/strongbox-storage-api/src/main/java/org/carlspring/strongbox/dependency/snippet/CodeSnippet.java
package org.carlspring.strongbox.dependency.snippet; import javax.annotation.Nonnull; public class CodeSnippet implements Comparable<CodeSnippet> { protected String name; protected String code; public CodeSnippet(String name, String code) { this.name = name; this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } @Override public int compareTo(@Nonnull CodeSnippet codeSnippet) { return name.compareTo(codeSnippet.getName()); } }
package org.carlspring.strongbox.dependency.snippet; import javax.annotation.Nonnull; import java.util.Objects; public class CodeSnippet implements Comparable<CodeSnippet> { protected String name; protected String code; public CodeSnippet(String name, String code) { this.name = name; this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } @Override public int compareTo(@Nonnull CodeSnippet codeSnippet) { return name.compareTo(codeSnippet.getName()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CodeSnippet snippet = (CodeSnippet) o; return Objects.equals(name, snippet.name) && Objects.equals(code, snippet.code); } @Override public int hashCode() { return Objects.hash(name, code); } }
Sort the artifact dependency synonyms by main layout provider and then alphabetic order
SB-1160: Sort the artifact dependency synonyms by main layout provider and then alphabetic order Sonar: Added equals() and hashCode() implementations.
Java
apache-2.0
strongbox/strongbox,sbespalov/strongbox,strongbox/strongbox,sbespalov/strongbox,strongbox/strongbox,strongbox/strongbox,sbespalov/strongbox,sbespalov/strongbox
java
## Code Before: package org.carlspring.strongbox.dependency.snippet; import javax.annotation.Nonnull; public class CodeSnippet implements Comparable<CodeSnippet> { protected String name; protected String code; public CodeSnippet(String name, String code) { this.name = name; this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } @Override public int compareTo(@Nonnull CodeSnippet codeSnippet) { return name.compareTo(codeSnippet.getName()); } } ## Instruction: SB-1160: Sort the artifact dependency synonyms by main layout provider and then alphabetic order Sonar: Added equals() and hashCode() implementations. ## Code After: package org.carlspring.strongbox.dependency.snippet; import javax.annotation.Nonnull; import java.util.Objects; public class CodeSnippet implements Comparable<CodeSnippet> { protected String name; protected String code; public CodeSnippet(String name, String code) { this.name = name; this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } @Override public int compareTo(@Nonnull CodeSnippet codeSnippet) { return name.compareTo(codeSnippet.getName()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CodeSnippet snippet = (CodeSnippet) o; return Objects.equals(name, snippet.name) && Objects.equals(code, snippet.code); } @Override public int hashCode() { return Objects.hash(name, code); } }
... package org.carlspring.strongbox.dependency.snippet; import javax.annotation.Nonnull; import java.util.Objects; public class CodeSnippet implements Comparable<CodeSnippet> ... return name.compareTo(codeSnippet.getName()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CodeSnippet snippet = (CodeSnippet) o; return Objects.equals(name, snippet.name) && Objects.equals(code, snippet.code); } @Override public int hashCode() { return Objects.hash(name, code); } } ...
8f15aaaa97c543496d7e934d1c16a0ceab49f342
shims/build.gradle.kts
shims/build.gradle.kts
// See https://blog.gradle.org/mrjars and https://github.com/melix/mrjar-gradle for more on multi release jars sourceSets { create("java11") { java { srcDir("src/java11/main") } } } tasks.named<JavaCompile>("compileJava11Java") { // Arrays.equals exists since JDK9, but the intent is to only use it on Java 11+, it seems. sourceCompatibility = "9" targetCompatibility = "9" } tasks.named<Jar>("jar") { into("META-INF/versions/11") { from(sourceSets.named("java11").get().output) } manifest.attributes( Pair("Multi-Release", "true") ) }
// See https://blog.gradle.org/mrjars and https://github.com/melix/mrjar-gradle for more on multi release jars sourceSets { create("java11") { java { srcDir("src/java11/main") } } } tasks.named<JavaCompile>("compileJava11Java") { // Arrays.equals exists since JDK9, but we make it available for 11+ so we can test the shim by using Java 11 // and the old way by using Java 10, which will compile the new code but not use it.. sourceCompatibility = "9" targetCompatibility = "9" } tasks.named<Jar>("jar") { into("META-INF/versions/11") { from(sourceSets.named("java11").get().output) } manifest.attributes( Pair("Multi-Release", "true") ) // normally jar is just main classes but we also have another sourceset dependsOn(tasks.named("compileJava11Java")) }
Tweak shims build to include shims in all cases
Tweak shims build to include shims in all cases
Kotlin
apache-2.0
lemire/RoaringBitmap,lemire/RoaringBitmap,lemire/RoaringBitmap,lemire/RoaringBitmap
kotlin
## Code Before: // See https://blog.gradle.org/mrjars and https://github.com/melix/mrjar-gradle for more on multi release jars sourceSets { create("java11") { java { srcDir("src/java11/main") } } } tasks.named<JavaCompile>("compileJava11Java") { // Arrays.equals exists since JDK9, but the intent is to only use it on Java 11+, it seems. sourceCompatibility = "9" targetCompatibility = "9" } tasks.named<Jar>("jar") { into("META-INF/versions/11") { from(sourceSets.named("java11").get().output) } manifest.attributes( Pair("Multi-Release", "true") ) } ## Instruction: Tweak shims build to include shims in all cases ## Code After: // See https://blog.gradle.org/mrjars and https://github.com/melix/mrjar-gradle for more on multi release jars sourceSets { create("java11") { java { srcDir("src/java11/main") } } } tasks.named<JavaCompile>("compileJava11Java") { // Arrays.equals exists since JDK9, but we make it available for 11+ so we can test the shim by using Java 11 // and the old way by using Java 10, which will compile the new code but not use it.. sourceCompatibility = "9" targetCompatibility = "9" } tasks.named<Jar>("jar") { into("META-INF/versions/11") { from(sourceSets.named("java11").get().output) } manifest.attributes( Pair("Multi-Release", "true") ) // normally jar is just main classes but we also have another sourceset dependsOn(tasks.named("compileJava11Java")) }
# ... existing code ... } tasks.named<JavaCompile>("compileJava11Java") { // Arrays.equals exists since JDK9, but we make it available for 11+ so we can test the shim by using Java 11 // and the old way by using Java 10, which will compile the new code but not use it.. sourceCompatibility = "9" targetCompatibility = "9" } # ... modified code ... manifest.attributes( Pair("Multi-Release", "true") ) // normally jar is just main classes but we also have another sourceset dependsOn(tasks.named("compileJava11Java")) } # ... rest of the code ...
ca1ecf4ffd8df93ede673896c82e0b160bd7ef16
worker/build.gradle.kts
worker/build.gradle.kts
plugins { id("java") id("application") } application { mainClassName = "com.github.k0kubun.gitstar_ranking.Main" } repositories { mavenCentral() } dependencies { compile("ch.qos.logback:logback-classic:1.3.0-alpha4") compile("com.google.guava:guava:21.0") compile("com.google.http-client:google-http-client:1.22.0") compile("io.sentry:sentry:1.5.2") compile("javax.json:javax.json-api:1.1") compile("javax.ws.rs:javax.ws.rs-api:2.0.1") compile("org.postgresql:postgresql:42.2.19") compile("org.antlr:stringtemplate:3.2.1") // Using ST3 because ST4 isn"t supported by JDBI 2 compile("org.glassfish:javax.json:1.1") compile("org.jboss.resteasy:resteasy-jackson2-provider:3.1.2.Final") compile("org.jdbi:jdbi:2.78") testCompile("junit:junit:4.12") }
plugins { id("java") id("application") } application { mainClass.set("com.github.k0kubun.gitstar_ranking.Main") } repositories { mavenCentral() } dependencies { implementation("ch.qos.logback:logback-classic:1.3.0-alpha4") implementation("com.google.guava:guava:21.0") implementation("com.google.http-client:google-http-client:1.22.0") implementation("io.sentry:sentry:1.5.2") implementation("javax.json:javax.json-api:1.1") implementation("javax.ws.rs:javax.ws.rs-api:2.0.1") implementation("org.postgresql:postgresql:42.2.19") implementation("org.antlr:stringtemplate:3.2.1") // Using ST3 because ST4 isn"t supported by JDBI 2 implementation("org.glassfish:javax.json:1.1") implementation("org.jboss.resteasy:resteasy-jackson2-provider:3.1.2.Final") implementation("org.jdbi:jdbi:2.78") testImplementation("junit:junit:4.12") }
Fix deprecation warnings in the Gradle config
Fix deprecation warnings in the Gradle config
Kotlin
mit
k0kubun/github-ranking,k0kubun/githubranking,k0kubun/github-ranking,k0kubun/githubranking,k0kubun/github-ranking,k0kubun/githubranking,k0kubun/github-ranking,k0kubun/githubranking,k0kubun/githubranking,k0kubun/github-ranking
kotlin
## Code Before: plugins { id("java") id("application") } application { mainClassName = "com.github.k0kubun.gitstar_ranking.Main" } repositories { mavenCentral() } dependencies { compile("ch.qos.logback:logback-classic:1.3.0-alpha4") compile("com.google.guava:guava:21.0") compile("com.google.http-client:google-http-client:1.22.0") compile("io.sentry:sentry:1.5.2") compile("javax.json:javax.json-api:1.1") compile("javax.ws.rs:javax.ws.rs-api:2.0.1") compile("org.postgresql:postgresql:42.2.19") compile("org.antlr:stringtemplate:3.2.1") // Using ST3 because ST4 isn"t supported by JDBI 2 compile("org.glassfish:javax.json:1.1") compile("org.jboss.resteasy:resteasy-jackson2-provider:3.1.2.Final") compile("org.jdbi:jdbi:2.78") testCompile("junit:junit:4.12") } ## Instruction: Fix deprecation warnings in the Gradle config ## Code After: plugins { id("java") id("application") } application { mainClass.set("com.github.k0kubun.gitstar_ranking.Main") } repositories { mavenCentral() } dependencies { implementation("ch.qos.logback:logback-classic:1.3.0-alpha4") implementation("com.google.guava:guava:21.0") implementation("com.google.http-client:google-http-client:1.22.0") implementation("io.sentry:sentry:1.5.2") implementation("javax.json:javax.json-api:1.1") implementation("javax.ws.rs:javax.ws.rs-api:2.0.1") implementation("org.postgresql:postgresql:42.2.19") implementation("org.antlr:stringtemplate:3.2.1") // Using ST3 because ST4 isn"t supported by JDBI 2 implementation("org.glassfish:javax.json:1.1") implementation("org.jboss.resteasy:resteasy-jackson2-provider:3.1.2.Final") implementation("org.jdbi:jdbi:2.78") testImplementation("junit:junit:4.12") }
... } application { mainClass.set("com.github.k0kubun.gitstar_ranking.Main") } repositories { ... } dependencies { implementation("ch.qos.logback:logback-classic:1.3.0-alpha4") implementation("com.google.guava:guava:21.0") implementation("com.google.http-client:google-http-client:1.22.0") implementation("io.sentry:sentry:1.5.2") implementation("javax.json:javax.json-api:1.1") implementation("javax.ws.rs:javax.ws.rs-api:2.0.1") implementation("org.postgresql:postgresql:42.2.19") implementation("org.antlr:stringtemplate:3.2.1") // Using ST3 because ST4 isn"t supported by JDBI 2 implementation("org.glassfish:javax.json:1.1") implementation("org.jboss.resteasy:resteasy-jackson2-provider:3.1.2.Final") implementation("org.jdbi:jdbi:2.78") testImplementation("junit:junit:4.12") } ...
b1a28600e6b97ab020c69ff410aebd962b4e1e93
testproject/tablib_test/tests.py
testproject/tablib_test/tests.py
from django.test import TestCase from django_tablib import ModelDataset, Field from .models import TestModel class DjangoTablibTestCase(TestCase): def setUp(self): TestModel.objects.create(field1='value') def test_declarative_fields(self): class TestModelDataset(ModelDataset): field1 = Field(header='Field 1') field2 = Field(attribute='field1') class Meta: model = TestModel data = TestModelDataset() self.assertEqual(len(data.headers), 3) self.assertTrue('id' in data.headers) self.assertFalse('field1' in data.headers) self.assertTrue('field2' in data.headers) self.assertTrue('Field 1' in data.headers) self.assertEqual(data[0][0], data[0][1])
from django.test import TestCase from django_tablib import ModelDataset, Field from .models import TestModel class DjangoTablibTestCase(TestCase): def setUp(self): TestModel.objects.create(field1='value') def test_declarative_fields(self): class TestModelDataset(ModelDataset): field1 = Field(header='Field 1') field2 = Field(attribute='field1') class Meta: model = TestModel data = TestModelDataset() self.assertEqual(len(data.headers), 3) self.assertTrue('id' in data.headers) self.assertFalse('field1' in data.headers) self.assertTrue('field2' in data.headers) self.assertTrue('Field 1' in data.headers) self.assertEqual(data[0][0], data[0][1]) def test_meta_fields(self): class TestModelDataset(ModelDataset): class Meta: model = TestModel fields = ['field1'] data = TestModelDataset() self.assertEqual(len(data.headers), 1) self.assertFalse('id' in data.headers) self.assertTrue('field1' in data.headers) def test_meta_exclude(self): class TestModelDataset(ModelDataset): class Meta: model = TestModel exclude = ['id'] data = TestModelDataset() self.assertEqual(len(data.headers), 1) self.assertFalse('id' in data.headers) self.assertTrue('field1' in data.headers) def test_meta_both(self): class TestModelDataset(ModelDataset): class Meta: model = TestModel fields = ['id', 'field1'] exclude = ['id'] data = TestModelDataset() self.assertEqual(len(data.headers), 1) self.assertFalse('id' in data.headers) self.assertTrue('field1' in data.headers)
Test that specifying fields and exclude in ModelDataset.Meta works.
Test that specifying fields and exclude in ModelDataset.Meta works.
Python
mit
joshourisman/django-tablib,ebrelsford/django-tablib,joshourisman/django-tablib,ebrelsford/django-tablib
python
## Code Before: from django.test import TestCase from django_tablib import ModelDataset, Field from .models import TestModel class DjangoTablibTestCase(TestCase): def setUp(self): TestModel.objects.create(field1='value') def test_declarative_fields(self): class TestModelDataset(ModelDataset): field1 = Field(header='Field 1') field2 = Field(attribute='field1') class Meta: model = TestModel data = TestModelDataset() self.assertEqual(len(data.headers), 3) self.assertTrue('id' in data.headers) self.assertFalse('field1' in data.headers) self.assertTrue('field2' in data.headers) self.assertTrue('Field 1' in data.headers) self.assertEqual(data[0][0], data[0][1]) ## Instruction: Test that specifying fields and exclude in ModelDataset.Meta works. ## Code After: from django.test import TestCase from django_tablib import ModelDataset, Field from .models import TestModel class DjangoTablibTestCase(TestCase): def setUp(self): TestModel.objects.create(field1='value') def test_declarative_fields(self): class TestModelDataset(ModelDataset): field1 = Field(header='Field 1') field2 = Field(attribute='field1') class Meta: model = TestModel data = TestModelDataset() self.assertEqual(len(data.headers), 3) self.assertTrue('id' in data.headers) self.assertFalse('field1' in data.headers) self.assertTrue('field2' in data.headers) self.assertTrue('Field 1' in data.headers) self.assertEqual(data[0][0], data[0][1]) def test_meta_fields(self): class TestModelDataset(ModelDataset): class Meta: model = TestModel fields = ['field1'] data = TestModelDataset() self.assertEqual(len(data.headers), 1) self.assertFalse('id' in data.headers) self.assertTrue('field1' in data.headers) def test_meta_exclude(self): class TestModelDataset(ModelDataset): class Meta: model = TestModel exclude = ['id'] data = TestModelDataset() self.assertEqual(len(data.headers), 1) self.assertFalse('id' in data.headers) self.assertTrue('field1' in data.headers) def test_meta_both(self): class TestModelDataset(ModelDataset): class Meta: model = TestModel fields = ['id', 'field1'] exclude = ['id'] data = TestModelDataset() self.assertEqual(len(data.headers), 1) self.assertFalse('id' in data.headers) self.assertTrue('field1' in data.headers)
// ... existing code ... self.assertTrue('Field 1' in data.headers) self.assertEqual(data[0][0], data[0][1]) def test_meta_fields(self): class TestModelDataset(ModelDataset): class Meta: model = TestModel fields = ['field1'] data = TestModelDataset() self.assertEqual(len(data.headers), 1) self.assertFalse('id' in data.headers) self.assertTrue('field1' in data.headers) def test_meta_exclude(self): class TestModelDataset(ModelDataset): class Meta: model = TestModel exclude = ['id'] data = TestModelDataset() self.assertEqual(len(data.headers), 1) self.assertFalse('id' in data.headers) self.assertTrue('field1' in data.headers) def test_meta_both(self): class TestModelDataset(ModelDataset): class Meta: model = TestModel fields = ['id', 'field1'] exclude = ['id'] data = TestModelDataset() self.assertEqual(len(data.headers), 1) self.assertFalse('id' in data.headers) self.assertTrue('field1' in data.headers) // ... rest of the code ...
34513dd1716f7299b2244d488055e82da1aea080
armstrong/core/arm_layout/utils.py
armstrong/core/arm_layout/utils.py
from django.utils.safestring import mark_safe from django.template.loader import render_to_string def get_layout_template_name(model, name): ret = [] for a in model.__class__.mro(): if not hasattr(a, "_meta"): continue ret.append("layout/%s/%s/%s.html" % (a._meta.app_label, a._meta.object_name.lower(), name)) return ret def render_model(object, name, dictionary=None, context_instance=None): dictionary = dictionary or {} dictionary["object"] = object return mark_safe(render_to_string(get_layout_template_name(object, name), dictionary=dictionary, context_instance=context_instance))
from django.utils.safestring import mark_safe from django.template.loader import render_to_string from armstrong.utils.backends import GenericBackend template_finder = GenericBackend('ARMSTRONG_LAYOUT_TEMPLATE_FINDER', defaults='armstrong.core.arm_layout.utils.get_layout_template_name')\ .get_backend def get_layout_template_name(model, name): ret = [] for a in model.__class__.mro(): if not hasattr(a, "_meta"): continue ret.append("layout/%s/%s/%s.html" % (a._meta.app_label, a._meta.object_name.lower(), name)) return ret def render_model(object, name, dictionary=None, context_instance=None): dictionary = dictionary or {} dictionary["object"] = object return mark_safe(render_to_string(template_finder(object, name), dictionary=dictionary, context_instance=context_instance))
Use a GenericBackend for our template finding function.
Use a GenericBackend for our template finding function.
Python
apache-2.0
armstrong/armstrong.core.arm_layout,armstrong/armstrong.core.arm_layout
python
## Code Before: from django.utils.safestring import mark_safe from django.template.loader import render_to_string def get_layout_template_name(model, name): ret = [] for a in model.__class__.mro(): if not hasattr(a, "_meta"): continue ret.append("layout/%s/%s/%s.html" % (a._meta.app_label, a._meta.object_name.lower(), name)) return ret def render_model(object, name, dictionary=None, context_instance=None): dictionary = dictionary or {} dictionary["object"] = object return mark_safe(render_to_string(get_layout_template_name(object, name), dictionary=dictionary, context_instance=context_instance)) ## Instruction: Use a GenericBackend for our template finding function. ## Code After: from django.utils.safestring import mark_safe from django.template.loader import render_to_string from armstrong.utils.backends import GenericBackend template_finder = GenericBackend('ARMSTRONG_LAYOUT_TEMPLATE_FINDER', defaults='armstrong.core.arm_layout.utils.get_layout_template_name')\ .get_backend def get_layout_template_name(model, name): ret = [] for a in model.__class__.mro(): if not hasattr(a, "_meta"): continue ret.append("layout/%s/%s/%s.html" % (a._meta.app_label, a._meta.object_name.lower(), name)) return ret def render_model(object, name, dictionary=None, context_instance=None): dictionary = dictionary or {} dictionary["object"] = object return mark_safe(render_to_string(template_finder(object, name), dictionary=dictionary, context_instance=context_instance))
// ... existing code ... from django.utils.safestring import mark_safe from django.template.loader import render_to_string from armstrong.utils.backends import GenericBackend template_finder = GenericBackend('ARMSTRONG_LAYOUT_TEMPLATE_FINDER', defaults='armstrong.core.arm_layout.utils.get_layout_template_name')\ .get_backend def get_layout_template_name(model, name): // ... modified code ... def render_model(object, name, dictionary=None, context_instance=None): dictionary = dictionary or {} dictionary["object"] = object return mark_safe(render_to_string(template_finder(object, name), dictionary=dictionary, context_instance=context_instance)) // ... rest of the code ...
12b313ed0be7049335046a00844c378b0bed7064
helpernmap.py
helpernmap.py
import nmap class HelperNmap: def __init__(self,args=""): self.args = args def process(self): print "Running Scan" nm = nmap.PortScanner() nm.scan(hosts='173.255.243.189', arguments='-sV -p1-5000') for host in nm.all_hosts(): print('----------------------------------------------------') print('Host : %s (%s)' % (host, nm[host].hostname())) print('State : %s' % nm[host].state()) for proto in nm[host].all_protocols(): print('----------') print('Protocol : %s' % proto) lport = nm[host][proto].keys() lport.sort() for port in lport: if nm[host][proto][port]['state'] == 'open': print ('port : %s\tstate : %s %s %s ' % (port, nm[host][proto][port]['product'], nm[host][proto][port]['version'], nm[host][proto][port]['cpe']))
import nmap class HelperNmap: def __init__(self,args=""): self.args = args def process(self): if self.__setParams(): print "Running Scan" nm = nmap.PortScanner() nm.scan(hosts=str(self.args), arguments='-sV -p1-5000') for host in nm.all_hosts(): print('----------------------------------------------------') print('Host : %s (%s)' % (host, nm[host].hostname())) print('State : %s' % nm[host].state()) for proto in nm[host].all_protocols(): print('----------') print('Protocol : %s' % proto) lport = nm[host][proto].keys() lport.sort() for port in lport: if nm[host][proto][port]['state'] == 'open': print ('port : %s\tstate : %s %s %s ' % (port, nm[host][proto][port]['product'], nm[host][proto][port]['version'], nm[host][proto][port]['cpe'])) else: print "Its not a valid argument" #private function to set params def __setParams(self): target = "" if self.args.find('net:') != -1: self.args = self.args.split(":")[1] return True else: return False
Add network target as a params
Add network target as a params Signed-off-by: Jacobo Tibaquira <[email protected]>
Python
apache-2.0
JKO/nsearch,JKO/nsearch
python
## Code Before: import nmap class HelperNmap: def __init__(self,args=""): self.args = args def process(self): print "Running Scan" nm = nmap.PortScanner() nm.scan(hosts='173.255.243.189', arguments='-sV -p1-5000') for host in nm.all_hosts(): print('----------------------------------------------------') print('Host : %s (%s)' % (host, nm[host].hostname())) print('State : %s' % nm[host].state()) for proto in nm[host].all_protocols(): print('----------') print('Protocol : %s' % proto) lport = nm[host][proto].keys() lport.sort() for port in lport: if nm[host][proto][port]['state'] == 'open': print ('port : %s\tstate : %s %s %s ' % (port, nm[host][proto][port]['product'], nm[host][proto][port]['version'], nm[host][proto][port]['cpe'])) ## Instruction: Add network target as a params Signed-off-by: Jacobo Tibaquira <[email protected]> ## Code After: import nmap class HelperNmap: def __init__(self,args=""): self.args = args def process(self): if self.__setParams(): print "Running Scan" nm = nmap.PortScanner() nm.scan(hosts=str(self.args), arguments='-sV -p1-5000') for host in nm.all_hosts(): print('----------------------------------------------------') print('Host : %s (%s)' % (host, nm[host].hostname())) print('State : %s' % nm[host].state()) for proto in nm[host].all_protocols(): print('----------') print('Protocol : %s' % proto) lport = nm[host][proto].keys() lport.sort() for port in lport: if nm[host][proto][port]['state'] == 'open': print ('port : %s\tstate : %s %s %s ' % (port, nm[host][proto][port]['product'], nm[host][proto][port]['version'], nm[host][proto][port]['cpe'])) else: print "Its not a valid argument" #private function to set params def __setParams(self): target = "" if self.args.find('net:') != -1: self.args = self.args.split(":")[1] return True else: return False
... self.args = args def process(self): if self.__setParams(): print "Running Scan" nm = nmap.PortScanner() nm.scan(hosts=str(self.args), arguments='-sV -p1-5000') for host in nm.all_hosts(): print('----------------------------------------------------') print('Host : %s (%s)' % (host, nm[host].hostname())) print('State : %s' % nm[host].state()) for proto in nm[host].all_protocols(): print('----------') print('Protocol : %s' % proto) lport = nm[host][proto].keys() lport.sort() for port in lport: if nm[host][proto][port]['state'] == 'open': print ('port : %s\tstate : %s %s %s ' % (port, nm[host][proto][port]['product'], nm[host][proto][port]['version'], nm[host][proto][port]['cpe'])) else: print "Its not a valid argument" #private function to set params def __setParams(self): target = "" if self.args.find('net:') != -1: self.args = self.args.split(":")[1] return True else: return False ...
b30d904fda46930f0650351272bb397c4979e15f
dropwizard-views/src/main/java/com/yammer/dropwizard/views/View.java
dropwizard-views/src/main/java/com/yammer/dropwizard/views/View.java
package com.yammer.dropwizard.views; import com.yammer.metrics.Metrics; import com.yammer.metrics.core.Timer; public abstract class View { private final String templateName; private final Timer renderingTimer; protected View(String templateName) { this.templateName = templateName; this.renderingTimer = Metrics.newTimer(getClass(), "rendering"); } public String getTemplateName() { return templateName; } Timer getRenderingTimer() { return renderingTimer; } }
package com.yammer.dropwizard.views; import com.yammer.metrics.Metrics; import com.yammer.metrics.core.Timer; import org.codehaus.jackson.annotate.JsonIgnore; public abstract class View { private final String templateName; private final Timer renderingTimer; protected View(String templateName) { this.templateName = templateName; this.renderingTimer = Metrics.newTimer(getClass(), "rendering"); } @JsonIgnore public String getTemplateName() { return templateName; } @JsonIgnore Timer getRenderingTimer() { return renderingTimer; } }
Make sure Jackson ignores the view getters.
Make sure Jackson ignores the view getters.
Java
apache-2.0
StanSvec/dropwizard,svenefftinge/dropwizard,dotCipher/dropwizard,cvent/dropwizard,csae1152/dropwizard,mnrasul/dropwizard,calou/dropwizard,ajaiyen/dropwizard,akraxx/dropwizard,akshaymaniyar/dropwizard,michelle-liang/dropwizard,jelgh/dropwizard,plausible-retired/warwizard,thomasandersen77/dropwizard,aaanders/dropwizard,sridhar-newsdistill/dropwizard,kdave47/dropwizard,AnuchitPrasertsang/dropwizard,zhiqinghuang/dropwizard,zhiqinghuang/dropwizard,ojacobson/dropwizard,vforce/dropwizard,qinfchen/dropwizard,bbrighttaer/dropwizard,randiroe/dropwizard,ckingsbu/dropwizard,kdave47/dropwizard,chaminda204/dropwizard,AnuchitPrasertsang/dropwizard,evnm/dropwizard,ptomli/dropwizard,qinfchen/dropwizard,shawnsmith/dropwizard,taohaolong/dropwizard,ojacobson/dropwizard,calou/dropwizard,tburch/dropwizard,dropwizard/dropwizard,ben1247/dropwizard,ckingsbu/dropwizard,MikaelAmborn/dropwizard,amillalen/dropwizard,yshaojie/dropwizard,vikasshinde22105/dropwizard,jamesward/dropwizard,puneetjaiswal/dropwizard,mnrasul/dropwizard,micsta/dropwizard,pradex/dropwizard,douzzi/dropwizard,jplock/dropwizard,mulloymorrow/dropwizard,hancy2013/dropwizard,benearlam/dropwizard,flipsterkeshav/dropwizard,evnm/dropwizard,mtbigham/dropwizard,tjcutajar/dropwizard,wangcan2014/dropwizard,christophercurrie/dropwizard,kdave47/dropwizard,pkwarren/dropwizard,mtbigham/dropwizard,jelgh/dropwizard,rgupta-okta/dropwizard,xiaoping2367/dropwizard,christophercurrie/dropwizard,sridhar-newsdistill/dropwizard,helt/dropwizard,ben1247/dropwizard,plausible-retired/warwizard,tjcutajar/dropwizard,biogerm/dropwizard,AnuchitPrasertsang/dropwizard,Trundle/dropwizard,Toilal/dropwizard,dropwizard/dropwizard,aaanders/dropwizard,tiankong1986/dropwizard,shawnsmith/dropwizard,yshaojie/dropwizard,hancy2013/dropwizard,taltmann/dropwizard,grange74/dropwizard,carlo-rtr/dropwizard,taltmann/dropwizard,nmharsha93/dropwizard,ojacobson/dropwizard,takecy/dropwizard,grange74/dropwizard,benearlam/dropwizard,boundary/dropwizard,pkwarren/dropwizard,nicktelford/dropwizard,dotCipher/dropwizard,nicktelford/dropwizard,randiroe/dropwizard,anonymint/dropwizard,phouse512/dropwizard,svenefftinge/dropwizard,tiankong1986/dropwizard,mtbigham/dropwizard,kjetilv/dropwizard,akshaymaniyar/dropwizard,douzzi/dropwizard,douzzi/dropwizard,Alexey1Gavrilov/dropwizard,pradex/dropwizard,wakandan/dropwizard,shawnsmith/dropwizard,arunsingh/dropwizard,thomasandersen77/dropwizard,Trundle/dropwizard,bbrighttaer/dropwizard,puneetjaiswal/dropwizard,tburch/dropwizard,carlo-rtr/dropwizard,phouse512/dropwizard,bbrighttaer/dropwizard,wilko55/dropwizard,csae1152/dropwizard,evnm/dropwizard,phambryan/dropwizard,jplock/dropwizard,pradex/dropwizard,hancy2013/dropwizard,taohaolong/dropwizard,sridhar-newsdistill/dropwizard,ptomli/dropwizard,ajaiyen/dropwizard,xiaoping2367/dropwizard,taohaolong/dropwizard,aaanders/dropwizard,micsta/dropwizard,edgarvonk/dropwizard,vikasshinde22105/dropwizard,michelle-liang/dropwizard,qinfchen/dropwizard,arunsingh/dropwizard,ckingsbu/dropwizard,edgarvonk/dropwizard,StanSvec/dropwizard,ryankennedy/dropwizard,philandstuff/dropwizard,mulloymorrow/dropwizard,hbrahi1/dropwizard,rgupta-okta/dropwizard,michelle-liang/dropwizard,wilko55/dropwizard,vikasshinde22105/dropwizard,ajaiyen/dropwizard,dsavinkov/dropwizard,thomasandersen77/dropwizard,phambryan/dropwizard,nickbabcock/dropwizard,phambryan/dropwizard,hbrahi1/dropwizard,tiankong1986/dropwizard,micsta/dropwizard,takecy/dropwizard,amillalen/dropwizard,kjetilv/dropwizard,Randgalt/dropwizard,cvent/dropwizard,wakandan/dropwizard,boundary/dropwizard,csae1152/dropwizard,mattnelson/dropwizard,csae1152/dropwizard,wakandan/dropwizard,benearlam/dropwizard,jplock/dropwizard,charlieg/dropwizard,ptomli/dropwizard,yshaojie/dropwizard,charlieg/dropwizard,nmharsha93/dropwizard,xiaoping2367/dropwizard,vforce/dropwizard,nickbabcock/dropwizard,Toilal/dropwizard,mosoft521/dropwizard,mattnelson/dropwizard,jelgh/dropwizard,Randgalt/dropwizard,Trundle/dropwizard,anonymint/dropwizard,dsavinkov/dropwizard,wilko55/dropwizard,dotCipher/dropwizard,charlieg/dropwizard,nmharsha93/dropwizard,mattnelson/dropwizard,sytolk/dropwizard,mosoft521/dropwizard,flipsterkeshav/dropwizard,wangcan2014/dropwizard,mosoft521/dropwizard,taltmann/dropwizard,flipsterkeshav/dropwizard,nickbabcock/dropwizard,sytolk/dropwizard,akraxx/dropwizard,amillalen/dropwizard,kjetilv/dropwizard,sytolk/dropwizard,Toilal/dropwizard,christophercurrie/dropwizard,StanSvec/dropwizard,tburch/dropwizard,patrox/dropwizard,wangcan2014/dropwizard,phouse512/dropwizard,MikaelAmborn/dropwizard,mulloymorrow/dropwizard,ryankennedy/dropwizard,philandstuff/dropwizard,biogerm/dropwizard,takecy/dropwizard,philandstuff/dropwizard,tjcutajar/dropwizard,helt/dropwizard,MikaelAmborn/dropwizard,Randgalt/dropwizard,chaminda204/dropwizard,patrox/dropwizard,svenefftinge/dropwizard,carlo-rtr/dropwizard,Alexey1Gavrilov/dropwizard,randiroe/dropwizard,mnrasul/dropwizard,vforce/dropwizard,biogerm/dropwizard,patrox/dropwizard,arunsingh/dropwizard,akraxx/dropwizard,ryankennedy/dropwizard,Alexey1Gavrilov/dropwizard,zhiqinghuang/dropwizard,jamesward/dropwizard,AnuchitPrasertsang/dropwizard,akshaymaniyar/dropwizard,chaminda204/dropwizard,helt/dropwizard,dsavinkov/dropwizard,puneetjaiswal/dropwizard,pkwarren/dropwizard,ben1247/dropwizard,calou/dropwizard,edgarvonk/dropwizard,charlieg/dropwizard,hbrahi1/dropwizard,cvent/dropwizard,dropwizard/dropwizard,rgupta-okta/dropwizard,grange74/dropwizard
java
## Code Before: package com.yammer.dropwizard.views; import com.yammer.metrics.Metrics; import com.yammer.metrics.core.Timer; public abstract class View { private final String templateName; private final Timer renderingTimer; protected View(String templateName) { this.templateName = templateName; this.renderingTimer = Metrics.newTimer(getClass(), "rendering"); } public String getTemplateName() { return templateName; } Timer getRenderingTimer() { return renderingTimer; } } ## Instruction: Make sure Jackson ignores the view getters. ## Code After: package com.yammer.dropwizard.views; import com.yammer.metrics.Metrics; import com.yammer.metrics.core.Timer; import org.codehaus.jackson.annotate.JsonIgnore; public abstract class View { private final String templateName; private final Timer renderingTimer; protected View(String templateName) { this.templateName = templateName; this.renderingTimer = Metrics.newTimer(getClass(), "rendering"); } @JsonIgnore public String getTemplateName() { return templateName; } @JsonIgnore Timer getRenderingTimer() { return renderingTimer; } }
# ... existing code ... import com.yammer.metrics.Metrics; import com.yammer.metrics.core.Timer; import org.codehaus.jackson.annotate.JsonIgnore; public abstract class View { private final String templateName; # ... modified code ... this.renderingTimer = Metrics.newTimer(getClass(), "rendering"); } @JsonIgnore public String getTemplateName() { return templateName; } @JsonIgnore Timer getRenderingTimer() { return renderingTimer; } # ... rest of the code ...
f4dfcf91c11fd06b5b71135f888b6979548a5147
conveyor/__main__.py
conveyor/__main__.py
from __future__ import absolute_import from .core import Conveyor def main(): Conveyor().run() if __name__ == "__main__": main()
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from .core import Conveyor def main(): Conveyor().run() if __name__ == "__main__": main()
Bring the standard __future__ imports over
Bring the standard __future__ imports over
Python
bsd-2-clause
crateio/carrier
python
## Code Before: from __future__ import absolute_import from .core import Conveyor def main(): Conveyor().run() if __name__ == "__main__": main() ## Instruction: Bring the standard __future__ imports over ## Code After: from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from .core import Conveyor def main(): Conveyor().run() if __name__ == "__main__": main()
... from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from .core import Conveyor ... def main(): Conveyor().run() if __name__ == "__main__": main() ...
b0434a28080d59c27a755b70be195c9f3135bf94
mdx_linkify/mdx_linkify.py
mdx_linkify/mdx_linkify.py
import bleach from html5lib.sanitizer import HTMLSanitizer from markdown.postprocessors import Postprocessor from markdown import Extension class MyTokenizer(HTMLSanitizer): def sanitize_token(self, token): return token class LinkifyPostprocessor(Postprocessor): def __init__(self, md, linkify_callbacks=[]): super(Postprocessor, self).__init__(md) self._callbacks = linkify_callbacks def run(self, text): text = bleach.linkify(text, callbacks=self._callbacks, tokenizer=MyTokenizer) return text class LinkifyExtension(Extension): config = {'linkify_callbacks': [[], 'Callbacks to send to bleach.linkify']} def extendMarkdown(self, md, md_globals): md.postprocessors.add( "linkify", LinkifyPostprocessor(md, self.getConfig('linkify_callbacks')), "_begin") def makeExtension(*args, **kwargs): return LinkifyExtension(*args, **kwargs)
import bleach from markdown.postprocessors import Postprocessor from markdown import Extension class LinkifyPostprocessor(Postprocessor): def __init__(self, md, linkify_callbacks=[]): super(Postprocessor, self).__init__(md) self._callbacks = linkify_callbacks def run(self, text): text = bleach.linkify(text, callbacks=self._callbacks) return text class LinkifyExtension(Extension): config = {'linkify_callbacks': [[], 'Callbacks to send to bleach.linkify']} def extendMarkdown(self, md, md_globals): md.postprocessors.add( "linkify", LinkifyPostprocessor(md, self.getConfig('linkify_callbacks')), "_begin") def makeExtension(*args, **kwargs): return LinkifyExtension(*args, **kwargs)
Make compatible with Bleach v2.0 and html5lib v1.0
Make compatible with Bleach v2.0 and html5lib v1.0
Python
mit
daGrevis/mdx_linkify
python
## Code Before: import bleach from html5lib.sanitizer import HTMLSanitizer from markdown.postprocessors import Postprocessor from markdown import Extension class MyTokenizer(HTMLSanitizer): def sanitize_token(self, token): return token class LinkifyPostprocessor(Postprocessor): def __init__(self, md, linkify_callbacks=[]): super(Postprocessor, self).__init__(md) self._callbacks = linkify_callbacks def run(self, text): text = bleach.linkify(text, callbacks=self._callbacks, tokenizer=MyTokenizer) return text class LinkifyExtension(Extension): config = {'linkify_callbacks': [[], 'Callbacks to send to bleach.linkify']} def extendMarkdown(self, md, md_globals): md.postprocessors.add( "linkify", LinkifyPostprocessor(md, self.getConfig('linkify_callbacks')), "_begin") def makeExtension(*args, **kwargs): return LinkifyExtension(*args, **kwargs) ## Instruction: Make compatible with Bleach v2.0 and html5lib v1.0 ## Code After: import bleach from markdown.postprocessors import Postprocessor from markdown import Extension class LinkifyPostprocessor(Postprocessor): def __init__(self, md, linkify_callbacks=[]): super(Postprocessor, self).__init__(md) self._callbacks = linkify_callbacks def run(self, text): text = bleach.linkify(text, callbacks=self._callbacks) return text class LinkifyExtension(Extension): config = {'linkify_callbacks': [[], 'Callbacks to send to bleach.linkify']} def extendMarkdown(self, md, md_globals): md.postprocessors.add( "linkify", LinkifyPostprocessor(md, self.getConfig('linkify_callbacks')), "_begin") def makeExtension(*args, **kwargs): return LinkifyExtension(*args, **kwargs)
// ... existing code ... import bleach from markdown.postprocessors import Postprocessor from markdown import Extension class LinkifyPostprocessor(Postprocessor): // ... modified code ... def run(self, text): text = bleach.linkify(text, callbacks=self._callbacks) return text // ... rest of the code ...
60bcd21c00443d947d76b268ed052b8787741f5b
setup.py
setup.py
from setuptools import setup import sys requires = ['feedgenerator', 'jinja2', 'pygments', 'docutils'] if sys.version_info < (2,7): requires.append('argparse') setup( name = "pelican", version = '2.3', url = 'http://alexis.notmyidea.org/pelican/', author = 'Alexis Metaireau', author_email = '[email protected]', description = "A tool to generate a static blog, with restructured text (or markdown) input files.", long_description=open('README.rst').read(), packages = ['pelican'], include_package_data = True, install_requires = requires, scripts = ['bin/pelican'], classifiers = ['Development Status :: 5 - Production/Stable', 'Environment :: Console', 'License :: OSI Approved :: GNU Affero General Public License v3', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
from setuptools import setup import sys requires = ['feedgenerator', 'jinja2', 'pygments', 'docutils', 'Markdown'] if sys.version_info < (2,7): requires.append('argparse') setup( name = "pelican", version = '2.3', url = 'http://alexis.notmyidea.org/pelican/', author = 'Alexis Metaireau', author_email = '[email protected]', description = "A tool to generate a static blog, with restructured text (or markdown) input files.", long_description=open('README.rst').read(), packages = ['pelican'], include_package_data = True, install_requires = requires, scripts = ['bin/pelican'], classifiers = ['Development Status :: 5 - Production/Stable', 'Environment :: Console', 'License :: OSI Approved :: GNU Affero General Public License v3', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
Add the dependency to Mardown.
Add the dependency to Mardown.
Python
agpl-3.0
rbarraud/pelican,eevee/pelican,lucasplus/pelican,ehashman/pelican,florianjacob/pelican,garbas/pelican,Scheirle/pelican,levanhien8/pelican,HyperGroups/pelican,TC01/pelican,crmackay/pelican,alexras/pelican,UdeskDeveloper/pelican,janaurka/git-debug-presentiation,jimperio/pelican,jvehent/pelican,levanhien8/pelican,liyonghelpme/myBlog,deved69/pelican-1,rbarraud/pelican,lucasplus/pelican,getpelican/pelican,goerz/pelican,number5/pelican,lucasplus/pelican,jvehent/pelican,btnpushnmunky/pelican,koobs/pelican,alexras/pelican,treyhunner/pelican,farseerfc/pelican,kernc/pelican,iurisilvio/pelican,zackw/pelican,rbarraud/pelican,goerz/pelican,Scheirle/pelican,Rogdham/pelican,abrahamvarricatt/pelican,GiovanniMoretti/pelican,ionelmc/pelican,ls2uper/pelican,HyperGroups/pelican,Polyconseil/pelican,JeremyMorgan/pelican,Polyconseil/pelican,iKevinY/pelican,UdeskDeveloper/pelican,liyonghelpme/myBlog,kennethlyn/pelican,crmackay/pelican,talha131/pelican,sunzhongwei/pelican,douglaskastle/pelican,koobs/pelican,eevee/pelican,florianjacob/pelican,levanhien8/pelican,11craft/pelican,karlcow/pelican,avaris/pelican,garbas/pelican,liyonghelpme/myBlog,Rogdham/pelican,sunzhongwei/pelican,deved69/pelican-1,51itclub/pelican,ehashman/pelican,catdog2/pelican,avaris/pelican,Summonee/pelican,51itclub/pelican,kernc/pelican,talha131/pelican,treyhunner/pelican,ingwinlu/pelican,justinmayer/pelican,Summonee/pelican,UdeskDeveloper/pelican,getpelican/pelican,kennethlyn/pelican,deved69/pelican-1,simonjj/pelican,HyperGroups/pelican,iurisilvio/pelican,treyhunner/pelican,simonjj/pelican,karlcow/pelican,arty-name/pelican,gymglish/pelican,11craft/pelican,fbs/pelican,GiovanniMoretti/pelican,joetboole/pelican,joetboole/pelican,TC01/pelican,ls2uper/pelican,eevee/pelican,TC01/pelican,joetboole/pelican,jo-tham/pelican,liyonghelpme/myBlog,sunzhongwei/pelican,JeremyMorgan/pelican,Rogdham/pelican,deanishe/pelican,koobs/pelican,GiovanniMoretti/pelican,iKevinY/pelican,btnpushnmunky/pelican,iurisilvio/pelican,abrahamvarricatt/pelican,btnpushnmunky/pelican,zackw/pelican,deanishe/pelican,farseerfc/pelican,Summonee/pelican,florianjacob/pelican,douglaskastle/pelican,ls2uper/pelican,zackw/pelican,karlcow/pelican,jo-tham/pelican,0xMF/pelican,JeremyMorgan/pelican,number5/pelican,crmackay/pelican,alexras/pelican,kennethlyn/pelican,liyonghelpme/myBlog,deanishe/pelican,catdog2/pelican,sunzhongwei/pelican,gymglish/pelican,ingwinlu/pelican,kernc/pelican,abrahamvarricatt/pelican,simonjj/pelican,number5/pelican,Scheirle/pelican,11craft/pelican,catdog2/pelican,gymglish/pelican,ehashman/pelican,janaurka/git-debug-presentiation,lazycoder-ru/pelican,51itclub/pelican,jimperio/pelican,goerz/pelican,jimperio/pelican,douglaskastle/pelican,Natim/pelican,garbas/pelican,lazycoder-ru/pelican,janaurka/git-debug-presentiation,lazycoder-ru/pelican,jvehent/pelican
python
## Code Before: from setuptools import setup import sys requires = ['feedgenerator', 'jinja2', 'pygments', 'docutils'] if sys.version_info < (2,7): requires.append('argparse') setup( name = "pelican", version = '2.3', url = 'http://alexis.notmyidea.org/pelican/', author = 'Alexis Metaireau', author_email = '[email protected]', description = "A tool to generate a static blog, with restructured text (or markdown) input files.", long_description=open('README.rst').read(), packages = ['pelican'], include_package_data = True, install_requires = requires, scripts = ['bin/pelican'], classifiers = ['Development Status :: 5 - Production/Stable', 'Environment :: Console', 'License :: OSI Approved :: GNU Affero General Public License v3', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ], ) ## Instruction: Add the dependency to Mardown. ## Code After: from setuptools import setup import sys requires = ['feedgenerator', 'jinja2', 'pygments', 'docutils', 'Markdown'] if sys.version_info < (2,7): requires.append('argparse') setup( name = "pelican", version = '2.3', url = 'http://alexis.notmyidea.org/pelican/', author = 'Alexis Metaireau', author_email = '[email protected]', description = "A tool to generate a static blog, with restructured text (or markdown) input files.", long_description=open('README.rst').read(), packages = ['pelican'], include_package_data = True, install_requires = requires, scripts = ['bin/pelican'], classifiers = ['Development Status :: 5 - Production/Stable', 'Environment :: Console', 'License :: OSI Approved :: GNU Affero General Public License v3', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
... from setuptools import setup import sys requires = ['feedgenerator', 'jinja2', 'pygments', 'docutils', 'Markdown'] if sys.version_info < (2,7): requires.append('argparse') ...
9b2d464a2562ecf915f22c4664f00af3d66b34ce
setup.py
setup.py
from setuptools import setup, find_packages import os scriptnames = ['runElegant.sh', 'sddsprintdata.sh', 'renametolower.sh', 'file2lower.sh', 'lte2json', 'json2lte', 'latticeviewer', 'lv'] def readme(): with open('README.rst') as f: return f.read() requiredpackages = ['pyrpn', 'h5py', 'numpy', 'matplotlib', 'pyepics', 'wxPython'] setup( name = "beamline", version = "1.3.6", description = "online model package for electron accelerator", long_description = readme() + '\n\n', author = "Tong Zhang", author_email = "[email protected]", platforms = ["Linux"], license = "MIT", packages = find_packages(), url = "http://archman.github.io/beamline/", scripts = [os.path.join('scripts',sn) for sn in scriptnames], requires = requiredpackages, install_requires = requiredpackages, extras_require = {'sdds': ['sddswhl']}, )
from setuptools import setup, find_packages import os scriptnames = ['runElegant.sh', 'sddsprintdata.sh', 'renametolower.sh', 'file2lower.sh', 'lte2json', 'json2lte', 'latticeviewer', 'lv'] def readme(): with open('README.rst') as f: return f.read() requiredpackages = ['pyrpn', 'h5py', 'numpy', 'matplotlib', 'pyepics'] setup( name = "beamline", version = "1.3.6", description = "online model package for electron accelerator", long_description = readme() + '\n\n', author = "Tong Zhang", author_email = "[email protected]", platforms = ["Linux"], license = "MIT", packages = find_packages(), url = "http://archman.github.io/beamline/", scripts = [os.path.join('scripts',sn) for sn in scriptnames], install_requires = requiredpackages, extras_require = {'sdds': ['sddswhl']}, )
Delete `requires` and `wxPython` dependency
Delete `requires` and `wxPython` dependency `wxPython` is not easily installable via pip on all Linux distributions without explicitly providing the path to the wheel, yet. `requires` is obsolete, because of the use of `install_requires`
Python
mit
Archman/beamline
python
## Code Before: from setuptools import setup, find_packages import os scriptnames = ['runElegant.sh', 'sddsprintdata.sh', 'renametolower.sh', 'file2lower.sh', 'lte2json', 'json2lte', 'latticeviewer', 'lv'] def readme(): with open('README.rst') as f: return f.read() requiredpackages = ['pyrpn', 'h5py', 'numpy', 'matplotlib', 'pyepics', 'wxPython'] setup( name = "beamline", version = "1.3.6", description = "online model package for electron accelerator", long_description = readme() + '\n\n', author = "Tong Zhang", author_email = "[email protected]", platforms = ["Linux"], license = "MIT", packages = find_packages(), url = "http://archman.github.io/beamline/", scripts = [os.path.join('scripts',sn) for sn in scriptnames], requires = requiredpackages, install_requires = requiredpackages, extras_require = {'sdds': ['sddswhl']}, ) ## Instruction: Delete `requires` and `wxPython` dependency `wxPython` is not easily installable via pip on all Linux distributions without explicitly providing the path to the wheel, yet. `requires` is obsolete, because of the use of `install_requires` ## Code After: from setuptools import setup, find_packages import os scriptnames = ['runElegant.sh', 'sddsprintdata.sh', 'renametolower.sh', 'file2lower.sh', 'lte2json', 'json2lte', 'latticeviewer', 'lv'] def readme(): with open('README.rst') as f: return f.read() requiredpackages = ['pyrpn', 'h5py', 'numpy', 'matplotlib', 'pyepics'] setup( name = "beamline", version = "1.3.6", description = "online model package for electron accelerator", long_description = readme() + '\n\n', author = "Tong Zhang", author_email = "[email protected]", platforms = ["Linux"], license = "MIT", packages = find_packages(), url = "http://archman.github.io/beamline/", scripts = [os.path.join('scripts',sn) for sn in scriptnames], install_requires = requiredpackages, extras_require = {'sdds': ['sddswhl']}, )
... with open('README.rst') as f: return f.read() requiredpackages = ['pyrpn', 'h5py', 'numpy', 'matplotlib', 'pyepics'] setup( name = "beamline", ... packages = find_packages(), url = "http://archman.github.io/beamline/", scripts = [os.path.join('scripts',sn) for sn in scriptnames], install_requires = requiredpackages, extras_require = {'sdds': ['sddswhl']}, ) ...
efdfcccf57b294d529039095c2c71401546b3519
elephas/utils/functional_utils.py
elephas/utils/functional_utils.py
from __future__ import absolute_import import numpy as np def add_params(p1, p2): res = [] for x,y in zip(p1,p2): res.append(x+y) return res def get_neutral(array): res = [] for x in array: res.append(np.zeros_like(x)) return res def divide_by(array_list, num_workers): for i in xrange(len(array_list)): array_list[i] /= num_workers return array_list
from __future__ import absolute_import import numpy as np def add_params(p1, p2): res = [] for x,y in zip(p1,p2): res.append(x+y) return res def subtract_params(p1, p2): res = [] for x,y in zip(p1,p2): res.append(x-y) return res def get_neutral(array): res = [] for x in array: res.append(np.zeros_like(x)) return res def divide_by(array_list, num_workers): for i in xrange(len(array_list)): array_list[i] /= num_workers return array_list
Subtract two sets of parameters
Subtract two sets of parameters
Python
mit
FighterLYL/elephas,maxpumperla/elephas,CheMcCandless/elephas,daishichao/elephas,maxpumperla/elephas,aarzhaev/elephas,darcy0511/elephas
python
## Code Before: from __future__ import absolute_import import numpy as np def add_params(p1, p2): res = [] for x,y in zip(p1,p2): res.append(x+y) return res def get_neutral(array): res = [] for x in array: res.append(np.zeros_like(x)) return res def divide_by(array_list, num_workers): for i in xrange(len(array_list)): array_list[i] /= num_workers return array_list ## Instruction: Subtract two sets of parameters ## Code After: from __future__ import absolute_import import numpy as np def add_params(p1, p2): res = [] for x,y in zip(p1,p2): res.append(x+y) return res def subtract_params(p1, p2): res = [] for x,y in zip(p1,p2): res.append(x-y) return res def get_neutral(array): res = [] for x in array: res.append(np.zeros_like(x)) return res def divide_by(array_list, num_workers): for i in xrange(len(array_list)): array_list[i] /= num_workers return array_list
// ... existing code ... res = [] for x,y in zip(p1,p2): res.append(x+y) return res def subtract_params(p1, p2): res = [] for x,y in zip(p1,p2): res.append(x-y) return res def get_neutral(array): // ... rest of the code ...
3e267511aceb753ac62f8628a551574567db980d
JECP-SE/src/com/annimon/jecp/se/JecpApplication.java
JECP-SE/src/com/annimon/jecp/se/JecpApplication.java
package com.annimon.jecp.se; import com.annimon.jecp.ApplicationListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JFrame; import javax.swing.WindowConstants; /** * * @author aNNiMON */ public abstract class JecpApplication extends JFrame implements ApplicationListener, WindowListener { private final JecpPaintPanel panel; public JecpApplication(int width, int height) { addWindowListener(JecpApplication.this); setLocationByPlatform(true); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); onStartApp(width, height); panel = new JecpPaintPanel(this, width, height); add(panel); pack(); setVisible(true); } @Override public void windowClosing(WindowEvent e) { onDestroyApp(); } @Override public void windowDeactivated(WindowEvent e) { onPauseApp(); } @Override public void windowOpened(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowActivated(WindowEvent e) { } }
package com.annimon.jecp.se; import com.annimon.jecp.ApplicationListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JFrame; import javax.swing.WindowConstants; /** * * @author aNNiMON */ public abstract class JecpApplication extends JFrame implements WindowListener { private final ApplicationListener listener; private final JecpPaintPanel panel; public JecpApplication(ApplicationListener listener, int width, int height) { this.listener = listener; addWindowListener(JecpApplication.this); setLocationByPlatform(true); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); listener.onStartApp(width, height); panel = new JecpPaintPanel(listener, width, height); add(panel); pack(); setVisible(true); } @Override public void windowClosing(WindowEvent e) { listener.onDestroyApp(); } @Override public void windowDeactivated(WindowEvent e) { listener.onPauseApp(); } @Override public void windowOpened(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowActivated(WindowEvent e) { } }
Change JecpApllication class in JECP-SE
Change JecpApllication class in JECP-SE
Java
apache-2.0
aNNiMON/JECP
java
## Code Before: package com.annimon.jecp.se; import com.annimon.jecp.ApplicationListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JFrame; import javax.swing.WindowConstants; /** * * @author aNNiMON */ public abstract class JecpApplication extends JFrame implements ApplicationListener, WindowListener { private final JecpPaintPanel panel; public JecpApplication(int width, int height) { addWindowListener(JecpApplication.this); setLocationByPlatform(true); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); onStartApp(width, height); panel = new JecpPaintPanel(this, width, height); add(panel); pack(); setVisible(true); } @Override public void windowClosing(WindowEvent e) { onDestroyApp(); } @Override public void windowDeactivated(WindowEvent e) { onPauseApp(); } @Override public void windowOpened(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowActivated(WindowEvent e) { } } ## Instruction: Change JecpApllication class in JECP-SE ## Code After: package com.annimon.jecp.se; import com.annimon.jecp.ApplicationListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JFrame; import javax.swing.WindowConstants; /** * * @author aNNiMON */ public abstract class JecpApplication extends JFrame implements WindowListener { private final ApplicationListener listener; private final JecpPaintPanel panel; public JecpApplication(ApplicationListener listener, int width, int height) { this.listener = listener; addWindowListener(JecpApplication.this); setLocationByPlatform(true); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); listener.onStartApp(width, height); panel = new JecpPaintPanel(listener, width, height); add(panel); pack(); setVisible(true); } @Override public void windowClosing(WindowEvent e) { listener.onDestroyApp(); } @Override public void windowDeactivated(WindowEvent e) { listener.onPauseApp(); } @Override public void windowOpened(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowActivated(WindowEvent e) { } }
# ... existing code ... * * @author aNNiMON */ public abstract class JecpApplication extends JFrame implements WindowListener { private final ApplicationListener listener; private final JecpPaintPanel panel; public JecpApplication(ApplicationListener listener, int width, int height) { this.listener = listener; addWindowListener(JecpApplication.this); setLocationByPlatform(true); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); listener.onStartApp(width, height); panel = new JecpPaintPanel(listener, width, height); add(panel); pack(); # ... modified code ... @Override public void windowClosing(WindowEvent e) { listener.onDestroyApp(); } @Override public void windowDeactivated(WindowEvent e) { listener.onPauseApp(); } @Override # ... rest of the code ...
07c9b76d63714c431a983f0506ff71f19face3bd
astroquery/alma/tests/setup_package.py
astroquery/alma/tests/setup_package.py
import os def get_package_data(): paths = [os.path.join('data', '*.txt')] return {'astroquery.alma.tests': paths}
import os def get_package_data(): paths = [os.path.join('data', '*.txt'), os.path.join('data', '*.xml')] return {'astroquery.alma.tests': paths}
Include xml datafile for alma tests
Include xml datafile for alma tests
Python
bsd-3-clause
imbasimba/astroquery,imbasimba/astroquery,ceb8/astroquery,ceb8/astroquery
python
## Code Before: import os def get_package_data(): paths = [os.path.join('data', '*.txt')] return {'astroquery.alma.tests': paths} ## Instruction: Include xml datafile for alma tests ## Code After: import os def get_package_data(): paths = [os.path.join('data', '*.txt'), os.path.join('data', '*.xml')] return {'astroquery.alma.tests': paths}
# ... existing code ... def get_package_data(): paths = [os.path.join('data', '*.txt'), os.path.join('data', '*.xml')] return {'astroquery.alma.tests': paths} # ... rest of the code ...
85df3afc75f52a2183ef46560f57bb6993091238
trex/urls.py
trex/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views import project urlpatterns = patterns( '', url(r"^admin/", include(admin.site.urls)), url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), )
from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views import project urlpatterns = patterns( '', url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), )
Remove the admin url mapping
Remove the admin url mapping
Python
mit
bjoernricks/trex,bjoernricks/trex
python
## Code Before: from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views import project urlpatterns = patterns( '', url(r"^admin/", include(admin.site.urls)), url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), ) ## Instruction: Remove the admin url mapping ## Code After: from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views import project urlpatterns = patterns( '', url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), )
... urlpatterns = patterns( '', url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), ...
a8ca548493fdf534918aa869ad645cfb4668bbb3
libreplan-business/src/main/java/org/libreplan/business/externalcompanies/entities/CommunicationType.java
libreplan-business/src/main/java/org/libreplan/business/externalcompanies/entities/CommunicationType.java
/* * This file is part of LibrePlan * * Copyright (C) 2011 WirelessGalicia, S.L. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.libreplan.business.externalcompanies.entities; import static org.libreplan.business.i18n.I18nHelper._; /** * Enum for specified the type of {@link CustomerCommunication} * * @author Susana Montes Pedreira <[email protected]> */ public enum CommunicationType { NEW_PROJECT(_("New project")), REPORT_PROGRESS(_("Report advance")); private String description; private CommunicationType(String description) { this.description = description; } public String toString() { return this.description; } public static CommunicationType getDefault() { return NEW_PROJECT; } }
/* * This file is part of LibrePlan * * Copyright (C) 2011 WirelessGalicia, S.L. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.libreplan.business.externalcompanies.entities; import static org.libreplan.business.i18n.I18nHelper._; /** * Enum for specified the type of {@link CustomerCommunication} * * @author Susana Montes Pedreira <[email protected]> */ public enum CommunicationType { NEW_PROJECT(_("New project")), REPORT_PROGRESS(_("Report advance")), UPDATE_DELIVERING_DATE( _("Update Delivering Date")); private String description; private CommunicationType(String description) { this.description = description; } public String toString() { return this.description; } public static CommunicationType getDefault() { return NEW_PROJECT; } }
Create new subcontractor communication type: UPDATE_DELIVERING_DATE
Create new subcontractor communication type: UPDATE_DELIVERING_DATE FEA: ItEr75S32AnA15S04UpdateDeliveringDateInSubcontracting
Java
agpl-3.0
skylow95/libreplan,Marine-22/libre,PaulLuchyn/libreplan,LibrePlan/libreplan,skylow95/libreplan,LibrePlan/libreplan,skylow95/libreplan,PaulLuchyn/libreplan,poum/libreplan,dgray16/libreplan,skylow95/libreplan,Marine-22/libre,LibrePlan/libreplan,Marine-22/libre,dgray16/libreplan,LibrePlan/libreplan,poum/libreplan,LibrePlan/libreplan,dgray16/libreplan,Marine-22/libre,dgray16/libreplan,PaulLuchyn/libreplan,PaulLuchyn/libreplan,PaulLuchyn/libreplan,dgray16/libreplan,skylow95/libreplan,dgray16/libreplan,PaulLuchyn/libreplan,Marine-22/libre,LibrePlan/libreplan,LibrePlan/libreplan,PaulLuchyn/libreplan,poum/libreplan,dgray16/libreplan,skylow95/libreplan,Marine-22/libre,poum/libreplan,poum/libreplan,poum/libreplan
java
## Code Before: /* * This file is part of LibrePlan * * Copyright (C) 2011 WirelessGalicia, S.L. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.libreplan.business.externalcompanies.entities; import static org.libreplan.business.i18n.I18nHelper._; /** * Enum for specified the type of {@link CustomerCommunication} * * @author Susana Montes Pedreira <[email protected]> */ public enum CommunicationType { NEW_PROJECT(_("New project")), REPORT_PROGRESS(_("Report advance")); private String description; private CommunicationType(String description) { this.description = description; } public String toString() { return this.description; } public static CommunicationType getDefault() { return NEW_PROJECT; } } ## Instruction: Create new subcontractor communication type: UPDATE_DELIVERING_DATE FEA: ItEr75S32AnA15S04UpdateDeliveringDateInSubcontracting ## Code After: /* * This file is part of LibrePlan * * Copyright (C) 2011 WirelessGalicia, S.L. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.libreplan.business.externalcompanies.entities; import static org.libreplan.business.i18n.I18nHelper._; /** * Enum for specified the type of {@link CustomerCommunication} * * @author Susana Montes Pedreira <[email protected]> */ public enum CommunicationType { NEW_PROJECT(_("New project")), REPORT_PROGRESS(_("Report advance")), UPDATE_DELIVERING_DATE( _("Update Delivering Date")); private String description; private CommunicationType(String description) { this.description = description; } public String toString() { return this.description; } public static CommunicationType getDefault() { return NEW_PROJECT; } }
// ... existing code ... */ public enum CommunicationType { NEW_PROJECT(_("New project")), REPORT_PROGRESS(_("Report advance")), UPDATE_DELIVERING_DATE( _("Update Delivering Date")); private String description; // ... rest of the code ...
f2b4e4758ae60526e8bb5c57e9c45b0a1901fa14
wagtail/wagtailforms/edit_handlers.py
wagtail/wagtailforms/edit_handlers.py
from __future__ import absolute_import, unicode_literals from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.wagtailadmin.edit_handlers import EditHandler class BaseFormSubmissionsPanel(EditHandler): template = "wagtailforms/edit_handlers/form_responses_panel.html" def render(self): from .models import FormSubmission submissions = FormSubmission.objects.filter(page=self.instance) if not submissions: return '' return mark_safe(render_to_string(self.template, { 'self': self, 'submissions': submissions })) class FormSubmissionsPanel(object): def __init__(self, heading=None): self.heading = heading def bind_to_model(self, model): heading = _('{} submissions').format(model._meta.model_name) return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), { 'model': model, 'heading': self.heading or heading, })
from __future__ import absolute_import, unicode_literals from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.wagtailadmin.edit_handlers import EditHandler class BaseFormSubmissionsPanel(EditHandler): template = "wagtailforms/edit_handlers/form_responses_panel.html" def render(self): from .models import FormSubmission submissions = FormSubmission.objects.filter(page=self.instance) if not submissions: return '' return mark_safe(render_to_string(self.template, { 'self': self, 'submissions': submissions })) class FormSubmissionsPanel(object): def __init__(self, heading=None): self.heading = heading def bind_to_model(self, model): heading = _('{} submissions').format(model.get_verbose_name()) return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), { 'model': model, 'heading': self.heading or heading, })
Use verbose name for FormSubmissionsPanel heading
Use verbose name for FormSubmissionsPanel heading
Python
bsd-3-clause
rsalmaso/wagtail,takeflight/wagtail,torchbox/wagtail,rsalmaso/wagtail,FlipperPA/wagtail,zerolab/wagtail,jnns/wagtail,nimasmi/wagtail,kaedroho/wagtail,thenewguy/wagtail,zerolab/wagtail,mikedingjan/wagtail,nimasmi/wagtail,wagtail/wagtail,thenewguy/wagtail,nutztherookie/wagtail,takeflight/wagtail,chrxr/wagtail,jnns/wagtail,gasman/wagtail,rsalmaso/wagtail,chrxr/wagtail,kaedroho/wagtail,gasman/wagtail,thenewguy/wagtail,nilnvoid/wagtail,wagtail/wagtail,timorieber/wagtail,torchbox/wagtail,timorieber/wagtail,zerolab/wagtail,thenewguy/wagtail,zerolab/wagtail,nutztherookie/wagtail,chrxr/wagtail,wagtail/wagtail,Toshakins/wagtail,iansprice/wagtail,iansprice/wagtail,rsalmaso/wagtail,gasman/wagtail,zerolab/wagtail,mixxorz/wagtail,nealtodd/wagtail,jnns/wagtail,timorieber/wagtail,kaedroho/wagtail,mikedingjan/wagtail,takeflight/wagtail,FlipperPA/wagtail,kaedroho/wagtail,Toshakins/wagtail,mixxorz/wagtail,nutztherookie/wagtail,nilnvoid/wagtail,nealtodd/wagtail,FlipperPA/wagtail,nutztherookie/wagtail,rsalmaso/wagtail,torchbox/wagtail,gasman/wagtail,Toshakins/wagtail,mixxorz/wagtail,kaedroho/wagtail,thenewguy/wagtail,chrxr/wagtail,nealtodd/wagtail,torchbox/wagtail,nilnvoid/wagtail,mixxorz/wagtail,mikedingjan/wagtail,gasman/wagtail,FlipperPA/wagtail,nimasmi/wagtail,timorieber/wagtail,Toshakins/wagtail,wagtail/wagtail,iansprice/wagtail,mikedingjan/wagtail,nilnvoid/wagtail,mixxorz/wagtail,nealtodd/wagtail,iansprice/wagtail,wagtail/wagtail,jnns/wagtail,nimasmi/wagtail,takeflight/wagtail
python
## Code Before: from __future__ import absolute_import, unicode_literals from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.wagtailadmin.edit_handlers import EditHandler class BaseFormSubmissionsPanel(EditHandler): template = "wagtailforms/edit_handlers/form_responses_panel.html" def render(self): from .models import FormSubmission submissions = FormSubmission.objects.filter(page=self.instance) if not submissions: return '' return mark_safe(render_to_string(self.template, { 'self': self, 'submissions': submissions })) class FormSubmissionsPanel(object): def __init__(self, heading=None): self.heading = heading def bind_to_model(self, model): heading = _('{} submissions').format(model._meta.model_name) return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), { 'model': model, 'heading': self.heading or heading, }) ## Instruction: Use verbose name for FormSubmissionsPanel heading ## Code After: from __future__ import absolute_import, unicode_literals from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.wagtailadmin.edit_handlers import EditHandler class BaseFormSubmissionsPanel(EditHandler): template = "wagtailforms/edit_handlers/form_responses_panel.html" def render(self): from .models import FormSubmission submissions = FormSubmission.objects.filter(page=self.instance) if not submissions: return '' return mark_safe(render_to_string(self.template, { 'self': self, 'submissions': submissions })) class FormSubmissionsPanel(object): def __init__(self, heading=None): self.heading = heading def bind_to_model(self, model): heading = _('{} submissions').format(model.get_verbose_name()) return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), { 'model': model, 'heading': self.heading or heading, })
// ... existing code ... self.heading = heading def bind_to_model(self, model): heading = _('{} submissions').format(model.get_verbose_name()) return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), { 'model': model, 'heading': self.heading or heading, // ... rest of the code ...
79770a0e0f31f1292f8b5ab103509e7835570f20
src/collectors/SmartCollector/SmartCollector.py
src/collectors/SmartCollector/SmartCollector.py
import diamond.collector import subprocess import re import os class SmartCollector(diamond.collector.Collector): """ Collect data from S.M.A.R.T.'s attribute reporting. """ def get_default_config(self): """ Returns default configuration options. """ return { 'path': 'smart', 'devices': '^disk[0-9]$|^sd[a-z]$|^hd[a-z]$' } def collect(self): """ Collect and publish S.M.A.R.T. attributes """ devices = re.compile(self.config['devices']) for device in os.listdir('/dev'): if devices.match(device): attributes = subprocess.Popen(["smartctl", "-A", os.path.join('/dev',device)], stdout=subprocess.PIPE).communicate()[0].strip().splitlines() for attr in attributes[7:]: self.publish("%s.%s" % (device, attr.split()[1]), attr.split()[9])
import diamond.collector import subprocess import re import os class SmartCollector(diamond.collector.Collector): """ Collect data from S.M.A.R.T.'s attribute reporting. """ def get_default_config(self): """ Returns default configuration options. """ return { 'path': 'smart', 'devices': '^disk[0-9]$|^sd[a-z]$|^hd[a-z]$' } def collect(self): """ Collect and publish S.M.A.R.T. attributes """ devices = re.compile(self.config['devices']) for device in os.listdir('/dev'): if devices.match(device): attributes = subprocess.Popen(["smartctl", "-A", os.path.join('/dev',device)], stdout=subprocess.PIPE).communicate()[0].strip().splitlines() for attr in attributes[7:]: attribute = attr.split() if attribute[1] != "Unknown_Attribute": self.publish("%s.%s" % (device, attribute[1]), attribute[9]) else: self.publish("%s.%s" % (device, attribute[0]), attribute[9])
Use ID instead of attribute if attribute name is 'Unknown_Attribute'.
Use ID instead of attribute if attribute name is 'Unknown_Attribute'.
Python
mit
zoidbergwill/Diamond,CYBERBUGJR/Diamond,TinLe/Diamond,tellapart/Diamond,Netuitive/Diamond,socialwareinc/Diamond,hvnsweeting/Diamond,joel-airspring/Diamond,joel-airspring/Diamond,hamelg/Diamond,signalfx/Diamond,stuartbfox/Diamond,disqus/Diamond,python-diamond/Diamond,rtoma/Diamond,mfriedenhagen/Diamond,socialwareinc/Diamond,EzyInsights/Diamond,gg7/diamond,CYBERBUGJR/Diamond,jriguera/Diamond,timchenxiaoyu/Diamond,jumping/Diamond,ramjothikumar/Diamond,anandbhoraskar/Diamond,sebbrandt87/Diamond,thardie/Diamond,eMerzh/Diamond-1,metamx/Diamond,eMerzh/Diamond-1,hamelg/Diamond,tuenti/Diamond,datafiniti/Diamond,janisz/Diamond-1,jumping/Diamond,janisz/Diamond-1,TinLe/Diamond,works-mobile/Diamond,skbkontur/Diamond,h00dy/Diamond,disqus/Diamond,timchenxiaoyu/Diamond,actmd/Diamond,mzupan/Diamond,Nihn/Diamond-1,signalfx/Diamond,eMerzh/Diamond-1,hvnsweeting/Diamond,russss/Diamond,Slach/Diamond,h00dy/Diamond,MediaMath/Diamond,szibis/Diamond,EzyInsights/Diamond,MediaMath/Diamond,mzupan/Diamond,krbaker/Diamond,eMerzh/Diamond-1,jriguera/Diamond,codepython/Diamond,sebbrandt87/Diamond,janisz/Diamond-1,h00dy/Diamond,anandbhoraskar/Diamond,dcsquared13/Diamond,zoidbergwill/Diamond,acquia/Diamond,codepython/Diamond,Basis/Diamond,mfriedenhagen/Diamond,signalfx/Diamond,saucelabs/Diamond,joel-airspring/Diamond,saucelabs/Diamond,TinLe/Diamond,stuartbfox/Diamond,works-mobile/Diamond,Clever/Diamond,MediaMath/Diamond,szibis/Diamond,Precis/Diamond,sebbrandt87/Diamond,cannium/Diamond,Netuitive/Diamond,timchenxiaoyu/Diamond,jriguera/Diamond,Ssawa/Diamond,h00dy/Diamond,szibis/Diamond,russss/Diamond,mfriedenhagen/Diamond,Netuitive/netuitive-diamond,jaingaurav/Diamond,janisz/Diamond-1,anandbhoraskar/Diamond,Netuitive/Diamond,thardie/Diamond,acquia/Diamond,bmhatfield/Diamond,datafiniti/Diamond,disqus/Diamond,signalfx/Diamond,stuartbfox/Diamond,hamelg/Diamond,tuenti/Diamond,python-diamond/Diamond,Basis/Diamond,cannium/Diamond,codepython/Diamond,TinLe/Diamond,jaingaurav/Diamond,bmhatfield/Diamond,tellapart/Diamond,Nihn/Diamond-1,works-mobile/Diamond,codepython/Diamond,skbkontur/Diamond,ramjothikumar/Diamond,Ssawa/Diamond,mzupan/Diamond,MediaMath/Diamond,bmhatfield/Diamond,Precis/Diamond,Ensighten/Diamond,TAKEALOT/Diamond,ramjothikumar/Diamond,ramjothikumar/Diamond,acquia/Diamond,dcsquared13/Diamond,krbaker/Diamond,Ormod/Diamond,Ensighten/Diamond,metamx/Diamond,Clever/Diamond,jriguera/Diamond,Ssawa/Diamond,Basis/Diamond,datafiniti/Diamond,Ensighten/Diamond,python-diamond/Diamond,cannium/Diamond,dcsquared13/Diamond,ceph/Diamond,jaingaurav/Diamond,socialwareinc/Diamond,Nihn/Diamond-1,Ormod/Diamond,tuenti/Diamond,anandbhoraskar/Diamond,Basis/Diamond,skbkontur/Diamond,socialwareinc/Diamond,acquia/Diamond,thardie/Diamond,Precis/Diamond,Clever/Diamond,rtoma/Diamond,ceph/Diamond,rtoma/Diamond,rtoma/Diamond,actmd/Diamond,russss/Diamond,tusharmakkar08/Diamond,actmd/Diamond,zoidbergwill/Diamond,hamelg/Diamond,Ssawa/Diamond,timchenxiaoyu/Diamond,ceph/Diamond,Precis/Diamond,tusharmakkar08/Diamond,Slach/Diamond,krbaker/Diamond,Slach/Diamond,Slach/Diamond,skbkontur/Diamond,datafiniti/Diamond,jaingaurav/Diamond,Clever/Diamond,gg7/diamond,sebbrandt87/Diamond,szibis/Diamond,Ormod/Diamond,tusharmakkar08/Diamond,zoidbergwill/Diamond,bmhatfield/Diamond,TAKEALOT/Diamond,hvnsweeting/Diamond,saucelabs/Diamond,gg7/diamond,Netuitive/Diamond,tuenti/Diamond,Netuitive/netuitive-diamond,tellapart/Diamond,dcsquared13/Diamond,krbaker/Diamond,mzupan/Diamond,MichaelDoyle/Diamond,Ormod/Diamond,joel-airspring/Diamond,tusharmakkar08/Diamond,russss/Diamond,TAKEALOT/Diamond,TAKEALOT/Diamond,CYBERBUGJR/Diamond,thardie/Diamond,MichaelDoyle/Diamond,works-mobile/Diamond,EzyInsights/Diamond,cannium/Diamond,Nihn/Diamond-1,tellapart/Diamond,Ensighten/Diamond,EzyInsights/Diamond,jumping/Diamond,stuartbfox/Diamond,Netuitive/netuitive-diamond,jumping/Diamond,hvnsweeting/Diamond,saucelabs/Diamond,mfriedenhagen/Diamond,MichaelDoyle/Diamond,MichaelDoyle/Diamond,CYBERBUGJR/Diamond,ceph/Diamond,Netuitive/netuitive-diamond,metamx/Diamond,actmd/Diamond,gg7/diamond
python
## Code Before: import diamond.collector import subprocess import re import os class SmartCollector(diamond.collector.Collector): """ Collect data from S.M.A.R.T.'s attribute reporting. """ def get_default_config(self): """ Returns default configuration options. """ return { 'path': 'smart', 'devices': '^disk[0-9]$|^sd[a-z]$|^hd[a-z]$' } def collect(self): """ Collect and publish S.M.A.R.T. attributes """ devices = re.compile(self.config['devices']) for device in os.listdir('/dev'): if devices.match(device): attributes = subprocess.Popen(["smartctl", "-A", os.path.join('/dev',device)], stdout=subprocess.PIPE).communicate()[0].strip().splitlines() for attr in attributes[7:]: self.publish("%s.%s" % (device, attr.split()[1]), attr.split()[9]) ## Instruction: Use ID instead of attribute if attribute name is 'Unknown_Attribute'. ## Code After: import diamond.collector import subprocess import re import os class SmartCollector(diamond.collector.Collector): """ Collect data from S.M.A.R.T.'s attribute reporting. """ def get_default_config(self): """ Returns default configuration options. """ return { 'path': 'smart', 'devices': '^disk[0-9]$|^sd[a-z]$|^hd[a-z]$' } def collect(self): """ Collect and publish S.M.A.R.T. attributes """ devices = re.compile(self.config['devices']) for device in os.listdir('/dev'): if devices.match(device): attributes = subprocess.Popen(["smartctl", "-A", os.path.join('/dev',device)], stdout=subprocess.PIPE).communicate()[0].strip().splitlines() for attr in attributes[7:]: attribute = attr.split() if attribute[1] != "Unknown_Attribute": self.publish("%s.%s" % (device, attribute[1]), attribute[9]) else: self.publish("%s.%s" % (device, attribute[0]), attribute[9])
... stdout=subprocess.PIPE).communicate()[0].strip().splitlines() for attr in attributes[7:]: attribute = attr.split() if attribute[1] != "Unknown_Attribute": self.publish("%s.%s" % (device, attribute[1]), attribute[9]) else: self.publish("%s.%s" % (device, attribute[0]), attribute[9]) ...
c859416d2d35aab83fc9e8f400e00f8f07c0b8a9
test/parser_test.py
test/parser_test.py
import socket client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect(("localhost", 5002)) with open("resources/Matrix.java", "r") as java_file: source = java_file.read() + "\nEOS_BITSHIFT" client_socket.send("%d\n%s" % (len(source), source)); data = '' while True: data = client_socket.recv(10000) if data != '': client_socket.close() break; print data;
import socket, sys file_name = 'resources/<name>.c' server_socket_number = 5001 if __name__ == '__main__': if len(sys.argv) == 1: print "Please input a parser to test." elif len(sys.argv) > 2: print "Too many arguments." else: if sys.argv[1] == 'c': pass elif sys.argv[1] == 'java': file_name = "resources/Matrix.java" server_socket_number = 5002 elif sys.argv[1] == 'ruby': file_name = "resources/<name>.rb" server_socket_number = 5003 client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect(("localhost", server_socket_number)) with open(file_name, "r") as source_file: source = source_file.read() client_socket.send("%d\n%s" % (len(source), source)); data = '' while True: data = client_socket.recv(10000) if data != '': client_socket.close() break; print data;
Change test file to support different parsers
Change test file to support different parsers
Python
mit
earwig/bitshift,earwig/bitshift,earwig/bitshift,earwig/bitshift,earwig/bitshift,earwig/bitshift
python
## Code Before: import socket client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect(("localhost", 5002)) with open("resources/Matrix.java", "r") as java_file: source = java_file.read() + "\nEOS_BITSHIFT" client_socket.send("%d\n%s" % (len(source), source)); data = '' while True: data = client_socket.recv(10000) if data != '': client_socket.close() break; print data; ## Instruction: Change test file to support different parsers ## Code After: import socket, sys file_name = 'resources/<name>.c' server_socket_number = 5001 if __name__ == '__main__': if len(sys.argv) == 1: print "Please input a parser to test." elif len(sys.argv) > 2: print "Too many arguments." else: if sys.argv[1] == 'c': pass elif sys.argv[1] == 'java': file_name = "resources/Matrix.java" server_socket_number = 5002 elif sys.argv[1] == 'ruby': file_name = "resources/<name>.rb" server_socket_number = 5003 client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect(("localhost", server_socket_number)) with open(file_name, "r") as source_file: source = source_file.read() client_socket.send("%d\n%s" % (len(source), source)); data = '' while True: data = client_socket.recv(10000) if data != '': client_socket.close() break; print data;
// ... existing code ... import socket, sys file_name = 'resources/<name>.c' server_socket_number = 5001 if __name__ == '__main__': if len(sys.argv) == 1: print "Please input a parser to test." elif len(sys.argv) > 2: print "Too many arguments." else: if sys.argv[1] == 'c': pass elif sys.argv[1] == 'java': file_name = "resources/Matrix.java" server_socket_number = 5002 elif sys.argv[1] == 'ruby': file_name = "resources/<name>.rb" server_socket_number = 5003 client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect(("localhost", server_socket_number)) with open(file_name, "r") as source_file: source = source_file.read() client_socket.send("%d\n%s" % (len(source), source)); data = '' while True: data = client_socket.recv(10000) if data != '': client_socket.close() break; print data; // ... rest of the code ...
3373521f43b0d605bba6cc36b190c064d5a0303e
kytos/core/link.py
kytos/core/link.py
import json from kytos.core.common import GenericEntity class Link(GenericEntity): """Define a link between two Endpoints.""" def __init__(self, endpoint_a, endpoint_b): """Create a Link instance and set its attributes.""" self.endpoint_a = endpoint_a self.endpoint_b = endpoint_b super().__init__() def __eq__(self, other): """Check if two instances of Link are equal.""" return ((self.endpoint_a == other.endpoint_a and self.endpoint_b == other.endpoint_b) or (self.endpoint_a == other.endpoint_b and self.endpoint_b == other.endpoint_a)) @property def id(self): # pylint: disable=invalid-name """Return id from Link intance. Returns: string: link id. """ return "{}:{}".format(self.endpoint_a.id, self.endpoint_b.id) def as_dict(self): """Return the Link as a dictionary.""" return {'id': self.id, 'endpoint_a': self.endpoint_a.as_dict(), 'endpoint_b': self.endpoint_b.as_dict(), 'metadata': self.metadata, 'active': self.active, 'enabled': self.enabled} def as_json(self): """Return the Link as a JSON string.""" return json.dumps(self.as_dict())
import json from uuid import uuid4 from kytos.core.common import GenericEntity class Link(GenericEntity): """Define a link between two Endpoints.""" def __init__(self, endpoint_a, endpoint_b): """Create a Link instance and set its attributes.""" self.endpoint_a = endpoint_a self.endpoint_b = endpoint_b self._uuid = uuid4() super().__init__() def __eq__(self, other): """Check if two instances of Link are equal.""" return ((self.endpoint_a == other.endpoint_a and self.endpoint_b == other.endpoint_b) or (self.endpoint_a == other.endpoint_b and self.endpoint_b == other.endpoint_a)) @property def id(self): # pylint: disable=invalid-name """Return id from Link intance. Returns: string: link id. """ return "{}".format(self._uuid) def as_dict(self): """Return the Link as a dictionary.""" return {'id': self.id, 'endpoint_a': self.endpoint_a.as_dict(), 'endpoint_b': self.endpoint_b.as_dict(), 'metadata': self.metadata, 'active': self.active, 'enabled': self.enabled} def as_json(self): """Return the Link as a JSON string.""" return json.dumps(self.as_dict())
Define Link ID as UUID
Define Link ID as UUID
Python
mit
kytos/kyco,kytos/kytos,renanrodrigo/kytos,macartur/kytos
python
## Code Before: import json from kytos.core.common import GenericEntity class Link(GenericEntity): """Define a link between two Endpoints.""" def __init__(self, endpoint_a, endpoint_b): """Create a Link instance and set its attributes.""" self.endpoint_a = endpoint_a self.endpoint_b = endpoint_b super().__init__() def __eq__(self, other): """Check if two instances of Link are equal.""" return ((self.endpoint_a == other.endpoint_a and self.endpoint_b == other.endpoint_b) or (self.endpoint_a == other.endpoint_b and self.endpoint_b == other.endpoint_a)) @property def id(self): # pylint: disable=invalid-name """Return id from Link intance. Returns: string: link id. """ return "{}:{}".format(self.endpoint_a.id, self.endpoint_b.id) def as_dict(self): """Return the Link as a dictionary.""" return {'id': self.id, 'endpoint_a': self.endpoint_a.as_dict(), 'endpoint_b': self.endpoint_b.as_dict(), 'metadata': self.metadata, 'active': self.active, 'enabled': self.enabled} def as_json(self): """Return the Link as a JSON string.""" return json.dumps(self.as_dict()) ## Instruction: Define Link ID as UUID ## Code After: import json from uuid import uuid4 from kytos.core.common import GenericEntity class Link(GenericEntity): """Define a link between two Endpoints.""" def __init__(self, endpoint_a, endpoint_b): """Create a Link instance and set its attributes.""" self.endpoint_a = endpoint_a self.endpoint_b = endpoint_b self._uuid = uuid4() super().__init__() def __eq__(self, other): """Check if two instances of Link are equal.""" return ((self.endpoint_a == other.endpoint_a and self.endpoint_b == other.endpoint_b) or (self.endpoint_a == other.endpoint_b and self.endpoint_b == other.endpoint_a)) @property def id(self): # pylint: disable=invalid-name """Return id from Link intance. Returns: string: link id. """ return "{}".format(self._uuid) def as_dict(self): """Return the Link as a dictionary.""" return {'id': self.id, 'endpoint_a': self.endpoint_a.as_dict(), 'endpoint_b': self.endpoint_b.as_dict(), 'metadata': self.metadata, 'active': self.active, 'enabled': self.enabled} def as_json(self): """Return the Link as a JSON string.""" return json.dumps(self.as_dict())
// ... existing code ... import json from uuid import uuid4 from kytos.core.common import GenericEntity // ... modified code ... """Create a Link instance and set its attributes.""" self.endpoint_a = endpoint_a self.endpoint_b = endpoint_b self._uuid = uuid4() super().__init__() def __eq__(self, other): ... string: link id. """ return "{}".format(self._uuid) def as_dict(self): """Return the Link as a dictionary.""" // ... rest of the code ...
59a7c02cc7f7caeb6a3a45f2fe4a0f37677286d8
web/src/main/java/uk/ac/ebi/atlas/commons/writers/impl/TsvWriterImpl.java
web/src/main/java/uk/ac/ebi/atlas/commons/writers/impl/TsvWriterImpl.java
package uk.ac.ebi.atlas.commons.writers.impl; import au.com.bytecode.opencsv.CSVWriter; import autovalue.shaded.com.google.common.common.base.Throwables; import uk.ac.ebi.atlas.commons.writers.TsvWriter; import java.io.IOException; import java.io.Writer; import java.util.List; public class TsvWriterImpl implements TsvWriter { private Writer writer; public TsvWriterImpl(Writer writer){ this.writer=writer; } @Override public void write(List<String[]> lines) { try(CSVWriter csvWriter = new CSVWriter(writer, '\t')){ csvWriter.writeAll(lines); } catch (IOException e) { throw Throwables.propagate(e); } } }
package uk.ac.ebi.atlas.commons.writers.impl; import au.com.bytecode.opencsv.CSVWriter; import com.google.common.base.Throwables; import uk.ac.ebi.atlas.commons.writers.TsvWriter; import java.io.IOException; import java.io.Writer; import java.util.List; public class TsvWriterImpl implements TsvWriter { private Writer writer; public TsvWriterImpl(Writer writer){ this.writer=writer; } @Override public void write(List<String[]> lines) { try(CSVWriter csvWriter = new CSVWriter(writer, '\t')){ csvWriter.writeAll(lines); } catch (IOException e) { throw Throwables.propagate(e); } } }
Replace shaded import with non-shaded one
Replace shaded import with non-shaded one
Java
apache-2.0
gxa/atlas,gxa/atlas,gxa/atlas,gxa/atlas,gxa/atlas
java
## Code Before: package uk.ac.ebi.atlas.commons.writers.impl; import au.com.bytecode.opencsv.CSVWriter; import autovalue.shaded.com.google.common.common.base.Throwables; import uk.ac.ebi.atlas.commons.writers.TsvWriter; import java.io.IOException; import java.io.Writer; import java.util.List; public class TsvWriterImpl implements TsvWriter { private Writer writer; public TsvWriterImpl(Writer writer){ this.writer=writer; } @Override public void write(List<String[]> lines) { try(CSVWriter csvWriter = new CSVWriter(writer, '\t')){ csvWriter.writeAll(lines); } catch (IOException e) { throw Throwables.propagate(e); } } } ## Instruction: Replace shaded import with non-shaded one ## Code After: package uk.ac.ebi.atlas.commons.writers.impl; import au.com.bytecode.opencsv.CSVWriter; import com.google.common.base.Throwables; import uk.ac.ebi.atlas.commons.writers.TsvWriter; import java.io.IOException; import java.io.Writer; import java.util.List; public class TsvWriterImpl implements TsvWriter { private Writer writer; public TsvWriterImpl(Writer writer){ this.writer=writer; } @Override public void write(List<String[]> lines) { try(CSVWriter csvWriter = new CSVWriter(writer, '\t')){ csvWriter.writeAll(lines); } catch (IOException e) { throw Throwables.propagate(e); } } }
# ... existing code ... package uk.ac.ebi.atlas.commons.writers.impl; import au.com.bytecode.opencsv.CSVWriter; import com.google.common.base.Throwables; import uk.ac.ebi.atlas.commons.writers.TsvWriter; import java.io.IOException; # ... rest of the code ...
2560ca287e81cbefb6037e5688bfa4ef74d85149
clock.py
clock.py
from __future__ import print_function from apscheduler.schedulers.blocking import BlockingScheduler import logging import subprocess logging.basicConfig() scheduler = BlockingScheduler() @scheduler.scheduled_job('interval', minutes=1) def timed_job_min1(): print("Run notifier") subprocess.run( "notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685", shell=True, check=True) # @scheduler.scheduled_job('interval', minutes=10) # def timed_job_min10(): # print("Run notifier") # subprocess.run( # "notifier -concurrency=5 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685", # shell=True, # check=True) scheduler.start()
from __future__ import print_function from apscheduler.schedulers.blocking import BlockingScheduler import logging import subprocess logging.basicConfig() scheduler = BlockingScheduler() @scheduler.scheduled_job('interval', minutes=1) def timed_job_min1(): print("Run notifier") subprocess.check_call( "notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685", shell=True) # @scheduler.scheduled_job('interval', minutes=10) # def timed_job_min10(): # print("Run notifier") # subprocess.run( # "notifier -concurrency=5 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685", # shell=True, # check=True) scheduler.start()
Change call method for Python2.7
Change call method for Python2.7
Python
mit
oinume/lekcije,oinume/dmm-eikaiwa-fft,oinume/lekcije,oinume/dmm-eikaiwa-fft,oinume/lekcije,oinume/dmm-eikaiwa-fft,oinume/lekcije,oinume/lekcije,oinume/lekcije,oinume/dmm-eikaiwa-fft
python
## Code Before: from __future__ import print_function from apscheduler.schedulers.blocking import BlockingScheduler import logging import subprocess logging.basicConfig() scheduler = BlockingScheduler() @scheduler.scheduled_job('interval', minutes=1) def timed_job_min1(): print("Run notifier") subprocess.run( "notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685", shell=True, check=True) # @scheduler.scheduled_job('interval', minutes=10) # def timed_job_min10(): # print("Run notifier") # subprocess.run( # "notifier -concurrency=5 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685", # shell=True, # check=True) scheduler.start() ## Instruction: Change call method for Python2.7 ## Code After: from __future__ import print_function from apscheduler.schedulers.blocking import BlockingScheduler import logging import subprocess logging.basicConfig() scheduler = BlockingScheduler() @scheduler.scheduled_job('interval', minutes=1) def timed_job_min1(): print("Run notifier") subprocess.check_call( "notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685", shell=True) # @scheduler.scheduled_job('interval', minutes=10) # def timed_job_min10(): # print("Run notifier") # subprocess.run( # "notifier -concurrency=5 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685", # shell=True, # check=True) scheduler.start()
# ... existing code ... @scheduler.scheduled_job('interval', minutes=1) def timed_job_min1(): print("Run notifier") subprocess.check_call( "notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685", shell=True) # @scheduler.scheduled_job('interval', minutes=10) # ... rest of the code ...
a3a5d2d6b76a4e903fea232b746b2df8b208ec9e
km3pipe/tests/test_plot.py
km3pipe/tests/test_plot.py
import numpy as np from km3pipe.testing import TestCase from km3pipe.plot import bincenters __author__ = "Moritz Lotze" __copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration." __credits__ = [] __license__ = "MIT" __maintainer__ = "Moritz Lotze" __email__ = "[email protected]" __status__ = "Development" class TestBins(TestCase): def test_binlims(self): bins = np.linspace(0, 20, 21) assert bincenters(bins).shape[0] == bins.shape[0] - 1
import numpy as np from km3pipe.testing import TestCase, patch from km3pipe.plot import bincenters, meshgrid, automeshgrid, diag __author__ = "Moritz Lotze" __copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration." __credits__ = [] __license__ = "MIT" __maintainer__ = "Moritz Lotze" __email__ = "[email protected]" __status__ = "Development" class TestBins(TestCase): def test_binlims(self): bins = np.linspace(0, 20, 21) assert bincenters(bins).shape[0] == bins.shape[0] - 1 class TestMeshStuff(TestCase): def test_meshgrid(self): xx, yy = meshgrid(-1, 1, 0.8) assert np.allclose([[-1.0, -0.2, 0.6], [-1.0, -0.2, 0.6], [-1.0, -0.2, 0.6]], xx) assert np.allclose([[-1.0, -1.0, -1.0], [-0.2, -0.2, -0.2], [0.6, 0.6, 0.6]], yy) def test_meshgrid_with_y_specs(self): xx, yy = meshgrid(-1, 1, 0.8, -10, 10, 8) assert np.allclose([[-1.0, -0.2, 0.6], [-1.0, -0.2, 0.6], [-1.0, -0.2, 0.6]], xx) assert np.allclose([[-10, -10, -10], [-2, -2, -2], [6, 6, 6]], yy) class TestDiag(TestCase): def test_call(self): diag()
Add tests for plot functions
Add tests for plot functions
Python
mit
tamasgal/km3pipe,tamasgal/km3pipe
python
## Code Before: import numpy as np from km3pipe.testing import TestCase from km3pipe.plot import bincenters __author__ = "Moritz Lotze" __copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration." __credits__ = [] __license__ = "MIT" __maintainer__ = "Moritz Lotze" __email__ = "[email protected]" __status__ = "Development" class TestBins(TestCase): def test_binlims(self): bins = np.linspace(0, 20, 21) assert bincenters(bins).shape[0] == bins.shape[0] - 1 ## Instruction: Add tests for plot functions ## Code After: import numpy as np from km3pipe.testing import TestCase, patch from km3pipe.plot import bincenters, meshgrid, automeshgrid, diag __author__ = "Moritz Lotze" __copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration." __credits__ = [] __license__ = "MIT" __maintainer__ = "Moritz Lotze" __email__ = "[email protected]" __status__ = "Development" class TestBins(TestCase): def test_binlims(self): bins = np.linspace(0, 20, 21) assert bincenters(bins).shape[0] == bins.shape[0] - 1 class TestMeshStuff(TestCase): def test_meshgrid(self): xx, yy = meshgrid(-1, 1, 0.8) assert np.allclose([[-1.0, -0.2, 0.6], [-1.0, -0.2, 0.6], [-1.0, -0.2, 0.6]], xx) assert np.allclose([[-1.0, -1.0, -1.0], [-0.2, -0.2, -0.2], [0.6, 0.6, 0.6]], yy) def test_meshgrid_with_y_specs(self): xx, yy = meshgrid(-1, 1, 0.8, -10, 10, 8) assert np.allclose([[-1.0, -0.2, 0.6], [-1.0, -0.2, 0.6], [-1.0, -0.2, 0.6]], xx) assert np.allclose([[-10, -10, -10], [-2, -2, -2], [6, 6, 6]], yy) class TestDiag(TestCase): def test_call(self): diag()
// ... existing code ... import numpy as np from km3pipe.testing import TestCase, patch from km3pipe.plot import bincenters, meshgrid, automeshgrid, diag __author__ = "Moritz Lotze" __copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration." // ... modified code ... def test_binlims(self): bins = np.linspace(0, 20, 21) assert bincenters(bins).shape[0] == bins.shape[0] - 1 class TestMeshStuff(TestCase): def test_meshgrid(self): xx, yy = meshgrid(-1, 1, 0.8) assert np.allclose([[-1.0, -0.2, 0.6], [-1.0, -0.2, 0.6], [-1.0, -0.2, 0.6]], xx) assert np.allclose([[-1.0, -1.0, -1.0], [-0.2, -0.2, -0.2], [0.6, 0.6, 0.6]], yy) def test_meshgrid_with_y_specs(self): xx, yy = meshgrid(-1, 1, 0.8, -10, 10, 8) assert np.allclose([[-1.0, -0.2, 0.6], [-1.0, -0.2, 0.6], [-1.0, -0.2, 0.6]], xx) assert np.allclose([[-10, -10, -10], [-2, -2, -2], [6, 6, 6]], yy) class TestDiag(TestCase): def test_call(self): diag() // ... rest of the code ...
1aa121daa3c99849173d5cd4c6a80d6bf94f5186
saleor/attribute/__init__.py
saleor/attribute/__init__.py
class AttributeInputType: """The type that we expect to render the attribute's values as.""" DROPDOWN = "dropdown" MULTISELECT = "multiselect" FILE = "file" REFERENCE = "reference" CHOICES = [ (DROPDOWN, "Dropdown"), (MULTISELECT, "Multi Select"), (FILE, "File"), (REFERENCE, "Reference"), ] # list of the input types that can be used in variant selection ALLOWED_IN_VARIANT_SELECTION = [DROPDOWN] class AttributeType: PRODUCT_TYPE = "product-type" PAGE_TYPE = "page-type" CHOICES = [(PRODUCT_TYPE, "Product type"), (PAGE_TYPE, "Page type")] class AttributeEntityType: """Type of a reference entity type. Must match the name of the graphql type.""" PAGE = "Page" PRODUCT = "Product" CHOICES = [(PAGE, "Page"), (PRODUCT, "Product")]
class AttributeInputType: """The type that we expect to render the attribute's values as.""" DROPDOWN = "dropdown" MULTISELECT = "multiselect" FILE = "file" REFERENCE = "reference" CHOICES = [ (DROPDOWN, "Dropdown"), (MULTISELECT, "Multi Select"), (FILE, "File"), (REFERENCE, "Reference"), ] # list of the input types that can be used in variant selection ALLOWED_IN_VARIANT_SELECTION = [DROPDOWN] class AttributeType: PRODUCT_TYPE = "product-type" PAGE_TYPE = "page-type" CHOICES = [(PRODUCT_TYPE, "Product type"), (PAGE_TYPE, "Page type")] class AttributeEntityType: """Type of a reference entity type. Must match the name of the graphql type. After adding new value, `REFERENCE_VALUE_NAME_MAPPING` and `ENTITY_TYPE_TO_MODEL_MAPPING` in saleor/graphql/attribute/utils.py must be updated. """ PAGE = "Page" PRODUCT = "Product" CHOICES = [(PAGE, "Page"), (PRODUCT, "Product")]
Add info about required updates in AttributeEntityType
Add info about required updates in AttributeEntityType
Python
bsd-3-clause
mociepka/saleor,mociepka/saleor,mociepka/saleor
python
## Code Before: class AttributeInputType: """The type that we expect to render the attribute's values as.""" DROPDOWN = "dropdown" MULTISELECT = "multiselect" FILE = "file" REFERENCE = "reference" CHOICES = [ (DROPDOWN, "Dropdown"), (MULTISELECT, "Multi Select"), (FILE, "File"), (REFERENCE, "Reference"), ] # list of the input types that can be used in variant selection ALLOWED_IN_VARIANT_SELECTION = [DROPDOWN] class AttributeType: PRODUCT_TYPE = "product-type" PAGE_TYPE = "page-type" CHOICES = [(PRODUCT_TYPE, "Product type"), (PAGE_TYPE, "Page type")] class AttributeEntityType: """Type of a reference entity type. Must match the name of the graphql type.""" PAGE = "Page" PRODUCT = "Product" CHOICES = [(PAGE, "Page"), (PRODUCT, "Product")] ## Instruction: Add info about required updates in AttributeEntityType ## Code After: class AttributeInputType: """The type that we expect to render the attribute's values as.""" DROPDOWN = "dropdown" MULTISELECT = "multiselect" FILE = "file" REFERENCE = "reference" CHOICES = [ (DROPDOWN, "Dropdown"), (MULTISELECT, "Multi Select"), (FILE, "File"), (REFERENCE, "Reference"), ] # list of the input types that can be used in variant selection ALLOWED_IN_VARIANT_SELECTION = [DROPDOWN] class AttributeType: PRODUCT_TYPE = "product-type" PAGE_TYPE = "page-type" CHOICES = [(PRODUCT_TYPE, "Product type"), (PAGE_TYPE, "Page type")] class AttributeEntityType: """Type of a reference entity type. Must match the name of the graphql type. After adding new value, `REFERENCE_VALUE_NAME_MAPPING` and `ENTITY_TYPE_TO_MODEL_MAPPING` in saleor/graphql/attribute/utils.py must be updated. """ PAGE = "Page" PRODUCT = "Product" CHOICES = [(PAGE, "Page"), (PRODUCT, "Product")]
# ... existing code ... class AttributeEntityType: """Type of a reference entity type. Must match the name of the graphql type. After adding new value, `REFERENCE_VALUE_NAME_MAPPING` and `ENTITY_TYPE_TO_MODEL_MAPPING` in saleor/graphql/attribute/utils.py must be updated. """ PAGE = "Page" PRODUCT = "Product" # ... rest of the code ...
d6929fa152bb8149fa9b4033135441030dd71260
authentic2/idp/idp_openid/context_processors.py
authentic2/idp/idp_openid/context_processors.py
def get_url(): return reverse('openid-provider-xrds') def openid_meta(request): context = { 'openid_server': context['request'].build_absolute_uri(get_url()) } content = '''<meta http-equiv="X-XRDS-Location" content="%(openid_server)s"/> <meta http-equiv="X-YADIS-Location" content="%(openid_server)s" /> ''' % context return { 'openid_meta': context }
from django.core.urlresolvers import reverse def get_url(): return reverse('openid-provider-xrds') def openid_meta(request): context = { 'openid_server': request.build_absolute_uri(get_url()) } content = '''<meta http-equiv="X-XRDS-Location" content="%(openid_server)s"/> <meta http-equiv="X-YADIS-Location" content="%(openid_server)s" /> ''' % context return { 'openid_meta': content }
Remove dependency on openid in the base template (bis)
Remove dependency on openid in the base template (bis) Fixes #1357
Python
agpl-3.0
BryceLohr/authentic,BryceLohr/authentic,incuna/authentic,incuna/authentic,adieu/authentic2,incuna/authentic,adieu/authentic2,adieu/authentic2,BryceLohr/authentic,pu239ppy/authentic2,adieu/authentic2,pu239ppy/authentic2,BryceLohr/authentic,pu239ppy/authentic2,incuna/authentic,pu239ppy/authentic2,incuna/authentic
python
## Code Before: def get_url(): return reverse('openid-provider-xrds') def openid_meta(request): context = { 'openid_server': context['request'].build_absolute_uri(get_url()) } content = '''<meta http-equiv="X-XRDS-Location" content="%(openid_server)s"/> <meta http-equiv="X-YADIS-Location" content="%(openid_server)s" /> ''' % context return { 'openid_meta': context } ## Instruction: Remove dependency on openid in the base template (bis) Fixes #1357 ## Code After: from django.core.urlresolvers import reverse def get_url(): return reverse('openid-provider-xrds') def openid_meta(request): context = { 'openid_server': request.build_absolute_uri(get_url()) } content = '''<meta http-equiv="X-XRDS-Location" content="%(openid_server)s"/> <meta http-equiv="X-YADIS-Location" content="%(openid_server)s" /> ''' % context return { 'openid_meta': content }
# ... existing code ... from django.core.urlresolvers import reverse def get_url(): return reverse('openid-provider-xrds') def openid_meta(request): context = { 'openid_server': request.build_absolute_uri(get_url()) } content = '''<meta http-equiv="X-XRDS-Location" content="%(openid_server)s"/> <meta http-equiv="X-YADIS-Location" content="%(openid_server)s" /> ''' % context return { 'openid_meta': content } # ... rest of the code ...
15ebd5a3509b20bad4cf0123dfac9be6878fa91c
app/models/bookmarks.py
app/models/bookmarks.py
from flask import current_app from .. import db, login_manager class Bookmarks(db.Model): id = db.Column(db.Integer, primary_key=True) listing_id = db.Column(db.Integer, unique=True) merchant_id = db.Column(db.Integer, db.ForeignKey('user.id')) #also needs to be added to Hunter's Vendors model def __init__(self, listing_id, merchant_id): self.listing_id = listing_id self.merchant_id = merchant_id def __repr__(self): return "<User: {} Bookmarked Listing: {}".format(self.merchant_id, self.listing_id)
from flask import current_app from .. import db, login_manager class Bookmarks(db.Model): id = db.Column(db.Integer, primary_key=True) listing_id = db.Column(db.Integer, unique=True) merchant_id = db.Column(db.Integer, db.ForeignKey('user.id')) merchant = db.relationship('User', backref=db.backref('bookmarks', lazy='dynamic')) def __init__(self, listing_id, merchant): self.listing_id = listing_id self.merchant = merchant def __repr__(self): return "<User: {} Bookmarked Listing: {}".format(self.merchant_id, self.listing_id)
Set up the relationship between bookmark and merchant
Set up the relationship between bookmark and merchant
Python
mit
hack4impact/reading-terminal-market,hack4impact/reading-terminal-market,hack4impact/reading-terminal-market
python
## Code Before: from flask import current_app from .. import db, login_manager class Bookmarks(db.Model): id = db.Column(db.Integer, primary_key=True) listing_id = db.Column(db.Integer, unique=True) merchant_id = db.Column(db.Integer, db.ForeignKey('user.id')) #also needs to be added to Hunter's Vendors model def __init__(self, listing_id, merchant_id): self.listing_id = listing_id self.merchant_id = merchant_id def __repr__(self): return "<User: {} Bookmarked Listing: {}".format(self.merchant_id, self.listing_id) ## Instruction: Set up the relationship between bookmark and merchant ## Code After: from flask import current_app from .. import db, login_manager class Bookmarks(db.Model): id = db.Column(db.Integer, primary_key=True) listing_id = db.Column(db.Integer, unique=True) merchant_id = db.Column(db.Integer, db.ForeignKey('user.id')) merchant = db.relationship('User', backref=db.backref('bookmarks', lazy='dynamic')) def __init__(self, listing_id, merchant): self.listing_id = listing_id self.merchant = merchant def __repr__(self): return "<User: {} Bookmarked Listing: {}".format(self.merchant_id, self.listing_id)
// ... existing code ... class Bookmarks(db.Model): id = db.Column(db.Integer, primary_key=True) listing_id = db.Column(db.Integer, unique=True) merchant_id = db.Column(db.Integer, db.ForeignKey('user.id')) merchant = db.relationship('User', backref=db.backref('bookmarks', lazy='dynamic')) def __init__(self, listing_id, merchant): self.listing_id = listing_id self.merchant = merchant def __repr__(self): return "<User: {} Bookmarked Listing: {}".format(self.merchant_id, self.listing_id) // ... rest of the code ...
cccd3fafcffa318fa783f857f84b5545028daca2
src/pubkey/if_algo/if_op.h
src/pubkey/if_algo/if_op.h
/************************************************* * IF Operations Header File * * (C) 1999-2008 Jack Lloyd * *************************************************/ #ifndef BOTAN_IF_OP_H__ #define BOTAN_IF_OP_H__ #include <botan/bigint.h> #include <botan/pow_mod.h> #include <botan/reducer.h> namespace Botan { /************************************************* * IF Operation * *************************************************/ class BOTAN_DLL IF_Operation { public: virtual BigInt public_op(const BigInt&) const = 0; virtual BigInt private_op(const BigInt&) const = 0; virtual IF_Operation* clone() const = 0; virtual ~IF_Operation() {} }; /************************************************* * Default IF Operation * *************************************************/ class Default_IF_Op : public IF_Operation { public: BigInt public_op(const BigInt& i) const { return powermod_e_n(i); } BigInt private_op(const BigInt&) const; IF_Operation* clone() const { return new Default_IF_Op(*this); } Default_IF_Op(const BigInt&, const BigInt&, const BigInt&, const BigInt&, const BigInt&, const BigInt&, const BigInt&, const BigInt&); private: Fixed_Exponent_Power_Mod powermod_e_n, powermod_d1_p, powermod_d2_q; Modular_Reducer reducer; BigInt c, q; }; } #endif
/************************************************* * IF Operations Header File * * (C) 1999-2008 Jack Lloyd * *************************************************/ #ifndef BOTAN_IF_OP_H__ #define BOTAN_IF_OP_H__ #include <botan/bigint.h> #include <botan/pow_mod.h> #include <botan/reducer.h> namespace Botan { /************************************************* * IF Operation * *************************************************/ class BOTAN_DLL IF_Operation { public: virtual BigInt public_op(const BigInt&) const = 0; virtual BigInt private_op(const BigInt&) const = 0; virtual IF_Operation* clone() const = 0; virtual ~IF_Operation() {} }; /************************************************* * Default IF Operation * *************************************************/ class BOTAN_DLL Default_IF_Op : public IF_Operation { public: BigInt public_op(const BigInt& i) const { return powermod_e_n(i); } BigInt private_op(const BigInt&) const; IF_Operation* clone() const { return new Default_IF_Op(*this); } Default_IF_Op(const BigInt&, const BigInt&, const BigInt&, const BigInt&, const BigInt&, const BigInt&, const BigInt&, const BigInt&); private: Fixed_Exponent_Power_Mod powermod_e_n, powermod_d1_p, powermod_d2_q; Modular_Reducer reducer; BigInt c, q; }; } #endif
Add BOTAN_DLL macro to Default_IF_Op
Add BOTAN_DLL macro to Default_IF_Op
C
bsd-2-clause
randombit/botan,webmaster128/botan,randombit/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,webmaster128/botan,randombit/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,randombit/botan,webmaster128/botan
c
## Code Before: /************************************************* * IF Operations Header File * * (C) 1999-2008 Jack Lloyd * *************************************************/ #ifndef BOTAN_IF_OP_H__ #define BOTAN_IF_OP_H__ #include <botan/bigint.h> #include <botan/pow_mod.h> #include <botan/reducer.h> namespace Botan { /************************************************* * IF Operation * *************************************************/ class BOTAN_DLL IF_Operation { public: virtual BigInt public_op(const BigInt&) const = 0; virtual BigInt private_op(const BigInt&) const = 0; virtual IF_Operation* clone() const = 0; virtual ~IF_Operation() {} }; /************************************************* * Default IF Operation * *************************************************/ class Default_IF_Op : public IF_Operation { public: BigInt public_op(const BigInt& i) const { return powermod_e_n(i); } BigInt private_op(const BigInt&) const; IF_Operation* clone() const { return new Default_IF_Op(*this); } Default_IF_Op(const BigInt&, const BigInt&, const BigInt&, const BigInt&, const BigInt&, const BigInt&, const BigInt&, const BigInt&); private: Fixed_Exponent_Power_Mod powermod_e_n, powermod_d1_p, powermod_d2_q; Modular_Reducer reducer; BigInt c, q; }; } #endif ## Instruction: Add BOTAN_DLL macro to Default_IF_Op ## Code After: /************************************************* * IF Operations Header File * * (C) 1999-2008 Jack Lloyd * *************************************************/ #ifndef BOTAN_IF_OP_H__ #define BOTAN_IF_OP_H__ #include <botan/bigint.h> #include <botan/pow_mod.h> #include <botan/reducer.h> namespace Botan { /************************************************* * IF Operation * *************************************************/ class BOTAN_DLL IF_Operation { public: virtual BigInt public_op(const BigInt&) const = 0; virtual BigInt private_op(const BigInt&) const = 0; virtual IF_Operation* clone() const = 0; virtual ~IF_Operation() {} }; /************************************************* * Default IF Operation * *************************************************/ class BOTAN_DLL Default_IF_Op : public IF_Operation { public: BigInt public_op(const BigInt& i) const { return powermod_e_n(i); } BigInt private_op(const BigInt&) const; IF_Operation* clone() const { return new Default_IF_Op(*this); } Default_IF_Op(const BigInt&, const BigInt&, const BigInt&, const BigInt&, const BigInt&, const BigInt&, const BigInt&, const BigInt&); private: Fixed_Exponent_Power_Mod powermod_e_n, powermod_d1_p, powermod_d2_q; Modular_Reducer reducer; BigInt c, q; }; } #endif
// ... existing code ... /************************************************* * Default IF Operation * *************************************************/ class BOTAN_DLL Default_IF_Op : public IF_Operation { public: BigInt public_op(const BigInt& i) const // ... rest of the code ...
8f094e1c3d4a64942cadf5603ce5b23706381fac
nubes/cmd/__init__.py
nubes/cmd/__init__.py
import openstack def main(): print("Hello Clouds!")
import argparse from nubes import dispatcher def main(): parser = argparse.ArgumentParser(description='Universal IaaS CLI') parser.add_argument('connector', help='IaaS Name') parser.add_argument('resource', help='Resource to perform action') parser.add_argument('action', help='Action to perform on resource') parser.add_argument('--auth-url') parser.add_argument('--username') parser.add_argument('--password') parser.add_argument('--project-name') args = parser.parse_args() dispatch = dispatcher.Dispatcher(args.connector, args.auth_url, args.username, args.password, args.project_name) resource = args.resource if args.action == 'list': # make plural resource = args.resource + 's' method_name = '_'.join([args.action, resource]) return getattr(dispatch, method_name)()
Make crude CLI commands work
Make crude CLI commands work This is mainly as an example to show what it can look like.
Python
apache-2.0
omninubes/nubes
python
## Code Before: import openstack def main(): print("Hello Clouds!") ## Instruction: Make crude CLI commands work This is mainly as an example to show what it can look like. ## Code After: import argparse from nubes import dispatcher def main(): parser = argparse.ArgumentParser(description='Universal IaaS CLI') parser.add_argument('connector', help='IaaS Name') parser.add_argument('resource', help='Resource to perform action') parser.add_argument('action', help='Action to perform on resource') parser.add_argument('--auth-url') parser.add_argument('--username') parser.add_argument('--password') parser.add_argument('--project-name') args = parser.parse_args() dispatch = dispatcher.Dispatcher(args.connector, args.auth_url, args.username, args.password, args.project_name) resource = args.resource if args.action == 'list': # make plural resource = args.resource + 's' method_name = '_'.join([args.action, resource]) return getattr(dispatch, method_name)()
# ... existing code ... import argparse from nubes import dispatcher def main(): parser = argparse.ArgumentParser(description='Universal IaaS CLI') parser.add_argument('connector', help='IaaS Name') parser.add_argument('resource', help='Resource to perform action') parser.add_argument('action', help='Action to perform on resource') parser.add_argument('--auth-url') parser.add_argument('--username') parser.add_argument('--password') parser.add_argument('--project-name') args = parser.parse_args() dispatch = dispatcher.Dispatcher(args.connector, args.auth_url, args.username, args.password, args.project_name) resource = args.resource if args.action == 'list': # make plural resource = args.resource + 's' method_name = '_'.join([args.action, resource]) return getattr(dispatch, method_name)() # ... rest of the code ...
62b90eb97c9e32280f7f1a9c1127099f20440c11
byceps/config_defaults.py
byceps/config_defaults.py
from datetime import timedelta from pytz import timezone # database connection SQLALCHEMY_ECHO = False # Disable Flask-SQLAlchemy's tracking of object modifications. SQLALCHEMY_TRACK_MODIFICATIONS = False # job queue JOBS_ASYNC = True # metrics METRICS_ENABLED = False # RQ dashboard (for job queue) RQ_DASHBOARD_ENABLED = False RQ_POLL_INTERVAL = 2500 # user accounts USER_REGISTRATION_ENABLED = True # login sessions PERMANENT_SESSION_LIFETIME = timedelta(14) # localization LOCALE = 'de_DE.UTF-8' LOCALES_FORMS = ['de'] # home page ROOT_REDIRECT_TARGET = None ROOT_REDIRECT_STATUS_CODE = 307 # news item pagination NEWS_ITEMS_PER_PAGE = 4 # message board pagination BOARD_TOPICS_PER_PAGE = 10 BOARD_POSTINGS_PER_PAGE = 10 # shop SHOP_ORDER_EXPORT_TIMEZONE = timezone('Europe/Berlin') # ticketing TICKET_MANAGEMENT_ENABLED = True # seating SEAT_MANAGEMENT_ENABLED = True
from datetime import timedelta from pytz import timezone # database connection SQLALCHEMY_ECHO = False # Disable Flask-SQLAlchemy's tracking of object modifications. SQLALCHEMY_TRACK_MODIFICATIONS = False # job queue JOBS_ASYNC = True # metrics METRICS_ENABLED = False # RQ dashboard (for job queue) RQ_DASHBOARD_ENABLED = False RQ_POLL_INTERVAL = 2500 WEB_BACKGROUND = 'white' # user accounts USER_REGISTRATION_ENABLED = True # login sessions PERMANENT_SESSION_LIFETIME = timedelta(14) # localization LOCALE = 'de_DE.UTF-8' LOCALES_FORMS = ['de'] # home page ROOT_REDIRECT_TARGET = None ROOT_REDIRECT_STATUS_CODE = 307 # news item pagination NEWS_ITEMS_PER_PAGE = 4 # message board pagination BOARD_TOPICS_PER_PAGE = 10 BOARD_POSTINGS_PER_PAGE = 10 # shop SHOP_ORDER_EXPORT_TIMEZONE = timezone('Europe/Berlin') # ticketing TICKET_MANAGEMENT_ENABLED = True # seating SEAT_MANAGEMENT_ENABLED = True
Set required background color for RQ dashboard
Set required background color for RQ dashboard BYCEPS doesn't use ra dashboard's default settings, so they need to be set explicitly as necessary.
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps
python
## Code Before: from datetime import timedelta from pytz import timezone # database connection SQLALCHEMY_ECHO = False # Disable Flask-SQLAlchemy's tracking of object modifications. SQLALCHEMY_TRACK_MODIFICATIONS = False # job queue JOBS_ASYNC = True # metrics METRICS_ENABLED = False # RQ dashboard (for job queue) RQ_DASHBOARD_ENABLED = False RQ_POLL_INTERVAL = 2500 # user accounts USER_REGISTRATION_ENABLED = True # login sessions PERMANENT_SESSION_LIFETIME = timedelta(14) # localization LOCALE = 'de_DE.UTF-8' LOCALES_FORMS = ['de'] # home page ROOT_REDIRECT_TARGET = None ROOT_REDIRECT_STATUS_CODE = 307 # news item pagination NEWS_ITEMS_PER_PAGE = 4 # message board pagination BOARD_TOPICS_PER_PAGE = 10 BOARD_POSTINGS_PER_PAGE = 10 # shop SHOP_ORDER_EXPORT_TIMEZONE = timezone('Europe/Berlin') # ticketing TICKET_MANAGEMENT_ENABLED = True # seating SEAT_MANAGEMENT_ENABLED = True ## Instruction: Set required background color for RQ dashboard BYCEPS doesn't use ra dashboard's default settings, so they need to be set explicitly as necessary. ## Code After: from datetime import timedelta from pytz import timezone # database connection SQLALCHEMY_ECHO = False # Disable Flask-SQLAlchemy's tracking of object modifications. SQLALCHEMY_TRACK_MODIFICATIONS = False # job queue JOBS_ASYNC = True # metrics METRICS_ENABLED = False # RQ dashboard (for job queue) RQ_DASHBOARD_ENABLED = False RQ_POLL_INTERVAL = 2500 WEB_BACKGROUND = 'white' # user accounts USER_REGISTRATION_ENABLED = True # login sessions PERMANENT_SESSION_LIFETIME = timedelta(14) # localization LOCALE = 'de_DE.UTF-8' LOCALES_FORMS = ['de'] # home page ROOT_REDIRECT_TARGET = None ROOT_REDIRECT_STATUS_CODE = 307 # news item pagination NEWS_ITEMS_PER_PAGE = 4 # message board pagination BOARD_TOPICS_PER_PAGE = 10 BOARD_POSTINGS_PER_PAGE = 10 # shop SHOP_ORDER_EXPORT_TIMEZONE = timezone('Europe/Berlin') # ticketing TICKET_MANAGEMENT_ENABLED = True # seating SEAT_MANAGEMENT_ENABLED = True
// ... existing code ... # RQ dashboard (for job queue) RQ_DASHBOARD_ENABLED = False RQ_POLL_INTERVAL = 2500 WEB_BACKGROUND = 'white' # user accounts USER_REGISTRATION_ENABLED = True // ... rest of the code ...
be44f004de4ea2201497755a74f7eacbaf26509b
src/main/java/fr/insee/pogues/webservice/rest/StromaePublishing.java
src/main/java/fr/insee/pogues/webservice/rest/StromaePublishing.java
package fr.insee.pogues.webservice.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; import org.apache.log4j.Logger; /** * Main WebService class of the StromaePublishing service * * @author I6VWID * */ @Path("/StromaePublishing") public class StromaePublishing { final static Logger logger = Logger.getLogger(StromaePublishing.class); /** * Dummy GET Helloworld used in unit tests * * @return "Hello world" as a String */ @GET @Path("helloworld") public String helloworld() { return "Hello world"; } }
package fr.insee.pogues.webservice.rest; import javax.ws.rs.Consumes; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.apache.log4j.Logger; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.Authorization; /** * Main WebService class of the StromaePublishing service * * @author I6VWID * */ @Path("/StromaePublishing") @Api(value = "PoguesStromaePublishing", authorizations = { @Authorization(value="sampleoauth", scopes = {}) }) public class StromaePublishing { final static Logger logger = Logger.getLogger(StromaePublishing.class); /** * Publish a questionnaire on the vizualisation platform * * @param name: * questionnaire * * in: body * * description: The questionnaire to publish * * required: true * * * @return 200: description: The questionnaire was published * * 400: description: Malformed object in the query * * 401: description: The client is not authorized for this operation */ @PUT @Path("questionnaire") @Consumes(MediaType.APPLICATION_JSON) @ApiOperation(value = "publishQuestionnaire", notes = "Publish a questionnaire on the vizualisation platform", response = String.class) public Response publishQuestionnaire(String jsonContent) { return Response.status(Status.NOT_IMPLEMENTED).build(); } }
Add swagger doc for StromaeAPI
Add swagger doc for StromaeAPI
Java
mit
InseeFr/Pogues-Back-Office,InseeFr/Pogues-Back-Office
java
## Code Before: package fr.insee.pogues.webservice.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; import org.apache.log4j.Logger; /** * Main WebService class of the StromaePublishing service * * @author I6VWID * */ @Path("/StromaePublishing") public class StromaePublishing { final static Logger logger = Logger.getLogger(StromaePublishing.class); /** * Dummy GET Helloworld used in unit tests * * @return "Hello world" as a String */ @GET @Path("helloworld") public String helloworld() { return "Hello world"; } } ## Instruction: Add swagger doc for StromaeAPI ## Code After: package fr.insee.pogues.webservice.rest; import javax.ws.rs.Consumes; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.apache.log4j.Logger; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.Authorization; /** * Main WebService class of the StromaePublishing service * * @author I6VWID * */ @Path("/StromaePublishing") @Api(value = "PoguesStromaePublishing", authorizations = { @Authorization(value="sampleoauth", scopes = {}) }) public class StromaePublishing { final static Logger logger = Logger.getLogger(StromaePublishing.class); /** * Publish a questionnaire on the vizualisation platform * * @param name: * questionnaire * * in: body * * description: The questionnaire to publish * * required: true * * * @return 200: description: The questionnaire was published * * 400: description: Malformed object in the query * * 401: description: The client is not authorized for this operation */ @PUT @Path("questionnaire") @Consumes(MediaType.APPLICATION_JSON) @ApiOperation(value = "publishQuestionnaire", notes = "Publish a questionnaire on the vizualisation platform", response = String.class) public Response publishQuestionnaire(String jsonContent) { return Response.status(Status.NOT_IMPLEMENTED).build(); } }
// ... existing code ... package fr.insee.pogues.webservice.rest; import javax.ws.rs.Consumes; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.apache.log4j.Logger; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.Authorization; /** * Main WebService class of the StromaePublishing service // ... modified code ... * */ @Path("/StromaePublishing") @Api(value = "PoguesStromaePublishing", authorizations = { @Authorization(value="sampleoauth", scopes = {}) }) public class StromaePublishing { final static Logger logger = Logger.getLogger(StromaePublishing.class); /** * Publish a questionnaire on the vizualisation platform * * @param name: * questionnaire * * in: body * * description: The questionnaire to publish * * required: true * * * @return 200: description: The questionnaire was published * * 400: description: Malformed object in the query * * 401: description: The client is not authorized for this operation */ @PUT @Path("questionnaire") @Consumes(MediaType.APPLICATION_JSON) @ApiOperation(value = "publishQuestionnaire", notes = "Publish a questionnaire on the vizualisation platform", response = String.class) public Response publishQuestionnaire(String jsonContent) { return Response.status(Status.NOT_IMPLEMENTED).build(); } } // ... rest of the code ...
de3161d66ab0a5661d98ace04f5f0ae7c01062bf
smsgateway/utils.py
smsgateway/utils.py
import logging logger = logging.getLogger(__name__) def strspn(source, allowed): newchrs = [] for c in source: if c in allowed: newchrs.append(c) return u''.join(newchrs) def check_cell_phone_number(number): cleaned_number = strspn(number, u'+0123456789') if not u'+' in cleaned_number[:1]: cleaned_number = u'+%s' % cleaned_number return cleaned_number def truncate_sms(text, max_length=160): if len(text) <= max_length: return text else: logger.error("Trying to send an SMS that is too long: %s", text) return text[:max_length-3] + '...' def parse_sms(content): content = content.upper().strip() from smsgateway.backends.base import hook for keyword, subkeywords in hook.iteritems(): if content[:len(keyword)] == unicode(keyword): remainder = content[len(keyword):].strip() if '*' in subkeywords: parts = remainder.split(u' ') subkeyword = parts[0].strip() if subkeyword in subkeywords: return [keyword] + parts return keyword, remainder else: for subkeyword in subkeywords: if remainder[:len(subkeyword)] == unicode(subkeyword): subremainder = remainder[len(subkeyword):].strip() return [keyword, subkeyword] + subremainder.split() return None
import logging logger = logging.getLogger(__name__) def strspn(source, allowed): newchrs = [] for c in source: if c in allowed: newchrs.append(c) return u''.join(newchrs) def check_cell_phone_number(number): cleaned_number = strspn(number, u'0123456789') #if not u'+' in cleaned_number[:1]: # cleaned_number = u'+%s' % cleaned_number return int(cleaned_number) def truncate_sms(text, max_length=160): if len(text) <= max_length: return text else: logger.error("Trying to send an SMS that is too long: %s", text) return text[:max_length-3] + '...' def parse_sms(content): content = content.upper().strip() from smsgateway.backends.base import hook for keyword, subkeywords in hook.iteritems(): if content[:len(keyword)] == unicode(keyword): remainder = content[len(keyword):].strip() if '*' in subkeywords: parts = remainder.split(u' ') subkeyword = parts[0].strip() if subkeyword in subkeywords: return [keyword] + parts return keyword, remainder else: for subkeyword in subkeywords: if remainder[:len(subkeyword)] == unicode(subkeyword): subremainder = remainder[len(subkeyword):].strip() return [keyword, subkeyword] + subremainder.split() return None
Use international MSISDN format according to SMPP protocol spec: 4.2.6.1.1
Use international MSISDN format according to SMPP protocol spec: 4.2.6.1.1
Python
bsd-3-clause
peterayeni/django-smsgateway,peterayeni/django-smsgateway,mvpoland/django-smsgateway,mvpoland/django-smsgateway,peterayeni/django-smsgateway,mvpoland/django-smsgateway,peterayeni/django-smsgateway
python
## Code Before: import logging logger = logging.getLogger(__name__) def strspn(source, allowed): newchrs = [] for c in source: if c in allowed: newchrs.append(c) return u''.join(newchrs) def check_cell_phone_number(number): cleaned_number = strspn(number, u'+0123456789') if not u'+' in cleaned_number[:1]: cleaned_number = u'+%s' % cleaned_number return cleaned_number def truncate_sms(text, max_length=160): if len(text) <= max_length: return text else: logger.error("Trying to send an SMS that is too long: %s", text) return text[:max_length-3] + '...' def parse_sms(content): content = content.upper().strip() from smsgateway.backends.base import hook for keyword, subkeywords in hook.iteritems(): if content[:len(keyword)] == unicode(keyword): remainder = content[len(keyword):].strip() if '*' in subkeywords: parts = remainder.split(u' ') subkeyword = parts[0].strip() if subkeyword in subkeywords: return [keyword] + parts return keyword, remainder else: for subkeyword in subkeywords: if remainder[:len(subkeyword)] == unicode(subkeyword): subremainder = remainder[len(subkeyword):].strip() return [keyword, subkeyword] + subremainder.split() return None ## Instruction: Use international MSISDN format according to SMPP protocol spec: 4.2.6.1.1 ## Code After: import logging logger = logging.getLogger(__name__) def strspn(source, allowed): newchrs = [] for c in source: if c in allowed: newchrs.append(c) return u''.join(newchrs) def check_cell_phone_number(number): cleaned_number = strspn(number, u'0123456789') #if not u'+' in cleaned_number[:1]: # cleaned_number = u'+%s' % cleaned_number return int(cleaned_number) def truncate_sms(text, max_length=160): if len(text) <= max_length: return text else: logger.error("Trying to send an SMS that is too long: %s", text) return text[:max_length-3] + '...' def parse_sms(content): content = content.upper().strip() from smsgateway.backends.base import hook for keyword, subkeywords in hook.iteritems(): if content[:len(keyword)] == unicode(keyword): remainder = content[len(keyword):].strip() if '*' in subkeywords: parts = remainder.split(u' ') subkeyword = parts[0].strip() if subkeyword in subkeywords: return [keyword] + parts return keyword, remainder else: for subkeyword in subkeywords: if remainder[:len(subkeyword)] == unicode(subkeyword): subremainder = remainder[len(subkeyword):].strip() return [keyword, subkeyword] + subremainder.split() return None
// ... existing code ... return u''.join(newchrs) def check_cell_phone_number(number): cleaned_number = strspn(number, u'0123456789') #if not u'+' in cleaned_number[:1]: # cleaned_number = u'+%s' % cleaned_number return int(cleaned_number) def truncate_sms(text, max_length=160): if len(text) <= max_length: // ... rest of the code ...
251d93f45709bf8d8022a33a779dad7c3b61e4b7
box-content-sdk/src/main/java/com/box/androidsdk/content/models/BoxIteratorRecentItems.java
box-content-sdk/src/main/java/com/box/androidsdk/content/models/BoxIteratorRecentItems.java
package com.box.androidsdk.content.models; /** * A class representing list of BoxRecentItem's */ public class BoxIteratorRecentItems extends BoxIterator<BoxRecentItem> { private static final long serialVersionUID = -2642748896882484555L; private transient BoxJsonObjectCreator<BoxRecentItem> representationCreator; @Override protected BoxJsonObjectCreator<BoxRecentItem> getObjectCreator() { if (representationCreator != null){ return representationCreator; } representationCreator = BoxJsonObject.getBoxJsonObjectCreator(BoxRecentItem.class); return representationCreator; } }
package com.box.androidsdk.content.models; import com.eclipsesource.json.JsonObject; /** * A class representing list of BoxRecentItem's */ public class BoxIteratorRecentItems extends BoxIterator<BoxRecentItem> { private static final long serialVersionUID = -2642748896882484555L; private transient BoxJsonObjectCreator<BoxRecentItem> representationCreator; public BoxIteratorRecentItems() { super(); } public BoxIteratorRecentItems(JsonObject jsonObject) { super(jsonObject); } @Override protected BoxJsonObjectCreator<BoxRecentItem> getObjectCreator() { if (representationCreator != null){ return representationCreator; } representationCreator = BoxJsonObject.getBoxJsonObjectCreator(BoxRecentItem.class); return representationCreator; } }
Store the GET response in levelDB and populate the UI
AND-7057: Store the GET response in levelDB and populate the UI Creating necessary constuctors for BoxIteratorRecentItems
Java
apache-2.0
box/box-android-sdk,seema-at-box/box-android-sdk,box/box-android-sdk,seema-at-box/box-android-sdk,box/box-android-sdk,seema-at-box/box-android-sdk
java
## Code Before: package com.box.androidsdk.content.models; /** * A class representing list of BoxRecentItem's */ public class BoxIteratorRecentItems extends BoxIterator<BoxRecentItem> { private static final long serialVersionUID = -2642748896882484555L; private transient BoxJsonObjectCreator<BoxRecentItem> representationCreator; @Override protected BoxJsonObjectCreator<BoxRecentItem> getObjectCreator() { if (representationCreator != null){ return representationCreator; } representationCreator = BoxJsonObject.getBoxJsonObjectCreator(BoxRecentItem.class); return representationCreator; } } ## Instruction: AND-7057: Store the GET response in levelDB and populate the UI Creating necessary constuctors for BoxIteratorRecentItems ## Code After: package com.box.androidsdk.content.models; import com.eclipsesource.json.JsonObject; /** * A class representing list of BoxRecentItem's */ public class BoxIteratorRecentItems extends BoxIterator<BoxRecentItem> { private static final long serialVersionUID = -2642748896882484555L; private transient BoxJsonObjectCreator<BoxRecentItem> representationCreator; public BoxIteratorRecentItems() { super(); } public BoxIteratorRecentItems(JsonObject jsonObject) { super(jsonObject); } @Override protected BoxJsonObjectCreator<BoxRecentItem> getObjectCreator() { if (representationCreator != null){ return representationCreator; } representationCreator = BoxJsonObject.getBoxJsonObjectCreator(BoxRecentItem.class); return representationCreator; } }
... package com.box.androidsdk.content.models; import com.eclipsesource.json.JsonObject; /** * A class representing list of BoxRecentItem's ... private static final long serialVersionUID = -2642748896882484555L; private transient BoxJsonObjectCreator<BoxRecentItem> representationCreator; public BoxIteratorRecentItems() { super(); } public BoxIteratorRecentItems(JsonObject jsonObject) { super(jsonObject); } @Override protected BoxJsonObjectCreator<BoxRecentItem> getObjectCreator() { ...
b071e9c5ac8ae479c8c5ab38c2e0a886c846b0e5
pybossa/repositories/project_stats_repository.py
pybossa/repositories/project_stats_repository.py
from sqlalchemy import or_, func from sqlalchemy.exc import IntegrityError from pybossa.repositories import Repository from pybossa.model.project_stats import ProjectStats from pybossa.exc import WrongObjectError, DBIntegrityError class ProjectStatsRepository(Repository): def __init__(self, db): self.db = db def get(self, id): return self.db.session.query(ProjectStats).get(id) def filter_by(self, limit=None, offset=0, yielded=False, last_id=None, desc=False, **filters): return self._filter_by(ProjectStats, limit, offset, yielded, last_id, **filters)
from sqlalchemy import or_, func from sqlalchemy.exc import IntegrityError from pybossa.repositories import Repository from pybossa.model.project_stats import ProjectStats from pybossa.exc import WrongObjectError, DBIntegrityError class ProjectStatsRepository(Repository): def __init__(self, db): self.db = db def get(self, id): return self.db.session.query(ProjectStats).get(id) def filter_by(self, limit=None, offset=0, yielded=False, last_id=None, fulltextsearch=None, desc=False, orderby='id', **filters): return self._filter_by(ProjectStats, limit, offset, yielded, last_id, fulltextsearch, desc, orderby, **filters)
Add desc and orderby to repo
Add desc and orderby to repo
Python
agpl-3.0
Scifabric/pybossa,PyBossa/pybossa,Scifabric/pybossa,PyBossa/pybossa
python
## Code Before: from sqlalchemy import or_, func from sqlalchemy.exc import IntegrityError from pybossa.repositories import Repository from pybossa.model.project_stats import ProjectStats from pybossa.exc import WrongObjectError, DBIntegrityError class ProjectStatsRepository(Repository): def __init__(self, db): self.db = db def get(self, id): return self.db.session.query(ProjectStats).get(id) def filter_by(self, limit=None, offset=0, yielded=False, last_id=None, desc=False, **filters): return self._filter_by(ProjectStats, limit, offset, yielded, last_id, **filters) ## Instruction: Add desc and orderby to repo ## Code After: from sqlalchemy import or_, func from sqlalchemy.exc import IntegrityError from pybossa.repositories import Repository from pybossa.model.project_stats import ProjectStats from pybossa.exc import WrongObjectError, DBIntegrityError class ProjectStatsRepository(Repository): def __init__(self, db): self.db = db def get(self, id): return self.db.session.query(ProjectStats).get(id) def filter_by(self, limit=None, offset=0, yielded=False, last_id=None, fulltextsearch=None, desc=False, orderby='id', **filters): return self._filter_by(ProjectStats, limit, offset, yielded, last_id, fulltextsearch, desc, orderby, **filters)
// ... existing code ... return self.db.session.query(ProjectStats).get(id) def filter_by(self, limit=None, offset=0, yielded=False, last_id=None, fulltextsearch=None, desc=False, orderby='id', **filters): return self._filter_by(ProjectStats, limit, offset, yielded, last_id, fulltextsearch, desc, orderby, **filters) // ... rest of the code ...