hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
b238ddb87672d7a51b78546cc0abed6cb1d4be0b
|
diff --git a/tests/phpunit/unit/Extensions/BaseExtensionTest.php b/tests/phpunit/unit/Extensions/BaseExtensionTest.php
index <HASH>..<HASH> 100644
--- a/tests/phpunit/unit/Extensions/BaseExtensionTest.php
+++ b/tests/phpunit/unit/Extensions/BaseExtensionTest.php
@@ -11,29 +11,8 @@ use Bolt\Tests\BoltUnitTest;
*
* @runTestsInSeparateProcesses
*/
-class BaseExtensionTest extends BoltUnitTest
+class BaseExtensionTest extends AbstractExtensionsUnitTest
{
- public function setup()
- {
- $this->php = \PHPUnit_Extension_FunctionMocker::start($this, 'Bolt')
- ->mockFunction('file_exists')
- ->mockFunction('is_readable')
- ->mockFunction('is_dir')
- ->mockFunction('copy')
- ->mockFunction('file_get_contents')
- ->getMock();
-
- $this->php2 = \PHPUnit_Extension_FunctionMocker::start($this, 'Bolt\Tests\Extensions\Mock')
- ->mockFunction('file_get_contents')
- ->getMock();
- }
-
- public function tearDown()
- {
- \PHPUnit_Extension_FunctionMocker::tearDown();
- @unlink(TEST_ROOT . '/app/cache/config_cache.php');
- }
-
public function testSetup()
{
$app = $this->getApp();
@@ -45,9 +24,8 @@ class BaseExtensionTest extends BoltUnitTest
public function testComposerLoading()
{
- $app = $this->makeApp();
- $app['resources']->setPath('extensions', __DIR__."/resources");
- $app->initialize();
+ $this->localExtensionInstall();
+ $app = $this->getApp();
$this->assertTrue($app['extensions']->isEnabled('testlocal'));
$config = $app['extensions.testlocal']->getExtensionConfig();
$this->assertNotEmpty($config);
|
[Tests] Have BaseExtensionTest extend the abstract extension class
|
bolt_bolt
|
train
|
fecde5d97f83bddfb312cb5f185027bf06845c2b
|
diff --git a/src/pybel/io/extras.py b/src/pybel/io/extras.py
index <HASH>..<HASH> 100644
--- a/src/pybel/io/extras.py
+++ b/src/pybel/io/extras.py
@@ -40,7 +40,7 @@ def to_graphml(graph, file):
graph.node_to_bel(u),
graph.node_to_bel(v),
key=key,
- relation=data[RELATION]
+ interaction=data[RELATION]
)
nx.write_graphml(g, file)
|
Rename attribute in GraphML export
|
pybel_pybel
|
train
|
c5c63ad6eb4bfd562020980efbc0ec25ad1a663a
|
diff --git a/test/unit/v2.1.0/converter-v21-to-v1.test.js b/test/unit/v2.1.0/converter-v21-to-v1.test.js
index <HASH>..<HASH> 100644
--- a/test/unit/v2.1.0/converter-v21-to-v1.test.js
+++ b/test/unit/v2.1.0/converter-v21-to-v1.test.js
@@ -788,6 +788,61 @@ describe('v2.1.0 to v1.0.0', function () {
done();
});
});
+
+ it('should set body mode (graphql) even if data is not set', function (done) {
+ transformer.convert({
+ info: {
+ _postman_id: '84b2b626-d3a6-0f31-c7a0-47733c01d0c2',
+ name: 'disabled-body',
+ schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json'
+ },
+ item: [{
+ _postman_id: '4f65e265-dd38-0a67-71a5-d9dd50fa37a1',
+ name: '',
+ request: {
+ body: {
+ mode: 'graphql'
+ },
+ header: [],
+ method: 'POST',
+ url: {
+ host: ['postman-echo', 'com'],
+ path: ['post'],
+ protocol: 'https',
+ raw: 'https://postman-echo.com/post'
+ }
+ },
+ response: []
+ }]
+ }, options, function (err, converted) {
+ expect(err).to.not.be.ok;
+
+ // remove `undefined` properties for testing
+ converted = JSON.parse(JSON.stringify(converted));
+
+ expect(converted).to.eql({
+ id: '84b2b626-d3a6-0f31-c7a0-47733c01d0c2',
+ name: 'disabled-body',
+ order: ['4f65e265-dd38-0a67-71a5-d9dd50fa37a1'],
+ folders_order: [],
+ folders: [],
+ requests: [{
+ id: '4f65e265-dd38-0a67-71a5-d9dd50fa37a1',
+ name: '',
+ collectionId: '84b2b626-d3a6-0f31-c7a0-47733c01d0c2',
+ method: 'POST',
+ headers: '',
+ dataMode: 'graphql',
+ url: 'https://postman-echo.com/post',
+ responses: [],
+ pathVariableData: [],
+ queryParams: [],
+ headerData: []
+ }]
+ });
+ done();
+ });
+ });
});
describe('protocolProfileBehavior', function () {
@@ -1421,6 +1476,7 @@ describe('v2.1.0 to v1.0.0', function () {
pathVariables: { pv_foo: 'pv_bar' },
pathVariableData: [{ description: null, key: 'pv_foo', value: 'pv_bar' }],
rawModeData: null,
+ graphqlModeData: null,
responses: [],
url: '?query_foo=query_bar',
data: [{ description: null, key: 'body_foo', value: 'body_bar' }],
@@ -1472,6 +1528,7 @@ describe('v2.1.0 to v1.0.0', function () {
headers: 'header_foo: header_bar',
url: '?query_foo=query_bar',
rawModeData: null,
+ graphqlModeData: null,
headerData: [{ key: 'header_foo', value: 'header_bar', description: null }],
queryParams: [{ key: 'query_foo', value: 'query_bar', description: null }]
});
@@ -1502,6 +1559,7 @@ describe('v2.1.0 to v1.0.0', function () {
headers: '',
url: '?query_foo=query_bar',
rawModeData: null,
+ graphqlModeData: null,
queryParams: [{ key: 'query_foo', value: 'query_bar', description: null }]
});
});
@@ -1544,6 +1602,7 @@ describe('v2.1.0 to v1.0.0', function () {
headers: 'header_foo: header_bar',
url: '?query_foo=query_bar',
rawModeData: null,
+ graphqlModeData: null,
headerData: [{ key: 'header_foo', value: 'header_bar', description: null }],
queryParams: [{ key: 'query_foo', value: 'query_bar', description: null }]
});
@@ -1574,6 +1633,46 @@ describe('v2.1.0 to v1.0.0', function () {
headerData: [],
queryParams: [],
rawModeData: 'foobar',
+ graphqlModeData: null,
+ dataDisabled: false,
+ url: 'https://postman-echo.com/get'
+ });
+ });
+ });
+
+ it('should work correctly for graphql bodies', function () {
+ transformer.convertSingle({
+ _postman_id: '9d123ce5-314a-40cd-9852-6a8569513f4e',
+ request: {
+ body: {
+ disabled: false,
+ mode: 'graphql',
+ graphql: {
+ query: 'query Test { hello }',
+ operationName: 'Test',
+ variables: '{"foo":"bar"}'
+ }
+ },
+ url: 'https://postman-echo.com/get'
+ }
+ }, options, function (err, result) {
+ expect(err).not.to.be.ok;
+
+ expect(JSON.parse(JSON.stringify(result))).to.eql({
+ id: '9d123ce5-314a-40cd-9852-6a8569513f4e',
+ dataMode: 'graphql',
+ data: null,
+ description: null,
+ pathVariableData: [],
+ headers: '',
+ headerData: [],
+ queryParams: [],
+ rawModeData: null,
+ graphqlModeData: {
+ query: 'query Test { hello }',
+ operationName: 'Test',
+ variables: '{"foo":"bar"}'
+ },
dataDisabled: false,
url: 'https://postman-echo.com/get'
});
|
Test: graphql body transformation for <I> -> v1
|
postmanlabs_postman-collection-transformer
|
train
|
48aef37e3461b97c74bbfa10ffa0c52bc3f547f2
|
diff --git a/src/main/java/io/lettuce/core/output/StreamReadOutput.java b/src/main/java/io/lettuce/core/output/StreamReadOutput.java
index <HASH>..<HASH> 100644
--- a/src/main/java/io/lettuce/core/output/StreamReadOutput.java
+++ b/src/main/java/io/lettuce/core/output/StreamReadOutput.java
@@ -46,6 +46,8 @@ public class StreamReadOutput<K, V> extends CommandOutput<K, V, List<StreamMessa
private Map<K, V> body;
+ private boolean bodyReceived = false;
+
public StreamReadOutput(RedisCodec<K, V> codec) {
super(codec, Collections.emptyList());
setSubscriber(ListSubscriber.instance());
@@ -70,6 +72,11 @@ public class StreamReadOutput<K, V> extends CommandOutput<K, V, List<StreamMessa
}
if (key == null) {
+ bodyReceived = true;
+ if (bytes == null) {
+ return;
+ }
+
key = codec.decodeKey(bytes);
return;
}
@@ -94,8 +101,9 @@ public class StreamReadOutput<K, V> extends CommandOutput<K, V, List<StreamMessa
@Override
public void complete(int depth) {
- if (depth == 3 && body != null) {
- subscriber.onNext(output, new StreamMessage<>(stream, id, body));
+ if (depth == 3 && bodyReceived) {
+ subscriber.onNext(output, new StreamMessage<>(stream, id, body == null ? Collections.emptyMap() : body));
+ bodyReceived = false;
key = null;
body = null;
id = null;
diff --git a/src/test/java/io/lettuce/core/commands/StreamCommandIntegrationTests.java b/src/test/java/io/lettuce/core/commands/StreamCommandIntegrationTests.java
index <HASH>..<HASH> 100644
--- a/src/test/java/io/lettuce/core/commands/StreamCommandIntegrationTests.java
+++ b/src/test/java/io/lettuce/core/commands/StreamCommandIntegrationTests.java
@@ -321,6 +321,22 @@ public class StreamCommandIntegrationTests extends TestSupport {
}
@Test
+ void xgroupreadDeletedMessage() {
+
+ redis.xgroupCreate(StreamOffset.latest(key), "del-group", XGroupCreateArgs.Builder.mkstream());
+ redis.xadd(key, Collections.singletonMap("key", "value1"));
+ redis.xreadgroup(Consumer.from("del-group", "consumer1"), StreamOffset.lastConsumed(key));
+
+ redis.xadd(key, XAddArgs.Builder.maxlen(1), Collections.singletonMap("key", "value2"));
+
+ List<StreamMessage<String, String>> messages = redis.xreadgroup(Consumer.from("del-group", "consumer1"),
+ StreamOffset.from(key, "0-0"));
+
+ assertThat(messages).hasSize(1);
+ assertThat(messages.get(0).getBody()).isEmpty();
+ }
+
+ @Test
void xpendingWithoutRead() {
redis.xgroupCreate(StreamOffset.latest(key), "group", XGroupCreateArgs.Builder.mkstream());
|
Fix StreamReadOutput when XREADGROUP doesn't report the body #<I>
We now correctly decode stream messages that are deleted (i.e. don't return the body).
|
lettuce-io_lettuce-core
|
train
|
06e9a5709b502bbd9f0329dde65197aea24507c6
|
diff --git a/test/ConfigTestCases.test.js b/test/ConfigTestCases.test.js
index <HASH>..<HASH> 100644
--- a/test/ConfigTestCases.test.js
+++ b/test/ConfigTestCases.test.js
@@ -226,6 +226,7 @@ describe("ConfigTestCases", () => {
);
if (exportedTests < filesCount)
return done(new Error("No tests exported by test case"));
+ if (testConfig.afterExecute) testConfig.afterExecute();
process.nextTick(done);
});
});
diff --git a/test/configCases/hash-length/output-filename/test.config.js b/test/configCases/hash-length/output-filename/test.config.js
index <HASH>..<HASH> 100644
--- a/test/configCases/hash-length/output-filename/test.config.js
+++ b/test/configCases/hash-length/output-filename/test.config.js
@@ -44,5 +44,8 @@ module.exports = {
}
return "./" + filename;
+ },
+ afterExecute: () => {
+ delete global.webpackJsonp;
}
};
|
get rid of webpackJsonp global leak
|
webpack_webpack
|
train
|
4103816c2d3bda0c880e88eca9c6ef559a940100
|
diff --git a/CHANGES.rst b/CHANGES.rst
index <HASH>..<HASH> 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -4,10 +4,11 @@
0.5.4-dev
=========
- * new ``taxit taxid_classified`` that decides if a tax_id is primary and valid (True/False)
+ * new ``taxit taxid_classified`` decides if a tax_id is primary and valid (True/False)
* ``taxit update_taxids`` will halt on unknown tax_ids unless ``--unknowns FILE`` is specified
* ``taxit update_taxids`` only requires a csv file with 'tax_id' column
* ``taxit update_taxids`` takes an optional ``--name-column`` to assist in assigning tax_ids
+ * ``taxit update_taxids`` will read stdin if csv file is not provided as argument
0.5.4
=====
diff --git a/taxtastic/subcommands/taxid_classified.py b/taxtastic/subcommands/taxid_classified.py
index <HASH>..<HASH> 100644
--- a/taxtastic/subcommands/taxid_classified.py
+++ b/taxtastic/subcommands/taxid_classified.py
@@ -32,6 +32,8 @@ log = logging.getLogger(__name__)
def build_parser(parser):
parser.add_argument(
'infile',
+ nargs='?',
+ default=sys.stdin,
help="""Input CSV file to process, minimally containing the
fields 'tax_id'. Rows with missing tax_ids are left unchanged.""")
parser.add_argument(
diff --git a/taxtastic/subcommands/update_taxids.py b/taxtastic/subcommands/update_taxids.py
index <HASH>..<HASH> 100644
--- a/taxtastic/subcommands/update_taxids.py
+++ b/taxtastic/subcommands/update_taxids.py
@@ -35,6 +35,8 @@ log = logging.getLogger(__name__)
def build_parser(parser):
parser.add_argument(
'infile',
+ nargs='?',
+ default=sys.stdin,
help="""Input CSV file to process, minimally containing the
fields 'tax_id'. Rows with missing tax_ids are left unchanged.""")
parser.add_argument(
@@ -129,7 +131,8 @@ def action(args):
if args.unknowns:
# unknown taxids are set to empty string in taxid_updater
rows[rows['tax_id'].isnull()].to_csv(
- args.unknowns, index=False, columns=columns, quoting=csv.QUOTE_NONNUMERIC)
+ args.unknowns, index=False,
+ columns=columns, quoting=csv.QUOTE_NONNUMERIC)
rows.to_csv(args.out_file, index=False, columns=columns,
quoting=csv.QUOTE_NONNUMERIC)
|
will read from stdin if csv file is not present as input arg
|
fhcrc_taxtastic
|
train
|
cebe22b3a091118cb15fc46ff422c2c136e44985
|
diff --git a/tests/bootstrap.php b/tests/bootstrap.php
index <HASH>..<HASH> 100644
--- a/tests/bootstrap.php
+++ b/tests/bootstrap.php
@@ -4,11 +4,9 @@ require_once __DIR__ . '/../src/neevo.php';
// Test helper objects autoloader
-function NeevoTestAutoload($class){
+spl_autoload_register(function($class){
$path = __DIR__ . "/mocks/$class.php";
if(file_exists($path))
return require_once $path;
return false;
-}
-
-spl_autoload_register('NeevoTestAutoload');
\ No newline at end of file
+});
\ No newline at end of file
|
Revert 'tests/bootstrap.php' to <I>ff1d5
|
smasty_Neevo
|
train
|
527a2b7cd349a72cb65a970c8ffe0f9a315ec635
|
diff --git a/pyzotero/zotero.py b/pyzotero/zotero.py
index <HASH>..<HASH> 100644
--- a/pyzotero/zotero.py
+++ b/pyzotero/zotero.py
@@ -141,7 +141,6 @@ def retrieve(func):
'text/plain': 'plain'
}
fmt = formats.get(self.request.headers['Content-Type'], 'json')
- processor = self.processors.get(content)
# clear all query parameters
self.url_params = None
# Or process atom if it's atom-formatted
@@ -151,9 +150,11 @@ def retrieve(func):
processor = self.processors.get(content)
# process the content correctly with a custom rule
return processor(parsed)
- # otherwise, just return the unparsed content as is
- else:
- return retrieved
+ if self.tag_data:
+ self.tag_data = False
+ return self._tags_data(retrieved)
+ # No need to do anything
+ return retrieved
return wrapped_f
@@ -181,6 +182,7 @@ class Zotero(object):
self.preserve_json_order = preserve_json_order
self.url_params = None
self.etags = None
+ self.tag_data = False
self.request = None
# these aren't valid item fields, so never send them to the server
self.temp_keys = set(['key', 'etag', 'group_id', 'updated'])
@@ -202,7 +204,7 @@ class Zotero(object):
'ris': self._bib_processor,
'tei': self._bib_processor,
'wikipedia': self._bib_processor,
- 'json': self._json_processor
+ 'json': self._json_processor,
}
self.links = None
self.templates = {}
@@ -461,9 +463,10 @@ class Zotero(object):
@retrieve
def tags(self, **kwargs):
- """ Get tags for a specific item
+ """ Get tags
"""
query_string = '/{t}/{u}/tags'
+ self.tag_data = True
return self._build_query(query_string)
@retrieve
@@ -474,6 +477,7 @@ class Zotero(object):
u=self.library_id,
t=self.library_type,
i=item.upper())
+ self.tag_data = True
return self._build_query(query_string)
def all_top(self, **kwargs):
@@ -582,7 +586,7 @@ class Zotero(object):
def _tags_data(self, retrieved):
""" Format and return data from API calls which return Tags
"""
- tags = [t['title'] for t in retrieved.entries]
+ tags = [t['tag'] for t in retrieved]
self.url_params = None
return tags
@@ -653,7 +657,7 @@ class Zotero(object):
liblevel = '/{t}/{u}/items/{i}/children'
# Create one or more new attachments
headers = dict({
- 'X-Zotero-Write-Token': token(),
+ 'Zotero-Write-Token': token(),
'Content-Type': 'application/json',
}.items() + self.default_headers().items())
to_send = json.dumps({'items': payload})
@@ -669,8 +673,8 @@ class Zotero(object):
req.raise_for_status()
except requests.exceptions.HTTPError:
error_handler(req)
- data = req.text
- return self._json_processor(feedparser.parse(data))
+ data = req.json()
+ return data
def get_auth(attachment):
"""
@@ -697,15 +701,14 @@ class Zotero(object):
url=self.endpoint
+ '/users/{u}/items/{i}/file?key={k}'.format(
u=self.library_id,
- i=created[idx]['key'],
- k=self.api_key),
+ i=created[idx]['key']),
data=data,
headers=auth_headers)
try:
auth_req.raise_for_status()
except requests.exceptions.HTTPError:
error_handler(auth_req)
- return json.loads(auth_req.text)
+ return auth_req.json()
def uploadfile(authdata):
"""
@@ -948,7 +951,7 @@ class Zotero(object):
if not 'parent' in payload:
payload['parent'] = ''
headers = {
- 'X-Zotero-Write-Token': token(),
+ 'Zotero-Write-Token': token(),
}
req = requests.post(
url=self.endpoint
diff --git a/test/test_zotero.py b/test/test_zotero.py
index <HASH>..<HASH> 100644
--- a/test/test_zotero.py
+++ b/test/test_zotero.py
@@ -233,7 +233,7 @@ class ZoteroTests(unittest.TestCase):
body=self.tags_doc)
# /users/myuserID/tags?key=myuserkey
tags_data = zot.tags()
- self.assertEqual(u'Community / Economic Development', tags_data[0]['tag'])
+ self.assertEqual(u'Community / Economic Development', tags_data[0])
@httpretty.activate
def testParseGroupsAtomDoc(self):
|
Content processing and write token fixes
- More robust content processing by specifically tracking 'tag' requests
- API v3 uses Zotero-Write-Token, as opposed to x-Zotero…
|
urschrei_pyzotero
|
train
|
d1c63b14082bd0c261800e1f9770b0d01812aab5
|
diff --git a/integration-tests/spec/messaging_spec.rb b/integration-tests/spec/messaging_spec.rb
index <HASH>..<HASH> 100644
--- a/integration-tests/spec/messaging_spec.rb
+++ b/integration-tests/spec/messaging_spec.rb
@@ -622,7 +622,7 @@ remote_describe "in-container messaging tests" do
end
after(:each) do
- @expire_queue.stop if @expire_queue
+ @expire_queue.stop_sync if @expire_queue
end
it "should return the default expiry address" do
@@ -725,7 +725,7 @@ remote_describe "in-container messaging tests" do
end
after(:each) do
- @dead_queue.stop if @dead_queue
+ @dead_queue.stop_sync if @dead_queue
end
it "should return the default dead letter address" do
|
Try to clean up messaging_spec on BuildHive
|
torquebox_torquebox
|
train
|
b6c45d837e535df38069db8040eb80d5588bdb23
|
diff --git a/lib/fog/openstack/models/compute/host.rb b/lib/fog/openstack/models/compute/host.rb
index <HASH>..<HASH> 100644
--- a/lib/fog/openstack/models/compute/host.rb
+++ b/lib/fog/openstack/models/compute/host.rb
@@ -8,10 +8,11 @@ module Fog
class Host < Fog::Model
attribute :host_name
- attribute :service
+ attribute :service_name
attribute :details
def initialize(attributes)
+ attributes["service_name"] = attributes.delete "service"
# Old 'connection' is renamed as service and should be used instead
prepare_service_value(attributes)
super
|
service attribute conflicts with the service defined in the parent
|
fog_fog
|
train
|
d57f196112c91f63c2705f6d2f44f7e6a9e592c6
|
diff --git a/interp/interp_test.go b/interp/interp_test.go
index <HASH>..<HASH> 100644
--- a/interp/interp_test.go
+++ b/interp/interp_test.go
@@ -1516,6 +1516,10 @@ var runTests = []runTest{
"block\n",
},
{
+ "[[ -e /dev/nvme0n1 ]] || { echo block; exit; }; [[ -b /dev/nvme0n1 ]] && echo block; [[ -c /dev/nvme0n1 ]] && echo char; true",
+ "block\n",
+ },
+ {
"[[ -e /dev/tty ]] || { echo char; exit; }; [[ -b /dev/tty ]] && echo block; [[ -c /dev/tty ]] && echo char; true",
"char\n",
},
|
interp: use /dev/nvme0n1 for testing "test -b" too
Most modern laptops use NVMe SSDs nowadays,
and those block devices tend to appear as nvme0n1 instead of sda.
Add a test case for that device path, too.
Both test cases have a fallback if the path doesn't exist.
|
mvdan_sh
|
train
|
52b303df5a11c7c3e7b06d2f96aa9c176e322feb
|
diff --git a/src/pyramid_jwt/__init__.py b/src/pyramid_jwt/__init__.py
index <HASH>..<HASH> 100644
--- a/src/pyramid_jwt/__init__.py
+++ b/src/pyramid_jwt/__init__.py
@@ -93,9 +93,14 @@ def set_jwt_cookie_authentication_policy(
json_encoder=None,
audience=None,
cookie_name=None,
- https_only=False,
+ https_only=True,
reissue_time=None,
):
+ settings = config.get_settings()
+ cookie_name = cookie_name or settings.get("jwt.cookie_name")
+ reissue_time = reissue_time or settings.get("jwt.cookie_reissue_time")
+ if https_only is None:
+ https_only = settings.get("jwt.https_only_cookie", True)
auth_policy = create_jwt_authentication_policy(
config,
diff --git a/src/pyramid_jwt/policy.py b/src/pyramid_jwt/policy.py
index <HASH>..<HASH> 100644
--- a/src/pyramid_jwt/policy.py
+++ b/src/pyramid_jwt/policy.py
@@ -168,7 +168,7 @@ class JWTCookieAuthenticationPolicy(JWTAuthenticationPolicy):
callback=None,
json_encoder=None,
audience=None,
- cookie_name="Authorization",
+ cookie_name=None,
https_only=True,
reissue_time=None,
):
@@ -187,7 +187,7 @@ class JWTCookieAuthenticationPolicy(JWTAuthenticationPolicy):
)
self.https_only = https_only
- self.cookie_name = cookie_name
+ self.cookie_name = cookie_name or "Authorization"
self.max_age = self.expiration and self.expiration.total_seconds()
if reissue_time and isinstance(reissue_time, datetime.timedelta):
diff --git a/tests/test_integration.py b/tests/test_integration.py
index <HASH>..<HASH> 100644
--- a/tests/test_integration.py
+++ b/tests/test_integration.py
@@ -112,7 +112,8 @@ def cookie_config(base_config):
# Enable JWT authentication on Cookies.
reissue_time = timedelta(seconds=1)
base_config.set_jwt_cookie_authentication_policy(
- "secret", cookie_name="Token", expiration=5, reissue_time=reissue_time
+ "secret", cookie_name="Token", expiration=5, reissue_time=reissue_time,
+ https_only=False
)
return base_config
|
Creating config file options for every cookie setting
|
wichert_pyramid_jwt
|
train
|
4667b8a47ccd34c00a27ac88e4ac248d0fa5268e
|
diff --git a/configman/__init__.py b/configman/__init__.py
index <HASH>..<HASH> 100644
--- a/configman/__init__.py
+++ b/configman/__init__.py
@@ -69,11 +69,10 @@ def configuration(*args, **kwargs):
"""this function just instantiates a ConfigurationManager and returns
the configuration dictionary. It accepts all the same parameters as the
constructor for the ConfigurationManager class."""
- if 'mapping_class' in kwargs:
- mapping_class = kwargs.pop('mapping_class')
- cm = ConfigurationManager(*args, **kwargs)
try:
- return cm.get_config(mapping_class=mapping_class)
- except NameError:
- return cm.get_config()
+ config_kwargs = {'mapping_class': kwargs.pop('mapping_class')}
+ except KeyError:
+ config_kwargs = {}
+ cm = ConfigurationManager(*args, **kwargs)
+ return cm.get_config(**config_kwargs)
|
clearer selection of kwargs on the configuration call
|
mozilla_configman
|
train
|
6349948049205bd12862ca95f9d39aa21f5d6023
|
diff --git a/lib/extensions/nfc/ext/nfc/platform/android/src/com/rhomobile/nfc/Nfc.java b/lib/extensions/nfc/ext/nfc/platform/android/src/com/rhomobile/nfc/Nfc.java
index <HASH>..<HASH> 100644
--- a/lib/extensions/nfc/ext/nfc/platform/android/src/com/rhomobile/nfc/Nfc.java
+++ b/lib/extensions/nfc/ext/nfc/platform/android/src/com/rhomobile/nfc/Nfc.java
@@ -4,13 +4,10 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
-import java.util.Map;
import java.util.Set;
-import android.app.Activity;
import android.app.Dialog;
import android.app.PendingIntent;
-import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
@@ -19,7 +16,6 @@ import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
-import android.nfc.NfcManager;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.MifareClassic;
@@ -32,17 +28,15 @@ import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.nfc.tech.TagTechnology;
import android.os.Build;
-import android.os.Bundle;
import android.os.Parcelable;
-import android.util.Log;
import com.rhomobile.rhodes.RhodesActivity;
import com.rhomobile.rhodes.RhodesService;
-import com.rhomobile.rhodes.extmanager.IRhoExtManager;;
+import com.rhomobile.rhodes.extmanager.IRhoExtManager;
import com.rhomobile.rhodes.extmanager.IRhoListener;
-import com.rhomobile.rhodes.extmanager.RhoExtManager;;
-import com.rhomobile.rhodes.util.Utils;
+import com.rhomobile.rhodes.util.ContextFactory;
import com.rhomobile.rhodes.util.PerformOnUiThread;
+import com.rhomobile.rhodes.util.Utils;
public class Nfc implements IRhoListener {
@@ -123,31 +117,24 @@ public class Nfc implements IRhoListener {
return ourInstance;
}
- public static NfcAdapter getDefaultAdapter(Context ctx) {
- Context context = ctx;
- if (ctx == null) {
- context = RhodesActivity.getContext();
- }
+ private static NfcAdapter getDefaultAdapter(Context ctx) {
NfcAdapter da = null;
try {
int sdkVersion = Build.VERSION.SDK_INT;
if (sdkVersion >= Build.VERSION_CODES.GINGERBREAD_MR1) {
- da = NfcAdapter.getDefaultAdapter(RhodesActivity.getContext());
+ da = NfcAdapter.getDefaultAdapter(ctx);
}
- else if (sdkVersion >= Build.VERSION_CODES.GINGERBREAD) {
- da = NfcAdapter.getDefaultAdapter();
- }
}
catch (Exception e) {
// nothing
- Utils.platformLog(TAG, "Exception during get NFCAdapter");
+ Utils.platformLog(TAG, "Exception during get NFCAdapter: " + e.getMessage());
e.printStackTrace();
}
return da;
}
public static int isSupported() {
- NfcAdapter da = getDefaultAdapter(null);
+ NfcAdapter da = getDefaultAdapter(ContextFactory.getContext());
if (da == null) {
return 0;
}
@@ -207,7 +194,7 @@ public class Nfc implements IRhoListener {
@Override
public void onPause(RhodesActivity activity) {
log(" $$$$$$$$$ onPause() ");
- NfcAdapter nfcAdapter = getDefaultAdapter(RhodesActivity.getContext());
+ NfcAdapter nfcAdapter = getDefaultAdapter(activity);
if (nfcAdapter != null) {
nfcAdapter.disableForegroundDispatch(activity);
nfcAdapter.disableForegroundNdefPush(activity);
@@ -217,7 +204,7 @@ public class Nfc implements IRhoListener {
@Override
public void onResume(RhodesActivity activity) {
log(" $$$$$$$$$ onResume() ");
- NfcAdapter nfcAdapter = getDefaultAdapter(RhodesActivity.getContext());
+ NfcAdapter nfcAdapter = getDefaultAdapter(activity);
if ((nfcAdapter != null) && (ourIsEnable)) {
IntentFilter[] filters = new IntentFilter[1];
filters[0] = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
|
Android: fix NFC extension build for java 7 compiler
|
rhomobile_rhodes
|
train
|
c8c0afb6182c728b9c1d01e6f93f20543481e240
|
diff --git a/lib/tapestry/version.rb b/lib/tapestry/version.rb
index <HASH>..<HASH> 100644
--- a/lib/tapestry/version.rb
+++ b/lib/tapestry/version.rb
@@ -1,7 +1,7 @@
module Tapestry
module_function
- VERSION = "0.5.0".freeze
+ VERSION = "0.6.0".freeze
def version
"""
|
Release of version <I>.
|
jeffnyman_tapestry
|
train
|
0b427935c68a5b77dc0f7372cbfe6825f0767306
|
diff --git a/print.js b/print.js
index <HASH>..<HASH> 100644
--- a/print.js
+++ b/print.js
@@ -99,11 +99,22 @@ function print(input, options = {}, name = "", refs = null){
refs.set(input, name);
+ /** Begin compiling some serious output */
+ let output = "";
+ let typeName = "";
+
+ let arrayLike;
+ let isFunc;
+ let ignoreNumbers;
+ let padBeforeProps;
+
+
/** Maps */
if("[object Map]" === type){
- let output = "";
- let index = 0;
+ padBeforeProps = true;
+ typeName = "Map";
+ let index = 0;
for(let entry of input.entries()){
const namePrefix = (name ? name : "Map") + ".entries";
const keyString = `${index}.` + "key";
@@ -121,19 +132,20 @@ function print(input, options = {}, name = "", refs = null){
delim = /^->\s/.test(value) ? " " : " => ";
str += "\n" + valueString + delim + value;
- output += str.replace(/^/gm, "\t") + "\n\n";
+ output += str + "\n\n";
++index;
}
- return "Map{\n" + output.replace(/(?:\n\s*\n)+$/m, "") + "\n}";
+ output = "\n" + output.replace(/(?:\n\s*\n)+$/m, "");
}
/** Sets */
- if("[object Set]" === type){
- let output = "";
- let index = 0;
+ else if("[object Set]" === type){
+ padBeforeProps = true;
+ typeName = "Set";
+ let index = 0;
for(let value of input.values()){
const valueName = (name ? name : "{input}") + ".entries[" + index + "]";
value = print(value, options, valueName, refs);
@@ -143,14 +155,16 @@ function print(input, options = {}, name = "", refs = null){
++index;
}
- return "Set{\n" + output.replace(/(?:\n\t*\n?)+$/, "").replace(/^/gm, "\t") + "\n}";
+ output = "\n" + output.replace(/(?:\n\t*\n?)+$/, "");
}
/** Objects, Arrays, and Functions */
- const arrayLike = "function" === typeof input[Symbol.iterator];
- const isFunc = "function" === typeof input;
- const ignoreNumbers = !showArrayIndices && arrayLike;
+ else{
+ arrayLike = "function" === typeof input[Symbol.iterator];
+ isFunc = "function" === typeof input;
+ ignoreNumbers = !showArrayIndices && arrayLike;
+ }
/** Obtain a list of every (non-symbolic) property to show */
@@ -203,8 +217,10 @@ function print(input, options = {}, name = "", refs = null){
});
- /** Begin compiling some serious output */
- let output = "";
+ /** Insert a blank line if existing lines have been printed for this object */
+ if(padBeforeProps && keys.length)
+ output += "\n";
+
/** Regular properties */
for(let i = 0, l = keys.length; i < l; ++i){
@@ -260,36 +276,34 @@ function print(input, options = {}, name = "", refs = null){
/** Tweak output based on the value's type */
- let typePrefix = "";
-
if("[object Arguments]" === type)
- typePrefix = "Arguments";
+ typeName = "Arguments";
else{
const ctr = input.constructor.name;
switch(ctr){
case "GeneratorFunction":
- typePrefix = "function*()";
+ typeName = "function*()";
break;
case "Function":
- typePrefix = "function()";
+ typeName = "function()";
break;
case "Array":
case "Object":
- typePrefix = "";
+ typeName = "";
break;
default:
- typePrefix = ctr;
+ typeName = ctr;
break;
}
}
output = output ? output.replace(/\n/g, "\n\t") + "\n" : "";
- return typePrefix + (arrayLike
+ return typeName + (arrayLike
? "[" + output + "]"
: "{" + output + "}");
}
diff --git a/test/3-collections.js b/test/3-collections.js
index <HASH>..<HASH> 100644
--- a/test/3-collections.js
+++ b/test/3-collections.js
@@ -36,13 +36,13 @@ describe("Maps", () => {
expect(map).to.print(`Map{
0.key => "alpha"
0.value => "A"
-
+
1.key => "beta"
1.value => "B"
-
+
2.key => "gamma"
2.value => "G"
-
+
3.key => "delta"
3.value => "D"
}`);
@@ -62,19 +62,19 @@ describe("Maps", () => {
a: "a"
A: "A"
}
-
+
1.key => "beta"
1.value => {
b: "b"
B: "B"
}
-
+
2.key => "gamma"
2.value => {
g: "g"
G: "G"
}
-
+
3.key => "delta"
3.value => {
d: "d"
@@ -123,7 +123,7 @@ describe("Maps", () => {
width: 28.52
}
0.value => "A"
-
+
1.key => {
age: 30
cereal: "Quuz"
|
Display named properties in Maps and Sets
|
Alhadis_Print
|
train
|
74f78cf99c512654d60be25b01247f631cfe66b9
|
diff --git a/lib/chef/resource/hostname.rb b/lib/chef/resource/hostname.rb
index <HASH>..<HASH> 100644
--- a/lib/chef/resource/hostname.rb
+++ b/lib/chef/resource/hostname.rb
@@ -50,6 +50,10 @@ class Chef
description: "An optional property to set the hostname if it differs from the resource block's name.",
name_property: true
+ property :fqdn, String,
+ description: "An optional property to set the fqdn if it differs from the resource block's hostname.",
+ introduced: "17.0"
+
property :ipaddress, String,
description: "The IP address to use when configuring the hosts file.",
default: lazy { node["ipaddress"] }, default_description: "The node's IP address as determined by Ohai."
@@ -115,7 +119,9 @@ class Chef
# make sure node['fqdn'] resolves via /etc/hosts
unless new_resource.ipaddress.nil?
- newline = "#{new_resource.ipaddress} #{new_resource.hostname}"
+ newline = "#{new_resource.ipaddress}"
+ newline << " #{new_resource.fqdn}" unless new_resource.fqdn.to_s.empty?
+ newline << " #{new_resource.hostname}"
newline << " #{new_resource.aliases.join(" ")}" if new_resource.aliases && !new_resource.aliases.empty?
newline << " #{new_resource.hostname[/[^\.]*/]}"
r = append_replacing_matching_lines("/etc/hosts", /^#{new_resource.ipaddress}\s+|\s+#{new_resource.hostname}\s+/, newline)
|
Added new property fqdn and made sure hosts entry includes the same
|
chef_chef
|
train
|
69b8b40d0d6be251e52ea09857fd1ab3986eed3b
|
diff --git a/mod/jodd/src/jodd/datetime/format/AbstractFormatter.java b/mod/jodd/src/jodd/datetime/format/AbstractFormatter.java
index <HASH>..<HASH> 100644
--- a/mod/jodd/src/jodd/datetime/format/AbstractFormatter.java
+++ b/mod/jodd/src/jodd/datetime/format/AbstractFormatter.java
@@ -237,4 +237,42 @@ public abstract class AbstractFormatter implements JdtFormatter {
}
throw new IllegalArgumentException("Value too big: " + value);
}
+
+ /**
+ * Prints 4 digits and optional minus sign.
+ */
+ protected static String printPad4(int value) {
+ char[] result = new char[5];
+ int count = 0;
+
+ if (value < 0) {
+ result[count++] = '-';
+ value = -value;
+ }
+
+ String str = Integer.toString(value);
+
+ if (value < 10) {
+ result[count++] = '0';
+ result[count++] = '0';
+ result[count++] = '0';
+ result[count++] = str.charAt(0);
+ } else if (value < 100) {
+ result[count++] = '0';
+ result[count++] = '0';
+ result[count++] = str.charAt(0);
+ result[count++] = str.charAt(1);
+ } else if (value < 1000) {
+ result[count++] = '0';
+ result[count++] = str.charAt(0);
+ result[count++] = str.charAt(1);
+ result[count++] = str.charAt(2);
+ } else {
+ result[count++] = str.charAt(0);
+ result[count++] = str.charAt(1);
+ result[count++] = str.charAt(2);
+ result[count++] = str.charAt(3);
+ }
+ return new String(result, 0, count);
+ }
}
diff --git a/mod/jodd/src/jodd/datetime/format/DefaultFormatter.java b/mod/jodd/src/jodd/datetime/format/DefaultFormatter.java
index <HASH>..<HASH> 100644
--- a/mod/jodd/src/jodd/datetime/format/DefaultFormatter.java
+++ b/mod/jodd/src/jodd/datetime/format/DefaultFormatter.java
@@ -4,7 +4,6 @@ package jodd.datetime.format;
import jodd.datetime.DateTimeStamp;
import jodd.datetime.JDateTime;
-import jodd.format.Printf;
import jodd.util.LocaleUtil;
import jodd.util.DateFormatSymbolsEx;
@@ -77,7 +76,7 @@ public class DefaultFormatter extends AbstractFormatter {
DateFormatSymbolsEx dfs = LocaleUtil.getDateFormatSymbols(jdt.getLocale());
switch (patternIndex) {
case 0:
- return Printf.str("%~04i", jdt.getYear());
+ return printPad4(jdt.getYear());
case 1:
return print2(jdt.getMonth());
case 2:
@@ -111,9 +110,15 @@ public class DefaultFormatter extends AbstractFormatter {
case 16:
return jdt.getEra() == 1 ? dfs.getAdEra() : dfs.getBcEra();
case 17:
- return jdt.getTimeZone().getDisplayName(false, TimeZone.LONG, jdt.getLocale());
+ return jdt.getTimeZone().getDisplayName(
+ jdt.isInDaylightTime(),
+ TimeZone.LONG,
+ jdt.getLocale());
case 18:
- return jdt.getTimeZone().getDisplayName(false, TimeZone.SHORT, jdt.getLocale());
+ return jdt.getTimeZone().getDisplayName(
+ jdt.isInDaylightTime(),
+ TimeZone.SHORT,
+ jdt.getLocale());
default:
return new String(patterns[patternIndex]);
}
|
added usage of isInDayLightTime()
|
oblac_jodd
|
train
|
6eb312490a19cecd6198a803c8574fcb92a52e72
|
diff --git a/src/main/java/water/util/MRUtils.java b/src/main/java/water/util/MRUtils.java
index <HASH>..<HASH> 100644
--- a/src/main/java/water/util/MRUtils.java
+++ b/src/main/java/water/util/MRUtils.java
@@ -292,6 +292,7 @@ public class MRUtils {
/**
* Correct probabilities obtained from training on oversampled data back to original distribution
* Following instructions by Guido Deutsch
+ * Also c.f. http://gking.harvard.edu/files/0s.pdf Eq.(28)
* @param fr Frame containing one label and C per-class probabilities (to be modified in-place)
* @param prior_fraction Prior per-class fractions
* @param model_fraction Modeled per-class fractions
|
Add reference to oversampling correction math.
|
h2oai_h2o-2
|
train
|
55a279adf44423c103464e35cc6835f4b90464d6
|
diff --git a/guice/restclient/src/main/java/com/peterphi/std/guice/restclient/resteasy/impl/ResteasyProxyClientFactoryImpl.java b/guice/restclient/src/main/java/com/peterphi/std/guice/restclient/resteasy/impl/ResteasyProxyClientFactoryImpl.java
index <HASH>..<HASH> 100644
--- a/guice/restclient/src/main/java/com/peterphi/std/guice/restclient/resteasy/impl/ResteasyProxyClientFactoryImpl.java
+++ b/guice/restclient/src/main/java/com/peterphi/std/guice/restclient/resteasy/impl/ResteasyProxyClientFactoryImpl.java
@@ -14,6 +14,7 @@ import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import java.net.URI;
import java.util.Arrays;
+import java.util.Objects;
@Singleton
public class ResteasyProxyClientFactoryImpl implements JAXRSProxyClientFactory
@@ -88,19 +89,36 @@ public class ResteasyProxyClientFactoryImpl implements JAXRSProxyClientFactory
@Override
public <T> T getClient(final Class<T> iface)
{
- // TODO allow a service to annotate itself with configurable names?
return getClient(iface, getServiceNames(iface));
}
+ /**
+ * Computes the default set of names for a service based on an interface class. The names produced are an ordered list:
+ * <ul>
+ * <li>The fully qualified class name</li>
+ * <li>If present, the {@link com.peterphi.std.annotation.ServiceName} annotation on the class (OR if not specified on the
+ * class, the {@link com.peterphi.std.annotation.ServiceName} specified on the package)</li>
+ * <li>The simple name of the class (the class name without the package prefix)</li>
+ * </ul>
+ *
+ * @param iface
+ * a JAX-RS service interface
+ *
+ * @return An array containing one or more names that could be used for the class; may contain nulls (which should be ignored)
+ */
private static String[] getServiceNames(Class<?> iface)
{
+ Objects.requireNonNull(iface, "Missing param: iface!");
+
return new String[]{iface.getName(), getServiceName(iface), iface.getSimpleName()};
}
private static String getServiceName(Class<?> iface)
{
+ Objects.requireNonNull(iface, "Missing param: iface!");
+
if (iface.isAnnotationPresent(ServiceName.class))
{
return iface.getAnnotation(ServiceName.class).value();
diff --git a/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/setup/JAXRSAutoRegisterServicesModule.java b/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/setup/JAXRSAutoRegisterServicesModule.java
index <HASH>..<HASH> 100644
--- a/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/setup/JAXRSAutoRegisterServicesModule.java
+++ b/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/setup/JAXRSAutoRegisterServicesModule.java
@@ -23,7 +23,9 @@ import java.util.List;
* startup will not be able to proceed.
* <p>
* If there are no implementations found then it is assumed the interface is a client interface in this context and it is
- * ignored.
+ * either bound to a service (if an endpoint is found of the form <code>service.<em>name</em>.endpoint</code> (see {@link
+ * com.peterphi.std.guice.restclient.resteasy.impl.ResteasyProxyClientFactoryImpl#getServiceNames(Class)} for how the
+ * <em>name</em> is computed)
*/
class JAXRSAutoRegisterServicesModule extends AbstractModule
{
diff --git a/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/setup/JAXRSClientProvider.java b/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/setup/JAXRSClientProvider.java
index <HASH>..<HASH> 100644
--- a/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/setup/JAXRSClientProvider.java
+++ b/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/setup/JAXRSClientProvider.java
@@ -3,8 +3,14 @@ package com.peterphi.std.guice.web.rest.setup;
import com.google.inject.Inject;
import com.google.inject.TypeLiteral;
import com.peterphi.std.guice.restclient.JAXRSProxyClientFactory;
+
import javax.inject.Provider;
+/**
+ * Builds JAX-RS Proxy Clients for interfaces using {@link com.peterphi.std.guice.restclient.JAXRSProxyClientFactory#getClient(Class)}
+ *
+ * @param <T>
+ */
class JAXRSClientProvider<T> implements Provider<T>
{
private final Class<? extends T> iface;
|
Improve javadoc on service client auto-binding
|
petergeneric_stdlib
|
train
|
dc1b14f4296190f9e294ec47c9c32e8a5fd2dfc7
|
diff --git a/arangodb/api.py b/arangodb/api.py
index <HASH>..<HASH> 100644
--- a/arangodb/api.py
+++ b/arangodb/api.py
@@ -350,6 +350,8 @@ class Database(object):
kwargs=data
)
+ Client.instance().set_database(name=name)
+
return db
@classmethod
|
Now by default a created database will set it's name as default database
|
saeschdivara_ArangoPy
|
train
|
3cabaa734e01ebacab33881824e8b861847a00d6
|
diff --git a/lib/foodcritic/rake_task.rb b/lib/foodcritic/rake_task.rb
index <HASH>..<HASH> 100644
--- a/lib/foodcritic/rake_task.rb
+++ b/lib/foodcritic/rake_task.rb
@@ -23,7 +23,7 @@ module FoodCritic
end
def define
- desc "Lint Chef cookbooks"
+ desc "Lint Chef cookbooks" unless ::Rake.application.last_comment
task(name) do
result = FoodCritic::Linter.new.check(options)
if result.warnings.any?
|
Allow to override description of Rake task
Example:
desc "Run Foodcritic lint checks"
FoodCritic::Rake::LintTask.new
|
Foodcritic_foodcritic
|
train
|
e998d908b213943b5b2d01fc1784786b591340a8
|
diff --git a/spatialist/vector.py b/spatialist/vector.py
index <HASH>..<HASH> 100644
--- a/spatialist/vector.py
+++ b/spatialist/vector.py
@@ -808,6 +808,9 @@ def intersect(obj1, obj2):
if not isinstance(obj1, Vector) or not isinstance(obj2, Vector):
raise RuntimeError('both objects must be of type Vector')
+ obj1 = obj1.clone()
+ obj2 = obj2.clone()
+
obj1.reproject(obj2.srs)
#######################################################
|
[vector.intersect] clone both Vector objects before doing anything
|
johntruckenbrodt_spatialist
|
train
|
1fccbe39e1df4b6c10788a825c4a361624f1feea
|
diff --git a/src/Http/Request.php b/src/Http/Request.php
index <HASH>..<HASH> 100644
--- a/src/Http/Request.php
+++ b/src/Http/Request.php
@@ -292,7 +292,7 @@ class Request
*
* @return string
*/
- public static function buildQueryString(array $data = null)
+ public static function buildQueryString(array $data = null, $urlEncode = true)
{
if ($data === null) {
$data = static::$get;
@@ -301,7 +301,7 @@ class Request
$query = [];
foreach ($data as $name => $value) {
- $query[] = "{$name}=" . urlencode($value);
+ $query[] = "{$name}=" . ($urlEncode ? urlencode($value) : $value);
}
if (count($query)) {
|
Add option to disable url encoding query string.
|
nirix_radium
|
train
|
f484850875c112dc23c8173e1911809e64cf7eb3
|
diff --git a/pypeerassets/protocol.py b/pypeerassets/protocol.py
index <HASH>..<HASH> 100644
--- a/pypeerassets/protocol.py
+++ b/pypeerassets/protocol.py
@@ -277,6 +277,7 @@ class DeckState:
def __init__(self, cards: Generator) -> None:
+ self.cards = cards
self.total = 0
self.burned = 0
self.balances = {}
@@ -322,12 +323,12 @@ class DeckState:
def _sort_cards(self, cards: list) -> None:
'''sort cards by blocknum and blockseq'''
- self.cards = sorted([card.__dict__ for card in cards],
+ return sorted([card.__dict__ for card in cards],
key=itemgetter('blocknum', 'blockseq', 'cardseq'))
def calc_state(self) -> None:
- for card in self._sort_cards:
+ for card in self._sort_cards(self.cards):
# txid + blockseq + cardseq, as unique ID
cid = card["txid"] + str(card["blockseq"]) + str(card["cardseq"])
|
DeckState: fix _sort_cards
|
PeerAssets_pypeerassets
|
train
|
18413201f490630d8adb0c8792ce9764680de180
|
diff --git a/py/apigen/htmlgen.py b/py/apigen/htmlgen.py
index <HASH>..<HASH> 100644
--- a/py/apigen/htmlgen.py
+++ b/py/apigen/htmlgen.py
@@ -322,7 +322,9 @@ class ApiPageBuilder(AbstractPageBuilder):
H.FunctionDef(localname, argdesc),
H.Docstring(docstring or H.em('no docstring available')),
H.div(H.a('show/hide info',
- onclick='showhideel(this.parentNode.lastChild);'),
+ href='#',
+ onclick=('showhideel(this.parentNode.lastChild);'
+ 'return false;')),
H.div(valuedesc, csource, style='display: none',
class_='funcinfo')),
)
|
[svn r<I>] Fixed link (now properly has an href).
--HG--
branch : trunk
|
pytest-dev_pytest
|
train
|
814b36a08a60f4159cdcbb1c466a6a0027440b6c
|
diff --git a/src/JavascriptRenderer.php b/src/JavascriptRenderer.php
index <HASH>..<HASH> 100644
--- a/src/JavascriptRenderer.php
+++ b/src/JavascriptRenderer.php
@@ -63,11 +63,11 @@ class JavascriptRenderer extends BaseJavascriptRenderer
$cssRoute = preg_replace('/\Ahttps?:/', '', $cssRoute);
$jsRoute = preg_replace('/\Ahttps?:/', '', $jsRoute);
- $html = "<link rel='stylesheet' type='text/css' property='stylesheet' href='{$cssRoute}'>";
- $html .= "<script src='{$jsRoute}'></script>";
+ $html = "<link rel='stylesheet' type='text/css' property='stylesheet' href='{$cssRoute}' data-turbolinks-eval='false' data-turbo-eval='false'>";
+ $html .= "<script src='{$jsRoute}' data-turbolinks-eval='false' data-turbo-eval='false'></script>";
if ($this->isJqueryNoConflictEnabled()) {
- $html .= '<script>jQuery.noConflict(true);</script>' . "\n";
+ $html .= '<script data-turbo-eval="false">jQuery.noConflict(true);</script>' . "\n";
}
$html .= $this->getInlineHtml();
|
Turbolinks compatibility (#<I>)
|
barryvdh_laravel-debugbar
|
train
|
f4c9986ab024579d0f4748248aef698f38c69f64
|
diff --git a/as/thrift.js b/as/thrift.js
index <HASH>..<HASH> 100644
--- a/as/thrift.js
+++ b/as/thrift.js
@@ -292,6 +292,7 @@ function send(request, endpoint, outHead, outBody, callback) {
}
};
+/*eslint-disable max-statements */
TChannelAsThrift.prototype._parse = function parse(opts) {
var self = this;
var spec = opts.spec || self.spec;
@@ -364,6 +365,7 @@ TChannelAsThrift.prototype._parse = function parse(opts) {
typeName: typeName
});
};
+/*eslint-enable max-statements */
TChannelAsThrift.prototype._stringify = function stringify(opts) {
var self = this;
|
linting: [as/thrift] comply with max-statements rule
|
uber_tchannel-node
|
train
|
d8468e3bf470c48fe6dcfe9d3a456ffafa1ee40b
|
diff --git a/generators/php/text.js b/generators/php/text.js
index <HASH>..<HASH> 100644
--- a/generators/php/text.js
+++ b/generators/php/text.js
@@ -226,7 +226,7 @@ Blockly.PHP['text_trim'] = function(block) {
Blockly.PHP['text_print'] = function(block) {
// Print statement.
var argument0 = Blockly.PHP.valueToCode(block, 'TEXT',
- Blockly.PHP.ORDER_FUNCTION_CALL) || '\'\'';
+ Blockly.PHP.ORDER_NONE) || '\'\'';
return 'print(' + argument0 + ');\n';
};
|
print statement fix from Neil's comments
|
LLK_scratch-blocks
|
train
|
36801f75fd78e2f8b16894acf4b6dca5d44e82d9
|
diff --git a/packages/neos-ui-guest-frame/src/initializeGuestFrame.js b/packages/neos-ui-guest-frame/src/initializeGuestFrame.js
index <HASH>..<HASH> 100644
--- a/packages/neos-ui-guest-frame/src/initializeGuestFrame.js
+++ b/packages/neos-ui-guest-frame/src/initializeGuestFrame.js
@@ -6,7 +6,7 @@ import {selectors, actions, actionTypes} from '@neos-project/neos-ui-redux-store
import initializeContentDomNode from './initializeContentDomNode';
import {
getGuestFrameWindow,
- getGuestFrameBody,
+ getGuestFrameDocument,
findAllNodesInGuestFrame,
findInGuestFrame,
findNodeInGuestFrame
@@ -55,7 +55,7 @@ export default ({globalRegistry, store}) => function * initializeGuestFrame() {
yield put(actions.UI.ContentCanvas.setPreviewUrl(documentInformation.metaData.previewUrl));
yield put(actions.CR.ContentDimensions.setActive(documentInformation.metaData.contentDimensions.active));
- getGuestFrameBody().addEventListener('click', e => {
+ getGuestFrameDocument().addEventListener('click', e => {
const clickPath = Array.prototype.slice.call(eventPath(e));
const isInsideInlineUi = clickPath.some(domNode =>
domNode &&
|
TASK: Listen to click on guest frame document rather than body
|
neos_neos-ui
|
train
|
59ffd7c33c164a7d0253d62a9050b22afa92029a
|
diff --git a/montblanc/impl/rime/tensorflow/feeders/rime_data_feeder.py b/montblanc/impl/rime/tensorflow/feeders/rime_data_feeder.py
index <HASH>..<HASH> 100644
--- a/montblanc/impl/rime/tensorflow/feeders/rime_data_feeder.py
+++ b/montblanc/impl/rime/tensorflow/feeders/rime_data_feeder.py
@@ -408,7 +408,7 @@ class MSRimeDataFeeder(RimeDataFeeder):
@cache_ms_read
def observed_vis(self, context):
- lrow, urow = context.dim_extents('nuvwrows')
+ lrow, urow = context.dim_extents('nrows')
data = self._tables[ORDERED_MAIN_TABLE].getcol(
DATA, startrow=lrow, nrow=urow-lrow)
@@ -417,7 +417,7 @@ class MSRimeDataFeeder(RimeDataFeeder):
@cache_ms_read
def flag(self, context):
- lrow, urow = context.dim_extents('nuvwrows')
+ lrow, urow = context.dim_extents('nrows')
flag = self._tables[ORDERED_MAIN_TABLE].getcol(
FLAG, startrow=lrow, nrow=urow-lrow)
@@ -426,7 +426,7 @@ class MSRimeDataFeeder(RimeDataFeeder):
@cache_ms_read
def weight(self, context):
- lrow, urow = context.dim_extents('nuvwrows')
+ lrow, urow = context.dim_extents('nrows')
nchan = context.dim_extent_size('nchanperband')
weight = self._tables[ORDERED_MAIN_TABLE].getcol(
|
Correct row dimension for primary MS columns
We have DATA, FLAG and WEIGHT rows for each timestep, baseline and band.
|
ska-sa_montblanc
|
train
|
d36151daa642dff6ffecac9ba1c72efb1cba0f5c
|
diff --git a/src/Illuminate/Foundation/Testing/TestResponse.php b/src/Illuminate/Foundation/Testing/TestResponse.php
index <HASH>..<HASH> 100644
--- a/src/Illuminate/Foundation/Testing/TestResponse.php
+++ b/src/Illuminate/Foundation/Testing/TestResponse.php
@@ -192,7 +192,7 @@ class TestResponse extends Response
*
* @return array
*/
- protected function decodeResponseJson()
+ public function decodeResponseJson()
{
$decodedResponse = json_decode($this->getContent(), true);
|
Make decodeResponseJson from protected to public (#<I>)
|
laravel_framework
|
train
|
addbb35a30526a66fe4526169020f731ae601946
|
diff --git a/heron/tools/tracker/src/python/config.py b/heron/tools/tracker/src/python/config.py
index <HASH>..<HASH> 100644
--- a/heron/tools/tracker/src/python/config.py
+++ b/heron/tools/tracker/src/python/config.py
@@ -50,13 +50,14 @@ class Config:
for extra_link in self.configs[EXTRA_LINKS_KEY]:
self.extra_links.append(self.validate_extra_link(extra_link))
- def validate_extra_link(self, extra_link: dict) -> None:
+ def validate_extra_link(self, extra_link: dict):
"""validate extra link"""
if EXTRA_LINK_NAME_KEY not in extra_link or EXTRA_LINK_FORMATTER_KEY not in extra_link:
raise Exception("Invalid extra.links format. " +
"Extra link must include a 'name' and 'formatter' field")
self.validated_formatter(extra_link[EXTRA_LINK_FORMATTER_KEY])
+ return extra_link
def validated_formatter(self, url_format: str) -> None:
"""Check visualization url format has no unrecongnised parameters."""
@@ -97,4 +98,4 @@ class Config:
@staticmethod
def config_str(config):
keys = ("type", "name", "hostport", "rootpath", "tunnelhost")
- return "".join("\t{k}: {config[k]}\n" for k in keys if k in config).rstrip()
+ return "".join("\t{}: {}\n".format(k, config[k]) for k in keys if k in config).rstrip()
|
Fix extra.links of heron-tracker (#<I>)
|
apache_incubator-heron
|
train
|
1543422a37904f99b7b7fa4e8d7c2d8e9e2e5bc3
|
diff --git a/cdk-data/cdk-data-core/src/test/java/com/cloudera/cdk/data/filesystem/TestFileSystemDatasetRepository.java b/cdk-data/cdk-data-core/src/test/java/com/cloudera/cdk/data/filesystem/TestFileSystemDatasetRepository.java
index <HASH>..<HASH> 100644
--- a/cdk-data/cdk-data-core/src/test/java/com/cloudera/cdk/data/filesystem/TestFileSystemDatasetRepository.java
+++ b/cdk-data/cdk-data-core/src/test/java/com/cloudera/cdk/data/filesystem/TestFileSystemDatasetRepository.java
@@ -21,6 +21,7 @@ import com.cloudera.cdk.data.DatasetRepositoryException;
import com.cloudera.cdk.data.Formats;
import com.cloudera.cdk.data.PartitionStrategy;
import com.google.common.collect.Lists;
+import com.google.common.collect.ImmutableMultiset;
import com.google.common.io.Files;
import java.io.IOException;
import org.apache.avro.Schema;
@@ -79,6 +80,51 @@ public class TestFileSystemDatasetRepository {
}
@Test
+ public void testList() {
+ Assert.assertEquals(ImmutableMultiset.of(),
+ ImmutableMultiset.copyOf(repo.list()));
+
+ repo.create("test1", new DatasetDescriptor.Builder()
+ .schema(testSchema).get());
+ Assert.assertEquals(ImmutableMultiset.of("test1"),
+ ImmutableMultiset.copyOf(repo.list()));
+
+ repo.create("test2", new DatasetDescriptor.Builder()
+ .schema(testSchema).get());
+ Assert.assertEquals(ImmutableMultiset.of("test1", "test2"),
+ ImmutableMultiset.copyOf(repo.list()));
+
+ repo.create("test3", new DatasetDescriptor.Builder()
+ .schema(testSchema).get());
+ Assert.assertEquals(ImmutableMultiset.of("test1", "test2", "test3"),
+ ImmutableMultiset.copyOf(repo.list()));
+
+ repo.delete("test2");
+ Assert.assertEquals(ImmutableMultiset.of("test1", "test3"),
+ ImmutableMultiset.copyOf(repo.list()));
+
+ repo.delete("test3");
+ Assert.assertEquals(ImmutableMultiset.of("test1"),
+ ImmutableMultiset.copyOf(repo.list()));
+
+ repo.delete("test1");
+ Assert.assertEquals(ImmutableMultiset.of(),
+ ImmutableMultiset.copyOf(repo.list()));
+ }
+
+ @Test
+ public void testExists() {
+ Assert.assertFalse(repo.exists("test1"));
+
+ repo.create("test1", new DatasetDescriptor.Builder()
+ .schema(testSchema).get());
+ Assert.assertTrue(repo.exists("test1"));
+
+ repo.delete("test1");
+ Assert.assertFalse(repo.exists("test1"));
+ }
+
+ @Test
public void testCreatePartitioned() throws IOException {
DatasetDescriptor descriptor = new DatasetDescriptor.Builder()
.schema(testSchema)
|
CDK-<I>: Adding FS tests for new repo API methods.
|
kite-sdk_kite
|
train
|
6cdc30afb66b8698d3dd69d2fac4211efb754454
|
diff --git a/sebastian/core/elements.py b/sebastian/core/elements.py
index <HASH>..<HASH> 100644
--- a/sebastian/core/elements.py
+++ b/sebastian/core/elements.py
@@ -1,4 +1,14 @@
from collections import Iterable
+import tempfile
+import subprocess as sp
+from StringIO import StringIO
+try:
+ from IPython.core.display import Image
+ ipython = True
+except ImportError:
+ ipython = False
+
+from sebastian.lilypond import write_lilypond
class UnificationError(Exception):
@@ -64,6 +74,27 @@ class SeqBase:
__or__ = transform
+ def _repr_png_(self):
+ """
+ Return a PNG representation of this sequence for IPython Notebook.
+ """
+ if not ipython:
+ return None
+
+ from sebastian.core.transforms import lilypond
+ seq = HSeq(self) | lilypond()
+ f = tempfile.NamedTemporaryFile(suffix=".preview.png")
+ basename = f.name[:-12] # everything except ".preview.png"
+
+ p = sp.Popen(["lilypond", "--png", "-dno-print-pages",
+ "-dpreview", "-o"+basename, "-"], stdin=sp.PIPE)
+ p.communicate(write_lilypond.output(seq))
+ if p.returncode != 0:
+ # there was an error
+ return None
+
+ return f.read()
+
def OSeq(offset_attr, duration_attr):
|
Output sequence in PNG for iPython Notebook
|
jtauber_sebastian
|
train
|
cd95a374bd38e3e4b1a1c4a1ef906f1099cb93e0
|
diff --git a/lib/textlint/plugin.rb b/lib/textlint/plugin.rb
index <HASH>..<HASH> 100644
--- a/lib/textlint/plugin.rb
+++ b/lib/textlint/plugin.rb
@@ -12,15 +12,15 @@ module Danger
#
# You should replace these comments with a public description of your library.
#
- # @example Run textlint and send as inline comment.
+ # @example Run textlint and send violations as inline comment.
#
- # textlint.lint "./articles/*.md"
- # textlint.lint "./articles/*.md"
+ # # Lint added and modified files only
+ # textlint.lint
#
- # @example Keep severity until warning.
+ # @example Keep severity until warning. It allows merging pull request if there are violations remaining.
#
# textlint.max_severity = "warn"
- # textlint.lint "./articles/*.md"
+ # textlint.lint
#
# @see Kesin11/danger-textlint
# @tags lint, textlint
@@ -36,12 +36,10 @@ module Danger
attr_accessor :max_severity
# Execute textlint and send comment
- # @param [String]
- # textlint target file(OR dir) path
# @return [void]
- def lint(target_path)
+ def lint
bin = textlint_path
- result_json = run_textlint(bin, target_path)
+ result_json = run_textlint(bin, target_files)
errors = parse(result_json)
send_comment(errors)
end
@@ -79,19 +77,23 @@ module Danger
File.exist?(local) ? local : find_executable("textlint")
end
- def textlint_command(bin, target_path)
+ def textlint_command(bin, target_files)
command = "#{bin} -f json"
command << " -c #{config_file}" if config_file
- command = "#{command} #{target_path}"
+ command = "#{command} #{target_files.join(' ')}"
p command
command
end
- def run_textlint(bin, target_path)
- command = textlint_command(bin, target_path)
+ def run_textlint(bin, target_files)
+ command = textlint_command(bin, target_files)
`#{command}`
end
+ def target_files
+ ((git.modified_files - git.deleted_files) + git.added_files)
+ end
+
def send_comment(errors)
errors.each do |error|
send(error[:severity], error[:message], file: error[:file_path], line: error[:line])
diff --git a/spec/textlint_spec.rb b/spec/textlint_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/textlint_spec.rb
+++ b/spec/textlint_spec.rb
@@ -9,6 +9,9 @@ module Danger
# stub
allow(Dir).to receive(:pwd).and_return("/Users/your/github/sample_repository")
allow(@textlint).to receive(:textlint_path).and_return("./node_modules/.bin/textlint")
+ allow(@textlint.git).to receive(:added_files).and_return([])
+ allow(@textlint.git).to receive(:modified_files).and_return([])
+ allow(@textlint.git).to receive(:deleted_files).and_return([])
end
let(:fixture) do
@@ -98,5 +101,28 @@ module Danger
end
end
end
+
+ describe ".target_files" do
+ let(:file1) { "articles/1.md" }
+ let(:file2) { "articles/2.md" }
+ let(:file3) { "articles/3.md" }
+
+ before do
+ allow(@textlint.git).to receive(:added_files).and_return([file1])
+ allow(@textlint.git).to receive(:modified_files).and_return([file2])
+ end
+
+ it "are add and modified files only" do
+ allow(@textlint.git).to receive(:deleted_files).and_return([])
+
+ expect(@textlint.send(:target_files)).to match_array([file1, file2])
+ end
+
+ it "are also include removed file" do
+ allow(@textlint.git).to receive(:deleted_files).and_return([file3])
+
+ expect(@textlint.send(:target_files)).to match_array([file1, file2])
+ end
+ end
end
end
|
Fix for target files are corrected from git status.
|
Kesin11_danger-textlint
|
train
|
f176f20b8e2d20a0069f8b32617396f21d4745eb
|
diff --git a/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java b/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java
index <HASH>..<HASH> 100644
--- a/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java
+++ b/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java
@@ -788,9 +788,6 @@ public abstract class AbstractCommandLineRunner<A extends Compiler,
/** Creates JS extern inputs from a list of files. */
@GwtIncompatible("Unnecessary")
private List<SourceFile> createExternInputs(List<String> files) throws IOException {
- if (files.isEmpty()) {
- return ImmutableList.of(SourceFile.fromCode("/dev/null", ""));
- }
List<FlagEntry<JsSourceType>> externFiles = new ArrayList<>();
for (String file : files) {
externFiles.add(new FlagEntry<JsSourceType>(JsSourceType.EXTERN, file));
|
Do not add an empty externs file when no externs have been given
-------------
Created by MOE: <URL>
|
google_closure-compiler
|
train
|
03f5f57af03b8fa251dc2a0bbc27960a61fce9ca
|
diff --git a/activestorage/test/models/attached/many_test.rb b/activestorage/test/models/attached/many_test.rb
index <HASH>..<HASH> 100644
--- a/activestorage/test/models/attached/many_test.rb
+++ b/activestorage/test/models/attached/many_test.rb
@@ -325,12 +325,12 @@ class ActiveStorage::ManyAttachedTest < ActiveSupport::TestCase
test "attaching an existing blob from a signed ID to a new record" do
User.new(name: "Jason").tap do |user|
- user.avatar.attach create_blob(filename: "funky.jpg").signed_id
+ user.highlights.attach create_blob(filename: "funky.jpg").signed_id
assert user.new_record?
- assert_equal "funky.jpg", user.avatar.filename.to_s
+ assert_equal "funky.jpg", user.highlights.first.filename.to_s
user.save!
- assert_equal "funky.jpg", user.reload.avatar.filename.to_s
+ assert_equal "funky.jpg", user.reload.highlights.first.filename.to_s
end
end
|
Test Attached::Many in Attached::Many test
This exact test exists in `one_test.rb`. It was probably overlooked
after being copied and pasted.
|
rails_rails
|
train
|
4a0f96d15c904c5006b14b97172f1f75d0aadd43
|
diff --git a/app/assets/javascripts/auth/users/profiles.js b/app/assets/javascripts/auth/users/profiles.js
index <HASH>..<HASH> 100644
--- a/app/assets/javascripts/auth/users/profiles.js
+++ b/app/assets/javascripts/auth/users/profiles.js
@@ -3,7 +3,7 @@
$(document).on("click","#get_activities",function(event){
var now = moment();
var now_start = now.unix();
- var startDate = now.startOf("year");
+ var startDate = now.startOf("month");
$.get( "/activities/get_activities",
{ user_id: $("#user_data").data("resource").id, range: {from: startDate.unix(), to: now_start} , only:["image_url"]},
function(data){
@@ -13,4 +13,6 @@ $(document).on("click","#get_activities",function(event){
"json"
);
-})
\ No newline at end of file
+});
+
+
diff --git a/app/models/auth/activity.rb b/app/models/auth/activity.rb
index <HASH>..<HASH> 100644
--- a/app/models/auth/activity.rb
+++ b/app/models/auth/activity.rb
@@ -4,40 +4,48 @@ module Auth
include Mongoid::Timestamps
field :user_id, type: BSON::ObjectId
- field :image_url, type: String, default: "/assets/auth/activity.jpg"
-
+ field :image_url, type: String
+
##@param[Hash] {"range" : {"from" : unix_epoch_as_string, "to" => unix_epoch_as_string}, "user_id": string, "only": [array_of_attributes_required]}
+ ##"range" => optional,if nil or empty, "from" and "to" will be automatically assigned to beginning_of_current_month and current_time respectively
+ ##"user_id" => required, will return empty hash if absent.
+ ##"only" => optional, will default to all attributes of the activity model.
##@return[Hash]: timestamp => activity_object hashified.
def self.get_in_range(params)
- ## return empty hash if there is no range
- return {} unless params[:range]
- ## return empty has if the range does not have a :from parameter
- return {} unless params[:range][:from]
+
## return empty hash if there is no user_id
return {} unless params[:user_id]
+
+ ## merge defaults
+ defaults = {"range" => {"from" => Time.now.beginning_of_month.to_i, "to" => Time.now.to_i}, "only" => Auth::Activity.fields.keys}
+ params = defaults.deep_merge(params)
+
##default from and to assigned here.
- from = params[:range][:from].to_i
- to = params[:range][:to].nil? ? Time.now.to_i : params[:range][:to].to_i
+ from = params["range"]["from"].to_i
+ to = params["range"]["to"].to_i
if from >= to
from = Time.now.beginning_of_month.to_i
to = Time.now.to_i
end
+
+
##defaults for only.
##if it is empty or nil, then it becomes all attributes
##otherwise it becomes the intersect of all attributes and the ones specified in the only
##created_at had to be added here, because otherwise it throws an error saying missing_attribute in the only. I think this has something to do with the fact that it is used in the query, so it will be included in the result.
- only = params[:only].blank? ? Auth::Activity.new.attributes.keys : ((Auth::Activity.new.attributes.keys & params[:only]) + [:created_at])
+ only = ((Auth::Activity.fields.keys & params["only"]) + ["created_at"])
##make the mongoid range call here.
- activities = Auth::Activity.where(:created_at.gte => from, :created_at.lte => to, :user_id => params[:user_id]).only(only)
+ activities = Auth::Activity.where(:created_at.gte => from, :created_at.lte => to, :user_id => params["user_id"]).only(only)
activities_hash = Hash[activities.entries.map{|c| c.created_at.to_i}.zip(activities.entries.map{|c| c.as_json})]
puts JSON.pretty_generate(activities_hash)
return activities_hash
+
end
############################################################
## Convenience functions, currently not used anywhere, just used once in rails console, to create 5 dummy activities.
|
all options for Auth::Activity.get_in_range now work, move onto integration with collage
|
wordjelly_Auth
|
train
|
2ffac1635a473a45ff14e138b84f06edd11e76ef
|
diff --git a/src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php b/src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php
index <HASH>..<HASH> 100644
--- a/src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php
+++ b/src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php
@@ -503,7 +503,7 @@ class HasManyThrough extends Relation
{
$query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash());
- $query->join($this->throughParent->getTable(), $this->getQualifiedParentKeyName(), '=', $hash.'.'.$this->secondLocalKey);
+ $query->join($this->throughParent->getTable(), $this->getQualifiedParentKeyName(), '=', $hash.'.'.$this->secondKey);
if ($this->throughParentSoftDeletes()) {
$query->whereNull($this->throughParent->getQualifiedDeletedAtColumn());
diff --git a/tests/Integration/Database/EloquentHasManyThroughTest.php b/tests/Integration/Database/EloquentHasManyThroughTest.php
index <HASH>..<HASH> 100644
--- a/tests/Integration/Database/EloquentHasManyThroughTest.php
+++ b/tests/Integration/Database/EloquentHasManyThroughTest.php
@@ -33,7 +33,7 @@ class EloquentHasManyThroughTest extends DatabaseTestCase
{
$user = User::create(['name' => str_random()]);
- $team1 = Team::create(['owner_id' => $user->id]);
+ $team1 = Team::create(['id' => 10, 'owner_id' => $user->id]);
$team2 = Team::create(['owner_id' => $user->id]);
$mate1 = User::create(['name' => str_random(), 'team_id' => $team1->id]);
@@ -127,5 +127,5 @@ class Team extends Model
{
public $table = 'teams';
public $timestamps = false;
- protected $guarded = ['id'];
+ protected $guarded = [];
}
|
Fix self-referencing HasManyThrough existence queries (#<I>)
|
laravel_framework
|
train
|
6008cea67a4306e00e5619f8c5f15986c0490cd5
|
diff --git a/properties/base/containers.py b/properties/base/containers.py
index <HASH>..<HASH> 100644
--- a/properties/base/containers.py
+++ b/properties/base/containers.py
@@ -180,7 +180,6 @@ class Tuple(basic.Property):
def __init__(self, doc, prop, **kwargs):
self.prop = prop
super(Tuple, self).__init__(doc, **kwargs)
- # self._unused_default_warning()
@property
def prop(self):
@@ -551,3 +550,61 @@ class Dict(basic.Property):
if self.value_prop:
self.value_prop.assert_valid(instance, val)
return True
+
+ def serialize(self, value, **kwargs):
+ """Return a serialized copy of the dict"""
+ kwargs.update({'include_class': kwargs.get('include_class', True)})
+ if self.serializer is not None:
+ return self.serializer(value, **kwargs)
+ if value is None:
+ return None
+ serial_tuples = [
+ (
+ self.key_prop.serialize(key, **kwargs),
+ self.value_prop.serialize(val, **kwargs)
+ )
+ for key, val in iteritems(value)
+ ]
+ try:
+ serial_dict = {key: val for key, val in serial_tuples}
+ except TypeError as er:
+ raise TypeError('Dict property {} cannot be serialized. '
+ 'Serialized keys contain {}'.format(self.name, er))
+ return serial_dict
+
+ def deserialize(self, value, **kwargs):
+ """Return a deserialized copy of the dict"""
+ kwargs.update({'trusted': kwargs.get('trusted', False)})
+ if self.deserializer is not None:
+ return self.deserializer(value, **kwargs)
+ if value is None:
+ return None
+ output_tuples = [
+ (
+ self.key_prop.deserialize(key, **kwargs),
+ self.value_prop.deserialize(val, **kwargs)
+ )
+ for key, val in iteritems(value)
+ ]
+ try:
+ output_dict = {key: val for key, val in output_tuples}
+ except TypeError as er:
+ raise TypeError('Dict property {} cannot be deserialized. '
+ 'Keys contain {}'.format(self.name, er))
+ return self._class_default(output_dict)
+
+ @staticmethod
+ def to_json(value, **kwargs):
+ """Return a copy of the dictionary
+
+ If the values are HasProperties instances, they are serialized
+ """
+ serial_dict = {
+ key: (
+ val.serialize(**kwargs) if isinstance(val, HasProperties)
+ else val
+ )
+ for key, val in iteritems(value)
+
+ }
+ return serial_dict
|
Add serialization/deserialization to Dict property
|
seequent_properties
|
train
|
f9715644a644b04c7406ac3913ab488f3b1bec08
|
diff --git a/src/Illuminate/View/View.php b/src/Illuminate/View/View.php
index <HASH>..<HASH> 100755
--- a/src/Illuminate/View/View.php
+++ b/src/Illuminate/View/View.php
@@ -2,6 +2,7 @@
namespace Illuminate\View;
+use Closure;
use Exception;
use Throwable;
use ArrayAccess;
@@ -161,6 +162,8 @@ class View implements ArrayAccess, ViewContract
foreach ($data as $key => $value) {
if ($value instanceof Renderable) {
$data[$key] = $value->render();
+ } elseif ($value instanceof Closure) {
+ $data[$key] = call_user_func($value);
}
}
|
[<I>] Allow passing a Closure to View::share() method (#<I>)
* [<I>] Allow passing a Closure to View::share() method
Allows you to pass a Closure as the $value parameter to View::share() method.
* Fix StyleCI
|
laravel_framework
|
train
|
de959a317c7d57ba596f1bdd5eb02cbf3dd78d21
|
diff --git a/plugins/CorePluginsAdmin/Controller.php b/plugins/CorePluginsAdmin/Controller.php
index <HASH>..<HASH> 100644
--- a/plugins/CorePluginsAdmin/Controller.php
+++ b/plugins/CorePluginsAdmin/Controller.php
@@ -143,9 +143,8 @@ class Controller extends \Piwik\Controller\Admin
$view = $this->configureView('@CorePluginsAdmin/browsePlugins');
$plugins = $marketplace->searchForPlugins('', $query, $sort);
- $loadedPlugins = PluginsManager::getInstance()->getLoadedPlugins();
foreach ($plugins as $plugin) {
- $plugin->isInstalled = !empty($loadedPlugins[$plugin->name]);
+ $plugin->isInstalled = PluginsManager::getInstance()->isPluginLoaded($plugin->name);
$plugin->lastUpdated = Date::factory($plugin->lastUpdated)->getLocalized(Piwik_Translate('CoreHome_ShortDateFormatWithYear'));
}
@@ -170,9 +169,8 @@ class Controller extends \Piwik\Controller\Admin
$view = $this->configureView('@CorePluginsAdmin/browseThemes');
$plugins = $marketplace->searchForThemes('', $query, $sort);
- $loadedPlugins = PluginsManager::getInstance()->getLoadedPlugins();
foreach ($plugins as $plugin) {
- $plugin->isInstalled = !empty($loadedPlugins[$plugin->name]);
+ $plugin->isInstalled = PluginsManager::getInstance()->isPluginLoaded($plugin->name);
$plugin->lastUpdated = Date::factory($plugin->lastUpdated)->getLocalized(Piwik_Translate('CoreHome_ShortDateFormatWithYear'));
}
@@ -362,10 +360,14 @@ class Controller extends \Piwik\Controller\Admin
$marketplace = new MarketplaceApiClient();
- if ($themesOnly) {
- $pluginsHavingUpdate = $marketplace->getInfoOfThemesHavingUpdate($loadedPlugins);
- } else {
- $pluginsHavingUpdate = $marketplace->getInfoOfPluginsHavingUpdate($loadedPlugins);
+ try {
+ if ($themesOnly) {
+ $pluginsHavingUpdate = $marketplace->getInfoOfThemesHavingUpdate($loadedPlugins);
+ } else {
+ $pluginsHavingUpdate = $marketplace->getInfoOfPluginsHavingUpdate($loadedPlugins);
+ }
+ } catch (\Exception $e) {
+ $pluginsHavingUpdate = array();
}
foreach ($pluginsHavingUpdate as $updatePlugin) {
|
refs #<I> catch possible error while fetching plugins from marketplace
|
matomo-org_matomo
|
train
|
bb52715ae44a5c09bb633f01ae8b8aedb88273a7
|
diff --git a/lib/escher/auth.rb b/lib/escher/auth.rb
index <HASH>..<HASH> 100644
--- a/lib/escher/auth.rb
+++ b/lib/escher/auth.rb
@@ -38,6 +38,8 @@ module Escher
begin
authenticate(*args)
return true
+ rescue EscherError
+ return false
rescue
return false
end
|
SECURITY-<I>: Specification of the caught exception
|
emartech_escher-ruby
|
train
|
7e628695d78b98f30dc7601af3bfc94f6d323e7f
|
diff --git a/emk.js b/emk.js
index <HASH>..<HASH> 100644
--- a/emk.js
+++ b/emk.js
@@ -878,8 +878,14 @@ module.exports = async() => {
],
run: /* syntax: bash */ `
+ # package directory relative to project root
+ PACKAGE_DIR='build/${s_channel}/package/${si_package}'
+
+ # copy .npmrc to package dir
+ cp .npmrc "$PACKAGE_DIR"
+
# enter package directory
- cd build/${s_channel}/package/${si_package}
+ cd "$PACKAGE_DIR"
# remove package lock
rm -f package-lock.json
|
fix(emk): .npmrc for links
|
blake-regalia_graphy.js
|
train
|
eaec9140aded97d4c922be6a1d0ac092ccff1531
|
diff --git a/packages/htmltopdf/src/Report/PdfReport.php b/packages/htmltopdf/src/Report/PdfReport.php
index <HASH>..<HASH> 100644
--- a/packages/htmltopdf/src/Report/PdfReport.php
+++ b/packages/htmltopdf/src/Report/PdfReport.php
@@ -74,7 +74,7 @@ class PdfReport implements ReportInterface
*
* @param array $options
*/
- public function setOptions(array $options)
+ public function setOptions(array $options): void
{
$this->pdfRender->setOptions($options);
}
@@ -90,7 +90,7 @@ class PdfReport implements ReportInterface
/**
* @param string $path
*/
- public function setBinPath(?string $path)
+ public function setBinPath(?string $path): void
{
$this->pdfRender->binary = $path;
}
@@ -99,6 +99,8 @@ class PdfReport implements ReportInterface
{
$this->pdfRender->addPage($html);
- return $this->pdfRender->toString();
+ $result = $this->pdfRender->toString();
+
+ return $result === false ? null : $result;
}
}
|
Fix PHPStan level 5 in report package
|
giansalex_greenter
|
train
|
428953db532f3da18e3bd922855a748a51fc3a21
|
diff --git a/js/cbrowser.js b/js/cbrowser.js
index <HASH>..<HASH> 100644
--- a/js/cbrowser.js
+++ b/js/cbrowser.js
@@ -889,7 +889,10 @@ Browser.prototype.realMakeTier = function(source) {
yAtLastReorder = ev.clientY;
}
- dragLabel.style.left = label.getBoundingClientRect().left + 'px'; dragLabel.style.top = ev.clientY - 10 + 'px';
+
+ var holderBCR = thisB.svgHolder.getBoundingClientRect();
+ dragLabel.style.left = (label.getBoundingClientRect().left - holderBCR.left) + 'px';
+ dragLabel.style.top = (ev.clientY - holderBCR.top - 10) + 'px';
var pty = ev.clientY - thisB.tierHolder.getBoundingClientRect().top;
for (var ti = 0; ti < thisB.tiers.length; ++ti) {
|
Drag tier-drag labels in the right place regardless of how other
elements have been positioned.
|
dasmoth_dalliance
|
train
|
d2e1e17ab507c4f70b5361b5fb1c376bc5a77d09
|
diff --git a/app/services/person_search.rb b/app/services/person_search.rb
index <HASH>..<HASH> 100644
--- a/app/services/person_search.rb
+++ b/app/services/person_search.rb
@@ -8,24 +8,32 @@ class PersonSearch
def perform_search
return [] if @query.blank?
- name_matches, query_matches, fuzzy_matches = perform_searches
- exact_matches = name_matches.select { |p| p.name == @query }
-
- exact_matches.
- push(*name_matches).
- push(*query_matches).
- push(*fuzzy_matches).
- uniq[0..@max - 1]
+ email_match = email_search
+ if email_match
+ [email_match]
+ else
+ exact_matches, name_matches, query_matches, fuzzy_matches = perform_searches
+ exact_matches.
+ push(*name_matches).
+ push(*query_matches).
+ push(*fuzzy_matches).
+ uniq[0..@max - 1]
+ end
end
private
+ def email_search
+ Person.find_by_email(@query.downcase)
+ end
+
def perform_searches
name_matches = search "name:#{@query}"
query_matches = search @query
fuzzy_matches = fuzzy_search
+ exact_matches = name_matches.select { |p| p.name == @query }
- [name_matches, query_matches, fuzzy_matches]
+ [exact_matches, name_matches, query_matches, fuzzy_matches]
end
def fuzzy_search
diff --git a/spec/services/person_search_spec.rb b/spec/services/person_search_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/services/person_search_spec.rb
+++ b/spec/services/person_search_spec.rb
@@ -35,6 +35,11 @@ RSpec.describe PersonSearch, elastic: true do
Person.__elasticsearch__.client.indices.refresh
end
+ it 'searches by email' do
+ results = search_for(alice.email.upcase)
+ expect(results).to eq [alice]
+ end
+
it 'searches by surname' do
results = search_for('Andrews')
expect(results).to include(alice)
|
Return email exact matches in search results
Search database for emails that match lowercased search query.
|
ministryofjustice_peoplefinder
|
train
|
b4ab6c1815e51fb7628df1f75838b8420e74ab53
|
diff --git a/de.tudarmstadt.ukp.wikipedia.datamachine/src/main/java/de/tudarmstadt/ukp/wikipedia/datamachine/dump/version/SingleDumpVersionJDKGeneric.java b/de.tudarmstadt.ukp.wikipedia.datamachine/src/main/java/de/tudarmstadt/ukp/wikipedia/datamachine/dump/version/SingleDumpVersionJDKGeneric.java
index <HASH>..<HASH> 100644
--- a/de.tudarmstadt.ukp.wikipedia.datamachine/src/main/java/de/tudarmstadt/ukp/wikipedia/datamachine/dump/version/SingleDumpVersionJDKGeneric.java
+++ b/de.tudarmstadt.ukp.wikipedia.datamachine/src/main/java/de/tudarmstadt/ukp/wikipedia/datamachine/dump/version/SingleDumpVersionJDKGeneric.java
@@ -4,7 +4,7 @@
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
- *
+ *
* Contributors:
* Torsten Zesch - initial API and implementation
******************************************************************************/
@@ -32,6 +32,8 @@ public class SingleDumpVersionJDKGeneric<KeyType, HashAlgorithm extends IStringH
extends AbstractDumpVersion {
private static final String SQL_NULL = "NULL";
+ //TODO This constant is used to flag page titles of discussion pages.
+ // We should make this configurable.
private static final String DISCUSSION_FLAG = "Discussion:";
private Map<Integer, String> pPageIdNameMap;
|
Added TODO to DISCUSSION_FLAG
|
dkpro_dkpro-jwpl
|
train
|
7c986efcdeb6634ac365cb272d289a624cb5f409
|
diff --git a/src/d3.flame.js b/src/d3.flame.js
index <HASH>..<HASH> 100644
--- a/src/d3.flame.js
+++ b/src/d3.flame.js
@@ -67,7 +67,7 @@
if (childValues < root.value) {
root.children.push(
{
- "name": null,
+ "name": "",
"value": root.value - childValues,
"dummy": true
}
|
Changing dummy frame names so they don't mess with sorting.
|
spiermar_d3-flame-graph
|
train
|
6815ce0be7febfea9b45643fb6b5e77e610bf0e6
|
diff --git a/activesupport/lib/active_support/deprecation/constant_accessor.rb b/activesupport/lib/active_support/deprecation/constant_accessor.rb
index <HASH>..<HASH> 100644
--- a/activesupport/lib/active_support/deprecation/constant_accessor.rb
+++ b/activesupport/lib/active_support/deprecation/constant_accessor.rb
@@ -15,7 +15,7 @@ module ActiveSupport
#
# PLANETS = %w(mercury venus earth mars jupiter saturn uranus neptune pluto)
#
- # (In a later update, the original implementation of `PLANETS` has been removed.)
+ # # (In a later update, the original implementation of `PLANETS` has been removed.)
#
# PLANETS_POST_2006 = %w(mercury venus earth mars jupiter saturn uranus neptune)
# include ActiveSupport::Deprecation::DeprecatedConstantAccessor
diff --git a/activesupport/lib/active_support/deprecation/proxy_wrappers.rb b/activesupport/lib/active_support/deprecation/proxy_wrappers.rb
index <HASH>..<HASH> 100644
--- a/activesupport/lib/active_support/deprecation/proxy_wrappers.rb
+++ b/activesupport/lib/active_support/deprecation/proxy_wrappers.rb
@@ -113,7 +113,7 @@ module ActiveSupport
#
# PLANETS = %w(mercury venus earth mars jupiter saturn uranus neptune pluto)
#
- # (In a later update, the original implementation of `PLANETS` has been removed.)
+ # # (In a later update, the original implementation of `PLANETS` has been removed.)
#
# PLANETS_POST_2006 = %w(mercury venus earth mars jupiter saturn uranus neptune)
# PLANETS = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('PLANETS', 'PLANETS_POST_2006')
|
Formatting fix for example code
Just cleaning up the formatting of the example code here to format an inline bit of commentary as a comment.
Before:

After:

[ci skip]
|
rails_rails
|
train
|
cefd25ce9a2fdb37e4deecc743a2c58cafecdf3f
|
diff --git a/swift_test.go b/swift_test.go
index <HASH>..<HASH> 100644
--- a/swift_test.go
+++ b/swift_test.go
@@ -929,6 +929,49 @@ func TestObjectOpenSeek(t *testing.T) {
}
}
+// Test seeking to the end to find the file size
+func TestObjectOpenSeekEnd(t *testing.T) {
+ file, _, err := c.ObjectOpen(CONTAINER, OBJECT, true, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ n, err := file.Seek(0, 2) // seek to end
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n != CONTENT_SIZE {
+ t.Fatal("Wrong offset", n)
+ }
+
+ // Now check reading returns EOF
+ buf := make([]byte, 16)
+ nn, err := io.ReadFull(file, buf)
+ if err != io.EOF {
+ t.Fatal(err)
+ }
+ if nn != 0 {
+ t.Fatal("wrong length", n)
+ }
+
+ // Now seek back to start and check we can read the file
+ n, err = file.Seek(0, 0) // seek to start
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n != 0 {
+ t.Fatal("Wrong offset", n)
+ }
+
+ // read file and check contents
+ buf, err = ioutil.ReadAll(file)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(buf) != CONTENTS {
+ t.Fatal("wrong contents", string(buf))
+ }
+}
+
func TestObjectUpdate(t *testing.T) {
err := c.ObjectUpdate(CONTAINER, OBJECT, m1.ObjectHeaders())
if err != nil {
|
Add test for seeking to end of file
|
ncw_swift
|
train
|
6d8f6d2d374c029fa35aeda08f449a4bbb0dceb1
|
diff --git a/spec/controllers/harvest_sources_controller_spec.rb b/spec/controllers/harvest_sources_controller_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/controllers/harvest_sources_controller_spec.rb
+++ b/spec/controllers/harvest_sources_controller_spec.rb
@@ -3,21 +3,18 @@ require 'spec_helper'
describe Krikri::HarvestSourcesController, :type => :controller do
routes { Krikri::Engine.routes }
-
- before(:all) do
- @harvest_sources_factory = create(:krikri_harvest_sources)
- end
+ let (:harvest_source) { create(:krikri_harvest_source) }
describe '#show' do
login_user
it 'assigns the requested harvest source to @harvest_source' do
- get :show, id: @harvest_sources_factory.id
- expect(assigns(:harvest_source)).to eq(@harvest_sources_factory)
+ get :show, id: harvest_source.id
+ expect(assigns(:harvest_source)).to eq(harvest_source)
end
it 'renders the :show view' do
- get :show, id: @harvest_sources_factory.id
+ get :show, id: harvest_source.id
expect(response).to render_template('krikri/harvest_sources/show')
end
end
diff --git a/spec/controllers/institutions_controller_spec.rb b/spec/controllers/institutions_controller_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/controllers/institutions_controller_spec.rb
+++ b/spec/controllers/institutions_controller_spec.rb
@@ -4,14 +4,14 @@ require 'database_cleaner'
describe Krikri::InstitutionsController, :type => :controller do
routes { Krikri::Engine.routes }
+ let (:harvest_source) { create(:krikri_harvest_source) }
+ let (:institution) { harvest_source.institution }
before(:all) do
# This clean statement is a safety precaution
# Occasionally there is an extra institution written to the test db
# for a reason I am yet to ascertain
DatabaseCleaner.clean_with(:truncation)
- @harvest_sources_factory = create(:krikri_harvest_sources)
- @institutions_factory = @harvest_sources_factory.institution
end
describe 'GET #index' do
@@ -19,7 +19,7 @@ describe Krikri::InstitutionsController, :type => :controller do
it 'assigns all institutions to @institutions' do
get :index
- expect(assigns(:institutions)).to eq([@institutions_factory])
+ expect(assigns(:institutions)).to eq([institution])
end
it 'renders the :index view' do
@@ -33,17 +33,17 @@ describe Krikri::InstitutionsController, :type => :controller do
login_user
it 'assigns the requested institution to @institution' do
- get :show, id: @institutions_factory.id
- expect(assigns(:institution)).to eq(@institutions_factory)
+ get :show, id: institution.id
+ expect(assigns(:institution)).to eq(institution)
end
it 'assigns associated harvest sources to @harvest_sources' do
- get :show, id: @institutions_factory.id
- expect(assigns(:harvest_sources)).to eq([@harvest_sources_factory])
+ get :show, id: institution.id
+ expect(assigns(:harvest_sources)).to eq([harvest_source])
end
it 'renders the :show view' do
- get :show, id: @institutions_factory.id
+ get :show, id: institution.id
expect(response).to render_template('krikri/institutions/show')
end
end
diff --git a/spec/factories/krikri_harvest_sources.rb b/spec/factories/krikri_harvest_sources.rb
index <HASH>..<HASH> 100644
--- a/spec/factories/krikri_harvest_sources.rb
+++ b/spec/factories/krikri_harvest_sources.rb
@@ -1,12 +1,12 @@
FactoryGirl.define do
- factory :krikri_harvest_sources, class: Krikri::HarvestSource do
+ factory :krikri_harvest_source, class: Krikri::HarvestSource do
name 'OAI feed'
source_type 'OAI'
metadata_schema 'MARC'
uri 'http://www.example.com'
notes 'These are notes about the Krikri Sample Source.'
- association :institution, factory: :krikri_institutions
+ association :institution, factory: :krikri_institution
end
end
diff --git a/spec/factories/krikri_institutions.rb b/spec/factories/krikri_institutions.rb
index <HASH>..<HASH> 100644
--- a/spec/factories/krikri_institutions.rb
+++ b/spec/factories/krikri_institutions.rb
@@ -1,6 +1,6 @@
FactoryGirl.define do
- factory :krikri_institutions, class: Krikri::Institution do
+ factory :krikri_institution, class: Krikri::Institution do
name 'Krikri Sample Institution'
notes 'These are notes about the Krikri Sample Institution.'
end
|
Fix spec style
- Singular factory names
- Use 'let' statements to assign factories
|
dpla_KriKri
|
train
|
33e4f82d7c94bb621767df1a5a101882d26bda08
|
diff --git a/internal/graphicsutil/vertices.go b/internal/graphicsutil/vertices.go
index <HASH>..<HASH> 100644
--- a/internal/graphicsutil/vertices.go
+++ b/internal/graphicsutil/vertices.go
@@ -69,7 +69,9 @@ func QuadVertices(width, height int, sx0, sy0, sx1, sy1 int, a, b, c, d, tx, ty
}
func quadVerticesImpl(x, y, u0, v0, u1, v1, a, b, c, d, tx, ty float32) []float32 {
- vs := theVerticesBackend.sliceForOneQuad()
+ // Specifying a range explicitly here is redundant but this helps optimization
+ // to eliminate boundry checks.
+ vs := theVerticesBackend.sliceForOneQuad()[0:24]
ax, by, cx, dy := a*x, b*y, c*x, d*y
|
graphicsutil: Optimization to avoid boundary checks
|
hajimehoshi_ebiten
|
train
|
5bd72238016869079487cfbd0bf6de8739128e56
|
diff --git a/climlab/dynamics/diffusion.py b/climlab/dynamics/diffusion.py
index <HASH>..<HASH> 100644
--- a/climlab/dynamics/diffusion.py
+++ b/climlab/dynamics/diffusion.py
@@ -4,9 +4,9 @@ Here is an example showing implementation of a vertical diffusion.
Example shows that a subprocess can work on just a subset of the parent process
state variables.
-from climlab.model.column import SingleColumnModel
+from climlab.model.column import GreyRadiationModel
from climlab.dynamics.diffusion import Diffusion
-c = SingleColumnModel()
+c = GreyRadiationModel()
K = 0.5
d = Diffusion(K=K, state=c.state['Tatm'], **c.param)
c.subprocess['diffusion'] = d
@@ -60,10 +60,10 @@ class Diffusion(ImplicitProcess):
super(Diffusion, self).__init__(**kwargs)
self.param['K'] = K # Diffusivity in units of [length]**2 / time
if diffusion_axis is None:
- _guess_diffusion_axis(self)
+ self.diffusion_axis = _guess_diffusion_axis(self)
else:
self.diffusion_axis = diffusion_axis
- # This currently only works with evenly space points
+ # This currently only works with evenly spaced points
for dom in self.domains.values():
delta = np.mean(dom.axes[self.diffusion_axis].delta)
bounds = dom.axes[self.diffusion_axis].bounds
|
Fixed broken example code in diffusion.py docstring.
|
brian-rose_climlab
|
train
|
b7f25f61e798952152d0009a7c94398b0ac2886a
|
diff --git a/components/Notification/components/GenericNotification.js b/components/Notification/components/GenericNotification.js
index <HASH>..<HASH> 100644
--- a/components/Notification/components/GenericNotification.js
+++ b/components/Notification/components/GenericNotification.js
@@ -124,7 +124,7 @@ class GenericNotification extends React.Component<Props, State> {
}
const CancelButton = ({ onClick }) => (
- <button className={styles.cancel} onClick={onClick}>
+ <button className={styles.cancel} type="button" onClick={onClick}>
<span className={styles.cancelInner}>
<Icon icon={closeIcon} role="img" title="close notification" />
</span>
|
adds type="button" on generic notification dismiss button. This prevents submitting forms by accident when dismissing notifications if the notification is inside a form tag
|
cultureamp_cultureamp-style-guide
|
train
|
943cff673a90d72f9c7b0567ed24638d9c874571
|
diff --git a/tests/Doctrine/Tests/ORM/Mapping/XmlMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/XmlMappingDriverTest.php
index <HASH>..<HASH> 100644
--- a/tests/Doctrine/Tests/ORM/Mapping/XmlMappingDriverTest.php
+++ b/tests/Doctrine/Tests/ORM/Mapping/XmlMappingDriverTest.php
@@ -87,7 +87,7 @@ class XmlMappingDriverTest extends AbstractMappingDriverTest
/**
* @group DDC-889
- * @expectedException Doctrine\ORM\Mapping\MappingException
+ * @expectedException Doctrine\Common\Persistence\Mapping\MappingException
* @expectedExceptionMessage Invalid mapping file 'Doctrine.Tests.Models.DDC889.DDC889Class.dcm.xml' for class 'Doctrine\Tests\Models\DDC889\DDC889Class'.
*/
public function testinvalidEntityOrMappedSuperClassShouldMentionParentClasses()
|
Fixing test expecting a ORM\Mapping exception
Those exceptions are now in the Common\Persistence\Mapping namespace
|
doctrine_orm
|
train
|
ad411c4346a085c89be51c6d62c9fa5c491e0508
|
diff --git a/command/ssh.go b/command/ssh.go
index <HASH>..<HASH> 100644
--- a/command/ssh.go
+++ b/command/ssh.go
@@ -69,5 +69,5 @@ func (copier *DefaultCopier) Execute(dest io.Writer, command string) (err error)
err = copier.session.Run(command)
}
}
- return nil
+ return err
}
|
small fix
actually returning the err object
|
pivotalservices_cfops
|
train
|
9cce566901799e4a1325da97d6f17650fcbffba1
|
diff --git a/galpy/potential_src/TwoPowerTriaxialPotential.py b/galpy/potential_src/TwoPowerTriaxialPotential.py
index <HASH>..<HASH> 100644
--- a/galpy/potential_src/TwoPowerTriaxialPotential.py
+++ b/galpy/potential_src/TwoPowerTriaxialPotential.py
@@ -653,18 +653,11 @@ class TriaxialNFWPotential(TwoPowerTriaxialPotential):
and not isinstance(normalize,bool)):
self.normalize(normalize)
else:
- if wrtcrit:
- od= overdens/bovy_conversion.dens_in_criticaldens(self._vo,
- self._ro,H=H)
- else:
- od= overdens/bovy_conversion.dens_in_meanmatterdens(self._vo,
- self._ro,
- H=H,Om=Om)
- mvirNatural= mvir*100./bovy_conversion.mass_in_1010msol(self._vo,
- self._ro)
- rvir= (3.*mvirNatural/od/4./numpy.pi)**(1./3.)
- self.a= rvir/conc
- self._amp= mvirNatural/(numpy.log(1.+conc)-conc/(1.+conc))
+ from galpy.potential import NFWPotential
+ dum= NFWPotential(mvir=mvir,conc=conc,ro=self._ro,vo=self._vo,
+ H=H,Om=Om,wrtcrit=wrtcrit,overdens=overdens)
+ self.a= dum.a
+ self._amp= dum._amp
self._scale= self.a
self.hasC= not self._glorder is None
self.hasC_dxdv= False
diff --git a/nose/test_potential.py b/nose/test_potential.py
index <HASH>..<HASH> 100644
--- a/nose/test_potential.py
+++ b/nose/test_potential.py
@@ -1165,6 +1165,36 @@ def test_NFW_virialsetup_wrtcrit():
wrtcrit=wrtcrit)/10.**12.) < 10.**-6., "NFWPotential virial setup's virial mass does not work"
return None
+def test_TriaxialNFW_virialsetup_wrtmeanmatter():
+ H, Om, overdens, wrtcrit= 71., 0.32, 201., False
+ ro, vo= 220., 8.
+ conc, mvir= 12., 1.1
+ np= potential.NFWPotential(conc=conc,mvir=mvir,vo=vo,ro=ro,
+ H=H,Om=Om,overdens=overdens,
+ wrtcrit=wrtcrit)
+ tnp= potential.TriaxialNFWPotential(b=0.3,c=0.7,
+ conc=conc,mvir=mvir,vo=vo,ro=ro,
+ H=H,Om=Om,overdens=overdens,
+ wrtcrit=wrtcrit)
+ assert numpy.fabs(np.a-tnp.a) < 10.**-10., "TriaxialNFWPotential virial setup's concentration does not work"
+ assert numpy.fabs(np._amp-tnp._amp) < 10.**-6., "TriaxialNFWPotential virial setup's virial mass does not work"
+ return None
+
+def test_TriaxialNFW_virialsetup_wrtcrit():
+ H, Om, overdens, wrtcrit= 71., 0.32, 201., True
+ ro, vo= 220., 8.
+ conc, mvir= 12., 1.1
+ np= potential.NFWPotential(conc=conc,mvir=mvir,vo=vo,ro=ro,
+ H=H,Om=Om,overdens=overdens,
+ wrtcrit=wrtcrit)
+ tnp= potential.TriaxialNFWPotential(b=0.3,c=0.7,
+ conc=conc,mvir=mvir,vo=vo,ro=ro,
+ H=H,Om=Om,overdens=overdens,
+ wrtcrit=wrtcrit)
+ assert numpy.fabs(np.a-tnp.a) < 10.**-10., "TriaxialNFWPotential virial setup's concentration does not work"
+ assert numpy.fabs(np._amp-tnp._amp) < 10.**-6., "TriaxialNFWPotential virial setup's virial mass does not work"
+ return None
+
def test_conc_attributeerror():
pp= potential.PowerSphericalPotential(normalize=1.)
#This potential doesn't have a scale, so we cannot calculate the concentration
|
Use spherical NFW's virial setup for Triaxial's virial setup; test
|
jobovy_galpy
|
train
|
846436f8a0c2aed4c4e8b86cda0153732c3ab410
|
diff --git a/test/unit/party.model.spec.js b/test/unit/party.model.spec.js
index <HASH>..<HASH> 100644
--- a/test/unit/party.model.spec.js
+++ b/test/unit/party.model.spec.js
@@ -2,6 +2,7 @@
/* dependencies */
const { expect } = require('chai');
+const { areSameObjectId } = require('@lykmapipo/mongoose-common');
const { Predefine } = require('@lykmapipo/predefine');
const { Party } = require('../..');
@@ -49,7 +50,7 @@ describe('Party Instance', () => {
child.preValidate(() => {
expect(child.ownership).to.exist;
- console.log(child);
+ expect(areSameObjectId(parent.ownership, child.ownership)).to.be.true;
done();
});
});
|
test(unit): derive ownership from parent
|
CodeTanzania_emis-stakeholder
|
train
|
4a1bf86faed2a2273c909edaa669f86daf33522d
|
diff --git a/mod/scorm/view.php b/mod/scorm/view.php
index <HASH>..<HASH> 100755
--- a/mod/scorm/view.php
+++ b/mod/scorm/view.php
@@ -59,7 +59,7 @@
update_module_button($cm->id, $course->id, $strscorm), navmenu($course, $cm));
notice(get_string("activityiscurrentlyhidden"));
} else {
- print_header($pagetitle, "$course->fullname","$navigation <a target=\"{$CFG->framename}\" href=\"$ME?id=$cm->id\" title=\"$scorm->summary\">$scorm->name</a>",
+ print_header($pagetitle, "$course->fullname","$navigation <a target=\"{$CFG->framename}\" href=\"view.php?id=$cm->id\">$scorm->name</a>",
"", "", true, update_module_button($cm->id, $course->id, $strscorm), navmenu($course, $cm));
if (isteacher($course->id)) {
@@ -141,6 +141,11 @@
} else {
echo " <img src=\"pix/spacer.gif\" alt=\" \" />\n";
}
+ //print_r ($sco->title);
+ if ($sco->title == "") {
+ $sco->title = get_string('notitle','scorm');
+ //echo '-'.$sco->title.'-';
+ }
if ($sco->launch) {
$score = "";
if ($sco_user=get_record("scorm_sco_users","scoid",$sco->id,"userid",$USER->id)) {
|
Some $ME are now out!
And 5 lines have been added because they weren't merged before! Please,
check them!
Merged from MOODLE_<I>_STABLE
|
moodle_moodle
|
train
|
b16d2beb87d8ef7e99a9d44686475730dee010d7
|
diff --git a/examples/appengine/example.py b/examples/appengine/example.py
index <HASH>..<HASH> 100644
--- a/examples/appengine/example.py
+++ b/examples/appengine/example.py
@@ -80,7 +80,7 @@ class BaseHandler(webapp2.RequestHandler):
user.access_token = cookie["access_token"]
user.put()
# User is now logged in
- self.session["user"] = dict(name=user.name, profile_url=user.profile_url, user=user.id, access_token=user.access_token)
+ self.session["user"] = dict(name=user.name, profile_url=user.profile_url, id=user.id, access_token=user.access_token)
return self.session.get("user")
return None
|
bugfix: changed key of id from user to id in the user dict stored in the session
|
mobolic_facebook-sdk
|
train
|
b5973ff132deafee64e36d84adf4a1c71a63359f
|
diff --git a/src/components/FileUploader/FileUploader-test.js b/src/components/FileUploader/FileUploader-test.js
index <HASH>..<HASH> 100644
--- a/src/components/FileUploader/FileUploader-test.js
+++ b/src/components/FileUploader/FileUploader-test.js
@@ -48,8 +48,8 @@ describe('FileUploaderButton', () => {
expect(mountWrapper.props().disableLabelChanges).toEqual(false);
});
- it('renders with default role', () => {
- expect(mountWrapper.props().role).toEqual('button');
+ it('does not have default role', () => {
+ expect(mountWrapper.props().role).not.toBeTruthy();
});
});
@@ -103,7 +103,9 @@ describe('FileUploader', () => {
).toEqual(true);
});
it('renders input with hidden prop', () => {
- expect(mountWrapper.find('input').props().hidden).toEqual(true);
+ expect(mountWrapper.find('input').props().className).toEqual(
+ 'bx--visually-hidden'
+ );
});
it('renders with empty div.bx--file-container by default', () => {
expect(mountWrapper.find('div.bx--file-container').text()).toEqual('');
diff --git a/src/components/FileUploader/FileUploader.js b/src/components/FileUploader/FileUploader.js
index <HASH>..<HASH> 100644
--- a/src/components/FileUploader/FileUploader.js
+++ b/src/components/FileUploader/FileUploader.js
@@ -27,7 +27,6 @@ export class FileUploaderButton extends Component {
multiple: false,
onChange: () => {},
onClick: () => {},
- role: 'button',
};
state = {
labelText: this.props.labelText,
@@ -88,7 +87,7 @@ export class FileUploaderButton extends Component {
{this.state.labelText}
</label>
<input
- hidden
+ className="bx--visually-hidden"
ref={input => (this.input = input)}
id={this.uid}
type="file"
|
fix(FileUploader): use an alternate way to hide pseudo <input> (#<I>)
Fixes #<I>.
|
carbon-design-system_carbon-components
|
train
|
c23d7146b51faf99875b89f6476fa5a9150df516
|
diff --git a/doc/brainstorm.rb b/doc/brainstorm.rb
index <HASH>..<HASH> 100644
--- a/doc/brainstorm.rb
+++ b/doc/brainstorm.rb
@@ -9,6 +9,10 @@ module Foo
@punctuation = '!'
end
+ before_launch do |arg|
+ puts arg if arg
+ end
+
having_launched do
@msg = 'Done' + self.class.punctuation
end
@@ -23,6 +27,10 @@ module Foo
puts @msg
end
+ def sub
+ Subshell.launch
+ end
+
class << self
def punctuation
@punctuation
@@ -31,4 +39,16 @@ module Foo
end
end
+module Foo
+ class Subshell < Bombshell::Environment
+ include Bombshell::Shell
+
+ def do_something_else
+ puts '... and done'
+ end
+
+ prompt_with '[foo::subshell]'
+ end
+end
+
Bombshell.launch(Foo::Shell)
diff --git a/lib/bombshell/shell.rb b/lib/bombshell/shell.rb
index <HASH>..<HASH> 100644
--- a/lib/bombshell/shell.rb
+++ b/lib/bombshell/shell.rb
@@ -30,8 +30,10 @@ module Bombshell
end
module ClassMethods
- def launch(arguments)
- @bombshell_callbacks[:before_launch].each(&:call)
+ def launch(arguments = [])
+ @bombshell_callbacks[:before_launch].each do |callback|
+ callback.call(*arguments.first(callback.arity))
+ end
shell = new
@bombshell_callbacks[:having_launched].each do |callback|
shell.instance_eval &callback
|
Demonstrate subshells. Give command-line arguments to before_launch callbacks. Demonstrate this feature.
|
rossmeissl_bombshell
|
train
|
2ef06e8b66182b85615a1df15a83fa1e2f90bfb1
|
diff --git a/textract/parsers/odt_parser.py b/textract/parsers/odt_parser.py
index <HASH>..<HASH> 100644
--- a/textract/parsers/odt_parser.py
+++ b/textract/parsers/odt_parser.py
@@ -28,21 +28,19 @@ class Parser(BaseParser):
def text_to_string(self, element):
buff = u""
- if element.tag == self.qn('text:tab'):
- buff = "\t"
- if element.tail is not None:
- buff += element.tail
- return buff
- if element.tag == self.qn('text:s'):
- buff = u" "
- if element.get(self.qn('text:c')) is not None:
- buff *= int(element.get(self.qn('text:c')))
- if element.tail is not None:
- buff += element.tail
- return buff
- if element.text:
+ if element.text is not None:
buff += element.text
for child in element:
+ if child.tag == self.qn('text:tab'):
+ buff += "\t"
+ if child.tail is not None:
+ buff += child.tail
+ elif child.tag == self.qn('text:s'):
+ buff += u" "
+ if child.get(self.qn('text:c')) is not None:
+ buff += u" " * (int(child.get(self.qn('text:c'))) - 1)
+ if child.tail is not None:
+ buff += child.tail
buff += self.text_to_string(child)
if element.tail is not None:
buff += element.tail
|
reorganize text_to_string method
|
deanmalmgren_textract
|
train
|
9fbce12cf31f5521cbac7d2fcc5f4e4aa493993a
|
diff --git a/views/js/runner/plugins/navigation/next.js b/views/js/runner/plugins/navigation/next.js
index <HASH>..<HASH> 100644
--- a/views/js/runner/plugins/navigation/next.js
+++ b/views/js/runner/plugins/navigation/next.js
@@ -31,10 +31,12 @@ define([
'taoQtiTest/runner/helpers/messages',
'taoQtiTest/runner/helpers/map',
'taoQtiTest/runner/helpers/stats',
+ 'taoQtiTest/runner/helpers/currentItem',
'util/shortcut',
'util/namespace',
'tpl!taoQtiTest/runner/plugins/templates/button'
-], function ($, _, __, hider, pluginFactory, nextWarningHelper, messages, mapHelper, statsHelper, shortcut, namespaceHelper, buttonTpl){
+], function ($, _, __, hider, pluginFactory, nextWarningHelper, messages,
+ mapHelper, statsHelper, currentItemHelper, shortcut, namespaceHelper, buttonTpl){
'use strict';
/**
@@ -195,7 +197,7 @@ define([
});
if(testConfig.allowShortcuts && pluginShortcuts.trigger){
- shortcut.add(namespaceHelper.namespaceAll(pluginShortcuts.trigger, this.getName(), true), function(e) {
+ shortcut.add(namespaceHelper.namespaceAll(pluginShortcuts.trigger, this.getName(), true), function() {
if (self.getState('enabled') === true) {
testRunner.trigger('nav-next', true);
}
diff --git a/views/js/runner/plugins/navigation/next/nextItemWarning.js b/views/js/runner/plugins/navigation/next/nextItemWarning.js
index <HASH>..<HASH> 100644
--- a/views/js/runner/plugins/navigation/next/nextItemWarning.js
+++ b/views/js/runner/plugins/navigation/next/nextItemWarning.js
@@ -59,9 +59,7 @@ define([
var customNextMessage = 'message';
var checkboxParams = null;
- var itemPartiallyAnswered = currentItemHelper.isAnswered(self, true);
-
- console.log('itemPartiallyAnswered?', itemPartiallyAnswered); // FIXME:
+ var itemPartiallyAnswered = currentItemHelper.isAnswered(testRunner, true);
// Handle disable & re-enable of navigation controls:
function enableNav() {
@@ -83,7 +81,6 @@ define([
// Load testStore checkbox value (async)
testStore.getStore(self.getName()).then(function(store) {
store.getItem('dontShowNextItemWarning').then(function(checkboxValue) {
- console.log('store.getItem dontShowNextItemWarning', checkboxValue);
// Show the warning unless user has turned it off:
if (checkboxValue !== true) {
@@ -199,8 +196,8 @@ define([
// Attach this plugin to 'next' & 'skip' events
testRunner
.on('init', function() {
- console.info('config: force the warning?', testConfig.forceEnableNextItemWarning);
- console.info('config: enable checkbox?', testConfig.enableNextItemWarningCheckbox);
+ console.warn('config: force the warning?', testConfig.forceEnableNextItemWarning);
+ console.warn('config: enable checkbox?', testConfig.enableNextItemWarningCheckbox);
// Clear the stored checkbox value before each test:
testStore.getStore(self.getName()).then(function(store) {
store.setItem('dontShowNextItemWarning', null);
|
Fixed issue with item isAnswered detection
|
oat-sa_extension-tao-testqti
|
train
|
aee7bc82f5a9b8158f3b2d94c8a8a7ae3ee0399d
|
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -4,8 +4,8 @@
const tag = require('tagged-template-literals')
const trimNewLines = require('trim-newlines')
-const indentionRegex = /^ +/
-const allEmpty = /^ +$/
+const indentionRegex = /^\s+/
+const allEmpty = /^\s+$/
function trim(strings: string | Array<string>, ...values: Array<any>): string {
let subject
|
Added triming of any whitespace character
|
steelbrain_cool-trim
|
train
|
9681d4372a081f47c91b78edcd2d8f4407279fcd
|
diff --git a/lib/jsdom/browser/index.js b/lib/jsdom/browser/index.js
index <HASH>..<HASH> 100644
--- a/lib/jsdom/browser/index.js
+++ b/lib/jsdom/browser/index.js
@@ -103,6 +103,18 @@ exports.createWindow = function(dom, options) {
var window = this.console._window = this;
+ /* Location hash support */
+ this.location.__defineGetter__("hash", function() {
+ return (window.location.href.split("#").length > 1)
+ ? "#"+window.location.href.split("#")[1]
+ : "";
+ });
+
+ this.location.__defineSetter__("hash", function(val) {
+ /* TODO: Should fire a hashchange event, but tests aren't working */
+ window.location.href = window.location.href.split("#")[0] + val;
+ });
+
if (options && options.document) {
options.document.location = this.location;
}
@@ -161,7 +173,7 @@ exports.createWindow = function(dom, options) {
if (this.document.close) {
// We need to empty out the event listener array because
// document.close() causes 'load' event to re-fire.
- this.document._listeners = []
+ this.document._listeners = [];
this.document.close();
}
delete this.document;
diff --git a/test/jsdom/index.js b/test/jsdom/index.js
index <HASH>..<HASH> 100644
--- a/test/jsdom/index.js
+++ b/test/jsdom/index.js
@@ -91,6 +91,22 @@ exports.tests = {
test.equal("http://www.example.com/",
window.location.href,
"location can be overriden by config.url");
+ test.equal("", window.location.hash,
+ "hash should be empty string by default");
+ test.done();
+ }
+ })
+ },
+
+ env_with_overridden_hash: function(test) {
+ var html = "<html><body><p>hello world!</p></body></html>";
+ jsdom.env({
+ html : html,
+ url : 'http://www.example.com/#foo',
+ done : function(errors, window) {
+ test.ok(null === errors, "error should be null");
+ test.equal("#foo", window.location.hash,
+ "hash should pull from URL");
test.done();
}
})
diff --git a/test/window/index.js b/test/window/index.js
index <HASH>..<HASH> 100644
--- a/test/window/index.js
+++ b/test/window/index.js
@@ -19,5 +19,18 @@ exports.tests = {
urlParts = rurl.exec(window.location.href);
test.ok(urlParts.length > 1, 'url shouldnt be blank');
test.done();
+ },
+
+ ensure_a_default_window_has_a_window_location_hash: function(test) {
+ var window = require("../../lib/jsdom/browser/index").windowAugmentation(dom);
+ var defaultHref = window.location.href;
+ test.equals(window.location.hash, "");
+ window.location.href = window.location.href + "#foobar";
+ test.equals(window.location.hash, "#foobar");
+ window.location.hash = "#baz";
+ test.equals(window.location.hash, "#baz");
+ test.equals(window.location.href, defaultHref + "#baz");
+ test.done();
}
+
};
|
Adding window.location.hash support to browser / window.
|
jsdom_jsdom
|
train
|
9fde7045aa392feb83f46b46dfa81f75c07af0e6
|
diff --git a/lib/gemsmith/aids/gem_spec.rb b/lib/gemsmith/aids/gem_spec.rb
index <HASH>..<HASH> 100644
--- a/lib/gemsmith/aids/gem_spec.rb
+++ b/lib/gemsmith/aids/gem_spec.rb
@@ -72,9 +72,8 @@ module Gemsmith
attr_reader :file_path, :spec, :shell
def validate
- unless spec.is_a?(self.class.specification)
- fail(Errors::Specification, %(Unknown gem specification: "#{file_path}".))
- end
+ return if spec.is_a?(self.class.specification)
+ fail(Errors::Specification, %(Unknown gem specification: "#{file_path}".))
end
end
end
|
Refactored gemspec aid to use guard clause when validating.
|
bkuhlmann_gemsmith
|
train
|
3cc95e33cb3e5cbcc32a301e46c0bab3af991916
|
diff --git a/src/org/apache/commons/httpclient/HttpMethodBase.java b/src/org/apache/commons/httpclient/HttpMethodBase.java
index <HASH>..<HASH> 100644
--- a/src/org/apache/commons/httpclient/HttpMethodBase.java
+++ b/src/org/apache/commons/httpclient/HttpMethodBase.java
@@ -51,10 +51,12 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/*
- * Forked class... needed by the (forked) HttpMethodDirector class.
+ * Forked class... (previously needed only by the (forked) HttpMethodDirector class).
*
* Changes:
* - Removed the characters "$" from the previous SVN keywords (HeadURL, Revision and Date) to avoid accidental expansions.
+ * - Always add the "?" character to the request URI (Issue 1180) in the method #generateRequestLine(HttpConnection, String,
+ * String, String, String) to preserve the intended request URI.
*
*/
/**
@@ -1579,9 +1581,10 @@ public abstract class HttpMethodBase implements HttpMethod {
}
// Append query, if any
if (query != null) {
- if (query.indexOf("?") != 0) {
+ // ZAP: If commented out to not change the intended request URI (i.e. if the query component starts with a "?" char)
+ //if (query.indexOf("?") != 0) {
buf.append("?");
- }
+ //}
buf.append(query);
}
// Append protocol
|
Issue <I> - Proxy corrupts URL when there are multiple question marks
Changed the method HttpMethodBase#generateRequestLine(HttpConnection, String, String, String, String) to always add the "?" char to the request-uri even if already present in the query component.
|
zaproxy_zaproxy
|
train
|
b7ad9beeb5b8b4fbef35f72c6e358d383a122922
|
diff --git a/js/core/DomElement.js b/js/core/DomElement.js
index <HASH>..<HASH> 100644
--- a/js/core/DomElement.js
+++ b/js/core/DomElement.js
@@ -718,6 +718,8 @@ define(["require", "js/core/EventDispatcher", "js/core/Component", "js/core/Cont
ctor: function (domEvent) {
this.domEvent = domEvent;
this.callBase(domEvent);
+
+ this.isDefaultPrevented = !!domEvent.defaultPrevented;
},
stopPropagation: function () {
this.callBase();
|
read defaultPrevented form domEvent to encapsulated domevent
|
rappid_rAppid.js
|
train
|
52d96fe5471be60a569701a6d0a0daf07f37541f
|
diff --git a/spinoff/util/logging.py b/spinoff/util/logging.py
index <HASH>..<HASH> 100644
--- a/spinoff/util/logging.py
+++ b/spinoff/util/logging.py
@@ -134,7 +134,7 @@ def _write(level, *args, **kwargs):
if isinstance(logstring, unicode):
logstring = logstring.encode('utf8')
else:
- logstring = caller_name + ':'
+ logstring = caller_name + (':' if args else '')
logstring = YELLOW + logstring + RESET_COLOR
|
Only append a colon to logstrings of logged messages if something is being logged
|
eallik_spinoff
|
train
|
cd39202a6328f1d701588bf090b4bfbe0131be7f
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,10 +2,14 @@
All enhancements and patches to cookiecutter-django will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
+## [2015-09-21]
+### Added
+- Ability to pass in extra tracking options to mailgun via API (@wsmith)
+
## [2015-09-14]
### Added
-- Support for `Recipient Variables`
-- Version specification in python module
+- Support for `Recipient Variables` (@wsmith)
+- Version specification in python module (@pydanny)
## [2015-09-08]
### Changed
diff --git a/README.rst b/README.rst
index <HASH>..<HASH> 100644
--- a/README.rst
+++ b/README.rst
@@ -6,8 +6,7 @@ A Django email backend for use with Mailgun
Overview
=================
-Django-Mailgun is a drop-in mail backend for Django_,
-per http://docs.djangoproject.com/en/dev/topics/email/#e-mail-backends
+Django-Mailgun is a drop-in mail backend for Django_.
Getting going
=============
@@ -69,4 +68,9 @@ validate your data for compliance with Mailgun's API; it merely maps over whatev
Mailgun's API states that no more than 3 tags are allowed per email, and each tag must be no greater than
128 characters (https://documentation.mailgun.com/user_manual.html#tagging). If you provide 4 tags,
or a tag longer than 128 characters, Django-Mailgun will attempt to send such (potentially) invalid
-data. You must ensure what you send is appropriate.
\ No newline at end of file
+data. You must ensure what you send is appropriate.
+
+Django Email Backend Reference
+================================
+
+* http://docs.djangoproject.com/en/dev/topics/email/#e-mail-backends
diff --git a/django_mailgun.py b/django_mailgun.py
index <HASH>..<HASH> 100644
--- a/django_mailgun.py
+++ b/django_mailgun.py
@@ -7,8 +7,8 @@ from django.core.mail.message import sanitize_address
from requests.packages.urllib3.filepost import encode_multipart_formdata
-__version__ = '0.6.0'
-version = '0.6.0'
+__version__ = '0.7.0'
+version = '0.7.0'
# A mapping of smtp headers to API key names, along
@@ -130,8 +130,8 @@ class MailgunBackend(BaseEmailBackend):
headers = None
response = requests.post(self._api_url + "messages",
- auth=("api", self._access_key),
- data=content, headers=headers)
+ auth=("api", self._access_key),
+ data=content, headers=headers)
except:
if not self.fail_silently:
raise
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -2,7 +2,7 @@ from setuptools import setup
import os
import sys
-version = '0.6.0'
+version = '0.7.0'
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
@@ -30,7 +30,7 @@ CLASSIFIERS = [
'Framework :: Django :: 1.5',
'Framework :: Django :: 1.6',
'Framework :: Django :: 1.7',
-' Framework :: Django :: 1.8',
+ 'Framework :: Django :: 1.8',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
diff --git a/test_django_mailgun.py b/test_django_mailgun.py
index <HASH>..<HASH> 100644
--- a/test_django_mailgun.py
+++ b/test_django_mailgun.py
@@ -66,4 +66,4 @@ def test_extra_headers_map():
('o:tracking-opens', 'no'),
('v:my-var', 'my_message_id: 123'),
]
- check_output_value(mb, message, test_input, expected_output)
\ No newline at end of file
+ check_output_value(mb, message, test_input, expected_output)
|
Prep for <I> release
|
BradWhittington_django-mailgun
|
train
|
d036411da3208c605cbd71e7654804698de451d8
|
diff --git a/pycrest/eve.py b/pycrest/eve.py
index <HASH>..<HASH> 100644
--- a/pycrest/eve.py
+++ b/pycrest/eve.py
@@ -95,7 +95,7 @@ class DictCache(APICache):
class APIConnection(object):
- def __init__(self, additional_headers=None, user_agent=None, cache_dir=None):
+ def __init__(self, additional_headers=None, user_agent=None, cache_dir=None, cache=None):
# Set up a Requests Session
session = requests.Session()
if additional_headers is None:
@@ -110,8 +110,13 @@ class APIConnection(object):
session.mount('https://public-crest.eveonline.com',
WeakCiphersAdapter())
self._session = session
- self.cache_dir = cache_dir
- if self.cache_dir:
+ if cache:
+ if isinstance(cache, APICache):
+ self.cache = cache # Inherit from parents
+ elif isinstance(cache, type):
+ self.cache = cache() # Instantiate a new cache
+ elif cache_dir:
+ self.cache_dir = cache_dir
self.cache = FileCache(self.cache_dir)
else:
self.cache = DictCache()
@@ -189,7 +194,7 @@ class EVE(APIConnection):
self._endpoint = self._public_endpoint
self._cache = {}
self._data = None
- APIConnection.__init__(self, cache_dir=kwargs.pop('cache_dir', None), **kwargs)
+ APIConnection.__init__(self, **kwargs)
def __call__(self):
if not self._data:
@@ -224,7 +229,7 @@ class EVE(APIConnection):
self._oauth_endpoint,
self.client_id,
self.api_key,
- cache_dir=self.cache_dir)
+ cache=self.cache)
def refr_authorize(self, refresh_token):
res = self._authorize(params={"grant_type": "refresh_token", "refresh_token": refresh_token})
@@ -235,7 +240,7 @@ class EVE(APIConnection):
self._oauth_endpoint,
self.client_id,
self.api_key,
- cache_dir=self.cache_dir)
+ cache=self.cache)
def temptoken_authorize(self, access_token, expires_in, refresh_token):
return AuthedConnection({'access_token': access_token,
@@ -245,7 +250,7 @@ class EVE(APIConnection):
self._oauth_endpoint,
self.client_id,
self.api_key,
- cache_dir=self.cache_dir)
+ cache=self.cache)
class AuthedConnection(EVE):
|
Allow one to manually supply a caching mechanism.
|
pycrest_PyCrest
|
train
|
d4ba101049c1871524c7abf659cb905f5aec4bae
|
diff --git a/bin/swf2svg.py b/bin/swf2svg.py
index <HASH>..<HASH> 100644
--- a/bin/swf2svg.py
+++ b/bin/swf2svg.py
@@ -1,6 +1,6 @@
import argparse
from swf.movie import SWF
-from swf.export import SVGExporter, SingleShapeSVGExporterMixin, FrameSVGExporterMixin
+from swf.export import SVGExporter, SingleShapeSVGExporterMixin, FrameSVGExporterMixin, NamesSVGExporterMixin
parser = argparse.ArgumentParser(description="Convert an SWF file into an SVG")
parser.add_argument("--swf", type=argparse.FileType('rb'),
@@ -11,6 +11,8 @@ parser.add_argument("--shape", type=int,
help="Only export shape SHAPE (integer)", required=False)
parser.add_argument("--frame", type=int,
help="Export frame FRAME (0-based index) instead of frame 0", required=False)
+parser.add_argument("--names", action='store_true',
+ help='For each element, extract SWF instanceName to class="n-<name>"', required=False)
options = parser.parse_args()
argparse.swf_file = options.swf
@@ -32,6 +34,10 @@ if options.frame is not None:
export_mixins.append(FrameSVGExporterMixin)
export_opts['frame'] = options.frame
+if options.names:
+ export_mixins.append(NamesSVGExporterMixin)
+
+
# create the SVG exporter
svg_exporter = SVGExporter()
diff --git a/swf/export.py b/swf/export.py
index <HASH>..<HASH> 100644
--- a/swf/export.py
+++ b/swf/export.py
@@ -899,12 +899,25 @@ class FrameSVGExporterMixin(object):
if not tag.hasCharacter:
tag.characterId = orig_tag.characterId
+ # this is for NamesSVGExporterMixin
+ if not tag.hasName:
+ tag.instanceName = orig_tag.instanceName
frame_tags[tag.depth] = tag
elif isinstance(tag, TagRemoveObject):
del frame_tags[tag.depth]
return super(FrameSVGExporterMixin, self).get_display_tags(frame_tags.values(), z_sorted)
+class NamesSVGExporterMixin(object):
+ '''
+ Add class="n-<name>" to SVG elements for tags that have an instanceName.
+ '''
+ def export_display_list_item(self, tag, parent=None):
+ use = super(NamesSVGExporterMixin, self).export_display_list_item(tag, parent)
+ if hasattr(tag, 'instanceName') and tag.instanceName is not None:
+ use.set('class', 'n-%s' % tag.instanceName)
+ return use
+
class SVGFilterFactory(object):
# http://commons.oreilly.com/wiki/index.php/SVG_Essentials/Filters
|
Added mixin for exporting object names as classes
|
timknip_pyswf
|
train
|
d8289524e91422a305c22b8cafbfa9cc41ebc355
|
diff --git a/src/js/cropper.js b/src/js/cropper.js
index <HASH>..<HASH> 100644
--- a/src/js/cropper.js
+++ b/src/js/cropper.js
@@ -106,12 +106,11 @@ class Cropper {
const { element, options } = this;
- if (
- !options.rotatable
- || !options.scalable
- || !options.checkOrientation
- || !window.ArrayBuffer
- ) {
+ if (!options.rotatable && !options.scalable) {
+ options.checkOrientation = false;
+ }
+
+ if (!options.checkOrientation || !window.ArrayBuffer) {
this.clone();
return;
}
diff --git a/test/specs/options/checkOrientation.spec.js b/test/specs/options/checkOrientation.spec.js
index <HASH>..<HASH> 100644
--- a/test/specs/options/checkOrientation.spec.js
+++ b/test/specs/options/checkOrientation.spec.js
@@ -30,4 +30,16 @@ describe('checkOrientation (option)', () => {
expect(cropper.options.checkOrientation).to.be.false;
});
+
+ it('should not check orientation when it is not rotatable and not scalable', () => {
+ const image = window.createImage({
+ src: imageURL,
+ });
+ const cropper = new Cropper(image, {
+ rotatable: false,
+ scalable: false,
+ });
+
+ expect(cropper.options.checkOrientation).to.be.false;
+ });
});
|
fix: set checkOrientation to false when it is unnecessary
|
fengyuanchen_cropperjs
|
train
|
74cc079a5baac9798376743b86cbdfac2fe77094
|
diff --git a/src/org/jenetics/Arrays.java b/src/org/jenetics/Arrays.java
index <HASH>..<HASH> 100644
--- a/src/org/jenetics/Arrays.java
+++ b/src/org/jenetics/Arrays.java
@@ -25,15 +25,26 @@ package org.jenetics;
import java.util.Random;
/**
+ * Utility class concerning arrays.
+ *
* @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
- * @version $Id: Arrays.java,v 1.1 2008-03-25 18:31:55 fwilhelm Exp $
+ * @version $Id: Arrays.java,v 1.2 2008-04-22 21:01:16 fwilhelm Exp $
*/
-final class Arrays {
+public final class Arrays {
private Arrays() {
}
- static <T> void swap(final T[] array, final int i, final int j) {
+ /**
+ * Swap two elements of an given array.
+ *
+ * @param <T> the array type.
+ * @param array the array
+ * @param i index of the first array element.
+ * @param j index of the second array element.
+ * @throws ArrayIndexOutOfBoundsException if one of the given indexes is out of bounds.
+ */
+ public static <T> void swap(final T[] array, final int i, final int j) {
final T temp = array[i];
array[i] = array[j];
array[j] = temp;
@@ -48,9 +59,43 @@ final class Arrays {
* @param random the {@link Random} object to use for randomize.
* @param array the {@code array} to randomize.
*/
- static <T> void randomize(final Random random, final T[] array) {
+ public static <T> void randomize(final Random random, final T[] array) {
for (int j = array.length - 1; j > 0; --j) {
swap(array, j, random.nextInt(j + 1));
}
}
+
+ /**
+ * Reverses the part of the array determined by the to indexes.
+ *
+ * @param <T> the array type.
+ * @param array the array to reverse
+ * @param from the first index (inclusive)
+ * @param to the second index (exclusive)
+ */
+ public static <T> void reverse(final T[] array, int from, int to) {
+ int i = from;
+ int j = to;
+
+ while (i < j) {
+ --j;
+ swap(array, i, j);
+ ++i;
+ }
+ }
+
+ /**
+ * Reverses the given array.
+ *
+ * @param <T> the array type.
+ * @param array the array to reverse.
+ */
+ public static <T> void reverse(final T[] array) {
+ reverse(array, 0, array.length);
+ }
+
+
}
+
+
+
|
Making the Array utility class public.
|
jenetics_jenetics
|
train
|
9e81df0147569434de0895d76caf2d502148cac3
|
diff --git a/flake8_bandit.py b/flake8_bandit.py
index <HASH>..<HASH> 100644
--- a/flake8_bandit.py
+++ b/flake8_bandit.py
@@ -2,13 +2,21 @@
import ast
import pycodestyle
+from flake8.options.config import ConfigFileFinder
+
from bandit.core.config import BanditConfig
from bandit.core.meta_ast import BanditMetaAst
from bandit.core.metrics import Metrics
from bandit.core.node_visitor import BanditNodeVisitor
from bandit.core.test_set import BanditTestSet
-__version__ = "2.0.1"
+try:
+ import configparser
+except ImportError:
+ import ConfigParser as configparser
+
+
+__version__ = "2.1.0"
class BanditTester(object):
@@ -28,10 +36,25 @@ class BanditTester(object):
self.lines = lines
def _check_source(self):
+ ini_file = ConfigFileFinder("bandit", None, None).local_config_files()
+ config = configparser.ConfigParser()
+ try:
+ config.read(ini_file)
+ profile = {k: v for k, v in config.items("bandit")}
+ if profile.get("skips"):
+ profile["exclude"] = profile.get("skips").split(",")
+ if profile.get("tests"):
+ profile["include"] = profile.get("tests").split(",")
+ except (configparser.Error, KeyError, TypeError) as e:
+ if str(e) != "No section: 'bandit'":
+ import sys
+ err = "Unable to parse config file: %s\n" % e
+ sys.stderr.write(err)
+ profile = {}
bnv = BanditNodeVisitor(
self.filename,
BanditMetaAst(),
- BanditTestSet(BanditConfig()),
+ BanditTestSet(BanditConfig(), profile=profile),
False,
[],
Metrics(),
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -3,7 +3,7 @@ import os
import sys
from shutil import rmtree
-from setuptools import find_packages, setup, Command
+from setuptools import Command, setup
def get_version(fname="flake8_bandit.py"):
|
added functionality for 'skips
' and 'tests' in a .bandit config file located anywhere along with current directory path
|
tylerwince_flake8-bandit
|
train
|
507391c722a5247baaf7c8e72ad8a88b7124958b
|
diff --git a/spec/unit/percheron/actions/create_spec.rb b/spec/unit/percheron/actions/create_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/percheron/actions/create_spec.rb
+++ b/spec/unit/percheron/actions/create_spec.rb
@@ -126,6 +126,12 @@ describe Percheron::Actions::Create do
context 'when a Docker unit already exists' do
let(:unit_exists) { true }
let(:unit) { Percheron::Unit.new(config, stack, 'debian') }
+ let(:container_double) { double('Docker::Container') }
+
+ before do
+ expect(Percheron::Actions::Build).to receive(:new).with(unit).and_return(build_double)
+ expect(build_double).to receive(:execute!)
+ end
context 'with no force' do
it 'warns the unit already exists' do
@@ -157,11 +163,7 @@ describe Percheron::Actions::Create do
let(:metastore_key) { 'stacks.debian_jessie.units.debian.dockerfile_md5' }
let(:metastore_key_md5) { '0b03152a88e90de1c5466d6484b8ce5b' }
- let(:container_double) { double('Docker::Container') }
-
before do
- expect(Percheron::Actions::Build).to receive(:new).with(unit).and_return(build_double)
- expect(build_double).to receive(:execute!)
expect(unit).to receive(:container).and_return(container_double)
end
|
Create spec fix, don't hit API
|
ashmckenzie_percheron
|
train
|
16696f8f786c56ac67d3cc8dbc93f328c9696542
|
diff --git a/sc2/client.py b/sc2/client.py
index <HASH>..<HASH> 100644
--- a/sc2/client.py
+++ b/sc2/client.py
@@ -32,10 +32,10 @@ class Client(Protocol):
self.game_step = 8
self._player_id = None
self._game_result = None
- self._debug_texts = list()
- self._debug_lines = list()
- self._debug_boxes = list()
- self._debug_spheres = list()
+ self._debug_texts = []
+ self._debug_lines = []
+ self._debug_boxes = []
+ self._debug_spheres = []
self._renderer = None
@@ -110,6 +110,8 @@ class Client(Protocol):
async def observation(self):
result = await self._execute(observation=sc_pb.RequestObservation())
+ assert result.HasField("observation")
+
if not self.in_game or result.observation.player_result:
# Sometimes game ends one step before results are available
if not result.observation.player_result:
diff --git a/sc2/main.py b/sc2/main.py
index <HASH>..<HASH> 100644
--- a/sc2/main.py
+++ b/sc2/main.py
@@ -112,7 +112,7 @@ async def _play_game_ai(client, player_id, ai, realtime, step_time_limit, game_t
if iteration == 0:
ai._prepare_first_step()
- logger.debug(f"Running AI step, it={iteration} {gs.game_loop * 0.725 * (1 / 16):.2f}s)")
+ logger.debug(f"Running AI step, it={iteration} {gs.game_loop * 0.725 * (1 / 16):.2f}s")
try:
await ai.issue_events()
diff --git a/sc2/protocol.py b/sc2/protocol.py
index <HASH>..<HASH> 100644
--- a/sc2/protocol.py
+++ b/sc2/protocol.py
@@ -1,4 +1,6 @@
+import sys
import aiohttp
+import asyncio
import logging
logger = logging.getLogger(__name__)
@@ -35,6 +37,15 @@ class Protocol:
except TypeError:
logger.exception("Cannot receive: Connection already closed.")
raise ConnectionAlreadyClosed("Connection already closed.")
+ except asyncio.CancelledError:
+ # If request is sent, the response must be received before reraising cancel
+ try:
+ await self._ws.receive_bytes()
+ except asyncio.CancelledError:
+ log.critical("Requests must not be cancelled multiple times")
+ sys.exit(2)
+ raise
+
response.ParseFromString(response_bytes)
logger.debug(f"Response received")
return response
diff --git a/sc2/sc2process.py b/sc2/sc2process.py
index <HASH>..<HASH> 100644
--- a/sc2/sc2process.py
+++ b/sc2/sc2process.py
@@ -52,7 +52,7 @@ class SC2Process:
async def __aenter__(self):
kill_switch.add(self)
- def signal_handler():
+ def signal_handler(*args):
kill_switch.kill_all()
signal.signal(signal.SIGINT, signal_handler)
|
Fix issue when timeout during ws send causes out-of-sync messaging
|
Dentosal_python-sc2
|
train
|
d48db43924c229071ae8163c6b8484852e370ef4
|
diff --git a/src/main/java/org/zalando/problem/spring/web/advice/HttpStatusAdapter.java b/src/main/java/org/zalando/problem/spring/web/advice/HttpStatusAdapter.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/zalando/problem/spring/web/advice/HttpStatusAdapter.java
+++ b/src/main/java/org/zalando/problem/spring/web/advice/HttpStatusAdapter.java
@@ -20,7 +20,7 @@ package org.zalando.problem.spring.web.advice;
* #L%
*/
-import com.google.common.base.Objects;
+import java.util.Objects;
import org.springframework.http.HttpStatus;
import javax.ws.rs.core.Response;
diff --git a/src/main/java/org/zalando/problem/spring/web/advice/validation/BaseValidationAdviceTrait.java b/src/main/java/org/zalando/problem/spring/web/advice/validation/BaseValidationAdviceTrait.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/zalando/problem/spring/web/advice/validation/BaseValidationAdviceTrait.java
+++ b/src/main/java/org/zalando/problem/spring/web/advice/validation/BaseValidationAdviceTrait.java
@@ -20,7 +20,6 @@ package org.zalando.problem.spring.web.advice.validation;
* #L%
*/
-import com.google.common.collect.ImmutableList;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.context.request.NativeWebRequest;
@@ -28,9 +27,9 @@ import org.zalando.problem.Problem;
import org.zalando.problem.spring.web.advice.AdviceTrait;
import java.util.Collection;
+import java.util.List;
import static java.util.Comparator.comparing;
-import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toList;
interface BaseValidationAdviceTrait extends AdviceTrait {
@@ -47,10 +46,10 @@ interface BaseValidationAdviceTrait extends AdviceTrait {
default ResponseEntity<Problem> newConstraintViolationProblem(final Collection<Violation> stream,
final NativeWebRequest request) throws HttpMediaTypeNotAcceptableException {
- final ImmutableList<Violation> violations = stream.stream()
+ final List<Violation> violations = stream.stream()
// sorting to make tests deterministic
.sorted(comparing(Violation::getField).thenComparing(Violation::getMessage))
- .collect(collectingAndThen(toList(), ImmutableList::copyOf));
+ .collect(toList());
return entity(new ConstraintViolationProblem(violations), request);
}
diff --git a/src/main/java/org/zalando/problem/spring/web/advice/validation/ConstraintViolationProblem.java b/src/main/java/org/zalando/problem/spring/web/advice/validation/ConstraintViolationProblem.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/zalando/problem/spring/web/advice/validation/ConstraintViolationProblem.java
+++ b/src/main/java/org/zalando/problem/spring/web/advice/validation/ConstraintViolationProblem.java
@@ -22,12 +22,13 @@ package org.zalando.problem.spring.web.advice.validation;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonTypeName;
-import com.google.common.collect.ImmutableList;
import org.zalando.problem.MoreStatus;
import org.zalando.problem.ThrowableProblem;
import javax.annotation.concurrent.Immutable;
import java.net.URI;
+import java.util.Collections;
+import java.util.List;
import java.util.Optional;
@Immutable
@@ -38,16 +39,16 @@ public final class ConstraintViolationProblem extends ThrowableProblem {
public static final URI CONSTRAINT_VIOLATION = URI.create(CONSTRAINT_VIOLATION_VALUE);
private final Optional<String> detail;
- private final ImmutableList<Violation> violations;
+ private final List<Violation> violations;
- public ConstraintViolationProblem(final ImmutableList<Violation> violations) {
+ public ConstraintViolationProblem(final List<Violation> violations) {
this(Optional.empty(), violations);
}
@JsonCreator
- private ConstraintViolationProblem(final Optional<String> detail, final ImmutableList<Violation> violations) {
+ private ConstraintViolationProblem(final Optional<String> detail, final List<Violation> violations) {
this.detail = detail;
- this.violations = violations;
+ this.violations = Collections.unmodifiableList(violations);
}
@Override
@@ -70,7 +71,7 @@ public final class ConstraintViolationProblem extends ThrowableProblem {
return detail;
}
- public ImmutableList<Violation> getViolations() {
+ public List<Violation> getViolations() {
return violations;
}
|
Removed guava ImmutableList from API
|
zalando_problem-spring-web
|
train
|
e969d42156437ec44a51828538e96846ab9c21bf
|
diff --git a/libcontainer/integration/exec_test.go b/libcontainer/integration/exec_test.go
index <HASH>..<HASH> 100644
--- a/libcontainer/integration/exec_test.go
+++ b/libcontainer/integration/exec_test.go
@@ -645,11 +645,11 @@ func testPids(t *testing.T, systemd bool) {
/bin/true | /bin/true | /bin/true | /bin/true | /bin/true | /bin/true | bin/true | /bin/true |
/bin/true | /bin/true | /bin/true | /bin/true | /bin/true | /bin/true | bin/true | /bin/true`)
if err != nil && !strings.Contains(out.String(), "sh: can't fork") {
- ok(t, err)
+ t.Fatal(err)
}
if err == nil {
- t.Fatalf("expected fork() to fail with restrictive pids limit")
+ t.Fatal("expected fork() to fail with restrictive pids limit")
}
// Minimal restrictions are not really supported, due to quirks in using Go
|
libct/int/testPids: logging nits
|
opencontainers_runc
|
train
|
b8d7ca4c592e71ecd806836cad8875ce1996bf6a
|
diff --git a/yt_array.py b/yt_array.py
index <HASH>..<HASH> 100644
--- a/yt_array.py
+++ b/yt_array.py
@@ -1085,7 +1085,7 @@ class YTArray(np.ndarray):
if ret_class is YTQuantity:
# This happens if you do ndarray * YTQuantity. Explicitly
# casting to YTArray avoids creating a YTQuantity with size > 1
- return YTArray(np.array(out_arr, unit))
+ return YTArray(np.array(out_arr), unit)
return ret_class(np.array(out_arr, copy=False), unit)
|
Fix API bug in YTArray casting during coercion from YTQuantity
--HG--
branch : yt
|
yt-project_unyt
|
train
|
aef38e32d630a2f67c02601418c7d99fb7d26371
|
diff --git a/core/src/main/java/com/google/common/truth/Platform.java b/core/src/main/java/com/google/common/truth/Platform.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/google/common/truth/Platform.java
+++ b/core/src/main/java/com/google/common/truth/Platform.java
@@ -201,6 +201,11 @@ final class Platform {
return Float.toString(value);
}
+ /** Turns a non-double, non-float object into a string. */
+ static String stringValueOfNonFloatingPoint(Object o) {
+ return String.valueOf(o);
+ }
+
/** Returns a human readable string representation of the throwable's stack trace. */
static String getStackTraceAsString(Throwable throwable) {
return Throwables.getStackTraceAsString(throwable);
diff --git a/core/src/main/java/com/google/common/truth/Subject.java b/core/src/main/java/com/google/common/truth/Subject.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/google/common/truth/Subject.java
+++ b/core/src/main/java/com/google/common/truth/Subject.java
@@ -24,6 +24,7 @@ import static com.google.common.truth.Fact.fact;
import static com.google.common.truth.Fact.simpleFact;
import static com.google.common.truth.Platform.doubleToString;
import static com.google.common.truth.Platform.floatToString;
+import static com.google.common.truth.Platform.stringValueOfNonFloatingPoint;
import static com.google.common.truth.Subject.EqualityCheck.SAME_INSTANCE;
import static com.google.common.truth.SubjectUtils.accumulate;
import static com.google.common.truth.SubjectUtils.append;
@@ -408,7 +409,7 @@ public class Subject {
} else if (o instanceof Float) {
return floatToString((Float) o);
} else {
- return String.valueOf(o);
+ return stringValueOfNonFloatingPoint(o);
}
}
diff --git a/core/src/main/java/com/google/common/truth/super/com/google/common/truth/Platform.java b/core/src/main/java/com/google/common/truth/super/com/google/common/truth/Platform.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/google/common/truth/super/com/google/common/truth/Platform.java
+++ b/core/src/main/java/com/google/common/truth/super/com/google/common/truth/Platform.java
@@ -20,6 +20,7 @@ import static java.lang.Float.parseFloat;
import static jsinterop.annotations.JsPackage.GLOBAL;
import com.google.common.collect.ImmutableList;
+import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -136,6 +137,31 @@ final class Platform {
return ((NativeNumber) (Object) value).toLocaleString("en-US", JavaLikeOptions.INSTANCE);
}
+ @JsType(isNative = true, namespace = "proto.im")
+ private static class Message {
+ public native String serialize();
+ }
+
+ @JsMethod(namespace = "proto.im.debug")
+ private static native Object dump(Message msg) /*-{
+ // Emtpy stub to make GWT happy. This will never get executed under GWT.
+ throw new Error();
+ }-*/;
+
+ /** Turns a non-double, non-float object into a string. */
+ static String stringValueOfNonFloatingPoint(Object o) {
+ // Check if we are in J2CL mode by probing a system property that only exists in GWT.
+ boolean inJ2clMode = System.getProperty("superdevmode", "doesntexist").equals("doesntexist");
+ if (inJ2clMode && o instanceof Message) {
+ Message msg = (Message) o;
+ boolean dumpAvailable =
+ "true".equals(System.getProperty("goog.DEBUG", "true"))
+ && !"true".equals(System.getProperty("COMPILED", "false"));
+ return dumpAvailable ? dump(msg).toString() : msg.serialize();
+ }
+ return String.valueOf(o);
+ }
+
/** Tests if current platform is Android which is always false. */
static boolean isAndroid() {
return false;
|
Add toString method to immutable proto dump object.
RELNOTES=n/a
PiperOrigin-RevId: <I>
|
google_truth
|
train
|
69c71a98da46f7077ccf44f26ade1b0c8aa5b1d1
|
diff --git a/xhyve.go b/xhyve.go
index <HASH>..<HASH> 100644
--- a/xhyve.go
+++ b/xhyve.go
@@ -38,10 +38,18 @@ func setTermios(state syscall.Termios) {
// on multiple OS threads again by Go's scheduler.
//export go_callback_exit
func go_callback_exit(status C.int) {
+ exitStatus := map[int]string{
+ 0: "Reset",
+ 1: "PowerOFF",
+ 2: "Halt",
+ 3: "TripleFault",
+ 100: "Internal error",
+ }
+
// Restores stty settings to the values that existed before running xhyve.
setTermios(termios)
- fmt.Printf("Exiting with status code %d\n", status)
+ fmt.Printf("VM has been suspended by %s event\n", exitStatus[int(status)])
fmt.Printf("Releasing allocated memory from Go land... ")
for _, arg := range argv {
C.free(unsafe.Pointer(arg))
@@ -50,10 +58,12 @@ func go_callback_exit(status C.int) {
// Turns exit flag On for mevent busy loop so that the next time kevent
// receives an event, mevent handles it and exits the loop.
+ fmt.Print("Signaling xhyve mevent dispatch loop to exit... ")
C.exit_mevent_dispatch_loop = true
// Forces kevent() to exit by using the self-pipe trick.
C.mevent_exit()
+ fmt.Println("done")
// Allows Go's scheduler to move the goroutine to a different OS thread.
runtime.UnlockOSThread()
|
Adds some additional logging when exiting the VM
|
hooklift_xhyve
|
train
|
afd0b93932373fb18a217d35d04f3330a3d6541e
|
diff --git a/lib/Pipe/Config.php b/lib/Pipe/Config.php
index <HASH>..<HASH> 100644
--- a/lib/Pipe/Config.php
+++ b/lib/Pipe/Config.php
@@ -12,9 +12,6 @@ class Config extends \ArrayObject
"uglify_js" => "\\Pipe\\Compressor\\UglifyJs"
);
- var $jsCompression = true;
- var $cssCompression = true;
-
# Public: Creates a config object from the YAML file/string.
#
# Returns a new Config object.
@@ -24,6 +21,9 @@ class Config extends \ArrayObject
return new static($config);
}
+ # Creates an environment from the config keys.
+ #
+ # Returns a new Environment instance.
function createEnvironment()
{
$env = new Environment;
@@ -31,7 +31,7 @@ class Config extends \ArrayObject
$loadPaths = $this['load_paths'] ?: array();
$env->appendPath($loadPaths);
- if ($this->jsCompression and $jsCompressor = $this['js_compressor']) {
+ if ($jsCompressor = $this['js_compressor']) {
if ($compressor = @$this->compressors[$jsCompressor]) {
$env->registerBundleProcessor('application/javascript', $compressor);
} else {
@@ -39,7 +39,7 @@ class Config extends \ArrayObject
}
}
- if ($this->cssCompression and $cssCompressor = $this["css_compressor"]) {
+ if ($cssCompressor = $this["css_compressor"]) {
if ($compressor = @$this->compressors[$cssCompressor]) {
$env->registerBundleProcessor('text/css', $compressor);
} else {
@@ -50,6 +50,12 @@ class Config extends \ArrayObject
return $env;
}
+ # Retrieves a config key. Makes no notices if the key
+ # does not exist.
+ #
+ # key - The config key to return.
+ #
+ # Returns the config value or null.
function offsetGet($key)
{
if (isset($this[$key])) {
|
Removed jsCompression and cssCompression flags. Just set either js_compressor or css_compressor.
|
CHH_pipe
|
train
|
e8bc3fb8185a000d9407fa64f435ae2e78214f09
|
diff --git a/app/Commands/Metric/AddMetricCommand.php b/app/Commands/Metric/AddMetricCommand.php
index <HASH>..<HASH> 100644
--- a/app/Commands/Metric/AddMetricCommand.php
+++ b/app/Commands/Metric/AddMetricCommand.php
@@ -72,10 +72,10 @@ class AddMetricCommand
'suffix' => 'required|string',
'description' => 'string',
'display_chart' => 'boolean',
- 'default_value' => 'numeric',
+ 'default_value' => 'integer',
'calc_type' => 'integer',
'display_chart' => 'integer',
- 'places' => 'numeric|min:0|max:4',
+ 'places' => 'integer|between:0,4',
];
/**
|
Use integer and between for metric rules
|
CachetHQ_Cachet
|
train
|
48fd51da8942615d0330173752e5d582593b108e
|
diff --git a/ethertdd/__init__.py b/ethertdd/__init__.py
index <HASH>..<HASH> 100644
--- a/ethertdd/__init__.py
+++ b/ethertdd/__init__.py
@@ -12,7 +12,7 @@ class EvmContract(object):
def __init__(self, compiled_abi, compiled_code, name,
constructor_args=[], sender=tester.k0, endowment=0,
- gas=None, state=None, event_listener=None):
+ gas=None, state=None, log_listener=None):
if not state:
state = tester.state()
@@ -30,9 +30,9 @@ class EvmContract(object):
self._translator = tester.abi.ContractTranslator(compiled_abi)
- if event_listener:
+ if log_listener:
self.state.block.log_listeners.append(
- lambda x: event_listener(self._translator.listen(x, noprint=True)))
+ lambda x: log_listener(self._translator.listen(x, noprint=True)))
if len(constructor_args) > 0:
compiled_code += self._translator.encode(name, constructor_args)[4:]
|
log_listener is more consistent with PyEthereum.
|
ethermarket_ethertdd.py
|
train
|
f9f9efa32bd9bca116cea8163409a2d5f44818b5
|
diff --git a/ChangeLog b/ChangeLog
index <HASH>..<HASH> 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,7 +1,7 @@
ChangeLog for Pylint
--------------------
-NOT RELEASED YET -- VERSION
+RELEASE DATE -- VERSION
* Don't require a docstring for empty modules. Closes issue #261.
* Fix a false positive with `too-few-format-args` string warning,
@@ -44,6 +44,10 @@ NOT RELEASED YET -- VERSION
* Add support for combining the Python 3 checker mode with the --jobs
flag (--py3k and --jobs). Closes issue #467.
+ * Add a new warning for the Python 3 porting checker, 'using-cmp-argument',
+ emitted when the `cmp` argument for the `list.sort` or `sorted builtin`
+ is encountered.
+
2015-01-16 -- 1.4.1
diff --git a/pylint/checkers/python3.py b/pylint/checkers/python3.py
index <HASH>..<HASH> 100644
--- a/pylint/checkers/python3.py
+++ b/pylint/checkers/python3.py
@@ -18,6 +18,7 @@ import re
import tokenize
import astroid
+from astroid import bases
from pylint import checkers, interfaces
from pylint.utils import WarningScope
from pylint.checkers import utils
@@ -326,6 +327,13 @@ class Python3Checker(checkers.BaseChecker):
'Used when the filter built-in is referenced in a non-iterating '
'context (returns an iterator in Python 3)',
{'maxversion': (3, 0)}),
+ 'W1640': ('Using the cmp argument for list.sort / sorted',
+ 'using-cmp-argument',
+ 'Using the cmp argument for list.sort or the sorted '
+ 'builtin should be avoided, since it was removed in '
+ 'Python 3. Using either `key` or `functools.cmp_to_key` '
+ 'should be preferred.',
+ {'maxversion': (3, 0)}),
}
_bad_builtins = frozenset([
@@ -425,7 +433,38 @@ class Python3Checker(checkers.BaseChecker):
else:
self.add_message('old-division', node=node)
+ def _check_cmp_argument(self, node):
+ # Check that the `cmp` argument is used
+ args = []
+ if (isinstance(node.func, astroid.Getattr)
+ and node.func.attrname == 'sort'):
+ inferred = utils.safe_infer(node.func.expr)
+ if not inferred:
+ return
+
+ builtins_list = "{}.list".format(bases.BUILTINS)
+ if (isinstance(inferred, astroid.List)
+ or inferred.qname() == builtins_list):
+ args = node.args
+
+ elif (isinstance(node.func, astroid.Name)
+ and node.func.name == 'sorted'):
+ inferred = utils.safe_infer(node.func)
+ if not inferred:
+ return
+
+ builtins_sorted = "{}.sorted".format(bases.BUILTINS)
+ if inferred.qname() == builtins_sorted:
+ args = node.args
+
+ for arg in args:
+ if isinstance(arg, astroid.Keyword) and arg.arg == 'cmp':
+ self.add_message('using-cmp-argument', node=node)
+ return
+
def visit_callfunc(self, node):
+ self._check_cmp_argument(node)
+
if isinstance(node.func, astroid.Getattr):
if any([node.args, node.starargs, node.kwargs]):
return
diff --git a/pylint/test/unittest_checker_python3.py b/pylint/test/unittest_checker_python3.py
index <HASH>..<HASH> 100644
--- a/pylint/test/unittest_checker_python3.py
+++ b/pylint/test/unittest_checker_python3.py
@@ -384,6 +384,19 @@ class Python3CheckerTest(testutils.CheckerTestCase):
with self.assertNoMessages():
self.walk(node)
+ def test_using_cmp_argument(self):
+ nodes = test_utils.extract_node("""
+ [].sort(cmp=lambda x: x) #@
+ a = list(range(x))
+ a.sort(cmp=lambda x: x) #@
+
+ sorted([], cmp=lambda x: x) #@
+ """)
+ for node in nodes:
+ message = testutils.Message('using-cmp-argument', node=node)
+ with self.assertAddsMessages(message):
+ self.checker.visit_callfunc(node)
+
@python2_only
class Python3TokenCheckerTest(testutils.CheckerTestCase):
|
Add a new warning for the Python 3 porting checker, 'using-cmp-argument'.
This warning is emitted when the `cmp` argument for the `list.sort` or `sorted builtin`
is encountered, since it was removed in Python 3. This is part of the issue #<I>.
|
PyCQA_pylint
|
train
|
ee2771ab1a855342089abe5206fc6a5071a6d99e
|
diff --git a/openstack_dashboard/settings.py b/openstack_dashboard/settings.py
index <HASH>..<HASH> 100644
--- a/openstack_dashboard/settings.py
+++ b/openstack_dashboard/settings.py
@@ -172,6 +172,7 @@ INSTALLED_APPS = [
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
AUTHENTICATION_BACKENDS = ('openstack_auth.backend.KeystoneBackend',)
AUTHENTICATION_URLS = ['openstack_auth.urls']
+AUTH_USER_MODEL = 'openstack_auth.User'
MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage'
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'
|
Use the User model from d-o-a
This patch moves us to explicitly using the replacement User
model from django-openstack-auth.
Change-Id: I<I>b9e0af3dd4c<I>f<I>cb9da<I>ef0bcc<I>e
Closes-Bug: <I>
Depends-On: I<I>cc5d<I>c<I>e<I>f2ad8c<I>
|
openstack_horizon
|
train
|
b38724296a42ec7dbe1d454a0351bff6d36a4104
|
diff --git a/pac4j-saml/src/main/java/org/pac4j/saml/credentials/authenticator/SAML2Authenticator.java b/pac4j-saml/src/main/java/org/pac4j/saml/credentials/authenticator/SAML2Authenticator.java
index <HASH>..<HASH> 100644
--- a/pac4j-saml/src/main/java/org/pac4j/saml/credentials/authenticator/SAML2Authenticator.java
+++ b/pac4j-saml/src/main/java/org/pac4j/saml/credentials/authenticator/SAML2Authenticator.java
@@ -3,6 +3,7 @@ package org.pac4j.saml.credentials.authenticator;
import org.opensaml.core.xml.XMLObject;
import org.opensaml.saml.saml2.core.Attribute;
import org.opensaml.saml.saml2.core.Conditions;
+import org.opensaml.saml.saml2.core.NameID;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.credentials.authenticator.Authenticator;
import org.pac4j.core.profile.definition.CommonProfileDefinition;
@@ -30,6 +31,10 @@ public class SAML2Authenticator extends ProfileDefinitionAware<SAML2Profile> imp
public static final String SESSION_INDEX = "sessionindex";
public static final String ISSUER_ID = "issuerId";
public static final String AUTHN_CONTEXT = "authnContext";
+ public static final String SAML_NAME_ID_FORMAT = "samlNameIdFormat";
+ public static final String SAML_NAME_ID_NAME_QUALIFIER = "samlNameIdNameQualifier";
+ public static final String SAML_NAME_ID_SP_NAME_QUALIFIER = "samlNameIdSpNameQualifier";
+ public static final String SAML_NAME_ID_SP_PROVIDED_ID = "samlNameIdSpProvidedId";
protected final Logger logger = LoggerFactory.getLogger(getClass());
@@ -43,8 +48,13 @@ public class SAML2Authenticator extends ProfileDefinitionAware<SAML2Profile> imp
init();
final SAML2Profile profile = getProfileDefinition().newProfile();
- profile.setId(credentials.getNameId().getValue());
+ final NameID nameId = credentials.getNameId();
+ profile.setId(nameId.getValue());
profile.addAttribute(SESSION_INDEX, credentials.getSessionIndex());
+ profile.addAuthenticationAttribute(SAML_NAME_ID_FORMAT, nameId.getFormat());
+ profile.addAuthenticationAttribute(SAML_NAME_ID_NAME_QUALIFIER, nameId.getNameQualifier());
+ profile.addAuthenticationAttribute(SAML_NAME_ID_SP_NAME_QUALIFIER, nameId.getSPNameQualifier());
+ profile.addAuthenticationAttribute(SAML_NAME_ID_SP_PROVIDED_ID, nameId.getSPProvidedID());
for (final Attribute attribute : credentials.getAttributes()) {
logger.debug("Processing profile attribute {}", attribute);
diff --git a/pac4j-saml/src/main/java/org/pac4j/saml/profile/SAML2Profile.java b/pac4j-saml/src/main/java/org/pac4j/saml/profile/SAML2Profile.java
index <HASH>..<HASH> 100644
--- a/pac4j-saml/src/main/java/org/pac4j/saml/profile/SAML2Profile.java
+++ b/pac4j-saml/src/main/java/org/pac4j/saml/profile/SAML2Profile.java
@@ -39,4 +39,21 @@ public class SAML2Profile extends CommonProfile {
public List<String> getAuthnContexts() {
return (List<String>) getAuthenticationAttribute(SAML2Authenticator.AUTHN_CONTEXT);
}
+
+ public String getSamlNameIdFormat() {
+ return (String) getAuthenticationAttribute(SAML2Authenticator.SAML_NAME_ID_FORMAT);
+ }
+
+ public String getSamlNameIdNameQualifier() {
+ return (String) getAuthenticationAttribute(SAML2Authenticator.SAML_NAME_ID_NAME_QUALIFIER);
+ }
+
+ public String getSamlNameIdSpNameQualifier() {
+ return (String) getAuthenticationAttribute(SAML2Authenticator.SAML_NAME_ID_SP_NAME_QUALIFIER);
+ }
+
+ public String getSamlNameIdSpProviderId() {
+ return (String) getAuthenticationAttribute(SAML2Authenticator.SAML_NAME_ID_SP_PROVIDED_ID);
+ }
+
}
diff --git a/pac4j-saml/src/main/java/org/pac4j/saml/sso/impl/SAML2LogoutRequestBuilder.java b/pac4j-saml/src/main/java/org/pac4j/saml/sso/impl/SAML2LogoutRequestBuilder.java
index <HASH>..<HASH> 100644
--- a/pac4j-saml/src/main/java/org/pac4j/saml/sso/impl/SAML2LogoutRequestBuilder.java
+++ b/pac4j-saml/src/main/java/org/pac4j/saml/sso/impl/SAML2LogoutRequestBuilder.java
@@ -80,6 +80,10 @@ public class SAML2LogoutRequestBuilder implements SAML2ObjectBuilder<LogoutReque
.getBuilder(NameID.DEFAULT_ELEMENT_NAME);
final NameID nameId = nameIdBuilder.buildObject();
nameId.setValue(samlP.getId());
+ nameId.setFormat(samlP.getSamlNameIdFormat());
+ nameId.setNameQualifier(samlP.getSamlNameIdNameQualifier());
+ nameId.setSPNameQualifier(samlP.getSamlNameIdSpNameQualifier());
+ nameId.setSPProvidedID(samlP.getSamlNameIdSpProviderId());
request.setNameID(nameId);
// session index added
final String sessIdx = (String) samlP.getAttribute("sessionindex");
|
SAML2 Single Logout - More info in logout requests for MS ADFS
Added 4 attributes of NameID to the SAML2 profile.
SAML2 single logout request will also have them set.
Conflicts:
pac4j-saml/src/main/java/org/pac4j/saml/credentials/authenticator/SAML2Authenticator.java
|
pac4j_pac4j
|
train
|
1a122f52fddf44cbe21e301cd77633e35eb51de3
|
diff --git a/lib/Document.js b/lib/Document.js
index <HASH>..<HASH> 100644
--- a/lib/Document.js
+++ b/lib/Document.js
@@ -286,7 +286,8 @@ function DocumentCarrier(model) {
return Promise.all(Document.attributesWithSchema(returnObject).map(async (key) => {
const value = utils.object.get(returnObject, key);
const modifierFunction = await model.schema.getAttributeSettingValue(modifier, key, {"returnFunction": true});
- if (modifierFunction && value) {
+ const isValueUndefined = typeof value === "undefined" || value === null;
+ if (modifierFunction && !isValueUndefined) {
utils.object.set(returnObject, key, await modifierFunction(value));
}
}));
|
Fixing issue where modifier wouldn’t be called on falsey values
|
dynamoosejs_dynamoose
|
train
|
36a099b062eca8a41c156648da09571cecf23c6f
|
diff --git a/src/streamlink/plugins/bbciplayer.py b/src/streamlink/plugins/bbciplayer.py
index <HASH>..<HASH> 100644
--- a/src/streamlink/plugins/bbciplayer.py
+++ b/src/streamlink/plugins/bbciplayer.py
@@ -96,8 +96,8 @@ class BBCiPlayer(Plugin):
@classmethod
def _extract_nonce(cls, http_result):
"""
- Given an HTTP response from the sessino endpoint, extract the nonce, so we can "sign" requests with it.
- We don't really sign the requests in the traditional sense of a nonce, we just incude them in the auth requests.
+ Given an HTTP response from the session endpoint, extract the nonce, so we can "sign" requests with it.
+ We don't really sign the requests in the traditional sense of a nonce, we just include them in the auth requests.
:param http_result: HTTP response from the bbc session endpoint.
:type http_result: requests.Response
@@ -105,16 +105,9 @@ class BBCiPlayer(Plugin):
:rtype: string
"""
- # Extract the redirect URL from the last call
- last_redirect_url = urlparse(http_result.history[-1].request.url)
- last_redirect_query = dict(parse_qsl(last_redirect_url.query))
- # Extract the nonce from the query string in the redirect URL
- final_url = urlparse(last_redirect_query['goto'])
- goto_url = dict(parse_qsl(final_url.query))
- goto_url_query = parse_json(goto_url['state'])
-
- # Return the nonce we can use for future queries
- return goto_url_query['nonce']
+ p = urlparse(http_result.url)
+ d = dict(parse_qsl(p.query))
+ return d.get("nonce")
def find_vpid(self, url, res=None):
"""
@@ -183,6 +176,7 @@ class BBCiPlayer(Plugin):
:return: Whether authentication was successful
:rtype: bool
"""
+
def auth_check(res):
return ptrt_url in ([h.url for h in res.history] + [res.url])
diff --git a/tests/plugins/test_bbciplayer.py b/tests/plugins/test_bbciplayer.py
index <HASH>..<HASH> 100644
--- a/tests/plugins/test_bbciplayer.py
+++ b/tests/plugins/test_bbciplayer.py
@@ -27,20 +27,8 @@ class TestPluginBBCiPlayer(unittest.TestCase):
def test_extract_nonce(self):
mock_nonce = "mock-nonce-nse"
-
- last_response = Response()
- last_response.request = Request('GET', "http://example.com/?" + urlencode(dict(
- goto="http://example.com/?" + urlencode(dict(
- state=json.dumps(dict(nonce=mock_nonce))
- ))
- )))
-
mock_response = Response()
- mock_response.history = [
- Response(), # Add some extra dummy responses in to make sure we always get the last
- Response(),
- last_response
- ]
+ mock_response.url = "http://example.com/?" + urlencode(dict(nonce=mock_nonce))
self.assertEqual(BBCiPlayer._extract_nonce(mock_response), mock_nonce)
|
plugins.bbciplayer: fix issue with nonce extraction
|
streamlink_streamlink
|
train
|
f8a607de9649c01f6a5baa6c7cdda12d144414a0
|
diff --git a/integration/mesos/src/main/java/alluxio/mesos/AlluxioScheduler.java b/integration/mesos/src/main/java/alluxio/mesos/AlluxioScheduler.java
index <HASH>..<HASH> 100644
--- a/integration/mesos/src/main/java/alluxio/mesos/AlluxioScheduler.java
+++ b/integration/mesos/src/main/java/alluxio/mesos/AlluxioScheduler.java
@@ -112,8 +112,9 @@ public class AlluxioScheduler implements Scheduler {
long masterMem =
Configuration.getBytes(PropertyKey.INTEGRATION_MASTER_RESOURCE_MEM) / Constants.MB;
long workerCpu = Configuration.getInt(PropertyKey.INTEGRATION_WORKER_RESOURCE_CPU);
- long workerMem =
+ long workerOverheadMem =
Configuration.getBytes(PropertyKey.INTEGRATION_WORKER_RESOURCE_MEM) / Constants.MB;
+ long ramdiskMem = Configuration.getBytes(PropertyKey.WORKER_MEMORY_SIZE) / Constants.MB;
LOG.info("Master launched {}, master count {}, "
+ "requested master cpu {} mem {} MB and required master hostname {}",
@@ -181,10 +182,10 @@ public class AlluxioScheduler implements Scheduler {
} else if (mMasterLaunched
&& !mWorkers.contains(offer.getHostname())
&& offerCpu >= workerCpu
- && offerMem >= workerMem
+ && offerMem >= (ramdiskMem + workerOverheadMem)
&& OfferUtils.hasAvailableWorkerPorts(offer)) {
LOG.debug("Creating Alluxio Worker executor");
- final String memSize = FormatUtils.getSizeFromBytes((long) workerMem * Constants.MB);
+ final String memSize = FormatUtils.getSizeFromBytes((long) ramdiskMem * Constants.MB);
executorBuilder
.setName("Alluxio Worker Executor")
.setSource("worker")
@@ -218,7 +219,7 @@ public class AlluxioScheduler implements Scheduler {
.build())
.build()));
// pre-build resource list here, then use it to build Protos.Task later.
- resources = getWorkerRequiredResources(workerCpu, workerMem);
+ resources = getWorkerRequiredResources(workerCpu, ramdiskMem + workerOverheadMem);
mWorkers.add(offer.getHostname());
mTaskName = Configuration.get(PropertyKey.INTEGRATION_MESOS_ALLUXIO_WORKER_NAME);
} else {
|
Include worker overhead in Mesos worker memory requirement
|
Alluxio_alluxio
|
train
|
a6f7f8e5b6c1a728274cb05aba3bc7a22687459a
|
diff --git a/lib/ircnode.js b/lib/ircnode.js
index <HASH>..<HASH> 100644
--- a/lib/ircnode.js
+++ b/lib/ircnode.js
@@ -303,19 +303,67 @@ irc.emitter.on('PRIVMSG', function (data) {
global.irc = irc;
irc.plugins = [];
+function unloadPlugin(filename) {
+ var ppath = path.join(plugin_dir, filename);
+ if (ppath.indexOf('.js', ppath.length - 3) === -1) {
+ console.log('Invalid plugin file: ' + filename);
+ } else {
+ if (require.cache[ppath] === undefined)
+ return;
+
+ var plugin = require.cache[ppath].exports;
+
+ for (var p in irc.plugins)
+ if (irc.plugins[p].name === plugin.name)
+ irc.plugins.pop(p);
+
+ for (var command in plugin.commands)
+ irc.emitter.removeListener(command, plugin.commands[command].handler);
+ delete require.cache[ppath];
+ }
+}
+function loadPlugin(filename) {
+ var ppath = path.join(plugin_dir, filename);
+ if (ppath.indexOf('.js', ppath.length - 3) === -1) {
+ console.log('Invalid plugin file: ' + filename);
+ } else {
+ unloadPlugin(filename);
+ var plugin = require(ppath);
+ for (var cmd in plugin.commands) {
+ if (typeof plugin.commands[cmd] === 'function')
+ plugin.commands[cmd] = { 'handler': plugin.commands[cmd] };
+ if (plugin.commands[cmd].enabled === undefined)
+ plugin.commands[cmd].enabled = true;
+ if (plugin.commands[cmd].enabled)
+ irc.emitter.on(cmd, plugin.commands[cmd].handler);
+ }
+ irc.plugins.push(plugin);
+ }
+}
fs.readdir(plugin_dir, function (err, files) {
for (var i = 0, len = files.length; i < len; i += 1) {
- var ppath = path.join(plugin_dir, files[i]);
- if (ppath.indexOf('.js', ppath.length - 3) === -1) {
- console.log('Invalid plugin file: ' + files[i]);
- } else {
- var plugin = require(ppath);
- plugin.enabled = true;
- irc.plugins.push(plugin);
- for (var e in plugin.name) {
- irc.emitter.on(plugin.name[e], plugin.handler[e]);
+ loadPlugin(files[i]);
+ }
+});
+fs.watch(plugin_dir, { persistent: false }, function (event, filename) {
+ if (!filename) {
+ console.log('Filename of modified plugin not provided');
+ } else if (event === 'rename') {
+ fs.exists(path.join(plugin_dir, filename), function (exists) {
+ if (exists) {
+ if (irc.debug)
+ console.log('Plugin file created: ' + filename);
+ loadPlugin(filename);
+ } else {
+ if (irc.debug)
+ console.log('Plugin file deleted: ' + filename);
+ unloadPlugin(filename);
}
- }
+ });
+ } else {
+ if (irc.debug)
+ console.log('Plugin file modified: ' + filename);
+ loadPlugin(filename);
}
});
@@ -323,10 +371,10 @@ irc.emitter.on('disable', function (act) {
irc.check_level(act.nick, act.host, 'admin', function (is_admin) {
if (is_admin) {
for (var p in irc.plugins) {
- for (var e in irc.plugins[p].name) {
- if (irc.plugins[p].name[e] === act.params[0]) {
- irc.plugins[p].enabled = false;
- irc.emitter.removeListener(irc.plugins[p].name[e], irc.plugins[p].handler[e]);
+ for (var cmd in irc.plugins[p].commands) {
+ if (cmd === act.params[0]) {
+ irc.plugins[p].commands[cmd].enabled = false;
+ irc.emitter.removeListener(cmd, irc.plugins[p].commands[cmd].handler);
irc.privmsg(act.source, act.params[0] + ' disabled');
}
}
@@ -341,11 +389,10 @@ irc.emitter.on('enable', function (act) {
irc.check_level(act.nick, act.host, 'admin', function (is_admin) {
if (is_admin) {
for (var p in irc.plugins) {
- for (var e in irc.plugins[p].name) {
- if (irc.plugins[p].name[e] === act.params[0] &&
- irc.plugins[p].enabled === false) {
- irc.plugins[p].enabled = true;
- irc.emitter.on(irc.plugins[p].name[e], irc.plugins[p].handler[e]);
+ for (var cmd in irc.plugins[p].commands) {
+ if (cmd === act.params[0] && irc.plugins[p].commands[cmd].enabled === false) {
+ irc.plugins[p].commands[cmd].enabled = true;
+ irc.emitter.on(cmd, irc.plugins[p].commands[cmd].handler);
irc.privmsg(act.source, act.params[0] + ' enabled');
}
}
|
added dynamic loading for plugins and changed what plugin.exports are expected
|
totallymike_ircnode
|
train
|
212a7bcb9f402d9a22fa534375e13786eee31ec3
|
diff --git a/regret_buffer.go b/regret_buffer.go
index <HASH>..<HASH> 100644
--- a/regret_buffer.go
+++ b/regret_buffer.go
@@ -30,13 +30,33 @@ type RegretOnceBufferCloser struct {
// underlying readCloser, and issued a Regret, we will not close it
// again.
func (rbc *RegretOnceBufferCloser) Close() error {
- if rbc.closed {
+ if rbc.regret && rbc.closed {
return nil
}
rbc.closed = true
return rbc.c.Close()
}
+func (rbc *RegretOnceBufferCloser) Read(p []byte) (n int, err error) {
+ if rbc.regret {
+ n, err = rbc.buf.Read(p)
+ if err != nil {
+ return
+ }
+ }
+ // don't read stream if already closed
+ if rbc.regret && rbc.closed {
+ return
+ }
+
+ en, err := rbc.r.Read(p[n:])
+ if !rbc.regret {
+ rbc.buf.Write(p[n : n+en])
+ }
+ n += en
+ return
+}
+
// initialize a RegretOnceBufferCloser with underlying readCloser rc
func NewRegretOnceBufferCloser(rc io.ReadCloser) *RegretOnceBufferCloser {
return &RegretOnceBufferCloser{*NewRegretOnceBuffer(rc), rc, false}
@@ -71,7 +91,7 @@ func NewRegretOnceBuffer(r io.Reader) *RegretOnceBuffer {
// reads from the underlying reader. Will buffer all input until Regret is called.
func (rb *RegretOnceBuffer) Read(p []byte) (n int, err error) {
if rb.regret {
- n, err = rb.buf.Read(p[:rb.buf.Len()])
+ n, err = rb.buf.Read(p)
if err != nil {
return
}
diff --git a/regret_buffer_test.go b/regret_buffer_test.go
index <HASH>..<HASH> 100644
--- a/regret_buffer_test.go
+++ b/regret_buffer_test.go
@@ -2,6 +2,7 @@ package goproxy
import (
"bytes"
+ "fmt"
"io"
"io/ioutil"
"testing"
@@ -125,6 +126,34 @@ func (cc *CloseCounter) Close() error {
return nil
}
+func assert(t *testing.T, b bool, msg string) {
+ if !b {
+ t.Errorf("Assertion Error: %s", msg)
+ }
+}
+
+func TestRegretBufferCloserEOF(t *testing.T) {
+ buf := new(bytes.Buffer)
+ cc := &CloseCounter{buf, 0}
+ mb := NewRegretOnceBufferCloser(cc)
+ word := "123"
+ buf.WriteString(word)
+
+ n, err := mb.Read([]byte{0,1})
+ assert(t, n==2 && err==nil, fmt.Sprint("unregreted read should work ",n, err))
+ mb.Close()
+ mb.Regret()
+
+ b := make([]byte, 10)
+ n, err = mb.Read(b)
+ assert(t, bytes.Equal(b[:2], []byte{'1', '2'}),
+ "read after regret should return all data until close")
+ assert(t, err==nil, fmt.Sprint("valid read return non nil", err))
+ n, err = mb.Read(b[2:])
+ assert(t, n==0, "reading after close should be zero length")
+ assert(t, err==io.EOF, fmt.Sprint("reading after close should be EOF ", err))
+}
+
func TestRegretBufferCloserRegretsClose(t *testing.T) {
buf := new(bytes.Buffer)
cc := &CloseCounter{buf, 0}
|
RegretOnceBufferCloser support Regret() after Read
|
elazarl_goproxy
|
train
|
574a85e3e0839c3aed330a1d05a95411c6000e0b
|
diff --git a/walrus/tusks/vedisdb.py b/walrus/tusks/vedisdb.py
index <HASH>..<HASH> 100644
--- a/walrus/tusks/vedisdb.py
+++ b/walrus/tusks/vedisdb.py
@@ -8,19 +8,19 @@ from walrus import *
class VedisList(List):
def extend(self, value):
- return self.database.lpush(self.key, *value)
+ return self.database.lmpush(self.key, value)
def pop(self):
return self.database.lpop(self.key)
class WalrusVedis(Vedis, Database):
- def __init__(self, filename=':memory:'):
+ def __init__(self, filename=':mem:'):
self._filename = filename
Vedis.__init__(self, filename)
def __repr__(self):
- if self._filename == ':memory:':
+ if self._filename in (':memory:', ':mem:'):
db_file = 'in-memory database'
else:
db_file = self._filename
@@ -32,8 +32,8 @@ class WalrusVedis(Vedis, Database):
def parse_response(self, *args, **kwargs):
raise RuntimeError('Error, parse_response should not be called.')
- def command(self, command_name, user_data=None):
- return self.register(command_name, user_data=user_data)
+ def command(self, command_name):
+ return self.register(command_name)
# Compatibility with method names from redis-py.
def getset(self, key, value):
@@ -45,35 +45,21 @@ class WalrusVedis(Vedis, Database):
def decrby(self, name, amount=1):
return self.decr_by(name, amount)
- # Provide "redis-like" names for the low-level KV-store functions.
- def kset(self, key, value):
- return self.kv_store(key, value)
+ # Compatibility with method signatures.
+ def mset(self, **data):
+ return super(WalrusVedis, self).mset(data)
- def kappend(self, key, value):
- return self.kv_append(key, value)
+ def mget(self, *keys):
+ return super(WalrusVedis, self).mget(list(keys))
- def kget(self, key, buf_size=4096, determine_buffer_size=False):
- return self.kv_fetch(key, buf_size, determine_buffer_size)
+ def __getitem__(self, key):
+ try:
+ return super(WalrusVedis, self).__getitem__(key)
+ except KeyError:
+ pass
- def kexists(self, key):
- return self.kv_exists(key)
-
- def kdel(self, key):
- return self.kv_delete(key)
-
- # Override certain methods to match either argument signature of Walrus,
- # or to consume a lazily-generated return value.
- def hmset(self, key, values):
- return super(WalrusVedis, self).hmset(key, **values)
-
- def smembers(self, key):
- return set(super(WalrusVedis, self).smembers(key))
-
- def sdiff(self, k1, k2):
- return set(super(WalrusVedis, self).sdiff(k1, k2))
-
- def sinter(self, k1, k2):
- return set(super(WalrusVedis, self).sinter(k1, k2))
+ def sadd(self, key, *items):
+ return super(WalrusVedis, self).smadd(key, list(items))
# Override the container types since Vedis provides its own using the
# same method-names as Walrus, and we want the Walrus containers.
@@ -170,22 +156,12 @@ class TestWalrusVedis(unittest.TestCase):
s1 = self.db.Set('s1')
s2 = self.db.Set('s2')
- s1.add(*range(5))
- s2.add(*range(3, 7))
+ s1.add(*map(str, range(5)))
+ s2.add(*map(str, range(3, 7)))
self.assertEqual(s1 - s2, set(['0', '1', '2']))
self.assertEqual(s2 - s1, set(['5', '6']))
self.assertEqual(s1 & s2, set(['3', '4']))
- def test_kv(self):
- self.db.kset('foo', 'bar')
- self.assertEqual(self.db.kget('foo'), 'bar')
- self.db.kappend('foo', 'xx')
- self.assertEqual(self.db.kget('foo'), 'barxx')
- self.assertTrue(self.db.kexists('foo'))
- self.assertFalse(self.db.kexists('xx'))
- self.db.kdel('foo')
- self.assertFalse(self.db.kexists('foo'))
-
def test_unsupported(self):
def assertUnsupported(cmd, *args):
method = getattr(self.db, cmd)
@@ -210,13 +186,13 @@ class TestWalrusVedis(unittest.TestCase):
self.db['n1'] = 'charlie'
self.db['n2'] = 'huey'
- self.assertTrue(self.db.KTITLE('n1'))
+ self.assertTrue(_ktitle_impl('n1'))
self.assertEqual(self.db['n1'], 'Charlie')
- self.assertTrue(self.db.KTITLE('n2'))
+ self.assertTrue(self.db.execute('KTITLE n2'))
self.assertEqual(self.db['n2'], 'Huey')
- self.assertFalse(self.db.KTITLE('nx'))
+ self.assertFalse(self.db.execute('KTITLE nx'))
self.assertIsNone(self.db['nx'])
|
Update Vedis integration for Walrus.
|
coleifer_walrus
|
train
|
2676d74be4218dd7c3ab8c6af76e95869e150928
|
diff --git a/src/Elcodi/CurrencyBundle/Twig/PrintPriceExtension.php b/src/Elcodi/CurrencyBundle/Twig/PrintPriceExtension.php
index <HASH>..<HASH> 100644
--- a/src/Elcodi/CurrencyBundle/Twig/PrintPriceExtension.php
+++ b/src/Elcodi/CurrencyBundle/Twig/PrintPriceExtension.php
@@ -70,7 +70,7 @@ class PrintPriceExtension extends Twig_Extension
/**
- * Return route of image
+ * Return a formatted price given an amount and the target currency
*
* @param float $amount the amount to print
* @param string $sourceCurrency Iso code of the source currency
|
Update PrintPriceExtension.php
Small docblock changes
|
sottosviluppo_elcodi
|
train
|
072d1cd283794fe0e6471237d818504168de4695
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -1,11 +1,18 @@
#!/usr/bin/env python
-from setuptools import setup, find_packages
+from codecs import open
+
+from setuptools import find_packages, setup
+
+
+with open('README.rst', 'r', 'utf-8') as f:
+ readme = f.read()
+
setup(
name='django-paginationlinks',
version='0.1',
description='Django Pagination Links',
- long_description=open('README.rst').read(),
+ long_description=readme,
url='https://github.com/blancltd/django-paginationlinks',
maintainer='Alex Tomkins',
maintainer_email='alex@blanc.ltd.uk',
|
Fix problems with UTF-8 README.rst
|
developersociety_django-paginationlinks
|
train
|
bbdd20cfeb8da8f5e684f614b7dfab5cfbceca59
|
diff --git a/activesupport/lib/active_support/core_ext/integer/time.rb b/activesupport/lib/active_support/core_ext/integer/time.rb
index <HASH>..<HASH> 100644
--- a/activesupport/lib/active_support/core_ext/integer/time.rb
+++ b/activesupport/lib/active_support/core_ext/integer/time.rb
@@ -17,21 +17,6 @@ class Integer
#
# # equivalent to Time.now.advance(months: 4, years: 5)
# (4.months + 5.years).from_now
- #
- # While these methods provide precise calculation when used as in the examples
- # above, care should be taken to note that this is not true if the result of
- # +months+, +years+, etc is converted before use:
- #
- # # equivalent to 30.days.to_i.from_now
- # 1.month.to_i.from_now
- #
- # # equivalent to 365.25.days.to_f.from_now
- # 1.year.to_f.from_now
- #
- # In such cases, Ruby's core
- # Date[http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html] and
- # Time[http://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html] should be used for precision
- # date and time arithmetic.
def months
ActiveSupport::Duration.new(self * 30.days, [[:months, self]])
end
diff --git a/activesupport/lib/active_support/core_ext/numeric/time.rb b/activesupport/lib/active_support/core_ext/numeric/time.rb
index <HASH>..<HASH> 100644
--- a/activesupport/lib/active_support/core_ext/numeric/time.rb
+++ b/activesupport/lib/active_support/core_ext/numeric/time.rb
@@ -18,21 +18,6 @@ class Numeric
#
# # equivalent to Time.current.advance(months: 4, years: 5)
# (4.months + 5.years).from_now
- #
- # While these methods provide precise calculation when used as in the examples above, care
- # should be taken to note that this is not true if the result of `months', `years', etc is
- # converted before use:
- #
- # # equivalent to 30.days.to_i.from_now
- # 1.month.to_i.from_now
- #
- # # equivalent to 365.25.days.to_f.from_now
- # 1.year.to_f.from_now
- #
- # In such cases, Ruby's core
- # Date[http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html] and
- # Time[http://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html] should be used for precision
- # date and time arithmetic.
def seconds
ActiveSupport::Duration.new(self, [[:seconds, self]])
end
|
Remove reference to Numeric#from_now, as it is no longer supported
|
rails_rails
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.