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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
3706700e4725d23752269c2e833adfa736d0ce96
|
worker/jobs/session/__init__.py
|
worker/jobs/session/__init__.py
|
import os
from typing import Optional, List
from jobs.base.job import Job
# If on a K8s cluster then use the K8s-based sessions
# otherwise use the subsprocess-based session
if "KUBERNETES_SERVICE_HOST" in os.environ:
from .kubernetes_session import KubernetesSession
Session = KubernetesSession # type: ignore
else:
from .subprocess_session import SubprocessSession
Session = SubprocessSession # type: ignore
Session.name = "session"
|
from typing import Type, Union
from .kubernetes_session import api_instance, KubernetesSession
from .subprocess_session import SubprocessSession
# If on a K8s is available then use that
# otherwise use the subsprocess-based session
Session: Type[Union[KubernetesSession, SubprocessSession]]
if api_instance is not None:
Session = KubernetesSession
else:
Session = SubprocessSession
Session.name = "session"
|
Improve switching between session types
|
fix(Worker): Improve switching between session types
|
Python
|
apache-2.0
|
stencila/hub,stencila/hub,stencila/hub,stencila/hub,stencila/hub
|
python
|
## Code Before:
import os
from typing import Optional, List
from jobs.base.job import Job
# If on a K8s cluster then use the K8s-based sessions
# otherwise use the subsprocess-based session
if "KUBERNETES_SERVICE_HOST" in os.environ:
from .kubernetes_session import KubernetesSession
Session = KubernetesSession # type: ignore
else:
from .subprocess_session import SubprocessSession
Session = SubprocessSession # type: ignore
Session.name = "session"
## Instruction:
fix(Worker): Improve switching between session types
## Code After:
from typing import Type, Union
from .kubernetes_session import api_instance, KubernetesSession
from .subprocess_session import SubprocessSession
# If on a K8s is available then use that
# otherwise use the subsprocess-based session
Session: Type[Union[KubernetesSession, SubprocessSession]]
if api_instance is not None:
Session = KubernetesSession
else:
Session = SubprocessSession
Session.name = "session"
|
// ... existing code ...
from typing import Type, Union
from .kubernetes_session import api_instance, KubernetesSession
from .subprocess_session import SubprocessSession
# If on a K8s is available then use that
# otherwise use the subsprocess-based session
Session: Type[Union[KubernetesSession, SubprocessSession]]
if api_instance is not None:
Session = KubernetesSession
else:
Session = SubprocessSession
Session.name = "session"
// ... rest of the code ...
|
f6c36bbb5b5afec1a029213557b722e50dd6aaaa
|
test/test_run_script.py
|
test/test_run_script.py
|
def test_dummy():
assert True
|
import subprocess
import pytest
def test_filter(tmp_path):
unit_test = tmp_path.joinpath('some_unit_test.sv')
unit_test.write_text('''
module some_unit_test;
import svunit_pkg::*;
`include "svunit_defines.svh"
string name = "some_ut";
svunit_testcase svunit_ut;
function void build();
svunit_ut = new(name);
endfunction
task setup();
svunit_ut.setup();
endtask
task teardown();
svunit_ut.teardown();
endtask
`SVUNIT_TESTS_BEGIN
`SVTEST(some_failing_test)
`FAIL_IF(1)
`SVTEST_END
`SVTEST(some_passing_test)
`FAIL_IF(0)
`SVTEST_END
`SVUNIT_TESTS_END
endmodule
''')
log = tmp_path.joinpath('run.log')
print('Filtering only the passing test should block the fail')
subprocess.check_call(['runSVUnit', '--filter', 'some_ut.some_passing_test'], cwd=tmp_path)
assert 'FAILED' not in log.read_text()
print('No explicit filter should cause both tests to run, hence trigger the fail')
subprocess.check_call(['runSVUnit'], cwd=tmp_path)
assert 'FAILED' in log.read_text()
|
Add test for '--filter' option
|
Add test for '--filter' option
The goal now is to make this test pass by implementing the necessary
production code.
|
Python
|
apache-2.0
|
svunit/svunit,svunit/svunit,svunit/svunit
|
python
|
## Code Before:
def test_dummy():
assert True
## Instruction:
Add test for '--filter' option
The goal now is to make this test pass by implementing the necessary
production code.
## Code After:
import subprocess
import pytest
def test_filter(tmp_path):
unit_test = tmp_path.joinpath('some_unit_test.sv')
unit_test.write_text('''
module some_unit_test;
import svunit_pkg::*;
`include "svunit_defines.svh"
string name = "some_ut";
svunit_testcase svunit_ut;
function void build();
svunit_ut = new(name);
endfunction
task setup();
svunit_ut.setup();
endtask
task teardown();
svunit_ut.teardown();
endtask
`SVUNIT_TESTS_BEGIN
`SVTEST(some_failing_test)
`FAIL_IF(1)
`SVTEST_END
`SVTEST(some_passing_test)
`FAIL_IF(0)
`SVTEST_END
`SVUNIT_TESTS_END
endmodule
''')
log = tmp_path.joinpath('run.log')
print('Filtering only the passing test should block the fail')
subprocess.check_call(['runSVUnit', '--filter', 'some_ut.some_passing_test'], cwd=tmp_path)
assert 'FAILED' not in log.read_text()
print('No explicit filter should cause both tests to run, hence trigger the fail')
subprocess.check_call(['runSVUnit'], cwd=tmp_path)
assert 'FAILED' in log.read_text()
|
...
import subprocess
import pytest
def test_filter(tmp_path):
unit_test = tmp_path.joinpath('some_unit_test.sv')
unit_test.write_text('''
module some_unit_test;
import svunit_pkg::*;
`include "svunit_defines.svh"
string name = "some_ut";
svunit_testcase svunit_ut;
function void build();
svunit_ut = new(name);
endfunction
task setup();
svunit_ut.setup();
endtask
task teardown();
svunit_ut.teardown();
endtask
`SVUNIT_TESTS_BEGIN
`SVTEST(some_failing_test)
`FAIL_IF(1)
`SVTEST_END
`SVTEST(some_passing_test)
`FAIL_IF(0)
`SVTEST_END
`SVUNIT_TESTS_END
endmodule
''')
log = tmp_path.joinpath('run.log')
print('Filtering only the passing test should block the fail')
subprocess.check_call(['runSVUnit', '--filter', 'some_ut.some_passing_test'], cwd=tmp_path)
assert 'FAILED' not in log.read_text()
print('No explicit filter should cause both tests to run, hence trigger the fail')
subprocess.check_call(['runSVUnit'], cwd=tmp_path)
assert 'FAILED' in log.read_text()
...
|
b89e4597612250df5b5a06917eaaf411ab4311c9
|
goci-data-services/goci-data-validation-services/src/main/java/uk/ac/ebi/spot/goci/service/AssociationCheckingService.java
|
goci-data-services/goci-data-validation-services/src/main/java/uk/ac/ebi/spot/goci/service/AssociationCheckingService.java
|
package uk.ac.ebi.spot.goci.service;
import uk.ac.ebi.spot.goci.model.Association;
import uk.ac.ebi.spot.goci.model.ValidationError;
import java.util.Collection;
/**
* Created by emma on 01/04/2016.
*
* @author emma
* <p>
* Interface that defines method(s) to run error ckecking of an association and then return a collection of
* errors.
*/
public interface AssociationCheckingService {
Collection<ValidationError> runChecks(Association association, ValidationChecksBuilder validationChecksBuilder);
/**
* Check if association is an OR or BETA type association
*
* @param association Association to check
*/
default String determineIfAssociationIsOrType(Association association) {
String effectType = "none";
if (association.getBetaNum() != null) {
effectType = "beta";
}
else {
if (association.getOrPerCopyNum() != null) {
effectType = "or";
}
}
return effectType;
}
}
|
package uk.ac.ebi.spot.goci.service;
import uk.ac.ebi.spot.goci.model.Association;
import uk.ac.ebi.spot.goci.model.ValidationError;
import java.util.Collection;
/**
* Created by emma on 01/04/2016.
*
* @author emma
* <p>
* Interface that defines method(s) to run error ckecking of an association and then return a collection of
* errors.
*/
public interface AssociationCheckingService {
Collection<ValidationError> runChecks(Association association, ValidationChecksBuilder validationChecksBuilder);
/**
* Check if association is an OR or BETA type association
*
* @param association Association to check
*/
default String determineIfAssociationIsOrType(Association association) {
String effectType = "none";
if (association.getOrPerCopyNum() != null) {
effectType = "or";
}
else {
if (association.getBetaNum() != null) {
effectType = "beta";
}
}
return effectType;
}
}
|
Update determine association type method
|
Update determine association type method
|
Java
|
apache-2.0
|
EBISPOT/goci,EBISPOT/goci,EBISPOT/goci,EBISPOT/goci,EBISPOT/goci,EBISPOT/goci
|
java
|
## Code Before:
package uk.ac.ebi.spot.goci.service;
import uk.ac.ebi.spot.goci.model.Association;
import uk.ac.ebi.spot.goci.model.ValidationError;
import java.util.Collection;
/**
* Created by emma on 01/04/2016.
*
* @author emma
* <p>
* Interface that defines method(s) to run error ckecking of an association and then return a collection of
* errors.
*/
public interface AssociationCheckingService {
Collection<ValidationError> runChecks(Association association, ValidationChecksBuilder validationChecksBuilder);
/**
* Check if association is an OR or BETA type association
*
* @param association Association to check
*/
default String determineIfAssociationIsOrType(Association association) {
String effectType = "none";
if (association.getBetaNum() != null) {
effectType = "beta";
}
else {
if (association.getOrPerCopyNum() != null) {
effectType = "or";
}
}
return effectType;
}
}
## Instruction:
Update determine association type method
## Code After:
package uk.ac.ebi.spot.goci.service;
import uk.ac.ebi.spot.goci.model.Association;
import uk.ac.ebi.spot.goci.model.ValidationError;
import java.util.Collection;
/**
* Created by emma on 01/04/2016.
*
* @author emma
* <p>
* Interface that defines method(s) to run error ckecking of an association and then return a collection of
* errors.
*/
public interface AssociationCheckingService {
Collection<ValidationError> runChecks(Association association, ValidationChecksBuilder validationChecksBuilder);
/**
* Check if association is an OR or BETA type association
*
* @param association Association to check
*/
default String determineIfAssociationIsOrType(Association association) {
String effectType = "none";
if (association.getOrPerCopyNum() != null) {
effectType = "or";
}
else {
if (association.getBetaNum() != null) {
effectType = "beta";
}
}
return effectType;
}
}
|
...
default String determineIfAssociationIsOrType(Association association) {
String effectType = "none";
if (association.getOrPerCopyNum() != null) {
effectType = "or";
}
else {
if (association.getBetaNum() != null) {
effectType = "beta";
}
}
return effectType;
...
|
6ff6bdad9f7544be103e798838c12509411a2098
|
tests/__init__.py
|
tests/__init__.py
|
import logging
from unittest import TestCase
import datetime
from redash import settings
settings.DATABASE_CONFIG = {
'name': 'circle_test',
'threadlocals': True
}
settings.REDIS_URL = "redis://localhost:6379/5"
from redash import models, redis_connection
logging.getLogger('peewee').setLevel(logging.INFO)
class BaseTestCase(TestCase):
def setUp(self):
models.create_db(True, True)
models.init_db()
def tearDown(self):
models.db.close_db(None)
models.create_db(False, True)
redis_connection.flushdb()
def assertResponseEqual(self, expected, actual):
for k, v in expected.iteritems():
if isinstance(v, datetime.datetime) or isinstance(actual[k], datetime.datetime):
continue
if isinstance(v, list):
continue
if isinstance(v, dict):
self.assertResponseEqual(v, actual[k])
continue
self.assertEqual(v, actual[k], "{} not equal (expected: {}, actual: {}).".format(k, v, actual[k]))
|
import os
os.environ['REDASH_REDIS_URL'] = "redis://localhost:6379/5"
import logging
from unittest import TestCase
import datetime
from redash import settings
settings.DATABASE_CONFIG = {
'name': 'circle_test',
'threadlocals': True
}
from redash import models, redis_connection
logging.getLogger('peewee').setLevel(logging.INFO)
class BaseTestCase(TestCase):
def setUp(self):
models.create_db(True, True)
models.init_db()
def tearDown(self):
models.db.close_db(None)
models.create_db(False, True)
redis_connection.flushdb()
def assertResponseEqual(self, expected, actual):
for k, v in expected.iteritems():
if isinstance(v, datetime.datetime) or isinstance(actual[k], datetime.datetime):
continue
if isinstance(v, list):
continue
if isinstance(v, dict):
self.assertResponseEqual(v, actual[k])
continue
self.assertEqual(v, actual[k], "{} not equal (expected: {}, actual: {}).".format(k, v, actual[k]))
|
Use the correct redis connection in tests
|
Use the correct redis connection in tests
|
Python
|
bsd-2-clause
|
guaguadev/redash,vishesh92/redash,easytaxibr/redash,guaguadev/redash,pubnative/redash,M32Media/redash,vishesh92/redash,rockwotj/redash,amino-data/redash,pubnative/redash,chriszs/redash,alexanderlz/redash,stefanseifert/redash,vishesh92/redash,hudl/redash,ninneko/redash,easytaxibr/redash,akariv/redash,denisov-vlad/redash,denisov-vlad/redash,M32Media/redash,crowdworks/redash,imsally/redash,ninneko/redash,crowdworks/redash,getredash/redash,imsally/redash,chriszs/redash,guaguadev/redash,useabode/redash,imsally/redash,akariv/redash,44px/redash,easytaxibr/redash,useabode/redash,chriszs/redash,easytaxibr/redash,easytaxibr/redash,rockwotj/redash,moritz9/redash,vishesh92/redash,akariv/redash,getredash/redash,denisov-vlad/redash,useabode/redash,chriszs/redash,useabode/redash,stefanseifert/redash,getredash/redash,pubnative/redash,44px/redash,guaguadev/redash,getredash/redash,alexanderlz/redash,rockwotj/redash,stefanseifert/redash,crowdworks/redash,rockwotj/redash,denisov-vlad/redash,jmvasquez/redashtest,jmvasquez/redashtest,crowdworks/redash,EverlyWell/redash,amino-data/redash,amino-data/redash,44px/redash,pubnative/redash,hudl/redash,EverlyWell/redash,jmvasquez/redashtest,M32Media/redash,hudl/redash,alexanderlz/redash,pubnative/redash,stefanseifert/redash,ninneko/redash,akariv/redash,getredash/redash,stefanseifert/redash,imsally/redash,M32Media/redash,alexanderlz/redash,ninneko/redash,denisov-vlad/redash,akariv/redash,jmvasquez/redashtest,EverlyWell/redash,hudl/redash,ninneko/redash,moritz9/redash,moritz9/redash,guaguadev/redash,amino-data/redash,44px/redash,EverlyWell/redash,moritz9/redash,jmvasquez/redashtest
|
python
|
## Code Before:
import logging
from unittest import TestCase
import datetime
from redash import settings
settings.DATABASE_CONFIG = {
'name': 'circle_test',
'threadlocals': True
}
settings.REDIS_URL = "redis://localhost:6379/5"
from redash import models, redis_connection
logging.getLogger('peewee').setLevel(logging.INFO)
class BaseTestCase(TestCase):
def setUp(self):
models.create_db(True, True)
models.init_db()
def tearDown(self):
models.db.close_db(None)
models.create_db(False, True)
redis_connection.flushdb()
def assertResponseEqual(self, expected, actual):
for k, v in expected.iteritems():
if isinstance(v, datetime.datetime) or isinstance(actual[k], datetime.datetime):
continue
if isinstance(v, list):
continue
if isinstance(v, dict):
self.assertResponseEqual(v, actual[k])
continue
self.assertEqual(v, actual[k], "{} not equal (expected: {}, actual: {}).".format(k, v, actual[k]))
## Instruction:
Use the correct redis connection in tests
## Code After:
import os
os.environ['REDASH_REDIS_URL'] = "redis://localhost:6379/5"
import logging
from unittest import TestCase
import datetime
from redash import settings
settings.DATABASE_CONFIG = {
'name': 'circle_test',
'threadlocals': True
}
from redash import models, redis_connection
logging.getLogger('peewee').setLevel(logging.INFO)
class BaseTestCase(TestCase):
def setUp(self):
models.create_db(True, True)
models.init_db()
def tearDown(self):
models.db.close_db(None)
models.create_db(False, True)
redis_connection.flushdb()
def assertResponseEqual(self, expected, actual):
for k, v in expected.iteritems():
if isinstance(v, datetime.datetime) or isinstance(actual[k], datetime.datetime):
continue
if isinstance(v, list):
continue
if isinstance(v, dict):
self.assertResponseEqual(v, actual[k])
continue
self.assertEqual(v, actual[k], "{} not equal (expected: {}, actual: {}).".format(k, v, actual[k]))
|
# ... existing code ...
import os
os.environ['REDASH_REDIS_URL'] = "redis://localhost:6379/5"
import logging
from unittest import TestCase
import datetime
from redash import settings
settings.DATABASE_CONFIG = {
'name': 'circle_test',
'threadlocals': True
}
from redash import models, redis_connection
# ... rest of the code ...
|
e1291e88e8d5cf1f50e9547fa78a4a53032cc89a
|
reproject/overlap.py
|
reproject/overlap.py
|
from ._overlap_wrapper import _computeOverlap
def compute_overlap(ilon, ilat, olon, olat, energy_mode=True, reference_area=1.):
"""
Compute the overlap between two 'pixels' in spherical coordinates
Parameters
----------
ilon : np.ndarray
The longitudes defining the four corners of the input pixel
ilat : np.ndarray
The latitudes defining the four corners of the input pixel
olon : np.ndarray
The longitudes defining the four corners of the output pixel
olat : np.ndarray
The latitudes defining the four corners of the output pixel
energy_mode : bool
Whether to work in energy-conserving or surface-brightness-conserving mode
reference_area : float
To be determined
"""
return _computeOverlap(ilon, ilat, olon, olat, int(energy_mode), reference_area)
|
from ._overlap_wrapper import _computeOverlap
def compute_overlap(ilon, ilat, olon, olat):
"""
Compute the overlap between two 'pixels' in spherical coordinates
Parameters
----------
ilon : np.ndarray
The longitudes defining the four corners of the input pixel
ilat : np.ndarray
The latitudes defining the four corners of the input pixel
olon : np.ndarray
The longitudes defining the four corners of the output pixel
olat : np.ndarray
The latitudes defining the four corners of the output pixel
"""
return _computeOverlap(ilon, ilat, olon, olat, 0, 1.)
|
Remove options until we actually need and understand them
|
Remove options until we actually need and understand them
|
Python
|
bsd-3-clause
|
barentsen/reproject,astrofrog/reproject,barentsen/reproject,mwcraig/reproject,astrofrog/reproject,astrofrog/reproject,mwcraig/reproject,barentsen/reproject,bsipocz/reproject,bsipocz/reproject
|
python
|
## Code Before:
from ._overlap_wrapper import _computeOverlap
def compute_overlap(ilon, ilat, olon, olat, energy_mode=True, reference_area=1.):
"""
Compute the overlap between two 'pixels' in spherical coordinates
Parameters
----------
ilon : np.ndarray
The longitudes defining the four corners of the input pixel
ilat : np.ndarray
The latitudes defining the four corners of the input pixel
olon : np.ndarray
The longitudes defining the four corners of the output pixel
olat : np.ndarray
The latitudes defining the four corners of the output pixel
energy_mode : bool
Whether to work in energy-conserving or surface-brightness-conserving mode
reference_area : float
To be determined
"""
return _computeOverlap(ilon, ilat, olon, olat, int(energy_mode), reference_area)
## Instruction:
Remove options until we actually need and understand them
## Code After:
from ._overlap_wrapper import _computeOverlap
def compute_overlap(ilon, ilat, olon, olat):
"""
Compute the overlap between two 'pixels' in spherical coordinates
Parameters
----------
ilon : np.ndarray
The longitudes defining the four corners of the input pixel
ilat : np.ndarray
The latitudes defining the four corners of the input pixel
olon : np.ndarray
The longitudes defining the four corners of the output pixel
olat : np.ndarray
The latitudes defining the four corners of the output pixel
"""
return _computeOverlap(ilon, ilat, olon, olat, 0, 1.)
|
...
from ._overlap_wrapper import _computeOverlap
def compute_overlap(ilon, ilat, olon, olat):
"""
Compute the overlap between two 'pixels' in spherical coordinates
...
The longitudes defining the four corners of the output pixel
olat : np.ndarray
The latitudes defining the four corners of the output pixel
"""
return _computeOverlap(ilon, ilat, olon, olat, 0, 1.)
...
|
ef0b1d076b6a4a3954358e07f432a3e57b1e0e4e
|
Classes/APIAFNetworkingHTTPClient.h
|
Classes/APIAFNetworkingHTTPClient.h
|
//
// APIAFNetworkingHTTPClient.h
// APIClient
//
// Created by Klaas Pieter Annema on 30-08-13.
// Copyright (c) 2013 Klaas Pieter Annema. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "AFNetworking.h"
#import "APIHTTPClient.h"
@interface APIAFNetworkingHTTPClient : NSObject <APIHTTPClient>
@property (nonatomic, readonly, copy) NSURL *baseURL;
@property (nonatomic, readonly, strong) NSURLSessionConfiguration *sessionConfiguration;
- (id)initWithBaseURL:(NSURL *)baseURL;
- (id)initWithBaseURL:(NSURL *)baseURL
sessionConfiguration:(NSURLSessionConfiguration *)sessionConfiguration NS_DESIGNATED_INITIALIZER;
@end
|
//
// APIAFNetworkingHTTPClient.h
// APIClient
//
// Created by Klaas Pieter Annema on 30-08-13.
// Copyright (c) 2013 Klaas Pieter Annema. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <AFNetworking/AFNetworking.h>
#import "APIHTTPClient.h"
@interface APIAFNetworkingHTTPClient : NSObject <APIHTTPClient>
@property (nonatomic, readonly, copy) NSURL *baseURL;
@property (nonatomic, readonly, strong) NSURLSessionConfiguration *sessionConfiguration;
- (id)initWithBaseURL:(NSURL *)baseURL;
- (id)initWithBaseURL:(NSURL *)baseURL
sessionConfiguration:(NSURLSessionConfiguration *)sessionConfiguration NS_DESIGNATED_INITIALIZER;
@end
|
Use the correct import syntax
|
Use the correct import syntax
|
C
|
mit
|
klaaspieter/APIClient
|
c
|
## Code Before:
//
// APIAFNetworkingHTTPClient.h
// APIClient
//
// Created by Klaas Pieter Annema on 30-08-13.
// Copyright (c) 2013 Klaas Pieter Annema. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "AFNetworking.h"
#import "APIHTTPClient.h"
@interface APIAFNetworkingHTTPClient : NSObject <APIHTTPClient>
@property (nonatomic, readonly, copy) NSURL *baseURL;
@property (nonatomic, readonly, strong) NSURLSessionConfiguration *sessionConfiguration;
- (id)initWithBaseURL:(NSURL *)baseURL;
- (id)initWithBaseURL:(NSURL *)baseURL
sessionConfiguration:(NSURLSessionConfiguration *)sessionConfiguration NS_DESIGNATED_INITIALIZER;
@end
## Instruction:
Use the correct import syntax
## Code After:
//
// APIAFNetworkingHTTPClient.h
// APIClient
//
// Created by Klaas Pieter Annema on 30-08-13.
// Copyright (c) 2013 Klaas Pieter Annema. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <AFNetworking/AFNetworking.h>
#import "APIHTTPClient.h"
@interface APIAFNetworkingHTTPClient : NSObject <APIHTTPClient>
@property (nonatomic, readonly, copy) NSURL *baseURL;
@property (nonatomic, readonly, strong) NSURLSessionConfiguration *sessionConfiguration;
- (id)initWithBaseURL:(NSURL *)baseURL;
- (id)initWithBaseURL:(NSURL *)baseURL
sessionConfiguration:(NSURLSessionConfiguration *)sessionConfiguration NS_DESIGNATED_INITIALIZER;
@end
|
# ... existing code ...
//
#import <Foundation/Foundation.h>
#import <AFNetworking/AFNetworking.h>
#import "APIHTTPClient.h"
# ... rest of the code ...
|
1b80972fe97bebbb20d9e6073b41d286f253c1ef
|
documents/views/utils.py
|
documents/views/utils.py
|
import mimetypes
import os
from django.http import HttpResponse
mimetypes.init()
mimetypes.add_type('application/epub+zip','.epub')
mimetypes.add_type('text/x-brl','.brl')
mimetypes.add_type('text/x-sbsform-g0','.bv')
mimetypes.add_type('text/x-sbsform-g1','.bv')
mimetypes.add_type('text/x-sbsform-g2','.bk')
def render_to_mimetype_response(mimetype, filename, outputFile):
ext = mimetypes.guess_extension(mimetype)
assert ext != None
response = HttpResponse(mimetype=mimetype)
response['Content-Disposition'] = "attachment; filename=\"%s%s\"" % (filename, ext)
f = open(outputFile)
try:
content = f.read()
response.write(content)
finally:
f.close()
# remove the tmp file
os.remove(outputFile)
return response
|
import mimetypes
import os
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
mimetypes.init()
mimetypes.add_type('application/epub+zip','.epub')
mimetypes.add_type('text/x-brl','.brl')
mimetypes.add_type('text/x-sbsform-g0','.bv')
mimetypes.add_type('text/x-sbsform-g1','.bv')
mimetypes.add_type('text/x-sbsform-g2','.bk')
def render_to_mimetype_response(mimetype, filename, outputFile):
ext = mimetypes.guess_extension(mimetype)
assert ext != None
wrapper = FileWrapper(file(outputFile))
response = HttpResponse(wrapper, mimetype=mimetype)
response['Content-Disposition'] = "attachment; filename=\"%s%s\"" % (filename, ext)
response['Content-Length'] = os.path.getsize(outputFile)
# remove the tmp file
os.remove(outputFile)
return response
|
Use FileWrapper to send files to browser in chunks of 8KB
|
Use FileWrapper to send files to browser in chunks of 8KB
Maybe this will fix a problem on the test server when it tries to send a huge file.
|
Python
|
agpl-3.0
|
sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer
|
python
|
## Code Before:
import mimetypes
import os
from django.http import HttpResponse
mimetypes.init()
mimetypes.add_type('application/epub+zip','.epub')
mimetypes.add_type('text/x-brl','.brl')
mimetypes.add_type('text/x-sbsform-g0','.bv')
mimetypes.add_type('text/x-sbsform-g1','.bv')
mimetypes.add_type('text/x-sbsform-g2','.bk')
def render_to_mimetype_response(mimetype, filename, outputFile):
ext = mimetypes.guess_extension(mimetype)
assert ext != None
response = HttpResponse(mimetype=mimetype)
response['Content-Disposition'] = "attachment; filename=\"%s%s\"" % (filename, ext)
f = open(outputFile)
try:
content = f.read()
response.write(content)
finally:
f.close()
# remove the tmp file
os.remove(outputFile)
return response
## Instruction:
Use FileWrapper to send files to browser in chunks of 8KB
Maybe this will fix a problem on the test server when it tries to send a huge file.
## Code After:
import mimetypes
import os
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
mimetypes.init()
mimetypes.add_type('application/epub+zip','.epub')
mimetypes.add_type('text/x-brl','.brl')
mimetypes.add_type('text/x-sbsform-g0','.bv')
mimetypes.add_type('text/x-sbsform-g1','.bv')
mimetypes.add_type('text/x-sbsform-g2','.bk')
def render_to_mimetype_response(mimetype, filename, outputFile):
ext = mimetypes.guess_extension(mimetype)
assert ext != None
wrapper = FileWrapper(file(outputFile))
response = HttpResponse(wrapper, mimetype=mimetype)
response['Content-Disposition'] = "attachment; filename=\"%s%s\"" % (filename, ext)
response['Content-Length'] = os.path.getsize(outputFile)
# remove the tmp file
os.remove(outputFile)
return response
|
...
import os
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
mimetypes.init()
mimetypes.add_type('application/epub+zip','.epub')
...
def render_to_mimetype_response(mimetype, filename, outputFile):
ext = mimetypes.guess_extension(mimetype)
assert ext != None
wrapper = FileWrapper(file(outputFile))
response = HttpResponse(wrapper, mimetype=mimetype)
response['Content-Disposition'] = "attachment; filename=\"%s%s\"" % (filename, ext)
response['Content-Length'] = os.path.getsize(outputFile)
# remove the tmp file
os.remove(outputFile)
return response
...
|
6740467a15a54d4ca0bf0a7e358e2e5c92e04344
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
import re
VERSIONFILE = "openomni/_version.py"
verstrline = open(VERSIONFILE, "rt").read()
VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]"
mo = re.search(VSRE, verstrline, re.M)
if mo:
verstr = mo.group(1)
else:
raise RuntimeError("Unable to find version string in %s." % (VERSIONFILE,))
setup(name='openomni',
version=verstr,
description='Omnipod Packet Decoding Library',
url='http://github.com/openaps/omni',
# See https://github.com/openaps/openomni/graphs/contributors for actual
# contributors...
author='Pete Schwamb',
author_email='[email protected]',
scripts=[
'openomni/bin/decode_omni',
'openomni/bin/omni_listen_rfcat',
'openomni/bin/omni_akimbo',
'openomni/bin/omni_explore',
'openomni/bin/omni_send_rfcat',
'openomni/bin/omni_forloop'],
packages=find_packages(),
install_requires=[
'crccheck',
],
zip_safe=False)
|
from setuptools import setup, find_packages
import re
VERSIONFILE = "openomni/_version.py"
verstrline = open(VERSIONFILE, "rt").read()
VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]"
mo = re.search(VSRE, verstrline, re.M)
if mo:
verstr = mo.group(1)
else:
raise RuntimeError("Unable to find version string in %s." % (VERSIONFILE,))
setup(name='openomni',
version=verstr,
description='Omnipod Packet Decoding Library',
url='http://github.com/openaps/omni',
# See https://github.com/openaps/openomni/graphs/contributors for actual
# contributors...
author='Pete Schwamb',
author_email='[email protected]',
scripts=[
'openomni/bin/decode_omni',
'openomni/bin/omni_listen_rfcat',
'openomni/bin/omni_akimbo',
'openomni/bin/omni_explore',
'openomni/bin/omni_send_rfcat',
'openomni/bin/omni_forloop'],
packages=find_packages(),
install_requires=[
'crccheck',
'enum34;python_version<"3.4"',
],
zip_safe=False)
|
Install enum34 if not provided
|
Install enum34 if not provided
|
Python
|
mit
|
openaps/openomni,openaps/openomni,openaps/openomni
|
python
|
## Code Before:
from setuptools import setup, find_packages
import re
VERSIONFILE = "openomni/_version.py"
verstrline = open(VERSIONFILE, "rt").read()
VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]"
mo = re.search(VSRE, verstrline, re.M)
if mo:
verstr = mo.group(1)
else:
raise RuntimeError("Unable to find version string in %s." % (VERSIONFILE,))
setup(name='openomni',
version=verstr,
description='Omnipod Packet Decoding Library',
url='http://github.com/openaps/omni',
# See https://github.com/openaps/openomni/graphs/contributors for actual
# contributors...
author='Pete Schwamb',
author_email='[email protected]',
scripts=[
'openomni/bin/decode_omni',
'openomni/bin/omni_listen_rfcat',
'openomni/bin/omni_akimbo',
'openomni/bin/omni_explore',
'openomni/bin/omni_send_rfcat',
'openomni/bin/omni_forloop'],
packages=find_packages(),
install_requires=[
'crccheck',
],
zip_safe=False)
## Instruction:
Install enum34 if not provided
## Code After:
from setuptools import setup, find_packages
import re
VERSIONFILE = "openomni/_version.py"
verstrline = open(VERSIONFILE, "rt").read()
VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]"
mo = re.search(VSRE, verstrline, re.M)
if mo:
verstr = mo.group(1)
else:
raise RuntimeError("Unable to find version string in %s." % (VERSIONFILE,))
setup(name='openomni',
version=verstr,
description='Omnipod Packet Decoding Library',
url='http://github.com/openaps/omni',
# See https://github.com/openaps/openomni/graphs/contributors for actual
# contributors...
author='Pete Schwamb',
author_email='[email protected]',
scripts=[
'openomni/bin/decode_omni',
'openomni/bin/omni_listen_rfcat',
'openomni/bin/omni_akimbo',
'openomni/bin/omni_explore',
'openomni/bin/omni_send_rfcat',
'openomni/bin/omni_forloop'],
packages=find_packages(),
install_requires=[
'crccheck',
'enum34;python_version<"3.4"',
],
zip_safe=False)
|
// ... existing code ...
packages=find_packages(),
install_requires=[
'crccheck',
'enum34;python_version<"3.4"',
],
zip_safe=False)
// ... rest of the code ...
|
b237e4cc2dd5b0d09fff6bb08bda087f32c569bb
|
src/protocolsupport/api/chat/modifiers/ClickAction.java
|
src/protocolsupport/api/chat/modifiers/ClickAction.java
|
package protocolsupport.api.chat.modifiers;
import java.net.MalformedURLException;
import java.net.URL;
import protocolsupport.utils.Utils;
public class ClickAction {
private final Type type;
private final String value;
public ClickAction(Type action, String value) {
this.type = action;
this.value = value;
}
public ClickAction(URL url) {
this.type = Type.OPEN_URL;
this.value = url.toString();
}
public Type getType() {
return type;
}
public String getValue() {
return value;
}
public URL getUrl() throws MalformedURLException {
if (type == Type.OPEN_URL) {
return new URL(value);
}
throw new IllegalStateException(type + " is not an " + Type.OPEN_URL);
}
@Override
public String toString() {
return Utils.toStringAllFields(this);
}
public static enum Type {
OPEN_URL, OPEN_FILE, RUN_COMMAND, TWITCH_USER_INFO, SUGGEST_COMMAND, CHANGE_PAGE;
}
}
|
package protocolsupport.api.chat.modifiers;
import java.net.MalformedURLException;
import java.net.URL;
import protocolsupport.utils.Utils;
public class ClickAction {
private final Type type;
private final String value;
public ClickAction(Type action, String value) {
this.type = action;
this.value = value;
}
public ClickAction(URL url) {
this.type = Type.OPEN_URL;
this.value = url.toString();
}
public Type getType() {
return type;
}
public String getValue() {
return value;
}
public URL getUrl() throws MalformedURLException {
if (type == Type.OPEN_URL) {
return new URL(value);
}
throw new IllegalStateException(type + " is not an " + Type.OPEN_URL);
}
@Override
public String toString() {
return Utils.toStringAllFields(this);
}
public static enum Type {
OPEN_URL, OPEN_FILE, RUN_COMMAND, TWITCH_USER_INFO, SUGGEST_COMMAND, CHANGE_PAGE, COPY_TO_CLIPBOARD;
}
}
|
Add click action copy to clipboard
|
Add click action copy to clipboard
|
Java
|
agpl-3.0
|
ProtocolSupport/ProtocolSupport
|
java
|
## Code Before:
package protocolsupport.api.chat.modifiers;
import java.net.MalformedURLException;
import java.net.URL;
import protocolsupport.utils.Utils;
public class ClickAction {
private final Type type;
private final String value;
public ClickAction(Type action, String value) {
this.type = action;
this.value = value;
}
public ClickAction(URL url) {
this.type = Type.OPEN_URL;
this.value = url.toString();
}
public Type getType() {
return type;
}
public String getValue() {
return value;
}
public URL getUrl() throws MalformedURLException {
if (type == Type.OPEN_URL) {
return new URL(value);
}
throw new IllegalStateException(type + " is not an " + Type.OPEN_URL);
}
@Override
public String toString() {
return Utils.toStringAllFields(this);
}
public static enum Type {
OPEN_URL, OPEN_FILE, RUN_COMMAND, TWITCH_USER_INFO, SUGGEST_COMMAND, CHANGE_PAGE;
}
}
## Instruction:
Add click action copy to clipboard
## Code After:
package protocolsupport.api.chat.modifiers;
import java.net.MalformedURLException;
import java.net.URL;
import protocolsupport.utils.Utils;
public class ClickAction {
private final Type type;
private final String value;
public ClickAction(Type action, String value) {
this.type = action;
this.value = value;
}
public ClickAction(URL url) {
this.type = Type.OPEN_URL;
this.value = url.toString();
}
public Type getType() {
return type;
}
public String getValue() {
return value;
}
public URL getUrl() throws MalformedURLException {
if (type == Type.OPEN_URL) {
return new URL(value);
}
throw new IllegalStateException(type + " is not an " + Type.OPEN_URL);
}
@Override
public String toString() {
return Utils.toStringAllFields(this);
}
public static enum Type {
OPEN_URL, OPEN_FILE, RUN_COMMAND, TWITCH_USER_INFO, SUGGEST_COMMAND, CHANGE_PAGE, COPY_TO_CLIPBOARD;
}
}
|
...
}
public static enum Type {
OPEN_URL, OPEN_FILE, RUN_COMMAND, TWITCH_USER_INFO, SUGGEST_COMMAND, CHANGE_PAGE, COPY_TO_CLIPBOARD;
}
}
...
|
064c0161e91e24217d712cb80656a2d0dad8c3b6
|
pretty.py
|
pretty.py
|
from termcolor import colored
def section(msg):
print(colored("\n::", "blue", attrs=["bold"]), colored(msg, attrs=["bold"]))
def task(msg):
print(colored("==>", "green", attrs=["bold"]), colored(msg, attrs=["bold"]))
def subtask(msg):
print(colored(" ->", "blue", attrs=["bold"]), colored(msg, attrs=["bold"]))
from progressbar import Bar, SimpleProgress, Percentage, ProgressBar, Timer, AbsoluteETA
def progress(number, **kwargs):
return ProgressBar(max_value=number, widgets=[Percentage(), ' (', SimpleProgress(), ') ', Bar(), ' ', Timer(), ' ', AbsoluteETA()], **kwargs).start()
|
from termcolor import colored
import datetime
def section(msg):
print(colored("\n::", "blue", attrs=["bold"]), colored(msg, attrs=["bold"]))
def task(msg):
print(colored("==>", "green", attrs=["bold"]), colored(msg, attrs=["bold"]))
def subtask(msg):
print(colored(" ->", "blue", attrs=["bold"]), colored(msg, attrs=["bold"]))
from progressbar import Bar, SimpleProgress, Percentage, ProgressBar, Timer
class AbsoluteETABrief(Timer):
'''Variation of progressbar.AbsoluteETA which is smaller for 80cols.'''
def _eta(self, progress, data, value, elapsed):
"""Update the widget to show the ETA or total time when finished."""
if value == progress.min_value: # pragma: no cover
return 'ETA: --:--:--'
elif progress.end_time:
return 'Fin: %s' % self._format(progress.end_time)
else:
eta = elapsed * progress.max_value / value - elapsed
now = datetime.datetime.now()
eta_abs = now + datetime.timedelta(seconds=eta)
return 'ETA: %s' % self._format(eta_abs)
def _format(self, t):
return t.strftime("%H:%M:%S")
def __call__(self, progress, data):
'''Updates the widget to show the ETA or total time when finished.'''
return self._eta(progress, data, data['value'],
data['total_seconds_elapsed'])
def progress(number, **kwargs):
return ProgressBar(max_value=number, widgets=[Percentage(), ' (', SimpleProgress(), ') ', Bar(), ' ', Timer(), ' ', AbsoluteETABrief()], **kwargs).start()
|
Fix progress bar to be 80-col-friendly.
|
Fix progress bar to be 80-col-friendly.
|
Python
|
mit
|
jonhoo/periscope,jonhoo/periscope
|
python
|
## Code Before:
from termcolor import colored
def section(msg):
print(colored("\n::", "blue", attrs=["bold"]), colored(msg, attrs=["bold"]))
def task(msg):
print(colored("==>", "green", attrs=["bold"]), colored(msg, attrs=["bold"]))
def subtask(msg):
print(colored(" ->", "blue", attrs=["bold"]), colored(msg, attrs=["bold"]))
from progressbar import Bar, SimpleProgress, Percentage, ProgressBar, Timer, AbsoluteETA
def progress(number, **kwargs):
return ProgressBar(max_value=number, widgets=[Percentage(), ' (', SimpleProgress(), ') ', Bar(), ' ', Timer(), ' ', AbsoluteETA()], **kwargs).start()
## Instruction:
Fix progress bar to be 80-col-friendly.
## Code After:
from termcolor import colored
import datetime
def section(msg):
print(colored("\n::", "blue", attrs=["bold"]), colored(msg, attrs=["bold"]))
def task(msg):
print(colored("==>", "green", attrs=["bold"]), colored(msg, attrs=["bold"]))
def subtask(msg):
print(colored(" ->", "blue", attrs=["bold"]), colored(msg, attrs=["bold"]))
from progressbar import Bar, SimpleProgress, Percentage, ProgressBar, Timer
class AbsoluteETABrief(Timer):
'''Variation of progressbar.AbsoluteETA which is smaller for 80cols.'''
def _eta(self, progress, data, value, elapsed):
"""Update the widget to show the ETA or total time when finished."""
if value == progress.min_value: # pragma: no cover
return 'ETA: --:--:--'
elif progress.end_time:
return 'Fin: %s' % self._format(progress.end_time)
else:
eta = elapsed * progress.max_value / value - elapsed
now = datetime.datetime.now()
eta_abs = now + datetime.timedelta(seconds=eta)
return 'ETA: %s' % self._format(eta_abs)
def _format(self, t):
return t.strftime("%H:%M:%S")
def __call__(self, progress, data):
'''Updates the widget to show the ETA or total time when finished.'''
return self._eta(progress, data, data['value'],
data['total_seconds_elapsed'])
def progress(number, **kwargs):
return ProgressBar(max_value=number, widgets=[Percentage(), ' (', SimpleProgress(), ') ', Bar(), ' ', Timer(), ' ', AbsoluteETABrief()], **kwargs).start()
|
// ... existing code ...
from termcolor import colored
import datetime
def section(msg):
print(colored("\n::", "blue", attrs=["bold"]), colored(msg, attrs=["bold"]))
// ... modified code ...
def subtask(msg):
print(colored(" ->", "blue", attrs=["bold"]), colored(msg, attrs=["bold"]))
from progressbar import Bar, SimpleProgress, Percentage, ProgressBar, Timer
class AbsoluteETABrief(Timer):
'''Variation of progressbar.AbsoluteETA which is smaller for 80cols.'''
def _eta(self, progress, data, value, elapsed):
"""Update the widget to show the ETA or total time when finished."""
if value == progress.min_value: # pragma: no cover
return 'ETA: --:--:--'
elif progress.end_time:
return 'Fin: %s' % self._format(progress.end_time)
else:
eta = elapsed * progress.max_value / value - elapsed
now = datetime.datetime.now()
eta_abs = now + datetime.timedelta(seconds=eta)
return 'ETA: %s' % self._format(eta_abs)
def _format(self, t):
return t.strftime("%H:%M:%S")
def __call__(self, progress, data):
'''Updates the widget to show the ETA or total time when finished.'''
return self._eta(progress, data, data['value'],
data['total_seconds_elapsed'])
def progress(number, **kwargs):
return ProgressBar(max_value=number, widgets=[Percentage(), ' (', SimpleProgress(), ') ', Bar(), ' ', Timer(), ' ', AbsoluteETABrief()], **kwargs).start()
// ... rest of the code ...
|
1648e071fe69ba159261f27e4b2d0e2b977d6d83
|
zou/app/models/working_file.py
|
zou/app/models/working_file.py
|
from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class WorkingFile(db.Model, BaseMixin, SerializerMixin):
shotgun_id = db.Column(db.Integer())
name = db.Column(db.String(250))
description = db.Column(db.String(200))
comment = db.Column(db.Text())
revision = db.Column(db.Integer())
size = db.Column(db.Integer())
checksum = db.Column(db.Integer())
task_id = db.Column(UUIDType(binary=False), db.ForeignKey("task.id"))
entity_id = db.Column(UUIDType(binary=False), db.ForeignKey("entity.id"))
person_id = \
db.Column(UUIDType(binary=False), db.ForeignKey("person.id"))
__table_args__ = (
db.UniqueConstraint(
"name",
"task_id",
"entity_id",
"revision",
name="working_file_uc"
),
)
def __repr__(self):
return "<WorkingFile %s>" % self.id
|
from sqlalchemy.orm import relationship
from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class WorkingFile(db.Model, BaseMixin, SerializerMixin):
shotgun_id = db.Column(db.Integer())
name = db.Column(db.String(250))
description = db.Column(db.String(200))
comment = db.Column(db.Text())
revision = db.Column(db.Integer())
size = db.Column(db.Integer())
checksum = db.Column(db.Integer())
path = db.Column(db.String(400))
task_id = db.Column(UUIDType(binary=False), db.ForeignKey("task.id"))
entity_id = db.Column(UUIDType(binary=False), db.ForeignKey("entity.id"))
person_id = \
db.Column(UUIDType(binary=False), db.ForeignKey("person.id"))
software_id = \
db.Column(UUIDType(binary=False), db.ForeignKey("software.id"))
outputs = relationship(
"OutputFile",
back_populates="source_file"
)
__table_args__ = (
db.UniqueConstraint(
"name",
"task_id",
"entity_id",
"revision",
name="working_file_uc"
),
)
def __repr__(self):
return "<WorkingFile %s>" % self.id
|
Add fields to working file model
|
Add fields to working file model
* Software
* List of output files generated
* Path used to store the working file
|
Python
|
agpl-3.0
|
cgwire/zou
|
python
|
## Code Before:
from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class WorkingFile(db.Model, BaseMixin, SerializerMixin):
shotgun_id = db.Column(db.Integer())
name = db.Column(db.String(250))
description = db.Column(db.String(200))
comment = db.Column(db.Text())
revision = db.Column(db.Integer())
size = db.Column(db.Integer())
checksum = db.Column(db.Integer())
task_id = db.Column(UUIDType(binary=False), db.ForeignKey("task.id"))
entity_id = db.Column(UUIDType(binary=False), db.ForeignKey("entity.id"))
person_id = \
db.Column(UUIDType(binary=False), db.ForeignKey("person.id"))
__table_args__ = (
db.UniqueConstraint(
"name",
"task_id",
"entity_id",
"revision",
name="working_file_uc"
),
)
def __repr__(self):
return "<WorkingFile %s>" % self.id
## Instruction:
Add fields to working file model
* Software
* List of output files generated
* Path used to store the working file
## Code After:
from sqlalchemy.orm import relationship
from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class WorkingFile(db.Model, BaseMixin, SerializerMixin):
shotgun_id = db.Column(db.Integer())
name = db.Column(db.String(250))
description = db.Column(db.String(200))
comment = db.Column(db.Text())
revision = db.Column(db.Integer())
size = db.Column(db.Integer())
checksum = db.Column(db.Integer())
path = db.Column(db.String(400))
task_id = db.Column(UUIDType(binary=False), db.ForeignKey("task.id"))
entity_id = db.Column(UUIDType(binary=False), db.ForeignKey("entity.id"))
person_id = \
db.Column(UUIDType(binary=False), db.ForeignKey("person.id"))
software_id = \
db.Column(UUIDType(binary=False), db.ForeignKey("software.id"))
outputs = relationship(
"OutputFile",
back_populates="source_file"
)
__table_args__ = (
db.UniqueConstraint(
"name",
"task_id",
"entity_id",
"revision",
name="working_file_uc"
),
)
def __repr__(self):
return "<WorkingFile %s>" % self.id
|
// ... existing code ...
from sqlalchemy.orm import relationship
from sqlalchemy_utils import UUIDType
from zou.app import db
// ... modified code ...
revision = db.Column(db.Integer())
size = db.Column(db.Integer())
checksum = db.Column(db.Integer())
path = db.Column(db.String(400))
task_id = db.Column(UUIDType(binary=False), db.ForeignKey("task.id"))
entity_id = db.Column(UUIDType(binary=False), db.ForeignKey("entity.id"))
person_id = \
db.Column(UUIDType(binary=False), db.ForeignKey("person.id"))
software_id = \
db.Column(UUIDType(binary=False), db.ForeignKey("software.id"))
outputs = relationship(
"OutputFile",
back_populates="source_file"
)
__table_args__ = (
db.UniqueConstraint(
// ... rest of the code ...
|
379e99a672537776ac0e160999967b5efce29305
|
tweepy/media.py
|
tweepy/media.py
|
from tweepy.mixins import DataMapping
class Media(DataMapping):
__slots__ = (
"data", "media_key", "type", "duration_ms", "height",
"non_public_metrics", "organic_metrics", "preview_image_url",
"promoted_metrics", "public_metrics", "width"
)
def __init__(self, data):
self.data = data
self.media_key = data["media_key"]
self.type = data["type"]
self.duration_ms = data.get("duration_ms")
self.height = data.get("height")
self.non_public_metrics = data.get("non_public_metrics")
self.organic_metrics = data.get("organic_metrics")
self.preview_image_url = data.get("preview_image_url")
self.promoted_metrics = data.get("promoted_metrics")
self.public_metrics = data.get("public_metrics")
self.width = data.get("width")
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.media_key == other.media_key
return NotImplemented
def __hash__(self):
return hash(self.media_key)
def __repr__(self):
return f"<Media media_key={self.media_key} type={self.type}>"
|
from tweepy.mixins import DataMapping
class Media(DataMapping):
__slots__ = (
"data", "media_key", "type", "duration_ms", "height",
"non_public_metrics", "organic_metrics", "preview_image_url",
"promoted_metrics", "public_metrics", "width", "alt_text"
)
def __init__(self, data):
self.data = data
self.media_key = data["media_key"]
self.type = data["type"]
self.duration_ms = data.get("duration_ms")
self.height = data.get("height")
self.non_public_metrics = data.get("non_public_metrics")
self.organic_metrics = data.get("organic_metrics")
self.preview_image_url = data.get("preview_image_url")
self.promoted_metrics = data.get("promoted_metrics")
self.public_metrics = data.get("public_metrics")
self.width = data.get("width")
self.alt_text = data.get("alt_text")
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.media_key == other.media_key
return NotImplemented
def __hash__(self):
return hash(self.media_key)
def __repr__(self):
return f"<Media media_key={self.media_key} type={self.type}>"
|
Add alt_text field for Media
|
Add alt_text field for Media
|
Python
|
mit
|
svven/tweepy,tweepy/tweepy
|
python
|
## Code Before:
from tweepy.mixins import DataMapping
class Media(DataMapping):
__slots__ = (
"data", "media_key", "type", "duration_ms", "height",
"non_public_metrics", "organic_metrics", "preview_image_url",
"promoted_metrics", "public_metrics", "width"
)
def __init__(self, data):
self.data = data
self.media_key = data["media_key"]
self.type = data["type"]
self.duration_ms = data.get("duration_ms")
self.height = data.get("height")
self.non_public_metrics = data.get("non_public_metrics")
self.organic_metrics = data.get("organic_metrics")
self.preview_image_url = data.get("preview_image_url")
self.promoted_metrics = data.get("promoted_metrics")
self.public_metrics = data.get("public_metrics")
self.width = data.get("width")
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.media_key == other.media_key
return NotImplemented
def __hash__(self):
return hash(self.media_key)
def __repr__(self):
return f"<Media media_key={self.media_key} type={self.type}>"
## Instruction:
Add alt_text field for Media
## Code After:
from tweepy.mixins import DataMapping
class Media(DataMapping):
__slots__ = (
"data", "media_key", "type", "duration_ms", "height",
"non_public_metrics", "organic_metrics", "preview_image_url",
"promoted_metrics", "public_metrics", "width", "alt_text"
)
def __init__(self, data):
self.data = data
self.media_key = data["media_key"]
self.type = data["type"]
self.duration_ms = data.get("duration_ms")
self.height = data.get("height")
self.non_public_metrics = data.get("non_public_metrics")
self.organic_metrics = data.get("organic_metrics")
self.preview_image_url = data.get("preview_image_url")
self.promoted_metrics = data.get("promoted_metrics")
self.public_metrics = data.get("public_metrics")
self.width = data.get("width")
self.alt_text = data.get("alt_text")
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.media_key == other.media_key
return NotImplemented
def __hash__(self):
return hash(self.media_key)
def __repr__(self):
return f"<Media media_key={self.media_key} type={self.type}>"
|
...
__slots__ = (
"data", "media_key", "type", "duration_ms", "height",
"non_public_metrics", "organic_metrics", "preview_image_url",
"promoted_metrics", "public_metrics", "width", "alt_text"
)
def __init__(self, data):
...
self.promoted_metrics = data.get("promoted_metrics")
self.public_metrics = data.get("public_metrics")
self.width = data.get("width")
self.alt_text = data.get("alt_text")
def __eq__(self, other):
if isinstance(other, self.__class__):
...
|
7942b21def39731496fc503c15a3e344ddec9db3
|
src/test/java/com/librato/metrics/SourceInformationTest.java
|
src/test/java/com/librato/metrics/SourceInformationTest.java
|
package com.librato.metrics;
import junit.framework.Assert;
import junit.framework.TestCase;
import java.util.regex.Pattern;
public class SourceInformationTest extends TestCase {
public void testHandlesNullRegex() throws Exception {
SourceInformation info = SourceInformation.from(null, "foo");
Assert.assertNull(info.source);
Assert.assertEquals("foo", info.name);
}
public void testExtractsSource() throws Exception {
Pattern pattern = Pattern.compile("^([^\\.]+)\\.");
SourceInformation info = SourceInformation.from(pattern, "foo.bar");
Assert.assertEquals("foo", info.source);
Assert.assertEquals("bar", info.name);
}
public void testRequiresAMatchingGroup() throws Exception {
Pattern pattern = Pattern.compile("^[^\\.]+\\.");
SourceInformation info = SourceInformation.from(pattern, "foo.bar");
Assert.assertNull(info.source);
Assert.assertEquals("foo.bar", info.name);
}
public void testPassesThroughNonMatchingMetricNames() throws Exception {
Pattern pattern = Pattern.compile("^([^\\.]+)\\.");
SourceInformation info = SourceInformation.from(pattern, "foo-bar");
Assert.assertNull(info.source);
Assert.assertEquals("foo-bar", info.name);
}
}
|
package com.librato.metrics;
import junit.framework.Assert;
import junit.framework.TestCase;
import java.util.regex.Pattern;
public class SourceInformationTest extends TestCase {
public void testHandlesNullRegex() throws Exception {
SourceInformation info = SourceInformation.from(null, "foo");
Assert.assertNull(info.source);
Assert.assertEquals("foo", info.name);
}
public void testExtractsSource() throws Exception {
Pattern pattern = Pattern.compile("^([^\\.]+)\\.");
SourceInformation info = SourceInformation.from(pattern, "foo.bar");
Assert.assertEquals("foo", info.source);
Assert.assertEquals("bar", info.name);
}
public void testRequiresAMatchingGroup() throws Exception {
Pattern pattern = Pattern.compile("^[^\\.]+\\.");
SourceInformation info = SourceInformation.from(pattern, "foo.bar");
Assert.assertNull(info.source);
Assert.assertEquals("foo.bar", info.name);
}
public void testPassesThroughNonMatchingMetricNames() throws Exception {
Pattern pattern = Pattern.compile("^([^\\.]+)\\.");
SourceInformation info = SourceInformation.from(pattern, "foo-bar");
Assert.assertNull(info.source);
Assert.assertEquals("foo-bar", info.name);
}
public void testExtractsGroupingInTheMiddleOfAnExpression() throws Exception {
Pattern pattern = Pattern.compile("^--(.*?)--");
SourceInformation info = SourceInformation.from(pattern, "--foo--bar.baz");
Assert.assertEquals("foo", info.source);
Assert.assertEquals("bar.baz", info.name);
}
}
|
Test for discarding text before and after the source match
|
Test for discarding text before and after the source match
|
Java
|
apache-2.0
|
librato/metrics-librato
|
java
|
## Code Before:
package com.librato.metrics;
import junit.framework.Assert;
import junit.framework.TestCase;
import java.util.regex.Pattern;
public class SourceInformationTest extends TestCase {
public void testHandlesNullRegex() throws Exception {
SourceInformation info = SourceInformation.from(null, "foo");
Assert.assertNull(info.source);
Assert.assertEquals("foo", info.name);
}
public void testExtractsSource() throws Exception {
Pattern pattern = Pattern.compile("^([^\\.]+)\\.");
SourceInformation info = SourceInformation.from(pattern, "foo.bar");
Assert.assertEquals("foo", info.source);
Assert.assertEquals("bar", info.name);
}
public void testRequiresAMatchingGroup() throws Exception {
Pattern pattern = Pattern.compile("^[^\\.]+\\.");
SourceInformation info = SourceInformation.from(pattern, "foo.bar");
Assert.assertNull(info.source);
Assert.assertEquals("foo.bar", info.name);
}
public void testPassesThroughNonMatchingMetricNames() throws Exception {
Pattern pattern = Pattern.compile("^([^\\.]+)\\.");
SourceInformation info = SourceInformation.from(pattern, "foo-bar");
Assert.assertNull(info.source);
Assert.assertEquals("foo-bar", info.name);
}
}
## Instruction:
Test for discarding text before and after the source match
## Code After:
package com.librato.metrics;
import junit.framework.Assert;
import junit.framework.TestCase;
import java.util.regex.Pattern;
public class SourceInformationTest extends TestCase {
public void testHandlesNullRegex() throws Exception {
SourceInformation info = SourceInformation.from(null, "foo");
Assert.assertNull(info.source);
Assert.assertEquals("foo", info.name);
}
public void testExtractsSource() throws Exception {
Pattern pattern = Pattern.compile("^([^\\.]+)\\.");
SourceInformation info = SourceInformation.from(pattern, "foo.bar");
Assert.assertEquals("foo", info.source);
Assert.assertEquals("bar", info.name);
}
public void testRequiresAMatchingGroup() throws Exception {
Pattern pattern = Pattern.compile("^[^\\.]+\\.");
SourceInformation info = SourceInformation.from(pattern, "foo.bar");
Assert.assertNull(info.source);
Assert.assertEquals("foo.bar", info.name);
}
public void testPassesThroughNonMatchingMetricNames() throws Exception {
Pattern pattern = Pattern.compile("^([^\\.]+)\\.");
SourceInformation info = SourceInformation.from(pattern, "foo-bar");
Assert.assertNull(info.source);
Assert.assertEquals("foo-bar", info.name);
}
public void testExtractsGroupingInTheMiddleOfAnExpression() throws Exception {
Pattern pattern = Pattern.compile("^--(.*?)--");
SourceInformation info = SourceInformation.from(pattern, "--foo--bar.baz");
Assert.assertEquals("foo", info.source);
Assert.assertEquals("bar.baz", info.name);
}
}
|
...
Assert.assertNull(info.source);
Assert.assertEquals("foo-bar", info.name);
}
public void testExtractsGroupingInTheMiddleOfAnExpression() throws Exception {
Pattern pattern = Pattern.compile("^--(.*?)--");
SourceInformation info = SourceInformation.from(pattern, "--foo--bar.baz");
Assert.assertEquals("foo", info.source);
Assert.assertEquals("bar.baz", info.name);
}
}
...
|
a7c27a794bf5e25046a75767f709f6619b61bcb1
|
grantlee_core_library/parser.h
|
grantlee_core_library/parser.h
|
/*
Copyright (c) 2009 Stephen Kelly <[email protected]>
*/
#ifndef PARSER_H
#define PARSER_H
#include <QStringList>
#include "token.h"
#include "node.h"
namespace Grantlee
{
class AbstractNodeFactory;
class TagLibraryInterface;
class Filter;
}
class ParserPrivate;
namespace Grantlee
{
class GRANTLEE_EXPORT Parser : public QObject
{
Q_OBJECT
public:
Parser( QList<Token> tokenList, QStringList pluginDirs, QObject *parent );
~Parser();
NodeList parse(QStringList stopAt, QObject *parent);
NodeList parse(QObject *parent);
Filter *getFilter(const QString &name);
void skipPast(const QString &tag);
Token nextToken();
bool hasNextToken();
void loadLib(const QString &name);
void emitError(int errorNumber, const QString &message);
protected:
void addTag(QObject *);
void getBuiltInLibrary();
void getDefaultLibrary();
void prependToken(Token token);
signals:
void error(int type, const QString &message);
private:
Q_DECLARE_PRIVATE(Parser);
ParserPrivate *d_ptr;
};
}
#endif
|
/*
Copyright (c) 2009 Stephen Kelly <[email protected]>
*/
#ifndef PARSER_H
#define PARSER_H
#include <QStringList>
#include "token.h"
#include "node.h"
namespace Grantlee
{
class Filter;
}
class ParserPrivate;
namespace Grantlee
{
class GRANTLEE_EXPORT Parser : public QObject
{
Q_OBJECT
public:
Parser( QList<Token> tokenList, QStringList pluginDirs, QObject *parent );
~Parser();
NodeList parse(QStringList stopAt, QObject *parent);
NodeList parse(QObject *parent);
Filter *getFilter(const QString &name);
void skipPast(const QString &tag);
Token nextToken();
bool hasNextToken();
void loadLib(const QString &name);
void emitError(int errorNumber, const QString &message);
protected:
void prependToken(Token token);
signals:
void error(int type, const QString &message);
private:
Q_DECLARE_PRIVATE(Parser);
ParserPrivate *d_ptr;
};
}
#endif
|
Remove some unused classes and methods.
|
Remove some unused classes and methods.
|
C
|
lgpl-2.1
|
cutelyst/grantlee,simonwagner/grantlee,simonwagner/grantlee,cutelyst/grantlee,cutelyst/grantlee,simonwagner/grantlee,simonwagner/grantlee,simonwagner/grantlee,cutelyst/grantlee,simonwagner/grantlee,cutelyst/grantlee
|
c
|
## Code Before:
/*
Copyright (c) 2009 Stephen Kelly <[email protected]>
*/
#ifndef PARSER_H
#define PARSER_H
#include <QStringList>
#include "token.h"
#include "node.h"
namespace Grantlee
{
class AbstractNodeFactory;
class TagLibraryInterface;
class Filter;
}
class ParserPrivate;
namespace Grantlee
{
class GRANTLEE_EXPORT Parser : public QObject
{
Q_OBJECT
public:
Parser( QList<Token> tokenList, QStringList pluginDirs, QObject *parent );
~Parser();
NodeList parse(QStringList stopAt, QObject *parent);
NodeList parse(QObject *parent);
Filter *getFilter(const QString &name);
void skipPast(const QString &tag);
Token nextToken();
bool hasNextToken();
void loadLib(const QString &name);
void emitError(int errorNumber, const QString &message);
protected:
void addTag(QObject *);
void getBuiltInLibrary();
void getDefaultLibrary();
void prependToken(Token token);
signals:
void error(int type, const QString &message);
private:
Q_DECLARE_PRIVATE(Parser);
ParserPrivate *d_ptr;
};
}
#endif
## Instruction:
Remove some unused classes and methods.
## Code After:
/*
Copyright (c) 2009 Stephen Kelly <[email protected]>
*/
#ifndef PARSER_H
#define PARSER_H
#include <QStringList>
#include "token.h"
#include "node.h"
namespace Grantlee
{
class Filter;
}
class ParserPrivate;
namespace Grantlee
{
class GRANTLEE_EXPORT Parser : public QObject
{
Q_OBJECT
public:
Parser( QList<Token> tokenList, QStringList pluginDirs, QObject *parent );
~Parser();
NodeList parse(QStringList stopAt, QObject *parent);
NodeList parse(QObject *parent);
Filter *getFilter(const QString &name);
void skipPast(const QString &tag);
Token nextToken();
bool hasNextToken();
void loadLib(const QString &name);
void emitError(int errorNumber, const QString &message);
protected:
void prependToken(Token token);
signals:
void error(int type, const QString &message);
private:
Q_DECLARE_PRIVATE(Parser);
ParserPrivate *d_ptr;
};
}
#endif
|
...
namespace Grantlee
{
class Filter;
}
...
void emitError(int errorNumber, const QString &message);
protected:
void prependToken(Token token);
signals:
...
|
da85cfae848df4cee5ccf2cbbbc370848ea172a7
|
src/txkube/_memory.py
|
src/txkube/_memory.py
|
from zope.interface import implementer
from twisted.python.url import URL
from twisted.web.resource import Resource
from treq.testing import RequestTraversalAgent
from . import IKubernetes, network_kubernetes
def memory_kubernetes():
"""
Create an in-memory Kubernetes-alike service.
This serves as a places to hold state for stateful Kubernetes interactions
allowed by ``IKubernetesClient``. Only clients created against the same
instance will all share state.
:return IKubernetes: The new Kubernetes-alike service.
"""
return _MemoryKubernetes()
@implementer(IKubernetes)
class _MemoryKubernetes(object):
"""
``_MemoryKubernetes`` maintains state in-memory which approximates
the state of a real Kubernetes deployment sufficiently to expose a
subset of the external Kubernetes API.
"""
def __init__(self):
base_url = URL.fromText(u"https://localhost/")
self._resource = _kubernetes_resource()
self._kubernetes = network_kubernetes(
base_url=base_url,
credentials=None,
agent=RequestTraversalAgent(self._resource),
)
def client(self, *args, **kwargs):
"""
:return IKubernetesClient: A new client which interacts with this
object rather than a real Kubernetes deployment.
"""
return self._kubernetes.client(*args, **kwargs)
def _kubernetes_resource():
return Resource()
|
from zope.interface import implementer
from twisted.python.url import URL
from twisted.web.resource import Resource
from treq.testing import RequestTraversalAgent
from . import IKubernetes, network_kubernetes
def memory_kubernetes():
"""
Create an in-memory Kubernetes-alike service.
This serves as a places to hold state for stateful Kubernetes interactions
allowed by ``IKubernetesClient``. Only clients created against the same
instance will all share state.
:return IKubernetes: The new Kubernetes-alike service.
"""
return _MemoryKubernetes()
@implementer(IKubernetes)
class _MemoryKubernetes(object):
"""
``_MemoryKubernetes`` maintains state in-memory which approximates
the state of a real Kubernetes deployment sufficiently to expose a
subset of the external Kubernetes API.
"""
def __init__(self):
base_url = URL.fromText(u"https://kubernetes.example.invalid./")
self._resource = _kubernetes_resource()
self._kubernetes = network_kubernetes(
base_url=base_url,
credentials=None,
agent=RequestTraversalAgent(self._resource),
)
def client(self, *args, **kwargs):
"""
:return IKubernetesClient: A new client which interacts with this
object rather than a real Kubernetes deployment.
"""
return self._kubernetes.client(*args, **kwargs)
def _kubernetes_resource():
return Resource()
|
Use a non-routeable address for this URL.
|
Use a non-routeable address for this URL.
We do not anticipate ever sending any traffic to this since this is the
in-memory-only implementation.
|
Python
|
mit
|
LeastAuthority/txkube
|
python
|
## Code Before:
from zope.interface import implementer
from twisted.python.url import URL
from twisted.web.resource import Resource
from treq.testing import RequestTraversalAgent
from . import IKubernetes, network_kubernetes
def memory_kubernetes():
"""
Create an in-memory Kubernetes-alike service.
This serves as a places to hold state for stateful Kubernetes interactions
allowed by ``IKubernetesClient``. Only clients created against the same
instance will all share state.
:return IKubernetes: The new Kubernetes-alike service.
"""
return _MemoryKubernetes()
@implementer(IKubernetes)
class _MemoryKubernetes(object):
"""
``_MemoryKubernetes`` maintains state in-memory which approximates
the state of a real Kubernetes deployment sufficiently to expose a
subset of the external Kubernetes API.
"""
def __init__(self):
base_url = URL.fromText(u"https://localhost/")
self._resource = _kubernetes_resource()
self._kubernetes = network_kubernetes(
base_url=base_url,
credentials=None,
agent=RequestTraversalAgent(self._resource),
)
def client(self, *args, **kwargs):
"""
:return IKubernetesClient: A new client which interacts with this
object rather than a real Kubernetes deployment.
"""
return self._kubernetes.client(*args, **kwargs)
def _kubernetes_resource():
return Resource()
## Instruction:
Use a non-routeable address for this URL.
We do not anticipate ever sending any traffic to this since this is the
in-memory-only implementation.
## Code After:
from zope.interface import implementer
from twisted.python.url import URL
from twisted.web.resource import Resource
from treq.testing import RequestTraversalAgent
from . import IKubernetes, network_kubernetes
def memory_kubernetes():
"""
Create an in-memory Kubernetes-alike service.
This serves as a places to hold state for stateful Kubernetes interactions
allowed by ``IKubernetesClient``. Only clients created against the same
instance will all share state.
:return IKubernetes: The new Kubernetes-alike service.
"""
return _MemoryKubernetes()
@implementer(IKubernetes)
class _MemoryKubernetes(object):
"""
``_MemoryKubernetes`` maintains state in-memory which approximates
the state of a real Kubernetes deployment sufficiently to expose a
subset of the external Kubernetes API.
"""
def __init__(self):
base_url = URL.fromText(u"https://kubernetes.example.invalid./")
self._resource = _kubernetes_resource()
self._kubernetes = network_kubernetes(
base_url=base_url,
credentials=None,
agent=RequestTraversalAgent(self._resource),
)
def client(self, *args, **kwargs):
"""
:return IKubernetesClient: A new client which interacts with this
object rather than a real Kubernetes deployment.
"""
return self._kubernetes.client(*args, **kwargs)
def _kubernetes_resource():
return Resource()
|
# ... existing code ...
subset of the external Kubernetes API.
"""
def __init__(self):
base_url = URL.fromText(u"https://kubernetes.example.invalid./")
self._resource = _kubernetes_resource()
self._kubernetes = network_kubernetes(
base_url=base_url,
# ... rest of the code ...
|
402035dd56261bce17a63b64bed810efdf14869e
|
exponent/substore.py
|
exponent/substore.py
|
from axiom import substore
def createStore(rootStore, pathSegments):
"""
Creates amd returns substore under the given root store with the given
path segments.
"""
return substore.SubStore.createNew(rootStore, pathSegments).open()
def getStore(rootStore, pathSegments):
"""
Gets a substore under the given root store with the given path segments.
"""
storePath = rootStore.filesdir
for segment in pathSegments:
storePath = storePath.child(segment)
withThisPath = substore.SubStore.storepath == storePath
return rootStore.findUnique(substore.SubStore, withThisPath).open()
|
from axiom import substore
def createStore(rootStore, pathSegments):
"""
Creates amd returns substore under the given root store with the given
path segments.
"""
return substore.SubStore.createNew(rootStore, pathSegments).open()
def getStore(rootStore, pathSegments):
"""
Gets a substore under the given root store with the given path segments.
Raises ``axiom.errors.ItemNotFound`` if no such store exists.
"""
storePath = rootStore.filesdir
for segment in pathSegments:
storePath = storePath.child(segment)
withThisPath = substore.SubStore.storepath == storePath
return rootStore.findUnique(substore.SubStore, withThisPath).open()
|
Document exception raised when a store does not exist
|
Document exception raised when a store does not exist
|
Python
|
isc
|
lvh/exponent
|
python
|
## Code Before:
from axiom import substore
def createStore(rootStore, pathSegments):
"""
Creates amd returns substore under the given root store with the given
path segments.
"""
return substore.SubStore.createNew(rootStore, pathSegments).open()
def getStore(rootStore, pathSegments):
"""
Gets a substore under the given root store with the given path segments.
"""
storePath = rootStore.filesdir
for segment in pathSegments:
storePath = storePath.child(segment)
withThisPath = substore.SubStore.storepath == storePath
return rootStore.findUnique(substore.SubStore, withThisPath).open()
## Instruction:
Document exception raised when a store does not exist
## Code After:
from axiom import substore
def createStore(rootStore, pathSegments):
"""
Creates amd returns substore under the given root store with the given
path segments.
"""
return substore.SubStore.createNew(rootStore, pathSegments).open()
def getStore(rootStore, pathSegments):
"""
Gets a substore under the given root store with the given path segments.
Raises ``axiom.errors.ItemNotFound`` if no such store exists.
"""
storePath = rootStore.filesdir
for segment in pathSegments:
storePath = storePath.child(segment)
withThisPath = substore.SubStore.storepath == storePath
return rootStore.findUnique(substore.SubStore, withThisPath).open()
|
# ... existing code ...
def getStore(rootStore, pathSegments):
"""
Gets a substore under the given root store with the given path segments.
Raises ``axiom.errors.ItemNotFound`` if no such store exists.
"""
storePath = rootStore.filesdir
for segment in pathSegments:
# ... rest of the code ...
|
1dd681517fd1831f3990caa043ea8220f5d1bb90
|
app/app.py
|
app/app.py
|
import os,time,asyncio,json
from datetime import datetime
from aiohttp import web
import logging;logging.basicConfig(level=logging.INFO)
from tools.log import Log
from tools.httptools import Middleware,Route
from tools.template import Template
from models import *
from tools.config import Config
@Route.get('/')
def index():
user=yield from User.findall()
print(user)
return Template.render('index.html')
@Route.get('/user/{id}/comment/{comment}')
def user(id,comment):
return '<h1>%s,%s</h1>'%(id,comment)
@asyncio.coroutine
def init(loop):
print(Middleware.allmiddlewares())
app=web.Application(loop=loop,middlewares=Middleware.allmiddlewares())
Template(app)
Route.register_route(app)
pool=yield from create_pool(loop)
srv=yield from loop.create_server(app.make_handler(),'127.0.0.1',8000)
logging.info('server started at http://127.0.0.1:8000')
Log.info("server startd at http://127.0.0.1:8000")
return srv
if __name__=="__main__":
loop=asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()
|
import os,time,asyncio,json
from datetime import datetime
from aiohttp import web
import logging;logging.basicConfig(level=logging.INFO)
from tools.log import Log
from tools.httptools import Middleware,Route
from tools.template import Template
from models import *
from tools.config import Config
@Route.get('/')
def index():
user=yield from User.findall()
print(user)
return Template('index.html').render()
@Route.get('/user/{id}/comment/{comment}')
def user(id,comment):
return '<h1>%s,%s</h1>'%(id,comment)
@asyncio.coroutine
def init(loop):
print(Middleware.allmiddlewares())
app=web.Application(loop=loop,middlewares=Middleware.allmiddlewares())
Template.init(app)
Route.register_route(app)
pool=yield from create_pool(loop)
srv=yield from loop.create_server(app.make_handler(),'127.0.0.1',8000)
logging.info('server started at http://127.0.0.1:8000')
Log.info("server startd at http://127.0.0.1:8000")
return srv
if __name__=="__main__":
loop=asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()
|
Change Template() to Template.init() in init function
|
Change Template() to Template.init() in init function
|
Python
|
mit
|
free-free/pyblog,free-free/pyblog,free-free/pyblog,free-free/pyblog
|
python
|
## Code Before:
import os,time,asyncio,json
from datetime import datetime
from aiohttp import web
import logging;logging.basicConfig(level=logging.INFO)
from tools.log import Log
from tools.httptools import Middleware,Route
from tools.template import Template
from models import *
from tools.config import Config
@Route.get('/')
def index():
user=yield from User.findall()
print(user)
return Template.render('index.html')
@Route.get('/user/{id}/comment/{comment}')
def user(id,comment):
return '<h1>%s,%s</h1>'%(id,comment)
@asyncio.coroutine
def init(loop):
print(Middleware.allmiddlewares())
app=web.Application(loop=loop,middlewares=Middleware.allmiddlewares())
Template(app)
Route.register_route(app)
pool=yield from create_pool(loop)
srv=yield from loop.create_server(app.make_handler(),'127.0.0.1',8000)
logging.info('server started at http://127.0.0.1:8000')
Log.info("server startd at http://127.0.0.1:8000")
return srv
if __name__=="__main__":
loop=asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()
## Instruction:
Change Template() to Template.init() in init function
## Code After:
import os,time,asyncio,json
from datetime import datetime
from aiohttp import web
import logging;logging.basicConfig(level=logging.INFO)
from tools.log import Log
from tools.httptools import Middleware,Route
from tools.template import Template
from models import *
from tools.config import Config
@Route.get('/')
def index():
user=yield from User.findall()
print(user)
return Template('index.html').render()
@Route.get('/user/{id}/comment/{comment}')
def user(id,comment):
return '<h1>%s,%s</h1>'%(id,comment)
@asyncio.coroutine
def init(loop):
print(Middleware.allmiddlewares())
app=web.Application(loop=loop,middlewares=Middleware.allmiddlewares())
Template.init(app)
Route.register_route(app)
pool=yield from create_pool(loop)
srv=yield from loop.create_server(app.make_handler(),'127.0.0.1',8000)
logging.info('server started at http://127.0.0.1:8000')
Log.info("server startd at http://127.0.0.1:8000")
return srv
if __name__=="__main__":
loop=asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()
|
# ... existing code ...
def index():
user=yield from User.findall()
print(user)
return Template('index.html').render()
@Route.get('/user/{id}/comment/{comment}')
def user(id,comment):
return '<h1>%s,%s</h1>'%(id,comment)
# ... modified code ...
def init(loop):
print(Middleware.allmiddlewares())
app=web.Application(loop=loop,middlewares=Middleware.allmiddlewares())
Template.init(app)
Route.register_route(app)
pool=yield from create_pool(loop)
srv=yield from loop.create_server(app.make_handler(),'127.0.0.1',8000)
# ... rest of the code ...
|
c97153e9d91af27713afce506bc658daa6b1a0e2
|
docs/manual/docsmanage.py
|
docs/manual/docsmanage.py
|
import os
import sys
sys.path.insert(0, os.path.join(__file__, "..", ".."))
sys.path.insert(0, os.path.dirname(__file__))
from reviewboard import settings
from django.core.management import execute_manager
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'reviewboard.settings')
def scan_resource(resource):
for child in resource.item_child_resources:
scan_resource(child)
for child in resource.list_child_resources:
scan_resource(child)
if __name__ == "__main__":
execute_manager(settings)
|
import os
import sys
sys.path.insert(0, os.path.join(__file__, "..", ".."))
sys.path.insert(0, os.path.dirname(__file__))
from reviewboard import settings
from django.core.management import execute_from_command_line
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'reviewboard.settings')
def scan_resource(resource):
for child in resource.item_child_resources:
scan_resource(child)
for child in resource.list_child_resources:
scan_resource(child)
if __name__ == "__main__":
execute_from_command_line()
|
Fix building the manual with Django 1.6.
|
Fix building the manual with Django 1.6.
This is a trivial change that just switches from calling execute_manager
to execute_from_command_line, in order to build again on Django 1.6.
|
Python
|
mit
|
chipx86/reviewboard,custode/reviewboard,KnowNo/reviewboard,bkochendorfer/reviewboard,bkochendorfer/reviewboard,beol/reviewboard,sgallagher/reviewboard,bkochendorfer/reviewboard,reviewboard/reviewboard,reviewboard/reviewboard,davidt/reviewboard,brennie/reviewboard,KnowNo/reviewboard,custode/reviewboard,1tush/reviewboard,KnowNo/reviewboard,1tush/reviewboard,davidt/reviewboard,1tush/reviewboard,1tush/reviewboard,bkochendorfer/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,KnowNo/reviewboard,brennie/reviewboard,davidt/reviewboard,beol/reviewboard,chipx86/reviewboard,sgallagher/reviewboard,1tush/reviewboard,custode/reviewboard,1tush/reviewboard,brennie/reviewboard,beol/reviewboard,1tush/reviewboard,davidt/reviewboard,sgallagher/reviewboard,chipx86/reviewboard,custode/reviewboard,1tush/reviewboard,reviewboard/reviewboard,brennie/reviewboard,beol/reviewboard,1tush/reviewboard,sgallagher/reviewboard
|
python
|
## Code Before:
import os
import sys
sys.path.insert(0, os.path.join(__file__, "..", ".."))
sys.path.insert(0, os.path.dirname(__file__))
from reviewboard import settings
from django.core.management import execute_manager
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'reviewboard.settings')
def scan_resource(resource):
for child in resource.item_child_resources:
scan_resource(child)
for child in resource.list_child_resources:
scan_resource(child)
if __name__ == "__main__":
execute_manager(settings)
## Instruction:
Fix building the manual with Django 1.6.
This is a trivial change that just switches from calling execute_manager
to execute_from_command_line, in order to build again on Django 1.6.
## Code After:
import os
import sys
sys.path.insert(0, os.path.join(__file__, "..", ".."))
sys.path.insert(0, os.path.dirname(__file__))
from reviewboard import settings
from django.core.management import execute_from_command_line
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'reviewboard.settings')
def scan_resource(resource):
for child in resource.item_child_resources:
scan_resource(child)
for child in resource.list_child_resources:
scan_resource(child)
if __name__ == "__main__":
execute_from_command_line()
|
...
sys.path.insert(0, os.path.dirname(__file__))
from reviewboard import settings
from django.core.management import execute_from_command_line
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'reviewboard.settings')
...
if __name__ == "__main__":
execute_from_command_line()
...
|
c1b6357c4d6876caa081af0799ec6c7a189ad13f
|
fabfile.py
|
fabfile.py
|
from fabric.api import *
from fabric.contrib.console import confirm
appengine_dir='appengine-web/src'
goldquest_dir='src'
def update():
# update to latest code from repo
local('git pull')
def test():
local("nosetests -m 'Test|test_' -w %(path)s" % dict(path=goldquest_dir))
# jslint
# pychecker
# run jasmine tests
def compile():
# Minimize javascript using google closure.
local("java -jar ~/bin/compiler.jar --js %(path)s/javascript/game.js --js_output_file %(path)s/javascript/game.min.js" % dict(path=appengine_dir))
def deploy_appengine():
local("appcfg.py update " + appengine_dir)
def prepare_deploy():
test()
compile()
def deploy():
update()
prepare_deploy()
deploy_appengine()
# tweet about release
|
from fabric.api import *
from fabric.contrib.console import confirm
cfg = dict(
appengine_dir='appengine-web/src',
goldquest_dir='src',
appengine_token='',
)
def update():
# update to latest code from repo
local('git pull')
def test():
local("nosetests -m 'Test|test_' -w %(goldquest_dir)s" % cfg)
# jslint
# pychecker
# run jasmine tests
def compile():
# Minimize javascript using google closure.
local("java -jar ~/bin/compiler.jar --js %(appengine_dir)s/javascript/game.js --js_output_file %(appengine_dir)s/javascript/game.min.js" % cfg)
def deploy_appengine():
local("appcfg.py --oauth2_refresh_token=%(appengine_token)s update %(appengine_dir)s" % cfg)
def prepare_deploy():
test()
compile()
def deploy():
update()
prepare_deploy()
deploy_appengine()
# tweet about release
|
Add support for appengine update oauth2 token in deploy script.
|
NEW: Add support for appengine update oauth2 token in deploy script.
|
Python
|
mit
|
ollej/GoldQuest,ollej/GoldQuest,ollej/GoldQuest,ollej/GoldQuest
|
python
|
## Code Before:
from fabric.api import *
from fabric.contrib.console import confirm
appengine_dir='appengine-web/src'
goldquest_dir='src'
def update():
# update to latest code from repo
local('git pull')
def test():
local("nosetests -m 'Test|test_' -w %(path)s" % dict(path=goldquest_dir))
# jslint
# pychecker
# run jasmine tests
def compile():
# Minimize javascript using google closure.
local("java -jar ~/bin/compiler.jar --js %(path)s/javascript/game.js --js_output_file %(path)s/javascript/game.min.js" % dict(path=appengine_dir))
def deploy_appengine():
local("appcfg.py update " + appengine_dir)
def prepare_deploy():
test()
compile()
def deploy():
update()
prepare_deploy()
deploy_appengine()
# tweet about release
## Instruction:
NEW: Add support for appengine update oauth2 token in deploy script.
## Code After:
from fabric.api import *
from fabric.contrib.console import confirm
cfg = dict(
appengine_dir='appengine-web/src',
goldquest_dir='src',
appengine_token='',
)
def update():
# update to latest code from repo
local('git pull')
def test():
local("nosetests -m 'Test|test_' -w %(goldquest_dir)s" % cfg)
# jslint
# pychecker
# run jasmine tests
def compile():
# Minimize javascript using google closure.
local("java -jar ~/bin/compiler.jar --js %(appengine_dir)s/javascript/game.js --js_output_file %(appengine_dir)s/javascript/game.min.js" % cfg)
def deploy_appengine():
local("appcfg.py --oauth2_refresh_token=%(appengine_token)s update %(appengine_dir)s" % cfg)
def prepare_deploy():
test()
compile()
def deploy():
update()
prepare_deploy()
deploy_appengine()
# tweet about release
|
// ... existing code ...
from fabric.api import *
from fabric.contrib.console import confirm
cfg = dict(
appengine_dir='appengine-web/src',
goldquest_dir='src',
appengine_token='',
)
def update():
# update to latest code from repo
// ... modified code ...
local('git pull')
def test():
local("nosetests -m 'Test|test_' -w %(goldquest_dir)s" % cfg)
# jslint
# pychecker
# run jasmine tests
...
def compile():
# Minimize javascript using google closure.
local("java -jar ~/bin/compiler.jar --js %(appengine_dir)s/javascript/game.js --js_output_file %(appengine_dir)s/javascript/game.min.js" % cfg)
def deploy_appengine():
local("appcfg.py --oauth2_refresh_token=%(appengine_token)s update %(appengine_dir)s" % cfg)
def prepare_deploy():
test()
// ... rest of the code ...
|
43c7a45566e6df0bcde37dca4d5d11f68330e833
|
ObjectiveRocks/RocksDBPlainTableOptions.h
|
ObjectiveRocks/RocksDBPlainTableOptions.h
|
//
// RocksDBPlainTableOptions.h
// ObjectiveRocks
//
// Created by Iska on 04/01/15.
// Copyright (c) 2015 BrainCookie. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef NS_ENUM(char, PlainTableEncodingType)
{
PlainTableEncodingPlain,
PlainTableEncodingPrefix
};
@interface RocksDBPlainTableOptions : NSObject
@property (nonatomic, assign) uint32_t userKeyLen;
@property (nonatomic, assign) int bloomBitsPerKey;
@property (nonatomic, assign) double hashTableRatio;
@property (nonatomic, assign) size_t indexSparseness;
@property (nonatomic, assign) size_t hugePageTlbSize;
@property (nonatomic, assign) PlainTableEncodingType encodingType;
@property (nonatomic, assign) BOOL fullScanMode;
@property (nonatomic, assign) BOOL storeIndexInFile;
@end
|
//
// RocksDBPlainTableOptions.h
// ObjectiveRocks
//
// Created by Iska on 04/01/15.
// Copyright (c) 2015 BrainCookie. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef NS_ENUM(char, PlainTableEncodingType)
{
PlainTableEncodingPlain,
PlainTableEncodingPrefix
};
@interface RocksDBPlainTableOptions : NSObject
/**
@brief
Plain table has optimization for fix-sized keys, which can
be specified via userKeyLen.
*/
@property (nonatomic, assign) uint32_t userKeyLen;
/**
@brief
The number of bits used for bloom filer per prefix.
To disable it pass a zero.
*/
@property (nonatomic, assign) int bloomBitsPerKey;
/**
@brief
The desired utilization of the hash table used for prefix hashing.
`hashTableRatio` = number of prefixes / #buckets in the hash table.
*/
@property (nonatomic, assign) double hashTableRatio;
/**
@brief
Used to build one index record inside each prefix for the number of
keys for the binary search inside each hash bucket.
*/
@property (nonatomic, assign) size_t indexSparseness;
/**
@brief
Huge page TLB size. The user needs to reserve huge pages
for it to be allocated, like:
`sysctl -w vm.nr_hugepages=20`
*/
@property (nonatomic, assign) size_t hugePageTlbSize;
/**
@brief
Encoding type for the keys. The value will determine how to encode keys
when writing to a new SST file.
*/
@property (nonatomic, assign) PlainTableEncodingType encodingType;
/**
@brief
Mode for reading the whole file one record by one without using the index.
*/
@property (nonatomic, assign) BOOL fullScanMode;
/**
@brief
Compute plain table index and bloom filter during file building and store
it in file. When reading file, index will be mmaped instead of recomputation.
*/
@property (nonatomic, assign) BOOL storeIndexInFile;
@end
|
Add source code documentation for the RocksDB Plain Table Options class
|
Add source code documentation for the RocksDB Plain Table Options class
|
C
|
mit
|
iabudiab/ObjectiveRocks,iabudiab/ObjectiveRocks,iabudiab/ObjectiveRocks,iabudiab/ObjectiveRocks
|
c
|
## Code Before:
//
// RocksDBPlainTableOptions.h
// ObjectiveRocks
//
// Created by Iska on 04/01/15.
// Copyright (c) 2015 BrainCookie. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef NS_ENUM(char, PlainTableEncodingType)
{
PlainTableEncodingPlain,
PlainTableEncodingPrefix
};
@interface RocksDBPlainTableOptions : NSObject
@property (nonatomic, assign) uint32_t userKeyLen;
@property (nonatomic, assign) int bloomBitsPerKey;
@property (nonatomic, assign) double hashTableRatio;
@property (nonatomic, assign) size_t indexSparseness;
@property (nonatomic, assign) size_t hugePageTlbSize;
@property (nonatomic, assign) PlainTableEncodingType encodingType;
@property (nonatomic, assign) BOOL fullScanMode;
@property (nonatomic, assign) BOOL storeIndexInFile;
@end
## Instruction:
Add source code documentation for the RocksDB Plain Table Options class
## Code After:
//
// RocksDBPlainTableOptions.h
// ObjectiveRocks
//
// Created by Iska on 04/01/15.
// Copyright (c) 2015 BrainCookie. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef NS_ENUM(char, PlainTableEncodingType)
{
PlainTableEncodingPlain,
PlainTableEncodingPrefix
};
@interface RocksDBPlainTableOptions : NSObject
/**
@brief
Plain table has optimization for fix-sized keys, which can
be specified via userKeyLen.
*/
@property (nonatomic, assign) uint32_t userKeyLen;
/**
@brief
The number of bits used for bloom filer per prefix.
To disable it pass a zero.
*/
@property (nonatomic, assign) int bloomBitsPerKey;
/**
@brief
The desired utilization of the hash table used for prefix hashing.
`hashTableRatio` = number of prefixes / #buckets in the hash table.
*/
@property (nonatomic, assign) double hashTableRatio;
/**
@brief
Used to build one index record inside each prefix for the number of
keys for the binary search inside each hash bucket.
*/
@property (nonatomic, assign) size_t indexSparseness;
/**
@brief
Huge page TLB size. The user needs to reserve huge pages
for it to be allocated, like:
`sysctl -w vm.nr_hugepages=20`
*/
@property (nonatomic, assign) size_t hugePageTlbSize;
/**
@brief
Encoding type for the keys. The value will determine how to encode keys
when writing to a new SST file.
*/
@property (nonatomic, assign) PlainTableEncodingType encodingType;
/**
@brief
Mode for reading the whole file one record by one without using the index.
*/
@property (nonatomic, assign) BOOL fullScanMode;
/**
@brief
Compute plain table index and bloom filter during file building and store
it in file. When reading file, index will be mmaped instead of recomputation.
*/
@property (nonatomic, assign) BOOL storeIndexInFile;
@end
|
# ... existing code ...
@interface RocksDBPlainTableOptions : NSObject
/**
@brief
Plain table has optimization for fix-sized keys, which can
be specified via userKeyLen.
*/
@property (nonatomic, assign) uint32_t userKeyLen;
/**
@brief
The number of bits used for bloom filer per prefix.
To disable it pass a zero.
*/
@property (nonatomic, assign) int bloomBitsPerKey;
/**
@brief
The desired utilization of the hash table used for prefix hashing.
`hashTableRatio` = number of prefixes / #buckets in the hash table.
*/
@property (nonatomic, assign) double hashTableRatio;
/**
@brief
Used to build one index record inside each prefix for the number of
keys for the binary search inside each hash bucket.
*/
@property (nonatomic, assign) size_t indexSparseness;
/**
@brief
Huge page TLB size. The user needs to reserve huge pages
for it to be allocated, like:
`sysctl -w vm.nr_hugepages=20`
*/
@property (nonatomic, assign) size_t hugePageTlbSize;
/**
@brief
Encoding type for the keys. The value will determine how to encode keys
when writing to a new SST file.
*/
@property (nonatomic, assign) PlainTableEncodingType encodingType;
/**
@brief
Mode for reading the whole file one record by one without using the index.
*/
@property (nonatomic, assign) BOOL fullScanMode;
/**
@brief
Compute plain table index and bloom filter during file building and store
it in file. When reading file, index will be mmaped instead of recomputation.
*/
@property (nonatomic, assign) BOOL storeIndexInFile;
@end
# ... rest of the code ...
|
f840af6621fd63dd9021fcb68a32ba14c925fcf7
|
wellknown/models.py
|
wellknown/models.py
|
from django.db import models
from django.db.models.signals import post_save
import mimetypes
import wellknown
#
# create default host-meta handler
#
from wellknown.resources import HostMeta
wellknown.register('host-meta', handler=HostMeta(), content_type='application/xrd+xml')
#
# resource model
#
class Resource(models.Model):
path = models.CharField(max_length=128)
content = models.TextField(blank=True)
content_type = models.CharField(max_length=128, blank=True)
class Meta:
ordering = ('path',)
def __unicode__(self):
return self.path
def save(self, **kwargs):
self.path = self.path.strip('/')
if not self.content_type:
self.content_type = mimetypes.guess_type(self.path)[0] or 'text/plain'
super(Resource, self).save(**kwargs)
#
# update resources when models are saved
#
def save_handler(sender, **kwargs):
reg = kwargs['instance']
wellknown.register(
reg.path,
content=reg.content,
content_type=reg.content_type,
update=True
)
post_save.connect(save_handler, sender=Resource)
|
from django.db import models
from django.db.models.signals import post_save
import mimetypes
import wellknown
#
# create default host-meta handler
#
from wellknown.resources import HostMeta
try:
wellknown.register('host-meta', handler=HostMeta(),
content_type='application/xrd+xml')
except ValueError:
pass
#
# resource model
#
class Resource(models.Model):
path = models.CharField(max_length=128)
content = models.TextField(blank=True)
content_type = models.CharField(max_length=128, blank=True)
class Meta:
ordering = ('path',)
def __unicode__(self):
return self.path
def save(self, **kwargs):
self.path = self.path.strip('/')
if not self.content_type:
self.content_type = mimetypes.guess_type(self.path)[0] or 'text/plain'
super(Resource, self).save(**kwargs)
#
# update resources when models are saved
#
def save_handler(sender, **kwargs):
reg = kwargs['instance']
wellknown.register(
reg.path,
content=reg.content,
content_type=reg.content_type,
update=True
)
post_save.connect(save_handler, sender=Resource)
|
Check for an existing handler before registering default host-meta handler.
|
Check for an existing handler before registering default host-meta handler.
|
Python
|
bsd-3-clause
|
jcarbaugh/django-wellknown
|
python
|
## Code Before:
from django.db import models
from django.db.models.signals import post_save
import mimetypes
import wellknown
#
# create default host-meta handler
#
from wellknown.resources import HostMeta
wellknown.register('host-meta', handler=HostMeta(), content_type='application/xrd+xml')
#
# resource model
#
class Resource(models.Model):
path = models.CharField(max_length=128)
content = models.TextField(blank=True)
content_type = models.CharField(max_length=128, blank=True)
class Meta:
ordering = ('path',)
def __unicode__(self):
return self.path
def save(self, **kwargs):
self.path = self.path.strip('/')
if not self.content_type:
self.content_type = mimetypes.guess_type(self.path)[0] or 'text/plain'
super(Resource, self).save(**kwargs)
#
# update resources when models are saved
#
def save_handler(sender, **kwargs):
reg = kwargs['instance']
wellknown.register(
reg.path,
content=reg.content,
content_type=reg.content_type,
update=True
)
post_save.connect(save_handler, sender=Resource)
## Instruction:
Check for an existing handler before registering default host-meta handler.
## Code After:
from django.db import models
from django.db.models.signals import post_save
import mimetypes
import wellknown
#
# create default host-meta handler
#
from wellknown.resources import HostMeta
try:
wellknown.register('host-meta', handler=HostMeta(),
content_type='application/xrd+xml')
except ValueError:
pass
#
# resource model
#
class Resource(models.Model):
path = models.CharField(max_length=128)
content = models.TextField(blank=True)
content_type = models.CharField(max_length=128, blank=True)
class Meta:
ordering = ('path',)
def __unicode__(self):
return self.path
def save(self, **kwargs):
self.path = self.path.strip('/')
if not self.content_type:
self.content_type = mimetypes.guess_type(self.path)[0] or 'text/plain'
super(Resource, self).save(**kwargs)
#
# update resources when models are saved
#
def save_handler(sender, **kwargs):
reg = kwargs['instance']
wellknown.register(
reg.path,
content=reg.content,
content_type=reg.content_type,
update=True
)
post_save.connect(save_handler, sender=Resource)
|
# ... existing code ...
#
from wellknown.resources import HostMeta
try:
wellknown.register('host-meta', handler=HostMeta(),
content_type='application/xrd+xml')
except ValueError:
pass
#
# resource model
# ... rest of the code ...
|
7b4b5bc95f0a498ab83422192410f9213bfdb251
|
praw/models/listing/mixins/submission.py
|
praw/models/listing/mixins/submission.py
|
"""Provide the SubmissionListingMixin class."""
from ....const import API_PATH
from ..generator import ListingGenerator
from .base import BaseListingMixin
from .gilded import GildedListingMixin
class SubmissionListingMixin(BaseListingMixin, GildedListingMixin):
"""Adds additional methods pertaining to Submission instances."""
def duplicates(self, **generator_kwargs):
"""Return a ListingGenerator for the submission's duplicates.
Additional keyword arguments are passed in the initialization of
:class:`.ListingGenerator`.
"""
url = API_PATH['duplicates'].format(submission_id=self.id)
return ListingGenerator(self._reddit, url, **generator_kwargs)
|
"""Provide the SubmissionListingMixin class."""
from ....const import API_PATH
from ..generator import ListingGenerator
from .gilded import GildedListingMixin
class SubmissionListingMixin(GildedListingMixin):
"""Adds additional methods pertaining to Submission instances."""
def duplicates(self, **generator_kwargs):
"""Return a ListingGenerator for the submission's duplicates.
Additional keyword arguments are passed in the initialization of
:class:`.ListingGenerator`.
"""
url = API_PATH['duplicates'].format(submission_id=self.id)
return ListingGenerator(self._reddit, url, **generator_kwargs)
|
Remove BaseListingMixin as superclass for SubmissionListingMixin
|
Remove BaseListingMixin as superclass for SubmissionListingMixin
|
Python
|
bsd-2-clause
|
darthkedrik/praw,leviroth/praw,praw-dev/praw,gschizas/praw,13steinj/praw,nmtake/praw,13steinj/praw,gschizas/praw,nmtake/praw,praw-dev/praw,darthkedrik/praw,leviroth/praw
|
python
|
## Code Before:
"""Provide the SubmissionListingMixin class."""
from ....const import API_PATH
from ..generator import ListingGenerator
from .base import BaseListingMixin
from .gilded import GildedListingMixin
class SubmissionListingMixin(BaseListingMixin, GildedListingMixin):
"""Adds additional methods pertaining to Submission instances."""
def duplicates(self, **generator_kwargs):
"""Return a ListingGenerator for the submission's duplicates.
Additional keyword arguments are passed in the initialization of
:class:`.ListingGenerator`.
"""
url = API_PATH['duplicates'].format(submission_id=self.id)
return ListingGenerator(self._reddit, url, **generator_kwargs)
## Instruction:
Remove BaseListingMixin as superclass for SubmissionListingMixin
## Code After:
"""Provide the SubmissionListingMixin class."""
from ....const import API_PATH
from ..generator import ListingGenerator
from .gilded import GildedListingMixin
class SubmissionListingMixin(GildedListingMixin):
"""Adds additional methods pertaining to Submission instances."""
def duplicates(self, **generator_kwargs):
"""Return a ListingGenerator for the submission's duplicates.
Additional keyword arguments are passed in the initialization of
:class:`.ListingGenerator`.
"""
url = API_PATH['duplicates'].format(submission_id=self.id)
return ListingGenerator(self._reddit, url, **generator_kwargs)
|
...
"""Provide the SubmissionListingMixin class."""
from ....const import API_PATH
from ..generator import ListingGenerator
from .gilded import GildedListingMixin
class SubmissionListingMixin(GildedListingMixin):
"""Adds additional methods pertaining to Submission instances."""
def duplicates(self, **generator_kwargs):
...
|
a56707d815271088c2c19f0c2c415d611886e859
|
db/__init__.py
|
db/__init__.py
|
import categories # nopep8
import plugins # nopep8
import submitted_plugins # nopep8
import tags # nopep8
|
import categories # NOQA: F401
import plugins # NOQA: F401
import submitted_plugins # NOQA: F401
import tags # NOQA: F401
|
Update nopep8 instructions to NOQA
|
Update nopep8 instructions to NOQA
`flake8` seems to have dropped support for `# nopep8` in the 3.x
versions (confirmed by testing with latest and `<3`). This causes our
style checking tests to fail.
Replace these with `# NOQA` and pin them to the specific error we care
about here (F401 unused import).
|
Python
|
mit
|
jonafato/vim-awesome,vim-awesome/vim-awesome,jonafato/vim-awesome,vim-awesome/vim-awesome,divad12/vim-awesome,jonafato/vim-awesome,vim-awesome/vim-awesome,divad12/vim-awesome,jonafato/vim-awesome,divad12/vim-awesome,vim-awesome/vim-awesome,divad12/vim-awesome,vim-awesome/vim-awesome
|
python
|
## Code Before:
import categories # nopep8
import plugins # nopep8
import submitted_plugins # nopep8
import tags # nopep8
## Instruction:
Update nopep8 instructions to NOQA
`flake8` seems to have dropped support for `# nopep8` in the 3.x
versions (confirmed by testing with latest and `<3`). This causes our
style checking tests to fail.
Replace these with `# NOQA` and pin them to the specific error we care
about here (F401 unused import).
## Code After:
import categories # NOQA: F401
import plugins # NOQA: F401
import submitted_plugins # NOQA: F401
import tags # NOQA: F401
|
# ... existing code ...
import categories # NOQA: F401
import plugins # NOQA: F401
import submitted_plugins # NOQA: F401
import tags # NOQA: F401
# ... rest of the code ...
|
df43357133c7765e064302a3165fd5ce0ec4a6a0
|
src/com/tortel/deploytrack/DeploymentFragmentAdapter.java
|
src/com/tortel/deploytrack/DeploymentFragmentAdapter.java
|
package com.tortel.deploytrack;
import java.util.List;
import com.tortel.deploytrack.data.*;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class DeploymentFragmentAdapter extends FragmentPagerAdapter {
private List<Deployment> deployments;
private DatabaseManager db;
public DeploymentFragmentAdapter(Context context, FragmentManager fm){
super(fm);
db = DatabaseManager.getInstance(context);
deployments = db.getAllDeployments();
}
public void reload(){
Log.d("Reloading data");
deployments = db.getAllDeployments();
notifyDataSetChanged();
}
@Override
public Fragment getItem(int position) {
if(deployments.size() == position){
return new NoDataFragment();
}
return DeploymentFragment.newInstance(deployments.get(position));
}
@Override
public int getCount() {
return deployments.size() + 1;
}
@Override
public CharSequence getPageTitle(int position){
if(deployments.size() == position){
return "Welcome";
}
return deployments.get(position).getName();
}
}
|
package com.tortel.deploytrack;
import java.util.List;
import com.tortel.deploytrack.data.*;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class DeploymentFragmentAdapter extends FragmentStatePagerAdapter {
private List<Deployment> deployments;
private DatabaseManager db;
public DeploymentFragmentAdapter(Context context, FragmentManager fm){
super(fm);
db = DatabaseManager.getInstance(context);
deployments = db.getAllDeployments();
}
public void reload(){
Log.d("Reloading data");
deployments = db.getAllDeployments();
notifyDataSetChanged();
}
@Override
public Fragment getItem(int position) {
if(deployments.size() == position){
return new NoDataFragment();
}
return DeploymentFragment.newInstance(deployments.get(position));
}
@Override
public int getCount() {
return deployments.size() + 1;
}
@Override
public CharSequence getPageTitle(int position){
if(deployments.size() == position){
return "Welcome";
}
return deployments.get(position).getName();
}
}
|
Change pager type to avoid NPEs
|
Change pager type to avoid NPEs
|
Java
|
apache-2.0
|
Tortel/DeployTrack,Tortel/DeployTrack
|
java
|
## Code Before:
package com.tortel.deploytrack;
import java.util.List;
import com.tortel.deploytrack.data.*;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class DeploymentFragmentAdapter extends FragmentPagerAdapter {
private List<Deployment> deployments;
private DatabaseManager db;
public DeploymentFragmentAdapter(Context context, FragmentManager fm){
super(fm);
db = DatabaseManager.getInstance(context);
deployments = db.getAllDeployments();
}
public void reload(){
Log.d("Reloading data");
deployments = db.getAllDeployments();
notifyDataSetChanged();
}
@Override
public Fragment getItem(int position) {
if(deployments.size() == position){
return new NoDataFragment();
}
return DeploymentFragment.newInstance(deployments.get(position));
}
@Override
public int getCount() {
return deployments.size() + 1;
}
@Override
public CharSequence getPageTitle(int position){
if(deployments.size() == position){
return "Welcome";
}
return deployments.get(position).getName();
}
}
## Instruction:
Change pager type to avoid NPEs
## Code After:
package com.tortel.deploytrack;
import java.util.List;
import com.tortel.deploytrack.data.*;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class DeploymentFragmentAdapter extends FragmentStatePagerAdapter {
private List<Deployment> deployments;
private DatabaseManager db;
public DeploymentFragmentAdapter(Context context, FragmentManager fm){
super(fm);
db = DatabaseManager.getInstance(context);
deployments = db.getAllDeployments();
}
public void reload(){
Log.d("Reloading data");
deployments = db.getAllDeployments();
notifyDataSetChanged();
}
@Override
public Fragment getItem(int position) {
if(deployments.size() == position){
return new NoDataFragment();
}
return DeploymentFragment.newInstance(deployments.get(position));
}
@Override
public int getCount() {
return deployments.size() + 1;
}
@Override
public CharSequence getPageTitle(int position){
if(deployments.size() == position){
return "Welcome";
}
return deployments.get(position).getName();
}
}
|
# ... existing code ...
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class DeploymentFragmentAdapter extends FragmentStatePagerAdapter {
private List<Deployment> deployments;
private DatabaseManager db;
# ... rest of the code ...
|
ed044a79347fcde11416c51a5c577fe2cc467050
|
pyfr/readers/base.py
|
pyfr/readers/base.py
|
import uuid
from abc import ABCMeta, abstractmethod
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Add metadata
mesh['mesh_uuid'] = str(uuid.uuid4())
return mesh
|
import re
import uuid
import itertools as it
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def _optimize(self, mesh):
# Sort interior interfaces
for f in it.ifilter(lambda f: re.match('con_p\d+', f), mesh):
mesh[f] = mesh[f][:,np.argsort(mesh[f][0])]
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Perform some simple optimizations on the mesh
self._optimize(mesh)
# Add metadata
mesh['mesh_uuid'] = str(uuid.uuid4())
return mesh
|
Add some simple optimizations into the mesh reader classes.
|
Add some simple optimizations into the mesh reader classes.
This yields a ~1.5% performance improvement.
|
Python
|
bsd-3-clause
|
tjcorona/PyFR,tjcorona/PyFR,BrianVermeire/PyFR,tjcorona/PyFR,Aerojspark/PyFR,iyer-arvind/PyFR
|
python
|
## Code Before:
import uuid
from abc import ABCMeta, abstractmethod
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Add metadata
mesh['mesh_uuid'] = str(uuid.uuid4())
return mesh
## Instruction:
Add some simple optimizations into the mesh reader classes.
This yields a ~1.5% performance improvement.
## Code After:
import re
import uuid
import itertools as it
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def _optimize(self, mesh):
# Sort interior interfaces
for f in it.ifilter(lambda f: re.match('con_p\d+', f), mesh):
mesh[f] = mesh[f][:,np.argsort(mesh[f][0])]
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Perform some simple optimizations on the mesh
self._optimize(mesh)
# Add metadata
mesh['mesh_uuid'] = str(uuid.uuid4())
return mesh
|
# ... existing code ...
import re
import uuid
import itertools as it
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
# ... modified code ...
def _to_raw_pyfrm(self):
pass
def _optimize(self, mesh):
# Sort interior interfaces
for f in it.ifilter(lambda f: re.match('con_p\d+', f), mesh):
mesh[f] = mesh[f][:,np.argsort(mesh[f][0])]
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Perform some simple optimizations on the mesh
self._optimize(mesh)
# Add metadata
mesh['mesh_uuid'] = str(uuid.uuid4())
# ... rest of the code ...
|
1030381f6a22d38fa48222f44858a8396970494e
|
nucleus/urls.py
|
nucleus/urls.py
|
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.http import HttpResponse
from watchman import views as watchman_views
admin.autodiscover() # Discover admin.py files for the admin interface.
urlpatterns = [
url(r'', include('nucleus.base.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^api-token-auth/',
'rest_framework.authtoken.views.obtain_auth_token'),
url(r'^rna/', include('rna.urls')),
url(r'^robots\.txt$', lambda r: HttpResponse(
"User-agent: *\n%s: /" % ('Allow' if settings.ENGAGE_ROBOTS else 'Disallow'),
content_type="text/plain")),
url(r'^healthz/$', watchman_views.ping, name="watchman.ping"),
url(r'^readiness/$', watchman_views.status, name="watchman.status"),
]
if settings.OIDC_ENABLE:
urlpatterns.append(url(r'^oidc/', include('mozilla_django_oidc.urls')))
|
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.http import HttpResponse
from watchman import views as watchman_views
admin.autodiscover() # Discover admin.py files for the admin interface.
admin.site.site_header = 'Release Notes Administration'
admin.site.site_title = 'Release Notes Administration'
urlpatterns = [
url(r'', include('nucleus.base.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^api-token-auth/',
'rest_framework.authtoken.views.obtain_auth_token'),
url(r'^rna/', include('rna.urls')),
url(r'^robots\.txt$', lambda r: HttpResponse(
"User-agent: *\n%s: /" % ('Allow' if settings.ENGAGE_ROBOTS else 'Disallow'),
content_type="text/plain")),
url(r'^healthz/$', watchman_views.ping, name="watchman.ping"),
url(r'^readiness/$', watchman_views.status, name="watchman.status"),
]
if settings.OIDC_ENABLE:
urlpatterns.append(url(r'^oidc/', include('mozilla_django_oidc.urls')))
|
Customize admin site title and header
|
Customize admin site title and header
|
Python
|
mpl-2.0
|
mozilla/nucleus,mozilla/nucleus,mozilla/nucleus,mozilla/nucleus
|
python
|
## Code Before:
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.http import HttpResponse
from watchman import views as watchman_views
admin.autodiscover() # Discover admin.py files for the admin interface.
urlpatterns = [
url(r'', include('nucleus.base.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^api-token-auth/',
'rest_framework.authtoken.views.obtain_auth_token'),
url(r'^rna/', include('rna.urls')),
url(r'^robots\.txt$', lambda r: HttpResponse(
"User-agent: *\n%s: /" % ('Allow' if settings.ENGAGE_ROBOTS else 'Disallow'),
content_type="text/plain")),
url(r'^healthz/$', watchman_views.ping, name="watchman.ping"),
url(r'^readiness/$', watchman_views.status, name="watchman.status"),
]
if settings.OIDC_ENABLE:
urlpatterns.append(url(r'^oidc/', include('mozilla_django_oidc.urls')))
## Instruction:
Customize admin site title and header
## Code After:
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.http import HttpResponse
from watchman import views as watchman_views
admin.autodiscover() # Discover admin.py files for the admin interface.
admin.site.site_header = 'Release Notes Administration'
admin.site.site_title = 'Release Notes Administration'
urlpatterns = [
url(r'', include('nucleus.base.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^api-token-auth/',
'rest_framework.authtoken.views.obtain_auth_token'),
url(r'^rna/', include('rna.urls')),
url(r'^robots\.txt$', lambda r: HttpResponse(
"User-agent: *\n%s: /" % ('Allow' if settings.ENGAGE_ROBOTS else 'Disallow'),
content_type="text/plain")),
url(r'^healthz/$', watchman_views.ping, name="watchman.ping"),
url(r'^readiness/$', watchman_views.status, name="watchman.status"),
]
if settings.OIDC_ENABLE:
urlpatterns.append(url(r'^oidc/', include('mozilla_django_oidc.urls')))
|
...
admin.autodiscover() # Discover admin.py files for the admin interface.
admin.site.site_header = 'Release Notes Administration'
admin.site.site_title = 'Release Notes Administration'
urlpatterns = [
url(r'', include('nucleus.base.urls')),
...
|
a9b225d033d0462f47e4adecef2ef90fc0bf2318
|
docs/conf.py
|
docs/conf.py
|
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from gravity import __version__ # noqa: E402
project = 'Gravity'
copyright = '2022, The Galaxy Project'
author = 'The Galaxy Project'
release = '__version__'
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = []
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = 'alabaster'
html_static_path = ['_static']
|
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from gravity import __version__ # noqa: E402
project = 'Gravity'
copyright = '2022, The Galaxy Project'
author = 'The Galaxy Project'
release = '__version__'
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = []
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = 'alabaster'
html_static_path = ['_static']
|
Correct path to parent dir
|
Correct path to parent dir
|
Python
|
mit
|
galaxyproject/gravity
|
python
|
## Code Before:
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from gravity import __version__ # noqa: E402
project = 'Gravity'
copyright = '2022, The Galaxy Project'
author = 'The Galaxy Project'
release = '__version__'
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = []
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = 'alabaster'
html_static_path = ['_static']
## Instruction:
Correct path to parent dir
## Code After:
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from gravity import __version__ # noqa: E402
project = 'Gravity'
copyright = '2022, The Galaxy Project'
author = 'The Galaxy Project'
release = '__version__'
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = []
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = 'alabaster'
html_static_path = ['_static']
|
// ... existing code ...
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from gravity import __version__ # noqa: E402
// ... rest of the code ...
|
5e824c74ed6a9bbe8acc518b0d723f6272af311a
|
languagetool-language-modules/fa/src/test/java/org/languagetool/tokenizers/PersianSRXSentenceTokenizerTest.java
|
languagetool-language-modules/fa/src/test/java/org/languagetool/tokenizers/PersianSRXSentenceTokenizerTest.java
|
/* LanguageTool, a natural language style checker
* Copyright (C) 2014 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.tokenizers;
import org.junit.Test;
import org.languagetool.TestTools;
import org.languagetool.language.Persian;
public class PersianSRXSentenceTokenizerTest {
private final SRXSentenceTokenizer stokenizer = new SRXSentenceTokenizer(new Persian());
@Test
public void test() {
testSplit("این یک جمله است. ", "حملهٔ بعدی");
}
private void testSplit(String... sentences) {
TestTools.testSplit(sentences, stokenizer);
}
}
|
/* LanguageTool, a natural language style checker
* Copyright (C) 2014 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.tokenizers;
import org.junit.Test;
import org.languagetool.TestTools;
import org.languagetool.language.Persian;
public class PersianSRXSentenceTokenizerTest {
private final SRXSentenceTokenizer stokenizer = new SRXSentenceTokenizer(new Persian());
@Test
public void test() {
// NOTE: sentences here need to end with a space character so they
// have correct whitespace when appended:
testSplit("این یک جمله است. ", "حملهٔ بعدی");
}
private void testSplit(String... sentences) {
TestTools.testSplit(sentences, stokenizer);
}
}
|
Bring back the accidentally removed comment
|
[fa] Bring back the accidentally removed comment
|
Java
|
lgpl-2.1
|
languagetool-org/languagetool,janissl/languagetool,janissl/languagetool,meg0man/languagetool,meg0man/languagetool,jimregan/languagetool,lopescan/languagetool,languagetool-org/languagetool,jimregan/languagetool,languagetool-org/languagetool,lopescan/languagetool,janissl/languagetool,meg0man/languagetool,janissl/languagetool,jimregan/languagetool,lopescan/languagetool,lopescan/languagetool,jimregan/languagetool,janissl/languagetool,meg0man/languagetool,meg0man/languagetool,lopescan/languagetool,languagetool-org/languagetool,jimregan/languagetool,languagetool-org/languagetool,janissl/languagetool
|
java
|
## Code Before:
/* LanguageTool, a natural language style checker
* Copyright (C) 2014 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.tokenizers;
import org.junit.Test;
import org.languagetool.TestTools;
import org.languagetool.language.Persian;
public class PersianSRXSentenceTokenizerTest {
private final SRXSentenceTokenizer stokenizer = new SRXSentenceTokenizer(new Persian());
@Test
public void test() {
testSplit("این یک جمله است. ", "حملهٔ بعدی");
}
private void testSplit(String... sentences) {
TestTools.testSplit(sentences, stokenizer);
}
}
## Instruction:
[fa] Bring back the accidentally removed comment
## Code After:
/* LanguageTool, a natural language style checker
* Copyright (C) 2014 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.tokenizers;
import org.junit.Test;
import org.languagetool.TestTools;
import org.languagetool.language.Persian;
public class PersianSRXSentenceTokenizerTest {
private final SRXSentenceTokenizer stokenizer = new SRXSentenceTokenizer(new Persian());
@Test
public void test() {
// NOTE: sentences here need to end with a space character so they
// have correct whitespace when appended:
testSplit("این یک جمله است. ", "حملهٔ بعدی");
}
private void testSplit(String... sentences) {
TestTools.testSplit(sentences, stokenizer);
}
}
|
...
@Test
public void test() {
// NOTE: sentences here need to end with a space character so they
// have correct whitespace when appended:
testSplit("این یک جمله است. ", "حملهٔ بعدی");
}
...
|
ad8b8d6db5e81884ff5e3270455c714024cccbc1
|
Tools/scripts/findlinksto.py
|
Tools/scripts/findlinksto.py
|
import os
import sys
import regex
import getopt
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], '')
if len(args) < 2:
raise getopt.error, 'not enough arguments'
except getopt.error, msg:
sys.stdout = sys.stderr
print msg
print 'usage: findlinksto pattern directory ...'
sys.exit(2)
pat, dirs = args[0], args[1:]
prog = regex.compile(pat)
for dirname in dirs:
os.path.walk(dirname, visit, prog)
def visit(prog, dirname, names):
if os.path.islink(dirname):
names[:] = []
return
if os.path.ismount(dirname):
print 'descend into', dirname
for name in names:
name = os.path.join(dirname, name)
try:
linkto = os.readlink(name)
if prog.search(linkto) >= 0:
print name, '->', linkto
except os.error:
pass
main()
|
import os
import sys
import re
import getopt
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], '')
if len(args) < 2:
raise getopt.GetoptError('not enough arguments', None)
except getopt.GetoptError, msg:
sys.stdout = sys.stderr
print msg
print 'usage: findlinksto pattern directory ...'
sys.exit(2)
pat, dirs = args[0], args[1:]
prog = re.compile(pat)
for dirname in dirs:
os.path.walk(dirname, visit, prog)
def visit(prog, dirname, names):
if os.path.islink(dirname):
names[:] = []
return
if os.path.ismount(dirname):
print 'descend into', dirname
for name in names:
name = os.path.join(dirname, name)
try:
linkto = os.readlink(name)
if prog.search(linkto) is not None:
print name, '->', linkto
except os.error:
pass
main()
|
Use new name for GetoptError, and pass it two arguments Use re module instead of regex
|
Use new name for GetoptError, and pass it two arguments
Use re module instead of regex
|
Python
|
mit
|
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
|
python
|
## Code Before:
import os
import sys
import regex
import getopt
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], '')
if len(args) < 2:
raise getopt.error, 'not enough arguments'
except getopt.error, msg:
sys.stdout = sys.stderr
print msg
print 'usage: findlinksto pattern directory ...'
sys.exit(2)
pat, dirs = args[0], args[1:]
prog = regex.compile(pat)
for dirname in dirs:
os.path.walk(dirname, visit, prog)
def visit(prog, dirname, names):
if os.path.islink(dirname):
names[:] = []
return
if os.path.ismount(dirname):
print 'descend into', dirname
for name in names:
name = os.path.join(dirname, name)
try:
linkto = os.readlink(name)
if prog.search(linkto) >= 0:
print name, '->', linkto
except os.error:
pass
main()
## Instruction:
Use new name for GetoptError, and pass it two arguments
Use re module instead of regex
## Code After:
import os
import sys
import re
import getopt
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], '')
if len(args) < 2:
raise getopt.GetoptError('not enough arguments', None)
except getopt.GetoptError, msg:
sys.stdout = sys.stderr
print msg
print 'usage: findlinksto pattern directory ...'
sys.exit(2)
pat, dirs = args[0], args[1:]
prog = re.compile(pat)
for dirname in dirs:
os.path.walk(dirname, visit, prog)
def visit(prog, dirname, names):
if os.path.islink(dirname):
names[:] = []
return
if os.path.ismount(dirname):
print 'descend into', dirname
for name in names:
name = os.path.join(dirname, name)
try:
linkto = os.readlink(name)
if prog.search(linkto) is not None:
print name, '->', linkto
except os.error:
pass
main()
|
// ... existing code ...
import os
import sys
import re
import getopt
def main():
// ... modified code ...
try:
opts, args = getopt.getopt(sys.argv[1:], '')
if len(args) < 2:
raise getopt.GetoptError('not enough arguments', None)
except getopt.GetoptError, msg:
sys.stdout = sys.stderr
print msg
print 'usage: findlinksto pattern directory ...'
sys.exit(2)
pat, dirs = args[0], args[1:]
prog = re.compile(pat)
for dirname in dirs:
os.path.walk(dirname, visit, prog)
...
name = os.path.join(dirname, name)
try:
linkto = os.readlink(name)
if prog.search(linkto) is not None:
print name, '->', linkto
except os.error:
pass
// ... rest of the code ...
|
23edca2a2a87ca0d96becd92a0bf930cc6c33b6f
|
alltheitems/world.py
|
alltheitems/world.py
|
import alltheitems.__main__ as ati
import api.v2
import enum
import minecraft
class Dimension(enum.Enum):
overworld = 0
nether = -1
end = 1
class World:
def __init__(self, world=None):
if world is None:
self.world = minecraft.World()
elif isinstance(world, minecraft.World):
self.world = world
elif isinstance(world, str):
self.world = minecraft.World(world)
else:
raise TypeError('Invalid world type: {}'.format(type(world)))
def block_at(self, x, y, z, dimension=Dimension.overworld):
chunk_x, block_x = divmod(x, 16)
chunk_y, block_y = divmod(y, 16)
chunk_z, block_z = divmod(z, 16)
chunk = {
Dimension.overworld: api.v2.chunk_info_overworld,
Dimension.nether: api.v2.chunk_info_nether,
Dimension.end: api.v2.chunk_info_end
}[dimension](self.world, chunk_x, chunk_y, chunk_z)
return chunk[block_y][block_z][block_x]
|
import alltheitems.__main__ as ati
import api.v2
import enum
import minecraft
class Dimension(enum.Enum):
overworld = 0
nether = -1
end = 1
class World:
def __init__(self, world=None):
if world is None:
self.world = minecraft.World()
elif isinstance(world, minecraft.World):
self.world = world
elif isinstance(world, str):
self.world = minecraft.World(world)
else:
raise TypeError('Invalid world type: {}'.format(type(world)))
def block_at(self, x, y, z, dimension=Dimension.overworld):
chunk_x, block_x = divmod(x, 16)
chunk_y, block_y = divmod(y, 16)
chunk_z, block_z = divmod(z, 16)
chunk = {
Dimension.overworld: api.v2.api_chunk_info_overworld,
Dimension.nether: api.v2.api_chunk_info_nether,
Dimension.end: api.v2.api_chunk_info_end
}[dimension](self.world, chunk_x, chunk_y, chunk_z)
return chunk[block_y][block_z][block_x]
|
Fix API method names called by World.block_at
|
Fix API method names called by World.block_at
|
Python
|
mit
|
wurstmineberg/alltheitems.wurstmineberg.de,wurstmineberg/alltheitems.wurstmineberg.de
|
python
|
## Code Before:
import alltheitems.__main__ as ati
import api.v2
import enum
import minecraft
class Dimension(enum.Enum):
overworld = 0
nether = -1
end = 1
class World:
def __init__(self, world=None):
if world is None:
self.world = minecraft.World()
elif isinstance(world, minecraft.World):
self.world = world
elif isinstance(world, str):
self.world = minecraft.World(world)
else:
raise TypeError('Invalid world type: {}'.format(type(world)))
def block_at(self, x, y, z, dimension=Dimension.overworld):
chunk_x, block_x = divmod(x, 16)
chunk_y, block_y = divmod(y, 16)
chunk_z, block_z = divmod(z, 16)
chunk = {
Dimension.overworld: api.v2.chunk_info_overworld,
Dimension.nether: api.v2.chunk_info_nether,
Dimension.end: api.v2.chunk_info_end
}[dimension](self.world, chunk_x, chunk_y, chunk_z)
return chunk[block_y][block_z][block_x]
## Instruction:
Fix API method names called by World.block_at
## Code After:
import alltheitems.__main__ as ati
import api.v2
import enum
import minecraft
class Dimension(enum.Enum):
overworld = 0
nether = -1
end = 1
class World:
def __init__(self, world=None):
if world is None:
self.world = minecraft.World()
elif isinstance(world, minecraft.World):
self.world = world
elif isinstance(world, str):
self.world = minecraft.World(world)
else:
raise TypeError('Invalid world type: {}'.format(type(world)))
def block_at(self, x, y, z, dimension=Dimension.overworld):
chunk_x, block_x = divmod(x, 16)
chunk_y, block_y = divmod(y, 16)
chunk_z, block_z = divmod(z, 16)
chunk = {
Dimension.overworld: api.v2.api_chunk_info_overworld,
Dimension.nether: api.v2.api_chunk_info_nether,
Dimension.end: api.v2.api_chunk_info_end
}[dimension](self.world, chunk_x, chunk_y, chunk_z)
return chunk[block_y][block_z][block_x]
|
// ... existing code ...
chunk_y, block_y = divmod(y, 16)
chunk_z, block_z = divmod(z, 16)
chunk = {
Dimension.overworld: api.v2.api_chunk_info_overworld,
Dimension.nether: api.v2.api_chunk_info_nether,
Dimension.end: api.v2.api_chunk_info_end
}[dimension](self.world, chunk_x, chunk_y, chunk_z)
return chunk[block_y][block_z][block_x]
// ... rest of the code ...
|
ab5996b9218ec51b2991bb1fd702885414fce8b0
|
lib/ansiblelint/rules/CommandsInsteadOfModulesRule.py
|
lib/ansiblelint/rules/CommandsInsteadOfModulesRule.py
|
import ansiblelint.utils
import os
from ansiblelint import AnsibleLintRule
class CommandsInsteadOfModulesRule(AnsibleLintRule):
id = 'ANSIBLE0006'
shortdesc = 'Using command rather than module'
description = 'Executing a command when there is an Ansible module ' + \
'is generally a bad idea'
tags = ['resources']
_commands = [ 'command', 'shell', 'raw' ]
_modules = { 'git': 'git', 'hg': 'hg', 'curl': 'get_url', 'wget': 'get_url',
'svn': 'subversion', 'cp': 'copy', 'service': 'service',
'mount': 'mount', 'rpm': 'yum', 'yum': 'yum', 'apt-get': 'apt-get' }
def matchtask(self, file, task):
if task["action"]["module"] in self._commands:
executable = os.path.basename(task["action"]["args"][0])
if self._modules.has_key(executable):
message = "{} used in place of {} module"
return message.format(executable, self._modules[executable])
|
import ansiblelint.utils
import os
from ansiblelint import AnsibleLintRule
class CommandsInsteadOfModulesRule(AnsibleLintRule):
id = 'ANSIBLE0006'
shortdesc = 'Using command rather than module'
description = 'Executing a command when there is an Ansible module ' + \
'is generally a bad idea'
tags = ['resources']
_commands = [ 'command', 'shell', 'raw' ]
_modules = { 'git': 'git', 'hg': 'hg', 'curl': 'get_url', 'wget': 'get_url',
'svn': 'subversion', 'cp': 'copy', 'service': 'service',
'mount': 'mount', 'rpm': 'yum', 'yum': 'yum', 'apt-get': 'apt-get',
'unzip': 'unarchive', 'tar': 'unarchive' }
def matchtask(self, file, task):
if task["action"]["module"] in self._commands:
executable = os.path.basename(task["action"]["args"][0])
if self._modules.has_key(executable):
message = "{} used in place of {} module"
return message.format(executable, self._modules[executable])
|
Check whether unzip or tar are used instead of unarchive
|
Check whether unzip or tar are used instead of unarchive
|
Python
|
mit
|
MatrixCrawler/ansible-lint,dataxu/ansible-lint,charleswhchan/ansible-lint,MiLk/ansible-lint,willthames/ansible-lint,schlueter/ansible-lint
|
python
|
## Code Before:
import ansiblelint.utils
import os
from ansiblelint import AnsibleLintRule
class CommandsInsteadOfModulesRule(AnsibleLintRule):
id = 'ANSIBLE0006'
shortdesc = 'Using command rather than module'
description = 'Executing a command when there is an Ansible module ' + \
'is generally a bad idea'
tags = ['resources']
_commands = [ 'command', 'shell', 'raw' ]
_modules = { 'git': 'git', 'hg': 'hg', 'curl': 'get_url', 'wget': 'get_url',
'svn': 'subversion', 'cp': 'copy', 'service': 'service',
'mount': 'mount', 'rpm': 'yum', 'yum': 'yum', 'apt-get': 'apt-get' }
def matchtask(self, file, task):
if task["action"]["module"] in self._commands:
executable = os.path.basename(task["action"]["args"][0])
if self._modules.has_key(executable):
message = "{} used in place of {} module"
return message.format(executable, self._modules[executable])
## Instruction:
Check whether unzip or tar are used instead of unarchive
## Code After:
import ansiblelint.utils
import os
from ansiblelint import AnsibleLintRule
class CommandsInsteadOfModulesRule(AnsibleLintRule):
id = 'ANSIBLE0006'
shortdesc = 'Using command rather than module'
description = 'Executing a command when there is an Ansible module ' + \
'is generally a bad idea'
tags = ['resources']
_commands = [ 'command', 'shell', 'raw' ]
_modules = { 'git': 'git', 'hg': 'hg', 'curl': 'get_url', 'wget': 'get_url',
'svn': 'subversion', 'cp': 'copy', 'service': 'service',
'mount': 'mount', 'rpm': 'yum', 'yum': 'yum', 'apt-get': 'apt-get',
'unzip': 'unarchive', 'tar': 'unarchive' }
def matchtask(self, file, task):
if task["action"]["module"] in self._commands:
executable = os.path.basename(task["action"]["args"][0])
if self._modules.has_key(executable):
message = "{} used in place of {} module"
return message.format(executable, self._modules[executable])
|
// ... existing code ...
_commands = [ 'command', 'shell', 'raw' ]
_modules = { 'git': 'git', 'hg': 'hg', 'curl': 'get_url', 'wget': 'get_url',
'svn': 'subversion', 'cp': 'copy', 'service': 'service',
'mount': 'mount', 'rpm': 'yum', 'yum': 'yum', 'apt-get': 'apt-get',
'unzip': 'unarchive', 'tar': 'unarchive' }
def matchtask(self, file, task):
// ... rest of the code ...
|
4a597ff48f5fd22ab1c6317e8ab1e65a887da284
|
dosagelib/__pyinstaller/hook-dosagelib.py
|
dosagelib/__pyinstaller/hook-dosagelib.py
|
from PyInstaller.utils.hooks import collect_data_files, collect_submodules, copy_metadata
hiddenimports = collect_submodules('dosagelib.plugins')
datas = copy_metadata('dosage') + collect_data_files('dosagelib')
|
from PyInstaller.utils.hooks import collect_data_files, collect_submodules, copy_metadata
hiddenimports = ['dosagelib.data'] + collect_submodules('dosagelib.plugins')
datas = copy_metadata('dosage') + collect_data_files('dosagelib')
|
Make sure dosagelib.data is importable
|
PyInstaller: Make sure dosagelib.data is importable
|
Python
|
mit
|
webcomics/dosage,webcomics/dosage
|
python
|
## Code Before:
from PyInstaller.utils.hooks import collect_data_files, collect_submodules, copy_metadata
hiddenimports = collect_submodules('dosagelib.plugins')
datas = copy_metadata('dosage') + collect_data_files('dosagelib')
## Instruction:
PyInstaller: Make sure dosagelib.data is importable
## Code After:
from PyInstaller.utils.hooks import collect_data_files, collect_submodules, copy_metadata
hiddenimports = ['dosagelib.data'] + collect_submodules('dosagelib.plugins')
datas = copy_metadata('dosage') + collect_data_files('dosagelib')
|
// ... existing code ...
from PyInstaller.utils.hooks import collect_data_files, collect_submodules, copy_metadata
hiddenimports = ['dosagelib.data'] + collect_submodules('dosagelib.plugins')
datas = copy_metadata('dosage') + collect_data_files('dosagelib')
// ... rest of the code ...
|
2a1d397457134ac81c54804a43c16ff15c5a5c9d
|
src/main/ioke/lang/Context.java
|
src/main/ioke/lang/Context.java
|
/*
* See LICENSE file in distribution for copyright and licensing information.
*/
package ioke.lang;
import java.util.IdentityHashMap;
/**
*
* @author <a href="mailto:[email protected]">Ola Bini</a>
*/
public class Context extends IokeObject {
IokeObject ground;
public IokeObject message;
public IokeObject surroundingContext;
public Context(Runtime runtime, IokeObject ground, String documentation, IokeObject message, IokeObject surroundingContext) {
super(runtime, documentation);
this.ground = ground.getRealContext();
this.message = message;
this.surroundingContext = surroundingContext;
if(runtime.context != null) {
this.mimics(runtime.context);
}
setCell("self", getRealContext());
}
public void init() {
}
public IokeObject getRealContext() {
return ground;
}
public IokeObject findCell(IokeObject m, IokeObject context, String name, IdentityHashMap<IokeObject, Object> visited) {
IokeObject nn = super.findCell(m, context, name, visited);
if(nn == runtime.nul) {
return ground.findCell(m, context, name, visited);
} else {
return nn;
}
}
@Override
public String toString() {
return "Context:" + System.identityHashCode(this) + "<" + ground + ">";
}
}// Context
|
/*
* See LICENSE file in distribution for copyright and licensing information.
*/
package ioke.lang;
import java.util.IdentityHashMap;
/**
*
* @author <a href="mailto:[email protected]">Ola Bini</a>
*/
public class Context extends IokeObject {
IokeObject ground;
public IokeObject message;
public IokeObject surroundingContext;
public Context(Runtime runtime, IokeObject ground, String documentation, IokeObject message, IokeObject surroundingContext) {
super(runtime, documentation);
this.ground = ground.getRealContext();
this.message = message;
this.surroundingContext = surroundingContext;
if(runtime.context != null) {
this.mimics(runtime.context);
}
setCell("self", getRealContext());
}
public void init() {
setKind("Context");
}
public IokeObject getRealContext() {
return ground;
}
public IokeObject findCell(IokeObject m, IokeObject context, String name, IdentityHashMap<IokeObject, Object> visited) {
IokeObject nn = super.findCell(m, context, name, visited);
if(nn == runtime.nul) {
return ground.findCell(m, context, name, visited);
} else {
return nn;
}
}
@Override
public String toString() {
return "Context:" + System.identityHashCode(this) + "<" + ground + ">";
}
}// Context
|
Complete refactoring, including addition of kind to all core objects
|
Complete refactoring, including addition of kind to all core objects
|
Java
|
mit
|
vic/ioke-outdated,vic/ioke-outdated,vic/ioke-outdated,vic/ioke-outdated
|
java
|
## Code Before:
/*
* See LICENSE file in distribution for copyright and licensing information.
*/
package ioke.lang;
import java.util.IdentityHashMap;
/**
*
* @author <a href="mailto:[email protected]">Ola Bini</a>
*/
public class Context extends IokeObject {
IokeObject ground;
public IokeObject message;
public IokeObject surroundingContext;
public Context(Runtime runtime, IokeObject ground, String documentation, IokeObject message, IokeObject surroundingContext) {
super(runtime, documentation);
this.ground = ground.getRealContext();
this.message = message;
this.surroundingContext = surroundingContext;
if(runtime.context != null) {
this.mimics(runtime.context);
}
setCell("self", getRealContext());
}
public void init() {
}
public IokeObject getRealContext() {
return ground;
}
public IokeObject findCell(IokeObject m, IokeObject context, String name, IdentityHashMap<IokeObject, Object> visited) {
IokeObject nn = super.findCell(m, context, name, visited);
if(nn == runtime.nul) {
return ground.findCell(m, context, name, visited);
} else {
return nn;
}
}
@Override
public String toString() {
return "Context:" + System.identityHashCode(this) + "<" + ground + ">";
}
}// Context
## Instruction:
Complete refactoring, including addition of kind to all core objects
## Code After:
/*
* See LICENSE file in distribution for copyright and licensing information.
*/
package ioke.lang;
import java.util.IdentityHashMap;
/**
*
* @author <a href="mailto:[email protected]">Ola Bini</a>
*/
public class Context extends IokeObject {
IokeObject ground;
public IokeObject message;
public IokeObject surroundingContext;
public Context(Runtime runtime, IokeObject ground, String documentation, IokeObject message, IokeObject surroundingContext) {
super(runtime, documentation);
this.ground = ground.getRealContext();
this.message = message;
this.surroundingContext = surroundingContext;
if(runtime.context != null) {
this.mimics(runtime.context);
}
setCell("self", getRealContext());
}
public void init() {
setKind("Context");
}
public IokeObject getRealContext() {
return ground;
}
public IokeObject findCell(IokeObject m, IokeObject context, String name, IdentityHashMap<IokeObject, Object> visited) {
IokeObject nn = super.findCell(m, context, name, visited);
if(nn == runtime.nul) {
return ground.findCell(m, context, name, visited);
} else {
return nn;
}
}
@Override
public String toString() {
return "Context:" + System.identityHashCode(this) + "<" + ground + ">";
}
}// Context
|
// ... existing code ...
}
public void init() {
setKind("Context");
}
public IokeObject getRealContext() {
// ... rest of the code ...
|
402c010b6ab4673ae3b5c684b8e0c155ec98b172
|
gentle/gt/operations.py
|
gentle/gt/operations.py
|
from __future__ import absolute_import
from fabric.api import local, run, sudo, task
from fabric.contrib.console import confirm
from fabric.state import env
from fabric.context_managers import cd, lcd, hide, settings
from fabric.colors import red, green
from .utils import repl_root
from .project import rsync_project
@task(alias='p', default=True)
def publish():
'''Publish your app'''
rsync()
restart()
@task(alias='rs')
def rsync():
'''Rsync your local dir to remote'''
rsync_project(env.rsync['rpath'], repl_root(env.rsync['lpath']),
sshpass=True)
@task(alias='rt')
def restart():
'''Restart your services'''
for service, need_ops in env.services.iteritems():
print(green(service + "start..."))
try:
rsync_project(need_ops['rpath'], need_ops['lpath'], sshpass=True)
if need_ops['sudo']:
sudo(need_ops['command'], pty=False,
user=need_ops['user'] if need_ops['user'] else env.user)
else:
run(need_ops['command'])
except:
print(red(service + "fail..."))
continue
print(green(service + "end..."))
|
from __future__ import absolute_import
from fabric.api import local, run, sudo, task
from fabric.contrib.console import confirm
from fabric.state import env
from fabric.context_managers import cd, lcd, hide, settings
from fabric.colors import red, green, yellow
from .utils import repl_root
from .project import rsync_project
@task(alias='p', default=True)
def publish():
'''Publish your app'''
rsync()
restart()
@task(alias='rs')
def rsync():
'''Rsync your local dir to remote'''
rsync_project(env.rsync['rpath'], repl_root(env.rsync['lpath']),
sshpass=True)
@task(alias='rt')
def restart():
'''Restart your services'''
for service, need_ops in env.services.iteritems():
print(yellow(service) + ": " + green("start..."))
try:
rsync_project(need_ops['rpath'], need_ops['lpath'], sshpass=True)
if need_ops['sudo']:
sudo(need_ops['command'], pty=False,
user=need_ops['user'] if need_ops['user'] else env.user)
else:
run(need_ops['command'])
except:
print(red(service + ": fail..."))
continue
print(yellow(service) + ": " + green("end..."))
|
Add yellow color for services
|
Add yellow color for services
|
Python
|
apache-2.0
|
dongweiming/gentle
|
python
|
## Code Before:
from __future__ import absolute_import
from fabric.api import local, run, sudo, task
from fabric.contrib.console import confirm
from fabric.state import env
from fabric.context_managers import cd, lcd, hide, settings
from fabric.colors import red, green
from .utils import repl_root
from .project import rsync_project
@task(alias='p', default=True)
def publish():
'''Publish your app'''
rsync()
restart()
@task(alias='rs')
def rsync():
'''Rsync your local dir to remote'''
rsync_project(env.rsync['rpath'], repl_root(env.rsync['lpath']),
sshpass=True)
@task(alias='rt')
def restart():
'''Restart your services'''
for service, need_ops in env.services.iteritems():
print(green(service + "start..."))
try:
rsync_project(need_ops['rpath'], need_ops['lpath'], sshpass=True)
if need_ops['sudo']:
sudo(need_ops['command'], pty=False,
user=need_ops['user'] if need_ops['user'] else env.user)
else:
run(need_ops['command'])
except:
print(red(service + "fail..."))
continue
print(green(service + "end..."))
## Instruction:
Add yellow color for services
## Code After:
from __future__ import absolute_import
from fabric.api import local, run, sudo, task
from fabric.contrib.console import confirm
from fabric.state import env
from fabric.context_managers import cd, lcd, hide, settings
from fabric.colors import red, green, yellow
from .utils import repl_root
from .project import rsync_project
@task(alias='p', default=True)
def publish():
'''Publish your app'''
rsync()
restart()
@task(alias='rs')
def rsync():
'''Rsync your local dir to remote'''
rsync_project(env.rsync['rpath'], repl_root(env.rsync['lpath']),
sshpass=True)
@task(alias='rt')
def restart():
'''Restart your services'''
for service, need_ops in env.services.iteritems():
print(yellow(service) + ": " + green("start..."))
try:
rsync_project(need_ops['rpath'], need_ops['lpath'], sshpass=True)
if need_ops['sudo']:
sudo(need_ops['command'], pty=False,
user=need_ops['user'] if need_ops['user'] else env.user)
else:
run(need_ops['command'])
except:
print(red(service + ": fail..."))
continue
print(yellow(service) + ": " + green("end..."))
|
...
from fabric.contrib.console import confirm
from fabric.state import env
from fabric.context_managers import cd, lcd, hide, settings
from fabric.colors import red, green, yellow
from .utils import repl_root
from .project import rsync_project
...
def restart():
'''Restart your services'''
for service, need_ops in env.services.iteritems():
print(yellow(service) + ": " + green("start..."))
try:
rsync_project(need_ops['rpath'], need_ops['lpath'], sshpass=True)
if need_ops['sudo']:
...
else:
run(need_ops['command'])
except:
print(red(service + ": fail..."))
continue
print(yellow(service) + ": " + green("end..."))
...
|
a23f6997f1f7ae38a56ffe961590ce167175f6b4
|
src/main/java/org/monospark/actioncontrol/kind/Kind.java
|
src/main/java/org/monospark/actioncontrol/kind/Kind.java
|
package org.monospark.actioncontrol.kind;
import org.monospark.actioncontrol.kind.matcher.KindMatcher;
public abstract class Kind implements KindMatcher {
private String name;
private int variant;
private KindType<?,?> type;
protected Kind(String name, int variant, KindType<?,?> type) {
this.name = name;
this.variant = variant;
this.type = type;
}
public final String getBaseName() {
return name;
}
public final String getName() {
return name + ":" + (variant != 0 ? variant : "");
}
public final int getVariant() {
return variant;
}
public final KindType<?,?> getType() {
return type;
}
}
|
package org.monospark.actioncontrol.kind;
import org.monospark.actioncontrol.kind.matcher.KindMatcher;
public abstract class Kind implements KindMatcher {
private String name;
private int variant;
private KindType<?,?> type;
protected Kind(String name, int variant, KindType<?,?> type) {
this.name = name;
this.variant = variant;
this.type = type;
}
public final String getBaseName() {
return name;
}
public final String getName() {
return name + (variant != 0 ? ":" + variant : "");
}
public final int getVariant() {
return variant;
}
public final KindType<?,?> getType() {
return type;
}
}
|
Fix string representation of kinds
|
Fix string representation of kinds
|
Java
|
mit
|
Monospark/ActionControl
|
java
|
## Code Before:
package org.monospark.actioncontrol.kind;
import org.monospark.actioncontrol.kind.matcher.KindMatcher;
public abstract class Kind implements KindMatcher {
private String name;
private int variant;
private KindType<?,?> type;
protected Kind(String name, int variant, KindType<?,?> type) {
this.name = name;
this.variant = variant;
this.type = type;
}
public final String getBaseName() {
return name;
}
public final String getName() {
return name + ":" + (variant != 0 ? variant : "");
}
public final int getVariant() {
return variant;
}
public final KindType<?,?> getType() {
return type;
}
}
## Instruction:
Fix string representation of kinds
## Code After:
package org.monospark.actioncontrol.kind;
import org.monospark.actioncontrol.kind.matcher.KindMatcher;
public abstract class Kind implements KindMatcher {
private String name;
private int variant;
private KindType<?,?> type;
protected Kind(String name, int variant, KindType<?,?> type) {
this.name = name;
this.variant = variant;
this.type = type;
}
public final String getBaseName() {
return name;
}
public final String getName() {
return name + (variant != 0 ? ":" + variant : "");
}
public final int getVariant() {
return variant;
}
public final KindType<?,?> getType() {
return type;
}
}
|
// ... existing code ...
}
public final String getName() {
return name + (variant != 0 ? ":" + variant : "");
}
public final int getVariant() {
// ... rest of the code ...
|
f463247198354b0af1d0b8a4ff63c0757d4c2839
|
regression.py
|
regression.py
|
import subprocess
subprocess.check_call(["coverage", "run", "--source", "toyplot", "-m", "nose"])
subprocess.check_call(["coverage", "run", "--append", "--source", "toyplot", "-m", "behave"])
subprocess.check_call(["coverage", "report"])
subprocess.check_call(["coverage", "html", "--directory", ".cover"])
|
import subprocess
subprocess.check_call(["coverage", "run", "--source", "toyplot", "--omit", "toyplot/testing.py", "-m", "nose"])
subprocess.check_call(["coverage", "run", "--append", "--source", "toyplot", "--omit", "toyplot/testing.py", "-m", "behave"])
subprocess.check_call(["coverage", "report"])
subprocess.check_call(["coverage", "html", "--directory", ".cover"])
|
Exclude the testing module from coverage results.
|
Exclude the testing module from coverage results.
|
Python
|
bsd-3-clause
|
cmorgan/toyplot,cmorgan/toyplot
|
python
|
## Code Before:
import subprocess
subprocess.check_call(["coverage", "run", "--source", "toyplot", "-m", "nose"])
subprocess.check_call(["coverage", "run", "--append", "--source", "toyplot", "-m", "behave"])
subprocess.check_call(["coverage", "report"])
subprocess.check_call(["coverage", "html", "--directory", ".cover"])
## Instruction:
Exclude the testing module from coverage results.
## Code After:
import subprocess
subprocess.check_call(["coverage", "run", "--source", "toyplot", "--omit", "toyplot/testing.py", "-m", "nose"])
subprocess.check_call(["coverage", "run", "--append", "--source", "toyplot", "--omit", "toyplot/testing.py", "-m", "behave"])
subprocess.check_call(["coverage", "report"])
subprocess.check_call(["coverage", "html", "--directory", ".cover"])
|
...
import subprocess
subprocess.check_call(["coverage", "run", "--source", "toyplot", "--omit", "toyplot/testing.py", "-m", "nose"])
subprocess.check_call(["coverage", "run", "--append", "--source", "toyplot", "--omit", "toyplot/testing.py", "-m", "behave"])
subprocess.check_call(["coverage", "report"])
subprocess.check_call(["coverage", "html", "--directory", ".cover"])
...
|
fae501041857f1e4eea2b5157feb94a3f3c84f18
|
pinax/__init__.py
|
pinax/__init__.py
|
VERSION = (0, 9, 0, "a", 1) # following PEP 386
def get_version():
version = "%s.%s" % (VERSION[0], VERSION[1])
if VERSION[2]:
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
return version
__version__ = get_version()
|
import os
VERSION = (0, 9, 0, "a", 1) # following PEP 386
def get_version():
version = "%s.%s" % (VERSION[0], VERSION[1])
if VERSION[2]:
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
dev = os.environ.get("PINAX_DEV_N")
if dev:
version = "%s.dev%s" % (version, dev)
return version
__version__ = get_version()
|
Support development versions using an environment variable
|
Support development versions using an environment variable
|
Python
|
mit
|
amarandon/pinax,amarandon/pinax,amarandon/pinax,amarandon/pinax
|
python
|
## Code Before:
VERSION = (0, 9, 0, "a", 1) # following PEP 386
def get_version():
version = "%s.%s" % (VERSION[0], VERSION[1])
if VERSION[2]:
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
return version
__version__ = get_version()
## Instruction:
Support development versions using an environment variable
## Code After:
import os
VERSION = (0, 9, 0, "a", 1) # following PEP 386
def get_version():
version = "%s.%s" % (VERSION[0], VERSION[1])
if VERSION[2]:
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
dev = os.environ.get("PINAX_DEV_N")
if dev:
version = "%s.dev%s" % (version, dev)
return version
__version__ = get_version()
|
// ... existing code ...
import os
VERSION = (0, 9, 0, "a", 1) # following PEP 386
// ... modified code ...
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
dev = os.environ.get("PINAX_DEV_N")
if dev:
version = "%s.dev%s" % (version, dev)
return version
// ... rest of the code ...
|
abd0a6854c90c3647d17dfb3ea980fa49aa5372f
|
pwndbg/commands/segments.py
|
pwndbg/commands/segments.py
|
from __future__ import print_function
import gdb
import pwndbg.regs
class segment(gdb.Function):
"""Get the flat address of memory based off of the named segment register.
"""
def __init__(self, name):
super(segment, self).__init__(name)
self.name = name
def invoke(self, arg=0):
result = getattr(pwndbg.regs, self.name)
return result + arg
segment('fsbase')
segment('gsbase')
|
from __future__ import print_function
import gdb
import pwndbg.regs
import pwndbg.commands
class segment(gdb.Function):
"""Get the flat address of memory based off of the named segment register.
"""
def __init__(self, name):
super(segment, self).__init__(name)
self.name = name
def invoke(self, arg=0):
result = getattr(pwndbg.regs, self.name)
return result + arg
segment('fsbase')
segment('gsbase')
@pwndbg.commands.OnlyWhenRunning
@pwndbg.commands.ParsedCommand
def fsbase():
"""
Prints out the FS base address. See also $fsbase.
"""
print(hex(pwndbg.regs.fsbase))
@pwndbg.commands.OnlyWhenRunning
@pwndbg.commands.ParsedCommand
def gsbase():
"""
Prints out the GS base address. See also $gsbase.
"""
print(hex(pwndbg.regs.gsbase))
|
Add fsbase and gsbase commands
|
Add fsbase and gsbase commands
|
Python
|
mit
|
cebrusfs/217gdb,anthraxx/pwndbg,chubbymaggie/pwndbg,anthraxx/pwndbg,disconnect3d/pwndbg,0xddaa/pwndbg,0xddaa/pwndbg,cebrusfs/217gdb,zachriggle/pwndbg,disconnect3d/pwndbg,pwndbg/pwndbg,disconnect3d/pwndbg,anthraxx/pwndbg,cebrusfs/217gdb,zachriggle/pwndbg,pwndbg/pwndbg,pwndbg/pwndbg,anthraxx/pwndbg,chubbymaggie/pwndbg,cebrusfs/217gdb,pwndbg/pwndbg,0xddaa/pwndbg
|
python
|
## Code Before:
from __future__ import print_function
import gdb
import pwndbg.regs
class segment(gdb.Function):
"""Get the flat address of memory based off of the named segment register.
"""
def __init__(self, name):
super(segment, self).__init__(name)
self.name = name
def invoke(self, arg=0):
result = getattr(pwndbg.regs, self.name)
return result + arg
segment('fsbase')
segment('gsbase')
## Instruction:
Add fsbase and gsbase commands
## Code After:
from __future__ import print_function
import gdb
import pwndbg.regs
import pwndbg.commands
class segment(gdb.Function):
"""Get the flat address of memory based off of the named segment register.
"""
def __init__(self, name):
super(segment, self).__init__(name)
self.name = name
def invoke(self, arg=0):
result = getattr(pwndbg.regs, self.name)
return result + arg
segment('fsbase')
segment('gsbase')
@pwndbg.commands.OnlyWhenRunning
@pwndbg.commands.ParsedCommand
def fsbase():
"""
Prints out the FS base address. See also $fsbase.
"""
print(hex(pwndbg.regs.fsbase))
@pwndbg.commands.OnlyWhenRunning
@pwndbg.commands.ParsedCommand
def gsbase():
"""
Prints out the GS base address. See also $gsbase.
"""
print(hex(pwndbg.regs.gsbase))
|
...
from __future__ import print_function
import gdb
import pwndbg.regs
import pwndbg.commands
class segment(gdb.Function):
"""Get the flat address of memory based off of the named segment register.
...
segment('fsbase')
segment('gsbase')
@pwndbg.commands.OnlyWhenRunning
@pwndbg.commands.ParsedCommand
def fsbase():
"""
Prints out the FS base address. See also $fsbase.
"""
print(hex(pwndbg.regs.fsbase))
@pwndbg.commands.OnlyWhenRunning
@pwndbg.commands.ParsedCommand
def gsbase():
"""
Prints out the GS base address. See also $gsbase.
"""
print(hex(pwndbg.regs.gsbase))
...
|
c19a64ecdbde5a387a84dec880c2ebea1013c3d6
|
canopus/auth/token_factory.py
|
canopus/auth/token_factory.py
|
from datetime import datetime, timedelta
from ..schema import UserSchema
class TokenFactory(object):
def __init__(self, request, user):
self.user = user
self.request = request
def create_access_token(self):
user = self.user
if user.last_signed_in is None:
user.welcome()
user.last_signed_in = datetime.now()
token = self.request.create_jwt_token(user.id, expiration=timedelta(days=7))
user_schema = UserSchema(exclude=('enabled',))
return dict(token=token, user={})
|
from datetime import datetime, timedelta
from ..schema import UserSchema
class TokenFactory(object):
def __init__(self, request, user):
self.user = user
self.request = request
def create_access_token(self):
user = self.user
user.last_signed_in = datetime.now()
token = self.request.create_jwt_token(user.id, expiration=timedelta(days=7))
user_schema = UserSchema(exclude=('enabled',))
return dict(token=token, user=user_schema.dump(user).data)
|
Include user in create_access_token return value
|
Include user in create_access_token return value
|
Python
|
mit
|
josuemontano/api-starter,josuemontano/API-platform,josuemontano/pyramid-angularjs-starter,josuemontano/API-platform,josuemontano/API-platform,josuemontano/api-starter,josuemontano/api-starter,josuemontano/pyramid-angularjs-starter,josuemontano/pyramid-angularjs-starter,josuemontano/API-platform
|
python
|
## Code Before:
from datetime import datetime, timedelta
from ..schema import UserSchema
class TokenFactory(object):
def __init__(self, request, user):
self.user = user
self.request = request
def create_access_token(self):
user = self.user
if user.last_signed_in is None:
user.welcome()
user.last_signed_in = datetime.now()
token = self.request.create_jwt_token(user.id, expiration=timedelta(days=7))
user_schema = UserSchema(exclude=('enabled',))
return dict(token=token, user={})
## Instruction:
Include user in create_access_token return value
## Code After:
from datetime import datetime, timedelta
from ..schema import UserSchema
class TokenFactory(object):
def __init__(self, request, user):
self.user = user
self.request = request
def create_access_token(self):
user = self.user
user.last_signed_in = datetime.now()
token = self.request.create_jwt_token(user.id, expiration=timedelta(days=7))
user_schema = UserSchema(exclude=('enabled',))
return dict(token=token, user=user_schema.dump(user).data)
|
...
def create_access_token(self):
user = self.user
user.last_signed_in = datetime.now()
token = self.request.create_jwt_token(user.id, expiration=timedelta(days=7))
user_schema = UserSchema(exclude=('enabled',))
return dict(token=token, user=user_schema.dump(user).data)
...
|
26579d307d44f00fe71853fa6c13957018fe5c0f
|
capnp/__init__.py
|
capnp/__init__.py
|
from .version import version as __version__
from .capnp import *
from .capnp import _DynamicStructReader, _DynamicStructBuilder, _DynamicResizableListBuilder, _DynamicListReader, _DynamicListBuilder, _DynamicOrphan, _DynamicResizableListBuilder, _MallocMessageBuilder, _PackedFdMessageReader, _StreamFdMessageReader, _write_message_to_fd, _write_packed_message_to_fd
del capnp
|
from .version import version as __version__
from .capnp import *
from .capnp import _DynamicStructReader, _DynamicStructBuilder, _DynamicResizableListBuilder, _DynamicListReader, _DynamicListBuilder, _DynamicOrphan, _DynamicResizableListBuilder, _MallocMessageBuilder, _PackedFdMessageReader, _StreamFdMessageReader, _write_message_to_fd, _write_packed_message_to_fd
del capnp
add_import_hook() # enable import hook by default
|
Enable import hook by default
|
Enable import hook by default
|
Python
|
bsd-2-clause
|
rcrowder/pycapnp,SymbiFlow/pycapnp,jparyani/pycapnp,SymbiFlow/pycapnp,SymbiFlow/pycapnp,tempbottle/pycapnp,tempbottle/pycapnp,jparyani/pycapnp,rcrowder/pycapnp,SymbiFlow/pycapnp,jparyani/pycapnp,jparyani/pycapnp,tempbottle/pycapnp,rcrowder/pycapnp,rcrowder/pycapnp,tempbottle/pycapnp
|
python
|
## Code Before:
from .version import version as __version__
from .capnp import *
from .capnp import _DynamicStructReader, _DynamicStructBuilder, _DynamicResizableListBuilder, _DynamicListReader, _DynamicListBuilder, _DynamicOrphan, _DynamicResizableListBuilder, _MallocMessageBuilder, _PackedFdMessageReader, _StreamFdMessageReader, _write_message_to_fd, _write_packed_message_to_fd
del capnp
## Instruction:
Enable import hook by default
## Code After:
from .version import version as __version__
from .capnp import *
from .capnp import _DynamicStructReader, _DynamicStructBuilder, _DynamicResizableListBuilder, _DynamicListReader, _DynamicListBuilder, _DynamicOrphan, _DynamicResizableListBuilder, _MallocMessageBuilder, _PackedFdMessageReader, _StreamFdMessageReader, _write_message_to_fd, _write_packed_message_to_fd
del capnp
add_import_hook() # enable import hook by default
|
// ... existing code ...
from .capnp import *
from .capnp import _DynamicStructReader, _DynamicStructBuilder, _DynamicResizableListBuilder, _DynamicListReader, _DynamicListBuilder, _DynamicOrphan, _DynamicResizableListBuilder, _MallocMessageBuilder, _PackedFdMessageReader, _StreamFdMessageReader, _write_message_to_fd, _write_packed_message_to_fd
del capnp
add_import_hook() # enable import hook by default
// ... rest of the code ...
|
83ef5cc17804f083c6c704796fcf85ecf94d584f
|
android-prerelise/BlueCharm/src/ru/spbau/bluecharm/CallsNotifier.java
|
android-prerelise/BlueCharm/src/ru/spbau/bluecharm/CallsNotifier.java
|
package ru.spbau.bluecharm;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.util.Log;
public class CallsNotifier extends BroadcastReceiver {
public static final String TAG = "CALLS_NOTIFIER";
@Override
public void onReceive(Context context, Intent intent) {
IBinder binder = peekService(context, new Intent(context, BlueCharmService.class));
if (binder != null) {
Messenger messenger = new Messenger(binder);
Message msg = Message.obtain(null, BlueCharmService.MSG_NOTIFY_LISTENERS, 0, 0);
Bundle bundle = new Bundle();
bundle.putString(null, intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER));
msg.setData(bundle);
try {
messenger.send(msg);
} catch (RemoteException e) {
Log.e(TAG, e.getLocalizedMessage());
}
} else {
Log.d(TAG, "BlueCharmService isn't running");
}
}
}
|
package ru.spbau.bluecharm;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.util.Log;
public class CallsNotifier extends BroadcastReceiver {
public static final String TAG = "CALLS_NOTIFIER";
@Override
public void onReceive(Context context, Intent intent) {
IBinder binder = peekService(context, new Intent(context, BlueCharmService.class));
if (binder != null) {
Log.d(TAG, "Intent received: " + intent.getStringExtra(TelephonyManager.EXTRA_STATE));
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)) {
Messenger messenger = new Messenger(binder);
Message msg = Message.obtain(null, BlueCharmService.MSG_NOTIFY_LISTENERS, 0, 0);
Bundle bundle = new Bundle();
bundle.putString(null, "Call: " + intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER));
msg.setData(bundle);
try {
messenger.send(msg);
} catch (RemoteException e) {
Log.e(TAG, e.getLocalizedMessage());
}
}
} else {
Log.d(TAG, "BlueCharmService isn't running");
}
}
}
|
Call prefix in a notification
|
Call prefix in a notification
|
Java
|
mit
|
krinkinmu/Blue-Charm,krinkinmu/Blue-Charm
|
java
|
## Code Before:
package ru.spbau.bluecharm;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.util.Log;
public class CallsNotifier extends BroadcastReceiver {
public static final String TAG = "CALLS_NOTIFIER";
@Override
public void onReceive(Context context, Intent intent) {
IBinder binder = peekService(context, new Intent(context, BlueCharmService.class));
if (binder != null) {
Messenger messenger = new Messenger(binder);
Message msg = Message.obtain(null, BlueCharmService.MSG_NOTIFY_LISTENERS, 0, 0);
Bundle bundle = new Bundle();
bundle.putString(null, intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER));
msg.setData(bundle);
try {
messenger.send(msg);
} catch (RemoteException e) {
Log.e(TAG, e.getLocalizedMessage());
}
} else {
Log.d(TAG, "BlueCharmService isn't running");
}
}
}
## Instruction:
Call prefix in a notification
## Code After:
package ru.spbau.bluecharm;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.util.Log;
public class CallsNotifier extends BroadcastReceiver {
public static final String TAG = "CALLS_NOTIFIER";
@Override
public void onReceive(Context context, Intent intent) {
IBinder binder = peekService(context, new Intent(context, BlueCharmService.class));
if (binder != null) {
Log.d(TAG, "Intent received: " + intent.getStringExtra(TelephonyManager.EXTRA_STATE));
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)) {
Messenger messenger = new Messenger(binder);
Message msg = Message.obtain(null, BlueCharmService.MSG_NOTIFY_LISTENERS, 0, 0);
Bundle bundle = new Bundle();
bundle.putString(null, "Call: " + intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER));
msg.setData(bundle);
try {
messenger.send(msg);
} catch (RemoteException e) {
Log.e(TAG, e.getLocalizedMessage());
}
}
} else {
Log.d(TAG, "BlueCharmService isn't running");
}
}
}
|
...
public void onReceive(Context context, Intent intent) {
IBinder binder = peekService(context, new Intent(context, BlueCharmService.class));
if (binder != null) {
Log.d(TAG, "Intent received: " + intent.getStringExtra(TelephonyManager.EXTRA_STATE));
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)) {
Messenger messenger = new Messenger(binder);
Message msg = Message.obtain(null, BlueCharmService.MSG_NOTIFY_LISTENERS, 0, 0);
Bundle bundle = new Bundle();
bundle.putString(null, "Call: " + intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER));
msg.setData(bundle);
try {
messenger.send(msg);
} catch (RemoteException e) {
Log.e(TAG, e.getLocalizedMessage());
}
}
} else {
Log.d(TAG, "BlueCharmService isn't running");
...
|
cfdbe06da6e35f2cb166374cf249d51f18e1224e
|
pryvate/blueprints/packages/packages.py
|
pryvate/blueprints/packages/packages.py
|
"""Package blueprint."""
import os
import magic
from flask import Blueprint, current_app, make_response, render_template
blueprint = Blueprint('packages', __name__, url_prefix='/packages')
@blueprint.route('')
def foo():
return 'ok'
@blueprint.route('/<package_type>/<letter>/<name>/<version>',
methods=['GET', 'HEAD'])
def packages(package_type, letter, name, version):
"""Get the contents of a package."""
filepath = os.path.join(current_app.config['BASEDIR'], name.lower(),
version.lower())
if os.path.isfile(filepath):
with open(filepath, 'rb') as egg:
mimetype = magic.from_file(filepath, mime=True)
contents = egg.read()
return make_response(contents, 200, {'Content-Type': mimetype})
|
"""Package blueprint."""
import os
import magic
from flask import Blueprint, current_app, make_response, render_template
blueprint = Blueprint('packages', __name__, url_prefix='/packages')
@blueprint.route('')
def foo():
return 'ok'
@blueprint.route('/<package_type>/<letter>/<name>/<version>',
methods=['GET', 'HEAD'])
def packages(package_type, letter, name, version):
"""Get the contents of a package."""
filepath = os.path.join(current_app.config['BASEDIR'], name.lower(),
version.lower())
if os.path.isfile(filepath):
with open(filepath, 'rb') as egg:
mimetype = magic.from_file(filepath, mime=True)
contents = egg.read()
return make_response(contents, 200, {'Content-Type': mimetype})
return make_response('Package not found', 404)
|
Return a 404 if the package was not found
|
Return a 404 if the package was not found
|
Python
|
mit
|
Dinoshauer/pryvate,Dinoshauer/pryvate
|
python
|
## Code Before:
"""Package blueprint."""
import os
import magic
from flask import Blueprint, current_app, make_response, render_template
blueprint = Blueprint('packages', __name__, url_prefix='/packages')
@blueprint.route('')
def foo():
return 'ok'
@blueprint.route('/<package_type>/<letter>/<name>/<version>',
methods=['GET', 'HEAD'])
def packages(package_type, letter, name, version):
"""Get the contents of a package."""
filepath = os.path.join(current_app.config['BASEDIR'], name.lower(),
version.lower())
if os.path.isfile(filepath):
with open(filepath, 'rb') as egg:
mimetype = magic.from_file(filepath, mime=True)
contents = egg.read()
return make_response(contents, 200, {'Content-Type': mimetype})
## Instruction:
Return a 404 if the package was not found
## Code After:
"""Package blueprint."""
import os
import magic
from flask import Blueprint, current_app, make_response, render_template
blueprint = Blueprint('packages', __name__, url_prefix='/packages')
@blueprint.route('')
def foo():
return 'ok'
@blueprint.route('/<package_type>/<letter>/<name>/<version>',
methods=['GET', 'HEAD'])
def packages(package_type, letter, name, version):
"""Get the contents of a package."""
filepath = os.path.join(current_app.config['BASEDIR'], name.lower(),
version.lower())
if os.path.isfile(filepath):
with open(filepath, 'rb') as egg:
mimetype = magic.from_file(filepath, mime=True)
contents = egg.read()
return make_response(contents, 200, {'Content-Type': mimetype})
return make_response('Package not found', 404)
|
# ... existing code ...
mimetype = magic.from_file(filepath, mime=True)
contents = egg.read()
return make_response(contents, 200, {'Content-Type': mimetype})
return make_response('Package not found', 404)
# ... rest of the code ...
|
315a5c25429b3910446714238c28382ba727add8
|
copywriting/urls.py
|
copywriting/urls.py
|
from django.conf.urls.defaults import *
from .feed import blogFeed
urlpatterns = patterns('copywriting',
(r'^feed\.rss$', blogFeed()),
(r'^feed/$', blogFeed()),
(r'^tag/(?P<in_tag>\w+)/$', 'views.withTag'),
# (r'^(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)/$', 'views.listBlogEntriesByYearMonthDay'),
(r'^(?P<requestYear>\d+)/(?P<requestMonth>\d+)/$', 'views.listArticlesByYearMonth'),
(r'^(?P<requestYear>\d+)/$', 'views.listArticlesByYear'),
(r'^(?P<slug>[^\.]+)/$', 'views.showArticle'),
(r'^$', 'views.listArticles'),
)
|
from django.conf.urls.defaults import *
from .feed import blogFeed
urlpatterns = patterns('copywriting',
(r'^feed\.rss$', blogFeed()),
(r'^feed/$', blogFeed()),
(r'^tag/(?P<in_tag>\w[\w-]+)/$', 'views.withTag'),
# (r'^(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)/$', 'views.listBlogEntriesByYearMonthDay'),
(r'^(?P<requestYear>\d+)/(?P<requestMonth>\d+)/$', 'views.listArticlesByYearMonth'),
(r'^(?P<requestYear>\d+)/$', 'views.listArticlesByYear'),
(r'^(?P<slug>[^\.]+)/$', 'views.showArticle'),
(r'^$', 'views.listArticles'),
)
|
Allow slugs in url patterns
|
Allow slugs in url patterns
|
Python
|
mit
|
arteria/django-copywriting,arteria/django-copywriting
|
python
|
## Code Before:
from django.conf.urls.defaults import *
from .feed import blogFeed
urlpatterns = patterns('copywriting',
(r'^feed\.rss$', blogFeed()),
(r'^feed/$', blogFeed()),
(r'^tag/(?P<in_tag>\w+)/$', 'views.withTag'),
# (r'^(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)/$', 'views.listBlogEntriesByYearMonthDay'),
(r'^(?P<requestYear>\d+)/(?P<requestMonth>\d+)/$', 'views.listArticlesByYearMonth'),
(r'^(?P<requestYear>\d+)/$', 'views.listArticlesByYear'),
(r'^(?P<slug>[^\.]+)/$', 'views.showArticle'),
(r'^$', 'views.listArticles'),
)
## Instruction:
Allow slugs in url patterns
## Code After:
from django.conf.urls.defaults import *
from .feed import blogFeed
urlpatterns = patterns('copywriting',
(r'^feed\.rss$', blogFeed()),
(r'^feed/$', blogFeed()),
(r'^tag/(?P<in_tag>\w[\w-]+)/$', 'views.withTag'),
# (r'^(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)/$', 'views.listBlogEntriesByYearMonthDay'),
(r'^(?P<requestYear>\d+)/(?P<requestMonth>\d+)/$', 'views.listArticlesByYearMonth'),
(r'^(?P<requestYear>\d+)/$', 'views.listArticlesByYear'),
(r'^(?P<slug>[^\.]+)/$', 'views.showArticle'),
(r'^$', 'views.listArticles'),
)
|
// ... existing code ...
from .feed import blogFeed
urlpatterns = patterns('copywriting',
(r'^feed\.rss$', blogFeed()),
(r'^feed/$', blogFeed()),
(r'^tag/(?P<in_tag>\w[\w-]+)/$', 'views.withTag'),
# (r'^(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)/$', 'views.listBlogEntriesByYearMonthDay'),
(r'^(?P<requestYear>\d+)/(?P<requestMonth>\d+)/$', 'views.listArticlesByYearMonth'),
(r'^(?P<requestYear>\d+)/$', 'views.listArticlesByYear'),
(r'^(?P<slug>[^\.]+)/$', 'views.showArticle'),
(r'^$', 'views.listArticles'),
)
// ... rest of the code ...
|
5a2f848badcdf9bf968e23cfb55f53eb023d18a4
|
tests/helper.py
|
tests/helper.py
|
import unittest
import os
import yaml
from functools import wraps
from cmd import init_db, seed_db
from models import db
from scuevals_api import create_app
class TestCase(unittest.TestCase):
def setUp(self):
app = create_app()
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['TEST_DATABASE_URL']
app.testing = True
self.appx = app
self.app = app.test_client()
with app.app_context():
init_db(app, db)
seed_db(db)
def tearDown(self):
with self.appx.app_context():
db.session.remove()
db.drop_all()
def use_data(file):
def use_data_decorator(f):
@wraps(f)
def wrapper(*args):
with open(os.path.join('fixtures/data', file), 'r') as stream:
data = yaml.load(stream)
args = args + (data, )
return f(*args)
return wrapper
return use_data_decorator
|
import unittest
import os
import yaml
from functools import wraps
from flask_jwt_simple import create_jwt
from cmd import init_db, seed_db
from models import db, Student
from scuevals_api import create_app
class TestCase(unittest.TestCase):
def setUp(self):
app = create_app()
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['TEST_DATABASE_URL']
app.testing = True
self.appx = app
self.app = app.test_client()
student = Student(
id=0,
email='[email protected]',
first_name='John',
last_name='Doe',
university_id=1
)
ident = {
'id': student.id,
'email': student.email,
'first_name': student.first_name,
'last_name': student.last_name
}
with app.app_context():
db.drop_all()
init_db(app, db)
seed_db(db)
db.session.add(student)
db.session.commit()
self.jwt = create_jwt(identity=ident)
def tearDown(self):
with self.appx.app_context():
db.session.remove()
db.drop_all()
def use_data(file):
def use_data_decorator(f):
@wraps(f)
def wrapper(*args):
with open(os.path.join('fixtures/data', file), 'r') as stream:
data = yaml.load(stream)
args = args + (data, )
return f(*args)
return wrapper
return use_data_decorator
|
Add authentication to base TestCase
|
Add authentication to base TestCase
|
Python
|
agpl-3.0
|
SCUEvals/scuevals-api,SCUEvals/scuevals-api
|
python
|
## Code Before:
import unittest
import os
import yaml
from functools import wraps
from cmd import init_db, seed_db
from models import db
from scuevals_api import create_app
class TestCase(unittest.TestCase):
def setUp(self):
app = create_app()
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['TEST_DATABASE_URL']
app.testing = True
self.appx = app
self.app = app.test_client()
with app.app_context():
init_db(app, db)
seed_db(db)
def tearDown(self):
with self.appx.app_context():
db.session.remove()
db.drop_all()
def use_data(file):
def use_data_decorator(f):
@wraps(f)
def wrapper(*args):
with open(os.path.join('fixtures/data', file), 'r') as stream:
data = yaml.load(stream)
args = args + (data, )
return f(*args)
return wrapper
return use_data_decorator
## Instruction:
Add authentication to base TestCase
## Code After:
import unittest
import os
import yaml
from functools import wraps
from flask_jwt_simple import create_jwt
from cmd import init_db, seed_db
from models import db, Student
from scuevals_api import create_app
class TestCase(unittest.TestCase):
def setUp(self):
app = create_app()
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['TEST_DATABASE_URL']
app.testing = True
self.appx = app
self.app = app.test_client()
student = Student(
id=0,
email='[email protected]',
first_name='John',
last_name='Doe',
university_id=1
)
ident = {
'id': student.id,
'email': student.email,
'first_name': student.first_name,
'last_name': student.last_name
}
with app.app_context():
db.drop_all()
init_db(app, db)
seed_db(db)
db.session.add(student)
db.session.commit()
self.jwt = create_jwt(identity=ident)
def tearDown(self):
with self.appx.app_context():
db.session.remove()
db.drop_all()
def use_data(file):
def use_data_decorator(f):
@wraps(f)
def wrapper(*args):
with open(os.path.join('fixtures/data', file), 'r') as stream:
data = yaml.load(stream)
args = args + (data, )
return f(*args)
return wrapper
return use_data_decorator
|
# ... existing code ...
import os
import yaml
from functools import wraps
from flask_jwt_simple import create_jwt
from cmd import init_db, seed_db
from models import db, Student
from scuevals_api import create_app
# ... modified code ...
self.appx = app
self.app = app.test_client()
student = Student(
id=0,
email='[email protected]',
first_name='John',
last_name='Doe',
university_id=1
)
ident = {
'id': student.id,
'email': student.email,
'first_name': student.first_name,
'last_name': student.last_name
}
with app.app_context():
db.drop_all()
init_db(app, db)
seed_db(db)
db.session.add(student)
db.session.commit()
self.jwt = create_jwt(identity=ident)
def tearDown(self):
with self.appx.app_context():
# ... rest of the code ...
|
7e6dc283dbecf4bf9674559198b4a2c06e9f4c2e
|
spacy/tests/regression/test_issue1799.py
|
spacy/tests/regression/test_issue1799.py
|
'''Test sentence boundaries are deserialized correctly,
even for non-projective sentences.'''
import pytest
import numpy
from ... tokens import Doc
from ... vocab import Vocab
from ... attrs import HEAD, DEP
def test_issue1799():
problem_sentence = 'Just what I was looking for.'
heads_deps = numpy.asarray([[1, 397], [4, 436], [2, 426], [1, 402],
[0, 8206900633647566924], [18446744073709551615, 440],
[18446744073709551614, 442]], dtype='uint64')
doc = Doc(Vocab(), words='Just what I was looking for .'.split())
doc.vocab.strings.add('ROOT')
doc = doc.from_array([HEAD, DEP], heads_deps)
assert len(list(doc.sents)) == 1
|
'''Test sentence boundaries are deserialized correctly,
even for non-projective sentences.'''
from __future__ import unicode_literals
import pytest
import numpy
from ... tokens import Doc
from ... vocab import Vocab
from ... attrs import HEAD, DEP
def test_issue1799():
problem_sentence = 'Just what I was looking for.'
heads_deps = numpy.asarray([[1, 397], [4, 436], [2, 426], [1, 402],
[0, 8206900633647566924], [18446744073709551615, 440],
[18446744073709551614, 442]], dtype='uint64')
doc = Doc(Vocab(), words='Just what I was looking for .'.split())
doc.vocab.strings.add('ROOT')
doc = doc.from_array([HEAD, DEP], heads_deps)
assert len(list(doc.sents)) == 1
|
Fix unicode import in test
|
Fix unicode import in test
|
Python
|
mit
|
aikramer2/spaCy,aikramer2/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,honnibal/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,aikramer2/spaCy,aikramer2/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy,recognai/spaCy,recognai/spaCy,explosion/spaCy,recognai/spaCy,honnibal/spaCy,spacy-io/spaCy
|
python
|
## Code Before:
'''Test sentence boundaries are deserialized correctly,
even for non-projective sentences.'''
import pytest
import numpy
from ... tokens import Doc
from ... vocab import Vocab
from ... attrs import HEAD, DEP
def test_issue1799():
problem_sentence = 'Just what I was looking for.'
heads_deps = numpy.asarray([[1, 397], [4, 436], [2, 426], [1, 402],
[0, 8206900633647566924], [18446744073709551615, 440],
[18446744073709551614, 442]], dtype='uint64')
doc = Doc(Vocab(), words='Just what I was looking for .'.split())
doc.vocab.strings.add('ROOT')
doc = doc.from_array([HEAD, DEP], heads_deps)
assert len(list(doc.sents)) == 1
## Instruction:
Fix unicode import in test
## Code After:
'''Test sentence boundaries are deserialized correctly,
even for non-projective sentences.'''
from __future__ import unicode_literals
import pytest
import numpy
from ... tokens import Doc
from ... vocab import Vocab
from ... attrs import HEAD, DEP
def test_issue1799():
problem_sentence = 'Just what I was looking for.'
heads_deps = numpy.asarray([[1, 397], [4, 436], [2, 426], [1, 402],
[0, 8206900633647566924], [18446744073709551615, 440],
[18446744073709551614, 442]], dtype='uint64')
doc = Doc(Vocab(), words='Just what I was looking for .'.split())
doc.vocab.strings.add('ROOT')
doc = doc.from_array([HEAD, DEP], heads_deps)
assert len(list(doc.sents)) == 1
|
# ... existing code ...
'''Test sentence boundaries are deserialized correctly,
even for non-projective sentences.'''
from __future__ import unicode_literals
import pytest
import numpy
# ... rest of the code ...
|
887ad6280df9c6e88a036783097f87626436ca9f
|
Lib/importlib/test/import_/util.py
|
Lib/importlib/test/import_/util.py
|
import functools
import importlib
import importlib._bootstrap
import unittest
using___import__ = False
def import_(*args, **kwargs):
"""Delegate to allow for injecting different implementations of import."""
if using___import__:
return __import__(*args, **kwargs)
else:
return importlib.__import__(*args, **kwargs)
importlib_only = unittest.skipIf(using___import__, "importlib-specific test")
def mock_path_hook(*entries, importer):
"""A mock sys.path_hooks entry."""
def hook(entry):
if entry not in entries:
raise ImportError
return importer
return hook
|
import functools
import importlib
import importlib._bootstrap
import unittest
using___import__ = False
def import_(*args, **kwargs):
"""Delegate to allow for injecting different implementations of import."""
if using___import__:
return __import__(*args, **kwargs)
else:
return importlib.__import__(*args, **kwargs)
def importlib_only(fxn):
"""Decorator to skip a test if using __builtins__.__import__."""
return unittest.skipIf(using___import__, "importlib-specific test")(fxn)
def mock_path_hook(*entries, importer):
"""A mock sys.path_hooks entry."""
def hook(entry):
if entry not in entries:
raise ImportError
return importer
return hook
|
Fix the importlib_only test decorator to work again; don't capture the flag variable as it might change later.
|
Fix the importlib_only test decorator to work again; don't capture the flag variable as it might change later.
|
Python
|
mit
|
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
|
python
|
## Code Before:
import functools
import importlib
import importlib._bootstrap
import unittest
using___import__ = False
def import_(*args, **kwargs):
"""Delegate to allow for injecting different implementations of import."""
if using___import__:
return __import__(*args, **kwargs)
else:
return importlib.__import__(*args, **kwargs)
importlib_only = unittest.skipIf(using___import__, "importlib-specific test")
def mock_path_hook(*entries, importer):
"""A mock sys.path_hooks entry."""
def hook(entry):
if entry not in entries:
raise ImportError
return importer
return hook
## Instruction:
Fix the importlib_only test decorator to work again; don't capture the flag variable as it might change later.
## Code After:
import functools
import importlib
import importlib._bootstrap
import unittest
using___import__ = False
def import_(*args, **kwargs):
"""Delegate to allow for injecting different implementations of import."""
if using___import__:
return __import__(*args, **kwargs)
else:
return importlib.__import__(*args, **kwargs)
def importlib_only(fxn):
"""Decorator to skip a test if using __builtins__.__import__."""
return unittest.skipIf(using___import__, "importlib-specific test")(fxn)
def mock_path_hook(*entries, importer):
"""A mock sys.path_hooks entry."""
def hook(entry):
if entry not in entries:
raise ImportError
return importer
return hook
|
// ... existing code ...
return importlib.__import__(*args, **kwargs)
def importlib_only(fxn):
"""Decorator to skip a test if using __builtins__.__import__."""
return unittest.skipIf(using___import__, "importlib-specific test")(fxn)
def mock_path_hook(*entries, importer):
// ... rest of the code ...
|
12dea43b35daf92a6087f3a980aff767ac0b7043
|
base/win/comptr.h
|
base/win/comptr.h
|
// LAF Base Library
// Copyright (c) 2017 David Capello
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#ifndef BASE_WIN_COMPTR_H_INCLUDED
#define BASE_WIN_COMPTR_H_INCLUDED
#pragma once
#if !defined(_WIN32)
#error This header file can be used only on Windows platform
#endif
#include "base/disable_copying.h"
namespace base {
template<class T>
class ComPtr {
public:
ComPtr() : m_ptr(nullptr) { }
~ComPtr() { reset(); }
T** operator&() { return &m_ptr; }
T* operator->() { return m_ptr; }
T* get() {
return m_ptr;
}
void reset() {
if (m_ptr) {
m_ptr->Release();
m_ptr = nullptr;
}
}
private:
T* m_ptr;
DISABLE_COPYING(ComPtr);
};
} // namespace base
#endif
|
// LAF Base Library
// Copyright (c) 2021 Igara Studio S.A.
// Copyright (c) 2017 David Capello
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#ifndef BASE_WIN_COMPTR_H_INCLUDED
#define BASE_WIN_COMPTR_H_INCLUDED
#pragma once
#if !defined(_WIN32)
#error This header file can be used only on Windows platform
#endif
#include <algorithm>
namespace base {
template<class T>
class ComPtr {
public:
ComPtr() : m_ptr(nullptr) {
}
ComPtr<T>(const ComPtr<T>& p) : m_ptr(p.m_ptr) {
if (m_ptr)
m_ptr->AddRef();
}
ComPtr(ComPtr&& tmp) {
std::swap(m_ptr, tmp.m_ptr);
}
~ComPtr() {
reset();
}
T** operator&() { return &m_ptr; }
T* operator->() { return m_ptr; }
operator bool() const { return m_ptr != nullptr; }
// Add new reference using operator=()
ComPtr<T>& operator=(const ComPtr<T>& p) {
if (m_ptr)
m_ptr->Release();
m_ptr = p.m_ptr;
if (m_ptr)
m_ptr->AddRef();
return *this;
}
ComPtr& operator=(std::nullptr_t) {
reset();
return *this;
}
T* get() {
return m_ptr;
}
void reset() {
if (m_ptr) {
m_ptr->Release();
m_ptr = nullptr;
}
}
private:
T* m_ptr;
};
} // namespace base
#endif
|
Add some extra operators to base::ComPtr
|
[win] Add some extra operators to base::ComPtr
|
C
|
mit
|
aseprite/laf,aseprite/laf
|
c
|
## Code Before:
// LAF Base Library
// Copyright (c) 2017 David Capello
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#ifndef BASE_WIN_COMPTR_H_INCLUDED
#define BASE_WIN_COMPTR_H_INCLUDED
#pragma once
#if !defined(_WIN32)
#error This header file can be used only on Windows platform
#endif
#include "base/disable_copying.h"
namespace base {
template<class T>
class ComPtr {
public:
ComPtr() : m_ptr(nullptr) { }
~ComPtr() { reset(); }
T** operator&() { return &m_ptr; }
T* operator->() { return m_ptr; }
T* get() {
return m_ptr;
}
void reset() {
if (m_ptr) {
m_ptr->Release();
m_ptr = nullptr;
}
}
private:
T* m_ptr;
DISABLE_COPYING(ComPtr);
};
} // namespace base
#endif
## Instruction:
[win] Add some extra operators to base::ComPtr
## Code After:
// LAF Base Library
// Copyright (c) 2021 Igara Studio S.A.
// Copyright (c) 2017 David Capello
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#ifndef BASE_WIN_COMPTR_H_INCLUDED
#define BASE_WIN_COMPTR_H_INCLUDED
#pragma once
#if !defined(_WIN32)
#error This header file can be used only on Windows platform
#endif
#include <algorithm>
namespace base {
template<class T>
class ComPtr {
public:
ComPtr() : m_ptr(nullptr) {
}
ComPtr<T>(const ComPtr<T>& p) : m_ptr(p.m_ptr) {
if (m_ptr)
m_ptr->AddRef();
}
ComPtr(ComPtr&& tmp) {
std::swap(m_ptr, tmp.m_ptr);
}
~ComPtr() {
reset();
}
T** operator&() { return &m_ptr; }
T* operator->() { return m_ptr; }
operator bool() const { return m_ptr != nullptr; }
// Add new reference using operator=()
ComPtr<T>& operator=(const ComPtr<T>& p) {
if (m_ptr)
m_ptr->Release();
m_ptr = p.m_ptr;
if (m_ptr)
m_ptr->AddRef();
return *this;
}
ComPtr& operator=(std::nullptr_t) {
reset();
return *this;
}
T* get() {
return m_ptr;
}
void reset() {
if (m_ptr) {
m_ptr->Release();
m_ptr = nullptr;
}
}
private:
T* m_ptr;
};
} // namespace base
#endif
|
# ... existing code ...
// LAF Base Library
// Copyright (c) 2021 Igara Studio S.A.
// Copyright (c) 2017 David Capello
//
// This file is released under the terms of the MIT license.
# ... modified code ...
#error This header file can be used only on Windows platform
#endif
#include <algorithm>
namespace base {
...
template<class T>
class ComPtr {
public:
ComPtr() : m_ptr(nullptr) {
}
ComPtr<T>(const ComPtr<T>& p) : m_ptr(p.m_ptr) {
if (m_ptr)
m_ptr->AddRef();
}
ComPtr(ComPtr&& tmp) {
std::swap(m_ptr, tmp.m_ptr);
}
~ComPtr() {
reset();
}
T** operator&() { return &m_ptr; }
T* operator->() { return m_ptr; }
operator bool() const { return m_ptr != nullptr; }
// Add new reference using operator=()
ComPtr<T>& operator=(const ComPtr<T>& p) {
if (m_ptr)
m_ptr->Release();
m_ptr = p.m_ptr;
if (m_ptr)
m_ptr->AddRef();
return *this;
}
ComPtr& operator=(std::nullptr_t) {
reset();
return *this;
}
T* get() {
return m_ptr;
...
private:
T* m_ptr;
};
} // namespace base
# ... rest of the code ...
|
c49b797d61e07f5986536a006a850569bb67a9d8
|
ResultsWizard2/src/mathsquared/resultswizard2/AdminGuiFrame.java
|
ResultsWizard2/src/mathsquared/resultswizard2/AdminGuiFrame.java
|
package mathsquared.resultswizard2;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
/**
* Runs the GUI by which an event administrator can input results.
*
* @author MathSquared
*
*/
public class AdminGuiFrame extends JFrame {
private JPanel contentPane;
/**
* Create the frame.
*/
public AdminGuiFrame () {
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
}
|
package mathsquared.resultswizard2;
import java.awt.BorderLayout;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
/**
* Runs the GUI by which an event administrator can input results.
*
* @author MathSquared
*
*/
public class AdminGuiFrame extends JFrame {
private ObjectInputStream ois;
private ObjectOutputStream oos;
private JPanel contentPane;
/**
* Create the frame.
*/
public AdminGuiFrame (ObjectInputStream ois, ObjectOutputStream oos) {
// Initialize comms
this.oos = oos;
this.ois = ois;
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
}
|
Add OIS/OOS to constructor and add fields
|
AGF: Add OIS/OOS to constructor and add fields
|
Java
|
mit
|
MathSquared/ResultsWizard2
|
java
|
## Code Before:
package mathsquared.resultswizard2;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
/**
* Runs the GUI by which an event administrator can input results.
*
* @author MathSquared
*
*/
public class AdminGuiFrame extends JFrame {
private JPanel contentPane;
/**
* Create the frame.
*/
public AdminGuiFrame () {
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
}
## Instruction:
AGF: Add OIS/OOS to constructor and add fields
## Code After:
package mathsquared.resultswizard2;
import java.awt.BorderLayout;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
/**
* Runs the GUI by which an event administrator can input results.
*
* @author MathSquared
*
*/
public class AdminGuiFrame extends JFrame {
private ObjectInputStream ois;
private ObjectOutputStream oos;
private JPanel contentPane;
/**
* Create the frame.
*/
public AdminGuiFrame (ObjectInputStream ois, ObjectOutputStream oos) {
// Initialize comms
this.oos = oos;
this.ois = ois;
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
}
|
# ... existing code ...
package mathsquared.resultswizard2;
import java.awt.BorderLayout;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.swing.JFrame;
import javax.swing.JPanel;
# ... modified code ...
*/
public class AdminGuiFrame extends JFrame {
private ObjectInputStream ois;
private ObjectOutputStream oos;
private JPanel contentPane;
/**
* Create the frame.
*/
public AdminGuiFrame (ObjectInputStream ois, ObjectOutputStream oos) {
// Initialize comms
this.oos = oos;
this.ois = ois;
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
# ... rest of the code ...
|
0b7a1904ef5511916fc4978c325862241a46aef3
|
lib/pyfrc/mains/cli_profiler.py
|
lib/pyfrc/mains/cli_profiler.py
|
import argparse
import inspect
import subprocess
import sys
class PyFrcProfiler:
"""
Wraps other commands by running them via the built in cProfile module.
Use this to profile your program and figure out where you're spending
a lot of time (note that cProfile only profiles the main thread)
"""
def __init__(self, parser):
parser.add_argument('args', nargs=argparse.REMAINDER,
help='Arguments to pass to robot.py')
def run(self, options, robot_class, **static_options):
from .. import config
config.mode = 'profiler'
try:
import cProfile
except ImportError:
print("Error importing cProfile module for profiling, your python interpreter may not support profiling\n", file=sys.stderr)
return 1
if len(options.args) == 0:
print("ERROR: Profiler command requires arguments to run other commands")
return 1
file_location = inspect.getfile(robot_class)
# construct the arguments to run the profiler
args = [sys.executable, '-m', 'cProfile', '-s', 'tottime', file_location] + options.args
return subprocess.call(args)
|
import argparse
import inspect
from os.path import abspath
import subprocess
import sys
class PyFrcProfiler:
"""
Wraps other commands by running them via the built in cProfile module.
Use this to profile your program and figure out where you're spending
a lot of time (note that cProfile only profiles the main thread)
"""
def __init__(self, parser):
parser.add_argument('-o', '--outfile', default=None,
help="Save stats to <outfile>")
parser.add_argument('args', nargs=argparse.REMAINDER,
help='Arguments to pass to robot.py')
def run(self, options, robot_class, **static_options):
from .. import config
config.mode = 'profiler'
try:
import cProfile
except ImportError:
print("Error importing cProfile module for profiling, your python interpreter may not support profiling\n", file=sys.stderr)
return 1
if len(options.args) == 0:
print("ERROR: Profiler command requires arguments to run other commands")
return 1
file_location = abspath(inspect.getfile(robot_class))
if options.outfile:
profile_args = ['-o', options.outfile]
else:
profile_args = ['-s', 'tottime']
# construct the arguments to run the profiler
args = [sys.executable, '-m', 'cProfile'] + profile_args + [file_location] + options.args
return subprocess.call(args)
|
Add output option for profiler
|
Add output option for profiler
|
Python
|
mit
|
robotpy/pyfrc
|
python
|
## Code Before:
import argparse
import inspect
import subprocess
import sys
class PyFrcProfiler:
"""
Wraps other commands by running them via the built in cProfile module.
Use this to profile your program and figure out where you're spending
a lot of time (note that cProfile only profiles the main thread)
"""
def __init__(self, parser):
parser.add_argument('args', nargs=argparse.REMAINDER,
help='Arguments to pass to robot.py')
def run(self, options, robot_class, **static_options):
from .. import config
config.mode = 'profiler'
try:
import cProfile
except ImportError:
print("Error importing cProfile module for profiling, your python interpreter may not support profiling\n", file=sys.stderr)
return 1
if len(options.args) == 0:
print("ERROR: Profiler command requires arguments to run other commands")
return 1
file_location = inspect.getfile(robot_class)
# construct the arguments to run the profiler
args = [sys.executable, '-m', 'cProfile', '-s', 'tottime', file_location] + options.args
return subprocess.call(args)
## Instruction:
Add output option for profiler
## Code After:
import argparse
import inspect
from os.path import abspath
import subprocess
import sys
class PyFrcProfiler:
"""
Wraps other commands by running them via the built in cProfile module.
Use this to profile your program and figure out where you're spending
a lot of time (note that cProfile only profiles the main thread)
"""
def __init__(self, parser):
parser.add_argument('-o', '--outfile', default=None,
help="Save stats to <outfile>")
parser.add_argument('args', nargs=argparse.REMAINDER,
help='Arguments to pass to robot.py')
def run(self, options, robot_class, **static_options):
from .. import config
config.mode = 'profiler'
try:
import cProfile
except ImportError:
print("Error importing cProfile module for profiling, your python interpreter may not support profiling\n", file=sys.stderr)
return 1
if len(options.args) == 0:
print("ERROR: Profiler command requires arguments to run other commands")
return 1
file_location = abspath(inspect.getfile(robot_class))
if options.outfile:
profile_args = ['-o', options.outfile]
else:
profile_args = ['-s', 'tottime']
# construct the arguments to run the profiler
args = [sys.executable, '-m', 'cProfile'] + profile_args + [file_location] + options.args
return subprocess.call(args)
|
// ... existing code ...
import argparse
import inspect
from os.path import abspath
import subprocess
import sys
// ... modified code ...
"""
def __init__(self, parser):
parser.add_argument('-o', '--outfile', default=None,
help="Save stats to <outfile>")
parser.add_argument('args', nargs=argparse.REMAINDER,
help='Arguments to pass to robot.py')
...
print("ERROR: Profiler command requires arguments to run other commands")
return 1
file_location = abspath(inspect.getfile(robot_class))
if options.outfile:
profile_args = ['-o', options.outfile]
else:
profile_args = ['-s', 'tottime']
# construct the arguments to run the profiler
args = [sys.executable, '-m', 'cProfile'] + profile_args + [file_location] + options.args
return subprocess.call(args)
// ... rest of the code ...
|
9cb8ff5ec62d943c193a32c842c3db92bd24d85d
|
bot.py
|
bot.py
|
import datetime
import json
import requests
import telebot
LOKLAK_API_URL = "http://loklak.org/api/search.json?q={query}"
bot = telebot.TeleBot("162563966:AAHRx_KauVWfNrS9ADn099kjxqGNB_jqzgo")
def get_tweet_rating(tweet):
"""
Function that count tweet rating based on favourites and retweets
"""
return (tweet['retweet_count'] * 2) + tweet['favourites_count']
@bot.message_handler(func=lambda m: True)
def search(message):
result = requests.get(LOKLAK_API_URL.format(query=message.text))
tweets = json.loads(result.text)['statuses']
# Find the best tweet for this search query,
# by using sorting
tweets.sort(key=get_tweet_rating, reverse=True)
tweet = '"{message}" - {author} \n\n{link}'.format(
message=tweets[0]['text'],
author=tweets[0]['screen_name'],
link=tweets[0]['link']
)
bot.reply_to(message, tweet)
bot.polling()
# Do not stop main thread
while True:
pass
|
import datetime
import json
import requests
import telebot
LOKLAK_API_URL = "http://loklak.org/api/search.json?q={query}"
bot = telebot.TeleBot("162563966:AAHRx_KauVWfNrS9ADn099kjxqGNB_jqzgo")
def get_tweet_rating(tweet):
"""
Function that count tweet rating based on favourites and retweets
"""
return (tweet['retweet_count'] * 2) + tweet['favourites_count']
@bot.message_handler()
def description(message):
pass
@bot.message_handler(func=lambda m: True)
def search(message):
result = requests.get(LOKLAK_API_URL.format(query=message.text))
tweets = json.loads(result.text)['statuses']
if tweets:
# Find the best tweet for this search query,
# by using sorting
tweets.sort(key=get_tweet_rating, reverse=True)
tweet = '"{message}" - {author} \n\n{link}'.format(
message=tweets[0]['text'],
author=tweets[0]['screen_name'],
link=tweets[0]['link']
)
bot.reply_to(message, tweet)
else:
bot.reply_to(message, 'Not found')
@bot.message_handler()
def description(message):
pass')
bot.polling()
# Do not stop main thread
while True:
pass
|
Fix IndexError while processing tweets
|
Fix IndexError while processing tweets
|
Python
|
mit
|
sevazhidkov/tweets-search-bot
|
python
|
## Code Before:
import datetime
import json
import requests
import telebot
LOKLAK_API_URL = "http://loklak.org/api/search.json?q={query}"
bot = telebot.TeleBot("162563966:AAHRx_KauVWfNrS9ADn099kjxqGNB_jqzgo")
def get_tweet_rating(tweet):
"""
Function that count tweet rating based on favourites and retweets
"""
return (tweet['retweet_count'] * 2) + tweet['favourites_count']
@bot.message_handler(func=lambda m: True)
def search(message):
result = requests.get(LOKLAK_API_URL.format(query=message.text))
tweets = json.loads(result.text)['statuses']
# Find the best tweet for this search query,
# by using sorting
tweets.sort(key=get_tweet_rating, reverse=True)
tweet = '"{message}" - {author} \n\n{link}'.format(
message=tweets[0]['text'],
author=tweets[0]['screen_name'],
link=tweets[0]['link']
)
bot.reply_to(message, tweet)
bot.polling()
# Do not stop main thread
while True:
pass
## Instruction:
Fix IndexError while processing tweets
## Code After:
import datetime
import json
import requests
import telebot
LOKLAK_API_URL = "http://loklak.org/api/search.json?q={query}"
bot = telebot.TeleBot("162563966:AAHRx_KauVWfNrS9ADn099kjxqGNB_jqzgo")
def get_tweet_rating(tweet):
"""
Function that count tweet rating based on favourites and retweets
"""
return (tweet['retweet_count'] * 2) + tweet['favourites_count']
@bot.message_handler()
def description(message):
pass
@bot.message_handler(func=lambda m: True)
def search(message):
result = requests.get(LOKLAK_API_URL.format(query=message.text))
tweets = json.loads(result.text)['statuses']
if tweets:
# Find the best tweet for this search query,
# by using sorting
tweets.sort(key=get_tweet_rating, reverse=True)
tweet = '"{message}" - {author} \n\n{link}'.format(
message=tweets[0]['text'],
author=tweets[0]['screen_name'],
link=tweets[0]['link']
)
bot.reply_to(message, tweet)
else:
bot.reply_to(message, 'Not found')
@bot.message_handler()
def description(message):
pass')
bot.polling()
# Do not stop main thread
while True:
pass
|
// ... existing code ...
return (tweet['retweet_count'] * 2) + tweet['favourites_count']
@bot.message_handler()
def description(message):
pass
@bot.message_handler(func=lambda m: True)
def search(message):
result = requests.get(LOKLAK_API_URL.format(query=message.text))
tweets = json.loads(result.text)['statuses']
if tweets:
# Find the best tweet for this search query,
# by using sorting
tweets.sort(key=get_tweet_rating, reverse=True)
tweet = '"{message}" - {author} \n\n{link}'.format(
message=tweets[0]['text'],
author=tweets[0]['screen_name'],
link=tweets[0]['link']
)
bot.reply_to(message, tweet)
else:
bot.reply_to(message, 'Not found')
@bot.message_handler()
def description(message):
pass')
bot.polling()
// ... rest of the code ...
|
0cff7d25a9d0fc76c723e058652551bb2c43d1fc
|
benchmarks/test_benchmark.py
|
benchmarks/test_benchmark.py
|
import re
import urllib
import random
import unittest
from funkload.FunkLoadTestCase import FunkLoadTestCase
class Benchmark(FunkLoadTestCase):
"""This test uses a configuration file Benchmark.conf."""
def setUp(self):
self.server_url = self.conf_get('main', 'url')
def test_simple(self):
server_url = self.server_url
if not re.match('https?://', server_url):
raise Exception("The `server_url` setting doesn't have a scheme.")
username = self.conf_get('test_benchmark', 'username', None)
password = self.conf_get('test_benchmark', 'password', None)
if username and password:
self.post(self.server_url + "/api/user/login",
params=[['username', username],
['password', password]],
description="Login as %s" % username)
nb_times = self.conf_getInt('test_benchmark', 'nb_times')
names = self.conf_get('test_benchmark', 'page_names').split(';')
for i in range(nb_times):
r = random.randint(0, len(names) - 1)
url = server_url + '/api/read/' + urllib.quote(names[r])
self.get(url, description='Getting %s' % names[r])
if __name__ in ('main', '__main__'):
unittest.main()
|
import re
import urllib.parse
import random
import unittest
from funkload.FunkLoadTestCase import FunkLoadTestCase
class Benchmark(FunkLoadTestCase):
"""This test uses a configuration file Benchmark.conf."""
def setUp(self):
self.server_url = self.conf_get('main', 'url')
def test_simple(self):
server_url = self.server_url
if not re.match('https?://', server_url):
raise Exception("The `server_url` setting doesn't have a scheme.")
username = self.conf_get('test_benchmark', 'username', None)
password = self.conf_get('test_benchmark', 'password', None)
if username and password:
self.post(self.server_url + "/api/user/login",
params=[['username', username],
['password', password]],
description="Login as %s" % username)
nb_times = self.conf_getInt('test_benchmark', 'nb_times')
names = self.conf_get('test_benchmark', 'page_names').split(';')
for i in range(nb_times):
r = random.randint(0, len(names) - 1)
url = server_url + '/api/read/' + urllib.parse.quote(names[r])
self.get(url, description='Getting %s' % names[r])
if __name__ in ('main', '__main__'):
unittest.main()
|
Update benchmarks to Pyton 3.
|
Update benchmarks to Pyton 3.
|
Python
|
apache-2.0
|
ludovicchabant/Wikked,ludovicchabant/Wikked,ludovicchabant/Wikked
|
python
|
## Code Before:
import re
import urllib
import random
import unittest
from funkload.FunkLoadTestCase import FunkLoadTestCase
class Benchmark(FunkLoadTestCase):
"""This test uses a configuration file Benchmark.conf."""
def setUp(self):
self.server_url = self.conf_get('main', 'url')
def test_simple(self):
server_url = self.server_url
if not re.match('https?://', server_url):
raise Exception("The `server_url` setting doesn't have a scheme.")
username = self.conf_get('test_benchmark', 'username', None)
password = self.conf_get('test_benchmark', 'password', None)
if username and password:
self.post(self.server_url + "/api/user/login",
params=[['username', username],
['password', password]],
description="Login as %s" % username)
nb_times = self.conf_getInt('test_benchmark', 'nb_times')
names = self.conf_get('test_benchmark', 'page_names').split(';')
for i in range(nb_times):
r = random.randint(0, len(names) - 1)
url = server_url + '/api/read/' + urllib.quote(names[r])
self.get(url, description='Getting %s' % names[r])
if __name__ in ('main', '__main__'):
unittest.main()
## Instruction:
Update benchmarks to Pyton 3.
## Code After:
import re
import urllib.parse
import random
import unittest
from funkload.FunkLoadTestCase import FunkLoadTestCase
class Benchmark(FunkLoadTestCase):
"""This test uses a configuration file Benchmark.conf."""
def setUp(self):
self.server_url = self.conf_get('main', 'url')
def test_simple(self):
server_url = self.server_url
if not re.match('https?://', server_url):
raise Exception("The `server_url` setting doesn't have a scheme.")
username = self.conf_get('test_benchmark', 'username', None)
password = self.conf_get('test_benchmark', 'password', None)
if username and password:
self.post(self.server_url + "/api/user/login",
params=[['username', username],
['password', password]],
description="Login as %s" % username)
nb_times = self.conf_getInt('test_benchmark', 'nb_times')
names = self.conf_get('test_benchmark', 'page_names').split(';')
for i in range(nb_times):
r = random.randint(0, len(names) - 1)
url = server_url + '/api/read/' + urllib.parse.quote(names[r])
self.get(url, description='Getting %s' % names[r])
if __name__ in ('main', '__main__'):
unittest.main()
|
...
import re
import urllib.parse
import random
import unittest
from funkload.FunkLoadTestCase import FunkLoadTestCase
...
names = self.conf_get('test_benchmark', 'page_names').split(';')
for i in range(nb_times):
r = random.randint(0, len(names) - 1)
url = server_url + '/api/read/' + urllib.parse.quote(names[r])
self.get(url, description='Getting %s' % names[r])
...
|
299fadcde71558bc1e77ba396cc544619373c2b1
|
conditional/blueprints/spring_evals.py
|
conditional/blueprints/spring_evals.py
|
from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
{
'name': "Liam Middlebrook",
'committee_meetings': 24,
'house_meetings_missed': [{'date': "aprial fools fayas ads", 'reason': "I was playing videogames"}],
'major_project': 'open_container',
'major_project_passed': True,
'comments': "please don't fail me",
'result': 'Pending'
},
{
'name': "Julien Eid",
'committee_meetings': 69,
'house_meetings_missed': [],
'major_project': 'wii-u shit',
'major_project_passed': True,
'comments': "imdabes",
'result': 'Passed'
}
]
# return names in 'first last (username)' format
return render_template('spring_evals.html',
username = user_name,
members = members)
|
from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
{
'name': "Liam Middlebrook",
'committee_meetings': 24,
'house_meetings_missed': [{'date': "aprial fools fayas ads", 'reason': "I was playing videogames"}],
'major_project': 'open_container',
'major_project_passed': True,
'social_events': "",
'comments': "please don't fail me",
'result': 'Pending'
},
{
'name': "Julien Eid",
'committee_meetings': 69,
'house_meetings_missed': [],
'major_project': 'wii-u shit',
'major_project_passed': True,
'social_events': "Manipulation and Opportunism",
'comments': "imdabes",
'result': 'Passed'
}
]
# return names in 'first last (username)' format
return render_template('spring_evals.html',
username = user_name,
members = members)
|
Add social events to spring evals 😿
|
Add social events to spring evals 😿
|
Python
|
mit
|
RamZallan/conditional,ComputerScienceHouse/conditional,RamZallan/conditional,ComputerScienceHouse/conditional,RamZallan/conditional,ComputerScienceHouse/conditional
|
python
|
## Code Before:
from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
{
'name': "Liam Middlebrook",
'committee_meetings': 24,
'house_meetings_missed': [{'date': "aprial fools fayas ads", 'reason': "I was playing videogames"}],
'major_project': 'open_container',
'major_project_passed': True,
'comments': "please don't fail me",
'result': 'Pending'
},
{
'name': "Julien Eid",
'committee_meetings': 69,
'house_meetings_missed': [],
'major_project': 'wii-u shit',
'major_project_passed': True,
'comments': "imdabes",
'result': 'Passed'
}
]
# return names in 'first last (username)' format
return render_template('spring_evals.html',
username = user_name,
members = members)
## Instruction:
Add social events to spring evals 😿
## Code After:
from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
{
'name': "Liam Middlebrook",
'committee_meetings': 24,
'house_meetings_missed': [{'date': "aprial fools fayas ads", 'reason': "I was playing videogames"}],
'major_project': 'open_container',
'major_project_passed': True,
'social_events': "",
'comments': "please don't fail me",
'result': 'Pending'
},
{
'name': "Julien Eid",
'committee_meetings': 69,
'house_meetings_missed': [],
'major_project': 'wii-u shit',
'major_project_passed': True,
'social_events': "Manipulation and Opportunism",
'comments': "imdabes",
'result': 'Passed'
}
]
# return names in 'first last (username)' format
return render_template('spring_evals.html',
username = user_name,
members = members)
|
// ... existing code ...
'house_meetings_missed': [{'date': "aprial fools fayas ads", 'reason': "I was playing videogames"}],
'major_project': 'open_container',
'major_project_passed': True,
'social_events': "",
'comments': "please don't fail me",
'result': 'Pending'
},
// ... modified code ...
'house_meetings_missed': [],
'major_project': 'wii-u shit',
'major_project_passed': True,
'social_events': "Manipulation and Opportunism",
'comments': "imdabes",
'result': 'Passed'
}
// ... rest of the code ...
|
36da7bdc8402494b5ef3588289739e1696ad6002
|
docs/_ext/djangodummy/settings.py
|
docs/_ext/djangodummy/settings.py
|
STATIC_URL = '/static/'
|
STATIC_URL = '/static/'
# Avoid error for missing the secret key
SECRET_KEY = 'docs'
|
Fix autodoc support with Django 1.5
|
Fix autodoc support with Django 1.5
|
Python
|
apache-2.0
|
django-fluent/django-fluent-contents,ixc/django-fluent-contents,pombredanne/django-fluent-contents,django-fluent/django-fluent-contents,ixc/django-fluent-contents,pombredanne/django-fluent-contents,jpotterm/django-fluent-contents,edoburu/django-fluent-contents,edoburu/django-fluent-contents,jpotterm/django-fluent-contents,jpotterm/django-fluent-contents,edoburu/django-fluent-contents,django-fluent/django-fluent-contents,ixc/django-fluent-contents,pombredanne/django-fluent-contents
|
python
|
## Code Before:
STATIC_URL = '/static/'
## Instruction:
Fix autodoc support with Django 1.5
## Code After:
STATIC_URL = '/static/'
# Avoid error for missing the secret key
SECRET_KEY = 'docs'
|
// ... existing code ...
STATIC_URL = '/static/'
# Avoid error for missing the secret key
SECRET_KEY = 'docs'
// ... rest of the code ...
|
ad813973421ed828f724a999fabbc12c4e429247
|
src/nodeconductor_paas_oracle/filters.py
|
src/nodeconductor_paas_oracle/filters.py
|
import django_filters
from .models import Deployment
class DeploymentFilter(django_filters.FilterSet):
db_name = django_filters.CharFilter()
state = django_filters.CharFilter()
class Meta(object):
model = Deployment
fields = [
'db_name',
'state',
]
order_by = [
'state',
# desc
'-state',
]
|
import django_filters
from nodeconductor.structure.filters import BaseResourceStateFilter
from .models import Deployment
class DeploymentFilter(BaseResourceStateFilter):
db_name = django_filters.CharFilter()
class Meta(BaseResourceStateFilter.Meta):
model = Deployment
fields = [
'db_name',
'state',
]
order_by = [
'state',
# desc
'-state',
]
|
Use generic state filter instead of custom one
|
Use generic state filter instead of custom one
- ITACLOUD-6837
|
Python
|
mit
|
opennode/nodeconductor-paas-oracle
|
python
|
## Code Before:
import django_filters
from .models import Deployment
class DeploymentFilter(django_filters.FilterSet):
db_name = django_filters.CharFilter()
state = django_filters.CharFilter()
class Meta(object):
model = Deployment
fields = [
'db_name',
'state',
]
order_by = [
'state',
# desc
'-state',
]
## Instruction:
Use generic state filter instead of custom one
- ITACLOUD-6837
## Code After:
import django_filters
from nodeconductor.structure.filters import BaseResourceStateFilter
from .models import Deployment
class DeploymentFilter(BaseResourceStateFilter):
db_name = django_filters.CharFilter()
class Meta(BaseResourceStateFilter.Meta):
model = Deployment
fields = [
'db_name',
'state',
]
order_by = [
'state',
# desc
'-state',
]
|
# ... existing code ...
import django_filters
from nodeconductor.structure.filters import BaseResourceStateFilter
from .models import Deployment
class DeploymentFilter(BaseResourceStateFilter):
db_name = django_filters.CharFilter()
class Meta(BaseResourceStateFilter.Meta):
model = Deployment
fields = [
'db_name',
# ... rest of the code ...
|
5e1e13c695494d5ff63c0f50e4b7641ae23144c3
|
sx_slentry.h
|
sx_slentry.h
|
struct sx_slentry {
STAILQ_ENTRY(sx_slentry) next;
char* text;
};
struct sx_slentry* sx_slentry_new(char* text);
struct sx_tentry {
RB_ENTRY(sx_tentry) entry;
char* text;
};
struct sx_tentry* sx_tentry_new(char* text);
#endif
|
/* OpenBSD-current as of 2015-08-30 does not define STAILQ_ENTRY anymore */
#ifndef STAILQ_ENTRY
#include "sys_queue.h"
#endif
#else
#include "sys_queue.h"
#endif
#if HAVE_SYS_TREE_H
#include <sys/tree.h>
#else
#include "sys_tree.h"
#endif
struct sx_slentry {
STAILQ_ENTRY(sx_slentry) next;
char* text;
};
struct sx_slentry* sx_slentry_new(char* text);
struct sx_tentry {
RB_ENTRY(sx_tentry) entry;
char* text;
};
struct sx_tentry* sx_tentry_new(char* text);
#endif
|
Check if sys/queue.h have STAILQ_ interface. At least OpenBSD's one does not...
|
Check if sys/queue.h have STAILQ_ interface. At least OpenBSD's one does not...
|
C
|
bsd-2-clause
|
ledeuns/bgpq3,kjniemi/bgpq3,ledeuns/bgpq3,ledeuns/bgpq3,kjniemi/bgpq3,kjniemi/bgpq3
|
c
|
## Code Before:
struct sx_slentry {
STAILQ_ENTRY(sx_slentry) next;
char* text;
};
struct sx_slentry* sx_slentry_new(char* text);
struct sx_tentry {
RB_ENTRY(sx_tentry) entry;
char* text;
};
struct sx_tentry* sx_tentry_new(char* text);
#endif
## Instruction:
Check if sys/queue.h have STAILQ_ interface. At least OpenBSD's one does not...
## Code After:
/* OpenBSD-current as of 2015-08-30 does not define STAILQ_ENTRY anymore */
#ifndef STAILQ_ENTRY
#include "sys_queue.h"
#endif
#else
#include "sys_queue.h"
#endif
#if HAVE_SYS_TREE_H
#include <sys/tree.h>
#else
#include "sys_tree.h"
#endif
struct sx_slentry {
STAILQ_ENTRY(sx_slentry) next;
char* text;
};
struct sx_slentry* sx_slentry_new(char* text);
struct sx_tentry {
RB_ENTRY(sx_tentry) entry;
char* text;
};
struct sx_tentry* sx_tentry_new(char* text);
#endif
|
// ... existing code ...
/* OpenBSD-current as of 2015-08-30 does not define STAILQ_ENTRY anymore */
#ifndef STAILQ_ENTRY
#include "sys_queue.h"
#endif
#else
#include "sys_queue.h"
#endif
#if HAVE_SYS_TREE_H
#include <sys/tree.h>
#else
#include "sys_tree.h"
#endif
struct sx_slentry {
STAILQ_ENTRY(sx_slentry) next;
// ... rest of the code ...
|
6093d2954861f2783da3e5b8473cb13b0469685b
|
elasticquery/filterquery.py
|
elasticquery/filterquery.py
|
import json
from .util import make_dsl_object, unroll_definitions, unroll_struct
class MetaFilterQuery(type):
def __init__(cls, name, bases, d):
super(MetaFilterQuery, cls).__init__(name, bases, d)
unroll_definitions(cls._definitions)
def __getattr__(cls, key):
if key not in cls._definitions:
raise cls._exception(key)
return lambda *args, **kwargs: make_dsl_object(
cls, key, cls._definitions[key],
*args, **kwargs
)
class BaseFilterQuery(object):
_type = None
_struct = None
_dsl_type = None
def __init__(self, dsl_type, struct):
self._struct = struct
self._dsl_type = dsl_type
def dict(self):
return {
self._dsl_type: unroll_struct(self._struct)
}
def __str__(self):
return json.dumps(self.dict(), indent=4)
|
import json
from .util import make_dsl_object, unroll_definitions, unroll_struct
class MetaFilterQuery(type):
def __init__(cls, name, bases, d):
super(MetaFilterQuery, cls).__init__(name, bases, d)
unroll_definitions(cls._definitions)
def __getattr__(cls, key):
if key == '__test__':
return None
if key not in cls._definitions:
raise cls._exception(key)
return lambda *args, **kwargs: make_dsl_object(
cls, key, cls._definitions[key],
*args, **kwargs
)
class BaseFilterQuery(object):
_type = None
_struct = None
_dsl_type = None
def __init__(self, dsl_type, struct):
self._struct = struct
self._dsl_type = dsl_type
def dict(self):
dsl_type = self._dsl_type[:1] if self._dsl_type.endswith('_') else self._dsl_type
return {
dsl_type: unroll_struct(self._struct)
}
def __str__(self):
return json.dumps(self.dict(), indent=4)
|
Support nosetests, handle magic names (and_, or_, etc)
|
Support nosetests, handle magic names (and_, or_, etc)
|
Python
|
mit
|
Fizzadar/ElasticQuery,Fizzadar/ElasticQuery
|
python
|
## Code Before:
import json
from .util import make_dsl_object, unroll_definitions, unroll_struct
class MetaFilterQuery(type):
def __init__(cls, name, bases, d):
super(MetaFilterQuery, cls).__init__(name, bases, d)
unroll_definitions(cls._definitions)
def __getattr__(cls, key):
if key not in cls._definitions:
raise cls._exception(key)
return lambda *args, **kwargs: make_dsl_object(
cls, key, cls._definitions[key],
*args, **kwargs
)
class BaseFilterQuery(object):
_type = None
_struct = None
_dsl_type = None
def __init__(self, dsl_type, struct):
self._struct = struct
self._dsl_type = dsl_type
def dict(self):
return {
self._dsl_type: unroll_struct(self._struct)
}
def __str__(self):
return json.dumps(self.dict(), indent=4)
## Instruction:
Support nosetests, handle magic names (and_, or_, etc)
## Code After:
import json
from .util import make_dsl_object, unroll_definitions, unroll_struct
class MetaFilterQuery(type):
def __init__(cls, name, bases, d):
super(MetaFilterQuery, cls).__init__(name, bases, d)
unroll_definitions(cls._definitions)
def __getattr__(cls, key):
if key == '__test__':
return None
if key not in cls._definitions:
raise cls._exception(key)
return lambda *args, **kwargs: make_dsl_object(
cls, key, cls._definitions[key],
*args, **kwargs
)
class BaseFilterQuery(object):
_type = None
_struct = None
_dsl_type = None
def __init__(self, dsl_type, struct):
self._struct = struct
self._dsl_type = dsl_type
def dict(self):
dsl_type = self._dsl_type[:1] if self._dsl_type.endswith('_') else self._dsl_type
return {
dsl_type: unroll_struct(self._struct)
}
def __str__(self):
return json.dumps(self.dict(), indent=4)
|
...
unroll_definitions(cls._definitions)
def __getattr__(cls, key):
if key == '__test__':
return None
if key not in cls._definitions:
raise cls._exception(key)
...
self._dsl_type = dsl_type
def dict(self):
dsl_type = self._dsl_type[:1] if self._dsl_type.endswith('_') else self._dsl_type
return {
dsl_type: unroll_struct(self._struct)
}
def __str__(self):
...
|
40fd8c680f335ebd1bc217f35a47f169c336530c
|
pyosf/tools.py
|
pyosf/tools.py
|
def find_by_key(in_list, key, val):
"""Returns the first item with key matching val
"""
return (item for item in in_list if item[key] == val).next()
def dict_from_list(in_list, key):
"""From a list of dicts creates a dict of dicts using a given key name
"""
d = {}
for entry in in_list:
d[entry[key]] = entry
return d
|
def find_by_key(in_list, key, val):
"""Returns the first item with key matching val
"""
return next(item for item in in_list if item[key] == val)
def dict_from_list(in_list, key):
"""From a list of dicts creates a dict of dicts using a given key name
"""
d = {}
for entry in in_list:
d[entry[key]] = entry
return d
|
Fix compatibility with Py3 (generators no longer have next())
|
Fix compatibility with Py3 (generators no longer have next())
But there is a next() function as a general built-in and works in 2.6 too
|
Python
|
mit
|
psychopy/pyosf
|
python
|
## Code Before:
def find_by_key(in_list, key, val):
"""Returns the first item with key matching val
"""
return (item for item in in_list if item[key] == val).next()
def dict_from_list(in_list, key):
"""From a list of dicts creates a dict of dicts using a given key name
"""
d = {}
for entry in in_list:
d[entry[key]] = entry
return d
## Instruction:
Fix compatibility with Py3 (generators no longer have next())
But there is a next() function as a general built-in and works in 2.6 too
## Code After:
def find_by_key(in_list, key, val):
"""Returns the first item with key matching val
"""
return next(item for item in in_list if item[key] == val)
def dict_from_list(in_list, key):
"""From a list of dicts creates a dict of dicts using a given key name
"""
d = {}
for entry in in_list:
d[entry[key]] = entry
return d
|
# ... existing code ...
def find_by_key(in_list, key, val):
"""Returns the first item with key matching val
"""
return next(item for item in in_list if item[key] == val)
def dict_from_list(in_list, key):
# ... rest of the code ...
|
164891392f9a68abb0fa29a74787ef127849d0c0
|
benchexec/tools/avr.py
|
benchexec/tools/avr.py
|
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for AVR -- Abstractly Verifying Reachability
URL: https://github.com/aman-goel/avr
"""
def executable(self, tool_locator):
return tool_locator.find_executable("avr.py")
def name(self):
return "AVR"
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + [task.single_input_file]
def determine_result(self, run):
"""
@return: status of AVR after executing a run
"""
if run.was_timeout:
return result.RESULT_TIMEOUT
status = None
for line in run.output:
if "avr-h" in line:
status = result.RESULT_TRUE_PROP
if "avr-v" in line:
status = result.RESULT_FALSE_PROP
if not status:
status = result.RESULT_ERROR
return status
|
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for AVR -- Abstractly Verifying Reachability
URL: https://github.com/aman-goel/avr
"""
def executable(self, tool_locator):
return tool_locator.find_executable("avr.py")
def name(self):
return "AVR"
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + [task.single_input_file]
def determine_result(self, run):
"""
@return: status of AVR after executing a run
"""
if run.was_timeout:
return result.RESULT_TIMEOUT
status = None
for line in run.output:
# skip the lines that do not contain verification result
if not line.startswith("Verification result:"):
continue
if "avr-h" in line:
status = result.RESULT_TRUE_PROP
if "avr-v" in line:
status = result.RESULT_FALSE_PROP
if not status:
status = result.RESULT_ERROR
return status
|
Determine AVR's results more precisely
|
Determine AVR's results more precisely
|
Python
|
apache-2.0
|
sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec
|
python
|
## Code Before:
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for AVR -- Abstractly Verifying Reachability
URL: https://github.com/aman-goel/avr
"""
def executable(self, tool_locator):
return tool_locator.find_executable("avr.py")
def name(self):
return "AVR"
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + [task.single_input_file]
def determine_result(self, run):
"""
@return: status of AVR after executing a run
"""
if run.was_timeout:
return result.RESULT_TIMEOUT
status = None
for line in run.output:
if "avr-h" in line:
status = result.RESULT_TRUE_PROP
if "avr-v" in line:
status = result.RESULT_FALSE_PROP
if not status:
status = result.RESULT_ERROR
return status
## Instruction:
Determine AVR's results more precisely
## Code After:
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for AVR -- Abstractly Verifying Reachability
URL: https://github.com/aman-goel/avr
"""
def executable(self, tool_locator):
return tool_locator.find_executable("avr.py")
def name(self):
return "AVR"
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + [task.single_input_file]
def determine_result(self, run):
"""
@return: status of AVR after executing a run
"""
if run.was_timeout:
return result.RESULT_TIMEOUT
status = None
for line in run.output:
# skip the lines that do not contain verification result
if not line.startswith("Verification result:"):
continue
if "avr-h" in line:
status = result.RESULT_TRUE_PROP
if "avr-v" in line:
status = result.RESULT_FALSE_PROP
if not status:
status = result.RESULT_ERROR
return status
|
// ... existing code ...
return result.RESULT_TIMEOUT
status = None
for line in run.output:
# skip the lines that do not contain verification result
if not line.startswith("Verification result:"):
continue
if "avr-h" in line:
status = result.RESULT_TRUE_PROP
if "avr-v" in line:
// ... rest of the code ...
|
291d26c5563307e33f7a4aaee406b75c4b8c591a
|
tulip/tasks_test.py
|
tulip/tasks_test.py
|
"""Tests for tasks.py."""
import time
import unittest
from . import events
from . import futures
from . import tasks
class TaskTests(unittest.TestCase):
def setUp(self):
self.event_loop = events.new_event_loop()
events.set_event_loop(self.event_loop)
def tearDown(self):
self.event_loop.close()
def testTaskClass(self):
@tasks.coroutine
def notmuch():
yield from []
return 'ok'
t = tasks.Task(notmuch())
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ok')
def testTaskDecorator(self):
@tasks.task
def notmuch():
yield from []
return 'ko'
t = notmuch()
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ko')
def testSleep(self):
@tasks.coroutine
def sleeper(dt, arg):
res = yield from futures.sleep(dt, arg)
return res
t = tasks.Task(sleeper(0.1, 'yeah'))
t0 = time.monotonic()
t._event_loop.run()
t1 = time.monotonic()
self.assertTrue(t1-t0 >= 0.09)
self.assertTrue(t.done())
self.assertEqual(t.result(), 'yeah')
if __name__ == '__main__':
unittest.main()
|
"""Tests for tasks.py."""
import time
import unittest
from . import events
from . import futures
from . import tasks
class TaskTests(unittest.TestCase):
def setUp(self):
self.event_loop = events.new_event_loop()
events.set_event_loop(self.event_loop)
def tearDown(self):
self.event_loop.close()
def testTaskClass(self):
@tasks.coroutine
def notmuch():
yield from []
return 'ok'
t = tasks.Task(notmuch())
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ok')
def testTaskDecorator(self):
@tasks.task
def notmuch():
yield from []
return 'ko'
t = notmuch()
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ko')
def testSleep(self):
@tasks.coroutine
def sleeper(dt, arg):
yield from futures.sleep(dt/2)
res = yield from futures.sleep(dt/2, arg)
return res
t = tasks.Task(sleeper(0.1, 'yeah'))
t0 = time.monotonic()
t._event_loop.run()
t1 = time.monotonic()
self.assertTrue(t1-t0 >= 0.09)
self.assertTrue(t.done())
self.assertEqual(t.result(), 'yeah')
if __name__ == '__main__':
unittest.main()
|
Test for sleep(dt) without extra arg.
|
Test for sleep(dt) without extra arg.
|
Python
|
apache-2.0
|
gvanrossum/asyncio,gsb-eng/asyncio,gsb-eng/asyncio,manipopopo/asyncio,gvanrossum/asyncio,haypo/trollius,gsb-eng/asyncio,vxgmichel/asyncio,ajdavis/asyncio,fallen/asyncio,jashandeep-sohi/asyncio,haypo/trollius,vxgmichel/asyncio,jashandeep-sohi/asyncio,gvanrossum/asyncio,Martiusweb/asyncio,ajdavis/asyncio,manipopopo/asyncio,vxgmichel/asyncio,ajdavis/asyncio,manipopopo/asyncio,1st1/asyncio,1st1/asyncio,fallen/asyncio,haypo/trollius,jashandeep-sohi/asyncio,Martiusweb/asyncio,fallen/asyncio,1st1/asyncio,Martiusweb/asyncio
|
python
|
## Code Before:
"""Tests for tasks.py."""
import time
import unittest
from . import events
from . import futures
from . import tasks
class TaskTests(unittest.TestCase):
def setUp(self):
self.event_loop = events.new_event_loop()
events.set_event_loop(self.event_loop)
def tearDown(self):
self.event_loop.close()
def testTaskClass(self):
@tasks.coroutine
def notmuch():
yield from []
return 'ok'
t = tasks.Task(notmuch())
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ok')
def testTaskDecorator(self):
@tasks.task
def notmuch():
yield from []
return 'ko'
t = notmuch()
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ko')
def testSleep(self):
@tasks.coroutine
def sleeper(dt, arg):
res = yield from futures.sleep(dt, arg)
return res
t = tasks.Task(sleeper(0.1, 'yeah'))
t0 = time.monotonic()
t._event_loop.run()
t1 = time.monotonic()
self.assertTrue(t1-t0 >= 0.09)
self.assertTrue(t.done())
self.assertEqual(t.result(), 'yeah')
if __name__ == '__main__':
unittest.main()
## Instruction:
Test for sleep(dt) without extra arg.
## Code After:
"""Tests for tasks.py."""
import time
import unittest
from . import events
from . import futures
from . import tasks
class TaskTests(unittest.TestCase):
def setUp(self):
self.event_loop = events.new_event_loop()
events.set_event_loop(self.event_loop)
def tearDown(self):
self.event_loop.close()
def testTaskClass(self):
@tasks.coroutine
def notmuch():
yield from []
return 'ok'
t = tasks.Task(notmuch())
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ok')
def testTaskDecorator(self):
@tasks.task
def notmuch():
yield from []
return 'ko'
t = notmuch()
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ko')
def testSleep(self):
@tasks.coroutine
def sleeper(dt, arg):
yield from futures.sleep(dt/2)
res = yield from futures.sleep(dt/2, arg)
return res
t = tasks.Task(sleeper(0.1, 'yeah'))
t0 = time.monotonic()
t._event_loop.run()
t1 = time.monotonic()
self.assertTrue(t1-t0 >= 0.09)
self.assertTrue(t.done())
self.assertEqual(t.result(), 'yeah')
if __name__ == '__main__':
unittest.main()
|
# ... existing code ...
def testSleep(self):
@tasks.coroutine
def sleeper(dt, arg):
yield from futures.sleep(dt/2)
res = yield from futures.sleep(dt/2, arg)
return res
t = tasks.Task(sleeper(0.1, 'yeah'))
t0 = time.monotonic()
# ... rest of the code ...
|
4eabf8bdb783ab8861d6eb9be6d1fcc4945760f4
|
java/src/main/java/com/thoughtworks/refactoring/replaceTempwithQuery/Product.java
|
java/src/main/java/com/thoughtworks/refactoring/replaceTempwithQuery/Product.java
|
package com.thoughtworks.refactoring.replaceTempwithQuery;
/**
* Created by xinzhang on 6/27/17.
*/
public class Product {
private String name;
private int purchasePrice;
public Product(String name) {
this.name = name;
}
public void setPurchasePrice(int purchasePrice) {
this.purchasePrice = purchasePrice;
}
public String getName() {
return name;
}
public int getPurchasePrice() {
return purchasePrice;
}
public double calcSellingPrice() {
int rate = this.purchasePrice <= 100 ? 3 : 2;
return this.purchasePrice * rate;
}
}
|
package com.thoughtworks.refactoring.replaceTempwithQuery;
/**
* Created by xinzhang on 6/27/17.
*/
public class Product {
private String name;
private int purchasePrice;
public Product(String name) {
this.name = name;
}
public void setPurchasePrice(int purchasePrice) {
this.purchasePrice = purchasePrice;
}
public String getName() {
return name;
}
public int getPurchasePrice() {
return purchasePrice;
}
public double calcSellingPrice() {
return this.purchasePrice * calcSellingRate();
}
private int calcSellingRate() {
return this.purchasePrice <= 100 ? 3 : 2;
}
}
|
Replace Temp With Query - Replace temp variable with query method.
|
[Xin] Replace Temp With Query - Replace temp variable with query method.
|
Java
|
mit
|
hellocreep/refactoring,hellocreep/refactoring,hellocreep/refactoring,hellocreep/refactoring,hellocreep/refactoring,hellocreep/refactoring
|
java
|
## Code Before:
package com.thoughtworks.refactoring.replaceTempwithQuery;
/**
* Created by xinzhang on 6/27/17.
*/
public class Product {
private String name;
private int purchasePrice;
public Product(String name) {
this.name = name;
}
public void setPurchasePrice(int purchasePrice) {
this.purchasePrice = purchasePrice;
}
public String getName() {
return name;
}
public int getPurchasePrice() {
return purchasePrice;
}
public double calcSellingPrice() {
int rate = this.purchasePrice <= 100 ? 3 : 2;
return this.purchasePrice * rate;
}
}
## Instruction:
[Xin] Replace Temp With Query - Replace temp variable with query method.
## Code After:
package com.thoughtworks.refactoring.replaceTempwithQuery;
/**
* Created by xinzhang on 6/27/17.
*/
public class Product {
private String name;
private int purchasePrice;
public Product(String name) {
this.name = name;
}
public void setPurchasePrice(int purchasePrice) {
this.purchasePrice = purchasePrice;
}
public String getName() {
return name;
}
public int getPurchasePrice() {
return purchasePrice;
}
public double calcSellingPrice() {
return this.purchasePrice * calcSellingRate();
}
private int calcSellingRate() {
return this.purchasePrice <= 100 ? 3 : 2;
}
}
|
# ... existing code ...
}
public double calcSellingPrice() {
return this.purchasePrice * calcSellingRate();
}
private int calcSellingRate() {
return this.purchasePrice <= 100 ? 3 : 2;
}
}
# ... rest of the code ...
|
6a3fbb7280c1078b574736eae3c6a3e4e42d3f46
|
seaborn/__init__.py
|
seaborn/__init__.py
|
import matplotlib as mpl
_orig_rc_params = mpl.rcParams.copy()
# Import seaborn objects
from .rcmod import *
from .utils import *
from .palettes import *
from .relational import *
from .regression import *
from .categorical import *
from .distributions import *
from .timeseries import *
from .matrix import *
from .miscplot import *
from .axisgrid import *
from .widgets import *
from .colors import xkcd_rgb, crayons
from . import cm
__version__ = "0.9.1.dev0"
|
import matplotlib as mpl
_orig_rc_params = mpl.rcParams.copy()
# Import seaborn objects
from .rcmod import *
from .utils import *
from .palettes import *
from .relational import *
from .regression import *
from .categorical import *
from .distributions import *
from .matrix import *
from .miscplot import *
from .axisgrid import *
from .widgets import *
from .colors import xkcd_rgb, crayons
from . import cm
__version__ = "0.9.1.dev0"
|
Remove top-level import of timeseries module
|
Remove top-level import of timeseries module
|
Python
|
bsd-3-clause
|
arokem/seaborn,mwaskom/seaborn,mwaskom/seaborn,arokem/seaborn,anntzer/seaborn,anntzer/seaborn
|
python
|
## Code Before:
import matplotlib as mpl
_orig_rc_params = mpl.rcParams.copy()
# Import seaborn objects
from .rcmod import *
from .utils import *
from .palettes import *
from .relational import *
from .regression import *
from .categorical import *
from .distributions import *
from .timeseries import *
from .matrix import *
from .miscplot import *
from .axisgrid import *
from .widgets import *
from .colors import xkcd_rgb, crayons
from . import cm
__version__ = "0.9.1.dev0"
## Instruction:
Remove top-level import of timeseries module
## Code After:
import matplotlib as mpl
_orig_rc_params = mpl.rcParams.copy()
# Import seaborn objects
from .rcmod import *
from .utils import *
from .palettes import *
from .relational import *
from .regression import *
from .categorical import *
from .distributions import *
from .matrix import *
from .miscplot import *
from .axisgrid import *
from .widgets import *
from .colors import xkcd_rgb, crayons
from . import cm
__version__ = "0.9.1.dev0"
|
# ... existing code ...
from .regression import *
from .categorical import *
from .distributions import *
from .matrix import *
from .miscplot import *
from .axisgrid import *
# ... rest of the code ...
|
0cf6f9be7e5af871c59dd6225cd7c4a5790711db
|
h2o-automl/src/main/java/ai/h2o/automl/targetencoding/BlendingParams.java
|
h2o-automl/src/main/java/ai/h2o/automl/targetencoding/BlendingParams.java
|
package ai.h2o.automl.targetencoding;
import water.Iced;
public class BlendingParams extends Iced<BlendingParams> {
private long k;
private long f;
public BlendingParams(long k, long f) {
this.k = k;
this.f = f;
}
public long getK() {
return k;
}
public long getF() {
return f;
}
}
|
package ai.h2o.automl.targetencoding;
import water.Iced;
public class BlendingParams extends Iced<BlendingParams> {
private double k;
private double f;
public BlendingParams(double k, double f) {
this.k = k;
this.f = f;
}
public double getK() {
return k;
}
public double getF() {
return f;
}
}
|
Change type of blending parameters from long to double.
|
PUBDEV-5378: Change type of blending parameters from long to double.
|
Java
|
apache-2.0
|
michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,h2oai/h2o-dev,h2oai/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3
|
java
|
## Code Before:
package ai.h2o.automl.targetencoding;
import water.Iced;
public class BlendingParams extends Iced<BlendingParams> {
private long k;
private long f;
public BlendingParams(long k, long f) {
this.k = k;
this.f = f;
}
public long getK() {
return k;
}
public long getF() {
return f;
}
}
## Instruction:
PUBDEV-5378: Change type of blending parameters from long to double.
## Code After:
package ai.h2o.automl.targetencoding;
import water.Iced;
public class BlendingParams extends Iced<BlendingParams> {
private double k;
private double f;
public BlendingParams(double k, double f) {
this.k = k;
this.f = f;
}
public double getK() {
return k;
}
public double getF() {
return f;
}
}
|
// ... existing code ...
import water.Iced;
public class BlendingParams extends Iced<BlendingParams> {
private double k;
private double f;
public BlendingParams(double k, double f) {
this.k = k;
this.f = f;
}
public double getK() {
return k;
}
public double getF() {
return f;
}
}
// ... rest of the code ...
|
1d62dd3d309d009ffa3f9a71cf141ab7689e1138
|
Maze/src/maze/proceduralmaze.h
|
Maze/src/maze/proceduralmaze.h
|
class ProceduralMaze
{
private:
int width;
int height;
public:
std::map<std::tuple<int, int>, int> grid;
ProceduralMaze(int width, int height);
void generate();
void clearGrid();
std::vector<std::tuple<int, int>> getAdjCells(std::tuple<int, int> center, Tile tile_state);
};
#endif
|
class ProceduralMaze
{
private:
int width;
int height;
std::map<std::tuple<int, int>, int> grid;
void clearGrid();
std::vector<std::tuple<int, int>> getAdjCells(std::tuple<int, int> center, Tile tile_state);
public:
ProceduralMaze(int width, int height);
void generate();
void print();
std::map<std::tuple<int, int>, int> getGrid() { return grid; }
};
#endif
|
Move some ProceduralMaze public methods to private
|
Move some ProceduralMaze public methods to private
|
C
|
mit
|
gfceccon/Maze,gfceccon/Maze
|
c
|
## Code Before:
class ProceduralMaze
{
private:
int width;
int height;
public:
std::map<std::tuple<int, int>, int> grid;
ProceduralMaze(int width, int height);
void generate();
void clearGrid();
std::vector<std::tuple<int, int>> getAdjCells(std::tuple<int, int> center, Tile tile_state);
};
#endif
## Instruction:
Move some ProceduralMaze public methods to private
## Code After:
class ProceduralMaze
{
private:
int width;
int height;
std::map<std::tuple<int, int>, int> grid;
void clearGrid();
std::vector<std::tuple<int, int>> getAdjCells(std::tuple<int, int> center, Tile tile_state);
public:
ProceduralMaze(int width, int height);
void generate();
void print();
std::map<std::tuple<int, int>, int> getGrid() { return grid; }
};
#endif
|
# ... existing code ...
private:
int width;
int height;
std::map<std::tuple<int, int>, int> grid;
void clearGrid();
std::vector<std::tuple<int, int>> getAdjCells(std::tuple<int, int> center, Tile tile_state);
public:
ProceduralMaze(int width, int height);
void generate();
void print();
std::map<std::tuple<int, int>, int> getGrid() { return grid; }
};
#endif
# ... rest of the code ...
|
7e59dc64a8aad61016c0b3f05b467bc4a3e02f57
|
deploy/generate_production_ini.py
|
deploy/generate_production_ini.py
|
import os
from dcicutils.deployment_utils import Deployer
class FourfrontDeployer(Deployer):
_MY_DIR = os.path.dirname(__file__)
TEMPLATE_DIR = os.path.join(_MY_DIR, "ini_files")
PYPROJECT_FILE_NAME = os.path.join(os.path.dirname(_MY_DIR), "pyproject.toml")
def main():
FourfrontDeployer.main()
if __name__ == '__main__':
main()
|
import os
from dcicutils.deployment_utils import BasicLegacyFourfrontIniFileManager
class FourfrontDeployer(BasicLegacyFourfrontIniFileManager):
_MY_DIR = os.path.dirname(__file__)
TEMPLATE_DIR = os.path.join(_MY_DIR, "ini_files")
PYPROJECT_FILE_NAME = os.path.join(os.path.dirname(_MY_DIR), "pyproject.toml")
def main():
FourfrontDeployer.main()
if __name__ == '__main__':
main()
|
Adjust deployer to use new class name for ini file management.
|
Adjust deployer to use new class name for ini file management.
|
Python
|
mit
|
4dn-dcic/fourfront,4dn-dcic/fourfront,4dn-dcic/fourfront,4dn-dcic/fourfront
|
python
|
## Code Before:
import os
from dcicutils.deployment_utils import Deployer
class FourfrontDeployer(Deployer):
_MY_DIR = os.path.dirname(__file__)
TEMPLATE_DIR = os.path.join(_MY_DIR, "ini_files")
PYPROJECT_FILE_NAME = os.path.join(os.path.dirname(_MY_DIR), "pyproject.toml")
def main():
FourfrontDeployer.main()
if __name__ == '__main__':
main()
## Instruction:
Adjust deployer to use new class name for ini file management.
## Code After:
import os
from dcicutils.deployment_utils import BasicLegacyFourfrontIniFileManager
class FourfrontDeployer(BasicLegacyFourfrontIniFileManager):
_MY_DIR = os.path.dirname(__file__)
TEMPLATE_DIR = os.path.join(_MY_DIR, "ini_files")
PYPROJECT_FILE_NAME = os.path.join(os.path.dirname(_MY_DIR), "pyproject.toml")
def main():
FourfrontDeployer.main()
if __name__ == '__main__':
main()
|
...
import os
from dcicutils.deployment_utils import BasicLegacyFourfrontIniFileManager
class FourfrontDeployer(BasicLegacyFourfrontIniFileManager):
_MY_DIR = os.path.dirname(__file__)
TEMPLATE_DIR = os.path.join(_MY_DIR, "ini_files")
PYPROJECT_FILE_NAME = os.path.join(os.path.dirname(_MY_DIR), "pyproject.toml")
...
|
8bb32136b29837113c1e74ae037bc01e60c0c3e1
|
core/src/test/java/de/otto/jlineup/image/LABTest.java
|
core/src/test/java/de/otto/jlineup/image/LABTest.java
|
package de.otto.jlineup.image;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
public class LABTest {
@Test
public void shouldCalculateCIEDE2000() {
LAB lab1 = LAB.fromRGB(55,44,33, 0);
LAB lab2 = LAB.fromRGB(66,55,44, 0);
double v = LAB.ciede2000(lab1, lab2);
assertThat(v, is(3.533443206558854d));
}
}
|
package de.otto.jlineup.image;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class LABTest {
@Test
public void shouldCalculateCIEDE2000() {
LAB lab1 = LAB.fromRGB(55,44,33, 0);
LAB lab2 = LAB.fromRGB(66,55,44, 0);
double v = Math.round(LAB.ciede2000(lab1, lab2) * Math.pow(10, 12)) / Math.pow(10, 12);
assertThat(v, is(3.533443206559));
}
}
|
Fix precision issue on MacOS
|
Fix precision issue on MacOS
Co-authored-by: Marco Geweke <[email protected]>
|
Java
|
apache-2.0
|
otto-de/jlineup,otto-de/jlineup,otto-de/jlineup
|
java
|
## Code Before:
package de.otto.jlineup.image;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
public class LABTest {
@Test
public void shouldCalculateCIEDE2000() {
LAB lab1 = LAB.fromRGB(55,44,33, 0);
LAB lab2 = LAB.fromRGB(66,55,44, 0);
double v = LAB.ciede2000(lab1, lab2);
assertThat(v, is(3.533443206558854d));
}
}
## Instruction:
Fix precision issue on MacOS
Co-authored-by: Marco Geweke <[email protected]>
## Code After:
package de.otto.jlineup.image;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class LABTest {
@Test
public void shouldCalculateCIEDE2000() {
LAB lab1 = LAB.fromRGB(55,44,33, 0);
LAB lab2 = LAB.fromRGB(66,55,44, 0);
double v = Math.round(LAB.ciede2000(lab1, lab2) * Math.pow(10, 12)) / Math.pow(10, 12);
assertThat(v, is(3.533443206559));
}
}
|
# ... existing code ...
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class LABTest {
# ... modified code ...
LAB lab1 = LAB.fromRGB(55,44,33, 0);
LAB lab2 = LAB.fromRGB(66,55,44, 0);
double v = Math.round(LAB.ciede2000(lab1, lab2) * Math.pow(10, 12)) / Math.pow(10, 12);
assertThat(v, is(3.533443206559));
}
}
# ... rest of the code ...
|
80bb5557f78268545139cd37f593278e35979fd5
|
corehq/mobile_flags.py
|
corehq/mobile_flags.py
|
from collections import namedtuple
MobileFlag = namedtuple('MobileFlag', 'slug label')
MULTIPLE_APPS_UNLIMITED = MobileFlag(
'multiple_apps_unlimited',
'Enable unlimited multiple apps'
)
|
from collections import namedtuple
MobileFlag = namedtuple('MobileFlag', 'slug label')
MULTIPLE_APPS_UNLIMITED = MobileFlag(
'multiple_apps_unlimited',
'Enable unlimited multiple apps'
)
ADVANCED_SETTINGS_ACCESS = MobileFlag(
'advanced_settings_access',
'Enable access to advanced settings'
)
|
Add Flag enum for settings access
|
Add Flag enum for settings access
|
Python
|
bsd-3-clause
|
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
|
python
|
## Code Before:
from collections import namedtuple
MobileFlag = namedtuple('MobileFlag', 'slug label')
MULTIPLE_APPS_UNLIMITED = MobileFlag(
'multiple_apps_unlimited',
'Enable unlimited multiple apps'
)
## Instruction:
Add Flag enum for settings access
## Code After:
from collections import namedtuple
MobileFlag = namedtuple('MobileFlag', 'slug label')
MULTIPLE_APPS_UNLIMITED = MobileFlag(
'multiple_apps_unlimited',
'Enable unlimited multiple apps'
)
ADVANCED_SETTINGS_ACCESS = MobileFlag(
'advanced_settings_access',
'Enable access to advanced settings'
)
|
...
'multiple_apps_unlimited',
'Enable unlimited multiple apps'
)
ADVANCED_SETTINGS_ACCESS = MobileFlag(
'advanced_settings_access',
'Enable access to advanced settings'
)
...
|
adf3a500e8ab8115520daa16bc008faeec7cfca9
|
gitfs/views/view.py
|
gitfs/views/view.py
|
import os
from abc import ABCMeta, abstractmethod
from gitfs import FuseMethodNotImplemented
from gitfs.filesystems.passthrough import PassthroughFuse
class View(PassthroughFuse):
__metaclass__ = ABCMeta
def __init__(self, *args, **kwargs):
self.args = args
for attr in kwargs:
setattr(self, attr, kwargs[attr])
def getxattr(self, path, name, position=0):
"""Get extended attributes"""
raise FuseMethodNotImplemented
|
import os
from abc import ABCMeta, abstractmethod
from gitfs import FuseMethodNotImplemented
class View(object):
__metaclass__ = ABCMeta
def __init__(self, *args, **kwargs):
self.args = args
for attr in kwargs:
setattr(self, attr, kwargs[attr])
def getxattr(self, path, name, position=0):
"""Get extended attributes"""
raise FuseMethodNotImplemented
|
Make View inherit from objects instead of PassthroughFuse
|
Make View inherit from objects instead of PassthroughFuse
|
Python
|
apache-2.0
|
PressLabs/gitfs,PressLabs/gitfs,rowhit/gitfs,bussiere/gitfs,ksmaheshkumar/gitfs
|
python
|
## Code Before:
import os
from abc import ABCMeta, abstractmethod
from gitfs import FuseMethodNotImplemented
from gitfs.filesystems.passthrough import PassthroughFuse
class View(PassthroughFuse):
__metaclass__ = ABCMeta
def __init__(self, *args, **kwargs):
self.args = args
for attr in kwargs:
setattr(self, attr, kwargs[attr])
def getxattr(self, path, name, position=0):
"""Get extended attributes"""
raise FuseMethodNotImplemented
## Instruction:
Make View inherit from objects instead of PassthroughFuse
## Code After:
import os
from abc import ABCMeta, abstractmethod
from gitfs import FuseMethodNotImplemented
class View(object):
__metaclass__ = ABCMeta
def __init__(self, *args, **kwargs):
self.args = args
for attr in kwargs:
setattr(self, attr, kwargs[attr])
def getxattr(self, path, name, position=0):
"""Get extended attributes"""
raise FuseMethodNotImplemented
|
...
from abc import ABCMeta, abstractmethod
from gitfs import FuseMethodNotImplemented
class View(object):
__metaclass__ = ABCMeta
def __init__(self, *args, **kwargs):
...
for attr in kwargs:
setattr(self, attr, kwargs[attr])
def getxattr(self, path, name, position=0):
"""Get extended attributes"""
...
|
0ea4abe8b2e44bdd02308ad590ffb1e846201300
|
terms/sitemaps.py
|
terms/sitemaps.py
|
from django.contrib.sitemaps import Sitemap
from .models import Term
class TermsSitemap(Sitemap):
changefreq = 'yearly'
priority = 0.1
def items(self):
return Term.objects.all()
|
from django.contrib.sitemaps import Sitemap
from django.db.models import Q
from .models import Term
class TermsSitemap(Sitemap):
changefreq = 'yearly'
priority = 0.1
def items(self):
return Term.objects.filter(Q(url__startswith='/') | Q(url=''))
|
Exclude external urls from the sitemap.
|
Exclude external urls from the sitemap.
|
Python
|
bsd-3-clause
|
philippeowagner/django-terms,BertrandBordage/django-terms,philippeowagner/django-terms,BertrandBordage/django-terms
|
python
|
## Code Before:
from django.contrib.sitemaps import Sitemap
from .models import Term
class TermsSitemap(Sitemap):
changefreq = 'yearly'
priority = 0.1
def items(self):
return Term.objects.all()
## Instruction:
Exclude external urls from the sitemap.
## Code After:
from django.contrib.sitemaps import Sitemap
from django.db.models import Q
from .models import Term
class TermsSitemap(Sitemap):
changefreq = 'yearly'
priority = 0.1
def items(self):
return Term.objects.filter(Q(url__startswith='/') | Q(url=''))
|
...
from django.contrib.sitemaps import Sitemap
from django.db.models import Q
from .models import Term
...
priority = 0.1
def items(self):
return Term.objects.filter(Q(url__startswith='/') | Q(url=''))
...
|
e7f8000d3a781cfe51e3205118446fd651b07587
|
src/main/java/org/utplsql/api/JavaApiVersionInfo.java
|
src/main/java/org/utplsql/api/JavaApiVersionInfo.java
|
package org.utplsql.api;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
/** This class is getting updated automatically by the build process.
* Please do not update its constants manually cause they will be overwritten.
*
* @author pesse
*/
public class JavaApiVersionInfo {
private JavaApiVersionInfo() { }
private static final String MAVEN_PROJECT_NAME = "utPLSQL-java-api";
private static String MAVEN_PROJECT_VERSION = "unknown";
static {
try {
MAVEN_PROJECT_VERSION = Files.readAllLines(
Paths.get(JavaApiVersionInfo.class.getClassLoader().getResource("utplsql-api.version").toURI())
, Charset.defaultCharset())
.get(0);
}
catch ( IOException | URISyntaxException e ) {
System.out.println("WARNING: Could not get Version information!");
}
}
public static String getVersion() { return MAVEN_PROJECT_VERSION; }
public static String getInfo() { return MAVEN_PROJECT_NAME + " " + getVersion(); }
}
|
package org.utplsql.api;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
/** This class is getting updated automatically by the build process.
* Please do not update its constants manually cause they will be overwritten.
*
* @author pesse
*/
public class JavaApiVersionInfo {
private JavaApiVersionInfo() { }
private static final String MAVEN_PROJECT_NAME = "utPLSQL-java-api";
private static String MAVEN_PROJECT_VERSION = "unknown";
static {
try {
try ( InputStream in = JavaApiVersionInfo.class.getClassLoader().getResourceAsStream("utplsql-api.version")) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
MAVEN_PROJECT_VERSION = reader.readLine();
reader.close();
}
}
catch ( IOException e ) {
System.out.println("WARNING: Could not get Version information!");
}
}
public static String getVersion() { return MAVEN_PROJECT_VERSION; }
public static String getInfo() { return MAVEN_PROJECT_NAME + " " + getVersion(); }
}
|
Use ResourceStream instead of NIO File access
|
Use ResourceStream instead of NIO File access
|
Java
|
apache-2.0
|
utPLSQL/utPLSQL-java-api,utPLSQL/utPLSQL-java-api,utPLSQL/utPLSQL-java-api
|
java
|
## Code Before:
package org.utplsql.api;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
/** This class is getting updated automatically by the build process.
* Please do not update its constants manually cause they will be overwritten.
*
* @author pesse
*/
public class JavaApiVersionInfo {
private JavaApiVersionInfo() { }
private static final String MAVEN_PROJECT_NAME = "utPLSQL-java-api";
private static String MAVEN_PROJECT_VERSION = "unknown";
static {
try {
MAVEN_PROJECT_VERSION = Files.readAllLines(
Paths.get(JavaApiVersionInfo.class.getClassLoader().getResource("utplsql-api.version").toURI())
, Charset.defaultCharset())
.get(0);
}
catch ( IOException | URISyntaxException e ) {
System.out.println("WARNING: Could not get Version information!");
}
}
public static String getVersion() { return MAVEN_PROJECT_VERSION; }
public static String getInfo() { return MAVEN_PROJECT_NAME + " " + getVersion(); }
}
## Instruction:
Use ResourceStream instead of NIO File access
## Code After:
package org.utplsql.api;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
/** This class is getting updated automatically by the build process.
* Please do not update its constants manually cause they will be overwritten.
*
* @author pesse
*/
public class JavaApiVersionInfo {
private JavaApiVersionInfo() { }
private static final String MAVEN_PROJECT_NAME = "utPLSQL-java-api";
private static String MAVEN_PROJECT_VERSION = "unknown";
static {
try {
try ( InputStream in = JavaApiVersionInfo.class.getClassLoader().getResourceAsStream("utplsql-api.version")) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
MAVEN_PROJECT_VERSION = reader.readLine();
reader.close();
}
}
catch ( IOException e ) {
System.out.println("WARNING: Could not get Version information!");
}
}
public static String getVersion() { return MAVEN_PROJECT_VERSION; }
public static String getInfo() { return MAVEN_PROJECT_NAME + " " + getVersion(); }
}
|
...
package org.utplsql.api;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
...
static {
try {
try ( InputStream in = JavaApiVersionInfo.class.getClassLoader().getResourceAsStream("utplsql-api.version")) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
MAVEN_PROJECT_VERSION = reader.readLine();
reader.close();
}
}
catch ( IOException e ) {
System.out.println("WARNING: Could not get Version information!");
}
}
...
|
48205d660f67fa6ee48d62aae7edab19cf15907b
|
lesson001/chapter006/task01/src/main/java/ru/spoddubnyak/CheckString.java
|
lesson001/chapter006/task01/src/main/java/ru/spoddubnyak/CheckString.java
|
package ru.spoddubnyak;
public class CheckString {
public String sub;
public String origin;
public CheckString(String origin, String sub) {
this.sub = sub;
this.origin = origin;
}
public boolean checkLineEntyAnotherLine() {
char[] subArray = this.sub.toCharArray();
char[] originArray = this.origin.toCharArray();
int count = 0;
for (int i = 0; i < originArray.length - subArray.length + 1; i++ ) {
if ((originArray[i] == subArray[0]) && (subArray.length + i <= originArray.length)) {
count = 1;
for (int j = 1; j < subArray.length; j++) {
if (originArray[i + j] != subArray[j]) {
break;
}
count++;
}
if (count == subArray.length) {
return true;
}
}
}
return false;
}
}
|
package ru.spoddubnyak;
public class CheckString {
public String sub;
public String origin;
public CheckString(String origin, String sub) {
this.sub = sub;
this.origin = origin;
}
public boolean checkLineEntyAnotherLine() {
char[] subArray = this.sub.toCharArray();
char[] originArray = this.origin.toCharArray();
int count = 0;
int i = 0;
while ((i < originArray.length - subArray.length + 1) && (count != subArray.length)) {
if ((originArray[i] == subArray[0]) && (subArray.length + i <= originArray.length)) {
count = 1;
for (int j = 1; j < subArray.length; j++) {
if (originArray[i + j] != subArray[j]) {
break;
}
count++;
}
}
i++;
}
return (count == subArray.length) ? true : false;
}
}
|
Update job task 6.1 lesson 1
|
Update job task 6.1 lesson 1
|
Java
|
apache-2.0
|
forvvard09/job4j_CoursesJunior
|
java
|
## Code Before:
package ru.spoddubnyak;
public class CheckString {
public String sub;
public String origin;
public CheckString(String origin, String sub) {
this.sub = sub;
this.origin = origin;
}
public boolean checkLineEntyAnotherLine() {
char[] subArray = this.sub.toCharArray();
char[] originArray = this.origin.toCharArray();
int count = 0;
for (int i = 0; i < originArray.length - subArray.length + 1; i++ ) {
if ((originArray[i] == subArray[0]) && (subArray.length + i <= originArray.length)) {
count = 1;
for (int j = 1; j < subArray.length; j++) {
if (originArray[i + j] != subArray[j]) {
break;
}
count++;
}
if (count == subArray.length) {
return true;
}
}
}
return false;
}
}
## Instruction:
Update job task 6.1 lesson 1
## Code After:
package ru.spoddubnyak;
public class CheckString {
public String sub;
public String origin;
public CheckString(String origin, String sub) {
this.sub = sub;
this.origin = origin;
}
public boolean checkLineEntyAnotherLine() {
char[] subArray = this.sub.toCharArray();
char[] originArray = this.origin.toCharArray();
int count = 0;
int i = 0;
while ((i < originArray.length - subArray.length + 1) && (count != subArray.length)) {
if ((originArray[i] == subArray[0]) && (subArray.length + i <= originArray.length)) {
count = 1;
for (int j = 1; j < subArray.length; j++) {
if (originArray[i + j] != subArray[j]) {
break;
}
count++;
}
}
i++;
}
return (count == subArray.length) ? true : false;
}
}
|
# ... existing code ...
char[] subArray = this.sub.toCharArray();
char[] originArray = this.origin.toCharArray();
int count = 0;
int i = 0;
while ((i < originArray.length - subArray.length + 1) && (count != subArray.length)) {
if ((originArray[i] == subArray[0]) && (subArray.length + i <= originArray.length)) {
count = 1;
for (int j = 1; j < subArray.length; j++) {
# ... modified code ...
}
count++;
}
}
i++;
}
return (count == subArray.length) ? true : false;
}
}
# ... rest of the code ...
|
cee60151acf606a4e22a92c51066b7fb720f35a3
|
application/models.py
|
application/models.py
|
import urllib2
import logging
def extractMetrics(team, metric):
"""
Parses the data available at the url into a data structure.
"""
url = "http://blends.debian.net/liststats/"+metric+"_"+team+"_year.txt"
lines = urllib2.urlopen(url).readlines()
ll = len(lines)
names = lines[0].split('\t')
results = list()
for i in range (1,ll):
data = lines[i].split('\t')
year = data[0]
results.append(dict());
results[len(results)-1]["year"]=year;
results[len(results)-1]["userdata"]=list();
lw = len(data)
yeardata=dict()
for j in range(1,lw):
results[len(results)-1]["userdata"].append(dict())
results[len(results)-1]["userdata"][len(results[len(results)-1]["userdata"])-1]["user"]=names[j]
results[len(results)-1]["userdata"][len(results[len(results)-1]["userdata"])-1]["data"]=data[j]
metricresult = dict()
metricresult["metric"]=metric
metricresult["data"]=results;
return metricresult
|
import urllib2
import logging
def extractMetrics(team, metric):
"""
Parses the data available at the url into a data structure.
"""
url = "http://blends.debian.net/liststats/"+metric+"_"+team+"_year.txt"
lines = urllib2.urlopen(url).readlines()
ll = len(lines)
names = lines[0].split('\t')
results = list()
for i in range(1,ll):
data = lines[i].split('\t')
ld = len(data)
for j in range (1,ld):
if(i==1):
results.append(dict())
results[j-1]["user"]=names[j].strip();
results[j-1]["userdata"]=list()
results[j-1]["userdata"].append(dict())
results[j-1]["userdata"][i-1]["year"]=data[0].strip()
results[j-1]["userdata"][i-1]["data"]=data[j].strip()
metricresult = dict()
metricresult["metric"]=metric
metricresult["data"]=results;
return metricresult
|
Update the API to make it more semantic.
|
Update the API to make it more semantic.
|
Python
|
mit
|
swvist/debmetrics,swvist/debmetrics
|
python
|
## Code Before:
import urllib2
import logging
def extractMetrics(team, metric):
"""
Parses the data available at the url into a data structure.
"""
url = "http://blends.debian.net/liststats/"+metric+"_"+team+"_year.txt"
lines = urllib2.urlopen(url).readlines()
ll = len(lines)
names = lines[0].split('\t')
results = list()
for i in range (1,ll):
data = lines[i].split('\t')
year = data[0]
results.append(dict());
results[len(results)-1]["year"]=year;
results[len(results)-1]["userdata"]=list();
lw = len(data)
yeardata=dict()
for j in range(1,lw):
results[len(results)-1]["userdata"].append(dict())
results[len(results)-1]["userdata"][len(results[len(results)-1]["userdata"])-1]["user"]=names[j]
results[len(results)-1]["userdata"][len(results[len(results)-1]["userdata"])-1]["data"]=data[j]
metricresult = dict()
metricresult["metric"]=metric
metricresult["data"]=results;
return metricresult
## Instruction:
Update the API to make it more semantic.
## Code After:
import urllib2
import logging
def extractMetrics(team, metric):
"""
Parses the data available at the url into a data structure.
"""
url = "http://blends.debian.net/liststats/"+metric+"_"+team+"_year.txt"
lines = urllib2.urlopen(url).readlines()
ll = len(lines)
names = lines[0].split('\t')
results = list()
for i in range(1,ll):
data = lines[i].split('\t')
ld = len(data)
for j in range (1,ld):
if(i==1):
results.append(dict())
results[j-1]["user"]=names[j].strip();
results[j-1]["userdata"]=list()
results[j-1]["userdata"].append(dict())
results[j-1]["userdata"][i-1]["year"]=data[0].strip()
results[j-1]["userdata"][i-1]["data"]=data[j].strip()
metricresult = dict()
metricresult["metric"]=metric
metricresult["data"]=results;
return metricresult
|
# ... existing code ...
ll = len(lines)
names = lines[0].split('\t')
results = list()
for i in range(1,ll):
data = lines[i].split('\t')
ld = len(data)
for j in range (1,ld):
if(i==1):
results.append(dict())
results[j-1]["user"]=names[j].strip();
results[j-1]["userdata"]=list()
results[j-1]["userdata"].append(dict())
results[j-1]["userdata"][i-1]["year"]=data[0].strip()
results[j-1]["userdata"][i-1]["data"]=data[j].strip()
metricresult = dict()
metricresult["metric"]=metric
metricresult["data"]=results;
return metricresult
# ... rest of the code ...
|
4163401f7185f4c0d595ec425732b29b152892fe
|
src/main/java/fr/alecharp/picshare/resource/EventResource.java
|
src/main/java/fr/alecharp/picshare/resource/EventResource.java
|
package fr.alecharp.picshare.resource;
import fr.alecharp.picshare.domain.Event;
import fr.alecharp.picshare.service.EventService;
import net.codestory.http.annotations.Get;
import net.codestory.http.templating.Model;
import net.codestory.http.templating.ModelAndView;
import javax.inject.Inject;
import java.util.Optional;
/**
* @author Adrien Lecharpentier
*/
public class EventResource {
private final EventService eventService;
@Inject
public EventResource(EventService eventService) {
this.eventService = eventService;
}
@Get("/event/:id")
public ModelAndView dashboard(String id) {
Optional<Event> event = eventService.get(id);
return event.isPresent() ?
ModelAndView.of("event/display.html", "event", event.get()) :
ModelAndView.of("404.html");
}
}
|
package fr.alecharp.picshare.resource;
import fr.alecharp.picshare.domain.Event;
import fr.alecharp.picshare.service.EventService;
import fr.alecharp.picshare.service.PictureService;
import net.codestory.http.Response;
import net.codestory.http.annotations.Get;
import net.codestory.http.annotations.Prefix;
import net.codestory.http.templating.Model;
import net.codestory.http.templating.ModelAndView;
import javax.inject.Inject;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Optional;
/**
* @author Adrien Lecharpentier
*/
@Prefix("/event")
public class EventResource {
private final EventService eventService;
private final PictureService pictureService;
@Inject
public EventResource(EventService eventService, PictureService pictureService) {
this.eventService = eventService;
this.pictureService = pictureService;
}
@Get("/:id")
public ModelAndView dashboard(String id) {
Optional<Event> event = eventService.get(id);
return event.isPresent() ?
ModelAndView.of("event/display.html", "event", event.get()) :
ModelAndView.of("404.html");
}
@Get("/:id/:picture")
public void download(String id, String picture, Response resp) throws IOException {
resp.setHeader("Content-Type", "application/octet-stream");
Files.copy(pictureService.getPicture(id, picture), resp.outputStream());
}
}
|
Create HTTP API to download the file
|
Create HTTP API to download the file
Using 'application/octet-stream' as content-type of the response, it
allow to force the download of the file, rather than opening it in the
browser.
|
Java
|
apache-2.0
|
obourgain/PicShare,obourgain/PicShare
|
java
|
## Code Before:
package fr.alecharp.picshare.resource;
import fr.alecharp.picshare.domain.Event;
import fr.alecharp.picshare.service.EventService;
import net.codestory.http.annotations.Get;
import net.codestory.http.templating.Model;
import net.codestory.http.templating.ModelAndView;
import javax.inject.Inject;
import java.util.Optional;
/**
* @author Adrien Lecharpentier
*/
public class EventResource {
private final EventService eventService;
@Inject
public EventResource(EventService eventService) {
this.eventService = eventService;
}
@Get("/event/:id")
public ModelAndView dashboard(String id) {
Optional<Event> event = eventService.get(id);
return event.isPresent() ?
ModelAndView.of("event/display.html", "event", event.get()) :
ModelAndView.of("404.html");
}
}
## Instruction:
Create HTTP API to download the file
Using 'application/octet-stream' as content-type of the response, it
allow to force the download of the file, rather than opening it in the
browser.
## Code After:
package fr.alecharp.picshare.resource;
import fr.alecharp.picshare.domain.Event;
import fr.alecharp.picshare.service.EventService;
import fr.alecharp.picshare.service.PictureService;
import net.codestory.http.Response;
import net.codestory.http.annotations.Get;
import net.codestory.http.annotations.Prefix;
import net.codestory.http.templating.Model;
import net.codestory.http.templating.ModelAndView;
import javax.inject.Inject;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Optional;
/**
* @author Adrien Lecharpentier
*/
@Prefix("/event")
public class EventResource {
private final EventService eventService;
private final PictureService pictureService;
@Inject
public EventResource(EventService eventService, PictureService pictureService) {
this.eventService = eventService;
this.pictureService = pictureService;
}
@Get("/:id")
public ModelAndView dashboard(String id) {
Optional<Event> event = eventService.get(id);
return event.isPresent() ?
ModelAndView.of("event/display.html", "event", event.get()) :
ModelAndView.of("404.html");
}
@Get("/:id/:picture")
public void download(String id, String picture, Response resp) throws IOException {
resp.setHeader("Content-Type", "application/octet-stream");
Files.copy(pictureService.getPicture(id, picture), resp.outputStream());
}
}
|
# ... existing code ...
import fr.alecharp.picshare.domain.Event;
import fr.alecharp.picshare.service.EventService;
import fr.alecharp.picshare.service.PictureService;
import net.codestory.http.Response;
import net.codestory.http.annotations.Get;
import net.codestory.http.annotations.Prefix;
import net.codestory.http.templating.Model;
import net.codestory.http.templating.ModelAndView;
import javax.inject.Inject;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Optional;
/**
* @author Adrien Lecharpentier
*/
@Prefix("/event")
public class EventResource {
private final EventService eventService;
private final PictureService pictureService;
@Inject
public EventResource(EventService eventService, PictureService pictureService) {
this.eventService = eventService;
this.pictureService = pictureService;
}
@Get("/:id")
public ModelAndView dashboard(String id) {
Optional<Event> event = eventService.get(id);
return event.isPresent() ?
# ... modified code ...
ModelAndView.of("event/display.html", "event", event.get()) :
ModelAndView.of("404.html");
}
@Get("/:id/:picture")
public void download(String id, String picture, Response resp) throws IOException {
resp.setHeader("Content-Type", "application/octet-stream");
Files.copy(pictureService.getPicture(id, picture), resp.outputStream());
}
}
# ... rest of the code ...
|
72dea9616a84cefd8424f965060552c84cfd241d
|
tests/test_luabject.py
|
tests/test_luabject.py
|
try:
import unittest2 as unittest
except ImportError:
import unittest
from village import _luabject
class TestDirect(unittest.TestCase):
def test_new(self):
state = _luabject.new()
# PyCObject isn't available to assertIsInstance, so:
self.assertEqual(type(state).__name__, 'PyCObject')
def test_load_script(self):
state = _luabject.new()
_luabject.load_script(state, "")
# Can load multiple scripts in one state.
_luabject.load_script(state, "")
# Can load a syntactically correct script.
state = _luabject.new()
_luabject.load_script(state, "function foo() prant() end")
# Can load multiple syntactically correct scripts in one state.
_luabject.load_script(state, "function bar() prant() end")
# Loading a syntactically incorrect script raises an exception.
state = _luabject.new()
with self.assertRaises(ValueError):
_luabject.load_script(state, "1+1")
# Can load a syntactically correct script even after loading an incorrect script raises an exception.
_luabject.load_script(state, "function foo() prant() end")
|
try:
import unittest2 as unittest
except ImportError:
import unittest
from village import _luabject
class TestDirect(unittest.TestCase):
def test_new(self):
state = _luabject.new()
# PyCObject isn't available to assertIsInstance, so:
self.assertEqual(type(state).__name__, 'PyCObject')
def test_load_script(self):
state = _luabject.new()
_luabject.load_script(state, "")
# Can load multiple scripts in one state.
_luabject.load_script(state, "")
# Can load a syntactically correct script.
state = _luabject.new()
_luabject.load_script(state, "function foo() prant() end")
# Can load multiple syntactically correct scripts in one state.
_luabject.load_script(state, "function bar() prant() end")
# Loading a syntactically incorrect script raises an exception.
state = _luabject.new()
with self.assertRaises(ValueError):
_luabject.load_script(state, "1+1")
# Can load a syntactically correct script even after a load_script() exception.
_luabject.load_script(state, "function foo() prant() end")
# Loading a syntactically correct script that causes an error raises an exception.
state = _luabject.new()
with self.assertRaises(ValueError):
_luabject.load_script(state, "hi()")
# Can load a syntactically correct script even after a load_script() exception.
_luabject.load_script(state, "function foo() prant() end")
|
Test unrunnable script exceptions too
|
Test unrunnable script exceptions too
|
Python
|
mit
|
markpasc/luabject,markpasc/luabject
|
python
|
## Code Before:
try:
import unittest2 as unittest
except ImportError:
import unittest
from village import _luabject
class TestDirect(unittest.TestCase):
def test_new(self):
state = _luabject.new()
# PyCObject isn't available to assertIsInstance, so:
self.assertEqual(type(state).__name__, 'PyCObject')
def test_load_script(self):
state = _luabject.new()
_luabject.load_script(state, "")
# Can load multiple scripts in one state.
_luabject.load_script(state, "")
# Can load a syntactically correct script.
state = _luabject.new()
_luabject.load_script(state, "function foo() prant() end")
# Can load multiple syntactically correct scripts in one state.
_luabject.load_script(state, "function bar() prant() end")
# Loading a syntactically incorrect script raises an exception.
state = _luabject.new()
with self.assertRaises(ValueError):
_luabject.load_script(state, "1+1")
# Can load a syntactically correct script even after loading an incorrect script raises an exception.
_luabject.load_script(state, "function foo() prant() end")
## Instruction:
Test unrunnable script exceptions too
## Code After:
try:
import unittest2 as unittest
except ImportError:
import unittest
from village import _luabject
class TestDirect(unittest.TestCase):
def test_new(self):
state = _luabject.new()
# PyCObject isn't available to assertIsInstance, so:
self.assertEqual(type(state).__name__, 'PyCObject')
def test_load_script(self):
state = _luabject.new()
_luabject.load_script(state, "")
# Can load multiple scripts in one state.
_luabject.load_script(state, "")
# Can load a syntactically correct script.
state = _luabject.new()
_luabject.load_script(state, "function foo() prant() end")
# Can load multiple syntactically correct scripts in one state.
_luabject.load_script(state, "function bar() prant() end")
# Loading a syntactically incorrect script raises an exception.
state = _luabject.new()
with self.assertRaises(ValueError):
_luabject.load_script(state, "1+1")
# Can load a syntactically correct script even after a load_script() exception.
_luabject.load_script(state, "function foo() prant() end")
# Loading a syntactically correct script that causes an error raises an exception.
state = _luabject.new()
with self.assertRaises(ValueError):
_luabject.load_script(state, "hi()")
# Can load a syntactically correct script even after a load_script() exception.
_luabject.load_script(state, "function foo() prant() end")
|
// ... existing code ...
with self.assertRaises(ValueError):
_luabject.load_script(state, "1+1")
# Can load a syntactically correct script even after a load_script() exception.
_luabject.load_script(state, "function foo() prant() end")
# Loading a syntactically correct script that causes an error raises an exception.
state = _luabject.new()
with self.assertRaises(ValueError):
_luabject.load_script(state, "hi()")
# Can load a syntactically correct script even after a load_script() exception.
_luabject.load_script(state, "function foo() prant() end")
// ... rest of the code ...
|
03b685055037283279394d940602520c5ff7a817
|
email_log/models.py
|
email_log/models.py
|
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
class Email(models.Model):
"""Model to store outgoing email information"""
from_email = models.TextField(_("from e-mail"))
recipients = models.TextField(_("recipients"))
subject = models.TextField(_("subject"))
body = models.TextField(_("body"))
ok = models.BooleanField(_("ok"), default=False, db_index=True)
date_sent = models.DateTimeField(_("date sent"), auto_now_add=True, db_index=True)
def __str__(self):
return "{s.recipients}: {s.subject}".format(s=self)
class Meta:
verbose_name = _("e-mail")
verbose_name_plural = _("e-mails")
ordering = ('-date_sent',)
|
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
class Email(models.Model):
"""Model to store outgoing email information"""
from_email = models.TextField(_("from e-mail"))
recipients = models.TextField(_("recipients"))
subject = models.TextField(_("subject"))
body = models.TextField(_("body"))
ok = models.BooleanField(_("ok"), default=False, db_index=True)
date_sent = models.DateTimeField(_("date sent"), auto_now_add=True,
db_index=True)
def __str__(self):
return "{s.recipients}: {s.subject}".format(s=self)
class Meta:
verbose_name = _("e-mail")
verbose_name_plural = _("e-mails")
ordering = ('-date_sent',)
|
Fix indentation problem and line length (PEP8)
|
Fix indentation problem and line length (PEP8)
|
Python
|
mit
|
treyhunner/django-email-log,treyhunner/django-email-log
|
python
|
## Code Before:
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
class Email(models.Model):
"""Model to store outgoing email information"""
from_email = models.TextField(_("from e-mail"))
recipients = models.TextField(_("recipients"))
subject = models.TextField(_("subject"))
body = models.TextField(_("body"))
ok = models.BooleanField(_("ok"), default=False, db_index=True)
date_sent = models.DateTimeField(_("date sent"), auto_now_add=True, db_index=True)
def __str__(self):
return "{s.recipients}: {s.subject}".format(s=self)
class Meta:
verbose_name = _("e-mail")
verbose_name_plural = _("e-mails")
ordering = ('-date_sent',)
## Instruction:
Fix indentation problem and line length (PEP8)
## Code After:
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
class Email(models.Model):
"""Model to store outgoing email information"""
from_email = models.TextField(_("from e-mail"))
recipients = models.TextField(_("recipients"))
subject = models.TextField(_("subject"))
body = models.TextField(_("body"))
ok = models.BooleanField(_("ok"), default=False, db_index=True)
date_sent = models.DateTimeField(_("date sent"), auto_now_add=True,
db_index=True)
def __str__(self):
return "{s.recipients}: {s.subject}".format(s=self)
class Meta:
verbose_name = _("e-mail")
verbose_name_plural = _("e-mails")
ordering = ('-date_sent',)
|
# ... existing code ...
subject = models.TextField(_("subject"))
body = models.TextField(_("body"))
ok = models.BooleanField(_("ok"), default=False, db_index=True)
date_sent = models.DateTimeField(_("date sent"), auto_now_add=True,
db_index=True)
def __str__(self):
return "{s.recipients}: {s.subject}".format(s=self)
class Meta:
verbose_name = _("e-mail")
verbose_name_plural = _("e-mails")
ordering = ('-date_sent',)
# ... rest of the code ...
|
141e8303fe8f1d6fe554770d7480ef50797d4735
|
books/forms.py
|
books/forms.py
|
from django import forms
from django.forms import ModelForm
from django.utils.translation import ugettext_lazy as _
from books.models import BookType
from egielda import settings
class BookForm(ModelForm):
# Different max_length than in model (to allow dividers in ISBN number)
isbn = forms.CharField(max_length=20, label=_("ISBN"))
class Meta:
model = BookType
fields = ['isbn', 'publisher', 'title', 'publication_year', 'price']
labels = {
'isbn': _("ISBN"),
'publisher': _("Publisher"),
'title': _("Title"),
'publication_year': _("Publication year"),
'price': _("Price (%s)") % getattr(settings, 'CURRENCY', 'USD'),
}
widgets = {
'isbn': forms.TextInput(attrs={'required': 'required'}),
'publisher': forms.TextInput(attrs={'required': 'required'}),
'title': forms.TextInput(attrs={'required': 'required'}),
'publication_year': forms.NumberInput(attrs={'required': 'required', 'min': '1900', 'max': '2100'}),
'price': forms.NumberInput(attrs={'required': 'required', 'max': '999.99'}),
}
def clean_isbn(self):
data = self.cleaned_data['isbn']
data = ''.join(filter(lambda x: x.isdigit(), data))
return data
|
from django import forms
from django.forms import ModelForm
from django.utils.translation import ugettext_lazy as _
from books.models import BookType
from egielda import settings
class BookForm(ModelForm):
# Different max_length than in model (to allow dashes in ISBN)
isbn = forms.CharField(max_length=20, label=_("ISBN"),
widget=forms.TextInput(
attrs={'required': 'required', 'pattern': '[0-9-]+', 'title': 'ISBN number'}))
class Meta:
model = BookType
fields = ['isbn', 'publisher', 'title', 'publication_year', 'price']
labels = {
'publisher': _("Publisher"),
'title': _("Title"),
'publication_year': _("Publication year"),
'price': _("Price (%s)") % getattr(settings, 'CURRENCY', 'USD'),
}
widgets = {
'publisher': forms.TextInput(attrs={'required': 'required'}),
'title': forms.TextInput(attrs={'required': 'required'}),
'publication_year': forms.NumberInput(attrs={'required': 'required', 'min': '1900', 'max': '2100'}),
'price': forms.NumberInput(attrs={'required': 'required', 'max': '999.99'}),
}
def clean_isbn(self):
data = self.cleaned_data['isbn']
data = ''.join(filter(lambda x: x.isdigit(), data))
return data
|
Improve ISBN field in Book Type form
|
Improve ISBN field in Book Type form
- Add required, pattern (to allow only numbers and dashes in HTML5-supporting browsers) and title properties
- Remove a bit of redundant code
|
Python
|
agpl-3.0
|
m4tx/egielda,m4tx/egielda,m4tx/egielda
|
python
|
## Code Before:
from django import forms
from django.forms import ModelForm
from django.utils.translation import ugettext_lazy as _
from books.models import BookType
from egielda import settings
class BookForm(ModelForm):
# Different max_length than in model (to allow dividers in ISBN number)
isbn = forms.CharField(max_length=20, label=_("ISBN"))
class Meta:
model = BookType
fields = ['isbn', 'publisher', 'title', 'publication_year', 'price']
labels = {
'isbn': _("ISBN"),
'publisher': _("Publisher"),
'title': _("Title"),
'publication_year': _("Publication year"),
'price': _("Price (%s)") % getattr(settings, 'CURRENCY', 'USD'),
}
widgets = {
'isbn': forms.TextInput(attrs={'required': 'required'}),
'publisher': forms.TextInput(attrs={'required': 'required'}),
'title': forms.TextInput(attrs={'required': 'required'}),
'publication_year': forms.NumberInput(attrs={'required': 'required', 'min': '1900', 'max': '2100'}),
'price': forms.NumberInput(attrs={'required': 'required', 'max': '999.99'}),
}
def clean_isbn(self):
data = self.cleaned_data['isbn']
data = ''.join(filter(lambda x: x.isdigit(), data))
return data
## Instruction:
Improve ISBN field in Book Type form
- Add required, pattern (to allow only numbers and dashes in HTML5-supporting browsers) and title properties
- Remove a bit of redundant code
## Code After:
from django import forms
from django.forms import ModelForm
from django.utils.translation import ugettext_lazy as _
from books.models import BookType
from egielda import settings
class BookForm(ModelForm):
# Different max_length than in model (to allow dashes in ISBN)
isbn = forms.CharField(max_length=20, label=_("ISBN"),
widget=forms.TextInput(
attrs={'required': 'required', 'pattern': '[0-9-]+', 'title': 'ISBN number'}))
class Meta:
model = BookType
fields = ['isbn', 'publisher', 'title', 'publication_year', 'price']
labels = {
'publisher': _("Publisher"),
'title': _("Title"),
'publication_year': _("Publication year"),
'price': _("Price (%s)") % getattr(settings, 'CURRENCY', 'USD'),
}
widgets = {
'publisher': forms.TextInput(attrs={'required': 'required'}),
'title': forms.TextInput(attrs={'required': 'required'}),
'publication_year': forms.NumberInput(attrs={'required': 'required', 'min': '1900', 'max': '2100'}),
'price': forms.NumberInput(attrs={'required': 'required', 'max': '999.99'}),
}
def clean_isbn(self):
data = self.cleaned_data['isbn']
data = ''.join(filter(lambda x: x.isdigit(), data))
return data
|
// ... existing code ...
class BookForm(ModelForm):
# Different max_length than in model (to allow dashes in ISBN)
isbn = forms.CharField(max_length=20, label=_("ISBN"),
widget=forms.TextInput(
attrs={'required': 'required', 'pattern': '[0-9-]+', 'title': 'ISBN number'}))
class Meta:
model = BookType
fields = ['isbn', 'publisher', 'title', 'publication_year', 'price']
labels = {
'publisher': _("Publisher"),
'title': _("Title"),
'publication_year': _("Publication year"),
// ... modified code ...
'price': _("Price (%s)") % getattr(settings, 'CURRENCY', 'USD'),
}
widgets = {
'publisher': forms.TextInput(attrs={'required': 'required'}),
'title': forms.TextInput(attrs={'required': 'required'}),
'publication_year': forms.NumberInput(attrs={'required': 'required', 'min': '1900', 'max': '2100'}),
// ... rest of the code ...
|
ae1696364f078d7813076c7e0a937ad30a19e84f
|
receiver/receive.py
|
receiver/receive.py
|
import socket, fcntl, sys
#Lock to only allow one instance of this program to run
pid_file = '/tmp/send.pid'
fp = open(pid_file, 'w')
try:
fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
print 'An instance of this program is already running'
sys.exit(0)
import Adafruit_CharLCD as LCD
lcd = LCD.Adafruit_CharLCDPlate()
lcd.set_color(0,0,0)
listener = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
number_packets_received = 0
def print_lcd():
lcd.clear()
lcd.message('# of packets\nreceived: ' + str(number_packets_received))
if __name__ == '__main__':
while True:
print_lcd()
print listener.recvfrom(7777), '\n', type(listener)
number_packets_received += 1
|
import socket, fcntl, sys
#Lock to only allow one instance of this program to run
pid_file = '/tmp/send.pid'
fp = open(pid_file, 'w')
try:
fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
print 'An instance of this program is already running'
sys.exit(0)
import Adafruit_CharLCD as LCD
lcd = LCD.Adafruit_CharLCDPlate()
lcd.set_color(0,0,0)
listener = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
number_packets_received = 0
def print_lcd():
lcd.clear()
lcd.message('# of packets\nreceived: ' + str(number_packets_received))
if __name__ == '__main__':
while True:
print_lcd()
print listener.recvfrom(7777)
number_packets_received += 1
|
Fix header of Python file
|
Fix header of Python file
Now correctly points to the Python interpretor
|
Python
|
mit
|
sapientsalamander/Pi_Packet_Project,sapientsalamander/Pi_Packet_Project,sapientsalamander/Pi_Packet_Project,sapientsalamander/Pi_Packet_Project,sapientsalamander/Pi_Packet_Project
|
python
|
## Code Before:
import socket, fcntl, sys
#Lock to only allow one instance of this program to run
pid_file = '/tmp/send.pid'
fp = open(pid_file, 'w')
try:
fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
print 'An instance of this program is already running'
sys.exit(0)
import Adafruit_CharLCD as LCD
lcd = LCD.Adafruit_CharLCDPlate()
lcd.set_color(0,0,0)
listener = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
number_packets_received = 0
def print_lcd():
lcd.clear()
lcd.message('# of packets\nreceived: ' + str(number_packets_received))
if __name__ == '__main__':
while True:
print_lcd()
print listener.recvfrom(7777), '\n', type(listener)
number_packets_received += 1
## Instruction:
Fix header of Python file
Now correctly points to the Python interpretor
## Code After:
import socket, fcntl, sys
#Lock to only allow one instance of this program to run
pid_file = '/tmp/send.pid'
fp = open(pid_file, 'w')
try:
fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
print 'An instance of this program is already running'
sys.exit(0)
import Adafruit_CharLCD as LCD
lcd = LCD.Adafruit_CharLCDPlate()
lcd.set_color(0,0,0)
listener = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
number_packets_received = 0
def print_lcd():
lcd.clear()
lcd.message('# of packets\nreceived: ' + str(number_packets_received))
if __name__ == '__main__':
while True:
print_lcd()
print listener.recvfrom(7777)
number_packets_received += 1
|
// ... existing code ...
if __name__ == '__main__':
while True:
print_lcd()
print listener.recvfrom(7777)
number_packets_received += 1
// ... rest of the code ...
|
7d3de3aa2441739aa951aa100c057cfa878887d5
|
nukedb.py
|
nukedb.py
|
import sqlite3
if __name__=="__main__":
conn = sqlite3.connect('auxgis.db')
c = conn.cursor()
try:
c.execute('''DROP TABLE pos;''')
except:
pass
try:
c.execute('''DROP TABLE data;''')
except:
pass
conn.commit()
|
import sqlite3
if __name__=="__main__":
conn = sqlite3.connect('auxgis.db')
c = conn.cursor()
try:
c.execute('''DROP TABLE pos;''')
except:
pass
try:
c.execute('''DROP TABLE data;''')
except:
pass
try:
c.execute('''DROP TABLE recentchanges;''')
except:
pass
conn.commit()
|
Drop recent changes on nuke
|
Drop recent changes on nuke
|
Python
|
bsd-3-clause
|
TimSC/auxgis
|
python
|
## Code Before:
import sqlite3
if __name__=="__main__":
conn = sqlite3.connect('auxgis.db')
c = conn.cursor()
try:
c.execute('''DROP TABLE pos;''')
except:
pass
try:
c.execute('''DROP TABLE data;''')
except:
pass
conn.commit()
## Instruction:
Drop recent changes on nuke
## Code After:
import sqlite3
if __name__=="__main__":
conn = sqlite3.connect('auxgis.db')
c = conn.cursor()
try:
c.execute('''DROP TABLE pos;''')
except:
pass
try:
c.execute('''DROP TABLE data;''')
except:
pass
try:
c.execute('''DROP TABLE recentchanges;''')
except:
pass
conn.commit()
|
# ... existing code ...
c.execute('''DROP TABLE data;''')
except:
pass
try:
c.execute('''DROP TABLE recentchanges;''')
except:
pass
conn.commit()
# ... rest of the code ...
|
3471dd3196c134f7aee35aa38370c93915be2197
|
example/__init__.py
|
example/__init__.py
|
import webapp2
class IntroHandler(webapp2.RequestHandler):
def get(self):
pass
app = webapp2.WSGIApplication([
('/', IntroHandler),
])
|
import logging
import webapp2
def example_function(*args, **kwargs):
logging.info('example_function executed with args: %r, kwargs: %r',
args, kwargs)
return args
class AsyncIntroHandler(webapp2.RequestHandler):
def get(self):
"""Create and insert a single furious task."""
from furious.async import Async
# Instantiate an Async object.
async_task = Async(
target=example_function, args=[1], kwargs={'some': 'value'})
# Insert the task to run the Async object, not that it may begin
# executing immediately or with some delay.
async_task.start()
logging.info('Async job kicked off.')
self.response.out.write('Successfully inserted Async job.')
class ContextIntroHandler(webapp2.RequestHandler):
def get(self):
"""Batch insert a group of furious tasks."""
from furious.async import Async
from furious import context
with context.new() as ctx:
# "Manually" instantiate and add an Async object.
async_task = Async(
target=example_function, kwargs={'first': 'async'})
ctx.add(async_task)
logging.info('Added manual job to context.')
for i in xrange(5):
ctx.add(target=example_function, args=[i])
logging.info('Added job %d to context.', i)
logging.info('Async jobs for context batch inserted.')
self.response.out.write('Successfully inserted a group of Async jobs.')
app = webapp2.WSGIApplication([
('/', AsyncIntroHandler),
('/context', ContextIntroHandler),
])
|
Add basic draft of example code.
|
Add basic draft of example code.
|
Python
|
apache-2.0
|
robertkluin/furious,Workiva/furious,rosshendrickson-wf/furious,andreleblanc-wf/furious,rosshendrickson-wf/furious,andreleblanc-wf/furious,beaulyddon-wf/furious,Workiva/furious,mattsanders-wf/furious,beaulyddon-wf/furious,mattsanders-wf/furious
|
python
|
## Code Before:
import webapp2
class IntroHandler(webapp2.RequestHandler):
def get(self):
pass
app = webapp2.WSGIApplication([
('/', IntroHandler),
])
## Instruction:
Add basic draft of example code.
## Code After:
import logging
import webapp2
def example_function(*args, **kwargs):
logging.info('example_function executed with args: %r, kwargs: %r',
args, kwargs)
return args
class AsyncIntroHandler(webapp2.RequestHandler):
def get(self):
"""Create and insert a single furious task."""
from furious.async import Async
# Instantiate an Async object.
async_task = Async(
target=example_function, args=[1], kwargs={'some': 'value'})
# Insert the task to run the Async object, not that it may begin
# executing immediately or with some delay.
async_task.start()
logging.info('Async job kicked off.')
self.response.out.write('Successfully inserted Async job.')
class ContextIntroHandler(webapp2.RequestHandler):
def get(self):
"""Batch insert a group of furious tasks."""
from furious.async import Async
from furious import context
with context.new() as ctx:
# "Manually" instantiate and add an Async object.
async_task = Async(
target=example_function, kwargs={'first': 'async'})
ctx.add(async_task)
logging.info('Added manual job to context.')
for i in xrange(5):
ctx.add(target=example_function, args=[i])
logging.info('Added job %d to context.', i)
logging.info('Async jobs for context batch inserted.')
self.response.out.write('Successfully inserted a group of Async jobs.')
app = webapp2.WSGIApplication([
('/', AsyncIntroHandler),
('/context', ContextIntroHandler),
])
|
// ... existing code ...
import logging
import webapp2
def example_function(*args, **kwargs):
logging.info('example_function executed with args: %r, kwargs: %r',
args, kwargs)
return args
class AsyncIntroHandler(webapp2.RequestHandler):
def get(self):
"""Create and insert a single furious task."""
from furious.async import Async
# Instantiate an Async object.
async_task = Async(
target=example_function, args=[1], kwargs={'some': 'value'})
# Insert the task to run the Async object, not that it may begin
# executing immediately or with some delay.
async_task.start()
logging.info('Async job kicked off.')
self.response.out.write('Successfully inserted Async job.')
class ContextIntroHandler(webapp2.RequestHandler):
def get(self):
"""Batch insert a group of furious tasks."""
from furious.async import Async
from furious import context
with context.new() as ctx:
# "Manually" instantiate and add an Async object.
async_task = Async(
target=example_function, kwargs={'first': 'async'})
ctx.add(async_task)
logging.info('Added manual job to context.')
for i in xrange(5):
ctx.add(target=example_function, args=[i])
logging.info('Added job %d to context.', i)
logging.info('Async jobs for context batch inserted.')
self.response.out.write('Successfully inserted a group of Async jobs.')
app = webapp2.WSGIApplication([
('/', AsyncIntroHandler),
('/context', ContextIntroHandler),
])
// ... rest of the code ...
|
cd41fdbdb53008c9701213d4f223bb8df0514ecb
|
byceps/util/datetime/timezone.py
|
byceps/util/datetime/timezone.py
|
from datetime import datetime
from flask import current_app
import pendulum
def local_tz_to_utc(dt: datetime):
"""Convert date/time object from configured default local time to UTC."""
tz_str = get_timezone_string()
return (pendulum.instance(dt)
.set(tz=tz_str)
.in_tz(pendulum.UTC)
# Keep SQLAlchemy from converting it to another zone.
.replace(tzinfo=None))
def utc_to_local_tz(dt: datetime) -> datetime:
"""Convert naive date/time object from UTC to configured time zone."""
tz_str = get_timezone_string()
return pendulum.instance(dt).in_tz(tz_str)
def get_timezone_string() -> str:
"""Return the configured default timezone as a string."""
return current_app.config['TIMEZONE']
|
from flask import current_app
def get_timezone_string() -> str:
"""Return the configured default timezone as a string."""
return current_app.config['TIMEZONE']
|
Remove unused custom functions `local_tz_to_utc`, `utc_to_local_tz`
|
Remove unused custom functions `local_tz_to_utc`, `utc_to_local_tz`
|
Python
|
bsd-3-clause
|
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
|
python
|
## Code Before:
from datetime import datetime
from flask import current_app
import pendulum
def local_tz_to_utc(dt: datetime):
"""Convert date/time object from configured default local time to UTC."""
tz_str = get_timezone_string()
return (pendulum.instance(dt)
.set(tz=tz_str)
.in_tz(pendulum.UTC)
# Keep SQLAlchemy from converting it to another zone.
.replace(tzinfo=None))
def utc_to_local_tz(dt: datetime) -> datetime:
"""Convert naive date/time object from UTC to configured time zone."""
tz_str = get_timezone_string()
return pendulum.instance(dt).in_tz(tz_str)
def get_timezone_string() -> str:
"""Return the configured default timezone as a string."""
return current_app.config['TIMEZONE']
## Instruction:
Remove unused custom functions `local_tz_to_utc`, `utc_to_local_tz`
## Code After:
from flask import current_app
def get_timezone_string() -> str:
"""Return the configured default timezone as a string."""
return current_app.config['TIMEZONE']
|
# ... existing code ...
from flask import current_app
def get_timezone_string() -> str:
# ... rest of the code ...
|
8fad8a4f1591fb4a7d7d1bdf932c5918197b475c
|
tests/client.py
|
tests/client.py
|
from htmltree import *
def start():
console.log("Starting")
newcontent = H1("Sanity check PASS", _class='test', style=dict(color='green'))
console.log(newcontent.render(0))
document.body.innerHTML = newcontent.render()
console.log("Finished")
document.addEventListener('DOMContentLoaded', start)
|
from htmltree import *
def start():
console.log("Starting")
## insert a style element at the end of the <head?
cssrules = {'.test':{'color':'green', 'text-align':'center'}}
style = Style(**cssrules)
document.head.insertAdjacentHTML('beforeend', style.render())
## Replace the <body> content
newcontent = Div(H1("Sanity check PASS", _class='test'))
document.body.innerHTML = newcontent.render()
console.log("Finished")
## JS is event driven.
## Wait for DOM load to complete before firing
## our start() function.
document.addEventListener('DOMContentLoaded', start)
|
Fix <style> rendering under Transcrypt.
|
Fix <style> rendering under Transcrypt.
The hasattr test in renderCss() was failing when it shouldn't have.
Fixed by removal. Updated tests/client.py to create and append a style
element to detect problems related to Style() on the client side.
|
Python
|
mit
|
Michael-F-Ellis/htmltree
|
python
|
## Code Before:
from htmltree import *
def start():
console.log("Starting")
newcontent = H1("Sanity check PASS", _class='test', style=dict(color='green'))
console.log(newcontent.render(0))
document.body.innerHTML = newcontent.render()
console.log("Finished")
document.addEventListener('DOMContentLoaded', start)
## Instruction:
Fix <style> rendering under Transcrypt.
The hasattr test in renderCss() was failing when it shouldn't have.
Fixed by removal. Updated tests/client.py to create and append a style
element to detect problems related to Style() on the client side.
## Code After:
from htmltree import *
def start():
console.log("Starting")
## insert a style element at the end of the <head?
cssrules = {'.test':{'color':'green', 'text-align':'center'}}
style = Style(**cssrules)
document.head.insertAdjacentHTML('beforeend', style.render())
## Replace the <body> content
newcontent = Div(H1("Sanity check PASS", _class='test'))
document.body.innerHTML = newcontent.render()
console.log("Finished")
## JS is event driven.
## Wait for DOM load to complete before firing
## our start() function.
document.addEventListener('DOMContentLoaded', start)
|
// ... existing code ...
from htmltree import *
def start():
console.log("Starting")
## insert a style element at the end of the <head?
cssrules = {'.test':{'color':'green', 'text-align':'center'}}
style = Style(**cssrules)
document.head.insertAdjacentHTML('beforeend', style.render())
## Replace the <body> content
newcontent = Div(H1("Sanity check PASS", _class='test'))
document.body.innerHTML = newcontent.render()
console.log("Finished")
## JS is event driven.
## Wait for DOM load to complete before firing
## our start() function.
document.addEventListener('DOMContentLoaded', start)
// ... rest of the code ...
|
0fbd7c2f68f9f751642fd0e618dfcb6726d79f44
|
fireplace/cards/wog/mage.py
|
fireplace/cards/wog/mage.py
|
from ..utils import *
##
# Minions
|
from ..utils import *
##
# Minions
class OG_083:
"Twilight Flamecaller"
play = Hit(ENEMY_MINIONS, 1)
class OG_120:
"Anomalus"
deathrattle = Hit(ALL_MINIONS, 8)
class OG_207:
"Faceless Summoner"
play = Summon(CONTROLLER, RandomMinion(cost=3))
|
Implement Twilight Flamecaller, Anomalus, Faceless Summoner
|
Implement Twilight Flamecaller, Anomalus, Faceless Summoner
|
Python
|
agpl-3.0
|
NightKev/fireplace,jleclanche/fireplace,beheh/fireplace
|
python
|
## Code Before:
from ..utils import *
##
# Minions
## Instruction:
Implement Twilight Flamecaller, Anomalus, Faceless Summoner
## Code After:
from ..utils import *
##
# Minions
class OG_083:
"Twilight Flamecaller"
play = Hit(ENEMY_MINIONS, 1)
class OG_120:
"Anomalus"
deathrattle = Hit(ALL_MINIONS, 8)
class OG_207:
"Faceless Summoner"
play = Summon(CONTROLLER, RandomMinion(cost=3))
|
# ... existing code ...
##
# Minions
class OG_083:
"Twilight Flamecaller"
play = Hit(ENEMY_MINIONS, 1)
class OG_120:
"Anomalus"
deathrattle = Hit(ALL_MINIONS, 8)
class OG_207:
"Faceless Summoner"
play = Summon(CONTROLLER, RandomMinion(cost=3))
# ... rest of the code ...
|
260cd3b96df3a4746560db0032d7b6042c55d7fc
|
integration-test/976-fractional-pois.py
|
integration-test/976-fractional-pois.py
|
assert_has_feature(
15, 5242, 12664, 'pois',
{ 'id': 147689077, 'min_zoom': 15.68 })
|
assert_has_feature(
15, 5242, 12664, 'pois',
{ 'id': 147689077, 'min_zoom': 15.68 })
# Test that source and min_zoom are set properly for boundaries, roads, transit, and water
assert_has_feature(
5, 9, 12, 'boundaries',
{ 'min_zoom': 0 , 'id': 8024,
'source': 'naturalearthdata.com',
'name': 'New Jersey - Pennsylvania' })
assert_has_feature(
5, 9, 12, 'roads',
{ 'min_zoom': 5 , 'id': 90,
'source': 'naturalearthdata.com' })
# There is no transit data from Natural Earth
assert_has_feature(
5, 9, 12, 'water',
{ 'min_zoom': 0 , 'id': 1144,
'source': 'naturalearthdata.com',
'name': 'John H. Kerr Reservoir' })
# https://www.openstreetmap.org/relation/224951
# https://www.openstreetmap.org/relation/61320
assert_has_feature(
9, 150, 192, 'boundaries',
{ 'min_zoom': 8, 'id': -224951,
'source': 'openstretmap.org',
'name': 'New Jersey - New York' })
assert_has_feature(
9, 150, 192, 'roads',
{ 'min_zoom': 8, 'sort_key': 381,
'source': 'openstretmap.org',
'kind': 'Major Road',
'network': 'US:NJ:Hudson' })
assert_has_feature(
9, 150, 192, 'transit',
{ 'min_zoom': 5, 'ref': '54-57',
'source': 'openstretmap.org',
'name': 'Vermonter' })
assert_has_feature(
9, 150, 192, 'water',
{ 'min_zoom': 0, 'id': 10613,
'source': 'openstretmapdata.com',
'kind': 'ocean',
'name': '' })
|
Add tests for source and min_zoom
|
Add tests for source and min_zoom
|
Python
|
mit
|
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
|
python
|
## Code Before:
assert_has_feature(
15, 5242, 12664, 'pois',
{ 'id': 147689077, 'min_zoom': 15.68 })
## Instruction:
Add tests for source and min_zoom
## Code After:
assert_has_feature(
15, 5242, 12664, 'pois',
{ 'id': 147689077, 'min_zoom': 15.68 })
# Test that source and min_zoom are set properly for boundaries, roads, transit, and water
assert_has_feature(
5, 9, 12, 'boundaries',
{ 'min_zoom': 0 , 'id': 8024,
'source': 'naturalearthdata.com',
'name': 'New Jersey - Pennsylvania' })
assert_has_feature(
5, 9, 12, 'roads',
{ 'min_zoom': 5 , 'id': 90,
'source': 'naturalearthdata.com' })
# There is no transit data from Natural Earth
assert_has_feature(
5, 9, 12, 'water',
{ 'min_zoom': 0 , 'id': 1144,
'source': 'naturalearthdata.com',
'name': 'John H. Kerr Reservoir' })
# https://www.openstreetmap.org/relation/224951
# https://www.openstreetmap.org/relation/61320
assert_has_feature(
9, 150, 192, 'boundaries',
{ 'min_zoom': 8, 'id': -224951,
'source': 'openstretmap.org',
'name': 'New Jersey - New York' })
assert_has_feature(
9, 150, 192, 'roads',
{ 'min_zoom': 8, 'sort_key': 381,
'source': 'openstretmap.org',
'kind': 'Major Road',
'network': 'US:NJ:Hudson' })
assert_has_feature(
9, 150, 192, 'transit',
{ 'min_zoom': 5, 'ref': '54-57',
'source': 'openstretmap.org',
'name': 'Vermonter' })
assert_has_feature(
9, 150, 192, 'water',
{ 'min_zoom': 0, 'id': 10613,
'source': 'openstretmapdata.com',
'kind': 'ocean',
'name': '' })
|
...
assert_has_feature(
15, 5242, 12664, 'pois',
{ 'id': 147689077, 'min_zoom': 15.68 })
# Test that source and min_zoom are set properly for boundaries, roads, transit, and water
assert_has_feature(
5, 9, 12, 'boundaries',
{ 'min_zoom': 0 , 'id': 8024,
'source': 'naturalearthdata.com',
'name': 'New Jersey - Pennsylvania' })
assert_has_feature(
5, 9, 12, 'roads',
{ 'min_zoom': 5 , 'id': 90,
'source': 'naturalearthdata.com' })
# There is no transit data from Natural Earth
assert_has_feature(
5, 9, 12, 'water',
{ 'min_zoom': 0 , 'id': 1144,
'source': 'naturalearthdata.com',
'name': 'John H. Kerr Reservoir' })
# https://www.openstreetmap.org/relation/224951
# https://www.openstreetmap.org/relation/61320
assert_has_feature(
9, 150, 192, 'boundaries',
{ 'min_zoom': 8, 'id': -224951,
'source': 'openstretmap.org',
'name': 'New Jersey - New York' })
assert_has_feature(
9, 150, 192, 'roads',
{ 'min_zoom': 8, 'sort_key': 381,
'source': 'openstretmap.org',
'kind': 'Major Road',
'network': 'US:NJ:Hudson' })
assert_has_feature(
9, 150, 192, 'transit',
{ 'min_zoom': 5, 'ref': '54-57',
'source': 'openstretmap.org',
'name': 'Vermonter' })
assert_has_feature(
9, 150, 192, 'water',
{ 'min_zoom': 0, 'id': 10613,
'source': 'openstretmapdata.com',
'kind': 'ocean',
'name': '' })
...
|
a14256e715d51728ad4c2bde7ec52f13def6b2a6
|
director/views.py
|
director/views.py
|
from django.shortcuts import redirect
from django.urls import reverse
from django.views.generic import View
class HomeView(View):
def get(self, *args, **kwargs):
if self.request.user.is_authenticated:
return redirect(reverse('project_list'))
else:
return redirect(reverse('beta_token'))
|
from django.shortcuts import redirect
from django.urls import reverse
from accounts.views import BetaTokenView
class HomeView(BetaTokenView):
"""
Home page view.
Care needs to be taken that this view returns a 200 response (not a redirect)
for unauthenticated users. This is because GCP load balancers ping the / path
as a health check and will fail if anything other than a 200 is returned.
"""
def get(self, *args, **kwargs):
if self.request.user.is_authenticated:
return redirect(reverse('project_list'))
else:
return super().get(*args, **kwargs)
|
Fix home view so it returns 200 for unauthenticated health check
|
Fix home view so it returns 200 for unauthenticated health check
|
Python
|
apache-2.0
|
stencila/hub,stencila/hub,stencila/hub,stencila/hub,stencila/hub
|
python
|
## Code Before:
from django.shortcuts import redirect
from django.urls import reverse
from django.views.generic import View
class HomeView(View):
def get(self, *args, **kwargs):
if self.request.user.is_authenticated:
return redirect(reverse('project_list'))
else:
return redirect(reverse('beta_token'))
## Instruction:
Fix home view so it returns 200 for unauthenticated health check
## Code After:
from django.shortcuts import redirect
from django.urls import reverse
from accounts.views import BetaTokenView
class HomeView(BetaTokenView):
"""
Home page view.
Care needs to be taken that this view returns a 200 response (not a redirect)
for unauthenticated users. This is because GCP load balancers ping the / path
as a health check and will fail if anything other than a 200 is returned.
"""
def get(self, *args, **kwargs):
if self.request.user.is_authenticated:
return redirect(reverse('project_list'))
else:
return super().get(*args, **kwargs)
|
# ... existing code ...
from django.shortcuts import redirect
from django.urls import reverse
from accounts.views import BetaTokenView
class HomeView(BetaTokenView):
"""
Home page view.
Care needs to be taken that this view returns a 200 response (not a redirect)
for unauthenticated users. This is because GCP load balancers ping the / path
as a health check and will fail if anything other than a 200 is returned.
"""
def get(self, *args, **kwargs):
if self.request.user.is_authenticated:
return redirect(reverse('project_list'))
else:
return super().get(*args, **kwargs)
# ... rest of the code ...
|
eb87f015b651e163be9767e7272535e7463332ff
|
ext/osl/rbosl_move.h
|
ext/osl/rbosl_move.h
|
extern VALUE cMove;
using namespace osl;
#ifdef __cplusplus
extern "C" {
#endif
extern void Init_move(VALUE mOsl);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* RBOSL_MOVE_H */
|
extern VALUE cMove;
#ifdef __cplusplus
extern "C" {
#endif
extern void Init_move(VALUE mOsl);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* RBOSL_MOVE_H */
|
Remove a needless using namespace
|
Remove a needless using namespace
|
C
|
mit
|
myokoym/ruby-osl,myokoym/ruby-osl,myokoym/ruby-osl
|
c
|
## Code Before:
extern VALUE cMove;
using namespace osl;
#ifdef __cplusplus
extern "C" {
#endif
extern void Init_move(VALUE mOsl);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* RBOSL_MOVE_H */
## Instruction:
Remove a needless using namespace
## Code After:
extern VALUE cMove;
#ifdef __cplusplus
extern "C" {
#endif
extern void Init_move(VALUE mOsl);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* RBOSL_MOVE_H */
|
// ... existing code ...
extern VALUE cMove;
#ifdef __cplusplus
extern "C" {
// ... rest of the code ...
|
ba171e94f1909e13294d21586c8e8e842924a272
|
Studiportal_Checker/src/de/hfu/studiportal/data/ExamCategory.java
|
Studiportal_Checker/src/de/hfu/studiportal/data/ExamCategory.java
|
package de.hfu.studiportal.data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class ExamCategory implements Serializable {
private static final long serialVersionUID = -5178814560848378523L;
private List<Exam> examList;
private String categoryName;
public ExamCategory(String categoryName) {
this.setCategoryName(categoryName);
this.examList = new ArrayList<>();
}
public String getCategoryName() {
return this.categoryName;
}
public void setCategoryName(String newName) {
this.categoryName = newName.replace(":", "").replace("*", "");
}
public void addExam(Exam e) {
this.examList.add(e);
}
public void removeExam(Exam e) {
this.examList.remove(e);
}
public void removeExam(int index) {
this.examList.remove(index);
}
public int getExamCount() {
return this.examList.size();
}
public Exam getExam(int index) {
return this.examList.get(index);
}
public List<Exam> getAllExams() {
return new ArrayList<>(this.examList);
}
}
|
package de.hfu.studiportal.data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class ExamCategory implements Serializable {
private static final long serialVersionUID = -5178814560848378523L;
private List<Exam> examList;
private String categoryName;
public ExamCategory(String categoryName) {
this.setCategoryName(categoryName);
this.examList = new ArrayList<>();
}
public String getCategoryName() {
return this.categoryName;
}
public void setCategoryName(String newName) {
//Replace long terms with short ones to keep the titles short.
//Replacing only parts of the title will reserve the meaning (even with unknown titles)
this.categoryName = newName.replace(":", "").replace("*", "")
.replace("Module/Teilmodule", "Module").replace("(ECTS) ", "")
.replace("Bestandene Module", "Bestanden").trim();
}
public void addExam(Exam e) {
this.examList.add(e);
}
public void removeExam(Exam e) {
this.examList.remove(e);
}
public void removeExam(int index) {
this.examList.remove(index);
}
public int getExamCount() {
return this.examList.size();
}
public Exam getExam(int index) {
return this.examList.get(index);
}
public List<Exam> getAllExams() {
return new ArrayList<>(this.examList);
}
}
|
Optimize category titles through replacing
|
Optimize category titles through replacing
|
Java
|
mit
|
crysxd/Studiportal-Checker
|
java
|
## Code Before:
package de.hfu.studiportal.data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class ExamCategory implements Serializable {
private static final long serialVersionUID = -5178814560848378523L;
private List<Exam> examList;
private String categoryName;
public ExamCategory(String categoryName) {
this.setCategoryName(categoryName);
this.examList = new ArrayList<>();
}
public String getCategoryName() {
return this.categoryName;
}
public void setCategoryName(String newName) {
this.categoryName = newName.replace(":", "").replace("*", "");
}
public void addExam(Exam e) {
this.examList.add(e);
}
public void removeExam(Exam e) {
this.examList.remove(e);
}
public void removeExam(int index) {
this.examList.remove(index);
}
public int getExamCount() {
return this.examList.size();
}
public Exam getExam(int index) {
return this.examList.get(index);
}
public List<Exam> getAllExams() {
return new ArrayList<>(this.examList);
}
}
## Instruction:
Optimize category titles through replacing
## Code After:
package de.hfu.studiportal.data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class ExamCategory implements Serializable {
private static final long serialVersionUID = -5178814560848378523L;
private List<Exam> examList;
private String categoryName;
public ExamCategory(String categoryName) {
this.setCategoryName(categoryName);
this.examList = new ArrayList<>();
}
public String getCategoryName() {
return this.categoryName;
}
public void setCategoryName(String newName) {
//Replace long terms with short ones to keep the titles short.
//Replacing only parts of the title will reserve the meaning (even with unknown titles)
this.categoryName = newName.replace(":", "").replace("*", "")
.replace("Module/Teilmodule", "Module").replace("(ECTS) ", "")
.replace("Bestandene Module", "Bestanden").trim();
}
public void addExam(Exam e) {
this.examList.add(e);
}
public void removeExam(Exam e) {
this.examList.remove(e);
}
public void removeExam(int index) {
this.examList.remove(index);
}
public int getExamCount() {
return this.examList.size();
}
public Exam getExam(int index) {
return this.examList.get(index);
}
public List<Exam> getAllExams() {
return new ArrayList<>(this.examList);
}
}
|
...
}
public void setCategoryName(String newName) {
//Replace long terms with short ones to keep the titles short.
//Replacing only parts of the title will reserve the meaning (even with unknown titles)
this.categoryName = newName.replace(":", "").replace("*", "")
.replace("Module/Teilmodule", "Module").replace("(ECTS) ", "")
.replace("Bestandene Module", "Bestanden").trim();
}
...
|
d153bc1225a6971bc3dc509dd3934fa15ad69477
|
setup.py
|
setup.py
|
from setuptools import setup
setup(name='tap-awin',
version='0.0.1',
description='Singer.io tap for extracting data from the Affiliate Window API',
author='Onedox',
url='https://onedox.com',
classifiers=['Programming Language :: Python :: 3 :: Only'],
py_modules=['tap_awin'],
install_requires=[
'zeep>=1.4.1',
'singer-python>=1.4.2',
'tzlocal>=1.3',
],
entry_points='''
[console_scripts]
tap-awin=tap_awin:main
''',
packages=['tap_awin'],
package_data = {
'tap_awin/schemas': [
"transactions.json",
"merchants.json",
],
},
include_package_data=True,
)
|
from setuptools import setup
setup(name='tap-awin',
version='0.0.1',
description='Singer.io tap for extracting data from the Affiliate Window API',
author='Onedox',
url='https://github.com/onedox/tap-awin',
download_url = 'https://github.com/onedox/tap-awin/archive/0.0.1.tar.gz',
classifiers=['Programming Language :: Python :: 3 :: Only'],
py_modules=['tap_awin'],
install_requires=[
'zeep>=1.4.1',
'singer-python>=1.4.2',
'tzlocal>=1.3',
],
entry_points='''
[console_scripts]
tap-awin=tap_awin:main
''',
packages=['tap_awin'],
package_data = {
'tap_awin/schemas': [
"transactions.json",
"merchants.json",
],
},
include_package_data=True,
)
|
Prepare for 0.0.1 release to PyPI
|
Prepare for 0.0.1 release to PyPI
|
Python
|
apache-2.0
|
onedox/tap-awin
|
python
|
## Code Before:
from setuptools import setup
setup(name='tap-awin',
version='0.0.1',
description='Singer.io tap for extracting data from the Affiliate Window API',
author='Onedox',
url='https://onedox.com',
classifiers=['Programming Language :: Python :: 3 :: Only'],
py_modules=['tap_awin'],
install_requires=[
'zeep>=1.4.1',
'singer-python>=1.4.2',
'tzlocal>=1.3',
],
entry_points='''
[console_scripts]
tap-awin=tap_awin:main
''',
packages=['tap_awin'],
package_data = {
'tap_awin/schemas': [
"transactions.json",
"merchants.json",
],
},
include_package_data=True,
)
## Instruction:
Prepare for 0.0.1 release to PyPI
## Code After:
from setuptools import setup
setup(name='tap-awin',
version='0.0.1',
description='Singer.io tap for extracting data from the Affiliate Window API',
author='Onedox',
url='https://github.com/onedox/tap-awin',
download_url = 'https://github.com/onedox/tap-awin/archive/0.0.1.tar.gz',
classifiers=['Programming Language :: Python :: 3 :: Only'],
py_modules=['tap_awin'],
install_requires=[
'zeep>=1.4.1',
'singer-python>=1.4.2',
'tzlocal>=1.3',
],
entry_points='''
[console_scripts]
tap-awin=tap_awin:main
''',
packages=['tap_awin'],
package_data = {
'tap_awin/schemas': [
"transactions.json",
"merchants.json",
],
},
include_package_data=True,
)
|
# ... existing code ...
version='0.0.1',
description='Singer.io tap for extracting data from the Affiliate Window API',
author='Onedox',
url='https://github.com/onedox/tap-awin',
download_url = 'https://github.com/onedox/tap-awin/archive/0.0.1.tar.gz',
classifiers=['Programming Language :: Python :: 3 :: Only'],
py_modules=['tap_awin'],
install_requires=[
# ... rest of the code ...
|
0b8b438a0c8b204d05bab41dbe0d493a409cb809
|
examples/flask_example/manage.py
|
examples/flask_example/manage.py
|
from flask.ext.script import Server, Manager, Shell
from flask.ext.evolution import Evolution
from example import app, db, models
evolution = Evolution(app)
manager = Manager(app)
manager.add_command('runserver', Server())
manager.add_command('shell', Shell(make_context=lambda: {
'app': app,
'db': db,
'models': models
}))
@manager.command
def migrate(action):
with app.app_context():
evolution.manager(action)
if __name__ == '__main__':
manager.run()
|
from flask.ext.script import Server, Manager, Shell
from flask.ext.evolution import Evolution
from example import app, db, models
evolution = Evolution(app)
manager = Manager(app)
manager.add_command('runserver', Server())
manager.add_command('shell', Shell(make_context=lambda: {
'app': app,
'db': db,
'models': models
}))
@manager.command
def migrate(action):
# ./manage.py migrate run
with app.app_context():
evolution.manager(action)
if __name__ == '__main__':
manager.run()
|
Comment on how to run migrations
|
Comment on how to run migrations
|
Python
|
bsd-3-clause
|
python-social-auth/social-storage-sqlalchemy,mathspace/python-social-auth,clef/python-social-auth,falcon1kr/python-social-auth,fearlessspider/python-social-auth,imsparsh/python-social-auth,mark-adams/python-social-auth,mathspace/python-social-auth,python-social-auth/social-core,duoduo369/python-social-auth,mark-adams/python-social-auth,VishvajitP/python-social-auth,degs098/python-social-auth,henocdz/python-social-auth,mrwags/python-social-auth,drxos/python-social-auth,merutak/python-social-auth,bjorand/python-social-auth,webjunkie/python-social-auth,joelstanner/python-social-auth,yprez/python-social-auth,lawrence34/python-social-auth,clef/python-social-auth,iruga090/python-social-auth,iruga090/python-social-auth,ariestiyansyah/python-social-auth,rsteca/python-social-auth,mchdks/python-social-auth,barseghyanartur/python-social-auth,daniula/python-social-auth,noodle-learns-programming/python-social-auth,merutak/python-social-auth,degs098/python-social-auth,S01780/python-social-auth,JerzySpendel/python-social-auth,lamby/python-social-auth,san-mate/python-social-auth,DhiaEddineSaidi/python-social-auth,mchdks/python-social-auth,hsr-ba-fs15-dat/python-social-auth,firstjob/python-social-auth,nirmalvp/python-social-auth,frankier/python-social-auth,jneves/python-social-auth,michael-borisov/python-social-auth,jameslittle/python-social-auth,lneoe/python-social-auth,san-mate/python-social-auth,yprez/python-social-auth,S01780/python-social-auth,daniula/python-social-auth,muhammad-ammar/python-social-auth,henocdz/python-social-auth,duoduo369/python-social-auth,ariestiyansyah/python-social-auth,tutumcloud/python-social-auth,ononeor12/python-social-auth,mrwags/python-social-auth,tkajtoch/python-social-auth,nirmalvp/python-social-auth,drxos/python-social-auth,bjorand/python-social-auth,firstjob/python-social-auth,mchdks/python-social-auth,bjorand/python-social-auth,tutumcloud/python-social-auth,san-mate/python-social-auth,msampathkumar/python-social-auth,lneoe/python-social-auth,webjunkie/python-social-auth,jeyraof/python-social-auth,robbiet480/python-social-auth,wildtetris/python-social-auth,rsteca/python-social-auth,michael-borisov/python-social-auth,Andygmb/python-social-auth,degs098/python-social-auth,falcon1kr/python-social-auth,cmichal/python-social-auth,tkajtoch/python-social-auth,contracode/python-social-auth,msampathkumar/python-social-auth,msampathkumar/python-social-auth,jeyraof/python-social-auth,lneoe/python-social-auth,joelstanner/python-social-auth,noodle-learns-programming/python-social-auth,mark-adams/python-social-auth,ByteInternet/python-social-auth,alrusdi/python-social-auth,python-social-auth/social-app-django,Andygmb/python-social-auth,nvbn/python-social-auth,MSOpenTech/python-social-auth,cjltsod/python-social-auth,robbiet480/python-social-auth,JJediny/python-social-auth,barseghyanartur/python-social-auth,ByteInternet/python-social-auth,garrett-schlesinger/python-social-auth,JJediny/python-social-auth,merutak/python-social-auth,henocdz/python-social-auth,imsparsh/python-social-auth,mathspace/python-social-auth,MSOpenTech/python-social-auth,barseghyanartur/python-social-auth,VishvajitP/python-social-auth,python-social-auth/social-docs,drxos/python-social-auth,webjunkie/python-social-auth,frankier/python-social-auth,chandolia/python-social-auth,rsalmaso/python-social-auth,alrusdi/python-social-auth,clef/python-social-auth,python-social-auth/social-core,robbiet480/python-social-auth,firstjob/python-social-auth,fearlessspider/python-social-auth,tkajtoch/python-social-auth,chandolia/python-social-auth,daniula/python-social-auth,rsalmaso/python-social-auth,muhammad-ammar/python-social-auth,noodle-learns-programming/python-social-auth,michael-borisov/python-social-auth,ariestiyansyah/python-social-auth,chandolia/python-social-auth,lamby/python-social-auth,alrusdi/python-social-auth,MSOpenTech/python-social-auth,SeanHayes/python-social-auth,fearlessspider/python-social-auth,Andygmb/python-social-auth,rsteca/python-social-auth,python-social-auth/social-app-cherrypy,iruga090/python-social-auth,jeyraof/python-social-auth,ByteInternet/python-social-auth,VishvajitP/python-social-auth,nirmalvp/python-social-auth,falcon1kr/python-social-auth,wildtetris/python-social-auth,jameslittle/python-social-auth,garrett-schlesinger/python-social-auth,tobias47n9e/social-core,contracode/python-social-auth,hsr-ba-fs15-dat/python-social-auth,JJediny/python-social-auth,jneves/python-social-auth,DhiaEddineSaidi/python-social-auth,lawrence34/python-social-auth,python-social-auth/social-app-django,S01780/python-social-auth,JerzySpendel/python-social-auth,cjltsod/python-social-auth,nvbn/python-social-auth,SeanHayes/python-social-auth,ononeor12/python-social-auth,yprez/python-social-auth,cmichal/python-social-auth,hsr-ba-fs15-dat/python-social-auth,cmichal/python-social-auth,muhammad-ammar/python-social-auth,mrwags/python-social-auth,joelstanner/python-social-auth,wildtetris/python-social-auth,lawrence34/python-social-auth,jneves/python-social-auth,imsparsh/python-social-auth,lamby/python-social-auth,python-social-auth/social-app-django,contracode/python-social-auth,ononeor12/python-social-auth,JerzySpendel/python-social-auth,jameslittle/python-social-auth,DhiaEddineSaidi/python-social-auth
|
python
|
## Code Before:
from flask.ext.script import Server, Manager, Shell
from flask.ext.evolution import Evolution
from example import app, db, models
evolution = Evolution(app)
manager = Manager(app)
manager.add_command('runserver', Server())
manager.add_command('shell', Shell(make_context=lambda: {
'app': app,
'db': db,
'models': models
}))
@manager.command
def migrate(action):
with app.app_context():
evolution.manager(action)
if __name__ == '__main__':
manager.run()
## Instruction:
Comment on how to run migrations
## Code After:
from flask.ext.script import Server, Manager, Shell
from flask.ext.evolution import Evolution
from example import app, db, models
evolution = Evolution(app)
manager = Manager(app)
manager.add_command('runserver', Server())
manager.add_command('shell', Shell(make_context=lambda: {
'app': app,
'db': db,
'models': models
}))
@manager.command
def migrate(action):
# ./manage.py migrate run
with app.app_context():
evolution.manager(action)
if __name__ == '__main__':
manager.run()
|
// ... existing code ...
@manager.command
def migrate(action):
# ./manage.py migrate run
with app.app_context():
evolution.manager(action)
// ... rest of the code ...
|
c9b2a1b593b8a2d8d42ffb99ae0aa704998e4917
|
src/main/java/com/clashsoft/hypercube/util/TextureLoader.java
|
src/main/java/com/clashsoft/hypercube/util/TextureLoader.java
|
package com.clashsoft.hypercube.util;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.scene.paint.Material;
import javafx.scene.paint.PhongMaterial;
import java.io.File;
public final class TextureLoader
{
public static Material material(String domain, String imageSource)
{
final PhongMaterial material = new PhongMaterial(Color.WHITE);
material.setDiffuseMap(load(domain, imageSource));
return material;
}
public static Image load(String domain, String imageSource)
{
try
{
return new Image(domain + File.separator + imageSource + ".png");
}
catch (Exception ex)
{
throw new RuntimeException("Cannot load image: " + domain + "/" + imageSource, ex);
}
}
}
|
package com.clashsoft.hypercube.util;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.scene.paint.Material;
import javafx.scene.paint.PhongMaterial;
public final class TextureLoader
{
public static Material material(String domain, String imageSource)
{
final PhongMaterial material = new PhongMaterial(Color.WHITE);
material.setDiffuseMap(load(domain, imageSource));
return material;
}
public static Image load(String domain, String imageSource)
{
try
{
return new Image(domain + '/' + imageSource + ".png");
}
catch (Exception ex)
{
throw new RuntimeException("Cannot load image: " + domain + "/" + imageSource, ex);
}
}
}
|
Fix Texture Loading on Windows
|
Fix Texture Loading on Windows
- Fixed Textures not being loaded correctly on Windows.
|
Java
|
bsd-3-clause
|
Dyvil/Hypercube
|
java
|
## Code Before:
package com.clashsoft.hypercube.util;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.scene.paint.Material;
import javafx.scene.paint.PhongMaterial;
import java.io.File;
public final class TextureLoader
{
public static Material material(String domain, String imageSource)
{
final PhongMaterial material = new PhongMaterial(Color.WHITE);
material.setDiffuseMap(load(domain, imageSource));
return material;
}
public static Image load(String domain, String imageSource)
{
try
{
return new Image(domain + File.separator + imageSource + ".png");
}
catch (Exception ex)
{
throw new RuntimeException("Cannot load image: " + domain + "/" + imageSource, ex);
}
}
}
## Instruction:
Fix Texture Loading on Windows
- Fixed Textures not being loaded correctly on Windows.
## Code After:
package com.clashsoft.hypercube.util;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.scene.paint.Material;
import javafx.scene.paint.PhongMaterial;
public final class TextureLoader
{
public static Material material(String domain, String imageSource)
{
final PhongMaterial material = new PhongMaterial(Color.WHITE);
material.setDiffuseMap(load(domain, imageSource));
return material;
}
public static Image load(String domain, String imageSource)
{
try
{
return new Image(domain + '/' + imageSource + ".png");
}
catch (Exception ex)
{
throw new RuntimeException("Cannot load image: " + domain + "/" + imageSource, ex);
}
}
}
|
...
import javafx.scene.paint.Color;
import javafx.scene.paint.Material;
import javafx.scene.paint.PhongMaterial;
public final class TextureLoader
{
...
{
try
{
return new Image(domain + '/' + imageSource + ".png");
}
catch (Exception ex)
{
...
|
a42f3c3899a20505f9aebe100aed6db4c91f4002
|
coop_cms/apps/email_auth/urls.py
|
coop_cms/apps/email_auth/urls.py
|
"""urls"""
from __future__ import unicode_literals
from django.conf.urls import include, url
from django.contrib.auth.views import login, password_change, password_reset, password_reset_confirm
from coop_cms.apps.email_auth.forms import BsPasswordChangeForm, BsPasswordResetForm, EmailAuthForm, BsSetPasswordForm
urlpatterns = [
url(
r'^login/$',
login,
{'authentication_form': EmailAuthForm},
name='login'
),
url(r'^password_change/$',
password_change,
{'password_change_form': BsPasswordChangeForm},
name='password_change'
),
url(
r'^password_reset/$',
password_reset,
{'password_reset_form': BsPasswordResetForm},
name='password_reset'
),
url(
r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
password_reset_confirm,
{'set_password_form': BsSetPasswordForm},
name='password_reset_confirm'
),
url(r'^', include('django.contrib.auth.urls')),
]
|
"""urls"""
from __future__ import unicode_literals
from django.conf.urls import include, url
from django.contrib.auth.views import LoginView, PasswordChangeView, PasswordResetView, PasswordResetConfirmView
from coop_cms.apps.email_auth.forms import BsPasswordChangeForm, BsPasswordResetForm, EmailAuthForm, BsSetPasswordForm
urlpatterns = [
url(
r'^login/$',
LoginView.as_view(authentication_form=EmailAuthForm),
name='login'
),
url(r'^password_change/$',
PasswordChangeView.as_view(form_class=BsPasswordChangeForm),
name='password_change'
),
url(
r'^password_reset/$',
PasswordResetView.as_view(form_class=BsPasswordResetForm),
name='password_reset'
),
url(
r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
PasswordResetConfirmView.as_view(form_class=BsSetPasswordForm),
name='password_reset_confirm'
),
url(r'^', include('django.contrib.auth.urls')),
]
|
Fix auth views : use class-based views
|
Fix auth views : use class-based views
|
Python
|
bsd-3-clause
|
ljean/coop_cms,ljean/coop_cms,ljean/coop_cms
|
python
|
## Code Before:
"""urls"""
from __future__ import unicode_literals
from django.conf.urls import include, url
from django.contrib.auth.views import login, password_change, password_reset, password_reset_confirm
from coop_cms.apps.email_auth.forms import BsPasswordChangeForm, BsPasswordResetForm, EmailAuthForm, BsSetPasswordForm
urlpatterns = [
url(
r'^login/$',
login,
{'authentication_form': EmailAuthForm},
name='login'
),
url(r'^password_change/$',
password_change,
{'password_change_form': BsPasswordChangeForm},
name='password_change'
),
url(
r'^password_reset/$',
password_reset,
{'password_reset_form': BsPasswordResetForm},
name='password_reset'
),
url(
r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
password_reset_confirm,
{'set_password_form': BsSetPasswordForm},
name='password_reset_confirm'
),
url(r'^', include('django.contrib.auth.urls')),
]
## Instruction:
Fix auth views : use class-based views
## Code After:
"""urls"""
from __future__ import unicode_literals
from django.conf.urls import include, url
from django.contrib.auth.views import LoginView, PasswordChangeView, PasswordResetView, PasswordResetConfirmView
from coop_cms.apps.email_auth.forms import BsPasswordChangeForm, BsPasswordResetForm, EmailAuthForm, BsSetPasswordForm
urlpatterns = [
url(
r'^login/$',
LoginView.as_view(authentication_form=EmailAuthForm),
name='login'
),
url(r'^password_change/$',
PasswordChangeView.as_view(form_class=BsPasswordChangeForm),
name='password_change'
),
url(
r'^password_reset/$',
PasswordResetView.as_view(form_class=BsPasswordResetForm),
name='password_reset'
),
url(
r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
PasswordResetConfirmView.as_view(form_class=BsSetPasswordForm),
name='password_reset_confirm'
),
url(r'^', include('django.contrib.auth.urls')),
]
|
# ... existing code ...
from __future__ import unicode_literals
from django.conf.urls import include, url
from django.contrib.auth.views import LoginView, PasswordChangeView, PasswordResetView, PasswordResetConfirmView
from coop_cms.apps.email_auth.forms import BsPasswordChangeForm, BsPasswordResetForm, EmailAuthForm, BsSetPasswordForm
# ... modified code ...
urlpatterns = [
url(
r'^login/$',
LoginView.as_view(authentication_form=EmailAuthForm),
name='login'
),
url(r'^password_change/$',
PasswordChangeView.as_view(form_class=BsPasswordChangeForm),
name='password_change'
),
url(
r'^password_reset/$',
PasswordResetView.as_view(form_class=BsPasswordResetForm),
name='password_reset'
),
url(
r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
PasswordResetConfirmView.as_view(form_class=BsSetPasswordForm),
name='password_reset_confirm'
),
url(r'^', include('django.contrib.auth.urls')),
# ... rest of the code ...
|
105f3ccbaf160b9401c4db1c10be78fff91e0fa8
|
src/main/java/net/opentsdb/contrib/tsquare/support/DataPointsAsDoubles.java
|
src/main/java/net/opentsdb/contrib/tsquare/support/DataPointsAsDoubles.java
|
/*
* Copyright (C) 2013 Conductor, 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.
*/
package net.opentsdb.contrib.tsquare.support;
import java.util.Iterator;
import net.opentsdb.core.Aggregator.Doubles;
import net.opentsdb.core.DataPoint;
import net.opentsdb.core.DataPoints;
/**
* Wraps a {@link DataPoints} object and exposes the data consistent
* with the {@link Doubles} interface.
*
* @author James Royalty (jroyalty) <i>[Jul 12, 2013]</i>
*/
public class DataPointsAsDoubles implements Doubles {
private final Iterator<DataPoint> iterator;
public DataPointsAsDoubles(final DataPoints points) {
this.iterator = points.iterator();
}
@Override
public boolean hasNextValue() {
return iterator.hasNext();
}
@Override
public double nextDoubleValue() {
return iterator.next().toDouble();
}
}
|
/*
* Copyright (C) 2013 Conductor, 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.
*/
package net.opentsdb.contrib.tsquare.support;
import java.util.Iterator;
import net.opentsdb.core.Aggregator.Doubles;
import net.opentsdb.core.DataPoint;
import net.opentsdb.core.DataPoints;
/**
* Wraps a {@link DataPoints} object and exposes the data consistent
* with the {@link Doubles} interface.
*
* @author James Royalty (jroyalty) <i>[Jul 12, 2013]</i>
*/
public class DataPointsAsDoubles implements Doubles {
private final Iterator<DataPoint> iterator;
public DataPointsAsDoubles(final DataPoints points) {
this.iterator = points.iterator();
}
@Override
public boolean hasNextValue() {
return iterator.hasNext();
}
@Override
public double nextDoubleValue() {
final DataPoint point = iterator.next();
return TsWebUtils.asDouble(point);
}
}
|
Use conversion methods in utils class.
|
Use conversion methods in utils class.
|
Java
|
apache-2.0
|
Conductor/tsquare
|
java
|
## Code Before:
/*
* Copyright (C) 2013 Conductor, 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.
*/
package net.opentsdb.contrib.tsquare.support;
import java.util.Iterator;
import net.opentsdb.core.Aggregator.Doubles;
import net.opentsdb.core.DataPoint;
import net.opentsdb.core.DataPoints;
/**
* Wraps a {@link DataPoints} object and exposes the data consistent
* with the {@link Doubles} interface.
*
* @author James Royalty (jroyalty) <i>[Jul 12, 2013]</i>
*/
public class DataPointsAsDoubles implements Doubles {
private final Iterator<DataPoint> iterator;
public DataPointsAsDoubles(final DataPoints points) {
this.iterator = points.iterator();
}
@Override
public boolean hasNextValue() {
return iterator.hasNext();
}
@Override
public double nextDoubleValue() {
return iterator.next().toDouble();
}
}
## Instruction:
Use conversion methods in utils class.
## Code After:
/*
* Copyright (C) 2013 Conductor, 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.
*/
package net.opentsdb.contrib.tsquare.support;
import java.util.Iterator;
import net.opentsdb.core.Aggregator.Doubles;
import net.opentsdb.core.DataPoint;
import net.opentsdb.core.DataPoints;
/**
* Wraps a {@link DataPoints} object and exposes the data consistent
* with the {@link Doubles} interface.
*
* @author James Royalty (jroyalty) <i>[Jul 12, 2013]</i>
*/
public class DataPointsAsDoubles implements Doubles {
private final Iterator<DataPoint> iterator;
public DataPointsAsDoubles(final DataPoints points) {
this.iterator = points.iterator();
}
@Override
public boolean hasNextValue() {
return iterator.hasNext();
}
@Override
public double nextDoubleValue() {
final DataPoint point = iterator.next();
return TsWebUtils.asDouble(point);
}
}
|
...
@Override
public double nextDoubleValue() {
final DataPoint point = iterator.next();
return TsWebUtils.asDouble(point);
}
}
...
|
80bb3a25b0425b4caa6a5ee3836c8425da75665d
|
src/main/java/org/spacehq/mc/protocol/packet/ingame/server/entity/ServerEntityHeadLookPacket.java
|
src/main/java/org/spacehq/mc/protocol/packet/ingame/server/entity/ServerEntityHeadLookPacket.java
|
package org.spacehq.mc.protocol.packet.ingame.server.entity;
import org.spacehq.packetlib.io.NetInput;
import org.spacehq.packetlib.io.NetOutput;
import org.spacehq.packetlib.packet.Packet;
import java.io.IOException;
public class ServerEntityHeadLookPacket implements Packet {
protected int entityId;
protected float headYaw;
@SuppressWarnings("unused")
private ServerEntityHeadLookPacket() {
}
public ServerEntityHeadLookPacket(int entityId, float headYaw) {
this.entityId = entityId;
this.headYaw = headYaw;
}
public int getEntityId() {
return this.entityId;
}
public float getHeadYaw() {
return this.headYaw;
}
@Override
public void read(NetInput in) throws IOException {
this.entityId = in.readVarInt();
this.headYaw = in.readByte() * 360 / 256f;
}
@Override
public void write(NetOutput out) throws IOException {
out.writeVarInt(this.entityId);
out.writeByte((byte) (this.headYaw * 256 / 360));
}
@Override
public boolean isPriority() {
return false;
}
}
|
package org.spacehq.mc.protocol.packet.ingame.server.entity;
import org.spacehq.packetlib.io.NetInput;
import org.spacehq.packetlib.io.NetOutput;
import org.spacehq.packetlib.packet.Packet;
import java.io.IOException;
public class ServerEntityHeadLookPacket implements Packet {
private int entityId;
private float headYaw;
@SuppressWarnings("unused")
private ServerEntityHeadLookPacket() {
}
public ServerEntityHeadLookPacket(int entityId, float headYaw) {
this.entityId = entityId;
this.headYaw = headYaw;
}
public int getEntityId() {
return this.entityId;
}
public float getHeadYaw() {
return this.headYaw;
}
@Override
public void read(NetInput in) throws IOException {
this.entityId = in.readVarInt();
this.headYaw = in.readByte() * 360 / 256f;
}
@Override
public void write(NetOutput out) throws IOException {
out.writeVarInt(this.entityId);
out.writeByte((byte) (this.headYaw * 256 / 360));
}
@Override
public boolean isPriority() {
return false;
}
}
|
Fix visibility in head look packet.
|
Fix visibility in head look packet.
|
Java
|
mit
|
Steveice10/MCProtocolLib,HexogenDev/MCProtocolLib,kukrimate/MCProtocolLib,xDiP/MCProtocolLib,ReplayMod/MCProtocolLib,MCGamerNetwork/MCProtocolLib,Johni0702/MCProtocolLib
|
java
|
## Code Before:
package org.spacehq.mc.protocol.packet.ingame.server.entity;
import org.spacehq.packetlib.io.NetInput;
import org.spacehq.packetlib.io.NetOutput;
import org.spacehq.packetlib.packet.Packet;
import java.io.IOException;
public class ServerEntityHeadLookPacket implements Packet {
protected int entityId;
protected float headYaw;
@SuppressWarnings("unused")
private ServerEntityHeadLookPacket() {
}
public ServerEntityHeadLookPacket(int entityId, float headYaw) {
this.entityId = entityId;
this.headYaw = headYaw;
}
public int getEntityId() {
return this.entityId;
}
public float getHeadYaw() {
return this.headYaw;
}
@Override
public void read(NetInput in) throws IOException {
this.entityId = in.readVarInt();
this.headYaw = in.readByte() * 360 / 256f;
}
@Override
public void write(NetOutput out) throws IOException {
out.writeVarInt(this.entityId);
out.writeByte((byte) (this.headYaw * 256 / 360));
}
@Override
public boolean isPriority() {
return false;
}
}
## Instruction:
Fix visibility in head look packet.
## Code After:
package org.spacehq.mc.protocol.packet.ingame.server.entity;
import org.spacehq.packetlib.io.NetInput;
import org.spacehq.packetlib.io.NetOutput;
import org.spacehq.packetlib.packet.Packet;
import java.io.IOException;
public class ServerEntityHeadLookPacket implements Packet {
private int entityId;
private float headYaw;
@SuppressWarnings("unused")
private ServerEntityHeadLookPacket() {
}
public ServerEntityHeadLookPacket(int entityId, float headYaw) {
this.entityId = entityId;
this.headYaw = headYaw;
}
public int getEntityId() {
return this.entityId;
}
public float getHeadYaw() {
return this.headYaw;
}
@Override
public void read(NetInput in) throws IOException {
this.entityId = in.readVarInt();
this.headYaw = in.readByte() * 360 / 256f;
}
@Override
public void write(NetOutput out) throws IOException {
out.writeVarInt(this.entityId);
out.writeByte((byte) (this.headYaw * 256 / 360));
}
@Override
public boolean isPriority() {
return false;
}
}
|
// ... existing code ...
public class ServerEntityHeadLookPacket implements Packet {
private int entityId;
private float headYaw;
@SuppressWarnings("unused")
private ServerEntityHeadLookPacket() {
// ... rest of the code ...
|
0793f8dcb6ed27832e7d0adfb920d9c70813f3c7
|
tasks.py
|
tasks.py
|
from invoke import task, run
@task
def clean():
run("rm -rf .coverage dist build")
@task(clean, default=True)
def test():
run("py.test")
@task(test)
def install():
run("pandoc --from=markdown --to=rst README.md -o README.rst")
run("python setup.py develop")
@task(test)
def release():
run("pandoc --from=markdown --to=rst README.md -o README.rst")
run("python setup.py register sdist bdist_wheel")
run("twine upload dist/*")
@task(test)
def bump(version="patch"):
run("bumpversion %s" % version)
run("git commit --amend")
|
from invoke import task
@task
def clean(context):
context.run("rm -rf .coverage dist build")
@task(clean, default=True)
def test(context):
context.run("py.test")
@task(test)
def install(context):
context.run("pandoc --from=markdown --to=rst README.md -o README.rst")
context.run("python setup.py develop")
@task(test)
def release(context):
context.run("pandoc --from=markdown --to=rst README.md -o README.rst")
context.run("python setup.py register sdist bdist_wheel")
context.run("twine upload dist/*")
@task(test)
def bump(context, version="patch"):
context.run("bumpversion %s" % version)
context.run("git commit --amend")
|
Use new invoke's context parameter
|
Use new invoke's context parameter
|
Python
|
apache-2.0
|
miso-belica/sumy,miso-belica/sumy
|
python
|
## Code Before:
from invoke import task, run
@task
def clean():
run("rm -rf .coverage dist build")
@task(clean, default=True)
def test():
run("py.test")
@task(test)
def install():
run("pandoc --from=markdown --to=rst README.md -o README.rst")
run("python setup.py develop")
@task(test)
def release():
run("pandoc --from=markdown --to=rst README.md -o README.rst")
run("python setup.py register sdist bdist_wheel")
run("twine upload dist/*")
@task(test)
def bump(version="patch"):
run("bumpversion %s" % version)
run("git commit --amend")
## Instruction:
Use new invoke's context parameter
## Code After:
from invoke import task
@task
def clean(context):
context.run("rm -rf .coverage dist build")
@task(clean, default=True)
def test(context):
context.run("py.test")
@task(test)
def install(context):
context.run("pandoc --from=markdown --to=rst README.md -o README.rst")
context.run("python setup.py develop")
@task(test)
def release(context):
context.run("pandoc --from=markdown --to=rst README.md -o README.rst")
context.run("python setup.py register sdist bdist_wheel")
context.run("twine upload dist/*")
@task(test)
def bump(context, version="patch"):
context.run("bumpversion %s" % version)
context.run("git commit --amend")
|
...
from invoke import task
@task
def clean(context):
context.run("rm -rf .coverage dist build")
@task(clean, default=True)
def test(context):
context.run("py.test")
@task(test)
def install(context):
context.run("pandoc --from=markdown --to=rst README.md -o README.rst")
context.run("python setup.py develop")
@task(test)
def release(context):
context.run("pandoc --from=markdown --to=rst README.md -o README.rst")
context.run("python setup.py register sdist bdist_wheel")
context.run("twine upload dist/*")
@task(test)
def bump(context, version="patch"):
context.run("bumpversion %s" % version)
context.run("git commit --amend")
...
|
ff4b34cda7c0b5bc516d9f9e3689818000301336
|
tests/test_planner.py
|
tests/test_planner.py
|
import cutplanner
import unittest
class TestPlanner(unittest.TestCase):
def setUp(self):
sizes = [80, 120]
needed = [10, 25, 75]
loss = 0.25
self.planner = cutplanner.Planner(sizes, needed, loss)
def test_get_largest(self):
largest = self.planner.get_largest_stock()
self.assertEqual(largest, 120)
if __name__ == '__main__':
unittest.main()
|
import cutplanner
import unittest
class TestPlanner(unittest.TestCase):
def setUp(self):
sizes = [80, 120]
needed = [10, 25, 75]
loss = 0.25
self.planner = cutplanner.Planner(sizes, needed, loss)
def test_largest_stock(self):
largest = self.planner.largest_stock
self.assertEqual(largest, 120)
if __name__ == '__main__':
unittest.main()
|
Update test for largest stock
|
Update test for largest stock
|
Python
|
mit
|
alanc10n/py-cutplanner
|
python
|
## Code Before:
import cutplanner
import unittest
class TestPlanner(unittest.TestCase):
def setUp(self):
sizes = [80, 120]
needed = [10, 25, 75]
loss = 0.25
self.planner = cutplanner.Planner(sizes, needed, loss)
def test_get_largest(self):
largest = self.planner.get_largest_stock()
self.assertEqual(largest, 120)
if __name__ == '__main__':
unittest.main()
## Instruction:
Update test for largest stock
## Code After:
import cutplanner
import unittest
class TestPlanner(unittest.TestCase):
def setUp(self):
sizes = [80, 120]
needed = [10, 25, 75]
loss = 0.25
self.planner = cutplanner.Planner(sizes, needed, loss)
def test_largest_stock(self):
largest = self.planner.largest_stock
self.assertEqual(largest, 120)
if __name__ == '__main__':
unittest.main()
|
// ... existing code ...
loss = 0.25
self.planner = cutplanner.Planner(sizes, needed, loss)
def test_largest_stock(self):
largest = self.planner.largest_stock
self.assertEqual(largest, 120)
if __name__ == '__main__':
// ... rest of the code ...
|
ddb3665a1450e8a1eeee57bbe4b5c0eb7f3f05b1
|
molly/utils/management/commands/generate_cache_manifest.py
|
molly/utils/management/commands/generate_cache_manifest.py
|
import os
import os.path
from django.core.management.base import NoArgsCommand
from django.conf import settings
class Command(NoArgsCommand):
can_import_settings = True
def handle_noargs(self, **options):
cache_manifest_path = os.path.join(settings.STATIC_ROOT,
'cache.manifest')
static_prefix_length = len(settings.STATIC_ROOT.split(os.sep))
with open(cache_manifest_path, 'w') as cache_manifest:
print >>cache_manifest, "CACHE MANIFEST"
print >>cache_manifest, "CACHE:"
for root, dirs, files in os.walk(settings.STATIC_ROOT):
if root == settings.STATIC_ROOT:
# Don't cache admin media, desktop or markers
dirs.remove('admin')
dirs.remove('desktop')
dirs.remove('markers')
url = '/'.join(root.split(os.sep)[static_prefix_length:])
for file in files:
# Don't cache uncompressed JS/CSS
_, ext = os.path.splitext(file)
if ext in ('.js','.css') and 'c' != url.split('/')[0]:
continue
print >>cache_manifest, "%s%s/%s" % (settings.STATIC_URL, url, file)
|
import os
import os.path
from django.core.management.base import NoArgsCommand
from django.conf import settings
class Command(NoArgsCommand):
can_import_settings = True
def handle_noargs(self, **options):
cache_manifest_path = os.path.join(settings.STATIC_ROOT,
'cache.manifest')
static_prefix_length = len(settings.STATIC_ROOT.split(os.sep))
with open(cache_manifest_path, 'w') as cache_manifest:
print >>cache_manifest, "CACHE MANIFEST"
print >>cache_manifest, "CACHE:"
for root, dirs, files in os.walk(settings.STATIC_ROOT):
if root == settings.STATIC_ROOT:
# Don't cache admin media, desktop or markers
if 'admin' in dirs: dirs.remove('admin')
if 'desktop' in dirs: dirs.remove('desktop')
if 'markers' in dirs: dirs.remove('markers')
if root == os.path.join(setting.STATIC_ROOT, 'touchmaplite', 'images'):
# Don't cache touchmaplite markers, we don't use them
if 'markers' in dirs: dirs.remove('markers')
if 'iui' in dirs: dirs.remove('iui')
url = '/'.join(root.split(os.sep)[static_prefix_length:])
for file in files:
# Don't cache uncompressed JS/CSS
_, ext = os.path.splitext(file)
if ext in ('.js','.css') and 'c' != url.split('/')[0]:
continue
# Don't cache ourselves!
print >>cache_manifest, "%s%s/%s" % (settings.STATIC_URL, url, file)
|
Fix cache.manifest generation when desktop app isn't loaded, also don't include unnecessary touchmaplite files (MOLLY-113)
|
Fix cache.manifest generation when desktop app isn't loaded, also don't include unnecessary touchmaplite files (MOLLY-113)
|
Python
|
apache-2.0
|
mollyproject/mollyproject,mollyproject/mollyproject,mollyproject/mollyproject
|
python
|
## Code Before:
import os
import os.path
from django.core.management.base import NoArgsCommand
from django.conf import settings
class Command(NoArgsCommand):
can_import_settings = True
def handle_noargs(self, **options):
cache_manifest_path = os.path.join(settings.STATIC_ROOT,
'cache.manifest')
static_prefix_length = len(settings.STATIC_ROOT.split(os.sep))
with open(cache_manifest_path, 'w') as cache_manifest:
print >>cache_manifest, "CACHE MANIFEST"
print >>cache_manifest, "CACHE:"
for root, dirs, files in os.walk(settings.STATIC_ROOT):
if root == settings.STATIC_ROOT:
# Don't cache admin media, desktop or markers
dirs.remove('admin')
dirs.remove('desktop')
dirs.remove('markers')
url = '/'.join(root.split(os.sep)[static_prefix_length:])
for file in files:
# Don't cache uncompressed JS/CSS
_, ext = os.path.splitext(file)
if ext in ('.js','.css') and 'c' != url.split('/')[0]:
continue
print >>cache_manifest, "%s%s/%s" % (settings.STATIC_URL, url, file)
## Instruction:
Fix cache.manifest generation when desktop app isn't loaded, also don't include unnecessary touchmaplite files (MOLLY-113)
## Code After:
import os
import os.path
from django.core.management.base import NoArgsCommand
from django.conf import settings
class Command(NoArgsCommand):
can_import_settings = True
def handle_noargs(self, **options):
cache_manifest_path = os.path.join(settings.STATIC_ROOT,
'cache.manifest')
static_prefix_length = len(settings.STATIC_ROOT.split(os.sep))
with open(cache_manifest_path, 'w') as cache_manifest:
print >>cache_manifest, "CACHE MANIFEST"
print >>cache_manifest, "CACHE:"
for root, dirs, files in os.walk(settings.STATIC_ROOT):
if root == settings.STATIC_ROOT:
# Don't cache admin media, desktop or markers
if 'admin' in dirs: dirs.remove('admin')
if 'desktop' in dirs: dirs.remove('desktop')
if 'markers' in dirs: dirs.remove('markers')
if root == os.path.join(setting.STATIC_ROOT, 'touchmaplite', 'images'):
# Don't cache touchmaplite markers, we don't use them
if 'markers' in dirs: dirs.remove('markers')
if 'iui' in dirs: dirs.remove('iui')
url = '/'.join(root.split(os.sep)[static_prefix_length:])
for file in files:
# Don't cache uncompressed JS/CSS
_, ext = os.path.splitext(file)
if ext in ('.js','.css') and 'c' != url.split('/')[0]:
continue
# Don't cache ourselves!
print >>cache_manifest, "%s%s/%s" % (settings.STATIC_URL, url, file)
|
# ... existing code ...
for root, dirs, files in os.walk(settings.STATIC_ROOT):
if root == settings.STATIC_ROOT:
# Don't cache admin media, desktop or markers
if 'admin' in dirs: dirs.remove('admin')
if 'desktop' in dirs: dirs.remove('desktop')
if 'markers' in dirs: dirs.remove('markers')
if root == os.path.join(setting.STATIC_ROOT, 'touchmaplite', 'images'):
# Don't cache touchmaplite markers, we don't use them
if 'markers' in dirs: dirs.remove('markers')
if 'iui' in dirs: dirs.remove('iui')
url = '/'.join(root.split(os.sep)[static_prefix_length:])
for file in files:
# Don't cache uncompressed JS/CSS
# ... modified code ...
_, ext = os.path.splitext(file)
if ext in ('.js','.css') and 'c' != url.split('/')[0]:
continue
# Don't cache ourselves!
print >>cache_manifest, "%s%s/%s" % (settings.STATIC_URL, url, file)
# ... rest of the code ...
|
c0c7222f4ab1c39dadd78c9bde40d882780ce741
|
benchexec/tools/legion.py
|
benchexec/tools/legion.py
|
import benchexec.result as result
import benchexec.util as util
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool):
"""
Tool info for Legion (https://github.com/Alan32Liu/Principes).
"""
REQUIRED_PATHS = [
"legion-sv",
"Legion.py",
"__VERIFIER.c",
"__trace_jump.s",
"tracejump.py",
"lib",
]
def executable(self):
return util.find_executable("legion-sv")
def version(self, executable):
return self._version_from_tool(executable)
def name(self):
return "Legion"
|
import benchexec.result as result
import benchexec.util as util
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool):
"""
Tool info for Legion (https://github.com/Alan32Liu/Principes).
"""
REQUIRED_PATHS = [
"legion-sv",
"Legion.py",
"__VERIFIER.c",
"__VERIFIER_assume.c",
"__VERIFIER_assume.instr.s",
"__trace_jump.s",
"__trace_buffered.c",
"tracejump.py",
"lib",
]
def executable(self):
return util.find_executable("legion-sv")
def version(self, executable):
return self._version_from_tool(executable)
def name(self):
return "Legion"
|
Add some files to Legion
|
Add some files to Legion
|
Python
|
apache-2.0
|
ultimate-pa/benchexec,dbeyer/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,sosy-lab/benchexec,dbeyer/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec
|
python
|
## Code Before:
import benchexec.result as result
import benchexec.util as util
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool):
"""
Tool info for Legion (https://github.com/Alan32Liu/Principes).
"""
REQUIRED_PATHS = [
"legion-sv",
"Legion.py",
"__VERIFIER.c",
"__trace_jump.s",
"tracejump.py",
"lib",
]
def executable(self):
return util.find_executable("legion-sv")
def version(self, executable):
return self._version_from_tool(executable)
def name(self):
return "Legion"
## Instruction:
Add some files to Legion
## Code After:
import benchexec.result as result
import benchexec.util as util
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool):
"""
Tool info for Legion (https://github.com/Alan32Liu/Principes).
"""
REQUIRED_PATHS = [
"legion-sv",
"Legion.py",
"__VERIFIER.c",
"__VERIFIER_assume.c",
"__VERIFIER_assume.instr.s",
"__trace_jump.s",
"__trace_buffered.c",
"tracejump.py",
"lib",
]
def executable(self):
return util.find_executable("legion-sv")
def version(self, executable):
return self._version_from_tool(executable)
def name(self):
return "Legion"
|
// ... existing code ...
"legion-sv",
"Legion.py",
"__VERIFIER.c",
"__VERIFIER_assume.c",
"__VERIFIER_assume.instr.s",
"__trace_jump.s",
"__trace_buffered.c",
"tracejump.py",
"lib",
]
// ... rest of the code ...
|
7b77297f9099019f4424c7115deb933dd51eaf80
|
setup.py
|
setup.py
|
from distutils.core import setup, Extension
setup(
name = 'Encoder',
version = '1.0',
description = 'Encode stuff',
ext_modules = [
Extension(
name = '_encoder',
sources = [
'src/encoder.c',
'src/module.c',
],
include_dirs = [
'include',
],
),
],
)
|
from distutils.core import setup, Extension
setup(
name = 'Encoder',
version = '1.0',
description = 'Encode stuff',
ext_modules = [
Extension(
name = '_encoder',
sources = [
'src/encoder.c',
'src/module.c',
],
include_dirs = [
'include',
],
depends = [
'include/buffer.h', # As this is essentially a source file
],
),
],
)
|
Include buffer.h as a dependency for rebuilds
|
Include buffer.h as a dependency for rebuilds
|
Python
|
apache-2.0
|
blake-sheridan/py-serializer,blake-sheridan/py-serializer
|
python
|
## Code Before:
from distutils.core import setup, Extension
setup(
name = 'Encoder',
version = '1.0',
description = 'Encode stuff',
ext_modules = [
Extension(
name = '_encoder',
sources = [
'src/encoder.c',
'src/module.c',
],
include_dirs = [
'include',
],
),
],
)
## Instruction:
Include buffer.h as a dependency for rebuilds
## Code After:
from distutils.core import setup, Extension
setup(
name = 'Encoder',
version = '1.0',
description = 'Encode stuff',
ext_modules = [
Extension(
name = '_encoder',
sources = [
'src/encoder.c',
'src/module.c',
],
include_dirs = [
'include',
],
depends = [
'include/buffer.h', # As this is essentially a source file
],
),
],
)
|
...
include_dirs = [
'include',
],
depends = [
'include/buffer.h', # As this is essentially a source file
],
),
],
)
...
|
925b24a73ccc90fbdb0dc99d6484baf882d221fd
|
src/main/java/EvenElement.java
|
src/main/java/EvenElement.java
|
/**
* Copyright (c) 2012 by Tyson Gern
* Licensed under the MIT License
*/
import java.util.*;
/**
* This class stores an element of a Coxeter group of rank "rank" as a
* signed permutation, oneLine. The methods contained in this class
* can preform elementary operations on the element.
* @author Tyson Gern ([email protected])
*/
abstract class EvenElement extends Element {
}
|
/**
* Copyright (c) 2012 by Tyson Gern
* Licensed under the MIT License
*/
import java.util.*;
/**
* This class stores an element of a Coxeter group of rank "rank" as a
* signed permutation, oneLine. The methods contained in this class
* can preform elementary operations on the element.
* @author Tyson Gern ([email protected])
*/
abstract class EvenElement extends Element {
protected int countNeg() {
int count = 0;
for (int i = 1; i <= size; i++) {
if (mapsto(i) < 0) count ++;
}
return count;
}
}
|
Add sign counting for future use in type B length function.
|
Add sign counting for future use in type B length function.
|
Java
|
mit
|
tygern/BuildDomino
|
java
|
## Code Before:
/**
* Copyright (c) 2012 by Tyson Gern
* Licensed under the MIT License
*/
import java.util.*;
/**
* This class stores an element of a Coxeter group of rank "rank" as a
* signed permutation, oneLine. The methods contained in this class
* can preform elementary operations on the element.
* @author Tyson Gern ([email protected])
*/
abstract class EvenElement extends Element {
}
## Instruction:
Add sign counting for future use in type B length function.
## Code After:
/**
* Copyright (c) 2012 by Tyson Gern
* Licensed under the MIT License
*/
import java.util.*;
/**
* This class stores an element of a Coxeter group of rank "rank" as a
* signed permutation, oneLine. The methods contained in this class
* can preform elementary operations on the element.
* @author Tyson Gern ([email protected])
*/
abstract class EvenElement extends Element {
protected int countNeg() {
int count = 0;
for (int i = 1; i <= size; i++) {
if (mapsto(i) < 0) count ++;
}
return count;
}
}
|
# ... existing code ...
*/
abstract class EvenElement extends Element {
protected int countNeg() {
int count = 0;
for (int i = 1; i <= size; i++) {
if (mapsto(i) < 0) count ++;
}
return count;
}
}
# ... rest of the code ...
|
828e75919bd71912baf75a64010efcfcd93d07f1
|
library_magic.py
|
library_magic.py
|
import sys
import subprocess
import shutil
executable = sys.argv[1]
execfolder = sys.argv[1].rsplit("/",1)[0]
libdir = execfolder+"/lib"
otool_cmd = ["otool", "-L",executable]
# Run otool
otool_out = subprocess.check_output(otool_cmd).split("\n\t")
# Find all the dylib files
for l in otool_out:
s = l.split(".dylib")
if len(s) > 1:
lib = s[0]+".dylib"
libname = lib.rsplit("/",1)[1]
shutil.copyfile(lib, libdir+"/"+libname)
install_name_tool = ["install_name_tool", "-change", lib, "@executable_path/lib/"+libname, executable]
subprocess.call(install_name_tool)
|
import sys
import subprocess
import shutil
copied = []
def update_libraries(executable):
# Find all the dylib files and recursively add dependencies
print "\nChecking dependencies of " + executable
otool_cmd = ["otool", "-L",executable]
execfolder = executable.rsplit("/",1)[0]
otool_out = subprocess.check_output(otool_cmd).split("\n\t")
execname = executable.rsplit("/",1)[1]
for l in otool_out:
s = l.split(".dylib")
if len(s) > 1:
lib = s[0]+".dylib"
libname = lib.rsplit("/",1)[1]
if libname not in copied:
print "Requires: " + lib
new_lib = execfolder+"/"+libname
if (lib != new_lib):
shutil.copyfile(lib, new_lib)
copied.append(libname)
install_name_tool = ["install_name_tool", "-change", lib, "./"+libname, executable]
print "Installing "+lib
subprocess.call(install_name_tool)
new_library = execfolder+"/"+libname
print "Calling on " + new_library
update_libraries(new_library)
# Update libraries on the default executable
update_libraries(sys.argv[1])
|
Update library magic to be recursive
|
Update library magic to be recursive
|
Python
|
bsd-3-clause
|
baubie/SpikeDB,baubie/SpikeDB,baubie/SpikeDB,baubie/SpikeDB
|
python
|
## Code Before:
import sys
import subprocess
import shutil
executable = sys.argv[1]
execfolder = sys.argv[1].rsplit("/",1)[0]
libdir = execfolder+"/lib"
otool_cmd = ["otool", "-L",executable]
# Run otool
otool_out = subprocess.check_output(otool_cmd).split("\n\t")
# Find all the dylib files
for l in otool_out:
s = l.split(".dylib")
if len(s) > 1:
lib = s[0]+".dylib"
libname = lib.rsplit("/",1)[1]
shutil.copyfile(lib, libdir+"/"+libname)
install_name_tool = ["install_name_tool", "-change", lib, "@executable_path/lib/"+libname, executable]
subprocess.call(install_name_tool)
## Instruction:
Update library magic to be recursive
## Code After:
import sys
import subprocess
import shutil
copied = []
def update_libraries(executable):
# Find all the dylib files and recursively add dependencies
print "\nChecking dependencies of " + executable
otool_cmd = ["otool", "-L",executable]
execfolder = executable.rsplit("/",1)[0]
otool_out = subprocess.check_output(otool_cmd).split("\n\t")
execname = executable.rsplit("/",1)[1]
for l in otool_out:
s = l.split(".dylib")
if len(s) > 1:
lib = s[0]+".dylib"
libname = lib.rsplit("/",1)[1]
if libname not in copied:
print "Requires: " + lib
new_lib = execfolder+"/"+libname
if (lib != new_lib):
shutil.copyfile(lib, new_lib)
copied.append(libname)
install_name_tool = ["install_name_tool", "-change", lib, "./"+libname, executable]
print "Installing "+lib
subprocess.call(install_name_tool)
new_library = execfolder+"/"+libname
print "Calling on " + new_library
update_libraries(new_library)
# Update libraries on the default executable
update_libraries(sys.argv[1])
|
# ... existing code ...
import subprocess
import shutil
copied = []
def update_libraries(executable):
# Find all the dylib files and recursively add dependencies
print "\nChecking dependencies of " + executable
otool_cmd = ["otool", "-L",executable]
execfolder = executable.rsplit("/",1)[0]
otool_out = subprocess.check_output(otool_cmd).split("\n\t")
execname = executable.rsplit("/",1)[1]
for l in otool_out:
s = l.split(".dylib")
if len(s) > 1:
lib = s[0]+".dylib"
libname = lib.rsplit("/",1)[1]
if libname not in copied:
print "Requires: " + lib
new_lib = execfolder+"/"+libname
if (lib != new_lib):
shutil.copyfile(lib, new_lib)
copied.append(libname)
install_name_tool = ["install_name_tool", "-change", lib, "./"+libname, executable]
print "Installing "+lib
subprocess.call(install_name_tool)
new_library = execfolder+"/"+libname
print "Calling on " + new_library
update_libraries(new_library)
# Update libraries on the default executable
update_libraries(sys.argv[1])
# ... rest of the code ...
|
8027a289674a4d2b1b25bd85a189e4886027a12d
|
src/com/itmill/toolkit/tests/TestForRichTextEditor.java
|
src/com/itmill/toolkit/tests/TestForRichTextEditor.java
|
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.tests;
import com.itmill.toolkit.data.Property.ValueChangeEvent;
import com.itmill.toolkit.data.Property.ValueChangeListener;
import com.itmill.toolkit.ui.Button;
import com.itmill.toolkit.ui.CustomComponent;
import com.itmill.toolkit.ui.Label;
import com.itmill.toolkit.ui.OrderedLayout;
import com.itmill.toolkit.ui.RichTextArea;
/**
*
* @author IT Mill Ltd.
*/
public class TestForRichTextEditor extends CustomComponent implements
ValueChangeListener {
private final OrderedLayout main = new OrderedLayout();
private Label l;
private RichTextArea rte;
public TestForRichTextEditor() {
setCompositionRoot(main);
createNewView();
}
public void createNewView() {
main.removeAllComponents();
main.addComponent(new Label(
"RTE uses google richtextArea and their examples toolbar."));
rte = new RichTextArea();
rte.addListener(this);
main.addComponent(rte);
main.addComponent(new Button("commit content to label below"));
l = new Label("", Label.CONTENT_XHTML);
main.addComponent(l);
}
public void valueChange(ValueChangeEvent event) {
l.setValue(rte.getValue());
}
}
|
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.tests;
import com.itmill.toolkit.data.Property.ValueChangeEvent;
import com.itmill.toolkit.data.Property.ValueChangeListener;
import com.itmill.toolkit.ui.Button;
import com.itmill.toolkit.ui.CustomComponent;
import com.itmill.toolkit.ui.Label;
import com.itmill.toolkit.ui.OrderedLayout;
import com.itmill.toolkit.ui.RichTextArea;
import com.itmill.toolkit.ui.Button.ClickEvent;
/**
*
* @author IT Mill Ltd.
*/
public class TestForRichTextEditor extends CustomComponent implements
ValueChangeListener {
private final OrderedLayout main = new OrderedLayout();
private Label l;
private RichTextArea rte;
public TestForRichTextEditor() {
setCompositionRoot(main);
createNewView();
}
public void createNewView() {
main.removeAllComponents();
main.addComponent(new Label(
"RTE uses google richtextArea and their examples toolbar."));
rte = new RichTextArea();
rte.addListener(this);
main.addComponent(rte);
main.addComponent(new Button("commit content to label below"));
l = new Label("", Label.CONTENT_XHTML);
main.addComponent(l);
Button b = new Button("enabled");
b.setSwitchMode(true);
b.setImmediate(true);
b.addListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
rte.setEnabled(!rte.isEnabled());
}
});
main.addComponent(b);
}
public void valueChange(ValueChangeEvent event) {
l.setValue(rte.getValue());
}
}
|
Test update: added toggle to edit enabled field
|
Test update: added toggle to edit enabled field
svn changeset:4325/svn branch:trunk
|
Java
|
apache-2.0
|
jdahlstrom/vaadin.react,sitexa/vaadin,Flamenco/vaadin,oalles/vaadin,Darsstar/framework,shahrzadmn/vaadin,kironapublic/vaadin,oalles/vaadin,carrchang/vaadin,travisfw/vaadin,mstahv/framework,peterl1084/framework,sitexa/vaadin,bmitc/vaadin,Darsstar/framework,kironapublic/vaadin,jdahlstrom/vaadin.react,peterl1084/framework,mstahv/framework,udayinfy/vaadin,asashour/framework,Flamenco/vaadin,sitexa/vaadin,kironapublic/vaadin,bmitc/vaadin,asashour/framework,Scarlethue/vaadin,fireflyc/vaadin,sitexa/vaadin,Flamenco/vaadin,Legioth/vaadin,cbmeeks/vaadin,fireflyc/vaadin,Peppe/vaadin,Peppe/vaadin,Scarlethue/vaadin,jdahlstrom/vaadin.react,peterl1084/framework,jdahlstrom/vaadin.react,Scarlethue/vaadin,travisfw/vaadin,magi42/vaadin,carrchang/vaadin,udayinfy/vaadin,mittop/vaadin,oalles/vaadin,carrchang/vaadin,peterl1084/framework,mittop/vaadin,synes/vaadin,cbmeeks/vaadin,synes/vaadin,mstahv/framework,Legioth/vaadin,synes/vaadin,mittop/vaadin,shahrzadmn/vaadin,asashour/framework,travisfw/vaadin,carrchang/vaadin,jdahlstrom/vaadin.react,magi42/vaadin,Scarlethue/vaadin,Peppe/vaadin,kironapublic/vaadin,fireflyc/vaadin,travisfw/vaadin,mstahv/framework,Darsstar/framework,kironapublic/vaadin,synes/vaadin,magi42/vaadin,cbmeeks/vaadin,Legioth/vaadin,synes/vaadin,oalles/vaadin,magi42/vaadin,asashour/framework,Scarlethue/vaadin,Flamenco/vaadin,sitexa/vaadin,bmitc/vaadin,Legioth/vaadin,cbmeeks/vaadin,Legioth/vaadin,travisfw/vaadin,shahrzadmn/vaadin,fireflyc/vaadin,peterl1084/framework,asashour/framework,Peppe/vaadin,fireflyc/vaadin,udayinfy/vaadin,shahrzadmn/vaadin,udayinfy/vaadin,Peppe/vaadin,shahrzadmn/vaadin,magi42/vaadin,Darsstar/framework,oalles/vaadin,mittop/vaadin,udayinfy/vaadin,bmitc/vaadin,Darsstar/framework,mstahv/framework
|
java
|
## Code Before:
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.tests;
import com.itmill.toolkit.data.Property.ValueChangeEvent;
import com.itmill.toolkit.data.Property.ValueChangeListener;
import com.itmill.toolkit.ui.Button;
import com.itmill.toolkit.ui.CustomComponent;
import com.itmill.toolkit.ui.Label;
import com.itmill.toolkit.ui.OrderedLayout;
import com.itmill.toolkit.ui.RichTextArea;
/**
*
* @author IT Mill Ltd.
*/
public class TestForRichTextEditor extends CustomComponent implements
ValueChangeListener {
private final OrderedLayout main = new OrderedLayout();
private Label l;
private RichTextArea rte;
public TestForRichTextEditor() {
setCompositionRoot(main);
createNewView();
}
public void createNewView() {
main.removeAllComponents();
main.addComponent(new Label(
"RTE uses google richtextArea and their examples toolbar."));
rte = new RichTextArea();
rte.addListener(this);
main.addComponent(rte);
main.addComponent(new Button("commit content to label below"));
l = new Label("", Label.CONTENT_XHTML);
main.addComponent(l);
}
public void valueChange(ValueChangeEvent event) {
l.setValue(rte.getValue());
}
}
## Instruction:
Test update: added toggle to edit enabled field
svn changeset:4325/svn branch:trunk
## Code After:
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.tests;
import com.itmill.toolkit.data.Property.ValueChangeEvent;
import com.itmill.toolkit.data.Property.ValueChangeListener;
import com.itmill.toolkit.ui.Button;
import com.itmill.toolkit.ui.CustomComponent;
import com.itmill.toolkit.ui.Label;
import com.itmill.toolkit.ui.OrderedLayout;
import com.itmill.toolkit.ui.RichTextArea;
import com.itmill.toolkit.ui.Button.ClickEvent;
/**
*
* @author IT Mill Ltd.
*/
public class TestForRichTextEditor extends CustomComponent implements
ValueChangeListener {
private final OrderedLayout main = new OrderedLayout();
private Label l;
private RichTextArea rte;
public TestForRichTextEditor() {
setCompositionRoot(main);
createNewView();
}
public void createNewView() {
main.removeAllComponents();
main.addComponent(new Label(
"RTE uses google richtextArea and their examples toolbar."));
rte = new RichTextArea();
rte.addListener(this);
main.addComponent(rte);
main.addComponent(new Button("commit content to label below"));
l = new Label("", Label.CONTENT_XHTML);
main.addComponent(l);
Button b = new Button("enabled");
b.setSwitchMode(true);
b.setImmediate(true);
b.addListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
rte.setEnabled(!rte.isEnabled());
}
});
main.addComponent(b);
}
public void valueChange(ValueChangeEvent event) {
l.setValue(rte.getValue());
}
}
|
// ... existing code ...
import com.itmill.toolkit.ui.Label;
import com.itmill.toolkit.ui.OrderedLayout;
import com.itmill.toolkit.ui.RichTextArea;
import com.itmill.toolkit.ui.Button.ClickEvent;
/**
*
// ... modified code ...
l = new Label("", Label.CONTENT_XHTML);
main.addComponent(l);
Button b = new Button("enabled");
b.setSwitchMode(true);
b.setImmediate(true);
b.addListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
rte.setEnabled(!rte.isEnabled());
}
});
main.addComponent(b);
}
public void valueChange(ValueChangeEvent event) {
// ... rest of the code ...
|
5354a39d62edc12cd5dbea6b1912bf6bdf846999
|
test_migrations/migrate_test/app/models.py
|
test_migrations/migrate_test/app/models.py
|
from __future__ import unicode_literals
from django.db import models
# from modeltrans.fields import TranslationField
class Category(models.Model):
name = models.CharField(max_length=255)
# i18n = TranslationField(fields=('name', ))
class Meta:
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Blog(models.Model):
title = models.CharField(max_length=255)
body = models.TextField(null=True, blank=True)
category = models.ForeignKey(Category, null=True, blank=True)
# i18n = TranslationField(fields=('title', 'body'))
def __str__(self):
return self.title
|
from __future__ import unicode_literals
from django.db import models
# from modeltrans.fields import TranslationField
class Category(models.Model):
name = models.CharField(max_length=255)
# i18n = TranslationField(fields=('name', ), virtual_fields=False)
class Meta:
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Blog(models.Model):
title = models.CharField(max_length=255)
body = models.TextField(null=True, blank=True)
category = models.ForeignKey(Category, null=True, blank=True)
# i18n = TranslationField(fields=('title', 'body'), virtual_fields=False)
def __str__(self):
return self.title
|
Disable adding virtual fields during migration
|
Disable adding virtual fields during migration
|
Python
|
bsd-3-clause
|
zostera/django-modeltrans,zostera/django-modeltrans
|
python
|
## Code Before:
from __future__ import unicode_literals
from django.db import models
# from modeltrans.fields import TranslationField
class Category(models.Model):
name = models.CharField(max_length=255)
# i18n = TranslationField(fields=('name', ))
class Meta:
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Blog(models.Model):
title = models.CharField(max_length=255)
body = models.TextField(null=True, blank=True)
category = models.ForeignKey(Category, null=True, blank=True)
# i18n = TranslationField(fields=('title', 'body'))
def __str__(self):
return self.title
## Instruction:
Disable adding virtual fields during migration
## Code After:
from __future__ import unicode_literals
from django.db import models
# from modeltrans.fields import TranslationField
class Category(models.Model):
name = models.CharField(max_length=255)
# i18n = TranslationField(fields=('name', ), virtual_fields=False)
class Meta:
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Blog(models.Model):
title = models.CharField(max_length=255)
body = models.TextField(null=True, blank=True)
category = models.ForeignKey(Category, null=True, blank=True)
# i18n = TranslationField(fields=('title', 'body'), virtual_fields=False)
def __str__(self):
return self.title
|
...
class Category(models.Model):
name = models.CharField(max_length=255)
# i18n = TranslationField(fields=('name', ), virtual_fields=False)
class Meta:
verbose_name_plural = 'categories'
...
category = models.ForeignKey(Category, null=True, blank=True)
# i18n = TranslationField(fields=('title', 'body'), virtual_fields=False)
def __str__(self):
return self.title
...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.