hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
d4b3cc4586219202880fac4e49548e50f604bca5
|
diff --git a/metnet/tests/test_fastcore.py b/metnet/tests/test_fastcore.py
index <HASH>..<HASH> 100755
--- a/metnet/tests/test_fastcore.py
+++ b/metnet/tests/test_fastcore.py
@@ -145,7 +145,8 @@ class TestFastcoreSimpleVlassisModel(unittest.TestCase):
@unittest.skipIf(cplex is None, 'solver not available')
def test_fastcore_global_inconsistent(self):
self.database.set_reaction('rxn_7', parse_reaction('|E| <=>'))
- with self.assertRaises(Exception):
+ self.model.add_reaction('rxn_7')
+ with self.assertRaises(fastcore.FastcoreError):
fastcore.fastcore(self.model, { 'rxn_7' }, 0.001,
solver=self.solver)
|
test: Fix fastcore global inconsistency test that did not work
Previously the test would simply test that an Exception was raised.
This simply silenced an error in the way the model was setup before
the call. Instead the FastcoreError is tested for an the reaction
is added properly to the model before the call.
|
zhanglab_psamm
|
train
|
4c4544a75086464bae71ebc238f87ed66d0a5118
|
diff --git a/lib/tinplate/request_authenticator.rb b/lib/tinplate/request_authenticator.rb
index <HASH>..<HASH> 100644
--- a/lib/tinplate/request_authenticator.rb
+++ b/lib/tinplate/request_authenticator.rb
@@ -45,9 +45,6 @@ module Tinplate
end
def signature
- #puts "CORRECT STRING: vibaHBXwUXFqVSg-+kTrqYJZEJkbVeqLc=bo.LlXPOSTmultipart/form-data; boundary=d8b4f160da95---------------d8b4f160da95tineye+logo%281%29.png1350511031wAqXrSG7mJPn5YA6cwDalG.Shttps://api.tineye.com/rest/search/limit=30&offset=0"
- #puts " MY STRING: #{signature_components.join}"
-
OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new("sha1"),
Tinplate.configuration.private_key,
signature_components.join)
diff --git a/lib/tinplate/tineye.rb b/lib/tinplate/tineye.rb
index <HASH>..<HASH> 100644
--- a/lib/tinplate/tineye.rb
+++ b/lib/tinplate/tineye.rb
@@ -14,12 +14,9 @@ module Tinplate
sort: sort,
order: order
}
+ img = image_url ? { image_url: image_url } : { image_path: image_path }
- response = if image_url
- get_request "search", options.merge(image_url: image_url)
- elsif image_path
- post_request "search", options.merge(image_path: image_path)
- end
+ response = request("search", options.merge(img))
Tinplate::SearchResults.new(response["results"])
end
@@ -35,31 +32,26 @@ module Tinplate
request("image_count")["results"]
end
-
private
- def get_request(action, params = {})
- auth = Tinplate::RequestAuthenticator.new(action, params)
- params.merge!(auth.params)
-
- response = ::JSON.parse(connection.get("#{action}/", params).body)
+ def request(action, params = {})
+ http_verb = :get
- if response["code"] != 200
- raise Tinplate::Error.from_response(response["code"], response["messages"][0], response["messages"][1])
+ upload = if params[:image_path]
+ http_verb = :post
+ Faraday::UploadIO.new(params.delete(:image_path), "image/jpeg")
end
- response
- end
-
- def post_request(action, params = {})
- image = params.delete(:image_path)
-
- auth = Tinplate::RequestAuthenticator.new(action, params, image)
+ auth = Tinplate::RequestAuthenticator.new(action, params, upload && upload.original_filename)
params.merge!(auth.params)
- params.merge!(image_upload: Faraday::UploadIO.new(image, "image/jpeg"))
+ params.merge!(image_upload: upload) if upload
+
+ response = ::JSON.parse(connection.send(http_verb, "#{action}/", params).body)
- response = ::JSON.parse(connection.post("#{action}/", params).body)
+ if response["code"] != 200
+ raise Tinplate::Error.from_response(response["code"], response["messages"][0], response["messages"][1])
+ end
response
end
diff --git a/spec/tineye_spec.rb b/spec/tineye_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/tineye_spec.rb
+++ b/spec/tineye_spec.rb
@@ -84,7 +84,7 @@ describe Tinplate::TinEye do
}.to_json
end
- it "parses results" do
+ it "parses results from URL search" do
connection = double(get: double(body: valid_response))
allow(tineye).to receive(:connection).and_return(connection)
@@ -96,6 +96,24 @@ describe Tinplate::TinEye do
expect(results.matches.first.backlinks.first).to be_a OpenStruct
end
+ it "parses results from upload search" do
+ path = "/home/jim/example.jpg"
+
+ connection = double(post: double(body: valid_response))
+ upload = double(original_filename: "example.jpg")
+
+ allow(tineye).to receive(:connection).and_return(connection)
+ allow(Faraday::UploadIO).to receive(:new).with(path, "image/jpeg").and_return upload
+
+ results = tineye.search(image_path: path)
+
+ expect(results.total_results).to eq 2
+ expect(results.total_backlinks).to eq 3
+ expect(results.matches.count). to eq 2
+
+ expect(results.matches.first.backlinks.first).to be_a OpenStruct
+ end
+
context "when the API returns an error" do
it "raises a generic error by default" do
connection = double(get: double(body: error_response))
|
Update TinEye spec with POST request.
|
unsplash_tinplate
|
train
|
2569ba3ab69f922011e28a4200b439984c11fa80
|
diff --git a/concrete/src/Entity/Attribute/Value/Value/TopicsValue.php b/concrete/src/Entity/Attribute/Value/Value/TopicsValue.php
index <HASH>..<HASH> 100644
--- a/concrete/src/Entity/Attribute/Value/Value/TopicsValue.php
+++ b/concrete/src/Entity/Attribute/Value/Value/TopicsValue.php
@@ -63,4 +63,16 @@ class TopicsValue extends AbstractValue
}
return implode(', ', $topics);
}
+
+ public function __clone()
+ {
+ $clonedSelectedTopics = new ArrayCollection();
+ foreach ($this->getSelectedTopics() as $selectedTopic) {
+ /** @var SelectedTopic $clonedSelectedTopic */
+ $clonedSelectedTopic = clone $selectedTopic;
+ $clonedSelectedTopic->setAttributeValue($this);
+ $clonedSelectedTopics->add($clonedSelectedTopic);
+ }
+ $this->setSelectedTopics($clonedSelectedTopics);
+ }
}
|
On cloning topics value, we need to clone selected topics too
(cherry picked from commit <I>ba7c<I>eb1f<I>e5b<I>baa8e0fd<I>ced)
|
concrete5_concrete5
|
train
|
cd295af283dc918b9fd704fa2edb249ece7dbe6c
|
diff --git a/Components/Queues/Drivers/StompQueueDriver.php b/Components/Queues/Drivers/StompQueueDriver.php
index <HASH>..<HASH> 100644
--- a/Components/Queues/Drivers/StompQueueDriver.php
+++ b/Components/Queues/Drivers/StompQueueDriver.php
@@ -161,6 +161,22 @@ class StompQueueDriver extends Service implements QueueDriverInterface
}
/**
+ * @return mixed
+ */
+ public function getTimeout()
+ {
+ return $this->timeout;
+ }
+
+ /**
+ * @return mixed
+ */
+ public function getVhost()
+ {
+ return $this->vhost;
+ }
+
+ /**
* @return int
*/
public function getDequeueingTimeMs()
@@ -184,8 +200,8 @@ class StompQueueDriver extends Service implements QueueDriverInterface
$client->setReceiptWait($this->timeout);
$client->setSync($sync);
$client->getConnection()->setReadTimeout($this->timeout);
- $client->setVersions([$version]);
- $client->setVhostname($vhost);
+ $client->setVersions([$this->stompVersion]);
+ $client->setVhostname($this->vhost);
$this->statefulStomp = new StatefulStomp($client);
}
|
Expose timeout and vhost in stomp driver
|
smartboxgroup_integration-framework-bundle
|
train
|
6f936197c35584d4123256cfa222289ba59c2934
|
diff --git a/lib/amazon.js b/lib/amazon.js
index <HASH>..<HASH> 100644
--- a/lib/amazon.js
+++ b/lib/amazon.js
@@ -123,14 +123,18 @@ Provider.prototype.status = function (name, node, callback) {
logger.debug('discovered instances', instances);
+ var instance = instances[instances.length - 1];
+
if (instances.length >= 2) {
- instances.forEach(function (instance) {
- logger.warn('multiple instances with the same name detected:', name, instance.id, instance.state);
- });
+ instances
+ .filter(function (inst) {
+ return ['shutting-down', 'terminated', 'stopping', 'stopped'].indexOf(inst.state) < 0 && instance != inst;
+ })
+ .forEach(function (inst) {
+ logger.warn('multiple instances with the same name detected:', name, inst.id, inst.state);
+ });
}
- var instance = instances[instances.length - 1];
-
var state;
switch (instance.state) {
|
Added ways to filter duplicate but terminating instances.
|
websecurify_node-vortex
|
train
|
e9bbdd9c2c5aea2605c06cbf52be41aacc80d12b
|
diff --git a/vault/core.go b/vault/core.go
index <HASH>..<HASH> 100644
--- a/vault/core.go
+++ b/vault/core.go
@@ -438,7 +438,7 @@ type CoreConfig struct {
func NewCore(conf *CoreConfig) (*Core, error) {
if conf.HAPhysical != nil && conf.HAPhysical.HAEnabled() {
if conf.RedirectAddr == "" {
- return nil, fmt.Errorf("missing redirect address")
+ return nil, fmt.Errorf("missing API address, please set in configuration or via environment")
}
}
|
Update redirect address error to be more clear
|
hashicorp_vault
|
train
|
d83f52e7339b3c4b08a8f11fa710b07b65f2e91a
|
diff --git a/src/lib/Supra/Authentication/AuthenticationController.php b/src/lib/Supra/Authentication/AuthenticationController.php
index <HASH>..<HASH> 100644
--- a/src/lib/Supra/Authentication/AuthenticationController.php
+++ b/src/lib/Supra/Authentication/AuthenticationController.php
@@ -53,7 +53,7 @@ abstract class AuthenticationController extends ControllerAbstraction implements
* @var array
*/
public $publicUrlList = array();
-
+
/**
* Defines, will be user redirected on login success
* @var boolean
@@ -67,7 +67,7 @@ abstract class AuthenticationController extends ControllerAbstraction implements
public function getPublicUrlList()
{
$list = $this->prepareUrlList($this->publicUrlList);
-
+
return $list;
}
@@ -76,16 +76,17 @@ abstract class AuthenticationController extends ControllerAbstraction implements
* @param array $list
* @return array
*/
- public function prepareUrlList($list) {
-
+ public function prepareUrlList($list)
+ {
+
$trimFunction = function ($value) {
return trim($value, '/');
};
$list = array_map($trimFunction, $list);
-
+
return $list;
}
-
+
/**
* Returns login field name
* @return string
@@ -170,7 +171,7 @@ abstract class AuthenticationController extends ControllerAbstraction implements
// TODO: maybe should fetch session manager by user provider
//$sessionManager = ObjectRepository::getSessionManager($userProvider);
$sessionManager = ObjectRepository::getSessionManager($this);
-
+
// TODO: cerate special namespace for this
$session = $sessionManager->getDefaultSessionNamespace();
/* @var $session SessionNamespace */
@@ -208,7 +209,7 @@ abstract class AuthenticationController extends ControllerAbstraction implements
// Authenticating user
$user = null;
-
+
$eventArgs = new Event\EventArgs($this);
$eventArgs->request = $request;
@@ -218,7 +219,7 @@ abstract class AuthenticationController extends ControllerAbstraction implements
if ($password->isEmpty()) {
throw new Exception\WrongPasswordException("Empty passwords are not allowed");
}
-
+
$eventManager = ObjectRepository::getEventManager($this);
$eventManager->fire(Event\EventArgs::preAuthenticate, $eventArgs);
@@ -228,10 +229,10 @@ abstract class AuthenticationController extends ControllerAbstraction implements
$auditLog = ObjectRepository::getAuditLogger($this);
$auditLog->info($this, "User '{$user->getEmail()}' logged in", $user);
-
+
$eventManager = ObjectRepository::getEventManager($this);
$eventManager->fire(Event\EventArgs::onAuthenticationSuccess, $eventArgs);
-
+
if ($xmlHttpRequest) {
$this->response->setCode(200);
$this->response->output('1');
@@ -246,20 +247,30 @@ abstract class AuthenticationController extends ControllerAbstraction implements
throw new StopRequestException("Login success");
} catch (Exception\AuthenticationFailure $exc) {
-
+
$eventManager = ObjectRepository::getEventManager($this);
$eventManager->fire(Event\EventArgs::onAuthenticationFailure, $eventArgs);
-
+
//TODO: pass the failure message somehow
// Login not successfull
- $message = 'Incorrect login name or password';
-
+ if ($exc instanceof Exception\WrongPasswordException) {
+ $message = 'Incorrect login name or password';
+ }
+
+ if ($exc instanceof Exception\UserNotFoundException) {
+ $message = 'Incorrect login name or password';
+ }
+
if ($exc instanceof Exception\AuthenticationBanException) {
$message = 'Too many authentication failures';
}
//TODO: i18n
if ($exc instanceof Exception\ExistingSessionLimitation) {
+
+ $message = $exc->getMessage();
+ } else if ($exc instanceof Exception\AuthenticationFailure) {
+
$message = $exc->getMessage();
}
@@ -284,7 +295,7 @@ abstract class AuthenticationController extends ControllerAbstraction implements
}
}
}
-
+
// Allow accessign public URL
if ($isPublicUrl) {
return;
@@ -335,10 +346,10 @@ abstract class AuthenticationController extends ControllerAbstraction implements
protected function isPublicUrl(Path $path)
{
$publicUrlList = $this->getPublicUrlList();
-
+
foreach ($publicUrlList as $publicUrl) {
$publicUrlPath = new Path($publicUrl);
-
+
if ($path->equals($publicUrlPath)) {
return true;
}
@@ -382,14 +393,14 @@ abstract class AuthenticationController extends ControllerAbstraction implements
return $uri;
}
-
+
/**
*
* @param boolean $skip
*/
- public function setSkipRedirect($skip)
+ public function setSkipRedirect($skip)
{
$this->skipRedirect = $skip;
}
-
+
}
\ No newline at end of file
|
Issue red #<I>;
* Modify AuthenticationController to process AuthenticationFailure exceptions better;
|
sitesupra_sitesupra
|
train
|
73015b57809ef9d2152b333a369bc1b7aefa8028
|
diff --git a/liquibase-core/src/main/java/liquibase/snapshot/jvm/CatalogSnapshotGenerator.java b/liquibase-core/src/main/java/liquibase/snapshot/jvm/CatalogSnapshotGenerator.java
index <HASH>..<HASH> 100644
--- a/liquibase-core/src/main/java/liquibase/snapshot/jvm/CatalogSnapshotGenerator.java
+++ b/liquibase-core/src/main/java/liquibase/snapshot/jvm/CatalogSnapshotGenerator.java
@@ -1,22 +1,15 @@
package liquibase.snapshot.jvm;
-import liquibase.CatalogAndSchema;
-import liquibase.database.AbstractJdbcDatabase;
import liquibase.database.Database;
-import liquibase.database.jvm.JdbcConnection;
+import liquibase.diff.compare.DatabaseObjectComparatorFactory;
import liquibase.exception.DatabaseException;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.snapshot.DatabaseSnapshot;
import liquibase.snapshot.InvalidExampleException;
import liquibase.structure.DatabaseObject;
import liquibase.structure.core.Catalog;
-import liquibase.diff.compare.DatabaseObjectComparatorFactory;
-import liquibase.util.JdbcUtils;
-import java.sql.ResultSet;
import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.List;
public class CatalogSnapshotGenerator extends JdbcSnapshotGenerator {
@@ -67,36 +60,5 @@ public class CatalogSnapshotGenerator extends JdbcSnapshotGenerator {
protected void addTo(DatabaseObject foundObject, DatabaseSnapshot snapshot) throws DatabaseException, InvalidExampleException {
//nothing to add to
}
-
- protected String[] getDatabaseCatalogNames(Database database) throws SQLException, DatabaseException {
- List<String> returnList = new ArrayList<String>();
-
- ResultSet catalogs = null;
-
- try {
- if (((AbstractJdbcDatabase) database).jdbcCallsCatalogsSchemas()) {
- catalogs = ((JdbcConnection) database.getConnection()).getMetaData().getSchemas();
- } else {
- catalogs = ((JdbcConnection) database.getConnection()).getMetaData().getCatalogs();
- }
- while (catalogs.next()) {
- if (((AbstractJdbcDatabase) database).jdbcCallsCatalogsSchemas()) {
- returnList.add(catalogs.getString("TABLE_SCHEM"));
- } else {
- returnList.add(catalogs.getString("TABLE_CAT"));
- }
- }
- } finally {
- if (catalogs != null) {
- try {
- catalogs.close();
- } catch (SQLException ignore) {
-
- }
- }
-
- }
- return returnList.toArray(new String[returnList.size()]);
- }
-
+
}
diff --git a/liquibase-core/src/main/java/liquibase/snapshot/jvm/JdbcSnapshotGenerator.java b/liquibase-core/src/main/java/liquibase/snapshot/jvm/JdbcSnapshotGenerator.java
index <HASH>..<HASH> 100644
--- a/liquibase-core/src/main/java/liquibase/snapshot/jvm/JdbcSnapshotGenerator.java
+++ b/liquibase-core/src/main/java/liquibase/snapshot/jvm/JdbcSnapshotGenerator.java
@@ -4,6 +4,7 @@ import liquibase.database.AbstractJdbcDatabase;
import liquibase.database.Database;
import liquibase.database.core.InformixDatabase;
import liquibase.database.core.PostgresDatabase;
+import liquibase.database.jvm.JdbcConnection;
import liquibase.diff.DiffStatusListener;
import liquibase.exception.DatabaseException;
import liquibase.logging.LogFactory;
@@ -13,7 +14,11 @@ import liquibase.snapshot.SnapshotGenerator;
import liquibase.snapshot.SnapshotGeneratorChain;
import liquibase.structure.DatabaseObject;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
import java.util.HashSet;
+import java.util.List;
import java.util.Set;
public abstract class JdbcSnapshotGenerator implements SnapshotGenerator {
@@ -119,4 +124,43 @@ public abstract class JdbcSnapshotGenerator implements SnapshotGenerator {
}
return objectName;
}
+
+ /**
+ * Fetches an array of Strings with the catalog names in the database.
+ * @param database The database from which to get the schema names
+ * @return An array of catalog name Strings (May be an empty array)
+ * @throws SQLException propagated java.sql.SQLException
+ * @throws DatabaseException if a different problem occurs during the DBMS-specific code
+ */
+ protected String[] getDatabaseCatalogNames(Database database) throws SQLException, DatabaseException {
+ List<String> returnList = new ArrayList<String>();
+
+ ResultSet catalogs = null;
+
+ try {
+ if (((AbstractJdbcDatabase) database).jdbcCallsCatalogsSchemas()) {
+ catalogs = ((JdbcConnection) database.getConnection()).getMetaData().getSchemas();
+ } else {
+ catalogs = ((JdbcConnection) database.getConnection()).getMetaData().getCatalogs();
+ }
+ while (catalogs.next()) {
+ if (((AbstractJdbcDatabase) database).jdbcCallsCatalogsSchemas()) {
+ returnList.add(catalogs.getString("TABLE_SCHEM"));
+ } else {
+ returnList.add(catalogs.getString("TABLE_CAT"));
+ }
+ }
+ } finally {
+ if (catalogs != null) {
+ try {
+ catalogs.close();
+ } catch (SQLException ignore) {
+
+ }
+ }
+
+ }
+ return returnList.toArray(new String[returnList.size()]);
+ }
+
}
|
Moved getDatabaseCatalogNames() into JdbcSnapshotGenerator, so SchemaSnapshotGenerator can use it
|
liquibase_liquibase
|
train
|
1518bae362be8c212e6d11318ea7b1c0e06ef393
|
diff --git a/gcsio/src/test/java/com/google/cloud/hadoop/gcsio/integration/GoogleCloudStorageTestHelper.java b/gcsio/src/test/java/com/google/cloud/hadoop/gcsio/integration/GoogleCloudStorageTestHelper.java
index <HASH>..<HASH> 100644
--- a/gcsio/src/test/java/com/google/cloud/hadoop/gcsio/integration/GoogleCloudStorageTestHelper.java
+++ b/gcsio/src/test/java/com/google/cloud/hadoop/gcsio/integration/GoogleCloudStorageTestHelper.java
@@ -259,8 +259,8 @@ public class GoogleCloudStorageTestHelper {
private static String makeBucketName(String prefix) {
String username = System.getProperty("user.name", "unknown").replaceAll("[-.]", "");
- username = username.substring(0, min(username.length(), 10));
- String uuidSuffix = UUID.randomUUID().toString().substring(0, 8);
+ username = username.substring(0, min(username.length(), 9));
+ String uuidSuffix = UUID.randomUUID().toString().substring(0, 6);
return prefix + DELIMITER + username + DELIMITER + uuidSuffix;
}
|
Decrease bucket prefix to not exceed max bucket size allowed (#<I>)
|
GoogleCloudPlatform_bigdata-interop
|
train
|
738cdc39ea402ff0e36e2e1e8c6342d3c6c3c94c
|
diff --git a/lib/version.rb b/lib/version.rb
index <HASH>..<HASH> 100644
--- a/lib/version.rb
+++ b/lib/version.rb
@@ -1,3 +1,3 @@
module MiniFB
- VERSION = "2.2.3"
+ VERSION = "2.3.0"
end
|
Bumped minor in case #<I> causes some issues (hopefully not).
|
appoxy_mini_fb
|
train
|
f1199eb4e1777c9fe19b8fc6cf1cdc58309cf8d0
|
diff --git a/lib/puppet/resource_api/base_context.rb b/lib/puppet/resource_api/base_context.rb
index <HASH>..<HASH> 100644
--- a/lib/puppet/resource_api/base_context.rb
+++ b/lib/puppet/resource_api/base_context.rb
@@ -18,7 +18,7 @@ class Puppet::ResourceApi::BaseContext
end
end
- [:creating, :updating, :deleting, :failing].each do |method|
+ [:creating, :updating, :deleting].each do |method|
define_method(method) do |titles, message: method.to_s.capitalize, &block|
start_time = Time.now
setup_context(titles, message)
@@ -35,6 +35,21 @@ class Puppet::ResourceApi::BaseContext
end
end
+ def failing(titles, message: 'Failing')
+ start_time = Time.now
+ setup_context(titles, message)
+ begin
+ debug('Start')
+ yield
+ warning("Finished failing in #{format_seconds(Time.now - start_time)} seconds")
+ rescue StandardError => e
+ err("Error after #{format_seconds(Time.now - start_time)} seconds: #{e}")
+ raise
+ ensure
+ @context = nil
+ end
+ end
+
def processing(titles, is, should, message: 'Processing')
start_time = Time.now
setup_context(titles, message)
diff --git a/spec/puppet/resource_api/base_context_spec.rb b/spec/puppet/resource_api/base_context_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/puppet/resource_api/base_context_spec.rb
+++ b/spec/puppet/resource_api/base_context_spec.rb
@@ -49,7 +49,7 @@ RSpec.describe Puppet::ResourceApi::BaseContext do
end
end
- [:creating, :updating, :deleting, :failing].each do |method|
+ [:creating, :updating, :deleting].each do |method|
describe "##{method}(title, &block)" do
it 'outputs the start and stop messages' do
allow(context).to receive(:send_log)
@@ -114,6 +114,74 @@ RSpec.describe Puppet::ResourceApi::BaseContext do
end
end
+ describe '#failing(titles, &block)' do
+ it 'logs a debug start message' do
+ allow(context).to receive(:send_log)
+ expect(context).to receive(:send_log).with(:debug, %r{\[Thing\[one\], Thing\[two\]\].*failing.*start}i)
+ context.failing(['Thing[one]', 'Thing[two]']) {}
+ end
+
+ it 'logs a warning on completion' do
+ allow(context).to receive(:send_log)
+ expect(context).to receive(:send_log).with(:warning, %r{\[Thing\[one\], Thing\[two\]\].*failing.*finished}i)
+ context.failing(['Thing[one]', 'Thing[two]']) {}
+ end
+
+ it 'logs completion time' do
+ allow(context).to receive(:send_log)
+ expect(context).to receive(:send_log).with(:warning, %r{finished failing in [0-9]*\.[0-9]* seconds}i)
+ context.failing(['Thing[one]', 'Thing[two]']) {}
+ end
+
+ it 'does not leak state between invocations' do
+ context.failing('resource_one') {}
+ expect(context).to receive(:send_log).with(:debug, %r{resource_two.*failing.*start}i)
+ expect(context).not_to receive(:send_log).with(anything, %r{.*resource_one.*})
+ context.failing('resource_two') {}
+ end
+
+ context 'when a StandardError is raised' do
+ it 'swallows the exception' do
+ pending('Currently the error is raised, when it should be swallowed')
+ expect {
+ context.failing('bad_resource') { raise StandardError, 'Bad Resource!' }
+ }.not_to raise_error
+ end
+
+ it 'logs an error' do
+ pending('Currently the error is raised, when it should be swallowed')
+ allow(context).to receive(:send_log)
+ expect(context).to receive(:send_log).with(:err, %r{bad_resource.*failing.*failed.*reasons}i)
+ context.failing('bad_resource') { raise StandardError, 'Reasons' }
+ end
+
+ it 'does not leak state into next invocation' do
+ pending('Currently the error is raised, when it should be swallowed')
+ context.failing('resource_one') { raise StandardError, 'Bad Resource!' }
+ expect(context).to receive(:send_log).with(:debug, %r{resource_two.*failing.*start}i)
+ expect(context).not_to receive(:send_log).with(anything, %r{.*resource_one.*})
+ context.failing('resource_two') {}
+ end
+ end
+
+ context 'when an Exception that is not StandardError is raised' do
+ it 'raises the exception' do
+ expect {
+ context.failing('total_failure') { raise LoadError, 'Disk Read Error' }
+ }.to raise_error(LoadError, 'Disk Read Error')
+ end
+
+ it 'does not leak state into next invocation' do
+ expect {
+ context.failing('resource_one') { raise LoadError, 'Uh oh' }
+ }.to raise_error(LoadError, 'Uh oh')
+ expect(context).to receive(:send_log).with(:debug, %r{resource_two.*failing.*start}i)
+ expect(context).not_to receive(:send_log).with(anything, %r{.*resource_one.*})
+ context.failing('resource_two') {}
+ end
+ end
+ end
+
[:created, :updated, :deleted].each do |method|
describe "##{method}(titles, message: '#{method.to_s.capitalize}')" do
it 'logs the action at :notice level' do
|
base_context#failing should always log completion as warning
|
puppetlabs_puppet-resource_api
|
train
|
bcb414466de88516c5b1d8a7f4e7db397503022a
|
diff --git a/with-jetty/src/main/java/com/aspectran/with/jetty/JettyServer.java b/with-jetty/src/main/java/com/aspectran/with/jetty/JettyServer.java
index <HASH>..<HASH> 100644
--- a/with-jetty/src/main/java/com/aspectran/with/jetty/JettyServer.java
+++ b/with-jetty/src/main/java/com/aspectran/with/jetty/JettyServer.java
@@ -57,6 +57,7 @@ public class JettyServer extends Server implements InitializableBean, Disposable
public void initialize() throws Exception {
synchronized (this) {
if (autoStart) {
+ log.info("Starting the Jetty server");
start();
}
}
@@ -65,10 +66,13 @@ public class JettyServer extends Server implements InitializableBean, Disposable
@Override
public void destroy() {
synchronized (this) {
+ log.info("Stopping the Jetty server");
try {
stop();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
} catch (Exception e) {
- log.error("JettyServer shutdown failed", e);
+ log.error("Failed to stop the Jetty server", e);
}
}
}
|
Fixed an issue where an interrupt exception was thrown when the Jetty server was stopped in a daemon environment.
|
aspectran_aspectran
|
train
|
9fd8f691a60c107b78690613577e6dec23580c3b
|
diff --git a/lib/module.js b/lib/module.js
index <HASH>..<HASH> 100644
--- a/lib/module.js
+++ b/lib/module.js
@@ -34,9 +34,19 @@ let writePayload = function(payload, route, root){
if (err) return console.error(err);
});
- // if routes are nested, ignore parent routes and extract last one
let data = eval('('+payload+')')
- const availableData = data.data.filter(d => Object.keys(d).length > 0).reduce((acc, current) => acc = { ...acc, ...current }, {})
+
+ // if routes are nested, merge them into one object
+ let availableData = data.data
+ .filter(d => Object.keys(d).length > 0)
+ .reduce((prev, current) => {
+ const colidingKey = Object.keys(prev).find(key => Object.keys(current).includes(key))
+ if(colidingKey)
+ console.error('Payload-extractor fails to extract nested routes data correctly because two routes have same field returned by asyncData: ' + colidingKey)
+ if(Object.keys(current).length > 1)
+ console.warn('Payload-extractor had to duplicate some nested routes data in extracted payload')
+ return { ...prev, ...current }
+ }, {})
fs.writeFile(path.resolve(dir, 'payload.json'), availableData ? JSON.stringify(availableData) : '', 'utf8', function (err) {
if (err) return console.error(err);
|
add warnings in case routes are nested
|
DreaMinder_nuxt-payload-extractor
|
train
|
60f7760866dd1c1f9e618630734dc57c63b94778
|
diff --git a/src/Mail/MailManager/index.js b/src/Mail/MailManager/index.js
index <HASH>..<HASH> 100644
--- a/src/Mail/MailManager/index.js
+++ b/src/Mail/MailManager/index.js
@@ -19,15 +19,29 @@ class MailManager {
}
/**
- * @description sends email with given data
+ * sends email with given data
+ *
* @method send
+ *
* @param {String} view
* @param {Object} data
* @param {Function} callback
- * @return {void}
+ * @param {String} [config]
+ *
+ * @return {Array}
+ *
+ * @example
+ * mail.send('welcome', {}, function (message) {
+ *
+ * })
+ * mail.send('welcome', {}, function (message) {
+ *
+ * }, 'alternate.config')
+ *
+ *
* @public
*/
- * send (view, data, callback) {
+ * send (view, data, callback, config) {
/**
* compiling view using view provider
* @type {String}
@@ -47,10 +61,31 @@ class MailManager {
* finally calling send method on
* driver to send email
*/
- return yield this.driver.send(message.data)
+ return yield this.driver.send(message.data, config)
}
- * raw (text, callback) {
+ /**
+ * sends email using raw text instead of making
+ * view from templates.
+ *
+ * @method raw
+ *
+ * @param {String} text
+ * @param {Function} callback
+ * @param {String} config
+ * @return {Array}
+ *
+ * @example
+ * mail.raw('<h2> Hello </h2>', function (message) {
+ *
+ * })
+ * mail.raw('<h2> Hello </h2>', function (message) {
+ *
+ * }, 'alternate.config')
+ *
+ * @public
+ */
+ raw (text, callback, config) {
/**
* creating a new message instance to be used for
* building mail options
@@ -64,7 +99,7 @@ class MailManager {
* finally calling send method on
* driver to send email
*/
- return yield this.driver.send(message.data)
+ return yield this.driver.send(message.data, config)
}
}
|
refactor(mail-manager): improve methods signature to accept config on send
now send and raw method can accept config key to be used for sending an email
|
adonisjs_adonis-mail
|
train
|
81bd628f013a9b37a8fe31b22643afc258ba3f51
|
diff --git a/lib/formats/auto.js b/lib/formats/auto.js
index <HASH>..<HASH> 100644
--- a/lib/formats/auto.js
+++ b/lib/formats/auto.js
@@ -15,7 +15,7 @@ var ssh = require('./ssh');
var rfc4253 = require('./rfc4253');
function read(buf) {
- if (buf.slice(0, 4).toString('ascii') === '----')
+ if (findPEMHeader(buf))
return (pem.read(buf));
if (buf.slice(0, 4).toString('ascii') === 'ssh-')
return (ssh.read(buf));
@@ -24,6 +24,25 @@ function read(buf) {
throw (new Error('Failed to auto-detect format of key'));
}
+function findPEMHeader(buf) {
+ var offset = 0;
+ while (offset < buf.length &&
+ (buf[offset] === 32 || buf[offset] === 10))
+ ++offset;
+ if (buf[offset] !== 45)
+ return (false);
+ while (offset < buf.length &&
+ (buf[offset] === 45))
+ ++offset;
+ while (offset < buf.length &&
+ (buf[offset] === 32))
+ ++offset;
+ if (offset + 5 > buf.length ||
+ buf.slice(offset, offset + 5).toString('ascii') !== 'BEGIN')
+ return (false);
+ return (true);
+}
+
function write(key) {
throw (new Error('"auto" format cannot be used for writing'));
}
diff --git a/lib/formats/pem.js b/lib/formats/pem.js
index <HASH>..<HASH> 100644
--- a/lib/formats/pem.js
+++ b/lib/formats/pem.js
@@ -15,6 +15,7 @@ var PrivateKey = require('../private-key');
var pkcs1 = require('./pkcs1');
var pkcs8 = require('./pkcs8');
var sshpriv = require('./ssh-private');
+var rfc4253 = require('./rfc4253');
/*
* For reading we support both PKCS#1 and PKCS#8. If we find a private key,
@@ -30,11 +31,11 @@ function read(buf, forceType) {
var lines = buf.split('\n');
var m = lines[0].match(/*JSSTYLED*/
- /BEGIN ([A-Z]+ )?(PUBLIC|PRIVATE) KEY/);
+ /[-]+[ ]*BEGIN ([A-Z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);
assert.ok(m, 'invalid PEM header');
var m2 = lines[lines.length - 2].match(/*JSSTYLED*/
- /END ([A-Z]+ )?(PUBLIC|PRIVATE) KEY/);
+ /[-]+[ ]*END ([A-Z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);
assert.ok(m2, 'invalid PEM footer');
/* Begin and end banners must match key type */
@@ -73,6 +74,8 @@ function read(buf, forceType) {
/* The new OpenSSH internal format abuses PEM headers */
if (alg && alg.toLowerCase() === 'openssh')
return (sshpriv.readSSHPrivate(type, buf));
+ if (alg && alg.toLowerCase() === 'ssh2')
+ return (rfc4253.readType(type, buf));
var der = new asn1.BerReader(buf);
der.originalInput = input;
diff --git a/lib/formats/ssh-private.js b/lib/formats/ssh-private.js
index <HASH>..<HASH> 100644
--- a/lib/formats/ssh-private.js
+++ b/lib/formats/ssh-private.js
@@ -92,6 +92,10 @@ function write(key) {
privBuf.writeInt(checkInt);
privBuf.write(key.toBuffer('rfc4253'));
privBuf.writeString(key.comment || '');
+
+ var n = 1;
+ while (privBuf._offset % 8 !== 0)
+ privBuf.writeChar(n++);
}
var buf = new SSHBuffer({});
@@ -116,13 +120,13 @@ function write(key) {
header = 'OPENSSH PUBLIC KEY';
var tmp = buf.toString('base64');
- var len = tmp.length + (tmp.length / 64) +
+ var len = tmp.length + (tmp.length / 70) +
18 + 16 + header.length*2 + 10;
buf = new Buffer(len);
var o = 0;
o += buf.write('-----BEGIN ' + header + '-----\n', o);
for (var i = 0; i < tmp.length; ) {
- var limit = i + 64;
+ var limit = i + 70;
if (limit > tmp.length)
limit = tmp.length;
o += buf.write(tmp.slice(i, limit), o);
|
Improve PEM validation, fix openssh private output
|
joyent_node-sshpk
|
train
|
cf41373f8f28fd335c2553ae97c334466cf33359
|
diff --git a/tests/test_algorithm.py b/tests/test_algorithm.py
index <HASH>..<HASH> 100644
--- a/tests/test_algorithm.py
+++ b/tests/test_algorithm.py
@@ -331,27 +331,27 @@ class TestMiscellaneousAPI(TestCase):
algo = TradingAlgorithm(asset_metadata=metadata)
# Test before either PLAY existed
- algo.datetime = pd.Timestamp('2001-12-01', tz='UTC')
+ algo.sim_params.period_end = pd.Timestamp('2001-12-01', tz='UTC')
with self.assertRaises(SymbolNotFound):
algo.symbol('PLAY')
with self.assertRaises(SymbolNotFound):
algo.symbols('PLAY')
# Test when first PLAY exists
- algo.datetime = pd.Timestamp('2002-12-01', tz='UTC')
+ algo.sim_params.period_end = pd.Timestamp('2002-12-01', tz='UTC')
list_result = algo.symbols('PLAY')
self.assertEqual(0, list_result[0])
# Test after first PLAY ends
- algo.datetime = pd.Timestamp('2004-12-01', tz='UTC')
+ algo.sim_params.period_end = pd.Timestamp('2004-12-01', tz='UTC')
self.assertEqual(0, algo.symbol('PLAY'))
# Test after second PLAY begins
- algo.datetime = pd.Timestamp('2005-12-01', tz='UTC')
+ algo.sim_params.period_end = pd.Timestamp('2005-12-01', tz='UTC')
self.assertEqual(1, algo.symbol('PLAY'))
# Test after second PLAY ends
- algo.datetime = pd.Timestamp('2006-12-01', tz='UTC')
+ algo.sim_params.period_end = pd.Timestamp('2006-12-01', tz='UTC')
self.assertEqual(1, algo.symbol('PLAY'))
list_result = algo.symbols('PLAY')
self.assertEqual(1, list_result[0])
diff --git a/zipline/algorithm.py b/zipline/algorithm.py
index <HASH>..<HASH> 100644
--- a/zipline/algorithm.py
+++ b/zipline/algorithm.py
@@ -695,7 +695,8 @@ class TradingAlgorithm(object):
"""
return self.asset_finder.lookup_symbol_resolve_multiple(
symbol_str,
- as_of_date=self.datetime)
+ as_of_date=self.sim_params.period_end
+ )
@api_method
def symbols(self, *args):
|
BUG: Symbol look-up now uses the sim_params.period_end as a look-up date
|
quantopian_zipline
|
train
|
991786b04088525dc5484d3ca54d86b51c648b42
|
diff --git a/Treant.js b/Treant.js
index <HASH>..<HASH> 100644
--- a/Treant.js
+++ b/Treant.js
@@ -154,13 +154,16 @@
/**
* Tree constructor.
*/
- var Tree = function (jsonConfig, treeId ) {
+ var Tree = function (jsonConfig, treeId, jQuery ) {
+
+ // optional
+ this.$ = jQuery;
this.id = treeId;
this.imageLoader = new ImageLoader();
this.CONFIG = UTIL.createMerge(Tree.CONFIG, jsonConfig.chart);
- this.drawArea = $(this.CONFIG.container).get(0);
+ this.drawArea = this.findEl( this.CONFIG.container, true );
this.drawArea.className += " Treant";
this.nodeDB = new NodeDB(jsonConfig.nodeStructure, this);
@@ -171,6 +174,17 @@
Tree.prototype = {
+ findEl: function( element, raw ) {
+ if ( this.$ ) {
+ var $element = this.$( element );
+ return ( raw? $element.get(0): $element );
+ }
+ else {
+ // todo add support for non-id elements
+ return document.getElementById( element.substring( 1 ) );
+ }
+ },
+
positionTree: function(callback) {
var self = this;
|
Beginnings of having optional jQuery support
|
fperucic_treant-js
|
train
|
75fe6b01bddb13fada33de88122f6fc421b87950
|
diff --git a/java/common/infrastructure-common/src/main/java/io/joynr/capabilities/DiscoveryEntryStoreInMemory.java b/java/common/infrastructure-common/src/main/java/io/joynr/capabilities/DiscoveryEntryStoreInMemory.java
index <HASH>..<HASH> 100644
--- a/java/common/infrastructure-common/src/main/java/io/joynr/capabilities/DiscoveryEntryStoreInMemory.java
+++ b/java/common/infrastructure-common/src/main/java/io/joynr/capabilities/DiscoveryEntryStoreInMemory.java
@@ -70,7 +70,7 @@ public class DiscoveryEntryStoreInMemory<T extends DiscoveryEntry> implements Di
* capabilities .DiscoveryEntry)
*/
@Override
- public synchronized void add(T discoveryEntry) {
+ public void add(T discoveryEntry) {
if (discoveryEntry.getDomain() == null || discoveryEntry.getInterfaceName() == null
|| discoveryEntry.getParticipantId() == null) {
String message = format("discoveryEntry being registered is not complete: %s", discoveryEntry);
|
[Java] Removed synchronized method attribute in DiscoveryEntryStoreInMemory
* Store is already protected in method body by synchronized(storeLock)
|
bmwcarit_joynr
|
train
|
d1d008aedfd0978d01a725330930c18121eb4fa2
|
diff --git a/hijack/contrib/admin/apps.py b/hijack/contrib/admin/apps.py
index <HASH>..<HASH> 100644
--- a/hijack/contrib/admin/apps.py
+++ b/hijack/contrib/admin/apps.py
@@ -1,8 +1,11 @@
+import logging
import warnings
from django.apps import AppConfig
from django.contrib.auth import get_user_model
+logger = logging.getLogger(__name__)
+
class HijackAdminConfig(AppConfig):
name = "hijack.contrib.admin"
@@ -25,13 +28,18 @@ class HijackAdminConfig(AppConfig):
UserWarning,
)
else:
- admin.site.unregister(UserModel)
-
- # We create a subclass including the HijackUserAdminMixin but keep the name
- # and module, to keep output form failing checks consistent.
- HijackUserModelAdmin = type(
- UserModelAdmin.__name__, (HijackUserAdminMixin, UserModelAdmin), {}
- )
- HijackUserModelAdmin.__module__ = UserModelAdmin.__module__
-
- admin.site.register(UserModel, HijackUserModelAdmin)
+ if issubclass(UserModelAdmin, HijackUserAdminMixin):
+ logger.debug(
+ "UserModelAdmin already is a subclass of HijackUserAdminMixin."
+ )
+ else:
+ admin.site.unregister(UserModel)
+
+ # We create a subclass including the HijackUserAdminMixin but keep the name
+ # and module, to keep output form failing checks consistent.
+ HijackUserModelAdmin = type(
+ UserModelAdmin.__name__, (HijackUserAdminMixin, UserModelAdmin), {}
+ )
+ HijackUserModelAdmin.__module__ = UserModelAdmin.__module__
+
+ admin.site.register(UserModel, HijackUserModelAdmin)
diff --git a/hijack/tests/test_admin.py b/hijack/tests/test_admin.py
index <HASH>..<HASH> 100644
--- a/hijack/tests/test_admin.py
+++ b/hijack/tests/test_admin.py
@@ -1,6 +1,8 @@
+import logging
from unittest.mock import MagicMock
import pytest
+from django.contrib.auth.admin import UserAdmin
from django.urls import reverse
from hijack.contrib.admin import HijackUserAdminMixin
@@ -16,17 +18,39 @@ class TestHijackUserAdminMixin:
assert b"data-hijack-user" in response.content
@pytest.fixture()
- def no_user_admin(self, settings):
+ def no_user_admin(self):
+ from django.contrib import admin
+
+ custom_user_admin = admin.site._registry.pop(CustomUser)
+ yield
+ admin.site._registry[CustomUser] = custom_user_admin
+
+ @pytest.fixture()
+ def custom_hijack_user_admin(self):
from django.contrib import admin
CustomUserAdmin = admin.site._registry.pop(CustomUser)
+ HijackAdmin = type(UserAdmin.__name__, (HijackUserAdminMixin, UserAdmin), {})
+ HijackAdmin.__module__ = UserAdmin.__module__
+ admin.site.register(CustomUser, HijackAdmin)
yield
+ admin.site.unregister(CustomUser)
admin.site._registry[CustomUser] = CustomUserAdmin
def test_user_admin__unregistered(self, no_user_admin, admin_client):
with pytest.warns(UserWarning, match="CustomUser is not registered"):
HijackAdminConfig.ready(None)
+ def test_user_admin__custom_subclass(
+ self, custom_hijack_user_admin, admin_client, caplog
+ ):
+ with caplog.at_level(logging.DEBUG):
+ HijackAdminConfig.ready(None)
+ assert (
+ "UserModelAdmin already is a subclass of HijackUserAdminMixin."
+ in caplog.text
+ )
+
def test_related_user(self, admin_client, admin_user):
url = reverse("admin:test_app_post_changelist")
Post.objects.create(author=admin_user)
|
Add support for custom user hijack admins
|
arteria_django-hijack
|
train
|
9fa7b6bb48ffb1cc37ec8921c4df327dcd099492
|
diff --git a/src/Model/MongoDB/BaseDocumentManager.php b/src/Model/MongoDB/BaseDocumentManager.php
index <HASH>..<HASH> 100644
--- a/src/Model/MongoDB/BaseDocumentManager.php
+++ b/src/Model/MongoDB/BaseDocumentManager.php
@@ -16,6 +16,8 @@ use Sonata\Doctrine\Model\BaseManager;
/**
* @author Hugo Briand <briand@ekino.com>
+ *
+ * @mixin DocumentManager
*/
abstract class BaseDocumentManager extends BaseManager
{
diff --git a/src/Model/ORM/BaseEntityManager.php b/src/Model/ORM/BaseEntityManager.php
index <HASH>..<HASH> 100644
--- a/src/Model/ORM/BaseEntityManager.php
+++ b/src/Model/ORM/BaseEntityManager.php
@@ -16,6 +16,8 @@ use Sonata\Doctrine\Model\BaseManager;
/**
* @author Sylvain Deloux <sylvain.deloux@ekino.com>
+ *
+ * @mixin EntityManager
*/
abstract class BaseEntityManager extends BaseManager
{
diff --git a/src/Model/PHPCR/BasePHPCRManager.php b/src/Model/PHPCR/BasePHPCRManager.php
index <HASH>..<HASH> 100644
--- a/src/Model/PHPCR/BasePHPCRManager.php
+++ b/src/Model/PHPCR/BasePHPCRManager.php
@@ -14,6 +14,9 @@ namespace Sonata\Doctrine\Model\PHPCR;
use Doctrine\Common\Persistence\ObjectManager;
use Sonata\Doctrine\Model\BaseManager;
+/**
+ * @mixin ObjectManager
+ */
abstract class BasePHPCRManager extends BaseManager
{
/**
|
Added @mixin to add autocompletion support
|
sonata-project_sonata-doctrine-extensions
|
train
|
cb72ae997ac1d3397caf18af96bd6919dc8b16c7
|
diff --git a/lib/slim/parser.rb b/lib/slim/parser.rb
index <HASH>..<HASH> 100644
--- a/lib/slim/parser.rb
+++ b/lib/slim/parser.rb
@@ -81,7 +81,7 @@ module Slim
#
in_comment, block_indent, text_indent,
current_tag, delimiter, delimiter_line,
- delimiter_lineno = false, nil, nil, nil, nil, nil, nil
+ delimiter_lineno, delimiter_indent = false, nil, nil, nil, nil, nil, nil, nil
str.each_line do |line|
lineno += 1
@@ -164,9 +164,10 @@ module Slim
# This line was deindented.
# Now we're have to go through the all the indents and figure out
# how many levels we've deindented.
+ last_indent = 0
while indent < indents.last
- indents.pop
- stacks.pop
+ last_indent = indents.pop
+ stacks.pop unless last_indent == delimiter_indent
end
# This line's indentation happens lie "between" two other line's
@@ -175,8 +176,20 @@ module Slim
# hello
# world
# this # <- This should not be possible!
+ #
+ # However, for readability, this is possible:
+ #
+ # li( id="myid"
+ # class="myclass"
+ # data-info="myinfo")
+ # a href="link" = edit_user
+ #
if indents.last < indent
- syntax_error!('Malformed indentation', line, lineno)
+ if last_indent == delimiter_indent
+ delimiter_indent = nil
+ else
+ syntax_error!('Malformed indentation', line, lineno)
+ end
end
end
@@ -265,6 +278,7 @@ module Slim
if delimiter = end_delimiter
# Save this information for easy error reporting
# if closing delimiter is not found
+ delimiter_indent = indent
delimiter_line = line
delimiter_lineno = lineno
end
diff --git a/test/slim/test_html_structure.rb b/test/slim/test_html_structure.rb
index <HASH>..<HASH> 100644
--- a/test/slim/test_html_structure.rb
+++ b/test/slim/test_html_structure.rb
@@ -411,4 +411,18 @@ p<id=id_helper
assert_html '<p class="martian" data-info="Illudium Q-36" id="notice"><span class="emphasis">THE</span> space modulator</p>', str
end
end
+
+ def test_multiline_attributes_with_nested_text_and_extra_indentation
+ source = %q{
+li< id="myid"
+ class="myclass"
+ data-info="myinfo">
+ a href="link" My Link
+}
+ Slim::Parser::DELIMITERS.each do |k,v|
+ str = source.sub('<',k).sub('>',v)
+ assert_html '<li class="myclass" data-info="myinfo" id="myid"><a href="link">My Link</a></li>', str
+ end
+ end
+
end
|
add some indentation forgiveness for readability
|
slim-template_slim
|
train
|
65b869f5ad02911250f775cb20afd562c88b76de
|
diff --git a/app/bind/binder.go b/app/bind/binder.go
index <HASH>..<HASH> 100644
--- a/app/bind/binder.go
+++ b/app/bind/binder.go
@@ -48,6 +48,8 @@ type App interface {
type Binder interface {
// BindApp makes the bind between the binder and an app.
BindApp(App) error
+ // BindUnit makes the bind between the binder and an unit.
+ BindUnit(Unit) (map[string]string, error)
// UnbindApp makes the unbind between the binder and an app.
UnbindApp(App) error
}
diff --git a/service/bind/bind_test.go b/service/bind/bind_test.go
index <HASH>..<HASH> 100644
--- a/service/bind/bind_test.go
+++ b/service/bind/bind_test.go
@@ -59,6 +59,33 @@ func createTestApp(name, framework string, teams []string, units []app.Unit) (ap
return a, err
}
+func (s *S) TestBindUnit(c *C) {
+ called := false
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.Write([]byte(`{"DATABASE_USER":"root","DATABASE_PASSWORD":"s3cr3t"}`))
+ }))
+ defer ts.Close()
+ srvc := service.Service{Name: "mysql", Endpoint: map[string]string{"production": ts.URL}}
+ err := srvc.Create()
+ c.Assert(err, IsNil)
+ defer db.Session.Services().Remove(bson.M{"_id": "mysql"})
+ instance := service.ServiceInstance{Name: "my-mysql", ServiceName: "mysql", Teams: []string{s.team.Name}}
+ instance.Create()
+ defer db.Session.ServiceInstances().Remove(bson.M{"_id": "my-mysql"})
+ a, err := createTestApp("painkiller", "", []string{s.team.Name}, []app.Unit{{Ip: "10.10.10.10"}})
+ c.Assert(err, IsNil)
+ defer db.Session.Apps().Remove(bson.M{"name": a.Name})
+ envs, err := instance.BindUnit(a.GetUnits()[0])
+ c.Assert(err, IsNil)
+ c.Assert(called, Equals, true)
+ expectedEnvs := map[string]string{
+ "DATABASE_USER": "root",
+ "DATABASE_PASSWORD": "s3cr3t",
+ }
+ c.Assert(envs, DeepEquals, expectedEnvs)
+}
+
func (s *S) TestBindAddsAppToTheServiceInstance(c *C) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"DATABASE_USER":"root","DATABASE_PASSWORD":"s3cr3t"}`))
diff --git a/service/service_instance.go b/service/service_instance.go
index <HASH>..<HASH> 100644
--- a/service/service_instance.go
+++ b/service/service_instance.go
@@ -82,7 +82,7 @@ func (si *ServiceInstance) BindApp(app bind.App) error {
}
var envs map[string]string
for _, unit := range app.GetUnits() {
- envs, err = cli.Bind(si, unit)
+ envs, err = si.BindUnit(unit)
if err != nil {
return err
}
@@ -104,6 +104,12 @@ func (si *ServiceInstance) BindApp(app bind.App) error {
return app.SetEnvs(envVars, false)
}
+// BindUnit makes the bind between the binder and an unit.
+func (si *ServiceInstance) BindUnit(unit bind.Unit) (map[string]string, error) {
+ cli := si.Service().ProductionEndpoint()
+ return cli.Bind(si, unit)
+}
+
// UnbindApp makes the unbind between the service instance and an app.
func (si *ServiceInstance) UnbindApp(app bind.App) error {
err := si.RemoveApp(app.GetName())
|
Added method to BindUnit.
Related to #<I>.
|
tsuru_tsuru
|
train
|
d911989b55edaea9715cd2d8eb9c68321d5054de
|
diff --git a/packages/cozy-scripts/test/cli.spec.js b/packages/cozy-scripts/test/cli.spec.js
index <HASH>..<HASH> 100644
--- a/packages/cozy-scripts/test/cli.spec.js
+++ b/packages/cozy-scripts/test/cli.spec.js
@@ -72,12 +72,12 @@ describe('cozy-scripts (cs) CLI', () => {
// clean args list
process.argv = [process.execPath, path.resolve('../bin/cozy-scripts')]
// default env
- process.env.HOT_RELOAD = undefined
- process.env.COZY_SCRIPTS_DEBUG = undefined
- process.env.COZY_SCRIPTS_ESLINT_FIX = undefined
- process.env.COZY_SCRIPTS_APP_SRC_DIR = undefined
- process.env.COZY_SCRIPTS_APP_BUILD_DIR = undefined
- process.env.COZY_SCRIPTS_APP_MANIFEST = undefined
+ delete process.env.HOT_RELOAD
+ delete process.env.COZY_SCRIPTS_DEBUG
+ delete process.env.COZY_SCRIPTS_ESLINT_FIX
+ delete process.env.COZY_SCRIPTS_APP_SRC_DIR
+ delete process.env.COZY_SCRIPTS_APP_BUILD_DIR
+ delete process.env.COZY_SCRIPTS_APP_MANIFEST
})
afterAll(() => {
|
test: :wrench: Better env reset beforeAll cli tests
|
CPatchane_create-cozy-app
|
train
|
360f988d840230845b8353488d25e555b6f193ce
|
diff --git a/examples/booktest/oracle/models/author.xo.go b/examples/booktest/oracle/models/author.xo.go
index <HASH>..<HASH> 100644
--- a/examples/booktest/oracle/models/author.xo.go
+++ b/examples/booktest/oracle/models/author.xo.go
@@ -9,8 +9,8 @@ import (
// Author represents a row from 'booktest.authors'.
type Author struct {
- AuthorID float64 `json:"author_id"` // author_id
- Name string `json:"name"` // name
+ AuthorID int64 `json:"author_id"` // author_id
+ Name string `json:"name"` // name
// xo fields
_exists, _deleted bool
@@ -56,7 +56,7 @@ func (a *Author) Insert(db XODB) error {
}
// set primary key and existence
- a.AuthorID = float64(id)
+ a.AuthorID = int64(id)
a._exists = true
return nil
@@ -167,8 +167,8 @@ func AuthorsByName(db XODB, name string) ([]*Author, error) {
// AuthorByAuthorID retrieves a row from 'booktest.authors' as a Author.
//
-// Generated from index 'sys_c0025502'.
-func AuthorByAuthorID(db XODB, authorID float64) (*Author, error) {
+// Generated from index 'sys_c0025665'.
+func AuthorByAuthorID(db XODB, authorID int64) (*Author, error) {
var err error
// sql query
diff --git a/examples/booktest/oracle/models/authorbookresult.xo.go b/examples/booktest/oracle/models/authorbookresult.xo.go
index <HASH>..<HASH> 100644
--- a/examples/booktest/oracle/models/authorbookresult.xo.go
+++ b/examples/booktest/oracle/models/authorbookresult.xo.go
@@ -5,12 +5,12 @@ package models
// AuthorBookResult is the result of a search.
type AuthorBookResult struct {
- AuthorID float64 // author_id
- AuthorName string // author_name
- BookID float64 // book_id
- BookIsbn string // book_isbn
- BookTitle string // book_title
- BookTags string // book_tags
+ AuthorID int64 // author_id
+ AuthorName string // author_name
+ BookID int64 // book_id
+ BookIsbn string // book_isbn
+ BookTitle string // book_title
+ BookTags string // book_tags
}
// AuthorBookResultsByTags runs a custom query, returning results as AuthorBookResult.
diff --git a/examples/booktest/oracle/models/book.xo.go b/examples/booktest/oracle/models/book.xo.go
index <HASH>..<HASH> 100644
--- a/examples/booktest/oracle/models/book.xo.go
+++ b/examples/booktest/oracle/models/book.xo.go
@@ -10,11 +10,11 @@ import (
// Book represents a row from 'booktest.books'.
type Book struct {
- BookID float64 `json:"book_id"` // book_id
- AuthorID float64 `json:"author_id"` // author_id
+ BookID int64 `json:"book_id"` // book_id
+ AuthorID int64 `json:"author_id"` // author_id
Isbn string `json:"isbn"` // isbn
Title string `json:"title"` // title
- Year float64 `json:"year"` // year
+ Year int64 `json:"year"` // year
Available time.Time `json:"available"` // available
Tags string `json:"tags"` // tags
@@ -62,7 +62,7 @@ func (b *Book) Insert(db XODB) error {
}
// set primary key and existence
- b.BookID = float64(id)
+ b.BookID = int64(id)
b._exists = true
return nil
@@ -134,7 +134,7 @@ func (b *Book) Delete(db XODB) error {
// Author returns the Author associated with the Book's AuthorID (author_id).
//
-// Generated from foreign key 'sys_c0025512'.
+// Generated from foreign key 'sys_c0025674'.
func (b *Book) Author(db XODB) (*Author, error) {
return AuthorByAuthorID(db, b.AuthorID)
}
@@ -142,7 +142,7 @@ func (b *Book) Author(db XODB) (*Author, error) {
// BooksByTitleYear retrieves a row from 'booktest.books' as a Book.
//
// Generated from index 'books_title_idx'.
-func BooksByTitleYear(db XODB, title string, year float64) ([]*Book, error) {
+func BooksByTitleYear(db XODB, title string, year int64) ([]*Book, error) {
var err error
// sql query
@@ -180,8 +180,8 @@ func BooksByTitleYear(db XODB, title string, year float64) ([]*Book, error) {
// BookByBookID retrieves a row from 'booktest.books' as a Book.
//
-// Generated from index 'sys_c0025510'.
-func BookByBookID(db XODB, bookID float64) (*Book, error) {
+// Generated from index 'sys_c0025672'.
+func BookByBookID(db XODB, bookID int64) (*Book, error) {
var err error
// sql query
@@ -206,7 +206,7 @@ func BookByBookID(db XODB, bookID float64) (*Book, error) {
// BookByIsbn retrieves a row from 'booktest.books' as a Book.
//
-// Generated from index 'sys_c0025511'.
+// Generated from index 'sys_c0025673'.
func BookByIsbn(db XODB, isbn string) (*Book, error) {
var err error
|
Updating booktest oracle models
|
xo_xo
|
train
|
d1dae7198d840200791af599863b6e1a9be60402
|
diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaSecurityGroup.java b/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaSecurityGroup.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaSecurityGroup.java
+++ b/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaSecurityGroup.java
@@ -90,7 +90,15 @@ public class NovaSecurityGroup extends AbstractFirewallSupport {
json.put("to_port", endPort);
json.put("parent_group_id", firewallId);
switch( sourceEndpoint.getRuleTargetType() ) {
- case CIDR: json.put("cidr", sourceEndpoint.getCidr()); break;
+ case CIDR: {
+ if (sourceEndpoint.getCidr().indexOf("/") == -1) {
+ json.put("cidr", sourceEndpoint.getCidr()+"/32");
+ }
+ else {
+ json.put("cidr", sourceEndpoint.getCidr());
+ }
+ break;
+ }
case VLAN: throw new OperationNotSupportedException("Cannot target VLANs with firewall rules");
case VM: throw new OperationNotSupportedException("Cannot target virtual machines with firewall rules");
case GLOBAL:
|
bugzid: <I>: set cidr mask to /<I> if single ip address is passed
|
dasein-cloud_dasein-cloud-openstack
|
train
|
a7d346e767ea9d4120c02bba8849a3b75800f418
|
diff --git a/nsqd/nsqd.go b/nsqd/nsqd.go
index <HASH>..<HASH> 100644
--- a/nsqd/nsqd.go
+++ b/nsqd/nsqd.go
@@ -13,7 +13,6 @@ import (
"os"
"path"
"runtime"
- "strings"
"sync"
"time"
)
@@ -106,83 +105,55 @@ func (n *NSQd) LoadMetadata() {
return
}
- // channels cannot start with '{' so we use that to introduce a way to pivot
- // and be backwards compatible. The new format is JSON so that adding fields
- // is easy going forward.
- if data[0] == '{' {
- js, err := simplejson.NewJson(data)
+ js, err := simplejson.NewJson(data)
+ if err != nil {
+ log.Printf("ERROR: failed to parse metadata - %s", err.Error())
+ return
+ }
+
+ topics, err := js.Get("topics").Array()
+ if err != nil {
+ log.Printf("ERROR: failed to parse metadata - %s", err.Error())
+ return
+ }
+
+ for ti, _ := range topics {
+ topicJs := js.Get("topics").GetIndex(ti)
+
+ topicName, err := topicJs.Get("name").String()
if err != nil {
log.Printf("ERROR: failed to parse metadata - %s", err.Error())
return
}
+ if !nsq.IsValidTopicName(topicName) {
+ log.Printf("WARNING: skipping creation of invalid topic %s", topicName)
+ continue
+ }
+ topic := n.GetTopic(topicName)
- topics, err := js.Get("topics").Array()
+ channels, err := topicJs.Get("channels").Array()
if err != nil {
log.Printf("ERROR: failed to parse metadata - %s", err.Error())
return
}
- for ti, _ := range topics {
- topicJs := js.Get("topics").GetIndex(ti)
+ for ci, _ := range channels {
+ channelJs := topicJs.Get("channels").GetIndex(ci)
- topicName, err := topicJs.Get("name").String()
+ channelName, err := channelJs.Get("name").String()
if err != nil {
log.Printf("ERROR: failed to parse metadata - %s", err.Error())
return
}
- if !nsq.IsValidTopicName(topicName) {
- log.Printf("WARNING: skipping creation of invalid topic %s", topicName)
+ if !nsq.IsValidChannelName(channelName) {
+ log.Printf("WARNING: skipping creation of invalid channel %s", channelName)
continue
}
- topic := n.GetTopic(topicName)
+ channel := topic.GetChannel(channelName)
- channels, err := topicJs.Get("channels").Array()
- if err != nil {
- log.Printf("ERROR: failed to parse metadata - %s", err.Error())
- return
- }
-
- for ci, _ := range channels {
- channelJs := topicJs.Get("channels").GetIndex(ci)
-
- channelName, err := channelJs.Get("name").String()
- if err != nil {
- log.Printf("ERROR: failed to parse metadata - %s", err.Error())
- return
- }
- if !nsq.IsValidChannelName(channelName) {
- log.Printf("WARNING: skipping creation of invalid channel %s", channelName)
- continue
- }
- channel := topic.GetChannel(channelName)
-
- paused, _ := channelJs.Get("paused").Bool()
- if paused {
- channel.Pause()
- }
- }
- }
- } else {
- // TODO: remove this in the next release
- // old line oriented, : separated, format
- for _, line := range strings.Split(string(data), "\n") {
- if line != "" {
- parts := strings.SplitN(line, ":", 2)
-
- if !nsq.IsValidTopicName(parts[0]) {
- log.Printf("WARNING: skipping creation of invalid topic %s", parts[0])
- continue
- }
- topic := n.GetTopic(parts[0])
-
- if len(parts) < 2 {
- continue
- }
- if !nsq.IsValidChannelName(parts[1]) {
- log.Printf("WARNING: skipping creation of invalid channel %s", parts[1])
- continue
- }
- topic.GetChannel(parts[1])
+ paused, _ := channelJs.Get("paused").Bool()
+ if paused {
+ channel.Pause()
}
}
}
diff --git a/nsqd/protocol_v2.go b/nsqd/protocol_v2.go
index <HASH>..<HASH> 100644
--- a/nsqd/protocol_v2.go
+++ b/nsqd/protocol_v2.go
@@ -306,12 +306,6 @@ func (p *ProtocolV2) SUB(client *ClientV2, params [][]byte) ([]byte, error) {
fmt.Sprintf("channel name '%s' is not valid", channelName))
}
- // TODO: this can be removed once all clients are updated to use IDENTIFY
- if len(params) == 5 {
- client.ShortIdentifier = string(params[3])
- client.LongIdentifier = string(params[4])
- }
-
topic := nsqd.GetTopic(topicName)
channel := topic.GetChannel(channelName)
channel.AddClient(client)
|
nsqd: remove support for identification in SUB; remove old process metadata format
|
nsqio_nsq
|
train
|
d5459b813ba1055893e69ad0bef069b03310b7f5
|
diff --git a/flask_jwt_extended/config.py b/flask_jwt_extended/config.py
index <HASH>..<HASH> 100644
--- a/flask_jwt_extended/config.py
+++ b/flask_jwt_extended/config.py
@@ -3,7 +3,18 @@ from warnings import warn
import simplekv
from flask import current_app
-from jwt.algorithms import requires_cryptography
+
+# Older versions of pyjwt do not have the requires_cryptography set. Also,
+# older versions will not be adding new algorithms to them, so I can hard code
+# the default version here and be safe. If there is a newer algorithm someone
+# wants to use, they will need newer versions of pyjwt and it will be included
+# in their requires_cryptography set, and if they attempt to use it in older
+# versions of pyjwt, it will kick it out as an unrecognized algorithm.
+try:
+ from jwt.algorithms import requires_cryptography
+except ImportError:
+ requires_cryptography = {'RS256', 'RS384', 'RS512', 'ES256', 'ES384',
+ 'ES521', 'ES512', 'PS256', 'PS384', 'PS512'}
class _Config(object):
|
Fix requires_cryptography exception on older pyjwt versions (hopefully)
This should fix import errors when trying to use requires_cryptography
on older versions of pyjwt. Refs #<I>
|
vimalloc_flask-jwt-extended
|
train
|
525ef3dee8be5841015ef02bb3aa2dba835d7569
|
diff --git a/src/components/Modal/Modal.js b/src/components/Modal/Modal.js
index <HASH>..<HASH> 100644
--- a/src/components/Modal/Modal.js
+++ b/src/components/Modal/Modal.js
@@ -98,7 +98,7 @@ export default class Modal extends Component {
}}
role="dialog"
className="bx--modal-container"
- ariaLabel={modalAriaLabel}>
+ aria-label={modalAriaLabel}>
<div className="bx--modal-header">
{passiveModal && modalButton}
{modalLabel && (
|
fix(Modal): change ariaLabel to aria-label (#<I>)
|
carbon-design-system_carbon-components
|
train
|
6ead7f986ad43de4b6555c86bb041949a72bf143
|
diff --git a/thinc/config.py b/thinc/config.py
index <HASH>..<HASH> 100644
--- a/thinc/config.py
+++ b/thinc/config.py
@@ -308,6 +308,8 @@ class registry(object):
# Update final config with parsed value if they're not equal (in
# value and in type) but not if it's a generator because we had to
# replace that to validate it correctly
+ elif key == ARGS_FIELD:
+ continue # don't substitute if list of positional args
elif (
value != final[key] or not isinstance(type(value), type(final[key]))
) and not isinstance(final[key], GeneratorType):
diff --git a/thinc/tests/test_config.py b/thinc/tests/test_config.py
index <HASH>..<HASH> 100644
--- a/thinc/tests/test_config.py
+++ b/thinc/tests/test_config.py
@@ -573,7 +573,7 @@ def test_validate_generator():
assert isinstance(result, GeneratorType)
@my_registry.optimizers("test_optimizer.v2")
- def test_optimizer(rate: Generator) -> Generator:
+ def test_optimizer2(rate: Generator) -> Generator:
return rate
cfg = {
@@ -584,7 +584,7 @@ def test_validate_generator():
assert isinstance(result, GeneratorType)
@my_registry.optimizers("test_optimizer.v3")
- def test_optimizer2(schedules: Dict[str, Generator]) -> Generator:
+ def test_optimizer3(schedules: Dict[str, Generator]) -> Generator:
return schedules["rate"]
cfg = {
@@ -594,6 +594,17 @@ def test_validate_generator():
result = my_registry.make_from_config({"test": cfg})["test"]
assert isinstance(result, GeneratorType)
+ @my_registry.optimizers("test_optimizer.v4")
+ def test_optimizer4(*schedules: Generator) -> Generator:
+ return schedules[0]
+
+ cfg = {
+ "@optimizers": "test_optimizer.v4",
+ "*": {"a": {"@schedules": "test_schedule.v2"}},
+ }
+ result = my_registry.make_from_config({"test": cfg})["test"]
+ assert isinstance(result, GeneratorType)
+
def test_handle_generic_model_type():
"""Test that validation can handle checks against arbitrary generic
|
More hacking around config with generators
|
explosion_thinc
|
train
|
603ed2621ed6340ececb10dfb0f2ec3a6d515744
|
diff --git a/src/com/aoindustries/io/CompressedDataInputStream.java b/src/com/aoindustries/io/CompressedDataInputStream.java
index <HASH>..<HASH> 100755
--- a/src/com/aoindustries/io/CompressedDataInputStream.java
+++ b/src/com/aoindustries/io/CompressedDataInputStream.java
@@ -137,4 +137,28 @@ public class CompressedDataInputStream extends DataInputStream {
public String readNullUTF() throws IOException {
return readBoolean() ? readUTF() : null;
}
+
+ /**
+ * Reads a string of any length.
+ */
+ public String readLongUTF() throws IOException {
+ int length = readCompressedInt();
+ StringBuilder SB = new StringBuilder(length);
+ for(int position = 0; position<length; position+=20480) {
+ int expectedLen = length - position;
+ if(expectedLen>20480) expectedLen = 20480;
+ String block = readUTF();
+ if(block.length()!=expectedLen) throw new IOException("Block has unexpected length: expected "+expectedLen+", got "+block.length());
+ SB.append(block);
+ }
+ if(SB.length()!=length) throw new IOException("StringBuilder has unexpected length: expected "+length+", got "+SB.length());
+ return SB.toString();
+ }
+
+ /**
+ * Reads a string of any length, supporting <code>null</code>.
+ */
+ public String readNullLongUTF() throws IOException {
+ return readBoolean() ? readLongUTF() : null;
+ }
}
diff --git a/src/com/aoindustries/io/CompressedDataOutputStream.java b/src/com/aoindustries/io/CompressedDataOutputStream.java
index <HASH>..<HASH> 100755
--- a/src/com/aoindustries/io/CompressedDataOutputStream.java
+++ b/src/com/aoindustries/io/CompressedDataOutputStream.java
@@ -127,4 +127,26 @@ public class CompressedDataOutputStream extends DataOutputStream {
writeBoolean(str!=null);
if(str!=null) writeUTF(str);
}
+
+ /**
+ * Writes a string of any length.
+ */
+ public void writeLongUTF(String str) throws IOException {
+ int length = str.length();
+ writeCompressedInt(length);
+ for(int position = 0; position<length; position+=20480) {
+ int blockLength = length - position;
+ if(blockLength>20480) blockLength = 20480;
+ String block = str.substring(position, position+blockLength);
+ writeUTF(block);
+ }
+ }
+
+ /**
+ * Writes a string of any length, supporting <code>null</code>.
+ */
+ public void writeNullLongUTF(String str) throws IOException {
+ writeBoolean(str!=null);
+ if(str!=null) writeLongUTF(str);
+ }
}
|
Added support for writing strings longer than <I>k.
|
aoindustries_aocode-public
|
train
|
918df628e32e5ec1909336ff588ef3a299bca572
|
diff --git a/yabt/graph.py b/yabt/graph.py
index <HASH>..<HASH> 100644
--- a/yabt/graph.py
+++ b/yabt/graph.py
@@ -334,7 +334,7 @@ def write_dot(build_context, conf: Config, out_f):
"""Write build graph in dot format to `out_f` file-like object."""
buildenvs = set(target.buildenv for target in
build_context.targets.values() if target.buildenv is not None)
- buildenv_targets = set()
+ buildenv_targets = set(buildenvs)
for buildenv in buildenvs:
buildenv_targets = buildenv_targets.union(
descendants(build_context.target_graph, buildenv))
|
include buildenvs in buildenv targets
|
resonai_ybt
|
train
|
67255f64bc219b40f658b508a3589f1709db091e
|
diff --git a/src/main/java/org/sikuli/slides/sikuli/SlideAction.java b/src/main/java/org/sikuli/slides/sikuli/SlideAction.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/sikuli/slides/sikuli/SlideAction.java
+++ b/src/main/java/org/sikuli/slides/sikuli/SlideAction.java
@@ -211,6 +211,8 @@ public class SlideAction {
This is important in case of opening the default browser or label target region could not be found.
*/
if(targetRegion==null){
+ logger.error("Failed to find the target to display a label on.");
+ logger.info("Displaying the label on the center of the screen.");
Dimension dimension = MyScreen.getScreenDimensions();
int width = UnitConverter.emuToPixels(slideLabel.getCx());
int height = UnitConverter.emuToPixels(slideLabel.getCy());
|
display logging info when the label target is not found
|
sikuli_sikuli-slides
|
train
|
a5da48d231bf1e4041e149a8d052d8450e41a4e9
|
diff --git a/railties/lib/generators/rails/app/templates/config/boot.rb b/railties/lib/generators/rails/app/templates/config/boot.rb
index <HASH>..<HASH> 100644
--- a/railties/lib/generators/rails/app/templates/config/boot.rb
+++ b/railties/lib/generators/rails/app/templates/config/boot.rb
@@ -5,13 +5,4 @@ rescue LoadError
require 'rubygems'
require 'bundler'
Bundler.setup
-
- # To use 2.x style vendor/rails and RubyGems
- #
- # vendor_rails = File.expand_path('../../vendor/rails', __FILE__)
- # if File.exist?(vendor_rails)
- # Dir["#{vendor_rails}/*/lib"].each { |path| $:.unshift(path) }
- # end
- #
- # require 'rubygems'
end
|
vendor/rails doesn't work anymore, remove it from the blank slate suggestion
|
rails_rails
|
train
|
53edfee461e1eb8dbc8fe5d7343322c8eeeaca22
|
diff --git a/taco-team-build.js b/taco-team-build.js
index <HASH>..<HASH> 100644
--- a/taco-team-build.js
+++ b/taco-team-build.js
@@ -136,7 +136,7 @@ function prepareProject(cordovaPlatforms, args, /* optional */ projectPath) {
promise = promise.then(function () {
// Build app with platform specific args if specified
var callArgs = utilities.getCallArgs(platform, args);
- var argsString = _getArgsString(callArgs);
+ var argsString = _getArgsString(callArgs.options);
console.log('Queueing prepare for platform ' + platform + ' w/options: ' +argsString);
return cordova.raw.prepare(callArgs);
});
@@ -192,7 +192,7 @@ function buildProject(cordovaPlatforms, args, /* optional */ projectPath) {
promise = promise.then(function () {
// Build app with platform specific args if specified
var callArgs = utilities.getCallArgs(platform, args, cordovaVersion);
- var argsString = _getArgsString(callArgs);
+ var argsString = _getArgsString(callArgs.options);
console.log('Queueing build for platform ' + platform + ' w/options: ' + argsString);
return cordova.raw.build(callArgs);
});
|
fix one more issue with displaying args passed to build
|
Microsoft_taco-team-build
|
train
|
be2f5afa6843b24698e3926feaf35b33615df65f
|
diff --git a/lib/container/container.go b/lib/container/container.go
index <HASH>..<HASH> 100644
--- a/lib/container/container.go
+++ b/lib/container/container.go
@@ -8,7 +8,7 @@ import (
"github.com/samalba/dockerclient"
)
-func RawStartContainer(containerConfig *dockerclient.ContainerConfig, hostConfig *dockerclient.HostConfig) (string, error) {
+func RawStartContainer(name string, containerConfig *dockerclient.ContainerConfig, hostConfig *dockerclient.HostConfig) (string, error) {
docker, err := dockerclient.NewDockerClient("unix:///var/run/docker.sock", nil)
containerId, err := docker.CreateContainer(containerConfig, "")
if err != nil {
@@ -26,7 +26,7 @@ func RawStartContainer(containerConfig *dockerclient.ContainerConfig, hostConfig
func StartContainer(image string, command []string) (string, error) {
containerConfig := &dockerclient.ContainerConfig{Image: image, Cmd: command}
- return RawStartContainer(containerConfig, &dockerclient.HostConfig{})
+ return RawStartContainer("", containerConfig, &dockerclient.HostConfig{})
}
// spinupContainer pulls image and starts a container from it with command. It
diff --git a/lib/pipeline/pipeline.go b/lib/pipeline/pipeline.go
index <HASH>..<HASH> 100644
--- a/lib/pipeline/pipeline.go
+++ b/lib/pipeline/pipeline.go
@@ -17,6 +17,7 @@ import (
)
type Pipeline struct {
+ name string
containerConfig dockerclient.ContainerConfig
hostConfig dockerclient.HostConfig
dataRepo, outRepo string
@@ -24,8 +25,9 @@ type Pipeline struct {
counter int
}
-func NewPipeline(dataRepo, outRepo, commit, branch string) *Pipeline {
+func NewPipeline(name, dataRepo, outRepo, commit, branch string) *Pipeline {
return &Pipeline{
+ name: name,
dataRepo: dataRepo,
outRepo: outRepo,
commit: commit,
@@ -61,7 +63,8 @@ func (p *Pipeline) Run(cmd []string) error {
// Make sure this bind is only visible for the duration of run
defer func() { p.hostConfig.Binds = p.hostConfig.Binds[:len(p.hostConfig.Binds)-1] }()
- containerId, err := container.RawStartContainer(&p.containerConfig, &p.hostConfig)
+ containerId, err := container.RawStartContainer(fmt.Sprintf("%d-%s", p.counter, p.name),
+ &p.containerConfig, &p.hostConfig)
if err != nil {
log.Print(err)
return err
diff --git a/lib/pipeline/pipeline_test.go b/lib/pipeline/pipeline_test.go
index <HASH>..<HASH> 100644
--- a/lib/pipeline/pipeline_test.go
+++ b/lib/pipeline/pipeline_test.go
@@ -20,7 +20,7 @@ func check(err error, t *testing.T) {
func TestOutput(t *testing.T) {
outRepo := "TestOuput"
check(btrfs.Init(outRepo), t)
- pipeline := NewPipeline("", outRepo, "", "master")
+ pipeline := NewPipeline("testOuput", "", outRepo, "", "master")
pachfile := `
image ubuntu
@@ -59,7 +59,7 @@ func TestInputOutput(t *testing.T) {
outRepo := "TestInputOutput_out"
check(btrfs.Init(outRepo), t)
- pipeline := NewPipeline(inRepo, outRepo, "commit", "master")
+ pipeline := NewPipeline("TestInputOutput", inRepo, outRepo, "commit", "master")
pachfile := `
image ubuntu
@@ -81,7 +81,7 @@ run cp /in/data/foo /out/foo
func TestLog(t *testing.T) {
outRepo := "TestLog"
check(btrfs.Init(outRepo), t)
- pipeline := NewPipeline("", outRepo, "", "master")
+ pipeline := NewPipeline("TestLog", "", outRepo, "", "master")
pachfile := `
image ubuntu
|
Adds a naming to pipelines.
|
pachyderm_pachyderm
|
train
|
d8773ef2154c960747c7af1727b9bdc105361754
|
diff --git a/src/Basset/Output/Server.php b/src/Basset/Output/Server.php
index <HASH>..<HASH> 100644
--- a/src/Basset/Output/Server.php
+++ b/src/Basset/Output/Server.php
@@ -53,7 +53,7 @@ class Server {
* @param array $collections
* @return void
*/
- public function __construct(Resolver $resolver, Repository $config, Store $session, UrlGenerator $url, array $collections)
+ public function __construct(Resolver $resolver, Repository $config, Store $session, UrlGenerator $url, array $collections = array())
{
$this->resolver = $resolver;
$this->config = $config;
@@ -63,6 +63,19 @@ class Server {
}
/**
+ * Set the collections on the server.
+ *
+ * @param array $collections
+ * @return Basset\Output\Server
+ */
+ public function setCollections(array $collections)
+ {
+ $this->collections = array_merge($this->collections, $collections);
+
+ return $this;
+ }
+
+ /**
* Serve the stylesheets for a given collection.
*
* @param string $collection
@@ -230,4 +243,44 @@ class Server {
return '<script src="'.$this->url->asset($path).'"></script>';
}
+ /**
+ * Get the output resolver instance.
+ *
+ * @return Basset\Output\Resolver
+ */
+ public function getResolver()
+ {
+ return $this->resolver;
+ }
+
+ /**
+ * Get the illuminate config repository instance.
+ *
+ * @return Illuminate\Config\Repository
+ */
+ public function getConfig()
+ {
+ return $this->config;
+ }
+
+ /**
+ * Get the illuminate session store instance.
+ *
+ * @return Illuminate\Session\Store
+ */
+ public function getSession()
+ {
+ return $this->session;
+ }
+
+ /**
+ * Get the illuminate url generator instance.
+ *
+ * @return Illuminate\Routing\UrlGenerator
+ */
+ public function getUrl()
+ {
+ return $this->url;
+ }
+
}
\ No newline at end of file
|
Allow setting of collections and getting of injected dependencies.
|
Marwelln_basset
|
train
|
f4066fb3177f37c6f82a5ab48f03047aa50498b3
|
diff --git a/bgzf/cache/cache.go b/bgzf/cache/cache.go
index <HASH>..<HASH> 100644
--- a/bgzf/cache/cache.go
+++ b/bgzf/cache/cache.go
@@ -10,14 +10,37 @@ import (
)
var (
- _ bgzf.Cache = (*LRU)(nil)
- _ bgzf.Cache = (*FIFO)(nil)
- _ bgzf.Cache = (*Random)(nil)
+ _ Cache = (*LRU)(nil)
+ _ Cache = (*FIFO)(nil)
+ _ Cache = (*Random)(nil)
)
+// Cache is an extension of bgzf.Cache that allows inspection
+// and manipulation of the cache.
+type Cache interface {
+ bgzf.Cache
+
+ // Len returns the number of elements held by
+ // the cache.
+ Len() int
+
+ // Cap returns the maximum number of elements
+ // that can be held by the cache.
+ Cap() int
+
+ // Resize changes the capacity of the cache to n,
+ // dropping excess blocks if n is less than the
+ // number of cached blocks.
+ Resize(int)
+
+ // Drop evicts n elements from the cache according
+ // to the cache eviction policy.
+ Drop(int)
+}
+
// NewLRU returns an LRU cache with the n slots. If n is less than 1
// a nil cache is returned.
-func NewLRU(n int) bgzf.Cache {
+func NewLRU(n int) Cache {
if n < 1 {
return nil
}
@@ -30,7 +53,7 @@ func NewLRU(n int) bgzf.Cache {
return &c
}
-// LRU satisfies the bgzf.Cache interface with least recently used eviction
+// LRU satisfies the Cache interface with least recently used eviction
// behavior.
type LRU struct {
root node
@@ -108,7 +131,7 @@ func (c *LRU) remove(n *node) {
// NewLRU returns a FIFO cache with the n slots. If n is less than 1
// a nil cache is returned.
-func NewFIFO(n int) bgzf.Cache {
+func NewFIFO(n int) Cache {
if n < 1 {
return nil
}
@@ -121,7 +144,7 @@ func NewFIFO(n int) bgzf.Cache {
return &c
}
-// FIFO satisfies the bgzf.Cache interface with first in first out eviction
+// FIFO satisfies the Cache interface with first in first out eviction
// behavior.
type FIFO struct {
root node
@@ -192,7 +215,7 @@ func (c *FIFO) remove(n *node) {
// NewLRU returns a random eviction cache with the n slots. If n is less than 1
// a nil cache is returned.
-func NewRandom(n int) bgzf.Cache {
+func NewRandom(n int) Cache {
if n < 1 {
return nil
}
@@ -202,7 +225,7 @@ func NewRandom(n int) bgzf.Cache {
}
}
-// Random satisfies the bgzf.Cache interface with random eviction behavior.
+// Random satisfies the Cache interface with random eviction behavior.
type Random struct {
table map[int64]bgzf.Block
cap int
|
Extend the returned interface definition
This change obviates clients needing to type assert if they wish to
interact with the cache manipulation methods available.
|
biogo_hts
|
train
|
bec1d4d910ea7fbd30dc90d7dd8e3776700eae6d
|
diff --git a/lib/client-api/src/config_api.js b/lib/client-api/src/config_api.js
index <HASH>..<HASH> 100644
--- a/lib/client-api/src/config_api.js
+++ b/lib/client-api/src/config_api.js
@@ -75,6 +75,10 @@ export default class ConfigApi {
if (this._channel) {
// in Browser
render();
+ // Send a signal to the manager that configure() is done. We do this in a timeout
+ // because the story_store sends stories in a debounced function, which results in
+ // as setTimeout. We want to ensure this happens after, to avoid a FOUC.
+ setTimeout(() => this._channel.emit(Events.STORIES_CONFIGURED), 0);
} else {
// in NodeJS
loaders();
diff --git a/lib/core-events/src/index.ts b/lib/core-events/src/index.ts
index <HASH>..<HASH> 100644
--- a/lib/core-events/src/index.ts
+++ b/lib/core-events/src/index.ts
@@ -4,6 +4,7 @@ enum events {
SET_CURRENT_STORY = 'setCurrentStory',
GET_STORIES = 'getStories',
SET_STORIES = 'setStories',
+ STORIES_CONFIGURED = 'storiesConfigured',
SELECT_STORY = 'selectStory',
PREVIEW_KEYDOWN = 'previewKeydown',
STORY_ADDED = 'storyAdded',
@@ -29,6 +30,7 @@ export const GET_CURRENT_STORY = events.GET_CURRENT_STORY;
export const SET_CURRENT_STORY = events.SET_CURRENT_STORY;
export const GET_STORIES = events.GET_STORIES;
export const SET_STORIES = events.SET_STORIES;
+export const STORIES_CONFIGURED = events.STORIES_CONFIGURED;
export const SELECT_STORY = events.SELECT_STORY;
export const PREVIEW_KEYDOWN = events.PREVIEW_KEYDOWN;
export const FORCE_RE_RENDER = events.FORCE_RE_RENDER;
diff --git a/lib/ui/src/containers/nav.js b/lib/ui/src/containers/nav.js
index <HASH>..<HASH> 100755
--- a/lib/ui/src/containers/nav.js
+++ b/lib/ui/src/containers/nav.js
@@ -97,10 +97,12 @@ export const mapper = (state, api) => {
storyId,
layout: { isFullscreen, showPanel, showNav, panelPosition },
storiesHash,
+ storiesConfigured,
} = state;
const shortcutKeys = api.getShortcutKeys();
return {
+ loading: !storiesConfigured,
title: name,
url,
notifications,
diff --git a/lib/ui/src/core/context.js b/lib/ui/src/core/context.js
index <HASH>..<HASH> 100644
--- a/lib/ui/src/core/context.js
+++ b/lib/ui/src/core/context.js
@@ -1,7 +1,7 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
-import Events from '@storybook/core-events';
+import Events, { STORIES_CONFIGURED } from '@storybook/core-events';
import initProviderApi from './init-provider-api';
@@ -94,6 +94,9 @@ export class Provider extends Component {
api.setOptions(options);
});
+ api.on(STORIES_CONFIGURED, () => {
+ store.setState({ storiesConfigured: true });
+ });
api.on(SELECT_STORY, ({ kind, story, ...rest }) => {
api.selectStory(kind, story, rest);
});
diff --git a/lib/ui/src/core/initial-state.js b/lib/ui/src/core/initial-state.js
index <HASH>..<HASH> 100644
--- a/lib/ui/src/core/initial-state.js
+++ b/lib/ui/src/core/initial-state.js
@@ -19,6 +19,7 @@ const initial = {
panelPosition: 'bottom',
},
customQueryParams: {},
+ storiesConfigured: false,
};
// Returns the initialState of the app
|
Added `STORIES_CONFIGURED` and use to drive loading state.
For #<I>
|
storybooks_storybook
|
train
|
10337fe152d6b762349f6a241c4c5ba1eb14fb6f
|
diff --git a/gnosis/safe/safe_tx.py b/gnosis/safe/safe_tx.py
index <HASH>..<HASH> 100644
--- a/gnosis/safe/safe_tx.py
+++ b/gnosis/safe/safe_tx.py
@@ -20,6 +20,7 @@ from .exceptions import (CouldNotPayGasWithEther, CouldNotPayGasWithToken,
NotEnoughSafeTransactionGas,
OnlyOwnersCanApproveAHash, OwnerManagerException,
SignatureNotProvidedByOwner, SignaturesDataTooShort)
+from .safe_signature import SafeSignature
from .signatures import (get_signing_address, signature_split,
signature_to_bytes)
@@ -111,11 +112,8 @@ class SafeTx:
@property
def signers(self) -> List[str]:
- owners = []
- for i in range(len(self.signatures) // 65):
- v, r, s = signature_split(self.signatures, i)
- owners.append(get_signing_address(self.safe_tx_hash, v, r, s))
- return owners
+ return list([safe_signature.owner for safe_signature
+ in SafeSignature.parse_signature(self.signatures, self.safe_tx_hash)])
@property
def sorted_signers(self):
|
Allow more types of signatures for SafeTx
|
gnosis_gnosis-py
|
train
|
87a87988bd57bc3d6b2e85262a5dc03a52cbfdc4
|
diff --git a/blinkpy/sync_module.py b/blinkpy/sync_module.py
index <HASH>..<HASH> 100644
--- a/blinkpy/sync_module.py
+++ b/blinkpy/sync_module.py
@@ -39,7 +39,7 @@ class BlinkSyncModule:
self.available = False
self.type_key_map = {
"mini": "owls",
- "lotus": "doorbells",
+ "doorbell": "doorbells",
}
@property
|
Update sync_module.py
Apologies. I missed this when submitting the last PR but had it locally for some reason. Without the change the device seems to work but gets identified as a mini and then incorrect end points are used.
|
fronzbot_blinkpy
|
train
|
70925daa9ae4ef29db09aa1c732b362d9013d18e
|
diff --git a/classes/Models/Traits/Exportable.php b/classes/Models/Traits/Exportable.php
index <HASH>..<HASH> 100644
--- a/classes/Models/Traits/Exportable.php
+++ b/classes/Models/Traits/Exportable.php
@@ -36,17 +36,31 @@ trait Exportable
*/
public function forExport()
{
- // Make a clone because converting to array directly was failing
- $clone = tap(new static, function ($instance) {
+ return $this->mapExportAttributes($this->cloneForExport());
+ }
+
+ /**
+ * Clone this model for export because converting self to an array directly
+ * was causing errors. This code is based on the Laravel replicate()
+ *
+ * @return $this
+ */
+ protected function cloneForExport()
+ {
+ return tap(new static, function ($instance) {
$instance->setRawAttributes($this->getAttributes());
$instance->setRelations($this->relations);
});
+ }
- // Convert clone to array
- $attributes = $clone->toArray();
-
- // Massage the values
- return collect($attributes)->map(function($value, $key) {
+ /**
+ * Massage attribute values. The CSV needs a flat array.
+ *
+ * @return array
+ */
+ protected function mapExportAttributes($attributes)
+ {
+ return collect($attributes->toArray())->map(function($value, $key) {
return $this->mapExportAttribute($value, $key);
})->toArray();
}
|
Breaking up CSV logic into smaller functions
For easier subclassing
#<I>
|
BKWLD_decoy
|
train
|
0a45b9373b936a54bfc265e445614bf53e231c9f
|
diff --git a/src/containers/ConnectorManagement.jsx b/src/containers/ConnectorManagement.jsx
index <HASH>..<HASH> 100644
--- a/src/containers/ConnectorManagement.jsx
+++ b/src/containers/ConnectorManagement.jsx
@@ -183,7 +183,7 @@ export default class ConnectorManagement extends Component {
const currentIdx = accounts.findIndex(a => a._id === accountID)
const folderPath = t('konnector default base folder', konnector)
return this.runConnection(
- {oauth: accounts[currentIdx].oauth},
+ accounts[currentIdx],
folderPath
).then(() => {
this.setState({
diff --git a/src/lib/CollectStore.js b/src/lib/CollectStore.js
index <HASH>..<HASH> 100644
--- a/src/lib/CollectStore.js
+++ b/src/lib/CollectStore.js
@@ -79,13 +79,23 @@ export default class CollectStore {
connectAccount (konnector, account, folderPath) {
// return object to store all business object implied in the connection
const connection = {}
+ // detect oauth case
+ const isOAuth = !!account.oauth
// 1. Create folder, will be replaced by an intent or something else
return cozy.client.files.createDirectoryByPath(folderPath)
// 2. Create account
.then(folder => {
connection.folder = folder
- return accounts.create(cozy.client, konnector, account.auth, folder)
+ if (isOAuth) {
+ const newAttributes = {
+ folderId: folder._id,
+ status: 'PENDING'
+ }
+ return accounts.update(cozy.client, account, Object.assign({}, account, newAttributes))
+ } else {
+ return accounts.create(cozy.client, konnector, account.auth, folder)
+ }
})
// 3. Konnector installation
.then(account => {
diff --git a/src/lib/accounts.js b/src/lib/accounts.js
index <HASH>..<HASH> 100644
--- a/src/lib/accounts.js
+++ b/src/lib/accounts.js
@@ -12,6 +12,10 @@ export function create (cozy, konnector, auth, folder, name = '') {
})
}
+export function update (cozy, account, newAccount) {
+ return cozy.data.update(ACCOUNTS_DOCTYPE, account, newAccount)
+}
+
export function _delete (cozy, account) {
return cozy.data.delete(ACCOUNTS_DOCTYPE, account)
}
|
fix: handle oauth account already created when first connexion :art:
|
cozy_cozy-home
|
train
|
4292f45536799699946d113c446db34482cccf10
|
diff --git a/fault/system_verilog_target.py b/fault/system_verilog_target.py
index <HASH>..<HASH> 100644
--- a/fault/system_verilog_target.py
+++ b/fault/system_verilog_target.py
@@ -15,6 +15,7 @@ from fault.wrapper import PortWrapper
from fault.subprocess_run import subprocess_run
import fault
import fault.expression as expression
+from fault.value import Value
from fault.ms_types import RealType
import os
import pysv
@@ -395,6 +396,10 @@ class SystemVerilogTarget(VerilogTarget):
return str(value)
elif isinstance(value, expression.CallExpression):
return value.str(True, self.compile_expression)
+ elif isinstance(value, Value):
+ if value == Value.Unknown:
+ return "'x";
+ raise NotImplementedError(value)
return value
def make_poke(self, i, action):
diff --git a/tests/test_system_verilog_target.py b/tests/test_system_verilog_target.py
index <HASH>..<HASH> 100644
--- a/tests/test_system_verilog_target.py
+++ b/tests/test_system_verilog_target.py
@@ -4,7 +4,11 @@ import tempfile
import magma as m
import fault
import pytest
-from .common import TestBasicClkCircuit
+from .common import TestBasicClkCircuit, pytest_sim_params
+
+
+def pytest_generate_tests(metafunc):
+ pytest_sim_params(metafunc, 'verilator', 'system-verilog')
@pytest.mark.parametrize("simulator,waveform_type", [("ncsim", "vcd"),
@@ -76,3 +80,24 @@ def test_wait_until_sv():
with open("build/Foo_tb.sv") as f:
# Should not be missing semicolon after wait
assert "#5;" in f.read()
+
+
+def test_unknown_value(target, simulator):
+ if target == "verilator":
+ pytest.skip("verilator does not support x")
+
+ class X(m.Circuit):
+ """
+ Stub circuit to generate x
+ """
+ io = m.IO(O=m.Out(m.Bits[4]))
+ verilog = "assign O = 'x;"
+
+ tester = fault.Tester(X)
+ tester.eval()
+ tester.circuit.O.expect(fault.UnknownValue)
+ tester.compile_and_run(target, simulator=simulator)
+ with pytest.raises(AssertionError):
+ # Expect is strict, so this should fail
+ tester.circuit.O.expect(0)
+ tester.compile_and_run(target, simulator=simulator)
|
Add support for compiling UnknownValue
This allows checking that a value is X, which could be useful for
verifying initialization behavior.
|
leonardt_fault
|
train
|
9cec67e6a33b337b18c23b2d3a26e5e28e54ef4f
|
diff --git a/app/models/manager_refresh/inventory_collection/builder.rb b/app/models/manager_refresh/inventory_collection/builder.rb
index <HASH>..<HASH> 100644
--- a/app/models/manager_refresh/inventory_collection/builder.rb
+++ b/app/models/manager_refresh/inventory_collection/builder.rb
@@ -158,11 +158,15 @@ module ManagerRefresh
def to_hash
add_inventory_attributes(auto_inventory_attributes) if @options[:auto_inventory_attributes]
- @properties.merge(
- :inventory_object_attributes => @inventory_object_attributes,
- :builder_params => @default_values,
- :dependency_attributes => @dependency_attributes
- )
+ @properties[:inventory_object_attributes] ||= @inventory_object_attributes
+
+ @properties[:builder_params] ||= {}
+ @properties[:builder_params].merge!(@default_values)
+
+ @properties[:dependency_attributes] ||= {}
+ @properties[:dependency_attributes].merge!(@dependency_attributes)
+
+ @properties
end
protected
diff --git a/app/models/manager_refresh/inventory_collection/builder/infra_manager.rb b/app/models/manager_refresh/inventory_collection/builder/infra_manager.rb
index <HASH>..<HASH> 100644
--- a/app/models/manager_refresh/inventory_collection/builder/infra_manager.rb
+++ b/app/models/manager_refresh/inventory_collection/builder/infra_manager.rb
@@ -211,6 +211,30 @@ module ManagerRefresh
:custom_save_block => snapshot_parent_save_block
)
end
+
+ def customization_specs
+ add_properties(:manager_ref => %i(name))
+
+ add_common_default_values
+ end
+
+ def miq_scsi_luns
+ add_properties(
+ :manager_ref => %i(miq_scsi_target uid_ems),
+ :parent_inventory_collections => %i(hosts)
+ )
+ end
+
+ def miq_scsi_targets
+ add_properties(
+ :manager_ref => %i(guest_device uid_ems),
+ :parent_inventory_collections => %i(hosts)
+ )
+ end
+
+ def storage_profiles
+ add_common_default_values
+ end
end
end
end
|
InventoryCollection definitions for vmware infra
Also fix for merging IC properties
(transferred from ManageIQ/manageiq@<I>c<I>c7e<I>b<I>bb<I>bbffeb9e8fda)
|
ManageIQ_inventory_refresh
|
train
|
8e9c23eb3a48dd3c6fc6de6a8fa962306eb83613
|
diff --git a/go/keybase/main.go b/go/keybase/main.go
index <HASH>..<HASH> 100644
--- a/go/keybase/main.go
+++ b/go/keybase/main.go
@@ -68,7 +68,7 @@ func mainInner(g *libkb.GlobalContext) error {
client.InitUI()
}
- if err = g.ConfigureAll(cl, cmd); err != nil {
+ if err = g.ConfigureCommand(cl, cmd); err != nil {
return err
}
g.StartupMessage()
diff --git a/go/libkb/env.go b/go/libkb/env.go
index <HASH>..<HASH> 100644
--- a/go/libkb/env.go
+++ b/go/libkb/env.go
@@ -681,3 +681,28 @@ func (e *Env) GetStoredSecretServiceName() string {
}
return serviceName
}
+
+type AppConfig struct {
+ NullConfiguration
+ HomeDir string
+ RunMode RunMode
+ Debug bool
+ LocalRPCDebug string
+ ServerURI string
+}
+
+func (c AppConfig) GetDebug() (bool, bool) {
+ return c.Debug, c.Debug
+}
+
+func (c AppConfig) GetLocalRPCDebug() string {
+ return c.LocalRPCDebug
+}
+
+func (c AppConfig) GetRunMode() (RunMode, error) {
+ return c.RunMode, nil
+}
+
+func (c AppConfig) GetHome() string {
+ return c.HomeDir
+}
diff --git a/go/libkb/globals.go b/go/libkb/globals.go
index <HASH>..<HASH> 100644
--- a/go/libkb/globals.go
+++ b/go/libkb/globals.go
@@ -248,13 +248,17 @@ func (u Usage) UseKeyring() bool {
return u.KbKeyring || u.GpgKeyring
}
-func (g *GlobalContext) ConfigureAll(line CommandLine, cmd Command) error {
+func (g *GlobalContext) ConfigureCommand(line CommandLine, cmd Command) error {
+ usage := cmd.GetUsage()
+ return g.Configure(line, usage)
+}
+func (g *GlobalContext) Configure(line CommandLine, usage Usage) error {
g.SetCommandLine(line)
-
- g.ConfigureLogging()
-
- usage := cmd.GetUsage()
+ err := g.ConfigureLogging()
+ if err != nil {
+ return err
+ }
return g.ConfigureUsage(usage)
}
diff --git a/go/loopback/main.go b/go/loopback/main.go
index <HASH>..<HASH> 100644
--- a/go/loopback/main.go
+++ b/go/loopback/main.go
@@ -13,60 +13,22 @@ import (
var con net.Conn
var startOnce sync.Once
-type debuggingConfig struct {
- libkb.NullConfiguration
- homeDir string
- runMode string
- serverURI string
-}
-
-func (n debuggingConfig) GetDebug() (bool, bool) {
- // if you want helpful debug info in xcode
- return true, true
- // return false, false
-}
-
-func (n debuggingConfig) GetLocalRPCDebug() string {
- // if you want helpful debug info in xcode
- return "Acsvip"
- // return ""
-}
-
-func (n debuggingConfig) GetRunMode() (libkb.RunMode, error) {
- if n.runMode == "" {
- return libkb.DevelRunMode, nil
- }
-
- return libkb.StringToRunMode(n.runMode)
-}
-
-func (n debuggingConfig) GetHome() string {
- return n.homeDir
-}
-
-func (n debuggingConfig) GetServerURI() string {
- return n.serverURI
-}
-
-func start(cmdline libkb.CommandLine) {
+// ServerURI should match run mode environment.
+func Init(homeDir string, runMode string, serverURI string) {
startOnce.Do(func() {
libkb.G.Init()
- libkb.G.SetCommandLine(cmdline)
- libkb.G.ConfigureLogging()
- libkb.G.ConfigureUsage(libkb.Usage{
+ usage := libkb.Usage{
Config: true,
API: true,
KbKeyring: true,
- })
+ }
+ config := libkb.AppConfig{HomeDir: homeDir, RunMode: libkb.DevelRunMode, Debug: true, LocalRPCDebug: "Acsvip", ServerURI: serverURI}
+ libkb.G.Configure(config, usage)
(service.NewService(false)).StartLoopbackServer(libkb.G)
Reset()
})
}
-func Init(homeDir string, runMode string, serverURI string) {
- start(debuggingConfig{libkb.NullConfiguration{}, homeDir, runMode, serverURI})
-}
-
// Takes base64 encoded msgpack rpc payload
func WriteB64(str string) bool {
data, err := base64.StdEncoding.DecodeString(str)
|
Tweaking config for apps
|
keybase_client
|
train
|
775ec0bd9895e2e60961b34185a7afb212782e90
|
diff --git a/stdlib/buffer.rb b/stdlib/buffer.rb
index <HASH>..<HASH> 100644
--- a/stdlib/buffer.rb
+++ b/stdlib/buffer.rb
@@ -1,3 +1,4 @@
+require 'native'
require 'buffer/array'
require 'buffer/view'
|
Require native inside buffer (which uses it)
|
opal_opal
|
train
|
8ea72d04a06649d6c352ca659ded1544a036a991
|
diff --git a/mousedb/data/admin.py b/mousedb/data/admin.py
index <HASH>..<HASH> 100644
--- a/mousedb/data/admin.py
+++ b/mousedb/data/admin.py
@@ -54,7 +54,7 @@ class StudyAdmin(admin.ModelAdmin):
admin.site.register(Study, StudyAdmin)
class TreatmentAdmin(admin.ModelAdmin):
- pass
+ raw_id_fields = ('animals',)
admin.site.register(Treatment, TreatmentAdmin)
class VendorAdmin(admin.ModelAdmin):
|
Made animal field in TreatmentAdmin a raw id field. Part of issue #<I>.
|
davebridges_mousedb
|
train
|
9db27e6ec9fe1eedb13b4a3d8c635500e9f9feb2
|
diff --git a/src/Generator/ModelGenerator.php b/src/Generator/ModelGenerator.php
index <HASH>..<HASH> 100644
--- a/src/Generator/ModelGenerator.php
+++ b/src/Generator/ModelGenerator.php
@@ -21,14 +21,9 @@ class ModelGenerator implements GeneratorInterface
const FILE_TYPE_MODEL = 'model';
- /**
- * @var \Joli\Jane\Generator\Naming
- */
- protected $naming;
-
public function __construct(Naming $naming)
{
- $this->naming = $naming;
+ $this->naming = $naming;
}
/**
@@ -42,7 +37,7 @@ class ModelGenerator implements GeneratorInterface
*/
public function generate($schema, $className, Context $context)
{
- $files = [];
+ $files = [];
foreach ($context->getObjectClassMap() as $class) {
$properties = [];
|
Fix notice with duplicated property between class and trait
|
janephp_jane
|
train
|
3a8b3649e6c09d7eb461d8aeef1edc660f467ef1
|
diff --git a/lib/jitsu/commands/install.js b/lib/jitsu/commands/install.js
index <HASH>..<HASH> 100644
--- a/lib/jitsu/commands/install.js
+++ b/lib/jitsu/commands/install.js
@@ -7,6 +7,7 @@ var jitsu = require('../../jitsu'),
path = require('path'),
fs = require('fs'),
npmModule = require('npm'),
+ mkdirp = require('mkdirp'),
thisPath = process.cwd();
var starters = {
@@ -43,7 +44,12 @@ var install = module.exports = function (starterName, callback) {
return cb(err);
}
rimraf(thisPath + '/node_modules', function (err) {
- cb(err, result);
+ if (err) {
+ return cb(err);
+ }
+ mkdirp('./node_modules/' + starterName, 0755, function (err) {
+ cb(err, result);
+ });
});
});
});
@@ -97,11 +103,11 @@ var install = module.exports = function (starterName, callback) {
winston.info('Node App has installed.')
- jitsu.prompt.get(['start_local'], function(err, result){
+ jitsu.prompt.get(['start_local'], function(err, results){
if (results['start_local'] !== 'yes') {
return cb(null);
}
- return startApp('local', cb(null));
+ return startApp('local', cb);
});
}
|
[fix] Create directory in node_modules/{starterName} as workaround for npm issue.
|
nodejitsu_jitsu
|
train
|
537cebab367c573f84a4d7a4f4bf82a3de12c96e
|
diff --git a/lib/routeExecutor.js b/lib/routeExecutor.js
index <HASH>..<HASH> 100644
--- a/lib/routeExecutor.js
+++ b/lib/routeExecutor.js
@@ -86,7 +86,14 @@ function convertToTemplate(buses, runner, mainProducer, onDef) {
var val = template.val;
runner = function () {
try {
- fn(prodObj, val);
+ if (fn) {
+ fn(prodObj, val);
+ }
+ else {
+ console.log(name + ' is missing an execution function. You probably forgot to add fn to the object or ' +
+ 'you didn\'t use the correct signature for the when(name, in, out, fn, opts) function');
+ throw('Missing fn to execute');
+ }
}
catch (err) {
console.log('ERROR: function (' + name + ') threw an exception (' + err + ') on input: \r\n' + safeJSONStringify(val, null, 2));
@@ -111,8 +118,8 @@ function convertToTemplate(buses, runner, mainProducer, onDef) {
console.log('ERROR: enter transform for function (' + name +
') threw an exception (' + err + ') on input: \r\n' +
safeJSONStringify(val, null, 2));
- console.log('Stack Trace: ' + err.stack);
prodObj.error(500, err);
+ console.log('Stack Trace: ' + err.stack);
}
if (!takeMany) {
return Bacon.noMore;
@@ -240,4 +247,4 @@ function routeExecutor(handler, phases, path, req, res, inject) {
module.exports = {
httpExecutor: routeExecutor,
customRenderExecutor: customRenderRouteExecutor
-};
\ No newline at end of file
+};
diff --git a/samples/uncaught.exception.js b/samples/uncaught.exception.js
index <HASH>..<HASH> 100644
--- a/samples/uncaught.exception.js
+++ b/samples/uncaught.exception.js
@@ -9,7 +9,7 @@ function createRoute(server) {
server.GET('/samples/uncaught.exception').onValue(function (path) {
path
.inject({demo: 'a value'})
- .when('Crashes On Purpose', ['demo'], function(produce, input) {
+ .when('Crashes On Purpose', ['demo'], [], function(produce, input) {
input.crashNow(); // oops input doesn't have a crashNow function.
produce.done();
})
@@ -25,7 +25,7 @@ function createRoute(server) {
writer.setStatus(code);
writer.writeBody(code + ' : An error occurred (' + description + '), but I intercepted it and wrote this to the client');
})
- .when('Crashes On Purpose', ['demo'], function(produce, input) {
+ .when('Crashes On Purpose', ['demo'], [], function(produce, input) {
input.crashNow(); // oops input doesn't have a crashNow function.
produce.done();
})
@@ -37,7 +37,7 @@ function createRoute(server) {
server.GET('/samples/uncaught.exception/enter').onValue(function (path) {
path
.inject({demo: 'a value'})
- .when('Crashes On Purpose', ['demo'], function(produce) {
+ .when('Crashes On Purpose', ['demo'], [], function(produce) {
produce.done();
},
{
@@ -70,4 +70,4 @@ function createRoute(server) {
}
-module.exports = createRoute;
\ No newline at end of file
+module.exports = createRoute;
|
fixed uncaught example and added better error message for missing fn
|
ayasin_frhttp
|
train
|
b9f3c67a4a48d7df8a54ff7bda641f0c88a2a971
|
diff --git a/system/classes/Validate.php b/system/classes/Validate.php
index <HASH>..<HASH> 100644
--- a/system/classes/Validate.php
+++ b/system/classes/Validate.php
@@ -185,7 +185,7 @@ class Validate
}
// valid_email
- protected function _valid_email($fieldData, $humanName)
+ protected function _valid_email($fieldData)
{
echo $fieldData;
if (preg_match('/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/', $fieldData)) {
@@ -195,7 +195,7 @@ class Validate
}
// mathces
- protected function _matches($fieldData, $humanName, $array)
+ protected function _matches($fieldData, $array)
{
var_dump($array);
}
|
Removed unneeded parameters from Validate checks.
|
joebubna_cora-framework
|
train
|
fa5e64d675ad390d1e5511a2ee698f177637b376
|
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index <HASH>..<HASH> 100644
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -3248,7 +3248,7 @@ class Cmd(cmd.Cmd):
for command in history:
fobj.write('{}\n'.format(command))
try:
- os.system('"{}" "{}"'.format(self.editor, fname))
+ self.do_edit(fname)
self.do_load(fname)
except Exception:
raise
@@ -3356,12 +3356,11 @@ class Cmd(cmd.Cmd):
if not self.editor:
raise EnvironmentError("Please use 'set editor' to specify your text editing program of choice.")
- editor = utils.quote_string_if_needed(self.editor)
+ command = utils.quote_string_if_needed(self.editor)
if args.file_path:
- expanded_path = utils.quote_string_if_needed(os.path.expanduser(args.file_path))
- os.system('{} {}'.format(editor, expanded_path))
- else:
- os.system('{}'.format(editor))
+ command += " " + utils.quote_string_if_needed(args.file_path)
+
+ self.do_shell(command)
@property
def _current_script_dir(self) -> Optional[str]:
diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py
index <HASH>..<HASH> 100644
--- a/tests/test_cmd2.py
+++ b/tests/test_cmd2.py
@@ -459,15 +459,15 @@ def test_history_edit(base_app, monkeypatch):
# going to call it due to the mock
base_app.editor = 'fooedit'
- # Mock out the os.system call so we don't actually open an editor
- m = mock.MagicMock(name='system')
- monkeypatch.setattr("os.system", m)
+ # Mock out the subprocess.Popen call so we don't actually open an editor
+ m = mock.MagicMock(name='Popen')
+ monkeypatch.setattr("subprocess.Popen", m)
# Run help command just so we have a command in history
run_cmd(base_app, 'help')
run_cmd(base_app, 'history -e 1')
- # We have an editor, so should expect a system call
+ # We have an editor, so should expect a Popen call
m.assert_called_once()
def test_history_run_all_commands(base_app):
@@ -883,46 +883,44 @@ def test_edit_file(base_app, request, monkeypatch):
base_app.editor = 'fooedit'
# Mock out the os.system call so we don't actually open an editor
- m = mock.MagicMock(name='system')
- monkeypatch.setattr("os.system", m)
+ m = mock.MagicMock(name='Popen')
+ monkeypatch.setattr("subprocess.Popen", m)
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, 'script.txt')
run_cmd(base_app, 'edit {}'.format(filename))
- # We think we have an editor, so should expect a system call
- m.assert_called_once_with('{} {}'.format(utils.quote_string_if_needed(base_app.editor),
- utils.quote_string_if_needed(filename)))
+ # We think we have an editor, so should expect a Popen call
+ m.assert_called_once()
def test_edit_file_with_spaces(base_app, request, monkeypatch):
# Set a fake editor just to make sure we have one. We aren't really going to call it due to the mock
base_app.editor = 'fooedit'
- # Mock out the os.system call so we don't actually open an editor
- m = mock.MagicMock(name='system')
- monkeypatch.setattr("os.system", m)
+ # Mock out the subprocess.Popen call so we don't actually open an editor
+ m = mock.MagicMock(name='Popen')
+ monkeypatch.setattr("subprocess.Popen", m)
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, 'my commands.txt')
run_cmd(base_app, 'edit "{}"'.format(filename))
- # We think we have an editor, so should expect a system call
- m.assert_called_once_with('{} {}'.format(utils.quote_string_if_needed(base_app.editor),
- utils.quote_string_if_needed(filename)))
+ # We think we have an editor, so should expect a Popen call
+ m.assert_called_once()
def test_edit_blank(base_app, monkeypatch):
# Set a fake editor just to make sure we have one. We aren't really going to call it due to the mock
base_app.editor = 'fooedit'
- # Mock out the os.system call so we don't actually open an editor
- m = mock.MagicMock(name='system')
- monkeypatch.setattr("os.system", m)
+ # Mock out the subprocess.Popen call so we don't actually open an editor
+ m = mock.MagicMock(name='Popen')
+ monkeypatch.setattr("subprocess.Popen", m)
run_cmd(base_app, 'edit')
- # We have an editor, so should expect a system call
+ # We have an editor, so should expect a Popen call
m.assert_called_once()
|
Removed os.system in favor of do_shell
|
python-cmd2_cmd2
|
train
|
d5161fef97c51b05150e0c76ba973c957f912f58
|
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -2,14 +2,21 @@ import Rx, { Observable, Subject } from 'rxjs';
/*
- * Remaps the subject methods `next` and `error` to the "root fucction" and
+ * Remaps the subject methods `next` and `error` to the "root function" and
* error prop respectively.
*/
function remapActions(actions) {
return Object.keys(actions)
.map(name => {
- let action = (val) => actions[name].next(val);
- action.error = (err) => actions[name].error(err);
+ let action = (val) => {
+ actions[name].next(val);
+ return actions[name];
+ };
+
+ action.error = (err) => {
+ actions[name].error(err);
+ return actions[name];
+ };
return [name, action]
})
|
Return action subject after invoking it
|
lohmander_RxSC
|
train
|
a5d1902d8e871a82acd22ac0ec27683be11b7928
|
diff --git a/src/main/java/com/googlecode/lanterna/gui2/dialogs/MessageDialog.java b/src/main/java/com/googlecode/lanterna/gui2/dialogs/MessageDialog.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/googlecode/lanterna/gui2/dialogs/MessageDialog.java
+++ b/src/main/java/com/googlecode/lanterna/gui2/dialogs/MessageDialog.java
@@ -65,6 +65,9 @@ public class MessageDialog extends DialogWindow {
MessageDialogBuilder builder = new MessageDialogBuilder()
.setTitle(title)
.setText(text);
+ if(buttons.length == 0) {
+ builder.addButton(MessageDialogButton.OK);
+ }
for(MessageDialogButton button: buttons) {
builder.addButton(button);
}
|
Adding a default OK button to MessageDialog if no buttons were given
|
mabe02_lanterna
|
train
|
d5b53da809d69fbd00007ac823b31f0c28b5344e
|
diff --git a/lib/resourceful/resource.js b/lib/resourceful/resource.js
index <HASH>..<HASH> 100644
--- a/lib/resourceful/resource.js
+++ b/lib/resourceful/resource.js
@@ -723,16 +723,52 @@ Resource.object = function (name, schema) {
};
Resource.method = function (name, fn, schema) {
+ var that = this;
+
if(typeof this[name] !== 'undefined') {
throw new Error(name + ' is a reserved word on the Resource definition')
}
if (typeof schema === 'object') {
this[name] = function(){
var args = utile.args(arguments);
- if(args.length === 0) {
- args[0] = {};
- }
- var valid = validator.validate(args[0], schema);
+ var payload = {};
+
+
+ //
+ // Compare parsed arguments to expected schema
+ //
+ args.forEach(function(arg, i){
+ //
+ // For every argument, try to match it to a schema value
+ // The order of arguments is expected to match the order of schema property declaration
+ //
+ Object.keys(schema.properties).forEach(function(prop, j){
+ if(j === i) {
+ payload[prop] = arg;
+ }
+ });
+ });
+
+ //
+ // TODO: better default settings using new(that)(payload) instance
+ //
+ Object.keys(schema.properties).forEach(function(prop, j){
+ if(typeof payload[prop] === "undefined" && typeof schema.properties[prop].default !== 'undefined') {
+ payload[prop] = schema.properties[prop].default;
+ }
+ });
+
+ // turn payload back into args
+ var _args = [];
+ Object.keys(payload).forEach(function(val){
+ _args.push(payload[val]); // ignore the key, assume order of arguments is 1:1 to schema property declarations
+ });
+
+ //
+ // TODO: if only argument is callback and its not provided,
+ // make noop callback so the method doesn't crash
+ //
+ var valid = validator.validate(payload, schema);
if(!valid.valid) {
if(typeof args.cb === 'function') {
args.cb(valid);
@@ -740,12 +776,18 @@ Resource.method = function (name, fn, schema) {
throw new Error(JSON.stringify(valid.errors)); // TODO: better errors
}
} else {
- return fn.apply(this, arguments);
+ //
+ // If there is a callback, push it back into the arguments
+ //
+ if(typeof args.cb === "function") {
+ _args.push(args.cb);
+ }
+ return fn.apply(this, _args);
}
};
- } else {
- this[name] = fn;
}
+
+ this[name] = fn;
this[name].type = "method";
this[name].schema = schema;
if(typeof this.methods === "undefined") {
|
[api] Improved argument parsing for functions bound with Resource.method
|
flatiron_resourceful
|
train
|
105c0adcfec2c8d263411d0b4cc43d0d2574b787
|
diff --git a/src/Tokenly/LaravelEventLog/EventLog.php b/src/Tokenly/LaravelEventLog/EventLog.php
index <HASH>..<HASH> 100644
--- a/src/Tokenly/LaravelEventLog/EventLog.php
+++ b/src/Tokenly/LaravelEventLog/EventLog.php
@@ -4,7 +4,7 @@ namespace Tokenly\LaravelEventLog;
use Exception;
-use Illuminate\Http\Exception\HttpResponseException;
+use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Log\Writer;
use RuntimeException;
|
Compatability update for Laravel >= <I>
|
tokenly_laravel-event-log
|
train
|
864d2f31b0d30a25d5986cb8682c5500454da6c8
|
diff --git a/lookup.py b/lookup.py
index <HASH>..<HASH> 100644
--- a/lookup.py
+++ b/lookup.py
@@ -154,6 +154,7 @@ def _filter_stmts(self, stmts, frame, offset):
break
if isinstance(node, nodes.Class) and self in node.bases:
break
+ assert hasattr(node, 'ass_type'), (node, node.scope(), node.scope().locals)
ass_type = node.ass_type()
if ass_type is mystmt and not isinstance(ass_type, (nodes.Class,
nodes.Function, nodes.Import, nodes.From, nodes.Lambda)):
diff --git a/scoped_nodes.py b/scoped_nodes.py
index <HASH>..<HASH> 100644
--- a/scoped_nodes.py
+++ b/scoped_nodes.py
@@ -88,6 +88,7 @@ class LocalsDictMixIn(object):
if the name is already defined, ignore it
"""
assert self.locals is not None, (self, id(self))
+ assert not stmt in self.locals.get(name, ()), (self, stmt)
self.locals.setdefault(name, []).append(stmt)
__setitem__ = set_local
|
add some assertion, to remove later
--HG--
branch : _ast_compat
|
PyCQA_astroid
|
train
|
32fb414726631082321154d09421dfec44af10c6
|
diff --git a/java/server/src/org/openqa/selenium/grid/commands/Hub.java b/java/server/src/org/openqa/selenium/grid/commands/Hub.java
index <HASH>..<HASH> 100644
--- a/java/server/src/org/openqa/selenium/grid/commands/Hub.java
+++ b/java/server/src/org/openqa/selenium/grid/commands/Hub.java
@@ -41,12 +41,16 @@ import org.openqa.selenium.grid.web.CombinedHandler;
import org.openqa.selenium.grid.web.RoutableHttpClientFactory;
import org.openqa.selenium.netty.server.NettyServer;
import org.openqa.selenium.remote.http.HttpClient;
+import org.openqa.selenium.remote.http.HttpHandler;
+import org.openqa.selenium.remote.http.Route;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Set;
import java.util.logging.Logger;
+import static org.openqa.selenium.remote.http.Route.combine;
+
@AutoService(CliCommand.class)
public class Hub extends TemplateGridCommand {
@@ -115,8 +119,9 @@ public class Hub extends TemplateGridCommand {
null);
handler.addHandler(distributor);
Router router = new Router(tracer, clientFactory, sessions, distributor);
+ HttpHandler httpHandler = combine(router, Route.prefix("/wd/hub").to(combine(router)));
- Server<?> server = new NettyServer(serverOptions, router);
+ Server<?> server = new NettyServer(serverOptions, httpHandler);
server.start();
BuildInfo info = new BuildInfo();
diff --git a/java/server/src/org/openqa/selenium/grid/commands/Standalone.java b/java/server/src/org/openqa/selenium/grid/commands/Standalone.java
index <HASH>..<HASH> 100644
--- a/java/server/src/org/openqa/selenium/grid/commands/Standalone.java
+++ b/java/server/src/org/openqa/selenium/grid/commands/Standalone.java
@@ -48,6 +48,8 @@ import org.openqa.selenium.grid.web.RoutableHttpClientFactory;
import org.openqa.selenium.net.NetworkUtils;
import org.openqa.selenium.netty.server.NettyServer;
import org.openqa.selenium.remote.http.HttpClient;
+import org.openqa.selenium.remote.http.HttpHandler;
+import org.openqa.selenium.remote.http.Route;
import java.net.MalformedURLException;
import java.net.URI;
@@ -56,6 +58,8 @@ import java.net.URL;
import java.util.Set;
import java.util.logging.Logger;
+import static org.openqa.selenium.remote.http.Route.combine;
+
@AutoService(CliCommand.class)
public class Standalone extends TemplateGridCommand {
@@ -128,6 +132,7 @@ public class Standalone extends TemplateGridCommand {
Distributor distributor = new LocalDistributor(tracer, bus, clientFactory, sessions, null);
combinedHandler.addHandler(distributor);
Router router = new Router(tracer, clientFactory, sessions, distributor);
+ HttpHandler httpHandler = combine(router, Route.prefix("/wd/hub").to(combine(router)));
LocalNode.Builder nodeBuilder = LocalNode.builder(
tracer,
@@ -144,7 +149,7 @@ public class Standalone extends TemplateGridCommand {
combinedHandler.addHandler(node);
distributor.add(node);
- Server<?> server = new NettyServer(new BaseServerOptions(config), router);
+ Server<?> server = new NettyServer(new BaseServerOptions(config), httpHandler);
server.start();
BuildInfo info = new BuildInfo();
diff --git a/java/server/src/org/openqa/selenium/grid/router/Router.java b/java/server/src/org/openqa/selenium/grid/router/Router.java
index <HASH>..<HASH> 100644
--- a/java/server/src/org/openqa/selenium/grid/router/Router.java
+++ b/java/server/src/org/openqa/selenium/grid/router/Router.java
@@ -33,7 +33,6 @@ import java.util.Objects;
import static org.openqa.selenium.remote.http.Route.combine;
import static org.openqa.selenium.remote.http.Route.get;
import static org.openqa.selenium.remote.http.Route.matching;
-import static org.openqa.selenium.remote.http.Route.prefix;
/**
* A simple router that is aware of the selenium-protocol.
@@ -49,7 +48,7 @@ public class Router implements Routable, HttpHandler {
Distributor distributor) {
Objects.requireNonNull(tracer, "Tracer to use must be set.");
- Routable nonPrefixedRoutes =
+ routes =
combine(
get("/status")
.to(() -> new GridStatusHandler(new Json(), tracer, clientFactory, distributor)),
@@ -57,7 +56,6 @@ public class Router implements Routable, HttpHandler {
distributor.with(new SpanDecorator(tracer, req -> "distributor")),
matching(req -> req.getUri().startsWith("/session/"))
.to(() -> new HandleSession(tracer, clientFactory, sessions)));
- routes = combine(nonPrefixedRoutes, prefix("/wd/hub").to(combine(nonPrefixedRoutes)));
}
@Override
|
[Grid] Prefixing only standalone and hub with /wd/hub
|
SeleniumHQ_selenium
|
train
|
fc0e15214ef1228e18de9551fe8ae22f50a9fe9e
|
diff --git a/pyoos/collectors/ioos/swe_sos.py b/pyoos/collectors/ioos/swe_sos.py
index <HASH>..<HASH> 100644
--- a/pyoos/collectors/ioos/swe_sos.py
+++ b/pyoos/collectors/ioos/swe_sos.py
@@ -9,15 +9,25 @@ class IoosSweSos(Collector):
super(IoosSweSos,self).__init__()
self.server = Sos(url, xml=xml)
- def metadata(self, **kwargs):
- callback = kwargs.get("feature_name_callback", None) or str
- kwargs['outputFormat'] = 'text/xml;subtype="sensorML/1.0.1"'
+ def metadata(self, output_format=None, feature_name_callback=None, **kwargs):
+ """
+ Gets SensorML objects for all procedures in your filtered features.
+
+ You should override the default output_format for servers that do not
+ respond properly.
+ """
+ callback = feature_name_callback or str
+ if output_format is None:
+ output_format = 'text/xml; subtype="sensorML/1.0.1/profiles/ioos_sos/1.0"'
responses = []
if self.features is not None:
for feature in self.features:
- kwargs['procedure'] = callback(feature)
- responses.append(SensorML(self.server.describe_sensor(**kwargs)))
+ ds_kwargs = kwargs.copy()
+ ds_kwargs.update({'outputFormat': output_format,
+ 'procedure' : callback(feature)})
+
+ responses.append(SensorML(self.server.describe_sensor(**ds_kwargs)))
return responses
diff --git a/tests/collectors/test_coops_sos.py b/tests/collectors/test_coops_sos.py
index <HASH>..<HASH> 100644
--- a/tests/collectors/test_coops_sos.py
+++ b/tests/collectors/test_coops_sos.py
@@ -25,7 +25,7 @@ class CoopsSosTest(unittest.TestCase):
def test_coops_describe_sensor(self):
self.c.features = ['8454000']
- response = self.c.metadata()
+ response = self.c.metadata(output_format='text/xml;subtype="sensorML/1.0.1"')
assert isinstance(response[0], SensorML)
def test_raw_coops_get_observation(self):
@@ -89,4 +89,4 @@ class CoopsSosTest(unittest.TestCase):
assert data[0]['datum_id'] == "urn:ogc:def:datum:epsg::5103"
assert data[0]['date_time'] == "2012-10-01T01:00:00Z"
assert data[0]['water_surface_height_above_reference_datum (m)'] == "0.863"
- assert data[0]['vertical_position (m)'] == "1.818"
\ No newline at end of file
+ assert data[0]['vertical_position (m)'] == "1.818"
diff --git a/tests/collectors/test_ndbc_sos.py b/tests/collectors/test_ndbc_sos.py
index <HASH>..<HASH> 100644
--- a/tests/collectors/test_ndbc_sos.py
+++ b/tests/collectors/test_ndbc_sos.py
@@ -24,7 +24,7 @@ class NdbcSosTest(unittest.TestCase):
def test_ndbc_describe_sensor(self):
self.c.features = ['41012']
- response = self.c.metadata()
+ response = self.c.metadata(output_format='text/xml;subtype="sensorML/1.0.1"')
assert isinstance(response, list)
assert isinstance(response[0], SensorML)
|
Update outputFormat for SOS collector. Fixes #<I>
|
ioos_pyoos
|
train
|
487fb64af2edab52fd316d955b416fdae5e575e4
|
diff --git a/lib/flipper-sequel.rb b/lib/flipper-sequel.rb
index <HASH>..<HASH> 100644
--- a/lib/flipper-sequel.rb
+++ b/lib/flipper-sequel.rb
@@ -5,3 +5,5 @@ Flipper.configure do |config|
Flipper.new(Flipper::Adapters::Sequel.new)
end
end
+
+Sequel::Model.include Flipper::Identifier
diff --git a/spec/flipper/adapters/active_record_spec.rb b/spec/flipper/adapters/active_record_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/flipper/adapters/active_record_spec.rb
+++ b/spec/flipper/adapters/active_record_spec.rb
@@ -60,7 +60,6 @@ RSpec.describe Flipper::Adapters::ActiveRecord do
end
it "defines #flipper_id on AR::Base" do
- binding.pry
expect(ActiveRecord::Base.ancestors).to include(Flipper::Identifier)
end
end
diff --git a/spec/flipper/adapters/sequel_spec.rb b/spec/flipper/adapters/sequel_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/flipper/adapters/sequel_spec.rb
+++ b/spec/flipper/adapters/sequel_spec.rb
@@ -29,12 +29,20 @@ RSpec.describe Flipper::Adapters::Sequel do
it_should_behave_like 'a flipper adapter'
- it 'configures itself on load' do
- Flipper.configuration = nil
- Flipper.instance = nil
+ context 'requiring "flipper-sequel"' do
+ before do
+ Flipper.configuration = nil
+ Flipper.instance = nil
- require 'flipper-sequel'
+ require 'flipper-sequel'
+ end
- expect(Flipper.adapter.adapter).to be_a(Flipper::Adapters::Sequel)
+ it 'configures itself' do
+ expect(Flipper.adapter.adapter).to be_a(Flipper::Adapters::Sequel)
+ end
+
+ it "defines #flipper_id on AR::Base" do
+ expect(Sequel::Model.ancestors).to include(Flipper::Identifier)
+ end
end
end
|
Include Filler::Identifier for sequel
|
jnunemaker_flipper
|
train
|
d75c577132f95b96c7838e6822316be8db0c1635
|
diff --git a/blimpy/utils.py b/blimpy/utils.py
index <HASH>..<HASH> 100644
--- a/blimpy/utils.py
+++ b/blimpy/utils.py
@@ -60,33 +60,22 @@ def unpack(data, nbit):
if nbit == 8:
return data
elif nbit == 4:
- #The process is this:
- #ABCDEFGH [Bits of one 4+4-bit value]
- #00000000ABCDEFGH [astype(uint16)]
- #0000ABCDEFGH0000 [<< 4]
- #0000ABCDXXXXEFGH [bitwise 'or' of previous two lines]
- #0000111100001111 [0x0F0F]
- #0000ABCD0000EFGH [bitwise 'and' of previous two lines]
- #ABCD0000EFGH0000 [<< 4]
- #which effectively pads the two 4-bit values with zeros on the right
- # Note: This technique assumes LSB-first ordering
- tmpdata = data.astype(np.int16)#np.empty(upshape, dtype=np.int16)
- tmpdata = (tmpdata | (tmpdata << 8)) & 0x0F0F
- tmpdata = tmpdata << 4 # Shift into high bits to avoid needing to sign extend
- updata = tmpdata
- return updata.view(data.dtype)
+ data = unpack_4to8(data)
+ return data
elif nbit == 2:
data = unpack_2to8(data)
return data
elif nbit == 1:
- tmpdata = data.astype(np.int64)#np.empty(upshape, dtype=np.int16)
- tmpdata = (tmpdata | (tmpdata << 32)) & 0x0000000F0000000F
- tmpdata = (tmpdata | (tmpdata << 16)) & 0x0003000300030003
- tmpdata = (tmpdata | (tmpdata << 8)) & 0x0101010101010101
- tmpdata = tmpdata << 7 # Shift into high bits to avoid needing to sign extend
- updata = tmpdata
- return updata.view(data.dtype)
+ data = unpack_1to8(data)
+ return data
+def unpack_1to8(data):
+ """ Promote 1-bit unisgned data into 8-bit unsigned data.
+
+ Args:
+ data: Numpy array with dtype == uint8
+ """
+ return np.unpackbits(data)
def unpack_2to8(data):
""" Promote 2-bit unisgned data into 8-bit unsigned data.
@@ -119,3 +108,28 @@ def unpack_2to8(data):
tmp = (tmp | (tmp << 6)) & 0x3030303
tmp = tmp.byteswap()
return tmp.view('uint8')
+
+def unpack_4to8(data):
+ """ Promote 2-bit unisgned data into 8-bit unsigned data.
+
+ Args:
+ data: Numpy array with dtype == uint8
+
+ Notes:
+ # The process is this:
+ # ABCDEFGH [Bits of one 4+4-bit value]
+ # 00000000ABCDEFGH [astype(uint16)]
+ # 0000ABCDEFGH0000 [<< 4]
+ # 0000ABCDXXXXEFGH [bitwise 'or' of previous two lines]
+ # 0000111100001111 [0x0F0F]
+ # 0000ABCD0000EFGH [bitwise 'and' of previous two lines]
+ # ABCD0000EFGH0000 [<< 4]
+ # which effectively pads the two 4-bit values with zeros on the right
+ # Note: This technique assumes LSB-first ordering
+ """
+
+ tmpdata = data.astype(np.int16) # np.empty(upshape, dtype=np.int16)
+ tmpdata = (tmpdata | (tmpdata << 4)) & 0x0F0F
+ # tmpdata = tmpdata << 4 # Shift into high bits to avoid needing to sign extend
+ updata = tmpdata.byteswap()
+ return updata.view(data.dtype)
|
Fixed up unpack code and added unittests
Former-commit-id: 1ef<I>cf<I>e1d<I>a<I>ebea<I>f<I>c<I>
|
UCBerkeleySETI_blimpy
|
train
|
baf9591d3b0eea51434f1e2ef726c29bd35c85d5
|
diff --git a/gson/src/main/java/com/google/gson/DisjunctionExclusionStrategy.java b/gson/src/main/java/com/google/gson/DisjunctionExclusionStrategy.java
index <HASH>..<HASH> 100644
--- a/gson/src/main/java/com/google/gson/DisjunctionExclusionStrategy.java
+++ b/gson/src/main/java/com/google/gson/DisjunctionExclusionStrategy.java
@@ -27,7 +27,7 @@ import java.util.Collection;
final class DisjunctionExclusionStrategy implements ExclusionStrategy {
private final Collection<ExclusionStrategy> strategies;
- public DisjunctionExclusionStrategy(Collection<ExclusionStrategy> strategies) {
+ DisjunctionExclusionStrategy(Collection<ExclusionStrategy> strategies) {
Preconditions.checkNotNull(strategies);
this.strategies = strategies;
}
diff --git a/gson/src/main/java/com/google/gson/GsonBuilder.java b/gson/src/main/java/com/google/gson/GsonBuilder.java
index <HASH>..<HASH> 100644
--- a/gson/src/main/java/com/google/gson/GsonBuilder.java
+++ b/gson/src/main/java/com/google/gson/GsonBuilder.java
@@ -464,7 +464,7 @@ public final class GsonBuilder {
*/
public GsonBuilder registerTypeHierarchyAdapter(Class<?> baseType, Object typeAdapter) {
Preconditions.checkArgument(typeAdapter instanceof JsonSerializer<?>
- || typeAdapter instanceof JsonDeserializer<?> || typeAdapter instanceof InstanceCreator<?>);
+ || typeAdapter instanceof JsonDeserializer<?> || typeAdapter instanceof InstanceCreator<?>);
if (typeAdapter instanceof InstanceCreator<?>) {
registerInstanceCreatorForTypeHierarchy(baseType, (InstanceCreator<?>) typeAdapter);
}
diff --git a/gson/src/main/java/com/google/gson/ModifyFirstLetterNamingPolicy.java b/gson/src/main/java/com/google/gson/ModifyFirstLetterNamingPolicy.java
index <HASH>..<HASH> 100644
--- a/gson/src/main/java/com/google/gson/ModifyFirstLetterNamingPolicy.java
+++ b/gson/src/main/java/com/google/gson/ModifyFirstLetterNamingPolicy.java
@@ -62,7 +62,7 @@ final class ModifyFirstLetterNamingPolicy extends RecursiveFieldNamingPolicy {
* @param modifier the type of modification that should be performed
* @throws IllegalArgumentException if {@code modifier} is null
*/
- public ModifyFirstLetterNamingPolicy(LetterModifier modifier) {
+ ModifyFirstLetterNamingPolicy(LetterModifier modifier) {
Preconditions.checkNotNull(modifier);
this.letterModifier = modifier;
}
diff --git a/gson/src/main/java/com/google/gson/VersionExclusionStrategy.java b/gson/src/main/java/com/google/gson/VersionExclusionStrategy.java
index <HASH>..<HASH> 100644
--- a/gson/src/main/java/com/google/gson/VersionExclusionStrategy.java
+++ b/gson/src/main/java/com/google/gson/VersionExclusionStrategy.java
@@ -28,7 +28,7 @@ import com.google.gson.annotations.Until;
final class VersionExclusionStrategy implements ExclusionStrategy {
private final double version;
- public VersionExclusionStrategy(double version) {
+ VersionExclusionStrategy(double version) {
Preconditions.checkArgument(version >= 0.0D);
this.version = version;
}
|
Made constructors package private for package private classes.
|
google_gson
|
train
|
ea3597e6b7f1c6eb378c66d88c7201caa2158ee8
|
diff --git a/test/unit/SessionTokenStoreTest.php b/test/unit/SessionTokenStoreTest.php
index <HASH>..<HASH> 100644
--- a/test/unit/SessionTokenStoreTest.php
+++ b/test/unit/SessionTokenStoreTest.php
@@ -66,8 +66,6 @@ class SessionTokenStoreTest extends TestCase {
$session = self::createMock(SessionStore::class);
$session->method("get")
->willReturn($existingTokens);
- $session->method("getMaxTokens")
- ->willReturn(10);
$existingTokensWithNewToken = [];
foreach($existingTokens as $key => $value) {
@@ -76,8 +74,18 @@ class SessionTokenStoreTest extends TestCase {
array_shift($existingTokensWithNewToken);
$existingTokensWithNewToken[$tokenToSet] = null;
+ $session->expects($this->once())
+ ->method("set")
+ ->with(
+ SessionTokenStore::SESSION_KEY,
+ $existingTokensWithNewToken
+ );
+
/** @var SessionStore $session */
- $sessionTokenStore = new SessionTokenStore($session);
+ $sessionTokenStore = new SessionTokenStore(
+ $session,
+ 10
+ );
$sessionTokenStore->saveToken($tokenToSet);
}
}
\ No newline at end of file
|
Test setting token when max tokens are used
|
PhpGt_Csrf
|
train
|
40f78d738991a90f62dbfa0c8939891ab174800e
|
diff --git a/test/test_peerassets.py b/test/test_peerassets.py
index <HASH>..<HASH> 100644
--- a/test/test_peerassets.py
+++ b/test/test_peerassets.py
@@ -31,7 +31,7 @@ def test_find_cards():
cards = pa.find_card_transfers(provider, deck)
assert cards
- assert isinstance(cards[0], pa.CardTransfer)
+ assert isinstance(next(cards), pa.CardTransfer)
def test_deck_spawn():
|
it's a generator, hit first element of it
|
PeerAssets_pypeerassets
|
train
|
96847790c659c1da9a712a5731ba1082f1066084
|
diff --git a/src/test/java/apoc/date/DateTest.java b/src/test/java/apoc/date/DateTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/apoc/date/DateTest.java
+++ b/src/test/java/apoc/date/DateTest.java
@@ -133,6 +133,22 @@ public class DateTest {
});
}
+ @Test public void testFromUnixtimeWithCorrectFormatAndTimeZone() throws Exception {
+ String pattern = "HH:mm:ss/yyyy";
+ String timezone = "America/New_York";
+ SimpleDateFormat customFormat = formatInCustomTimeZone(pattern, timezone);
+ testCall(db,
+ "CALL apoc.date.formatTimeZone(0,'s',{pattern},{timezone})",
+ map("pattern",pattern,"timezone",timezone),
+ row -> {
+ try {
+ assertEquals(new java.util.Date(0L), customFormat.parse((String) row.get("value")));
+ } catch (ParseException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ }
+
@Test public void testFromUnixtimeWithIncorrectPatternFormat() throws Exception {
expected.expect(instanceOf(QueryExecutionException.class));
testCall(db,
@@ -140,6 +156,13 @@ public class DateTest {
row -> {});
}
+ @Test public void testFromUnixtimeWithIncorrectPatternFormatAndTimeZone() throws Exception {
+ expected.expect(instanceOf(QueryExecutionException.class));
+ testCall(db,
+ "CALL apoc.date.formatTimeZone(0,'s','HH:mm:ss/yyyy/neo4j','Neo4j/Apoc')",
+ row -> {});
+ }
+
@Test public void testFromUnixtimeWithNegativeInput() throws Exception {
expected.expect(instanceOf(QueryExecutionException.class));
testCall(db, "CALL apoc.date.formatDefault(-1,'s')", row -> {});
@@ -246,4 +269,10 @@ public class DateTest {
customFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return customFormat;
}
+
+ private SimpleDateFormat formatInCustomTimeZone(final String pattern, final String timezone) {
+ SimpleDateFormat customFormat = new SimpleDateFormat(pattern);
+ customFormat.setTimeZone(TimeZone.getTimeZone(timezone));
+ return customFormat;
+ }
}
|
Tests for formatTimeZone procedure
|
neo4j-contrib_neo4j-apoc-procedures
|
train
|
afb12734a5652a7e1666e474225369ec86ad1480
|
diff --git a/example/advanced/server.js b/example/advanced/server.js
index <HASH>..<HASH> 100644
--- a/example/advanced/server.js
+++ b/example/advanced/server.js
@@ -1,5 +1,6 @@
-var titan = require('../../');
+var path = require('path');
var siren = require('argo-formatter-siren');
+var titan = require('../../');
titan()
.allow('*')
@@ -10,5 +11,5 @@ titan()
'application/json': siren
}
})
- .load()
+ .load(path.join(__dirname, 'resources'))
.listen(3000);
diff --git a/titan.js b/titan.js
index <HASH>..<HASH> 100644
--- a/titan.js
+++ b/titan.js
@@ -117,8 +117,9 @@ Titan.prototype.compress = function() {
};
Titan.prototype.load = function(factory) {
- if (!factory) {
- factory = new DirectoryResourceFactory();
+ if (!factory || typeof factory === 'string') {
+ var opts = { directory: factory };
+ factory = new DirectoryResourceFactory(opts);
};
this.resourceFactory = factory;
return this;
|
Making directory loading of resources a little more explicit.
|
argo_titan
|
train
|
430c186bf89ab779de84393c2df0f2462ef55d56
|
diff --git a/client/signup/config/flows-pure.js b/client/signup/config/flows-pure.js
index <HASH>..<HASH> 100644
--- a/client/signup/config/flows-pure.js
+++ b/client/signup/config/flows-pure.js
@@ -145,33 +145,6 @@ export function generateFlows( {
lastModified: '2019-04-30',
},
- 'delta-discover': {
- steps: [ 'user' ],
- destination: '/',
- description:
- 'A copy of the `account` flow for the Delta email campaigns. Half of users who ' +
- 'go through this flow receive a reader-specific drip email series.',
- lastModified: '2016-05-03',
- },
-
- 'delta-blog': {
- steps: [ 'about', 'themes', 'domains', 'plans', 'user' ],
- destination: getSiteDestination,
- description:
- 'A copy of the `blog` flow for the Delta email campaigns. Half of users who go ' +
- 'through this flow receive a blogging-specific drip email series.',
- lastModified: '2018-01-24',
- },
-
- 'delta-site': {
- steps: [ 'about', 'themes', 'domains', 'plans', 'user' ],
- destination: getSiteDestination,
- description:
- 'A copy of the `website` flow for the Delta email campaigns. Half of users who go ' +
- 'through this flow receive a website-specific drip email series.',
- lastModified: '2018-01-24',
- },
-
desktop: {
steps: [ 'about', 'themes', 'domains', 'plans', 'user' ],
destination: getChecklistDestination,
diff --git a/client/signup/config/steps-pure.js b/client/signup/config/steps-pure.js
index <HASH>..<HASH> 100644
--- a/client/signup/config/steps-pure.js
+++ b/client/signup/config/steps-pure.js
@@ -38,9 +38,7 @@ export function generateSteps( {
stepName: 'survey',
props: {
surveySiteType:
- currentPage && currentPage.toString().match( /\/start\/(blog|delta-blog)/ )
- ? 'blog'
- : 'site',
+ currentPage && currentPage.toString().match( /\/start\/blog/ ) ? 'blog' : 'site',
},
providesDependencies: [ 'surveySiteType', 'surveyQuestion' ],
},
|
Remove unused delta signup flows (#<I>)
* Remove unused delta signup flows
Remove `delta-blog`, `delta-discover`, and `delta-site` signup flows. These were once used for email campaigns, but have since been redirected from landing pages to point to `/start`.
* Remove reference to `delta-blog` in survey step regex.
|
Automattic_wp-calypso
|
train
|
f801a089746c7ffafca52e014bae1d1a511cb598
|
diff --git a/patroni/version.py b/patroni/version.py
index <HASH>..<HASH> 100644
--- a/patroni/version.py
+++ b/patroni/version.py
@@ -1 +1 @@
-__version__ = '0.80'
+__version__ = '0.90'
|
Bumped version to <I>
|
zalando_patroni
|
train
|
1215511b088422695a0b26e22dfe901f5d7b3c49
|
diff --git a/kubetest/kind/kind.go b/kubetest/kind/kind.go
index <HASH>..<HASH> 100644
--- a/kubetest/kind/kind.go
+++ b/kubetest/kind/kind.go
@@ -335,28 +335,8 @@ func (d *Deployer) Up() error {
func (d *Deployer) IsUp() error {
log.Println("kind.go:IsUp()")
- // Proceed only if a cluster exists.
- exists, err := d.clusterExists()
- if err != nil {
- return err
- }
- if !exists {
- log.Printf("kind.go:IsUp(): no such cluster %q; skipping IsUp()!", d.kindClusterName)
- return nil
- }
-
- // Obtain the path of the kubeconfig.
- path, err := d.getKubeConfigPath()
- if err != nil {
- return err
- }
-
- // Check if kubectl reports nodes for that kubeconfig file.
+ // Check if kubectl reports nodes.
cmd, err := d.KubectlCommand()
- cmd.Env = append(cmd.Env, "KUBECONFIG="+path)
- if err != nil {
- return err
- }
cmd.Args = append(cmd.Args, []string{"get", "nodes", "--no-headers"}...)
o, err := d.control.Output(cmd)
if err != nil {
@@ -417,7 +397,7 @@ func (d *Deployer) TestSetup() error {
// clusterExists checks if a kind cluster with 'name' exists
func (d *Deployer) clusterExists() (bool, error) {
- log.Printf("kind.go:clusterExists(): %s", d.kindClusterName)
+ log.Printf("kind.go:clusterExists()")
cmd := exec.Command("kind")
cmd.Args = append(cmd.Args, []string{"get", "clusters", flagLogLevel}...)
@@ -428,7 +408,8 @@ func (d *Deployer) clusterExists() (bool, error) {
lines := strings.Split(string(out), "\n")
for _, line := range lines {
- if strings.Contains(line, d.kindClusterName) {
+ if line == d.kindClusterName {
+ log.Printf("kind.go:clusterExists(): found %q", d.kindClusterName)
return true, nil
}
}
|
kubetest/kind: simplify IsUp()
- remove from IsUp():
- check if cluster exists
- fetching and setting kubeconfig path
- clusterExists():
- properly compare line in the out from `kind get clusters`
- show message if cluster is found
|
kubernetes_test-infra
|
train
|
0c68d6e2f2f40f189c60338c1895d7060ab27117
|
diff --git a/metadata/metadata.go b/metadata/metadata.go
index <HASH>..<HASH> 100644
--- a/metadata/metadata.go
+++ b/metadata/metadata.go
@@ -37,7 +37,13 @@ func DecodeKeyValue(k, v string) (string, string, error) {
type MD map[string][]string
// New creates an MD from a given key-value map.
-// Keys are automatically converted to lowercase.
+//
+// Only the following ASCII characters are allowed in keys:
+// - digits: 0-9
+// - uppercase letters: A-Z (normalized to lower)
+// - lowercase letters: a-z
+// - special characters: -_.
+// Uppercase letters are automatically converted to lowercase.
func New(m map[string]string) MD {
md := MD{}
for k, val := range m {
@@ -49,7 +55,13 @@ func New(m map[string]string) MD {
// Pairs returns an MD formed by the mapping of key, value ...
// Pairs panics if len(kv) is odd.
-// Keys are automatically converted to lowercase.
+//
+// Only the following ASCII characters are allowed in keys:
+// - digits: 0-9
+// - uppercase letters: A-Z (normalized to lower)
+// - lowercase letters: a-z
+// - special characters: -_.
+// Uppercase letters are automatically converted to lowercase.
func Pairs(kv ...string) MD {
if len(kv)%2 == 1 {
panic(fmt.Sprintf("metadata: Pairs got the odd number of input pairs for metadata: %d", len(kv)))
|
Specify characters allowed in metadata keys (#<I>)
|
grpc_grpc-go
|
train
|
4ef6a7947fbd6c78e03afefed36747d33f6ad7ec
|
diff --git a/lib/viewpoint/spws/spws_client.rb b/lib/viewpoint/spws/spws_client.rb
index <HASH>..<HASH> 100644
--- a/lib/viewpoint/spws/spws_client.rb
+++ b/lib/viewpoint/spws/spws_client.rb
@@ -71,4 +71,19 @@ class Viewpoint::SPWSClient
lists_ws.delete_list(list)
end
+ # ========= UserGroup Accessor Proxy Methods =========
+
+ # Retrieve a user by e-mail
+ # @param [String] user either in e-mail form or DOMAIN\login form. If you
+ # specify an e-mail there is an additional web service call that needs
+ # to be made so if you're worried about performance use the DOMAIN\login
+ # form.
+ # @return [Viewpoint::SPWS::Types::User]
+ def get_user(user)
+ if user =~ /@/
+ ulh = usergroup_ws.get_user_login_from_email [user]
+ user = ulh[user]
+ end
+ usergroup_ws.get_user_info user
+ end
end
|
#get_user added to SPWSClient
|
zenchild_viewpoint-spws
|
train
|
fdf173938cd72d6ea78d38f25a3e311b6499d2e8
|
diff --git a/lib/octopress-ink/assets/page.rb b/lib/octopress-ink/assets/page.rb
index <HASH>..<HASH> 100644
--- a/lib/octopress-ink/assets/page.rb
+++ b/lib/octopress-ink/assets/page.rb
@@ -59,7 +59,8 @@ module Octopress
def info
message = super
- message.ljust(25) + url_info
+ message.sub!(/#{filename}/, permalink_name.ljust(filename.size))
+ message.ljust(25) + page.permalink
end
def permalink
@@ -80,10 +81,6 @@ module Octopress
File.join(plugin_dir, dir, file)
end
- def url_info
- "/#{page.url.sub(/^\//,'')}"
- end
-
def user_dir
File.join Octopress.site.source, Plugins.custom_dir, plugin.slug, base
end
|
Now displaying page permalink names instead of filenames with ink list view
|
octopress_ink
|
train
|
068e368949cc9570d972b19d52f1ac2be8781c28
|
diff --git a/aws/resource_aws_dynamodb_table_test.go b/aws/resource_aws_dynamodb_table_test.go
index <HASH>..<HASH> 100644
--- a/aws/resource_aws_dynamodb_table_test.go
+++ b/aws/resource_aws_dynamodb_table_test.go
@@ -902,6 +902,40 @@ func TestAccAWSDynamoDbTable_gsiUpdateOtherAttributes(t *testing.T) {
})
}
+// Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/15115
+func TestAccAWSDynamoDbTable_lsiNonKeyAttributes(t *testing.T) {
+ var conf dynamodb.DescribeTableOutput
+ resourceName := "aws_dynamodb_table.test"
+ rName := acctest.RandomWithPrefix("tf-acc-test")
+
+ resource.ParallelTest(t, resource.TestCase{
+ PreCheck: func() { testAccPreCheck(t) },
+ Providers: testAccProviders,
+ CheckDestroy: testAccCheckAWSDynamoDbTableDestroy,
+ Steps: []resource.TestStep{
+ {
+ Config: testAccAWSDynamoDbConfigLsiNonKeyAttributes(rName),
+ Check: resource.ComposeTestCheckFunc(
+ testAccCheckInitialAWSDynamoDbTableExists(resourceName, &conf),
+ resource.TestCheckResourceAttr(resourceName, "local_secondary_index.#", "1"),
+ tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "local_secondary_index.*", map[string]string{
+ "name": "TestTableLSI",
+ "non_key_attributes.#": "1",
+ "non_key_attributes.0": "TestNonKeyAttribute",
+ "projection_type": "INCLUDE",
+ "range_key": "TestLSIRangeKey",
+ }),
+ ),
+ },
+ {
+ ResourceName: resourceName,
+ ImportState: true,
+ ImportStateVerify: true,
+ },
+ },
+ })
+}
+
// https://github.com/terraform-providers/terraform-provider-aws/issues/566
func TestAccAWSDynamoDbTable_gsiUpdateNonKeyAttributes(t *testing.T) {
var conf dynamodb.DescribeTableOutput
@@ -2053,6 +2087,40 @@ resource "aws_dynamodb_table" "test" {
`, name, attributes)
}
+func testAccAWSDynamoDbConfigLsiNonKeyAttributes(name string) string {
+ return fmt.Sprintf(`
+resource "aws_dynamodb_table" "test" {
+ name = "%s"
+ hash_key = "TestTableHashKey"
+ range_key = "TestTableRangeKey"
+ write_capacity = 1
+ read_capacity = 1
+
+ attribute {
+ name = "TestTableHashKey"
+ type = "S"
+ }
+
+ attribute {
+ name = "TestTableRangeKey"
+ type = "S"
+ }
+
+ attribute {
+ name = "TestLSIRangeKey"
+ type = "N"
+ }
+
+ local_secondary_index {
+ name = "TestTableLSI"
+ range_key = "TestLSIRangeKey"
+ projection_type = "INCLUDE"
+ non_key_attributes = ["TestNonKeyAttribute"]
+ }
+}
+`, name)
+}
+
func testAccAWSDynamoDbConfigTimeToLive(rName string, ttlEnabled bool) string {
return fmt.Sprintf(`
resource "aws_dynamodb_table" "test" {
diff --git a/aws/structure.go b/aws/structure.go
index <HASH>..<HASH> 100644
--- a/aws/structure.go
+++ b/aws/structure.go
@@ -4247,6 +4247,10 @@ func expandDynamoDbProjection(data map[string]interface{}) *dynamodb.Projection
ProjectionType: aws.String(data["projection_type"].(string)),
}
+ if v, ok := data["non_key_attributes"].([]interface{}); ok && len(v) > 0 {
+ projection.NonKeyAttributes = expandStringList(v)
+ }
+
if v, ok := data["non_key_attributes"].(*schema.Set); ok && v.Len() > 0 {
projection.NonKeyAttributes = expandStringList(v.List())
}
|
re-add logic to expand non_key_attributes configured in a TypeList
|
terraform-providers_terraform-provider-aws
|
train
|
8ff1504fe7ca1424eed05d5fb5bf417df83e8e3f
|
diff --git a/metal/analysis.py b/metal/analysis.py
index <HASH>..<HASH> 100644
--- a/metal/analysis.py
+++ b/metal/analysis.py
@@ -188,7 +188,7 @@ def LF_coverages(L):
L: an N x M scipy.sparse matrix where L_{i,j} is the label given by the
jth LF to the ith candidate:
"""
- return (L != 0).sum(axis=0) / L.shape[0]
+ return np.ravel((L != 0).sum(axis=0)) / L.shape[0]
def LF_overlaps(L, normalize_by_coverage=False):
"""Return the **fraction of items each LF labels that are also labeled by at
|
Raveling return of LF_coverages
|
HazyResearch_metal
|
train
|
ee0672b79c991912533ad6eaf8cfcf712df78c43
|
diff --git a/boskos/client/client.go b/boskos/client/client.go
index <HASH>..<HASH> 100644
--- a/boskos/client/client.go
+++ b/boskos/client/client.go
@@ -150,6 +150,11 @@ func (c *Client) Reset(rtype string, state string, expire time.Duration, dest st
return c.reset(rtype, state, expire, dest)
}
+// HasResource tells if current client holds any resources
+func (c *Client) HasResource() bool {
+ return len(c.resources) > 0
+}
+
// private methods
func (c *Client) popResource() (string, bool) {
diff --git a/kubetest/BUILD b/kubetest/BUILD
index <HASH>..<HASH> 100644
--- a/kubetest/BUILD
+++ b/kubetest/BUILD
@@ -31,6 +31,7 @@ go_library(
"util.go",
],
tags = ["automanaged"],
+ deps = ["//boskos/client:go_default_library"],
)
filegroup(
diff --git a/kubetest/main.go b/kubetest/main.go
index <HASH>..<HASH> 100644
--- a/kubetest/main.go
+++ b/kubetest/main.go
@@ -30,6 +30,8 @@ import (
"regexp"
"strings"
"time"
+
+ "k8s.io/test-infra/boskos/client"
)
var (
@@ -41,6 +43,7 @@ var (
terminated = false
verbose = false
timeout = time.Duration(0)
+ boskos = client.NewClient(os.Getenv("JOB_NAME"), "http://boskos")
)
// Joins os.Getwd() and path
@@ -187,7 +190,15 @@ func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
o := defineFlags()
flag.Parse()
- if err := complete(o); err != nil {
+ err := complete(o)
+
+ if boskos.HasResource() {
+ if berr := boskos.ReleaseAll("dirty"); berr != nil {
+ log.Fatalf("[Boskos] Fail To Release: %v, kubetest err: %v", berr, err)
+ }
+ }
+
+ if err != nil {
log.Fatalf("Something went wrong: %v", err)
}
}
@@ -403,7 +414,18 @@ func prepareGcp(kubernetesProvider string) error {
// Ensure project is set
p := os.Getenv("PROJECT")
if p == "" {
- return fmt.Errorf("KUBERNETES_PROVIDER=%s requires setting PROJECT", kubernetesProvider)
+ p, err := boskos.Acquire("project", "free", "busy")
+ if err != nil {
+ return fmt.Errorf("KUBERNETES_PROVIDER=%s boskos fail to acquire PROJECT:%s", kubernetesProvider, err)
+ }
+
+ go func(c *client.Client, proj string) {
+ for range time.Tick(time.Minute * 5) {
+ if err := c.UpdateOne(p, "busy"); err != nil {
+ log.Printf("[Boskos] Update %p failed with %v", p, err)
+ }
+ }
+ }(boskos, p)
}
// gcloud creds may have changed
|
Make kubetest use boskos to get projects
|
kubernetes_test-infra
|
train
|
4fca4b2556743d226c8b2ac13aea1f68abe0bc86
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -16,6 +16,7 @@
failure_threshold_percentage, 0.2,
retry_timeout: 10
)
+ circuit_breaker.protect { sleep(10) }
```
### Running the specs
diff --git a/lib/circuit_breaker-ruby/shield.rb b/lib/circuit_breaker-ruby/shield.rb
index <HASH>..<HASH> 100644
--- a/lib/circuit_breaker-ruby/shield.rb
+++ b/lib/circuit_breaker-ruby/shield.rb
@@ -22,7 +22,7 @@ module CircuitBreaker
CircuitBreaker.config
end
- def call(&block)
+ def protect(&block)
case prev_state = state
when States::CLOSED, States::HALF_OPEN
connect(&block).tap { update_total_count(prev_state) }
diff --git a/spec/circuit_breaker/shield_spec.rb b/spec/circuit_breaker/shield_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/circuit_breaker/shield_spec.rb
+++ b/spec/circuit_breaker/shield_spec.rb
@@ -11,7 +11,7 @@ describe CircuitBreaker::Shield do
let(:circuit_breaker_shield) { CircuitBreaker::Shield.new }
it 'goes to closed state' do
- circuit_breaker_shield.call { sleep(0.1) }
+ circuit_breaker_shield.protect { sleep(0.1) }
expect(circuit_breaker_shield.send :state).to be(CircuitBreaker::Shield::States::CLOSED)
end
@@ -20,8 +20,8 @@ describe CircuitBreaker::Shield do
no_of_tries = circuit_breaker_shield.failure_threshold * 2
no_of_failures = no_of_tries * circuit_breaker_shield.config.failure_threshold_percentage
no_of_success = no_of_tries - no_of_failures
- no_of_success.to_i.times { circuit_breaker_shield.call { sleep(0.1) } }
- no_of_failures.to_i.times { circuit_breaker_shield.call { sleep(2) } }
+ no_of_success.to_i.times { circuit_breaker_shield.protect { sleep(0.1) } }
+ no_of_failures.to_i.times { circuit_breaker_shield.protect { sleep(2) } }
expect(circuit_breaker_shield.send :state).to be(CircuitBreaker::Shield::States::OPEN)
end
@@ -30,8 +30,8 @@ describe CircuitBreaker::Shield do
no_of_tries = circuit_breaker_shield.failure_threshold * 2
no_of_failures = no_of_tries * circuit_breaker_shield.config.failure_threshold_percentage
no_of_success = no_of_tries - no_of_failures
- no_of_success.to_i.times { circuit_breaker_shield.call { sleep(0.1) } }
- no_of_failures.to_i.times { circuit_breaker_shield.call { sleep(2) } }
+ no_of_success.to_i.times { circuit_breaker_shield.protect { sleep(0.1) } }
+ no_of_failures.to_i.times { circuit_breaker_shield.protect { sleep(2) } }
sleep(1)
expect(circuit_breaker_shield.send :state).to be(CircuitBreaker::Shield::States::HALF_OPEN)
@@ -41,9 +41,9 @@ describe CircuitBreaker::Shield do
no_of_tries = circuit_breaker_shield.failure_threshold * 2
no_of_failures = no_of_tries * circuit_breaker_shield.config.failure_threshold_percentage
no_of_success = no_of_tries - no_of_failures
- no_of_success.to_i.times { circuit_breaker_shield.call { sleep(0.1) } }
+ no_of_success.to_i.times { circuit_breaker_shield.protect { sleep(0.1) } }
- expect { (no_of_failures.to_i + 1).times { circuit_breaker_shield.call { sleep(2) } } }.to(
+ expect { (no_of_failures.to_i + 1).times { circuit_breaker_shield.protect { sleep(2) } } }.to(
raise_error(CircuitBreaker::Open)
)
end
|
Rename call method to protect in Shield
|
scripbox_circuit_breaker-ruby
|
train
|
ebf70d9da604728f4fb692a208744f987eb810ab
|
diff --git a/src/parsimmon.js b/src/parsimmon.js
index <HASH>..<HASH> 100644
--- a/src/parsimmon.js
+++ b/src/parsimmon.js
@@ -97,6 +97,15 @@ Parsimmon.Parser = P(function(_, _super, Parser) {
});
};
+
+ var seqMap = Parsimmon.seqMap = function() {
+ var args = [].slice.call(arguments);
+ var mapper = args.pop();
+ return seq.apply(null, args).map(function(results) {
+ return mapper.apply(null, results);
+ });
+ };
+
/**
* Allows to add custom primitive parsers
*/
@@ -338,6 +347,14 @@ Parsimmon.Parser = P(function(_, _super, Parser) {
});
};
+ var oneOf = Parsimmon.oneOf = function(str) {
+ return test(function(ch) { return str.indexOf(ch) >= 0; });
+ };
+
+ var noneOf = Parsimmon.noneOf = function(str) {
+ return test(function(ch) { return str.indexOf(ch) < 0; });
+ };
+
var takeWhile = Parsimmon.takeWhile = function(predicate) {
return Parser(function(stream, i) {
var j = i;
|
add seqMap, oneOf, and noneOf
|
jneen_parsimmon
|
train
|
6a12e812cd948dfb2d1dd2a3430f54c367ab3c1a
|
diff --git a/src/collapse/Collapse.js b/src/collapse/Collapse.js
index <HASH>..<HASH> 100644
--- a/src/collapse/Collapse.js
+++ b/src/collapse/Collapse.js
@@ -22,6 +22,7 @@ export default class Collapse extends Component {
}
}
onItemClick(key) {
+ const { onChange } = this.props;
let activeKey = this.state.activeKey;
if (this.props.accordion) {
activeKey = activeKey[0] === key ? [] : [key];
@@ -35,7 +36,9 @@ export default class Collapse extends Component {
activeKey.push(key);
}
}
- this.setState({ activeKey });
+ this.setState({ activeKey }, () => {
+ onChange && onChange(activeKey, this.props)
+ });
}
render() {
const { prefixCls, className, children, accordion, bordered, activeKey, showArrow, ...resetProps } = this.props;
@@ -74,6 +77,7 @@ Collapse.propTypes = {
prefixCls: PropTypes.string,
accordion: PropTypes.bool,
showArrow: PropTypes.bool,
+ onChange: PropTypes.func,
activeKey: PropTypes.oneOfType([
PropTypes.string,
PropTypes.arrayOf(PropTypes.string),
|
Collapse component to add onChange event.
|
uiwjs_uiw
|
train
|
13b1275acc37c58f01e82e2ed5a893762ffb67fd
|
diff --git a/lib/parameters/param.rb b/lib/parameters/param.rb
index <HASH>..<HASH> 100644
--- a/lib/parameters/param.rb
+++ b/lib/parameters/param.rb
@@ -53,8 +53,9 @@ module Parameters
#
# Coerces a given value into a specific type.
#
- # @param [Class] type
- # The type to coerce the value into.
+ # @param [Class, Proc] type
+ # The type to coerce the value into. If a Proc is given, it will be
+ # called with the value to coerce.
#
# @param [Object] value
# The value to coerce.
@@ -87,6 +88,8 @@ module Parameters
coerce_array(Array,value).map do |element|
coerce_type(type.first,element)
end
+ elsif type.kind_of?(Proc)
+ type.call(value)
elsif (method_name = TYPE_COERSION[type])
self.send(method_name,type,value)
else
diff --git a/spec/class_param_spec.rb b/spec/class_param_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/class_param_spec.rb
+++ b/spec/class_param_spec.rb
@@ -166,6 +166,14 @@ describe Parameters::ClassParam do
param.value.should == false
end
+ it "should coerce values using a Proc for the type" do
+ coercion_logic = lambda { |x| x.to_i.floor }
+ param = Parameters::ClassParam.new(:x,coercion_logic)
+
+ param.value = 2.5
+ param.value.should == 2
+ end
+
it "should not coerce nil into a type" do
param = Parameters::ClassParam.new(:x,String)
obj1 = Object.new
diff --git a/spec/instance_param_spec.rb b/spec/instance_param_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/instance_param_spec.rb
+++ b/spec/instance_param_spec.rb
@@ -186,6 +186,14 @@ describe Parameters::InstanceParam do
param.value.should == false
end
+ it "should coerce values using a Proc for the type" do
+ coercion_logic = lambda { |x| x.to_i.floor }
+ param = Parameters::InstanceParam.new(@obj,:x,coercion_logic)
+
+ param.value = 2.5
+ param.value.should == 2
+ end
+
it "should not coerce nil into a type" do
param = Parameters::InstanceParam.new(@obj,:x,String)
|
Allow a proc to be given as the coercion type for Param#coerce_type.
|
postmodern_parameters
|
train
|
1a8d88e29b8593ea521c82a801578aa5929047d5
|
diff --git a/scapy/arch/__init__.py b/scapy/arch/__init__.py
index <HASH>..<HASH> 100644
--- a/scapy/arch/__init__.py
+++ b/scapy/arch/__init__.py
@@ -52,6 +52,7 @@ SOLARIS=sys.platform.startswith("sunos")
WINDOWS=sys.platform.startswith("win32")
X86_64 = not WINDOWS and (os.uname()[4] == 'x86_64')
+ARM_64 = not WINDOWS and (os.uname()[4] == 'aarch64')
# Next step is to import following architecture specific functions:
diff --git a/scapy/arch/linux.py b/scapy/arch/linux.py
index <HASH>..<HASH> 100644
--- a/scapy/arch/linux.py
+++ b/scapy/arch/linux.py
@@ -132,7 +132,7 @@ def attach_filter(s, filter):
# XXX. Argl! We need to give the kernel a pointer on the BPF,
# python object header seems to be 20 bytes. 36 bytes for x86 64bits arch.
- if scapy.arch.X86_64:
+ if scapy.arch.X86_64 or scapy.arch.ARM_64:
bpfh = struct.pack("HL", nb, id(bpf)+36)
else:
bpfh = struct.pack("HI", nb, id(bpf)+20)
@@ -282,7 +282,7 @@ def get_if(iff,cmd):
def get_if_index(iff):
return int(struct.unpack("I",get_if(iff, SIOCGIFINDEX)[16:20])[0])
-if os.uname()[4] == 'x86_64':
+if os.uname()[4] in [ 'x86_64', 'aarch64' ]:
def get_last_packet_timestamp(sock):
ts = ioctl(sock, SIOCGSTAMP, "1234567890123456")
s,us = struct.unpack("QQ",ts)
|
Support form arm<I>
--HG--
branch : Issue #<I>
|
secdev_scapy
|
train
|
23b6a7747948661029ace7fb80698109c4079bd8
|
diff --git a/tests/unit/core/oxshopTest.php b/tests/unit/core/oxshopTest.php
index <HASH>..<HASH> 100644
--- a/tests/unit/core/oxshopTest.php
+++ b/tests/unit/core/oxshopTest.php
@@ -133,12 +133,7 @@ class Unit_Core_oxshopTest extends OxidTestCase
public function testGetMultishopTablesDefaultNotSet()
{
$oShop = new oxShop();
- if (OXID_VERSION_EE) {
- $this->getConfig()->setConfigParam('aMultiShopTables', array('table1', 'table2'));
- $this->assertEquals(array('table1', 'table2'), $oShop->getMultiShopTables());
- } else {
$this->assertEquals(array(), $oShop->getMultiShopTables());
- }
}
|
code review: modified version checking, so it will be parsed out for different versions
|
OXID-eSales_oxideshop_ce
|
train
|
673f5f68a0232be6830b3186bf7cb1f140138e12
|
diff --git a/PySimpleGUIWx/PySimpleGUIWx.py b/PySimpleGUIWx/PySimpleGUIWx.py
index <HASH>..<HASH> 100644
--- a/PySimpleGUIWx/PySimpleGUIWx.py
+++ b/PySimpleGUIWx/PySimpleGUIWx.py
@@ -5746,14 +5746,8 @@ ScrolledTextBox = PopupScrolled
# Sets the icon to be used by default #
# ===================================================#
def SetGlobalIcon(icon):
- global _my_windows
-
- try:
- with open(icon, 'r') as icon_file:
- pass
- except:
- raise FileNotFoundError
- _my_windows.user_defined_icon = icon
+ if icon is not None:
+ Window.user_defined_icon = icon
return True
@@ -5804,7 +5798,8 @@ def SetOptions(icon=None, button_color=None, element_size=(None, None), button_e
global DEFAULT_INPUT_TEXT_COLOR
global DEFAULT_TOOLTIP_TIME
- Window.user_defined_icon = icon
+ if icon is not None:
+ Window.user_defined_icon = icon
if button_color != None:
DEFAULT_BUTTON_COLOR = button_color
@@ -6882,6 +6877,7 @@ def PopupGetText(message, title=None, default_text='', password_char='', size=(N
def main():
ChangeLookAndFeel('GreenTan')
+
layout = [
[Text('Welcome to PySimpleGUI!', font='Arial 15', text_color='red')],
[Text('You should be importing this module rather than running it', justification='l', size=(50, 1))],
|
Added check for None when setting icon using SetOptions
|
PySimpleGUI_PySimpleGUI
|
train
|
80a0687615a9ee6df59ca7d3d03a4e1af25234c9
|
diff --git a/eventsourcing/application.py b/eventsourcing/application.py
index <HASH>..<HASH> 100644
--- a/eventsourcing/application.py
+++ b/eventsourcing/application.py
@@ -284,23 +284,35 @@ class ProcessEvent:
self.aggregates: Dict[UUID, Aggregate] = {}
self.saved_kwargs: Dict[Any, Any] = {}
- def save(
+ def collect_events(
self,
- *aggregates: Optional[Union[Aggregate, AggregateEvent[Aggregate]]],
+ *objs: Optional[Union[Aggregate, AggregateEvent[Aggregate]]],
**kwargs: Any,
) -> None:
"""
Collects pending domain events from the given aggregate.
"""
- for aggregate in aggregates:
- if isinstance(aggregate, AggregateEvent):
- self.events.append(aggregate)
- elif isinstance(aggregate, Aggregate):
- self.aggregates[aggregate.id] = aggregate
- for event in aggregate.collect_events():
+ for obj in objs:
+ if isinstance(obj, AggregateEvent):
+ self.events.append(obj)
+ elif isinstance(obj, Aggregate):
+ self.aggregates[obj.id] = obj
+ for event in obj.collect_events():
self.events.append(event)
self.saved_kwargs.update(kwargs)
+ def save(
+ self,
+ *aggregates: Optional[Union[Aggregate, AggregateEvent[Aggregate]]],
+ **kwargs: Any,
+ ) -> None:
+ """
+ DEPRECATED, in favour of collect(). Will be removed in future version.
+
+ Collects pending domain events from the given aggregate.
+ """
+ self.collect_events(*aggregates, **kwargs)
+
class Application(ABC, Generic[TAggregate]):
"""
@@ -432,7 +444,7 @@ class Application(ABC, Generic[TAggregate]):
def save(
self,
- *aggregates: Optional[Union[TAggregate, AggregateEvent[Aggregate]]],
+ *objs: Optional[Union[TAggregate, AggregateEvent[Aggregate]]],
**kwargs: Any,
) -> Optional[int]:
"""
@@ -440,7 +452,7 @@ class Application(ABC, Generic[TAggregate]):
puts them in the application's event store.
"""
process_event = ProcessEvent()
- process_event.save(*aggregates, **kwargs)
+ process_event.collect_events(*objs, **kwargs)
returning = self.record(process_event)
self.take_snapshots(process_event)
self.notify(process_event.events)
diff --git a/eventsourcing/tests/test_processapplication.py b/eventsourcing/tests/test_processapplication.py
index <HASH>..<HASH> 100644
--- a/eventsourcing/tests/test_processapplication.py
+++ b/eventsourcing/tests/test_processapplication.py
@@ -81,7 +81,7 @@ class EmailNotifications(ProcessApplication):
subject="Your New Account",
message="Dear {}, ...".format(domain_event.full_name),
)
- process_event.save(notification)
+ process_event.collect_events(notification)
class PromptForwarder(Promptable):
diff --git a/eventsourcing/tests/test_processingpolicy.py b/eventsourcing/tests/test_processingpolicy.py
index <HASH>..<HASH> 100644
--- a/eventsourcing/tests/test_processingpolicy.py
+++ b/eventsourcing/tests/test_processingpolicy.py
@@ -16,11 +16,22 @@ def policy(domain_event, process_event: ProcessEvent):
subject="Your New Account",
message="Dear {}".format(domain_event.full_name),
)
- process_event.save(notification)
+ process_event.collect_events(notification)
+
+
+@singledispatch
+def policy_legacy_save(domain_event, process_event: ProcessEvent):
+ if isinstance(domain_event, BankAccount.Opened):
+ notification = EmailNotification.create(
+ to=domain_event.email_address,
+ subject="Your New Account",
+ message="Dear {}".format(domain_event.full_name),
+ )
+ process_event.collect_events(notification)
class TestProcessingPolicy(TestCase):
- def test(self):
+ def test_policy(self):
# Open an account.
account = BankAccount.open(
full_name="Alice",
@@ -44,6 +55,30 @@ class TestProcessingPolicy(TestCase):
EmailNotification.Created,
)
+ def test_legacy_save(self):
+ # Open an account.
+ account = BankAccount.open(
+ full_name="Alice",
+ email_address="alice@example.com",
+ )
+ events = account.collect_events()
+ created_event = events[0]
+
+ process_event = ProcessEvent(
+ tracking=Tracking(
+ application_name="upstream_app",
+ notification_id=5,
+ )
+ )
+
+ policy_legacy_save(created_event, process_event)
+
+ self.assertEqual(len(process_event.events), 1)
+ self.assertIsInstance(
+ process_event.events[0],
+ EmailNotification.Created,
+ )
+
class EmailNotification(Aggregate):
def __init__(self, to, subject, message):
|
Renamed ProcessEvent.collect_events(). Because save() is a bit strong.
|
johnbywater_eventsourcing
|
train
|
921c464b40f3068f17c4c8ab017e9b27d84fab07
|
diff --git a/externs/es6.js b/externs/es6.js
index <HASH>..<HASH> 100644
--- a/externs/es6.js
+++ b/externs/es6.js
@@ -718,10 +718,10 @@ IThenable.prototype.then = function(opt_onFulfilled, opt_onRejected) {};
/**
- * @see http://dom.spec.whatwg.org/#futures
+ * @see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-promise-objects
* @param {function(
- * function((TYPE|IThenable.<TYPE>|Thenable)),
- * function(*))} resolver
+ * function((TYPE|IThenable.<TYPE>|Thenable|null)=),
+ * function(*=))} resolver
* @constructor
* @implements {IThenable.<TYPE>}
* @template TYPE
|
Make the args to ES6 Promise resolve and reject optional.
This allows the following code to compile successfully:
var p = new Promise(
function(resolve, reject) {
if (someCondition) {
resolve();
} else {
reject();
}
});
-------------
Created by MOE: <URL>
|
google_closure-compiler
|
train
|
0417870325d54aad82942850c5cf4393ff3837d6
|
diff --git a/pymemcache/test/test_client_hash.py b/pymemcache/test/test_client_hash.py
index <HASH>..<HASH> 100644
--- a/pymemcache/test/test_client_hash.py
+++ b/pymemcache/test/test_client_hash.py
@@ -137,10 +137,11 @@ class TestHashClient(ClientTestMixin, unittest.TestCase):
client._get_client = get_clients
- result = client.set(b'key1', b'value1', noreply=False)
- result = client.set(b'key3', b'value2', noreply=False)
+ assert client.set(b'key1', b'value1', noreply=False) is True
+ assert client.set(b'key3', b'value2', noreply=False) is True
result = client.gets_many([b'key1', b'key3'])
- assert result == {b'key1': (b'value1', b'1'), b'key3': (b'value2', b'1')}
+ assert (result ==
+ {b'key1': (b'value1', b'1'), b'key3': (b'value2', b'1')})
def test_no_servers_left(self):
from pymemcache.client.hash import HashClient
|
Introduce some missing .set() assertions
Also wrap a line that exceeds <I> characters.
|
pinterest_pymemcache
|
train
|
1da4a6d98b0f679b639af388c9a25222887c68d4
|
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index <HASH>..<HASH> 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -725,6 +725,7 @@ Performance Improvements
Bug Fixes
~~~~~~~~~
+- Bug in incorrection computation of ``.mean()`` on ``timedelta64[ns]`` because of overflow (:issue:`9442`)
- Bug in ``DataFrame.to_html(index=False)`` renders unnecessary ``name`` row (:issue:`10344`)
- Bug in ``DataFrame.apply`` when function returns categorical series. (:issue:`9573`)
- Bug in ``to_datetime`` with invalid dates and formats supplied (:issue:`10154`)
diff --git a/pandas/core/common.py b/pandas/core/common.py
index <HASH>..<HASH> 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -63,6 +63,7 @@ _DATELIKE_DTYPES = set([np.dtype(t) for t in ['M8[ns]', '<M8[ns]', '>M8[ns]',
_int8_max = np.iinfo(np.int8).max
_int16_max = np.iinfo(np.int16).max
_int32_max = np.iinfo(np.int32).max
+_int64_max = np.iinfo(np.int64).max
# define abstract base classes to enable isinstance type checking on our
# objects
diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index <HASH>..<HASH> 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -21,7 +21,8 @@ from pandas.core.common import (isnull, notnull, _values_from_object,
is_bool_dtype, is_object_dtype,
is_datetime64_dtype, is_timedelta64_dtype,
is_datetime_or_timedelta_dtype, _get_dtype,
- is_int_or_datetime_dtype, is_any_int_dtype)
+ is_int_or_datetime_dtype, is_any_int_dtype,
+ _int64_max)
class disallow(object):
@@ -145,7 +146,7 @@ def _get_fill_value(dtype, fill_value=None, fill_value_typ=None):
else:
if fill_value_typ == '+inf':
# need the max int here
- return np.iinfo(np.int64).max
+ return _int64_max
else:
return tslib.iNaT
@@ -223,7 +224,12 @@ def _wrap_results(result, dtype):
result = result.view(dtype)
elif is_timedelta64_dtype(dtype):
if not isinstance(result, np.ndarray):
- result = lib.Timedelta(result)
+
+ # raise if we have a timedelta64[ns] which is too large
+ if np.fabs(result) > _int64_max:
+ raise ValueError("overflow in timedelta operation")
+
+ result = lib.Timedelta(result, unit='ns')
else:
result = result.astype('i8').view(dtype)
@@ -247,6 +253,8 @@ def nansum(values, axis=None, skipna=True):
dtype_sum = dtype_max
if is_float_dtype(dtype):
dtype_sum = dtype
+ elif is_timedelta64_dtype(dtype):
+ dtype_sum = np.float64
the_sum = values.sum(axis, dtype=dtype_sum)
the_sum = _maybe_null_out(the_sum, axis, mask)
@@ -260,7 +268,7 @@ def nanmean(values, axis=None, skipna=True):
dtype_sum = dtype_max
dtype_count = np.float64
- if is_integer_dtype(dtype):
+ if is_integer_dtype(dtype) or is_timedelta64_dtype(dtype):
dtype_sum = np.float64
elif is_float_dtype(dtype):
dtype_sum = dtype
diff --git a/pandas/tseries/tests/test_timedeltas.py b/pandas/tseries/tests/test_timedeltas.py
index <HASH>..<HASH> 100644
--- a/pandas/tseries/tests/test_timedeltas.py
+++ b/pandas/tseries/tests/test_timedeltas.py
@@ -686,6 +686,25 @@ class TestTimedeltas(tm.TestCase):
s = Series([Timestamp('2015-02-03'), Timestamp('2015-02-07'), Timestamp('2015-02-15')])
self.assertEqual(s.diff().median(), timedelta(days=6))
+ def test_overflow(self):
+ # GH 9442
+ s = Series(pd.date_range('20130101',periods=100000,freq='H'))
+ s[0] += pd.Timedelta('1s 1ms')
+
+ # mean
+ result = (s-s.min()).mean()
+ expected = pd.Timedelta((pd.DatetimeIndex((s-s.min())).asi8/len(s)).sum())
+
+ # the computation is converted to float so might be some loss of precision
+ self.assertTrue(np.allclose(result.value/1000, expected.value/1000))
+
+ # sum
+ self.assertRaises(ValueError, lambda : (s-s.min()).sum())
+ s1 = s[0:10000]
+ self.assertRaises(ValueError, lambda : (s1-s1.min()).sum())
+ s2 = s[0:1000]
+ result = (s2-s2.min()).sum()
+
def test_timedelta_ops_scalar(self):
# GH 6808
base = pd.to_datetime('20130101 09:01:12.123456')
|
BUG: Bug in incorrection computation of .mean() on timedelta<I>[ns] because of overflow #<I>
|
pandas-dev_pandas
|
train
|
9df54949fbfe3f5468b50a6e54dc4381b0d92ab0
|
diff --git a/lib/Model/Table.php b/lib/Model/Table.php
index <HASH>..<HASH> 100644
--- a/lib/Model/Table.php
+++ b/lib/Model/Table.php
@@ -147,7 +147,7 @@ class Model_Table extends Model {
/**/$this->api->pr->start('selectQuery/getActualF');
- $actual_fields=$fields?:$this->actual_fields?:$this->getActualFields();
+ $actual_fields=$fields?:$this->getActualFields();
$this->_selectQuery=$select=$this->_dsql()->del('fields');
|
Model_Table: small fix
This checking is also done in Model->getActualFields, so there's no need to do this two times.
|
atk4_atk4
|
train
|
acc1a60fba3f3fd4d02efb20ee10dc79bce39390
|
diff --git a/qbit/core/src/test/java/io/advantageous/qbit/service/ServiceBundleAndEvents.java b/qbit/core/src/test/java/io/advantageous/qbit/service/ServiceBundleAndEvents.java
index <HASH>..<HASH> 100644
--- a/qbit/core/src/test/java/io/advantageous/qbit/service/ServiceBundleAndEvents.java
+++ b/qbit/core/src/test/java/io/advantageous/qbit/service/ServiceBundleAndEvents.java
@@ -69,21 +69,21 @@ public class ServiceBundleAndEvents extends TimedTesting {
testService.method1("HELLO");
testService.clientProxyFlush();
- waitForTrigger(4, o -> (method.get() != null) &&
+ waitForTrigger(1, o -> (method.get() != null) &&
method.get().equals("method1 HELLO"));
assertEquals("method1 HELLO\n", method.get());
sender.event("EVENT 1");
+ sender.clientProxyFlush();
- waitForTrigger(4, o -> (event.get() != null) &&
+ waitForTrigger(1, o -> (event.get() != null) &&
event.get().equals("GOT EVENT EVENT 1\n"));
assertEquals("GOT EVENT EVENT 1\n", event.get());
- sender.event("EVENT 2");
}
@@ -109,16 +109,16 @@ public class ServiceBundleAndEvents extends TimedTesting {
public class TestServiceImpl implements EventChannel1 {
public void method1(String arg) {
-
- method.set(sputs("method1", arg));
puts("method1", arg);
+ method.set(sputs("method1", arg));
}
@Override
public void event(String arg) {
- event.set(sputs("GOT EVENT", arg));
puts("GOT EVENT", arg);
+ event.set(sputs("GOT EVENT", arg));
+
}
}
}
diff --git a/qbit/core/src/test/java/io/advantageous/qbit/service/ServiceQueueErrorHandlingTest.java b/qbit/core/src/test/java/io/advantageous/qbit/service/ServiceQueueErrorHandlingTest.java
index <HASH>..<HASH> 100644
--- a/qbit/core/src/test/java/io/advantageous/qbit/service/ServiceQueueErrorHandlingTest.java
+++ b/qbit/core/src/test/java/io/advantageous/qbit/service/ServiceQueueErrorHandlingTest.java
@@ -86,7 +86,7 @@ public class ServiceQueueErrorHandlingTest {
public void process() {
if (forceError) {
- throw new RuntimeException();
+ throw new RuntimeException("Exception was thrown on purpose");
}
}
|
cranky old test is giving me trouble
|
advantageous_qbit
|
train
|
b87c14d8f26a0b069f0ffa87e1afd830e2a8b428
|
diff --git a/events.go b/events.go
index <HASH>..<HASH> 100644
--- a/events.go
+++ b/events.go
@@ -43,9 +43,6 @@ type MessageEvent int
* depending on the message events. All the events only require an opdata,
* the event, and the context. The message and err will be NULL except for
* some events (see below). The possible events are:
- * - OTRL_MSGEVENT_ENCRYPTION_ERROR
- * An error occured while encrypting a message and the message
- * was not sent.
* - OTRL_MSGEVENT_MSG_RESENT
* The previous message was resent.
* - OTRL_MSGEVENT_RCVDMSG_NOT_IN_PRIVATE
@@ -63,7 +60,8 @@ const (
// MessageEventEncryptionRequired is signaled when our policy requires encryption bt we are trying to send an unencrypted message
MessageEventEncryptionRequired MessageEvent = iota
- // MessageEventEncryptionError
+ // MessageEventEncryptionError is signaled when an error occured while encrypting a message and the message was not sent
+ MessageEventEncryptionError
// MessageEventConnectionEnded is signaled when we are asked to send a message but the peer has ended the private conversation. At this point the connection should be closed or refreshed
MessageEventConnectionEnded
@@ -213,3 +211,7 @@ func messageEventReceivedUnrecognizedMessage(c *Conversation) {
func messageEventReceivedMessageForOtherInstance(c *Conversation) {
c.getEventHandler().HandleMessageEvent(MessageEventReceivedMessageForOtherInstance, nil, nil)
}
+
+func messageEventEncryptionError(c *Conversation) {
+ c.getEventHandler().HandleMessageEvent(MessageEventEncryptionError, nil, nil)
+}
diff --git a/send.go b/send.go
index <HASH>..<HASH> 100644
--- a/send.go
+++ b/send.go
@@ -18,7 +18,11 @@ func (c *Conversation) Send(msg ValidMessage) ([]ValidMessage, error) {
}
return []ValidMessage{msg}, nil
case encrypted:
- return c.createSerializedDataMessage(msg, messageFlagNormal, []tlv{})
+ result, err := c.createSerializedDataMessage(msg, messageFlagNormal, []tlv{})
+ if err != nil {
+ messageEventEncryptionError(c)
+ }
+ return result, err
case finished:
messageEventConnectionEnded(c)
return nil, errors.New("otr: cannot send message because secure conversation has finished")
diff --git a/send_test.go b/send_test.go
index <HASH>..<HASH> 100644
--- a/send_test.go
+++ b/send_test.go
@@ -56,3 +56,16 @@ func Test_Send_signalsMessageEventIfTryingToSendOnAFinishedChannel(t *testing.T)
c.Send(m)
}, MessageEventConnectionEnded, nil, nil)
}
+
+func Test_Send_signalsEncryptionErrorMessageEventIfSomethingWentWrong(t *testing.T) {
+ msg := []byte("hello")
+
+ c := bobContextAfterAKE()
+ c.msgState = encrypted
+ c.Policies = policies(allowV3)
+ c.keys.theirKeyID = 0
+
+ c.expectMessageEvent(t, func() {
+ c.Send(msg)
+ }, MessageEventEncryptionError, nil, nil)
+}
|
Add support for Message Event Encryption Error (#<I>)
|
coyim_otr3
|
train
|
6619f7daa7f3c6daa5c1ba72d9c41f5d6492d0f6
|
diff --git a/test/tc_help.rb b/test/tc_help.rb
index <HASH>..<HASH> 100644
--- a/test/tc_help.rb
+++ b/test/tc_help.rb
@@ -58,7 +58,7 @@ class TC_testHelp < Clean::Test::TestCase
}
end
- test_that "the help command can be configured to skip things declaratively regardless of when it the object was created" do
+ test_that "the help command can be configured to skip things declaratively regardless of when the object was created" do
Given {
GLI::Commands::Help.skips_pre = false
GLI::Commands::Help.skips_post = false
|
Removed spurious word in a unit test description
|
davetron5000_gli
|
train
|
82ea3fa0201b6f048975df4b7c88da1b2bddc787
|
diff --git a/genkeys.go b/genkeys.go
index <HASH>..<HASH> 100644
--- a/genkeys.go
+++ b/genkeys.go
@@ -114,7 +114,7 @@ const uiKeysGlfwTmpl = `{{.License}}
package ui
import (
- glfw "github.com/go-gl/glfw3"
+ glfw "github.com/go-gl/glfw/v3.0/glfw"
)
var glfwKeyCodeToKey = map[glfw.Key]Key{
diff --git a/internal/graphics/internal/opengl/context.go b/internal/graphics/internal/opengl/context.go
index <HASH>..<HASH> 100644
--- a/internal/graphics/internal/opengl/context.go
+++ b/internal/graphics/internal/opengl/context.go
@@ -19,7 +19,7 @@ package opengl
import (
"errors"
"fmt"
- "github.com/go-gl/glow/gl-core/3.2/gl"
+ "github.com/go-gl/gl/v3.2-core/gl"
)
type Texture uint32
diff --git a/internal/ui/input_glfw.go b/internal/ui/input_glfw.go
index <HASH>..<HASH> 100644
--- a/internal/ui/input_glfw.go
+++ b/internal/ui/input_glfw.go
@@ -17,7 +17,7 @@
package ui
import (
- glfw "github.com/go-gl/glfw3"
+ glfw "github.com/go-gl/glfw/v3.0/glfw"
"math"
)
diff --git a/internal/ui/keys_glfw.go b/internal/ui/keys_glfw.go
index <HASH>..<HASH> 100644
--- a/internal/ui/keys_glfw.go
+++ b/internal/ui/keys_glfw.go
@@ -19,7 +19,7 @@
package ui
import (
- glfw "github.com/go-gl/glfw3"
+ glfw "github.com/go-gl/glfw/v3.0/glfw"
)
var glfwKeyCodeToKey = map[glfw.Key]Key{
diff --git a/internal/ui/ui_glfw.go b/internal/ui/ui_glfw.go
index <HASH>..<HASH> 100644
--- a/internal/ui/ui_glfw.go
+++ b/internal/ui/ui_glfw.go
@@ -18,7 +18,7 @@ package ui
import (
"fmt"
- glfw "github.com/go-gl/glfw3"
+ glfw "github.com/go-gl/glfw/v3.0/glfw"
"runtime"
"time"
)
|
#<I>: Fix import paths (Use go-gl/gl and go-gl/glfw instead of go-gl/glow and go-gl/glfw3
|
hajimehoshi_ebiten
|
train
|
7ab1a3935a2d1fb68a9c9da557e58cf3419c548b
|
diff --git a/lib/helper/Nightmare.js b/lib/helper/Nightmare.js
index <HASH>..<HASH> 100644
--- a/lib/helper/Nightmare.js
+++ b/lib/helper/Nightmare.js
@@ -480,6 +480,19 @@ class Nightmare extends Helper {
stringIncludes('HTML source of a page').negate(text, source);
}
+ /**
+ * asserts that an element appears a given number of times in the DOM
+ * Element is located by label or name or CSS or XPath.
+ *
+ * ```js
+ * I.seeNumberOfElements('#submitBtn', 1);
+ * ```
+ */
+ async seeNumberOfElements(selector, num) {
+ const elements = await this._locate(selector);
+ return equals(`expected number of elements (${selector}) is ${num}, but found ${elements.length}`).assert(elements.length, num);
+ }
+
/**
* {{> ../webapi/click }}
diff --git a/test/helper/Nightmare_test.js b/test/helper/Nightmare_test.js
index <HASH>..<HASH> 100644
--- a/test/helper/Nightmare_test.js
+++ b/test/helper/Nightmare_test.js
@@ -156,4 +156,9 @@ describe('Nightmare', function () {
assert.equal(url, nextUrl);
});
});
+
+ describe('#seeNumberOfElements', () => {
+ it('should return 1 as count', () => I.amOnPage('/')
+ .then(() => I.seeNumberOfElements('#area1', 1)));
+ });
});
|
Added I.seeNumberOfElements() to Nightmare helper (#<I>)
|
Codeception_CodeceptJS
|
train
|
2d19dd99aa534d41a60667a14f9d8db10e6cb083
|
diff --git a/pipe.go b/pipe.go
index <HASH>..<HASH> 100644
--- a/pipe.go
+++ b/pipe.go
@@ -28,13 +28,18 @@ func (p *PipeReader) Close() error {
// NewPipeReader creates a new in-memory reader that reads from all loggers
// The caller must call Close on the returned reader when done.
+//
+// By default, it:
+//
+// 1. Logs JSON.
+// 2. Logs at the Debug level. However, unless SetLogLevel is called on a
+// subsystem logger to decrease the default log level, for that subsystem,
+// only error messages will be logged.
func NewPipeReader(opts ...PipeReaderOption) *PipeReader {
- loggerMutex.Lock()
opt := pipeReaderOptions{
- format: defaultFormat,
+ format: JSONOutput,
level: LevelDebug,
}
- loggerMutex.Unlock()
for _, o := range opts {
o.setOption(&opt)
|
fix: log with the JSON format by default and avoid taking a lock.
This seems like the most reasonable default. We no longer need to take a lock to
read the global log level, so we might as well drop the lock entirely.
|
ipfs_go-log
|
train
|
ecafc99d15fbd79e5526315bcddab65fc583aa6a
|
diff --git a/plugins/CoreHome/javascripts/corehome.js b/plugins/CoreHome/javascripts/corehome.js
index <HASH>..<HASH> 100755
--- a/plugins/CoreHome/javascripts/corehome.js
+++ b/plugins/CoreHome/javascripts/corehome.js
@@ -149,7 +149,7 @@
}
loading.hide();
- report.html($(response)).css('display', 'inline-block');
+ report.css('display', 'inline-block').html($(response));
// scroll to report
piwikHelper.lazyScrollTo(report, 400);
|
fixes #<I> make sure content is visible before updating the report otherwise the dataTable.js handler might not work correct
|
matomo-org_matomo
|
train
|
d66b8375108f77988437f1f9f7f20e15ed8d0816
|
diff --git a/isort/settings.py b/isort/settings.py
index <HASH>..<HASH> 100644
--- a/isort/settings.py
+++ b/isort/settings.py
@@ -30,6 +30,8 @@ from collections import namedtuple
from pies import *
+MAX_CONFIG_SEARCH_DEPTH = 20 # The number '..' directories isort will look for config file within
+
WrapModes = ('GRID', 'VERTICAL', 'HANGING_INDENT', 'VERTICAL_HANGING_INDENT', 'VERTICAL_GRID', 'VERTICAL_GRID_GROUPED')
WrapModes = namedtuple('WrapModes', WrapModes)(*range(len(WrapModes)))
@@ -67,7 +69,20 @@ default = {'force_to_top': [],
try:
from configparser import SafeConfigParser
- with open(os.path.expanduser('~/.isort.cfg')) as config_file:
+ isort_config_file = '~/.isort.cfg'
+
+ tries = 0
+ current_directory = os.getcwd()
+ while current_directory and tries < MAX_CONFIG_SEARCH_DEPTH:
+ potential_path = os.path.join(current_directory, "isort.cfg")
+ if os.path.exists(potential_path):
+ isort_config_file = potential_path
+ break
+
+ current_directory = path.split()[0]
+ tries += 1
+
+ with open(os.path.expanduser(isort_config_file)) as config_file:
config = SafeConfigParser()
config.readfp(config_file)
settings = dict(config.items('settings'))
|
Add initial support for project level configs, fixing issue #<I>
|
timothycrosley_isort
|
train
|
6c40441c2240c695fd25b819fe50e3c0fe6af372
|
diff --git a/pyipmi/hpm.py b/pyipmi/hpm.py
index <HASH>..<HASH> 100644
--- a/pyipmi/hpm.py
+++ b/pyipmi/hpm.py
@@ -258,26 +258,26 @@ class Hpm(object):
def get_upgrade_version_from_file(filename):
image = UpgradeImage(filename)
for action in image.actions:
- if type(action) == UpgradeActionRecordUploadForUpgrade:
+ if isinstance(action, UpgradeActionRecordUploadForUpgrade):
return action.firmware_version
return None
@staticmethod
def _do_upgrade_action_backup(image):
for action in image.actions:
- if type(action) == UpgradeActionRecordBackup:
+ if isinstance(action, UpgradeActionRecordBackup):
pass
@staticmethod
def _do_upgrade_action_prepare(image):
for action in image.actions:
- if type(action) == UpgradeActionRecordPrepare:
+ if isinstance(action, UpgradeActionRecordPrepare):
print("do ACTION_PREPARE_COMPONENT")
@staticmethod
def _do_upgrade_action_upload(image):
for action in image.actions:
- if type(action) == UpgradeActionRecordUploadForUpgrade:
+ if isinstance(action, UpgradeActionRecordUploadForUpgrade):
print("do ACTION_UPLOAD_FOR_UPGRADE")
def preparation_stage(self, image):
@@ -319,7 +319,7 @@ class Hpm(object):
if action.components & (1 << component) == 0:
continue
self.initiate_upgrade_action_and_wait(1 << component, action.action_type)
- if type(action) == UpgradeActionRecordUploadForUpgrade:
+ if isinstance(action, UpgradeActionRecordUploadForUpgrade):
self.upload_binary(action.firmware_image_data)
self.finish_upload_and_wait(component, action.firmware_length)
|
change use of type() to isnstance()
|
kontron_python-ipmi
|
train
|
46295345ebc148944ec1746f5d883389547ef16a
|
diff --git a/src/FieldHandlers/FileFieldHandler.php b/src/FieldHandlers/FileFieldHandler.php
index <HASH>..<HASH> 100644
--- a/src/FieldHandlers/FileFieldHandler.php
+++ b/src/FieldHandlers/FileFieldHandler.php
@@ -29,7 +29,7 @@ class FileFieldHandler extends BaseFieldHandler
if (empty($data)) {
$result = $this->_renderInput($field);
} else {
- $result = $this->_renderInputWithValue($field);
+ $result = $this->_renderInputWithValue($table, $field, $data);
}
return $result;
@@ -59,7 +59,7 @@ class FileFieldHandler extends BaseFieldHandler
* @param string $field name
* @return string HTML input field with data attribute.
*/
- protected function _renderInputWithValue($field)
+ protected function _renderInputWithValue($table, $field, $data)
{
$cakeView = new AppView();
$cakeView->loadHelper(
|
Required params (task #<I>)
|
QoboLtd_cakephp-csv-migrations
|
train
|
61ba7bf413384fe9b6674a2c4518985bdf730ac2
|
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index <HASH>..<HASH> 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2417,17 +2417,18 @@ class DataFrame(NDFrame):
Notes
-----
- * To select all *numeric* types use the numpy dtype ``numpy.number``
+ * To select all *numeric* types, use ``np.number`` or ``'number'``
* To select strings you must use the ``object`` dtype, but note that
this will return *all* object dtype columns
* See the `numpy dtype hierarchy
<http://docs.scipy.org/doc/numpy/reference/arrays.scalars.html>`__
- * To select datetimes, use np.datetime64, 'datetime' or 'datetime64'
- * To select timedeltas, use np.timedelta64, 'timedelta' or
- 'timedelta64'
- * To select Pandas categorical dtypes, use 'category'
- * To select Pandas datetimetz dtypes, use 'datetimetz' (new in 0.20.0),
- or a 'datetime64[ns, tz]' string
+ * To select datetimes, use ``np.datetime64``, ``'datetime'`` or
+ ``'datetime64'``
+ * To select timedeltas, use ``np.timedelta64``, ``'timedelta'`` or
+ ``'timedelta64'``
+ * To select Pandas categorical dtypes, use ``'category'``
+ * To select Pandas datetimetz dtypes, use ``'datetimetz'`` (new in
+ 0.20.0) or ``'datetime64[ns, tz]'``
Examples
--------
@@ -2436,12 +2437,12 @@ class DataFrame(NDFrame):
... 'c': [1.0, 2.0] * 3})
>>> df
a b c
- 0 0.3962 True 1
- 1 0.1459 False 2
- 2 0.2623 True 1
- 3 0.0764 False 2
- 4 -0.9703 True 1
- 5 -1.2094 False 2
+ 0 0.3962 True 1.0
+ 1 0.1459 False 2.0
+ 2 0.2623 True 1.0
+ 3 0.0764 False 2.0
+ 4 -0.9703 True 1.0
+ 5 -1.2094 False 2.0
>>> df.select_dtypes(include='bool')
c
0 True
@@ -2452,12 +2453,12 @@ class DataFrame(NDFrame):
5 False
>>> df.select_dtypes(include=['float64'])
c
- 0 1
- 1 2
- 2 1
- 3 2
- 4 1
- 5 2
+ 0 1.0
+ 1 2.0
+ 2 1.0
+ 3 2.0
+ 4 1.0
+ 5 2.0
>>> df.select_dtypes(exclude=['floating'])
b
0 True
|
DOC: Improve DataFrame.select_dtypes examples (#<I>)
|
pandas-dev_pandas
|
train
|
d6026eb0f4c7db98cc676dab119f8c4715775f6a
|
diff --git a/src/FormLabel.js b/src/FormLabel.js
index <HASH>..<HASH> 100644
--- a/src/FormLabel.js
+++ b/src/FormLabel.js
@@ -59,20 +59,20 @@ const FormLabel = React.forwardRef(
column && 'col-form-label',
);
- if (column) return <Col {...props} className={classes} as="label" />;
-
warning(
controlId == null || !htmlFor,
'`controlId` is ignored on `<FormLabel>` when `htmlFor` is specified.',
);
+ htmlFor = htmlFor || controlId;
+
+ if (column)
+ return (
+ <Col as="label" className={classes} htmlFor={htmlFor} {...props} />
+ );
+
return (
// eslint-disable-next-line jsx-a11y/label-has-for, jsx-a11y/label-has-associated-control
- <label
- {...props}
- htmlFor={htmlFor || controlId}
- ref={ref}
- className={classes}
- />
+ <label ref={ref} className={classes} htmlFor={htmlFor} {...props} />
);
},
);
diff --git a/test/FormLabelSpec.js b/test/FormLabelSpec.js
index <HASH>..<HASH> 100644
--- a/test/FormLabelSpec.js
+++ b/test/FormLabelSpec.js
@@ -27,6 +27,13 @@ describe('<FormLabel>', () => {
</FormLabel>,
).assertSingle('label.col-sm-4.col-form-label');
});
+ it('should use controlId for htmlFor when render as Col', () => {
+ mount(
+ <FormGroup controlId="foo">
+ <FormLabel column sm={4} />
+ </FormGroup>,
+ ).assertSingle('label[htmlFor="foo"].col-sm-4.col-form-label');
+ });
it('should respect srOnly', () => {
mount(<FormLabel srOnly>Label</FormLabel>).assertSingle(
|
Add htmlFor to label when rendered as column (#<I>)
* Add htmlFor to label when rendered as column
* Compute value for htmlFor at one place in FormLabel
* Change props order when rendering FormLabel
|
react-bootstrap_react-bootstrap
|
train
|
80d8476bc5db87d60a0f1ad772a099ba0c54177a
|
diff --git a/src/preloadjs/ImageLoader.js b/src/preloadjs/ImageLoader.js
index <HASH>..<HASH> 100644
--- a/src/preloadjs/ImageLoader.js
+++ b/src/preloadjs/ImageLoader.js
@@ -47,6 +47,7 @@ this.createjs = this.createjs||{};
this._tagSrcAttribute = "src";
this._tag = document.createElement("img");
+ this._tag.style.visibility = "hidden";
this.on("initialize", this._updateXHR, this);
this.resultFormatter = this._formatResult;
@@ -86,10 +87,11 @@ this.createjs = this.createjs||{};
};
p._formatResult = function(loader) {
+ var URL = window.URL || window.webkitURL;
if (!this._useXHR) {
document.body.removeChild(loader.getTag());
- } else if (window.URL && window.URL.createObjectURL) {
- var objURL = window.URL.createObjectURL(loader.getResult(true));
+ } else if (URL) {
+ var objURL = URL.createObjectURL(loader.getResult(true));
this._tag.src = objURL;
this._tag.onLoad = function() {
window.URL.revokeObjectURL(this.src);
@@ -98,6 +100,7 @@ this.createjs = this.createjs||{};
loader.getTag().src = loader.getItem().src;
}
+ this._tag.style.visibility = "visible";
return this._tag;
};
|
Correctly toggling image tag visibility. Added window.webkitURL for older browser support.
|
CreateJS_PreloadJS
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.