hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
26a4d445e84d4337b38e97cd339ea10587880523
diff --git a/tchannel/tornado/dispatch.py b/tchannel/tornado/dispatch.py index <HASH>..<HASH> 100644 --- a/tchannel/tornado/dispatch.py +++ b/tchannel/tornado/dispatch.py @@ -112,7 +112,7 @@ class RequestDispatcher(object): self.handle_call(req, connection) except TChannelError as e: - log.warn('Received a bad request.', exc_info=True) + log.warning('Received a bad request.', exc_info=True) if req: e.tracing = req.tracing connection.send_error(e)
Fixing deprecated warn method
uber_tchannel-python
train
d716517fe89ff9dcbca76d0b9c200778b8de59f1
diff --git a/h2o-persist-hdfs/src/test/java/water/persist/PersistS3HdfsTest.java b/h2o-persist-hdfs/src/test/java/water/persist/PersistS3HdfsTest.java index <HASH>..<HASH> 100644 --- a/h2o-persist-hdfs/src/test/java/water/persist/PersistS3HdfsTest.java +++ b/h2o-persist-hdfs/src/test/java/water/persist/PersistS3HdfsTest.java @@ -1,5 +1,10 @@ package water.persist; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.fs.s3.S3FileSystem; +import org.jets3t.service.S3Service; +import org.jets3t.service.model.S3Object; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Rule; @@ -7,31 +12,54 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import water.H2O; import water.TestUtil; +import water.util.ReflectionUtils; import java.net.URI; -import static junit.framework.TestCase.assertTrue; -import static org.hamcrest.Matchers.endsWith; +import static junit.framework.TestCase.assertFalse; +import static junit.framework.TestCase.assertNotNull; public class PersistS3HdfsTest extends TestUtil { @BeforeClass - public static void setup() { stall_till_cloudsize(1); } + public static void setup() { + stall_till_cloudsize(1); + } @Rule public ExpectedException thrown = ExpectedException.none(); @Test - @Ignore - public void testPubDev5663() { // Demonstrates that S3FileSystem is broken - thrown.expect(water.api.HDFSIOException.class); - thrown.expectMessage(endsWith("java.io.IOException: /smalldata/airlines/AirlinesTrain.csv.zip doesn't exist")); // should not start with a slash!!! + public void testPubDev5663() throws Exception { // Demonstrates that S3FileSystem is broken + final String bucket = "h2o-public-test-data"; + final String key = "smalldata/airlines/AirlinesTrain.csv.zip"; + + PersistHdfs hdfsPersist = (PersistHdfs) H2O.getPM().getPersistForURI(URI.create("hdfs://localhost/")); + + String existing = "s3://" + bucket + "/" + key; + Path p = new Path(existing); - Persist hdfsPersist = H2O.getPM().getPersistForURI(URI.create("hdfs://localhost/")); + S3FileSystem fs = (S3FileSystem) FileSystem.get(p.toUri(), PersistHdfs.CONF); + // use crazy reflection to get to the actual S3 Service instance + S3Service s3Service = (S3Service) getValue(fs, "store", "h", "proxyDescriptor", "fpp", "proxy", "s3Service"); + + S3Object s3Object = s3Service.getObject(bucket, key); + assertNotNull(s3Object); // The object exists + assertFalse(fs.exists(p)); // But FS says it doesn't => S3 is broken in Hadoop + assertFalse(hdfsPersist.exists(existing)); // Our persist gives the same result + } - String existing = "s3://h2o-public-test-data/smalldata/airlines/AirlinesTrain.csv.zip"; - assertTrue(hdfsPersist.exists(existing)); + private Object getValue(Object o, String... fieldNames) { + StringBuilder path = new StringBuilder(o.getClass().getName()); + for (String f : fieldNames) { + path.append('.').append(f); + Object no = ReflectionUtils.getFieldValue(o, f); + if (no == null) + throw new IllegalStateException("Invalid path: " + path.toString() + ", object is instance of " + o.getClass()); + o = no; + } + return o; } }
PUBDEV-<I>: Demonstrates that S3 is broken in Hadoop (#<I>) * PUBDEV-<I>: Demonstrates that S3 is broken in Hadoop
h2oai_h2o-3
train
77e6c72ca7d6981f4022302a3c426db15f0821a8
diff --git a/src/Reform/EventListener/HoneypotListener.php b/src/Reform/EventListener/HoneypotListener.php index <HASH>..<HASH> 100644 --- a/src/Reform/EventListener/HoneypotListener.php +++ b/src/Reform/EventListener/HoneypotListener.php @@ -26,7 +26,7 @@ class HoneypotListener implements EventSubscriberInterface protected $form_field; protected $form_label; - public function __construct($throw_exception = false, $form_field = 'rating', $form_label = 'Do not complete this field') + public function __construct($form_field = 'rating', $form_label = 'Do not complete this field', $throw_exception = false) { $this->throw_exception = $throw_exception; $this->form_field = $form_field; diff --git a/tests/Reform/Tests/EventListener/HoneypotListenerTest.php b/tests/Reform/Tests/EventListener/HoneypotListenerTest.php index <HASH>..<HASH> 100644 --- a/tests/Reform/Tests/EventListener/HoneypotListenerTest.php +++ b/tests/Reform/Tests/EventListener/HoneypotListenerTest.php @@ -40,7 +40,7 @@ class HoneypotListenerTest extends \PHPUnit_Framework_TestCase public function testSpecifiedFieldIsAppliedToForm() { - $this->listener = new HoneypotListener(false, 'foo'); + $this->listener = new HoneypotListener('foo'); $this->assertNull($this->form->getTag(HoneypotListener::ROW)); $this->listener->onFormCreate($this->newEvent()); $this->assertSame('foo', $this->form->getTag(HoneypotListener::ROW)); @@ -78,7 +78,7 @@ class HoneypotListenerTest extends \PHPUnit_Framework_TestCase public function testHoneypotCaughtThrowException() { - $listener = new HoneypotListener(true); + $listener = new HoneypotListener('rating', 'Do not complete', true); //to pass into function scope for PHP 5.3 $form = $this->form;
Changing the order of HoneypotListener#__construct(). This is consistent with CsrfListener.
glynnforrest_reform
train
2aa877302735b083d5231a34ee3637ffc960d125
diff --git a/shared/local-debug.desktop.js b/shared/local-debug.desktop.js index <HASH>..<HASH> 100644 --- a/shared/local-debug.desktop.js +++ b/shared/local-debug.desktop.js @@ -26,6 +26,7 @@ let config: {[key: string]: any} = { printOutstandingRPCs: false, printRPC: false, printRoutes: false, + filterActionLogs: null, reactPerf: false, redirectOnLogout: true, reduxSagaLogger: false, @@ -45,8 +46,9 @@ if (__DEV__ && process.env.KEYBASE_LOCAL_DEBUG) { config.logStatFrequency = 0.8 config.overrideLoggedInTab = Tabs.settingsTab config.printOutstandingRPCs = true - config.printRPC = true - config.printRoutes = true + config.printRPC = false + config.printRoutes = false + config.filterActionLogs = null // '^chat|entity' config.redirectOnLogout = false config.reduxSagaLogger = false config.reduxSagaLoggerMasked = false @@ -108,6 +110,7 @@ export const { showAllTrackers, showDevTools, skipSecondaryDevtools, + filterActionLogs, } = config export function envVarDebugJson() { diff --git a/shared/local-debug.native.js b/shared/local-debug.native.js index <HASH>..<HASH> 100644 --- a/shared/local-debug.native.js +++ b/shared/local-debug.native.js @@ -35,6 +35,7 @@ let config: {[key: string]: any} = { printRPC: false, printBridgeB64: false, // raw b64 going over the wire printRoutes: false, + filterActionLogs: null, reactPerf: false, reduxSagaLogger: false, reduxSagaLoggerMasked: true, @@ -126,6 +127,7 @@ export const { reduxSagaLogger, showAllTrackers, showDevTools, + filterActionLogs, } = config export function setup(store: any) { diff --git a/shared/store/configure-store.js b/shared/store/configure-store.js index <HASH>..<HASH> 100644 --- a/shared/store/configure-store.js +++ b/shared/store/configure-store.js @@ -12,6 +12,7 @@ import { enableActionLogging, closureStoreCheck, immediateStateLogging, + filterActionLogs, } from '../local-debug' import {globalError} from '../constants/config' import {isMobile} from '../constants/platform' @@ -40,8 +41,12 @@ if (enableStoreLogging) { const logger = setupLogger('storeLogger', 100, immediateStateLogging, immutableToJS, 50, true) loggerMiddleware = createLogger({ actionTransformer: (...args) => { - console.log('Action:', ...args) - logger.log('Action:', ...args) + if (filterActionLogs) { + args[0].type.match(filterActionLogs) && console.log('Action:', ...args) + } else if (args[0] && args[0].type) { + console.log('Action:', ...args) + logger.log('Action:', ...args) + } return null }, collapsed: true, @@ -55,7 +60,8 @@ if (enableStoreLogging) { warn: () => {}, }, stateTransformer: (...args) => { - logger.log('State:', ...args) + // This is noisy, so let's not show it while filtering action logs + !filterActionLogs && logger.log('State:', ...args) return null }, titleFormatter: () => null,
Add debug flag to filter which actions are logged (#<I>)
keybase_client
train
8cf6c94b27f2dcf255144646cb281f0df4e84206
diff --git a/Solr.php b/Solr.php index <HASH>..<HASH> 100644 --- a/Solr.php +++ b/Solr.php @@ -15,6 +15,7 @@ use FS\SolrBundle\Query\FindByIdentifierQuery; use FS\SolrBundle\Query\SolrQuery; use FS\SolrBundle\Repository\Repository; use Solarium\Client; +use Symfony\Component\EventDispatcher\EventDispatcher; class Solr { @@ -35,7 +36,7 @@ class Solr private $commandFactory = null; /** - * @var EventManager + * @var EventDispatcher */ private $eventManager = null; @@ -53,7 +54,7 @@ class Solr public function __construct( Client $client, CommandFactory $commandFactory, - EventManager $manager, + EventDispatcher $manager, MetaInformationFactory $metaInformationFactory ) { $this->solrClient = $client; @@ -160,10 +161,10 @@ class Solr $errorEvent = new ErrorEvent(null, null, 'delete-document'); $errorEvent->setException($e); - $this->eventManager->handle(EventManager::ERROR, $errorEvent); + $this->eventManager->dispatch(EventManager::ERROR, $errorEvent); } - $this->eventManager->handle(EventManager::DELETE, new Event($this->solrClient, $metaInformations)); + $this->eventManager->dispatch(EventManager::DELETE, new Event($this->solrClient, $metaInformations)); } } @@ -180,7 +181,7 @@ class Solr $doc = $this->toDocument($metaInformation); - $this->eventManager->handle(EventManager::INSERT, new Event($this->solrClient, $metaInformation)); + $this->eventManager->dispatch(EventManager::INSERT, new Event($this->solrClient, $metaInformation)); $this->addDocumentToIndex($doc); } @@ -223,7 +224,7 @@ class Solr $errorEvent = new ErrorEvent(null, null, 'query solr'); $errorEvent->setException($e); - $this->eventManager->handle(EventManager::ERROR, $errorEvent); + $this->eventManager->dispatch(EventManager::ERROR, $errorEvent); return array(); } @@ -253,7 +254,7 @@ class Solr $errorEvent = new ErrorEvent(null, null, 'clear-index'); $errorEvent->setException($e); - $this->eventManager->handle(EventManager::ERROR, $errorEvent); + $this->eventManager->dispatch(EventManager::ERROR, $errorEvent); } } @@ -274,7 +275,7 @@ class Solr $doc = $this->toDocument($metaInformations); - $this->eventManager->handle(EventManager::UPDATE, new Event($this->solrClient, $metaInformations)); + $this->eventManager->dispatch(EventManager::UPDATE, new Event($this->solrClient, $metaInformations)); $this->addDocumentToIndex($doc); @@ -310,7 +311,7 @@ class Solr $errorEvent = new ErrorEvent(null, null, json_encode($this->solrClient->getOptions())); $errorEvent->setException($e); - $this->eventManager->handle(EventManager::ERROR, $errorEvent); + $this->eventManager->dispatch(EventManager::ERROR, $errorEvent); } } }
change to symfony event-dispatcher - change type hints - change notify method calls
floriansemm_SolrBundle
train
d4ed6faaa29114936ed07aa0a1e9ddabee4e6456
diff --git a/protocols/log/src/main/java/io/atomix/protocols/log/DistributedLogProtocol.java b/protocols/log/src/main/java/io/atomix/protocols/log/DistributedLogProtocol.java index <HASH>..<HASH> 100644 --- a/protocols/log/src/main/java/io/atomix/protocols/log/DistributedLogProtocol.java +++ b/protocols/log/src/main/java/io/atomix/protocols/log/DistributedLogProtocol.java @@ -70,7 +70,7 @@ public class DistributedLogProtocol implements LogProtocol { * Log protocol type. */ public static final class Type implements PrimitiveProtocol.Type<DistributedLogProtocolConfig> { - private static final String NAME = "log"; + private static final String NAME = "multi-log"; @Override public String name() {
Change distributed log protocol name to multi-log for consistency with other partitioned protocols.
atomix_atomix
train
04c963bbfde71b5394e8862a718b16869490fb2a
diff --git a/app/models/host/discovered.rb b/app/models/host/discovered.rb index <HASH>..<HASH> 100644 --- a/app/models/host/discovered.rb +++ b/app/models/host/discovered.rb @@ -7,7 +7,7 @@ class Host::Discovered < ::Host::Base belongs_to :subnet belongs_to :hostgroup - validates :mac, :uniqueness => true, :format => {:with => Net::Validations::MAC_REGEXP}, :presence => true + validates :mac, :uniqueness => true, :mac_address => true, :presence => true validates :ip, :format => {:with => Net::Validations::IP_REGEXP}, :uniqueness => true scoped_search :on => :name, :complete_value => true, :default_order => true
Fix mac address validation Foreman has mac address valdiator since <I>. Regexp does not exist anymore.
theforeman_foreman_discovery
train
61f83339d738649c7a6745d297ddc66557f7a70b
diff --git a/valid8/tests/test_validation_lib/test_validators_comparables.py b/valid8/tests/test_validation_lib/test_validators_comparables.py index <HASH>..<HASH> 100644 --- a/valid8/tests/test_validation_lib/test_validators_comparables.py +++ b/valid8/tests/test_validation_lib/test_validators_comparables.py @@ -1,18 +1,18 @@ import pytest -from valid8 import gt, gts, lt, lts, between, Failure +from valid8 import gt, gts, lt, lts, between, NotInRange, TooSmall, TooBig def test_gt(): """ tests that the gt() function works """ assert gt(1)(1) - with pytest.raises(Failure): + with pytest.raises(TooSmall): gt(-1)(-1.1) def test_gts(): """ tests that the gts() function works """ - with pytest.raises(Failure): + with pytest.raises(TooSmall): gts(1)(1) assert gts(-1)(-0.9) @@ -20,13 +20,13 @@ def test_gts(): def test_lt(): """ tests that the lt() function works """ assert lt(1)(1) - with pytest.raises(Failure): + with pytest.raises(TooBig): lt(-1)(-0.9) def test_lts(): """ tests that the lts() function works """ - with pytest.raises(Failure): + with pytest.raises(TooBig): lts(1)(1) assert lts(-1)(-1.1) @@ -36,8 +36,8 @@ def test_between(): assert between(0, 1)(0) assert between(0, 1)(1) - with pytest.raises(Failure): + with pytest.raises(NotInRange): between(0, 1)(-0.1) - with pytest.raises(Failure): + with pytest.raises(NotInRange): between(0, 1)(1.1) diff --git a/valid8/tests/test_validation_lib/test_validators_numbers.py b/valid8/tests/test_validation_lib/test_validators_numbers.py index <HASH>..<HASH> 100644 --- a/valid8/tests/test_validation_lib/test_validators_numbers.py +++ b/valid8/tests/test_validation_lib/test_validators_numbers.py @@ -1,21 +1,21 @@ import pytest -from valid8 import is_even, is_odd, is_multiple_of, Failure +from valid8 import is_even, is_odd, is_multiple_of, IsNotMultipleOf, IsNotOdd, IsNotEven def test_is_even(): assert is_even(2) - with pytest.raises(Failure): + with pytest.raises(IsNotEven): is_even(-1) def test_is_odd(): assert is_odd(-1) - with pytest.raises(Failure): + with pytest.raises(IsNotOdd): is_odd(-2) def test_is_multiple_of(): assert is_multiple_of(3)(-9) - with pytest.raises(Failure): + with pytest.raises(IsNotMultipleOf): is_multiple_of(3)(-10)
Improved slightly the tests for comparables and numbers
smarie_python-valid8
train
f5ebd2088f3122a98c0dcd36857f735b027ca813
diff --git a/tests/ResponseTransferTest.php b/tests/ResponseTransferTest.php index <HASH>..<HASH> 100644 --- a/tests/ResponseTransferTest.php +++ b/tests/ResponseTransferTest.php @@ -434,6 +434,14 @@ class ResponseTransferTest extends \PHPUnit_Framework_TestCase $this->assertSame($expect, $actual); } + public function testSetAndGetLayoutContentVar() + { + $expect = 'my_content_var'; + $this->response->setLayoutContentVar($expect); + $actual = $this->response->getLayoutContentVar(); + $this->assertSame($expect, $actual); + } + /** * @todo Implement testSetFormat(). */
increase test coverage to <I>%
auraphp_Aura.Web
train
bb5e61760018049b83a820111d72ac2267ab666b
diff --git a/ooquery/ooquery.py b/ooquery/ooquery.py index <HASH>..<HASH> 100644 --- a/ooquery/ooquery.py +++ b/ooquery/ooquery.py @@ -22,30 +22,11 @@ class OOQuery(object): else: return self.table - def get_field_from_table(self, table, field): - return getattr(table, field) - - def get_field_from_related_table(self, join_path_list, field_name): - self.parser.parse_join(join_path_list) - path = '.'.join(join_path_list) - join = self.parser.joins_map.get(path) - if join: - table = join.right - return self.get_field_from_table(table, field_name) - - def get_table_field(self, field): - if '.' in field: - return self.get_field_from_related_table( - field.split('.')[:-1], field.split('.')[-1] - ) - else: - return self.get_field_from_table(self.table, field) - @property def fields(self): fields = [] for field in self._fields: - table_field = self.get_table_field(field) + table_field = self.parser.get_table_field(field) fields.append(table_field.as_(field.replace('.', '_'))) return fields diff --git a/ooquery/parser.py b/ooquery/parser.py index <HASH>..<HASH> 100644 --- a/ooquery/parser.py +++ b/ooquery/parser.py @@ -30,6 +30,25 @@ class Parser(object): else: return self.table + def get_field_from_table(self, table, field): + return getattr(table, field) + + def get_field_from_related_table(self, join_path_list, field_name): + self.parse_join(join_path_list) + path = '.'.join(join_path_list) + join = self.joins_map.get(path) + if join: + table = join.right + return self.get_field_from_table(table, field_name) + + def get_table_field(self, field): + if '.' in field: + return self.get_field_from_related_table( + field.split('.')[:-1], field.split('.')[-1] + ) + else: + return self.get_field_from_table(self.table, field) + def parse_join(self, fields_join): table = self.table join_path = []
Moved methods to parser because it's more appropiate
gisce_ooquery
train
860680695de4912bb63174cb276e09f115782ac8
diff --git a/spec/controllers/pages_controller_spec.rb b/spec/controllers/pages_controller_spec.rb index <HASH>..<HASH> 100644 --- a/spec/controllers/pages_controller_spec.rb +++ b/spec/controllers/pages_controller_spec.rb @@ -2,26 +2,21 @@ require 'spec_helper' describe Alchemy::PagesController do - render_views - - before(:each) do - @default_language = Alchemy::Language.get_default - @default_language_root = FactoryGirl.create(:language_root_page, :language => @default_language, :name => 'Home', :public => true) - end + let(:default_language) { Alchemy::Language.get_default } + let(:default_language_root) { FactoryGirl.create(:language_root_page, :language => default_language, :name => 'Home', :public => true) } context "requested for a page containing a feed" do + render_views - before(:each) do - @page = FactoryGirl.create(:public_page, :parent_id => @default_language_root.id, :page_layout => 'news', :name => 'News', :language => @default_language, :do_not_autogenerate => false) - end + let(:page) { FactoryGirl.create(:public_page, :parent_id => default_language_root.id, :page_layout => 'news', :name => 'News', :language => default_language, :do_not_autogenerate => false) } it "should render a rss feed" do - get :show, :urlname => 'news', :format => :rss + get :show, :urlname => page.urlname, :format => :rss response.content_type.should == 'application/rss+xml' end it "should include content" do - @page.elements.first.content_by_name('news_headline').essence.update_attributes({:body => 'Peters Petshop'}) + page.elements.first.content_by_name('news_headline').essence.update_attributes({:body => 'Peters Petshop'}) get :show, :urlname => 'news', :format => :rss response.body.should match /Peters Petshop/ end @@ -31,7 +26,7 @@ describe Alchemy::PagesController do context "requested for a page that does not contain a feed" do it "should render xml 404 error" do - get :show, :urlname => 'home', :format => :rss + get :show, :urlname => default_language_root.urlname, :format => :rss response.status.should == 404 end @@ -59,11 +54,14 @@ describe Alchemy::PagesController do context "with params layout set to not existing layout" do it "should raise ActionView::MissingTemplate" do - expect { get :show, :urlname => :home, :layout => 'lkuiuk' }.to raise_error(ActionView::MissingTemplate) + expect { + get :show, :urlname => default_language_root.urlname, :layout => 'lkuiuk' + }.to raise_error(ActionView::MissingTemplate) end end context "with param layout set to a custom layout" do + render_views before do @custom_layout = Rails.root.join('app/views/layouts', 'custom.html.erb') @@ -73,7 +71,7 @@ describe Alchemy::PagesController do end it "should render the custom layout" do - get :show, :urlname => :home, :layout => 'custom' + get :show, :urlname => default_language_root.urlname, :layout => 'custom' response.body.should have_content('I am a custom layout') end @@ -85,11 +83,12 @@ describe Alchemy::PagesController do end describe "url nesting" do + render_views before(:each) do - @catalog = FactoryGirl.create(:public_page, :name => "Catalog", :parent_id => @default_language_root.id, :language => @default_language) - @products = FactoryGirl.create(:public_page, :name => "Products", :parent_id => @catalog.id, :language => @default_language) - @product = FactoryGirl.create(:public_page, :name => "Screwdriver", :parent_id => @products.id, :language => @default_language, :do_not_autogenerate => false) + @catalog = FactoryGirl.create(:public_page, :name => "Catalog", :parent_id => default_language_root.id, :language => default_language) + @products = FactoryGirl.create(:public_page, :name => "Products", :parent_id => @catalog.id, :language => default_language) + @product = FactoryGirl.create(:public_page, :name => "Screwdriver", :parent_id => @products.id, :language => default_language, :do_not_autogenerate => false) @product.elements.find_by_name('article').contents.essence_texts.first.essence.update_column(:body, 'screwdriver') controller.stub!(:configuration) { |arg| arg == :url_nesting ? true : false } end
Refactors some pages controller specs.
AlchemyCMS_alchemy_cms
train
e6bf0db048220e6d7b3a9fe27c3bac1ddb8a4b2b
diff --git a/introspection.go b/introspection.go index <HASH>..<HASH> 100644 --- a/introspection.go +++ b/introspection.go @@ -3,6 +3,7 @@ package graphql import ( "fmt" "reflect" + "sort" "github.com/graphql-go/graphql/language/ast" "github.com/graphql-go/graphql/language/printer" @@ -518,11 +519,16 @@ func init() { return nil, nil } fields := []*FieldDefinition{} - for _, field := range ttype.Fields() { + var fieldNames sort.StringSlice + for name, field := range ttype.Fields() { if !includeDeprecated && field.DeprecationReason != "" { continue } - fields = append(fields, field) + fieldNames = append(fieldNames, name) + } + sort.Sort(fieldNames) + for _, name := range fieldNames { + fields = append(fields, ttype.Fields()[name]) } return fields, nil case *Interface:
Sort fields by name for introspection.
graphql-go_graphql
train
2030c6953c49c6e4232fce25be214fc46e9dcb31
diff --git a/smokesignal.py b/smokesignal.py index <HASH>..<HASH> 100644 --- a/smokesignal.py +++ b/smokesignal.py @@ -58,8 +58,7 @@ def _on(signals, callback, max_calls=None): Proxy for `smokesignal.on`, which is compatible as both a function call and a decorator. This method cannot be used as a decorator """ - print signals, callback, max_calls - assert callable(callback), u'Signal callbacks must be callable' + assert callable(callback), 'Signal callbacks must be callable' # Support for lists of signals if not isinstance(signals, (list, tuple)): diff --git a/tests.py b/tests.py index <HASH>..<HASH> 100644 --- a/tests.py +++ b/tests.py @@ -90,7 +90,7 @@ class SmokesignalTestCase(TestCase): assert len(smokesignal._receivers['foo']) == 1 # Call a bunch of times - for x in xrange(5): + for x in range(10): smokesignal.emit('foo') assert cb.call_count == 3 @@ -126,7 +126,7 @@ class SmokesignalTestCase(TestCase): assert len(smokesignal._receivers['foo']) == 1 # Call a bunch of times - for x in xrange(5): + for x in range(10): smokesignal.emit('foo') assert cb.call_count == 3 diff --git a/tox.ini b/tox.ini index <HASH>..<HASH> 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,5 @@ [tox] -envlist = py26,py27,py33 +envlist = py26,py27,py32,py33,pypy downloadcache = {toxworkdir}/_download/ [base] @@ -12,4 +12,4 @@ deps = {[base]deps} sitepackages = False commands = - {envbindir}/py.test + {envbindir}/py.test tests.py
Fixes for tox envs
shaunduncan_smokesignal
train
b5a9440318bdf671a8d9d6d75dd043f4b9ebbf62
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -51,7 +51,7 @@ function check(port, host) { return deferred.promise; } - if (!is.hostAddress(host)) { + if (is.nullOrUndefined(host)) { debug('set host address to default 127.0.0.1'); host = '127.0.0.1'; } @@ -123,7 +123,7 @@ function waitUntilFreeOnHost(port, host, retryTimeMs, timeOutMs) { return deferred.promise; } - if (!is.hostAddress(host)) { + if (!is.nullOrUndefined(host)) { host = '127.0.0.1'; debug('waitUntilUsedOnHost set host to default "127.0.0.1"'); } @@ -232,7 +232,7 @@ function waitUntilUsedOnHost(port, host, retryTimeMs, timeOutMs) { return deferred.promise; } - if (!is.hostAddress(host)) { + if (is.nullOrUndefined(host)) { host = '127.0.0.1'; debug('waitUntilUsedOnHost set host to default "127.0.0.1"'); }
Swapped is.hostAddress for is.nullOrUndefined.
stdarg_tcp-port-used
train
9860d8ab2d152dfd292465af301866a273d4ec4c
diff --git a/Source/com/drew/imaging/FileType.java b/Source/com/drew/imaging/FileType.java index <HASH>..<HASH> 100644 --- a/Source/com/drew/imaging/FileType.java +++ b/Source/com/drew/imaging/FileType.java @@ -89,7 +89,13 @@ public enum FileType } @Nullable - public String[] getExtension() + public String getCommonExtension() + { + return _extensions.length == 0 ? null : _extensions[0]; + } + + @Nullable + public String[] getAllExtensions() { return _extensions; } diff --git a/Source/com/drew/metadata/file/FileMetadataReader.java b/Source/com/drew/metadata/file/FileMetadataReader.java index <HASH>..<HASH> 100644 --- a/Source/com/drew/metadata/file/FileMetadataReader.java +++ b/Source/com/drew/metadata/file/FileMetadataReader.java @@ -60,8 +60,8 @@ public class FileMetadataReader directory.setString(FileMetadataDirectory.TAG_FILE_MIME_TYPE, fileType.getMimeType()); } - if (fileType.getExtension() != null) { - directory.setStringArray(FileMetadataDirectory.TAG_FILE_EXTENSION, fileType.getExtension()); + if (fileType.getCommonExtension() != null) { + directory.setString(FileMetadataDirectory.TAG_FILE_EXTENSION, fileType.getCommonExtension()); } metadata.addDirectory(directory);
Differentiate between common/all extensions Many use cases will want a single extension (file renaming for example). Other use cases will want the list of potential names.
drewnoakes_metadata-extractor
train
3192e062ba27afa75fd616eab1228bd56a1a9c93
diff --git a/spec/scripts/server_importer_spec.rb b/spec/scripts/server_importer_spec.rb index <HASH>..<HASH> 100644 --- a/spec/scripts/server_importer_spec.rb +++ b/spec/scripts/server_importer_spec.rb @@ -135,8 +135,13 @@ module RightScale context 'rs_connect -a url -c cloud' do it 'should attach this machine to a server and set cloud name to "cloud"' do flexmock(RightScale::AgentConfig).should_receive(:cloud_file_path).and_return("cloud_file_path") + spool_dir = '/var/spool' + if RightScale::Platform::windows? + flexmock(File).should_receive(:join).with(Dir::COMMON_APPDATA, 'RightScale', 'spool')\ + .and_return(spool_dir) + end flexmock(File).should_receive(:join)\ - .with(RightScale::Platform.filesystem.spool_dir, "cloud", 'user-data.txt')\ + .with(spool_dir, "cloud", 'user-data.txt')\ .and_return("/var/spool/cloud/user-data.txt") do_attach('url', false, "cloud") end
keep rs_connect spec green on windows
rightscale_right_link
train
8c980857e8d0cd82d90a296c024988cb3b05fda3
diff --git a/lib/lit/adapters/redis_storage.rb b/lib/lit/adapters/redis_storage.rb index <HASH>..<HASH> 100644 --- a/lib/lit/adapters/redis_storage.rb +++ b/lib/lit/adapters/redis_storage.rb @@ -32,6 +32,12 @@ module Lit Lit.redis.exists(_prefixed_key(key)) end + def sort + Lit.redis.keys.sort.map do |k| + [k, self.[](k)] + end + end + private def _prefixed_key(key="") prefix = "lit:"
sort for redis storage - added to support lit:export task (returns array of [k,v])
prograils_lit
train
a6d357ff70213cfa9cd21f045637c3032158e562
diff --git a/closure/goog/deps.js b/closure/goog/deps.js index <HASH>..<HASH> 100644 --- a/closure/goog/deps.js +++ b/closure/goog/deps.js @@ -1196,7 +1196,7 @@ goog.addDependency('ui/ac/ac.js', ['goog.ui.ac'], ['goog.ui.ac.ArrayMatcher', 'g goog.addDependency('ui/ac/ac_test.js', ['goog.ui.acTest'], ['goog.array', 'goog.asserts', 'goog.dom', 'goog.dom.NodeType', 'goog.dom.classlist', 'goog.dom.selection', 'goog.events', 'goog.events.BrowserEvent', 'goog.events.Event', 'goog.events.EventType', 'goog.events.KeyCodes', 'goog.style', 'goog.testing.MockClock', 'goog.testing.jsunit', 'goog.ui.ac', 'goog.userAgent'], {}); goog.addDependency('ui/ac/arraymatcher.js', ['goog.ui.ac.ArrayMatcher'], ['goog.string'], {}); goog.addDependency('ui/ac/arraymatcher_test.js', ['goog.ui.ac.ArrayMatcherTest'], ['goog.testing.jsunit', 'goog.ui.ac.ArrayMatcher'], {}); -goog.addDependency('ui/ac/autocomplete.js', ['goog.ui.ac.AutoComplete', 'goog.ui.ac.AutoComplete.EventType'], ['goog.array', 'goog.asserts', 'goog.events', 'goog.events.EventTarget', 'goog.object'], {}); +goog.addDependency('ui/ac/autocomplete.js', ['goog.ui.ac.AutoComplete', 'goog.ui.ac.AutoComplete.EventType'], ['goog.array', 'goog.asserts', 'goog.events', 'goog.events.EventTarget', 'goog.object', 'goog.ui.ac.RenderOptions'], {}); goog.addDependency('ui/ac/autocomplete_test.js', ['goog.ui.ac.AutoCompleteTest'], ['goog.a11y.aria', 'goog.a11y.aria.Role', 'goog.dom', 'goog.dom.InputType', 'goog.dom.TagName', 'goog.events.EventHandler', 'goog.events.EventTarget', 'goog.string', 'goog.testing.MockControl', 'goog.testing.events', 'goog.testing.jsunit', 'goog.testing.mockmatchers', 'goog.ui.ac.AutoComplete', 'goog.ui.ac.InputHandler', 'goog.ui.ac.RenderOptions', 'goog.ui.ac.Renderer'], {}); goog.addDependency('ui/ac/cachingmatcher.js', ['goog.ui.ac.CachingMatcher'], ['goog.array', 'goog.async.Throttle', 'goog.ui.ac.ArrayMatcher', 'goog.ui.ac.RenderOptions'], {}); goog.addDependency('ui/ac/cachingmatcher_test.js', ['goog.ui.ac.CachingMatcherTest'], ['goog.testing.MockControl', 'goog.testing.jsunit', 'goog.testing.mockmatchers', 'goog.ui.ac.CachingMatcher'], {}); diff --git a/closure/goog/ui/ac/autocomplete.js b/closure/goog/ui/ac/autocomplete.js index <HASH>..<HASH> 100644 --- a/closure/goog/ui/ac/autocomplete.js +++ b/closure/goog/ui/ac/autocomplete.js @@ -26,8 +26,7 @@ goog.require('goog.asserts'); goog.require('goog.events'); goog.require('goog.events.EventTarget'); goog.require('goog.object'); - -goog.forwardDeclare('goog.ui.ac.RenderOptions'); +goog.require('goog.ui.ac.RenderOptions'); /**
Require goog.ui.ac.RenderOptions in autocomplete.js instead of forward declaring it. RELNOTES: n/a ------------- Created by MOE: <URL>
google_closure-library
train
6f899c59a69b7f9cdc94c1f72a6d51f8050f94ef
diff --git a/sdk/spring/azure-spring-boot/src/main/java/com/azure/spring/aad/webapp/AADWebSecurityConfigurerAdapter.java b/sdk/spring/azure-spring-boot/src/main/java/com/azure/spring/aad/webapp/AADWebSecurityConfigurerAdapter.java index <HASH>..<HASH> 100644 --- a/sdk/spring/azure-spring-boot/src/main/java/com/azure/spring/aad/webapp/AADWebSecurityConfigurerAdapter.java +++ b/sdk/spring/azure-spring-boot/src/main/java/com/azure/spring/aad/webapp/AADWebSecurityConfigurerAdapter.java @@ -45,16 +45,12 @@ public abstract class AADWebSecurityConfigurerAdapter extends WebSecurityConfigu .anyRequest().authenticated() .and() .oauth2Login() - .authorizationEndpoint() - .authorizationRequestResolver(requestResolver()) - .and() .tokenEndpoint() .accessTokenResponseClient(accessTokenResponseClient()) .and() .userInfoEndpoint() .oidcUserService(oidcUserService) .and() - .failureHandler(failureHandler()) .and() .logout() .logoutSuccessHandler(oidcLogoutSuccessHandler())
Delete conditional access related configuration. (#<I>)
Azure_azure-sdk-for-java
train
d073004d283e35fd341dbcd132355cd45455901e
diff --git a/src/js/react-datatable/cell.js b/src/js/react-datatable/cell.js index <HASH>..<HASH> 100644 --- a/src/js/react-datatable/cell.js +++ b/src/js/react-datatable/cell.js @@ -45,7 +45,7 @@ var RDTCell = React.createClass({ var target = event.target; - if ( !this.state.isEditMode && this.props.editable ) { + if ( !this.state.editMode && this.props.col.editable ) { this.setState( { record : this.state.record, property : this.state.property, editMode : true } ); } @@ -156,4 +156,4 @@ var RDTCell = React.createClass({ }); -module.exports = RDTCell; \ No newline at end of file +module.exports = RDTCell;
Fixes editMode editMode was not functional
wmira_react-datatable
train
c18cc058e701dbf1e7cbf4179ea78cf273269130
diff --git a/spec/requests/fae_filter_select_spec.rb b/spec/requests/fae_filter_select_spec.rb index <HASH>..<HASH> 100644 --- a/spec/requests/fae_filter_select_spec.rb +++ b/spec/requests/fae_filter_select_spec.rb @@ -38,11 +38,11 @@ describe 'fae_filter_select' do end describe 'placeholder option' do - it 'should default to "Select a Class Name" and be overridable' do + it 'should default to "All Class Names" and be overridable' do admin_login get admin_releases_path - expect(response.body).to include('Select a Wine') + expect(response.body).to include('All Wines') expect(response.body).to include('Select some stuff') end end
update spec to new way we are setting default
wearefine_fae
train
926580f20cc8cfd06de6047acb8ab56a1f5773b5
diff --git a/packages/mendel-middleware/index.js b/packages/mendel-middleware/index.js index <HASH>..<HASH> 100644 --- a/packages/mendel-middleware/index.js +++ b/packages/mendel-middleware/index.js @@ -60,7 +60,7 @@ function MendelMiddleware(opts) { return next(); } var bundleConfig = bundles[params.bundle]; - var dirs = params.variations.split(','); + var dirs = params.variations.split(/(,|%2C)/i); dirs = resolveVariations(existingVariations, dirs); if (!dirs.length || !bundleConfig) {
Add support for different express parsers
yahoo_mendel
train
f2312ac3bc42ad064df6d5336334a538e6b00bec
diff --git a/lib/index.js b/lib/index.js index <HASH>..<HASH> 100644 --- a/lib/index.js +++ b/lib/index.js @@ -213,9 +213,9 @@ module.exports = class Telnet extends events.EventEmitter { this.sendTimeout = opts.timeout || this.sendTimeout this.maxBufferLength = opts.maxBufferLength || this.maxBufferLength this.waitfor = (opts.waitfor ? (opts.waitfor instanceof RegExp ? opts.waitfor : RegExp(opts.waitfor)) : false); - - data += this.ors } + + data += this.ors if (this.socket.writable) { this.socket.write(data, () => {
keep the call style same (#<I>) * keep the call style same for now,we must provide a object as the second parameter in the "send" function,which is different with "exec" function.besides,the second pararmeter can be optional. * Update index.js
mkozjak_node-telnet-client
train
3c9fc6b250db0a2d6bc96791b8254e15376d685b
diff --git a/sdk/resources/mgmt/src/test/java/com/azure/resourcemanager/resources/core/ResourceGroupTaggingPolicy.java b/sdk/resources/mgmt/src/test/java/com/azure/resourcemanager/resources/core/ResourceGroupTaggingPolicy.java index <HASH>..<HASH> 100644 --- a/sdk/resources/mgmt/src/test/java/com/azure/resourcemanager/resources/core/ResourceGroupTaggingPolicy.java +++ b/sdk/resources/mgmt/src/test/java/com/azure/resourcemanager/resources/core/ResourceGroupTaggingPolicy.java @@ -10,6 +10,7 @@ import com.azure.core.http.HttpResponse; import com.azure.core.http.policy.HttpPipelinePolicy; import com.azure.core.management.serializer.AzureJacksonAdapter; import com.azure.core.util.serializer.SerializerEncoding; +import com.azure.resourcemanager.resources.fluent.ResourceGroupsClient; import com.azure.resourcemanager.resources.fluent.inner.ResourceGroupInner; import reactor.core.publisher.Mono; @@ -24,7 +25,7 @@ import java.util.Map; */ public class ResourceGroupTaggingPolicy implements HttpPipelinePolicy { // private static final String LOGGING_CONTEXT = "com.microsoft.azure.management.resources.ResourceGroups createOrUpdate"; - private static final String CALLER_METHOD = "com.azure.resourcemanager.resources.models.ResourceGroupsInner$ResourceGroupsService.createOrUpdate"; + private static final String CALLER_METHOD = String.format("%s$ResourceGroupsService.createOrUpdate", ResourceGroupsClient.class.getName()); private AzureJacksonAdapter adapter = new AzureJacksonAdapter(); @Override
Mgmt fix group tagging policy (#<I>) * fix group tagging policy * change class name string to class dependency
Azure_azure-sdk-for-java
train
1e2f1c0e6a00772390afae9abcaba44b9e91abd3
diff --git a/sqlbrite/src/androidTest/java/com/squareup/sqlbrite3/BriteDatabaseTest.java b/sqlbrite/src/androidTest/java/com/squareup/sqlbrite3/BriteDatabaseTest.java index <HASH>..<HASH> 100644 --- a/sqlbrite/src/androidTest/java/com/squareup/sqlbrite3/BriteDatabaseTest.java +++ b/sqlbrite/src/androidTest/java/com/squareup/sqlbrite3/BriteDatabaseTest.java @@ -1110,6 +1110,46 @@ public final class BriteDatabaseTest { } } + @Test public void synchronousQueryWithSupportSQLiteQueryDuringTransaction() { + Transaction transaction = db.newTransaction(); + try { + transaction.markSuccessful(); + assertCursor(db.query(new SimpleSQLiteQuery(SELECT_EMPLOYEES))) + .hasRow("alice", "Alice Allison") + .hasRow("bob", "Bob Bobberson") + .hasRow("eve", "Eve Evenson") + .isExhausted(); + } finally { + transaction.end(); + } + } + + @Test public void synchronousQueryWithSupportSQLiteQueryDuringTransactionSeesChanges() { + Transaction transaction = db.newTransaction(); + try { + assertCursor(db.query(new SimpleSQLiteQuery(SELECT_EMPLOYEES))) + .hasRow("alice", "Alice Allison") + .hasRow("bob", "Bob Bobberson") + .hasRow("eve", "Eve Evenson") + .isExhausted(); + + db.insert(TABLE_EMPLOYEE, CONFLICT_NONE, employee("john", "John Johnson")); + db.insert(TABLE_EMPLOYEE, CONFLICT_NONE, employee("nick", "Nick Nickers")); + + assertCursor(db.query(new SimpleSQLiteQuery(SELECT_EMPLOYEES))) + .hasRow("alice", "Alice Allison") + .hasRow("bob", "Bob Bobberson") + .hasRow("eve", "Eve Evenson") + .hasRow("john", "John Johnson") + .hasRow("nick", "Nick Nickers") + .isExhausted(); + + transaction.markSuccessful(); + } finally { + transaction.end(); + } + } + @Test public void nestedTransactionsOnlyNotifyOnce() { db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES).subscribe(o); o.assertCursor() diff --git a/sqlbrite/src/main/java/com/squareup/sqlbrite3/BriteDatabase.java b/sqlbrite/src/main/java/com/squareup/sqlbrite3/BriteDatabase.java index <HASH>..<HASH> 100644 --- a/sqlbrite/src/main/java/com/squareup/sqlbrite3/BriteDatabase.java +++ b/sqlbrite/src/main/java/com/squareup/sqlbrite3/BriteDatabase.java @@ -406,6 +406,21 @@ public final class BriteDatabase implements Closeable { } /** + * Runs the provided {@link SupportSQLiteQuery} and returns a {@link Cursor} over the result set. + * + * @see SupportSQLiteDatabase#query(SupportSQLiteQuery) + */ + @CheckResult @WorkerThread + public Cursor query(@NonNull SupportSQLiteQuery query) { + Cursor cursor = getReadableDatabase().query(query); + if (logging) { + log("QUERY\n sql: %s", indentSql(query.getSql())); + } + + return cursor; + } + + /** * Insert a row into the specified {@code table} and notify any subscribed queries. * * @see SupportSQLiteDatabase#insert(String, int, ContentValues)
Add query(SupportSQLiteQuery) method
square_sqlbrite
train
62bd497d7057380d15ed0b01033ef0e69bdd0a4d
diff --git a/spyderlib/widgets/shell.py b/spyderlib/widgets/shell.py index <HASH>..<HASH> 100644 --- a/spyderlib/widgets/shell.py +++ b/spyderlib/widgets/shell.py @@ -15,6 +15,7 @@ import os import time import os.path as osp import re +import sys from spyderlib.qt.QtGui import (QMenu, QApplication, QToolTip, QKeySequence, QMessageBox, QMouseEvent, QTextCursor, @@ -226,9 +227,13 @@ class ShellBaseWidget(ConsoleBaseWidget, SaveHistoryMixin): """Copy text to clipboard... or keyboard interrupt""" if self.has_selected_text(): ConsoleBaseWidget.copy(self) - else: - self.emit(SIGNAL("keyboard_interrupt()")) - + elif not sys.platform == 'darwin': + self.interrupt() + + def interrupt(self): + """Keyboard interrupt""" + self.emit(SIGNAL("keyboard_interrupt()")) + def cut(self): """Cut text""" self.check_selection() @@ -302,8 +307,12 @@ class ShellBaseWidget(ConsoleBaseWidget, SaveHistoryMixin): # (otherwise, right below, we would remove selection # if not on current line) ctrl = event.modifiers() & Qt.ControlModifier - if event.key() == Qt.Key_C and ctrl: - self.copy() + meta = event.modifiers() & Qt.MetaModifier # meta=ctrl in OSX + if event.key() == (Qt.Key_C and ctrl) or (Qt.Key_C and meta): + if meta and sys.platform == 'darwin': + self.interrupt() + elif ctrl: + self.copy() event.accept() return True
External Console: Use Ctrl+C to interrupt on Mac Update Issue <I> Status: Fixed - Before only Cmd+C was triggering an interrupt but this shorcut is used only for copying.
spyder-ide_spyder
train
6316fd9e038466140bce478a25943e1cf367e4e4
diff --git a/src/common/cli.js b/src/common/cli.js index <HASH>..<HASH> 100644 --- a/src/common/cli.js +++ b/src/common/cli.js @@ -69,6 +69,8 @@ sre.Cli.prototype.commandLine = function() { /** @type {!boolean} */ commander.speech = false; /** @type {!boolean} */ + commander.ssml = false; + /** @type {!boolean} */ commander.xml = false; commander.version(system.version). @@ -85,6 +87,7 @@ sre.Cli.prototype.commandLine = function() { option('-j, --json', 'Generate JSON of semantic tree.'). option('-m, --mathml', 'Generate enriched MathML.'). option('-p, --speech', 'Generate speech output (default).'). + option('-r, --ssml', 'Generate speech output with SSML tags.'). option('-x, --xml', 'Generate XML of semantic tree.'). option(''). option('-v, --verbose', 'Verbose mode.'). @@ -105,7 +108,8 @@ sre.Cli.prototype.commandLine = function() { 'semantics': commander.semantics, 'domain': commander.dom, 'style': commander.style, - 'mode': sre.Engine.Mode.SYNC + 'mode': sre.Engine.Mode.SYNC, + 'ssml': commander.ssml }); if (commander.verbose) { sre.Debugger.getInstance().init(commander.log);
Exposes SSML output via the CLI.
zorkow_speech-rule-engine
train
7f28a8bc5d833ac445e70e9739f3f9c63c48e798
diff --git a/core/src/main/java/org/springframework/security/ldap/populator/DefaultLdapAuthoritiesPopulator.java b/core/src/main/java/org/springframework/security/ldap/populator/DefaultLdapAuthoritiesPopulator.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/org/springframework/security/ldap/populator/DefaultLdapAuthoritiesPopulator.java +++ b/core/src/main/java/org/springframework/security/ldap/populator/DefaultLdapAuthoritiesPopulator.java @@ -99,8 +99,6 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator */ private GrantedAuthority defaultRole; - private ContextSource contextSource; - private SpringSecurityLdapTemplate ldapTemplate; /** @@ -143,8 +141,10 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator * context factory. */ public DefaultLdapAuthoritiesPopulator(ContextSource contextSource, String groupSearchBase) { - this.setContextSource(contextSource); - this.setGroupSearchBase(groupSearchBase); + Assert.notNull(contextSource, "contextSource must not be null"); + ldapTemplate = new SpringSecurityLdapTemplate(contextSource); + ldapTemplate.setSearchControls(searchControls); + setGroupSearchBase(groupSearchBase); } //~ Methods ======================================================================================================== @@ -226,20 +226,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator } protected ContextSource getContextSource() { - return contextSource; - } - - /** - * Set the {@link ContextSource} - * - * @param contextSource supplies the contexts used to search for user roles. - */ - private void setContextSource(ContextSource contextSource) { - Assert.notNull(contextSource, "contextSource must not be null"); - this.contextSource = contextSource; - - ldapTemplate = new SpringSecurityLdapTemplate(contextSource); - ldapTemplate.setSearchControls(searchControls); + return ldapTemplate.getContextSource(); } /**
Refactored DefaultLdapAuthoritiesPopulator to remove contextSource field and setter method.
spring-projects_spring-security
train
142c4864b8e2be6f39d4fc63b6988020d4d4b1b3
diff --git a/salt/modules/beacons.py b/salt/modules/beacons.py index <HASH>..<HASH> 100644 --- a/salt/modules/beacons.py +++ b/salt/modules/beacons.py @@ -27,6 +27,11 @@ def list_(return_yaml=True): ''' List the beacons currently configured on the minion + .. versionadded:: Beryllium + + :param return_yaml: Whether to return YAML formatted output, default True + :return: List of currently configured Beacons. + CLI Example: .. code-block:: bash @@ -65,11 +70,17 @@ def add(name, beacon_data, **kwargs): ''' Add a beacon on the minion + .. versionadded:: Beryllium + + :param name: Name of the beacon to configure + :param beacon_data: Dictionary or list containing configuration for beacon. + :return: Boolean and status message on success or failure of add. + CLI Example: .. code-block:: bash - salt '*' beacons.add + salt '*' beacons.add ps "{'salt-master': 'stopped', 'apache2': 'stopped'}" ''' ret = {'comment': 'Failed to add beacon {0}.'.format(name), @@ -122,13 +133,19 @@ def add(name, beacon_data, **kwargs): def modify(name, beacon_data, **kwargs): ''' - Modify an existing job in the schedule + Modify an existing beacon + + .. versionadded:: Beryllium + + :param name: Name of the beacon to configure + :param beacon_data: Dictionary or list containing updated configuration for beacon. + :return: Boolean and status message on success or failure of modify. CLI Example: .. code-block:: bash - salt '*' schedule.modify job1 function='test.ping' seconds=3600 + salt '*' beacon.modify ps "{'salt-master': 'stopped', 'apache2': 'stopped'}" ''' ret = {'comment': '', @@ -200,6 +217,11 @@ def delete(name, **kwargs): ''' Delete a beacon item + .. versionadded:: Beryllium + + :param name: Name of the beacon to delete + :return: Boolean and status message on success or failure of delete. + CLI Example: .. code-block:: bash @@ -238,6 +260,10 @@ def save(): ''' Save all beacons on the minion + .. versionadded:: Beryllium + + :return: Boolean and status message on success or failure of save. + CLI Example: .. code-block:: bash @@ -273,6 +299,10 @@ def enable(**kwargs): ''' Enable all beacons on the minion + .. versionadded:: Beryllium + + :return: Boolean and status message on success or failure of enable. + CLI Example: .. code-block:: bash @@ -310,6 +340,10 @@ def disable(**kwargs): ''' Disable all beaconsd jobs on the minion + .. versionadded:: Beryllium + + :return: Boolean and status message on success or failure of disable. + CLI Example: .. code-block:: bash @@ -348,6 +382,11 @@ def enable_beacon(name, **kwargs): ''' Enable beacon on the minion + .. versionadded:: Beryllium + + :name: Name of the beacon to enable. + :return: Boolean and status message on success or failure of enable. + CLI Example: .. code-block:: bash @@ -393,6 +432,11 @@ def disable_beacon(name, **kwargs): ''' Disable beacon on the minion + .. versionadded:: Beryllium + + :name: Name of the beacon to enable. + :return: Boolean and status message on success or failure of disable. + CLI Example: .. code-block:: bash diff --git a/salt/states/beacon.py b/salt/states/beacon.py index <HASH>..<HASH> 100644 --- a/salt/states/beacon.py +++ b/salt/states/beacon.py @@ -3,6 +3,8 @@ Management of the Salt beacons ============================================== +.. versionadded:: Beryllium + .. code-block:: yaml ps: @@ -28,9 +30,6 @@ Management of the Salt beacons ''' -import logging -log = logging.getLogger(__name__) - def present(name, **kwargs):
Adding some additional documentation to state and execution modules.
saltstack_salt
train
d1f9efb3fc92cefd7b6d5dc147af11dc17a8a910
diff --git a/core/node/groups.go b/core/node/groups.go index <HASH>..<HASH> 100644 --- a/core/node/groups.go +++ b/core/node/groups.go @@ -96,11 +96,11 @@ func LibP2P(bcfg *BuildCfg, cfg *config.Config) fx.Option { BaseLibP2P, fx.Provide(libp2p.AddrFilters(cfg.Swarm.AddrFilters)), - fx.Invoke(libp2p.SetupDiscovery(cfg.Discovery.MDNS.Enabled, cfg.Discovery.MDNS.Interval)), fx.Provide(libp2p.AddrsFactory(cfg.Addresses.Announce, cfg.Addresses.NoAnnounce)), fx.Provide(libp2p.SmuxTransport(bcfg.getOpt("mplex"))), fx.Provide(libp2p.Relay(cfg.Swarm.DisableRelay, cfg.Swarm.EnableRelayHop)), fx.Invoke(libp2p.StartListening(cfg.Addresses.Swarm)), + fx.Invoke(libp2p.SetupDiscovery(cfg.Discovery.MDNS.Enabled, cfg.Discovery.MDNS.Interval)), fx.Provide(libp2p.Security(!bcfg.DisableEncryptedConnections, cfg.Experimental.PreferTLS)),
Merge pull request #<I> from sanderpick/sander/move-discovery libp2p: moves discovery after host listen
ipfs_go-ipfs
train
c679f7a75f56d6d920d4bce4936862bed7fab480
diff --git a/spark/components/accordions/react/SprkAccordionItem.js b/spark/components/accordions/react/SprkAccordionItem.js index <HASH>..<HASH> 100644 --- a/spark/components/accordions/react/SprkAccordionItem.js +++ b/spark/components/accordions/react/SprkAccordionItem.js @@ -98,23 +98,23 @@ SprkAccordionItem.defaultProps = { }; SprkAccordionItem.propTypes = { - // Content for the item + /** Content for the item */ children: PropTypes.node, - // Value for the data-analytics attribute on the accordion trigger + /** Value for the data-analytics attribute on the accordion trigger */ analyticsString: PropTypes.string, - // The item heading + /** The item heading */ heading: PropTypes.string.isRequired, - // Additional classes for the heading + /** Additional classes for the heading */ headingAddClasses: PropTypes.string, - // Additional classes for the item + /** Additional classes for the item */ additionalClasses: PropTypes.string, - // The data-id value for the accordion item + /** The data-id value for the accordion item */ idString: PropTypes.string, - // Used to specify whether the item should be open by default + /** Used to specify whether the item should be open by default */ isDefaultOpen: PropTypes.bool, - // Additional classes for the toggle icon + /** Additional classes for the toggle icon */ iconAddClasses: PropTypes.string, - // Additional classes for the toggle content + /** Additional classes for the toggle content */ contentAddClasses: PropTypes.string, };
Update comments for SprkAccordionItem
sparkdesignsystem_spark-design-system
train
beb9e22e105cb6cbbbea21c3c3542566d9d700e3
diff --git a/webpack.config.js b/webpack.config.js index <HASH>..<HASH> 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -14,18 +14,19 @@ const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin'); const MinimizeJSPlugin = require('terser-webpack-plugin'); const PostBuild = require('./src/utils/post-build'); -const pkg = require('./package.json'); +module.exports = (env, argv, dir = __dirname) => { + const pkg = require(path.resolve(dir, './package.json')); + + const banner = `/*! + * ${pkg.name} - ${pkg.description} + * Author: ${pkg.author} + * Version: v${pkg.version} + * Url: ${pkg.homepage} + * License(s): ${pkg.license} + */ + `; -const banner = `/*! - ${pkg.name} - ${pkg.description} - Author: ${pkg.author} - Version: v${pkg.version} - Url: ${pkg.homepage} - License(s): ${pkg.license} -*/ -`; -module.exports = (env, argv, dir = __dirname) => { const debug = !argv || !argv.mode || !argv.mode.match(/production/); const isTest = argv && Boolean(argv.isTest);
Added possibility to change dev port
xdan_jodit
train
5c64feb2799333bc97d94a719c234675bbc7d870
diff --git a/tests/integration/reactor/test_reactor.py b/tests/integration/reactor/test_reactor.py index <HASH>..<HASH> 100644 --- a/tests/integration/reactor/test_reactor.py +++ b/tests/integration/reactor/test_reactor.py @@ -35,4 +35,4 @@ class ReactorTest(ModuleCase, SaltMinionEventAssertsMixin): e.fire_event({'a': 'b'}, '/test_event') - self.assertMinionEventReceived({'a': 'b'}) + self.assertMinionEventReceived({'a': 'b'}, timeout=30) diff --git a/tests/support/mixins.py b/tests/support/mixins.py index <HASH>..<HASH> 100644 --- a/tests/support/mixins.py +++ b/tests/support/mixins.py @@ -687,10 +687,10 @@ class SaltMinionEventAssertsMixin(object): #TODO raise salt.exceptions.NotImplemented('assertMinionEventFired() not implemented') - def assertMinionEventReceived(self, desired_event): - queue_wait = 5 # 2.5s + def assertMinionEventReceived(self, desired_event, timeout=5, sleep_time=0.5): + queue_wait = timeout / sleep_time while self.q.empty(): - time.sleep(0.5) # Wait for events to be pushed into the queue + time.sleep(sleep_time) # Wait for events to be pushed into the queue queue_wait -= 1 if queue_wait <= 0: raise AssertionError('Queue wait timer expired')
Wait longer for ping reaction Wait longer for the ping reaction in case there are multiple events on the bus and/or high load on the system running tests
saltstack_salt
train
0c1d3cfaf825d27d84b7bad519987158bf1f727e
diff --git a/etk/core.py b/etk/core.py index <HASH>..<HASH> 100644 --- a/etk/core.py +++ b/etk/core.py @@ -61,6 +61,8 @@ _LANDMARK_RULES = 'landmark_rules' _URL = 'url' _AGE = 'age' _POSTING_DATE = 'posting_date' +_SOCIAL_MEDIA = 'social_media' +_ADDRESS = 'address' _RESOURCES = 'resources' _DATA_EXTRACTION = 'data_extraction' _FIELDS = 'fields' @@ -121,10 +123,11 @@ class Core(object): self.content_extraction_path = None self.data_extraction_path = dict() if load_spacy: - self.load_matchers() + self.prep_spacy() else: self.nlp = None self.country_code_dict = None + self.matchers = dict() """ Define all API methods """ @@ -747,23 +750,22 @@ class Core(object): return None def extract_using_spacy(self, d, config): - field = config[_FIELD_NAME] - if _SPACY_EXTRACTION not in d: - d[_SPACY_EXTRACTION] = self.run_spacy_extraction(d) - return d[_SPACY_EXTRACTION][field] if field in d[_SPACY_EXTRACTION] else None - - def run_spacy_extraction(self, d): + field_name = config[_FIELD_NAME] if not self.nlp: - self.load_matchers() + self.prep_spacy() nlp_doc = self.nlp(d[_SIMPLE_TOKENS]) - spacy_extractions = dict() - - spacy_extractions[_POSTING_DATE] = self._relevant_text_from_context(d[_SIMPLE_TOKENS], spacy_date_extractor. - extract(nlp_doc, self.matchers['date']), _POSTING_DATE) - spacy_extractions[_AGE] = self._relevant_text_from_context(d[_SIMPLE_TOKENS], - spacy_age_extractor.extract(nlp_doc, self.matchers['age']), _AGE) - return spacy_extractions + self.load_matchers(field_name) + results = None + if field_name == _AGE: + results = self._relevant_text_from_context(d[_SIMPLE_TOKENS], spacy_age_extractor.extract(nlp_doc, self.matchers[_AGE]), _AGE) + elif field_name == _POSTING_DATE: + results = self._relevant_text_from_context(d[_SIMPLE_TOKENS], spacy_date_extractor.extract(nlp_doc, self.matchers[_POSTING_DATE]), _POSTING_DATE) + elif field_name == _SOCIAL_MEDIA: + results = self._relevant_text_from_context(d[_SIMPLE_TOKENS], spacy_social_media_extractor.extract(nlp_doc, self.matchers[_SOCIAL_MEDIA]), _SOCIAL_MEDIA) + elif field_name == _ADDRESS: + results = self._relevant_text_from_context(d[_SIMPLE_TOKENS], spacy_address_extractor.extract(nlp_doc, self.matchers[_ADDRESS]), _ADDRESS) + return results def extract_from_landmark(self, doc, config): field_name = config[_FIELD_NAME] @@ -997,29 +999,26 @@ class Core(object): def extract_landmark(html, url, extraction_rules, threshold=0.5): return landmark_extraction.extract(html, url, extraction_rules, threshold) - def load_matchers(self): + def prep_spacy(self): self.nlp = spacy.load('en') self.old_tokenizer = self.nlp.tokenizer - self.nlp.tokenizer = lambda tokens: self.old_tokenizer.tokens_from_list( - tokens) - - matchers = dict() - - # Load date_extractor matcher - matchers['date'] = spacy_date_extractor.load_date_matcher(self.nlp) - - # Load age_extractor matcher - matchers['age'] = spacy_age_extractor.load_age_matcher(self.nlp) - - # Load social_media_extractor matcher - matchers['social_media'] = spacy_social_media_extractor.load_social_media_matcher( - self.nlp) - - # Load address matcher - matchers['address'] = spacy_address_extractor.load_address_matcher( - self.nlp) - - self.matchers = matchers + self.nlp.tokenizer = lambda tokens: self.old_tokenizer.tokens_from_list(tokens) + + def load_matchers(self, field_name=None): + if field_name: + if field_name == _AGE: + if _AGE not in self.matchers: + self.matchers[_AGE] = spacy_age_extractor.load_age_matcher(self.nlp) + + if field_name == _POSTING_DATE: + if _POSTING_DATE not in self.matchers: + self.matchers[_POSTING_DATE] = spacy_date_extractor.load_date_matcher(self.nlp) + if field_name == _SOCIAL_MEDIA: + if _SOCIAL_MEDIA not in self.matchers: + self.matchers[_SOCIAL_MEDIA] = spacy_social_media_extractor.load_social_media_matcher(self.nlp) + if field_name == _ADDRESS: + if _ADDRESS not in self.matchers: + self.matchers[_ADDRESS] = spacy_address_extractor.load_address_matcher(self.nlp) @staticmethod def create_list_data_extraction(data_extraction, field_name, method=_EXTRACT_USING_DICTIONARY):
load spacy matchers as needed
usc-isi-i2_etk
train
e18515a84fb1fe3299700f18c9e3daf353bfca83
diff --git a/test/install-init_test.js b/test/install-init_test.js index <HASH>..<HASH> 100644 --- a/test/install-init_test.js +++ b/test/install-init_test.js @@ -26,11 +26,31 @@ exports['install-init'] = { done(); }, 'multiTask': function(test) { - test.expect(0); - // Locate {{user directory}}/tasks/init - var initDir = grunt.file.userDir('tasks/init'); + var path = require('path'), + initDir = grunt.file.userDir('tasks/init'); + + // Collect the files to assert existence of + var srcFiles = grunt.file.expandFiles({'dot': true}, 'test_files/**'); + + // There will be one assertion per file and one in the end for any errors + test.expect(srcFiles.length); + + // Iterate over each file + srcFiles.forEach(function (srcFile) { + // Remove test_files from srcFile + var _srcFile = srcFile.replace('test_files', ''), + destFile = path.join(initDir, _srcFile); + + // Read in ours and their file + var expectedContent = grunt.file.read(srcFile), + actualContent = grunt.file.read(destFile); + + // Assert that they are the same + test.equal(actualContent, expectedContent, srcFile + ' did not match ' + destFile); + }); + // Callback now that the test is done test.done(); } };
Init test should be passing but it seems not to be
twolfson_grunt-install-init
train
9267307f47ada256f3b0704df44599dc33b1f9cd
diff --git a/supervisor.go b/supervisor.go index <HASH>..<HASH> 100644 --- a/supervisor.go +++ b/supervisor.go @@ -94,7 +94,7 @@ func (s *Supervisor) prepare() { s.backoff = make(map[string]*backoff) s.cancelations = make(map[string]context.CancelFunc) s.services = make(map[string]Service) - s.startedServices = make(chan struct{}) + s.startedServices = make(chan struct{}, 1) s.stoppedService = make(chan struct{}, 1) if s.Log == nil {
fix a deadlock in a test when adding a service after supervisor is started
cirello-io_supervisor
train
bdedf1938e8ffa5f7e2753dae93bc49229a451ee
diff --git a/src/JoomlaBrowser.php b/src/JoomlaBrowser.php index <HASH>..<HASH> 100644 --- a/src/JoomlaBrowser.php +++ b/src/JoomlaBrowser.php @@ -763,7 +763,7 @@ class JoomlaBrowser extends WebDriver { $this->debug("Searching for $name"); $this->fillField(['id' => "filter_search"], $name); - $this->click(['xpath' => "//button[@type='submit' and @data-original-title='Search']"]); + $this->click(['xpath' => "//button[@title='Search']"]); return; } @@ -925,22 +925,19 @@ class JoomlaBrowser extends WebDriver switch ($input) { case "new": - $this->click(['xpath' => "//div[@id='toolbar-new']//button"]); - break; - case "edit": - $this->click(['xpath' => "//div[@id='toolbar-edit']//button"]); + $this->click(['id' => "toolbar-new"]); break; case "publish": - $this->click(['xpath' => "//div[@id='toolbar-publish']//button"]); + $this->click(['id' => "toolbar-publish"]); break; case "unpublish": - $this->click(['xpath' => "//div[@id='toolbar-unpublish']//button"]); + $this->click(['id' => "toolbar-unpublish"]); break; case "archive": - $this->click(['xpath' => "//div[@id='toolbar-archive']//button"]); + $this->click(['id' => "toolbar-archive"]); break; case "check-in": - $this->click(['xpath' => "//div[@id='toolbar-checkin']//button"]); + $this->click(['id' => "'toolbar-checkin"]); break; case "batch": $this->click(['xpath' => "//div[@id='toolbar-batch']//button"]); @@ -949,25 +946,28 @@ class JoomlaBrowser extends WebDriver $this->click(['xpath' => "//div[@id='toolbar-refresh']//button"]); break; case "trash": - $this->click(['xpath' => "//div[@id='toolbar-trash']//button"]); + $this->click(['id' => "toolbar-trash"]); break; case "save": - $this->click(['xpath' => "//div[@id='toolbar-apply']//button"]); + $this->click(['id' => "toolbar-apply"]); break; case "save & close": - $this->click(['xpath' => "//div[@id='toolbar-save']//button"]); + $this->click(['id' => "toolbar-save"]); break; case "save & new": - $this->click(['xpath' => "//div[@id='toolbar-save-new']//button"]); + $this->click(['id' => "toolbar-save-new"]); break; case "cancel": - $this->click(['xpath' => "//div[@id='toolbar-cancel']//button"]); + $this->click(['id' => "toolbar-cancel"]); break; case "options": - $this->click(['xpath' => "//div[@id='toolbar-options']//button"]); + $this->click(['id' => "toolbar-options"]); break; case "empty trash": - $this->click(['xpath' => "//div[@id='toolbar-delete']//button"]); + $this->click(['id' => "toolbar-"]); + break; + case "feature": + $this->click(['id' => "toolbar-featured"]); break; } } @@ -1101,8 +1101,8 @@ class JoomlaBrowser extends WebDriver { $this->debug('I click on never'); $this->wait(1); - $this->waitForElement(['class' => 'js-pstats-btn-allow-always'], TIMEOUT); - $this->click(['class' => 'js-pstats-btn-allow-always']); + $this->waitForElement(['link' => 'Always'], TIMEOUT); + $this->click(['link' => 'Always']); } /**
Updating Locator for Statistics Disable in Joomla 4 (#<I>) * Updating Locator for Statistics Disable in Joomla 4 * Updating Some more Locators
joomla-projects_joomla-browser
train
1af9cac6375b7bd27efdab5caf8b5d4c741c67e9
diff --git a/benchmarks/main_test.go b/benchmarks/main_test.go index <HASH>..<HASH> 100644 --- a/benchmarks/main_test.go +++ b/benchmarks/main_test.go @@ -3,8 +3,8 @@ package benchmarks import ( "io/ioutil" - "github.com/tdewolff/buffer" "github.com/tdewolff/minify" + "github.com/tdewolff/parse/buffer" ) var m = minify.New() diff --git a/common.go b/common.go index <HASH>..<HASH> 100644 --- a/common.go +++ b/common.go @@ -6,7 +6,7 @@ import ( "net/url" "github.com/tdewolff/parse" - "github.com/tdewolff/strconv" + "github.com/tdewolff/parse/strconv" ) // Epsilon is the closest number to zero that is not considered to be zero. diff --git a/html/html.go b/html/html.go index <HASH>..<HASH> 100644 --- a/html/html.go +++ b/html/html.go @@ -5,9 +5,9 @@ import ( "bytes" "io" - "github.com/tdewolff/buffer" "github.com/tdewolff/minify" "github.com/tdewolff/parse" + "github.com/tdewolff/parse/buffer" "github.com/tdewolff/parse/html" ) diff --git a/svg/pathdata.go b/svg/pathdata.go index <HASH>..<HASH> 100644 --- a/svg/pathdata.go +++ b/svg/pathdata.go @@ -5,7 +5,7 @@ import ( "github.com/tdewolff/minify" "github.com/tdewolff/parse" - "github.com/tdewolff/strconv" + "github.com/tdewolff/parse/strconv" ) type PathData struct { diff --git a/svg/svg.go b/svg/svg.go index <HASH>..<HASH> 100644 --- a/svg/svg.go +++ b/svg/svg.go @@ -5,10 +5,10 @@ import ( "bytes" "io" - "github.com/tdewolff/buffer" "github.com/tdewolff/minify" minifyCSS "github.com/tdewolff/minify/css" "github.com/tdewolff/parse" + "github.com/tdewolff/parse/buffer" "github.com/tdewolff/parse/css" "github.com/tdewolff/parse/svg" "github.com/tdewolff/parse/xml"
Merge buffer and strconv packages
tdewolff_minify
train
8c25ce0205b8187a6fc00372505f8a08e5cf95dd
diff --git a/fog-core.gemspec b/fog-core.gemspec index <HASH>..<HASH> 100644 --- a/fog-core.gemspec +++ b/fog-core.gemspec @@ -5,7 +5,7 @@ require 'fog/core/version' Gem::Specification.new do |spec| spec.name = "fog-core" - spec.version = Fog::VERSION + spec.version = Fog::Core::VERSION spec.authors = ["Evan Light", "Wesley Beary"] spec.email = ["evan@tripledogdare.net", "geemus@gmail.com"] spec.summary = %q{Shared classes and tests for fog providers and services.} diff --git a/lib/fog/core/connection.rb b/lib/fog/core/connection.rb index <HASH>..<HASH> 100644 --- a/lib/fog/core/connection.rb +++ b/lib/fog/core/connection.rb @@ -34,7 +34,7 @@ module Fog params[:debug_response] = true unless params.key?(:debug_response) params[:headers] ||= {} - params[:headers]["User-Agent"] ||= "fog/#{Fog::VERSION}" + params[:headers]["User-Agent"] ||= "fog/#{Fog::Core::VERSION}" params.merge!(:persistent => params.fetch(:persistent, persistent)) @excon = Excon.new(url, params) end diff --git a/lib/fog/core/version.rb b/lib/fog/core/version.rb index <HASH>..<HASH> 100644 --- a/lib/fog/core/version.rb +++ b/lib/fog/core/version.rb @@ -1,3 +1,5 @@ module Fog - VERSION = "1.24.0" + module Core + VERSION = "1.24.0" + end end diff --git a/spec/connection_spec.rb b/spec/connection_spec.rb index <HASH>..<HASH> 100644 --- a/spec/connection_spec.rb +++ b/spec/connection_spec.rb @@ -14,9 +14,9 @@ describe Fog::Core::Connection do end end - it "writes the Fog::VERSION to the User-Agent header" do + it "writes the Fog::Core::VERSION to the User-Agent header" do connection = Fog::Core::Connection.new("http://example.com") - assert_equal "fog/#{Fog::VERSION}", + assert_equal "fog/#{Fog::Core::VERSION}", connection.instance_variable_get(:@excon).data[:headers]["User-Agent"] end
Fix conflict with the main Fog gem The fog gem depends on `fog-provider*` gems that depende on `fog-core`. Both define the same constant `Fog::Version` which might conflicting.
fog_fog-core
train
22f31f5b002bb714d7eef943bcca744f03909041
diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index <HASH>..<HASH> 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -2193,6 +2193,10 @@ public abstract class Maybe<T> implements MaybeSource<T> { * Returns a Maybe that emits the item emitted by the source Maybe or a specified default item * if the source Maybe is empty. * <p> + * Note that the result Maybe is semantically equivalent to a {@code Single}, since it's guaranteed + * to emit exactly one item or an error. See {@link #toSingle(Object)} for a method with equivalent + * behavior which returns a {@code Single}. + * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/defaultIfEmpty.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> diff --git a/src/test/java/io/reactivex/JavadocWording.java b/src/test/java/io/reactivex/JavadocWording.java index <HASH>..<HASH> 100644 --- a/src/test/java/io/reactivex/JavadocWording.java +++ b/src/test/java/io/reactivex/JavadocWording.java @@ -148,9 +148,11 @@ public class JavadocWording { for (;;) { int idx = m.javadoc.indexOf("Single", jdx); if (idx >= 0) { - if (!m.signature.contains("Single")) { + int j = m.javadoc.indexOf("#toSingle", jdx); + int k = m.javadoc.indexOf("{@code Single", jdx); + if (!m.signature.contains("Single") && (j + 3 != idx && k + 7 != idx)) { e.append("java.lang.RuntimeException: Maybe doc mentions Single but not in the signature\r\n at io.reactivex.") - .append("Maybe (Maybe.java:").append(m.javadocLine + lineNumber(m.javadoc, idx) - 1).append(")\r\n\r\n"); + .append("Maybe(Maybe.java:").append(m.javadocLine + lineNumber(m.javadoc, idx) - 1).append(")\r\n\r\n"); } jdx = idx + 6; } else {
2.x: small note on Maybe.defaultIfEmpty regarding toSingle (#<I>)
ReactiveX_RxJava
train
921a1d10510ba7da7430e1f9a6a8d4fdbe7e8839
diff --git a/src/Mailer/Message.php b/src/Mailer/Message.php index <HASH>..<HASH> 100644 --- a/src/Mailer/Message.php +++ b/src/Mailer/Message.php @@ -1236,6 +1236,21 @@ class Message implements JsonSerializable, Serializable } /** + * Get generated body as string. + * + * @param string $eol End of line string for imploding. + * @return string + * @see Message::getBody() + */ + public function getBodyString(string $eol = "\r\n"): string + { + /** @var array $lines */ + $lines = $this->getBody(); + + return implode($eol, $lines); + } + + /** * Create unique boundary identifier * * @return void diff --git a/src/Mailer/Transport/MailTransport.php b/src/Mailer/Transport/MailTransport.php index <HASH>..<HASH> 100644 --- a/src/Mailer/Transport/MailTransport.php +++ b/src/Mailer/Transport/MailTransport.php @@ -58,7 +58,7 @@ class MailTransport extends AbstractTransport $subject = str_replace(["\r", "\n"], '', $message->getSubject()); $to = str_replace(["\r", "\n"], '', $to); - $message = implode($eol, (array)$message->getBody()); + $message = $message->getBodyString($eol); $params = $this->_config['additionalParameters'] ?? ''; $this->_mail($to, $subject, $message, $headers, $params);
Add method to get generated message body as string.
cakephp_cakephp
train
88c1bc10c4c2490789953e4d6065cab6e9b1585b
diff --git a/integration-cli/docker_cli_build_test.go b/integration-cli/docker_cli_build_test.go index <HASH>..<HASH> 100644 --- a/integration-cli/docker_cli_build_test.go +++ b/integration-cli/docker_cli_build_test.go @@ -759,7 +759,7 @@ ADD test_file .`, close(errChan) }() select { - case <-time.After(5 * time.Second): + case <-time.After(15 * time.Second): c.Fatal("Build with adding to workdir timed out") case err := <-errChan: c.Assert(err, check.IsNil) @@ -1408,7 +1408,7 @@ COPY test_file .`, close(errChan) }() select { - case <-time.After(5 * time.Second): + case <-time.After(15 * time.Second): c.Fatal("Build with adding to workdir timed out") case err := <-errChan: c.Assert(err, check.IsNil) diff --git a/integration-cli/docker_cli_events_test.go b/integration-cli/docker_cli_events_test.go index <HASH>..<HASH> 100644 --- a/integration-cli/docker_cli_events_test.go +++ b/integration-cli/docker_cli_events_test.go @@ -53,7 +53,7 @@ func (s *DockerSuite) TestEventsUntag(c *check.C) { dockerCmd(c, "rmi", "utest:tag1") dockerCmd(c, "rmi", "utest:tag2") eventsCmd := exec.Command(dockerBinary, "events", "--since=1") - out, exitCode, _, err := runCommandWithOutputForDuration(eventsCmd, time.Duration(time.Millisecond*500)) + out, exitCode, _, err := runCommandWithOutputForDuration(eventsCmd, time.Duration(time.Millisecond*2500)) c.Assert(err, checker.IsNil) c.Assert(exitCode, checker.Equals, 0, check.Commentf("Failed to get events")) events := strings.Split(out, "\n") diff --git a/integration-cli/docker_cli_exec_unix_test.go b/integration-cli/docker_cli_exec_unix_test.go index <HASH>..<HASH> 100644 --- a/integration-cli/docker_cli_exec_unix_test.go +++ b/integration-cli/docker_cli_exec_unix_test.go @@ -35,7 +35,7 @@ func (s *DockerSuite) TestExecInteractiveStdinClose(c *check.C) { c.Assert(err, checker.IsNil) output := b.String() c.Assert(strings.TrimSpace(output), checker.Equals, "hello") - case <-time.After(1 * time.Second): + case <-time.After(5 * time.Second): c.Fatal("timed out running docker exec") } } diff --git a/integration-cli/docker_cli_start_test.go b/integration-cli/docker_cli_start_test.go index <HASH>..<HASH> 100644 --- a/integration-cli/docker_cli_start_test.go +++ b/integration-cli/docker_cli_start_test.go @@ -33,7 +33,7 @@ func (s *DockerSuite) TestStartAttachReturnsOnError(c *check.C) { select { case err := <-ch: c.Assert(err, check.IsNil) - case <-time.After(time.Second): + case <-time.After(5 * time.Second): c.Fatalf("Attach did not exit properly") } } diff --git a/integration-cli/docker_utils.go b/integration-cli/docker_utils.go index <HASH>..<HASH> 100644 --- a/integration-cli/docker_utils.go +++ b/integration-cli/docker_utils.go @@ -1517,7 +1517,7 @@ func setupRegistry(c *check.C) *testRegistryV2 { c.Assert(err, check.IsNil) // Wait for registry to be ready to serve requests. - for i := 0; i != 5; i++ { + for i := 0; i != 50; i++ { if err = reg.Ping(); err == nil { break }
Increase timeouts to fix test on ARM
containers_storage
train
655ff2675ee651cb30e964434f2b83944900e0da
diff --git a/src/utils.js b/src/utils.js index <HASH>..<HASH> 100644 --- a/src/utils.js +++ b/src/utils.js @@ -74,20 +74,20 @@ export const detectInit = function (text, cnf) { let args = inits.map((init) => init.args); Object.keys(args).forEach((argKey) => { Object.keys(args[argKey]).forEach((key) => { - // if (key.indexOf('__') === 0) { - // log.debug('sanitize deleting prototype option', args[key]); - // delete args[argKey][key]; - // } - - // if (key.indexOf('proto') >= 0) { - // log.debug('sanitize deleting prototype option', args[key]); - // delete args[argKey][key]; - // } - - // if (key.indexOf('constr') >= 0) { - // log.debug('sanitize deleting prototype option', args[key]); - // delete args[argKey][key]; - // } + if (key.indexOf('__') === 0) { + log.debug('sanitize deleting prototype option', args[key]); + delete args[argKey][key]; + } + + if (key.indexOf('proto') >= 0) { + log.debug('sanitize deleting prototype option', args[key]); + delete args[argKey][key]; + } + + if (key.indexOf('constr') >= 0) { + log.debug('sanitize deleting prototype option', args[key]); + delete args[argKey][key]; + } if(configKeys.indexOf(key)<0) { log.debug('sanitize deleting option', args[argKey][key]); delete args[argKey][key];
#<I> Excluding using a black list as well
knsv_mermaid
train
6bfda949d6762779889a9917d4b0cbe6d8570198
diff --git a/internal/service/cognitoidp/risk_configuration.go b/internal/service/cognitoidp/risk_configuration.go index <HASH>..<HASH> 100644 --- a/internal/service/cognitoidp/risk_configuration.go +++ b/internal/service/cognitoidp/risk_configuration.go @@ -121,7 +121,7 @@ func ResourceRiskConfiguration() *schema.Resource { "html_body": { Type: schema.TypeString, Required: true, - ValidateFunc: validation.StringLenBetween(6, 2000), + ValidateFunc: validation.StringLenBetween(6, 20000), }, "subject": { Type: schema.TypeString, @@ -131,7 +131,7 @@ func ResourceRiskConfiguration() *schema.Resource { "text_body": { Type: schema.TypeString, Required: true, - ValidateFunc: validation.StringLenBetween(6, 2000), + ValidateFunc: validation.StringLenBetween(6, 20000), }, }, }, @@ -149,7 +149,7 @@ func ResourceRiskConfiguration() *schema.Resource { "html_body": { Type: schema.TypeString, Required: true, - ValidateFunc: validation.StringLenBetween(6, 2000), + ValidateFunc: validation.StringLenBetween(6, 20000), }, "subject": { Type: schema.TypeString, @@ -159,7 +159,7 @@ func ResourceRiskConfiguration() *schema.Resource { "text_body": { Type: schema.TypeString, Required: true, - ValidateFunc: validation.StringLenBetween(6, 2000), + ValidateFunc: validation.StringLenBetween(6, 20000), }, }, }, @@ -173,7 +173,7 @@ func ResourceRiskConfiguration() *schema.Resource { "html_body": { Type: schema.TypeString, Required: true, - ValidateFunc: validation.StringLenBetween(6, 2000), + ValidateFunc: validation.StringLenBetween(6, 20000), }, "subject": { Type: schema.TypeString, @@ -183,7 +183,7 @@ func ResourceRiskConfiguration() *schema.Resource { "text_body": { Type: schema.TypeString, Required: true, - ValidateFunc: validation.StringLenBetween(6, 2000), + ValidateFunc: validation.StringLenBetween(6, 20000), }, }, },
#<I> fix typo; maximum size is <I>, not <I>
terraform-providers_terraform-provider-aws
train
f3069f460565af19a27b941b17af3869fd46f590
diff --git a/spec/functional/resource/mount_spec.rb b/spec/functional/resource/mount_spec.rb index <HASH>..<HASH> 100644 --- a/spec/functional/resource/mount_spec.rb +++ b/spec/functional/resource/mount_spec.rb @@ -43,6 +43,13 @@ describe Chef::Resource::Mount, :requires_root, :external => include_flag do shell_out!("mkfs -V #{fstype} #{device}") when "ubuntu", "centos" device = "/dev/ram1" + shell_out("ls -1 /dev/ram*").stdout.each_line do |d| + if shell_out("mount | grep #{d}").exitstatus == "1" + # this device is not mounted, so use it. + device = d + break + end + end fstype = "tmpfs" shell_out!("mkfs -q #{device} 512") else
mount functional test- use free ramdisk device for tests.
chef_chef
train
af3f7c866e195707f0bdc648692615d6269b2f3a
diff --git a/lib/websearch_blueprint.py b/lib/websearch_blueprint.py index <HASH>..<HASH> 100644 --- a/lib/websearch_blueprint.py +++ b/lib/websearch_blueprint.py @@ -22,16 +22,18 @@ import json import string import functools +import cStringIO from math import ceil from flask import make_response, g, request, flash, jsonify, \ - redirect, url_for, current_app, abort + redirect, url_for, current_app, abort, session from invenio import bibindex_model as BibIndex from invenio import websearch_receivers from invenio.bibindex_engine import get_index_id_from_index_name from invenio.bibformat import get_output_format_content_type, print_records from invenio.cache import cache -from invenio.config import CFG_WEBSEARCH_RSS_TTL +from invenio.config import CFG_WEBSEARCH_RSS_TTL, \ + CFG_WEBSEARCH_PREV_NEXT_HIT_LIMIT from invenio.websearch_cache import \ get_search_query_id, get_collection_name_from_cache from invenio.access_control_engine import acc_authorize_action @@ -50,7 +52,7 @@ from invenio.websearch_facet_builders import \ from invenio.search_engine import get_creation_date, perform_request_search,\ print_record, create_nearest_terms_box, browse_pattern_phrases from invenio.paginationutils import Pagination - + blueprint = InvenioBlueprint('search', __name__, url_prefix="", config='invenio.search_engine_config', breadcrumbs=[], @@ -374,6 +376,19 @@ def search(collection, p, of, so, rm): if len(of)>0 and of[0] == 'h': recids.reverse() + # back-to-search related code + if request and not isinstance(request.get_legacy_request(), cStringIO.OutputType): + # store the last search results page + session['websearch-last-query'] = request.get_legacy_request().unparsed_uri + if len(recids) > CFG_WEBSEARCH_PREV_NEXT_HIT_LIMIT: + last_query_hits = None + else: + last_query_hits = recids + # store list of results if user wants to display hits + # in a single list, or store list of collections of records + # if user displays hits split by collections: + session["websearch-last-query-hits"] = last_query_hits + ctx = dict(facets=FACETS.config(collection=collection, qid=qid), records=len(get_current_user_records_that_can_be_displayed(qid)), qid=qid, rg=rg,
BibFormat: port back-to-search links * Revives links displayed on the detailed view of a record to let users flip quickly between detailed record pages. Conflicts: modules/bibformat/etc/templates/format_templates/Default_HTML_detailed.tpl modules/webstyle/css/invenio.css
inveniosoftware_invenio-records
train
70c1f0be7a3f11348c6c2ec402a7dbd8e8037c95
diff --git a/sprinter/directory.py b/sprinter/directory.py index <HASH>..<HASH> 100644 --- a/sprinter/directory.py +++ b/sprinter/directory.py @@ -8,17 +8,14 @@ import os import shutil import stat -# .rc sources .env if necessary (sentinel not set) +# .rc always sources .env rc_template = """ -if [ -z "$%s" -a -r "%s" ]; then - . %s -fi +[ -r "%s" ] && . %s """ -# .env sources util.sh if necessary, then exports sentinel +# .env sources util.sh if necessary env_template = """ declare -f sprinter_prepend_path > /dev/null || . %s -export %s=1 """ # utils.sh is the same for every namespace, only sourced once @@ -51,7 +48,6 @@ class Directory(object): # preserved, and will not be modifiable rc_file = None # file handler for rc file env_file = None # file handler for env file - sentinel_var = None # env var used by .rc to indicate if .env has been sourced def __init__(self, namespace, rewrite_config=True, sprinter_root=os.path.join("~", ".sprinter"), logger=logging.getLogger('sprinter')): @@ -62,7 +58,6 @@ class Directory(object): self.manifest_path = os.path.join(self.root_dir, "manifest.cfg") self.utils_path = os.path.join(self.root_dir, "utils.sh") self.rewrite_config = rewrite_config - self.sentinel_var = "SPRINTER_INIT_%s" % namespace.upper() def __del__(self): if self.rc_file: @@ -174,7 +169,7 @@ class Directory(object): if not os.path.exists(env_path): fh = open(env_path, "w+") # .env will source utils.sh if it hasn't already - fh.write(env_template % (self.utils_path, self.sentinel_var)) + fh.write(env_template % self.utils_path) return (env_path, open(env_path, "w+")) def __get_rc_handle(self, root_dir): @@ -182,9 +177,9 @@ class Directory(object): rc_path = os.path.join(root_dir, '.rc') if not os.path.exists(rc_path): fh = open(rc_path, "w+") - # .rc will source .env if it hasn't already + # .rc will always source .env env_path = os.path.join(root_dir, '.env') - fh.write(rc_template % (self.sentinel_var, env_path, env_path)) + fh.write(rc_template % (env_path, env_path)) return (rc_path, open(rc_path, "w+")) def __symlink_dir(self, dir_name, name, path):
.rc always sources .env, and does not export sentinel.
toumorokoshi_sprinter
train
6f6a1682eb02b8f3d78c67f63a2231ed01f9d6ee
diff --git a/src/Sulu/Bundle/SecurityBundle/Tests/Functional/Controller/UserControllerTest.php b/src/Sulu/Bundle/SecurityBundle/Tests/Functional/Controller/UserControllerTest.php index <HASH>..<HASH> 100644 --- a/src/Sulu/Bundle/SecurityBundle/Tests/Functional/Controller/UserControllerTest.php +++ b/src/Sulu/Bundle/SecurityBundle/Tests/Functional/Controller/UserControllerTest.php @@ -785,18 +785,18 @@ class UserControllerTest extends SuluTestCase $user = $users[0]; $contact = $user->contact; - $this->assertFalse(property_exists($contact, 'account')); - $this->assertFalse(property_exists($contact, 'phones')); - $this->assertFalse(property_exists($contact, 'faxes')); - $this->assertFalse(property_exists($contact, 'emails')); - $this->assertFalse(property_exists($contact, 'position')); - $this->assertFalse(property_exists($contact, 'addresses')); - $this->assertFalse(property_exists($contact, 'notes')); - $this->assertFalse(property_exists($contact, 'tags')); - $this->assertFalse(property_exists($contact, 'medias')); - $this->assertFalse(property_exists($contact, 'categories')); - $this->assertFalse(property_exists($contact, 'urls')); - $this->assertFalse(property_exists($contact, 'bankaccounts')); + $this->assertObjectNotHasAttribute('account', $contact); + $this->assertObjectNotHasAttribute('phones', $contact); + $this->assertObjectNotHasAttribute('faxes', $contact); + $this->assertObjectNotHasAttribute('emails', $contact); + $this->assertObjectNotHasAttribute('position', $contact); + $this->assertObjectNotHasAttribute('addresses', $contact); + $this->assertObjectNotHasAttribute('notes', $contact); + $this->assertObjectNotHasAttribute('tags', $contact); + $this->assertObjectNotHasAttribute('medias', $contact); + $this->assertObjectNotHasAttribute('categories', $contact); + $this->assertObjectNotHasAttribute('urls', $contact); + $this->assertObjectNotHasAttribute('bankAccounts', $contact); } public function testPutWithRemovedRoles()
added objectNotHasAttribute assertion to tests
sulu_sulu
train
cb01a385e70d734f424e98142772af88ed76dafa
diff --git a/lib/Doctrine/ODM/MongoDB/UnitOfWork.php b/lib/Doctrine/ODM/MongoDB/UnitOfWork.php index <HASH>..<HASH> 100644 --- a/lib/Doctrine/ODM/MongoDB/UnitOfWork.php +++ b/lib/Doctrine/ODM/MongoDB/UnitOfWork.php @@ -690,7 +690,7 @@ class UnitOfWork implements PropertyChangedListener // and we have a copy of the original data $originalData = $this->originalDocumentData[$oid]; $isChangeTrackingNotify = $class->isChangeTrackingNotify(); - if ($isChangeTrackingNotify && ! $recompute) { + if ($isChangeTrackingNotify && ! $recompute && isset($this->documentChangeSets[$oid])) { $changeSet = $this->documentChangeSets[$oid]; } else { $changeSet = array(); diff --git a/tests/Doctrine/ODM/MongoDB/Tests/UnitOfWorkTest.php b/tests/Doctrine/ODM/MongoDB/Tests/UnitOfWorkTest.php index <HASH>..<HASH> 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/UnitOfWorkTest.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/UnitOfWorkTest.php @@ -240,6 +240,24 @@ class UnitOfWorkTest extends \Doctrine\ODM\MongoDB\Tests\BaseTest $this->assertTrue($updates[0] === $item); } + public function testDoubleCommitWithChangeTrackingNotify() + { + $pb = $this->getMockPersistenceBuilder(); + + $class = $this->dm->getClassMetadata('Doctrine\ODM\MongoDB\Tests\NotifyChangedDocument'); + $persister = $this->getMockDocumentPersister($pb, $class); + $this->uow->setDocumentPersister($class->name, $persister); + + $entity = new NotifyChangedDocument(); + $entity->setId(2); + $this->uow->persist($entity); + + $this->uow->commit($entity); + @$this->uow->commit($entity); + + $this->assertNull(error_get_last(), 'Expected not to get an error after committing an entity multiple times using the NOTIFY change tracking policy.'); + } + public function testGetDocumentStateWithAssignedIdentity() { $pb = $this->getMockPersistenceBuilder();
Committing multiple times with NOTIFY change tracking policy doesn't raise a notice error
doctrine_mongodb-odm
train
d0ff4a9e819d4ec4a37592eba48f51e1eeafaa46
diff --git a/src/Utils/XmlLoaderUtils.php b/src/Utils/XmlLoaderUtils.php index <HASH>..<HASH> 100644 --- a/src/Utils/XmlLoaderUtils.php +++ b/src/Utils/XmlLoaderUtils.php @@ -23,7 +23,10 @@ class XmlLoaderUtils throw new OpdsParserNotFoundException(); } - $content = fread($handle, filesize($file)); + + while (!feof($handle)) { + $content .= fread($handle, 8192); // 8192 : nombre d'octets équivalent à la taille d'un bloc + } fclose($handle); return new \SimpleXMLElement($content);
MBW-<I> update read file
BOOKEEN_opds-parser
train
4ebb28cb24fadcdf0efd3ec6af879c0cf76dd0e2
diff --git a/lib/fog/aws/requests/storage/copy_object.rb b/lib/fog/aws/requests/storage/copy_object.rb index <HASH>..<HASH> 100644 --- a/lib/fog/aws/requests/storage/copy_object.rb +++ b/lib/fog/aws/requests/storage/copy_object.rb @@ -55,7 +55,7 @@ module Fog response.status = 200 target_object = source_object.dup target_object.merge!({ - 'Name' => target_object_name + 'Key' => target_object_name }) target_bucket[:objects][target_object_name] = target_object response.body = {
We use 'Key' for all S3 objects now.
fog_fog
train
7bf58a555e4490b3d2783d5bfbf27e7370136c26
diff --git a/lib/core/core.js b/lib/core/core.js index <HASH>..<HASH> 100644 --- a/lib/core/core.js +++ b/lib/core/core.js @@ -122,4 +122,48 @@ return child; }; + // this will spawn a daemon process there will: + // 1. spawn a pump process + // 2. handle and store pump output + // 2a. a part of this output will the the PID of the watched process + // when the pump process dies: + // 3. the daemon will kill the watched process + // 4. the daemon will start a new pump process and send it the unhandled output (error message) + // when the daemon itself dies: + // 5. the pump process has continuously watched the daemon and know when it dies + // 6. pump will kill the watched process + // 7. pump will start a daemon + // 8. pump will kill itself + // 9a. the new daemon will start pump + // 9b. the pump will start a watched process + exports.spawnDaemon = function (options) { + var child = new Process({ + exec: process.execPath, + file: path.join(helpers.core, 'daemon.js'), + nested: true + }, options); + + child.close(); + return child; + }; + + // this will spawn an uattached pump process this way: + // 1. spawn a process (child) + // 2. close all std connections + // 3a. child will spawn a daemon or a pump process depending on the mode + // 3b. if mode was daemon it will spawn a pump process + // 3c. the pump process will spawn the desired process + // 4. the child will kill itself + exports.spawnProcess = function(options) { + var child = new Process({ + exec: process.execPath, + file: path.join(helpers.core, 'execute.js'), + nested: true + }, options); + + child.close(); + return child; + }; + + })();
[refactor] markup the daemon and unattached workflow
AndreasMadsen_immortal
train
d5ac1c475b9d00c8081250ab8689f8cdd893572b
diff --git a/SurveyorCore/src/main/java/org/wwarn/surveyor/client/mvp/view/table/CellTableServer.java b/SurveyorCore/src/main/java/org/wwarn/surveyor/client/mvp/view/table/CellTableServer.java index <HASH>..<HASH> 100644 --- a/SurveyorCore/src/main/java/org/wwarn/surveyor/client/mvp/view/table/CellTableServer.java +++ b/SurveyorCore/src/main/java/org/wwarn/surveyor/client/mvp/view/table/CellTableServer.java @@ -36,6 +36,7 @@ package org.wwarn.surveyor.client.mvp.view.table; import com.google.gwt.cell.client.ActionCell; import com.google.gwt.cell.client.ClickableTextCell; import com.google.gwt.cell.client.SafeHtmlCell; +import com.google.gwt.core.client.GWT; import com.google.gwt.i18n.client.NumberFormat; import com.google.gwt.safehtml.client.SafeHtmlTemplates; import com.google.gwt.safehtml.shared.SafeHtml; @@ -51,8 +52,11 @@ import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.view.client.HasRows; import com.google.gwt.view.client.ListDataProvider; import com.google.gwt.view.client.Range; +import com.google.web.bindery.event.shared.binder.EventBinder; +import com.google.web.bindery.event.shared.binder.EventHandler; import org.wwarn.mapcore.client.utils.StringUtils; import org.wwarn.surveyor.client.core.RecordList; +import org.wwarn.surveyor.client.event.ResultChangedEvent; import org.wwarn.surveyor.client.model.TableViewConfig; import org.wwarn.surveyor.client.mvp.ClientFactory; import org.wwarn.surveyor.client.mvp.SimpleClientFactory; @@ -65,37 +69,43 @@ import java.util.List; */ public class CellTableServer extends Composite { + ClientFactory clientFactory = SimpleClientFactory.getInstance(); + interface CellTableServerEventBinder extends EventBinder<CellTableServer> {}; + TableViewConfig tableViewConfig; CellTable<RecordList.Record> cellTable; - ClientFactory clientFactory = SimpleClientFactory.getInstance(); - SimplePager pager; DataAsyncDataProvider dataProviderAsync; public CellTableServer(TableViewConfig tableViewConfig) { + CellTableServerEventBinder eventBinder = GWT.create(CellTableServerEventBinder.class); + eventBinder.bindEventHandlers(this, clientFactory.getEventBus()); this.tableViewConfig = tableViewConfig; - cellTable = new CellTable<RecordList.Record>(); + initWidget(setupPanel()); + buildTable(); + createWithAsyncDataProvider(); + + } + + private VerticalPanel setupPanel(){ VerticalPanel panel = new VerticalPanel(); + cellTable = new CellTable<RecordList.Record>(); + cellTable.setPageSize(tableViewConfig.getPageSize()); pager = new SimplePager(); pager.setDisplay(cellTable); panel.add(cellTable); panel.add(pager); - initWidget(panel); - - cellTable.setPageSize(tableViewConfig.getPageSize()); + return panel; + } - buildTable(); - createWithAsyncDataProvider(); - } private void createWithAsyncDataProvider() { dataProviderAsync = new DataAsyncDataProvider(tableViewConfig); dataProviderAsync.addDataDisplay(cellTable); - } @@ -138,7 +148,6 @@ public class CellTableServer extends Composite { } }; } - cellTable.addColumn(tableColumn, column.getFieldTitle()); } @@ -148,32 +157,9 @@ public class CellTableServer extends Composite { return fieldName.startsWith("func"); } -// public class MySimplePager extends SimplePager { -// -// public MySimplePager() { -// this.setRangeLimited(true); -// } -// -// public MySimplePager(TextLocation location, Resources resources, boolean showFastForwardButton, int fastForwardRows, boolean showLastPageButton) { -// super(location, resources, showFastForwardButton, fastForwardRows, showLastPageButton); -// this.setRangeLimited(true); -// } -// -// public void setPageStart(int index) { -// -// if (this.getDisplay() != null) { -// Range range = getDisplay().getVisibleRange(); -// int pageSize = range.getLength(); -// if (!isRangeLimited() && getDisplay().isRowCountExact()) { -// index = Math.min(index, getDisplay().getRowCount() - pageSize); -// } -// index = Math.max(0, index); -// if (index != range.getStart()) { -// getDisplay().setVisibleRange(index, pageSize); -// } -// } -// } -// -// } + @EventHandler + public void onResultChanged(ResultChangedEvent resultChangedEvent){ + pager.firstPage(); + } }
Bug: When the filters change, the table should show the first page.
WorldwideAntimalarialResistanceNetwork_WWARN-Maps-Surveyor
train
1fb56f9f1faa6617f9ea2a66bcc08c66c4d25da3
diff --git a/libcontainer/cgroups/devices/devices_emulator.go b/libcontainer/cgroups/devices/devices_emulator.go index <HASH>..<HASH> 100644 --- a/libcontainer/cgroups/devices/devices_emulator.go +++ b/libcontainer/cgroups/devices/devices_emulator.go @@ -258,9 +258,9 @@ func (e *Emulator) Apply(rule devices.Rule) error { if rule.Allow { return e.allow(innerRule) - } else { - return e.deny(innerRule) } + + return e.deny(innerRule) } // EmulatorFromList takes a reader to a "devices.list"-like source, and returns
libcontainer/cgroups/devices: if block ends with a return statement libcontainer/cgroups/devices/devices_emulator.go:<I>:9: `if` block ends with a `return` statement, so drop this `else` and outdent its block (golint) } else { ^
opencontainers_runc
train
a33b77005376bfbe33c54e362ce1afb92a9d0a7a
diff --git a/packages/eslint-config-4catalyzer-typescript/rules.js b/packages/eslint-config-4catalyzer-typescript/rules.js index <HASH>..<HASH> 100644 --- a/packages/eslint-config-4catalyzer-typescript/rules.js +++ b/packages/eslint-config-4catalyzer-typescript/rules.js @@ -24,7 +24,16 @@ module.exports = { 'typescript/no-parameter-properties': 'error', 'typescript/no-triple-slash-reference': 'error', 'no-unused-vars': 'off', - 'typescript/no-unused-vars': 'error', + 'typescript/no-unused-vars': [ + 'error', + { + vars: 'all', + varsIgnorePattern: '^_', + args: 'after-used', + ignoreRestSiblings: false, + argsIgnorePattern: '^_', + }, + ], 'typescript/no-use-before-define': 'error', 'typescript/no-var-requires': 'error', 'typescript/prefer-namespace-keyword': 'error',
fix: ts no-unused has same ingore pattern as js rule (#<I>)
4Catalyzer_javascript
train
7dc5752d654dca4b527baf6830c20afa7e79cf3d
diff --git a/lib/virtualmonkey/ebs.rb b/lib/virtualmonkey/ebs.rb index <HASH>..<HASH> 100644 --- a/lib/virtualmonkey/ebs.rb +++ b/lib/virtualmonkey/ebs.rb @@ -28,7 +28,7 @@ module VirtualMonkey # sets the lineage for the deployment # * kind<~String> can be "chef" or nil def set_variation_lineage(kind = nil) - @lineage = "testlineage#{rand(1000000)}" + @lineage = "testlineage#{@deployment.href.split(/\//).last}" if kind raise "Only support nil kind for ebs lineage" else diff --git a/lib/virtualmonkey/mysql.rb b/lib/virtualmonkey/mysql.rb index <HASH>..<HASH> 100644 --- a/lib/virtualmonkey/mysql.rb +++ b/lib/virtualmonkey/mysql.rb @@ -9,7 +9,7 @@ module VirtualMonkey # sets the lineage for the deployment # * kind<~String> can be "chef" or nil def set_variation_lineage(kind = nil) - @lineage = "testlineage#{rand(1000000)}" + @lineage = "testlineage#{@deployment.href.split(/\//).last}" if kind == "chef" @deployment.set_input('db/backup/lineage', "text:#{@lineage}") # unset all server level inputs in the deployment to ensure use of
Changed lineage from rand to deployment id
jeremyd_virtualmonkey
train
9e7f4e8199db3be14d0066082f0911f90a407760
diff --git a/lib/flor/pcore/_pat_obj.rb b/lib/flor/pcore/_pat_obj.rb index <HASH>..<HASH> 100644 --- a/lib/flor/pcore/_pat_obj.rb +++ b/lib/flor/pcore/_pat_obj.rb @@ -50,21 +50,43 @@ class Flor::Pro::PatObj < Flor::Pro::PatContainer def receive_non_att + key = @node['key'] ret = payload['ret'] - if key = @node['key'] - return wrap_no_match_reply unless val[key] == ret - @node['key'] = nil - else + unless key return wrap_no_match_reply unless val.has_key?(ret) @node['key'] = ret + return super + end + + ct = child_type(@fcid) + + if ct == :pattern + +# TODO + + elsif ct.is_a?(String) + + @node['binding'][ct] = val[@node['key']] if ct != '_' + + elsif ct.is_a?(Array) + +#p [ :else, ct ] +# TODO + + elsif val[key] != ret + + return wrap_no_match_reply unless val[key] == ret end + @node['key'] = nil + super end def receive_last +#p :rl payload['_pat_binding'] = @node['binding'] payload.delete('_pat_val') diff --git a/spec/pcore/_pat_obj_spec.rb b/spec/pcore/_pat_obj_spec.rb index <HASH>..<HASH> 100644 --- a/spec/pcore/_pat_obj_spec.rb +++ b/spec/pcore/_pat_obj_spec.rb @@ -22,6 +22,7 @@ describe 'Flor procedures' do [ %q{ _pat_obj \ a; 1 }, 1, nil ], [ %q{ _pat_obj \ a; 1 }, { 'a' => 2 }, nil ], [ %q{ _pat_obj \ a; 1 }, { 'a' => 1 }, {} ], + [ %q{ _pat_obj \ a; b }, { 'a' => 2 }, { 'b' => 2 } ], ].each do |code, val, expected|
Unlock binding for "_pat_obj"
floraison_flor
train
51e6c6cf0d5f8f51b23932dcad060ba7ac0d1b46
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -28,6 +28,9 @@ setup( 'scubainit', ], }, + data_files = [ + ('/etc/bash_completion.d', ['bash_completion/scuba']), + ], zip_safe = False, # http://stackoverflow.com/q/24642788/119527 entry_points = { 'console_scripts': [
completion: Install via setup.py
JonathonReinhart_scuba
train
995a0412984234d7c8f0aec6364df277b149a820
diff --git a/INSTALL.txt b/INSTALL.txt index <HASH>..<HASH> 100644 --- a/INSTALL.txt +++ b/INSTALL.txt @@ -11,9 +11,9 @@ into a directory that's on your Python path:: The other method is to download a packaged version and use Python's ``distutils`` to install it onto your Python path:: - wget http://django-contact-form.googlecode.com/files/contact_form-0.2.tar.gz - tar zxvf contact_form-0.2.tar.gz - cd contact-form-0.2 + wget http://django-contact-form.googlecode.com/files/contact_form-0.3.tar.gz + tar zxvf contact_form-0.3.tar.gz + cd contact-form-0.3 python setup.py install Depending on your system configuration, you may need to prefix the diff --git a/contact_form/forms.py b/contact_form/forms.py index <HASH>..<HASH> 100644 --- a/contact_form/forms.py +++ b/contact_form/forms.py @@ -4,13 +4,16 @@ a web interface, and a subclass demonstrating useful functionality. """ + import sha + from django import newforms as forms from django.conf import settings from django.core.mail import send_mail from django.template import loader, RequestContext from django.contrib.sites.models import Site + # I put this on all required fields, because it's easier to pick up # on them with CSS or JavaScript if they have a class of "required" # in the HTML. Your mileage may vary. diff --git a/contact_form/urls.py b/contact_form/urls.py index <HASH>..<HASH> 100644 --- a/contact_form/urls.py +++ b/contact_form/urls.py @@ -10,15 +10,18 @@ hierarchy (for best results with the defaults, include it under """ + from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template + from contact_form.views import contact_form + urlpatterns = patterns('', - url(r'^contact/$', + url(r'^$', contact_form, name='contact_form'), - url(r'^contact/sent/$', + url(r'^sent/$', direct_to_template, { 'template': 'contact_form/contact_form_sent.html' }, name='contact_form_sent'), diff --git a/contact_form/views.py b/contact_form/views.py index <HASH>..<HASH> 100644 --- a/contact_form/views.py +++ b/contact_form/views.py @@ -1,9 +1,17 @@ +""" +View which can render and send email from a contact form. + +""" + + from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.auth.views import redirect_to_login + from contact_form.forms import ContactForm + def contact_form(request, form_class=ContactForm, template_name='contact_form/contact_form.html', success_url='/contact/sent/', login_required=False, fail_silently=False): """ Renders a contact form, validates its input and sends an email diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -1,7 +1,7 @@ from distutils.core import setup setup(name='contact_form', - version='0.2', + version='0.3', description='Generic contact-form application for Django', author='James Bennett', author_email='james@b-list.org',
Couple fixes and tweaks, bumping to <I>
ubernostrum_django-contact-form
train
22ec5341e99aa6d0fbf3fc8cfbadad570dda876b
diff --git a/cairo/cairo.go b/cairo/cairo.go index <HASH>..<HASH> 100644 --- a/cairo/cairo.go +++ b/cairo/cairo.go @@ -2491,6 +2491,8 @@ func (surface *SurfaceObserver) Elapsed() float64 { } // See cairo_device_observer_elapsed(). +// +// C API documentation: http://cairographics.org/manual/cairo-cairo-device-t.html#cairo-device-observer-elapsed func (device *Device) ObserverElapsed() float64 { ret := float64(C.cairo_device_observer_elapsed(device.Ptr)) if err := device.status(); err != nil { @@ -2500,6 +2502,8 @@ func (device *Device) ObserverElapsed() float64 { } // See cairo_device_observer_paint_elapsed(). +// +// C API documentation: http://cairographics.org/manual/cairo-cairo-device-t.html#cairo-device-observer-paint-elapsed func (device *Device) ObserverPaintElapsed() float64 { ret := float64(C.cairo_device_observer_paint_elapsed(device.Ptr)) if err := device.status(); err != nil { @@ -2509,6 +2513,8 @@ func (device *Device) ObserverPaintElapsed() float64 { } // See cairo_device_observer_mask_elapsed(). +// +// C API documentation: http://cairographics.org/manual/cairo-cairo-device-t.html#cairo-device-observer-mask-elapsed func (device *Device) ObserverMaskElapsed() float64 { ret := float64(C.cairo_device_observer_mask_elapsed(device.Ptr)) if err := device.status(); err != nil { @@ -2518,6 +2524,8 @@ func (device *Device) ObserverMaskElapsed() float64 { } // See cairo_device_observer_fill_elapsed(). +// +// C API documentation: http://cairographics.org/manual/cairo-cairo-device-t.html#cairo-device-observer-fill-elapsed func (device *Device) ObserverFillElapsed() float64 { ret := float64(C.cairo_device_observer_fill_elapsed(device.Ptr)) if err := device.status(); err != nil { @@ -2527,6 +2535,8 @@ func (device *Device) ObserverFillElapsed() float64 { } // See cairo_device_observer_stroke_elapsed(). +// +// C API documentation: http://cairographics.org/manual/cairo-cairo-device-t.html#cairo-device-observer-stroke-elapsed func (device *Device) ObserverStrokeElapsed() float64 { ret := float64(C.cairo_device_observer_stroke_elapsed(device.Ptr)) if err := device.status(); err != nil { @@ -2536,6 +2546,8 @@ func (device *Device) ObserverStrokeElapsed() float64 { } // See cairo_device_observer_glyphs_elapsed(). +// +// C API documentation: http://cairographics.org/manual/cairo-cairo-device-t.html#cairo-device-observer-glyphs-elapsed func (device *Device) ObserverGlyphsElapsed() float64 { ret := float64(C.cairo_device_observer_glyphs_elapsed(device.Ptr)) if err := device.status(); err != nil { @@ -2739,6 +2751,8 @@ func (surface *Surface) MarkDirtyRectangle(x, y, width, height int) { } // See cairo_surface_set_device_scale(). +// +// C API documentation: http://cairographics.org/manual/cairo-cairo-surface-t.html#cairo-surface-set-device-scale func (surface *Surface) SetDeviceScale(xScale, yScale float64) { C.cairo_surface_set_device_scale(surface.Ptr, C.double(xScale), C.double(yScale)) if err := surface.status(); err != nil { @@ -2747,6 +2761,8 @@ func (surface *Surface) SetDeviceScale(xScale, yScale float64) { } // See cairo_surface_get_device_scale(). +// +// C API documentation: http://cairographics.org/manual/cairo-cairo-surface-t.html#cairo-surface-get-device-scale func (surface *Surface) GetDeviceScale() (float64, float64) { var xScale C.double var yScale C.double
more documentation links Unfortunately, links to documentation in the generated file depend on the local system's devhelp docs. Running the generator on my newer Arch system means we get more links.
evmar_gocairo
train
464a2d43519004174f1b530a595ee0ad9ffda870
diff --git a/pgjdbc/src/main/java/org/postgresql/jdbc/PgDatabaseMetaData.java b/pgjdbc/src/main/java/org/postgresql/jdbc/PgDatabaseMetaData.java index <HASH>..<HASH> 100644 --- a/pgjdbc/src/main/java/org/postgresql/jdbc/PgDatabaseMetaData.java +++ b/pgjdbc/src/main/java/org/postgresql/jdbc/PgDatabaseMetaData.java @@ -1137,7 +1137,7 @@ public class PgDatabaseMetaData implements DatabaseMetaData { if (returnTypeType.equals("c") || (returnTypeType.equals("p") && argModesArray != null)) { String columnsql = "SELECT a.attname,a.atttypid FROM pg_catalog.pg_attribute a " + " WHERE a.attrelid = " + returnTypeRelid - + " AND a.attnum > 0 ORDER BY a.attnum "; + + " AND NOT a.attisdropped AND a.attnum > 0 ORDER BY a.attnum "; Statement columnstmt = connection.createStatement(); ResultSet columnrs = columnstmt.executeQuery(columnsql); while (columnrs.next()) { diff --git a/pgjdbc/src/test/java/org/postgresql/test/jdbc2/DatabaseMetaDataTest.java b/pgjdbc/src/test/java/org/postgresql/test/jdbc2/DatabaseMetaDataTest.java index <HASH>..<HASH> 100644 --- a/pgjdbc/src/test/java/org/postgresql/test/jdbc2/DatabaseMetaDataTest.java +++ b/pgjdbc/src/test/java/org/postgresql/test/jdbc2/DatabaseMetaDataTest.java @@ -492,6 +492,22 @@ public class DatabaseMetaDataTest { assertEquals(3, rs.getInt("ORDINAL_POSITION")); assertTrue(!rs.next()); rs.close(); + + /* getFunctionColumns also has to be aware of dropped columns + add this in here to make sure it can deal with them + */ + rs = dbmd.getFunctionColumns(null, null, "f4", null); + assertTrue(rs.next()); + + assertTrue(rs.next()); + assertEquals("id", rs.getString(4)); + + assertTrue(rs.next()); + assertEquals("updated", rs.getString(4)); + + + rs.close(); + } @Test
fix issue #<I> make sure we don't get columns that are dropped (#<I>) * fix issue #<I> make sure we don't get columns that are dropped * added test case
pgjdbc_pgjdbc
train
e185118e518202be73a234ac2cb24d9590669ede
diff --git a/peewee.py b/peewee.py index <HASH>..<HASH> 100644 --- a/peewee.py +++ b/peewee.py @@ -19,6 +19,7 @@ import sys import threading import time import uuid +import warnings import weakref try: @@ -88,6 +89,10 @@ if sqlite3: sqlite3.register_adapter(datetime.time, str) +def __deprecated__(s): + warnings.warn(s, DeprecationWarning) + + class attrdict(dict): def __getattr__(self, attr): return self[attr] def __setattr__(self, attr, value): self[attr] = value @@ -2770,7 +2775,17 @@ class Field(ColumnBase): def __init__(self, null=False, index=False, unique=False, column_name=None, default=None, primary_key=False, constraints=None, - sequence=None, collation=None, unindexed=False): + sequence=None, collation=None, unindexed=False, + db_column=None, related_name=None): + if db_column is not None: + __deprecated__('"db_column" has been deprecated in favor of ' + '"column_name" for Field objects.') + column_name = db_column + if related_name is not None: + __deprecated__('"related_name" has been deprecated in favor of ' + '"backref" for Field objects.') + backref = related_name + self.null = null self.index = index self.unique = unique @@ -3139,8 +3154,18 @@ class ForeignKeyField(Field): accessor_class = ForeignKeyAccessor def __init__(self, model, field=None, backref=None, on_delete=None, - on_update=None, _deferred=None, *args, **kwargs): + on_update=None, _deferred=None, rel_model=None, to_field=None, + *args, **kwargs): super(ForeignKeyField, self).__init__(*args, **kwargs) + if rel_model is not None: + __deprecated__('"rel_model" has been deprecated in favor of ' + '"model" for ForeignKeyField objects.') + model = rel_model + if to_field is not None: + __deprecated__('"to_field" has been deprecated in favor of ' + '"field" for ForeignKeyField objects.') + field = to_field + self.rel_model = model self.rel_field = field self.backref = backref @@ -3589,7 +3614,11 @@ class Metadata(object): def __init__(self, model, database=None, table_name=None, indexes=None, primary_key=None, constraints=None, schema=None, only_save_dirty=False, table_alias=None, depends_on=None, - options=None, **kwargs): + options=None, db_table=None, **kwargs): + if db_table is not None: + __deprecated__('"db_table" has been deprecated in favor of ' + '"table_name" for Models.') + table_name = db_table self.model = model self.database = database
Backwards-compatible support + deprecation warnings.
coleifer_peewee
train
1826a8f12524862e7fdd56cc887c80fc1d6a398d
diff --git a/kalibro_client/base.py b/kalibro_client/base.py index <HASH>..<HASH> 100644 --- a/kalibro_client/base.py +++ b/kalibro_client/base.py @@ -21,12 +21,13 @@ class Base(object): def service_address(cls): raise NotImplementedError - def request(self, action, params=None, method='post', prefix=None): - url = self.service_address() + @classmethod + def request(cls, action, params=None, method='post', prefix=None): + url = cls.service_address() if prefix: url += "/" + prefix - url += "/{}/{}".format(self.endpoint(), action) + url += "/{}/{}".format(cls.endpoint(), action) response = requests.request(method, url, data=json.dumps(params), headers={'Content-Type': 'application/json'}) diff --git a/tests/test_base.py b/tests/test_base.py index <HASH>..<HASH> 100644 --- a/tests/test_base.py +++ b/tests/test_base.py @@ -52,12 +52,12 @@ class TestBase(TestCase): @raises(NotImplementedError) def test_service_address(self): - self.base.service_address() + Base.service_address() @patch('requests.request') def test_request(self, requests_request): - self.base.endpoint = Mock(return_value="base") - self.base.service_address = Mock(return_value="http://base:8000") + self.base.__class__.endpoint = Mock(return_value="base") + self.base.__class__.service_address = Mock(return_value="http://base:8000") response_mock = Mock() response_mock.json = Mock(return_value=self.attributes)
Request is now a class method.
mezuro_kalibro_client_py
train
f56d43751df831e34ff96d6b8540f9a6df719ed1
diff --git a/services/service_instance_lifecycle.go b/services/service_instance_lifecycle.go index <HASH>..<HASH> 100644 --- a/services/service_instance_lifecycle.go +++ b/services/service_instance_lifecycle.go @@ -458,7 +458,7 @@ var _ = ServicesDescribe("Service Instance Lifecycle", func() { restageApp := cf.Cf("restage", appName).Wait(Config.CfPushTimeoutDuration()) Expect(restageApp).To(Exit(0), "failed restaging app") - checkForAppEvent(appName, "audit.app.restage") + checkForAppEvent(appName, "audit.app.build.create") appEnv := cf.Cf("env", appName).Wait() Expect(appEnv).To(Exit(0), "failed get env for app")
Change restage event to look for v3 equivalent There is no `audit.app.restage` event that gets created in v3, because the idea of "restaging" has been broken into smaller pieces (create package, stage package, etc). We now look for `audit.app.build.create` to indicate the staging process has begun.
cloudfoundry_cf-acceptance-tests
train
f3ed734ba2c3cdbd4cfe0b8b5299ad5aff753850
diff --git a/ores/applications/util.py b/ores/applications/util.py index <HASH>..<HASH> 100644 --- a/ores/applications/util.py +++ b/ores/applications/util.py @@ -48,7 +48,7 @@ def configure_logging(verbose=False, debug=False, logging_config=None, **kwargs) # Secret sauce: if running from the console, mirror logs there. if sys.stdin.isatty(): - handler = logging.StreamHandler(stream=sys.stdout) + handler = logging.StreamHandler(stream=sys.stderr) formatter = logging.Formatter(fmt=DEFAULT_FORMAT) handler.setFormatter(formatter) logging.getLogger().addHandler(handler)
Default to stderr for consistency with logging.basicConfig
wikimedia_ores
train
155f80aa941b2235b651fb8e8124f2928fc12ff1
diff --git a/drizzlepac/haputils/cell_utils.py b/drizzlepac/haputils/cell_utils.py index <HASH>..<HASH> 100644 --- a/drizzlepac/haputils/cell_utils.py +++ b/drizzlepac/haputils/cell_utils.py @@ -889,10 +889,13 @@ class ProjectionCell(object): mosaic_edges_x, mosaic_edges_y = self.wcs.world_to_pixel_values(mosaic_ra, mosaic_dec) # Determine roughly what sky cells overlap this mosaic - mosaic_edges_x = (mosaic_edges_x / skycell00.wcs.pixel_shape[0] + 0.5).astype(np.int32) - mosaic_edges_y = (mosaic_edges_y / skycell00.wcs.pixel_shape[1] + 0.5).astype(np.int32) - mosaic_xr = [mosaic_edges_x.min() - 1, mosaic_edges_x.max() + 2] - mosaic_yr = [mosaic_edges_y.min() - 1, mosaic_edges_y.max() + 2] + # The 1.5 enforces 1-based indexing for the SkyCell IDs within the Projection Cell + mosaic_edges_x = (mosaic_edges_x / skycell00.wcs.pixel_shape[0] + 1.5).astype(np.int32) + mosaic_edges_y = (mosaic_edges_y / skycell00.wcs.pixel_shape[1] + 1.5).astype(np.int32) + # Define range of SkyCells in X,Y to evaluate for overlap + # Enforce a range of SkyCell IDs that are 1-based from 1 to self.sc_nxy + mosaic_xr = [max(1, mosaic_edges_x.min() - 1), min(self.sc_nxy, mosaic_edges_x.max() + 2)] + mosaic_yr = [max(1, mosaic_edges_y.min() - 1), min(self.sc_nxy, mosaic_edges_y.max() + 2)] print("SkyCell Ranges: {}, {}".format(mosaic_xr, mosaic_yr)) # for each suspected sky cell or neighbor, look for any pixel by pixel
Fix indexing of SkyCell IDs (#<I>)
spacetelescope_drizzlepac
train
e7469f79321e0e9707eaefd010a2bca028fd6644
diff --git a/pyresttest/test_tests.py b/pyresttest/test_tests.py index <HASH>..<HASH> 100644 --- a/pyresttest/test_tests.py +++ b/pyresttest/test_tests.py @@ -78,6 +78,50 @@ class TestsTest(unittest.TestCase): except TypeError: pass + def test_parse_extractor_bind(self): + """ Test parsing of extractors """ + test_config = { + "url": '/api', + 'extract_binds': { + 'id': {'jsonpath_mini': 'idfield'}, + 'name': {'jsonpath_mini': 'firstname'} + } + } + test = Test.build_test('', test_config) + self.assertTrue(test.extract_binds) + self.assertEqual(2, len(test.extract_binds)) + self.assertTrue('id' in test.extract_binds) + self.assertTrue('name' in test.extract_binds) + + # Test extractors config'd correctly for extraction + myjson = '{"idfield": 3, "firstname": "bob"}' + extracted = test.extract_binds['id'].extract(myjson) + self.assertEqual(3, extracted) + + extracted = test.extract_binds['name'].extract(myjson) + self.assertEqual('bob', extracted) + + def test_parse_extractor_errors(self): + """ Test that expected errors are thrown on parsing """ + test_config = { + "url": '/api', + 'extract_binds': {'id': {}} + } + try: + test = Test.build_test('', test_config) + self.fail("Should throw an error when doing empty mapping") + except TypeError: + pass + + test_config['extract_binds']['id'] = { + 'jsonpath_mini': 'query', + 'test':'anotherquery' + } + try: + test = Test.build_test('', test_config) + self.fail("Should throw an error when given multiple extractors") + except ValueError as te: + pass def test_variable_binding(self): """ Test that tests successfully bind variables """ diff --git a/pyresttest/tests.py b/pyresttest/tests.py index <HASH>..<HASH> 100644 --- a/pyresttest/tests.py +++ b/pyresttest/tests.py @@ -291,20 +291,20 @@ class Test(object): elif configelement == u'name': #Test name assert isinstance(configvalue,str) or isinstance(configvalue,unicode) or isinstance(configvalue,int) mytest.name = unicode(configvalue,'UTF-8') - elif configelement == u'extractors': - # Add a list of validators - if not isinstance(configvalue, list): - raise Exception('Misconfigured extractors section, must be a list of validators') - if mytest.extractors is None: - mytest.extractors = list() - - # create extractor and add to list of extractors - for var in configvalue: - if not isinstance(var, dict): - raise TypeError("Extractors must be defined as extractorType:{configs} ") - for extractor_type, extractor_config in var.items(): - extractor = extractors.parse_extractor(extractor_type, extractor_config) - mytest.extractors.append(extractor) + elif configelement == u'extract_binds': + # Add a list of extractors, of format: + # {variable_name: {extractor_type: extractor_config}, ... } + binds = flatten_dictionaries(configvalue) + if mytest.extract_binds is None: + mytest.extract_binds = dict() + + for variable_name, extractor in binds.items(): + if not isinstance(extractor, dict) or len(extractor) == 0: + raise TypeError("Extractors must be defined as maps of extractorType:{configs} with 1 entry") + if len(extractor) > 1: + raise ValueError("Cannot define multiple extractors for given variable name") + extractor_type, extractor_config = extractor.items()[0] + mytest.extract_binds[variable_name] = validators.parse_extractor(extractor_type, extractor_config) elif configelement == u'validators': # Add a list of validators
Finish parsing for extractor binds in tests, and add tests for same
svanoort_pyresttest
train
674d6796894cae4908846221ed16ea5966bb7c28
diff --git a/models/User.php b/models/User.php index <HASH>..<HASH> 100644 --- a/models/User.php +++ b/models/User.php @@ -9,7 +9,7 @@ use RainLab\User\Models\Settings as UserSettings; class User extends UserBase { - use \October\Rain\Database\Traits\SoftDeleting; + use \October\Rain\Database\Traits\SoftDelete; /** * @var string The database table used by the model.
Replace Deprecate SoftDeleting by SoftDelete
rainlab_user-plugin
train
c81e2a160a9083e2ad898340d2a2559246edcaa9
diff --git a/src/main/java/com/github/theholywaffle/lolchatapi/LolStatus.java b/src/main/java/com/github/theholywaffle/lolchatapi/LolStatus.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/github/theholywaffle/lolchatapi/LolStatus.java +++ b/src/main/java/com/github/theholywaffle/lolchatapi/LolStatus.java @@ -132,7 +132,8 @@ public class LolStatus { gameStatus, isObservable, mobile, - rankedSoloRestricted; + rankedSoloRestricted, + championMasteryScore; @Override public String toString() { @@ -251,9 +252,19 @@ public class LolStatus { } private int getInt(XMLProperty p) { + return getInt(p, -1); + } + + /** + * If the value exists it returns its value else the default value + * @param p the {@link XMLProperty} + * @param defaultValue the fallback value + * @return returns the value of the given {@link XMLProperty} + */ + private int getInt(XMLProperty p, int defaultValue) { final String value = get(p); if (value.isEmpty()) { - return -1; + return defaultValue; } return Integer.parseInt(value); } @@ -532,6 +543,10 @@ public class LolStatus { return Boolean.valueOf(get(XMLProperty.rankedSoloRestricted)); } + public int getChampionMasteryScore() { + return getInt(XMLProperty.championMasteryScore, 0); + } + @Override public String toString() { return outputter.outputString(doc.getRootElement());
solved issue #<I>: added championMasteryScore to LolStatus
TheHolyWaffle_League-of-Legends-XMPP-Chat-Library
train
eba10dd4a707fda6a162760fa877227fa08e6783
diff --git a/src/Factory/Factory.php b/src/Factory/Factory.php index <HASH>..<HASH> 100644 --- a/src/Factory/Factory.php +++ b/src/Factory/Factory.php @@ -55,7 +55,9 @@ class Factory implements FactoryInterface */ public function make($type, $name, $value, $options = []) { - $typeClass = $this->getFieldTypeClass($type); + $typeClass = $this->getFieldTypeClass($type, $this->namespace); + + if (! $typeClass) throw new \Exception("No supported Field Type [{$type}]"); return new $typeClass($name, $value, $options); } @@ -64,15 +66,15 @@ class Factory implements FactoryInterface * @param $type * @throws \Exception */ - protected function getFieldTypeClass($type) + protected function getFieldTypeClass($type, $namespace) { if (isset($this->classMap[$type])) return $this->classMap[$type]; - if (class_exists($this->namespace . Str::studly($type))) { - return $this->namespace . Str::studly($type); - } + $typeClass = $namespace . Str::studly($type); + + if (class_exists($typeClass)) return $typeClass; - throw new \Exception("No supported Field Type [{$type}]"); + return false; } protected function resolveFieldValues($name, $value) {
+ Make package autopublishable = fix restfulizer route
marcmascarell_formality
train
4ab5fe5bd3818780eba6720819a342dc4e9a4f36
diff --git a/Ludown/lib/parseFileContents.js b/Ludown/lib/parseFileContents.js index <HASH>..<HASH> 100644 --- a/Ludown/lib/parseFileContents.js +++ b/Ludown/lib/parseFileContents.js @@ -199,7 +199,7 @@ module.exports.parseFile = function(fileContent, log) // add this to entities collection unless it already exists addItemIfNotPresent(LUISJsonStruct, LUISObjNameEnum.ENTITIES, entity); // clean up uttearnce to only include labelledentityValue and add to utterances collection - var startPos = updatedUtterance.search(srcEntityStructure); + var startPos = updatedUtterance.indexOf(srcEntityStructure); var endPos = startPos + labelledValue.length - 1; updatedUtterance = updatedUtterance.replace("{" + entity + "=" + labelledValue + "}", labelledValue); entitiesInUtterance.push({
using str.indexOf to avoid issues when entity text includes regexp control characters
Microsoft_botbuilder-tools
train
a174f3bcaa40024f5fc2f22890d433d3a02f99fa
diff --git a/l10n/management/commands/extract.py b/l10n/management/commands/extract.py index <HASH>..<HASH> 100644 --- a/l10n/management/commands/extract.py +++ b/l10n/management/commands/extract.py @@ -55,7 +55,7 @@ def tweak_message(message): return message -def extract_amo_python(fileobj, keywords, comment_tags, options): +def extract_tower_python(fileobj, keywords, comment_tags, options): for lineno, funcname, message, comments in \ list(extract_python(fileobj, keywords, comment_tags, options)): @@ -64,7 +64,7 @@ def extract_amo_python(fileobj, keywords, comment_tags, options): yield lineno, funcname, message, comments -def extract_amo_template(fileobj, keywords, comment_tags, options): +def extract_tower_template(fileobj, keywords, comment_tags, options): for lineno, funcname, message, comments in \ list(ext.babel_extract(fileobj, keywords, comment_tags, options)): @@ -79,7 +79,7 @@ def create_pounit(filename, lineno, message, comments): _, s = split_context(message[0]) c, p = split_context(message[1]) unit.setsource([s, p]) - # Workaround for http://bugs.locamotion.org/show_bug.cgi?id=1385 + # Workaround for http://bugs.loctowertion.org/show_bug.cgi?id=1385 unit.target = [u"", u""] else: c, m = split_context(message) diff --git a/tests/test_l10n.py b/tests/test_l10n.py index <HASH>..<HASH> 100644 --- a/tests/test_l10n.py +++ b/tests/test_l10n.py @@ -201,9 +201,9 @@ def test_template_gettext_functions(): eq_(render(s), '1') -def test_extract_amo_python(): +def test_extract_tower_python(): fileobj = StringIO(TEST_PO_INPUT) - method = 'l10n.management.commands.extract.extract_amo_python' + method = 'l10n.management.commands.extract.extract_tower_python' output = fake_extract_from_dir(filename="filename", fileobj=fileobj, method=method) @@ -211,9 +211,9 @@ def test_extract_amo_python(): eq_(TEST_PO_OUTPUT, unicode(create_pofile_from_babel(output))) -def test_extract_amo_template(): +def test_extract_tower_template(): fileobj = StringIO(TEST_TEMPLATE_INPUT) - method = 'l10n.management.commands.extract.extract_amo_template' + method = 'l10n.management.commands.extract.extract_tower_template' output = fake_extract_from_dir(filename="filename", fileobj=fileobj, method=method)
Renaming *_amo_* to *_tower_*.
clouserw_tower
train
b277e108758873f730386315cbdb1be74d02da84
diff --git a/test/Reporting/Reporters/CustomReporterTests.js b/test/Reporting/Reporters/CustomReporterTests.js index <HASH>..<HASH> 100644 --- a/test/Reporting/Reporters/CustomReporterTests.js +++ b/test/Reporting/Reporters/CustomReporterTests.js @@ -19,7 +19,8 @@ var MyCustomReporter = function () { var globalCustomReporter = new MyCustomReporter(); require('../../../lib/Approvals').configure({ - reporters: [globalCustomReporter] + reporters: [globalCustomReporter], + errorOnStaleApprovedFiles: false }).mocha(__dirname); describe("CustomReporter", function () {
This is an ugly fix... Due the global state of configuraiton, the CLI test in this project is has an approval file that is detected as a stale file - (but it's not). This fixes it, but we need to work on a better strategy for stale files
approvals_Approvals.NodeJS
train
45e10c0826402da6c4b751b7987fa48a3615f90b
diff --git a/test.py b/test.py index <HASH>..<HASH> 100644 --- a/test.py +++ b/test.py @@ -2,6 +2,7 @@ import logging import subprocess import sys import os +import json from nose.tools import raises logger = logging.getLogger(__name__) @@ -219,7 +220,7 @@ def test_subset_removal(): def test_pipeline_crushing(): """Overlord should kill pipelines on crash""" # The presence of "poison_pill" as a keyword will cause stage-two to assert - # False. + # False mid-run. docs = [ {'text': 'This is an example', 'title': 'example-1', @@ -236,6 +237,15 @@ def test_pipeline_crushing(): job_result = PROJECT.wait_for(job_id) assert job_result['success'] is False + # Giving a spurious background-space name will cause a failure on startup. + # In this case, there's no need to wait; the crushing should happen before + # the job number even comes back. + job_id = PROJECT.post_data('docs', json.dumps(docs), 'application/json', + background_name='spuriousname') + job_result = PROJECT.get('jobs/id/' + str(job_id)) + assert job_result['stop_time'] is not None + assert job_result['success'] is False + def teardown(): """ Pack everything up, we're done.
Test for new pipeline-initialization failure
LuminosoInsight_luminoso-api-client-python
train
7eeae1a63e44b949e823e425c80bf44108ee24ab
diff --git a/course/lib.php b/course/lib.php index <HASH>..<HASH> 100644 --- a/course/lib.php +++ b/course/lib.php @@ -3420,10 +3420,12 @@ function duplicate_module($course, $cm) { $rc = new restore_controller($backupid, $course->id, backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING); - // Configure the plan. + // Make sure that the restore_general_groups setting is always enabled when duplicating an activity. $plan = $rc->get_plan(); $groupsetting = $plan->get_setting('groups'); - $groupsetting->set_value(true); + if (empty($groupsetting->get_value())) { + $groupsetting->set_value(true); + } $cmcontext = context_module::instance($cm->id); if (!$rc->execute_precheck()) {
MDL-<I> course: Only set the groups setting to true when necessary * Plus update the comment to be more descriptive.
moodle_moodle
train
18186a683e9fcc295c5965976d76f7dff994a49a
diff --git a/libkbfs/folder_update_prepper.go b/libkbfs/folder_update_prepper.go index <HASH>..<HASH> 100644 --- a/libkbfs/folder_update_prepper.go +++ b/libkbfs/folder_update_prepper.go @@ -44,7 +44,7 @@ func (fup folderUpdatePrepper) readyBlockMultiple(ctx context.Context, info BlockInfo, plainSize int, err error) { info, plainSize, readyBlockData, err := ReadyBlock(ctx, fup.config.BlockCache(), fup.config.BlockOps(), - fup.config.Crypto(), kmd, currBlock, uid, bType) + fup.config.cryptoPure(), kmd, currBlock, uid, bType) if err != nil { return } @@ -64,7 +64,7 @@ func (fup folderUpdatePrepper) unembedBlockChanges( // Treat the block change list as a file so we can reuse all the // indirection code in fileData. block := NewFileBlock().(*FileBlock) - bid, err := fup.config.Crypto().MakeTemporaryBlockID() + bid, err := fup.config.cryptoPure().MakeTemporaryBlockID() if err != nil { return err } @@ -104,7 +104,7 @@ func (fup folderUpdatePrepper) unembedBlockChanges( } df := newDirtyFile(file, dirtyBcache) - fd := newFileData(file, uid, fup.config.Crypto(), + fd := newFileData(file, uid, fup.config.cryptoPure(), fup.config.BlockSplitter(), md.ReadOnly(), getter, cacher, fup.log) // Write all the data.
folder_update_prepper: use cryptoPure instead of Crypto Suggested by jzila. Issue: #<I>
keybase_client
train
ef2b0f5ca3aae8caf9a2a457da7b62f015fc0f9a
diff --git a/version.php b/version.php index <HASH>..<HASH> 100644 --- a/version.php +++ b/version.php @@ -29,7 +29,7 @@ defined('MOODLE_INTERNAL') || die(); -$version = 2013101100.00; // YYYYMMDD = weekly release date of this DEV branch. +$version = 2013101500.00; // YYYYMMDD = weekly release date of this DEV branch. // RR = release increments - 00 in DEV branches. // .XX = incremental changes.
MDL-<I> Javascript: Add version bump for YUI update
moodle_moodle
train
f5cddeb3e1dde82f16968ee9cf876cd52d4407da
diff --git a/core/common/src/main/java/alluxio/util/FormatUtils.java b/core/common/src/main/java/alluxio/util/FormatUtils.java index <HASH>..<HASH> 100644 --- a/core/common/src/main/java/alluxio/util/FormatUtils.java +++ b/core/common/src/main/java/alluxio/util/FormatUtils.java @@ -211,7 +211,7 @@ public final class FormatUtils { * @return the JSON-encoded version of the input string */ public static String encodeJson(String input) { - return "\"" + StringEscapeUtils.escapeJson(input) + "\""; + return "\"" + StringEscapeUtils.escapeJava(input) + "\""; } private FormatUtils() {} // prevent instantiation diff --git a/core/common/src/test/java/alluxio/util/FormatUtilsTest.java b/core/common/src/test/java/alluxio/util/FormatUtilsTest.java index <HASH>..<HASH> 100644 --- a/core/common/src/test/java/alluxio/util/FormatUtilsTest.java +++ b/core/common/src/test/java/alluxio/util/FormatUtilsTest.java @@ -265,7 +265,6 @@ public class FormatUtilsTest { public void encodeJsonTest() { Set<String> escapedChars = new HashSet<>(); escapedChars.add("\""); - escapedChars.add("/"); escapedChars.add("\\"); for (char i = 32; i < 128; i++) { String s = String.valueOf(i); diff --git a/core/server/src/main/java/alluxio/worker/block/BlockWorkerClientRestServiceHandler.java b/core/server/src/main/java/alluxio/worker/block/BlockWorkerClientRestServiceHandler.java index <HASH>..<HASH> 100644 --- a/core/server/src/main/java/alluxio/worker/block/BlockWorkerClientRestServiceHandler.java +++ b/core/server/src/main/java/alluxio/worker/block/BlockWorkerClientRestServiceHandler.java @@ -289,7 +289,7 @@ public final class BlockWorkerClientRestServiceHandler { @POST @Path(REQUEST_BLOCK_LOCATION) @Produces(MediaType.APPLICATION_JSON) - @ReturnType("java.lang.Long") + @ReturnType("java.lang.String") public Response requestBlockLocation(@QueryParam("sessionId") Long sessionId, @QueryParam("blockId") Long blockId, @QueryParam("initialBytes") Long initialBytes) { try {
Fixing JSON encoding.
Alluxio_alluxio
train
e0c859765cd668b94bf2d943c866f4108ea0304b
diff --git a/main.go b/main.go index <HASH>..<HASH> 100644 --- a/main.go +++ b/main.go @@ -5,6 +5,7 @@ import ( "fmt" "io/ioutil" "os" + "path/filepath" "strings" "github.com/alanctgardner/gogen-avro/generator" @@ -91,7 +92,8 @@ func codegenComment(sources []string) string { } for _, source := range sources { - sourceBlock = append(sourceBlock, fmt.Sprintf(" * %s", source)) + _, fName := filepath.Split(source) + sourceBlock = append(sourceBlock, fmt.Sprintf(" * %s", fName)) } return fmt.Sprintf(fileComment, strings.Join(sourceBlock, "\n"))
Fix sources header to only show file names
actgardner_gogen-avro
train
0cea1fdd9f6b191f199de8e2f5624e67533e6cce
diff --git a/src/main/java/com/sdl/selenium/extjs6/slider/Slider.java b/src/main/java/com/sdl/selenium/extjs6/slider/Slider.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/sdl/selenium/extjs6/slider/Slider.java +++ b/src/main/java/com/sdl/selenium/extjs6/slider/Slider.java @@ -34,7 +34,7 @@ public class Slider extends WebLocator { do { boolean vertical = getAttributeClass().contains("x-slider-vert"); int value = Integer.parseInt(getAttribute("aria-valuenow")); - if (value > distance || value == 0) { + if (value > distance) { if (vertical) { distanceTemp = value - distance; } else {
improvement Slider with select vertical, and DateField select hour and minutes
sdl_Testy
train
173d0110ef4ecc107e8b77dc8bbc924e2f5a851a
diff --git a/pymatgen/analysis/tests/test_interface_reactions.py b/pymatgen/analysis/tests/test_interface_reactions.py index <HASH>..<HASH> 100644 --- a/pymatgen/analysis/tests/test_interface_reactions.py +++ b/pymatgen/analysis/tests/test_interface_reactions.py @@ -345,7 +345,7 @@ class InterfaceReactionTest(unittest.TestCase): for x, e in points] relative_vectors = zip(relative_vectors_1, relative_vectors_2) positions = [np.cross(v1, v2) for v1, v2 in relative_vectors] - test1 = np.all(positions >= 0) + test1 = np.all(np.array(positions) <= 0) hull = ConvexHull(points) test2 = len(hull.vertices) == len(points)
fix bug in test_interface_reactions file
materialsproject_pymatgen
train
bad600fd6239f39e26ce1ed89d2cc22d372368d5
diff --git a/lib/webspicy/tester/fakesmtp.rb b/lib/webspicy/tester/fakesmtp.rb index <HASH>..<HASH> 100644 --- a/lib/webspicy/tester/fakesmtp.rb +++ b/lib/webspicy/tester/fakesmtp.rb @@ -30,7 +30,7 @@ module Webspicy end def last_email - emails.last + emails.first end end # class Fakesmtp
Fix fakestmp last_email.
enspirit_webspicy
train
b419afdf5644e489068742f5476dbf7a429dd24e
diff --git a/bundles/org.eclipse.orion.client.ui/web/orion/projectCommands.js b/bundles/org.eclipse.orion.client.ui/web/orion/projectCommands.js index <HASH>..<HASH> 100644 --- a/bundles/org.eclipse.orion.client.ui/web/orion/projectCommands.js +++ b/bundles/org.eclipse.orion.client.ui/web/orion/projectCommands.js @@ -363,7 +363,7 @@ define(['i18n!orion/navigate/nls/messages', 'orion/webui/littlelib', 'orion/comm callback: function(data) { var item = forceSingleItem(data.items); - data.oldParams = item.params; + data.oldParams = item.Params; var func = arguments.callee; var params = handleParamsInCommand(func, data, start? "Start application" : "Stop application");
Bug <I> - Launch conf properties are lost on retry
eclipse_orion.client
train
21721cff690422200583dd7119ac4b97f9cdce32
diff --git a/is_core/forms/forms.py b/is_core/forms/forms.py index <HASH>..<HASH> 100644 --- a/is_core/forms/forms.py +++ b/is_core/forms/forms.py @@ -97,8 +97,13 @@ class ReadonlyBoundField(SmartBoundField): def as_widget(self, widget=None, attrs=None, only_initial=False): if not widget: widget = self.field.widget - return super(ReadonlyBoundField, self).as_widget(self.form._get_readonly_widget(self.name, self.field, - widget), attrs, only_initial) + + if widget.is_hidden: + return mark_safe('') + else: + return super(ReadonlyBoundField, self).as_widget( + self.form._get_readonly_widget(self.name, self.field, widget), attrs, only_initial + ) def as_hidden(self, attrs=None, **kwargs): """ diff --git a/is_core/version.py b/is_core/version.py index <HASH>..<HASH> 100644 --- a/is_core/version.py +++ b/is_core/version.py @@ -1,4 +1,4 @@ -VERSION = (1, 3, 40) +VERSION = (1, 3, 41) def get_version(): return '.'.join(map(str, VERSION))
<I> Fixed readonly hidden fields (returns only '')
matllubos_django-is-core
train
e504fa436719cd5ea2d58ac659d3db9c778f2e18
diff --git a/test/middleware/authenticate-test.js b/test/middleware/authenticate-test.js index <HASH>..<HASH> 100644 --- a/test/middleware/authenticate-test.js +++ b/test/middleware/authenticate-test.js @@ -98,6 +98,32 @@ MockBadRequestStrategy.prototype.authenticate = function(req) { this.fail(400); } + +function MockLocalStrategy(options) { + this.options = options || {}; +} + +MockLocalStrategy.prototype.authenticate = function(req) { + if (!this.options.fail) { + this.success({ username: 'bob-local' }); + } else { + this.fail('Bad username or password'); + } +} + +function MockSingleUseTokenStrategy(options) { + this.options = options || {}; +} + +MockSingleUseTokenStrategy.prototype.authenticate = function(req) { + if (!this.options.fail) { + this.success({ username: 'bob-sut' }); + } else { + this.fail('Bad token'); + } +} + + function MockRequest() { } @@ -2779,4 +2805,70 @@ vows.describe('authenticate').addBatch({ }, }, + 'with a multiple UI strategies with the first one succeeding': { + topic: function() { + var self = this; + var passport = new Passport(); + passport.use('local', new MockLocalStrategy()); + passport.use('single-use-token', new MockSingleUseTokenStrategy()); + return passport.authenticate(['local', 'single-use-token']); + }, + + 'when handling a request': { + topic: function(authenticate) { + var self = this; + var req = new MockRequest(); + var res = new MockResponse(); + + function next(err) { + self.callback(err, req, res); + } + process.nextTick(function () { + authenticate(req, res, next) + }); + }, + + 'should not generate an error' : function(err, req, res) { + assert.isNull(err); + }, + 'should set user on request' : function(err, req, res) { + assert.isObject(req.user); + assert.equal(req.user.username, 'bob-local'); + }, + }, + }, + + 'with a multiple UI strategies with the second one succeeding': { + topic: function() { + var self = this; + var passport = new Passport(); + passport.use('local', new MockLocalStrategy({ fail: true })); + passport.use('single-use-token', new MockSingleUseTokenStrategy()); + return passport.authenticate(['local', 'single-use-token']); + }, + + 'when handling a request': { + topic: function(authenticate) { + var self = this; + var req = new MockRequest(); + var res = new MockResponse(); + + function next(err) { + self.callback(err, req, res); + } + process.nextTick(function () { + authenticate(req, res, next) + }); + }, + + 'should not generate an error' : function(err, req, res) { + assert.isNull(err); + }, + 'should set user on request' : function(err, req, res) { + assert.isObject(req.user); + assert.equal(req.user.username, 'bob-sut'); + }, + }, + }, + }).export(module);
Test cases for multiple UI strategies alternately succeeding.
jaredhanson_passport
train
a51a50f7ab1d9143fb6a7fa87e3448ed6e981fe4
diff --git a/spec/controllers/accounts_controller_spec.rb b/spec/controllers/accounts_controller_spec.rb index <HASH>..<HASH> 100644 --- a/spec/controllers/accounts_controller_spec.rb +++ b/spec/controllers/accounts_controller_spec.rb @@ -355,7 +355,7 @@ describe AccountsController do specify { response.should render_template('recover_password') } it "should display an error" do - response.flash[:error].should_not be_empty + request.flash[:error].should_not be_empty end end end
Replace deprecated response.flash with request.flash.
publify_publify
train
c04892703f89e27e17f83a140466251f418520d5
diff --git a/src/Pingpong/Shortcode/Shortcode.php b/src/Pingpong/Shortcode/Shortcode.php index <HASH>..<HASH> 100644 --- a/src/Pingpong/Shortcode/Shortcode.php +++ b/src/Pingpong/Shortcode/Shortcode.php @@ -8,7 +8,7 @@ use Illuminate\Support\Str; class Shortcode implements Countable { /** - * @var array + * @var array */ protected $shortcodes = array(); @@ -46,7 +46,7 @@ class Shortcode implements Countable { unset($this->shortcodes[$name]); } - } + } /** * Unregister all shortcodes. @@ -57,11 +57,11 @@ class Shortcode implements Countable public function destroy() { $this->shortcodes = array(); - } + } /** * Get regex. - * + * * @copyright Wordpress * @return string */ @@ -70,34 +70,34 @@ class Shortcode implements Countable $names = array_keys($this->shortcodes); $shortcode = join('|', array_map('preg_quote', $names)); return - '\\[' - . '(\\[?)' - . "($shortcode)" - . '(?![\\w-])' - . '(' - . '[^\\]\\/]*' + '\\[' + . '(\\[?)' + . "($shortcode)" + . '(?![\\w-])' + . '(' + . '[^\\]\\/]*' . '(?:' - . '\\/(?!\\])' - . '[^\\]\\/]*' + . '\\/(?!\\])' + . '[^\\]\\/]*' . ')*?' . ')' . '(?:' - . '(\\/)' - . '\\]' + . '(\\/)' + . '\\]' . '|' - . '\\]' + . '\\]' . '(?:' - . '(' - . '[^\\[]*+' + . '(' + . '[^\\[]*+' . '(?:' - . '\\[(?!\\/\\2\\])' - . '[^\\[]*+' + . '\\[(?!\\/\\2\\])' + . '[^\\[]*+' . ')*+' . ')' - . '\\[\\/\\2\\]' + . '\\[\\/\\2\\]' . ')?' . ')' - . '(\\]?)'; + . '(\\]?)'; } /** @@ -130,6 +130,29 @@ class Shortcode implements Countable } /** + * Strip any shortcodes + * + * @param string $content + * @return string + */ + public function strip($content) + { + if (empty($this->shortcodes)) return $content; + + $pattern = $this->getRegex(); + + return preg_replace_callback("/$pattern/s", function($m) + { + if ($m[1] == '[' && $m[6] == ']') + { + return substr($m[0], 1, -1); + } + + return $m[1] . $m[6]; + }, $content); + } + + /** * Get count from all shortcodes. * * @return integer @@ -140,7 +163,7 @@ class Shortcode implements Countable } /** - * Return true is the given name exist in shortcodes array. + * Return true is the given name exist in shortcodes array. * * @param string $name * @return boolean @@ -151,7 +174,7 @@ class Shortcode implements Countable } /** - * Return true is the given content contain the given name shortcode. + * Return true is the given content contain the given name shortcode. * * @param string $content * @param string $name @@ -173,13 +196,13 @@ class Shortcode implements Countable } /** - * Compile the gived content. + * Compile the gived content. * * @param string $content * @return void */ public function compile($content) - { + { if( ! $this->count()) { return $content; @@ -201,12 +224,12 @@ class Shortcode implements Countable $content = array_get($matches, 5); $callback = $this->getCallback($name); $params = $this->getParameter($matches); - $params = [$params, $content, $name]; + $params = [$params, $content, $name]; return call_user_func_array($callback, $params); } /** - * Get parameters. + * Get parameters. * * @param array $matches * @return array @@ -231,7 +254,7 @@ class Shortcode implements Countable { $callback = $this->shortcodes[$name]; if(is_string($callback)) - { + { if(str_contains($name, '@')) { $_callback = Str::parseCallback($callback, 'register'); @@ -248,4 +271,4 @@ class Shortcode implements Countable return $callback; } -} \ No newline at end of file +} diff --git a/tests/ShorcodesTests.php b/tests/ShorcodesTests.php index <HASH>..<HASH> 100644 --- a/tests/ShorcodesTests.php +++ b/tests/ShorcodesTests.php @@ -6,7 +6,7 @@ use Pingpong\Shortcode\Shortcode; function boldTagFunction($attr, $content = null, $name = null) { return '<b>'.$content.'</b>'; -} +} class ShortcodesTests extends PHPUnit_Framework_TestCase { @@ -71,4 +71,19 @@ class ShortcodesTests extends PHPUnit_Framework_TestCase $this->assertEquals($boldTag, $boldTagFromShortcode); } -} \ No newline at end of file + + /** + * Test the strip functionality + * + * @return void + */ + public function testStrippingShortcodesFromContent() + { + $this->shortcode->register('b', 'boldTagFunction'); + + $content = 'This is just a shortcode [b]example[/b].'; + $expected = 'This is just a shortcode .'; + + $this->assertEquals($expected, $this->shortcode->strip($content)); + } +}
Added strip() method to Shortcode class
pingpong-labs_shortcode
train
79d0cef1b2068b7e7db72690f5774abf93928df5
diff --git a/findimports.py b/findimports.py index <HASH>..<HASH> 100755 --- a/findimports.py +++ b/findimports.py @@ -95,15 +95,20 @@ class ImportFinder(ASTVisitor): def __init__(self, filename): self.imports = [] + self.imported_names = sets.Set() self.filename = filename + def processImport(self, name, imported_as, full_name, node): + self.imports.append(full_name) + def visitImport(self, node): for name, imported_as in node.names: - self.imports.append(name) + self.processImport(name, imported_as, name, node) def visitFrom(self, node): for name, imported_as in node.names: - self.imports.append('%s.%s' % (node.modname, name)) + self.processImport(name, imported_as, + '%s.%s' % (node.modname, name), node) def visitSomethingWithADocstring(self, node): self.processDocstring(node.doc, node.lineno) @@ -143,23 +148,13 @@ class ImportFinderAndNameTracker(ImportFinder): ImportFinder.__init__(self, filename) self.unused_names = {} - def visitImport(self, node): - ImportFinder.visitImport(self, node) - for name, imported_as in node.names: - if not imported_as: - imported_as = name - if imported_as != "*": - self.unused_names[imported_as] = UnusedName(imported_as, - node.lineno) - - def visitFrom(self, node): - ImportFinder.visitFrom(self, node) - for name, imported_as in node.names: - if not imported_as: - imported_as = name - if imported_as != "*": - self.unused_names[imported_as] = UnusedName(imported_as, - node.lineno) + def processImport(self, name, imported_as, full_name, node): + ImportFinder.processImport(self, name, imported_as, full_name, node) + if not imported_as: + imported_as = name + if imported_as != "*": + self.unused_names[imported_as] = UnusedName(imported_as, + node.lineno) def visitName(self, node): if node.name in self.unused_names:
Refactoring: push common parts of visitImport and visitFrom into processImport. Originally committed <I>-<I>-<I> <I>:<I>:<I> <I> to a different SVN repository (python-tools) as revision <I>.
mgedmin_findimports
train
7240a960f2e515316ac4d962482f678b67b83b8c
diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb index <HASH>..<HASH> 100644 --- a/actionpack/test/template/text_helper_test.rb +++ b/actionpack/test/template/text_helper_test.rb @@ -207,6 +207,10 @@ class TextHelperTest < ActionView::TestCase assert_nil excerpt("This is a beautiful morning", "day") end + def test_excerpt_should_not_be_html_safe + assert !excerpt('This is a beautiful! morning', 'beautiful', 5).html_safe? + end + def test_excerpt_in_borderline_cases assert_equal("", excerpt("", "", 0)) assert_equal("a", excerpt("a", "a", 0))
excerpt shoudn't return safe output test added [#<I>]
rails_rails
train
125e941cb0e4e5daea00ce5b45d9925e4915b67b
diff --git a/spyderlib/widgets/tabs.py b/spyderlib/widgets/tabs.py index <HASH>..<HASH> 100644 --- a/spyderlib/widgets/tabs.py +++ b/spyderlib/widgets/tabs.py @@ -46,6 +46,7 @@ class TabBar(QTabBar): # Dragging tabs self.__drag_start_pos = QPoint() self.setAcceptDrops(True) + self.setUsesScrollButtons(True) def mousePressEvent(self, event): """Reimplement Qt method"""
Consoles: Add scroll buttons to their tab widgets Fixes #<I>
spyder-ide_spyder
train
e74a58130e0ecc896669bd0c659090dbc38fe889
diff --git a/job-scheduler/src/test/java/org/hawkular/metrics/scheduler/impl/JobExecutionTest.java b/job-scheduler/src/test/java/org/hawkular/metrics/scheduler/impl/JobExecutionTest.java index <HASH>..<HASH> 100644 --- a/job-scheduler/src/test/java/org/hawkular/metrics/scheduler/impl/JobExecutionTest.java +++ b/job-scheduler/src/test/java/org/hawkular/metrics/scheduler/impl/JobExecutionTest.java @@ -23,6 +23,7 @@ import static java.util.UUID.randomUUID; import static org.hawkular.metrics.datetime.DateTimeService.currentMinute; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @@ -35,6 +36,7 @@ import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Random; +import java.util.Set; import java.util.UUID; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; @@ -186,7 +188,8 @@ public class JobExecutionTest extends JobSchedulerTest { tickScheduler.advanceTimeTo(timeSlice.getMillis(), TimeUnit.MILLISECONDS); assertTrue(timeSliceFinished.await(10, TimeUnit.SECONDS)); - assertEquals(getActiveTimeSlices(), emptySet()); + Set<DateTime> activeTimeSlices = getActiveTimeSlices(); + assertFalse(activeTimeSlices.contains(timeSlice)); assertEquals(getScheduledJobs(timeSlice), emptySet()); assertEquals(getFinishedJobs(timeSlice), emptySet()); }
relax verification check I had this change made already at some point and I guess it got reverted back during a merge.
hawkular_hawkular-metrics
train
574f33902fbb7a33be9d6153bcc45a8443a6fd6b
diff --git a/Context.js b/Context.js index <HASH>..<HASH> 100644 --- a/Context.js +++ b/Context.js @@ -368,6 +368,7 @@ function Context(gl){ //Texture Targets this.TEXTURE_2D = gl.TEXTURE_2D; + this.TEXTURE_CUBE_MAP = gl.TEXTURE_CUBE_MAP; this.TEXTURE_CUBE_MAP_POSITIVE_X = gl.TEXTURE_CUBE_MAP_POSITIVE_X; this.TEXTURE_CUBE_MAP_NEGATIVE_X = gl.TEXTURE_CUBE_MAP_NEGATIVE_X; this.TEXTURE_CUBE_MAP_POSITIVE_Y = gl.TEXTURE_CUBE_MAP_POSITIVE_Y;
Added missing TEXTURE_CUBE_MAP constant
pex-gl_pex-context
train
298c65d8ea018ed416dd9b744779feffede1e4bc
diff --git a/tchannel/sync/client.py b/tchannel/sync/client.py index <HASH>..<HASH> 100644 --- a/tchannel/sync/client.py +++ b/tchannel/sync/client.py @@ -57,14 +57,14 @@ class TChannelSyncClient(object): :param process_name: Name of the calling process. Used for logging purposes only. """ - self.async_client = async.TChannel( + self._async_client = async.TChannel( name, process_name=process_name, known_peers=known_peers, trace=trace ) - self.threadloop = ThreadLoop() - self.threadloop.start() + self._threadloop = ThreadLoop() + self._threadloop.start() def request(self, *args, **kwargs): """Initiate a new request to a peer. @@ -80,8 +80,8 @@ class TChannelSyncClient(object): :returns SyncClientOperation: An object with a ``send(arg1, arg2, arg3)`` operation. """ - operation = self.async_client.request(*args, **kwargs) - operation = SyncClientOperation(operation, self.threadloop) + operation = self._async_client.request(*args, **kwargs) + operation = SyncClientOperation(operation, self._threadloop) return operation @@ -98,12 +98,7 @@ class TChannelSyncClient(object): @gen.coroutine def make_request(): - # begin listening in thread, note that this - # running listen in the main thread will cause the - # sync clients advertise to not work - self.async_client.listen() - - response = yield self.async_client.advertise( + response = yield self._async_client.advertise( routers=routers, name=name, timeout=timeout, @@ -116,7 +111,7 @@ class TChannelSyncClient(object): raise gen.Return(result) - future = self.threadloop.submit(make_request) + future = self._threadloop.submit(make_request) # we're going to wait 1s longer than advertises # timeout mechanism, so it has a chance to timeout @@ -146,7 +141,7 @@ class SyncClientOperation(object): assert operation, "operation is required" assert threadloop, "threadloop.ThreadLoop is required" self.operation = operation - self.threadloop = threadloop + self._threadloop = threadloop def send(self, arg1, arg2, arg3): """Send the given triple over the wire. @@ -179,7 +174,7 @@ class SyncClientOperation(object): raise gen.Return(result) - future = self.threadloop.submit(make_request) + future = self._threadloop.submit(make_request) return future diff --git a/tchannel/sync/thrift.py b/tchannel/sync/thrift.py index <HASH>..<HASH> 100644 --- a/tchannel/sync/thrift.py +++ b/tchannel/sync/thrift.py @@ -72,11 +72,11 @@ def client_for(service, service_module, thrift_service_name=None): def init(self, tchannel_sync, hostport=None, trace=False): self.async_thrift = self.__async_client_class__( - tchannel_sync.async_client, + tchannel_sync._async_client, hostport, trace, ) - self.threadloop = tchannel_sync.threadloop + self.threadloop = tchannel_sync._threadloop init.__name__ = '__init__' methods = { diff --git a/tests/sync/test_client.py b/tests/sync/test_client.py index <HASH>..<HASH> 100644 --- a/tests/sync/test_client.py +++ b/tests/sync/test_client.py @@ -68,7 +68,7 @@ def test_advertise_should_result_in_peer_connections(tchannel_server): assert result.header == "" # @todo https://github.com/uber/tchannel-python/issues/34 assert result.body == json.dumps(body) - assert client.async_client.peers.hosts == routers + assert client._async_client.peers.hosts == routers def test_failing_advertise_should_raise(tchannel_server): @@ -90,6 +90,6 @@ def test_failing_advertise_should_raise(tchannel_server): def test_should_discover_ip(): client = TChannelSyncClient('test-client') - hostport = client.async_client.hostport + hostport = client._async_client.hostport assert '0.0.0.0:0' != hostport
async_client and threadloop should be protected
uber_tchannel-python
train
86119494160dc97ef09ce4d63f293ecdedbfb04e
diff --git a/spillway/views.py b/spillway/views.py index <HASH>..<HASH> 100644 --- a/spillway/views.py +++ b/spillway/views.py @@ -24,8 +24,8 @@ class MapView(GenericAPIView): class TileView(BaseGeoView, ListAPIView): """View for serving tiled GeoJSON from a GeoModel.""" renderer_classes = (renderers.GeoJSONRenderer,) - # Geometry simplification tolerances based on tile zlevel, thanks to - # TileStache for determining these values. + # Geometry simplification tolerances based on tile zlevel, see + # http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames. tolerances = [6378137 * 2 * math.pi / (2 ** (zoom + 8)) for zoom in range(20)] diff --git a/tests/test_views.py b/tests/test_views.py index <HASH>..<HASH> 100644 --- a/tests/test_views.py +++ b/tests/test_views.py @@ -22,6 +22,8 @@ class TileViewTestCase(APITestCase): def test_response(self): response = self.client.get('/vectiles/10/553/347/') d = json.loads(response.content) + self.assertNotEqual(d['features'][0]['geometry']['coordinates'], + self.geometry['coordinates']) # This particular geometry clipped to a tile should have +1 coords. self.assertEqual(len(d['features'][0]['geometry']['coordinates'][0]), len(self.geometry['coordinates'][0]) + 1)
Tiled geometries should not be equal
bkg_django-spillway
train
139b099c81e1116ad8a1580a4bab9740450d217d
diff --git a/Tests/Functional/Entity/ExtendsEntityPage.php b/Tests/Functional/Entity/ExtendsEntityPage.php index <HASH>..<HASH> 100644 --- a/Tests/Functional/Entity/ExtendsEntityPage.php +++ b/Tests/Functional/Entity/ExtendsEntityPage.php @@ -6,8 +6,6 @@ use Axstrad\DoctrineExtensions\Activatable\ActivatableEntity; use Axstrad\DoctrineExtensions\Mapping\Annotation as Axstrad; use Doctrine\ORM\Mapping as ORM; -new Axstrad\Activatable(array()); - /** * @Axstrad\Activatable(fieldName="active") * @ORM\Entity diff --git a/Tests/Functional/Entity/SelfConfiguredPage.php b/Tests/Functional/Entity/SelfConfiguredPage.php index <HASH>..<HASH> 100644 --- a/Tests/Functional/Entity/SelfConfiguredPage.php +++ b/Tests/Functional/Entity/SelfConfiguredPage.php @@ -5,9 +5,6 @@ use Axstrad\Component\DoctrineOrm\Entity\BaseEntity; use Axstrad\DoctrineExtensions\Mapping\Annotation as Axstrad; use Doctrine\ORM\Mapping as ORM; -new ORM\Entity; -new ORM\Column; - /** * @Axstrad\Activatable(fieldName="active") * @ORM\Entity diff --git a/Tests/Functional/Entity/UsesTraitPage.php b/Tests/Functional/Entity/UsesTraitPage.php index <HASH>..<HASH> 100644 --- a/Tests/Functional/Entity/UsesTraitPage.php +++ b/Tests/Functional/Entity/UsesTraitPage.php @@ -6,11 +6,6 @@ use Axstrad\DoctrineExtensions\Activatable\ActivatableTrait; use Axstrad\DoctrineExtensions\Mapping\Annotation as Axstrad; use Doctrine\ORM\Mapping as ORM; -new ORM\Column; -new ORM\Entity; -new ORM\GeneratedValue; -new ORM\Id; - /** * @Axstrad\Activatable(fieldName="active") * @ORM\Entity
Fix the need to create new annotation configuration objects This was required when the test interacted with code that relied on annotations for configuration.
dankempster_axstrad-doctrine-extensions-bundle
train
6dbde83f5ed1449b27770517612ff4e4e4b00cc0
diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/cdi/ListProducer.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/cdi/ListProducer.java index <HASH>..<HASH> 100644 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/cdi/ListProducer.java +++ b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/cdi/ListProducer.java @@ -11,8 +11,11 @@ import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.CDI; import javax.enterprise.inject.spi.InjectionPoint; +/** + * @deprecated This class will be deleted very soon + */ public class ListProducer { - + @SuppressWarnings({ "rawtypes", "unchecked" }) @Produces public <T> List<T> producesList(InjectionPoint injectionPoint){ @@ -22,9 +25,9 @@ public class ListProducer { BeanManager beanManager = currentCDI.getBeanManager(); Set<Bean<?>> beans = beanManager.getBeans(klass); ArrayList objects = new ArrayList(); - for (Bean<?> bean : beans) { + for (Bean<?> bean : beans) { objects.add(currentCDI.select(bean.getBeanClass()).get()); } return objects; } -} +} \ No newline at end of file
deprecating ListProducer for now
caelum_vraptor4
train
786d26bce63175ef4b9acc516d52f9a662c13665
diff --git a/lib/Console/Commands/ElectionCommand.php b/lib/Console/Commands/ElectionCommand.php index <HASH>..<HASH> 100644 --- a/lib/Console/Commands/ElectionCommand.php +++ b/lib/Console/Commands/ElectionCommand.php @@ -23,6 +23,10 @@ use Symfony\Component\Console\Question\Question; class ElectionCommand extends Command { + protected Election $election; + protected string $candidates; + protected string $votes; + protected function configure () : void { $this->setName('election') @@ -33,24 +37,18 @@ class ElectionCommand extends Command , InputOption::VALUE_REQUIRED , 'Candidates List file path or direct input' ) - - ->addOption( 'votes','i' , InputOption::VALUE_REQUIRED , 'Votes List file path or direct input' ) - - ->addOption( 'stats','s' , InputOption::VALUE_NONE , 'Get detailled stats' ) - ->addOption( 'natural-condorcet','r' , InputOption::VALUE_NONE , 'Print natual Condorcet Winner / Loser' ) - ->addArgument( 'methods' , InputArgument::OPTIONAL | InputArgument::IS_ARRAY @@ -59,11 +57,14 @@ class ElectionCommand extends Command ; } - protected function execute (InputInterface $input, OutputInterface $output) : void + protected function initialize (InputInterface $input, OutputInterface $output) : void { - $election = new Election; + $this->election = new Election; + } - // Interractive Candidates + protected function interact (InputInterface $input, OutputInterface $output) : void + { + // Interactive Candidates if (empty($candidates = $input->getOption('candidates'))) : $helper = $this->getHelper('question'); @@ -81,10 +82,14 @@ class ElectionCommand extends Command endif; endwhile; - $candidates = implode(';', $registeringCandidates); + $this->candidates = implode(';', $registeringCandidates); + + // Non-interactive candidates + else : + $this->candidates = $candidates; endif; - // Interractive Candidates + // Interactive Votes if (empty($votes = $input->getOption('votes'))) : $helper = $this->getHelper('question'); @@ -102,11 +107,27 @@ class ElectionCommand extends Command endif; endwhile; - $votes = implode(';', $registeringvotes); + $this->votes = implode(';', $registeringvotes); + + // Non-interactive votes + else : + $this->votes = $votes; + endif; + } + + protected function execute (InputInterface $input, OutputInterface $output) : void + { + if ($file = $this->getFilePath($this->candidates)) : + $this->election->parseCandidates($file, true); + else : + $this->election->parseCandidates($this->candidates); endif; - $election->parseCandidates($candidates); - $election->parseVotes($votes); + if ($file = $this->getFilePath($this->votes)) : + $this->election->parseVotes($file, true); + else : + $this->election->parseVotes($this->votes); + endif; // Input Sum Up if ($output->isVerbose()) : @@ -128,7 +149,7 @@ class ElectionCommand extends Command foreach ($methods as $oneMethod) : - $result = $election->getResult(); + $result = $this->election->getResult(); $table = new Table($output); @@ -190,4 +211,21 @@ class ElectionCommand extends Command return $resultArray; } + protected function getFilePath (string $path) : ?string + { + if ($this->isAbsolute($path) && \is_file($path)) : + return $path; + elseif (\is_file($file = getcwd().\DIRECTORY_SEPARATOR.$path)) : + return $file; + else: + return null; + endif; + ; + } + + protected function isAbsolute (string $path) : bool + { + return strspn($path, '/\\', 0, 1) || (\strlen($path) > 3 && ctype_alpha($path[0]) && ':' === $path[1] && strspn($path, '/\\', 2, 1)); + } + } \ No newline at end of file
Refactoring election command & add file support.
julien-boudry_Condorcet
train
406b4ae5ff10e059589df7d84c531f1e2842bddd
diff --git a/device.js b/device.js index <HASH>..<HASH> 100644 --- a/device.js +++ b/device.js @@ -177,10 +177,10 @@ class Device extends EventEmitter { /** * Indicate that you want to monitor defined properties. */ - monitor() { + monitor(interval) { clearInterval(this._propertyMonitor); - this._propertyMonitor = setInterval(this._loadProperties, 30000); + this._propertyMonitor = setInterval(this._loadProperties, interval || 30000); return this._loadProperties(); }
Allow monitoring interval to be overriden
aholstenson_miio
train
b11a7bb0f5210f0f67828960fbae4cff5830adce
diff --git a/src/ProductSearch/ContentDelivery/ProductSearchApiV1GetRequestHandler.php b/src/ProductSearch/ContentDelivery/ProductSearchApiV1GetRequestHandler.php index <HASH>..<HASH> 100644 --- a/src/ProductSearch/ContentDelivery/ProductSearchApiV1GetRequestHandler.php +++ b/src/ProductSearch/ContentDelivery/ProductSearchApiV1GetRequestHandler.php @@ -116,7 +116,7 @@ class ProductSearchApiV1GetRequestHandler extends ApiRequestHandler private function getNumberOfProductPerPage(HttpRequest $request) : int { if ($request->hasQueryParameter(self::NUMBER_OF_PRODUCTS_PER_PAGE_PARAMETER)) { - return (int) ($request->getQueryParameter(self::NUMBER_OF_PRODUCTS_PER_PAGE_PARAMETER)); + return (int) $request->getQueryParameter(self::NUMBER_OF_PRODUCTS_PER_PAGE_PARAMETER); } return $this->defaultNumberOfProductPerPage; @@ -125,7 +125,7 @@ class ProductSearchApiV1GetRequestHandler extends ApiRequestHandler private function getPageNumber(HttpRequest $request) : int { if ($request->hasQueryParameter(self::PAGE_NUMBER_PARAMETER)) { - return (int) ($request->getQueryParameter(self::PAGE_NUMBER_PARAMETER)); + return (int) $request->getQueryParameter(self::PAGE_NUMBER_PARAMETER); } return 0;
Issue: #<I>: Remove superfluous parentheses
lizards-and-pumpkins_catalog
train
2673d0dd785bab51d088fe7ecdaedbf7854bb8b1
diff --git a/jgrassgears/src/main/java/org/jgrasstools/gears/io/dxfdwg/libs/dxf/DxfLWPOLYLINE.java b/jgrassgears/src/main/java/org/jgrasstools/gears/io/dxfdwg/libs/dxf/DxfLWPOLYLINE.java index <HASH>..<HASH> 100644 --- a/jgrassgears/src/main/java/org/jgrasstools/gears/io/dxfdwg/libs/dxf/DxfLWPOLYLINE.java +++ b/jgrassgears/src/main/java/org/jgrasstools/gears/io/dxfdwg/libs/dxf/DxfLWPOLYLINE.java @@ -52,8 +52,8 @@ public class DxfLWPOLYLINE extends DxfENTITY { super("DEFAULT"); } - public static DxfGroup readEntity( RandomAccessFile raf, - FeatureCollection<SimpleFeatureType, SimpleFeature> entities ) throws IOException { + public static DxfGroup readEntity( RandomAccessFile raf, FeatureCollection<SimpleFeatureType, SimpleFeature> entities ) + throws IOException { SimpleFeatureBuilder builder = new SimpleFeatureBuilder(DxfFile.DXF_LINESCHEMA); String layer = ""; String ltype = ""; @@ -110,10 +110,10 @@ public class DxfLWPOLYLINE extends DxfENTITY { group = DxfGroup.readGroup(raf); } } - if (geomType.equals("LineString")) { + if (geomType.equals("LineString") || coordList.size() < 4) { LineString lineString = gF.createLineString(coordList.toCoordinateArray()); - Object[] values = new Object[]{lineString, layer, ltype, elevation, thickness, - color, text, text_height, text_style}; + Object[] values = new Object[]{lineString, layer, ltype, elevation, thickness, color, text, text_height, + text_style}; builder.addAll(values); StringBuilder featureId = new StringBuilder(); featureId.append(DxfFile.DXF_LINESCHEMA.getTypeName()); @@ -123,10 +123,8 @@ public class DxfLWPOLYLINE extends DxfENTITY { entities.add(feature); } else if (geomType.equals("Polygon")) { coordList.closeRing(); - Polygon polygon = gF.createPolygon(gF.createLinearRing(coordList - .toCoordinateArray()), null); - Object[] values = new Object[]{polygon, layer, ltype, elevation, thickness, color, - text, text_height, text_style}; + Polygon polygon = gF.createPolygon(gF.createLinearRing(coordList.toCoordinateArray()), null); + Object[] values = new Object[]{polygon, layer, ltype, elevation, thickness, color, text, text_height, text_style}; builder.addAll(values); StringBuilder featureId = new StringBuilder(); featureId.append(DxfFile.DXF_LINESCHEMA.getTypeName()); @@ -135,6 +133,7 @@ public class DxfLWPOLYLINE extends DxfENTITY { SimpleFeature feature = builder.buildFeature(featureId.toString()); entities.add(feature); } else { + System.out.println("Can't handle geometry type: " + geomType); } } catch (IOException ioe) { throw ioe;
check on polygon creation from dxf - coord num
TheHortonMachine_hortonmachine
train