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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
3249f48c79fefb59f834a02fb8c0acb816064610
|
include/shell.h
|
include/shell.h
|
__FUNCTION__, \
__LINE__, \
strerror(errno));
#define sizeof_array(x) (sizeof(x) / sizeof(*x))
#define DEFAULT_PROMPT "$ "
#define DEFAULT_PATH "/bin:/usr/bin/:/sbin/:/usr/local/bin"
#define DEFAULT_HOME "/"
typedef struct command_t{
char **array;
unsigned int elements;
}command_t;
typedef struct shell_t{
bool running;
struct environ_t *env;
pid_t shell_pid;
char *pwd;
}shell_t;
char *copy_string(const char *str);
unsigned int count_token(char *string, const char *token_string);
void free_command(command_t *command);
command_t *parse(char *line);
int change_shell_dir(char *path);
int execute_builtins(char **input);
int execute_command(command_t *c);
#endif
|
__FUNCTION__, \
__LINE__, \
strerror(errno));
#define sizeof_array(x) (sizeof(x) / sizeof(*x))
typedef struct command_t{
char **array;
unsigned int elements;
}command_t;
typedef struct shell_t{
bool running;
struct environ_t *env;
pid_t shell_pid;
char *pwd;
}shell_t;
char *copy_string(const char *str);
unsigned int count_token(char *string, const char *token_string);
void free_command(command_t *command);
command_t *parse(char *line);
int change_shell_dir(char *path);
int execute_builtins(char **input);
int execute_command(command_t *c);
#endif
|
Remove double definition of default env variables
|
Remove double definition of default env variables
|
C
|
mit
|
tywkeene/Shell
|
c
|
## Code Before:
__FUNCTION__, \
__LINE__, \
strerror(errno));
#define sizeof_array(x) (sizeof(x) / sizeof(*x))
#define DEFAULT_PROMPT "$ "
#define DEFAULT_PATH "/bin:/usr/bin/:/sbin/:/usr/local/bin"
#define DEFAULT_HOME "/"
typedef struct command_t{
char **array;
unsigned int elements;
}command_t;
typedef struct shell_t{
bool running;
struct environ_t *env;
pid_t shell_pid;
char *pwd;
}shell_t;
char *copy_string(const char *str);
unsigned int count_token(char *string, const char *token_string);
void free_command(command_t *command);
command_t *parse(char *line);
int change_shell_dir(char *path);
int execute_builtins(char **input);
int execute_command(command_t *c);
#endif
## Instruction:
Remove double definition of default env variables
## Code After:
__FUNCTION__, \
__LINE__, \
strerror(errno));
#define sizeof_array(x) (sizeof(x) / sizeof(*x))
typedef struct command_t{
char **array;
unsigned int elements;
}command_t;
typedef struct shell_t{
bool running;
struct environ_t *env;
pid_t shell_pid;
char *pwd;
}shell_t;
char *copy_string(const char *str);
unsigned int count_token(char *string, const char *token_string);
void free_command(command_t *command);
command_t *parse(char *line);
int change_shell_dir(char *path);
int execute_builtins(char **input);
int execute_command(command_t *c);
#endif
|
...
strerror(errno));
#define sizeof_array(x) (sizeof(x) / sizeof(*x))
typedef struct command_t{
char **array;
...
|
75e0c323871d6eae6959523b105a06cfe8460a28
|
etk2/etk.py
|
etk2/etk.py
|
import json
class ETK(object):
def __init__(self):
pass
def get_glossary(self, file_path):
res = dict()
with open(file_path) as fp:
line = fp.readline().rstrip('\n')
while line:
res[line] = line
line = fp.readline().rstrip('\n')
return res
def invoke_extractor(self, extractor=None, doc=None, json_path=None, input_key=None, output_key=None):
# cache parsed json_path, not a string, globally
containers = doc.cdr_document['__content_strict']
# containers = doc.select_containers(json_path)
if isinstance(containers, list):
for c in containers:
segment = c.get(input_key)
tokens = doc.get_tokens(segment)
else:
segment = containers.get(input_key)
tokens = doc.get_tokens(segment)
fake_extraction = [i.text for i in tokens]
doc.store_extraction(extractor, fake_extraction, containers, output_key)
print(json.dumps(doc.cdr_document, indent=2))
# if extractor.requires_tokens():
# tokens = doc.get_tokens(segment, tokenizer=extractor.preferred_tokenizer())
# if tokens:
# extraction = extractor.extract(tokens, doc)
# doc.store_extraction(extractor, extraction, c, output_key)
|
from typing import List
import json
class ETK(object):
def __init__(self):
pass
def get_glossary(self, file_path) -> List[str]:
"""
A glossary is a text file, one entry per line.
Args:
file_path (str): path to a text file containing a glossary.
Returns: List of the strings in the glossary.
"""
#to-do: this should be a list, not a dict
res = dict()
with open(file_path) as fp:
line = fp.readline().rstrip('\n')
while line:
res[line] = line
line = fp.readline().rstrip('\n')
return res
def invoke_extractor(self, extractor=None, doc=None, json_path=None, input_key=None, output_key=None):
# cache parsed json_path, not a string, globally
containers = doc.cdr_document['__content_strict']
# containers = doc.select_containers(json_path)
if isinstance(containers, list):
for c in containers:
segment = c.get(input_key)
tokens = doc.get_tokens(segment)
else:
segment = containers.get(input_key)
tokens = doc.get_tokens(segment)
fake_extraction = [i.text for i in tokens]
doc.store_extraction(extractor, fake_extraction, containers, output_key)
print(json.dumps(doc.cdr_document, indent=2))
# if extractor.requires_tokens():
# tokens = doc.get_tokens(segment, tokenizer=extractor.preferred_tokenizer())
# if tokens:
# extraction = extractor.extract(tokens, doc)
# doc.store_extraction(extractor, extraction, c, output_key)
|
Add comments and typing annotations
|
Add comments and typing annotations
|
Python
|
mit
|
usc-isi-i2/etk,usc-isi-i2/etk,usc-isi-i2/etk
|
python
|
## Code Before:
import json
class ETK(object):
def __init__(self):
pass
def get_glossary(self, file_path):
res = dict()
with open(file_path) as fp:
line = fp.readline().rstrip('\n')
while line:
res[line] = line
line = fp.readline().rstrip('\n')
return res
def invoke_extractor(self, extractor=None, doc=None, json_path=None, input_key=None, output_key=None):
# cache parsed json_path, not a string, globally
containers = doc.cdr_document['__content_strict']
# containers = doc.select_containers(json_path)
if isinstance(containers, list):
for c in containers:
segment = c.get(input_key)
tokens = doc.get_tokens(segment)
else:
segment = containers.get(input_key)
tokens = doc.get_tokens(segment)
fake_extraction = [i.text for i in tokens]
doc.store_extraction(extractor, fake_extraction, containers, output_key)
print(json.dumps(doc.cdr_document, indent=2))
# if extractor.requires_tokens():
# tokens = doc.get_tokens(segment, tokenizer=extractor.preferred_tokenizer())
# if tokens:
# extraction = extractor.extract(tokens, doc)
# doc.store_extraction(extractor, extraction, c, output_key)
## Instruction:
Add comments and typing annotations
## Code After:
from typing import List
import json
class ETK(object):
def __init__(self):
pass
def get_glossary(self, file_path) -> List[str]:
"""
A glossary is a text file, one entry per line.
Args:
file_path (str): path to a text file containing a glossary.
Returns: List of the strings in the glossary.
"""
#to-do: this should be a list, not a dict
res = dict()
with open(file_path) as fp:
line = fp.readline().rstrip('\n')
while line:
res[line] = line
line = fp.readline().rstrip('\n')
return res
def invoke_extractor(self, extractor=None, doc=None, json_path=None, input_key=None, output_key=None):
# cache parsed json_path, not a string, globally
containers = doc.cdr_document['__content_strict']
# containers = doc.select_containers(json_path)
if isinstance(containers, list):
for c in containers:
segment = c.get(input_key)
tokens = doc.get_tokens(segment)
else:
segment = containers.get(input_key)
tokens = doc.get_tokens(segment)
fake_extraction = [i.text for i in tokens]
doc.store_extraction(extractor, fake_extraction, containers, output_key)
print(json.dumps(doc.cdr_document, indent=2))
# if extractor.requires_tokens():
# tokens = doc.get_tokens(segment, tokenizer=extractor.preferred_tokenizer())
# if tokens:
# extraction = extractor.extract(tokens, doc)
# doc.store_extraction(extractor, extraction, c, output_key)
|
// ... existing code ...
from typing import List
import json
class ETK(object):
// ... modified code ...
def __init__(self):
pass
def get_glossary(self, file_path) -> List[str]:
"""
A glossary is a text file, one entry per line.
Args:
file_path (str): path to a text file containing a glossary.
Returns: List of the strings in the glossary.
"""
#to-do: this should be a list, not a dict
res = dict()
with open(file_path) as fp:
line = fp.readline().rstrip('\n')
...
res[line] = line
line = fp.readline().rstrip('\n')
return res
def invoke_extractor(self, extractor=None, doc=None, json_path=None, input_key=None, output_key=None):
# cache parsed json_path, not a string, globally
// ... rest of the code ...
|
da56651517b98d4a4c4f629e30d17b9d34e1c606
|
src/protocolsupport/zplatform/impl/spigot/block/SpigotBlocksBoundsAdjust.java
|
src/protocolsupport/zplatform/impl/spigot/block/SpigotBlocksBoundsAdjust.java
|
package protocolsupport.zplatform.impl.spigot.block;
import net.minecraft.server.v1_14_R1.BlockWaterLily;
import net.minecraft.server.v1_14_R1.VoxelShapes;
import protocolsupport.utils.ReflectionUtils;
public class SpigotBlocksBoundsAdjust {
public static void inject() throws IllegalAccessException {
ReflectionUtils.cloneFields(VoxelShapes.create(0.0625, 0.0, 0.0625, 0.9375, 0.015625, 0.9375), ReflectionUtils.getField(BlockWaterLily.class, "a").get(null));
}
}
|
package protocolsupport.zplatform.impl.spigot.block;
import net.minecraft.server.v1_14_R1.BlockLadder;
import net.minecraft.server.v1_14_R1.BlockWaterLily;
import net.minecraft.server.v1_14_R1.VoxelShapes;
import protocolsupport.utils.ReflectionUtils;
public class SpigotBlocksBoundsAdjust {
public static void inject() throws IllegalAccessException {
ReflectionUtils.cloneFields(VoxelShapes.create(0.0625D, 0.0, 0.0625D, 0.9375D, 0.015625D, 0.9375D), ReflectionUtils.getField(BlockWaterLily.class, "a").get(null));
ReflectionUtils.cloneFields(VoxelShapes.create(0.0D, 0.0D, 0.0D, 0.124D, 1.0D, 1.0D), ReflectionUtils.getField(BlockLadder.class, "c").get(null));
ReflectionUtils.cloneFields(VoxelShapes.create(0.876D, 0.0D, 0.0D, 1.0D, 1.0D, 1.0D), ReflectionUtils.getField(BlockLadder.class, "d").get(null));
ReflectionUtils.cloneFields(VoxelShapes.create(0.0D, 0.0D, 0.0D, 1.0D, 1.0D, 0.124D), ReflectionUtils.getField(BlockLadder.class, "e").get(null));
ReflectionUtils.cloneFields(VoxelShapes.create(0.0D, 0.0D, 0.876D, 1.0D, 1.0D, 1.0D), ReflectionUtils.getField(BlockLadder.class, "f").get(null));
}
}
|
Set ladder bounds to pre 1.9.
|
Set ladder bounds to pre 1.9.
A bit smaller actually, but it has to be done, so the VoxelShape type is
the same.
|
Java
|
agpl-3.0
|
ProtocolSupport/ProtocolSupport
|
java
|
## Code Before:
package protocolsupport.zplatform.impl.spigot.block;
import net.minecraft.server.v1_14_R1.BlockWaterLily;
import net.minecraft.server.v1_14_R1.VoxelShapes;
import protocolsupport.utils.ReflectionUtils;
public class SpigotBlocksBoundsAdjust {
public static void inject() throws IllegalAccessException {
ReflectionUtils.cloneFields(VoxelShapes.create(0.0625, 0.0, 0.0625, 0.9375, 0.015625, 0.9375), ReflectionUtils.getField(BlockWaterLily.class, "a").get(null));
}
}
## Instruction:
Set ladder bounds to pre 1.9.
A bit smaller actually, but it has to be done, so the VoxelShape type is
the same.
## Code After:
package protocolsupport.zplatform.impl.spigot.block;
import net.minecraft.server.v1_14_R1.BlockLadder;
import net.minecraft.server.v1_14_R1.BlockWaterLily;
import net.minecraft.server.v1_14_R1.VoxelShapes;
import protocolsupport.utils.ReflectionUtils;
public class SpigotBlocksBoundsAdjust {
public static void inject() throws IllegalAccessException {
ReflectionUtils.cloneFields(VoxelShapes.create(0.0625D, 0.0, 0.0625D, 0.9375D, 0.015625D, 0.9375D), ReflectionUtils.getField(BlockWaterLily.class, "a").get(null));
ReflectionUtils.cloneFields(VoxelShapes.create(0.0D, 0.0D, 0.0D, 0.124D, 1.0D, 1.0D), ReflectionUtils.getField(BlockLadder.class, "c").get(null));
ReflectionUtils.cloneFields(VoxelShapes.create(0.876D, 0.0D, 0.0D, 1.0D, 1.0D, 1.0D), ReflectionUtils.getField(BlockLadder.class, "d").get(null));
ReflectionUtils.cloneFields(VoxelShapes.create(0.0D, 0.0D, 0.0D, 1.0D, 1.0D, 0.124D), ReflectionUtils.getField(BlockLadder.class, "e").get(null));
ReflectionUtils.cloneFields(VoxelShapes.create(0.0D, 0.0D, 0.876D, 1.0D, 1.0D, 1.0D), ReflectionUtils.getField(BlockLadder.class, "f").get(null));
}
}
|
// ... existing code ...
package protocolsupport.zplatform.impl.spigot.block;
import net.minecraft.server.v1_14_R1.BlockLadder;
import net.minecraft.server.v1_14_R1.BlockWaterLily;
import net.minecraft.server.v1_14_R1.VoxelShapes;
import protocolsupport.utils.ReflectionUtils;
// ... modified code ...
public class SpigotBlocksBoundsAdjust {
public static void inject() throws IllegalAccessException {
ReflectionUtils.cloneFields(VoxelShapes.create(0.0625D, 0.0, 0.0625D, 0.9375D, 0.015625D, 0.9375D), ReflectionUtils.getField(BlockWaterLily.class, "a").get(null));
ReflectionUtils.cloneFields(VoxelShapes.create(0.0D, 0.0D, 0.0D, 0.124D, 1.0D, 1.0D), ReflectionUtils.getField(BlockLadder.class, "c").get(null));
ReflectionUtils.cloneFields(VoxelShapes.create(0.876D, 0.0D, 0.0D, 1.0D, 1.0D, 1.0D), ReflectionUtils.getField(BlockLadder.class, "d").get(null));
ReflectionUtils.cloneFields(VoxelShapes.create(0.0D, 0.0D, 0.0D, 1.0D, 1.0D, 0.124D), ReflectionUtils.getField(BlockLadder.class, "e").get(null));
ReflectionUtils.cloneFields(VoxelShapes.create(0.0D, 0.0D, 0.876D, 1.0D, 1.0D, 1.0D), ReflectionUtils.getField(BlockLadder.class, "f").get(null));
}
}
// ... rest of the code ...
|
e560ea4a419e1e61d776245b99ffa0e60b4d0e22
|
InvenTree/stock/forms.py
|
InvenTree/stock/forms.py
|
from __future__ import unicode_literals
from django import forms
from InvenTree.forms import HelperForm
from .models import StockLocation, StockItem
class EditStockLocationForm(HelperForm):
class Meta:
model = StockLocation
fields = [
'name',
'parent',
'description'
]
class CreateStockItemForm(HelperForm):
class Meta:
model = StockItem
fields = [
'part',
'supplier_part',
'location',
'belongs_to',
'serial',
'batch',
'quantity',
'status',
# 'customer',
'URL',
]
class MoveStockItemForm(forms.ModelForm):
class Meta:
model = StockItem
fields = [
'location',
]
class StocktakeForm(forms.ModelForm):
class Meta:
model = StockItem
fields = [
'quantity',
]
class EditStockItemForm(HelperForm):
class Meta:
model = StockItem
fields = [
'quantity',
'batch',
'status',
]
|
from __future__ import unicode_literals
from django import forms
from InvenTree.forms import HelperForm
from .models import StockLocation, StockItem
class EditStockLocationForm(HelperForm):
class Meta:
model = StockLocation
fields = [
'name',
'parent',
'description'
]
class CreateStockItemForm(HelperForm):
class Meta:
model = StockItem
fields = [
'part',
'supplier_part',
'location',
'belongs_to',
'serial',
'batch',
'quantity',
'status',
# 'customer',
'URL',
]
class MoveStockItemForm(forms.ModelForm):
class Meta:
model = StockItem
fields = [
'location',
]
class StocktakeForm(forms.ModelForm):
class Meta:
model = StockItem
fields = [
'quantity',
]
class EditStockItemForm(HelperForm):
class Meta:
model = StockItem
fields = [
'batch',
'status',
'notes'
]
|
Update edit form for StockItem
|
Update edit form for StockItem
- Disallow direct quantity editing (must perform stocktake)
- Add notes field to allow editing
|
Python
|
mit
|
SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree
|
python
|
## Code Before:
from __future__ import unicode_literals
from django import forms
from InvenTree.forms import HelperForm
from .models import StockLocation, StockItem
class EditStockLocationForm(HelperForm):
class Meta:
model = StockLocation
fields = [
'name',
'parent',
'description'
]
class CreateStockItemForm(HelperForm):
class Meta:
model = StockItem
fields = [
'part',
'supplier_part',
'location',
'belongs_to',
'serial',
'batch',
'quantity',
'status',
# 'customer',
'URL',
]
class MoveStockItemForm(forms.ModelForm):
class Meta:
model = StockItem
fields = [
'location',
]
class StocktakeForm(forms.ModelForm):
class Meta:
model = StockItem
fields = [
'quantity',
]
class EditStockItemForm(HelperForm):
class Meta:
model = StockItem
fields = [
'quantity',
'batch',
'status',
]
## Instruction:
Update edit form for StockItem
- Disallow direct quantity editing (must perform stocktake)
- Add notes field to allow editing
## Code After:
from __future__ import unicode_literals
from django import forms
from InvenTree.forms import HelperForm
from .models import StockLocation, StockItem
class EditStockLocationForm(HelperForm):
class Meta:
model = StockLocation
fields = [
'name',
'parent',
'description'
]
class CreateStockItemForm(HelperForm):
class Meta:
model = StockItem
fields = [
'part',
'supplier_part',
'location',
'belongs_to',
'serial',
'batch',
'quantity',
'status',
# 'customer',
'URL',
]
class MoveStockItemForm(forms.ModelForm):
class Meta:
model = StockItem
fields = [
'location',
]
class StocktakeForm(forms.ModelForm):
class Meta:
model = StockItem
fields = [
'quantity',
]
class EditStockItemForm(HelperForm):
class Meta:
model = StockItem
fields = [
'batch',
'status',
'notes'
]
|
# ... existing code ...
model = StockItem
fields = [
'batch',
'status',
'notes'
]
# ... rest of the code ...
|
eb477c92d61c1f2db3d5fd98e842050a4313ba3a
|
main.c
|
main.c
|
int main(int argc, char **argv) {
GObject *ep;
GValue val = G_VALUE_INIT;
GError *err = NULL;
KmsConnection *conn = NULL;
g_type_init();
ep = g_object_new(KMS_TYPE_ENDPOINT, "localname", "test_ep", NULL);
if (ep == NULL) {
g_print("Create endpont is: NULL\n");
return 1;
}
g_value_init(&val, G_TYPE_STRING);
g_object_get_property(ep, "localname", &val);
g_print("Created ep with localname: %s\n", g_value_get_string(&val));
conn = kms_endpoint_create_connection(KMS_ENDPOINT(ep),
KMS_CONNECTION_TYPE_RTP, &err);
if (conn == NULL) {
g_print("Connection can not be created: %s\n", err->message);;
g_error_free(err);
goto end;
}
end:
g_object_unref(ep);
return 0;
}
|
int main(int argc, char **argv) {
GObject *ep;
GValue val = G_VALUE_INIT;
GError *err = NULL;
KmsConnection *conn = NULL;
g_type_init();
ep = g_object_new(KMS_TYPE_ENDPOINT, "localname", "test_ep", NULL);
if (ep == NULL) {
g_print("Create endpont is: NULL\n");
return 1;
}
g_value_init(&val, G_TYPE_STRING);
g_object_get_property(ep, "localname", &val);
g_print("Created ep with localname: %s\n", g_value_get_string(&val));
conn = kms_endpoint_create_connection(KMS_ENDPOINT(ep),
KMS_CONNECTION_TYPE_RTP, &err);
if (conn == NULL) {
g_print("Connection can not be created: %s\n", err->message);;
g_error_free(err);
goto end;
}
g_object_get_property(G_OBJECT(conn), "id", &val);
g_print("Created local connection with id: %s\n",
g_value_get_string(&val));
if (!kms_endpoint_delete_connection(KMS_ENDPOINT(ep), conn, &err)) {
g_printerr("Connection can not be deleted: %s", err->message);
g_error_free(err);
goto end;
}
end:
g_object_unref(ep);
return 0;
}
|
Add test for delete connection method
|
Add test for delete connection method
|
C
|
lgpl-2.1
|
mparis/kurento-media-server,lulufei/kurento-media-server,lulufei/kurento-media-server,mparis/kurento-media-server,Kurento/kurento-media-server,todotobe1/kurento-media-server,TribeMedia/kurento-media-server,shelsonjava/kurento-media-server,TribeMedia/kurento-media-server,shelsonjava/kurento-media-server,Kurento/kurento-media-server,todotobe1/kurento-media-server
|
c
|
## Code Before:
int main(int argc, char **argv) {
GObject *ep;
GValue val = G_VALUE_INIT;
GError *err = NULL;
KmsConnection *conn = NULL;
g_type_init();
ep = g_object_new(KMS_TYPE_ENDPOINT, "localname", "test_ep", NULL);
if (ep == NULL) {
g_print("Create endpont is: NULL\n");
return 1;
}
g_value_init(&val, G_TYPE_STRING);
g_object_get_property(ep, "localname", &val);
g_print("Created ep with localname: %s\n", g_value_get_string(&val));
conn = kms_endpoint_create_connection(KMS_ENDPOINT(ep),
KMS_CONNECTION_TYPE_RTP, &err);
if (conn == NULL) {
g_print("Connection can not be created: %s\n", err->message);;
g_error_free(err);
goto end;
}
end:
g_object_unref(ep);
return 0;
}
## Instruction:
Add test for delete connection method
## Code After:
int main(int argc, char **argv) {
GObject *ep;
GValue val = G_VALUE_INIT;
GError *err = NULL;
KmsConnection *conn = NULL;
g_type_init();
ep = g_object_new(KMS_TYPE_ENDPOINT, "localname", "test_ep", NULL);
if (ep == NULL) {
g_print("Create endpont is: NULL\n");
return 1;
}
g_value_init(&val, G_TYPE_STRING);
g_object_get_property(ep, "localname", &val);
g_print("Created ep with localname: %s\n", g_value_get_string(&val));
conn = kms_endpoint_create_connection(KMS_ENDPOINT(ep),
KMS_CONNECTION_TYPE_RTP, &err);
if (conn == NULL) {
g_print("Connection can not be created: %s\n", err->message);;
g_error_free(err);
goto end;
}
g_object_get_property(G_OBJECT(conn), "id", &val);
g_print("Created local connection with id: %s\n",
g_value_get_string(&val));
if (!kms_endpoint_delete_connection(KMS_ENDPOINT(ep), conn, &err)) {
g_printerr("Connection can not be deleted: %s", err->message);
g_error_free(err);
goto end;
}
end:
g_object_unref(ep);
return 0;
}
|
# ... existing code ...
goto end;
}
g_object_get_property(G_OBJECT(conn), "id", &val);
g_print("Created local connection with id: %s\n",
g_value_get_string(&val));
if (!kms_endpoint_delete_connection(KMS_ENDPOINT(ep), conn, &err)) {
g_printerr("Connection can not be deleted: %s", err->message);
g_error_free(err);
goto end;
}
end:
g_object_unref(ep);
# ... rest of the code ...
|
2328de89d07a4040d9dc53f9ee75d7794498f204
|
Apptentive/Apptentive/Misc/ApptentiveSafeCollections.h
|
Apptentive/Apptentive/Misc/ApptentiveSafeCollections.h
|
//
// ApptentiveSafeCollections.h
// Apptentive
//
// Created by Alex Lementuev on 3/20/17.
// Copyright © 2017 Apptentive, Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
Returns non-nil value or NSNull
*/
id ApptentiveCollectionValue(id value);
/**
Safely adds key and value into the dictionary
*/
void ApptentiveDictionarySetKeyValue(NSMutableDictionary *dictionary, id<NSCopying> key, id value);
/**
Tries to add nullable value into the dictionary
*/
BOOL ApptentiveDictionaryTrySetKeyValue(NSMutableDictionary *dictionary, id<NSCopying> key, id value);
/**
Safely retrieves string from a dictionary (or returns nil if failed)
*/
NSString *ApptentiveDictionaryGetString(NSDictionary *dictionary, id<NSCopying> key);
/**
Safely retrieves array from a dictionary (or returns nil if failed)
*/
NSArray *ApptentiveDictionaryGetArray(NSDictionary *dictionary, id<NSCopying> key);
/**
Safely adds an object to the array.
*/
void ApptentiveArrayAddObject(NSMutableArray *array, id object);
NS_ASSUME_NONNULL_END
|
//
// ApptentiveSafeCollections.h
// Apptentive
//
// Created by Alex Lementuev on 3/20/17.
// Copyright © 2017 Apptentive, Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
Returns non-nil value or NSNull
*/
id ApptentiveCollectionValue(id value);
/**
Safely adds key and value into the dictionary
*/
void ApptentiveDictionarySetKeyValue(NSMutableDictionary *dictionary, id<NSCopying> key, id value);
/**
Tries to add nullable value into the dictionary
*/
BOOL ApptentiveDictionaryTrySetKeyValue(NSMutableDictionary *dictionary, id<NSCopying> key, id value);
/**
Safely retrieves string from a dictionary (or returns nil if failed)
*/
NSString * _Nullable ApptentiveDictionaryGetString (NSDictionary *dictionary, id<NSCopying> key);
/**
Safely retrieves array from a dictionary (or returns nil if failed)
*/
NSArray * _Nullable ApptentiveDictionaryGetArray(NSDictionary *dictionary, id<NSCopying> key);
/**
Safely adds an object to the array.
*/
void ApptentiveArrayAddObject(NSMutableArray *array, id object);
NS_ASSUME_NONNULL_END
|
Add nullable flag to ApptentiveDictionaryGetArray and -String
|
Add nullable flag to ApptentiveDictionaryGetArray and -String
|
C
|
bsd-3-clause
|
apptentive/apptentive-ios,apptentive/apptentive-ios,apptentive/apptentive-ios
|
c
|
## Code Before:
//
// ApptentiveSafeCollections.h
// Apptentive
//
// Created by Alex Lementuev on 3/20/17.
// Copyright © 2017 Apptentive, Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
Returns non-nil value or NSNull
*/
id ApptentiveCollectionValue(id value);
/**
Safely adds key and value into the dictionary
*/
void ApptentiveDictionarySetKeyValue(NSMutableDictionary *dictionary, id<NSCopying> key, id value);
/**
Tries to add nullable value into the dictionary
*/
BOOL ApptentiveDictionaryTrySetKeyValue(NSMutableDictionary *dictionary, id<NSCopying> key, id value);
/**
Safely retrieves string from a dictionary (or returns nil if failed)
*/
NSString *ApptentiveDictionaryGetString(NSDictionary *dictionary, id<NSCopying> key);
/**
Safely retrieves array from a dictionary (or returns nil if failed)
*/
NSArray *ApptentiveDictionaryGetArray(NSDictionary *dictionary, id<NSCopying> key);
/**
Safely adds an object to the array.
*/
void ApptentiveArrayAddObject(NSMutableArray *array, id object);
NS_ASSUME_NONNULL_END
## Instruction:
Add nullable flag to ApptentiveDictionaryGetArray and -String
## Code After:
//
// ApptentiveSafeCollections.h
// Apptentive
//
// Created by Alex Lementuev on 3/20/17.
// Copyright © 2017 Apptentive, Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
Returns non-nil value or NSNull
*/
id ApptentiveCollectionValue(id value);
/**
Safely adds key and value into the dictionary
*/
void ApptentiveDictionarySetKeyValue(NSMutableDictionary *dictionary, id<NSCopying> key, id value);
/**
Tries to add nullable value into the dictionary
*/
BOOL ApptentiveDictionaryTrySetKeyValue(NSMutableDictionary *dictionary, id<NSCopying> key, id value);
/**
Safely retrieves string from a dictionary (or returns nil if failed)
*/
NSString * _Nullable ApptentiveDictionaryGetString (NSDictionary *dictionary, id<NSCopying> key);
/**
Safely retrieves array from a dictionary (or returns nil if failed)
*/
NSArray * _Nullable ApptentiveDictionaryGetArray(NSDictionary *dictionary, id<NSCopying> key);
/**
Safely adds an object to the array.
*/
void ApptentiveArrayAddObject(NSMutableArray *array, id object);
NS_ASSUME_NONNULL_END
|
// ... existing code ...
/**
Safely retrieves string from a dictionary (or returns nil if failed)
*/
NSString * _Nullable ApptentiveDictionaryGetString (NSDictionary *dictionary, id<NSCopying> key);
/**
Safely retrieves array from a dictionary (or returns nil if failed)
*/
NSArray * _Nullable ApptentiveDictionaryGetArray(NSDictionary *dictionary, id<NSCopying> key);
/**
Safely adds an object to the array.
// ... rest of the code ...
|
923fa72ce9ff0bf5715de8f4d7e8db852cd5a8e6
|
src/main/java/eu/rekawek/coffeegb/memory/Dma.java
|
src/main/java/eu/rekawek/coffeegb/memory/Dma.java
|
package eu.rekawek.coffeegb.memory;
import eu.rekawek.coffeegb.AddressSpace;
import eu.rekawek.coffeegb.cpu.SpeedMode;
public class Dma implements AddressSpace {
private final AddressSpace addressSpace;
private final AddressSpace oam;
private final SpeedMode speedMode;
private boolean transferInProgress;
private boolean restarted;
private int from;
private int ticks;
public Dma(AddressSpace addressSpace, AddressSpace oam, SpeedMode speedMode) {
this.addressSpace = addressSpace;
this.speedMode = speedMode;
this.oam = oam;
}
@Override
public boolean accepts(int address) {
return address == 0xff46;
}
public void tick() {
if (transferInProgress) {
if (++ticks >= 648 / speedMode.getSpeedMode()) {
transferInProgress = false;
restarted = false;
ticks = 0;
for (int i = 0; i < 0xa0; i++) {
oam.setByte(0xfe00 + i, addressSpace.getByte(from + i));
}
}
}
}
@Override
public void setByte(int address, int value) {
from = value * 0x100;
restarted = isOamBlocked();
ticks = 0;
transferInProgress = true;
}
@Override
public int getByte(int address) {
return 0;
}
public boolean isOamBlocked() {
return restarted || (transferInProgress && ticks >= 5);
}
}
|
package eu.rekawek.coffeegb.memory;
import eu.rekawek.coffeegb.AddressSpace;
import eu.rekawek.coffeegb.cpu.SpeedMode;
public class Dma implements AddressSpace {
private final AddressSpace addressSpace;
private final AddressSpace oam;
private final SpeedMode speedMode;
private boolean transferInProgress;
private boolean restarted;
private int from;
private int ticks;
private int regValue = 0xff;
public Dma(AddressSpace addressSpace, AddressSpace oam, SpeedMode speedMode) {
this.addressSpace = addressSpace;
this.speedMode = speedMode;
this.oam = oam;
}
@Override
public boolean accepts(int address) {
return address == 0xff46;
}
public void tick() {
if (transferInProgress) {
if (++ticks >= 648 / speedMode.getSpeedMode()) {
transferInProgress = false;
restarted = false;
ticks = 0;
for (int i = 0; i < 0xa0; i++) {
oam.setByte(0xfe00 + i, addressSpace.getByte(from + i));
}
}
}
}
@Override
public void setByte(int address, int value) {
from = value * 0x100;
restarted = isOamBlocked();
ticks = 0;
transferInProgress = true;
regValue = value;
}
@Override
public int getByte(int address) {
return regValue;
}
public boolean isOamBlocked() {
return restarted || (transferInProgress && ticks >= 5);
}
}
|
Return the written value of DMA register.
|
Return the written value of DMA register.
|
Java
|
mit
|
trekawek/coffee-gb,trekawek/coffee-gb
|
java
|
## Code Before:
package eu.rekawek.coffeegb.memory;
import eu.rekawek.coffeegb.AddressSpace;
import eu.rekawek.coffeegb.cpu.SpeedMode;
public class Dma implements AddressSpace {
private final AddressSpace addressSpace;
private final AddressSpace oam;
private final SpeedMode speedMode;
private boolean transferInProgress;
private boolean restarted;
private int from;
private int ticks;
public Dma(AddressSpace addressSpace, AddressSpace oam, SpeedMode speedMode) {
this.addressSpace = addressSpace;
this.speedMode = speedMode;
this.oam = oam;
}
@Override
public boolean accepts(int address) {
return address == 0xff46;
}
public void tick() {
if (transferInProgress) {
if (++ticks >= 648 / speedMode.getSpeedMode()) {
transferInProgress = false;
restarted = false;
ticks = 0;
for (int i = 0; i < 0xa0; i++) {
oam.setByte(0xfe00 + i, addressSpace.getByte(from + i));
}
}
}
}
@Override
public void setByte(int address, int value) {
from = value * 0x100;
restarted = isOamBlocked();
ticks = 0;
transferInProgress = true;
}
@Override
public int getByte(int address) {
return 0;
}
public boolean isOamBlocked() {
return restarted || (transferInProgress && ticks >= 5);
}
}
## Instruction:
Return the written value of DMA register.
## Code After:
package eu.rekawek.coffeegb.memory;
import eu.rekawek.coffeegb.AddressSpace;
import eu.rekawek.coffeegb.cpu.SpeedMode;
public class Dma implements AddressSpace {
private final AddressSpace addressSpace;
private final AddressSpace oam;
private final SpeedMode speedMode;
private boolean transferInProgress;
private boolean restarted;
private int from;
private int ticks;
private int regValue = 0xff;
public Dma(AddressSpace addressSpace, AddressSpace oam, SpeedMode speedMode) {
this.addressSpace = addressSpace;
this.speedMode = speedMode;
this.oam = oam;
}
@Override
public boolean accepts(int address) {
return address == 0xff46;
}
public void tick() {
if (transferInProgress) {
if (++ticks >= 648 / speedMode.getSpeedMode()) {
transferInProgress = false;
restarted = false;
ticks = 0;
for (int i = 0; i < 0xa0; i++) {
oam.setByte(0xfe00 + i, addressSpace.getByte(from + i));
}
}
}
}
@Override
public void setByte(int address, int value) {
from = value * 0x100;
restarted = isOamBlocked();
ticks = 0;
transferInProgress = true;
regValue = value;
}
@Override
public int getByte(int address) {
return regValue;
}
public boolean isOamBlocked() {
return restarted || (transferInProgress && ticks >= 5);
}
}
|
# ... existing code ...
private int from;
private int ticks;
private int regValue = 0xff;
public Dma(AddressSpace addressSpace, AddressSpace oam, SpeedMode speedMode) {
this.addressSpace = addressSpace;
# ... modified code ...
restarted = isOamBlocked();
ticks = 0;
transferInProgress = true;
regValue = value;
}
@Override
public int getByte(int address) {
return regValue;
}
public boolean isOamBlocked() {
# ... rest of the code ...
|
2119d75d1115b28fb768dafb2df2e2f13e761310
|
setup.py
|
setup.py
|
import os.path as op
from glob import glob
from setuptools import setup
from setup_helper import SetupHelper
name = "goatools"
classifiers = [
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering :: Bio-Informatics',
]
# Use the helper
h = SetupHelper(initfile="goatools/__init__.py", readmefile="README.md")
setup_dir = op.abspath(op.dirname(__file__))
requirements = ['wget'] + [x.strip() for x in
open(op.join(setup_dir, 'requirements.txt')).readlines()]
setup(
name=name,
version=h.version,
author=h.author,
author_email=h.email,
license=h.license,
long_description=h.long_description,
packages=[name],
scripts=glob('scripts/*.py'),
classifiers=classifiers,
url='http://github.com/tanghaibao/goatools',
description="Python scripts to find enrichment of GO terms",
install_requires=requirements
)
|
import os.path as op
from glob import glob
from setuptools import setup
from setup_helper import SetupHelper
name = "goatools"
classifiers = [
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering :: Bio-Informatics',
]
# Use the helper
h = SetupHelper(initfile="goatools/__init__.py", readmefile="README.md")
setup_dir = op.abspath(op.dirname(__file__))
requirements = ['wget'] + [x.strip() for x in
open(op.join(setup_dir, 'requirements.txt')).readlines()]
setup(
name=name,
version=h.version,
author=h.author,
author_email=h.email,
license=h.license,
long_description=h.long_description,
packages=[name, name + ".test_data", name + ".anno"],
scripts=glob('scripts/*.py'),
classifiers=classifiers,
url='http://github.com/tanghaibao/goatools',
description="Python scripts to find enrichment of GO terms",
install_requires=requirements
)
|
Include .anno and .test_data in dist
|
[CI] Include .anno and .test_data in dist
|
Python
|
bsd-2-clause
|
lileiting/goatools,tanghaibao/goatools,lileiting/goatools,tanghaibao/goatools
|
python
|
## Code Before:
import os.path as op
from glob import glob
from setuptools import setup
from setup_helper import SetupHelper
name = "goatools"
classifiers = [
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering :: Bio-Informatics',
]
# Use the helper
h = SetupHelper(initfile="goatools/__init__.py", readmefile="README.md")
setup_dir = op.abspath(op.dirname(__file__))
requirements = ['wget'] + [x.strip() for x in
open(op.join(setup_dir, 'requirements.txt')).readlines()]
setup(
name=name,
version=h.version,
author=h.author,
author_email=h.email,
license=h.license,
long_description=h.long_description,
packages=[name],
scripts=glob('scripts/*.py'),
classifiers=classifiers,
url='http://github.com/tanghaibao/goatools',
description="Python scripts to find enrichment of GO terms",
install_requires=requirements
)
## Instruction:
[CI] Include .anno and .test_data in dist
## Code After:
import os.path as op
from glob import glob
from setuptools import setup
from setup_helper import SetupHelper
name = "goatools"
classifiers = [
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering :: Bio-Informatics',
]
# Use the helper
h = SetupHelper(initfile="goatools/__init__.py", readmefile="README.md")
setup_dir = op.abspath(op.dirname(__file__))
requirements = ['wget'] + [x.strip() for x in
open(op.join(setup_dir, 'requirements.txt')).readlines()]
setup(
name=name,
version=h.version,
author=h.author,
author_email=h.email,
license=h.license,
long_description=h.long_description,
packages=[name, name + ".test_data", name + ".anno"],
scripts=glob('scripts/*.py'),
classifiers=classifiers,
url='http://github.com/tanghaibao/goatools',
description="Python scripts to find enrichment of GO terms",
install_requires=requirements
)
|
...
author_email=h.email,
license=h.license,
long_description=h.long_description,
packages=[name, name + ".test_data", name + ".anno"],
scripts=glob('scripts/*.py'),
classifiers=classifiers,
url='http://github.com/tanghaibao/goatools',
...
|
b39518482da1d3e064cdbc34490e4a9924f6d5f1
|
quantecon/tests/test_ecdf.py
|
quantecon/tests/test_ecdf.py
|
import unittest
import numpy as np
from quantecon import ECDF
class TestECDF(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.obs = np.random.rand(40) # observations defining dist
cls.ecdf = ECDF(cls.obs)
def test_call_high(self):
"ecdf: x above all obs give 1.0"
# all of self.obs <= 1 so ecdf(1.1) should be 1
self.assertAlmostEqual(self.ecdf(1.1), 1.0)
def test_call_low(self):
"ecdf: x below all obs give 0.0"
# all of self.obs <= 1 so ecdf(1.1) should be 1
self.assertAlmostEqual(self.ecdf(-0.1), 0.0)
def test_ascending(self):
"ecdf: larger values should return F(x) at least as big"
x = np.random.rand()
F_1 = self.ecdf(x)
F_2 = self.ecdf(1.1 * x)
self.assertGreaterEqual(F_2, F_1)
|
import unittest
import numpy as np
from quantecon import ECDF
class TestECDF(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.obs = np.random.rand(40) # observations defining dist
cls.ecdf = ECDF(cls.obs)
def test_call_high(self):
"ecdf: x above all obs give 1.0"
# all of self.obs <= 1 so ecdf(1.1) should be 1
self.assertAlmostEqual(self.ecdf(1.1), 1.0)
def test_call_low(self):
"ecdf: x below all obs give 0.0"
# all of self.obs <= 1 so ecdf(1.1) should be 1
self.assertAlmostEqual(self.ecdf(-0.1), 0.0)
def test_ascending(self):
"ecdf: larger values should return F(x) at least as big"
x = np.random.rand()
F_1 = self.ecdf(x)
F_2 = self.ecdf(1.1 * x)
self.assertGreaterEqual(F_2, F_1)
def test_vectorized(self):
"ecdf: testing vectorized __call__ method"
t = np.linspace(-1, 1, 100)
self.assertEqual(t.shape, self.ecdf(t).shape)
t = np.linspace(-1, 1, 100).reshape(2, 2, 25)
self.assertEqual(t.shape, self.ecdf(t).shape)
|
Add a test for vectorized call
|
TST: Add a test for vectorized call
|
Python
|
bsd-3-clause
|
oyamad/QuantEcon.py,QuantEcon/QuantEcon.py,oyamad/QuantEcon.py,QuantEcon/QuantEcon.py
|
python
|
## Code Before:
import unittest
import numpy as np
from quantecon import ECDF
class TestECDF(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.obs = np.random.rand(40) # observations defining dist
cls.ecdf = ECDF(cls.obs)
def test_call_high(self):
"ecdf: x above all obs give 1.0"
# all of self.obs <= 1 so ecdf(1.1) should be 1
self.assertAlmostEqual(self.ecdf(1.1), 1.0)
def test_call_low(self):
"ecdf: x below all obs give 0.0"
# all of self.obs <= 1 so ecdf(1.1) should be 1
self.assertAlmostEqual(self.ecdf(-0.1), 0.0)
def test_ascending(self):
"ecdf: larger values should return F(x) at least as big"
x = np.random.rand()
F_1 = self.ecdf(x)
F_2 = self.ecdf(1.1 * x)
self.assertGreaterEqual(F_2, F_1)
## Instruction:
TST: Add a test for vectorized call
## Code After:
import unittest
import numpy as np
from quantecon import ECDF
class TestECDF(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.obs = np.random.rand(40) # observations defining dist
cls.ecdf = ECDF(cls.obs)
def test_call_high(self):
"ecdf: x above all obs give 1.0"
# all of self.obs <= 1 so ecdf(1.1) should be 1
self.assertAlmostEqual(self.ecdf(1.1), 1.0)
def test_call_low(self):
"ecdf: x below all obs give 0.0"
# all of self.obs <= 1 so ecdf(1.1) should be 1
self.assertAlmostEqual(self.ecdf(-0.1), 0.0)
def test_ascending(self):
"ecdf: larger values should return F(x) at least as big"
x = np.random.rand()
F_1 = self.ecdf(x)
F_2 = self.ecdf(1.1 * x)
self.assertGreaterEqual(F_2, F_1)
def test_vectorized(self):
"ecdf: testing vectorized __call__ method"
t = np.linspace(-1, 1, 100)
self.assertEqual(t.shape, self.ecdf(t).shape)
t = np.linspace(-1, 1, 100).reshape(2, 2, 25)
self.assertEqual(t.shape, self.ecdf(t).shape)
|
// ... existing code ...
F_1 = self.ecdf(x)
F_2 = self.ecdf(1.1 * x)
self.assertGreaterEqual(F_2, F_1)
def test_vectorized(self):
"ecdf: testing vectorized __call__ method"
t = np.linspace(-1, 1, 100)
self.assertEqual(t.shape, self.ecdf(t).shape)
t = np.linspace(-1, 1, 100).reshape(2, 2, 25)
self.assertEqual(t.shape, self.ecdf(t).shape)
// ... rest of the code ...
|
12f3cc403f6ba0be957d1fb18253fb7529009764
|
moss/plotting.py
|
moss/plotting.py
|
import matplotlib.pyplot as plt
def grid_axes_labels(f, xlabel=None, ylabel=None, **kws):
axes = f.axes
plt.setp(axes.flat, xlabel="", ylabel="")
if xlabel is not None:
for ax in axes[-1]:
ax.set_xlabel(xlabel, **kws)
if ylabel is not None:
for ax in axes[0]:
ax.set_ylabel(ylabel, **kws)
|
import matplotlib.pyplot as plt
def grid_axes_labels(axes, xlabel=None, ylabel=None, **kws):
plt.setp(axes.flat, xlabel="", ylabel="")
if xlabel is not None:
for ax in axes[-1]:
ax.set_xlabel(xlabel, **kws)
if ylabel is not None:
for ax in axes[0]:
ax.set_ylabel(ylabel, **kws)
|
Use matrix of axes not figure
|
Use matrix of axes not figure
|
Python
|
bsd-3-clause
|
mwaskom/moss,mwaskom/moss
|
python
|
## Code Before:
import matplotlib.pyplot as plt
def grid_axes_labels(f, xlabel=None, ylabel=None, **kws):
axes = f.axes
plt.setp(axes.flat, xlabel="", ylabel="")
if xlabel is not None:
for ax in axes[-1]:
ax.set_xlabel(xlabel, **kws)
if ylabel is not None:
for ax in axes[0]:
ax.set_ylabel(ylabel, **kws)
## Instruction:
Use matrix of axes not figure
## Code After:
import matplotlib.pyplot as plt
def grid_axes_labels(axes, xlabel=None, ylabel=None, **kws):
plt.setp(axes.flat, xlabel="", ylabel="")
if xlabel is not None:
for ax in axes[-1]:
ax.set_xlabel(xlabel, **kws)
if ylabel is not None:
for ax in axes[0]:
ax.set_ylabel(ylabel, **kws)
|
# ... existing code ...
import matplotlib.pyplot as plt
def grid_axes_labels(axes, xlabel=None, ylabel=None, **kws):
plt.setp(axes.flat, xlabel="", ylabel="")
# ... rest of the code ...
|
4f037a15329c960fc769172393ada47ad73bf339
|
src/main/java/com/github/aureliano/achmed/resources/properties/IResourceProperties.java
|
src/main/java/com/github/aureliano/achmed/resources/properties/IResourceProperties.java
|
package com.github.aureliano.achmed.resources.properties;
public interface IResourceProperties {
public abstract IResourceProperties put(String key, Object value);
public abstract Object get(String key);
}
|
package com.github.aureliano.achmed.resources.properties;
public interface IResourceProperties {
public abstract IResourceProperties put(String key, Object value);
public abstract Object get(String key);
public abstract void configureAttributes();
}
|
Add abstract method for parsing attributes.
|
Add abstract method for parsing attributes.
|
Java
|
mit
|
aureliano/achmed
|
java
|
## Code Before:
package com.github.aureliano.achmed.resources.properties;
public interface IResourceProperties {
public abstract IResourceProperties put(String key, Object value);
public abstract Object get(String key);
}
## Instruction:
Add abstract method for parsing attributes.
## Code After:
package com.github.aureliano.achmed.resources.properties;
public interface IResourceProperties {
public abstract IResourceProperties put(String key, Object value);
public abstract Object get(String key);
public abstract void configureAttributes();
}
|
...
public abstract IResourceProperties put(String key, Object value);
public abstract Object get(String key);
public abstract void configureAttributes();
}
...
|
b1a33b1a89c00ee6de7949c529ecd4bcf2d38578
|
python/helper/asset_loading.py
|
python/helper/asset_loading.py
|
def load_image(image_name, fade_enabled=False):
"""fade_enabled should be True if you want images to be able to fade"""
try:
#! Add stuff for loading images of the correct resolution
# depending on the player's resolution settings
if not fade_enabled:
return pygame.image.load("".join((
file_directory, "Image Files\\",
image_name, ".png"
))).convert_alpha() # Fixes per pixel alphas permanently
else:
return pygame.image.load("".join((
file_directory, "Image Files\\",
image_name, ".png"
))).convert()
except Exception as error:
log("".join(("Failed to load image: ", image_name, ".png")))
|
def load_image(image_name, fade_enabled=False):
"""fade_enabled should be True if you want images to be able to fade"""
try:
#! Add stuff for loading images of the correct resolution
# depending on the player's resolution settings
if not fade_enabled:
return pygame.image.load("".join((
file_directory, "assets\\images\\",
image_name, ".png"
))).convert_alpha() # Fixes per pixel alphas permanently
else:
return pygame.image.load("".join((
file_directory, "assets\\images\\",
image_name, ".png"
))).convert()
except Exception as error:
log("".join(("Failed to load image: ", image_name, ".png")))
|
Fix error in file path of where images are loaded from in load_image()
|
Fix error in file path of where images are loaded from in load_image()
|
Python
|
mit
|
AndyDeany/pygame-template
|
python
|
## Code Before:
def load_image(image_name, fade_enabled=False):
"""fade_enabled should be True if you want images to be able to fade"""
try:
#! Add stuff for loading images of the correct resolution
# depending on the player's resolution settings
if not fade_enabled:
return pygame.image.load("".join((
file_directory, "Image Files\\",
image_name, ".png"
))).convert_alpha() # Fixes per pixel alphas permanently
else:
return pygame.image.load("".join((
file_directory, "Image Files\\",
image_name, ".png"
))).convert()
except Exception as error:
log("".join(("Failed to load image: ", image_name, ".png")))
## Instruction:
Fix error in file path of where images are loaded from in load_image()
## Code After:
def load_image(image_name, fade_enabled=False):
"""fade_enabled should be True if you want images to be able to fade"""
try:
#! Add stuff for loading images of the correct resolution
# depending on the player's resolution settings
if not fade_enabled:
return pygame.image.load("".join((
file_directory, "assets\\images\\",
image_name, ".png"
))).convert_alpha() # Fixes per pixel alphas permanently
else:
return pygame.image.load("".join((
file_directory, "assets\\images\\",
image_name, ".png"
))).convert()
except Exception as error:
log("".join(("Failed to load image: ", image_name, ".png")))
|
// ... existing code ...
# depending on the player's resolution settings
if not fade_enabled:
return pygame.image.load("".join((
file_directory, "assets\\images\\",
image_name, ".png"
))).convert_alpha() # Fixes per pixel alphas permanently
else:
return pygame.image.load("".join((
file_directory, "assets\\images\\",
image_name, ".png"
))).convert()
except Exception as error:
// ... rest of the code ...
|
e1349cedc6eb26f8f550d00e8249cb52920fdf75
|
setup.py
|
setup.py
|
from setuptools import setup
setup(name="gimlet",
version='0.1',
description='Simple High-Performance WSGI Sessions',
long_description='',
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Development Status :: 3 - Alpha',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware',
'Topic :: Internet :: WWW/HTTP :: Session',
],
keywords='wsgi sessions middleware beaker cookie',
url='http://github.com/storborg/gimlet',
author='Scott Torborg',
author_email='[email protected]',
install_requires=[
'itsdangerous',
'webob',
'redis',
'pylibmc',
# Required for cookie encryption.
'pycrypto',
# These are for tests.
'coverage',
'nose>=1.1',
'nose-cover3',
'webtest',
],
license='MIT',
packages=['gimlet'],
test_suite='nose.collector',
tests_require=['nose'],
zip_safe=False)
|
from setuptools import setup
setup(name="gimlet",
version='0.1',
description='Simple High-Performance WSGI Sessions',
long_description='',
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Development Status :: 3 - Alpha',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware',
'Topic :: Internet :: WWW/HTTP :: Session',
],
keywords='wsgi sessions middleware beaker cookie',
url='http://github.com/storborg/gimlet',
author='Scott Torborg',
author_email='[email protected]',
install_requires=[
'itsdangerous',
'webob',
'redis',
'pylibmc',
'sqlalchemy',
# Required for cookie encryption.
'pycrypto',
# These are for tests.
'coverage',
'nose>=1.1',
'nose-cover3',
'webtest',
],
license='MIT',
packages=['gimlet'],
test_suite='nose.collector',
tests_require=['nose'],
zip_safe=False)
|
Add sqlalchemy to gimlet dependencies
|
Add sqlalchemy to gimlet dependencies
|
Python
|
mit
|
storborg/gimlet
|
python
|
## Code Before:
from setuptools import setup
setup(name="gimlet",
version='0.1',
description='Simple High-Performance WSGI Sessions',
long_description='',
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Development Status :: 3 - Alpha',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware',
'Topic :: Internet :: WWW/HTTP :: Session',
],
keywords='wsgi sessions middleware beaker cookie',
url='http://github.com/storborg/gimlet',
author='Scott Torborg',
author_email='[email protected]',
install_requires=[
'itsdangerous',
'webob',
'redis',
'pylibmc',
# Required for cookie encryption.
'pycrypto',
# These are for tests.
'coverage',
'nose>=1.1',
'nose-cover3',
'webtest',
],
license='MIT',
packages=['gimlet'],
test_suite='nose.collector',
tests_require=['nose'],
zip_safe=False)
## Instruction:
Add sqlalchemy to gimlet dependencies
## Code After:
from setuptools import setup
setup(name="gimlet",
version='0.1',
description='Simple High-Performance WSGI Sessions',
long_description='',
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Development Status :: 3 - Alpha',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware',
'Topic :: Internet :: WWW/HTTP :: Session',
],
keywords='wsgi sessions middleware beaker cookie',
url='http://github.com/storborg/gimlet',
author='Scott Torborg',
author_email='[email protected]',
install_requires=[
'itsdangerous',
'webob',
'redis',
'pylibmc',
'sqlalchemy',
# Required for cookie encryption.
'pycrypto',
# These are for tests.
'coverage',
'nose>=1.1',
'nose-cover3',
'webtest',
],
license='MIT',
packages=['gimlet'],
test_suite='nose.collector',
tests_require=['nose'],
zip_safe=False)
|
// ... existing code ...
'webob',
'redis',
'pylibmc',
'sqlalchemy',
# Required for cookie encryption.
'pycrypto',
# These are for tests.
// ... rest of the code ...
|
4a20a36aa920a6450eb526a9913d8fb0ab08fa8c
|
buildlet/runner/simple.py
|
buildlet/runner/simple.py
|
from .base import BaseRunner
class SimpleRunner(BaseRunner):
"""
Simple blocking task runner.
"""
@classmethod
def run(cls, task):
"""
Simple blocking task runner.
Run `task` and its unfinished ancestors.
"""
task.pre_run()
try:
for parent in task.get_parents():
# This is redundant because `.load` or `.run` is called
# for *all* tasks regardless the state (need rerun or not).
cls.run(parent)
if task.is_finished():
task.load()
else:
task.run()
task.post_success_run()
except Exception as e:
task.post_error_run(e)
raise
|
from .base import BaseRunner
class SimpleRunner(BaseRunner):
"""
Simple blocking task runner.
"""
@classmethod
def run(cls, task):
"""
Simple blocking task runner.
Run `task` and its unfinished ancestors.
"""
for parent in task.get_parents():
# This is redundant because `.load` or `.run` is called
# for *all* tasks regardless the state (need rerun or not).
cls.run(parent)
# .. note:: Do *not* put ``cls.run(parent)`` in the next try
# block because the error in parent task is treated by its
# `post_error_run` hook.
task.pre_run()
try:
if task.is_finished():
task.load()
else:
task.run()
task.post_success_run()
except Exception as e:
task.post_error_run(e)
raise
|
Tweak SimpleRunner.run: make it close to the parallel one
|
Tweak SimpleRunner.run: make it close to the parallel one
|
Python
|
bsd-3-clause
|
tkf/buildlet
|
python
|
## Code Before:
from .base import BaseRunner
class SimpleRunner(BaseRunner):
"""
Simple blocking task runner.
"""
@classmethod
def run(cls, task):
"""
Simple blocking task runner.
Run `task` and its unfinished ancestors.
"""
task.pre_run()
try:
for parent in task.get_parents():
# This is redundant because `.load` or `.run` is called
# for *all* tasks regardless the state (need rerun or not).
cls.run(parent)
if task.is_finished():
task.load()
else:
task.run()
task.post_success_run()
except Exception as e:
task.post_error_run(e)
raise
## Instruction:
Tweak SimpleRunner.run: make it close to the parallel one
## Code After:
from .base import BaseRunner
class SimpleRunner(BaseRunner):
"""
Simple blocking task runner.
"""
@classmethod
def run(cls, task):
"""
Simple blocking task runner.
Run `task` and its unfinished ancestors.
"""
for parent in task.get_parents():
# This is redundant because `.load` or `.run` is called
# for *all* tasks regardless the state (need rerun or not).
cls.run(parent)
# .. note:: Do *not* put ``cls.run(parent)`` in the next try
# block because the error in parent task is treated by its
# `post_error_run` hook.
task.pre_run()
try:
if task.is_finished():
task.load()
else:
task.run()
task.post_success_run()
except Exception as e:
task.post_error_run(e)
raise
|
# ... existing code ...
Run `task` and its unfinished ancestors.
"""
for parent in task.get_parents():
# This is redundant because `.load` or `.run` is called
# for *all* tasks regardless the state (need rerun or not).
cls.run(parent)
# .. note:: Do *not* put ``cls.run(parent)`` in the next try
# block because the error in parent task is treated by its
# `post_error_run` hook.
task.pre_run()
try:
if task.is_finished():
task.load()
else:
# ... rest of the code ...
|
1af3cc43ae482549ee058e801b4f65e2af78653c
|
grow/testing/testdata/pod/extensions/preprocessors.py
|
grow/testing/testdata/pod/extensions/preprocessors.py
|
from grow import Preprocessor
from protorpc import messages
class CustomPreprocessor(Preprocessor):
KIND = 'custom_preprocessor'
class Config(messages.Message):
value = messages.StringField(1)
def run(self, **kwargs):
# To allow the test to check the result
self.pod._custom_preprocessor_value = self.config.value
|
import grow
from protorpc import messages
class CustomPreprocessor(grow.Preprocessor):
KIND = 'custom_preprocessor'
class Config(messages.Message):
value = messages.StringField(1)
def run(self, **kwargs):
# To allow the test to check the result
self.pod._custom_preprocessor_value = self.config.value
|
Update preprocessor testdata to use grow.Preprocessor.
|
Update preprocessor testdata to use grow.Preprocessor.
|
Python
|
mit
|
grow/pygrow,denmojo/pygrow,grow/grow,grow/grow,grow/pygrow,denmojo/pygrow,denmojo/pygrow,grow/grow,denmojo/pygrow,grow/grow,grow/pygrow
|
python
|
## Code Before:
from grow import Preprocessor
from protorpc import messages
class CustomPreprocessor(Preprocessor):
KIND = 'custom_preprocessor'
class Config(messages.Message):
value = messages.StringField(1)
def run(self, **kwargs):
# To allow the test to check the result
self.pod._custom_preprocessor_value = self.config.value
## Instruction:
Update preprocessor testdata to use grow.Preprocessor.
## Code After:
import grow
from protorpc import messages
class CustomPreprocessor(grow.Preprocessor):
KIND = 'custom_preprocessor'
class Config(messages.Message):
value = messages.StringField(1)
def run(self, **kwargs):
# To allow the test to check the result
self.pod._custom_preprocessor_value = self.config.value
|
// ... existing code ...
import grow
from protorpc import messages
class CustomPreprocessor(grow.Preprocessor):
KIND = 'custom_preprocessor'
class Config(messages.Message):
// ... rest of the code ...
|
7b9206d7c3fcf91c6ac16b54b9e1d13b92f7802a
|
tests/test_testing.py
|
tests/test_testing.py
|
"""Test MetPy's testing utilities."""
import numpy as np
import pytest
from metpy.testing import assert_array_almost_equal
# Test #1183: numpy.testing.assert_array* ignores any masked value, so work-around
def test_masked_arrays():
"""Test that we catch masked arrays with different masks."""
with pytest.raises(AssertionError):
assert_array_almost_equal(np.array([10, 20]),
np.ma.array([10, np.nan], mask=[False, True]), 2)
def test_masked_and_no_mask():
"""Test that we can compare a masked array with no masked values and a regular array."""
a = np.array([10, 20])
b = np.ma.array([10, 20], mask=[False, False])
assert_array_almost_equal(a, b)
|
"""Test MetPy's testing utilities."""
import warnings
import numpy as np
import pytest
from metpy.deprecation import MetpyDeprecationWarning
from metpy.testing import assert_array_almost_equal, check_and_silence_deprecation
# Test #1183: numpy.testing.assert_array* ignores any masked value, so work-around
def test_masked_arrays():
"""Test that we catch masked arrays with different masks."""
with pytest.raises(AssertionError):
assert_array_almost_equal(np.array([10, 20]),
np.ma.array([10, np.nan], mask=[False, True]), 2)
def test_masked_and_no_mask():
"""Test that we can compare a masked array with no masked values and a regular array."""
a = np.array([10, 20])
b = np.ma.array([10, 20], mask=[False, False])
assert_array_almost_equal(a, b)
@check_and_silence_deprecation
def test_deprecation_decorator():
"""Make sure the deprecation checker works."""
warnings.warn('Testing warning.', MetpyDeprecationWarning)
|
Add explicit test for deprecation decorator
|
MNT: Add explicit test for deprecation decorator
|
Python
|
bsd-3-clause
|
dopplershift/MetPy,ShawnMurd/MetPy,ahaberlie/MetPy,Unidata/MetPy,Unidata/MetPy,ahaberlie/MetPy,dopplershift/MetPy
|
python
|
## Code Before:
"""Test MetPy's testing utilities."""
import numpy as np
import pytest
from metpy.testing import assert_array_almost_equal
# Test #1183: numpy.testing.assert_array* ignores any masked value, so work-around
def test_masked_arrays():
"""Test that we catch masked arrays with different masks."""
with pytest.raises(AssertionError):
assert_array_almost_equal(np.array([10, 20]),
np.ma.array([10, np.nan], mask=[False, True]), 2)
def test_masked_and_no_mask():
"""Test that we can compare a masked array with no masked values and a regular array."""
a = np.array([10, 20])
b = np.ma.array([10, 20], mask=[False, False])
assert_array_almost_equal(a, b)
## Instruction:
MNT: Add explicit test for deprecation decorator
## Code After:
"""Test MetPy's testing utilities."""
import warnings
import numpy as np
import pytest
from metpy.deprecation import MetpyDeprecationWarning
from metpy.testing import assert_array_almost_equal, check_and_silence_deprecation
# Test #1183: numpy.testing.assert_array* ignores any masked value, so work-around
def test_masked_arrays():
"""Test that we catch masked arrays with different masks."""
with pytest.raises(AssertionError):
assert_array_almost_equal(np.array([10, 20]),
np.ma.array([10, np.nan], mask=[False, True]), 2)
def test_masked_and_no_mask():
"""Test that we can compare a masked array with no masked values and a regular array."""
a = np.array([10, 20])
b = np.ma.array([10, 20], mask=[False, False])
assert_array_almost_equal(a, b)
@check_and_silence_deprecation
def test_deprecation_decorator():
"""Make sure the deprecation checker works."""
warnings.warn('Testing warning.', MetpyDeprecationWarning)
|
# ... existing code ...
"""Test MetPy's testing utilities."""
import warnings
import numpy as np
import pytest
from metpy.deprecation import MetpyDeprecationWarning
from metpy.testing import assert_array_almost_equal, check_and_silence_deprecation
# Test #1183: numpy.testing.assert_array* ignores any masked value, so work-around
# ... modified code ...
a = np.array([10, 20])
b = np.ma.array([10, 20], mask=[False, False])
assert_array_almost_equal(a, b)
@check_and_silence_deprecation
def test_deprecation_decorator():
"""Make sure the deprecation checker works."""
warnings.warn('Testing warning.', MetpyDeprecationWarning)
# ... rest of the code ...
|
25d39a7b78860102f7971033227ec157789a40b3
|
reporter/components/api_client.py
|
reporter/components/api_client.py
|
import json
import os
import requests
class ApiClient:
def __init__(self, host=None, timeout=5):
self.host = host or self.__default_host()
self.timeout = timeout
def post(self, payload):
print("Submitting payload to %s" % self.host)
headers = {"Content-Type": "application/json"}
response = requests.post(
"%s/test_reports" % self.host,
data=json.dumps(payload),
headers=headers,
timeout=self.timeout
)
return response
def __default_host(self):
return os.environ.get("CODECLIMATE_HOST", "https://codeclimate.com")
|
import json
import os
import requests
class ApiClient:
def __init__(self, host=None, timeout=5):
self.host = host or self.__default_host().rstrip("/")
self.timeout = timeout
def post(self, payload):
print("Submitting payload to %s" % self.host)
headers = {"Content-Type": "application/json"}
response = requests.post(
"%s/test_reports" % self.host,
data=json.dumps(payload),
headers=headers,
timeout=self.timeout
)
return response
def __default_host(self):
return os.environ.get("CODECLIMATE_API_HOST", "https://codeclimate.com")
|
Update ApiClient host env var to CODECLIMATE_API_HOST
|
Update ApiClient host env var to CODECLIMATE_API_HOST
This commit also strips trailing slashes from the host.
|
Python
|
mit
|
codeclimate/python-test-reporter,codeclimate/python-test-reporter
|
python
|
## Code Before:
import json
import os
import requests
class ApiClient:
def __init__(self, host=None, timeout=5):
self.host = host or self.__default_host()
self.timeout = timeout
def post(self, payload):
print("Submitting payload to %s" % self.host)
headers = {"Content-Type": "application/json"}
response = requests.post(
"%s/test_reports" % self.host,
data=json.dumps(payload),
headers=headers,
timeout=self.timeout
)
return response
def __default_host(self):
return os.environ.get("CODECLIMATE_HOST", "https://codeclimate.com")
## Instruction:
Update ApiClient host env var to CODECLIMATE_API_HOST
This commit also strips trailing slashes from the host.
## Code After:
import json
import os
import requests
class ApiClient:
def __init__(self, host=None, timeout=5):
self.host = host or self.__default_host().rstrip("/")
self.timeout = timeout
def post(self, payload):
print("Submitting payload to %s" % self.host)
headers = {"Content-Type": "application/json"}
response = requests.post(
"%s/test_reports" % self.host,
data=json.dumps(payload),
headers=headers,
timeout=self.timeout
)
return response
def __default_host(self):
return os.environ.get("CODECLIMATE_API_HOST", "https://codeclimate.com")
|
// ... existing code ...
class ApiClient:
def __init__(self, host=None, timeout=5):
self.host = host or self.__default_host().rstrip("/")
self.timeout = timeout
def post(self, payload):
// ... modified code ...
return response
def __default_host(self):
return os.environ.get("CODECLIMATE_API_HOST", "https://codeclimate.com")
// ... rest of the code ...
|
daca2bb7810b4c8eaf9f6a0598d8c6b41e0f2e10
|
froide_theme/settings.py
|
froide_theme/settings.py
|
from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3 # noqa
class CustomThemeBase(ThemeBase):
FROIDE_THEME = 'froide_theme.theme'
SITE_NAME = "My Froide"
SITE_EMAIL = "[email protected]"
SITE_URL = 'http://localhost:8000'
SECRET_URLS = {
"admin": "admin",
}
class Dev(CustomThemeBase, Base):
pass
class ThemeHerokuPostmark(CustomThemeBase, HerokuPostmark):
pass
class ThemeHerokuPostmarkS3(CustomThemeBase, HerokuPostmarkS3):
pass
try:
from .local_settings import * # noqa
except ImportError:
pass
|
import os
from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3 # noqa
class CustomThemeBase(ThemeBase):
FROIDE_THEME = 'froide_theme.theme'
SITE_NAME = "My Froide"
SITE_EMAIL = "[email protected]"
SITE_URL = 'http://localhost:8000'
SECRET_URLS = {
"admin": "admin",
}
@property
def LOCALE_PATHS(self):
return list(super(CustomThemeBase, self).LOCALE_PATHS.default) + [
os.path.abspath(
os.path.join(os.path.dirname(__file__), '..', "locale")
)
]
class Dev(CustomThemeBase, Base):
pass
class ThemeHerokuPostmark(CustomThemeBase, HerokuPostmark):
pass
class ThemeHerokuPostmarkS3(CustomThemeBase, HerokuPostmarkS3):
pass
try:
from .local_settings import * # noqa
except ImportError:
pass
|
Add own locale directory to LOCALE_PATHS
|
Add own locale directory to LOCALE_PATHS
|
Python
|
mit
|
CodeforHawaii/uipa_org,CodeforHawaii/uipa_org,CodeforHawaii/uipa_org,okfde/froide-theme
|
python
|
## Code Before:
from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3 # noqa
class CustomThemeBase(ThemeBase):
FROIDE_THEME = 'froide_theme.theme'
SITE_NAME = "My Froide"
SITE_EMAIL = "[email protected]"
SITE_URL = 'http://localhost:8000'
SECRET_URLS = {
"admin": "admin",
}
class Dev(CustomThemeBase, Base):
pass
class ThemeHerokuPostmark(CustomThemeBase, HerokuPostmark):
pass
class ThemeHerokuPostmarkS3(CustomThemeBase, HerokuPostmarkS3):
pass
try:
from .local_settings import * # noqa
except ImportError:
pass
## Instruction:
Add own locale directory to LOCALE_PATHS
## Code After:
import os
from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3 # noqa
class CustomThemeBase(ThemeBase):
FROIDE_THEME = 'froide_theme.theme'
SITE_NAME = "My Froide"
SITE_EMAIL = "[email protected]"
SITE_URL = 'http://localhost:8000'
SECRET_URLS = {
"admin": "admin",
}
@property
def LOCALE_PATHS(self):
return list(super(CustomThemeBase, self).LOCALE_PATHS.default) + [
os.path.abspath(
os.path.join(os.path.dirname(__file__), '..', "locale")
)
]
class Dev(CustomThemeBase, Base):
pass
class ThemeHerokuPostmark(CustomThemeBase, HerokuPostmark):
pass
class ThemeHerokuPostmarkS3(CustomThemeBase, HerokuPostmarkS3):
pass
try:
from .local_settings import * # noqa
except ImportError:
pass
|
# ... existing code ...
import os
from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3 # noqa
# ... modified code ...
SECRET_URLS = {
"admin": "admin",
}
@property
def LOCALE_PATHS(self):
return list(super(CustomThemeBase, self).LOCALE_PATHS.default) + [
os.path.abspath(
os.path.join(os.path.dirname(__file__), '..', "locale")
)
]
class Dev(CustomThemeBase, Base):
# ... rest of the code ...
|
7793f135808c1c133187f1d0a053b4f5549b58e8
|
lgogwebui.py
|
lgogwebui.py
|
import json
import os
import config
from models import Game, Status, session
from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)
@app.route('/')
def library():
with open(os.path.join(config.lgog_cache, 'gamedetails.json')) as f:
data = json.load(f)
if data is None:
return "Unable to load the GOG games database."
for game in data['games']:
game['download'] = -1
state = session.query(Game.state).filter(Game.name == game['gamename']).one()
if state == 'queue':
game['download'] = 0
elif state == 'running':
game['download'] = 0
elif os.path.isdir(os.path.join(config.lgog_library, game['gamename'])):
game['download'] = 1
return render_template('library.html', data=data['games'])
@app.route('/download/<game>')
def download(game):
db_game = session.query(Game).filter(Game.name == game).one()
if db_game.state != 'running':
db_game.state = 'queue'
session.commit()
return redirect(url_for('library'))
|
import json
import os
import config
from models import Game, Status, session
from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)
@app.route('/')
def library():
with open(os.path.join(config.lgog_cache, 'gamedetails.json'), encoding='utf-8') as f:
data = json.load(f)
if data is None:
return "Unable to load the GOG games database."
for game in data['games']:
game['download'] = -1
state = session.query(Game.state).filter(Game.name == game['gamename']).one()
if state == 'queue':
game['download'] = 0
elif state == 'running':
game['download'] = 0
elif os.path.isdir(os.path.join(config.lgog_library, game['gamename'])):
game['download'] = 1
return render_template('library.html', data=data['games'])
@app.route('/download/<game>')
def download(game):
db_game = session.query(Game).filter(Game.name == game).one()
if db_game.state != 'running':
db_game.state = 'queue'
session.commit()
return redirect(url_for('library'))
|
Correct UTF encoding of lgogdownloader json file.
|
Correct UTF encoding of lgogdownloader json file.
|
Python
|
bsd-2-clause
|
graag/lgogwebui,graag/lgogwebui,graag/lgogwebui
|
python
|
## Code Before:
import json
import os
import config
from models import Game, Status, session
from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)
@app.route('/')
def library():
with open(os.path.join(config.lgog_cache, 'gamedetails.json')) as f:
data = json.load(f)
if data is None:
return "Unable to load the GOG games database."
for game in data['games']:
game['download'] = -1
state = session.query(Game.state).filter(Game.name == game['gamename']).one()
if state == 'queue':
game['download'] = 0
elif state == 'running':
game['download'] = 0
elif os.path.isdir(os.path.join(config.lgog_library, game['gamename'])):
game['download'] = 1
return render_template('library.html', data=data['games'])
@app.route('/download/<game>')
def download(game):
db_game = session.query(Game).filter(Game.name == game).one()
if db_game.state != 'running':
db_game.state = 'queue'
session.commit()
return redirect(url_for('library'))
## Instruction:
Correct UTF encoding of lgogdownloader json file.
## Code After:
import json
import os
import config
from models import Game, Status, session
from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)
@app.route('/')
def library():
with open(os.path.join(config.lgog_cache, 'gamedetails.json'), encoding='utf-8') as f:
data = json.load(f)
if data is None:
return "Unable to load the GOG games database."
for game in data['games']:
game['download'] = -1
state = session.query(Game.state).filter(Game.name == game['gamename']).one()
if state == 'queue':
game['download'] = 0
elif state == 'running':
game['download'] = 0
elif os.path.isdir(os.path.join(config.lgog_library, game['gamename'])):
game['download'] = 1
return render_template('library.html', data=data['games'])
@app.route('/download/<game>')
def download(game):
db_game = session.query(Game).filter(Game.name == game).one()
if db_game.state != 'running':
db_game.state = 'queue'
session.commit()
return redirect(url_for('library'))
|
# ... existing code ...
@app.route('/')
def library():
with open(os.path.join(config.lgog_cache, 'gamedetails.json'), encoding='utf-8') as f:
data = json.load(f)
if data is None:
return "Unable to load the GOG games database."
# ... rest of the code ...
|
933a082a76c6c9b72aaf275f45f0d155f66eeacf
|
asv/__init__.py
|
asv/__init__.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys
if sys.version_info >= (3, 3):
# OS X framework builds of Python 3.3 can not call other 3.3
# virtualenvs as a subprocess because `__PYENV_LAUNCHER__` is
# inherited.
if os.environ.get('__PYVENV_LAUNCHER__'):
os.unsetenv('__PYVENV_LAUNCHER__')
|
Fix Python 3.3 calling another virtualenv as a subprocess.
|
Fix Python 3.3 calling another virtualenv as a subprocess.
|
Python
|
bsd-3-clause
|
waylonflinn/asv,airspeed-velocity/asv,edisongustavo/asv,giltis/asv,giltis/asv,qwhelan/asv,edisongustavo/asv,pv/asv,edisongustavo/asv,waylonflinn/asv,mdboom/asv,qwhelan/asv,cpcloud/asv,spacetelescope/asv,qwhelan/asv,pv/asv,giltis/asv,ericdill/asv,cpcloud/asv,mdboom/asv,mdboom/asv,ericdill/asv,cpcloud/asv,pv/asv,airspeed-velocity/asv,spacetelescope/asv,airspeed-velocity/asv,airspeed-velocity/asv,spacetelescope/asv,mdboom/asv,qwhelan/asv,spacetelescope/asv,ericdill/asv,waylonflinn/asv,pv/asv,ericdill/asv
|
python
|
## Code Before:
from __future__ import (absolute_import, division, print_function,
unicode_literals)
## Instruction:
Fix Python 3.3 calling another virtualenv as a subprocess.
## Code After:
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys
if sys.version_info >= (3, 3):
# OS X framework builds of Python 3.3 can not call other 3.3
# virtualenvs as a subprocess because `__PYENV_LAUNCHER__` is
# inherited.
if os.environ.get('__PYVENV_LAUNCHER__'):
os.unsetenv('__PYVENV_LAUNCHER__')
|
# ... existing code ...
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys
if sys.version_info >= (3, 3):
# OS X framework builds of Python 3.3 can not call other 3.3
# virtualenvs as a subprocess because `__PYENV_LAUNCHER__` is
# inherited.
if os.environ.get('__PYVENV_LAUNCHER__'):
os.unsetenv('__PYVENV_LAUNCHER__')
# ... rest of the code ...
|
53ce60063c8a308cbbe08eddd264dd1e30c93615
|
jarbas/core/tests/test_loaddatasets_command.py
|
jarbas/core/tests/test_loaddatasets_command.py
|
from django.test import TestCase
from jarbas.core.management.commands.loaddatasets import Command
class TestSerializer(TestCase):
def setUp(self):
self.command = Command()
def test_force_int(self):
self.assertEqual(self.command.force_int('1'), 1)
self.assertEqual(self.command.force_int('1.0'), 1)
with self.assertRaises(ValueError):
self.command.force_int('abc')
|
from django.test import TestCase
from jarbas.core.management.commands.loaddatasets import Command
class TestSerializer(TestCase):
def setUp(self):
self.command = Command()
def test_force_int(self):
self.assertEqual(self.command.force_int('1'), 1)
self.assertEqual(self.command.force_int('1.0'), 1)
with self.assertRaises(ValueError):
self.command.force_int('abc')
def test_serializer(self):
expected = {
'document_id': 1,
'congressperson_id': 1,
'congressperson_document': 1,
'term': 1,
'term_id': 1,
'subquota_number': 1,
'subquota_group_id': 1,
'document_type': 1,
'month': 1,
'year': 1,
'installment': 1,
'batch_number': 1,
'reimbursement_number': 1,
'applicant_id': 1,
'document_value': 1.1,
'remark_value': 1.1,
'net_value': 1.1,
'reimbursement_value': 1.1,
'issue_date': None,
}
document = {
'document_id': '1',
'congressperson_id': '1',
'congressperson_document': '1',
'term': '1',
'term_id': '1',
'subquota_number': '1',
'subquota_group_id': '1',
'document_type': '1',
'month': '1',
'year': '1',
'installment': '1',
'batch_number': '1',
'reimbursement_number': '1',
'applicant_id': '1',
'document_value': '1.1',
'remark_value': '1.1',
'net_value': '1.1',
'reimbursement_value': '1.1',
'issue_date': '',
}
self.assertEqual(self.command.serialize(document), expected)
|
Add loaddatasets serializer tests for real
|
Add loaddatasets serializer tests for real
|
Python
|
mit
|
marcusrehm/serenata-de-amor,rogeriochaves/jarbas,datasciencebr/serenata-de-amor,rogeriochaves/jarbas,marcusrehm/serenata-de-amor,rogeriochaves/jarbas,Guilhermeslucas/jarbas,datasciencebr/jarbas,rogeriochaves/jarbas,datasciencebr/serenata-de-amor,Guilhermeslucas/jarbas,datasciencebr/jarbas,Guilhermeslucas/jarbas,datasciencebr/jarbas,datasciencebr/jarbas,marcusrehm/serenata-de-amor,marcusrehm/serenata-de-amor,Guilhermeslucas/jarbas
|
python
|
## Code Before:
from django.test import TestCase
from jarbas.core.management.commands.loaddatasets import Command
class TestSerializer(TestCase):
def setUp(self):
self.command = Command()
def test_force_int(self):
self.assertEqual(self.command.force_int('1'), 1)
self.assertEqual(self.command.force_int('1.0'), 1)
with self.assertRaises(ValueError):
self.command.force_int('abc')
## Instruction:
Add loaddatasets serializer tests for real
## Code After:
from django.test import TestCase
from jarbas.core.management.commands.loaddatasets import Command
class TestSerializer(TestCase):
def setUp(self):
self.command = Command()
def test_force_int(self):
self.assertEqual(self.command.force_int('1'), 1)
self.assertEqual(self.command.force_int('1.0'), 1)
with self.assertRaises(ValueError):
self.command.force_int('abc')
def test_serializer(self):
expected = {
'document_id': 1,
'congressperson_id': 1,
'congressperson_document': 1,
'term': 1,
'term_id': 1,
'subquota_number': 1,
'subquota_group_id': 1,
'document_type': 1,
'month': 1,
'year': 1,
'installment': 1,
'batch_number': 1,
'reimbursement_number': 1,
'applicant_id': 1,
'document_value': 1.1,
'remark_value': 1.1,
'net_value': 1.1,
'reimbursement_value': 1.1,
'issue_date': None,
}
document = {
'document_id': '1',
'congressperson_id': '1',
'congressperson_document': '1',
'term': '1',
'term_id': '1',
'subquota_number': '1',
'subquota_group_id': '1',
'document_type': '1',
'month': '1',
'year': '1',
'installment': '1',
'batch_number': '1',
'reimbursement_number': '1',
'applicant_id': '1',
'document_value': '1.1',
'remark_value': '1.1',
'net_value': '1.1',
'reimbursement_value': '1.1',
'issue_date': '',
}
self.assertEqual(self.command.serialize(document), expected)
|
# ... existing code ...
self.assertEqual(self.command.force_int('1.0'), 1)
with self.assertRaises(ValueError):
self.command.force_int('abc')
def test_serializer(self):
expected = {
'document_id': 1,
'congressperson_id': 1,
'congressperson_document': 1,
'term': 1,
'term_id': 1,
'subquota_number': 1,
'subquota_group_id': 1,
'document_type': 1,
'month': 1,
'year': 1,
'installment': 1,
'batch_number': 1,
'reimbursement_number': 1,
'applicant_id': 1,
'document_value': 1.1,
'remark_value': 1.1,
'net_value': 1.1,
'reimbursement_value': 1.1,
'issue_date': None,
}
document = {
'document_id': '1',
'congressperson_id': '1',
'congressperson_document': '1',
'term': '1',
'term_id': '1',
'subquota_number': '1',
'subquota_group_id': '1',
'document_type': '1',
'month': '1',
'year': '1',
'installment': '1',
'batch_number': '1',
'reimbursement_number': '1',
'applicant_id': '1',
'document_value': '1.1',
'remark_value': '1.1',
'net_value': '1.1',
'reimbursement_value': '1.1',
'issue_date': '',
}
self.assertEqual(self.command.serialize(document), expected)
# ... rest of the code ...
|
c784fb30beac7abe958867345161f74876ca940d
|
causalinfo/__init__.py
|
causalinfo/__init__.py
|
from .probability import (
vs,
Variable,
make_variables,
UniformDist,
JointDist,
JointDistByState
)
from .network import CausalGraph, Equation
from .measure import MeasureCause, MeasureSuccess
from .payoff import PayoffMatrix
import equations
__version__ = "0.1.0"
__title__ = "causalinfo"
__description__ = "Attributes without boilerplate."
__uri__ = "http://github/brettc/causalinfo/"
__author__ = "Brett Calcott"
__email__ = "[email protected]"
__license__ = "MIT"
__copyright__ = "Copyright (c) 2015 Brett Calcott"
__all__ = [
"CausalGraph",
"Equation",
"vs",
"Variable",
"make_variables",
"UniformDist",
"JointDist",
"JointDistByState",
"MeasureCause",
"MeasureSuccess",
"PayoffMatrix",
"equations",
]
|
from .probability import (
vs,
Variable,
make_variables,
UniformDist,
JointDist,
JointDistByState
)
from .network import CausalGraph, Equation
from .measure import MeasureCause, MeasureSuccess
from .payoff import PayoffMatrix
import equations
__version__ = "0.1.0"
__title__ = "causalinfo"
__description__ = "Information Measures on Causal Graphs."
__uri__ = "http://github/brettc/causalinfo/"
__author__ = "Brett Calcott"
__email__ = "[email protected]"
__license__ = "MIT"
__copyright__ = "Copyright (c) 2015 Brett Calcott"
__all__ = [
"CausalGraph",
"Equation",
"vs",
"Variable",
"make_variables",
"UniformDist",
"JointDist",
"JointDistByState",
"MeasureCause",
"MeasureSuccess",
"PayoffMatrix",
"equations",
]
|
Fix silly boiler plate copy issue.
|
Fix silly boiler plate copy issue.
|
Python
|
mit
|
brettc/causalinfo
|
python
|
## Code Before:
from .probability import (
vs,
Variable,
make_variables,
UniformDist,
JointDist,
JointDistByState
)
from .network import CausalGraph, Equation
from .measure import MeasureCause, MeasureSuccess
from .payoff import PayoffMatrix
import equations
__version__ = "0.1.0"
__title__ = "causalinfo"
__description__ = "Attributes without boilerplate."
__uri__ = "http://github/brettc/causalinfo/"
__author__ = "Brett Calcott"
__email__ = "[email protected]"
__license__ = "MIT"
__copyright__ = "Copyright (c) 2015 Brett Calcott"
__all__ = [
"CausalGraph",
"Equation",
"vs",
"Variable",
"make_variables",
"UniformDist",
"JointDist",
"JointDistByState",
"MeasureCause",
"MeasureSuccess",
"PayoffMatrix",
"equations",
]
## Instruction:
Fix silly boiler plate copy issue.
## Code After:
from .probability import (
vs,
Variable,
make_variables,
UniformDist,
JointDist,
JointDistByState
)
from .network import CausalGraph, Equation
from .measure import MeasureCause, MeasureSuccess
from .payoff import PayoffMatrix
import equations
__version__ = "0.1.0"
__title__ = "causalinfo"
__description__ = "Information Measures on Causal Graphs."
__uri__ = "http://github/brettc/causalinfo/"
__author__ = "Brett Calcott"
__email__ = "[email protected]"
__license__ = "MIT"
__copyright__ = "Copyright (c) 2015 Brett Calcott"
__all__ = [
"CausalGraph",
"Equation",
"vs",
"Variable",
"make_variables",
"UniformDist",
"JointDist",
"JointDistByState",
"MeasureCause",
"MeasureSuccess",
"PayoffMatrix",
"equations",
]
|
...
__version__ = "0.1.0"
__title__ = "causalinfo"
__description__ = "Information Measures on Causal Graphs."
__uri__ = "http://github/brettc/causalinfo/"
__author__ = "Brett Calcott"
...
|
6fd8bf7a3113c82c88325dd04fe610ba10049855
|
setup.py
|
setup.py
|
from distutils.core import setup
long_description = '''
This module allows you to perform IP subnet calculations, there is support
for both IPv4 and IPv6 CIDR notation.
'''
setup(name='ipcalc',
version='0.4',
description='IP subnet calculator',
long_description=long_description,
author='Wijnand Modderman',
author_email='[email protected]',
url='http://dev.tehmaze.com/projects/ipcalc',
packages = [''],
package_dir = {'': 'src'},
)
|
from distutils.core import setup
setup(name='ipcalc',
version='0.4',
description='IP subnet calculator',
long_description=file('README.rst').read(),
author='Wijnand Modderman',
author_email='[email protected]',
url='http://dev.tehmaze.com/projects/ipcalc',
packages = [''],
package_dir = {'': 'src'},
)
|
Read README.rst for the long description
|
Read README.rst for the long description
|
Python
|
bsd-2-clause
|
panaceya/ipcalc,tehmaze/ipcalc
|
python
|
## Code Before:
from distutils.core import setup
long_description = '''
This module allows you to perform IP subnet calculations, there is support
for both IPv4 and IPv6 CIDR notation.
'''
setup(name='ipcalc',
version='0.4',
description='IP subnet calculator',
long_description=long_description,
author='Wijnand Modderman',
author_email='[email protected]',
url='http://dev.tehmaze.com/projects/ipcalc',
packages = [''],
package_dir = {'': 'src'},
)
## Instruction:
Read README.rst for the long description
## Code After:
from distutils.core import setup
setup(name='ipcalc',
version='0.4',
description='IP subnet calculator',
long_description=file('README.rst').read(),
author='Wijnand Modderman',
author_email='[email protected]',
url='http://dev.tehmaze.com/projects/ipcalc',
packages = [''],
package_dir = {'': 'src'},
)
|
# ... existing code ...
from distutils.core import setup
setup(name='ipcalc',
version='0.4',
description='IP subnet calculator',
long_description=file('README.rst').read(),
author='Wijnand Modderman',
author_email='[email protected]',
url='http://dev.tehmaze.com/projects/ipcalc',
# ... rest of the code ...
|
12e2cdc94c33d7a5988f41e8f8120c40cd6f2ec6
|
RetroXUtils/src/retrobox/utils/MountPoint.java
|
RetroXUtils/src/retrobox/utils/MountPoint.java
|
package retrobox.utils;
import java.io.File;
import xtvapps.core.Utils;
public class MountPoint {
File dir;
String description;
String filesystem = "unknown";
public MountPoint(String path) {
this.dir = new File(path);
}
public MountPoint(File dir) {
this.dir = dir;
}
public MountPoint() {
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isValid() {
return dir!=null;
}
public long getFreeSpace() {
return dir==null?0:dir.getFreeSpace();
}
public long getTotalSpace() {
return dir==null?0:dir.getTotalSpace();
}
public File getDir() {
return dir;
}
public String getFilesystem() {
return filesystem;
}
public void setFilesystem(String filesystem) {
this.filesystem = filesystem;
}
public String getFriendlyFreeSpace() {
return Utils.size2humanDetailed(getFreeSpace()) + " free of " + Utils.size2humanDetailed(getTotalSpace());
}
@Override
public String toString() {
return String.format("path:%s, desc:%s", dir!=null?dir.getAbsolutePath():"null", description);
}
}
|
package retrobox.utils;
import java.io.File;
import xtvapps.core.Utils;
public class MountPoint {
File dir;
String description;
String filesystem = "unknown";
boolean isWritable = false;
public MountPoint(String path) {
this.dir = new File(path);
}
public MountPoint(File dir) {
this.dir = dir;
}
public MountPoint() {
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isValid() {
return dir!=null;
}
public long getFreeSpace() {
return dir==null?0:dir.getFreeSpace();
}
public long getTotalSpace() {
return dir==null?0:dir.getTotalSpace();
}
public File getDir() {
return dir;
}
public String getFilesystem() {
return filesystem;
}
public void setFilesystem(String filesystem) {
this.filesystem = filesystem;
}
public String getFriendlyFreeSpace() {
return Utils.size2humanDetailed(getFreeSpace()) + " free of " + Utils.size2humanDetailed(getTotalSpace());
}
public boolean isWritable() {
return isWritable;
}
public void setWritable(boolean isWritable) {
this.isWritable = isWritable;
}
@Override
public String toString() {
return String.format("path:%s, desc:%s", dir!=null?dir.getAbsolutePath():"null", description);
}
}
|
Allow setting a flag for writable / non writable folders
|
Allow setting a flag for writable / non writable folders
|
Java
|
lgpl-2.1
|
fcatrin/retroxlibs
|
java
|
## Code Before:
package retrobox.utils;
import java.io.File;
import xtvapps.core.Utils;
public class MountPoint {
File dir;
String description;
String filesystem = "unknown";
public MountPoint(String path) {
this.dir = new File(path);
}
public MountPoint(File dir) {
this.dir = dir;
}
public MountPoint() {
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isValid() {
return dir!=null;
}
public long getFreeSpace() {
return dir==null?0:dir.getFreeSpace();
}
public long getTotalSpace() {
return dir==null?0:dir.getTotalSpace();
}
public File getDir() {
return dir;
}
public String getFilesystem() {
return filesystem;
}
public void setFilesystem(String filesystem) {
this.filesystem = filesystem;
}
public String getFriendlyFreeSpace() {
return Utils.size2humanDetailed(getFreeSpace()) + " free of " + Utils.size2humanDetailed(getTotalSpace());
}
@Override
public String toString() {
return String.format("path:%s, desc:%s", dir!=null?dir.getAbsolutePath():"null", description);
}
}
## Instruction:
Allow setting a flag for writable / non writable folders
## Code After:
package retrobox.utils;
import java.io.File;
import xtvapps.core.Utils;
public class MountPoint {
File dir;
String description;
String filesystem = "unknown";
boolean isWritable = false;
public MountPoint(String path) {
this.dir = new File(path);
}
public MountPoint(File dir) {
this.dir = dir;
}
public MountPoint() {
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isValid() {
return dir!=null;
}
public long getFreeSpace() {
return dir==null?0:dir.getFreeSpace();
}
public long getTotalSpace() {
return dir==null?0:dir.getTotalSpace();
}
public File getDir() {
return dir;
}
public String getFilesystem() {
return filesystem;
}
public void setFilesystem(String filesystem) {
this.filesystem = filesystem;
}
public String getFriendlyFreeSpace() {
return Utils.size2humanDetailed(getFreeSpace()) + " free of " + Utils.size2humanDetailed(getTotalSpace());
}
public boolean isWritable() {
return isWritable;
}
public void setWritable(boolean isWritable) {
this.isWritable = isWritable;
}
@Override
public String toString() {
return String.format("path:%s, desc:%s", dir!=null?dir.getAbsolutePath():"null", description);
}
}
|
# ... existing code ...
File dir;
String description;
String filesystem = "unknown";
boolean isWritable = false;
public MountPoint(String path) {
this.dir = new File(path);
# ... modified code ...
return Utils.size2humanDetailed(getFreeSpace()) + " free of " + Utils.size2humanDetailed(getTotalSpace());
}
public boolean isWritable() {
return isWritable;
}
public void setWritable(boolean isWritable) {
this.isWritable = isWritable;
}
@Override
public String toString() {
return String.format("path:%s, desc:%s", dir!=null?dir.getAbsolutePath():"null", description);
# ... rest of the code ...
|
6d2d915d7bec4e4a8e733a073ec3dc79a1d06812
|
src/stop.py
|
src/stop.py
|
import os
import json
from flask import Flask
from flask import request
from flask import json
import services
app = Flask(__name__)
digitransitAPIService = services.DigitransitAPIService()
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/test')
def digitransit_test():
return json.dumps(digitransitAPIService.get_stops(60.203978, 24.9633573))
@app.route('/stops', methods=['GET'])
def stops():
lat = float(request.args.get('lat'))
lon = float(request.args.get('lon'))
result = digitransitAPIService.get_stops(lat, lon)
print(result)
return json.dumps(result)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=os.getenv('PORT', '5000'))
|
import os
import json
from flask import Flask
from flask import make_response
from flask import request
from flask import json
import services
app = Flask(__name__)
digitransitAPIService = services.DigitransitAPIService()
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/test')
def digitransit_test():
return json.dumps(digitransitAPIService.get_stops(60.203978, 24.9633573))
@app.route('/stops', methods=['GET'])
def stops():
lat = float(request.args.get('lat'))
lon = float(request.args.get('lon'))
result = digitransitAPIService.get_stops(lat, lon)
resp = make_response(json.dumps(result))
resp.mimetype = 'application/json'
return resp
if __name__ == '__main__':
app.run(host='0.0.0.0', port=os.getenv('PORT', '5000'))
|
Set response content type of a json response to application/json
|
Set response content type of a json response to application/json
|
Python
|
mit
|
STOP2/stop2.0-backend,STOP2/stop2.0-backend
|
python
|
## Code Before:
import os
import json
from flask import Flask
from flask import request
from flask import json
import services
app = Flask(__name__)
digitransitAPIService = services.DigitransitAPIService()
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/test')
def digitransit_test():
return json.dumps(digitransitAPIService.get_stops(60.203978, 24.9633573))
@app.route('/stops', methods=['GET'])
def stops():
lat = float(request.args.get('lat'))
lon = float(request.args.get('lon'))
result = digitransitAPIService.get_stops(lat, lon)
print(result)
return json.dumps(result)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=os.getenv('PORT', '5000'))
## Instruction:
Set response content type of a json response to application/json
## Code After:
import os
import json
from flask import Flask
from flask import make_response
from flask import request
from flask import json
import services
app = Flask(__name__)
digitransitAPIService = services.DigitransitAPIService()
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/test')
def digitransit_test():
return json.dumps(digitransitAPIService.get_stops(60.203978, 24.9633573))
@app.route('/stops', methods=['GET'])
def stops():
lat = float(request.args.get('lat'))
lon = float(request.args.get('lon'))
result = digitransitAPIService.get_stops(lat, lon)
resp = make_response(json.dumps(result))
resp.mimetype = 'application/json'
return resp
if __name__ == '__main__':
app.run(host='0.0.0.0', port=os.getenv('PORT', '5000'))
|
...
import os
import json
from flask import Flask
from flask import make_response
from flask import request
from flask import json
...
lat = float(request.args.get('lat'))
lon = float(request.args.get('lon'))
result = digitransitAPIService.get_stops(lat, lon)
resp = make_response(json.dumps(result))
resp.mimetype = 'application/json'
return resp
if __name__ == '__main__':
app.run(host='0.0.0.0', port=os.getenv('PORT', '5000'))
...
|
7512f4b5fb5ebad5781e76ecd61c0e2d24b54f6c
|
projects/urls.py
|
projects/urls.py
|
from django.conf import settings
from django.conf.urls import include, url
from django.views.generic import TemplateView
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
# Include any views
from . import views
urlpatterns = [
url(r'^$', views.index, name='projects'),
url(r'^(?P<slug>.+)$', views.post, name='project'),
]
# Blog URLs
if 'projects' in settings.INSTALLED_APPS:
urlpatterns += [
url(r'^projects/', include(projects.urls, app_name='projects',
namespace='projects')),
]
|
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='projects'),
url(r'^(?P<slug>.+)', views.project, name='project'),
]
|
Add license statement, removed unused code, and set up the project URL mapping
|
Add license statement, removed unused code, and set up the project URL mapping
|
Python
|
agpl-3.0
|
lo-windigo/fragdev,lo-windigo/fragdev
|
python
|
## Code Before:
from django.conf import settings
from django.conf.urls import include, url
from django.views.generic import TemplateView
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
# Include any views
from . import views
urlpatterns = [
url(r'^$', views.index, name='projects'),
url(r'^(?P<slug>.+)$', views.post, name='project'),
]
# Blog URLs
if 'projects' in settings.INSTALLED_APPS:
urlpatterns += [
url(r'^projects/', include(projects.urls, app_name='projects',
namespace='projects')),
]
## Instruction:
Add license statement, removed unused code, and set up the project URL mapping
## Code After:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='projects'),
url(r'^(?P<slug>.+)', views.project, name='project'),
]
|
// ... existing code ...
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='projects'),
url(r'^(?P<slug>.+)', views.project, name='project'),
]
// ... rest of the code ...
|
48ec1d9494ae8215f6b4bc4b79bcefe318d8a5b4
|
create_csv.py
|
create_csv.py
|
import csv
from datetime import date
from scraper.draft_scraper import scrape
CSV_FILE = 'datasets/%s_nbadraft.csv'
for year in range(1947, date.today().year):
draft = scrape(year)
header = [key for key in draft[1].keys()]
with open(CSV_FILE % year, 'w', newline='') as outfile:
dw = csv.DictWriter(outfile, header)
dw.writeheader()
dw.writerows([row for index, row in draft.items()])
|
import csv
from datetime import date
from scraper.draft_scraper import scrape
CSV_FILE = 'datasets/%s_nbadraft.csv'
for year in range(1947, date.today().year):
draft = scrape(year)
header = [key for key in draft[1].keys()]
with open(CSV_FILE % year, 'w', newline='') as outfile:
dw = csv.DictWriter(outfile, header)
dw.writeheader()
dw.writerows([row for index, row in draft.items()])
print('Data processed for %s.' % year)
|
Print line after creating each csv
|
Print line after creating each csv
|
Python
|
mit
|
kshvmdn/nbadrafts
|
python
|
## Code Before:
import csv
from datetime import date
from scraper.draft_scraper import scrape
CSV_FILE = 'datasets/%s_nbadraft.csv'
for year in range(1947, date.today().year):
draft = scrape(year)
header = [key for key in draft[1].keys()]
with open(CSV_FILE % year, 'w', newline='') as outfile:
dw = csv.DictWriter(outfile, header)
dw.writeheader()
dw.writerows([row for index, row in draft.items()])
## Instruction:
Print line after creating each csv
## Code After:
import csv
from datetime import date
from scraper.draft_scraper import scrape
CSV_FILE = 'datasets/%s_nbadraft.csv'
for year in range(1947, date.today().year):
draft = scrape(year)
header = [key for key in draft[1].keys()]
with open(CSV_FILE % year, 'w', newline='') as outfile:
dw = csv.DictWriter(outfile, header)
dw.writeheader()
dw.writerows([row for index, row in draft.items()])
print('Data processed for %s.' % year)
|
// ... existing code ...
dw = csv.DictWriter(outfile, header)
dw.writeheader()
dw.writerows([row for index, row in draft.items()])
print('Data processed for %s.' % year)
// ... rest of the code ...
|
adf71b59168c81240258a2b344e4bea1f6377e7b
|
etools/apps/uptime/forms/report_forms.py
|
etools/apps/uptime/forms/report_forms.py
|
from django import forms
from bootstrap3_datetime.widgets import DateTimePicker
class ChooseReportForm(forms.Form):
date_from = forms.DateField(
widget=DateTimePicker(options={"locale": "ru",
"pickTime": False}),
label='От даты:',
)
date = forms.DateField(
widget=DateTimePicker(options={"locale": "ru",
"pickTime": False}),
label=', на дату:',
)
def __init__(self, choices=None, *args, **kwargs):
super(ChooseReportForm, self).__init__(*args, **kwargs)
if choices:
self.fields.update(
{'report_id': forms.ChoiceField(widget=forms.Select,
label='отчет:',
choices=choices)}
)
|
from django import forms
from bootstrap3_datetime.widgets import DateTimePicker
class ChooseReportForm(forms.Form):
date_from = forms.DateField(
widget=DateTimePicker(options={"locale": "ru",
"pickTime": False,
"startDate": "1/1/1953"}),
label='От даты:',
)
date = forms.DateField(
widget=DateTimePicker(options={"locale": "ru",
"pickTime": False,
"startDate": "1/1/1953"}),
label=', на дату:',
)
def __init__(self, choices=None, *args, **kwargs):
super(ChooseReportForm, self).__init__(*args, **kwargs)
if choices:
self.fields.update(
{'report_id': forms.ChoiceField(widget=forms.Select,
label='отчет:',
choices=choices)}
)
|
Fix minimum date for uptime:reports
|
Fix minimum date for uptime:reports
|
Python
|
bsd-3-clause
|
Igelinmist/etools,Igelinmist/etools
|
python
|
## Code Before:
from django import forms
from bootstrap3_datetime.widgets import DateTimePicker
class ChooseReportForm(forms.Form):
date_from = forms.DateField(
widget=DateTimePicker(options={"locale": "ru",
"pickTime": False}),
label='От даты:',
)
date = forms.DateField(
widget=DateTimePicker(options={"locale": "ru",
"pickTime": False}),
label=', на дату:',
)
def __init__(self, choices=None, *args, **kwargs):
super(ChooseReportForm, self).__init__(*args, **kwargs)
if choices:
self.fields.update(
{'report_id': forms.ChoiceField(widget=forms.Select,
label='отчет:',
choices=choices)}
)
## Instruction:
Fix minimum date for uptime:reports
## Code After:
from django import forms
from bootstrap3_datetime.widgets import DateTimePicker
class ChooseReportForm(forms.Form):
date_from = forms.DateField(
widget=DateTimePicker(options={"locale": "ru",
"pickTime": False,
"startDate": "1/1/1953"}),
label='От даты:',
)
date = forms.DateField(
widget=DateTimePicker(options={"locale": "ru",
"pickTime": False,
"startDate": "1/1/1953"}),
label=', на дату:',
)
def __init__(self, choices=None, *args, **kwargs):
super(ChooseReportForm, self).__init__(*args, **kwargs)
if choices:
self.fields.update(
{'report_id': forms.ChoiceField(widget=forms.Select,
label='отчет:',
choices=choices)}
)
|
...
class ChooseReportForm(forms.Form):
date_from = forms.DateField(
widget=DateTimePicker(options={"locale": "ru",
"pickTime": False,
"startDate": "1/1/1953"}),
label='От даты:',
)
date = forms.DateField(
widget=DateTimePicker(options={"locale": "ru",
"pickTime": False,
"startDate": "1/1/1953"}),
label=', на дату:',
)
...
|
984089c3e963998d62768721f23d7e7c72880e39
|
tests/testapp/test_fhadmin.py
|
tests/testapp/test_fhadmin.py
|
from django.contrib.auth.models import User
from django.test import Client, TestCase
class AdminTest(TestCase):
def login(self):
client = Client()
u = User.objects.create(
username="test", is_active=True, is_staff=True, is_superuser=True
)
client.force_login(u)
return client
def test_dashboard(self):
client = self.login()
response = client.get("/admin/")
self.assertContains(response, '<div class="groups">')
self.assertContains(response, "<h2>Modules</h2>")
self.assertContains(response, "<h2>Preferences</h2>")
print(response, response.content.decode("utf-8"))
|
from django.contrib import admin
from django.contrib.auth.models import User
from django.test import Client, RequestFactory, TestCase
from fhadmin.templatetags.fhadmin_module_groups import generate_group_list
class AdminTest(TestCase):
def login(self):
client = Client()
u = User.objects.create(
username="test", is_active=True, is_staff=True, is_superuser=True
)
client.force_login(u)
return client
def test_dashboard(self):
client = self.login()
response = client.get("/admin/")
self.assertContains(response, '<div class="groups">')
self.assertContains(response, "<h2>Modules</h2>")
self.assertContains(response, "<h2>Preferences</h2>")
# print(response, response.content.decode("utf-8"))
def test_app_list(self):
request = RequestFactory().get("/")
request.user = User.objects.create(is_superuser=True)
groups = list(generate_group_list(admin.sites.site, request))
# from pprint import pprint; pprint(groups)
self.assertEqual(groups[0][0], "Modules")
self.assertEqual(groups[0][1][0]["app_label"], "testapp")
self.assertEqual(len(groups[0][1][0]["models"]), 1)
|
Test the app list generation a bit
|
Test the app list generation a bit
|
Python
|
bsd-3-clause
|
feinheit/django-fhadmin,feinheit/django-fhadmin,feinheit/django-fhadmin
|
python
|
## Code Before:
from django.contrib.auth.models import User
from django.test import Client, TestCase
class AdminTest(TestCase):
def login(self):
client = Client()
u = User.objects.create(
username="test", is_active=True, is_staff=True, is_superuser=True
)
client.force_login(u)
return client
def test_dashboard(self):
client = self.login()
response = client.get("/admin/")
self.assertContains(response, '<div class="groups">')
self.assertContains(response, "<h2>Modules</h2>")
self.assertContains(response, "<h2>Preferences</h2>")
print(response, response.content.decode("utf-8"))
## Instruction:
Test the app list generation a bit
## Code After:
from django.contrib import admin
from django.contrib.auth.models import User
from django.test import Client, RequestFactory, TestCase
from fhadmin.templatetags.fhadmin_module_groups import generate_group_list
class AdminTest(TestCase):
def login(self):
client = Client()
u = User.objects.create(
username="test", is_active=True, is_staff=True, is_superuser=True
)
client.force_login(u)
return client
def test_dashboard(self):
client = self.login()
response = client.get("/admin/")
self.assertContains(response, '<div class="groups">')
self.assertContains(response, "<h2>Modules</h2>")
self.assertContains(response, "<h2>Preferences</h2>")
# print(response, response.content.decode("utf-8"))
def test_app_list(self):
request = RequestFactory().get("/")
request.user = User.objects.create(is_superuser=True)
groups = list(generate_group_list(admin.sites.site, request))
# from pprint import pprint; pprint(groups)
self.assertEqual(groups[0][0], "Modules")
self.assertEqual(groups[0][1][0]["app_label"], "testapp")
self.assertEqual(len(groups[0][1][0]["models"]), 1)
|
// ... existing code ...
from django.contrib import admin
from django.contrib.auth.models import User
from django.test import Client, RequestFactory, TestCase
from fhadmin.templatetags.fhadmin_module_groups import generate_group_list
class AdminTest(TestCase):
// ... modified code ...
self.assertContains(response, "<h2>Modules</h2>")
self.assertContains(response, "<h2>Preferences</h2>")
# print(response, response.content.decode("utf-8"))
def test_app_list(self):
request = RequestFactory().get("/")
request.user = User.objects.create(is_superuser=True)
groups = list(generate_group_list(admin.sites.site, request))
# from pprint import pprint; pprint(groups)
self.assertEqual(groups[0][0], "Modules")
self.assertEqual(groups[0][1][0]["app_label"], "testapp")
self.assertEqual(len(groups[0][1][0]["models"]), 1)
// ... rest of the code ...
|
37cbdc6402f568f7bf613a69f029a068f4ef3113
|
vector/src/main/java/im/vector/EventEmitter.java
|
vector/src/main/java/im/vector/EventEmitter.java
|
package im.vector;
import android.os.Handler;
import android.os.Looper;
import org.matrix.androidsdk.util.Log;
import java.util.HashSet;
import java.util.Set;
public class EventEmitter<T> {
private static final String LOG_TAG = EventEmitter.class.getSimpleName();
private final Set<Listener<T>> mCallbacks;
private final Handler mUiHandler;
public EventEmitter() {
mCallbacks = new HashSet<>();
mUiHandler = new Handler(Looper.getMainLooper());
}
public void register(Listener<T> cb) {
mCallbacks.add(cb);
}
public void unregister(Listener<T> cb) {
mCallbacks.remove(cb);
}
/**
* Fires all registered callbacks on the UI thread.
*
* @param t
*/
public void fire(final T t) {
final Set<Listener<T>> callbacks = new HashSet<>(mCallbacks);
mUiHandler.post(new Runnable() {
@Override
public void run() {
for (Listener<T> cb : callbacks) {
try {
cb.onEventFired(EventEmitter.this, t);
} catch (Exception e) {
Log.e(LOG_TAG, "Callback threw: " + e.getMessage(), e);
}
}
}
}
);
}
public interface Listener<T> {
void onEventFired(EventEmitter<T> emitter, T t);
}
}
|
package im.vector;
import android.os.Handler;
import android.os.Looper;
import org.matrix.androidsdk.util.Log;
import java.util.HashSet;
import java.util.Set;
public class EventEmitter<T> {
private static final String LOG_TAG = EventEmitter.class.getSimpleName();
private final Set<Listener<T>> mCallbacks;
private final Handler mUiHandler;
public EventEmitter() {
mCallbacks = new HashSet<>();
mUiHandler = new Handler(Looper.getMainLooper());
}
public void register(Listener<T> cb) {
mCallbacks.add(cb);
}
public void unregister(Listener<T> cb) {
mCallbacks.remove(cb);
}
/**
* Fires all registered callbacks on the UI thread.
*
* @param t passed to the callback
*/
public void fire(final T t) {
final Set<Listener<T>> callbacks = new HashSet<>(mCallbacks);
mUiHandler.post(new Runnable() {
@Override
public void run() {
for (Listener<T> cb : callbacks) {
try {
cb.onEventFired(EventEmitter.this, t);
} catch (Exception e) {
Log.e(LOG_TAG, "Callback threw: " + e.getMessage(), e);
}
}
}
}
);
}
public interface Listener<T> {
void onEventFired(EventEmitter<T> emitter, T t);
}
}
|
Add parameter documentation to the even emitter
|
Add parameter documentation to the even emitter
|
Java
|
apache-2.0
|
vector-im/vector-android,vector-im/vector-android,vector-im/riot-android,vector-im/riot-android,vector-im/vector-android,vector-im/riot-android,vector-im/vector-android,vector-im/riot-android,vector-im/riot-android
|
java
|
## Code Before:
package im.vector;
import android.os.Handler;
import android.os.Looper;
import org.matrix.androidsdk.util.Log;
import java.util.HashSet;
import java.util.Set;
public class EventEmitter<T> {
private static final String LOG_TAG = EventEmitter.class.getSimpleName();
private final Set<Listener<T>> mCallbacks;
private final Handler mUiHandler;
public EventEmitter() {
mCallbacks = new HashSet<>();
mUiHandler = new Handler(Looper.getMainLooper());
}
public void register(Listener<T> cb) {
mCallbacks.add(cb);
}
public void unregister(Listener<T> cb) {
mCallbacks.remove(cb);
}
/**
* Fires all registered callbacks on the UI thread.
*
* @param t
*/
public void fire(final T t) {
final Set<Listener<T>> callbacks = new HashSet<>(mCallbacks);
mUiHandler.post(new Runnable() {
@Override
public void run() {
for (Listener<T> cb : callbacks) {
try {
cb.onEventFired(EventEmitter.this, t);
} catch (Exception e) {
Log.e(LOG_TAG, "Callback threw: " + e.getMessage(), e);
}
}
}
}
);
}
public interface Listener<T> {
void onEventFired(EventEmitter<T> emitter, T t);
}
}
## Instruction:
Add parameter documentation to the even emitter
## Code After:
package im.vector;
import android.os.Handler;
import android.os.Looper;
import org.matrix.androidsdk.util.Log;
import java.util.HashSet;
import java.util.Set;
public class EventEmitter<T> {
private static final String LOG_TAG = EventEmitter.class.getSimpleName();
private final Set<Listener<T>> mCallbacks;
private final Handler mUiHandler;
public EventEmitter() {
mCallbacks = new HashSet<>();
mUiHandler = new Handler(Looper.getMainLooper());
}
public void register(Listener<T> cb) {
mCallbacks.add(cb);
}
public void unregister(Listener<T> cb) {
mCallbacks.remove(cb);
}
/**
* Fires all registered callbacks on the UI thread.
*
* @param t passed to the callback
*/
public void fire(final T t) {
final Set<Listener<T>> callbacks = new HashSet<>(mCallbacks);
mUiHandler.post(new Runnable() {
@Override
public void run() {
for (Listener<T> cb : callbacks) {
try {
cb.onEventFired(EventEmitter.this, t);
} catch (Exception e) {
Log.e(LOG_TAG, "Callback threw: " + e.getMessage(), e);
}
}
}
}
);
}
public interface Listener<T> {
void onEventFired(EventEmitter<T> emitter, T t);
}
}
|
...
package im.vector;
import android.os.Handler;
import android.os.Looper;
...
/**
* Fires all registered callbacks on the UI thread.
*
* @param t passed to the callback
*/
public void fire(final T t) {
final Set<Listener<T>> callbacks = new HashSet<>(mCallbacks);
...
|
f622569041c3aae25a243029609d63606b29015f
|
start.py
|
start.py
|
try:
import rc
except ImportError:
import vx
# which keybinding do we want
from keybindings import hopscotch
vx.default_start()
|
try:
import rc
except ImportError:
import vx
# which keybinding do we want
from keybindings import concat
vx.default_keybindings = concat.load
vx.default_start()
|
Change default keybindings to concat since these are the only ones that work
|
Change default keybindings to concat since these are the only ones that work
At least for now
|
Python
|
mit
|
philipdexter/vx,philipdexter/vx
|
python
|
## Code Before:
try:
import rc
except ImportError:
import vx
# which keybinding do we want
from keybindings import hopscotch
vx.default_start()
## Instruction:
Change default keybindings to concat since these are the only ones that work
At least for now
## Code After:
try:
import rc
except ImportError:
import vx
# which keybinding do we want
from keybindings import concat
vx.default_keybindings = concat.load
vx.default_start()
|
...
import vx
# which keybinding do we want
from keybindings import concat
vx.default_keybindings = concat.load
vx.default_start()
...
|
146d71c86c5e58b0ed41e66de7a5c94e937fc6a9
|
setup.py
|
setup.py
|
from setuptools import find_packages, setup
VERSION = "1.0.0"
with open("requirements.txt", "rt") as f:
requirements= f.read().splitlines()
setup(name="sacad",
version=VERSION,
author="desbma",
packages=find_packages(),
entry_points={"console_scripts": ["sacad = sacad:cl_main"]},
package_data={"": ["LICENSE", "README.md", "requirements.txt"]},
test_suite="tests",
install_requires=requirements,
description="Search and download music album covers",
url="https://github.com/desbma/sacad",
download_url="https://github.com/desbma/sacad/tarball/%s" % (VERSION),
keywords=["dowload", "album", "cover", "art", "albumart", "music"],
classifiers=["Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Multimedia :: Graphics",
"Topic :: Utilities"])
|
from setuptools import find_packages, setup
VERSION = "1.0.0"
with open("requirements.txt", "rt") as f:
requirements= f.read().splitlines()
setup(name="sacad",
version=VERSION,
author="desbma",
packages=find_packages(),
entry_points={"console_scripts": ["sacad = sacad:cl_main"]},
package_data={"": ["LICENSE", "README.md", "requirements.txt"]},
test_suite="tests",
install_requires=requirements,
description="Search and download music album covers",
url="https://github.com/desbma/sacad",
download_url="https://github.com/desbma/sacad/archive/%s.tar.gz" % (VERSION),
keywords=["dowload", "album", "cover", "art", "albumart", "music"],
classifiers=["Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Multimedia :: Graphics",
"Topic :: Utilities"])
|
Use alternate GitHub download URL
|
Use alternate GitHub download URL
|
Python
|
mpl-2.0
|
desbma/sacad,desbma/sacad
|
python
|
## Code Before:
from setuptools import find_packages, setup
VERSION = "1.0.0"
with open("requirements.txt", "rt") as f:
requirements= f.read().splitlines()
setup(name="sacad",
version=VERSION,
author="desbma",
packages=find_packages(),
entry_points={"console_scripts": ["sacad = sacad:cl_main"]},
package_data={"": ["LICENSE", "README.md", "requirements.txt"]},
test_suite="tests",
install_requires=requirements,
description="Search and download music album covers",
url="https://github.com/desbma/sacad",
download_url="https://github.com/desbma/sacad/tarball/%s" % (VERSION),
keywords=["dowload", "album", "cover", "art", "albumart", "music"],
classifiers=["Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Multimedia :: Graphics",
"Topic :: Utilities"])
## Instruction:
Use alternate GitHub download URL
## Code After:
from setuptools import find_packages, setup
VERSION = "1.0.0"
with open("requirements.txt", "rt") as f:
requirements= f.read().splitlines()
setup(name="sacad",
version=VERSION,
author="desbma",
packages=find_packages(),
entry_points={"console_scripts": ["sacad = sacad:cl_main"]},
package_data={"": ["LICENSE", "README.md", "requirements.txt"]},
test_suite="tests",
install_requires=requirements,
description="Search and download music album covers",
url="https://github.com/desbma/sacad",
download_url="https://github.com/desbma/sacad/archive/%s.tar.gz" % (VERSION),
keywords=["dowload", "album", "cover", "art", "albumart", "music"],
classifiers=["Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Multimedia :: Graphics",
"Topic :: Utilities"])
|
// ... existing code ...
install_requires=requirements,
description="Search and download music album covers",
url="https://github.com/desbma/sacad",
download_url="https://github.com/desbma/sacad/archive/%s.tar.gz" % (VERSION),
keywords=["dowload", "album", "cover", "art", "albumart", "music"],
classifiers=["Development Status :: 4 - Beta",
"Environment :: Console",
// ... rest of the code ...
|
b9ef100c4d101a7b35c6d1e71b438356580a61cb
|
com.codeaffine.eclipse.swt/src/com/codeaffine/eclipse/swt/widget/scrollable/HorizontalSelectionListener.java
|
com.codeaffine.eclipse.swt/src/com/codeaffine/eclipse/swt/widget/scrollable/HorizontalSelectionListener.java
|
package com.codeaffine.eclipse.swt.widget.scrollable;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import com.codeaffine.eclipse.swt.widget.scrollable.context.AdaptionContext;
import com.codeaffine.eclipse.swt.widget.scrollbar.FlatScrollBar;
class HorizontalSelectionListener extends SelectionAdapter {
private final AdaptionContext<?> context;
HorizontalSelectionListener( AdaptionContext<?> context ) {
this.context = context;
}
@Override
public void widgetSelected( SelectionEvent event ) {
updateLocation( new Point( -getSelection( event ), computeHeight() ) );
}
private int computeHeight() {
if( context.isScrollableReplacedByAdapter() ) {
return -context.getBorderWidth();
}
return context.getScrollable().getLocation().y - context.getBorderWidth();
}
private int getSelection( SelectionEvent event ) {
return ( ( FlatScrollBar )event.widget ).getSelection() + context.getBorderWidth();
}
private void updateLocation( final Point result ) {
context.getReconciliation().runWhileSuspended( new Runnable() {
@Override
public void run() {
context.getScrollable().setLocation( result );
}
} );
}
}
|
package com.codeaffine.eclipse.swt.widget.scrollable;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import com.codeaffine.eclipse.swt.widget.scrollable.context.AdaptionContext;
import com.codeaffine.eclipse.swt.widget.scrollbar.FlatScrollBar;
class HorizontalSelectionListener extends SelectionAdapter {
private final AdaptionContext<?> context;
HorizontalSelectionListener( AdaptionContext<?> context ) {
this.context = context;
}
@Override
public void widgetSelected( SelectionEvent event ) {
updateLocation( new Point( -getSelection( event ), computeHeight() ) );
}
private int computeHeight() {
if( context.isScrollableReplacedByAdapter() ) {
return -context.getBorderWidth();
}
return context.getScrollable().getLocation().y - context.getBorderWidth();
}
private int getSelection( SelectionEvent event ) {
return ( ( FlatScrollBar )event.widget ).getSelection() + context.getBorderWidth();
}
private void updateLocation( final Point result ) {
context.getReconciliation().runWhileSuspended( () -> context.getScrollable().setLocation( result ) );
}
}
|
Replace anonymous Runnable with lambda expression
|
Replace anonymous Runnable with lambda expression
|
Java
|
epl-1.0
|
jbuchberger/xiliary,jbuchberger/xiliary,fappel/xiliary,fappel/xiliary,jbuchberger/xiliary,fappel/xiliary,fappel/xiliary,jbuchberger/xiliary
|
java
|
## Code Before:
package com.codeaffine.eclipse.swt.widget.scrollable;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import com.codeaffine.eclipse.swt.widget.scrollable.context.AdaptionContext;
import com.codeaffine.eclipse.swt.widget.scrollbar.FlatScrollBar;
class HorizontalSelectionListener extends SelectionAdapter {
private final AdaptionContext<?> context;
HorizontalSelectionListener( AdaptionContext<?> context ) {
this.context = context;
}
@Override
public void widgetSelected( SelectionEvent event ) {
updateLocation( new Point( -getSelection( event ), computeHeight() ) );
}
private int computeHeight() {
if( context.isScrollableReplacedByAdapter() ) {
return -context.getBorderWidth();
}
return context.getScrollable().getLocation().y - context.getBorderWidth();
}
private int getSelection( SelectionEvent event ) {
return ( ( FlatScrollBar )event.widget ).getSelection() + context.getBorderWidth();
}
private void updateLocation( final Point result ) {
context.getReconciliation().runWhileSuspended( new Runnable() {
@Override
public void run() {
context.getScrollable().setLocation( result );
}
} );
}
}
## Instruction:
Replace anonymous Runnable with lambda expression
## Code After:
package com.codeaffine.eclipse.swt.widget.scrollable;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import com.codeaffine.eclipse.swt.widget.scrollable.context.AdaptionContext;
import com.codeaffine.eclipse.swt.widget.scrollbar.FlatScrollBar;
class HorizontalSelectionListener extends SelectionAdapter {
private final AdaptionContext<?> context;
HorizontalSelectionListener( AdaptionContext<?> context ) {
this.context = context;
}
@Override
public void widgetSelected( SelectionEvent event ) {
updateLocation( new Point( -getSelection( event ), computeHeight() ) );
}
private int computeHeight() {
if( context.isScrollableReplacedByAdapter() ) {
return -context.getBorderWidth();
}
return context.getScrollable().getLocation().y - context.getBorderWidth();
}
private int getSelection( SelectionEvent event ) {
return ( ( FlatScrollBar )event.widget ).getSelection() + context.getBorderWidth();
}
private void updateLocation( final Point result ) {
context.getReconciliation().runWhileSuspended( () -> context.getScrollable().setLocation( result ) );
}
}
|
# ... existing code ...
}
private void updateLocation( final Point result ) {
context.getReconciliation().runWhileSuspended( () -> context.getScrollable().setLocation( result ) );
}
}
# ... rest of the code ...
|
c5aa1c7ee17313e3abe156c2bfa429f124a451d5
|
bc125csv/__init__.py
|
bc125csv/__init__.py
|
__author__ = "Folkert de Vries"
__email__ = "[email protected]"
__version__ = "1.0.0"
__date__ = "Aug 02, 2015"
# Expose main function for setup.py console_scripts
from bc125csv.handler import main
|
__author__ = "Folkert de Vries"
__email__ = "[email protected]"
__version__ = "1.0.0"
__date__ = "Aug 02, 2015"
# Expose main function for setup.py console_scripts
from bc125csv.handler import main
if __name__ == "__main__":
main()
|
Call main when run directly
|
Call main when run directly
|
Python
|
mit
|
fdev/bc125csv
|
python
|
## Code Before:
__author__ = "Folkert de Vries"
__email__ = "[email protected]"
__version__ = "1.0.0"
__date__ = "Aug 02, 2015"
# Expose main function for setup.py console_scripts
from bc125csv.handler import main
## Instruction:
Call main when run directly
## Code After:
__author__ = "Folkert de Vries"
__email__ = "[email protected]"
__version__ = "1.0.0"
__date__ = "Aug 02, 2015"
# Expose main function for setup.py console_scripts
from bc125csv.handler import main
if __name__ == "__main__":
main()
|
...
# Expose main function for setup.py console_scripts
from bc125csv.handler import main
if __name__ == "__main__":
main()
...
|
84e964eba11e344f6f0ec612b5743e693a8825bd
|
thoonk/config.py
|
thoonk/config.py
|
import json
import threading
import uuid
from thoonk.consts import *
class ConfigCache(object):
def __init__(self, pubsub):
self._feeds = {}
self.pubsub = pubsub
self.lock = threading.Lock()
self.instance = uuid.uuid4().hex
def __getitem__(self, feed):
with self.lock:
if feed in self._feeds:
return self._feeds[feed]
else:
if not self.pubsub.feed_exists(feed):
raise FeedDoesNotExist
config = json.loads(self.pubsub.redis.get(FEEDCONFIG % feed))
self._feeds[feed] = self.pubsub.feedtypes[config.get(u'type', u'feed')](self.pubsub, feed, config)
return self._feeds[feed]
def invalidate(self, feed, instance, delete=False):
if instance != self.instance:
with self.lock:
if feed in self._feeds:
if delete:
del self._feeds[feed]
else:
del self._feeds[feed].config
|
import json
import threading
import uuid
class ConfigCache(object):
"""
The ConfigCache class stores an in-memory version of each
feed's configuration. As there may be multiple systems using
Thoonk with the same Redis server, and each with its own
ConfigCache instance, each ConfigCache has a self.instance
field to uniquely identify itself.
Attributes:
thoonk -- The main Thoonk object.
instance -- A hex string for uniquely identifying this
ConfigCache instance.
Methods:
invalidate -- Force a feed's config to be retrieved from
Redis instead of in-memory.
"""
def __init__(self, thoonk):
"""
Create a new configuration cache.
Arguments:
thoonk -- The main Thoonk object.
"""
self._feeds = {}
self.thoonk = thoonk
self.lock = threading.Lock()
self.instance = uuid.uuid4().hex
def __getitem__(self, feed):
"""
Return a feed object for a given feed name.
Arguments:
feed -- The name of the requested feed.
"""
with self.lock:
if feed in self._feeds:
return self._feeds[feed]
else:
if not self.thoonk.feed_exists(feed):
raise FeedDoesNotExist
config = self.thoonk.redis.get('feed.config:%s' % feed)
config = json.loads(config)
feed_type = config.get(u'type', u'feed')
feed_class = self.thoonk.feedtypes[feed_type]
self._feeds[feed] = feed_class(self.thoonk, feed, config)
return self._feeds[feed]
def invalidate(self, feed, instance, delete=False):
"""
Delete a configuration so that it will be retrieved from Redis
instead of from the cache.
Arguments:
feed -- The name of the feed to invalidate.
instance -- A UUID identifying the cache which made the
invalidation request.
delete -- Indicates if the entire feed object should be
invalidated, or just its configuration.
"""
if instance != self.instance:
with self.lock:
if feed in self._feeds:
if delete:
del self._feeds[feed]
else:
del self._feeds[feed].config
|
Add docs to the ConfigCache.
|
Add docs to the ConfigCache.
|
Python
|
mit
|
andyet/thoonk.py,fritzy/thoonk.py
|
python
|
## Code Before:
import json
import threading
import uuid
from thoonk.consts import *
class ConfigCache(object):
def __init__(self, pubsub):
self._feeds = {}
self.pubsub = pubsub
self.lock = threading.Lock()
self.instance = uuid.uuid4().hex
def __getitem__(self, feed):
with self.lock:
if feed in self._feeds:
return self._feeds[feed]
else:
if not self.pubsub.feed_exists(feed):
raise FeedDoesNotExist
config = json.loads(self.pubsub.redis.get(FEEDCONFIG % feed))
self._feeds[feed] = self.pubsub.feedtypes[config.get(u'type', u'feed')](self.pubsub, feed, config)
return self._feeds[feed]
def invalidate(self, feed, instance, delete=False):
if instance != self.instance:
with self.lock:
if feed in self._feeds:
if delete:
del self._feeds[feed]
else:
del self._feeds[feed].config
## Instruction:
Add docs to the ConfigCache.
## Code After:
import json
import threading
import uuid
class ConfigCache(object):
"""
The ConfigCache class stores an in-memory version of each
feed's configuration. As there may be multiple systems using
Thoonk with the same Redis server, and each with its own
ConfigCache instance, each ConfigCache has a self.instance
field to uniquely identify itself.
Attributes:
thoonk -- The main Thoonk object.
instance -- A hex string for uniquely identifying this
ConfigCache instance.
Methods:
invalidate -- Force a feed's config to be retrieved from
Redis instead of in-memory.
"""
def __init__(self, thoonk):
"""
Create a new configuration cache.
Arguments:
thoonk -- The main Thoonk object.
"""
self._feeds = {}
self.thoonk = thoonk
self.lock = threading.Lock()
self.instance = uuid.uuid4().hex
def __getitem__(self, feed):
"""
Return a feed object for a given feed name.
Arguments:
feed -- The name of the requested feed.
"""
with self.lock:
if feed in self._feeds:
return self._feeds[feed]
else:
if not self.thoonk.feed_exists(feed):
raise FeedDoesNotExist
config = self.thoonk.redis.get('feed.config:%s' % feed)
config = json.loads(config)
feed_type = config.get(u'type', u'feed')
feed_class = self.thoonk.feedtypes[feed_type]
self._feeds[feed] = feed_class(self.thoonk, feed, config)
return self._feeds[feed]
def invalidate(self, feed, instance, delete=False):
"""
Delete a configuration so that it will be retrieved from Redis
instead of from the cache.
Arguments:
feed -- The name of the feed to invalidate.
instance -- A UUID identifying the cache which made the
invalidation request.
delete -- Indicates if the entire feed object should be
invalidated, or just its configuration.
"""
if instance != self.instance:
with self.lock:
if feed in self._feeds:
if delete:
del self._feeds[feed]
else:
del self._feeds[feed].config
|
// ... existing code ...
import threading
import uuid
class ConfigCache(object):
"""
The ConfigCache class stores an in-memory version of each
feed's configuration. As there may be multiple systems using
Thoonk with the same Redis server, and each with its own
ConfigCache instance, each ConfigCache has a self.instance
field to uniquely identify itself.
Attributes:
thoonk -- The main Thoonk object.
instance -- A hex string for uniquely identifying this
ConfigCache instance.
Methods:
invalidate -- Force a feed's config to be retrieved from
Redis instead of in-memory.
"""
def __init__(self, thoonk):
"""
Create a new configuration cache.
Arguments:
thoonk -- The main Thoonk object.
"""
self._feeds = {}
self.thoonk = thoonk
self.lock = threading.Lock()
self.instance = uuid.uuid4().hex
def __getitem__(self, feed):
"""
Return a feed object for a given feed name.
Arguments:
feed -- The name of the requested feed.
"""
with self.lock:
if feed in self._feeds:
return self._feeds[feed]
else:
if not self.thoonk.feed_exists(feed):
raise FeedDoesNotExist
config = self.thoonk.redis.get('feed.config:%s' % feed)
config = json.loads(config)
feed_type = config.get(u'type', u'feed')
feed_class = self.thoonk.feedtypes[feed_type]
self._feeds[feed] = feed_class(self.thoonk, feed, config)
return self._feeds[feed]
def invalidate(self, feed, instance, delete=False):
"""
Delete a configuration so that it will be retrieved from Redis
instead of from the cache.
Arguments:
feed -- The name of the feed to invalidate.
instance -- A UUID identifying the cache which made the
invalidation request.
delete -- Indicates if the entire feed object should be
invalidated, or just its configuration.
"""
if instance != self.instance:
with self.lock:
if feed in self._feeds:
// ... rest of the code ...
|
7a02c1174d819be374c24fd8b406ff3d66c9bbab
|
src/util.h
|
src/util.h
|
/*** Utility functions ***/
#define ALLOC(type) ALLOC_N(type, 1)
#define ALLOC_N(type, n) ((type*) xmalloc(sizeof(type) * (n)))
void *xmalloc(size_t);
char *hextoa(const char *, int);
#define STARTS_WITH(x, y) (strncmp((x), (y), strlen(y)) == 0)
#endif /* UTIL_H */
|
/*** Utility functions ***/
#define ALLOC(type) ALLOC_N(type, 1)
#define ALLOC_N(type, n) ((type*) xmalloc(sizeof(type) * (n)))
#define MEMCPY(dst, src, type) MEMCPY_N(dst, src, type, 1)
#define MEMCPY_N(dst, src, type, n) (memcpy((dst), (src), sizeof(type) * (n)))
void *xmalloc(size_t);
char *hextoa(const char *, int);
#define STARTS_WITH(x, y) (strncmp((x), (y), strlen(y)) == 0)
#endif /* UTIL_H */
|
Add MEMCPY and MEMCPY_N macros
|
Add MEMCPY and MEMCPY_N macros
|
C
|
apache-2.0
|
mopidy/libmockspotify,mopidy/libmockspotify,mopidy/libmockspotify
|
c
|
## Code Before:
/*** Utility functions ***/
#define ALLOC(type) ALLOC_N(type, 1)
#define ALLOC_N(type, n) ((type*) xmalloc(sizeof(type) * (n)))
void *xmalloc(size_t);
char *hextoa(const char *, int);
#define STARTS_WITH(x, y) (strncmp((x), (y), strlen(y)) == 0)
#endif /* UTIL_H */
## Instruction:
Add MEMCPY and MEMCPY_N macros
## Code After:
/*** Utility functions ***/
#define ALLOC(type) ALLOC_N(type, 1)
#define ALLOC_N(type, n) ((type*) xmalloc(sizeof(type) * (n)))
#define MEMCPY(dst, src, type) MEMCPY_N(dst, src, type, 1)
#define MEMCPY_N(dst, src, type, n) (memcpy((dst), (src), sizeof(type) * (n)))
void *xmalloc(size_t);
char *hextoa(const char *, int);
#define STARTS_WITH(x, y) (strncmp((x), (y), strlen(y)) == 0)
#endif /* UTIL_H */
|
...
#define ALLOC(type) ALLOC_N(type, 1)
#define ALLOC_N(type, n) ((type*) xmalloc(sizeof(type) * (n)))
#define MEMCPY(dst, src, type) MEMCPY_N(dst, src, type, 1)
#define MEMCPY_N(dst, src, type, n) (memcpy((dst), (src), sizeof(type) * (n)))
void *xmalloc(size_t);
char *hextoa(const char *, int);
...
|
e547e45c7c45b8960c78ff9ccde2e9ebf51550e0
|
Android/Sample/app/src/main/java/net/wequick/example/small/Application.java
|
Android/Sample/app/src/main/java/net/wequick/example/small/Application.java
|
package net.wequick.example.small;
import net.wequick.small.Small;
/**
* Created by galen on 15/11/3.
*/
public class Application extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
Small.setBaseUri("http://m.wequick.net/demo/");
}
}
|
package net.wequick.example.small;
import net.wequick.small.Small;
/**
* Created by galen on 15/11/3.
*/
public class Application extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
// Options
Small.setBaseUri("http://m.wequick.net/demo/");
// Required
Small.preSetUp(this);
}
}
|
Add Small.preSetUp to sample application
|
Add Small.preSetUp to sample application
|
Java
|
apache-2.0
|
wequick/Small,sailor1861/small_debug,zhaoya188/Small,zhaoya188/Small,zhaoya188/Small,wequick/Small,wequick/Small,zhaoya188/Small,sailor1861/small_debug,wequick/Small,wequick/Small,sailor1861/small_debug,wu4321/Small,wu4321/Small,sailor1861/small_debug,wu4321/Small,wu4321/Small
|
java
|
## Code Before:
package net.wequick.example.small;
import net.wequick.small.Small;
/**
* Created by galen on 15/11/3.
*/
public class Application extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
Small.setBaseUri("http://m.wequick.net/demo/");
}
}
## Instruction:
Add Small.preSetUp to sample application
## Code After:
package net.wequick.example.small;
import net.wequick.small.Small;
/**
* Created by galen on 15/11/3.
*/
public class Application extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
// Options
Small.setBaseUri("http://m.wequick.net/demo/");
// Required
Small.preSetUp(this);
}
}
|
...
@Override
public void onCreate() {
super.onCreate();
// Options
Small.setBaseUri("http://m.wequick.net/demo/");
// Required
Small.preSetUp(this);
}
}
...
|
1b726978e1604269c8c4d2728a6f7ce774e5d16d
|
src/ggrc/models/control_assessment.py
|
src/ggrc/models/control_assessment.py
|
from ggrc import db
from .mixins import (
deferred, BusinessObject, Timeboxed, CustomAttributable, TestPlanned
)
from .object_document import Documentable
from .object_owner import Ownable
from .object_person import Personable
from .relationship import Relatable
from .track_object_state import HasObjectState, track_state_for_class
from ggrc.models.reflection import PublishOnly
class ControlAssessment(HasObjectState, TestPlanned, CustomAttributable,
Documentable, Personable, Timeboxed, Ownable,
Relatable, BusinessObject, db.Model):
__tablename__ = 'control_assessments'
design = deferred(db.Column(db.String), 'ControlAssessment')
operationally = deferred(db.Column(db.String), 'ControlAssessment')
control_id = db.Column(db.Integer, db.ForeignKey('controls.id'))
control = db.relationship('Control', foreign_keys=[control_id])
# REST properties
_publish_attrs = [
'design',
'operationally',
'control'
]
track_state_for_class(ControlAssessment)
|
from ggrc import db
from .mixins import (
deferred, BusinessObject, Timeboxed, CustomAttributable, TestPlanned
)
from .object_document import Documentable
from .object_owner import Ownable
from .object_person import Personable
from .relationship import Relatable
from .track_object_state import HasObjectState, track_state_for_class
from ggrc.models.reflection import PublishOnly
class ControlAssessment(HasObjectState, TestPlanned, CustomAttributable,
Documentable, Personable, Timeboxed, Ownable,
Relatable, BusinessObject, db.Model):
__tablename__ = 'control_assessments'
design = deferred(db.Column(db.String), 'ControlAssessment')
operationally = deferred(db.Column(db.String), 'ControlAssessment')
control_id = db.Column(db.Integer, db.ForeignKey('controls.id'))
control = db.relationship('Control', foreign_keys=[control_id])
audit = {} # we add this for the sake of client side error checking
# REST properties
_publish_attrs = [
'design',
'operationally',
'control',
PublishOnly('audit')
]
track_state_for_class(ControlAssessment)
|
Fix edit control assessment modal
|
Fix edit control assessment modal
This works, because our client side verification checks only if the
audit attr exists.
ref: core-1643
|
Python
|
apache-2.0
|
kr41/ggrc-core,kr41/ggrc-core,vladan-m/ggrc-core,vladan-m/ggrc-core,vladan-m/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,VinnieJohns/ggrc-core,prasannav7/ggrc-core,andrei-karalionak/ggrc-core,andrei-karalionak/ggrc-core,jmakov/ggrc-core,AleksNeStu/ggrc-core,uskudnik/ggrc-core,uskudnik/ggrc-core,selahssea/ggrc-core,hasanalom/ggrc-core,j0gurt/ggrc-core,NejcZupec/ggrc-core,AleksNeStu/ggrc-core,prasannav7/ggrc-core,hyperNURb/ggrc-core,kr41/ggrc-core,AleksNeStu/ggrc-core,uskudnik/ggrc-core,uskudnik/ggrc-core,hasanalom/ggrc-core,hyperNURb/ggrc-core,prasannav7/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,josthkko/ggrc-core,NejcZupec/ggrc-core,uskudnik/ggrc-core,edofic/ggrc-core,josthkko/ggrc-core,j0gurt/ggrc-core,plamut/ggrc-core,josthkko/ggrc-core,jmakov/ggrc-core,hasanalom/ggrc-core,andrei-karalionak/ggrc-core,vladan-m/ggrc-core,j0gurt/ggrc-core,plamut/ggrc-core,VinnieJohns/ggrc-core,edofic/ggrc-core,VinnieJohns/ggrc-core,j0gurt/ggrc-core,plamut/ggrc-core,jmakov/ggrc-core,edofic/ggrc-core,hasanalom/ggrc-core,kr41/ggrc-core,prasannav7/ggrc-core,vladan-m/ggrc-core,hasanalom/ggrc-core,andrei-karalionak/ggrc-core,edofic/ggrc-core,selahssea/ggrc-core,hyperNURb/ggrc-core,hyperNURb/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,jmakov/ggrc-core,hyperNURb/ggrc-core,NejcZupec/ggrc-core,NejcZupec/ggrc-core,jmakov/ggrc-core
|
python
|
## Code Before:
from ggrc import db
from .mixins import (
deferred, BusinessObject, Timeboxed, CustomAttributable, TestPlanned
)
from .object_document import Documentable
from .object_owner import Ownable
from .object_person import Personable
from .relationship import Relatable
from .track_object_state import HasObjectState, track_state_for_class
from ggrc.models.reflection import PublishOnly
class ControlAssessment(HasObjectState, TestPlanned, CustomAttributable,
Documentable, Personable, Timeboxed, Ownable,
Relatable, BusinessObject, db.Model):
__tablename__ = 'control_assessments'
design = deferred(db.Column(db.String), 'ControlAssessment')
operationally = deferred(db.Column(db.String), 'ControlAssessment')
control_id = db.Column(db.Integer, db.ForeignKey('controls.id'))
control = db.relationship('Control', foreign_keys=[control_id])
# REST properties
_publish_attrs = [
'design',
'operationally',
'control'
]
track_state_for_class(ControlAssessment)
## Instruction:
Fix edit control assessment modal
This works, because our client side verification checks only if the
audit attr exists.
ref: core-1643
## Code After:
from ggrc import db
from .mixins import (
deferred, BusinessObject, Timeboxed, CustomAttributable, TestPlanned
)
from .object_document import Documentable
from .object_owner import Ownable
from .object_person import Personable
from .relationship import Relatable
from .track_object_state import HasObjectState, track_state_for_class
from ggrc.models.reflection import PublishOnly
class ControlAssessment(HasObjectState, TestPlanned, CustomAttributable,
Documentable, Personable, Timeboxed, Ownable,
Relatable, BusinessObject, db.Model):
__tablename__ = 'control_assessments'
design = deferred(db.Column(db.String), 'ControlAssessment')
operationally = deferred(db.Column(db.String), 'ControlAssessment')
control_id = db.Column(db.Integer, db.ForeignKey('controls.id'))
control = db.relationship('Control', foreign_keys=[control_id])
audit = {} # we add this for the sake of client side error checking
# REST properties
_publish_attrs = [
'design',
'operationally',
'control',
PublishOnly('audit')
]
track_state_for_class(ControlAssessment)
|
# ... existing code ...
control_id = db.Column(db.Integer, db.ForeignKey('controls.id'))
control = db.relationship('Control', foreign_keys=[control_id])
audit = {} # we add this for the sake of client side error checking
# REST properties
_publish_attrs = [
'design',
'operationally',
'control',
PublishOnly('audit')
]
track_state_for_class(ControlAssessment)
# ... rest of the code ...
|
54bce2a224843ec9c1c8b7eb35cdc6bf19d5726b
|
expensonator/api.py
|
expensonator/api.py
|
from tastypie.authorization import Authorization
from tastypie.fields import CharField
from tastypie.resources import ModelResource
from expensonator.models import Expense
class ExpenseResource(ModelResource):
tags = CharField()
def dehydrate_tags(self, bundle):
return bundle.obj.tags_as_string()
def save(self, bundle, skip_errors=False):
bundle = super(ExpenseResource, self).save(bundle, skip_errors)
bundle.obj.reset_tags_from_string(bundle.data["tags"])
return bundle
class Meta:
queryset = Expense.objects.all()
excludes = ["created", "updated"]
# WARNING: Tastypie docs say that this is VERY INSECURE!
# For development only!
authorization = Authorization()
|
from tastypie.authorization import Authorization
from tastypie.fields import CharField
from tastypie.resources import ModelResource
from expensonator.models import Expense
class ExpenseResource(ModelResource):
tags = CharField()
def dehydrate_tags(self, bundle):
return bundle.obj.tags_as_string()
def save(self, bundle, skip_errors=False):
bundle = super(ExpenseResource, self).save(bundle, skip_errors)
if "tags" in bundle.data:
bundle.obj.reset_tags_from_string(bundle.data["tags"])
return bundle
class Meta:
queryset = Expense.objects.all()
excludes = ["created", "updated"]
# WARNING: Tastypie docs say that this is VERY INSECURE!
# For development only!
authorization = Authorization()
|
Fix key error when no tags are specified
|
Fix key error when no tags are specified
|
Python
|
mit
|
matt-haigh/expensonator
|
python
|
## Code Before:
from tastypie.authorization import Authorization
from tastypie.fields import CharField
from tastypie.resources import ModelResource
from expensonator.models import Expense
class ExpenseResource(ModelResource):
tags = CharField()
def dehydrate_tags(self, bundle):
return bundle.obj.tags_as_string()
def save(self, bundle, skip_errors=False):
bundle = super(ExpenseResource, self).save(bundle, skip_errors)
bundle.obj.reset_tags_from_string(bundle.data["tags"])
return bundle
class Meta:
queryset = Expense.objects.all()
excludes = ["created", "updated"]
# WARNING: Tastypie docs say that this is VERY INSECURE!
# For development only!
authorization = Authorization()
## Instruction:
Fix key error when no tags are specified
## Code After:
from tastypie.authorization import Authorization
from tastypie.fields import CharField
from tastypie.resources import ModelResource
from expensonator.models import Expense
class ExpenseResource(ModelResource):
tags = CharField()
def dehydrate_tags(self, bundle):
return bundle.obj.tags_as_string()
def save(self, bundle, skip_errors=False):
bundle = super(ExpenseResource, self).save(bundle, skip_errors)
if "tags" in bundle.data:
bundle.obj.reset_tags_from_string(bundle.data["tags"])
return bundle
class Meta:
queryset = Expense.objects.all()
excludes = ["created", "updated"]
# WARNING: Tastypie docs say that this is VERY INSECURE!
# For development only!
authorization = Authorization()
|
...
def save(self, bundle, skip_errors=False):
bundle = super(ExpenseResource, self).save(bundle, skip_errors)
if "tags" in bundle.data:
bundle.obj.reset_tags_from_string(bundle.data["tags"])
return bundle
class Meta:
...
|
fce96b88bf1183c7806835bb77e32551c17413ff
|
algorithms/insertion-sort/InsertionSort.java
|
algorithms/insertion-sort/InsertionSort.java
|
public class InsertionSort {
public static int[] sort(int[] array) {
for (int i = 1; i < array.length; i++) {
int item = array[i];
int indexHole = i;
while (indexHole > 0 && array[indexHole - 1] > item) {
array[indexHole] = array[--indexHole];
}
array[indexHole] = item;
}
return array;
}
}
|
public class InsertionSort {
public static void sort(int[] array) {
for (int i = 1; i < array.length; i++) {
int item = array[i];
int indexHole = i;
while (indexHole > 0 && array[indexHole - 1] > item) {
array[indexHole] = array[--indexHole];
}
array[indexHole] = item;
}
}
}
|
Fix return type of insertion sort
|
Fix return type of insertion sort
|
Java
|
mit
|
Tyriar/growing-with-the-web,gwtw/growing-with-the-web,Tyriar/growing-with-the-web,gwtw/growing-with-the-web
|
java
|
## Code Before:
public class InsertionSort {
public static int[] sort(int[] array) {
for (int i = 1; i < array.length; i++) {
int item = array[i];
int indexHole = i;
while (indexHole > 0 && array[indexHole - 1] > item) {
array[indexHole] = array[--indexHole];
}
array[indexHole] = item;
}
return array;
}
}
## Instruction:
Fix return type of insertion sort
## Code After:
public class InsertionSort {
public static void sort(int[] array) {
for (int i = 1; i < array.length; i++) {
int item = array[i];
int indexHole = i;
while (indexHole > 0 && array[indexHole - 1] > item) {
array[indexHole] = array[--indexHole];
}
array[indexHole] = item;
}
}
}
|
// ... existing code ...
public class InsertionSort {
public static void sort(int[] array) {
for (int i = 1; i < array.length; i++) {
int item = array[i];
int indexHole = i;
// ... modified code ...
}
array[indexHole] = item;
}
}
}
// ... rest of the code ...
|
31b69d9810fb694be005e21d9c1fc80574460d97
|
promgen/tests/test_rules.py
|
promgen/tests/test_rules.py
|
from unittest import mock
from django.test import TestCase
from promgen import models, prometheus
_RULES = '''
# Service: Service 1
# Service URL: /service/1/
ALERT RuleName
IF up==0
FOR 1s
LABELS {severity="severe"}
ANNOTATIONS {service="http://example.com/service/1/", summary="Test case"}
'''.lstrip()
class RuleTest(TestCase):
@mock.patch('django.db.models.signals.post_save', mock.Mock())
def setUp(self):
self.shard = models.Shard.objects.create(name='Shard 1')
self.service = models.Service.objects.create(id=1, name='Service 1', shard=self.shard)
self.rule = models.Rule.objects.create(
name='RuleName',
clause='up==0',
duration='1s',
service=self.service
)
models.RuleLabel.objects.create(name='severity', value='severe', rule=self.rule)
models.RuleAnnotation.objects.create(name='summary', value='Test case', rule=self.rule)
@mock.patch('django.db.models.signals.post_save')
def test_write(self, mock_render):
result = prometheus.render_rules()
self.assertEqual(result, _RULES)
|
from unittest import mock
from django.test import TestCase
from promgen import models, prometheus
_RULES = '''
# Service: Service 1
# Service URL: /service/1/
ALERT RuleName
IF up==0
FOR 1s
LABELS {severity="severe"}
ANNOTATIONS {service="http://example.com/service/1/", summary="Test case"}
'''.lstrip()
class RuleTest(TestCase):
@mock.patch('django.db.models.signals.post_save', mock.Mock())
def setUp(self):
self.shard = models.Shard.objects.create(name='Shard 1')
self.service = models.Service.objects.create(id=1, name='Service 1', shard=self.shard)
self.rule = models.Rule.objects.create(
name='RuleName',
clause='up==0',
duration='1s',
service=self.service
)
models.RuleLabel.objects.create(name='severity', value='severe', rule=self.rule)
models.RuleAnnotation.objects.create(name='summary', value='Test case', rule=self.rule)
@mock.patch('django.db.models.signals.post_save')
def test_write(self, mock_render):
result = prometheus.render_rules()
self.assertEqual(result, _RULES)
@mock.patch('django.db.models.signals.post_save')
def test_copy(self, mock_render):
service = models.Service.objects.create(name='Service 2', shard=self.shard)
copy = self.rule.copy_to(service)
self.assertIn('severity', copy.labels())
self.assertIn('summary', copy.annotations())
|
Add test for copying rules with their labels and annotations
|
Add test for copying rules with their labels and annotations
|
Python
|
mit
|
kfdm/promgen,kfdm/promgen,kfdm/promgen,kfdm/promgen
|
python
|
## Code Before:
from unittest import mock
from django.test import TestCase
from promgen import models, prometheus
_RULES = '''
# Service: Service 1
# Service URL: /service/1/
ALERT RuleName
IF up==0
FOR 1s
LABELS {severity="severe"}
ANNOTATIONS {service="http://example.com/service/1/", summary="Test case"}
'''.lstrip()
class RuleTest(TestCase):
@mock.patch('django.db.models.signals.post_save', mock.Mock())
def setUp(self):
self.shard = models.Shard.objects.create(name='Shard 1')
self.service = models.Service.objects.create(id=1, name='Service 1', shard=self.shard)
self.rule = models.Rule.objects.create(
name='RuleName',
clause='up==0',
duration='1s',
service=self.service
)
models.RuleLabel.objects.create(name='severity', value='severe', rule=self.rule)
models.RuleAnnotation.objects.create(name='summary', value='Test case', rule=self.rule)
@mock.patch('django.db.models.signals.post_save')
def test_write(self, mock_render):
result = prometheus.render_rules()
self.assertEqual(result, _RULES)
## Instruction:
Add test for copying rules with their labels and annotations
## Code After:
from unittest import mock
from django.test import TestCase
from promgen import models, prometheus
_RULES = '''
# Service: Service 1
# Service URL: /service/1/
ALERT RuleName
IF up==0
FOR 1s
LABELS {severity="severe"}
ANNOTATIONS {service="http://example.com/service/1/", summary="Test case"}
'''.lstrip()
class RuleTest(TestCase):
@mock.patch('django.db.models.signals.post_save', mock.Mock())
def setUp(self):
self.shard = models.Shard.objects.create(name='Shard 1')
self.service = models.Service.objects.create(id=1, name='Service 1', shard=self.shard)
self.rule = models.Rule.objects.create(
name='RuleName',
clause='up==0',
duration='1s',
service=self.service
)
models.RuleLabel.objects.create(name='severity', value='severe', rule=self.rule)
models.RuleAnnotation.objects.create(name='summary', value='Test case', rule=self.rule)
@mock.patch('django.db.models.signals.post_save')
def test_write(self, mock_render):
result = prometheus.render_rules()
self.assertEqual(result, _RULES)
@mock.patch('django.db.models.signals.post_save')
def test_copy(self, mock_render):
service = models.Service.objects.create(name='Service 2', shard=self.shard)
copy = self.rule.copy_to(service)
self.assertIn('severity', copy.labels())
self.assertIn('summary', copy.annotations())
|
// ... existing code ...
def test_write(self, mock_render):
result = prometheus.render_rules()
self.assertEqual(result, _RULES)
@mock.patch('django.db.models.signals.post_save')
def test_copy(self, mock_render):
service = models.Service.objects.create(name='Service 2', shard=self.shard)
copy = self.rule.copy_to(service)
self.assertIn('severity', copy.labels())
self.assertIn('summary', copy.annotations())
// ... rest of the code ...
|
339942cb4715cbc46328abfc2244c50b15f72b89
|
com.codeaffine.extras.jdt.test/src/com/codeaffine/extras/jdt/internal/prefs/ExpressionEvaluatorTest.java
|
com.codeaffine.extras.jdt.test/src/com/codeaffine/extras/jdt/internal/prefs/ExpressionEvaluatorTest.java
|
package com.codeaffine.extras.jdt.internal.prefs;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.services.IEvaluationService;
import org.junit.Before;
import org.junit.Test;
public class ExpressionEvaluatorTest {
private IWorkbench workbench;
@Before
public void setUp() {
workbench = mock( IWorkbench.class );
}
@Test
public void testEvaluate() {
IEvaluationService evaluationService = mock( IEvaluationService.class );
when( workbench.getService( IEvaluationService.class ) ).thenReturn( evaluationService );
new ExpressionEvaluator( workbench ).evaluate();
verify( evaluationService ).requestEvaluation( PreferencePropertyTester.PROP_IS_TRUE );
}
@Test
public void testEvaluateWithNullworkbench() {
try {
new ExpressionEvaluator( null ).evaluate();
} catch( RuntimeException notExpected ) {
fail();
}
}
@Test
public void testEvaluateWithoutEvaluationService() {
new ExpressionEvaluator( workbench ).evaluate();
verify( workbench ).getService( IEvaluationService.class );
}
}
|
package com.codeaffine.extras.jdt.internal.prefs;
import static com.codeaffine.test.util.lang.ThrowableCaptor.thrownBy;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.services.IEvaluationService;
import org.junit.Before;
import org.junit.Test;
public class ExpressionEvaluatorTest {
private IWorkbench workbench;
@Before
public void setUp() {
workbench = mock( IWorkbench.class );
}
@Test
public void testEvaluate() {
IEvaluationService evaluationService = mock( IEvaluationService.class );
when( workbench.getService( IEvaluationService.class ) ).thenReturn( evaluationService );
new ExpressionEvaluator( workbench ).evaluate();
verify( evaluationService ).requestEvaluation( PreferencePropertyTester.PROP_IS_TRUE );
}
@Test
public void testEvaluateWithNullWorkbench() {
Throwable throwable = thrownBy( () -> new ExpressionEvaluator( null ).evaluate() );
assertThat( throwable ).isNull();
}
@Test
public void testEvaluateWithoutEvaluationService() {
new ExpressionEvaluator( workbench ).evaluate();
verify( workbench ).getService( IEvaluationService.class );
}
}
|
Rewrite test to use ThrowableCaptor
|
Rewrite test to use ThrowableCaptor
|
Java
|
epl-1.0
|
rherrmann/eclipse-extras,rherrmann/eclipse-extras
|
java
|
## Code Before:
package com.codeaffine.extras.jdt.internal.prefs;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.services.IEvaluationService;
import org.junit.Before;
import org.junit.Test;
public class ExpressionEvaluatorTest {
private IWorkbench workbench;
@Before
public void setUp() {
workbench = mock( IWorkbench.class );
}
@Test
public void testEvaluate() {
IEvaluationService evaluationService = mock( IEvaluationService.class );
when( workbench.getService( IEvaluationService.class ) ).thenReturn( evaluationService );
new ExpressionEvaluator( workbench ).evaluate();
verify( evaluationService ).requestEvaluation( PreferencePropertyTester.PROP_IS_TRUE );
}
@Test
public void testEvaluateWithNullworkbench() {
try {
new ExpressionEvaluator( null ).evaluate();
} catch( RuntimeException notExpected ) {
fail();
}
}
@Test
public void testEvaluateWithoutEvaluationService() {
new ExpressionEvaluator( workbench ).evaluate();
verify( workbench ).getService( IEvaluationService.class );
}
}
## Instruction:
Rewrite test to use ThrowableCaptor
## Code After:
package com.codeaffine.extras.jdt.internal.prefs;
import static com.codeaffine.test.util.lang.ThrowableCaptor.thrownBy;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.services.IEvaluationService;
import org.junit.Before;
import org.junit.Test;
public class ExpressionEvaluatorTest {
private IWorkbench workbench;
@Before
public void setUp() {
workbench = mock( IWorkbench.class );
}
@Test
public void testEvaluate() {
IEvaluationService evaluationService = mock( IEvaluationService.class );
when( workbench.getService( IEvaluationService.class ) ).thenReturn( evaluationService );
new ExpressionEvaluator( workbench ).evaluate();
verify( evaluationService ).requestEvaluation( PreferencePropertyTester.PROP_IS_TRUE );
}
@Test
public void testEvaluateWithNullWorkbench() {
Throwable throwable = thrownBy( () -> new ExpressionEvaluator( null ).evaluate() );
assertThat( throwable ).isNull();
}
@Test
public void testEvaluateWithoutEvaluationService() {
new ExpressionEvaluator( workbench ).evaluate();
verify( workbench ).getService( IEvaluationService.class );
}
}
|
// ... existing code ...
package com.codeaffine.extras.jdt.internal.prefs;
import static com.codeaffine.test.util.lang.ThrowableCaptor.thrownBy;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
// ... modified code ...
}
@Test
public void testEvaluateWithNullWorkbench() {
Throwable throwable = thrownBy( () -> new ExpressionEvaluator( null ).evaluate() );
assertThat( throwable ).isNull();
}
@Test
// ... rest of the code ...
|
2b803a4d6e2f425633eabf2a364ffd9972a1b3d0
|
src/Divider.h
|
src/Divider.h
|
class Divider {
public:
Divider(int interval = 1) {
setInterval(interval);
}
void setInterval(int interval) {
this->interval = interval;
clockCounter = interval - 1;
}
void tick() {
clockCounter++;
if (clockCounter == interval) {
clockCounter = 0;
}
}
bool hasClocked() {
return clockCounter == 0;
}
private:
int interval;
int clockCounter;
};
#endif
|
class Divider {
public:
Divider(int interval = 1) {
setInterval(interval);
reset();
}
void setInterval(int interval) {
if (interval < 1) {
resetValue = 0;
}
else {
resetValue = interval - 1;
}
}
void reset() {
clockCounter = resetValue;
}
void tick() {
if (clockCounter == 0) {
clockCounter = resetValue;
}
else {
--clockCounter;
}
}
bool hasClocked() {
return clockCounter == resetValue;
}
private:
int resetValue;
int clockCounter;
};
#endif
|
Rewrite divider to change interval without resetting it
|
Rewrite divider to change interval without resetting it
|
C
|
mit
|
scottjcrouch/ScootNES,scottjcrouch/ScootNES,scottjcrouch/ScootNES
|
c
|
## Code Before:
class Divider {
public:
Divider(int interval = 1) {
setInterval(interval);
}
void setInterval(int interval) {
this->interval = interval;
clockCounter = interval - 1;
}
void tick() {
clockCounter++;
if (clockCounter == interval) {
clockCounter = 0;
}
}
bool hasClocked() {
return clockCounter == 0;
}
private:
int interval;
int clockCounter;
};
#endif
## Instruction:
Rewrite divider to change interval without resetting it
## Code After:
class Divider {
public:
Divider(int interval = 1) {
setInterval(interval);
reset();
}
void setInterval(int interval) {
if (interval < 1) {
resetValue = 0;
}
else {
resetValue = interval - 1;
}
}
void reset() {
clockCounter = resetValue;
}
void tick() {
if (clockCounter == 0) {
clockCounter = resetValue;
}
else {
--clockCounter;
}
}
bool hasClocked() {
return clockCounter == resetValue;
}
private:
int resetValue;
int clockCounter;
};
#endif
|
// ... existing code ...
public:
Divider(int interval = 1) {
setInterval(interval);
reset();
}
void setInterval(int interval) {
if (interval < 1) {
resetValue = 0;
}
else {
resetValue = interval - 1;
}
}
void reset() {
clockCounter = resetValue;
}
void tick() {
if (clockCounter == 0) {
clockCounter = resetValue;
}
else {
--clockCounter;
}
}
bool hasClocked() {
return clockCounter == resetValue;
}
private:
int resetValue;
int clockCounter;
};
// ... rest of the code ...
|
50305f63fda1127530650e030f23e92e8a725b8a
|
cgi-bin/user_register.py
|
cgi-bin/user_register.py
|
from MySQLdb import Error
from util import connect_db, dump_response_and_exit
import cgi
import hashlib
import json
import re
import sys
print "Content-type:applicaion/json\r\n\r\n"
form = cgi.FieldStorage()
username = form.getvalue('username')
password = form.getvalue('password')
if username is None or password is None:
dump_response_and_exit(False, 'Missing field: username or password.')
if re.match(r"^[a-zA-Z0-9_.-]+$", username) is None:
dump_response_and_exit(False, 'Invalid username.')
if re.match(r'[A-Za-z0-9@#$%^&+=_.-]{6,}', password) is None:
dump_response_and_exit(False, 'Invalid password.')
try:
con = connect_db()
with con:
cur = con.cursor()
cur.execute("INSERT INTO User values (%s, %s)",
(username, hashlib.sha1(password).digest()))
con.commit()
dump_response_and_exit(True, 'Done.')
except Error, e:
if con:
con.rollback()
dump_response_and_exit(False, e[1])
finally:
con.close()
|
from MySQLdb import Error
from util import connect_db, dump_response_and_exit
import cgi
import hashlib
import json
import re
import sys
print "Content-type:applicaion/json\r\n\r\n"
form = cgi.FieldStorage()
username = form.getvalue('username')
password = form.getvalue('password')
if username is None or password is None:
dump_response_and_exit(False, 'Missing field: username or password.')
if re.match(r"^[a-zA-Z0-9_.-]+$", username) is None:
dump_response_and_exit(False, 'Invalid username.')
if re.match(r'[A-Za-z0-9@#$%^&+=_.-]{6,}', password) is None:
dump_response_and_exit(False, 'Invalid password.')
try:
con = connect_db()
with con:
cur = con.cursor()
cur.execute("INSERT INTO User(username, password) values (%s, %s)",
(username, hashlib.sha1(password).digest()))
con.commit()
dump_response_and_exit(True, 'Done.')
except Error, e:
if con:
con.rollback()
dump_response_and_exit(False, e[1])
finally:
con.close()
|
Fix bug when inserting user.
|
Fix bug when inserting user.
Scheme of table: User has changed.
|
Python
|
mit
|
zhchbin/Yagra,zhchbin/Yagra,zhchbin/Yagra
|
python
|
## Code Before:
from MySQLdb import Error
from util import connect_db, dump_response_and_exit
import cgi
import hashlib
import json
import re
import sys
print "Content-type:applicaion/json\r\n\r\n"
form = cgi.FieldStorage()
username = form.getvalue('username')
password = form.getvalue('password')
if username is None or password is None:
dump_response_and_exit(False, 'Missing field: username or password.')
if re.match(r"^[a-zA-Z0-9_.-]+$", username) is None:
dump_response_and_exit(False, 'Invalid username.')
if re.match(r'[A-Za-z0-9@#$%^&+=_.-]{6,}', password) is None:
dump_response_and_exit(False, 'Invalid password.')
try:
con = connect_db()
with con:
cur = con.cursor()
cur.execute("INSERT INTO User values (%s, %s)",
(username, hashlib.sha1(password).digest()))
con.commit()
dump_response_and_exit(True, 'Done.')
except Error, e:
if con:
con.rollback()
dump_response_and_exit(False, e[1])
finally:
con.close()
## Instruction:
Fix bug when inserting user.
Scheme of table: User has changed.
## Code After:
from MySQLdb import Error
from util import connect_db, dump_response_and_exit
import cgi
import hashlib
import json
import re
import sys
print "Content-type:applicaion/json\r\n\r\n"
form = cgi.FieldStorage()
username = form.getvalue('username')
password = form.getvalue('password')
if username is None or password is None:
dump_response_and_exit(False, 'Missing field: username or password.')
if re.match(r"^[a-zA-Z0-9_.-]+$", username) is None:
dump_response_and_exit(False, 'Invalid username.')
if re.match(r'[A-Za-z0-9@#$%^&+=_.-]{6,}', password) is None:
dump_response_and_exit(False, 'Invalid password.')
try:
con = connect_db()
with con:
cur = con.cursor()
cur.execute("INSERT INTO User(username, password) values (%s, %s)",
(username, hashlib.sha1(password).digest()))
con.commit()
dump_response_and_exit(True, 'Done.')
except Error, e:
if con:
con.rollback()
dump_response_and_exit(False, e[1])
finally:
con.close()
|
...
con = connect_db()
with con:
cur = con.cursor()
cur.execute("INSERT INTO User(username, password) values (%s, %s)",
(username, hashlib.sha1(password).digest()))
con.commit()
dump_response_and_exit(True, 'Done.')
...
|
c659079a6af6107c1b8ef25d70ed317532dc99f5
|
github-android/src/main/java/com/github/mobile/android/util/Html.java
|
github-android/src/main/java/com/github/mobile/android/util/Html.java
|
package com.github.mobile.android.util;
import android.text.Html.ImageGetter;
/**
* Html Utilities
*/
public class Html {
/**
* Encode HTML
*
* @param html
* @return html
*/
public static CharSequence encode(String html) {
return encode(html, null);
}
/**
* Encode HTML
*
* @param html
* @param imageGetter
* @return html
*/
public static CharSequence encode(String html, ImageGetter imageGetter) {
if (html == null)
return "";
if (html.length() == 0)
return html;
// These add extra padding that should be styled explicitly
if (html.startsWith("<p>") && html.endsWith("</p>"))
html = html.substring(3, html.length() - 4);
return android.text.Html.fromHtml(html, imageGetter, null);
}
}
|
package com.github.mobile.android.util;
import android.text.Html.ImageGetter;
/**
* Html Utilities
*/
public class Html {
/**
* Encode HTML
*
* @param html
* @return html
*/
public static CharSequence encode(String html) {
return encode(html, null);
}
/**
* Encode HTML
*
* @param html
* @param imageGetter
* @return html
*/
public static CharSequence encode(String html, ImageGetter imageGetter) {
if (html == null)
return "";
if (html.length() == 0)
return html;
// These add extra padding that should be styled explicitly
html = html.replace("<p>", "");
html = html.replace("</p>", "<br>");
while (html.length() > 0)
if (html.startsWith("<br>"))
html = html.substring(4);
else if (html.endsWith("<br>"))
html = html.substring(0, html.length() - 4);
else
break;
return android.text.Html.fromHtml(html, imageGetter, null);
}
}
|
Drop <p> tags and replace </p> with <br>
|
Drop <p> tags and replace </p> with <br>
This was causing an excessive amount of bottom padding
|
Java
|
apache-2.0
|
esironal/PocketHub,roadrunner1987/PocketHub,xiaoleigua/PocketHub,Liyue1314/PocketHub,xiaoleigua/PocketHub,Damonzh/PocketHub,acemaster/android,erpragatisingh/android-1,forkhubs/android,tempbottle/PocketHub,Leaking/android,micrologic/PocketHub,Calamus-Cajan/PocketHub,gvaish/PocketHub,yummy222/PocketHub,Calamus-Cajan/PocketHub,bineanzhou/android_github,yytang2012/PocketHub,ywk248248/Forkhub_cloned,yongjhih/PocketHub,rmad17/PocketHub,Tadakatsu/android,wubin28/android,Katariaa/PocketHub,pockethub/PocketHub,KingLiuDao/android,danielferecatu/android,funsociety/PocketHub,sudosurootdev/packages_apps_Github,Katariaa/PocketHub,PeterDaveHello/PocketHub,yuanhuihui/PocketHub,tempbottle/PocketHub,lzy-h2o2/PocketHub,zhuxiaohao/PocketHub,yummy222/PocketHub,jonan/ForkHub,mishin/ForkHub,jchenga/android,M13Kd/PocketHub,nvoron23/android,simple88/PocketHub,forkhubs/android,rmad17/PocketHub,kebenxiaoming/android-1,wshh08/PocketHub,njucsyyh/android,wang0818/android,roadrunner1987/PocketHub,soztzfsnf/PocketHub,ywk248248/Forkhub_cloned,weiyihz/PocketHub,theiven70/PocketHub,PKRoma/github-android,shekibobo/android,xfumihiro/PocketHub,generalzou/PocketHub,supercocoa/PocketHub,LeoLamCY/PocketHub,zhengxiaopeng/github-app,zhangtianqiu/githubandroid,samuelralak/ForkHub,songful/PocketHub,abhishekbm/android,kebenxiaoming/android-1,theiven70/PocketHub,funsociety/PocketHub,xfumihiro/ForkHub,Leaking/android,M13Kd/PocketHub,soztzfsnf/PocketHub,fadils/android,work4life/PocketHub,danielferecatu/android,work4life/PocketHub,yytang2012/PocketHub,chaoallsome/PocketHub,JosephYao/android,Cl3Kener/darkhub,micrologic/PocketHub,PKRoma/PocketHub,gvaish/PocketHub,repanda/PocketHub,funsociety/PocketHub,liqk2014/PocketHub,cnoldtree/PocketHub,sam14305/bhoot.life,wshh08/PocketHub,micrologic/PocketHub,xen0n/android,vfs1234/android,Damonzh/PocketHub,yongjhih/PocketHub,repanda/PocketHub,hufsm/PocketHub,generalzou/PocketHub,wang0818/android,Liyue1314/PocketHub,gmyboy/android,generalzou/PocketHub,PeterDaveHello/PocketHub,GeekHades/PocketHub,sam14305/bhoot.life,KishorAndroid/PocketHub,ywk248248/Forkhub_cloned,Meisolsson/PocketHub,njucsyyh/android,Calamus-Cajan/PocketHub,sydneyagcaoili/PocketHub,larsgrefer/pocket-hub,hgl888/PocketHub,Kevin16Wang/PocketHub,gmyboy/android,acemaster/android,Tadakatsu/android,mishin/ForkHub,work4life/PocketHub,fadils/android,erpragatisingh/android-1,esironal/PocketHub,jchenga/android,abhishekbm/android,M13Kd/PocketHub,PKRoma/PocketHub,larsgrefer/github-android-app,cnoldtree/PocketHub,sydneyagcaoili/PocketHub,common2015/PocketHub,hufsm/PocketHub,arcivanov/ForkHub,karllindmark/PocketHub,hgl888/PocketHub,tsdl2013/android,huangsongyan/PocketHub,KingLiuDao/android,xen0n/android,kostaskoukouvis/android,lzy-h2o2/PocketHub,condda/android,Kevin16Wang/PocketHub,marceloneil/PocketHub,marceloneil/PocketHub,PKRoma/PocketHub,zhangtianqiu/githubandroid,xfumihiro/PocketHub,hufsm/PocketHub,shekibobo/android,Androidbsw/android,DeLaSalleUniversity-Manila/forkhub-JJCpro10,zhuxiaohao/PocketHub,JosephYao/android,roadrunner1987/PocketHub,Meisolsson/PocketHub,xen0n/android,tsdl2013/android,wubin28/android,common2015/PocketHub,JLLK/PocketHub-scala,mishin/ForkHub,ISkyLove/PocketHub,supercocoa/PocketHub,usr80/Android,condda/android,reproio/github-for-android,GeekHades/PocketHub,JosephYao/android,pockethub/PocketHub,Tadakatsu/android,LeoLamCY/PocketHub,wubin28/android,Liyue1314/PocketHub,liqk2014/PocketHub,kebenxiaoming/android-1,Bloody-Badboy/PocketHub,xiaoleigua/PocketHub,Chalmers-SEP-GitHubApp-Group/android,pockethub/PocketHub,tempbottle/PocketHub,common2015/PocketHub,simple88/PocketHub,DeLaSalleUniversity-Manila/forkhub-JJCpro10,rmad17/PocketHub,PKRoma/github-android,weiyihz/PocketHub,navychang/android,GeekHades/PocketHub,bineanzhou/android_github,yongjhih/PocketHub,PeterDaveHello/PocketHub,xfumihiro/ForkHub,KishorAndroid/PocketHub,bineanzhou/android_github,danielferecatu/android,zhengxiaopeng/github-app,condda/android,gvaish/PocketHub,Damonzh/PocketHub,qiancy/PocketHub,Androidbsw/android,huangsongyan/PocketHub,yuanhuihui/PocketHub,soztzfsnf/PocketHub,reproio/github-for-android,sudosurootdev/packages_apps_Github,wshh08/PocketHub,wang0818/android,Katariaa/PocketHub,navychang/android,ISkyLove/PocketHub,larsgrefer/github-android-app,nvoron23/android,samuelralak/ForkHub,Meisolsson/PocketHub,jchenga/android,DeLaSalleUniversity-Manila/forkhub-JJCpro10,nvoron23/android,xiaopengs/PocketHub,forkhubs/android,simple88/PocketHub,cnoldtree/PocketHub,KishorAndroid/PocketHub,yuanhuihui/PocketHub,PKRoma/PocketHub,songful/PocketHub,hgl888/PocketHub,gmyboy/android,jonan/ForkHub,Chalmers-SEP-GitHubApp-Group/android,yytang2012/PocketHub,karllindmark/PocketHub,vfs1234/android,KingLiuDao/android,sam14305/bhoot.life,karllindmark/PocketHub,arcivanov/ForkHub,Kevin16Wang/PocketHub,chaoallsome/PocketHub,xfumihiro/PocketHub,larsgrefer/pocket-hub,yummy222/PocketHub,huangsongyan/PocketHub,navychang/android,lzy-h2o2/PocketHub,abhishekbm/android,supercocoa/PocketHub,zhangtianqiu/githubandroid,chaoallsome/PocketHub,shekibobo/android,larsgrefer/pocket-hub,zhuxiaohao/PocketHub,xfumihiro/ForkHub,Meisolsson/PocketHub,njucsyyh/android,samuelralak/ForkHub,marceloneil/PocketHub,ISkyLove/PocketHub,PKRoma/github-android,Cl3Kener/darkhub,Bloody-Badboy/PocketHub,songful/PocketHub,qiancy/PocketHub,erpragatisingh/android-1,repanda/PocketHub,songful/PocketHub,larsgrefer/github-android-app,weiyihz/PocketHub,xiaopengs/PocketHub,sydneyagcaoili/PocketHub,jonan/ForkHub,Bloody-Badboy/PocketHub,liqk2014/PocketHub,reproio/github-for-android,Androidbsw/android,esironal/PocketHub,LeoLamCY/PocketHub,theiven70/PocketHub,fadils/android,pockethub/PocketHub,usr80/Android,qiancy/PocketHub,vfs1234/android,acemaster/android,arcivanov/ForkHub,kostaskoukouvis/android,zhengxiaopeng/github-app,tsdl2013/android,Cl3Kener/darkhub,xiaopengs/PocketHub
|
java
|
## Code Before:
package com.github.mobile.android.util;
import android.text.Html.ImageGetter;
/**
* Html Utilities
*/
public class Html {
/**
* Encode HTML
*
* @param html
* @return html
*/
public static CharSequence encode(String html) {
return encode(html, null);
}
/**
* Encode HTML
*
* @param html
* @param imageGetter
* @return html
*/
public static CharSequence encode(String html, ImageGetter imageGetter) {
if (html == null)
return "";
if (html.length() == 0)
return html;
// These add extra padding that should be styled explicitly
if (html.startsWith("<p>") && html.endsWith("</p>"))
html = html.substring(3, html.length() - 4);
return android.text.Html.fromHtml(html, imageGetter, null);
}
}
## Instruction:
Drop <p> tags and replace </p> with <br>
This was causing an excessive amount of bottom padding
## Code After:
package com.github.mobile.android.util;
import android.text.Html.ImageGetter;
/**
* Html Utilities
*/
public class Html {
/**
* Encode HTML
*
* @param html
* @return html
*/
public static CharSequence encode(String html) {
return encode(html, null);
}
/**
* Encode HTML
*
* @param html
* @param imageGetter
* @return html
*/
public static CharSequence encode(String html, ImageGetter imageGetter) {
if (html == null)
return "";
if (html.length() == 0)
return html;
// These add extra padding that should be styled explicitly
html = html.replace("<p>", "");
html = html.replace("</p>", "<br>");
while (html.length() > 0)
if (html.startsWith("<br>"))
html = html.substring(4);
else if (html.endsWith("<br>"))
html = html.substring(0, html.length() - 4);
else
break;
return android.text.Html.fromHtml(html, imageGetter, null);
}
}
|
// ... existing code ...
if (html.length() == 0)
return html;
// These add extra padding that should be styled explicitly
html = html.replace("<p>", "");
html = html.replace("</p>", "<br>");
while (html.length() > 0)
if (html.startsWith("<br>"))
html = html.substring(4);
else if (html.endsWith("<br>"))
html = html.substring(0, html.length() - 4);
else
break;
return android.text.Html.fromHtml(html, imageGetter, null);
}
}
// ... rest of the code ...
|
d237c121955b7249e0e2ab5580d2abc2d19b0f25
|
noveltorpedo/models.py
|
noveltorpedo/models.py
|
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Story(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
contents = models.TextField(default='')
def __str__(self):
return self.title
|
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Story(models.Model):
authors = models.ManyToManyField(Author)
title = models.CharField(max_length=255)
contents = models.TextField(default='')
def __str__(self):
return self.title
|
Allow a story to have many authors
|
Allow a story to have many authors
|
Python
|
mit
|
NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo
|
python
|
## Code Before:
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Story(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
contents = models.TextField(default='')
def __str__(self):
return self.title
## Instruction:
Allow a story to have many authors
## Code After:
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Story(models.Model):
authors = models.ManyToManyField(Author)
title = models.CharField(max_length=255)
contents = models.TextField(default='')
def __str__(self):
return self.title
|
# ... existing code ...
class Story(models.Model):
authors = models.ManyToManyField(Author)
title = models.CharField(max_length=255)
contents = models.TextField(default='')
# ... rest of the code ...
|
6311df0e55fe234c39cecf6112091e65c1baf52b
|
tnrs.py
|
tnrs.py
|
import sys
import caching
import urllib
import urllib2
import re
from pyquery import PyQuery as p
try: cache = caching.get_cache('tnrs')
except: cache = {}
def tnrs_lookup(name, TIMEOUT=10, CACHE=True):
'''
Look up "name" on the TNRS web service. If a most likely standard name can be identified,
returns that name. Returns False if no or ambiguous result.
'''
name = name.replace("'", '').lower()
if name in cache and CACHE:
return cache[name]
url = "http://tnrs.iplantc.org/tnrsm-svc/matchNames?retrieve=best&names=%s"
# lookup canonical plant names on TNRS web service
try:
response = urllib2.urlopen(url % name.replace(' ', '%20'), timeout=TIMEOUT).read()
response_dict = eval(response, {}, {'true':True, 'false':False, 'null':None})
sci_name = response_dict['items'][0]['nameScientific']
if sci_name: result = sci_name
else: result = None
except Exception as e:
print e
result = False
# cache results and return
cache[name] = result
if CACHE: caching.save_cache(cache, 'tnrs')
return result
if __name__=='__main__':
if len(sys.argv) > 1: names = sys.argv[1:]
else: names = [raw_input('species name: ')]
for name in names:
print name, '->', tnrs_lookup(name)
|
import sys
import caching
import urllib
import urllib2
import re
import json
from pyquery import PyQuery as p
try: cache = caching.get_cache('tnrs')
except: cache = {}
def tnrs_lookup(name, TIMEOUT=10, CACHE=True):
'''
Look up "name" on the TNRS web service. If a most likely standard name can be identified,
returns that name. Returns False if no or ambiguous result.
'''
name = name.replace("'", '').lower()
if name in cache and CACHE:
return cache[name]
url = "http://tnrs.iplantc.org/tnrsm-svc/matchNames?retrieve=best&names=%s"
# lookup canonical plant names on TNRS web service
try:
response = urllib2.urlopen(url % name.replace(' ', '%20'), timeout=TIMEOUT).read()
#response_dict = eval(response, {}, {'true':True, 'false':False, 'null':None})
response_dict = json.loads(response)
sci_name = response_dict['items'][0]['nameScientific']
if sci_name: result = sci_name
else: result = None
except Exception as e:
print e
result = False
# cache results and return
cache[name] = result
if CACHE: caching.save_cache(cache, 'tnrs')
return result
if __name__=='__main__':
if len(sys.argv) > 1: names = sys.argv[1:]
else: names = [raw_input('species name: ')]
for name in names:
print name, '->', tnrs_lookup(name)
|
Use json library instead of eval.
|
Use json library instead of eval.
|
Python
|
mit
|
bendmorris/tax_resolve
|
python
|
## Code Before:
import sys
import caching
import urllib
import urllib2
import re
from pyquery import PyQuery as p
try: cache = caching.get_cache('tnrs')
except: cache = {}
def tnrs_lookup(name, TIMEOUT=10, CACHE=True):
'''
Look up "name" on the TNRS web service. If a most likely standard name can be identified,
returns that name. Returns False if no or ambiguous result.
'''
name = name.replace("'", '').lower()
if name in cache and CACHE:
return cache[name]
url = "http://tnrs.iplantc.org/tnrsm-svc/matchNames?retrieve=best&names=%s"
# lookup canonical plant names on TNRS web service
try:
response = urllib2.urlopen(url % name.replace(' ', '%20'), timeout=TIMEOUT).read()
response_dict = eval(response, {}, {'true':True, 'false':False, 'null':None})
sci_name = response_dict['items'][0]['nameScientific']
if sci_name: result = sci_name
else: result = None
except Exception as e:
print e
result = False
# cache results and return
cache[name] = result
if CACHE: caching.save_cache(cache, 'tnrs')
return result
if __name__=='__main__':
if len(sys.argv) > 1: names = sys.argv[1:]
else: names = [raw_input('species name: ')]
for name in names:
print name, '->', tnrs_lookup(name)
## Instruction:
Use json library instead of eval.
## Code After:
import sys
import caching
import urllib
import urllib2
import re
import json
from pyquery import PyQuery as p
try: cache = caching.get_cache('tnrs')
except: cache = {}
def tnrs_lookup(name, TIMEOUT=10, CACHE=True):
'''
Look up "name" on the TNRS web service. If a most likely standard name can be identified,
returns that name. Returns False if no or ambiguous result.
'''
name = name.replace("'", '').lower()
if name in cache and CACHE:
return cache[name]
url = "http://tnrs.iplantc.org/tnrsm-svc/matchNames?retrieve=best&names=%s"
# lookup canonical plant names on TNRS web service
try:
response = urllib2.urlopen(url % name.replace(' ', '%20'), timeout=TIMEOUT).read()
#response_dict = eval(response, {}, {'true':True, 'false':False, 'null':None})
response_dict = json.loads(response)
sci_name = response_dict['items'][0]['nameScientific']
if sci_name: result = sci_name
else: result = None
except Exception as e:
print e
result = False
# cache results and return
cache[name] = result
if CACHE: caching.save_cache(cache, 'tnrs')
return result
if __name__=='__main__':
if len(sys.argv) > 1: names = sys.argv[1:]
else: names = [raw_input('species name: ')]
for name in names:
print name, '->', tnrs_lookup(name)
|
// ... existing code ...
import urllib
import urllib2
import re
import json
from pyquery import PyQuery as p
// ... modified code ...
try:
response = urllib2.urlopen(url % name.replace(' ', '%20'), timeout=TIMEOUT).read()
#response_dict = eval(response, {}, {'true':True, 'false':False, 'null':None})
response_dict = json.loads(response)
sci_name = response_dict['items'][0]['nameScientific']
if sci_name: result = sci_name
// ... rest of the code ...
|
dcecd75cae428bb27ec8759a21e52267a55f149a
|
django_comments/signals.py
|
django_comments/signals.py
|
from django.dispatch import Signal
# Sent just before a comment will be posted (after it's been approved and
# moderated; this can be used to modify the comment (in place) with posting
# details or other such actions. If any receiver returns False the comment will be
# discarded and a 400 response. This signal is sent at more or less
# the same time (just before, actually) as the Comment object's pre-save signal,
# except that the HTTP request is sent along with this signal.
comment_will_be_posted = Signal(providing_args=["comment", "request"])
# Sent just after a comment was posted. See above for how this differs
# from the Comment object's post-save signal.
comment_was_posted = Signal(providing_args=["comment", "request"])
# Sent after a comment was "flagged" in some way. Check the flag to see if this
# was a user requesting removal of a comment, a moderator approving/removing a
# comment, or some other custom user flag.
comment_was_flagged = Signal(providing_args=["comment", "flag", "created", "request"])
|
from django.dispatch import Signal
# Sent just before a comment will be posted (after it's been approved and
# moderated; this can be used to modify the comment (in place) with posting
# details or other such actions. If any receiver returns False the comment will be
# discarded and a 400 response. This signal is sent at more or less
# the same time (just before, actually) as the Comment object's pre-save signal,
# except that the HTTP request is sent along with this signal.
# Arguments: "comment", "request"
comment_will_be_posted = Signal()
# Sent just after a comment was posted. See above for how this differs
# from the Comment object's post-save signal.
# Arguments: "comment", "request"
comment_was_posted = Signal()
# Sent after a comment was "flagged" in some way. Check the flag to see if this
# was a user requesting removal of a comment, a moderator approving/removing a
# comment, or some other custom user flag.
# Arguments: "comment", "flag", "created", "request"
comment_was_flagged = Signal()
|
Remove Signal(providing_args) argument b/c it is deprecated
|
Remove Signal(providing_args) argument b/c it is deprecated
RemovedInDjango40Warning: The providing_args argument is deprecated.
As it is purely documentational, it has no replacement. If you rely
on this argument as documentation, you can move the text to a code
comment or docstring.
|
Python
|
bsd-3-clause
|
django/django-contrib-comments,django/django-contrib-comments
|
python
|
## Code Before:
from django.dispatch import Signal
# Sent just before a comment will be posted (after it's been approved and
# moderated; this can be used to modify the comment (in place) with posting
# details or other such actions. If any receiver returns False the comment will be
# discarded and a 400 response. This signal is sent at more or less
# the same time (just before, actually) as the Comment object's pre-save signal,
# except that the HTTP request is sent along with this signal.
comment_will_be_posted = Signal(providing_args=["comment", "request"])
# Sent just after a comment was posted. See above for how this differs
# from the Comment object's post-save signal.
comment_was_posted = Signal(providing_args=["comment", "request"])
# Sent after a comment was "flagged" in some way. Check the flag to see if this
# was a user requesting removal of a comment, a moderator approving/removing a
# comment, or some other custom user flag.
comment_was_flagged = Signal(providing_args=["comment", "flag", "created", "request"])
## Instruction:
Remove Signal(providing_args) argument b/c it is deprecated
RemovedInDjango40Warning: The providing_args argument is deprecated.
As it is purely documentational, it has no replacement. If you rely
on this argument as documentation, you can move the text to a code
comment or docstring.
## Code After:
from django.dispatch import Signal
# Sent just before a comment will be posted (after it's been approved and
# moderated; this can be used to modify the comment (in place) with posting
# details or other such actions. If any receiver returns False the comment will be
# discarded and a 400 response. This signal is sent at more or less
# the same time (just before, actually) as the Comment object's pre-save signal,
# except that the HTTP request is sent along with this signal.
# Arguments: "comment", "request"
comment_will_be_posted = Signal()
# Sent just after a comment was posted. See above for how this differs
# from the Comment object's post-save signal.
# Arguments: "comment", "request"
comment_was_posted = Signal()
# Sent after a comment was "flagged" in some way. Check the flag to see if this
# was a user requesting removal of a comment, a moderator approving/removing a
# comment, or some other custom user flag.
# Arguments: "comment", "flag", "created", "request"
comment_was_flagged = Signal()
|
...
# discarded and a 400 response. This signal is sent at more or less
# the same time (just before, actually) as the Comment object's pre-save signal,
# except that the HTTP request is sent along with this signal.
# Arguments: "comment", "request"
comment_will_be_posted = Signal()
# Sent just after a comment was posted. See above for how this differs
# from the Comment object's post-save signal.
# Arguments: "comment", "request"
comment_was_posted = Signal()
# Sent after a comment was "flagged" in some way. Check the flag to see if this
# was a user requesting removal of a comment, a moderator approving/removing a
# comment, or some other custom user flag.
# Arguments: "comment", "flag", "created", "request"
comment_was_flagged = Signal()
...
|
164b860e4a44a22a1686cf6133fac6258fc97db6
|
nbgrader/tests/apps/test_nbgrader_fetch.py
|
nbgrader/tests/apps/test_nbgrader_fetch.py
|
from nbgrader.tests import run_command
from nbgrader.tests.apps.base import BaseTestApp
class TestNbGraderFetch(BaseTestApp):
def test_help(self):
"""Does the help display without error?"""
run_command("nbgrader fetch --help-all")
|
import os
from nbgrader.tests import run_command
from nbgrader.tests.apps.base import BaseTestApp
class TestNbGraderFetch(BaseTestApp):
def _fetch(self, assignment, exchange, flags="", retcode=0):
run_command(
'nbgrader fetch abc101 {} '
'--TransferApp.exchange_directory={} '
'{}'.format(assignment, exchange, flags),
retcode=retcode)
def test_help(self):
"""Does the help display without error?"""
run_command("nbgrader fetch --help-all")
def test_fetch(self, exchange):
self._copy_file("files/test.ipynb", os.path.join(exchange, "abc101/outbound/ps1/p1.ipynb"))
self._fetch("ps1", exchange)
assert os.path.isfile("ps1/p1.ipynb")
# make sure it fails if the assignment already exists
self._fetch("ps1", exchange, retcode=1)
# make sure it fails even if the assignment is incomplete
os.remove("ps1/p1.ipynb")
self._fetch("ps1", exchange, retcode=1)
|
Add some basic tests for nbgrader fetch
|
Add some basic tests for nbgrader fetch
|
Python
|
bsd-3-clause
|
modulexcite/nbgrader,jupyter/nbgrader,MatKallada/nbgrader,alope107/nbgrader,modulexcite/nbgrader,dementrock/nbgrader,alope107/nbgrader,EdwardJKim/nbgrader,jhamrick/nbgrader,jhamrick/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,EdwardJKim/nbgrader,ellisonbg/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,EdwardJKim/nbgrader,jupyter/nbgrader,jupyter/nbgrader,EdwardJKim/nbgrader,MatKallada/nbgrader,ellisonbg/nbgrader,dementrock/nbgrader,ellisonbg/nbgrader,ellisonbg/nbgrader
|
python
|
## Code Before:
from nbgrader.tests import run_command
from nbgrader.tests.apps.base import BaseTestApp
class TestNbGraderFetch(BaseTestApp):
def test_help(self):
"""Does the help display without error?"""
run_command("nbgrader fetch --help-all")
## Instruction:
Add some basic tests for nbgrader fetch
## Code After:
import os
from nbgrader.tests import run_command
from nbgrader.tests.apps.base import BaseTestApp
class TestNbGraderFetch(BaseTestApp):
def _fetch(self, assignment, exchange, flags="", retcode=0):
run_command(
'nbgrader fetch abc101 {} '
'--TransferApp.exchange_directory={} '
'{}'.format(assignment, exchange, flags),
retcode=retcode)
def test_help(self):
"""Does the help display without error?"""
run_command("nbgrader fetch --help-all")
def test_fetch(self, exchange):
self._copy_file("files/test.ipynb", os.path.join(exchange, "abc101/outbound/ps1/p1.ipynb"))
self._fetch("ps1", exchange)
assert os.path.isfile("ps1/p1.ipynb")
# make sure it fails if the assignment already exists
self._fetch("ps1", exchange, retcode=1)
# make sure it fails even if the assignment is incomplete
os.remove("ps1/p1.ipynb")
self._fetch("ps1", exchange, retcode=1)
|
// ... existing code ...
import os
from nbgrader.tests import run_command
from nbgrader.tests.apps.base import BaseTestApp
// ... modified code ...
class TestNbGraderFetch(BaseTestApp):
def _fetch(self, assignment, exchange, flags="", retcode=0):
run_command(
'nbgrader fetch abc101 {} '
'--TransferApp.exchange_directory={} '
'{}'.format(assignment, exchange, flags),
retcode=retcode)
def test_help(self):
"""Does the help display without error?"""
run_command("nbgrader fetch --help-all")
def test_fetch(self, exchange):
self._copy_file("files/test.ipynb", os.path.join(exchange, "abc101/outbound/ps1/p1.ipynb"))
self._fetch("ps1", exchange)
assert os.path.isfile("ps1/p1.ipynb")
# make sure it fails if the assignment already exists
self._fetch("ps1", exchange, retcode=1)
# make sure it fails even if the assignment is incomplete
os.remove("ps1/p1.ipynb")
self._fetch("ps1", exchange, retcode=1)
// ... rest of the code ...
|
2b5e33bf178cd1fdd8e320051d0c99a45d7613a1
|
models/product_bundle.py
|
models/product_bundle.py
|
from openerp import fields, models, _
import openerp.addons.decimal_precision as dp
class product_bundle(models.Model):
_name = 'product.bundle'
_description = 'Product bundle'
name = fields.Char(_('Name'), help=_('Product bundle name'), required=True)
bundle_line_ids = fields.Many2many(
'product.bundle.line', 'product_bundle_product_bundle_line',
'product_bundle_id', 'product_bundle_line_id', string=_('Bundle lines'))
class product_bundle_line(models.Model):
_name = 'product.bundle.line'
_description = 'Product bundle line'
product_id = fields.Many2one('product.template', string=_('Product'), required=True)
quantity = fields.Float(
string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'),
required=True, default=1)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
from openerp import fields, models, _
import openerp.addons.decimal_precision as dp
class product_bundle(models.Model):
_name = 'product.bundle'
_description = 'Product bundle'
name = fields.Char(_('Name'), help=_('Product bundle name'), required=True)
bundle_line_ids = fields.Many2many(
'product.bundle.line', 'product_bundle_product_bundle_line',
'product_bundle_id', 'product_bundle_line_id', string=_('Bundle lines'))
class product_bundle_line(models.Model):
_name = 'product.bundle.line'
_description = 'Product bundle line'
product_id = fields.Many2one(
'product.product', domain=[('sale_ok', '=', True)], string=_('Product'), required=True)
quantity = fields.Float(
string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'),
required=True, default=1)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
Use of product.template instead of product.product in bundle line
|
Use of product.template instead of product.product in bundle line
|
Python
|
agpl-3.0
|
akretion/sale-workflow,richard-willowit/sale-workflow,ddico/sale-workflow,Eficent/sale-workflow,anas-taji/sale-workflow,BT-cserra/sale-workflow,BT-fgarbely/sale-workflow,fevxie/sale-workflow,diagramsoftware/sale-workflow,adhoc-dev/sale-workflow,thomaspaulb/sale-workflow,kittiu/sale-workflow,factorlibre/sale-workflow,numerigraphe/sale-workflow,xpansa/sale-workflow,brain-tec/sale-workflow,acsone/sale-workflow,brain-tec/sale-workflow,Endika/sale-workflow,open-synergy/sale-workflow,anybox/sale-workflow,BT-ojossen/sale-workflow,BT-jmichaud/sale-workflow,acsone/sale-workflow,luistorresm/sale-workflow,jjscarafia/sale-workflow,alexsandrohaag/sale-workflow,Antiun/sale-workflow,Rona111/sale-workflow,jabibi/sale-workflow,akretion/sale-workflow,numerigraphe/sale-workflow,kittiu/sale-workflow
|
python
|
## Code Before:
from openerp import fields, models, _
import openerp.addons.decimal_precision as dp
class product_bundle(models.Model):
_name = 'product.bundle'
_description = 'Product bundle'
name = fields.Char(_('Name'), help=_('Product bundle name'), required=True)
bundle_line_ids = fields.Many2many(
'product.bundle.line', 'product_bundle_product_bundle_line',
'product_bundle_id', 'product_bundle_line_id', string=_('Bundle lines'))
class product_bundle_line(models.Model):
_name = 'product.bundle.line'
_description = 'Product bundle line'
product_id = fields.Many2one('product.template', string=_('Product'), required=True)
quantity = fields.Float(
string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'),
required=True, default=1)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
## Instruction:
Use of product.template instead of product.product in bundle line
## Code After:
from openerp import fields, models, _
import openerp.addons.decimal_precision as dp
class product_bundle(models.Model):
_name = 'product.bundle'
_description = 'Product bundle'
name = fields.Char(_('Name'), help=_('Product bundle name'), required=True)
bundle_line_ids = fields.Many2many(
'product.bundle.line', 'product_bundle_product_bundle_line',
'product_bundle_id', 'product_bundle_line_id', string=_('Bundle lines'))
class product_bundle_line(models.Model):
_name = 'product.bundle.line'
_description = 'Product bundle line'
product_id = fields.Many2one(
'product.product', domain=[('sale_ok', '=', True)], string=_('Product'), required=True)
quantity = fields.Float(
string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'),
required=True, default=1)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
# ... existing code ...
_name = 'product.bundle.line'
_description = 'Product bundle line'
product_id = fields.Many2one(
'product.product', domain=[('sale_ok', '=', True)], string=_('Product'), required=True)
quantity = fields.Float(
string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'),
required=True, default=1)
# ... rest of the code ...
|
984d8626a146770fe93d54ae107cd33dc3d2f481
|
dbmigrator/commands/init_schema_migrations.py
|
dbmigrator/commands/init_schema_migrations.py
|
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_directory='', **kwargs):
cursor.execute("""\
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT NOT NULL
)""")
cursor.execute("""\
DELETE FROM schema_migrations""")
versions = []
for version, name in utils.get_migrations(migrations_directory):
versions.append((version,))
cursor.executemany("""\
INSERT INTO schema_migrations VALUES (%s)
""", versions)
def cli_loader(parser):
return cli_command
|
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_directory='', **kwargs):
cursor.execute("""\
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT NOT NULL,
applied TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
)""")
cursor.execute("""\
DELETE FROM schema_migrations""")
versions = []
for version, name in utils.get_migrations(migrations_directory):
versions.append((version,))
cursor.executemany("""\
INSERT INTO schema_migrations VALUES (%s)
""", versions)
def cli_loader(parser):
return cli_command
|
Add "applied" timestamp to schema migrations table
|
Add "applied" timestamp to schema migrations table
|
Python
|
agpl-3.0
|
karenc/db-migrator
|
python
|
## Code Before:
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_directory='', **kwargs):
cursor.execute("""\
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT NOT NULL
)""")
cursor.execute("""\
DELETE FROM schema_migrations""")
versions = []
for version, name in utils.get_migrations(migrations_directory):
versions.append((version,))
cursor.executemany("""\
INSERT INTO schema_migrations VALUES (%s)
""", versions)
def cli_loader(parser):
return cli_command
## Instruction:
Add "applied" timestamp to schema migrations table
## Code After:
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_directory='', **kwargs):
cursor.execute("""\
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT NOT NULL,
applied TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
)""")
cursor.execute("""\
DELETE FROM schema_migrations""")
versions = []
for version, name in utils.get_migrations(migrations_directory):
versions.append((version,))
cursor.executemany("""\
INSERT INTO schema_migrations VALUES (%s)
""", versions)
def cli_loader(parser):
return cli_command
|
...
def cli_command(cursor, migrations_directory='', **kwargs):
cursor.execute("""\
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT NOT NULL,
applied TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
)""")
cursor.execute("""\
DELETE FROM schema_migrations""")
...
|
236a881c46f7930f74ed656d85c18a93e2fb9e25
|
CMSIS/DSP/Platforms/IPSS/ipss_bench.h
|
CMSIS/DSP/Platforms/IPSS/ipss_bench.h
|
extern void start_ipss_measurement();
extern void stop_ipss_measurement();
#endif
|
extern "C"
{
#endif
void start_ipss_measurement();
void stop_ipss_measurement();
#ifdef __cplusplus
}
#endif
#endif
|
Update header for use from C++
|
CMSIS-DSP: Update header for use from C++
|
C
|
apache-2.0
|
JonatanAntoni/CMSIS_5,JonatanAntoni/CMSIS_5,ARM-software/CMSIS_5,JonatanAntoni/CMSIS_5,JonatanAntoni/CMSIS_5,JonatanAntoni/CMSIS_5,ARM-software/CMSIS_5,ARM-software/CMSIS_5,ARM-software/CMSIS_5,JonatanAntoni/CMSIS_5,ARM-software/CMSIS_5,ARM-software/CMSIS_5
|
c
|
## Code Before:
extern void start_ipss_measurement();
extern void stop_ipss_measurement();
#endif
## Instruction:
CMSIS-DSP: Update header for use from C++
## Code After:
extern "C"
{
#endif
void start_ipss_measurement();
void stop_ipss_measurement();
#ifdef __cplusplus
}
#endif
#endif
|
# ... existing code ...
extern "C"
{
#endif
void start_ipss_measurement();
void stop_ipss_measurement();
#ifdef __cplusplus
}
#endif
#endif
# ... rest of the code ...
|
fa9577f875c999ea876c99e30614051f7ceba129
|
authentication_app/models.py
|
authentication_app/models.py
|
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models
'''
@name : Account
@desc : Account model. This model is generic to represent a user that has an
account in the ShopIT application. This user can be the store manager or the
mobile app user.
'''
class Account(AbstractBaseUser):
email = models.EmailField(unique=True)
username = models.CharField(max_length=50, unique=True)
first_name = models.CharField(max_length=50, blank=True)
last_name = models.CharField(max_length=50, blank=True)
is_admin = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = AccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def __unicode__(self):
return self.email
def get_full_name(self):
return ' '.join([self.first_name, self.last_name])
def get_short_name(self):
return self.first_name
|
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models
'''
@name : AccountManager
@desc : AccountManager model. The AccountManager is responsible to manage
the creation of users and superusers.
'''
class AccountManager(BaseUserManager):
def create_user(self, email, password=None, **kwargs):
if not email:
raise ValueError('Users must have a valid email adress.')
if not kwargs.get('username'):
raise ValueError('Users must have a valid username.')
account = self.model(
email = self.normalize_email(email), username= kwargs.get('username')
)
account.set_password(password)
account.save()
return account
def create_superuser(self, email, password, **kwargs):
account = self.create_user(email, password, **kwargs)
account.is_admin = True
account.save()
return account
'''
@name : Account
@desc : Account model. This model is generic to represent a user that has an
account in the ShopIT application. This user can be the store manager or the
mobile app user.
'''
class Account(AbstractBaseUser):
email = models.EmailField(unique=True)
username = models.CharField(max_length=50, unique=True)
first_name = models.CharField(max_length=50, blank=True)
last_name = models.CharField(max_length=50, blank=True)
is_admin = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = AccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def __unicode__(self):
return self.email
def get_full_name(self):
return ' '.join([self.first_name, self.last_name])
def get_short_name(self):
return self.first_name
|
Add the account manager that support the creation of accounts.
|
Add the account manager that support the creation of accounts.
|
Python
|
mit
|
mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app
|
python
|
## Code Before:
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models
'''
@name : Account
@desc : Account model. This model is generic to represent a user that has an
account in the ShopIT application. This user can be the store manager or the
mobile app user.
'''
class Account(AbstractBaseUser):
email = models.EmailField(unique=True)
username = models.CharField(max_length=50, unique=True)
first_name = models.CharField(max_length=50, blank=True)
last_name = models.CharField(max_length=50, blank=True)
is_admin = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = AccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def __unicode__(self):
return self.email
def get_full_name(self):
return ' '.join([self.first_name, self.last_name])
def get_short_name(self):
return self.first_name
## Instruction:
Add the account manager that support the creation of accounts.
## Code After:
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models
'''
@name : AccountManager
@desc : AccountManager model. The AccountManager is responsible to manage
the creation of users and superusers.
'''
class AccountManager(BaseUserManager):
def create_user(self, email, password=None, **kwargs):
if not email:
raise ValueError('Users must have a valid email adress.')
if not kwargs.get('username'):
raise ValueError('Users must have a valid username.')
account = self.model(
email = self.normalize_email(email), username= kwargs.get('username')
)
account.set_password(password)
account.save()
return account
def create_superuser(self, email, password, **kwargs):
account = self.create_user(email, password, **kwargs)
account.is_admin = True
account.save()
return account
'''
@name : Account
@desc : Account model. This model is generic to represent a user that has an
account in the ShopIT application. This user can be the store manager or the
mobile app user.
'''
class Account(AbstractBaseUser):
email = models.EmailField(unique=True)
username = models.CharField(max_length=50, unique=True)
first_name = models.CharField(max_length=50, blank=True)
last_name = models.CharField(max_length=50, blank=True)
is_admin = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = AccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def __unicode__(self):
return self.email
def get_full_name(self):
return ' '.join([self.first_name, self.last_name])
def get_short_name(self):
return self.first_name
|
# ... existing code ...
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models
'''
@name : AccountManager
@desc : AccountManager model. The AccountManager is responsible to manage
the creation of users and superusers.
'''
class AccountManager(BaseUserManager):
def create_user(self, email, password=None, **kwargs):
if not email:
raise ValueError('Users must have a valid email adress.')
if not kwargs.get('username'):
raise ValueError('Users must have a valid username.')
account = self.model(
email = self.normalize_email(email), username= kwargs.get('username')
)
account.set_password(password)
account.save()
return account
def create_superuser(self, email, password, **kwargs):
account = self.create_user(email, password, **kwargs)
account.is_admin = True
account.save()
return account
'''
@name : Account
# ... rest of the code ...
|
e97755ebee7c5994d0b65da9578e1a233b3fdee7
|
sampleapp/src/it/java/edu/samplu/mainmenu/test/TermLookUpLegacyIT.java
|
sampleapp/src/it/java/edu/samplu/mainmenu/test/TermLookUpLegacyIT.java
|
/**
* Copyright 2005-2011 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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 edu.samplu.mainmenu.test;
import org.junit.Test;
import edu.samplu.common.MainMenuLookupLegacyITBase;
/**
* tests that user 'admin' can display the Term lookup screen, search,
* initiate an Term maintenance document via an edit action on the search results and
* finally cancel the maintenance document
*
* @author Kuali Rice Team ([email protected])
*/
public class TermLookUpLegacyIT extends MainMenuLookupLegacyITBase {
@Override
public String getLinkLocator() {
return "Term Lookup";
}
@Test
public void lookupAssertions() throws Exception{
gotoMenuLinkLocator();
super.testTermLookUp();
}
}
|
/**
* Copyright 2005-2011 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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 edu.samplu.mainmenu.test;
import org.junit.Test;
import edu.samplu.common.MainMenuLookupLegacyITBase;
/**
* tests that user 'admin' can display the Term lookup screen, search,
* initiate an Term maintenance document via an edit action on the search results and
* finally cancel the maintenance document
*
* @author Kuali Rice Team ([email protected])
*/
public class TermLookUpLegacyIT extends MainMenuLookupLegacyITBase {
@Override
public void testLookUp() {} // no-op to avoid https://jira.kuali.org/browse/KULRICE-9047 messing up the server state
@Override
public String getLinkLocator() {
return "Term Lookup";
}
@Test
public void lookupAssertions() throws Exception{
gotoMenuLinkLocator();
super.testTermLookUp();
}
}
|
Disable term lookup smoke test to avoid any server impact till fixed.
|
KULRICE-9047: Disable term lookup smoke test to avoid any server impact till fixed.
git-svn-id: 2a5d2b5a02908a0c4ba7967b726d8c4198d1b9ed@37464 7a7aa7f6-c479-11dc-97e2-85a2497f191d
|
Java
|
apache-2.0
|
ricepanda/rice,ricepanda/rice,ricepanda/rice,ricepanda/rice
|
java
|
## Code Before:
/**
* Copyright 2005-2011 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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 edu.samplu.mainmenu.test;
import org.junit.Test;
import edu.samplu.common.MainMenuLookupLegacyITBase;
/**
* tests that user 'admin' can display the Term lookup screen, search,
* initiate an Term maintenance document via an edit action on the search results and
* finally cancel the maintenance document
*
* @author Kuali Rice Team ([email protected])
*/
public class TermLookUpLegacyIT extends MainMenuLookupLegacyITBase {
@Override
public String getLinkLocator() {
return "Term Lookup";
}
@Test
public void lookupAssertions() throws Exception{
gotoMenuLinkLocator();
super.testTermLookUp();
}
}
## Instruction:
KULRICE-9047: Disable term lookup smoke test to avoid any server impact till fixed.
git-svn-id: 2a5d2b5a02908a0c4ba7967b726d8c4198d1b9ed@37464 7a7aa7f6-c479-11dc-97e2-85a2497f191d
## Code After:
/**
* Copyright 2005-2011 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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 edu.samplu.mainmenu.test;
import org.junit.Test;
import edu.samplu.common.MainMenuLookupLegacyITBase;
/**
* tests that user 'admin' can display the Term lookup screen, search,
* initiate an Term maintenance document via an edit action on the search results and
* finally cancel the maintenance document
*
* @author Kuali Rice Team ([email protected])
*/
public class TermLookUpLegacyIT extends MainMenuLookupLegacyITBase {
@Override
public void testLookUp() {} // no-op to avoid https://jira.kuali.org/browse/KULRICE-9047 messing up the server state
@Override
public String getLinkLocator() {
return "Term Lookup";
}
@Test
public void lookupAssertions() throws Exception{
gotoMenuLinkLocator();
super.testTermLookUp();
}
}
|
# ... existing code ...
*/
public class TermLookUpLegacyIT extends MainMenuLookupLegacyITBase {
@Override
public void testLookUp() {} // no-op to avoid https://jira.kuali.org/browse/KULRICE-9047 messing up the server state
@Override
public String getLinkLocator() {
return "Term Lookup";
}
# ... rest of the code ...
|
c18884b10f345a8a094a3c4bf589888027d43bd5
|
examples/django_app/example_app/urls.py
|
examples/django_app/example_app/urls.py
|
from django.conf.urls import include, url
from django.contrib import admin
from example_app.views import ChatterBotAppView, ChatterBotApiView
urlpatterns = [
url(r'^$', ChatterBotAppView.as_view(), name='main'),
url(r'^admin/', include(admin.site.urls), name='admin'),
url(r'^api/chatterbot/', ChatterBotApiView.as_view(), name='chatterbot'),
]
|
from django.conf.urls import url
from django.contrib import admin
from example_app.views import ChatterBotAppView, ChatterBotApiView
urlpatterns = [
url(r'^$', ChatterBotAppView.as_view(), name='main'),
url(r'^admin/', admin.site.urls, name='admin'),
url(r'^api/chatterbot/', ChatterBotApiView.as_view(), name='chatterbot'),
]
|
Remove url inlude for Django 2.0
|
Remove url inlude for Django 2.0
|
Python
|
bsd-3-clause
|
gunthercox/ChatterBot,vkosuri/ChatterBot
|
python
|
## Code Before:
from django.conf.urls import include, url
from django.contrib import admin
from example_app.views import ChatterBotAppView, ChatterBotApiView
urlpatterns = [
url(r'^$', ChatterBotAppView.as_view(), name='main'),
url(r'^admin/', include(admin.site.urls), name='admin'),
url(r'^api/chatterbot/', ChatterBotApiView.as_view(), name='chatterbot'),
]
## Instruction:
Remove url inlude for Django 2.0
## Code After:
from django.conf.urls import url
from django.contrib import admin
from example_app.views import ChatterBotAppView, ChatterBotApiView
urlpatterns = [
url(r'^$', ChatterBotAppView.as_view(), name='main'),
url(r'^admin/', admin.site.urls, name='admin'),
url(r'^api/chatterbot/', ChatterBotApiView.as_view(), name='chatterbot'),
]
|
# ... existing code ...
from django.conf.urls import url
from django.contrib import admin
from example_app.views import ChatterBotAppView, ChatterBotApiView
# ... modified code ...
urlpatterns = [
url(r'^$', ChatterBotAppView.as_view(), name='main'),
url(r'^admin/', admin.site.urls, name='admin'),
url(r'^api/chatterbot/', ChatterBotApiView.as_view(), name='chatterbot'),
]
# ... rest of the code ...
|
2321a73ac4bc7ae3fc543c36e690d9831040160a
|
Sub-Terra/include/Oscillator.h
|
Sub-Terra/include/Oscillator.h
|
class Oscillator {
public:
WaveShape waveShape;
double frequency = 1.0;
double amplitude = 1.0;
double speed = 1.0;
uint32_t phaseAccumulator = 0;
Oscillator() = default;
Oscillator(const WaveShape &waveShape) : waveShape(waveShape), frequency(waveShape.preferredFrequency) {}
static constexpr uint32_t LowerMask(unsigned int n) {
return (n == 0)
? 0
: ((LowerMask(n - 1) << 1) | 1);
}
static constexpr uint32_t UpperMask(unsigned int n) {
return LowerMask(n) << (32 - n);
}
inline uint16_t Tick(const double sampleRate) {
double frequencyOut = frequency * speed;
uint32_t frequencyControlWord = frequencyOut * static_cast<double>(1ull << 32) / sampleRate;
phaseAccumulator += frequencyControlWord;
return amplitude * waveShape.table[(phaseAccumulator & UpperMask(WaveShape::granularity)) >> 22];
}
};
|
class Oscillator {
public:
WaveShape waveShape;
double frequency = 1.0;
double amplitude = 1.0;
double speed = 1.0;
uint32_t phaseAccumulator = 0;
Oscillator() = default;
Oscillator(const WaveShape &waveShape) : waveShape(waveShape), frequency(waveShape.preferredFrequency) {}
static constexpr uint32_t LowerMask(unsigned int n) {
return (n == 0)
? 0
: ((LowerMask(n - 1) << 1) | 1);
}
static constexpr uint32_t UpperMask(unsigned int n) {
return LowerMask(n) << (32 - n);
}
inline uint16_t Tick(const double sampleRate) {
double frequencyOut = frequency * speed;
uint32_t frequencyControlWord = static_cast<uint32_t>(frequencyOut * static_cast<double>(1ull << 32) / sampleRate);
phaseAccumulator += frequencyControlWord;
return static_cast<uint32_t>(amplitude * waveShape.table[(phaseAccumulator & UpperMask(WaveShape::granularity)) >> 22]);
}
};
|
Fix warnings and remove unused header
|
Fix warnings and remove unused header
|
C
|
mpl-2.0
|
polar-engine/polar,polar-engine/polar,shockkolate/polar4,shockkolate/polar4,shockkolate/polar4,shockkolate/polar4
|
c
|
## Code Before:
class Oscillator {
public:
WaveShape waveShape;
double frequency = 1.0;
double amplitude = 1.0;
double speed = 1.0;
uint32_t phaseAccumulator = 0;
Oscillator() = default;
Oscillator(const WaveShape &waveShape) : waveShape(waveShape), frequency(waveShape.preferredFrequency) {}
static constexpr uint32_t LowerMask(unsigned int n) {
return (n == 0)
? 0
: ((LowerMask(n - 1) << 1) | 1);
}
static constexpr uint32_t UpperMask(unsigned int n) {
return LowerMask(n) << (32 - n);
}
inline uint16_t Tick(const double sampleRate) {
double frequencyOut = frequency * speed;
uint32_t frequencyControlWord = frequencyOut * static_cast<double>(1ull << 32) / sampleRate;
phaseAccumulator += frequencyControlWord;
return amplitude * waveShape.table[(phaseAccumulator & UpperMask(WaveShape::granularity)) >> 22];
}
};
## Instruction:
Fix warnings and remove unused header
## Code After:
class Oscillator {
public:
WaveShape waveShape;
double frequency = 1.0;
double amplitude = 1.0;
double speed = 1.0;
uint32_t phaseAccumulator = 0;
Oscillator() = default;
Oscillator(const WaveShape &waveShape) : waveShape(waveShape), frequency(waveShape.preferredFrequency) {}
static constexpr uint32_t LowerMask(unsigned int n) {
return (n == 0)
? 0
: ((LowerMask(n - 1) << 1) | 1);
}
static constexpr uint32_t UpperMask(unsigned int n) {
return LowerMask(n) << (32 - n);
}
inline uint16_t Tick(const double sampleRate) {
double frequencyOut = frequency * speed;
uint32_t frequencyControlWord = static_cast<uint32_t>(frequencyOut * static_cast<double>(1ull << 32) / sampleRate);
phaseAccumulator += frequencyControlWord;
return static_cast<uint32_t>(amplitude * waveShape.table[(phaseAccumulator & UpperMask(WaveShape::granularity)) >> 22]);
}
};
|
// ... existing code ...
inline uint16_t Tick(const double sampleRate) {
double frequencyOut = frequency * speed;
uint32_t frequencyControlWord = static_cast<uint32_t>(frequencyOut * static_cast<double>(1ull << 32) / sampleRate);
phaseAccumulator += frequencyControlWord;
return static_cast<uint32_t>(amplitude * waveShape.table[(phaseAccumulator & UpperMask(WaveShape::granularity)) >> 22]);
}
};
// ... rest of the code ...
|
8b013deb4e9cd4130ece436909878b7ec7d90a60
|
src/shared/platform/win/nacl_exit.c
|
src/shared/platform/win/nacl_exit.c
|
/*
* Copyright 2011 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can
* be found in the LICENSE file.
*/
#include <stdlib.h>
#include <stdio.h>
#include "native_client/src/include/portability.h"
#include "native_client/src/shared/platform/nacl_exit.h"
#include "native_client/src/trusted/service_runtime/nacl_signal.h"
void NaClAbort(void) {
NaClExit(-SIGABRT);
}
void NaClExit(int err_code) {
#ifdef COVERAGE
/* Give coverage runs a chance to flush coverage data */
exit(err_code);
#else
/* If the process is scheduled for termination, wait for it.*/
if (TerminateProcess(GetCurrentProcess(), err_code)) {
printf("Terminate passed, but returned.\n");
while(1);
}
printf("Terminate failed with %d.\n", GetLastError());
/* Otherwise use the standard C process exit to bybass destructors. */
ExitProcess(err_code);
#endif
}
|
/*
* Copyright (c) 2011 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* be found in the LICENSE file.
*/
#include <stdlib.h>
#include <stdio.h>
#include "native_client/src/include/portability.h"
#include "native_client/src/shared/platform/nacl_exit.h"
#include "native_client/src/trusted/service_runtime/nacl_signal.h"
void NaClAbort(void) {
NaClExit(-SIGABRT);
}
void NaClExit(int err_code) {
#ifdef COVERAGE
/* Give coverage runs a chance to flush coverage data */
exit(err_code);
#else
/* If the process is scheduled for termination, wait for it.*/
if (TerminateProcess(GetCurrentProcess(), err_code)) {
while(1);
}
/* Otherwise use the standard C process exit to bybass destructors. */
ExitProcess(err_code);
#endif
}
|
Remove printfs in exit path
|
Remove printfs in exit path
Due to failures in Win7Atom I added printfs for debugging. This CL removes the printfs which should
not be in the shipping code.
TEST= all
BUG= nacl1561
Review URL: http://codereview.chromium.org/6825057
git-svn-id: 721b910a23eff8a86f00c8fd261a7587cddf18f8@4846 fcba33aa-ac0c-11dd-b9e7-8d5594d729c2
|
C
|
bsd-3-clause
|
nacl-webkit/native_client,sbc100/native_client,sbc100/native_client,nacl-webkit/native_client,sbc100/native_client,nacl-webkit/native_client,sbc100/native_client,nacl-webkit/native_client,sbc100/native_client,sbc100/native_client,nacl-webkit/native_client
|
c
|
## Code Before:
/*
* Copyright 2011 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can
* be found in the LICENSE file.
*/
#include <stdlib.h>
#include <stdio.h>
#include "native_client/src/include/portability.h"
#include "native_client/src/shared/platform/nacl_exit.h"
#include "native_client/src/trusted/service_runtime/nacl_signal.h"
void NaClAbort(void) {
NaClExit(-SIGABRT);
}
void NaClExit(int err_code) {
#ifdef COVERAGE
/* Give coverage runs a chance to flush coverage data */
exit(err_code);
#else
/* If the process is scheduled for termination, wait for it.*/
if (TerminateProcess(GetCurrentProcess(), err_code)) {
printf("Terminate passed, but returned.\n");
while(1);
}
printf("Terminate failed with %d.\n", GetLastError());
/* Otherwise use the standard C process exit to bybass destructors. */
ExitProcess(err_code);
#endif
}
## Instruction:
Remove printfs in exit path
Due to failures in Win7Atom I added printfs for debugging. This CL removes the printfs which should
not be in the shipping code.
TEST= all
BUG= nacl1561
Review URL: http://codereview.chromium.org/6825057
git-svn-id: 721b910a23eff8a86f00c8fd261a7587cddf18f8@4846 fcba33aa-ac0c-11dd-b9e7-8d5594d729c2
## Code After:
/*
* Copyright (c) 2011 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* be found in the LICENSE file.
*/
#include <stdlib.h>
#include <stdio.h>
#include "native_client/src/include/portability.h"
#include "native_client/src/shared/platform/nacl_exit.h"
#include "native_client/src/trusted/service_runtime/nacl_signal.h"
void NaClAbort(void) {
NaClExit(-SIGABRT);
}
void NaClExit(int err_code) {
#ifdef COVERAGE
/* Give coverage runs a chance to flush coverage data */
exit(err_code);
#else
/* If the process is scheduled for termination, wait for it.*/
if (TerminateProcess(GetCurrentProcess(), err_code)) {
while(1);
}
/* Otherwise use the standard C process exit to bybass destructors. */
ExitProcess(err_code);
#endif
}
|
...
/*
* Copyright (c) 2011 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* be found in the LICENSE file.
*/
...
#else
/* If the process is scheduled for termination, wait for it.*/
if (TerminateProcess(GetCurrentProcess(), err_code)) {
while(1);
}
/* Otherwise use the standard C process exit to bybass destructors. */
ExitProcess(err_code);
...
|
94df985fece5c2515917b01f273ace4d1a7c99a2
|
src/main/java/linenux/control/ControlUnit.java
|
src/main/java/linenux/control/ControlUnit.java
|
package linenux.control;
import java.nio.file.Paths;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import linenux.command.result.CommandResult;
import linenux.model.Schedule;
import linenux.storage.XmlScheduleStorage;
/**
* Controls data flow for the entire application.
*/
public class ControlUnit {
private Schedule schedule;
private XmlScheduleStorage scheduleStorage;
private CommandManager commandManager;
private ObjectProperty<CommandResult> lastCommandResult = new SimpleObjectProperty<>();
public ControlUnit() {
this.scheduleStorage = new XmlScheduleStorage(getDefaultFilePath());
this.schedule = (hasExistingSchedule()) ? getExistingSchedule() : new Schedule();
this.commandManager = new CommandManager(schedule);
}
public CommandResult execute(String userInput) {
CommandResult result = commandManager.delegateCommand(userInput);
lastCommandResult.setValue(result);
scheduleStorage.saveScheduleToFile(schedule);
return result;
}
private boolean hasExistingSchedule() {
return scheduleStorage.getFile().exists();
}
private Schedule getExistingSchedule() {
return scheduleStorage.loadScheduleFromFile();
}
private String getDefaultFilePath() {
return Paths.get(".").toAbsolutePath().toString();
}
public Schedule getSchedule() {
return this.schedule;
}
public ObjectProperty<CommandResult> getLastCommandResultProperty() {
return this.lastCommandResult;
}
}
|
package linenux.control;
import java.nio.file.Paths;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import linenux.command.result.CommandResult;
import linenux.model.Schedule;
import linenux.storage.XmlScheduleStorage;
/**
* Controls data flow for the entire application.
*/
public class ControlUnit {
private Schedule schedule;
private XmlScheduleStorage scheduleStorage;
private CommandManager commandManager;
private ObjectProperty<CommandResult> lastCommandResult = new SimpleObjectProperty<>();
public ControlUnit() {
this.scheduleStorage = new XmlScheduleStorage(getDefaultFilePath());
if (this.hasExistingSchedule() && getSchedule() != null) {
this.schedule = getSchedule();
} else {
this.schedule = new Schedule();
}
this.commandManager = new CommandManager(schedule);
}
public CommandResult execute(String userInput) {
CommandResult result = commandManager.delegateCommand(userInput);
lastCommandResult.setValue(result);
scheduleStorage.saveScheduleToFile(schedule);
return result;
}
private boolean hasExistingSchedule() {
return scheduleStorage.getFile().exists();
}
private Schedule getExistingSchedule() {
return scheduleStorage.loadScheduleFromFile();
}
private String getDefaultFilePath() {
return Paths.get(".").toAbsolutePath().toString();
}
public Schedule getSchedule() {
return this.schedule;
}
public ObjectProperty<CommandResult> getLastCommandResultProperty() {
return this.lastCommandResult;
}
}
|
Fix loading schedule from file
|
Fix loading schedule from file
|
Java
|
mit
|
CS2103AUG2016-W11-C1/main
|
java
|
## Code Before:
package linenux.control;
import java.nio.file.Paths;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import linenux.command.result.CommandResult;
import linenux.model.Schedule;
import linenux.storage.XmlScheduleStorage;
/**
* Controls data flow for the entire application.
*/
public class ControlUnit {
private Schedule schedule;
private XmlScheduleStorage scheduleStorage;
private CommandManager commandManager;
private ObjectProperty<CommandResult> lastCommandResult = new SimpleObjectProperty<>();
public ControlUnit() {
this.scheduleStorage = new XmlScheduleStorage(getDefaultFilePath());
this.schedule = (hasExistingSchedule()) ? getExistingSchedule() : new Schedule();
this.commandManager = new CommandManager(schedule);
}
public CommandResult execute(String userInput) {
CommandResult result = commandManager.delegateCommand(userInput);
lastCommandResult.setValue(result);
scheduleStorage.saveScheduleToFile(schedule);
return result;
}
private boolean hasExistingSchedule() {
return scheduleStorage.getFile().exists();
}
private Schedule getExistingSchedule() {
return scheduleStorage.loadScheduleFromFile();
}
private String getDefaultFilePath() {
return Paths.get(".").toAbsolutePath().toString();
}
public Schedule getSchedule() {
return this.schedule;
}
public ObjectProperty<CommandResult> getLastCommandResultProperty() {
return this.lastCommandResult;
}
}
## Instruction:
Fix loading schedule from file
## Code After:
package linenux.control;
import java.nio.file.Paths;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import linenux.command.result.CommandResult;
import linenux.model.Schedule;
import linenux.storage.XmlScheduleStorage;
/**
* Controls data flow for the entire application.
*/
public class ControlUnit {
private Schedule schedule;
private XmlScheduleStorage scheduleStorage;
private CommandManager commandManager;
private ObjectProperty<CommandResult> lastCommandResult = new SimpleObjectProperty<>();
public ControlUnit() {
this.scheduleStorage = new XmlScheduleStorage(getDefaultFilePath());
if (this.hasExistingSchedule() && getSchedule() != null) {
this.schedule = getSchedule();
} else {
this.schedule = new Schedule();
}
this.commandManager = new CommandManager(schedule);
}
public CommandResult execute(String userInput) {
CommandResult result = commandManager.delegateCommand(userInput);
lastCommandResult.setValue(result);
scheduleStorage.saveScheduleToFile(schedule);
return result;
}
private boolean hasExistingSchedule() {
return scheduleStorage.getFile().exists();
}
private Schedule getExistingSchedule() {
return scheduleStorage.loadScheduleFromFile();
}
private String getDefaultFilePath() {
return Paths.get(".").toAbsolutePath().toString();
}
public Schedule getSchedule() {
return this.schedule;
}
public ObjectProperty<CommandResult> getLastCommandResultProperty() {
return this.lastCommandResult;
}
}
|
// ... existing code ...
public ControlUnit() {
this.scheduleStorage = new XmlScheduleStorage(getDefaultFilePath());
if (this.hasExistingSchedule() && getSchedule() != null) {
this.schedule = getSchedule();
} else {
this.schedule = new Schedule();
}
this.commandManager = new CommandManager(schedule);
}
// ... rest of the code ...
|
64004e35e1f83933a97e4c8155d5b48c612a2c37
|
src/com/karateca/ddescriber/toolWindow/JasminFile.java
|
src/com/karateca/ddescriber/toolWindow/JasminFile.java
|
package com.karateca.ddescriber.toolWindow;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.karateca.ddescriber.Hierarchy;
import com.karateca.ddescriber.JasmineFinder;
/**
* @author Andres Dominguez.
*/
public class JasminFile {
private final VirtualFile virtualFile;
private Hierarchy hierarchy;
public JasminFile(VirtualFile virtualFile) {
this.virtualFile = virtualFile;
}
public Hierarchy createHierarchy(Project project) {
FileDocumentManager instance = FileDocumentManager.getInstance();
Document document = instance.getDocument(virtualFile);
JasmineFinder jasmineFinder = new JasmineFinder(project, document);
jasmineFinder.findAll();
hierarchy = new Hierarchy(document, jasmineFinder.getFindResults(), 0);
return hierarchy;
}
@Override
public String toString() {
return virtualFile.getName();
}
public VirtualFile getVirtualFile() {
return virtualFile;
}
}
|
package com.karateca.ddescriber.toolWindow;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.karateca.ddescriber.ActionUtil;
import com.karateca.ddescriber.Hierarchy;
import com.karateca.ddescriber.JasmineFinder;
/**
* @author Andres Dominguez.
*/
class JasminFile {
private final VirtualFile virtualFile;
public JasminFile(VirtualFile virtualFile) {
this.virtualFile = virtualFile;
}
public Hierarchy createHierarchy(Project project) {
Document document = ActionUtil.getDocument(virtualFile);
JasmineFinder jasmineFinder = new JasmineFinder(project, document);
jasmineFinder.findAll();
Hierarchy hierarchy = new Hierarchy(document, jasmineFinder.getFindResults(), 0);
return hierarchy;
}
@Override
public String toString() {
return virtualFile.getName();
}
public VirtualFile getVirtualFile() {
return virtualFile;
}
}
|
Use action util to get doc
|
Use action util to get doc
|
Java
|
mit
|
andresdominguez/ddescriber,andresdominguez/ddescriber
|
java
|
## Code Before:
package com.karateca.ddescriber.toolWindow;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.karateca.ddescriber.Hierarchy;
import com.karateca.ddescriber.JasmineFinder;
/**
* @author Andres Dominguez.
*/
public class JasminFile {
private final VirtualFile virtualFile;
private Hierarchy hierarchy;
public JasminFile(VirtualFile virtualFile) {
this.virtualFile = virtualFile;
}
public Hierarchy createHierarchy(Project project) {
FileDocumentManager instance = FileDocumentManager.getInstance();
Document document = instance.getDocument(virtualFile);
JasmineFinder jasmineFinder = new JasmineFinder(project, document);
jasmineFinder.findAll();
hierarchy = new Hierarchy(document, jasmineFinder.getFindResults(), 0);
return hierarchy;
}
@Override
public String toString() {
return virtualFile.getName();
}
public VirtualFile getVirtualFile() {
return virtualFile;
}
}
## Instruction:
Use action util to get doc
## Code After:
package com.karateca.ddescriber.toolWindow;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.karateca.ddescriber.ActionUtil;
import com.karateca.ddescriber.Hierarchy;
import com.karateca.ddescriber.JasmineFinder;
/**
* @author Andres Dominguez.
*/
class JasminFile {
private final VirtualFile virtualFile;
public JasminFile(VirtualFile virtualFile) {
this.virtualFile = virtualFile;
}
public Hierarchy createHierarchy(Project project) {
Document document = ActionUtil.getDocument(virtualFile);
JasmineFinder jasmineFinder = new JasmineFinder(project, document);
jasmineFinder.findAll();
Hierarchy hierarchy = new Hierarchy(document, jasmineFinder.getFindResults(), 0);
return hierarchy;
}
@Override
public String toString() {
return virtualFile.getName();
}
public VirtualFile getVirtualFile() {
return virtualFile;
}
}
|
...
package com.karateca.ddescriber.toolWindow;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.karateca.ddescriber.ActionUtil;
import com.karateca.ddescriber.Hierarchy;
import com.karateca.ddescriber.JasmineFinder;
...
/**
* @author Andres Dominguez.
*/
class JasminFile {
private final VirtualFile virtualFile;
public JasminFile(VirtualFile virtualFile) {
this.virtualFile = virtualFile;
...
}
public Hierarchy createHierarchy(Project project) {
Document document = ActionUtil.getDocument(virtualFile);
JasmineFinder jasmineFinder = new JasmineFinder(project, document);
jasmineFinder.findAll();
Hierarchy hierarchy = new Hierarchy(document, jasmineFinder.getFindResults(), 0);
return hierarchy;
}
...
|
4f497d86f7fedfb19ec910d5f0978f72d260b935
|
begotemp/views/geo_zone.py
|
begotemp/views/geo_zone.py
|
""" Tools for geographical zones management."""
import logging
from pyramid.view import view_config
from webhelpers import paginate
from anuket.models import DBSession
from begotemp.models.zone import Zone
log = logging.getLogger(__name__)
def includeme(config):
config.add_route('geo.zone_list', '/geo/zone')
@view_config(route_name='geo.zone_list', permission='admin',
renderer='/geo/zone/zone_list.mako')
def zone_list_view(request):
stats=None
# construct the query
zones = DBSession.query(Zone)
zones = zones.order_by(Zone.zone_number)
# paginate results
page_url = paginate.PageURL_WebOb(request)
zones = paginate.Page(zones,
page=int(request.params.get("page", 1)),
items_per_page=20,
url=page_url)
return dict(zones=zones, stats=stats)
|
""" Tools for geographical zones management."""
import logging
from pyramid.view import view_config
from webhelpers import paginate
from anuket.models import DBSession
from begotemp.models.zone import Zone
log = logging.getLogger(__name__)
def includeme(config):
config.add_route('geo.zone_list', '/geo/zone')
@view_config(route_name='geo.zone_list', permission='admin',
renderer='/geo/zone/zone_list.mako')
def zone_list_view(request):
_ = request.translate
stats=None
# construct the query
zones = DBSession.query(Zone)
zones = zones.order_by(Zone.zone_number)
# add a flash message for empty results
if zones.count() == 0:
request.session.flash(_(u"There is no results!"), 'error')
# paginate results
page_url = paginate.PageURL_WebOb(request)
zones = paginate.Page(zones,
page=int(request.params.get("page", 1)),
items_per_page=20,
url=page_url)
return dict(zones=zones, stats=stats)
|
Add a flash message for empty zone list
|
Add a flash message for empty zone list
|
Python
|
mit
|
miniwark/begotemp
|
python
|
## Code Before:
""" Tools for geographical zones management."""
import logging
from pyramid.view import view_config
from webhelpers import paginate
from anuket.models import DBSession
from begotemp.models.zone import Zone
log = logging.getLogger(__name__)
def includeme(config):
config.add_route('geo.zone_list', '/geo/zone')
@view_config(route_name='geo.zone_list', permission='admin',
renderer='/geo/zone/zone_list.mako')
def zone_list_view(request):
stats=None
# construct the query
zones = DBSession.query(Zone)
zones = zones.order_by(Zone.zone_number)
# paginate results
page_url = paginate.PageURL_WebOb(request)
zones = paginate.Page(zones,
page=int(request.params.get("page", 1)),
items_per_page=20,
url=page_url)
return dict(zones=zones, stats=stats)
## Instruction:
Add a flash message for empty zone list
## Code After:
""" Tools for geographical zones management."""
import logging
from pyramid.view import view_config
from webhelpers import paginate
from anuket.models import DBSession
from begotemp.models.zone import Zone
log = logging.getLogger(__name__)
def includeme(config):
config.add_route('geo.zone_list', '/geo/zone')
@view_config(route_name='geo.zone_list', permission='admin',
renderer='/geo/zone/zone_list.mako')
def zone_list_view(request):
_ = request.translate
stats=None
# construct the query
zones = DBSession.query(Zone)
zones = zones.order_by(Zone.zone_number)
# add a flash message for empty results
if zones.count() == 0:
request.session.flash(_(u"There is no results!"), 'error')
# paginate results
page_url = paginate.PageURL_WebOb(request)
zones = paginate.Page(zones,
page=int(request.params.get("page", 1)),
items_per_page=20,
url=page_url)
return dict(zones=zones, stats=stats)
|
...
renderer='/geo/zone/zone_list.mako')
def zone_list_view(request):
_ = request.translate
stats=None
# construct the query
zones = DBSession.query(Zone)
zones = zones.order_by(Zone.zone_number)
# add a flash message for empty results
if zones.count() == 0:
request.session.flash(_(u"There is no results!"), 'error')
# paginate results
page_url = paginate.PageURL_WebOb(request)
...
items_per_page=20,
url=page_url)
return dict(zones=zones, stats=stats)
...
|
2216caf836c1f2864103e8930f60713c226a8464
|
src/sql/parse.py
|
src/sql/parse.py
|
from ConfigParser import ConfigParser
from sqlalchemy.engine.url import URL
def parse(cell, config):
parts = [part.strip() for part in cell.split(None, 1)]
if not parts:
return {'connection': '', 'sql': ''}
if parts[0].startswith('[') and parts[0].endswith(']'):
parser = ConfigParser()
parser.read(config.dsn_filename)
section = parts[0].lstrip('[').rstrip(']')
connection = str(URL(drivername=parser.get(section, 'drivername'),
username=parser.get(section, 'username'),
password=parser.get(section, 'password'),
host=parser.get(section, 'host'),
database=parser.get(section, 'database')))
sql = parts[1] if len(parts) > 1 else ''
elif '@' in parts[0] or '://' in parts[0]:
connection = parts[0]
if len(parts) > 1:
sql = parts[1]
else:
sql = ''
else:
connection = ''
sql = cell
return {'connection': connection.strip(),
'sql': sql.strip()
}
|
from ConfigParser import ConfigParser
from sqlalchemy.engine.url import URL
def parse(cell, config):
parts = [part.strip() for part in cell.split(None, 1)]
if not parts:
return {'connection': '', 'sql': ''}
if parts[0].startswith('[') and parts[0].endswith(']'):
section = parts[0].lstrip('[').rstrip(']')
parser = ConfigParser()
parser.read(config.dsn_filename)
cfg_dict = dict(parser.items(section))
connection = str(URL(**cfg_dict))
sql = parts[1] if len(parts) > 1 else ''
elif '@' in parts[0] or '://' in parts[0]:
connection = parts[0]
if len(parts) > 1:
sql = parts[1]
else:
sql = ''
else:
connection = ''
sql = cell
return {'connection': connection.strip(),
'sql': sql.strip()}
|
Allow DNS file to be less specific
|
Allow DNS file to be less specific
|
Python
|
mit
|
catherinedevlin/ipython-sql,catherinedevlin/ipython-sql
|
python
|
## Code Before:
from ConfigParser import ConfigParser
from sqlalchemy.engine.url import URL
def parse(cell, config):
parts = [part.strip() for part in cell.split(None, 1)]
if not parts:
return {'connection': '', 'sql': ''}
if parts[0].startswith('[') and parts[0].endswith(']'):
parser = ConfigParser()
parser.read(config.dsn_filename)
section = parts[0].lstrip('[').rstrip(']')
connection = str(URL(drivername=parser.get(section, 'drivername'),
username=parser.get(section, 'username'),
password=parser.get(section, 'password'),
host=parser.get(section, 'host'),
database=parser.get(section, 'database')))
sql = parts[1] if len(parts) > 1 else ''
elif '@' in parts[0] or '://' in parts[0]:
connection = parts[0]
if len(parts) > 1:
sql = parts[1]
else:
sql = ''
else:
connection = ''
sql = cell
return {'connection': connection.strip(),
'sql': sql.strip()
}
## Instruction:
Allow DNS file to be less specific
## Code After:
from ConfigParser import ConfigParser
from sqlalchemy.engine.url import URL
def parse(cell, config):
parts = [part.strip() for part in cell.split(None, 1)]
if not parts:
return {'connection': '', 'sql': ''}
if parts[0].startswith('[') and parts[0].endswith(']'):
section = parts[0].lstrip('[').rstrip(']')
parser = ConfigParser()
parser.read(config.dsn_filename)
cfg_dict = dict(parser.items(section))
connection = str(URL(**cfg_dict))
sql = parts[1] if len(parts) > 1 else ''
elif '@' in parts[0] or '://' in parts[0]:
connection = parts[0]
if len(parts) > 1:
sql = parts[1]
else:
sql = ''
else:
connection = ''
sql = cell
return {'connection': connection.strip(),
'sql': sql.strip()}
|
# ... existing code ...
if not parts:
return {'connection': '', 'sql': ''}
if parts[0].startswith('[') and parts[0].endswith(']'):
section = parts[0].lstrip('[').rstrip(']')
parser = ConfigParser()
parser.read(config.dsn_filename)
cfg_dict = dict(parser.items(section))
connection = str(URL(**cfg_dict))
sql = parts[1] if len(parts) > 1 else ''
elif '@' in parts[0] or '://' in parts[0]:
connection = parts[0]
# ... modified code ...
connection = ''
sql = cell
return {'connection': connection.strip(),
'sql': sql.strip()}
# ... rest of the code ...
|
4af9f51da1557715a1eaaac1c2828de4dfe5b7c7
|
lib/globals.py
|
lib/globals.py
|
SCREEN_SIZE = (384, 226)
FULL_SCALE = 3
FRAME_RATE = 60.0
INPUT_NAMES = ["up", "back", "down", "forward", "light_punch",
"medium_punch", "heavy_punch", "light_kick",
"medium_kick", "heavy_kick", "start", "cancel"]
|
SCREEN_SIZE = (384, 226)
FULL_SCALE = 3
FRAME_RATE = 60.0
INPUT_NAMES = ("up", "back", "down", "forward", "light_punch",
"medium_punch", "heavy_punch", "light_kick",
"medium_kick", "heavy_kick", "start", "cancel")
DEFAULT_NAMES = ('intro',
'stand',
'walk',
'crouch_down',
'crouching_idle',
'jump_up',
'jump_forward',
'jump_back',
'block_standing',
'block_high',
'block_low',
'standing_recoil',
'crouching_recoil',
'jumping_recoil',
'tripped',
'launched',
'falling',
'knockdown',
'recover',
'dizzy',
'chip_ko',
'victory')
|
Add DEFAULT_NAMES as a global tuple constant
|
Add DEFAULT_NAMES as a global tuple constant
They will be referenced in various places in the game and should not
be subject to change.
INPUT_NAMES was also changed into a tuple for guaranteed immutability.
|
Python
|
unlicense
|
MarquisLP/Sidewalk-Champion
|
python
|
## Code Before:
SCREEN_SIZE = (384, 226)
FULL_SCALE = 3
FRAME_RATE = 60.0
INPUT_NAMES = ["up", "back", "down", "forward", "light_punch",
"medium_punch", "heavy_punch", "light_kick",
"medium_kick", "heavy_kick", "start", "cancel"]
## Instruction:
Add DEFAULT_NAMES as a global tuple constant
They will be referenced in various places in the game and should not
be subject to change.
INPUT_NAMES was also changed into a tuple for guaranteed immutability.
## Code After:
SCREEN_SIZE = (384, 226)
FULL_SCALE = 3
FRAME_RATE = 60.0
INPUT_NAMES = ("up", "back", "down", "forward", "light_punch",
"medium_punch", "heavy_punch", "light_kick",
"medium_kick", "heavy_kick", "start", "cancel")
DEFAULT_NAMES = ('intro',
'stand',
'walk',
'crouch_down',
'crouching_idle',
'jump_up',
'jump_forward',
'jump_back',
'block_standing',
'block_high',
'block_low',
'standing_recoil',
'crouching_recoil',
'jumping_recoil',
'tripped',
'launched',
'falling',
'knockdown',
'recover',
'dizzy',
'chip_ko',
'victory')
|
...
SCREEN_SIZE = (384, 226)
FULL_SCALE = 3
FRAME_RATE = 60.0
INPUT_NAMES = ("up", "back", "down", "forward", "light_punch",
"medium_punch", "heavy_punch", "light_kick",
"medium_kick", "heavy_kick", "start", "cancel")
DEFAULT_NAMES = ('intro',
'stand',
'walk',
'crouch_down',
'crouching_idle',
'jump_up',
'jump_forward',
'jump_back',
'block_standing',
'block_high',
'block_low',
'standing_recoil',
'crouching_recoil',
'jumping_recoil',
'tripped',
'launched',
'falling',
'knockdown',
'recover',
'dizzy',
'chip_ko',
'victory')
...
|
f62980f99654b22930cac6716410b145b590221f
|
Lib/lib-tk/FixTk.py
|
Lib/lib-tk/FixTk.py
|
import sys, os
v = os.path.join(sys.prefix, "tcl", "tcl8.3")
if os.path.exists(os.path.join(v, "init.tcl")):
os.environ["TCL_LIBRARY"] = v
|
import sys, os, _tkinter
ver = str(_tkinter.TCL_VERSION)
v = os.path.join(sys.prefix, "tcl", "tcl"+ver)
if os.path.exists(os.path.join(v, "init.tcl")):
os.environ["TCL_LIBRARY"] = v
|
Work the Tcl version number in the path we search for.
|
Work the Tcl version number in the path we search for.
|
Python
|
mit
|
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
|
python
|
## Code Before:
import sys, os
v = os.path.join(sys.prefix, "tcl", "tcl8.3")
if os.path.exists(os.path.join(v, "init.tcl")):
os.environ["TCL_LIBRARY"] = v
## Instruction:
Work the Tcl version number in the path we search for.
## Code After:
import sys, os, _tkinter
ver = str(_tkinter.TCL_VERSION)
v = os.path.join(sys.prefix, "tcl", "tcl"+ver)
if os.path.exists(os.path.join(v, "init.tcl")):
os.environ["TCL_LIBRARY"] = v
|
...
import sys, os, _tkinter
ver = str(_tkinter.TCL_VERSION)
v = os.path.join(sys.prefix, "tcl", "tcl"+ver)
if os.path.exists(os.path.join(v, "init.tcl")):
os.environ["TCL_LIBRARY"] = v
...
|
d15c830111987388bec89c2549a16b809d656a83
|
jarn/mkrelease/scp.py
|
jarn/mkrelease/scp.py
|
from process import Process
from exit import err_exit
class SCP(object):
"""Secure copy abstraction."""
def __init__(self, process=None):
self.process = process or Process()
def has_host(self, location):
colon = location.find(':')
slash = location.find('/')
return colon > 0 and (slash < 0 or slash > colon)
def join(self, distbase, location):
sep = ''
if distbase and distbase[-1] not in (':', '/'):
sep = '/'
return distbase + sep + location
def run_scp(self, distfile, location):
if not self.process.quiet:
print 'copying to %(location)s' % locals()
rc = self.process.os_system(
'scp "%(distfile)s" "%(location)s"' % locals())
if rc != 0:
err_exit('scp failed')
return rc
|
from tempfile import NamedTemporaryFile
from process import Process
from exit import err_exit
class SCP(object):
"""Secure copy and FTP abstraction."""
def __init__(self, process=None):
self.process = process or Process()
def run_scp(self, distfile, location):
if not self.process.quiet:
print 'scp-ing to %(location)s' % locals()
rc = self.process.os_system(
'scp "%(distfile)s" "%(location)s"' % locals())
if rc != 0:
err_exit('scp failed')
return rc
def run_sftp(self, distfile, location):
if not self.process.quiet:
print 'sftp-ing to %(location)s' % locals()
with NamedTemporaryFile(prefix='sftp-') as file:
file.write('put "%(distfile)s"\n' % locals())
file.write('bye\n')
cmdfile = file.name
rc = self.process.os_system(
'sftp -b "%(cmdfile)s" "%(location)s"' % locals())
if rc != 0:
err_exit('sftp failed')
return rc
|
Add run_sftp and remove URL manipulation methods from SCP.
|
Add run_sftp and remove URL manipulation methods from SCP.
|
Python
|
bsd-2-clause
|
Jarn/jarn.mkrelease
|
python
|
## Code Before:
from process import Process
from exit import err_exit
class SCP(object):
"""Secure copy abstraction."""
def __init__(self, process=None):
self.process = process or Process()
def has_host(self, location):
colon = location.find(':')
slash = location.find('/')
return colon > 0 and (slash < 0 or slash > colon)
def join(self, distbase, location):
sep = ''
if distbase and distbase[-1] not in (':', '/'):
sep = '/'
return distbase + sep + location
def run_scp(self, distfile, location):
if not self.process.quiet:
print 'copying to %(location)s' % locals()
rc = self.process.os_system(
'scp "%(distfile)s" "%(location)s"' % locals())
if rc != 0:
err_exit('scp failed')
return rc
## Instruction:
Add run_sftp and remove URL manipulation methods from SCP.
## Code After:
from tempfile import NamedTemporaryFile
from process import Process
from exit import err_exit
class SCP(object):
"""Secure copy and FTP abstraction."""
def __init__(self, process=None):
self.process = process or Process()
def run_scp(self, distfile, location):
if not self.process.quiet:
print 'scp-ing to %(location)s' % locals()
rc = self.process.os_system(
'scp "%(distfile)s" "%(location)s"' % locals())
if rc != 0:
err_exit('scp failed')
return rc
def run_sftp(self, distfile, location):
if not self.process.quiet:
print 'sftp-ing to %(location)s' % locals()
with NamedTemporaryFile(prefix='sftp-') as file:
file.write('put "%(distfile)s"\n' % locals())
file.write('bye\n')
cmdfile = file.name
rc = self.process.os_system(
'sftp -b "%(cmdfile)s" "%(location)s"' % locals())
if rc != 0:
err_exit('sftp failed')
return rc
|
# ... existing code ...
from tempfile import NamedTemporaryFile
from process import Process
from exit import err_exit
class SCP(object):
"""Secure copy and FTP abstraction."""
def __init__(self, process=None):
self.process = process or Process()
def run_scp(self, distfile, location):
if not self.process.quiet:
print 'scp-ing to %(location)s' % locals()
rc = self.process.os_system(
'scp "%(distfile)s" "%(location)s"' % locals())
if rc != 0:
# ... modified code ...
err_exit('scp failed')
return rc
def run_sftp(self, distfile, location):
if not self.process.quiet:
print 'sftp-ing to %(location)s' % locals()
with NamedTemporaryFile(prefix='sftp-') as file:
file.write('put "%(distfile)s"\n' % locals())
file.write('bye\n')
cmdfile = file.name
rc = self.process.os_system(
'sftp -b "%(cmdfile)s" "%(location)s"' % locals())
if rc != 0:
err_exit('sftp failed')
return rc
# ... rest of the code ...
|
03dd8ef55e56e43bc1793349dba1a7975a292aa7
|
backend/src/test/java/ch/zuehlke/campplanner/CampplannerApplicationTests.java
|
backend/src/test/java/ch/zuehlke/campplanner/CampplannerApplicationTests.java
|
package ch.zuehlke.campplanner;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = CampplannerApplication.class)
@WebAppConfiguration
public class CampplannerApplicationTests {
@Test
public void contextLoads() {
}
}
|
package ch.zuehlke.campplanner;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("dev")
@SpringApplicationConfiguration(classes = CampplannerApplication.class)
@WebAppConfiguration
public class CampplannerApplicationTests {
@Test
public void contextLoads() {
}
}
|
Use dev profile for integration tests.
|
Use dev profile for integration tests.
|
Java
|
mit
|
joachimprinzbach/ng2-camp,joachimprinzbach/ng2-camp,joachimprinzbach/ng2-camp,joachimprinzbach/ng2-camp
|
java
|
## Code Before:
package ch.zuehlke.campplanner;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = CampplannerApplication.class)
@WebAppConfiguration
public class CampplannerApplicationTests {
@Test
public void contextLoads() {
}
}
## Instruction:
Use dev profile for integration tests.
## Code After:
package ch.zuehlke.campplanner;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("dev")
@SpringApplicationConfiguration(classes = CampplannerApplication.class)
@WebAppConfiguration
public class CampplannerApplicationTests {
@Test
public void contextLoads() {
}
}
|
...
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("dev")
@SpringApplicationConfiguration(classes = CampplannerApplication.class)
@WebAppConfiguration
public class CampplannerApplicationTests {
...
|
b95512545ade73a18f180231b4742f61982c07d0
|
iclij/iclij-common/iclij-config/src/main/java/roart/iclij/config/MLConfig.java
|
iclij/iclij-common/iclij-config/src/main/java/roart/iclij/config/MLConfig.java
|
package roart.iclij.config;
public class MLConfig {
// load before evolve or use
private Boolean load;
// enable evolve or use
private Boolean enable;
// ml persistence
private Boolean persistml;
public Boolean getLoad() {
return load;
}
public void setLoad(Boolean load) {
this.load = load;
}
public Boolean getEnable() {
return enable;
}
public void setEnable(Boolean enable) {
this.enable = enable;
}
public Boolean getPersistml() {
return persistml;
}
public void setPersistml(Boolean persistml) {
this.persistml = persistml;
}
public void merge(MLConfig other) {
if (other == null) {
return;
}
if (other.load != null) {
this.load = other.load;
}
if (other.enable != null) {
this.enable = other.enable;
}
}
}
|
package roart.iclij.config;
public class MLConfig {
// load before evolve or use
private Boolean load;
// enable evolve or use
private Boolean enable;
public Boolean getLoad() {
return load;
}
public void setLoad(Boolean load) {
this.load = load;
}
public Boolean getEnable() {
return enable;
}
public void setEnable(Boolean enable) {
this.enable = enable;
}
public void merge(MLConfig other) {
if (other == null) {
return;
}
if (other.load != null) {
this.load = other.load;
}
if (other.enable != null) {
this.enable = other.enable;
}
}
}
|
Remove this, use only enable, for Machine learning persist (I114).
|
Remove this, use only enable, for Machine learning persist (I114).
|
Java
|
agpl-3.0
|
rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat
|
java
|
## Code Before:
package roart.iclij.config;
public class MLConfig {
// load before evolve or use
private Boolean load;
// enable evolve or use
private Boolean enable;
// ml persistence
private Boolean persistml;
public Boolean getLoad() {
return load;
}
public void setLoad(Boolean load) {
this.load = load;
}
public Boolean getEnable() {
return enable;
}
public void setEnable(Boolean enable) {
this.enable = enable;
}
public Boolean getPersistml() {
return persistml;
}
public void setPersistml(Boolean persistml) {
this.persistml = persistml;
}
public void merge(MLConfig other) {
if (other == null) {
return;
}
if (other.load != null) {
this.load = other.load;
}
if (other.enable != null) {
this.enable = other.enable;
}
}
}
## Instruction:
Remove this, use only enable, for Machine learning persist (I114).
## Code After:
package roart.iclij.config;
public class MLConfig {
// load before evolve or use
private Boolean load;
// enable evolve or use
private Boolean enable;
public Boolean getLoad() {
return load;
}
public void setLoad(Boolean load) {
this.load = load;
}
public Boolean getEnable() {
return enable;
}
public void setEnable(Boolean enable) {
this.enable = enable;
}
public void merge(MLConfig other) {
if (other == null) {
return;
}
if (other.load != null) {
this.load = other.load;
}
if (other.enable != null) {
this.enable = other.enable;
}
}
}
|
# ... existing code ...
// enable evolve or use
private Boolean enable;
public Boolean getLoad() {
return load;
}
# ... modified code ...
this.enable = enable;
}
public void merge(MLConfig other) {
if (other == null) {
return;
# ... rest of the code ...
|
c4e291a94360b117fcdd4ea141599de0c670e70a
|
src/core/server.h
|
src/core/server.h
|
namespace ApiMock {
class Server {
typedef std::function<ResponseData(RequestData)> CreateResponse;
struct ServerImpl;
std::unique_ptr<ServerImpl> _impl;
Server& operator=(const Server&);
Server(const Server&);
public:
Server();
~Server();
void startServer(const std::string& address, int port, int bufferSize, CreateResponse createResponse);
};
}
#endif
|
namespace ApiMock {
class Server {
struct ServerImpl;
std::unique_ptr<ServerImpl> _impl;
Server& operator=(const Server&);
Server(const Server&);
public:
typedef std::function<ResponseData(RequestData)> CreateResponse;
Server();
~Server();
void startServer(const std::string& address, int port, int bufferSize, CreateResponse createResponse);
};
}
#endif
|
Make the CreateResponse typedef public
|
Make the CreateResponse typedef public
|
C
|
mit
|
Lavesson/api-mock,Lavesson/api-mock,Lavesson/api-mock,Lavesson/api-mock
|
c
|
## Code Before:
namespace ApiMock {
class Server {
typedef std::function<ResponseData(RequestData)> CreateResponse;
struct ServerImpl;
std::unique_ptr<ServerImpl> _impl;
Server& operator=(const Server&);
Server(const Server&);
public:
Server();
~Server();
void startServer(const std::string& address, int port, int bufferSize, CreateResponse createResponse);
};
}
#endif
## Instruction:
Make the CreateResponse typedef public
## Code After:
namespace ApiMock {
class Server {
struct ServerImpl;
std::unique_ptr<ServerImpl> _impl;
Server& operator=(const Server&);
Server(const Server&);
public:
typedef std::function<ResponseData(RequestData)> CreateResponse;
Server();
~Server();
void startServer(const std::string& address, int port, int bufferSize, CreateResponse createResponse);
};
}
#endif
|
// ... existing code ...
namespace ApiMock {
class Server {
struct ServerImpl;
std::unique_ptr<ServerImpl> _impl;
// ... modified code ...
Server(const Server&);
public:
typedef std::function<ResponseData(RequestData)> CreateResponse;
Server();
~Server();
void startServer(const std::string& address, int port, int bufferSize, CreateResponse createResponse);
// ... rest of the code ...
|
224773dfaf6fb2facfa7ed7e5473e0361d936187
|
app/android/Sensorama/app/src/main/java/com/barvoy/sensorama/SRAPIPerms.java
|
app/android/Sensorama/app/src/main/java/com/barvoy/sensorama/SRAPIPerms.java
|
// Copyright (c) 2015, Wojciech Adam Koszek <[email protected]>
// All rights reserved.
package com.barvoy.sensorama;
public class SRAPIPerms {
public static final String parseAPIID = "PARSE_API_ID";
public static final String parseCLIID = "PARSE_CLIENT_ID";
}
|
// Copyright (c) 2015, Wojciech Adam Koszek <[email protected]>
// All rights reserved.
package com.barvoy.sensorama;
public class SRAPIPerms {
public static final String parseAPIID = "UNUSED_PARSE_API_ID";
public static final String parseCLIID = "UNUSED_PARSE_CLIENT_ID";
}
|
Mark this file as unused for now.
|
Mark this file as unused for now.
|
Java
|
bsd-2-clause
|
wkoszek/sensorama,wkoszek/sensorama
|
java
|
## Code Before:
// Copyright (c) 2015, Wojciech Adam Koszek <[email protected]>
// All rights reserved.
package com.barvoy.sensorama;
public class SRAPIPerms {
public static final String parseAPIID = "PARSE_API_ID";
public static final String parseCLIID = "PARSE_CLIENT_ID";
}
## Instruction:
Mark this file as unused for now.
## Code After:
// Copyright (c) 2015, Wojciech Adam Koszek <[email protected]>
// All rights reserved.
package com.barvoy.sensorama;
public class SRAPIPerms {
public static final String parseAPIID = "UNUSED_PARSE_API_ID";
public static final String parseCLIID = "UNUSED_PARSE_CLIENT_ID";
}
|
# ... existing code ...
public class SRAPIPerms {
public static final String parseAPIID = "UNUSED_PARSE_API_ID";
public static final String parseCLIID = "UNUSED_PARSE_CLIENT_ID";
}
# ... rest of the code ...
|
3bfcd86532a3c068e804e3f569de38f6412d8e90
|
core/src/main/java/bisq/core/btc/model/InputsAndChangeOutput.java
|
core/src/main/java/bisq/core/btc/model/InputsAndChangeOutput.java
|
/*
* This file is part of Bisq.
*
* Bisq 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.
*
* Bisq 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 Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package bisq.core.btc.model;
import java.util.ArrayList;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkArgument;
public class InputsAndChangeOutput {
public final ArrayList<RawTransactionInput> rawTransactionInputs;
// Is set to 0L in case we don't have an output
public final long changeOutputValue;
@Nullable
public final String changeOutputAddress;
public InputsAndChangeOutput(ArrayList<RawTransactionInput> rawTransactionInputs, long changeOutputValue, @Nullable String changeOutputAddress) {
checkArgument(!rawTransactionInputs.isEmpty(), "rawInputs.isEmpty()");
this.rawTransactionInputs = rawTransactionInputs;
this.changeOutputValue = changeOutputValue;
this.changeOutputAddress = changeOutputAddress;
}
}
|
/*
* This file is part of Bisq.
*
* Bisq 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.
*
* Bisq 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 Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package bisq.core.btc.model;
import java.util.List;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkArgument;
public class InputsAndChangeOutput {
public final List<RawTransactionInput> rawTransactionInputs;
// Is set to 0L in case we don't have an output
public final long changeOutputValue;
@Nullable
public final String changeOutputAddress;
public InputsAndChangeOutput(List<RawTransactionInput> rawTransactionInputs, long changeOutputValue, @Nullable String changeOutputAddress) {
checkArgument(!rawTransactionInputs.isEmpty(), "rawInputs.isEmpty()");
this.rawTransactionInputs = rawTransactionInputs;
this.changeOutputValue = changeOutputValue;
this.changeOutputAddress = changeOutputAddress;
}
}
|
Use List instead of ArrayList as type
|
Use List instead of ArrayList as type
|
Java
|
agpl-3.0
|
bitsquare/bitsquare,bisq-network/exchange,bisq-network/exchange,bitsquare/bitsquare
|
java
|
## Code Before:
/*
* This file is part of Bisq.
*
* Bisq 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.
*
* Bisq 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 Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package bisq.core.btc.model;
import java.util.ArrayList;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkArgument;
public class InputsAndChangeOutput {
public final ArrayList<RawTransactionInput> rawTransactionInputs;
// Is set to 0L in case we don't have an output
public final long changeOutputValue;
@Nullable
public final String changeOutputAddress;
public InputsAndChangeOutput(ArrayList<RawTransactionInput> rawTransactionInputs, long changeOutputValue, @Nullable String changeOutputAddress) {
checkArgument(!rawTransactionInputs.isEmpty(), "rawInputs.isEmpty()");
this.rawTransactionInputs = rawTransactionInputs;
this.changeOutputValue = changeOutputValue;
this.changeOutputAddress = changeOutputAddress;
}
}
## Instruction:
Use List instead of ArrayList as type
## Code After:
/*
* This file is part of Bisq.
*
* Bisq 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.
*
* Bisq 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 Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package bisq.core.btc.model;
import java.util.List;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkArgument;
public class InputsAndChangeOutput {
public final List<RawTransactionInput> rawTransactionInputs;
// Is set to 0L in case we don't have an output
public final long changeOutputValue;
@Nullable
public final String changeOutputAddress;
public InputsAndChangeOutput(List<RawTransactionInput> rawTransactionInputs, long changeOutputValue, @Nullable String changeOutputAddress) {
checkArgument(!rawTransactionInputs.isEmpty(), "rawInputs.isEmpty()");
this.rawTransactionInputs = rawTransactionInputs;
this.changeOutputValue = changeOutputValue;
this.changeOutputAddress = changeOutputAddress;
}
}
|
...
package bisq.core.btc.model;
import java.util.List;
import javax.annotation.Nullable;
...
import static com.google.common.base.Preconditions.checkArgument;
public class InputsAndChangeOutput {
public final List<RawTransactionInput> rawTransactionInputs;
// Is set to 0L in case we don't have an output
public final long changeOutputValue;
...
@Nullable
public final String changeOutputAddress;
public InputsAndChangeOutput(List<RawTransactionInput> rawTransactionInputs, long changeOutputValue, @Nullable String changeOutputAddress) {
checkArgument(!rawTransactionInputs.isEmpty(), "rawInputs.isEmpty()");
this.rawTransactionInputs = rawTransactionInputs;
...
|
c7b74cb6719b799a89cc4e88c19591c9075e15d6
|
mywebio-examples/src/main/java/io/myweb/examples/VibratorExample.java
|
mywebio-examples/src/main/java/io/myweb/examples/VibratorExample.java
|
package io.myweb.examples;
import android.content.Context;
import android.os.Vibrator;
import org.json.JSONArray;
import org.json.JSONException;
import io.myweb.api.GET;
import io.myweb.http.Response;
public class VibratorExample {
@GET("/vibrator/*toggle?:pattern=[500,1000]&:repeat=0")
public Response vibrator(Context context, String toggle, JSONArray pattern, int repeat) throws JSONException {
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (!v.hasVibrator()) return Response.serviceUnavailable();
if (toggle.equals("on")) {
v.vibrate(jsonArrayToLongArray(pattern), repeat);
} else if (toggle.equals("off")) {
v.cancel();
} else return Response.notFound();
return Response.ok();
}
private long[] jsonArrayToLongArray(JSONArray ja) throws JSONException {
long[] la = new long[ja.length()];
for (int i=0; i<la.length; i++) {
la[i] = ja.getLong(i);
}
return la;
}
}
|
package io.myweb.examples;
import android.content.Context;
import android.os.Vibrator;
import org.json.JSONArray;
import org.json.JSONException;
import io.myweb.api.GET;
import io.myweb.http.Response;
public class VibratorExample {
@GET("/vibrator/*toggle?:pattern=[500,1000,500,1000,500,1000]&:repeat=-1")
public Response vibrator(Context context, String toggle, JSONArray pattern, int repeat) throws JSONException {
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (!v.hasVibrator()) return Response.serviceUnavailable();
if (toggle.equals("on")) {
v.vibrate(jsonArrayToLongArray(pattern), repeat);
} else if (toggle.equals("off")) {
v.cancel();
} else return Response.notFound();
return Response.ok();
}
private long[] jsonArrayToLongArray(JSONArray ja) throws JSONException {
long[] la = new long[ja.length()];
for (int i=0; i<la.length; i++) {
la[i] = ja.getLong(i);
}
return la;
}
}
|
Stop vibrations in default vibration example
|
Stop vibrations in default vibration example
|
Java
|
mit
|
mywebio/mywebio-sdk,mywebio/mywebio-sdk,mywebio/mywebio-sdk
|
java
|
## Code Before:
package io.myweb.examples;
import android.content.Context;
import android.os.Vibrator;
import org.json.JSONArray;
import org.json.JSONException;
import io.myweb.api.GET;
import io.myweb.http.Response;
public class VibratorExample {
@GET("/vibrator/*toggle?:pattern=[500,1000]&:repeat=0")
public Response vibrator(Context context, String toggle, JSONArray pattern, int repeat) throws JSONException {
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (!v.hasVibrator()) return Response.serviceUnavailable();
if (toggle.equals("on")) {
v.vibrate(jsonArrayToLongArray(pattern), repeat);
} else if (toggle.equals("off")) {
v.cancel();
} else return Response.notFound();
return Response.ok();
}
private long[] jsonArrayToLongArray(JSONArray ja) throws JSONException {
long[] la = new long[ja.length()];
for (int i=0; i<la.length; i++) {
la[i] = ja.getLong(i);
}
return la;
}
}
## Instruction:
Stop vibrations in default vibration example
## Code After:
package io.myweb.examples;
import android.content.Context;
import android.os.Vibrator;
import org.json.JSONArray;
import org.json.JSONException;
import io.myweb.api.GET;
import io.myweb.http.Response;
public class VibratorExample {
@GET("/vibrator/*toggle?:pattern=[500,1000,500,1000,500,1000]&:repeat=-1")
public Response vibrator(Context context, String toggle, JSONArray pattern, int repeat) throws JSONException {
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (!v.hasVibrator()) return Response.serviceUnavailable();
if (toggle.equals("on")) {
v.vibrate(jsonArrayToLongArray(pattern), repeat);
} else if (toggle.equals("off")) {
v.cancel();
} else return Response.notFound();
return Response.ok();
}
private long[] jsonArrayToLongArray(JSONArray ja) throws JSONException {
long[] la = new long[ja.length()];
for (int i=0; i<la.length; i++) {
la[i] = ja.getLong(i);
}
return la;
}
}
|
// ... existing code ...
import io.myweb.http.Response;
public class VibratorExample {
@GET("/vibrator/*toggle?:pattern=[500,1000,500,1000,500,1000]&:repeat=-1")
public Response vibrator(Context context, String toggle, JSONArray pattern, int repeat) throws JSONException {
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (!v.hasVibrator()) return Response.serviceUnavailable();
// ... rest of the code ...
|
3ac9c317e266d79e96c20121996a4af4d82776dd
|
setup.py
|
setup.py
|
from distutils.core import setup
import winsys
if __name__ == '__main__':
setup (
name='WinSys',
version=winsys.__version__,
url='http://svn.timgolden.me.uk/winsys',
download_url='http://timgolden.me.uk/python/downloads',
license='MIT',
author='Tim Golden',
author_email='[email protected]',
description='Python tools for the Windows sysadmin',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: Windows',
'Programming Language :: Python',
'Topic :: Utilities',
],
platforms='win32',
packages=['winsys'],
)
|
from distutils.core import setup
import winsys
if __name__ == '__main__':
setup (
name='WinSys',
version=winsys.__version__,
url='http://code.google.com/p/winsys',
download_url='http://timgolden.me.uk/python/downloads/winsys',
license='MIT',
author='Tim Golden',
author_email='[email protected]',
description='Python tools for the Windows sysadmin',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: Windows',
'Programming Language :: Python',
'Topic :: Utilities',
],
platforms='win32',
packages=['winsys', 'winsys.test', 'winsys._security', 'winsys.extras'],
)
|
Correct the packaging of packages on winsys
|
Correct the packaging of packages on winsys
modified setup.py
|
Python
|
mit
|
one2pret/winsys,one2pret/winsys
|
python
|
## Code Before:
from distutils.core import setup
import winsys
if __name__ == '__main__':
setup (
name='WinSys',
version=winsys.__version__,
url='http://svn.timgolden.me.uk/winsys',
download_url='http://timgolden.me.uk/python/downloads',
license='MIT',
author='Tim Golden',
author_email='[email protected]',
description='Python tools for the Windows sysadmin',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: Windows',
'Programming Language :: Python',
'Topic :: Utilities',
],
platforms='win32',
packages=['winsys'],
)
## Instruction:
Correct the packaging of packages on winsys
modified setup.py
## Code After:
from distutils.core import setup
import winsys
if __name__ == '__main__':
setup (
name='WinSys',
version=winsys.__version__,
url='http://code.google.com/p/winsys',
download_url='http://timgolden.me.uk/python/downloads/winsys',
license='MIT',
author='Tim Golden',
author_email='[email protected]',
description='Python tools for the Windows sysadmin',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: Windows',
'Programming Language :: Python',
'Topic :: Utilities',
],
platforms='win32',
packages=['winsys', 'winsys.test', 'winsys._security', 'winsys.extras'],
)
|
...
setup (
name='WinSys',
version=winsys.__version__,
url='http://code.google.com/p/winsys',
download_url='http://timgolden.me.uk/python/downloads/winsys',
license='MIT',
author='Tim Golden',
author_email='[email protected]',
...
'Topic :: Utilities',
],
platforms='win32',
packages=['winsys', 'winsys.test', 'winsys._security', 'winsys.extras'],
)
...
|
edc7a7607ced0e5ab1366b7423a388d8cde3ba0d
|
app/src/main/java/com/bubbletastic/android/ping/Ping.java
|
app/src/main/java/com/bubbletastic/android/ping/Ping.java
|
package com.bubbletastic.android.ping;
import android.app.Application;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import com.squareup.otto.Bus;
import com.squareup.otto.ThreadEnforcer;
/**
* Created by brendanmartens on 4/13/15.
*/
public class Ping extends Application {
private Bus bus;
private JobScheduler jobScheduler;
private HostService hostService;
@Override
public void onCreate() {
super.onCreate();
bus = new Bus(ThreadEnforcer.ANY);
hostService = HostService.getInstance(this);
JobInfo updateHostsJob = new JobInfo.Builder(UpdateHostsService.JOB_ID, new ComponentName(this, UpdateHostsService.class))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
//update hosts once a minute
.setPeriodic(60000)
//service scheduling should survive reboots
.setPersisted(true)
.build();
//schedule the update hosts job
jobScheduler = ((JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE));
jobScheduler.schedule(updateHostsJob);
}
public Bus getBus() {
return bus;
}
public HostService getHostService() {
return hostService;
}
}
|
package com.bubbletastic.android.ping;
import android.app.Application;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import com.squareup.otto.Bus;
import com.squareup.otto.ThreadEnforcer;
/**
* Created by brendanmartens on 4/13/15.
*/
public class Ping extends Application {
private Bus bus;
private JobScheduler jobScheduler;
private HostService hostService;
@Override
public void onCreate() {
super.onCreate();
bus = new Bus(ThreadEnforcer.ANY);
hostService = HostService.getInstance(this);
JobInfo updateHostsJob = new JobInfo.Builder(UpdateHostsService.JOB_ID, new ComponentName(this, UpdateHostsService.class))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
//update hosts once every 4 minutes
.setPeriodic(240000)
//service scheduling should survive reboots
.setPersisted(true)
.build();
//schedule the update hosts job
jobScheduler = ((JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE));
jobScheduler.schedule(updateHostsJob);
}
public Bus getBus() {
return bus;
}
public HostService getHostService() {
return hostService;
}
}
|
Increase time between host refreshing to four minutes.
|
Increase time between host refreshing to four minutes.
|
Java
|
mit
|
shrift/ping_android,shrift/ping_android
|
java
|
## Code Before:
package com.bubbletastic.android.ping;
import android.app.Application;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import com.squareup.otto.Bus;
import com.squareup.otto.ThreadEnforcer;
/**
* Created by brendanmartens on 4/13/15.
*/
public class Ping extends Application {
private Bus bus;
private JobScheduler jobScheduler;
private HostService hostService;
@Override
public void onCreate() {
super.onCreate();
bus = new Bus(ThreadEnforcer.ANY);
hostService = HostService.getInstance(this);
JobInfo updateHostsJob = new JobInfo.Builder(UpdateHostsService.JOB_ID, new ComponentName(this, UpdateHostsService.class))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
//update hosts once a minute
.setPeriodic(60000)
//service scheduling should survive reboots
.setPersisted(true)
.build();
//schedule the update hosts job
jobScheduler = ((JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE));
jobScheduler.schedule(updateHostsJob);
}
public Bus getBus() {
return bus;
}
public HostService getHostService() {
return hostService;
}
}
## Instruction:
Increase time between host refreshing to four minutes.
## Code After:
package com.bubbletastic.android.ping;
import android.app.Application;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import com.squareup.otto.Bus;
import com.squareup.otto.ThreadEnforcer;
/**
* Created by brendanmartens on 4/13/15.
*/
public class Ping extends Application {
private Bus bus;
private JobScheduler jobScheduler;
private HostService hostService;
@Override
public void onCreate() {
super.onCreate();
bus = new Bus(ThreadEnforcer.ANY);
hostService = HostService.getInstance(this);
JobInfo updateHostsJob = new JobInfo.Builder(UpdateHostsService.JOB_ID, new ComponentName(this, UpdateHostsService.class))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
//update hosts once every 4 minutes
.setPeriodic(240000)
//service scheduling should survive reboots
.setPersisted(true)
.build();
//schedule the update hosts job
jobScheduler = ((JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE));
jobScheduler.schedule(updateHostsJob);
}
public Bus getBus() {
return bus;
}
public HostService getHostService() {
return hostService;
}
}
|
# ... existing code ...
JobInfo updateHostsJob = new JobInfo.Builder(UpdateHostsService.JOB_ID, new ComponentName(this, UpdateHostsService.class))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
//update hosts once every 4 minutes
.setPeriodic(240000)
//service scheduling should survive reboots
.setPersisted(true)
.build();
# ... rest of the code ...
|
80cac09dcd3f6227f81cc56169d69e1fae129b5d
|
test/Frontend/dependency-generation-crash.c
|
test/Frontend/dependency-generation-crash.c
|
// RUN: touch %t
// RUN: chmod 0 %t
// %clang -E -dependency-file bla -MT %t -MP -o %t -x c /dev/null
// rdar://9286457
|
// RUN: touch %t
// RUN: chmod 0 %t
// RUN: not %clang_cc1 -E -dependency-file bla -MT %t -MP -o %t -x c /dev/null 2>&1 | FileCheck %s
// RUN: rm -f %t
// CHECK: error: unable to open output file
// rdar://9286457
|
Fix dependency generation crash test to run clang and clean up after itself.
|
Fix dependency generation crash test to run clang and clean up after itself.
Previously the test did not have a RUN: prefix for the clang command.
In addition it was leaving behind a tmp file with no permissions causing issues when
deleting the build directory on Windows.
Differential Revision: http://reviews.llvm.org/D7534
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@228919 91177308-0d34-0410-b5e6-96231b3b80d8
|
C
|
apache-2.0
|
apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang
|
c
|
## Code Before:
// RUN: touch %t
// RUN: chmod 0 %t
// %clang -E -dependency-file bla -MT %t -MP -o %t -x c /dev/null
// rdar://9286457
## Instruction:
Fix dependency generation crash test to run clang and clean up after itself.
Previously the test did not have a RUN: prefix for the clang command.
In addition it was leaving behind a tmp file with no permissions causing issues when
deleting the build directory on Windows.
Differential Revision: http://reviews.llvm.org/D7534
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@228919 91177308-0d34-0410-b5e6-96231b3b80d8
## Code After:
// RUN: touch %t
// RUN: chmod 0 %t
// RUN: not %clang_cc1 -E -dependency-file bla -MT %t -MP -o %t -x c /dev/null 2>&1 | FileCheck %s
// RUN: rm -f %t
// CHECK: error: unable to open output file
// rdar://9286457
|
# ... existing code ...
// RUN: touch %t
// RUN: chmod 0 %t
// RUN: not %clang_cc1 -E -dependency-file bla -MT %t -MP -o %t -x c /dev/null 2>&1 | FileCheck %s
// RUN: rm -f %t
// CHECK: error: unable to open output file
// rdar://9286457
# ... rest of the code ...
|
69c3f107e2c8a2eef56249a87c8e192d8f6abe5c
|
sys/sparc64/include/ieeefp.h
|
sys/sparc64/include/ieeefp.h
|
/*
* Written by J.T. Conklin, Apr 6, 1995
* Public domain.
* $FreeBSD$
*/
#ifndef _MACHINE_IEEEFP_H_
#define _MACHINE_IEEEFP_H_
typedef int fp_except_t;
#define FP_X_IMP 0x01 /* imprecise (loss of precision) */
#define FP_X_DZ 0x02 /* divide-by-zero exception */
#define FP_X_UFL 0x04 /* underflow exception */
#define FP_X_OFL 0x08 /* overflow exception */
#define FP_X_INV 0x10 /* invalid operation exception */
typedef enum {
FP_RN=0, /* round to nearest representable number */
FP_RZ=1, /* round to zero (truncate) */
FP_RP=2, /* round toward positive infinity */
FP_RM=3 /* round toward negative infinity */
} fp_rnd_t;
#endif /* _MACHINE_IEEEFP_H_ */
|
/*
* Written by J.T. Conklin, Apr 6, 1995
* Public domain.
* $FreeBSD$
*/
#ifndef _MACHINE_IEEEFP_H_
#define _MACHINE_IEEEFP_H_
#include <machine/fsr.h>
typedef int fp_except_t;
#define FP_X_IMP FSR_NX /* imprecise (loss of precision) */
#define FP_X_DZ FSR_DZ /* divide-by-zero exception */
#define FP_X_UFL FSR_UF /* underflow exception */
#define FP_X_OFL FSR_OF /* overflow exception */
#define FP_X_INV FSR_NV /* invalid operation exception */
typedef enum {
FP_RN = FSR_RD_N, /* round to nearest representable number */
FP_RZ = FSR_RD_Z, /* round to zero (truncate) */
FP_RP = FSR_RD_PINF, /* round toward positive infinity */
FP_RM = FSR_RD_NINF /* round toward negative infinity */
} fp_rnd_t;
#endif /* _MACHINE_IEEEFP_H_ */
|
Use the definitions in machine/fsr.h instead of duplicating these magic numbers here (the values need to correspond to the %fsr ones for some libc functions to work right).
|
Use the definitions in machine/fsr.h instead of duplicating these magic
numbers here (the values need to correspond to the %fsr ones for some
libc functions to work right).
|
C
|
bsd-3-clause
|
jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase
|
c
|
## Code Before:
/*
* Written by J.T. Conklin, Apr 6, 1995
* Public domain.
* $FreeBSD$
*/
#ifndef _MACHINE_IEEEFP_H_
#define _MACHINE_IEEEFP_H_
typedef int fp_except_t;
#define FP_X_IMP 0x01 /* imprecise (loss of precision) */
#define FP_X_DZ 0x02 /* divide-by-zero exception */
#define FP_X_UFL 0x04 /* underflow exception */
#define FP_X_OFL 0x08 /* overflow exception */
#define FP_X_INV 0x10 /* invalid operation exception */
typedef enum {
FP_RN=0, /* round to nearest representable number */
FP_RZ=1, /* round to zero (truncate) */
FP_RP=2, /* round toward positive infinity */
FP_RM=3 /* round toward negative infinity */
} fp_rnd_t;
#endif /* _MACHINE_IEEEFP_H_ */
## Instruction:
Use the definitions in machine/fsr.h instead of duplicating these magic
numbers here (the values need to correspond to the %fsr ones for some
libc functions to work right).
## Code After:
/*
* Written by J.T. Conklin, Apr 6, 1995
* Public domain.
* $FreeBSD$
*/
#ifndef _MACHINE_IEEEFP_H_
#define _MACHINE_IEEEFP_H_
#include <machine/fsr.h>
typedef int fp_except_t;
#define FP_X_IMP FSR_NX /* imprecise (loss of precision) */
#define FP_X_DZ FSR_DZ /* divide-by-zero exception */
#define FP_X_UFL FSR_UF /* underflow exception */
#define FP_X_OFL FSR_OF /* overflow exception */
#define FP_X_INV FSR_NV /* invalid operation exception */
typedef enum {
FP_RN = FSR_RD_N, /* round to nearest representable number */
FP_RZ = FSR_RD_Z, /* round to zero (truncate) */
FP_RP = FSR_RD_PINF, /* round toward positive infinity */
FP_RM = FSR_RD_NINF /* round toward negative infinity */
} fp_rnd_t;
#endif /* _MACHINE_IEEEFP_H_ */
|
# ... existing code ...
#ifndef _MACHINE_IEEEFP_H_
#define _MACHINE_IEEEFP_H_
#include <machine/fsr.h>
typedef int fp_except_t;
#define FP_X_IMP FSR_NX /* imprecise (loss of precision) */
#define FP_X_DZ FSR_DZ /* divide-by-zero exception */
#define FP_X_UFL FSR_UF /* underflow exception */
#define FP_X_OFL FSR_OF /* overflow exception */
#define FP_X_INV FSR_NV /* invalid operation exception */
typedef enum {
FP_RN = FSR_RD_N, /* round to nearest representable number */
FP_RZ = FSR_RD_Z, /* round to zero (truncate) */
FP_RP = FSR_RD_PINF, /* round toward positive infinity */
FP_RM = FSR_RD_NINF /* round toward negative infinity */
} fp_rnd_t;
#endif /* _MACHINE_IEEEFP_H_ */
# ... rest of the code ...
|
3654f9926d4015a10d62ab6bb93087974d510daf
|
framegrab.h
|
framegrab.h
|
typedef void *fg_handle;
/* fourcc constants */
#define FG_FORMAT_YUYV 0x56595559
#define FG_FORMAT_RGB24 0x33424752
struct fg_image {
int width;
int height;
int format;
};
fg_handle fg_init(char *, int);
int fg_deinit(fg_handle);
int fg_start(fg_handle);
int fg_stop(fg_handle);
int fg_set_format(fg_handle, struct fg_image *);
int fg_get_format(fg_handle, struct fg_image *);
int fg_get_frame(fg_handle, void *, size_t len);
int fg_write_jpeg(char *, int, struct fg_image *, void *);
#endif
|
extern "C" {
#endif
#include <stdlib.h>
#if defined(_WIN32) && !defined(__CYGWIN__)
# ifdef BUILDING_DLL
# define EXPORT __declspec(dllexport)
# else
# define EXPORT __declspec(dllimport)
# endif
#elif __GNUC__ >= 4 || defined(__HP_cc)
# define EXPORT __attribute__((visibility ("default")))
#elif defined(__SUNPRO_C)
# define EXPORT __global
#else
# define EXPORT
#endif
typedef void *fg_handle;
/* fourcc constants */
#define FG_FORMAT_YUYV 0x56595559
#define FG_FORMAT_RGB24 0x33424752
struct fg_image {
int width;
int height;
int format;
};
EXPORT fg_handle fg_init(char *, int);
EXPORT int fg_deinit(fg_handle);
EXPORT int fg_start(fg_handle);
EXPORT int fg_stop(fg_handle);
EXPORT int fg_set_format(fg_handle, struct fg_image *);
EXPORT int fg_get_format(fg_handle, struct fg_image *);
EXPORT int fg_get_frame(fg_handle, void *, size_t len);
EXPORT int fg_write_jpeg(char *, int, struct fg_image *, void *);
#ifdef __cplusplus
}
#endif
#endif
|
Add C++ and shared library stuff to header file
|
Add C++ and shared library stuff to header file
We're not using it yet, but it's a nice thing to have.
Signed-off-by: Claudio Matsuoka <[email protected]>
|
C
|
mit
|
cmatsuoka/framegrab,cmatsuoka/framegrab
|
c
|
## Code Before:
typedef void *fg_handle;
/* fourcc constants */
#define FG_FORMAT_YUYV 0x56595559
#define FG_FORMAT_RGB24 0x33424752
struct fg_image {
int width;
int height;
int format;
};
fg_handle fg_init(char *, int);
int fg_deinit(fg_handle);
int fg_start(fg_handle);
int fg_stop(fg_handle);
int fg_set_format(fg_handle, struct fg_image *);
int fg_get_format(fg_handle, struct fg_image *);
int fg_get_frame(fg_handle, void *, size_t len);
int fg_write_jpeg(char *, int, struct fg_image *, void *);
#endif
## Instruction:
Add C++ and shared library stuff to header file
We're not using it yet, but it's a nice thing to have.
Signed-off-by: Claudio Matsuoka <[email protected]>
## Code After:
extern "C" {
#endif
#include <stdlib.h>
#if defined(_WIN32) && !defined(__CYGWIN__)
# ifdef BUILDING_DLL
# define EXPORT __declspec(dllexport)
# else
# define EXPORT __declspec(dllimport)
# endif
#elif __GNUC__ >= 4 || defined(__HP_cc)
# define EXPORT __attribute__((visibility ("default")))
#elif defined(__SUNPRO_C)
# define EXPORT __global
#else
# define EXPORT
#endif
typedef void *fg_handle;
/* fourcc constants */
#define FG_FORMAT_YUYV 0x56595559
#define FG_FORMAT_RGB24 0x33424752
struct fg_image {
int width;
int height;
int format;
};
EXPORT fg_handle fg_init(char *, int);
EXPORT int fg_deinit(fg_handle);
EXPORT int fg_start(fg_handle);
EXPORT int fg_stop(fg_handle);
EXPORT int fg_set_format(fg_handle, struct fg_image *);
EXPORT int fg_get_format(fg_handle, struct fg_image *);
EXPORT int fg_get_frame(fg_handle, void *, size_t len);
EXPORT int fg_write_jpeg(char *, int, struct fg_image *, void *);
#ifdef __cplusplus
}
#endif
#endif
|
// ... existing code ...
extern "C" {
#endif
#include <stdlib.h>
#if defined(_WIN32) && !defined(__CYGWIN__)
# ifdef BUILDING_DLL
# define EXPORT __declspec(dllexport)
# else
# define EXPORT __declspec(dllimport)
# endif
#elif __GNUC__ >= 4 || defined(__HP_cc)
# define EXPORT __attribute__((visibility ("default")))
#elif defined(__SUNPRO_C)
# define EXPORT __global
#else
# define EXPORT
#endif
typedef void *fg_handle;
// ... modified code ...
int format;
};
EXPORT fg_handle fg_init(char *, int);
EXPORT int fg_deinit(fg_handle);
EXPORT int fg_start(fg_handle);
EXPORT int fg_stop(fg_handle);
EXPORT int fg_set_format(fg_handle, struct fg_image *);
EXPORT int fg_get_format(fg_handle, struct fg_image *);
EXPORT int fg_get_frame(fg_handle, void *, size_t len);
EXPORT int fg_write_jpeg(char *, int, struct fg_image *, void *);
#ifdef __cplusplus
}
#endif
#endif
// ... rest of the code ...
|
08dba183a3e7f08db526e63b91136575163a4252
|
src/test/java/edu/chl/proton/model/FolderTest.java
|
src/test/java/edu/chl/proton/model/FolderTest.java
|
package edu.chl.proton.model;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
/**
* @author Stina Werme
* Created by stinawerme on 11/05/17.
*/
public class FolderTest {
@Test
public void removeFolderTest() {
Folder parent = new Folder("parent");
Folder child = new Folder("child", parent);
parent.removeFolder(child);
assertTrue("The folder parent should not be null", parent != null);
assertTrue("The folder child should not be null", child != null);
assertTrue("ParentFolder should be null", child.getParentFolder() == null);
}
@Test
public void removeFileTest() {
File file = new File("file");
Folder folder = new Folder("folder");
folder.removeFile(file);
assertTrue("The file file should not be null", file != null);
assertTrue("The folder folder should not be null", folder != null);
assertTrue("ParentFolder should be null", file.getParentFolder() == null);
}
}
}
|
package edu.chl.proton.model;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
/**
* @author Stina Werme
* Created by stinawerme on 11/05/17.
*/
public class FolderTest {
@Test
public void removeFolderTest() {
Folder parent = new Folder("parent");
Folder child = new Folder("child", parent);
parent.removeFolder(child);
assertTrue("The folder parent should not be null", parent != null);
assertTrue("The folder child should not be null", child != null);
assertTrue("ParentFolder should be null", child.getParentFolder() == null);
}
@Test
public void removeFileTest() {
File file = new File("file");
Folder folder = new Folder("folder");
folder.removeFile(file);
assertTrue("The file file should not be null", file != null);
assertTrue("The folder folder should not be null", folder != null);
assertTrue("ParentFolder should be null", file.getParentFolder() == null);
}
@Test
public void addFileTest() {
Folder parent = new Folder("parent");
File childFile = new File("childFile", parent);
Folder newParent = new Folder("newParent");
newParent.addFile(childFile);
assertTrue("The folder parent should not be null", parent != null);
assertTrue("The file childFile should not be null", childFile != null);
assertTrue("The folder newParent should not be null", newParent != null);
assertTrue("ParentFolder should be newParent", childFile.getParentFolder() == newParent);
}
@Test
public void addFolderTest() {
Folder one = new Folder("one");
Folder two = new Folder("two", one);
Folder three = new Folder("three");
two.addFolder(three);
assertTrue("The folder one should not be null", one != null);
assertTrue("The folder two should not be null", two != null);
assertTrue("The folder three should not be null", three != null);
assertTrue("ParentFolder should be three", two.getParentFolder() == three);
}
}
|
Add test for addFile and addFolder
|
Add test for addFile and addFolder
|
Java
|
agpl-3.0
|
Levis92/proton-text
|
java
|
## Code Before:
package edu.chl.proton.model;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
/**
* @author Stina Werme
* Created by stinawerme on 11/05/17.
*/
public class FolderTest {
@Test
public void removeFolderTest() {
Folder parent = new Folder("parent");
Folder child = new Folder("child", parent);
parent.removeFolder(child);
assertTrue("The folder parent should not be null", parent != null);
assertTrue("The folder child should not be null", child != null);
assertTrue("ParentFolder should be null", child.getParentFolder() == null);
}
@Test
public void removeFileTest() {
File file = new File("file");
Folder folder = new Folder("folder");
folder.removeFile(file);
assertTrue("The file file should not be null", file != null);
assertTrue("The folder folder should not be null", folder != null);
assertTrue("ParentFolder should be null", file.getParentFolder() == null);
}
}
}
## Instruction:
Add test for addFile and addFolder
## Code After:
package edu.chl.proton.model;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
/**
* @author Stina Werme
* Created by stinawerme on 11/05/17.
*/
public class FolderTest {
@Test
public void removeFolderTest() {
Folder parent = new Folder("parent");
Folder child = new Folder("child", parent);
parent.removeFolder(child);
assertTrue("The folder parent should not be null", parent != null);
assertTrue("The folder child should not be null", child != null);
assertTrue("ParentFolder should be null", child.getParentFolder() == null);
}
@Test
public void removeFileTest() {
File file = new File("file");
Folder folder = new Folder("folder");
folder.removeFile(file);
assertTrue("The file file should not be null", file != null);
assertTrue("The folder folder should not be null", folder != null);
assertTrue("ParentFolder should be null", file.getParentFolder() == null);
}
@Test
public void addFileTest() {
Folder parent = new Folder("parent");
File childFile = new File("childFile", parent);
Folder newParent = new Folder("newParent");
newParent.addFile(childFile);
assertTrue("The folder parent should not be null", parent != null);
assertTrue("The file childFile should not be null", childFile != null);
assertTrue("The folder newParent should not be null", newParent != null);
assertTrue("ParentFolder should be newParent", childFile.getParentFolder() == newParent);
}
@Test
public void addFolderTest() {
Folder one = new Folder("one");
Folder two = new Folder("two", one);
Folder three = new Folder("three");
two.addFolder(three);
assertTrue("The folder one should not be null", one != null);
assertTrue("The folder two should not be null", two != null);
assertTrue("The folder three should not be null", three != null);
assertTrue("ParentFolder should be three", two.getParentFolder() == three);
}
}
|
...
assertTrue("The folder folder should not be null", folder != null);
assertTrue("ParentFolder should be null", file.getParentFolder() == null);
}
@Test
public void addFileTest() {
Folder parent = new Folder("parent");
File childFile = new File("childFile", parent);
Folder newParent = new Folder("newParent");
newParent.addFile(childFile);
assertTrue("The folder parent should not be null", parent != null);
assertTrue("The file childFile should not be null", childFile != null);
assertTrue("The folder newParent should not be null", newParent != null);
assertTrue("ParentFolder should be newParent", childFile.getParentFolder() == newParent);
}
@Test
public void addFolderTest() {
Folder one = new Folder("one");
Folder two = new Folder("two", one);
Folder three = new Folder("three");
two.addFolder(three);
assertTrue("The folder one should not be null", one != null);
assertTrue("The folder two should not be null", two != null);
assertTrue("The folder three should not be null", three != null);
assertTrue("ParentFolder should be three", two.getParentFolder() == three);
}
}
...
|
aa974a2d12020e324db222b022594d9e489e559f
|
convert.py
|
convert.py
|
import argparse
import numpy as np
from PIL import Image
lookup = " .,:-?X#"
def image_to_ascii(image):
"""
PIL image object -> 2d array of values
"""
quantised = image.quantize(len(lookup))
quantised.show()
array = np.asarray(quantised.resize((128,64)))
return [[lookup[k] for k in i] for i in array]
def convert_file(fn):
converted = ""
try:
image = Image.open(fn)
converted = image_to_ascii(image)
except Exception as e:
print e.message
return converted
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--filename",
help="Convert this file to ASCII art",
required=True)
args = parser.parse_args()
print args
filename = args.filename
converted = convert_file(filename)
print '\n'.join(''.join(i) for i in converted)
|
import argparse
import numpy as np
from PIL import Image
lookup = " .,:-!?X#"
def image_to_ascii(image, width=128):
"""
PIL image object -> 2d array of values
"""
def scale_height(h, w, new_width):
print "original height: {}".format(h)
print "original width: {}".format(w)
print "new width: {}".format(new_width)
conversion_factor = float(1.0 * new_width / w)
print "conversion factor {}".format(conversion_factor)
new_height = (h * conversion_factor) / 2.0
print "new height: {}".format(new_height)
return int(new_height)
quantised = image.quantize(len(lookup))
#quantised.show()
array = np.asarray(quantised.resize((width, scale_height(image.height, image.width, width))))
return [[lookup[k] for k in i] for i in array]
def convert_file(fn):
converted = ""
try:
image = Image.open(fn)
converted = image_to_ascii(image)
except Exception as e:
print e.message
return converted
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--filename",
help="Convert this file to ASCII art",
required=True)
args = parser.parse_args()
print args
filename = args.filename
converted = convert_file(filename)
print '\n'.join(''.join(i) for i in converted)
|
CORRECT height/width conversion this time around
|
CORRECT height/width conversion this time around
|
Python
|
mit
|
machineperson/fantastic-doodle
|
python
|
## Code Before:
import argparse
import numpy as np
from PIL import Image
lookup = " .,:-?X#"
def image_to_ascii(image):
"""
PIL image object -> 2d array of values
"""
quantised = image.quantize(len(lookup))
quantised.show()
array = np.asarray(quantised.resize((128,64)))
return [[lookup[k] for k in i] for i in array]
def convert_file(fn):
converted = ""
try:
image = Image.open(fn)
converted = image_to_ascii(image)
except Exception as e:
print e.message
return converted
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--filename",
help="Convert this file to ASCII art",
required=True)
args = parser.parse_args()
print args
filename = args.filename
converted = convert_file(filename)
print '\n'.join(''.join(i) for i in converted)
## Instruction:
CORRECT height/width conversion this time around
## Code After:
import argparse
import numpy as np
from PIL import Image
lookup = " .,:-!?X#"
def image_to_ascii(image, width=128):
"""
PIL image object -> 2d array of values
"""
def scale_height(h, w, new_width):
print "original height: {}".format(h)
print "original width: {}".format(w)
print "new width: {}".format(new_width)
conversion_factor = float(1.0 * new_width / w)
print "conversion factor {}".format(conversion_factor)
new_height = (h * conversion_factor) / 2.0
print "new height: {}".format(new_height)
return int(new_height)
quantised = image.quantize(len(lookup))
#quantised.show()
array = np.asarray(quantised.resize((width, scale_height(image.height, image.width, width))))
return [[lookup[k] for k in i] for i in array]
def convert_file(fn):
converted = ""
try:
image = Image.open(fn)
converted = image_to_ascii(image)
except Exception as e:
print e.message
return converted
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--filename",
help="Convert this file to ASCII art",
required=True)
args = parser.parse_args()
print args
filename = args.filename
converted = convert_file(filename)
print '\n'.join(''.join(i) for i in converted)
|
// ... existing code ...
from PIL import Image
lookup = " .,:-!?X#"
def image_to_ascii(image, width=128):
"""
PIL image object -> 2d array of values
"""
def scale_height(h, w, new_width):
print "original height: {}".format(h)
print "original width: {}".format(w)
print "new width: {}".format(new_width)
conversion_factor = float(1.0 * new_width / w)
print "conversion factor {}".format(conversion_factor)
new_height = (h * conversion_factor) / 2.0
print "new height: {}".format(new_height)
return int(new_height)
quantised = image.quantize(len(lookup))
#quantised.show()
array = np.asarray(quantised.resize((width, scale_height(image.height, image.width, width))))
return [[lookup[k] for k in i] for i in array]
// ... rest of the code ...
|
4c20c2137eb1cee69511ecd8a83a499147b42373
|
tests/thread-test.py
|
tests/thread-test.py
|
import pstack
import json
threads, text = pstack.JSON(["tests/thread"])
result = json.loads(text)
# we have 10 threads + main
assert len(threads) == 11
entryThreads = 0
for thread in threads:
assert thread["ti_lid"] in result["lwps"], "LWP %d not in %s" % (thread["ti_lid"], result["lwps"])
assert thread["ti_tid"] in result["threads"], "thread %d not in %s" % (thread["ti_lid"], result["threads"])
for frame in thread["ti_stack"]:
if frame['die'] == 'entry':
entryThreads += 1
# the soruce for "entry" should be thread.c
if not frame['source']:
print "warning: no source info to test"
else:
assert frame['source'][0]['file'].endswith( 'thread.cc' )
lineNo = frame['source'][0]['line']
# we should be between unlocking the mutex and pausing
assert lineNo == result["assert_at"]
assert entryThreads == 10
|
import pstack
import json
pstack, text = pstack.JSON(["tests/thread"])
result = json.loads(text)
threads = result["threads"]
lwps = result["lwps"]
assert_at = result["assert_at"]
# we have 10 threads + main
assert len(threads) == 11
for thread in pstack:
# this will throw an error if the thread or LWP is not in the output for
# the command, indicating a thread or LWP id from pstack was wrong.
threads.remove(thread["ti_tid"])
lwps.remove(thread["ti_lid"])
for frame in thread["ti_stack"]:
if frame['die'] == 'entry':
# the soruce for "entry" should be thread.c
if not frame['source']:
print "warning: no source info to test"
else:
assert frame['source'][0]['file'].endswith( 'thread.cc' )
lineNo = frame['source'][0]['line']
# we should be between unlocking the mutex and pausing
assert lineNo == assert_at
# When we are finished, pstack should have found all the threads and lwps that
# reported in the output from the command.
assert not lwps
assert not threads
|
Clean up changes to thread test
|
Clean up changes to thread test
|
Python
|
bsd-2-clause
|
peadar/pstack,peadar/pstack,peadar/pstack,peadar/pstack
|
python
|
## Code Before:
import pstack
import json
threads, text = pstack.JSON(["tests/thread"])
result = json.loads(text)
# we have 10 threads + main
assert len(threads) == 11
entryThreads = 0
for thread in threads:
assert thread["ti_lid"] in result["lwps"], "LWP %d not in %s" % (thread["ti_lid"], result["lwps"])
assert thread["ti_tid"] in result["threads"], "thread %d not in %s" % (thread["ti_lid"], result["threads"])
for frame in thread["ti_stack"]:
if frame['die'] == 'entry':
entryThreads += 1
# the soruce for "entry" should be thread.c
if not frame['source']:
print "warning: no source info to test"
else:
assert frame['source'][0]['file'].endswith( 'thread.cc' )
lineNo = frame['source'][0]['line']
# we should be between unlocking the mutex and pausing
assert lineNo == result["assert_at"]
assert entryThreads == 10
## Instruction:
Clean up changes to thread test
## Code After:
import pstack
import json
pstack, text = pstack.JSON(["tests/thread"])
result = json.loads(text)
threads = result["threads"]
lwps = result["lwps"]
assert_at = result["assert_at"]
# we have 10 threads + main
assert len(threads) == 11
for thread in pstack:
# this will throw an error if the thread or LWP is not in the output for
# the command, indicating a thread or LWP id from pstack was wrong.
threads.remove(thread["ti_tid"])
lwps.remove(thread["ti_lid"])
for frame in thread["ti_stack"]:
if frame['die'] == 'entry':
# the soruce for "entry" should be thread.c
if not frame['source']:
print "warning: no source info to test"
else:
assert frame['source'][0]['file'].endswith( 'thread.cc' )
lineNo = frame['source'][0]['line']
# we should be between unlocking the mutex and pausing
assert lineNo == assert_at
# When we are finished, pstack should have found all the threads and lwps that
# reported in the output from the command.
assert not lwps
assert not threads
|
# ... existing code ...
import pstack
import json
pstack, text = pstack.JSON(["tests/thread"])
result = json.loads(text)
threads = result["threads"]
lwps = result["lwps"]
assert_at = result["assert_at"]
# we have 10 threads + main
assert len(threads) == 11
for thread in pstack:
# this will throw an error if the thread or LWP is not in the output for
# the command, indicating a thread or LWP id from pstack was wrong.
threads.remove(thread["ti_tid"])
lwps.remove(thread["ti_lid"])
for frame in thread["ti_stack"]:
if frame['die'] == 'entry':
# the soruce for "entry" should be thread.c
if not frame['source']:
print "warning: no source info to test"
# ... modified code ...
assert frame['source'][0]['file'].endswith( 'thread.cc' )
lineNo = frame['source'][0]['line']
# we should be between unlocking the mutex and pausing
assert lineNo == assert_at
# When we are finished, pstack should have found all the threads and lwps that
# reported in the output from the command.
assert not lwps
assert not threads
# ... rest of the code ...
|
8d0325e28a1836a8afdfc33916d36a3e259ad131
|
fil_finder/__init__.py
|
fil_finder/__init__.py
|
__version__ = "1.2.2"
from .analysis import Analysis
from .filfind_class import fil_finder_2D
from .width_profiles import filament_profile
|
__version__ = "1.2.2"
from .analysis import Analysis
from .filfind_class import fil_finder_2D
|
Revert importing from the top
|
Revert importing from the top
|
Python
|
mit
|
e-koch/FilFinder
|
python
|
## Code Before:
__version__ = "1.2.2"
from .analysis import Analysis
from .filfind_class import fil_finder_2D
from .width_profiles import filament_profile
## Instruction:
Revert importing from the top
## Code After:
__version__ = "1.2.2"
from .analysis import Analysis
from .filfind_class import fil_finder_2D
|
# ... existing code ...
from .analysis import Analysis
from .filfind_class import fil_finder_2D
# ... rest of the code ...
|
cc8a30b5422fbc9d0db438ef9bc497686577bdc8
|
src/main/java/com/toomasr/sgf4j/filetree/FileFormatCell.java
|
src/main/java/com/toomasr/sgf4j/filetree/FileFormatCell.java
|
package com.toomasr.sgf4j.filetree;
import java.io.File;
import javafx.scene.control.TreeCell;
public class FileFormatCell extends TreeCell<File> {
public FileFormatCell() {
super();
}
protected void updateItem(File item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
}
else {
/*
* For a root device on a Mac getName will return an empty string
* but actually I'd like to show a slash designating the root device
*
*/
if ("".equals(item.getName()))
setText(item.getAbsolutePath());
else
setText(item.getName());
}
}
}
|
package com.toomasr.sgf4j.filetree;
import java.io.File;
import com.toomasr.sgf4j.metasystem.MetaSystem;
import com.toomasr.sgf4j.metasystem.ProblemStatus;
import javafx.scene.control.TreeCell;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class FileFormatCell extends TreeCell<File> {
private Image noneImage = new Image(getClass().getResourceAsStream("/icons/none_16x16.png"));
private Image failedImage = new Image(getClass().getResourceAsStream("/icons/failed_16x16.png"));
private Image solvedImage = new Image(getClass().getResourceAsStream("/icons/solved_16x16.png"));
public FileFormatCell() {
super();
}
protected void updateItem(File file, boolean empty) {
super.updateItem(file, empty);
if (empty || file == null) {
setText(null);
setGraphic(null);
}
else {
/*
* For a root device on a Mac getName will return an empty string
* but actually I'd like to show a slash designating the root device
*
*/
if ("".equals(file.getName()))
setText(file.getAbsolutePath());
/*
* For SGF files we want to show some custom icons.
*/
else if (file != null && file.isFile() && file.toString().toLowerCase().endsWith("sgf")) {
setText(file.getName());
if (MetaSystem.systemExists(file.toPath())) {
ProblemStatus status = MetaSystem.getStatus(file.toPath());
if (status == ProblemStatus.NONE)
setGraphic(new ImageView(noneImage));
else if (status == ProblemStatus.FAIL)
setGraphic(new ImageView(failedImage));
else
setGraphic(new ImageView(solvedImage));
}
else {
setGraphic(null);
}
}
else {
setText(file.getName());
setGraphic(null);
}
}
}
}
|
Use new icons in the tree
|
Use new icons in the tree
|
Java
|
apache-2.0
|
toomasr/sgf4j-gui,toomasr/sgf4j-gui
|
java
|
## Code Before:
package com.toomasr.sgf4j.filetree;
import java.io.File;
import javafx.scene.control.TreeCell;
public class FileFormatCell extends TreeCell<File> {
public FileFormatCell() {
super();
}
protected void updateItem(File item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
}
else {
/*
* For a root device on a Mac getName will return an empty string
* but actually I'd like to show a slash designating the root device
*
*/
if ("".equals(item.getName()))
setText(item.getAbsolutePath());
else
setText(item.getName());
}
}
}
## Instruction:
Use new icons in the tree
## Code After:
package com.toomasr.sgf4j.filetree;
import java.io.File;
import com.toomasr.sgf4j.metasystem.MetaSystem;
import com.toomasr.sgf4j.metasystem.ProblemStatus;
import javafx.scene.control.TreeCell;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class FileFormatCell extends TreeCell<File> {
private Image noneImage = new Image(getClass().getResourceAsStream("/icons/none_16x16.png"));
private Image failedImage = new Image(getClass().getResourceAsStream("/icons/failed_16x16.png"));
private Image solvedImage = new Image(getClass().getResourceAsStream("/icons/solved_16x16.png"));
public FileFormatCell() {
super();
}
protected void updateItem(File file, boolean empty) {
super.updateItem(file, empty);
if (empty || file == null) {
setText(null);
setGraphic(null);
}
else {
/*
* For a root device on a Mac getName will return an empty string
* but actually I'd like to show a slash designating the root device
*
*/
if ("".equals(file.getName()))
setText(file.getAbsolutePath());
/*
* For SGF files we want to show some custom icons.
*/
else if (file != null && file.isFile() && file.toString().toLowerCase().endsWith("sgf")) {
setText(file.getName());
if (MetaSystem.systemExists(file.toPath())) {
ProblemStatus status = MetaSystem.getStatus(file.toPath());
if (status == ProblemStatus.NONE)
setGraphic(new ImageView(noneImage));
else if (status == ProblemStatus.FAIL)
setGraphic(new ImageView(failedImage));
else
setGraphic(new ImageView(solvedImage));
}
else {
setGraphic(null);
}
}
else {
setText(file.getName());
setGraphic(null);
}
}
}
}
|
...
import java.io.File;
import com.toomasr.sgf4j.metasystem.MetaSystem;
import com.toomasr.sgf4j.metasystem.ProblemStatus;
import javafx.scene.control.TreeCell;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class FileFormatCell extends TreeCell<File> {
private Image noneImage = new Image(getClass().getResourceAsStream("/icons/none_16x16.png"));
private Image failedImage = new Image(getClass().getResourceAsStream("/icons/failed_16x16.png"));
private Image solvedImage = new Image(getClass().getResourceAsStream("/icons/solved_16x16.png"));
public FileFormatCell() {
super();
}
protected void updateItem(File file, boolean empty) {
super.updateItem(file, empty);
if (empty || file == null) {
setText(null);
setGraphic(null);
}
...
* but actually I'd like to show a slash designating the root device
*
*/
if ("".equals(file.getName()))
setText(file.getAbsolutePath());
/*
* For SGF files we want to show some custom icons.
*/
else if (file != null && file.isFile() && file.toString().toLowerCase().endsWith("sgf")) {
setText(file.getName());
if (MetaSystem.systemExists(file.toPath())) {
ProblemStatus status = MetaSystem.getStatus(file.toPath());
if (status == ProblemStatus.NONE)
setGraphic(new ImageView(noneImage));
else if (status == ProblemStatus.FAIL)
setGraphic(new ImageView(failedImage));
else
setGraphic(new ImageView(solvedImage));
}
else {
setGraphic(null);
}
}
else {
setText(file.getName());
setGraphic(null);
}
}
}
}
...
|
c6eadf70db6113900a61674fd7195a9977f428a5
|
RealmSwift/Tests/TestUtils.h
|
RealmSwift/Tests/TestUtils.h
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// 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.
//
////////////////////////////////////////////////////////////////////////////
#import <Foundation/Foundation.h>
#import <XCTest/XCTestCase.h>
// An XCTestCase that invokes each test in an autorelease pool
// Works around a swift 1.1 limitation where `super` can't be used in a block
@interface RLMAutoreleasePoolTestCase : XCTestCase
@end
FOUNDATION_EXTERN void RLMAssertThrows(XCTestCase *self, dispatch_block_t block, NSString *message, NSString *fileName, NSUInteger lineNumber);
// Forcibly deallocate the RLMRealm for the given path on the main thread
// Will cause crashes if it's alive for a reason other than being leaked by RLMAssertThrows
FOUNDATION_EXTERN void RLMDeallocateRealm(NSString *path);
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// 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.
//
////////////////////////////////////////////////////////////////////////////
#import <Foundation/Foundation.h>
#import <XCTest/XCTestCase.h>
// An XCTestCase that invokes each test in an autorelease pool
// Works around a swift 1.1 limitation where `super` can't be used in a block
@interface RLMAutoreleasePoolTestCase : XCTestCase
@end
FOUNDATION_EXTERN void RLMAssertThrows(XCTestCase *self, __attribute__((noescape)) dispatch_block_t block, NSString *message, NSString *fileName, NSUInteger lineNumber);
// Forcibly deallocate the RLMRealm for the given path on the main thread
// Will cause crashes if it's alive for a reason other than being leaked by RLMAssertThrows
FOUNDATION_EXTERN void RLMDeallocateRealm(NSString *path);
|
Annotate RLMAssertThrows' block argument with noescape
|
[Tests] Annotate RLMAssertThrows' block argument with noescape
|
C
|
apache-2.0
|
duk42111/realm-cocoa,ul7290/realm-cocoa,codyDu/realm-cocoa,kylebshr/realm-cocoa,AlexanderMazaletskiy/realm-cocoa,bugix/realm-cocoa,bestwpw/realm-cocoa,yuuki1224/realm-cocoa,nathankot/realm-cocoa,xmartlabs/realm-cocoa,lumoslabs/realm-cocoa,codyDu/realm-cocoa,lumoslabs/realm-cocoa,imjerrybao/realm-cocoa,lumoslabs/realm-cocoa,Palleas/realm-cocoa,bestwpw/realm-cocoa,kylebshr/realm-cocoa,sunzeboy/realm-cocoa,AlexanderMazaletskiy/realm-cocoa,isaacroldan/realm-cocoa,Havi4/realm-cocoa,ChenJian345/realm-cocoa,thdtjsdn/realm-cocoa,thdtjsdn/realm-cocoa,neonichu/realm-cocoa,kevinmlong/realm-cocoa,vuchau/realm-cocoa,vuchau/realm-cocoa,hejunbinlan/realm-cocoa,dilizarov/realm-cocoa,lumoslabs/realm-cocoa,tenebreux/realm-cocoa,vuchau/realm-cocoa,bestwpw/realm-cocoa,bugix/realm-cocoa,tenebreux/realm-cocoa,hejunbinlan/realm-cocoa,duk42111/realm-cocoa,ul7290/realm-cocoa,dilizarov/realm-cocoa,tenebreux/realm-cocoa,thdtjsdn/realm-cocoa,sunzeboy/realm-cocoa,bestwpw/realm-cocoa,imjerrybao/realm-cocoa,iOSCowboy/realm-cocoa,HuylensHu/realm-cocoa,yuuki1224/realm-cocoa,Palleas/realm-cocoa,zilaiyedaren/realm-cocoa,ul7290/realm-cocoa,sunfei/realm-cocoa,Palleas/realm-cocoa,kevinmlong/realm-cocoa,neonichu/realm-cocoa,ChenJian345/realm-cocoa,zilaiyedaren/realm-cocoa,iOSCowboy/realm-cocoa,sunzeboy/realm-cocoa,ChenJian345/realm-cocoa,xmartlabs/realm-cocoa,kylebshr/realm-cocoa,duk42111/realm-cocoa,sunfei/realm-cocoa,isaacroldan/realm-cocoa,isaacroldan/realm-cocoa,zilaiyedaren/realm-cocoa,nathankot/realm-cocoa,iOS--wsl--victor/realm-cocoa,sunzeboy/realm-cocoa,iOSCowboy/realm-cocoa,isaacroldan/realm-cocoa,brasbug/realm-cocoa,tenebreux/realm-cocoa,iOS--wsl--victor/realm-cocoa,Havi4/realm-cocoa,Havi4/realm-cocoa,iOS--wsl--victor/realm-cocoa,iOSCowboy/realm-cocoa,sunzeboy/realm-cocoa,kevinmlong/realm-cocoa,isaacroldan/realm-cocoa,lumoslabs/realm-cocoa,neonichu/realm-cocoa,codyDu/realm-cocoa,ul7290/realm-cocoa,nathankot/realm-cocoa,hejunbinlan/realm-cocoa,brasbug/realm-cocoa,codyDu/realm-cocoa,iOS--wsl--victor/realm-cocoa,yuuki1224/realm-cocoa,zilaiyedaren/realm-cocoa,vuchau/realm-cocoa,imjerrybao/realm-cocoa,kylebshr/realm-cocoa,dilizarov/realm-cocoa,HuylensHu/realm-cocoa,kylebshr/realm-cocoa,zilaiyedaren/realm-cocoa,Havi4/realm-cocoa,hejunbinlan/realm-cocoa,brasbug/realm-cocoa,HuylensHu/realm-cocoa,hejunbinlan/realm-cocoa,codyDu/realm-cocoa,Palleas/realm-cocoa,Palleas/realm-cocoa,AlexanderMazaletskiy/realm-cocoa,HuylensHu/realm-cocoa,bestwpw/realm-cocoa,xmartlabs/realm-cocoa,ul7290/realm-cocoa,nathankot/realm-cocoa,duk42111/realm-cocoa,yuuki1224/realm-cocoa,bugix/realm-cocoa,thdtjsdn/realm-cocoa,Havi4/realm-cocoa,bugix/realm-cocoa,HuylensHu/realm-cocoa,ChenJian345/realm-cocoa,sunfei/realm-cocoa,xmartlabs/realm-cocoa,imjerrybao/realm-cocoa,neonichu/realm-cocoa,brasbug/realm-cocoa,bugix/realm-cocoa,sunfei/realm-cocoa,iOSCowboy/realm-cocoa,neonichu/realm-cocoa,yuuki1224/realm-cocoa,ChenJian345/realm-cocoa,duk42111/realm-cocoa,AlexanderMazaletskiy/realm-cocoa,kevinmlong/realm-cocoa,kevinmlong/realm-cocoa,dilizarov/realm-cocoa,iOS--wsl--victor/realm-cocoa,tenebreux/realm-cocoa,dilizarov/realm-cocoa,imjerrybao/realm-cocoa,nathankot/realm-cocoa,sunfei/realm-cocoa,xmartlabs/realm-cocoa,thdtjsdn/realm-cocoa,AlexanderMazaletskiy/realm-cocoa,vuchau/realm-cocoa,brasbug/realm-cocoa
|
c
|
## Code Before:
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// 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.
//
////////////////////////////////////////////////////////////////////////////
#import <Foundation/Foundation.h>
#import <XCTest/XCTestCase.h>
// An XCTestCase that invokes each test in an autorelease pool
// Works around a swift 1.1 limitation where `super` can't be used in a block
@interface RLMAutoreleasePoolTestCase : XCTestCase
@end
FOUNDATION_EXTERN void RLMAssertThrows(XCTestCase *self, dispatch_block_t block, NSString *message, NSString *fileName, NSUInteger lineNumber);
// Forcibly deallocate the RLMRealm for the given path on the main thread
// Will cause crashes if it's alive for a reason other than being leaked by RLMAssertThrows
FOUNDATION_EXTERN void RLMDeallocateRealm(NSString *path);
## Instruction:
[Tests] Annotate RLMAssertThrows' block argument with noescape
## Code After:
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// 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.
//
////////////////////////////////////////////////////////////////////////////
#import <Foundation/Foundation.h>
#import <XCTest/XCTestCase.h>
// An XCTestCase that invokes each test in an autorelease pool
// Works around a swift 1.1 limitation where `super` can't be used in a block
@interface RLMAutoreleasePoolTestCase : XCTestCase
@end
FOUNDATION_EXTERN void RLMAssertThrows(XCTestCase *self, __attribute__((noescape)) dispatch_block_t block, NSString *message, NSString *fileName, NSUInteger lineNumber);
// Forcibly deallocate the RLMRealm for the given path on the main thread
// Will cause crashes if it's alive for a reason other than being leaked by RLMAssertThrows
FOUNDATION_EXTERN void RLMDeallocateRealm(NSString *path);
|
...
@interface RLMAutoreleasePoolTestCase : XCTestCase
@end
FOUNDATION_EXTERN void RLMAssertThrows(XCTestCase *self, __attribute__((noescape)) dispatch_block_t block, NSString *message, NSString *fileName, NSUInteger lineNumber);
// Forcibly deallocate the RLMRealm for the given path on the main thread
// Will cause crashes if it's alive for a reason other than being leaked by RLMAssertThrows
...
|
36fb88bf5f60a656defaafc7626c373e59a70e05
|
tests/util.py
|
tests/util.py
|
from __future__ import absolute_import
from __future__ import unicode_literals
import codecs
import contextlib
import functools
import os
class Env(object):
def __init__(self):
self.user = os.getenv('AWS_ACCESS_KEY_ID', None)
assert self.user, \
'Required environment variable `AWS_ACCESS_KEY_ID` not found.'
self.password = os.getenv('AWS_SECRET_ACCESS_KEY', None)
assert self.password, \
'Required environment variable `AWS_SECRET_ACCESS_KEY` not found.'
self.region_name = os.getenv('AWS_DEFAULT_REGION', None)
assert self.region_name, \
'Required environment variable `AWS_DEFAULT_REGION` not found.'
self.s3_staging_dir = os.getenv('AWS_ATHENA_S3_STAGING_DIR', None)
assert self.s3_staging_dir, \
'Required environment variable `AWS_ATHENA_S3_STAGING_DIR` not found.'
def with_cursor(fn):
@functools.wraps(fn)
def wrapped_fn(self, *args, **kwargs):
with contextlib.closing(self.connect()) as conn:
with conn.cursor() as cursor:
fn(self, cursor, *args, **kwargs)
return wrapped_fn
def read_query(path):
with codecs.open(path, 'rb', 'utf-8') as f:
query = f.read()
return [q.strip() for q in query.split(';') if q and q.strip()]
|
from __future__ import absolute_import
from __future__ import unicode_literals
import codecs
import contextlib
import functools
import os
class Env(object):
def __init__(self):
# self.user = os.getenv('AWS_ACCESS_KEY_ID', None)
# assert self.user, \
# 'Required environment variable `AWS_ACCESS_KEY_ID` not found.'
# self.password = os.getenv('AWS_SECRET_ACCESS_KEY', None)
# assert self.password, \
# 'Required environment variable `AWS_SECRET_ACCESS_KEY` not found.'
self.region_name = os.getenv('AWS_DEFAULT_REGION', None)
assert self.region_name, \
'Required environment variable `AWS_DEFAULT_REGION` not found.'
self.s3_staging_dir = os.getenv('AWS_ATHENA_S3_STAGING_DIR', None)
assert self.s3_staging_dir, \
'Required environment variable `AWS_ATHENA_S3_STAGING_DIR` not found.'
def with_cursor(fn):
@functools.wraps(fn)
def wrapped_fn(self, *args, **kwargs):
with contextlib.closing(self.connect()) as conn:
with conn.cursor() as cursor:
fn(self, cursor, *args, **kwargs)
return wrapped_fn
def read_query(path):
with codecs.open(path, 'rb', 'utf-8') as f:
query = f.read()
return [q.strip() for q in query.split(';') if q and q.strip()]
|
Comment out assertion of environment variables(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY). When test fail, all environment variables appear in the error log in some case. Use credential file(~/.aws/credential) configuration for testing.
|
Comment out assertion of environment variables(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY).
When test fail, all environment variables appear in the error log in some case.
Use credential file(~/.aws/credential) configuration for testing.
|
Python
|
mit
|
laughingman7743/PyAthenaJDBC,laughingman7743/PyAthenaJDBC
|
python
|
## Code Before:
from __future__ import absolute_import
from __future__ import unicode_literals
import codecs
import contextlib
import functools
import os
class Env(object):
def __init__(self):
self.user = os.getenv('AWS_ACCESS_KEY_ID', None)
assert self.user, \
'Required environment variable `AWS_ACCESS_KEY_ID` not found.'
self.password = os.getenv('AWS_SECRET_ACCESS_KEY', None)
assert self.password, \
'Required environment variable `AWS_SECRET_ACCESS_KEY` not found.'
self.region_name = os.getenv('AWS_DEFAULT_REGION', None)
assert self.region_name, \
'Required environment variable `AWS_DEFAULT_REGION` not found.'
self.s3_staging_dir = os.getenv('AWS_ATHENA_S3_STAGING_DIR', None)
assert self.s3_staging_dir, \
'Required environment variable `AWS_ATHENA_S3_STAGING_DIR` not found.'
def with_cursor(fn):
@functools.wraps(fn)
def wrapped_fn(self, *args, **kwargs):
with contextlib.closing(self.connect()) as conn:
with conn.cursor() as cursor:
fn(self, cursor, *args, **kwargs)
return wrapped_fn
def read_query(path):
with codecs.open(path, 'rb', 'utf-8') as f:
query = f.read()
return [q.strip() for q in query.split(';') if q and q.strip()]
## Instruction:
Comment out assertion of environment variables(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY).
When test fail, all environment variables appear in the error log in some case.
Use credential file(~/.aws/credential) configuration for testing.
## Code After:
from __future__ import absolute_import
from __future__ import unicode_literals
import codecs
import contextlib
import functools
import os
class Env(object):
def __init__(self):
# self.user = os.getenv('AWS_ACCESS_KEY_ID', None)
# assert self.user, \
# 'Required environment variable `AWS_ACCESS_KEY_ID` not found.'
# self.password = os.getenv('AWS_SECRET_ACCESS_KEY', None)
# assert self.password, \
# 'Required environment variable `AWS_SECRET_ACCESS_KEY` not found.'
self.region_name = os.getenv('AWS_DEFAULT_REGION', None)
assert self.region_name, \
'Required environment variable `AWS_DEFAULT_REGION` not found.'
self.s3_staging_dir = os.getenv('AWS_ATHENA_S3_STAGING_DIR', None)
assert self.s3_staging_dir, \
'Required environment variable `AWS_ATHENA_S3_STAGING_DIR` not found.'
def with_cursor(fn):
@functools.wraps(fn)
def wrapped_fn(self, *args, **kwargs):
with contextlib.closing(self.connect()) as conn:
with conn.cursor() as cursor:
fn(self, cursor, *args, **kwargs)
return wrapped_fn
def read_query(path):
with codecs.open(path, 'rb', 'utf-8') as f:
query = f.read()
return [q.strip() for q in query.split(';') if q and q.strip()]
|
...
class Env(object):
def __init__(self):
# self.user = os.getenv('AWS_ACCESS_KEY_ID', None)
# assert self.user, \
# 'Required environment variable `AWS_ACCESS_KEY_ID` not found.'
# self.password = os.getenv('AWS_SECRET_ACCESS_KEY', None)
# assert self.password, \
# 'Required environment variable `AWS_SECRET_ACCESS_KEY` not found.'
self.region_name = os.getenv('AWS_DEFAULT_REGION', None)
assert self.region_name, \
'Required environment variable `AWS_DEFAULT_REGION` not found.'
...
|
993414b8c0e99bf88285dd7c3f0fa0e41ab7d0d9
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
EXTRAS_REQUIRES = dict(
web=[
'bottle>=0.11',
],
test=[
'pytest>=2.2.4',
'mock>=0.8.0',
],
dev=[
'ipython>=0.13',
],
)
# Tests always depend on all other requirements, except dev
for k,v in EXTRAS_REQUIRES.iteritems():
if k == 'test' or k == 'dev':
continue
EXTRAS_REQUIRES['test'] += v
setup(
name='tle',
version='0.0.1',
description=('tle -- Glue code for TheLeanEntrepreneur between the '
'Gumroad and Kajabi APIs'
),
author='Andres Buritica',
author_email='[email protected]',
maintainer='Andres Buritica',
maintainer_email='[email protected]',
packages = find_packages(),
test_suite='nose.collector',
install_requires=[
'setuptools',
],
extras_require=EXTRAS_REQUIRES,
entry_points={
'console_scripts': [
'tle = tle.cli.glue_api:main[web]',
],
},
)
|
from setuptools import setup, find_packages
EXTRAS_REQUIRES = dict(
web=[
'bottle>=0.11',
'paste>=1.7.5.1',
],
mongo=[
'pymongo>=2.3',
],
test=[
'pytest>=2.2.4',
'mock>=0.8.0',
],
dev=[
'ipython>=0.13',
],
)
# Tests always depend on all other requirements, except dev
for k,v in EXTRAS_REQUIRES.iteritems():
if k == 'test' or k == 'dev':
continue
EXTRAS_REQUIRES['test'] += v
setup(
name='tle',
version='0.0.1',
description=('tle -- Glue code for TheLeanEntrepreneur between the '
'Gumroad and Kajabi APIs'
),
author='Andres Buritica',
author_email='[email protected]',
maintainer='Andres Buritica',
maintainer_email='[email protected]',
packages = find_packages(),
test_suite='nose.collector',
install_requires=[
'setuptools',
],
extras_require=EXTRAS_REQUIRES,
entry_points={
'console_scripts': [
'tle = tle.cli.glue_api:main[web]',
],
},
)
|
Add paste and pymongo dependencies
|
Add paste and pymongo dependencies
|
Python
|
mit
|
thelinuxkid/gumjabi
|
python
|
## Code Before:
from setuptools import setup, find_packages
EXTRAS_REQUIRES = dict(
web=[
'bottle>=0.11',
],
test=[
'pytest>=2.2.4',
'mock>=0.8.0',
],
dev=[
'ipython>=0.13',
],
)
# Tests always depend on all other requirements, except dev
for k,v in EXTRAS_REQUIRES.iteritems():
if k == 'test' or k == 'dev':
continue
EXTRAS_REQUIRES['test'] += v
setup(
name='tle',
version='0.0.1',
description=('tle -- Glue code for TheLeanEntrepreneur between the '
'Gumroad and Kajabi APIs'
),
author='Andres Buritica',
author_email='[email protected]',
maintainer='Andres Buritica',
maintainer_email='[email protected]',
packages = find_packages(),
test_suite='nose.collector',
install_requires=[
'setuptools',
],
extras_require=EXTRAS_REQUIRES,
entry_points={
'console_scripts': [
'tle = tle.cli.glue_api:main[web]',
],
},
)
## Instruction:
Add paste and pymongo dependencies
## Code After:
from setuptools import setup, find_packages
EXTRAS_REQUIRES = dict(
web=[
'bottle>=0.11',
'paste>=1.7.5.1',
],
mongo=[
'pymongo>=2.3',
],
test=[
'pytest>=2.2.4',
'mock>=0.8.0',
],
dev=[
'ipython>=0.13',
],
)
# Tests always depend on all other requirements, except dev
for k,v in EXTRAS_REQUIRES.iteritems():
if k == 'test' or k == 'dev':
continue
EXTRAS_REQUIRES['test'] += v
setup(
name='tle',
version='0.0.1',
description=('tle -- Glue code for TheLeanEntrepreneur between the '
'Gumroad and Kajabi APIs'
),
author='Andres Buritica',
author_email='[email protected]',
maintainer='Andres Buritica',
maintainer_email='[email protected]',
packages = find_packages(),
test_suite='nose.collector',
install_requires=[
'setuptools',
],
extras_require=EXTRAS_REQUIRES,
entry_points={
'console_scripts': [
'tle = tle.cli.glue_api:main[web]',
],
},
)
|
// ... existing code ...
EXTRAS_REQUIRES = dict(
web=[
'bottle>=0.11',
'paste>=1.7.5.1',
],
mongo=[
'pymongo>=2.3',
],
test=[
'pytest>=2.2.4',
'mock>=0.8.0',
// ... rest of the code ...
|
e563e8f8f1af691c4c9aa2f6177fbf2c8e2a4855
|
della/user_manager/draw_service.py
|
della/user_manager/draw_service.py
|
import json
from django.conf import settings
def _get_default_file_content():
return {'status': False}
def _write_status_file():
file_path = settings.STATUS_FILE
with open(file_path, 'w') as f:
json.dump({'status': True}, f)
return True
def _get_status_file():
file_path = settings.STATUS_FILE
try:
with open(file_path) as f:
return json.load(f)
except FileNotFoundError:
with open(file_path, 'w') as f:
response = _get_default_file_content()
json.dump(response, f)
return response
def get_draw_status():
return _get_status_file()['status']
def flip_draw_status():
if not _get_status_file()['status']:
return _write_status_file()
return True
|
import json
import random
from collections import deque
from django.conf import settings
from django.contrib.auth.models import User
def _get_default_file_content():
return {'status': False}
def _write_status_file():
file_path = settings.STATUS_FILE
with open(file_path, 'w') as f:
json.dump({'status': True}, f)
return True
def _get_status_file():
file_path = settings.STATUS_FILE
try:
with open(file_path) as f:
return json.load(f)
except FileNotFoundError:
with open(file_path, 'w') as f:
response = _get_default_file_content()
json.dump(response, f)
return response
def get_draw_status():
return _get_status_file()['status']
def flip_draw_status():
if not _get_status_file()['status']:
return _write_status_file()
return True
def draw_names():
pass
def make_pairs(user_ids):
while True:
pairs = _get_pairs(user_ids=user_ids)
if _is_valid_pair(pairs=pairs):
break
return pairs
def _get_pairs(user_ids):
user_ids_copy = user_ids.copy()
random.shuffle(user_ids_copy)
pairs = deque(user_ids_copy)
pairs.rotate()
return list(zip(user_ids, user_ids_copy))
def _is_valid_pair(pairs):
"""
Checks if the pair and list of pairs is valid. A pair is invalid if both
santa and santee are same i.e. (1, 1)
"""
for pair in pairs:
if pair[0] == pair[1]:
return False
return True
|
Add helper funtions for making pairs
|
Add helper funtions for making pairs
|
Python
|
mit
|
avinassh/della,avinassh/della,avinassh/della
|
python
|
## Code Before:
import json
from django.conf import settings
def _get_default_file_content():
return {'status': False}
def _write_status_file():
file_path = settings.STATUS_FILE
with open(file_path, 'w') as f:
json.dump({'status': True}, f)
return True
def _get_status_file():
file_path = settings.STATUS_FILE
try:
with open(file_path) as f:
return json.load(f)
except FileNotFoundError:
with open(file_path, 'w') as f:
response = _get_default_file_content()
json.dump(response, f)
return response
def get_draw_status():
return _get_status_file()['status']
def flip_draw_status():
if not _get_status_file()['status']:
return _write_status_file()
return True
## Instruction:
Add helper funtions for making pairs
## Code After:
import json
import random
from collections import deque
from django.conf import settings
from django.contrib.auth.models import User
def _get_default_file_content():
return {'status': False}
def _write_status_file():
file_path = settings.STATUS_FILE
with open(file_path, 'w') as f:
json.dump({'status': True}, f)
return True
def _get_status_file():
file_path = settings.STATUS_FILE
try:
with open(file_path) as f:
return json.load(f)
except FileNotFoundError:
with open(file_path, 'w') as f:
response = _get_default_file_content()
json.dump(response, f)
return response
def get_draw_status():
return _get_status_file()['status']
def flip_draw_status():
if not _get_status_file()['status']:
return _write_status_file()
return True
def draw_names():
pass
def make_pairs(user_ids):
while True:
pairs = _get_pairs(user_ids=user_ids)
if _is_valid_pair(pairs=pairs):
break
return pairs
def _get_pairs(user_ids):
user_ids_copy = user_ids.copy()
random.shuffle(user_ids_copy)
pairs = deque(user_ids_copy)
pairs.rotate()
return list(zip(user_ids, user_ids_copy))
def _is_valid_pair(pairs):
"""
Checks if the pair and list of pairs is valid. A pair is invalid if both
santa and santee are same i.e. (1, 1)
"""
for pair in pairs:
if pair[0] == pair[1]:
return False
return True
|
...
import json
import random
from collections import deque
from django.conf import settings
from django.contrib.auth.models import User
def _get_default_file_content():
...
if not _get_status_file()['status']:
return _write_status_file()
return True
def draw_names():
pass
def make_pairs(user_ids):
while True:
pairs = _get_pairs(user_ids=user_ids)
if _is_valid_pair(pairs=pairs):
break
return pairs
def _get_pairs(user_ids):
user_ids_copy = user_ids.copy()
random.shuffle(user_ids_copy)
pairs = deque(user_ids_copy)
pairs.rotate()
return list(zip(user_ids, user_ids_copy))
def _is_valid_pair(pairs):
"""
Checks if the pair and list of pairs is valid. A pair is invalid if both
santa and santee are same i.e. (1, 1)
"""
for pair in pairs:
if pair[0] == pair[1]:
return False
return True
...
|
bb47d7db349b6de54440b2298fb0c6377a4a7e0a
|
thingc/thingc/thingc/NumberInstance.h
|
thingc/thingc/thingc/NumberInstance.h
|
class NumberInstance : public ThingInstance {
public:
NumberInstance(int val) : val(val), ThingInstance(NumberInstance::methods) {};
virtual std::string text() const override {
return std::to_string(val);
}
const int val;
static const std::vector<InternalMethod> methods;
};
|
class NumberInstance : public ThingInstance {
public:
NumberInstance(int val) : val(val), ThingInstance(NumberInstance::methods) {};
virtual std::string text() const override {
return std::to_string(val);
}
static void add() {
auto lhs = static_cast<NumberInstance*>(Program::pop().get());
auto rhs = static_cast<NumberInstance*>(Program::pop().get());
auto ptr = PThingInstance(new NumberInstance(lhs->val + rhs->val));
Program::push(ptr);
}
const int val;
static const std::vector<InternalMethod> methods;
};
|
Implement + support in numbers
|
Implement + support in numbers
|
C
|
mit
|
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
|
c
|
## Code Before:
class NumberInstance : public ThingInstance {
public:
NumberInstance(int val) : val(val), ThingInstance(NumberInstance::methods) {};
virtual std::string text() const override {
return std::to_string(val);
}
const int val;
static const std::vector<InternalMethod> methods;
};
## Instruction:
Implement + support in numbers
## Code After:
class NumberInstance : public ThingInstance {
public:
NumberInstance(int val) : val(val), ThingInstance(NumberInstance::methods) {};
virtual std::string text() const override {
return std::to_string(val);
}
static void add() {
auto lhs = static_cast<NumberInstance*>(Program::pop().get());
auto rhs = static_cast<NumberInstance*>(Program::pop().get());
auto ptr = PThingInstance(new NumberInstance(lhs->val + rhs->val));
Program::push(ptr);
}
const int val;
static const std::vector<InternalMethod> methods;
};
|
...
return std::to_string(val);
}
static void add() {
auto lhs = static_cast<NumberInstance*>(Program::pop().get());
auto rhs = static_cast<NumberInstance*>(Program::pop().get());
auto ptr = PThingInstance(new NumberInstance(lhs->val + rhs->val));
Program::push(ptr);
}
const int val;
static const std::vector<InternalMethod> methods;
...
|
8a7b6be29b3a839ba8e5c2cb33322d90d51d5fc4
|
karbor/tests/unit/conf_fixture.py
|
karbor/tests/unit/conf_fixture.py
|
import os
from oslo_config import cfg
CONF = cfg.CONF
CONF.import_opt('policy_file', 'karbor.policy', group='oslo_policy')
def set_defaults(conf):
conf.set_default('connection', 'sqlite://', group='database')
conf.set_default('sqlite_synchronous', False, group='database')
conf.set_default('policy_file', 'karbor.tests.unit/policy.json',
group='oslo_policy')
conf.set_default('policy_dirs', [], group='oslo_policy')
conf.set_default('auth_strategy', 'noauth')
conf.set_default('state_path', os.path.abspath(
os.path.join(os.path.dirname(__file__), '..', '..', '..')))
conf.set_default('provider_config_dir',
os.path.join(os.path.dirname(__file__), 'fake_providers'))
|
import os
from oslo_config import cfg
CONF = cfg.CONF
CONF.import_opt('policy_file', 'karbor.policy', group='oslo_policy')
CONF.import_opt('provider_config_dir', 'karbor.services.protection.provider')
def set_defaults(conf):
conf.set_default('connection', 'sqlite://', group='database')
conf.set_default('sqlite_synchronous', False, group='database')
conf.set_default('policy_file', 'karbor.tests.unit/policy.json',
group='oslo_policy')
conf.set_default('policy_dirs', [], group='oslo_policy')
conf.set_default('auth_strategy', 'noauth')
conf.set_default('state_path', os.path.abspath(
os.path.join(os.path.dirname(__file__), '..', '..', '..')))
conf.set_default('provider_config_dir',
os.path.join(os.path.dirname(__file__), 'fake_providers'))
|
Fix loading 'provider_config_dir' opt error
|
Fix loading 'provider_config_dir' opt error
When run unit test using 'ostestr --pdb' command. it may get
an error that can not find the config opt 'provider_config_dir'.
Change-Id: Ibc1c693a1531c791ad434ff56ee349ba3afb3d63
Closes-Bug: #1649443
|
Python
|
apache-2.0
|
openstack/smaug,openstack/smaug
|
python
|
## Code Before:
import os
from oslo_config import cfg
CONF = cfg.CONF
CONF.import_opt('policy_file', 'karbor.policy', group='oslo_policy')
def set_defaults(conf):
conf.set_default('connection', 'sqlite://', group='database')
conf.set_default('sqlite_synchronous', False, group='database')
conf.set_default('policy_file', 'karbor.tests.unit/policy.json',
group='oslo_policy')
conf.set_default('policy_dirs', [], group='oslo_policy')
conf.set_default('auth_strategy', 'noauth')
conf.set_default('state_path', os.path.abspath(
os.path.join(os.path.dirname(__file__), '..', '..', '..')))
conf.set_default('provider_config_dir',
os.path.join(os.path.dirname(__file__), 'fake_providers'))
## Instruction:
Fix loading 'provider_config_dir' opt error
When run unit test using 'ostestr --pdb' command. it may get
an error that can not find the config opt 'provider_config_dir'.
Change-Id: Ibc1c693a1531c791ad434ff56ee349ba3afb3d63
Closes-Bug: #1649443
## Code After:
import os
from oslo_config import cfg
CONF = cfg.CONF
CONF.import_opt('policy_file', 'karbor.policy', group='oslo_policy')
CONF.import_opt('provider_config_dir', 'karbor.services.protection.provider')
def set_defaults(conf):
conf.set_default('connection', 'sqlite://', group='database')
conf.set_default('sqlite_synchronous', False, group='database')
conf.set_default('policy_file', 'karbor.tests.unit/policy.json',
group='oslo_policy')
conf.set_default('policy_dirs', [], group='oslo_policy')
conf.set_default('auth_strategy', 'noauth')
conf.set_default('state_path', os.path.abspath(
os.path.join(os.path.dirname(__file__), '..', '..', '..')))
conf.set_default('provider_config_dir',
os.path.join(os.path.dirname(__file__), 'fake_providers'))
|
...
CONF = cfg.CONF
CONF.import_opt('policy_file', 'karbor.policy', group='oslo_policy')
CONF.import_opt('provider_config_dir', 'karbor.services.protection.provider')
def set_defaults(conf):
...
|
2044e5ed29fd356b17e437fb360c3c5311f701b9
|
src/forager/server/ListManager.java
|
src/forager/server/ListManager.java
|
package forager.server;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Handles the active and completed task lists and allows them to be flushed
* and synced to disk.
*
* @author malensek
*/
public class ListManager {
public static final String DEFAULT_LIST_NAME = "tasklist";
private FileOutputStream taskListOut;
private PrintWriter taskListWriter;
private FileOutputStream completedListOut;
private PrintWriter completedListWriter;
public ListManager() throws IOException {
this(DEFAULT_LIST_NAME);
}
public ListManager(String taskListName) throws IOException {
taskListOut = new FileOutputStream(taskListName, true);
taskListWriter = new PrintWriter(
new BufferedOutputStream(taskListOut));
String completedName = taskListName + ".done";
completedListOut = new FileOutputStream(completedName, true);
completedListWriter = new PrintWriter(
new BufferedOutputStream(completedListOut));
}
public void addTask(String command) {
taskListWriter.println(command);
}
public void addCompletedTask(String command) {
completedListWriter.println(command);
}
public void sync() throws IOException {
taskListWriter.flush();
taskListOut.getFD().sync();
}
}
|
package forager.server;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Handles the active and completed task lists and allows them to be flushed
* and synced to disk.
*
* @author malensek
*/
public class ListManager {
public static final String DEFAULT_LIST_NAME = "tasklist";
private FileOutputStream taskListOut;
private PrintWriter taskListWriter;
private FileOutputStream completedListOut;
private PrintWriter completedListWriter;
public ListManager() throws IOException {
this(DEFAULT_LIST_NAME);
}
public ListManager(String taskListName) throws IOException {
taskListOut = new FileOutputStream(taskListName, true);
taskListWriter = new PrintWriter(
new BufferedOutputStream(taskListOut));
String completedName = taskListName + ".done";
completedListOut = new FileOutputStream(completedName, true);
completedListWriter = new PrintWriter(
new BufferedOutputStream(completedListOut));
}
public void addTask(String command) {
taskListWriter.println(command);
}
public void addCompletedTask(String command) {
completedListWriter.println(command);
}
public void sync() throws IOException {
taskListWriter.flush();
taskListOut.getFD().sync();
}
public static boolean listsExist() {
return listsExist(DEFAULT_LIST_NAME);
}
public static boolean listsExist(String taskListName) {
File listFile = new File(taskListName);
File doneFile = new File(taskListName + ".done");
return (listFile.exists() || doneFile.exists());
}
}
|
Add checks for list files
|
Add checks for list files
|
Java
|
bsd-2-clause
|
malensek/forager,malensek/forager
|
java
|
## Code Before:
package forager.server;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Handles the active and completed task lists and allows them to be flushed
* and synced to disk.
*
* @author malensek
*/
public class ListManager {
public static final String DEFAULT_LIST_NAME = "tasklist";
private FileOutputStream taskListOut;
private PrintWriter taskListWriter;
private FileOutputStream completedListOut;
private PrintWriter completedListWriter;
public ListManager() throws IOException {
this(DEFAULT_LIST_NAME);
}
public ListManager(String taskListName) throws IOException {
taskListOut = new FileOutputStream(taskListName, true);
taskListWriter = new PrintWriter(
new BufferedOutputStream(taskListOut));
String completedName = taskListName + ".done";
completedListOut = new FileOutputStream(completedName, true);
completedListWriter = new PrintWriter(
new BufferedOutputStream(completedListOut));
}
public void addTask(String command) {
taskListWriter.println(command);
}
public void addCompletedTask(String command) {
completedListWriter.println(command);
}
public void sync() throws IOException {
taskListWriter.flush();
taskListOut.getFD().sync();
}
}
## Instruction:
Add checks for list files
## Code After:
package forager.server;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Handles the active and completed task lists and allows them to be flushed
* and synced to disk.
*
* @author malensek
*/
public class ListManager {
public static final String DEFAULT_LIST_NAME = "tasklist";
private FileOutputStream taskListOut;
private PrintWriter taskListWriter;
private FileOutputStream completedListOut;
private PrintWriter completedListWriter;
public ListManager() throws IOException {
this(DEFAULT_LIST_NAME);
}
public ListManager(String taskListName) throws IOException {
taskListOut = new FileOutputStream(taskListName, true);
taskListWriter = new PrintWriter(
new BufferedOutputStream(taskListOut));
String completedName = taskListName + ".done";
completedListOut = new FileOutputStream(completedName, true);
completedListWriter = new PrintWriter(
new BufferedOutputStream(completedListOut));
}
public void addTask(String command) {
taskListWriter.println(command);
}
public void addCompletedTask(String command) {
completedListWriter.println(command);
}
public void sync() throws IOException {
taskListWriter.flush();
taskListOut.getFD().sync();
}
public static boolean listsExist() {
return listsExist(DEFAULT_LIST_NAME);
}
public static boolean listsExist(String taskListName) {
File listFile = new File(taskListName);
File doneFile = new File(taskListName + ".done");
return (listFile.exists() || doneFile.exists());
}
}
|
# ... existing code ...
taskListWriter.flush();
taskListOut.getFD().sync();
}
public static boolean listsExist() {
return listsExist(DEFAULT_LIST_NAME);
}
public static boolean listsExist(String taskListName) {
File listFile = new File(taskListName);
File doneFile = new File(taskListName + ".done");
return (listFile.exists() || doneFile.exists());
}
}
# ... rest of the code ...
|
5c30173731d058b51d7a94238a3ccf5984e2e790
|
echo_server.py
|
echo_server.py
|
import socket
def main():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
socket.IPPROTO_IP)
server_socket.bind(('127.0.0.1', 50000))
server_socket.listen(1)
conn, addr = server_socket.accept()
msg = conn.recv(1024)
conn.sendall(msg)
conn.shutdown(socket.SHUT_WR)
conn.close()
if __name__ == '__main__':
main()
|
import socket
def main():
server_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
server_socket.bind(('127.0.0.1', 50000))
server_socket.listen(1)
conn, addr = server_socket.accept()
msg = conn.recv(1024)
conn.sendall(msg)
conn.shutdown(socket.SHUT_WR)
conn.close()
if __name__ == '__main__':
main()
|
Change format to satify pedantic linter
|
Change format to satify pedantic linter
|
Python
|
mit
|
charlieRode/network_tools
|
python
|
## Code Before:
import socket
def main():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
socket.IPPROTO_IP)
server_socket.bind(('127.0.0.1', 50000))
server_socket.listen(1)
conn, addr = server_socket.accept()
msg = conn.recv(1024)
conn.sendall(msg)
conn.shutdown(socket.SHUT_WR)
conn.close()
if __name__ == '__main__':
main()
## Instruction:
Change format to satify pedantic linter
## Code After:
import socket
def main():
server_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
server_socket.bind(('127.0.0.1', 50000))
server_socket.listen(1)
conn, addr = server_socket.accept()
msg = conn.recv(1024)
conn.sendall(msg)
conn.shutdown(socket.SHUT_WR)
conn.close()
if __name__ == '__main__':
main()
|
...
def main():
server_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
server_socket.bind(('127.0.0.1', 50000))
server_socket.listen(1)
conn, addr = server_socket.accept()
...
|
1d26fddd3fb1581138117b2fbeeb21877bc48883
|
sample_app/utils.py
|
sample_app/utils.py
|
import tornado.web
import ipy_table
from transperth.location import Location
class BaseRequestHandler(tornado.web.RequestHandler):
@property
def args(self):
args = self.request.arguments
return {
k: [sv.decode() for sv in v]
for k, v in args.items()
}
def get_location(self, key):
return Location.from_location(
self.get_argument(key)
)
def fares_to_table(fares):
keys, values = zip(*fares.items())
table_rows = [['Fare Type']]
table_rows[-1].extend(key.title() for key in keys)
for key in values[0].keys():
table_rows.append([key.title()])
table_rows[-1].extend(
ticket_type[key]
for ticket_type in values
)
table = ipy_table.make_table(table_rows)
table.apply_theme('basic')
return table
|
import tornado.web
import ipy_table
from transperth.location import Location
class BaseRequestHandler(tornado.web.RequestHandler):
@property
def args(self):
args = self.request.arguments
return {
k: [sv.decode() for sv in v]
for k, v in args.items()
}
def get_location(self, key):
return Location.from_location(
self.get_argument(key)
)
def fares_to_table(fares):
keys, values = zip(*fares.items())
table_rows = [['Fare Type']]
table_rows[-1].extend(key.title() for key in keys)
for key in sorted(values[0].keys()):
table_rows.append([key.title()])
table_rows[-1].extend(
'${}'.format(ticket_type[key])
for ticket_type in values
)
table = ipy_table.make_table(table_rows)
table.apply_theme('basic')
return table
|
Add dollar sign to fares, sort by fare type
|
Add dollar sign to fares, sort by fare type
|
Python
|
mit
|
Mause/pytransperth,Mause/pytransperth
|
python
|
## Code Before:
import tornado.web
import ipy_table
from transperth.location import Location
class BaseRequestHandler(tornado.web.RequestHandler):
@property
def args(self):
args = self.request.arguments
return {
k: [sv.decode() for sv in v]
for k, v in args.items()
}
def get_location(self, key):
return Location.from_location(
self.get_argument(key)
)
def fares_to_table(fares):
keys, values = zip(*fares.items())
table_rows = [['Fare Type']]
table_rows[-1].extend(key.title() for key in keys)
for key in values[0].keys():
table_rows.append([key.title()])
table_rows[-1].extend(
ticket_type[key]
for ticket_type in values
)
table = ipy_table.make_table(table_rows)
table.apply_theme('basic')
return table
## Instruction:
Add dollar sign to fares, sort by fare type
## Code After:
import tornado.web
import ipy_table
from transperth.location import Location
class BaseRequestHandler(tornado.web.RequestHandler):
@property
def args(self):
args = self.request.arguments
return {
k: [sv.decode() for sv in v]
for k, v in args.items()
}
def get_location(self, key):
return Location.from_location(
self.get_argument(key)
)
def fares_to_table(fares):
keys, values = zip(*fares.items())
table_rows = [['Fare Type']]
table_rows[-1].extend(key.title() for key in keys)
for key in sorted(values[0].keys()):
table_rows.append([key.title()])
table_rows[-1].extend(
'${}'.format(ticket_type[key])
for ticket_type in values
)
table = ipy_table.make_table(table_rows)
table.apply_theme('basic')
return table
|
// ... existing code ...
table_rows = [['Fare Type']]
table_rows[-1].extend(key.title() for key in keys)
for key in sorted(values[0].keys()):
table_rows.append([key.title()])
table_rows[-1].extend(
'${}'.format(ticket_type[key])
for ticket_type in values
)
// ... rest of the code ...
|
c83e0134104d4ee6de9a3e5b7d0e34be2a684daa
|
tests/test_shared.py
|
tests/test_shared.py
|
from flask.ext.testing import TestCase
import os
import tempfile
import shutil
import websmash
class ModelTestCase(TestCase):
def create_app(self):
self.app = websmash.app
self.dl = websmash.dl
self.app.config['TESTING'] = True
self.app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite://"
websmash.mail.suppress = True
return self.app
def setUp(self):
self.db = websmash.db
self.db.create_all()
def tearDown(self):
self.db.session.remove()
self.db.drop_all()
class WebsmashTestCase(ModelTestCase):
def create_app(self):
return super(WebsmashTestCase, self).create_app()
def setUp(self):
super(WebsmashTestCase, self).setUp()
self.tmpdir = tempfile.mkdtemp()
(fd, self.tmp_name) = tempfile.mkstemp(dir=self.tmpdir, suffix='.fa')
self.tmp_file = os.fdopen(fd, 'w+b')
self.tmp_file.write('>test\nATGACCGAGAGTACATAG\n')
self.app.config['RESULTS_PATH'] = self.tmpdir
def tearDown(self):
super(WebsmashTestCase, self).tearDown()
self.tmp_file.close()
shutil.rmtree(self.tmpdir)
|
from flask.ext.testing import TestCase
import os
import tempfile
import shutil
import websmash
class ModelTestCase(TestCase):
def create_app(self):
self.app = websmash.app
self.dl = websmash.dl
self.app.config['TESTING'] = True
self.app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite://"
websmash.mail.suppress = True
return self.app
def setUp(self):
self.db = websmash.db
self.db.create_all()
def tearDown(self):
self.db.session.remove()
self.db.drop_all()
class WebsmashTestCase(ModelTestCase):
def create_app(self):
return super(WebsmashTestCase, self).create_app()
def setUp(self):
super(WebsmashTestCase, self).setUp()
self.tmpdir = tempfile.mkdtemp()
(fd, self.tmp_name) = tempfile.mkstemp(dir=self.tmpdir, suffix='.fa')
tmp_file = os.fdopen(fd, 'w+b')
tmp_file.write('>test\nATGACCGAGAGTACATAG\n')
tmp_file.close()
self.tmp_file = open(self.tmp_name, 'r')
self.app.config['RESULTS_PATH'] = self.tmpdir
def tearDown(self):
super(WebsmashTestCase, self).tearDown()
self.tmp_file.close()
shutil.rmtree(self.tmpdir)
|
Fix the temp file initialization
|
tests: Fix the temp file initialization
Signed-off-by: Kai Blin <94ddc6985b47aef772521e302594241f46a8f665@biotech.uni-tuebingen.de>
|
Python
|
agpl-3.0
|
antismash/ps-web,antismash/ps-web,antismash/websmash,antismash/ps-web
|
python
|
## Code Before:
from flask.ext.testing import TestCase
import os
import tempfile
import shutil
import websmash
class ModelTestCase(TestCase):
def create_app(self):
self.app = websmash.app
self.dl = websmash.dl
self.app.config['TESTING'] = True
self.app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite://"
websmash.mail.suppress = True
return self.app
def setUp(self):
self.db = websmash.db
self.db.create_all()
def tearDown(self):
self.db.session.remove()
self.db.drop_all()
class WebsmashTestCase(ModelTestCase):
def create_app(self):
return super(WebsmashTestCase, self).create_app()
def setUp(self):
super(WebsmashTestCase, self).setUp()
self.tmpdir = tempfile.mkdtemp()
(fd, self.tmp_name) = tempfile.mkstemp(dir=self.tmpdir, suffix='.fa')
self.tmp_file = os.fdopen(fd, 'w+b')
self.tmp_file.write('>test\nATGACCGAGAGTACATAG\n')
self.app.config['RESULTS_PATH'] = self.tmpdir
def tearDown(self):
super(WebsmashTestCase, self).tearDown()
self.tmp_file.close()
shutil.rmtree(self.tmpdir)
## Instruction:
tests: Fix the temp file initialization
Signed-off-by: Kai Blin <94ddc6985b47aef772521e302594241f46a8f665@biotech.uni-tuebingen.de>
## Code After:
from flask.ext.testing import TestCase
import os
import tempfile
import shutil
import websmash
class ModelTestCase(TestCase):
def create_app(self):
self.app = websmash.app
self.dl = websmash.dl
self.app.config['TESTING'] = True
self.app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite://"
websmash.mail.suppress = True
return self.app
def setUp(self):
self.db = websmash.db
self.db.create_all()
def tearDown(self):
self.db.session.remove()
self.db.drop_all()
class WebsmashTestCase(ModelTestCase):
def create_app(self):
return super(WebsmashTestCase, self).create_app()
def setUp(self):
super(WebsmashTestCase, self).setUp()
self.tmpdir = tempfile.mkdtemp()
(fd, self.tmp_name) = tempfile.mkstemp(dir=self.tmpdir, suffix='.fa')
tmp_file = os.fdopen(fd, 'w+b')
tmp_file.write('>test\nATGACCGAGAGTACATAG\n')
tmp_file.close()
self.tmp_file = open(self.tmp_name, 'r')
self.app.config['RESULTS_PATH'] = self.tmpdir
def tearDown(self):
super(WebsmashTestCase, self).tearDown()
self.tmp_file.close()
shutil.rmtree(self.tmpdir)
|
# ... existing code ...
super(WebsmashTestCase, self).setUp()
self.tmpdir = tempfile.mkdtemp()
(fd, self.tmp_name) = tempfile.mkstemp(dir=self.tmpdir, suffix='.fa')
tmp_file = os.fdopen(fd, 'w+b')
tmp_file.write('>test\nATGACCGAGAGTACATAG\n')
tmp_file.close()
self.tmp_file = open(self.tmp_name, 'r')
self.app.config['RESULTS_PATH'] = self.tmpdir
def tearDown(self):
# ... rest of the code ...
|
104da4df7e0cd09d32457cf56fc00dc96fcdbdac
|
euler/p005.py
|
euler/p005.py
|
from fractions import gcd
from functools import reduce
MAXIMUM = 20
def compute(maximum=MAXIMUM):
"""Compute the LCM of all integers from 1 to `maximum`."""
return int(reduce(lambda x, y: (x*y)/gcd(x, y), range(1, maximum + 1)))
|
from functools import reduce
MAXIMUM = 20
def gcd(num1, num2):
"""Return greatest common divisor using Euclid's Algorithm."""
while num2:
num1, num2 = num2, num1 % num2
return num1
def lcm(num1, num2):
"""Return lowest common multiple."""
return num1 * num2 // gcd(num1, num2)
def lcmm(*args):
"""Return LCM of args."""
return reduce(lcm, args)
def compute(maximum=MAXIMUM):
"""Compute the LCM of all integers from 1 to `maximum`."""
return lcmm(*range(1, maximum + 1))
|
Replace deprecated fractions.gcd with Euclid's Algorithm
|
Replace deprecated fractions.gcd with Euclid's Algorithm
|
Python
|
mit
|
2Cubed/ProjectEuler
|
python
|
## Code Before:
from fractions import gcd
from functools import reduce
MAXIMUM = 20
def compute(maximum=MAXIMUM):
"""Compute the LCM of all integers from 1 to `maximum`."""
return int(reduce(lambda x, y: (x*y)/gcd(x, y), range(1, maximum + 1)))
## Instruction:
Replace deprecated fractions.gcd with Euclid's Algorithm
## Code After:
from functools import reduce
MAXIMUM = 20
def gcd(num1, num2):
"""Return greatest common divisor using Euclid's Algorithm."""
while num2:
num1, num2 = num2, num1 % num2
return num1
def lcm(num1, num2):
"""Return lowest common multiple."""
return num1 * num2 // gcd(num1, num2)
def lcmm(*args):
"""Return LCM of args."""
return reduce(lcm, args)
def compute(maximum=MAXIMUM):
"""Compute the LCM of all integers from 1 to `maximum`."""
return lcmm(*range(1, maximum + 1))
|
// ... existing code ...
from functools import reduce
MAXIMUM = 20
def gcd(num1, num2):
"""Return greatest common divisor using Euclid's Algorithm."""
while num2:
num1, num2 = num2, num1 % num2
return num1
def lcm(num1, num2):
"""Return lowest common multiple."""
return num1 * num2 // gcd(num1, num2)
def lcmm(*args):
"""Return LCM of args."""
return reduce(lcm, args)
def compute(maximum=MAXIMUM):
"""Compute the LCM of all integers from 1 to `maximum`."""
return lcmm(*range(1, maximum + 1))
// ... rest of the code ...
|
530f540b11959956c0cd08b95b2c7c373d829c8e
|
python/sherlock-and-valid-string.py
|
python/sherlock-and-valid-string.py
|
import math
import os
import random
import re
import sys
from collections import Counter
def isValid(s):
return "YES" if containsOnlyOneDifferentCharacterCount(s) else "NO"
def containsOnlyOneDifferentCharacterCount(string):
characterCounts = Counter(string)
if allOccurencesAreEqual(characterCounts):
return True
else:
# Try to remove one occurence of every character
for character in characterCounts:
characterCountWithOneRemovedCharacter = dict.copy(characterCounts)
characterCountWithOneRemovedCharacter[character] -= 1
if allOccurencesAreEqual(characterCountWithOneRemovedCharacter):
return True
return False
def allOccurencesAreEqual(dict):
return len(set(dict.values())) == 1
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = isValid(s)
fptr.write(result + '\n')
fptr.close()
|
import math
import os
import random
import re
import sys
from collections import Counter
import copy
def isValid(s):
return "YES" if containsOnlyOneDifferentCharacterCount(s) else "NO"
def containsOnlyOneDifferentCharacterCount(string):
characterCounts = Counter(string)
if allOccurencesAreEqual(characterCounts):
return True
else:
# Try to remove one occurence of every character
for character in characterCounts:
characterCountWithOneRemovedCharacter = characterCounts.copy()
characterCountWithOneRemovedCharacter[character] -= 1
characterCountWithOneRemovedCharacter += Counter() # remove zero and negative counts
if allOccurencesAreEqual(characterCountWithOneRemovedCharacter):
return True
return False
def allOccurencesAreEqual(dict):
return len(set(dict.values())) == 1
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = isValid(s)
fptr.write(result + '\n')
fptr.close()
|
Handle edge case with zero count
|
Handle edge case with zero count
|
Python
|
mit
|
rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank
|
python
|
## Code Before:
import math
import os
import random
import re
import sys
from collections import Counter
def isValid(s):
return "YES" if containsOnlyOneDifferentCharacterCount(s) else "NO"
def containsOnlyOneDifferentCharacterCount(string):
characterCounts = Counter(string)
if allOccurencesAreEqual(characterCounts):
return True
else:
# Try to remove one occurence of every character
for character in characterCounts:
characterCountWithOneRemovedCharacter = dict.copy(characterCounts)
characterCountWithOneRemovedCharacter[character] -= 1
if allOccurencesAreEqual(characterCountWithOneRemovedCharacter):
return True
return False
def allOccurencesAreEqual(dict):
return len(set(dict.values())) == 1
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = isValid(s)
fptr.write(result + '\n')
fptr.close()
## Instruction:
Handle edge case with zero count
## Code After:
import math
import os
import random
import re
import sys
from collections import Counter
import copy
def isValid(s):
return "YES" if containsOnlyOneDifferentCharacterCount(s) else "NO"
def containsOnlyOneDifferentCharacterCount(string):
characterCounts = Counter(string)
if allOccurencesAreEqual(characterCounts):
return True
else:
# Try to remove one occurence of every character
for character in characterCounts:
characterCountWithOneRemovedCharacter = characterCounts.copy()
characterCountWithOneRemovedCharacter[character] -= 1
characterCountWithOneRemovedCharacter += Counter() # remove zero and negative counts
if allOccurencesAreEqual(characterCountWithOneRemovedCharacter):
return True
return False
def allOccurencesAreEqual(dict):
return len(set(dict.values())) == 1
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = isValid(s)
fptr.write(result + '\n')
fptr.close()
|
// ... existing code ...
import re
import sys
from collections import Counter
import copy
def isValid(s):
// ... modified code ...
else:
# Try to remove one occurence of every character
for character in characterCounts:
characterCountWithOneRemovedCharacter = characterCounts.copy()
characterCountWithOneRemovedCharacter[character] -= 1
characterCountWithOneRemovedCharacter += Counter() # remove zero and negative counts
if allOccurencesAreEqual(characterCountWithOneRemovedCharacter):
return True
return False
// ... rest of the code ...
|
306e6939c5b369f4a4ef4bb4d16948dc1f027f53
|
tests/test_initial_ismaster.py
|
tests/test_initial_ismaster.py
|
import time
from mockupdb import MockupDB, wait_until
from pymongo import MongoClient
from tests import unittest
class TestInitialIsMaster(unittest.TestCase):
def test_initial_ismaster(self):
server = MockupDB()
server.run()
self.addCleanup(server.stop)
start = time.time()
client = MongoClient(server.uri)
self.addCleanup(client.close)
# A single ismaster is enough for the client to be connected.
self.assertIsNone(client.address)
server.receives('ismaster').ok()
wait_until(lambda: client.address is not None,
'update address', timeout=1)
# At least 10 seconds before next heartbeat.
server.receives('ismaster').ok()
self.assertGreaterEqual(time.time() - start, 10)
if __name__ == '__main__':
unittest.main()
|
import time
from mockupdb import MockupDB, wait_until
from pymongo import MongoClient
from tests import unittest
class TestInitialIsMaster(unittest.TestCase):
def test_initial_ismaster(self):
server = MockupDB()
server.run()
self.addCleanup(server.stop)
start = time.time()
client = MongoClient(server.uri)
self.addCleanup(client.close)
# A single ismaster is enough for the client to be connected.
self.assertFalse(client.nodes)
server.receives('ismaster').ok(ismaster=True)
wait_until(lambda: client.nodes,
'update nodes', timeout=1)
# At least 10 seconds before next heartbeat.
server.receives('ismaster').ok(ismaster=True)
self.assertGreaterEqual(time.time() - start, 10)
if __name__ == '__main__':
unittest.main()
|
Update for PYTHON 985: MongoClient properties now block until connected.
|
Update for PYTHON 985: MongoClient properties now block until connected.
|
Python
|
apache-2.0
|
ajdavis/pymongo-mockup-tests
|
python
|
## Code Before:
import time
from mockupdb import MockupDB, wait_until
from pymongo import MongoClient
from tests import unittest
class TestInitialIsMaster(unittest.TestCase):
def test_initial_ismaster(self):
server = MockupDB()
server.run()
self.addCleanup(server.stop)
start = time.time()
client = MongoClient(server.uri)
self.addCleanup(client.close)
# A single ismaster is enough for the client to be connected.
self.assertIsNone(client.address)
server.receives('ismaster').ok()
wait_until(lambda: client.address is not None,
'update address', timeout=1)
# At least 10 seconds before next heartbeat.
server.receives('ismaster').ok()
self.assertGreaterEqual(time.time() - start, 10)
if __name__ == '__main__':
unittest.main()
## Instruction:
Update for PYTHON 985: MongoClient properties now block until connected.
## Code After:
import time
from mockupdb import MockupDB, wait_until
from pymongo import MongoClient
from tests import unittest
class TestInitialIsMaster(unittest.TestCase):
def test_initial_ismaster(self):
server = MockupDB()
server.run()
self.addCleanup(server.stop)
start = time.time()
client = MongoClient(server.uri)
self.addCleanup(client.close)
# A single ismaster is enough for the client to be connected.
self.assertFalse(client.nodes)
server.receives('ismaster').ok(ismaster=True)
wait_until(lambda: client.nodes,
'update nodes', timeout=1)
# At least 10 seconds before next heartbeat.
server.receives('ismaster').ok(ismaster=True)
self.assertGreaterEqual(time.time() - start, 10)
if __name__ == '__main__':
unittest.main()
|
// ... existing code ...
self.addCleanup(client.close)
# A single ismaster is enough for the client to be connected.
self.assertFalse(client.nodes)
server.receives('ismaster').ok(ismaster=True)
wait_until(lambda: client.nodes,
'update nodes', timeout=1)
# At least 10 seconds before next heartbeat.
server.receives('ismaster').ok(ismaster=True)
self.assertGreaterEqual(time.time() - start, 10)
if __name__ == '__main__':
// ... rest of the code ...
|
1a0df1a9eb803e9fa4b130ee133959bebcd0bb70
|
src/mazegenerator/MazeGenerator.java
|
src/mazegenerator/MazeGenerator.java
|
package mazegenerator;
import java.util.ArrayList;
import java.util.Arrays;
import util.MathUtil;
/**
*
* @author mallory
*/
public class MazeGenerator {
public static void main(String[] args) throws Exception {
// byte value = 0;
// for(; value < 33; value++){
// MazeTile tile = new MazeTile(value);
// System.out.println(tile + " " + value);
// System.out.println();
// }
// MazeTile[][] maze = new MazeTile[2][2];
// maze[0][0] = new MazeTile(true,false,true,false);
// maze[0][1] = new MazeTile(false,true,true,false);
// maze[1][0] = new MazeTile(true,false,false,true);
// maze[1][1] = new MazeTile(false,true,false,true);
Maze maze = new Maze(47, 11, 1,1);
//Test
maze.generate();
System.out.print(maze.toString());
}
}
|
package mazegenerator;
import java.util.ArrayList;
import java.util.Arrays;
import util.MathUtil;
/**
*
* @author mallory
*/
public class MazeGenerator {
public static void main(String[] args) throws Exception {
// byte value = 0;
// for(; value < 33; value++){
// MazeTile tile = new MazeTile(value);
// System.out.println(tile + " " + value);
// System.out.println();
// }
// MazeTile[][] maze = new MazeTile[2][2];
// maze[0][0] = new MazeTile(true,false,true,false);
// maze[0][1] = new MazeTile(false,true,true,false);
// maze[1][0] = new MazeTile(true,false,false,true);
// maze[1][1] = new MazeTile(false,true,false,true);
Maze maze = new Maze(47, 11, 1,1);
//Test
//Test 2
maze.generate();
System.out.print(maze.toString());
}
}
|
Test Commit. Attempt to fix username.
|
Test Commit. Attempt to fix username.
|
Java
|
mit
|
nmpandafish6/MazeGenerator
|
java
|
## Code Before:
package mazegenerator;
import java.util.ArrayList;
import java.util.Arrays;
import util.MathUtil;
/**
*
* @author mallory
*/
public class MazeGenerator {
public static void main(String[] args) throws Exception {
// byte value = 0;
// for(; value < 33; value++){
// MazeTile tile = new MazeTile(value);
// System.out.println(tile + " " + value);
// System.out.println();
// }
// MazeTile[][] maze = new MazeTile[2][2];
// maze[0][0] = new MazeTile(true,false,true,false);
// maze[0][1] = new MazeTile(false,true,true,false);
// maze[1][0] = new MazeTile(true,false,false,true);
// maze[1][1] = new MazeTile(false,true,false,true);
Maze maze = new Maze(47, 11, 1,1);
//Test
maze.generate();
System.out.print(maze.toString());
}
}
## Instruction:
Test Commit. Attempt to fix username.
## Code After:
package mazegenerator;
import java.util.ArrayList;
import java.util.Arrays;
import util.MathUtil;
/**
*
* @author mallory
*/
public class MazeGenerator {
public static void main(String[] args) throws Exception {
// byte value = 0;
// for(; value < 33; value++){
// MazeTile tile = new MazeTile(value);
// System.out.println(tile + " " + value);
// System.out.println();
// }
// MazeTile[][] maze = new MazeTile[2][2];
// maze[0][0] = new MazeTile(true,false,true,false);
// maze[0][1] = new MazeTile(false,true,true,false);
// maze[1][0] = new MazeTile(true,false,false,true);
// maze[1][1] = new MazeTile(false,true,false,true);
Maze maze = new Maze(47, 11, 1,1);
//Test
//Test 2
maze.generate();
System.out.print(maze.toString());
}
}
|
// ... existing code ...
// maze[1][1] = new MazeTile(false,true,false,true);
Maze maze = new Maze(47, 11, 1,1);
//Test
//Test 2
maze.generate();
System.out.print(maze.toString());
// ... rest of the code ...
|
8a6015610bba2dcdc0a2cb031b2f58606328841f
|
src/fastpb/generator.py
|
src/fastpb/generator.py
|
import plugin_pb2
from jinja2 import Template
from pkg_resources import resource_string
import os.path
import sys
import tempfile
def main():
log = sys.stderr
request = plugin_pb2.CodeGeneratorRequest()
request.ParseFromString(sys.stdin.read())
path = tempfile.mkdtemp()
generateFiles = set(request.file_to_generate)
files = []
for file in request.proto_file:
if file.name not in generateFiles:
continue
name = file.name.split('.')[0]
files.append(name)
context = {
'moduleName': name,
'messages': file.message_type
}
cFilePath = os.path.join(path, name + '.c')
with open(cFilePath, 'w') as f:
t = Template(resource_string(__name__, 'template/module.jinja.c'))
f.write(t.render(context))
setupPyPath = os.path.join(path, 'setup.py')
with open(setupPyPath, 'w') as f:
t = Template(resource_string(__name__, 'template/setup.jinja.py'))
f.write(t.render({'files': files}))
print >> log, path
if __name__ == '__main__':
main()
|
import plugin_pb2
from jinja2 import Template
from pkg_resources import resource_string
import os.path
import sys
import tempfile
def main():
request = plugin_pb2.CodeGeneratorRequest()
request.ParseFromString(sys.stdin.read())
response = plugin_pb2.CodeGeneratorResponse()
generateFiles = set(request.file_to_generate)
files = []
for file in request.proto_file:
if file.name not in generateFiles:
continue
name = file.name.split('.')[0]
files.append(name)
context = {
'moduleName': name,
'messages': file.message_type
}
# Write the C file.
t = Template(resource_string(__name__, 'template/module.jinja.c'))
cFile = response.file.add()
cFile.name = name + '.c'
cFile.content = t.render(context)
# Write setup.py.
t = Template(resource_string(__name__, 'template/setup.jinja.py'))
setupFile = response.file.add()
setupFile.name = 'setup.py'
setupFile.content = t.render({'files': files})
sys.stdout.write(response.SerializeToString())
if __name__ == '__main__':
main()
|
Use protoc for file output
|
Use protoc for file output
|
Python
|
apache-2.0
|
Cue/fast-python-pb
|
python
|
## Code Before:
import plugin_pb2
from jinja2 import Template
from pkg_resources import resource_string
import os.path
import sys
import tempfile
def main():
log = sys.stderr
request = plugin_pb2.CodeGeneratorRequest()
request.ParseFromString(sys.stdin.read())
path = tempfile.mkdtemp()
generateFiles = set(request.file_to_generate)
files = []
for file in request.proto_file:
if file.name not in generateFiles:
continue
name = file.name.split('.')[0]
files.append(name)
context = {
'moduleName': name,
'messages': file.message_type
}
cFilePath = os.path.join(path, name + '.c')
with open(cFilePath, 'w') as f:
t = Template(resource_string(__name__, 'template/module.jinja.c'))
f.write(t.render(context))
setupPyPath = os.path.join(path, 'setup.py')
with open(setupPyPath, 'w') as f:
t = Template(resource_string(__name__, 'template/setup.jinja.py'))
f.write(t.render({'files': files}))
print >> log, path
if __name__ == '__main__':
main()
## Instruction:
Use protoc for file output
## Code After:
import plugin_pb2
from jinja2 import Template
from pkg_resources import resource_string
import os.path
import sys
import tempfile
def main():
request = plugin_pb2.CodeGeneratorRequest()
request.ParseFromString(sys.stdin.read())
response = plugin_pb2.CodeGeneratorResponse()
generateFiles = set(request.file_to_generate)
files = []
for file in request.proto_file:
if file.name not in generateFiles:
continue
name = file.name.split('.')[0]
files.append(name)
context = {
'moduleName': name,
'messages': file.message_type
}
# Write the C file.
t = Template(resource_string(__name__, 'template/module.jinja.c'))
cFile = response.file.add()
cFile.name = name + '.c'
cFile.content = t.render(context)
# Write setup.py.
t = Template(resource_string(__name__, 'template/setup.jinja.py'))
setupFile = response.file.add()
setupFile.name = 'setup.py'
setupFile.content = t.render({'files': files})
sys.stdout.write(response.SerializeToString())
if __name__ == '__main__':
main()
|
// ... existing code ...
def main():
request = plugin_pb2.CodeGeneratorRequest()
request.ParseFromString(sys.stdin.read())
response = plugin_pb2.CodeGeneratorResponse()
generateFiles = set(request.file_to_generate)
files = []
// ... modified code ...
'messages': file.message_type
}
# Write the C file.
t = Template(resource_string(__name__, 'template/module.jinja.c'))
cFile = response.file.add()
cFile.name = name + '.c'
cFile.content = t.render(context)
# Write setup.py.
t = Template(resource_string(__name__, 'template/setup.jinja.py'))
setupFile = response.file.add()
setupFile.name = 'setup.py'
setupFile.content = t.render({'files': files})
sys.stdout.write(response.SerializeToString())
if __name__ == '__main__':
// ... rest of the code ...
|
ff96f3fd6835f11f3725ab398b2a6b7ba4275e93
|
thinglang/compiler/references.py
|
thinglang/compiler/references.py
|
class Reference(object):
def __init__(self, type):
super().__init__()
self._type = type
@property
def type(self):
return self._type
class ElementReference(Reference):
def __init__(self, thing, element):
super(ElementReference, self).__init__(element.type)
self.thing, self.element = thing, element
@property
def thing_index(self):
return self.thing.index
@property
def element_index(self):
return self.element.index
@property
def convention(self):
return self.element.convention
@property
def static(self):
return self.element.static
class LocalReference(Reference):
def __init__(self, local):
super(LocalReference, self).__init__(local.type)
self.local = local
@property
def local_index(self):
return self.local.index
class StaticReference(Reference):
def __init__(self, value):
super(StaticReference, self).__init__(value.type)
self.value = value
|
class Reference(object):
def __init__(self, type):
super().__init__()
self._type = type
@property
def type(self):
return self._type
class ElementReference(Reference):
def __init__(self, thing, element, local=None):
super(ElementReference, self).__init__(element.type)
self.thing, self.element, self.local = thing, element, local
@property
def thing_index(self):
return self.thing.index
@property
def element_index(self):
return self.element.index
@property
def local_index(self):
return self.local.index
@property
def convention(self):
return self.element.convention
@property
def static(self):
return self.element.static
class LocalReference(Reference):
def __init__(self, local):
super(LocalReference, self).__init__(local.type)
self.local = local
@property
def local_index(self):
return self.local.index
class StaticReference(Reference):
def __init__(self, value):
super(StaticReference, self).__init__(value.type)
self.value = value
|
Add locally referenced subtype to element referenced opcodes
|
Add locally referenced subtype to element referenced opcodes
|
Python
|
mit
|
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
|
python
|
## Code Before:
class Reference(object):
def __init__(self, type):
super().__init__()
self._type = type
@property
def type(self):
return self._type
class ElementReference(Reference):
def __init__(self, thing, element):
super(ElementReference, self).__init__(element.type)
self.thing, self.element = thing, element
@property
def thing_index(self):
return self.thing.index
@property
def element_index(self):
return self.element.index
@property
def convention(self):
return self.element.convention
@property
def static(self):
return self.element.static
class LocalReference(Reference):
def __init__(self, local):
super(LocalReference, self).__init__(local.type)
self.local = local
@property
def local_index(self):
return self.local.index
class StaticReference(Reference):
def __init__(self, value):
super(StaticReference, self).__init__(value.type)
self.value = value
## Instruction:
Add locally referenced subtype to element referenced opcodes
## Code After:
class Reference(object):
def __init__(self, type):
super().__init__()
self._type = type
@property
def type(self):
return self._type
class ElementReference(Reference):
def __init__(self, thing, element, local=None):
super(ElementReference, self).__init__(element.type)
self.thing, self.element, self.local = thing, element, local
@property
def thing_index(self):
return self.thing.index
@property
def element_index(self):
return self.element.index
@property
def local_index(self):
return self.local.index
@property
def convention(self):
return self.element.convention
@property
def static(self):
return self.element.static
class LocalReference(Reference):
def __init__(self, local):
super(LocalReference, self).__init__(local.type)
self.local = local
@property
def local_index(self):
return self.local.index
class StaticReference(Reference):
def __init__(self, value):
super(StaticReference, self).__init__(value.type)
self.value = value
|
// ... existing code ...
class ElementReference(Reference):
def __init__(self, thing, element, local=None):
super(ElementReference, self).__init__(element.type)
self.thing, self.element, self.local = thing, element, local
@property
def thing_index(self):
// ... modified code ...
return self.element.index
@property
def local_index(self):
return self.local.index
@property
def convention(self):
return self.element.convention
...
@property
def static(self):
return self.element.static
class LocalReference(Reference):
// ... rest of the code ...
|
f5e4a8000e23e279192834d03e4b5b9ecca6b2b0
|
linguist/utils/__init__.py
|
linguist/utils/__init__.py
|
from .i18n import (get_language_name,
get_language,
get_fallback_language,
build_localized_field_name,
build_localized_verbose_name)
from .models import load_class, get_model_string
from .template import select_template_name
from .views import get_language_parameter, get_language_tabs
__all__ = [
'get_language_name',
'get_language',
'get_fallback_language',
'build_localized_field_name',
'build_localized_verbose_name',
'load_class',
'get_model_string',
'select_template_name',
'get_language_parameter',
'get_language_tabs',
'chunks',
]
def chunks(l, n):
"""
Yields successive n-sized chunks from l.
"""
for i in xrange(0, len(l), n):
yield l[i:i + n]
|
from .i18n import (get_language_name,
get_language,
get_fallback_language,
get_real_field_name,
get_fallback_field_name,
build_localized_field_name,
build_localized_verbose_name)
from .models import load_class, get_model_string
from .template import select_template_name
from .views import get_language_parameter, get_language_tabs
__all__ = [
'get_language_name',
'get_language',
'get_fallback_language',
'build_localized_field_name',
'build_localized_verbose_name',
'load_class',
'get_model_string',
'select_template_name',
'get_language_parameter',
'get_language_tabs',
'chunks',
]
def chunks(l, n):
"""
Yields successive n-sized chunks from l.
"""
for i in xrange(0, len(l), n):
yield l[i:i + n]
|
Fix new i18n utils imports.
|
Fix new i18n utils imports.
|
Python
|
mit
|
ulule/django-linguist
|
python
|
## Code Before:
from .i18n import (get_language_name,
get_language,
get_fallback_language,
build_localized_field_name,
build_localized_verbose_name)
from .models import load_class, get_model_string
from .template import select_template_name
from .views import get_language_parameter, get_language_tabs
__all__ = [
'get_language_name',
'get_language',
'get_fallback_language',
'build_localized_field_name',
'build_localized_verbose_name',
'load_class',
'get_model_string',
'select_template_name',
'get_language_parameter',
'get_language_tabs',
'chunks',
]
def chunks(l, n):
"""
Yields successive n-sized chunks from l.
"""
for i in xrange(0, len(l), n):
yield l[i:i + n]
## Instruction:
Fix new i18n utils imports.
## Code After:
from .i18n import (get_language_name,
get_language,
get_fallback_language,
get_real_field_name,
get_fallback_field_name,
build_localized_field_name,
build_localized_verbose_name)
from .models import load_class, get_model_string
from .template import select_template_name
from .views import get_language_parameter, get_language_tabs
__all__ = [
'get_language_name',
'get_language',
'get_fallback_language',
'build_localized_field_name',
'build_localized_verbose_name',
'load_class',
'get_model_string',
'select_template_name',
'get_language_parameter',
'get_language_tabs',
'chunks',
]
def chunks(l, n):
"""
Yields successive n-sized chunks from l.
"""
for i in xrange(0, len(l), n):
yield l[i:i + n]
|
# ... existing code ...
from .i18n import (get_language_name,
get_language,
get_fallback_language,
get_real_field_name,
get_fallback_field_name,
build_localized_field_name,
build_localized_verbose_name)
# ... rest of the code ...
|
ca778ee95c0e3c52065feda21e1e1a4e8c284cd1
|
SmartChat/src/main/java/io/smartlogic/smartchat/GcmIntentService.java
|
SmartChat/src/main/java/io/smartlogic/smartchat/GcmIntentService.java
|
package io.smartlogic.smartchat;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import io.smartlogic.smartchat.activities.DisplaySmartChatActivity;
import io.smartlogic.smartchat.activities.MainActivity;
public class GcmIntentService extends IntentService {
public GcmIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("New SmartChat")
.setContentText("SmartChat from " + extras.getString("creator_email"));
Intent resultIntent = new Intent(this, DisplaySmartChatActivity.class);
resultIntent.putExtras(extras);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
|
package io.smartlogic.smartchat;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import io.smartlogic.smartchat.activities.DisplaySmartChatActivity;
import io.smartlogic.smartchat.activities.MainActivity;
public class GcmIntentService extends IntentService {
public GcmIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("New SmartChat")
.setContentText("SmartChat from " + extras.getString("creator_email"));
Intent resultIntent = new Intent(this, DisplaySmartChatActivity.class);
resultIntent.putExtras(extras);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(extras.getInt("id", 1), mBuilder.build());
}
}
|
Use the media id as notification id
|
Use the media id as notification id
|
Java
|
mit
|
smartlogic/smartchat-android,smartlogic/smartchat-android
|
java
|
## Code Before:
package io.smartlogic.smartchat;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import io.smartlogic.smartchat.activities.DisplaySmartChatActivity;
import io.smartlogic.smartchat.activities.MainActivity;
public class GcmIntentService extends IntentService {
public GcmIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("New SmartChat")
.setContentText("SmartChat from " + extras.getString("creator_email"));
Intent resultIntent = new Intent(this, DisplaySmartChatActivity.class);
resultIntent.putExtras(extras);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
## Instruction:
Use the media id as notification id
## Code After:
package io.smartlogic.smartchat;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import io.smartlogic.smartchat.activities.DisplaySmartChatActivity;
import io.smartlogic.smartchat.activities.MainActivity;
public class GcmIntentService extends IntentService {
public GcmIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("New SmartChat")
.setContentText("SmartChat from " + extras.getString("creator_email"));
Intent resultIntent = new Intent(this, DisplaySmartChatActivity.class);
resultIntent.putExtras(extras);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(extras.getInt("id", 1), mBuilder.build());
}
}
|
...
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(extras.getInt("id", 1), mBuilder.build());
}
}
...
|
d60dea7b7b1fb073eef2c350177b3920f32de748
|
6/e6.py
|
6/e6.py
|
def sum_seq_squares(n):
return (n * (n+1) * ((2*n)+1)) / 6
def sum_seq(n):
return (n * (n + 1)) / 2
def main():
sum_seq_sq_100 = sum_seq_squares(100)
sum_seq_100 = sum_seq(100)
sq_sum_seq_100 = sum_seq_100**2
diff = sq_sum_seq_100 - sum_seq_sq_100
print('diff is {0}'.format(diff))
if __name__ == '__main__':
main()
|
def sum_seq_squares(n):
return (n * (n+1) * ((2*n)+1)) / 6
# http://www.regentsprep.org/regents/math/algtrig/ATP2/ArithSeq.htm
def sum_seq(n):
return (n * (n + 1)) / 2
def main():
sum_seq_sq_100 = sum_seq_squares(100)
sum_seq_100 = sum_seq(100)
sq_sum_seq_100 = sum_seq_100**2
diff = sq_sum_seq_100 - sum_seq_sq_100
print('diff is {0}'.format(diff))
if __name__ == '__main__':
main()
|
Add comments indicating source of formulae..
|
Add comments indicating source of formulae..
|
Python
|
mit
|
cveazey/ProjectEuler,cveazey/ProjectEuler
|
python
|
## Code Before:
def sum_seq_squares(n):
return (n * (n+1) * ((2*n)+1)) / 6
def sum_seq(n):
return (n * (n + 1)) / 2
def main():
sum_seq_sq_100 = sum_seq_squares(100)
sum_seq_100 = sum_seq(100)
sq_sum_seq_100 = sum_seq_100**2
diff = sq_sum_seq_100 - sum_seq_sq_100
print('diff is {0}'.format(diff))
if __name__ == '__main__':
main()
## Instruction:
Add comments indicating source of formulae..
## Code After:
def sum_seq_squares(n):
return (n * (n+1) * ((2*n)+1)) / 6
# http://www.regentsprep.org/regents/math/algtrig/ATP2/ArithSeq.htm
def sum_seq(n):
return (n * (n + 1)) / 2
def main():
sum_seq_sq_100 = sum_seq_squares(100)
sum_seq_100 = sum_seq(100)
sq_sum_seq_100 = sum_seq_100**2
diff = sq_sum_seq_100 - sum_seq_sq_100
print('diff is {0}'.format(diff))
if __name__ == '__main__':
main()
|
...
def sum_seq_squares(n):
return (n * (n+1) * ((2*n)+1)) / 6
# http://www.regentsprep.org/regents/math/algtrig/ATP2/ArithSeq.htm
def sum_seq(n):
return (n * (n + 1)) / 2
...
|
f76015fdf37db44a54ce0e0038b4b85978c39839
|
tests/test_utils.py
|
tests/test_utils.py
|
import __future__ # noqa: F401
import json # noqa: F401
from os import path # noqa: F401
from re import IGNORECASE, sub # noqa: F401
import my_module # noqa: F401
from my_module.utils import add_two_numbers
import pytest
class TestUtils: # noqa: D101
@pytest.mark.parametrize('number_left, number_right', [
(None, 1), (1, None), (None, None)
])
def test_add_two_numbers_no_input(self, number_left, number_right):
"""Basic input validation."""
with pytest.raises(ValueError):
add_two_numbers(number_left, number_right)
def test_add_two_numbers_regular_input(self):
"""Basic asserting test."""
assert add_two_numbers(2, 3) == 5
|
import __future__ # noqa: F401
import json # noqa: F401
from os import path # noqa: F401
from re import IGNORECASE, sub # noqa: F401
import click # noqa: F401
import my_module # noqa: F401
from my_module.utils import add_two_numbers
import pytest
import requests # noqa: F401
class TestUtils: # noqa: D101
@pytest.mark.parametrize('number_left, number_right', [
(None, 1), (1, None), (None, None)
])
def test_add_two_numbers_no_input(self, number_left, number_right):
"""Basic input validation."""
with pytest.raises(ValueError):
add_two_numbers(number_left, number_right)
def test_add_two_numbers_regular_input(self):
"""Basic asserting test."""
assert add_two_numbers(2, 3) == 5
|
Add import statements breaking linter
|
Add import statements breaking linter
|
Python
|
apache-2.0
|
BastiTee/bastis-python-toolbox
|
python
|
## Code Before:
import __future__ # noqa: F401
import json # noqa: F401
from os import path # noqa: F401
from re import IGNORECASE, sub # noqa: F401
import my_module # noqa: F401
from my_module.utils import add_two_numbers
import pytest
class TestUtils: # noqa: D101
@pytest.mark.parametrize('number_left, number_right', [
(None, 1), (1, None), (None, None)
])
def test_add_two_numbers_no_input(self, number_left, number_right):
"""Basic input validation."""
with pytest.raises(ValueError):
add_two_numbers(number_left, number_right)
def test_add_two_numbers_regular_input(self):
"""Basic asserting test."""
assert add_two_numbers(2, 3) == 5
## Instruction:
Add import statements breaking linter
## Code After:
import __future__ # noqa: F401
import json # noqa: F401
from os import path # noqa: F401
from re import IGNORECASE, sub # noqa: F401
import click # noqa: F401
import my_module # noqa: F401
from my_module.utils import add_two_numbers
import pytest
import requests # noqa: F401
class TestUtils: # noqa: D101
@pytest.mark.parametrize('number_left, number_right', [
(None, 1), (1, None), (None, None)
])
def test_add_two_numbers_no_input(self, number_left, number_right):
"""Basic input validation."""
with pytest.raises(ValueError):
add_two_numbers(number_left, number_right)
def test_add_two_numbers_regular_input(self):
"""Basic asserting test."""
assert add_two_numbers(2, 3) == 5
|
// ... existing code ...
from os import path # noqa: F401
from re import IGNORECASE, sub # noqa: F401
import click # noqa: F401
import my_module # noqa: F401
from my_module.utils import add_two_numbers
import pytest
import requests # noqa: F401
class TestUtils: # noqa: D101
// ... rest of the code ...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.