hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
6023cf252e487c8836ca06fb854f0cd2f99464ee
diff --git a/lib/deliver/upload_metadata.rb b/lib/deliver/upload_metadata.rb index <HASH>..<HASH> 100644 --- a/lib/deliver/upload_metadata.rb +++ b/lib/deliver/upload_metadata.rb @@ -17,12 +17,13 @@ module Deliver def upload(options) app = options[:app] + details = app.details v = app.edit_version raise "Could not find a version to edit for app '#{app.name}'".red unless v # TODO: Create new language - LOCALISED_VERSION_VALUES.each do |key| + (LOCALISED_VERSION_VALUES + LOCALISED_APP_VALUES).each do |key| value = options[key] next unless value @@ -32,18 +33,21 @@ module Deliver end value.each do |language, value| - v.send(key)[language] = value + v.send(key)[language] = value if LOCALISED_VERSION_VALUES.include?(key) + details.send(key)[language] = value if LOCALISED_APP_VALUES.include?(key) end end - NON_LOCALISED_VERSION_VALUES.each do |key| + (NON_LOCALISED_VERSION_VALUES + NON_LOCALISED_APP_VALUES).each do |key| value = options[key] next unless value - v.send("#{key}=", value) + v.send("#{key}=", value) if NON_LOCALISED_VERSION_VALUES.include?(key) + details.send("#{key}=", value) if NON_LOCALISED_APP_VALUES.include?(key) end Helper.log.info "Uploading metadata to iTunes Connect" v.save! + details.save! Helper.log.info "Successfully uploaded initial set of metadata to iTunes Connect".green end @@ -71,7 +75,7 @@ module Deliver next unless File.exist?(path) Helper.log.info "Loading '#{path}'..." - options[key] ||= File.read(path) # we can use the `lng`, it will be converted later + options[key] ||= File.read(path) end end end
Added upload of app details as well
fastlane_fastlane
train
5d9fa6d16167d23dc033f258db52d09e3721643e
diff --git a/ast.go b/ast.go index <HASH>..<HASH> 100644 --- a/ast.go +++ b/ast.go @@ -84,12 +84,17 @@ func (a Assign) End() Pos { type Redirect struct { OpPos Pos Op Token - N Lit + N *Lit Word Word Hdoc *Lit } -func (r Redirect) Pos() Pos { return r.N.Pos() } +func (r Redirect) Pos() Pos { + if r.N != nil { + return r.N.Pos() + } + return r.OpPos +} func (r Redirect) End() Pos { return r.Word.End() } // Command represents a command execution or function call. diff --git a/ast_test.go b/ast_test.go index <HASH>..<HASH> 100644 --- a/ast_test.go +++ b/ast_test.go @@ -780,7 +780,7 @@ var astTests = []testCase{ Redirs: []Redirect{ {Op: DPLOUT, Word: litWord("2")}, {Op: DPLIN, Word: litWord("0")}, - {Op: GTR, N: lit("2"), Word: litWord("file")}, + {Op: GTR, N: litRef("2"), Word: litWord("file")}, {Op: RDRINOUT, Word: litWord("f2")}, {Op: RDRALL, Word: litWord("f3")}, {Op: APPALL, Word: litWord("f4")}, @@ -2063,7 +2063,9 @@ func setPosRecurse(tb testing.TB, v interface{}, to Pos, diff bool) Node { for i := range x.Redirs { r := &x.Redirs[i] setPos(&r.OpPos) - recurse(&r.N) + if r.N != nil { + recurse(r.N) + } recurse(r.Word) if r.Hdoc != nil { recurse(r.Hdoc) diff --git a/parse.go b/parse.go index <HASH>..<HASH> 100644 --- a/parse.go +++ b/parse.go @@ -933,7 +933,10 @@ func (p *parser) gotRedirect() bool { s := p.stmtStack[len(p.stmtStack)-1] s.Redirs = append(s.Redirs, Redirect{}) r := &s.Redirs[len(s.Redirs)-1] - p.gotLit(&r.N) + var l Lit + if p.gotLit(&l) { + r.N = &l + } r.Op = p.tok r.OpPos = p.pos p.next() diff --git a/print.go b/print.go index <HASH>..<HASH> 100644 --- a/print.go +++ b/print.go @@ -418,6 +418,10 @@ func (p *printer) node(n Node) { for _, n := range x.Parts { p.nonSpaced(n) } + case *Lit: + if x != nil { + p.nonSpaced(x.Value) + } case Lit: p.nonSpaced(x.Value) case SglQuoted:
ast: make Redirect.N a pointer
mvdan_sh
train
cc42aad389c4022c5b7a1cfd72c4173d1ee23e62
diff --git a/README.rst b/README.rst index <HASH>..<HASH> 100644 --- a/README.rst +++ b/README.rst @@ -343,7 +343,7 @@ into this behavior, but Blessings makes it optional. If you want to do the state-restoration thing, use these capabilities: ``enter_fullscreen`` - Switch to the terminal mode where full-screen output is sanctioned. Call + Switch to the terminal mode where full-screen output is sanctioned. Print this before you do any output. ``exit_fullscreen`` Switch back to normal mode, restoring the exact state from before @@ -361,7 +361,7 @@ There's also a context manager you can use as a shortcut:: # Print some stuff. Besides brevity, another advantage is that it switches back to normal mode even -if an exception is raised in the with block. +if an exception is raised in the ``with`` block. Pipe Savvy ---------- @@ -434,6 +434,8 @@ Version History * Add syntactic sugar and documentation for ``enter_fullscreen`` and ``exit_fullscreen``. * Add context managers ``fullscreen()`` and ``hidden_cursor()``. + * Now you can force a ``Terminal`` never to emit styles by passing + ``force_styling=None``. 1.4 * Add syntactic sugar for cursor visibility control and single-space-movement diff --git a/blessings/__init__.py b/blessings/__init__.py index <HASH>..<HASH> 100644 --- a/blessings/__init__.py +++ b/blessings/__init__.py @@ -69,6 +69,9 @@ class Terminal(object): somewhere, and stdout is probably where the output is ultimately headed. If not, stderr is probably bound to the same terminal.) + If you want to force styling to not happen, pass + ``force_styling=None``. + """ if stream is None: stream = sys.__stdout__ @@ -80,7 +83,8 @@ class Terminal(object): stream_descriptor = None self.is_a_tty = stream_descriptor is not None and isatty(stream_descriptor) - self._does_styling = self.is_a_tty or force_styling + self._does_styling = ((self.is_a_tty or force_styling) and + force_styling is not None) # The desciptor to direct terminal initialization sequences to. # sys.__stdout__ seems to always have a descriptor of 1, even if output diff --git a/blessings/tests.py b/blessings/tests.py index <HASH>..<HASH> 100644 --- a/blessings/tests.py +++ b/blessings/tests.py @@ -248,3 +248,9 @@ def test_init_descriptor_always_initted(): """We should be able to get a height and width even on no-tty Terminals.""" t = Terminal(stream=StringIO()) eq_(type(t.height), int) + + +def test_force_styling_none(): + """If ``force_styling=None`` is passed to the constructor, don't ever do styling.""" + t = TestTerminal(force_styling=None) + eq_(t.save, '')
Provide a decent way to say "don't style". Closes #<I>.
erikrose_blessings
train
da8ae29620811f3dc058e0e665d402a208a1fe6c
diff --git a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go index <HASH>..<HASH> 100644 --- a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go +++ b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go @@ -292,7 +292,11 @@ func ListResource(r rest.Lister, rw rest.Watcher, scope RequestScope, forceWatch opts.FieldSelector = nameSelector } - if (opts.Watch || forceWatch) && rw != nil { + if opts.Watch || forceWatch { + if rw == nil { + scope.err(errors.NewMethodNotSupported(scope.Resource.GroupResource(), "watch"), w, req) + return + } // TODO: Currently we explicitly ignore ?timeout= and use only ?timeoutSeconds=. timeout := time.Duration(0) if opts.TimeoutSeconds != nil {
Return MethodNotSupported when accessing unwatcheable resource with ?watch=true
kubernetes_kubernetes
train
be65546fbe2bbe3115755f5350507a92aac1cd41
diff --git a/src/Command/SelfUpdate.php b/src/Command/SelfUpdate.php index <HASH>..<HASH> 100644 --- a/src/Command/SelfUpdate.php +++ b/src/Command/SelfUpdate.php @@ -36,6 +36,11 @@ class SelfUpdate extends Command protected $output; /** + * @var string + */ + protected $version; + + /** * Execute the command. * * @param InputInterface $input @@ -44,26 +49,45 @@ class SelfUpdate extends Command protected function execute(InputInterface $input, OutputInterface $output) { $this->output = $output; - /** - * This specific code assumes migration from manual SHA-1 tracked - * development versions to either a pre-release (default) or solely - * a stable version. An option is allowed for going back to manual - * phar builds at the development level. - * - * Will be updated again once the stable track is established. - */ + $this->version = $this->getApplication()->getVersion(); + $parser = new VersionParser; + + if ($input->getOption('rollback')) { + $this->rollback(); + return; + } + + if ($input->getOption('dev')) { + $this->updateToDevelopmentBuild(); + return; + } + if ($input->getOption('pre')) { $this->updateToPreReleaseBuild(); return; } - /** - * This is the final development build being installed automatically - * Any future dev updates need to carry the --dev flag in command. - */ - $this->updateToDevelopmentBuild(); - // alpha/beta/rc? - // Can likely add update config at some point... + if ($input->getOption('stable')) { + $this->updateToStableBuild(); + return; + } + + if ($input->getOption('check')) { + throw new \RuntimeException('Not implemented.') + return; + } + + if ($parser->isStable($this->version)) { + $this->updateToStableBuild(); + return; + } + + if ($parser->isPreRelease($this->version)) { + $this->updateToPreReleaseBuild(); + return; + } + + $this->updateToDevelopmentBuild(); } protected function updateToStableBuild() @@ -93,9 +117,7 @@ class SelfUpdate extends Command { $updater->getStrategy()->setPackageName(self::PACKAGE_NAME); $updater->getStrategy()->setPharName(self::FILE_NAME); - $updater->getStrategy()->setCurrentLocalVersion( - $this->getApplication()->getVersion() - ); + $updater->getStrategy()->setCurrentLocalVersion($this->version); $this->update($updater); } @@ -138,6 +160,21 @@ class SelfUpdate extends Command $this->output->writeln('You can also select update stability using --dev, --pre (alpha/beta/rc) or --stable.'); } + protected function rollback() + { + $updater = new Updater; + try { + $result = $updater->rollback(); + if ($result) { + $this->output->writeln('<fg=green>Humbug has been rolled back to prior version.</fg=green>'); + } else { + $this->output->writeln('<fg=red>Rollback failed for reasons unknown.</fg=red>'); + } + } catch (\Exception $e) { + $this->output->writeln(sprintf('Error: <fg=yellow>%s</fg=yellow>', $e->getMessage())); + } + } + protected function configure() { $this
Update self-update workflow to automatically use current stability as minimum when updating
humbug_humbug
train
abed0101c48c84bfef804726d8541816260e0c81
diff --git a/rinoh/document.py b/rinoh/document.py index <HASH>..<HASH> 100644 --- a/rinoh/document.py +++ b/rinoh/document.py @@ -163,6 +163,7 @@ class DocumentSection(object): def __init__(self, document): self.document = document self._parts = [part_class(self) for part_class in self.parts] + self.total_number_of_pages = 0 @property def number_of_pages(self): @@ -184,6 +185,7 @@ class DocumentSection(object): def render(self): for part in self._parts: part.render() + self.total_number_of_pages = self.number_of_pages class Document(object): @@ -253,13 +255,15 @@ to the terms of the GNU Affero General Public License version 3.''') with open(filename + self.CACHE_EXTENSION, 'rb') as file: prev_number_of_pages, prev_page_references = pickle.load(file) except IOError: - prev_number_of_pages, prev_page_references = -1, {} + prev_number_of_pages, prev_page_references = None, {} return prev_number_of_pages, prev_page_references def _save_cache(self, filename): """Save the current state of the page references to `<filename>.ptc`""" with open(filename + self.CACHE_EXTENSION, 'wb') as file: - cache = self.total_number_of_pages, self.page_references + cache = ([section.total_number_of_pages + for section in self._sections], + self.page_references) pickle.dump(cache, file) def get_style_var(self, name): @@ -281,6 +285,9 @@ to the terms of the GNU Affero General Public License version 3.''') self.page_references == prev_page_references) prev_number_of_pages, prev_page_references = self._load_cache(filename) + if prev_number_of_pages: + for prev_num, section in zip(prev_number_of_pages, self._sections): + section.total_number_of_pages = prev_num self.total_number_of_pages = prev_number_of_pages self.page_references = prev_page_references.copy() for flowable in self.content_flowables: diff --git a/rinoh/reference.py b/rinoh/reference.py index <HASH>..<HASH> 100644 --- a/rinoh/reference.py +++ b/rinoh/reference.py @@ -44,7 +44,8 @@ class Variable(Field): text = format_number(container.page.number, container.page.number_format) elif self.type == NUMBER_OF_PAGES: - number = container.document_part.document_section.number_of_pages + section = container.document_part.document_section + number = section.total_number_of_pages text = format_number(number, container.page.number_format) elif self.type == SECTION_NUMBER and container.page.section: section_id = container.page.section.get_id(container.document) diff --git a/rinohlib/templates/base.py b/rinohlib/templates/base.py index <HASH>..<HASH> 100644 --- a/rinohlib/templates/base.py +++ b/rinohlib/templates/base.py @@ -4,7 +4,8 @@ from rinoh.document import Document, DocumentPart, Page, PORTRAIT from rinoh.layout import (Container, FootnoteContainer, Chain, UpExpandingContainer, DownExpandingContainer) from rinoh.paper import A4 -from rinoh.reference import Variable, PAGE_NUMBER, SECTION_NUMBER, SECTION_TITLE +from rinoh.reference import Variable, PAGE_NUMBER, SECTION_NUMBER, SECTION_TITLE, \ + NUMBER_OF_PAGES from rinoh.structure import Section, Heading, TableOfContents, Header, Footer from rinoh.text import Tab from rinoh.util import NotImplementedAttribute @@ -117,7 +118,8 @@ class DocumentOptions(dict): 'page_vertical_margin': 3*CM, 'header_text': (Variable(SECTION_NUMBER) + ' ' + Variable(SECTION_TITLE)), - 'footer_text': Tab() + Variable(PAGE_NUMBER)} + 'footer_text': Tab() + Variable(PAGE_NUMBER) + + '/' + Variable(NUMBER_OF_PAGES)} def __init__(self, **options): for name, value in options.items():
Cache each section's total number of pages
brechtm_rinohtype
train
e4762f28e9b34bc5fc50c87a0e8de8aba4d92e10
diff --git a/ddl/ddl_api.go b/ddl/ddl_api.go index <HASH>..<HASH> 100644 --- a/ddl/ddl_api.go +++ b/ddl/ddl_api.go @@ -21,6 +21,7 @@ import ( "bytes" "context" "fmt" + "math" "strconv" "strings" "sync/atomic" @@ -1134,7 +1135,7 @@ func checkConstraintNames(constraints []*ast.Constraint) error { return nil } -func setTableAutoRandomBits(tbInfo *model.TableInfo, colDefs []*ast.ColumnDef) error { +func setTableAutoRandomBits(ctx sessionctx.Context, tbInfo *model.TableInfo, colDefs []*ast.ColumnDef) error { allowAutoRandom := config.GetGlobalConfig().Experimental.AllowAutoRandom pkColName := tbInfo.GetPkName() for _, col := range colDefs { @@ -1163,6 +1164,10 @@ func setTableAutoRandomBits(tbInfo *model.TableInfo, colDefs []*ast.ColumnDef) e return ErrInvalidAutoRandom.GenWithStackByArgs(fmt.Sprintf(autoid.AutoRandomOverflowErrMsg, col.Name.Name.L, maxFieldTypeBitsLength, autoRandBits, col.Name.Name.L, maxFieldTypeBitsLength-1)) } tbInfo.AutoRandomBits = autoRandBits + + availableBits := maxFieldTypeBitsLength - 1 - autoRandBits + msg := fmt.Sprintf(autoid.AutoRandomAvailableAllocTimesNote, uint64(math.Pow(2, float64(availableBits)))-1) + ctx.GetSessionVars().StmtCtx.AppendNote(errors.Errorf(msg)) } } return nil @@ -1364,7 +1369,7 @@ func buildTableInfoWithCheck(ctx sessionctx.Context, s *ast.CreateTableStmt, dbC tbInfo.Collate = tableCollate tbInfo.Charset = tableCharset - if err = setTableAutoRandomBits(tbInfo, colDefs); err != nil { + if err = setTableAutoRandomBits(ctx, tbInfo, colDefs); err != nil { return nil, errors.Trace(err) } diff --git a/ddl/serial_test.go b/ddl/serial_test.go index <HASH>..<HASH> 100644 --- a/ddl/serial_test.go +++ b/ddl/serial_test.go @@ -882,6 +882,23 @@ func (s *testSerialSuite) TestAutoRandom(c *C) { assertModifyColType("alter table t modify column a smallint auto_random(3)") }) + // Test show warnings when create auto_random table. + assertShowWarningCorrect := func(sql string, times int) { + mustExecAndDrop(sql, func() { + note := fmt.Sprintf(autoid.AutoRandomAvailableAllocTimesNote, times) + result := fmt.Sprintf("Note|1105|%s", note) + tk.MustQuery("show warnings").Check(testutil.RowsWithSep("|", result)) + c.Assert(tk.Se.GetSessionVars().StmtCtx.WarningCount(), Equals, uint16(0)) + }) + } + assertShowWarningCorrect("create table t (a tinyint unsigned auto_random(6) primary key)", 1) + assertShowWarningCorrect("create table t (a tinyint unsigned auto_random(5) primary key)", 3) + assertShowWarningCorrect("create table t (a tinyint auto_random(4) primary key)", 7) + assertShowWarningCorrect("create table t (a bigint auto_random(62) primary key)", 1) + assertShowWarningCorrect("create table t (a bigint unsigned auto_random(61) primary key)", 3) + assertShowWarningCorrect("create table t (a int auto_random(30) primary key)", 1) + assertShowWarningCorrect("create table t (a int auto_random(29) primary key)", 3) + // Disallow using it when allow-auto-random is not enabled. config.GetGlobalConfig().Experimental.AllowAutoRandom = false assertExperimentDisabled("create table auto_random_table (a int primary key auto_random(3))") diff --git a/meta/autoid/errors.go b/meta/autoid/errors.go index <HASH>..<HASH> 100644 --- a/meta/autoid/errors.go +++ b/meta/autoid/errors.go @@ -45,4 +45,6 @@ const ( AutoRandomAlterErrMsg = "adding/dropping/modifying auto_random is not supported" // AutoRandomNonPositive is reported then a user specifies a non-positive value for auto_random. AutoRandomNonPositive = "the value of auto_random should be positive" + // AutoRandomAvailableAllocTimesNote is reported when a table containing auto_random is created. + AutoRandomAvailableAllocTimesNote = "Available implicit allocation times: %d" )
ddl: show max allocate times when an auto_random table is created (#<I>)
pingcap_tidb
train
d2ea11079076e7446a162bb799af40d973f58c3a
diff --git a/Classes/Persistence/YamlPersistenceManager.php b/Classes/Persistence/YamlPersistenceManager.php index <HASH>..<HASH> 100644 --- a/Classes/Persistence/YamlPersistenceManager.php +++ b/Classes/Persistence/YamlPersistenceManager.php @@ -51,11 +51,13 @@ class YamlPersistenceManager implements FormPersistenceManagerInterface { foreach ($this->allowedDirectories as $directory) { $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory)); foreach ($iterator as $fileObject) { - $form = $this->load($fileObject->getPathname()); - $forms[] = array( - 'name' => $form['identifier'], - 'persistenceIdentifier' => $fileObject->getPathname() - ); + if ($fileObject->isFile()) { + $form = $this->load($fileObject->getPathname()); + $forms[] = array( + 'name' => $form['identifier'], + 'persistenceIdentifier' => $fileObject->getPathname() + ); + } } } return $forms;
[BUGFIX] only add form to list if it is a regular file
neos_form
train
12a962266c5efd9f6be2c203ac7fd9ffb4d1d57b
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -136,6 +136,31 @@ async def main() -> None: await client.programs.start(1) await client.programs.stop(1) + # Get basic details about all zones: + zones = await client.zones.all(): + + # Get advanced details about all zones: + zones = await client.zones.all(details=True): + + # Include inactive zones: + zones = await client.zones.all(include_inactive=True): + + # Get basic details about a specific zone: + zone_1 = await client.zones.get(1) + + # Get advanced details about a specific zone: + zone_1 = await client.zones.get(1, details=True) + + # Enable or disable a specific zone: + await client.zones.enable(1) + await client.zones.disable(1) + + # Start a zone for 60 seconds: + await client.zones.start(1, 60) + + # ...and stop it: + await client.zones.stop(1) + # Get the device name: name = await client.provisioning.device_name diff --git a/regenmaschine/program.py b/regenmaschine/program.py index <HASH>..<HASH> 100644 --- a/regenmaschine/program.py +++ b/regenmaschine/program.py @@ -10,7 +10,7 @@ class Program: self._request = request async def _post(self, program_id: int = None, json: dict = None) -> dict: - """Set whether a program is active or not.""" + """Post data to a (non)existing program.""" return await self._request( 'post', 'program/{0}'.format(program_id), json=json) diff --git a/regenmaschine/zone.py b/regenmaschine/zone.py index <HASH>..<HASH> 100644 --- a/regenmaschine/zone.py +++ b/regenmaschine/zone.py @@ -9,6 +9,11 @@ class Zone: """Initialize.""" self._request = request + async def _post(self, zone_id: int = None, json: dict = None) -> dict: + """Post data to a (non)existing zone.""" + return await self._request( + 'post', 'zone/{0}'.format(zone_id), json=json) + async def all( self, *, details: bool = False, include_inactive: bool = False) -> list: @@ -19,6 +24,14 @@ class Zone: data = await self._request('get', endpoint) return [z for z in data['zones'] if include_inactive or z['active']] + async def disable(self, zone_id: int) -> dict: + """Disable a zone.""" + return await self._post(zone_id, {'active': False}) + + async def enable(self, zone_id: int) -> dict: + """Enable a zone.""" + return await self._post(zone_id, {'active': True}) + async def get(self, zone_id: int, *, details: bool = False) -> dict: """Return a specific zone.""" endpoint = 'zone/{0}'.format(zone_id) diff --git a/tests/fixtures/zone.py b/tests/fixtures/zone.py index <HASH>..<HASH> 100644 --- a/tests/fixtures/zone.py +++ b/tests/fixtures/zone.py @@ -46,6 +46,15 @@ def zone_id_properties_json(): @pytest.fixture() +def zone_post_json(): + """Return a /zone (POST) response.""" + return { + "statusCode": 0, + "message": "OK" + } + + [email protected]() def zone_properties_json(): """Return a /zone/properties response.""" return { diff --git a/tests/test_zone.py b/tests/test_zone.py index <HASH>..<HASH> 100644 --- a/tests/test_zone.py +++ b/tests/test_zone.py @@ -16,6 +16,35 @@ from .fixtures.zone import * @pytest.mark.asyncio +async def test_zone_enable_disable( + aresponses, authenticated_client, event_loop, zone_post_json): + """Test enabling a zone.""" + async with authenticated_client: + authenticated_client.add( + '{0}:{1}'.format(TEST_HOST, TEST_PORT), '/api/4/zone/1', 'post', + aresponses.Response( + text=json.dumps(zone_post_json), status=200)) + authenticated_client.add( + '{0}:{1}'.format(TEST_HOST, TEST_PORT), '/api/4/zone/1', 'post', + aresponses.Response( + text=json.dumps(zone_post_json), status=200)) + + async with aiohttp.ClientSession(loop=event_loop) as websession: + client = await login( + TEST_HOST, + TEST_PASSWORD, + websession, + port=TEST_PORT, + ssl=False) + + resp = await client.zones.enable(1) + assert resp['message'] == 'OK' + + resp = await client.zones.disable(1) + assert resp['message'] == 'OK' + + [email protected] async def test_zone_get_all( aresponses, authenticated_client, event_loop, zone_properties_json): """Test getting info on all zones."""
Add ability to enable and disable zones (#<I>) * Updated docstring * Added functionality * Updated README
bachya_regenmaschine
train
f35c82117ae3617172bd3ac82b212b662e81568e
diff --git a/bloop/engine.py b/bloop/engine.py index <HASH>..<HASH> 100644 --- a/bloop/engine.py +++ b/bloop/engine.py @@ -60,10 +60,23 @@ def _dump_key(engine, obj): return key -class LoadRequest: +class _LoadManager: + """ + The load operation involves a double indexing to provide O(1) + lookup from a table name and dictionary of attributes. + + Besides the lookups to associate a blob of attributes with an + instance of a model, loading involves manipulating these blobs + into real python values, and modifying the tracking for each object. + + This class exists to keep the more complex of the three pieces + separated, and easier to maintain. + """ def __init__(self, engine): self.engine = engine self.indexed_objects = {} + # If there are any objects in this set after popping all the items + # from a response, then the remaining items were not processed. self.objects = set() self.table_keys = {} self.wire = {} @@ -93,10 +106,6 @@ class LoadRequest: self.indexed_objects[table_name][index] = obj self.objects.add(obj) - def extend(self, objects): - for obj in objects: - self.add(obj) - def pop(self, table_name, item): objects = self.indexed_objects[table_name] keys = self.table_keys[table_name] @@ -105,10 +114,6 @@ class LoadRequest: self.objects.remove(obj) return obj - @property - def missing(self): - return self.objects - class Engine: model = None @@ -238,20 +243,20 @@ class Engine: # Load multiple instances engine.load(hash_only, hash_and_range) """ - request = LoadRequest(self) - request.extend(_list_of(objs)) - results = self.client.batch_get_items(request.wire) + request = _LoadManager(self) + for obj in _list_of(objs): + request.add(obj) + response = self.client.batch_get_items(request.wire) - for table_name, items in results.items(): + for table_name, items in response.items(): for item in items: obj = request.pop(table_name, item) self._update(obj, item, obj.Meta.columns) - bloop.tracking.set_snapshot(obj, self) bloop.tracking.set_synced(obj) - if request.missing: - raise bloop.exceptions.NotModified("load", request.missing) + if request.objects: + raise bloop.exceptions.NotModified("load", request.objects) def query(self, obj): if isinstance(obj, bloop.index._Index):
Rename LoadRequest, docstring its purpose
numberoverzero_bloop
train
57c23e213cc18f610473892113a105ef390f0620
diff --git a/src/test/java/io/nats/streaming/PublishTests.java b/src/test/java/io/nats/streaming/PublishTests.java index <HASH>..<HASH> 100644 --- a/src/test/java/io/nats/streaming/PublishTests.java +++ b/src/test/java/io/nats/streaming/PublishTests.java @@ -114,7 +114,7 @@ public class PublishTests { // Send more than one message, if MaxPubAcksInflight() works, one // of the publish call should block for up to PubAckWait. - Instant start = Instant.now(); + Instant start = Instant.now().minusMillis(100); try { for (int i = 0; i < 2; i++) { sc.publish("foo", msg, null); @@ -123,7 +123,7 @@ public class PublishTests { ex.printStackTrace(); // Should get one of these for timeout } - Instant end = Instant.now(); + Instant end = Instant.now().plusMillis(100); // So if the loop ended before the PubAckWait timeout, then it's a failure. if (Duration.between(start, end).compareTo(Duration.ofSeconds(1)) < 0) { fail("Should have blocked after 1 message sent"); diff --git a/src/test/java/io/nats/streaming/SubscribeTests.java b/src/test/java/io/nats/streaming/SubscribeTests.java index <HASH>..<HASH> 100644 --- a/src/test/java/io/nats/streaming/SubscribeTests.java +++ b/src/test/java/io/nats/streaming/SubscribeTests.java @@ -754,13 +754,13 @@ public class SubscribeTests { new SubscriptionOptions.Builder().deliverAllAvailable().build())) { // Wait for our expected count. - assertTrue("Did not receive our messages", latch.await(5, TimeUnit.SECONDS)); + assertTrue("Did not receive our messages", latch.await(10, TimeUnit.SECONDS)); // Wait to see if the subscriber receives any duplicate messages. - try{Thread.sleep(250);}catch(Exception exp){} + try{Thread.sleep(1000);}catch(Exception exp){} // Make sure we've received the exact count of sent messages. - assertEquals("Didn't get expected #messages.", sent.get(), received.get()); + assertEquals("Didn't get expected number of messages.", sent.get(), received.get()); } }
Workign on flaky tests and timing on travis.
nats-io_java-nats-streaming
train
2c27b24e352c16adf97d913c17f6e60ecbf3dcae
diff --git a/sphinx_revealjs/directives.py b/sphinx_revealjs/directives.py index <HASH>..<HASH> 100644 --- a/sphinx_revealjs/directives.py +++ b/sphinx_revealjs/directives.py @@ -29,26 +29,26 @@ def raw_json(argument): REVEALJS_SECTION_ATTRIBUTES = { - # Color backgrounds + # Backgrounds / Color Backgrounds "data-background-color": directives.unchanged, - # Image backgrounds + # Backgrounds / Image Backgrounds "data-background-image": directives.unchanged, "data-background-position": directives.unchanged, "data-background-repeat": directives.unchanged, - # Video backgrounds + # Backgrounds / Video Backgrounds "data-background-video": directives.unchanged, "data-background-video-loop": directives.unchanged, "data-background-video-muted": directives.unchanged, - # Image/Video backgrounds + # Backgrounds / Image and Video Backgrounds "data-background-size": directives.unchanged, "data-background-opacity": directives.unchanged, - # Iframe backgrounds + # Backgrounds / Iframe Backgrounds "data-background-iframe": directives.unchanged, "data-background-interactive": lambda x: FlagAttribute(), - # Transition + # Transitions "data-transition": directives.unchanged, "data-background-transition": directives.unchanged, - # Animations + # Auto-Animate "data-auto-animate": lambda x: FlagAttribute(), "data-auto-animate-delay": directives.unchanged, "data-auto-animate-duration": directives.unchanged,
refactor: Rename title of attributes on comments
attakei_sphinx-revealjs
train
19a9c2d8c8f5ab096e6ab98c80c336f0c7cccb7f
diff --git a/lib/environment/LocalStorageKeyEnvironment.js b/lib/environment/LocalStorageKeyEnvironment.js index <HASH>..<HASH> 100644 --- a/lib/environment/LocalStorageKeyEnvironment.js +++ b/lib/environment/LocalStorageKeyEnvironment.js @@ -1,4 +1,4 @@ -"use strict"; +'use strict'; var Environment = require('./Environment'); @@ -9,29 +9,40 @@ function LocalStorageKeyEnvironment(key) { this.key = key; this.onStorage = this.onStorage.bind(this); Environment.call(this); + + var store = this.onStorage; + this.storage = (typeof window !== 'undefined' && window.localStorage) || { + data: {}, + getItem: function(key) {return this.data[key];}, + setItem: function(key, val) {this.data[key]=val;store();} + }; } LocalStorageKeyEnvironment.prototype = Object.create(Environment.prototype); LocalStorageKeyEnvironment.prototype.constructor = LocalStorageKeyEnvironment; LocalStorageKeyEnvironment.prototype.getPath = function() { - return window.localStorage.getItem(this.key) || ''; + return this.storage.getItem(this.key) || ''; }; LocalStorageKeyEnvironment.prototype.pushState = function(path, navigation) { - window.localStorage.setItem(this.key, path); + this.storage.setItem(this.key, path); }; LocalStorageKeyEnvironment.prototype.replaceState = function(path, navigation) { - window.localStorage.setItem(this.key, path); + this.storage.setItem(this.key, path); }; LocalStorageKeyEnvironment.prototype.start = function() { - window.addEventListener('storage', this.onStorage, false); + if (typeof window !== 'undefined' && window.addEventListener) { + window.addEventListener('storage', this.onStorage, false); + } }; LocalStorageKeyEnvironment.prototype.stop = function() { - window.removeEventListener('storage', this.onStorage); + if (typeof window !== 'undefined' && window.removeEventListener) { + window.removeEventListener('storage', this.onStorage); + } }; LocalStorageKeyEnvironment.prototype.onStorage = function() {
make local storage fallback to in-memory if local storage is not available.
STRML_react-router-component
train
f1139a5985ecdcd5723f854d4eb941fb440b4bcd
diff --git a/lib/capybara/selector/regexp_disassembler.rb b/lib/capybara/selector/regexp_disassembler.rb index <HASH>..<HASH> 100644 --- a/lib/capybara/selector/regexp_disassembler.rb +++ b/lib/capybara/selector/regexp_disassembler.rb @@ -100,6 +100,8 @@ module Capybara def extract_strings(process_alternatives) strings = [] each do |exp| + next if exp.ignore? + next strings.push(nil) if exp.optional? && !process_alternatives next strings.push(exp.alternative_strings) if exp.alternation? && process_alternatives @@ -159,6 +161,11 @@ module Capybara alts.all?(&:any?) ? Set.new(alts) : nil end + def ignore? + [Regexp::Expression::Assertion::NegativeLookahead, + Regexp::Expression::Assertion::NegativeLookbehind].any? { |klass| @exp.is_a? klass } + end + private def indeterminate? diff --git a/spec/regexp_dissassembler_spec.rb b/spec/regexp_dissassembler_spec.rb index <HASH>..<HASH> 100644 --- a/spec/regexp_dissassembler_spec.rb +++ b/spec/regexp_dissassembler_spec.rb @@ -212,6 +212,16 @@ RSpec.describe Capybara::Selector::RegexpDisassembler, :aggregate_failures do ) end + it 'ignores negative lookaheads' do + verify_strings( + /^(?!.*\bContributing Editor\b).*$/ => %w[], + /abc(?!.*def).*/ => %w[abc], + /(?!.*def)abc/ => %w[abc], + /abc(?!.*def.*).*ghi/ => %w[abc ghi], + /abc(?!.*bcd)def/ => %w[abcdef] + ) + end + it 'handles anchors' do verify_strings( /^abc/ => %w[abc],
Ignore negative text requirements when extracting strings from regexps
teamcapybara_capybara
train
ec85c50d1da02e7a764a0d013b9e502a23aa96c9
diff --git a/src/Table.js b/src/Table.js index <HASH>..<HASH> 100644 --- a/src/Table.js +++ b/src/Table.js @@ -5,6 +5,7 @@ import isArray from 'lodash/isArray'; import debounce from 'lodash/debounce'; import isEqual from 'lodash/isEqual'; import omit from 'lodash/omit'; +import merge from 'lodash/merge'; import isUndefined from 'lodash/isUndefined'; import pick from 'lodash/pick'; @@ -70,8 +71,11 @@ function colSpanCells(cells) { for (let j = 0; j < colSpan; j += 1) { let nextCell = cells[i + j]; if (nextCell) { - let { rowData, dataKey, width: colSpanWidth } = nextCell.props; - if (rowData && isNullOrUndefined(rowData[dataKey])) { + let { rowData, dataKey, children, width: colSpanWidth, isHeaderCell } = nextCell.props; + if ( + (rowData && isNullOrUndefined(rowData[dataKey])) || + (isHeaderCell && isNullOrUndefined(children)) + ) { nextWidth += colSpanWidth; cells[i + j] = cloneCell(nextCell, { removed: true @@ -335,8 +339,11 @@ class Table extends React.Component { }; let headerCellsProps = { + ...pick(column.props, Object.keys(Column.propTypes)), + width: nextWidth, headerHeight: headerHeight || rowHeight, dataKey: columnChildren[1].props.dataKey, + isHeaderCell: true, sortColumn, sortType, onSortColumn, @@ -344,9 +351,11 @@ class Table extends React.Component { }; if (resizable) { - headerCellsProps.onColumnResizeEnd = this.onColumnResizeEnd; - headerCellsProps.onColumnResizeStart = this.onColumnResizeStart; - headerCellsProps.onColumnResizeMove = this.onColumnResizeMove; + merge(headerCellsProps, { + onColumnResizeEnd: this.onColumnResizeEnd, + onColumnResizeStart: this.onColumnResizeStart, + onColumnResizeMove: this.onColumnResizeMove + }); } headerCells.push(cloneCell(columnChildren[0], {
Added support for merging cells in the Header
rsuite_rsuite-table
train
d07e0e099c8e89c9584c6ef6a9fe6b2b66b5f383
diff --git a/src/svg/Painter.js b/src/svg/Painter.js index <HASH>..<HASH> 100644 --- a/src/svg/Painter.js +++ b/src/svg/Painter.js @@ -96,12 +96,13 @@ var SVGPainter = function (root, storage, opts) { svgRoot.setAttribute('version', '1.1'); svgRoot.setAttribute('baseProfile', 'full'); svgRoot.style['user-select'] = 'none'; + svgRoot.style.cssText = 'position:absolute;left:0;top:0;'; this.gradientManager = new GradientManager(svgRoot); this.clipPathManager = new ClippathManager(svgRoot); var viewport = document.createElement('div'); - viewport.style.cssText = 'overflow: hidden;'; + viewport.style.cssText = 'overflow:hidden;position:relative'; this._svgRoot = svgRoot; this._viewport = viewport;
fix: svg bug when roaming with bmap
ecomfe_zrender
train
1b150b982f6573dc93b6c84063ff402da713c5aa
diff --git a/src/Spec/Spec.php b/src/Spec/Spec.php index <HASH>..<HASH> 100644 --- a/src/Spec/Spec.php +++ b/src/Spec/Spec.php @@ -385,6 +385,11 @@ class Spec return false; } + return $this->subjectFieldIsBlank($subject); + } + + protected function subjectFieldIsBlank($subject) + { // the field name $field = $this->field; diff --git a/src/Spec/ValidateSpec.php b/src/Spec/ValidateSpec.php index <HASH>..<HASH> 100644 --- a/src/Spec/ValidateSpec.php +++ b/src/Spec/ValidateSpec.php @@ -165,12 +165,12 @@ class ValidateSpec extends Spec */ protected function applyRule($subject) { - if (! $this->rule) { - return false; + if ($this->subjectFieldIsBlank($subject)) { + return $this->allow_blank; } - if (! isset($subject->{$this->field})) { - return false; + if (! $this->rule) { + return $this->reverse; } if ($this->reverse) { diff --git a/tests/Spec/ValidateSpecTest.php b/tests/Spec/ValidateSpecTest.php index <HASH>..<HASH> 100644 --- a/tests/Spec/ValidateSpecTest.php +++ b/tests/Spec/ValidateSpecTest.php @@ -144,4 +144,37 @@ class ValidateSpecTest extends \PHPUnit_Framework_TestCase $subject->foo = 'zimgir'; $this->assertTrue($this->spec->__invoke($subject)); } + + public function testIsNotBlank() + { + $this->spec->field('foo')->isNotBlank(); + + $subject = (object) array(); + + $subject->foo = 0; + $this->assertTrue($this->spec->__invoke($subject)); + + $subject->foo = '0'; + $this->assertTrue($this->spec->__invoke($subject)); + + $subject->foo = 'bar'; + $this->assertTrue($this->spec->__invoke($subject)); + + $expect = 'foo should not have been blank'; + + $subject = (object) array(); + $this->assertFalse($this->spec->__invoke($subject)); + $this->assertSame($expect, $this->spec->getMessage()); + + $subject->foo = null; + $this->assertFalse($this->spec->__invoke($subject)); + $this->assertSame($expect, $this->spec->getMessage()); + + $subject->foo = ' '; + $this->assertFalse($this->spec->__invoke($subject)); + $this->assertSame($expect, $this->spec->getMessage()); + + $subject->foo = 123; + $this->assertTrue($this->spec->__invoke($subject)); + } }
better isNotBlank() checking, and better test for it
auraphp_Aura.Filter
train
9d247718d7e17037999316f5114f7fe08df01e03
diff --git a/cmd/ctr/commands/tasks/list.go b/cmd/ctr/commands/tasks/list.go index <HASH>..<HASH> 100644 --- a/cmd/ctr/commands/tasks/list.go +++ b/cmd/ctr/commands/tasks/list.go @@ -34,7 +34,7 @@ var listCommand = cli.Command{ Flags: []cli.Flag{ cli.BoolFlag{ Name: "quiet, q", - Usage: "print only the task id & pid", + Usage: "print only the task id", }, }, Action: func(context *cli.Context) error {
Update ctr tasks list usage for quiet flag
containerd_containerd
train
4b525daf72c6a5002f74d7969a11fc62cb41c95f
diff --git a/lib/6to5/transformation/transformers/es6-for-of.js b/lib/6to5/transformation/transformers/es6-for-of.js index <HASH>..<HASH> 100644 --- a/lib/6to5/transformation/transformers/es6-for-of.js +++ b/lib/6to5/transformation/transformers/es6-for-of.js @@ -30,6 +30,9 @@ exports.ForOfStatement = function (node, parent, scope, context, file) { // push the rest of the original loop body onto our new body block.body = block.body.concat(node.body.body); + // todo: find out why this is necessary? #538 + loop._scopeInfo = node._scopeInfo; + return loop; };
fix forOf scope declarations not propagating to new for loop - fixes #<I>
babel_babel
train
20ba641d0a04cada2863e7a6961a46bded48452d
diff --git a/eZ/Publish/Core/SignalSlot/Slot/LegacySlotTiein.php b/eZ/Publish/Core/SignalSlot/Slot/LegacySlotTiein.php index <HASH>..<HASH> 100644 --- a/eZ/Publish/Core/SignalSlot/Slot/LegacySlotTiein.php +++ b/eZ/Publish/Core/SignalSlot/Slot/LegacySlotTiein.php @@ -1,6 +1,6 @@ <?php /** - * File containing the SignalDispatcher class + * File containing the LegacySlotTiein class * * @copyright Copyright (C) 1999-2012 eZ Systems AS. All rights reserved. * @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 @@ -13,7 +13,7 @@ use eZ\Publish\Core\SignalSlot\Slot; use Closure; /** - * A generic slot made to be able to be catch all on content & Location related signals. + * A generic slot made to be able to be catch all on content & Location related signals and pass it on to legacy. */ class LegacySlotTiein extends Slot { diff --git a/eZ/Publish/Core/SignalSlot/SlotFactory/GeneralSlotFactory.php b/eZ/Publish/Core/SignalSlot/SlotFactory/GeneralSlotFactory.php index <HASH>..<HASH> 100644 --- a/eZ/Publish/Core/SignalSlot/SlotFactory/GeneralSlotFactory.php +++ b/eZ/Publish/Core/SignalSlot/SlotFactory/GeneralSlotFactory.php @@ -1,6 +1,6 @@ <?php /** - * File containing the NullSlotFactory class + * File containing the GeneralSlotFactory class * * @copyright Copyright (C) 1999-2012 eZ Systems AS. All rights reserved. * @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 @@ -10,6 +10,9 @@ namespace eZ\Publish\Core\SignalSlot\SlotFactory; use eZ\Publish\Core\SignalSlot\SlotFactory; +/** + * Slot factory that is able to lookup slots based on identifier. + */ class GeneralSlotFactory extends SlotFactory { /**
Add Documentation on classes for Legacy Slot impl
ezsystems_ezpublish-kernel
train
d3671a9cd0ff4bd75ea63e741b73f5b168dd93a0
diff --git a/src/Illuminate/View/Factory.php b/src/Illuminate/View/Factory.php index <HASH>..<HASH> 100755 --- a/src/Illuminate/View/Factory.php +++ b/src/Illuminate/View/Factory.php @@ -516,7 +516,7 @@ class Factory implements FactoryContract */ public function callComposer(ViewContract $view) { - $this->events->fire('composing: '.$view->getName(), [$view]); + $this->events->fire('composing: '.$view->name(), [$view]); } /** @@ -527,7 +527,7 @@ class Factory implements FactoryContract */ public function callCreator(ViewContract $view) { - $this->events->fire('creating: '.$view->getName(), [$view]); + $this->events->fire('creating: '.$view->name(), [$view]); } /** diff --git a/tests/View/ViewFactoryTest.php b/tests/View/ViewFactoryTest.php index <HASH>..<HASH> 100755 --- a/tests/View/ViewFactoryTest.php +++ b/tests/View/ViewFactoryTest.php @@ -209,7 +209,7 @@ class ViewFactoryTest extends PHPUnit_Framework_TestCase { $factory = $this->getFactory(); $view = m::mock('Illuminate\View\View'); - $view->shouldReceive('getName')->once()->andReturn('name'); + $view->shouldReceive('name')->once()->andReturn('name'); $factory->getDispatcher()->shouldReceive('fire')->once()->with('composing: name', [$view]); $factory->callComposer($view);
Prefers View contract name() method (#<I>)
laravel_framework
train
4fb27e09be08a298c9d0c237de074e57816232ea
diff --git a/src/GitHub_Updater/Base.php b/src/GitHub_Updater/Base.php index <HASH>..<HASH> 100644 --- a/src/GitHub_Updater/Base.php +++ b/src/GitHub_Updater/Base.php @@ -1311,12 +1311,8 @@ class Base { $type = 'plugin'; // For extended naming - foreach ( (array) $this->config as $repo ) { - if ( $slug === $repo->repo || $slug === $repo->extended_repo ) { - $slug = $repo->repo; - break; - } - } + $repo = $this->get_repo_slugs( $slug ); + $slug = $repo['repo']; } if ( isset( $_GET['theme'] ) && 'upgrade-theme' === $_GET['action'] ) {
use existing code for extended naming check
afragen_github-updater
train
37263d1eb807d1521efe0b33a009d9c6412d5f3b
diff --git a/lib/extr/transaction.rb b/lib/extr/transaction.rb index <HASH>..<HASH> 100644 --- a/lib/extr/transaction.rb +++ b/lib/extr/transaction.rb @@ -66,29 +66,36 @@ module Extr begin controller = Config.get_controller_path(self.action) + token = get_token(controller) unless controller.constantize.mimes_for_respond_to.key?(Mime::EXT.symbol) self.request.format= :json end - my_env = self.request.env - my_env["REQUEST_URI"] = request.host_with_port+"/#{controller.constantize.controller_path}" - my_env["PATH_INFO"] = controller.constantize.controller_path - my_env.delete("action_dispatch.request.request_parameters") - my_env.delete("action_dispatch.request.parameters") - my_env.delete("action_dispatch.path_parameters") - - - #params = HashWithIndifferentAccess.new - #params[:method] = self.method - #params[:tid] = self.tid - #params[:data] = self.data - #params[controller.constantize.request_forgery_protection_token] = get_token(controller) - #self.request.env["action_dispatch.request.request_parameters"] = nil - #self.request.env["action_dispatch.request.parameters"] = params + #my_env = self.request.env + + #my_env["REQUEST_URI"] = request.host_with_port+"/#{controller.constantize.controller_path}" + #my_env["PATH_INFO"] = "/#{controller.constantize.controller_path}" + #my_env.delete("action_dispatch.request.request_parameters") + #my_env.delete("action_dispatch.request.parameters") + #my_env.delete("action_dispatch.path_parameters") + + + + params = HashWithIndifferentAccess.new + params[:method] = self.method + params[:tid] = self.tid + params[:data] = self.data + params[controller.constantize.request_forgery_protection_token] = token + self.request.env["action_dispatch.request.parameters"] = params + self.request.env["action_dispatch.request.request_parameters"] = nil + + + #my_env["action_dispatch.request.parameters"] = params #debugger - body = controller.constantize.action(self.method).call(my_env).to_a.last.body - #body = controller.constantize.action(self.method).call(self.request.env).to_a.last.body + #body = controller.constantize.action(self.method).call(my_env).to_a.last.body + + body = controller.constantize.action(self.method).call(self.request.env).to_a.last.body ext['result'] = body.empty? ? "" : ActiveSupport::JSON.decode(body) rescue => e diff --git a/test/dummy/app/controllers/application_controller.rb b/test/dummy/app/controllers/application_controller.rb index <HASH>..<HASH> 100644 --- a/test/dummy/app/controllers/application_controller.rb +++ b/test/dummy/app/controllers/application_controller.rb @@ -2,7 +2,7 @@ class ApplicationController < ActionController::Base protect_from_forgery - #include Extr::DirectController + include Extr::DirectController #extdirect :methods => {:makeone => 1} diff --git a/test/dummy/app/controllers/projects_controller.rb b/test/dummy/app/controllers/projects_controller.rb index <HASH>..<HASH> 100644 --- a/test/dummy/app/controllers/projects_controller.rb +++ b/test/dummy/app/controllers/projects_controller.rb @@ -3,20 +3,10 @@ class ProjectsController < ApplicationController # GET /projects.json - protect_from_forgery - - include Extr::DirectController - - - respond_to :json#, :ext - - #respond_to :ext - extdirect :name => "Mike", :methods => {:makeone => 1, :getChildProject => 1, :getChildNodes => 0} def getChildProject - #p request.headers #controllers with respond_to #p direct_controllers = ActionController::Base.descendants.select{|klass| klass.mimes_for_respond_to.key?(:ext)} @@ -26,8 +16,8 @@ class ProjectsController < ApplicationController #instance_methods(false) #p self.mimes_for_respond_to.key?(:ext) @project = {:name => "Project #{Random.rand(11)}"} - #render :json => @project - respond_with @project, :location => nil + render :json => @project + #respond_with @project, :location => nil end
working but only with location nil
skeller1_extr
train
d51f68a2c268494639a259f2e363073f6d9bdae7
diff --git a/worker/peergrouper/worker_test.go b/worker/peergrouper/worker_test.go index <HASH>..<HASH> 100644 --- a/worker/peergrouper/worker_test.go +++ b/worker/peergrouper/worker_test.go @@ -7,7 +7,6 @@ import ( "errors" "fmt" "net" - "reflect" "sort" "strconv" "sync" @@ -483,9 +482,7 @@ func (s *workerSuite) TestControllersArePublished(c *gc.C) { DoTestForIPv4AndIPv6(c, s, func(ipVersion TestIPVersion) { publishCh := make(chan []network.SpaceHostPorts) publish := func(apiServers []network.SpaceHostPorts) error { - // Publish a copy, so we don't get a race when sorting - // for comparisons later. - publishCh <- append([]network.SpaceHostPorts{}, apiServers...) + publishCh <- apiServers return nil } @@ -501,36 +498,24 @@ func (s *workerSuite) TestControllersArePublished(c *gc.C) { c.Fatalf("timed out waiting for publish") } - // Change one of the server API addresses. + // If a config change wakes up the loop *after* the controller topology + // is published, then we will get another call to setAPIHostPorts. + select { + case <-publishCh: + case <-time.After(coretesting.ShortWait): + } + + // Change one of the server API addresses and check that it is + // published. newMachine10Addresses := network.NewSpaceAddresses(ipVersion.extraHost) st.controller("10").setAddresses(newMachine10Addresses...) - - // Set up our sorted expectation for the new server addresses. - expected := ExpectedAPIHostPorts(3, ipVersion) - expected[0] = network.SpaceAddressesWithPort(newMachine10Addresses, apiPort) - sort.Sort(hostPortSliceByHostPort(expected)) - - // If a config change wakes up the loop *after* the controller topology - // is published, then we will get another call to setAPIHostPorts with - // the original values. - // This can take an indeterminate amount of time, so we just loop until - // we see the expected addresses, or hit the timeout. - timeout := time.After(coretesting.LongWait) - for { - select { - case servers := <-publishCh: - sort.Sort(hostPortSliceByHostPort(servers)) - if reflect.DeepEqual(servers, expected) { - // This doubles as an assertion that no incorrect values - // are published later, as the worker will not die cleanly - // if such a publish via the channel is pending. - workertest.CleanKill(c, w) - return - } - case <-timeout: - workertest.DirtyKill(c, w) - c.Fatalf("timed out waiting for correct addresses to be published") - } + select { + case servers := <-publishCh: + expected := ExpectedAPIHostPorts(3, ipVersion) + expected[0] = network.SpaceAddressesWithPort(newMachine10Addresses, apiPort) + AssertAPIHostPorts(c, servers, expected) + case <-time.After(coretesting.LongWait): + c.Fatalf("timed out waiting for publish") } }) }
Restores original test composition for TestControllersArePublished. That change made was in response to an issue with type comparisons that was later identified and fixed by @thumper. It introduced a possible failure mode where the double-publish of controller topology could include the changed controller address in the *first* broadcast, which would block the worker shutdown.
juju_juju
train
5847b93c94587ae994df78573a3dcf275b6315de
diff --git a/drivers/shared/executor/legacy_executor_wrapper.go b/drivers/shared/executor/legacy_executor_wrapper.go index <HASH>..<HASH> 100644 --- a/drivers/shared/executor/legacy_executor_wrapper.go +++ b/drivers/shared/executor/legacy_executor_wrapper.go @@ -36,6 +36,9 @@ type legacyExecutorWrapper struct { logger hclog.Logger } +// validate that legacyExecutorWrapper is an executor +var _ Executor = (*legacyExecutorWrapper)(nil) + func (l *legacyExecutorWrapper) Launch(launchCmd *ExecCommand) (*ProcessState, error) { return nil, fmt.Errorf("operation not supported for legacy exec wrapper") } @@ -133,6 +136,11 @@ func (l *legacyExecutorWrapper) Exec(deadline time.Time, cmd string, args []stri return l.client.Exec(deadline, cmd, args) } +func (l *legacyExecutorWrapper) ExecStreaming(ctx context.Context, cmd []string, tty bool, + stream drivers.ExecTaskStream) error { + return fmt.Errorf("operation not supported for legacy exec wrapper") +} + type pre09ExecutorRPC struct { client *rpc.Client logger hclog.Logger
Legacy executors are executors after all This fixes a bug where pre-<I> executors fail to recover after an upgrade. The bug is that legacyExecutorWrappers didn't get updated with ExecStreaming function, and thus failed to implement the Executor function. Sadly, this meant that all recovery attempts fail, as the runtime check in <URL>
hashicorp_nomad
train
8084bc7bae84ad63001637f566e0f224a14dd1ed
diff --git a/java/src/com/google/template/soy/data/SoyData.java b/java/src/com/google/template/soy/data/SoyData.java index <HASH>..<HASH> 100644 --- a/java/src/com/google/template/soy/data/SoyData.java +++ b/java/src/com/google/template/soy/data/SoyData.java @@ -16,11 +16,6 @@ package com.google.template.soy.data; -import com.google.template.soy.data.restricted.BooleanData; -import com.google.template.soy.data.restricted.FloatData; -import com.google.template.soy.data.restricted.IntegerData; -import com.google.template.soy.data.restricted.NullData; -import com.google.template.soy.data.restricted.StringData; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; @@ -46,33 +41,14 @@ public abstract class SoyData extends SoyAbstractValue { */ @Deprecated public static SoyData createFromExistingData(Object obj) { - - // Important: This is frozen for backwards compatibility, For future changes (pun not intended), - // use SoyValueConverter, which works with the new interfaces SoyValue and SoyValueProvider. - - if (obj == null) { - return NullData.INSTANCE; - } else if (obj instanceof SoyData) { + if (obj instanceof SoyData) { return (SoyData) obj; - } else if (obj instanceof String) { - return StringData.forValue((String) obj); - } else if (obj instanceof Boolean) { - return BooleanData.forValue((Boolean) obj); - } else if (obj instanceof Integer) { - return IntegerData.forValue((Integer) obj); - } else if (obj instanceof Long) { - return IntegerData.forValue((Long) obj); } else if (obj instanceof Map<?, ?>) { @SuppressWarnings("unchecked") Map<String, ?> objCast = (Map<String, ?>) obj; return new SoyMapData(objCast); } else if (obj instanceof Iterable<?>) { return new SoyListData((Iterable<?>) obj); - } else if (obj instanceof Double) { - return FloatData.forValue((Double) obj); - } else if (obj instanceof Float) { - // Automatically convert float to double. - return FloatData.forValue((Float) obj); } else if (obj instanceof Future<?>) { // Note: In the old SoyData, we don't support late-resolution of Futures. We immediately // resolve the Future object here. For late-resolution, use SoyValueConverter.convert(). @@ -86,6 +62,10 @@ public abstract class SoyData extends SoyAbstractValue { "Encountered ExecutionException when resolving Future object.", e); } } else { + SoyValue soyValue = SoyValueConverter.INSTANCE.convert(obj).resolve(); + if (soyValue instanceof SoyData) { + return (SoyData) soyValue; + } throw new SoyDataException( "Attempting to convert unrecognized object to Soy data (object type " + obj.getClass().getName()
Support all values supported by SoyValueConverter in SoyData. The code in the wild is full of new SoyMapData(...) and similar. I want to pass SafeHtml and similar here without converting all the code to something else. GITHUB_BREAKING_CHANGES=None. ------------- Created by MOE: <URL>
google_closure-templates
train
8aecabed53825ab8a2c4e611339fd478ac89203f
diff --git a/spotify.go b/spotify.go index <HASH>..<HASH> 100644 --- a/spotify.go +++ b/spotify.go @@ -13,6 +13,8 @@ import ( "net/http" "strconv" "time" + + "golang.org/x/oauth2" ) // Version is the version of this library. @@ -307,3 +309,16 @@ func (c *Client) NewReleases(ctx context.Context, opts ...RequestOption) (albums return &result, nil } + +// Token gets the client's current token. +func (c *Client) Token() (*oauth2.Token, error) { + transport, ok := c.http.Transport.(*oauth2.Transport) + if !ok { + return nil, errors.New("spotify: client not backed by oauth2 transport") + } + t, err := transport.Source.Token() + if err != nil { + return nil, err + } + return t, nil +}
Add method to get the current OAuth token from client
zmb3_spotify
train
b1a3eddbdeb20a1b711994c66c8a0164be9068d5
diff --git a/packages/ember-metal/lib/computed.js b/packages/ember-metal/lib/computed.js index <HASH>..<HASH> 100644 --- a/packages/ember-metal/lib/computed.js +++ b/packages/ember-metal/lib/computed.js @@ -222,11 +222,11 @@ ComputedPropertyPrototype.cacheable = function(aFlag) { mode the computed property will not automatically cache the return value. ```javascript - MyApp.outsideService = Ember.Object.create({ + MyApp.outsideService = Ember.Object.extend({ value: function() { return OutsideService.getValue(); }.property().volatile() - }); + }).create(); ``` @method volatile @@ -242,12 +242,14 @@ ComputedPropertyPrototype.volatile = function() { mode the computed property will throw an error when set. ```javascript - MyApp.person = Ember.Object.create({ + MyApp.Person = Ember.Object.extend({ guid: function() { return 'guid-guid-guid'; }.property().readOnly() }); + MyApp.person = MyApp.Person.create(); + MyApp.person.set('guid', 'new-guid'); // will throw an exception ``` @@ -265,7 +267,7 @@ ComputedPropertyPrototype.readOnly = function(readOnly) { arguments containing key paths that this computed property depends on. ```javascript - MyApp.president = Ember.Object.create({ + MyApp.President = Ember.Object.extend({ fullName: Ember.computed(function() { return this.get('firstName') + ' ' + this.get('lastName'); @@ -273,6 +275,12 @@ ComputedPropertyPrototype.readOnly = function(readOnly) { // and lastName }).property('firstName', 'lastName') }); + + MyApp.president = MyApp.President.create({ + firstName: 'Barack', + lastName: 'Obama', + }); + MyApp.president.get('fullName'); // Barack Obama ``` @method property
[DOC beta] Fix Ember.computed docs
emberjs_ember.js
train
0bfec67f33841b136aa0617fac195a3d0493b601
diff --git a/protobuf3/compiler/plugin_api.py b/protobuf3/compiler/plugin_api.py index <HASH>..<HASH> 100644 --- a/protobuf3/compiler/plugin_api.py +++ b/protobuf3/compiler/plugin_api.py @@ -193,3 +193,14 @@ class CodeGeneratorRequest(Message): file_to_generate = StringField(field_number=1, repeated=True) parameter = StringField(field_number=2, optional=True) proto_file = MessageField(field_number=15, repeated=True, message_cls=FileDescriptorProto) + + +class CodeGeneratorResponse(Message): + error = StringField(field_number=1, optional=True) + + class File(Message): + name = StringField(field_number=1, optional=True) + insertion_point = StringField(field_number=2, optional=True) + content = StringField(field_number=15, optional=True) + + file = MessageField(field_number=15, repeated=True, message_cls=File)
Added CodeGeneratorResponse to plugin_api
Pr0Ger_protobuf3
train
ff3cfb1acbe7038b990ccf75703b66bc9e64653e
diff --git a/daftlistings/daft.py b/daftlistings/daft.py index <HASH>..<HASH> 100644 --- a/daftlistings/daft.py +++ b/daftlistings/daft.py @@ -93,7 +93,7 @@ class Daft: def set_min_lease(self, min_lease: int): # Measured in months - self._set_range_from("leaseLength".str(min_lease)) + self._set_range_from("leaseLength", str(min_lease)) def set_max_lease(self, max_lease: int): # Measured in months
(#<I>) . should be ,
AnthonyBloomer_daftlistings
train
585d474bd387dde8e38c65bdc1e358724f566212
diff --git a/provision/docker/commands.go b/provision/docker/commands.go index <HASH>..<HASH> 100644 --- a/provision/docker/commands.go +++ b/provision/docker/commands.go @@ -25,11 +25,7 @@ func deployCmds(app provision.App, version string) ([]string, error) { return nil, err } appRepo := repository.ReadOnlyURL(app.GetName()) - user, err := config.GetString("docker:ssh:user") - if err != nil { - return nil, err - } - cmds := []string{"sudo", "-u", user, deployCmd, appRepo, version} + cmds := []string{deployCmd, appRepo, version} return cmds, nil } diff --git a/provision/docker/commands_test.go b/provision/docker/commands_test.go index <HASH>..<HASH> 100644 --- a/provision/docker/commands_test.go +++ b/provision/docker/commands_test.go @@ -21,9 +21,7 @@ func (s *S) TestDeployCmds(c *gocheck.C) { c.Assert(err, gocheck.IsNil) version := "version" appRepo := repository.ReadOnlyURL(app.GetName()) - user, err := config.GetString("docker:ssh:user") - c.Assert(err, gocheck.IsNil) - expected := []string{"sudo", "-u", user, deployCmd, appRepo, version} + expected := []string{deployCmd, appRepo, version} cmds, err := deployCmds(app, version) c.Assert(err, gocheck.IsNil) c.Assert(cmds, gocheck.DeepEquals, expected)
provision/docker: remove sudo -u from deployCmd Somehow related to #<I>.
tsuru_tsuru
train
c9bb8e41f60227dbd2ab16ecb8cf69efdaa41cd3
diff --git a/lenstronomy/LensModel/lens_model_extensions.py b/lenstronomy/LensModel/lens_model_extensions.py index <HASH>..<HASH> 100644 --- a/lenstronomy/LensModel/lens_model_extensions.py +++ b/lenstronomy/LensModel/lens_model_extensions.py @@ -303,6 +303,32 @@ class LensModelExtensions(object): dec_crit_list += dec_crit # list addition return np.array(ra_crit_list), np.array(dec_crit_list) + def caustic_area(self, kwargs_lens, kwargs_caustic_num, index_vertices=0): + """ + computes the area within a caustic curve + + :param kwargs_lens: lens model keyword argument list + :param kwargs_caustic_num: keyword arguments for the numerical calculation of the caustics, as input of + self.critical_curve_caustics() + :param index_vertices: integer, index of connected vortex from the output of self.critical_curve_caustics() + of disconnected curves. + :return: area within the caustic curve selected + """ + + ra_crit_list, dec_crit_list, ra_caustic_list, dec_caustic_list = self.critical_curve_caustics(kwargs_lens, + **kwargs_caustic_num) + + # select specific vortex + ra_caustic_inner = ra_caustic_list[index_vertices] + dec_caustic_inner = dec_caustic_list[index_vertices] + + # merge RA DEC to vertices + C = np.dstack([ra_caustic_inner, dec_caustic_inner])[0] + + # compute area + a = util.area(C) + return a + def _tiling_crit(self, edge1, edge2, edge_90, max_order, kwargs_lens): """ tiles a rectangular triangle and compares the signs of the magnification diff --git a/lenstronomy/Util/util.py b/lenstronomy/Util/util.py index <HASH>..<HASH> 100644 --- a/lenstronomy/Util/util.py +++ b/lenstronomy/Util/util.py @@ -648,4 +648,22 @@ def convert_bool_list(n, k=None): raise ValueError("k as set by %s is not convertable in a bool string!" % k) else: raise ValueError('input list k as %s not compatible' % k) - return bool_list \ No newline at end of file + return bool_list + + +def area(vs): + """ + Use Green's theorem to compute the area enclosed by the given contour. + + param vs: 2d array of vertices of a contour line + return: area within contour line + """ + a = 0 + x0, y0 = vs[0] + for [x1, y1] in vs[1:]: + dx = x1 - x0 + dy = y1 - y0 + a += 0.5 * (y0 * dx - x0 * dy) + x0 = x1 + y0 = y1 + return abs(a) diff --git a/test/test_LensModel/test_lens_model_extensions.py b/test/test_LensModel/test_lens_model_extensions.py index <HASH>..<HASH> 100644 --- a/test/test_LensModel/test_lens_model_extensions.py +++ b/test/test_LensModel/test_lens_model_extensions.py @@ -239,6 +239,17 @@ class TestLensModelExtensions(object): tang_stretch_ave = lensModelExtensions.tangential_average(x=1.1, y=0, kwargs_lens=[{'theta_E': 1, 'center_x': 0, 'center_y': 0}], dr=1, smoothing=None, num_average=9) npt.assert_almost_equal(tang_stretch_ave, -2.525501464097973, decimal=6) + def test_caustic_area(self): + lens_model_list = ['SIE'] + lensModel = LensModel(lens_model_list=lens_model_list) + lensModelExtensions = LensModelExtensions(lensModel=lensModel) + kwargs_lens = [{'theta_E': 1, 'e1': 0.2, 'e2': 0, 'center_x': 0, 'center_y': 0}] + kwargs_caustic_num = {'compute_window': 3, 'grid_scale': 0.005, 'center_x': 0, 'center_y': 0} + + area = lensModelExtensions.caustic_area(kwargs_lens=kwargs_lens, kwargs_caustic_num=kwargs_caustic_num, + index_vertices=0) + npt.assert_almost_equal(area, 0.08445866728739478, decimal=3) + if __name__ == '__main__': pytest.main("-k TestLensModel") diff --git a/test/test_Util/test_util.py b/test/test_Util/test_util.py index <HASH>..<HASH> 100644 --- a/test/test_Util/test_util.py +++ b/test/test_Util/test_util.py @@ -385,6 +385,14 @@ def test_convert_bool_list(): assert bool_list[0] is False +def test_area(): + r = 1 + x_, y_ = util.points_on_circle(radius=r, connect_ends=True, num_points=1000) + vs = np.dstack([x_, y_])[0] + a = util.area(vs) + npt.assert_almost_equal(a, np.pi * r**2, decimal=3) + + class TestRaise(unittest.TestCase): def test_raise(self):
minor change in emcee option for number of walkers
sibirrer_lenstronomy
train
4e27661f05b4640232e20cd95cde9b115d967c17
diff --git a/backend/pfamserver/services/uniprot_service.py b/backend/pfamserver/services/uniprot_service.py index <HASH>..<HASH> 100644 --- a/backend/pfamserver/services/uniprot_service.py +++ b/backend/pfamserver/services/uniprot_service.py @@ -20,24 +20,33 @@ def handle_no_result_found(e): raise UniprotServiceError("Uniprot doesn" "t exist.") -def query_uniprot(uniprot: str): - uniprot = uniprot.upper() +def query_uniprot_and_pfams_included(query_string: str): + uniprot = query_string.upper() query = db.session.query(Uniprot) query = query.join(Uniprot.pfams) + query = uniprot_query_filter(uniprot, query) + return query + + +def uniprot_query_filter(uniprot, query): query = query.filter( or_(Uniprot.uniprot_id == uniprot, Uniprot.uniprot_acc == uniprot) ) + return query @merry._try -def get_uniprot(uniprot: str): - return query_uniprot(uniprot).one() +def get_uniprot(query_string: str): + uniprot = query_string.upper() + query = db.session.query(Uniprot) + query = uniprot_query_filter(uniprot, query) + return query.one() @merry._try def get_pfams_from_uniprot(uniprot): - query = query_uniprot(uniprot) + query = query_uniprot_and_pfams_included(uniprot) query = query.filter(UniprotRegFull.uniprot_acc == Uniprot.uniprot_acc) query = query.filter(PfamA.pfamA_acc == UniprotRegFull.pfamA_acc) query = query.order_by(UniprotRegFull.seq_start)
[#<I>] Optimize uniprots description to be a bit faster.
ecolell_pfamserver
train
87be05ba17a5b24dc3294a89cdf569e02e9414d6
diff --git a/src/saml2/s2repoze/plugins/sp.py b/src/saml2/s2repoze/plugins/sp.py index <HASH>..<HASH> 100644 --- a/src/saml2/s2repoze/plugins/sp.py +++ b/src/saml2/s2repoze/plugins/sp.py @@ -102,7 +102,7 @@ class SAML2Plugin(object): self.discosrv = discovery self.idp_query_param = idp_query_param self.logout_endpoints = [ - parse.urlparse(ep)[2] for ep in config.endpoint("single_logout_service") + parse.urlparse(ep).path for ep in config.endpoint("single_logout_service") ] try: self.metadata = self.conf.metadata
Use .path instead of an indexed member
IdentityPython_pysaml2
train
e33b5471f1bda43e1f91b95132feb60eab39cde5
diff --git a/seravo-plugin.php b/seravo-plugin.php index <HASH>..<HASH> 100644 --- a/seravo-plugin.php +++ b/seravo-plugin.php @@ -1,7 +1,7 @@ <?php // phpcs:disable WordPress.Files.FileName.InvalidClassFileName /** * Plugin Name: Seravo Plugin - * Version: 1.9.17 + * Version: 1.9.18 * Plugin URI: https://github.com/Seravo/seravo-plugin * Description: Enhances WordPress with Seravo.com specific features and integrations. * Author: Seravo Oy
Bump to version <I>
Seravo_seravo-plugin
train
70e99464f00eb868a63110a9598110386fcd66a7
diff --git a/ga4gh/cli.py b/ga4gh/cli.py index <HASH>..<HASH> 100644 --- a/ga4gh/cli.py +++ b/ga4gh/cli.py @@ -795,16 +795,15 @@ class SearchExpressionLevelsRunner(AbstractSearchRunner): def __init__(self, args): super(SearchExpressionLevelsRunner, self).__init__(args) self._rnaQuantificationId = args.rnaQuantificationId - if len(args.feature_ids) > 0: - self._feature_ids = args.feature_ids.split(",") - else: - self._feature_ids = [] + self._feature_ids = [] + if len(args.featureIds) > 0: + self._feature_ids = args.featureIds.split(",") self.threshold = args.threshold def run(self): iterator = self._client.search_expression_levels( - rnaQuantificationId=self._rnaQuantificationId, - featureIds=self._featureIds, + rna_quantification_id=self._rnaQuantificationId, + feature_ids=self._feature_ids, threshold=self.threshold) self._output(iterator) @@ -1580,7 +1579,7 @@ def addExpressionLevelsSearchParser(subparsers): addPageSizeArgument(parser) addFeatureIdsArgument(parser) parser.add_argument( - "--rnaQuantificationId", default=None, + "--rnaQuantificationId", default='', help="The RNA Quantification Id to search over") parser.add_argument( "--threshold", default=0.0, type=float, diff --git a/tests/end_to_end/test_client_json.py b/tests/end_to_end/test_client_json.py index <HASH>..<HASH> 100644 --- a/tests/end_to_end/test_client_json.py +++ b/tests/end_to_end/test_client_json.py @@ -35,6 +35,8 @@ class TestClientOutput(unittest.TestCase): dataRepository.open(datarepo.MODE_READ) self._backend = backend.Backend(dataRepository) self._client = client.LocalClient(self._backend) + # TODO probably could use a cache of objects, so we don't + # need to keep re-fetching them def captureCliOutput(self, command, arguments, outputFormat): clientCommand = "{} {} {} -O {}".format( @@ -345,14 +347,73 @@ class TestClientJson(TestClientOutput): # def testSearchFeatureSets(self): # TODO - # def testSearchExpressionLevels(self): # TODO - - # def testSearchRnaQuantifications(self): # TODO - - # def testSearchRnaQuantifications(self): # TODO - - # def testGetExpressionLevels(self): # TODO + def testSearchExpressionLevels(self): + for dataset in self._client.search_datasets(): + for rnaQuantificationSet in \ + self._client.search_rna_quantification_sets(dataset.id): + for rnaQuantification in \ + self._client.search_rna_quantifications( + rnaQuantificationSet.id): + iterator = self._client.search_expression_levels( + rnaQuantification.id) + cliString = ( + "expressionlevels-search " + "--rnaQuantificationId {}".format( + rnaQuantification.id)) + self.verifyParsedOutputsEqual(iterator, cliString) + + def testSearchRnaQuantifications(self): + for dataset in self._client.search_datasets(): + for rnaQuantificationSet in \ + self._client.search_rna_quantification_sets(dataset.id): + iterator = self._client.search_rna_quantifications( + rnaQuantificationSet.id) + cliString = ( + "rnaquantifications-search " + "--rnaQuantificationSetId {}".format( + rnaQuantificationSet.id)) + self.verifyParsedOutputsEqual(iterator, cliString) + + def testSearchRnaQuantificationSets(self): + for dataset in self._client.search_datasets(): + iterator = self._client.search_rna_quantification_sets(dataset.id) + cliString = ( + "rnaquantificationsets-search --datasetId {}".format( + dataset.id)) + self.verifyParsedOutputsEqual(iterator, cliString) - # def testGetRnaQuantifications(self): # TODO + def testGetExpressionLevel(self): + for dataset in self._client.search_datasets(): + for rnaQuantificationSet in \ + self._client.search_rna_quantification_sets(dataset.id): + for rnaQuantification in \ + self._client.search_rna_quantifications( + rnaQuantificationSet.id): + for expressionLevel in \ + self._client.search_expression_levels( + rnaQuantification.id): + self.verifyParsedOutputsEqual( + [expressionLevel], + "expressionlevels-get", + expressionLevel.id) + + def testGetRnaQuantification(self): + for dataset in self._client.search_datasets(): + for rnaQuantificationSet in \ + self._client.search_rna_quantification_sets(dataset.id): + for rnaQuantification in \ + self._client.search_rna_quantifications( + rnaQuantificationSet.id): + self.verifyParsedOutputsEqual( + [rnaQuantification], + "rnaquantifications-get", + rnaQuantification.id) - # def testGetRnaQuantificationSets(self): # TODO + def testGetRnaQuantificationSet(self): + for dataset in self._client.search_datasets(): + for rnaQuantificationSet in \ + self._client.search_rna_quantification_sets(dataset.id): + self.verifyParsedOutputsEqual( + [rnaQuantificationSet], + "rnaquantificationsets-get", + rnaQuantificationSet.id)
End to end json tests for RNA
ga4gh_ga4gh-server
train
6d0e98ababbfb164fca1c2bc26d403b895b10d0e
diff --git a/xchange-core/src/main/java/org/knowm/xchange/utils/jackson/ISO8601DateDeserializer.java b/xchange-core/src/main/java/org/knowm/xchange/utils/jackson/ISO8601DateDeserializer.java index <HASH>..<HASH> 100644 --- a/xchange-core/src/main/java/org/knowm/xchange/utils/jackson/ISO8601DateDeserializer.java +++ b/xchange-core/src/main/java/org/knowm/xchange/utils/jackson/ISO8601DateDeserializer.java @@ -18,7 +18,7 @@ import com.fasterxml.jackson.databind.JsonDeserializer; public class ISO8601DateDeserializer extends JsonDeserializer<Date> { @Override - public Date deserialize(JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { + public Date deserialize(JsonParser jp, final DeserializationContext ctxt) throws IOException { return DateUtils.fromISO8601DateString(jp.getValueAsString()); }
[core] delete unnecessary exception from throws list
knowm_XChange
train
5c35214102fe8838824b576d73249e489362d7ee
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index <HASH>..<HASH> 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -6,6 +6,7 @@ * Fix bug validating models with a `defautl` attribute _(Issue #124)_ * Fix bug validating models without properties _(Issue #122)_ * swagger-metadata now converts paramters to their appropriate type _(Issue #119)_ +* swagger-router now handles void responses for mock mode _(Issue #112)_ * swagger-router now wraps controller calls in try/catch block and sends errors downstream via `next` _(Issue #123)_ * swagger-security now sends authentication/authorization errors downstream via `next` _(Issue #117)_ diff --git a/middleware/helpers.js b/middleware/helpers.js index <HASH>..<HASH> 100644 --- a/middleware/helpers.js +++ b/middleware/helpers.js @@ -199,7 +199,7 @@ module.exports.getHandlerName = function getHandlerName (version, req) { }; var getMockValue = function getMockValue (version, schema) { - var type = schema.type; + var type = _.isPlainObject(schema) ? schema.type : schema; var value; if (!type) { @@ -334,15 +334,19 @@ var mockResponse = function mockResponse (version, req, res, next, handlerName) apiDOrSO = req.swagger.swaggerObject; if (method === 'post' && operation.responses['201']) { - responseType = operation.responses['201'].schema; + responseType = operation.responses['201']; + + res.statusCode = 201; + } else if (method === 'delete' && operation.responses['204']) { + responseType = operation.responses['204']; + + res.statusCode = 204; } else if (operation.responses['200']) { responseType = operation.responses['200']; } else if (operation.responses['default']) { responseType = operation.responses['default']; - } else if (operation.schema) { - responseType = operation.schema.type || 'object'; } else { - responseType = operation.type; + responseType = 'void'; } break; @@ -361,7 +365,9 @@ var mockResponse = function mockResponse (version, req, res, next, handlerName) } }); } else { - return sendResponse(undefined, JSON.stringify(getMockValue(version, responseType.schema))); + return sendResponse(undefined, JSON.stringify(getMockValue(version, responseType.schema ? + responseType.schema : + responseType))); } } else { return sendResponse(undefined, getMockValue(version, responseType)); diff --git a/test/1.2/test-middleware-swagger-router.js b/test/1.2/test-middleware-swagger-router.js index <HASH>..<HASH> 100644 --- a/test/1.2/test-middleware-swagger-router.js +++ b/test/1.2/test-middleware-swagger-router.js @@ -251,5 +251,18 @@ describe('Swagger Router Middleware v1.2', function () { .end(helpers.expectContent('Cannot read property \'fake\' of undefined', done)); }); }); + + it('mock mode should support void responses (Issue 112)', function (done) { + helpers.createServer([rlJson, [petJson, storeJson, userJson]], { + swaggerRouterOptions: { + useStubs: true + } + }, function (app) { + request(app) + .delete('/api/pet/1') + .expect(200) + .end(helpers.expectContent('', done)); + }); + }); }); }); diff --git a/test/2.0/test-middleware-swagger-router.js b/test/2.0/test-middleware-swagger-router.js index <HASH>..<HASH> 100644 --- a/test/2.0/test-middleware-swagger-router.js +++ b/test/2.0/test-middleware-swagger-router.js @@ -250,7 +250,6 @@ describe('Swagger Router Middleware v2.0', function () { describe('issues', function () { it('should handle uncaught exceptions (Issue 123)', function (done) { - helpers.createServer([petStoreJson], { swaggerRouterOptions: { controllers: { @@ -271,5 +270,18 @@ describe('Swagger Router Middleware v2.0', function () { .end(helpers.expectContent('Cannot read property \'fake\' of undefined', done)); }); }); + + it('mock mode should support void responses (Issue 112)', function (done) { + helpers.createServer([petStoreJson], { + swaggerRouterOptions: { + useStubs: true + } + }, function (app) { + request(app) + .delete('/api/pets/1') + .expect(204) + .end(helpers.expectContent('', done)); + }); + }); }); });
Mock mode supports void responses Fixes #<I>
apigee-127_swagger-tools
train
ab244176a9152082ef69ae1a9c8c021570883328
diff --git a/lib/sass/selector/sequence.rb b/lib/sass/selector/sequence.rb index <HASH>..<HASH> 100644 --- a/lib/sass/selector/sequence.rb +++ b/lib/sass/selector/sequence.rb @@ -87,6 +87,16 @@ module Sass Haml::Util.flatten(paths.map {|path| weave(path)}, 1).map {|p| Sequence.new(p)} end + # Returns whether or not this selector matches all elements + # that the given selector matches (as well as possibly more). + # + # @example + # (.foo).superselector?(.foo.bar) #=> true + # (.foo).superselector?(.bar) #=> false + # (.bar .foo).superselector?(.foo) #=> false + # + # @param sseq [SimpleSequence] + # @return [Boolean] def superselector?(sseq) return false unless members.size == 1 members.last.superselector?(sseq) diff --git a/lib/sass/selector/simple_sequence.rb b/lib/sass/selector/simple_sequence.rb index <HASH>..<HASH> 100644 --- a/lib/sass/selector/simple_sequence.rb +++ b/lib/sass/selector/simple_sequence.rb @@ -99,6 +99,15 @@ module Sass SimpleSequence.new(sseq) end + # Returns whether or not this selector matches all elements + # that the given selector matches (as well as possibly more). + # + # @example + # (.foo).superselector?(.foo.bar) #=> true + # (.foo).superselector?(.bar) #=> false + # + # @param sseq [SimpleSequence] + # @return [Boolean] def superselector?(sseq) (base.nil? || base.eql?(sseq.base)) && rest.subset?(sseq.rest) end
[Sass] Document the #superselector? methods.
sass_ruby-sass
train
fd227083ef1469c7550166c2a94ccf3202c216ae
diff --git a/test/unit/clone.test.js b/test/unit/clone.test.js index <HASH>..<HASH> 100644 --- a/test/unit/clone.test.js +++ b/test/unit/clone.test.js @@ -16,5 +16,16 @@ module.exports = { clone.g.should.equal(50); clone.b.should.equal(0); clone.a.should.equal(1); + }, + + 'test HSLA': function(){ + var node = new nodes.HSLA(100, 50, 12, 1) + , clone = node.clone(); + + clone.should.not.equal(node); + clone.h.should.equal(100); + clone.s.should.equal(50); + clone.l.should.equal(12); + clone.a.should.equal(1); } }; \ No newline at end of file
Added HSLA#clone() test
stylus_stylus
train
428166520389562fa0c95283a1af9c73f95fd233
diff --git a/spyderlib/plugins/externalconsole.py b/spyderlib/plugins/externalconsole.py index <HASH>..<HASH> 100644 --- a/spyderlib/plugins/externalconsole.py +++ b/spyderlib/plugins/externalconsole.py @@ -415,6 +415,8 @@ class ExternalConsoleConfigPage(PluginConfigPage): Automatically change to default PYTHONSTARTUP file if scientific libs are not available """ + if not isinstance(pyexec, basestring): + pyexec = unicode(pyexec.toUtf8(), 'utf-8') old_pyexec = self.get_option("pythonexecutable") if not (pyexec == old_pyexec) and custom_radio.isChecked(): scientific = scientific_libs_available(pyexec) @@ -424,10 +426,14 @@ class ExternalConsoleConfigPage(PluginConfigPage): def change_qtapi(self, pyexec): """Automatically change qt_api setting after changing interpreter""" + if not isinstance(pyexec, basestring): + pyexec = unicode(pyexec.toUtf8(), 'utf-8') old_pyexec = self.get_option("pythonexecutable") if not (pyexec == old_pyexec): - has_pyqt4 = programs.is_module_installed('PyQt4', interpreter=pyexec) - has_pyside = programs.is_module_installed('PySide', interpreter=pyexec) + has_pyqt4 = programs.is_module_installed('PyQt4', + interpreter=pyexec) + has_pyside = programs.is_module_installed('PySide', + interpreter=pyexec) for cb in self.comboboxes: if self.comboboxes[cb][0] == 'qt/api': qt_setapi_cb = cb
External Console: Fix PyQt API#1 errors in change_pystartup and change_qtapi Update Issue <I>
spyder-ide_spyder
train
bdf5418fd27eddb7c90c44c90585adcaa24a2103
diff --git a/vagrant_box_defaults.rb b/vagrant_box_defaults.rb index <HASH>..<HASH> 100644 --- a/vagrant_box_defaults.rb +++ b/vagrant_box_defaults.rb @@ -3,10 +3,10 @@ Vagrant.require_version ">= 2.2.0" $SERVER_BOX = "cilium/ubuntu-dev" -$SERVER_VERSION= "173" +$SERVER_VERSION= "175" $NETNEXT_SERVER_BOX= "cilium/ubuntu-next" -$NETNEXT_SERVER_VERSION= "59" +$NETNEXT_SERVER_VERSION= "60" @v419_SERVER_BOX= "cilium/ubuntu-4-19" -@v419_SERVER_VERSION= "14" +@v419_SERVER_VERSION= "16" @v49_SERVER_BOX= "cilium/ubuntu" -@v49_SERVER_VERSION= "173" +@v49_SERVER_VERSION= "175"
vagrant: bump all vagrant box versions These include a fix for #<I>. Fixes: #<I>
cilium_cilium
train
6969f8fb2871f06df449cc587376e13793d422cc
diff --git a/src/geometries/geometry.js b/src/geometries/geometry.js index <HASH>..<HASH> 100644 --- a/src/geometries/geometry.js +++ b/src/geometries/geometry.js @@ -18,16 +18,16 @@ import extent from 'turf-extent'; */ export default class Geometry { - constructor(map, type, coordinates) { + constructor(map, type, data) { this._map = map; this.drawId = hat(); - this.coordinates = coordinates; + this.coordinates = data.geometry.coordinates; + var props = data.properties || {}; + props.drawId = this.drawId; this.geojson = { type: 'Feature', - properties: { - drawId: this.drawId - }, + properties: props, geometry: { type: type, coordinates: this.coordinates.toJS() diff --git a/src/geometries/line.js b/src/geometries/line.js index <HASH>..<HASH> 100644 --- a/src/geometries/line.js +++ b/src/geometries/line.js @@ -15,8 +15,9 @@ import { translatePoint, DOM } from '../util'; export default class Line extends Geometry { constructor(map, data) { - var coordinates = Immutable.List(data ? data.geometry.coordinates : [[0, 0], [0, 0]]); - super(map, 'LineString', coordinates); + if (!data) data = { geometry: {} }; + data.geometry.coordinates = Immutable.List(data.geometry.coordinates || [[0, 0], [0, 0]]); + super(map, 'LineString', data); this.type = 'line'; diff --git a/src/geometries/point.js b/src/geometries/point.js index <HASH>..<HASH> 100644 --- a/src/geometries/point.js +++ b/src/geometries/point.js @@ -14,8 +14,9 @@ import Immutable from 'immutable'; export default class Point extends Geometry { constructor(map, data) { - var coordinates = Immutable.List(data ? data.geometry.coordinates : [0, 0]); - super(map, 'Point', coordinates); + if (!data) data = { geometry: {} }; + data.geometry.coordinates = Immutable.List(data.geometry.coordinates || [0, 0]); + super(map, 'Point', data); this.type = 'point'; this.completeDraw = this._completeDraw.bind(this); } diff --git a/src/geometries/polygon.js b/src/geometries/polygon.js index <HASH>..<HASH> 100644 --- a/src/geometries/polygon.js +++ b/src/geometries/polygon.js @@ -15,8 +15,9 @@ import { translatePoint, DOM } from '../util'; export default class Polygon extends Geometry { constructor(map, data) { - var coordinates = Immutable.fromJS(data ? data.geometry.coordinates : [[[0, 0],[0, 0], [0, 0], [0, 0]]]); - super(map, 'Polygon', coordinates); + if (!data) data = { geometry: {} }; + data.geometry.coordinates = Immutable.fromJS(data.geometry.coordinates || [[[0, 0],[0, 0], [0, 0], [0, 0]]]); + super(map, 'Polygon', data); // event handlers this.addVertex = this._addVertex.bind(this); diff --git a/src/geometries/square.js b/src/geometries/square.js index <HASH>..<HASH> 100644 --- a/src/geometries/square.js +++ b/src/geometries/square.js @@ -14,8 +14,9 @@ import { translatePoint, DOM } from '../util'; export default class Square extends Geometry { constructor(map) { - var coordinates = Immutable.fromJS([[[0, 0],[0, 0], [0, 0], [0, 0], [0, 0]]]); - super(map, 'Polygon', coordinates); + var data = { geometry: {} }; + data.geometry.coordinates = Immutable.fromJS([[[0, 0],[0, 0], [0, 0], [0, 0], [0, 0]]]); + super(map, 'Polygon', data); this.type = 'square';
preserve feature properties on input - closes #<I>
mapbox_mapbox-gl-draw
train
1f23fd7845d7f9f560f20ea437163604b451cc60
diff --git a/gremlin/gremlin-test/src/main/java/com/tinkerpop/gremlin/structure/IoTest.java b/gremlin/gremlin-test/src/main/java/com/tinkerpop/gremlin/structure/IoTest.java index <HASH>..<HASH> 100644 --- a/gremlin/gremlin-test/src/main/java/com/tinkerpop/gremlin/structure/IoTest.java +++ b/gremlin/gremlin-test/src/main/java/com/tinkerpop/gremlin/structure/IoTest.java @@ -131,12 +131,27 @@ public class IoTest extends AbstractGremlinTest { @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_INTEGER_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = FEATURE_FLOAT_VALUES) @LoadGraphWith(LoadGraphWith.GraphData.CLASSIC) - public void shouldReadWriteToKryo() throws Exception { - // todo: this is just temporary until we get the modern graph in and annotations can be tested cleanly - g.annotations().set("testString", "judas"); - g.annotations().set("testLong", 100l); - g.annotations().set("testInt", 100); + public void shouldReadWriteClassicToKryo() throws Exception { + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + final KryoWriter writer = new KryoWriter(g); + writer.writeGraph(os); + os.close(); + + final Graph g1 = graphProvider.openTestGraph(graphProvider.newGraphConfiguration("readGraph")); + final KryoReader reader = new KryoReader.Builder(g1) + .setWorkingDirectory(File.separator + "tmp").build(); + reader.readGraph(new ByteArrayInputStream(os.toByteArray())); + + assertClassicGraph(g1); + } + + @Test + @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) + @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_INTEGER_VALUES) + @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = FEATURE_FLOAT_VALUES) + @LoadGraphWith(LoadGraphWith.GraphData.MODERN) + public void shouldReadWriteModernToKryo() throws Exception { final ByteArrayOutputStream os = new ByteArrayOutputStream(); final KryoWriter writer = new KryoWriter(g); writer.writeGraph(os); @@ -147,11 +162,12 @@ public class IoTest extends AbstractGremlinTest { .setWorkingDirectory(File.separator + "tmp").build(); reader.readGraph(new ByteArrayInputStream(os.toByteArray())); - assertEquals("judas", g1.annotations().get("testString").get()); - assertEquals(100l, g1.annotations().get("testLong").get()); - assertEquals(100, g1.annotations().get("testInt").get()); + assertModernGraph(g1); + } - assertClassicGraph(g1); + private void assertModernGraph(final Graph g1) { + assertEquals(6, g1.V().count()); + assertEquals(8, g1.E().count()); } private void assertClassicGraph(final Graph g1) {
Add test reading/writing kryo modern graph.
apache_tinkerpop
train
5b43d8cd79136236bf3c2cee7824949704cc5462
diff --git a/vespa/populations.py b/vespa/populations.py index <HASH>..<HASH> 100644 --- a/vespa/populations.py +++ b/vespa/populations.py @@ -31,7 +31,7 @@ from isochrones import StarModel from .transit_basic import occultquad, ldcoeffs, minimum_inclination from .transit_basic import MAInterpolationFunction from .transit_basic import eclipse_pars -from .transit_basic import eclipse, NoEclipseError +from .transit_basic import eclipse, eclipse_tt, NoEclipseError from .fitebs import fitebs from .plotutils import setfig, plot2dhist @@ -691,8 +691,7 @@ class EclipsePopulation(StarPopulation): bbox=dict(boxstyle='round',fc='w'), xycoords='figure fraction',fontsize=15) - def eclipse(self, i, secondary=False, npoints=200, width=3, - texp=0.020434028, MAfn=None, batman=True): + def eclipse_pars(self, i, secondary=False): s = self.stars.iloc[i] P = s['P'] @@ -710,10 +709,25 @@ class EclipsePopulation(StarPopulation): b = s['b_pri'] frac = s['fluxfrac_1'] - return eclipse(p0, b, aR, P=P, ecc=s['ecc'], w=s['w'], npts=npoints, - cadence=texp, frac=frac, conv=True, - sec=secondary, MAfn=MAfn, batman=batman) + return dict(P=P, p0=p0, b=b, aR=aR, frac=frac, u1=mu1, u2=mu2, + ecc=s['ecc'], w=s['w']) + + def eclipse(self, i, secondary=False, **kwargs): + pars = self.eclipse_pars(i, secondary=secondary) + + for k,v in pars.items(): + kwargs[k] = v + + return eclipse(sec=secondary, **kwargs) + def eclipse_trapfit(self, i, secondary=False, **kwargs): + pars = self.eclipse_pars(i, secondary=secondary) + + for k,v in pars.items(): + kwargs[k] = v + + return eclipse_tt(**kwargs) + def eclipse_new(self, i, secondary=False, npoints=200, width=3, texp=0.020434028): """ diff --git a/vespa/transit_basic.py b/vespa/transit_basic.py index <HASH>..<HASH> 100644 --- a/vespa/transit_basic.py +++ b/vespa/transit_basic.py @@ -329,7 +329,7 @@ def a_over_Rs(P,R2,M2,M1=1,R1=1,planet=True): return semimajor(P,M1+M2)*AU/(R1*RSUN) def eclipse(p0,b,aR,P=1,ecc=0,w=0,npts=100,u1=0.394,u2=0.261,width=3, - conv=True,cadence=0.020434028,frac=1,sec=False): + conv=True,cadence=0.020434028,frac=1,sec=False,tol=1e-4): dur = transit_duration(p0, P, b, aR, ecc, w*np.pi/180, sec) if np.isnan(dur): @@ -339,12 +339,12 @@ def eclipse(p0,b,aR,P=1,ecc=0,w=0,npts=100,u1=0.394,u2=0.261,width=3, M0 = minimize(angle_from_occultation, -np.pi/2 - w*np.pi/180, args=(ecc, w*np.pi/180), - method='Nelder-Mead', tol=1e-3).x[0] + method='Nelder-Mead', tol=tol).x[0] else: M0 = minimize(angle_from_transit, np.pi/2 - w*np.pi/180, args=(ecc, w*np.pi/180), - method='Nelder-Mead', tol=1e-3).x[0] + method='Nelder-Mead', tol=tol).x[0] Mlo = M0 - (dur/P)*2*np.pi * width/2. Mhi = M0 + (dur/P)*2*np.pi * width/2. @@ -420,7 +420,7 @@ def eclipse_new(p0,b,aR,P=1,ecc=0,w=0,npts=200,MAfn=None,u1=0.394,u2=0.261,width return ts, fs -def eclipse_tt(p0,b,aR,P=1,ecc=0,w=0,npts=100,u1=0.394,u2=0.261,conv=True,cadence=0.020434028,frac=1,sec=False,pars0=None): +def eclipse_tt(p0,b,aR,P=1,ecc=0,w=0,npts=100,u1=0.394,u2=0.261,conv=True,cadence=0.020434028,frac=1,sec=False,pars0=None,tol=1e-4): """ Trapezoidal parameters for simulated orbit. @@ -434,7 +434,7 @@ def eclipse_tt(p0,b,aR,P=1,ecc=0,w=0,npts=100,u1=0.394,u2=0.261,conv=True,cadenc """ ts,fs = eclipse(p0=p0,b=b,aR=aR,P=P,ecc=ecc,w=w,npts=npts,u1=u1,u2=u2, - conv=conv,cadence=cadence,frac=frac,sec=sec) + conv=conv,cadence=cadence,frac=frac,sec=sec,tol=tol) #logging.debug('{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}'.format(p0,b,aR,P,ecc,w,xmax,npts,u1,u2,leastsq,conv,cadence,frac,sec,new)) #logging.debug('ts: {} fs: {}'.format(ts,fs))
added eclipse_trapfit method, changed default min-M-finding tolerance
timothydmorton_VESPA
train
00e941cc4242f60f8233b3719fec30fe378ed806
diff --git a/src/models/StyledComponent.js b/src/models/StyledComponent.js index <HASH>..<HASH> 100644 --- a/src/models/StyledComponent.js +++ b/src/models/StyledComponent.js @@ -84,7 +84,7 @@ export default (ComponentStyle: Function) => { const propsForElement = {} /* Don't pass through non HTML tags through to HTML elements */ Object.keys(this.props) - .filter(propName => !isTag(target) || validAttr(propName)) + .filter(propName => propName !== 'innerRef' && (!isTag(target) || validAttr(propName))) .forEach(propName => { propsForElement[propName] = this.props[propName] }) diff --git a/src/test/basic.test.js b/src/test/basic.test.js index <HASH>..<HASH> 100644 --- a/src/test/basic.test.js +++ b/src/test/basic.test.js @@ -54,18 +54,31 @@ describe('basic', () => { describe('jsdom tests', () => { jsdom() - it('should pass ref to the component', () => { - const Comp = styled.div`` - const WrapperComp = class extends Component { + + let Comp + let WrapperComp + let wrapper + + beforeEach(() => { + Comp = styled.div`` + WrapperComp = class extends Component { testRef: any; render() { return <Comp innerRef={(comp) => { this.testRef = comp }} /> } } - const wrapper = mount(<WrapperComp />) + wrapper = mount(<WrapperComp />) + }) + + it('should pass ref to the component', () => { // $FlowIssue expect(wrapper.node.testRef).toExist() }) + + it('should not pass innerRef to the component', () => { + // $FlowIssue + expect(wrapper.node.ref).toNotExist() + }) }) })
Do not pass innerRef to the component
styled-components_styled-components
train
1ceca9e1648b206ed33caad30c5dd73cc5ec4f7a
diff --git a/validation/linux_ns_path.go b/validation/linux_ns_path.go index <HASH>..<HASH> 100644 --- a/validation/linux_ns_path.go +++ b/validation/linux_ns_path.go @@ -181,13 +181,16 @@ func main() { err := testNamespacePath(t, c.name, c.unshareOpt) t.Ok(err == nil, fmt.Sprintf("set %s namespace by path", c.name)) if err != nil { - specErr := specerror.NewError(specerror.NSProcInPath, err, rspec.Version) + rfcError, errRfc := specerror.NewRFCError(specerror.NSProcInPath, err, rspec.Version) + if errRfc != nil { + continue + } diagnostic := map[string]string{ "actual": fmt.Sprintf("err == %v", err), "expected": "err == nil", "namespace type": c.name, - "level": specErr.(*specerror.Error).Err.Level.String(), - "reference": specErr.(*specerror.Error).Err.Reference, + "level": rfcError.Level.String(), + "reference": rfcError.Reference, } t.YAML(diagnostic) }
validation: use rfcError instead of specerror Now that a new helper `NewRFCError()` is available, we should make use of the helper instead of `specerror.NewError()`. This way, we can avoid doing multiple casts to be able to get rfcError.
opencontainers_runtime-tools
train
687629a078e83cdfb28fbe7f022869b376152c9a
diff --git a/src/Services/QueuedJobService.php b/src/Services/QueuedJobService.php index <HASH>..<HASH> 100644 --- a/src/Services/QueuedJobService.php +++ b/src/Services/QueuedJobService.php @@ -28,6 +28,7 @@ use SilverStripe\Security\Security; use SilverStripe\Subsites\Model\Subsite; use Symbiote\QueuedJobs\DataObjects\QueuedJobDescriptor; use Symbiote\QueuedJobs\Interfaces\UserContextInterface; +use Symbiote\QueuedJobs\Jobs\RunBuildTaskJob; use Symbiote\QueuedJobs\QJUtils; use Symbiote\QueuedJobs\Tasks\Engines\TaskRunnerEngine; @@ -445,7 +446,17 @@ class QueuedJobService ]) ->where('"StepsProcessed" = "LastProcessedCount"'); + /** @var QueuedJobDescriptor $stalledJob */ foreach ($stalledJobs as $stalledJob) { + $jobClass = $stalledJob->Implementation; + $jobSingleton = singleton($jobClass); + + if ($jobSingleton instanceof RunBuildTaskJob) { + // Exclude Tasks which are running via Job wrapper as they never have steps + // so they could be incorrectly recognized as stalled + continue; + } + $this->restartStalledJob($stalledJob); } diff --git a/tests/QueuedJobsTest.php b/tests/QueuedJobsTest.php index <HASH>..<HASH> 100644 --- a/tests/QueuedJobsTest.php +++ b/tests/QueuedJobsTest.php @@ -2,6 +2,7 @@ namespace Symbiote\QueuedJobs\Tests; +use Exception; use Psr\Log\LoggerInterface; use ReflectionClass; use SilverStripe\Core\Config\Config; @@ -11,6 +12,7 @@ use SilverStripe\ORM\DataObject; use SilverStripe\ORM\FieldType\DBDatetime; use SilverStripe\ORM\ValidationException; use Symbiote\QueuedJobs\DataObjects\QueuedJobDescriptor; +use Symbiote\QueuedJobs\Jobs\RunBuildTaskJob; use Symbiote\QueuedJobs\Services\QueuedJob; use Symbiote\QueuedJobs\Services\QueuedJobService; use Symbiote\QueuedJobs\Tests\QueuedJobsTest\TestExceptingJob; @@ -380,7 +382,7 @@ class QueuedJobsTest extends AbstractTest $svc->checkJobHealth(QueuedJob::IMMEDIATE); $nextJob = $svc->getNextPendingJob(QueuedJob::IMMEDIATE); - // This job is resumed and exeuction is attempted this round + // This job is resumed and execution is attempted this round $descriptor = QueuedJobDescriptor::get()->byID($id); $this->assertEquals($nextJob->ID, $descriptor->ID); $this->assertEquals(QueuedJob::STATUS_WAIT, $descriptor->JobStatus); @@ -675,6 +677,37 @@ class QueuedJobsTest extends AbstractTest $this->assertCount(0, QueuedJobDescriptor::get()->filter(['NotifiedBroken' => 0])); } + /** + * @param string $jobClass + * @param int $expected + * @throws ValidationException + * @throws Exception + * @dataProvider healthCheckProvider + */ + public function testExcludeTasksFromHealthCheck(string $jobClass, int $expected): void + { + $service = $this->getService(); + $now = '2019-01-01 16:00:00'; + DBDatetime::set_mock_now($now); + + // Emulate stalled job + $descriptor = QueuedJobDescriptor::create(); + $descriptor->Implementation = $jobClass; + $descriptor->JobType = QueuedJob::IMMEDIATE; + $descriptor->JobStatus = QueuedJob::STATUS_RUN; + $descriptor->Expiry = $now; + $descriptor->LastProcessedCount = 0; + $descriptor->StepsProcessed = 0; + $descriptor->write(); + + $service->checkJobHealth(QueuedJob::IMMEDIATE); + + $this->assertCount( + $expected, + QueuedJobDescriptor::get()->filter(['JobStatus' => QueuedJob::STATUS_WAIT]) + ); + } + public function jobsProvider(): array { return [ @@ -696,4 +729,12 @@ class QueuedJobsTest extends AbstractTest ], ]; } + + public function healthCheckProvider(): array + { + return [ + [TestExceptingJob::class, 1], + [RunBuildTaskJob::class, 0], + ]; + } }
BUG: Exclude tasks run via a job from health check.
symbiote_silverstripe-queuedjobs
train
a8dcd9143dba98117a6bbe6b4ef61ead625826c1
diff --git a/src/test/moment/format.js b/src/test/moment/format.js index <HASH>..<HASH> 100644 --- a/src/test/moment/format.js +++ b/src/test/moment/format.js @@ -154,7 +154,7 @@ test('toISOString', function (assert) { test('inspect', function (assert) { function roundtrip(m) { /*jshint evil:true */ - return eval(m.inspect()); + return (new Function('moment', 'return ' + m.inspect()))(moment); } function testInspect(date, string) { var inspected = date.inspect();
Use Function constructor in place of eval for rollup's satisfaction
moment_moment
train
b9c4c64517e148cf1deca1ec6344e7b988878486
diff --git a/route.py b/route.py index <HASH>..<HASH> 100644 --- a/route.py +++ b/route.py @@ -33,14 +33,12 @@ class PartialDefer(object): def __call__(self, kwargs): unbound = self.default.copy() - logger.debug('UNBOUND: {} {}'.format(self.command, unbound)) # Only map params this function expects for key in unbound: new_value = kwargs.get(key, missing) # Don't overwrite defaults with nothing if new_value not in [missing, None]: unbound[key] = new_value - logger.debug('UNBOUND: {} {}'.format(self.command, unbound)) bound = self.sig.bind(**unbound) self.func(*bound.args, **bound.kwargs) @@ -107,8 +105,10 @@ def validate(command, func): def unpack(prefix, command, params, message): - logger.debug("---UNPACK--- {} {} {} {}".format(prefix, command, params, message)) - route = get_route(command) + try: + route = get_route(command) + except ValueError: + logger.debug("---UNPACK--- {} {} {} {}".format(prefix, command, params, message)) return route.command.upper(), route.unpack(prefix, params, message) @@ -185,3 +185,7 @@ class NoticeRoute(Route): kwargs['message'] = message return kwargs register(NoticeRoute) + + +class WelcomeRoute(Route): + command = 'RPL_WELCOME'
Silence routing exceptions to generate list of missing routes
numberoverzero_bottom
train
0f67cf19abc74ba5ee2bdc9c946b2bf62d85149c
diff --git a/src/Illuminate/Foundation/Http/Kernel.php b/src/Illuminate/Foundation/Http/Kernel.php index <HASH>..<HASH> 100644 --- a/src/Illuminate/Foundation/Http/Kernel.php +++ b/src/Illuminate/Foundation/Http/Kernel.php @@ -111,9 +111,12 @@ class Kernel implements KernelContract { $this->verifySessionConfigurationIsValid(); + $shouldSkipMiddleware = $this->app->bound('middleware.disable') && + $this->app->make('middleware.disable') === true; + return (new Pipeline($this->app)) ->send($request) - ->through($this->middleware) + ->through($shouldSkipMiddleware ? [] : $this->middleware) ->then($this->dispatchToRouter()); } diff --git a/src/Illuminate/Routing/ControllerDispatcher.php b/src/Illuminate/Routing/ControllerDispatcher.php index <HASH>..<HASH> 100644 --- a/src/Illuminate/Routing/ControllerDispatcher.php +++ b/src/Illuminate/Routing/ControllerDispatcher.php @@ -96,12 +96,15 @@ class ControllerDispatcher { { $middleware = $this->getMiddleware($instance, $method); + $shouldSkipMiddleware = $this->container->bound('middleware.disable') && + $this->container->make('middleware.disable') === true; + // Here we will make a stack onion instance to execute this request in, which gives // us the ability to define middlewares on controllers. We will return the given // response back out so that "after" filters can be run after the middlewares. return (new Pipeline($this->container)) ->send($request) - ->through($middleware) + ->through($shouldSkipMiddleware ? [] : $middleware) ->then(function($request) use ($instance, $route, $method) { return $this->router->prepareResponse( diff --git a/src/Illuminate/Routing/Router.php b/src/Illuminate/Routing/Router.php index <HASH>..<HASH> 100755 --- a/src/Illuminate/Routing/Router.php +++ b/src/Illuminate/Routing/Router.php @@ -691,9 +691,12 @@ class Router implements RegistrarContract { { $middleware = $this->gatherRouteMiddlewares($route); + $shouldSkipMiddleware = $this->container->bound('middleware.disable') && + $this->container->make('middleware.disable') === true; + return (new Pipeline($this->container)) ->send($request) - ->through($middleware) + ->through($shouldSkipMiddleware ? [] : $middleware) ->then(function($request) use ($route) { return $this->prepareResponse(
Allow disabling of middleware (for test reasons).
laravel_framework
train
488dffd04bfad7b9b8a5cea0565b75a59ec0589c
diff --git a/lib/postal/config.rb b/lib/postal/config.rb index <HASH>..<HASH> 100644 --- a/lib/postal/config.rb +++ b/lib/postal/config.rb @@ -153,14 +153,6 @@ module Postal raise ConfigError, "No config found at #{self.config_file_path}" end - unless File.exist?(self.smtp_private_key_path) - raise ConfigError, "No SMTP private key found at #{self.smtp_private_key_path}" - end - - unless File.exist?(self.smtp_certificate_path) - raise ConfigError, "No SMTP certificate found at #{self.smtp_certificate_path}" - end - unless File.exists?(self.lets_encrypt_private_key_path) raise ConfigError, "No Let's Encrypt private key found at #{self.lets_encrypt_private_key_path}" end diff --git a/script/generate_initial_config.rb b/script/generate_initial_config.rb index <HASH>..<HASH> 100755 --- a/script/generate_initial_config.rb +++ b/script/generate_initial_config.rb @@ -15,25 +15,6 @@ unless File.exist?(Postal.config_file_path) puts "Created example config file at #{Postal.config_file_path}" end -unless File.exists?(Postal.smtp_private_key_path) - key = OpenSSL::PKey::RSA.new(2048).to_s - File.open(Postal.smtp_private_key_path, 'w') { |f| f.write(key) } - puts "Created new private key for encrypting SMTP connections" -end - -unless File.exist?(Postal.smtp_certificate_path) - cert = OpenSSL::X509::Certificate.new - cert.subject = cert.issuer = OpenSSL::X509::Name.parse("/C=GB/O=Test/OU=Test/CN=Test") - cert.not_before = Time.now - cert.not_after = Time.now + 365 * 24 * 60 * 60 - cert.public_key = Postal.smtp_private_key.public_key - cert.serial = 0x0 - cert.version = 2 - cert.sign Postal.smtp_private_key, OpenSSL::Digest::SHA256.new - File.open(Postal.smtp_certificate_path, 'w') { |f| f.write(cert.to_pem) } - puts "Created new self signed certificate for encrypting SMTP connections" -end - unless File.exists?(Postal.lets_encrypt_private_key_path) key = OpenSSL::PKey::RSA.new(2048).to_s File.open(Postal.lets_encrypt_private_key_path, 'w') { |f| f.write(key) }
don't generate self signed smtp certificates
atech_postal
train
06021285e88a35002024f8acf7eb649e7900c3ad
diff --git a/jbpm-human-task/jbpm-human-task-core/src/main/java/org/jbpm/services/task/impl/model/xml/JaxbTaskData.java b/jbpm-human-task/jbpm-human-task-core/src/main/java/org/jbpm/services/task/impl/model/xml/JaxbTaskData.java index <HASH>..<HASH> 100644 --- a/jbpm-human-task/jbpm-human-task-core/src/main/java/org/jbpm/services/task/impl/model/xml/JaxbTaskData.java +++ b/jbpm-human-task/jbpm-human-task-core/src/main/java/org/jbpm/services/task/impl/model/xml/JaxbTaskData.java @@ -23,8 +23,6 @@ import org.kie.api.task.model.Status; import org.kie.api.task.model.TaskData; import org.kie.api.task.model.User; import org.kie.internal.task.api.model.AccessType; -import org.kie.internal.task.api.model.ContentData; -import org.kie.internal.task.api.model.FaultData; import org.kie.internal.task.api.model.InternalTaskData; @XmlType(name = "task-data") @@ -152,13 +150,21 @@ public class JaxbTaskData extends AbstractJaxbTaskObject<TaskData> implements Ta this.workItemId = taskData.getWorkItemId(); this.processInstanceId = taskData.getProcessInstanceId(); this.documentType = taskData.getDocumentType(); - this.documentAccessType = ((InternalTaskData) taskData).getDocumentAccessType(); + if( taskData instanceof JaxbTaskData ) { + JaxbTaskData jaxbTaskData = (JaxbTaskData) taskData; + this.documentAccessType = jaxbTaskData.getDocumentAccessType(); + this.outputAccessType = jaxbTaskData.getOutputAccessType(); + this.faultAccessType = jaxbTaskData.getFaultAccessType(); + } else if( taskData instanceof InternalTaskData ) { + InternalTaskData internalTaskData = (InternalTaskData) taskData; + this.documentAccessType = internalTaskData.getDocumentAccessType(); + this.outputAccessType = internalTaskData.getOutputAccessType(); + this.faultAccessType = internalTaskData.getFaultAccessType(); + } this.documentContentId = taskData.getDocumentContentId(); this.outputType = taskData.getOutputType(); - this.outputAccessType = ((InternalTaskData) taskData).getOutputAccessType(); this.outputContentId = taskData.getOutputContentId(); this.faultName = taskData.getFaultName(); - this.faultAccessType = ((InternalTaskData) taskData).getFaultAccessType(); this.faultType = taskData.getFaultType(); this.faultContentId = taskData.getFaultContentId(); this.parentId = taskData.getParentId();
BZ-<I> - TaskData object not storing Comments, CreatedOn, ExpirationTime (cherry picked from commit b<I>e<I>e2e<I>ac<I>dbacb<I>dd<I>a)
kiegroup_jbpm
train
1cc536a0dbf6801b4cd0dc58cc28d7de9c10a207
diff --git a/source/Pagination.php b/source/Pagination.php index <HASH>..<HASH> 100644 --- a/source/Pagination.php +++ b/source/Pagination.php @@ -113,7 +113,7 @@ class Pagination $this->currentPage = self::BASE_PAGE; } $this->totalPages = (int) ceil($this->totalItems / $this->perPage); - if ($this->currentPage > $this->totalPages) { + if ($this->currentPage > $this->totalPages && $this->totalPages > 0) { $this->currentPage = $this->totalPages; } $this->offset = abs(intval($this->currentPage * $this->perPage - $this->perPage)); diff --git a/source/Tests/PaginationTest.php b/source/Tests/PaginationTest.php index <HASH>..<HASH> 100644 --- a/source/Tests/PaginationTest.php +++ b/source/Tests/PaginationTest.php @@ -21,6 +21,8 @@ class PaginationTest extends \PHPUnit_Framework_TestCase { $pagination = new Pagination(10, 2, 5); $this->assertEquals(5, $pagination->offset()); + $pagination = new Pagination(0, 1, 5); + $this->assertEquals(0, $pagination->offset()); } public function testLimit() @@ -33,6 +35,8 @@ class PaginationTest extends \PHPUnit_Framework_TestCase { $pagination = new Pagination(20, 2, 10); $this->assertEquals(2, $pagination->currentPage()); + $pagination = new Pagination(0, 1, 10); + $this->assertEquals(1, $pagination->currentPage()); } public function testBuild() @@ -84,5 +88,7 @@ class PaginationTest extends \PHPUnit_Framework_TestCase $this->assertEquals(5, $pagination->totalPages()); $pagination = new Pagination(11, 1, 3); $this->assertEquals(4, $pagination->totalPages()); + $pagination = new Pagination(0, 1, 4); + $this->assertEquals(0, $pagination->totalPages()); } }
Fixed invalid 'offset' and 'currentPage' with empty items
AmsTaFFix_pagination
train
611274767c4daf68534830dbd2b9d7208d1f9cb9
diff --git a/docs/conf.py b/docs/conf.py index <HASH>..<HASH> 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -51,7 +51,7 @@ copyright = u'2012, coagulant' # The short X.Y version. version = '0.2.3' # The full version, including alpha/beta/rc tags. -release = '0.2.3dev' +release = '0.2.3' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages.
Bumped version to <I>
futurecolors_django-geoip
train
a119b4dc3a100fd7e2ee8dffc2f950d470bb6074
diff --git a/src/main/java/de/flapdoodle/embed/process/runtime/Executable.java b/src/main/java/de/flapdoodle/embed/process/runtime/Executable.java index <HASH>..<HASH> 100644 --- a/src/main/java/de/flapdoodle/embed/process/runtime/Executable.java +++ b/src/main/java/de/flapdoodle/embed/process/runtime/Executable.java @@ -68,14 +68,22 @@ public abstract class Executable<T extends ExecutableProcessConfig,P extends ISt s.stop(); } stopables=Lists.newArrayList(); - - if (executable.exists() && !Files.forceDelete(executable)) - logger.warning("Could not delete executable NOW: " + executable); - stopped = true; + + deleteExecutable(); + stopped = true; } } - /** + /** + * Delete the executable at stop time; available here for + * subclassing. + */ + protected void deleteExecutable() { + if (executable.exists() && !Files.forceDelete(executable)) + logger.warning("Could not delete executable NOW: " + executable); + } + + /** * */ class JobKiller implements Runnable {
Allow a subclass of Executable to provide its own implementation of deleting the executable. Perhaps it doesn't want to delete it at all, because it wants to start and stop more than once on one unpack?
flapdoodle-oss_de.flapdoodle.embed.process
train
bd3b61562f1eaaa7c48409afca44c6117203cc6a
diff --git a/aeron-tools/src/main/java/uk/co/real_logic/aeron/tools/ChannelDescriptor.java b/aeron-tools/src/main/java/uk/co/real_logic/aeron/tools/ChannelDescriptor.java index <HASH>..<HASH> 100644 --- a/aeron-tools/src/main/java/uk/co/real_logic/aeron/tools/ChannelDescriptor.java +++ b/aeron-tools/src/main/java/uk/co/real_logic/aeron/tools/ChannelDescriptor.java @@ -21,8 +21,8 @@ package uk.co.real_logic.aeron.tools; */ public class ChannelDescriptor { - String channel; - int[] streamIds; + private String channel; + private int[] streamIds; ChannelDescriptor() { diff --git a/aeron-tools/src/main/java/uk/co/real_logic/aeron/tools/ThwackerTool.java b/aeron-tools/src/main/java/uk/co/real_logic/aeron/tools/ThwackerTool.java index <HASH>..<HASH> 100644 --- a/aeron-tools/src/main/java/uk/co/real_logic/aeron/tools/ThwackerTool.java +++ b/aeron-tools/src/main/java/uk/co/real_logic/aeron/tools/ThwackerTool.java @@ -365,7 +365,7 @@ public class ThwackerTool implements InactiveConnectionHandler, NewConnectionHan { thwackerThreads.get(i).join(); } - catch (InterruptedException e) + catch (final InterruptedException e) { e.printStackTrace(); } @@ -511,7 +511,7 @@ public class ThwackerTool implements InactiveConnectionHandler, NewConnectionHan { Thread.sleep(1); } - catch (InterruptedException e) + catch (final InterruptedException e) { e.printStackTrace(); } @@ -542,7 +542,6 @@ public class ThwackerTool implements InactiveConnectionHandler, NewConnectionHan LOG.debug("RecSubs all done!"); } - @Override public void onInactiveConnection( final String channel, final int streamId, @@ -552,7 +551,6 @@ public class ThwackerTool implements InactiveConnectionHandler, NewConnectionHan LOG.debug("ON INACTIVE ::: " + channel + streamId + sessionId + position); } - @Override public void onNewConnection( final String channel, final int streamId, @@ -819,7 +817,7 @@ public class ThwackerTool implements InactiveConnectionHandler, NewConnectionHan { ms = new MessageStream(minSize, maxSize, verify); } - catch (Exception e) + catch (final Exception e) { e.printStackTrace(); } @@ -861,7 +859,7 @@ public class ThwackerTool implements InactiveConnectionHandler, NewConnectionHan rc = pub.offer(buffer.get(), 0, bytesSent.get()); retryCount++; } - catch (Exception e) + catch (final Exception e) { e.printStackTrace(); LOG.debug("BytesSent: " + bytesSent.get()); diff --git a/aeron-tools/src/test/java/uk/co/real_logic/aeron/tools/RateControllerTest.java b/aeron-tools/src/test/java/uk/co/real_logic/aeron/tools/RateControllerTest.java index <HASH>..<HASH> 100644 --- a/aeron-tools/src/test/java/uk/co/real_logic/aeron/tools/RateControllerTest.java +++ b/aeron-tools/src/test/java/uk/co/real_logic/aeron/tools/RateControllerTest.java @@ -44,13 +44,11 @@ public class RateControllerTest protected long numMessagesSent = 0; protected long numBitsSent = 0; - @Override public long numMessagesSent() { return numMessagesSent; } - @Override public long numBitsSent() { return numBitsSent; @@ -157,14 +155,11 @@ public class RateControllerTest class Callback extends TestCallback { - - @Override public int onNext() { numMessagesSent++; return 0; } - } final RateController.Callback callback = new Callback(); @@ -185,15 +180,12 @@ public class RateControllerTest class Callback extends TestCallback { - - @Override public int onNext() { numMessagesSent++; numBitsSent += 1; return 1; } - } final RateController.Callback callback = new Callback(); @@ -214,15 +206,12 @@ public class RateControllerTest class Callback extends TestCallback { - - @Override public int onNext() { numMessagesSent++; numBitsSent += 10; return 10; } - } final RateController.Callback callback = new Callback(); @@ -245,15 +234,12 @@ public class RateControllerTest class Callback extends TestCallback { - - @Override public int onNext() { numMessagesSent++; numBitsSent += 10; return 10; } - } final RateController.Callback callback = new Callback(); @@ -277,15 +263,12 @@ public class RateControllerTest class Callback extends TestCallback { - - @Override public int onNext() { numMessagesSent++; numBitsSent += 10; return 10; } - } final RateController.Callback callback = new Callback();
Removed some @Overrides, made some variables private instead of package scope.
real-logic_aeron
train
b723319f88abf8aa26e42d7f2824e651b684b678
diff --git a/src/xopen/__init__.py b/src/xopen/__init__.py index <HASH>..<HASH> 100644 --- a/src/xopen/__init__.py +++ b/src/xopen/__init__.py @@ -786,10 +786,15 @@ def xopen( if mode not in ('rt', 'rb', 'wt', 'wb', 'at', 'ab'): raise ValueError("Mode '{}' not supported".format(mode)) filename = os.fspath(filename) - text_mode_kwargs = dict(encoding=encoding, errors=errors, newline=newline) if filename == '-': return _open_stdin_or_out(mode) + if 'b' in mode: + # Do not pass encoding etc. in binary mode as this raises errors. + text_mode_kwargs = dict() + else: + text_mode_kwargs = dict(encoding=encoding, errors=errors, newline=newline) + detected_format = _detect_format_from_extension(filename) if detected_format is None and "w" not in mode: detected_format = _detect_format_from_content(filename)
Make sure encoding is not passed in binary mode
marcelm_xopen
train
3aed29a8c92a577e5e2361fae5bc02002add2e67
diff --git a/flink-java/src/main/java/org/apache/flink/api/java/ExecutionEnvironment.java b/flink-java/src/main/java/org/apache/flink/api/java/ExecutionEnvironment.java index <HASH>..<HASH> 100644 --- a/flink-java/src/main/java/org/apache/flink/api/java/ExecutionEnvironment.java +++ b/flink-java/src/main/java/org/apache/flink/api/java/ExecutionEnvironment.java @@ -801,15 +801,9 @@ public class ExecutionEnvironment { } private void consolidateParallelismDefinitionsInConfiguration() { - final int execParallelism = getParallelism(); - if (execParallelism == ExecutionConfig.PARALLELISM_DEFAULT) { - return; + if (getParallelism() == ExecutionConfig.PARALLELISM_DEFAULT) { + configuration.getOptional(CoreOptions.DEFAULT_PARALLELISM).ifPresent(this::setParallelism); } - - // if parallelism is set in the ExecutorConfig, then - // that value takes precedence over any other value. - - configuration.set(CoreOptions.DEFAULT_PARALLELISM, execParallelism); } /** diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java index <HASH>..<HASH> 100644 --- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java +++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java @@ -1556,15 +1556,9 @@ public class StreamExecutionEnvironment { } private void consolidateParallelismDefinitionsInConfiguration() { - final int execParallelism = getParallelism(); - if (execParallelism == ExecutionConfig.PARALLELISM_DEFAULT) { - return; + if (getParallelism() == ExecutionConfig.PARALLELISM_DEFAULT) { + configuration.getOptional(CoreOptions.DEFAULT_PARALLELISM).ifPresent(this::setParallelism); } - - // if parallelism is set in the ExecutorConfig, then - // that value takes precedence over any other value. - - configuration.set(CoreOptions.DEFAULT_PARALLELISM, execParallelism); } /**
[hotfix] Fix parallelism consolidation logic in the (Stream)ExecutionEnvironment.
apache_flink
train
702165d18e447dedc81fde022e3a9dfe6f8cc262
diff --git a/test/bin_runner_test.rb b/test/bin_runner_test.rb index <HASH>..<HASH> 100644 --- a/test/bin_runner_test.rb +++ b/test/bin_runner_test.rb @@ -1,5 +1,6 @@ require File.join(File.dirname(__FILE__), 'test_helper') require 'boson/runners/bin_runner' +BinRunner = Boson::BinRunner context "BinRunner" do def start(*args) @@ -8,7 +9,7 @@ context "BinRunner" do end before {|e| - Boson::BinRunner.instance_variables.each {|e| Boson::BinRunner.instance_variable_set(e, nil)} + BinRunner.instance_variables.each {|e| BinRunner.instance_variable_set(e, nil)} } context "at commandline" do before_all { reset } @@ -25,9 +26,9 @@ context "BinRunner" do capture_stdout { start '-h' }.should =~ /^boson/ end - # test "help option and command prints help" do - # capture_stdout { start('-h', 'commands') }.should =~ /^commands/ - # end + test "help option and command prints help" do + capture_stdout { start('-h', 'commands') }.should =~ /^commands/ + end test "load option loads libraries" do Manager.expects(:load).with {|*args| args[0][0].is_a?(Module) ? true : args[0][0] == 'blah'}.times(2) @@ -48,18 +49,15 @@ context "BinRunner" do capture_stderr { start("--console") }.should =~ /Console not found/ end - # td: stderr test "execute option executes string" do BinRunner.expects(:define_autoloader) - capture_stderr { - capture_stdout { start("-e", "p 1 + 1") }.should == "2\n" - } + capture_stdout { start("-e", "p 1 + 1") }.should == "2\n" end - # test "global option takes value with whitespace" do - # View.expects(:render).with {|*args| args[1][:fields] = %w{f1 f2} } - # start('commands', '-f', 'f1, f2') - # end + test "global option takes value with whitespace" do + View.expects(:render).with {|*args| args[1][:fields] = %w{f1 f2} } + start('commands', '-f', 'f1, f2') + end test "execute option errors are caught" do capture_stderr { start("-e", "raise 'blah'") }.should =~ /^Error:/ @@ -71,12 +69,11 @@ context "BinRunner" do } end - # td: too many arguments occuring within a command - # test "normal command and too many arguments prints error" do - # capture_stdout { - # capture_stderr { start('render') }.should =~ /'render'.*incorrect/ - # } - # end + test "normal command and too many arguments prints error" do + capture_stdout { + capture_stderr { start('render') }.should =~ /'render'.*incorrect/ + } + end test "failed subcommand prints error and not command not found" do BinRunner.expects(:execute_command).raises("bling") @@ -144,11 +141,11 @@ context "BinRunner" do }.should =~ /Error:.*failed.*changed/ end - # test "with core command updates index and doesn't print index message" do - # Index.indexes[0].expects(:write) - # Boson.main_object.expects(:send).with('libraries') - # capture_stdout { start 'libraries'}.should !~ /index/i - # end + test "with core command updates index and doesn't print index message" do + Index.indexes[0].expects(:write) + Boson.main_object.expects(:send).with('libraries') + capture_stdout { start 'libraries'}.should.not =~ /index/i + end test "with non-core command not finding library, does update index" do Index.expects(:find_library).returns(nil, 'sweet_lib') diff --git a/test/test_helper.rb b/test/test_helper.rb index <HASH>..<HASH> 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -4,7 +4,7 @@ require File.dirname(__FILE__)+'/bacon_extensions' require 'mocha' require 'mocha-on-bacon' require 'boson' -include Boson +Boson.constants.each {|e| Object.const_set(e, Boson.const_get(e)) unless Object.const_defined?(e) } module TestHelpers # make local so it doesn't pick up my real boson dir
fixed bin_runner tests failing because of include Boson
cldwalker_boson
train
34a9a21be556b39832a5b9a93ade91aa7495a0e8
diff --git a/lib/sprockets/server.rb b/lib/sprockets/server.rb index <HASH>..<HASH> 100644 --- a/lib/sprockets/server.rb +++ b/lib/sprockets/server.rb @@ -25,11 +25,6 @@ module Sprockets msg = "Served asset #{env['PATH_INFO']} -" - # URLs containing a `".."` are rejected for security reasons. - if forbidden_request?(env) - return forbidden_response - end - # Mark session as "skipped" so no `Set-Cookie` header is set env['rack.session.options'] ||= {} env['rack.session.options'][:defer] = true @@ -38,6 +33,11 @@ module Sprockets # Extract the path from everything after the leading slash path = unescape(env['PATH_INFO'].to_s.sub(/^\//, '')) + # URLs containing a `".."` are rejected for security reasons. + if forbidden_request?(path) + return forbidden_response + end + # Strip fingerprint if fingerprint = path_fingerprint(path) path = path.sub("-#{fingerprint}", '') @@ -85,12 +85,12 @@ module Sprockets end private - def forbidden_request?(env) + def forbidden_request?(path) # Prevent access to files elsewhere on the file system # # http://example.org/assets/../../../etc/passwd # - env["PATH_INFO"].include?("..") + path.include?("..") end # Returns a 403 Forbidden response tuple diff --git a/test/test_server.rb b/test/test_server.rb index <HASH>..<HASH> 100644 --- a/test/test_server.rb +++ b/test/test_server.rb @@ -185,6 +185,9 @@ class TestServer < Sprockets::TestCase test "illegal require outside load path" do get "/assets/../config/passwd" assert_equal 403, last_response.status + + get "/assets/%2e%2e/config/passwd" + assert_equal 403, last_response.status end test "add new source to tree" do
Check for directory traversal after unescaping The `forbidden_request?` check could be trivially bypassed by percent encoding .. as %2e%2e. After auditing Sprockets and Hike and fuzzing a simple server, I don't believe this is exploitable. However, better safe than sorry/defense in depth/etc.
rails_sprockets
train
099f1700c831a5e27793ea68a1c0d375a22fbcee
diff --git a/lib/ohai/dsl/plugin.rb b/lib/ohai/dsl/plugin.rb index <HASH>..<HASH> 100644 --- a/lib/ohai/dsl/plugin.rb +++ b/lib/ohai/dsl/plugin.rb @@ -30,6 +30,15 @@ module Ohai Class.new(DSL::Plugin::VersionVI, &block) end + # cross platform /dev/null + def self.dev_null + if RUBY_PLATFORM =~ /mswin|mingw|windows/ + "NUL" + else + "/dev/null" + end + end + module DSL class Plugin include Ohai::OS @@ -190,7 +199,7 @@ module Ohai hints[name] end - #emulates the old plugin loading behavior + # emulates the old plugin loading behavior def safe_run begin self.run diff --git a/lib/ohai/plugins/java.rb b/lib/ohai/plugins/java.rb index <HASH>..<HASH> 100644 --- a/lib/ohai/plugins/java.rb +++ b/lib/ohai/plugins/java.rb @@ -26,7 +26,7 @@ Ohai.plugin do status, stdout, stderr = nil if RUBY_PLATFORM.downcase.include?("darwin") - if system("/usr/libexec/java_home 2>&1 >/dev/null") + if system("/usr/libexec/java_home 2>&1 >#{Ohai.dev_null}") status, stdout, stderr = run_command(:no_status_check => true, :command => "java -version") end else diff --git a/spec/unit/path/ohai_plugin_common.rb b/spec/unit/path/ohai_plugin_common.rb index <HASH>..<HASH> 100644 --- a/spec/unit/path/ohai_plugin_common.rb +++ b/spec/unit/path/ohai_plugin_common.rb @@ -54,7 +54,7 @@ module OhaiPluginCommon def plugin_path get_path '/../../../lib/ohai/plugins' end - + # read in the data file for fake executables def read_output( cmd, path = "#{data_path}" )
Make invocations of /dev/null cross platform
chef_ohai
train
4b84717442acd2f65c6c12b94baf14fc38513d7e
diff --git a/h2o-algos/src/test/java/hex/tree/drf/DRFTest.java b/h2o-algos/src/test/java/hex/tree/drf/DRFTest.java index <HASH>..<HASH> 100755 --- a/h2o-algos/src/test/java/hex/tree/drf/DRFTest.java +++ b/h2o-algos/src/test/java/hex/tree/drf/DRFTest.java @@ -218,7 +218,7 @@ public class DRFTest extends TestUtil { } - @Ignore //1-vs-5 node discrepancy + @Ignore //1-vs-5 node discrepancy (parsing into different number of chunks?) @Test public void testAirlines() throws Throwable { basicDRFTestOOBE_Classification( "./smalldata/airlines/allyears2k_headers.zip", "airlines.hex", @@ -349,7 +349,7 @@ public class DRFTest extends TestUtil { } } - // HDEXDEV-194 Check reproducibility for the same # of chunks (i.e., same # of nodes) and same parameters + // HEXDEV-194 Check reproducibility for the same # of chunks (i.e., same # of nodes) and same parameters @Test public void testReprodubility() { Frame tfr=null, vfr=null; final int N = 5; @@ -402,4 +402,68 @@ public class DRFTest extends TestUtil { assertEquals(mses[i], mses[0], 1e-15); } } + + // PUBDEV-557 Test dependency on # chunks + @Ignore + @Test public void testReprodubilityAirline() { + Frame tfr=null, vfr=null; + final int N = 1; + double[] mses = new double[N]; + + Scope.enter(); + try { + // Load data, hack frames + tfr = parse_test_file("./smalldata/airlines/allyears2k_headers.zip"); + + // rebalance to fixed number of chunks + Key dest = Key.make("df.rebalanced.hex"); + RebalanceDataSet rb = new RebalanceDataSet(tfr, dest, 256); + H2O.submitTask(rb); + rb.join(); + tfr.delete(); + tfr = DKV.get(dest).get(); +// Scope.track(tfr.replace(54, tfr.vecs()[54].toEnum())._key); +// DKV.put(tfr); + for (String s : new String[]{ + "DepTime", "ArrTime", "ActualElapsedTime", + "AirTime", "ArrDelay", "DepDelay", "Cancelled", + "CancellationCode", "CarrierDelay", "WeatherDelay", + "NASDelay", "SecurityDelay", "LateAircraftDelay", "IsArrDelayed" + }) { + tfr.remove(s).remove(); + } + DKV.put(tfr); + for (int i=0; i<N; ++i) { + DRFModel.DRFParameters parms = new DRFModel.DRFParameters(); + parms._train = tfr._key; + parms._response_column = "IsDepDelayed"; + parms._nbins = 10; + parms._ntrees = 7; + parms._max_depth = 10; + parms._mtries = -1; + parms._min_rows = 1; + parms._sample_rate = 0.66667f; // Simulated sampling with replacement + parms._seed = (1L<<32)|2; + + // Build a first model; all remaining models should be equal + DRF job = new DRF(parms); + DRFModel drf = job.trainModel().get(); + assertEquals(drf._output._ntrees, parms._ntrees); + + mses[i] = drf._output._mse_train[drf._output._mse_train.length-1]; + job.remove(); + drf.delete(); + } + } finally{ + if (tfr != null) tfr.remove(); + if (vfr != null) vfr.remove(); + } + Scope.exit(); + for (int i=0; i<mses.length; ++i) { + Log.info("trial: " + i + " -> mse: " + mses[i]); + } + for (int i=0; i<mses.length; ++i) { + assertEquals(0.2273639898, mses[i], 1e-9); //check for the same result on 1 nodes and 5 nodes + } + } }
PUBDEV-<I>: Add DRF JUnit to test the reproducibility with different # of JVMs. Not working yet, even for fix # chunks. However, it converges with increasing number of bins, need to look into it. GBM gives the same results for small number of bins.
h2oai_h2o-3
train
7e58a948879f70f293f9e8412be1f668815a724d
diff --git a/servo-core/src/main/java/com/netflix/servo/publish/JmxMetricPoller.java b/servo-core/src/main/java/com/netflix/servo/publish/JmxMetricPoller.java index <HASH>..<HASH> 100644 --- a/servo-core/src/main/java/com/netflix/servo/publish/JmxMetricPoller.java +++ b/servo-core/src/main/java/com/netflix/servo/publish/JmxMetricPoller.java @@ -222,11 +222,15 @@ public final class JmxMetricPoller implements MetricPoller { MBeanServerConnection con = connector.getConnection(); for (ObjectName query : queries) { Set<ObjectName> names = con.queryNames(query, null); - for (ObjectName name : names) { - try { - getMetrics(con, filter, metrics, name); - } catch (Exception e) { - LOGGER.warn("failed to get metrics for: " + name, e); + if (names.isEmpty()) { + LOGGER.warn("no mbeans matched query: {}", query); + } else { + for (ObjectName name : names) { + try { + getMetrics(con, filter, metrics, name); + } catch (Exception e) { + LOGGER.warn("failed to get metrics for: " + name, e); + } } } }
Logging warning when mbean query doesn't match any mbeans in JmxMetricPoller poll
Netflix_servo
train
4575c4ab6fb3e5a4814dd29bbb710ddc898379c8
diff --git a/src/ol/interaction/draw.js b/src/ol/interaction/draw.js index <HASH>..<HASH> 100644 --- a/src/ol/interaction/draw.js +++ b/src/ol/interaction/draw.js @@ -374,7 +374,7 @@ ol.interaction.Draw.handleUpEvent_ = function(event) { this.addToDrawing_(event); } pass = false; - } else if (circleMode) { + } else if (circleMode && this.freehand_) { this.finishCoordinate_ = null; } return pass;
Do not draw circle when pointer not moved AND freehand is on
openlayers_openlayers
train
357473bafb5571debadfa14fa2b9dd15380c3333
diff --git a/Source/com/drew/metadata/tiff/DirectoryTiffHandler.java b/Source/com/drew/metadata/tiff/DirectoryTiffHandler.java index <HASH>..<HASH> 100644 --- a/Source/com/drew/metadata/tiff/DirectoryTiffHandler.java +++ b/Source/com/drew/metadata/tiff/DirectoryTiffHandler.java @@ -24,6 +24,7 @@ import com.drew.imaging.tiff.TiffHandler; import com.drew.lang.Rational; import com.drew.lang.annotations.NotNull; import com.drew.metadata.Directory; +import com.drew.metadata.ErrorDirectory; import com.drew.metadata.Metadata; import com.drew.metadata.StringValue; @@ -78,12 +79,24 @@ public abstract class DirectoryTiffHandler implements TiffHandler public void warn(@NotNull String message) { - _currentDirectory.addError(message); + getCurrentOrErrorDirectory().addError(message); } public void error(@NotNull String message) { - _currentDirectory.addError(message); + getCurrentOrErrorDirectory().addError(message); + } + + @NotNull + private Directory getCurrentOrErrorDirectory() + { + if (_currentDirectory != null) + return _currentDirectory; + ErrorDirectory error = _metadata.getFirstDirectoryOfType(ErrorDirectory.class); + if (error != null) + return error; + pushDirectory(ErrorDirectory.class); + return _currentDirectory; } public void setByteArray(int tagId, @NotNull byte[] bytes)
(.NET @aab<I>d) Fix NRE during reporting of early TIFF error via new ErrorDirectory.
drewnoakes_metadata-extractor
train
b2e852c42311847040e38da1df8e12b016a02f8c
diff --git a/src/main/java/com/github/dockerjava/core/command/FrameReader.java b/src/main/java/com/github/dockerjava/core/command/FrameReader.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/github/dockerjava/core/command/FrameReader.java +++ b/src/main/java/com/github/dockerjava/core/command/FrameReader.java @@ -7,6 +7,8 @@ import java.util.Arrays; import com.github.dockerjava.api.model.Frame; import com.github.dockerjava.api.model.StreamType; +import javax.annotation.CheckForNull; + /** * Breaks the input into frame. Similar to how a buffered reader would readLies. * <p/> @@ -42,14 +44,16 @@ public class FrameReader implements AutoCloseable { /** * @return A frame, or null if no more frames. */ + @CheckForNull public Frame readFrame() throws IOException { if (rawStreamDetected) { - int read = inputStream.read(rawBuffer); + if (read == -1) { + return null; + } return new Frame(StreamType.RAW, Arrays.copyOf(rawBuffer, read)); - } else { byte[] header = new byte[HEADER_SIZE];
Fix NegativeArraySizeException in awaitCompletion()
docker-java_docker-java
train
9584da11c07b6a48d5872dcaf6b74bf0cd79ad7a
diff --git a/EventListener/ControllerListener.php b/EventListener/ControllerListener.php index <HASH>..<HASH> 100644 --- a/EventListener/ControllerListener.php +++ b/EventListener/ControllerListener.php @@ -46,6 +46,11 @@ class ControllerListener implements EventSubscriberInterface public function decodeRequest(FilterControllerEvent $event) { $request = $event->getRequest(); + + if (!$request->attributes->has(RouteKeys::DEFINITION)) { + return; + } + $action = $request->attributes->get(RouteKeys::ACTION); switch ($action) { @@ -93,6 +98,10 @@ class ControllerListener implements EventSubscriberInterface */ public function validateContent(GetResponseForControllerResultEvent $event) { + if (!$event->getRequest()->attributes->has(RouteKeys::DEFINITION)) { + return; + } + $action = $event->getRequest()->attributes->get(RouteKeys::ACTION); if (in_array($action, ['index', 'get', 'create', 'update'], true)) {
only handle event if it is a resource request
Innmind_RestBundle
train
288e0b8ddd9bdb6ecc9686c121977fdb3914aad9
diff --git a/pyradigm/base.py b/pyradigm/base.py index <HASH>..<HASH> 100644 --- a/pyradigm/base.py +++ b/pyradigm/base.py @@ -20,6 +20,11 @@ class PyradigmException(Exception): pass +class ConstantValuesException(PyradigmException): + """Customized exception to identify the error more precisely.""" + pass + + def is_iterable_but_not_str(value): """Boolean check for iterables that are not strings""" @@ -1258,9 +1263,11 @@ class BaseDataset(ABC): for samplet, features in data.items(): # when there is only one unique value, among n features + # Note: NaN != NaN, so when its all NaN, num. of uniq elements > 1 if np.unique(features).size < 2: - raise PyradigmException('Constant values detected for {} - double ' - 'check the process'.format(samplet)) + raise ConstantValuesException('Constant values detected for {} ' + '- double check the process' + ''.format(samplet)) def _check_for_constant_features_across_samplets(self, data_matrix): @@ -1271,9 +1278,10 @@ class BaseDataset(ABC): # notice the transpose, which makes it a column for col_ix, col in enumerate(data_matrix.T): if np.unique(col).size < 2: - raise PyradigmException('Constant values detected for feature {}' - ' (index {}) - double check the process' - ''.format(self._feature_names[col_ix], + raise ConstantValuesException('Constant values detected ' + 'for feature {} (index {}) - ' + 'double check the process' + ''.format(self._feature_names[col_ix], col_ix))
custom exception to identify the source of error more precisely
raamana_pyradigm
train
a911cfd7f5c22737431327d5c2b71c0e06a9d86f
diff --git a/servers/src/test/java/tachyon/master/next/filesystem/meta/InodeTreeTests.java b/servers/src/test/java/tachyon/master/next/filesystem/meta/InodeTreeTests.java index <HASH>..<HASH> 100644 --- a/servers/src/test/java/tachyon/master/next/filesystem/meta/InodeTreeTests.java +++ b/servers/src/test/java/tachyon/master/next/filesystem/meta/InodeTreeTests.java @@ -148,8 +148,33 @@ public final class InodeTreeTests { // add nested file mTree.createPath(new TachyonURI("/nested/test/file"), Constants.KB, true, false); + // all inodes under root List<Inode> inodes = mTree.getInodeChildrenRecursive((InodeDirectory) mTree.getInodeById(0)); - // /test, /nested/, /nested/test, /nested/test/file + // /test, /nested, /nested/test, /nested/test/file Assert.assertEquals(4, inodes.size()); } + + @Test + public void deleteInode() throws Exception { + Inode nested = mTree.createPath(NESTED_URI, Constants.KB, true, true); + + // all inodes under root + List<Inode> inodes = mTree.getInodeChildrenRecursive((InodeDirectory) mTree.getInodeById(0)); + // /nested, /nested/test + Assert.assertEquals(2, inodes.size()); + // delete the nested inode + mTree.deleteInode(nested); + inodes = mTree.getInodeChildrenRecursive((InodeDirectory) mTree.getInodeById(0)); + // only /nested left + Assert.assertEquals(1, inodes.size()); + } + + @Test + public void deleteNoexistingInode() throws Exception { + mThrown.expect(FileDoesNotExistException.class); + mThrown.expectMessage("Inode id 1 does not exist"); + + Inode testFile = new InodeFile("testFile1", 1, 1, Constants.KB, System.currentTimeMillis()); + mTree.deleteInode(testFile); + } }
Added tests for deleteInode
Alluxio_alluxio
train
4dcad5606f0924438e912a630b1cee13838445af
diff --git a/validator/journal/consensus/poet1/validator_registry.py b/validator/journal/consensus/poet1/validator_registry.py index <HASH>..<HASH> 100644 --- a/validator/journal/consensus/poet1/validator_registry.py +++ b/validator/journal/consensus/poet1/validator_registry.py @@ -78,11 +78,10 @@ class Update(object): KnownVerbs = ['reg'] @staticmethod - def register_validator(regtxn, validator_name, validator_id, signup_info): + def register_validator(validator_name, validator_id, signup_info): """Creates a new Update object to register a validator. Args: - regtxn: Transaction registering the validator validator_name: Human readable name of the validator validator_id: Bitcoin-style address of the validators public key signup_info: Serialized dict of SignupData with keys... @@ -96,22 +95,20 @@ class Update(object): minfo['validator_name'] = validator_name minfo['validator_id'] = validator_id minfo['signup_info'] = signup_info - update = Update(regtxn, minfo) + update = Update(minfo) update.verb = 'reg' return update - def __init__(self, txn=None, minfo=None): + def __init__(self, minfo=None): """Constructor for Update class. Args: - txn: The transaction - minfo (dict): Dictionary of values for update fields... + minfo (dict): Update values extracted from a message {'verb', 'validator_name', 'validator_id', 'signup_info'} """ if minfo is None: minfo = {} - self.transaction = txn self.verb = minfo.get('verb', 'reg') self.validator_name = minfo.get('validator_name', '') self.validator_id = minfo.get('validator_id', NullIdentifier) @@ -138,29 +135,28 @@ class Update(object): return True - def check_valid(self, store): + def check_valid(self, store, txn): """Determines if the update is valid. Check policy on each element of validator_name, validator_id, - registration_txn_id, and signup_info + and signup_info Args: - store (dict): Transaction store mapping. + store (Store): Transaction store. + txn (Transaction): Transaction encompassing this update. """ LOGGER.debug('check update %s from %s', str(self), self.validator_id) - assert self.transaction - # Nothing to check on transaction id (comes directly from the object) # Check name if not self.is_valid_name(): raise InvalidTransactionError( 'Illegal validator name {}'.format(self.validator_name[:64])) - # Check validator ID. Only self registrations - if self.validator_id != self.transaction.OriginatorID: + # Check registering validator matches transaction signer. + if self.validator_id != txn.OriginatorID: raise InvalidTransactionError( 'Signature mismatch on validator registration with validator' ' {} signed by {}'.format(self.validator_id, - self.transaction.OriginatorID)) + txn.OriginatorID)) # Nothing to check for anti_sybil_id # Apply will invalidate any previous entries for this anti_sybil_id @@ -172,11 +168,12 @@ class Update(object): 'Invalid Signup Info: {}'.format(self.signup_info)) return True - def apply(self, store): + def apply(self, store, txn): """Applies the update to the validator entry in the store. Args: - store (dict): Transaction store mapping. + store (Store): Transaction store. + txn (Transaction): Transaction encompassing this update. """ LOGGER.debug('apply %s', str(self)) @@ -184,13 +181,12 @@ class Update(object): for validator, registration in store.iteritems(): if registration['anti_sybil_id'] == self.signup_info.anti_sybil_id: if registration['revoked'] is not None: - registration['revoked'] = self.transaction.Identifier + registration['revoked'] = txn.Identifier if self.verb == 'reg': store[self.validator_id] = { 'validator_name': self.validator_name, 'validator_id': self.validator_id, - 'registration_txn_id': self.transaction.Identifier, 'poet_pubkey': self.signup_info.poet_pubkey, 'anti_sybil_id': self.signup_info.anti_sybil_id, 'proof_data': self.signup_info.proof_data, @@ -206,7 +202,6 @@ class Update(object): dict: A dictionary containing attributes from the update object. """ - assert self.transaction result = { 'verb': self.verb, @@ -251,8 +246,8 @@ class ValidatorRegistryTransaction(transaction.Transaction): registering the validator. """ regtxn = ValidatorRegistryTransaction() - regtxn.Update = Update.register_validator(regtxn, validator_id, - validator_name, signup_info) + regtxn.Update = Update.register_validator(validator_id, validator_name, + signup_info) return regtxn @@ -264,7 +259,7 @@ class ValidatorRegistryTransaction(transaction.Transaction): self.Update = None if 'Update' in minfo: - self.Update = Update(txn=self, minfo=minfo['Update']) + self.Update = Update(minfo=minfo['Update']) def __str__(self): return str(self.Update) @@ -280,7 +275,7 @@ class ValidatorRegistryTransaction(transaction.Transaction): """ super(ValidatorRegistryTransaction, self).check_valid(store) assert self.Update - self.Update.check_valid(store) + self.Update.check_valid(store, self) return True def apply(self, store): @@ -290,7 +285,7 @@ class ValidatorRegistryTransaction(transaction.Transaction): Args: store (dict): Transaction store mapping. """ - self.Update.apply(store) + self.Update.apply(store, self) def dump(self): """Returns a dict with attributes from the transaction object.
fixup: refactor txn pointer Remove pointer from update constructor and into parameter for check_valid and apply.
hyperledger_sawtooth-core
train
e6ae48b172e39be6f63de87be7dd8961f1366acb
diff --git a/go/kbfs/libdokan/fs.go b/go/kbfs/libdokan/fs.go index <HASH>..<HASH> 100644 --- a/go/kbfs/libdokan/fs.go +++ b/go/kbfs/libdokan/fs.go @@ -367,31 +367,16 @@ func (f *FS) open(ctx context.Context, oc *openContext, ps []string) (dokan.File oc.isUppercasePath = true fallthrough case PublicName == ps[0]: - // Refuse private directories while we are in a a generic error state. - if f.remoteStatus.ExtraFileName() == libfs.HumanErrorFileName { - f.log.CWarningf(ctx, "Refusing access to public directory while errors are present!") - return nil, 0, dokan.ErrAccessDenied - } return f.root.public.open(ctx, oc, ps[1:]) case strings.ToUpper(PrivateName) == ps[0]: oc.isUppercasePath = true fallthrough case PrivateName == ps[0]: - // Refuse private directories while we are in a error state. - if f.remoteStatus.ExtraFileName() != "" { - f.log.CWarningf(ctx, "Refusing access to private directory while errors are present!") - return nil, 0, dokan.ErrAccessDenied - } return f.root.private.open(ctx, oc, ps[1:]) case strings.ToUpper(TeamName) == ps[0]: oc.isUppercasePath = true fallthrough case TeamName == ps[0]: - // Refuse team directories while we are in a error state. - if f.remoteStatus.ExtraFileName() != "" { - f.log.CWarningf(ctx, "Refusing access to team directory while errors are present!") - return nil, 0, dokan.ErrAccessDenied - } return f.root.team.open(ctx, oc, ps[1:]) } return nil, 0, dokan.ErrObjectNameNotFound @@ -674,28 +659,22 @@ func (r *Root) FindFiles(ctx context.Context, fi *dokan.FileInfo, ignored string var ns dokan.NamedStat var err error ns.FileAttributes = dokan.FileAttributeDirectory - ename, esize := r.private.fs.remoteStatus.ExtraFileNameAndSize() - switch ename { - case "": - ns.Name = PrivateName - err = callback(&ns) - if err != nil { - return err - } - ns.Name = TeamName - err = callback(&ns) - if err != nil { - return err - } - fallthrough - case libfs.HumanNoLoginFileName: - ns.Name = PublicName - err = callback(&ns) - if err != nil { - return err - } + ns.Name = PrivateName + err = callback(&ns) + if err != nil { + return err + } + ns.Name = TeamName + err = callback(&ns) + if err != nil { + return err + } + ns.Name = PublicName + err = callback(&ns) + if err != nil { + return err } - if ename != "" { + if ename, esize := r.private.fs.remoteStatus.ExtraFileNameAndSize(); ename != "" { ns.Name = ename ns.FileAttributes = dokan.FileAttributeNormal ns.FileSize = esize
libdokan offline (#<I>) * Allow more offline operations with libdokan * libdokan: Simplify offline/error state logic even more
keybase_client
train
66cba56d82e40d6c6808217dfe354da21e78a82d
diff --git a/pyamg/relaxation/relaxation.py b/pyamg/relaxation/relaxation.py index <HASH>..<HASH> 100644 --- a/pyamg/relaxation/relaxation.py +++ b/pyamg/relaxation/relaxation.py @@ -240,7 +240,9 @@ def schwarz(A, x, b, iterations=1, subdomain=None, subdomain_ptr=None, >>> residuals=[] >>> x = sa.solve(b, x0=x0, tol=1e-8, residuals=residuals) """ + A, x, b = make_system(A, x, b, formats=['csr']) + A.sort_indices() if subdomain is None and inv_subblock is not None: raise ValueError("inv_subblock must be None if subdomain is None") diff --git a/pyamg/relaxation/smoothing.py b/pyamg/relaxation/smoothing.py index <HASH>..<HASH> 100644 --- a/pyamg/relaxation/smoothing.py +++ b/pyamg/relaxation/smoothing.py @@ -462,12 +462,13 @@ def setup_schwarz(lvl, iterations=DEFAULT_NITER, subdomain=None, subdomain_ptr=N inv_subblock=None, inv_subblock_ptr=None, sweep=DEFAULT_SWEEP): matrix_asformat(lvl, 'A', 'csr') + lvl.Acsr.sort_indices() subdomain, subdomain_ptr, inv_subblock, inv_subblock_ptr = \ relaxation.schwarz_parameters(lvl.Acsr, subdomain, subdomain_ptr, inv_subblock, inv_subblock_ptr) def smoother(A, x, b): - relaxation.schwarz(A, x, b, iterations=iterations, subdomain=subdomain, + relaxation.schwarz(lvl.Acsr, x, b, iterations=iterations, subdomain=subdomain, subdomain_ptr=subdomain_ptr, inv_subblock=inv_subblock, inv_subblock_ptr=inv_subblock_ptr, sweep=sweep) @@ -482,6 +483,7 @@ def setup_strength_based_schwarz(lvl, iterations=DEFAULT_NITER, sweep=DEFAULT_SW else: C = lvl.C.tocsr() + C.sort_indices() subdomain_ptr = C.indptr.copy() subdomain = C.indices.copy()
Ben Southworth reported a bug in Schwarz when the indices are not sorted. I believe this will ensure that Schwarz is always called with a sorted matrix.
pyamg_pyamg
train
1f353376c0bf70bebe183cf285b6ad96286d7fb9
diff --git a/python_modules/dagster/dagster_tests/core_tests/launcher_tests/test_persistent_grpc_run_launcher.py b/python_modules/dagster/dagster_tests/core_tests/launcher_tests/test_persistent_grpc_run_launcher.py index <HASH>..<HASH> 100644 --- a/python_modules/dagster/dagster_tests/core_tests/launcher_tests/test_persistent_grpc_run_launcher.py +++ b/python_modules/dagster/dagster_tests/core_tests/launcher_tests/test_persistent_grpc_run_launcher.py @@ -12,6 +12,7 @@ from dagster.core.host_representation.repository_location import GrpcServerRepos from dagster.core.instance import DagsterInstance from dagster.core.launcher.grpc_run_launcher import GrpcRunLauncher from dagster.core.storage.pipeline_run import PipelineRunStatus +from dagster.core.storage.tags import GRPC_INFO_TAG from dagster.core.test_utils import ( instance_for_test, poll_for_event, @@ -20,6 +21,7 @@ from dagster.core.test_utils import ( ) from dagster.core.types.loadable_target_origin import LoadableTargetOrigin from dagster.grpc.server import GrpcServerProcess +from dagster.utils import find_free_port, merge_dicts @solid @@ -524,7 +526,7 @@ def test_server_down(): recon_repo = ReconstructableRepository.from_legacy_repository_yaml(repo_yaml) loadable_target_origin = recon_repo.get_origin().loadable_target_origin server_process = GrpcServerProcess( - loadable_target_origin=loadable_target_origin, max_workers=4 + loadable_target_origin=loadable_target_origin, max_workers=4, force_port=True ) with server_process.create_ephemeral_client() as api_client: @@ -553,10 +555,24 @@ def test_server_down(): assert launcher.can_terminate(pipeline_run.run_id) - server_process.server_process.kill() + original_run_tags = instance.get_run_by_id(pipeline_run.run_id).tags[GRPC_INFO_TAG] + + # Replace run tags with an invalid port + instance.add_run_tags( + pipeline_run.run_id, + { + GRPC_INFO_TAG: seven.json.dumps( + merge_dicts({"host": "localhost"}, {"port": find_free_port()}) + ) + }, + ) - assert not launcher.can_terminate(pipeline_run.run_id) + assert not launcher.can_terminate(pipeline_run.run_id) + + instance.add_run_tags( + pipeline_run.run_id, {GRPC_INFO_TAG: original_run_tags,}, + ) - instance.report_run_failed(pipeline_run) + assert launcher.terminate(pipeline_run.run_id) server_process.wait()
Fix Flaky gRPC server down test Summary: Rather than SIGKILLing the server process to test it going down, which breaks tests in various ways, simulate the server being down by pointing the run at an entirely different port. Test Plan: BK + Azure Reviewers: sashank, alangenfeld, max Reviewed By: sashank Differential Revision: <URL>
dagster-io_dagster
train
c3b5750667546ec2a322f885676ed6fa95ac048f
diff --git a/gulpfile.js b/gulpfile.js index <HASH>..<HASH> 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -115,7 +115,7 @@ gulp.task('karma-sauce', ['build', 'start-sauce-connect'], function(callback) { 'internet explorer': '10..11' }, 'Windows 10': { - 'internet explorer': '13' + 'MicrosoftEdge': '13' }, 'OS X 10.10': { 'chrome': '43..44',
IE to Edge browser name on sauce labs is MicrosoftEdge not internet explorer anymore...
angular-ui_ui-mask
train
730c62e8e5d6f951c2114cc9c633edd60a131167
diff --git a/lib/compiler.js b/lib/compiler.js index <HASH>..<HASH> 100644 --- a/lib/compiler.js +++ b/lib/compiler.js @@ -41,8 +41,8 @@ function extractMetadata(file, type) { if (Utils.isHTML(type)) { // Currently leaving out the PARAM directive (until better planned) directives = { - "COOKIES" : "object", "QUERY" : "query", + "COOKIE" : "object", "SESSION" : "object", "CACHE" : "boolean" };
Change "COOKIES" directive to "COOKIE" (to align with res.cookie in Express)
shippjs_shipp-server
train
104bd418b9ebe905213ffa0c7a492a08e4713149
diff --git a/src/helper.js b/src/helper.js index <HASH>..<HASH> 100644 --- a/src/helper.js +++ b/src/helper.js @@ -1,9 +1,11 @@ import * as zrUtil from 'zrender/src/core/util'; import createListFromArray from './chart/helper/createListFromArray'; -import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge'; +// import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge'; import * as axisHelper from './coord/axisHelper'; import axisModelCommonMixin from './coord/axisModelCommonMixin'; import Model from './model/Model'; +import {getLayoutRect} from '../util/layout'; + /** * Create a muti dimension List structure from seriesModel. @@ -14,11 +16,13 @@ export function createList(seriesModel) { return createListFromArray(seriesModel.getSource(), seriesModel); } -export function createGraph(seriesModel) { - var nodes = seriesModel.get('data'); - var links = seriesModel.get('links'); - return createGraphFromNodeEdge(nodes, links, seriesModel); -} +// export function createGraph(seriesModel) { +// var nodes = seriesModel.get('data'); +// var links = seriesModel.get('links'); +// return createGraphFromNodeEdge(nodes, links, seriesModel); +// } + +export {getLayoutRect}; /** * // TODO: @deprecated
expose getLayoutRect temporarily. And remove createGraph temporarily.
apache_incubator-echarts
train
b241a5027f99d38deb4bb1feabbcd54bc2189af8
diff --git a/hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/JobExecutionService.java b/hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/JobExecutionService.java index <HASH>..<HASH> 100644 --- a/hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/JobExecutionService.java +++ b/hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/JobExecutionService.java @@ -35,17 +35,19 @@ import com.hazelcast.spi.impl.NodeEngineImpl; import java.security.AccessController; import java.security.PrivilegedAction; -import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.Supplier; +import static com.hazelcast.jet.function.DistributedFunctions.entryKey; +import static com.hazelcast.jet.function.DistributedFunctions.entryValue; import static com.hazelcast.jet.impl.util.ExceptionUtil.withTryCatch; import static com.hazelcast.jet.impl.util.Util.idToString; import static com.hazelcast.jet.impl.util.Util.jobAndExecutionId; import static java.util.Collections.newSetFromMap; +import static java.util.stream.Collectors.toMap; import static java.util.stream.Collectors.toSet; public class JobExecutionService { @@ -79,8 +81,10 @@ public class JobExecutionService { return executionContexts.get(executionId); } - Map<Long, ExecutionContext> getExecutionContexts() { - return new HashMap<>(executionContexts); + Map<Long, ExecutionContext> getExecutionContextsFor(Address member) { + return executionContexts.entrySet().stream() + .filter(entry -> entry.getValue().hasParticipant(member)) + .collect(toMap(entryKey(), entryValue())); } Map<Integer, Map<Integer, Map<Address, SenderTasklet>>> getSenderMap(long executionId) { diff --git a/hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/Networking.java b/hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/Networking.java index <HASH>..<HASH> 100644 --- a/hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/Networking.java +++ b/hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/Networking.java @@ -114,12 +114,9 @@ public class Networking { private byte[] createFlowControlPacket(Address member) throws IOException { try (BufferObjectDataOutput out = createObjectDataOutput(nodeEngine)) { final boolean[] hasData = {false}; - Map<Long, ExecutionContext> executionContexts = jobExecutionService.getExecutionContexts(); + Map<Long, ExecutionContext> executionContexts = jobExecutionService.getExecutionContextsFor(member); out.writeInt(executionContexts.size()); executionContexts.forEach((execId, exeCtx) -> uncheckRun(() -> { - if (!exeCtx.hasParticipant(member)) { - return; - } out.writeLong(execId); out.writeInt(exeCtx.receiverMap().values().stream().mapToInt(Map::size).sum()); exeCtx.receiverMap().forEach((vertexId, ordinalToSenderToTasklet) ->
Fix incorrect flow control packet (#<I>) Fixes #<I>
hazelcast_hazelcast
train
189a265c71298fa40efc42ea0e7268373661449b
diff --git a/main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/outline/SARLOutlineTreeProvider.java b/main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/outline/SARLOutlineTreeProvider.java index <HASH>..<HASH> 100644 --- a/main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/outline/SARLOutlineTreeProvider.java +++ b/main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/outline/SARLOutlineTreeProvider.java @@ -27,7 +27,10 @@ import com.google.common.base.Objects; import com.google.common.base.Strings; import com.google.inject.Inject; import org.eclipse.emf.ecore.EObject; +import org.eclipse.jdt.internal.ui.viewsupport.ColoringLabelProvider; +import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider; import org.eclipse.jface.viewers.ILabelDecorator; +import org.eclipse.jface.viewers.StyledString; import org.eclipse.swt.graphics.Image; import org.eclipse.xtend.core.xtend.XtendClass; import org.eclipse.xtend.core.xtend.XtendMember; @@ -458,4 +461,18 @@ public class SARLOutlineTreeProvider extends XbaseWithAnnotationsOutlineTreeProv return this.diagnoticDecorator.decorateImage(img, modelElement); } + /** Compute the text for the given JVM constructor, which is usually a inherited constructor. + * + * @param modelElement the model + * @return the text. + */ + protected CharSequence _text(JvmConstructor modelElement) { + if (this.labelProvider instanceof IStyledLabelProvider) { + final StyledString str = ((IStyledLabelProvider) this.labelProvider).getStyledText(modelElement); + str.setStyle(0, str.length(), ColoringLabelProvider.INHERITED_STYLER); + return str; + } + return this.labelProvider.getText(modelElement); + } + }
[ui] Colorized into the outline the inherited constructors with the "ingerited member" color.
sarl_sarl
train
cca52c0f7f34e93cf30b969f15d727deca6c9eab
diff --git a/selenium_test/environment.py b/selenium_test/environment.py index <HASH>..<HASH> 100644 --- a/selenium_test/environment.py +++ b/selenium_test/environment.py @@ -171,8 +171,6 @@ def before_all(context): context.tunnel = None context.sc_tunnel_tempdir = None - setup_screenshots(context) - context.selenium_quit = os.environ.get("SELENIUM_QUIT") userdata = context.config.userdata context.builder = builder = Builder(conf_path, userdata) @@ -182,6 +180,8 @@ def before_all(context): if userdata.get("check_selenium_config", False): exit(0) + setup_screenshots(context) + browser_to_tag_value = { "INTERNETEXPLORER": "ie", "CHROME": "ch", @@ -374,9 +374,8 @@ def before_step(context, step): if context.behave_captions: # We send a comment as a "script" so that we get something # in the record of Selenium commands. - context.driver.execute_script("// STEP: " + step.keyword + " " - + step.name + - "\n") + context.driver.execute_script("// STEP: " + step.keyword + " " + + step.name + "\n") if context.behave_wait: time.sleep(context.behave_wait) @@ -385,8 +384,8 @@ def after_step(context, step): driver = context.driver if step.status == "failed": name = os.path.join(context.screenshots_dir_path, - slugify(context.scenario.name + "_" - + step.name) + ".png") + slugify(context.scenario.name + "_" + + step.name) + ".png") driver.save_screenshot(name) print("") print("Captured screenshot:", name)
Don't setup screenshots before parameter check. If check_selenium_config was turned on, it would still create the directory for the screenshots, needlessly.
mangalam-research_wed
train
8b440dd79c4630dd84fb3aaac7e339f256a6d0c0
diff --git a/src/main/java/com/zaxxer/hikari/HikariPool.java b/src/main/java/com/zaxxer/hikari/HikariPool.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/zaxxer/hikari/HikariPool.java +++ b/src/main/java/com/zaxxer/hikari/HikariPool.java @@ -325,20 +325,19 @@ public final class HikariPool implements HikariPoolMBean try { Connection connection = dataSource.getConnection(); - IHikariConnectionProxy proxyConnection = (IHikariConnectionProxy) ProxyFactory.getProxyConnection(this, connection); - + + connection.setAutoCommit(isAutoCommit); if (transactionIsolation < 0) { transactionIsolation = connection.getTransactionIsolation(); } - - boolean alive = isConnectionAlive(proxyConnection, configuration.getConnectionTimeout()); - if (!alive) + else { - // This will be caught below... - throw new RuntimeException("Connection not alive, retry."); + connection.setTransactionIsolation(transactionIsolation); } + IHikariConnectionProxy proxyConnection = (IHikariConnectionProxy) ProxyFactory.getProxyConnection(this, connection, transactionIsolation); + String initSql = configuration.getConnectionInitSql(); if (initSql != null && initSql.length() > 0) { diff --git a/src/main/java/com/zaxxer/hikari/proxy/ConnectionProxy.java b/src/main/java/com/zaxxer/hikari/proxy/ConnectionProxy.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/zaxxer/hikari/proxy/ConnectionProxy.java +++ b/src/main/java/com/zaxxer/hikari/proxy/ConnectionProxy.java @@ -46,6 +46,7 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy private boolean isClosed; private boolean forceClose; private boolean isTransactionIsolationDirty; + private int currentIsolationLevel; private final long creationTime; private volatile long lastAccess; @@ -64,14 +65,14 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy SQL_ERRORS.add("01002"); // SQL92 disconnect error } - protected ConnectionProxy(HikariPool pool, Connection connection) + protected ConnectionProxy(HikariPool pool, Connection connection, int defaultIsolationLevel) { this.parentPool = pool; this.delegate = connection; + this.currentIsolationLevel = defaultIsolationLevel; creationTime = lastAccess = System.currentTimeMillis(); openStatements = new FastStatementList(); - isTransactionIsolationDirty = true; } public final void unregisterStatement(Object statement) @@ -418,7 +419,8 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy try { delegate.setTransactionIsolation(level); - isTransactionIsolationDirty = true; + isTransactionIsolationDirty |= (currentIsolationLevel == level); + currentIsolationLevel = level; } catch (SQLException e) { diff --git a/src/main/java/com/zaxxer/hikari/proxy/ProxyFactory.java b/src/main/java/com/zaxxer/hikari/proxy/ProxyFactory.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/zaxxer/hikari/proxy/ProxyFactory.java +++ b/src/main/java/com/zaxxer/hikari/proxy/ProxyFactory.java @@ -31,7 +31,7 @@ import com.zaxxer.hikari.HikariPool; */ public final class ProxyFactory { - public static Connection getProxyConnection(HikariPool pool, Connection connection) + public static Connection getProxyConnection(HikariPool pool, Connection connection, int defaultIsolationLevel) { // Body is injected by JavassistProxyFactory return null;
Track current transaction isolation level so that we can reset it only when necessary (as it often requires a round trip to the server).
brettwooldridge_HikariCP
train
e84c81c43860269ab55a5b62b32398eab4211b41
diff --git a/simulator/src/main/java/com/hazelcast/simulator/worker/tasks/AbstractWorker.java b/simulator/src/main/java/com/hazelcast/simulator/worker/tasks/AbstractWorker.java index <HASH>..<HASH> 100644 --- a/simulator/src/main/java/com/hazelcast/simulator/worker/tasks/AbstractWorker.java +++ b/simulator/src/main/java/com/hazelcast/simulator/worker/tasks/AbstractWorker.java @@ -35,7 +35,7 @@ public abstract class AbstractWorker<O extends Enum<O>> implements IWorker { // local variables long iteration; - boolean isWorkerStopped = false; + boolean isWorkerStopped; public AbstractWorker(OperationSelectorBuilder<O> operationSelectorBuilder) { this.selector = operationSelectorBuilder.build();
Removed default value from boolean in AbstractWorker (CheckStyle issue).
hazelcast_hazelcast-simulator
train
f48b621d8c58181cfce644fa1d9fdfb9eb2d1da4
diff --git a/archunit/src/main/java/com/tngtech/archunit/core/PluginLoader.java b/archunit/src/main/java/com/tngtech/archunit/core/PluginLoader.java index <HASH>..<HASH> 100644 --- a/archunit/src/main/java/com/tngtech/archunit/core/PluginLoader.java +++ b/archunit/src/main/java/com/tngtech/archunit/core/PluginLoader.java @@ -150,7 +150,7 @@ public class PluginLoader<T> { }; private static final Ordering<JavaVersion> FROM_NEWEST_TO_OLDEST_ORDERING = Ordering.explicit(JAVA_9); - private static final Pattern VERSION_PATTERN = Pattern.compile("([^.-]+).*"); + private static final Pattern VERSION_PATTERN = Pattern.compile("^(\\d+).*"); public abstract boolean isLessOrEqualThan(String version);
It is probably more resilient if we just look for any consecutive group of numbers at the start of the string, then if matcher.matches(..) Integer.parseInt(..) should at least always work.
TNG_ArchUnit
train
cd9bc032617dc7cf1a2d69ffacb7019943e59250
diff --git a/findiff/coefs.py b/findiff/coefs.py index <HASH>..<HASH> 100644 --- a/findiff/coefs.py +++ b/findiff/coefs.py @@ -25,19 +25,12 @@ def coefficients(deriv, acc): ret = {} - num_central = 2 * math.floor((deriv + 1) / 2) - 1 + acc - num_side = num_central // 2 - # Determine central coefficients - matrix = _build_matrix(num_side, num_side, deriv) - - rhs = _build_rhs(num_side, num_side, deriv) + num_central = 2 * math.floor((deriv + 1) / 2) - 1 + acc + num_side = num_central // 2 - ret["center"] = { - "coefficients": np.linalg.solve(matrix, rhs), - "offsets": np.array([p for p in range(-num_side, num_side+1)]) - } + ret["center"] = _calc_coef(num_side, num_side, deriv) # Determine forward coefficients @@ -46,28 +39,26 @@ def coefficients(deriv, acc): else: num_coef = num_central - matrix = _build_matrix(0, num_coef - 1, deriv) + ret["forward"] = _calc_coef(0, num_coef - 1, deriv) - rhs = _build_rhs(0, num_coef - 1, deriv) + # Determine backward coefficients - ret["forward"] = { - "coefficients": np.linalg.solve(matrix, rhs), - "offsets": np.array([p for p in range(num_coef)]) - } + ret["backward"] = _calc_coef(num_coef - 1, 0, deriv) - # Determine backward coefficients + return ret - matrix = _build_matrix(num_coef - 1, 0, deriv) - rhs = _build_rhs(num_coef - 1, 0, deriv) +def _calc_coef(left, right, deriv): - ret["backward"] = { + matrix = _build_matrix(left, right, deriv) + + rhs = _build_rhs(left, right, deriv) + + return { "coefficients": np.linalg.solve(matrix, rhs), - "offsets": np.array([p for p in range(-num_coef+1, 1)]) + "offsets": np.array([p for p in range(-left, right+1)]) } - return ret - def coefficients_non_uni(deriv, acc, coords, idx): """
Minor refactoring of coefficient calculation.
maroba_findiff
train
70693109f769d755ba42c0deb98e06f79bf31559
diff --git a/library/CM/FormField/Date.php b/library/CM/FormField/Date.php index <HASH>..<HASH> 100755 --- a/library/CM/FormField/Date.php +++ b/library/CM/FormField/Date.php @@ -2,6 +2,9 @@ class CM_FormField_Date extends CM_FormField_Abstract { + /** @var DateTimeZone|null */ + protected $_timeZone; + /** @var int */ protected $_yearFirst; @@ -9,6 +12,7 @@ class CM_FormField_Date extends CM_FormField_Abstract { protected $_yearLast; protected function _initialize() { + $this->_timeZone = $this->_params->has('timeZone') ? $this->_params->getDateTimeZone('timeZone') : null; $this->_yearFirst = $this->_params->getInt('yearFirst', date('Y') - 100); $this->_yearLast = $this->_params->getInt('yearLast', date('Y')); parent::_initialize(); @@ -19,7 +23,7 @@ class CM_FormField_Date extends CM_FormField_Abstract { $mm = (int) trim($userInput['month']); $yy = (int) trim($userInput['year']); - return new DateTime($yy . '-' . $mm . '-' . $dd, $environment->getTimeZone()); + return new DateTime($yy . '-' . $mm . '-' . $dd, $this->_getTimeZone($environment)); } public function prepare(CM_Params $renderParams, CM_Frontend_Environment $environment, CM_Frontend_ViewResponse $viewResponse) { @@ -37,7 +41,7 @@ class CM_FormField_Date extends CM_FormField_Abstract { $value = $this->getValue(); $year = $month = $day = null; if (null !== $value) { - $value->setTimezone($environment->getTimeZone()); + $value->setTimezone($this->_getTimeZone($environment)); $year = $value->format('Y'); $month = $value->format('n'); $day = $value->format('j'); @@ -51,4 +55,15 @@ class CM_FormField_Date extends CM_FormField_Abstract { public function isEmpty($userInput) { return empty($userInput['day']) || empty($userInput['month']) || empty($userInput['year']); } + + /** + * @param CM_Frontend_Environment $environment + * @return DateTimeZone + */ + protected function _getTimeZone(CM_Frontend_Environment $environment) { + if (null === $this->_timeZone) { + return $environment->getTimeZone(); + } + return $this->_timeZone; + } } diff --git a/library/CM/FormField/DateTimeInterval.php b/library/CM/FormField/DateTimeInterval.php index <HASH>..<HASH> 100755 --- a/library/CM/FormField/DateTimeInterval.php +++ b/library/CM/FormField/DateTimeInterval.php @@ -2,6 +2,9 @@ class CM_FormField_DateTimeInterval extends CM_FormField_Abstract { + /** @var DateTimeZone|null */ + protected $_timeZone; + /** @var int */ protected $_yearFirst; @@ -9,6 +12,7 @@ class CM_FormField_DateTimeInterval extends CM_FormField_Abstract { protected $_yearLast; protected function _initialize() { + $this->_timeZone = $this->_params->has('timeZone') ? $this->_params->getDateTimeZone('timeZone') : null; $this->_yearFirst = $this->_params->getInt('yearFirst', date('Y') - 100); $this->_yearLast = $this->_params->getInt('yearLast', date('Y')); parent::_initialize(); @@ -21,7 +25,7 @@ class CM_FormField_DateTimeInterval extends CM_FormField_Abstract { $start = trim($userInput['start']); $end = trim($userInput['end']); - $base = new DateTime($yy . '-' . $mm . '-' . $dd, $environment->getTimeZone()); + $base = new DateTime($yy . '-' . $mm . '-' . $dd, $this->_getTimeZone($environment)); $from = clone $base; $from->add($this->_processTime($start)); $until = clone $base; @@ -47,7 +51,7 @@ class CM_FormField_DateTimeInterval extends CM_FormField_Abstract { $value = $this->getValue(); $year = $month = $day = null; if (null !== $value) { - $value->setTimezone($environment->getTimeZone()); + $value->setTimezone($this->_getTimeZone($environment)); $year = $value->format('Y'); $month = $value->format('n'); $day = $value->format('j'); @@ -80,4 +84,15 @@ class CM_FormField_DateTimeInterval extends CM_FormField_Abstract { } return new DateInterval('PT' . $hour . 'H' . $minute . 'M'); } + + /** + * @param CM_Frontend_Environment $environment + * @return DateTimeZone + */ + protected function _getTimeZone(CM_Frontend_Environment $environment) { + if (null === $this->_timeZone) { + return $environment->getTimeZone(); + } + return $this->_timeZone; + } }
Allow to pass timeZone to date related form fields
cargomedia_cm
train
fe243e1dfa0edf3cfffdf4cdfd9ef26212d9be7c
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -260,7 +260,7 @@ Client.prototype.downloadFile = function(params) { * - recursive: false * - s3Params: * - Bucket: params.s3Params.Bucket, - * - Delimiter: '/', + * - Delimiter: null, * - EncodingType: 'url', * - Marker: null, * - MaxKeys: null, @@ -432,7 +432,6 @@ function syncDir(self, params, directionIsToS3) { recursive: true, s3Params: { Bucket: bucket, - Delimiter: '/', EncodingType: 'url', Marker: null, MaxKeys: null, diff --git a/test/test.js b/test/test.js index <HASH>..<HASH> 100644 --- a/test/test.js +++ b/test/test.js @@ -309,7 +309,6 @@ describe("s3", function () { }); }); - it("take advantage of not setting a delimiter when calling listObjects"); it("downloadDir with deleteRemoved should delete local folders"); });
uploadDir/downloadDir: don't set Delimiter
andrewrk_node-s3-client
train
5332fa9cd22298cc24464e1c1eaca932608291df
diff --git a/cake/libs/view/helpers/form.php b/cake/libs/view/helpers/form.php index <HASH>..<HASH> 100644 --- a/cake/libs/view/helpers/form.php +++ b/cake/libs/view/helpers/form.php @@ -795,7 +795,6 @@ class FormHelper extends AppHelper { } $this->setFormTag($fieldName); - $this->__secure(); $attributes = $this->domId((array)$attributes); if ($this->tagIsInvalid()) { @@ -822,6 +821,7 @@ class FormHelper extends AppHelper { $tag = $this->Html->tags['selectmultiplestart']; } else { $tag = $this->Html->tags['selectstart']; + $this->__secure(); } $select[] = sprintf($tag, $this->model(), $this->field(), $this->Html->_parseAttributes($attributes));
Adding fix to allow empty multiple select when using the Security component. Prior to this fix a form would be considered invalid if nothing was selected. git-svn-id: <URL>
cakephp_cakephp
train
3378b0494288e8c1cb9e318854944e67d45cdccb
diff --git a/java/server/test/org/openqa/selenium/remote/server/DefaultSessionTest.java b/java/server/test/org/openqa/selenium/remote/server/DefaultSessionTest.java index <HASH>..<HASH> 100644 --- a/java/server/test/org/openqa/selenium/remote/server/DefaultSessionTest.java +++ b/java/server/test/org/openqa/selenium/remote/server/DefaultSessionTest.java @@ -39,6 +39,7 @@ public class DefaultSessionTest extends MockTestBase { checking(new Expectations() {{ oneOf(tempFs).deleteTemporaryFiles(); + oneOf(tempFs).deleteBaseDir(); }}); Session session = DefaultSession.createSession(factory, tempFs, null, DesiredCapabilities.firefox());
EranMes on behalf of EmmaSoderberg: Updating expectations in a broken test. r<I>
SeleniumHQ_selenium
train
d379c776bff41e5ad17452c6d2454240e1acd575
diff --git a/core/modules/requestsMonitor/requestsMonitor.js b/core/modules/requestsMonitor/requestsMonitor.js index <HASH>..<HASH> 100644 --- a/core/modules/requestsMonitor/requestsMonitor.js +++ b/core/modules/requestsMonitor/requestsMonitor.js @@ -12,7 +12,7 @@ exports.module = function(phantomas) { var mainRequestUrl = ''; // register metric - phantomas.setMetric('mainRequestStatusCodes', new Array(), true); // @desc the HTTP status code of the main request (after following all redirects, etc) + phantomas.setMetric('mainRequestStatusCodesTrail', new Array(), true); // @desc the HTTP status code of the main request (after following all redirects, etc) phantomas.setMetric('requests'); // @desc total number of HTTP requests made phantomas.setMetric('gzipRequests'); // @desc number of gzipped HTTP responses @unreliable phantomas.setMetric('postRequests'); // @desc number of POST requests @@ -292,7 +292,7 @@ exports.module = function(phantomas) { phantomas.on('recv', function(entry, res) { // Sometimes these URLs differ (for example, trailing slash) so accounting for it here if (res.url.indexOf(mainRequestUrl) == 0 || mainRequestUrl.indexOf(res.url) == 0) { - phantomas.getMetric('mainRequestStatusCodes').push(res.status); + phantomas.getMetric('mainRequestStatusCodesTrail').push(res.status); if (entry.isRedirect === true) { mainRequestUrl = res.redirectURL; }
Renamed the metric to be more self-descriptive
macbre_phantomas
train
61427616d9080622d246b06cea7b74d5f2aad645
diff --git a/src/java/voldemort/server/protocol/vold/VoldemortNativeRequestHandler.java b/src/java/voldemort/server/protocol/vold/VoldemortNativeRequestHandler.java index <HASH>..<HASH> 100644 --- a/src/java/voldemort/server/protocol/vold/VoldemortNativeRequestHandler.java +++ b/src/java/voldemort/server/protocol/vold/VoldemortNativeRequestHandler.java @@ -8,6 +8,8 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import org.apache.log4j.Logger; + import voldemort.VoldemortException; import voldemort.serialization.VoldemortOpCode; import voldemort.server.StoreRepository; @@ -29,6 +31,8 @@ import voldemort.versioning.Versioned; */ public class VoldemortNativeRequestHandler extends AbstractRequestHandler implements RequestHandler { + private final Logger logger = Logger.getLogger(VoldemortNativeRequestHandler.class); + private final int protocolVersion; public VoldemortNativeRequestHandler(ErrorCodeMapper errorMapper, @@ -72,18 +76,23 @@ public class VoldemortNativeRequestHandler extends AbstractRequestHandler implem outputStream.flush(); } + /** + * This is pretty ugly. We end up mimicking the request logic here, so this + * needs to stay in sync with handleRequest. + */ + public boolean isCompleteRequest(final ByteBuffer buffer) { DataInputStream inputStream = new DataInputStream(new ByteBufferBackedInputStream(buffer)); try { - byte opCode = buffer.get(); + byte opCode = inputStream.readByte(); // Read the store name in, but just to skip the bytes. inputStream.readUTF(); // Read the 'is routed' flag in, but just to skip the byte. if(protocolVersion > 0) - buffer.get(); + inputStream.readBoolean(); switch(opCode) { case VoldemortOpCode.GET_OP_CODE: @@ -123,7 +132,14 @@ public class VoldemortNativeRequestHandler extends AbstractRequestHandler implem // If there aren't any remaining, we've "consumed" all the bytes and // thus have a complete request... return !buffer.hasRemaining(); - } catch(Throwable t) { + } catch(Exception e) { + // This could also occur if the various methods we call into + // re-throw a corrupted value error as some other type of exception. + // For example, updating the position on a buffer past its limit + // throws an InvalidArgumentException. + if(logger.isDebugEnabled()) + logger.debug("Probable partial read occurred causing exception", e); + return false; } }
Added comments and exception handling clean up for isCompleteRequest.
voldemort_voldemort
train
3bd6cf4d04a49ba9c03e4a3b7a657b95e0b42141
diff --git a/gwpy/io/nds.py b/gwpy/io/nds.py index <HASH>..<HASH> 100644 --- a/gwpy/io/nds.py +++ b/gwpy/io/nds.py @@ -20,6 +20,7 @@ to LIGO data. """ +import os import sys import warnings @@ -84,11 +85,38 @@ class NDSWarning(UserWarning): warnings.simplefilter('always', NDSWarning) -def host_resolution_order(ifo): +def host_resolution_order(ifo, env='NDSSERVER'): + """Generate a logical ordering of NDS (host, port) tuples for this IFO + + Parameters + ---------- + ifo : `str` + prefix for IFO of interest + env : `str`, optional + environment variable name to use for server order, + default ``'NDSSERVER'`` + + Returns + ------- + hro : `list` of `2-tuples <tuple>` + `list` of ``(host, port)`` tuples + """ hosts = [] - if ifo in DEFAULT_HOSTS: - hosts.append(DEFAULT_HOSTS[ifo]) - for difo, hp in DEFAULT_HOSTS.iteritems(): - if difo != ifo and hp not in hosts: - hosts.append(hp) + # if NDSSERVER environment variable exists, it will contain a + # comma-separated list of host:port strings giving the logical ordering + if env and os.getenv('NDSSERVER'): + for host in os.getenv('NDSSERVER').split(','): + try: + host, port = host.rsplit(':', 1) + except ValueError: + port = None + else: + port = int(port) + if (host, port) not in hosts: + hosts.append((host, port)) + # otherwise, return the server for this IFO and the backup at CIT + else: + for difo in [ifo, None]: + if difo in DEFAULT_HOSTS: + hosts.append(DEFAULT_HOSTS[difo]) return hosts
io.nds.host_resolution_order: use $NDSSERVER - CDS@LLO uses NDSSERVER env variable for host ordering, so we should use that, if it exists - this method now doesn't return the NDS server for the other IFO, i.e. an L1 search wont return the ligo-wa server
gwpy_gwpy
train
9e77ca35b3e3faec0a826345dd6326946b8f5079
diff --git a/fritzconnection/core/logger.py b/fritzconnection/core/logger.py index <HASH>..<HASH> 100644 --- a/fritzconnection/core/logger.py +++ b/fritzconnection/core/logger.py @@ -13,14 +13,26 @@ that can get imported by: >>> from fritzconnection.core.logger import fritzlogger -The fritzlogger instance is preset to logging.NOTSET. To do some logging, the logger must get enabled and a handler should be provided: +The fritzlogger instance is preset to logging.NOTSET. To do some +logging, the logger must get enabled and a handler should be provided: ->>> fritzlogger.enable() ->>> fritzlogger.add_handler(the_handler) +>>> fritzlogger.add_handler(<the_handler>) +>>> fritzlogger.enable(<the_loglevel>, <propagate_flag>) >>> fritzlogger.log("the message") # will get logged now For convenience fritzlogger provides the methods `set_streamhandler` and -`set_filehandler` to add predefined handlers. +`set_filehandler` to add predefined handlers and `log_debug` to emit a +message on debug-level. Example to track the data exchanged with the +router: + +>>> fritzlogger.set_filehandler(<the_filename>) +>>> fritzlogger.enable() +>>> fritzlogger.log_debug("the message") + +If `enable` gets called with the log-level DEBUG and the argument +`propagate` set to True, the data to and from the router will also get +forwarded to the parent log-handlers. (Keep in mind that this can be a +lot of data.) """ import logging @@ -31,8 +43,10 @@ class FritzLogger: Wrapper for the logging library to reduce executable code on module global level. As multiple instances would use the same logger, to not get confused this class is a singleton. - Initially the logger has no log-level, is disabled and does not propagate messages to parent handlers. - Primary use of the logger is to report the data exchanged by the library and the router. + Initially the logger has no log-level, is disabled and does not + propagate messages to parent handlers. + Primary use of the logger is to report the data exchanged by the + library and the router. """ _instance = None @@ -63,12 +77,19 @@ class FritzLogger: self.logger.disabled = False def set_streamhandler(self): - """Sets the StreamHandler logging to stderr.""" - self.add_handler(logging.StreamHandler()) + """Set a StreamHandler logging to stderr on debug level.""" + handler = logging.StreamHandler() + handler.setLevel(logging.DEBUG) + self.add_handler(handler) def set_filehandler(self, filename): - """Sets the FileHandler logging to the given filename.""" - self.add_handler(logging.FileHandler(filename, encoding="utf-8")) + """ + Set a FileHandler logging on debug level to the given filename + with utf-8 encoding. + """ + handler = logging.FileHandler(filename, encoding="utf-8") + handler.setLevel(logging.DEBUG) + self.add_handler(handler) def add_handler(self, handler): """
Handlers adapted and documentation enhanced.
kbr_fritzconnection
train
409a8f8e23f6dc4baa4c72c38decabba24a75621
diff --git a/lib/active_scaffold/delayed_setup.rb b/lib/active_scaffold/delayed_setup.rb index <HASH>..<HASH> 100644 --- a/lib/active_scaffold/delayed_setup.rb +++ b/lib/active_scaffold/delayed_setup.rb @@ -11,26 +11,27 @@ module ActiveScaffold module ClassMethods def active_scaffold(model_id = nil, &block) - @delayed_mutex ||= Mutex.new - @active_scaffold_delayed = proc { super(model_id, &block) } + @delayed_monitor ||= Monitor.new + @active_scaffold_delayed = proc do + begin + unless @active_scaffold_config # avoid running again if config is set (e.g. call active_scaffold_config inside block) + @_prefixes = nil # clean prefixes in case is already cached, so our local_prefixes override is picked up + super(model_id, &block) + end + rescue StandardError + # clear config variable if failed, so next request tries again + @active_scaffold_config = nil + raise + end + end end def config_active_scaffold_delayed - # Thread variable is used to disable this method while block is being eval'ed - return if @delayed_mutex.nil? || Thread.current["#{name}_running_delayed_init"] - @delayed_mutex.synchronize do - return unless @active_scaffold_delayed - @_prefixes = nil # clean prefixes in case is already cached, so our local_prefixes override is picked up - Thread.current["#{name}_running_delayed_init"] = true - begin - @active_scaffold_delayed.call - @active_scaffold_delayed = nil # not cleared if exception is raised, try again on next request - ensure - # ensure is cleared if exception is raised, to try again on next request - Thread.current["#{name}_running_delayed_init"] = nil - end + @delayed_monitor&.synchronize do + @active_scaffold_delayed&.call + @active_scaffold_delayed = nil if @active_scaffold_config # cleared only if config was set end - @delayed_mutex = nil # cleared only when config was loaded successfully + @delayed_monitor = nil if @active_scaffold_config # cleared only when config was loaded successfully end def active_scaffold_config
fix errors when config failed in one thread, avoid creating thread variables
activescaffold_active_scaffold
train
01a205b5a3c3f6f493fe7d34a2c97fbdc5c03818
diff --git a/project_generator/tools/coide.py b/project_generator/tools/coide.py index <HASH>..<HASH> 100644 --- a/project_generator/tools/coide.py +++ b/project_generator/tools/coide.py @@ -204,13 +204,13 @@ class Coide(Tool, Exporter, Builder): logger.debug("Mcu definitions: %s" % mcu_def_dic) # correct attributes from definition, as yaml does not allowed multiple keys (=dict), we need to # do this magic. - for k, v in mcu_def_dic['Device'].items(): + for k, v in dict(mcu_def_dic['Device']).items(): del mcu_def_dic['Device'][k] mcu_def_dic['Device']['@' + k] = str(v) memory_areas = [] for k, v in mcu_def_dic['MemoryAreas'].items(): # ??? duplicate use of k - for k, att in v.items(): + for k, att in dict(v).items(): del v[k] v['@' + k] = str(att) memory_areas.append(v)
Fix iterating over a dictionary while removing elements
project-generator_project_generator
train
7ef967c4f25b8aa30a8c35ec4cd854546b4648c4
diff --git a/lib/rails_pdate/p_date.rb b/lib/rails_pdate/p_date.rb index <HASH>..<HASH> 100644 --- a/lib/rails_pdate/p_date.rb +++ b/lib/rails_pdate/p_date.rb @@ -62,19 +62,6 @@ class PDate alias_method :default_inspect, :inspect alias_method :inspect, :readable_inspect - # Converts a Date instance to a Time, where the time is set to the beginning of the day. - # The timezone can be either :local or :utc (default :local). - # - # date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007 - # - # date.to_time # => Sat Nov 10 00:00:00 0800 2007 - # date.to_time(:local) # => Sat Nov 10 00:00:00 0800 2007 - # - # date.to_time(:utc) # => Sat Nov 10 00:00:00 UTC 2007 - def to_time(form = :local) - ::Time.send(form, year, month, day) - end - def xmlschema in_time_zone.xmlschema end
Remove to_time method of PDate
mohsen-alizadeh_rails-pdate
train
03753a377bd4381e7697f54f96d5ade1115a4e4c
diff --git a/app/views/govuk_publishing_components/components/_button.html.erb b/app/views/govuk_publishing_components/components/_button.html.erb index <HASH>..<HASH> 100644 --- a/app/views/govuk_publishing_components/components/_button.html.erb +++ b/app/views/govuk_publishing_components/components/_button.html.erb @@ -3,7 +3,7 @@ <% if button.link? %> <%= link_to button.text, button.href, button.html_options %> <% else %> - <%= button_tag button.text, button.html_options %> + <%= content_tag :button, button.text, button.html_options %> <% end %> <% if button.info_text %> diff --git a/lib/govuk_publishing_components/presenters/button_helper.rb b/lib/govuk_publishing_components/presenters/button_helper.rb index <HASH>..<HASH> 100644 --- a/lib/govuk_publishing_components/presenters/button_helper.rb +++ b/lib/govuk_publishing_components/presenters/button_helper.rb @@ -24,6 +24,7 @@ module GovukPublishingComponents def html_options options = { class: css_classes } options[:role] = "button" if link? + options[:type] = "submit" unless link? options[:rel] = rel if rel options[:data] = data_attributes if data_attributes options[:title] = title if title diff --git a/spec/components/button_spec.rb b/spec/components/button_spec.rb index <HASH>..<HASH> 100644 --- a/spec/components/button_spec.rb +++ b/spec/components/button_spec.rb @@ -12,7 +12,7 @@ describe "Button", type: :view do it "renders the correct defaults" do render_component(text: "Submit") - assert_select ".govuk-button", text: "Submit" + assert_select ".govuk-button[type=submit]", text: "Submit" assert_select ".govuk-button--start", false assert_select ".gem-c-button__info-text", false end @@ -24,7 +24,7 @@ describe "Button", type: :view do it "renders start now button" do render_component(text: "Start now", href: "#", start: true) - assert_select ".govuk-button", text: "Start now", href: "#" + assert_select ".govuk-button[href='#']", text: "Start now" assert_select ".govuk-button--start" end
Use content_tag instead of button_tag for buttons When using a button to submit a GET form, the button element becomes an unwanted parameter sent to the server. The button_tag helper sets two attributes: name ('button') and type ('submit'), the former being the cause of the issue and the latter being something we can set manually.
alphagov_govuk_publishing_components
train
e892b18858225eefe20fc91ec901aa65b20fc187
diff --git a/code/modifiers/tax/FlatTaxModifier.php b/code/modifiers/tax/FlatTaxModifier.php index <HASH>..<HASH> 100644 --- a/code/modifiers/tax/FlatTaxModifier.php +++ b/code/modifiers/tax/FlatTaxModifier.php @@ -18,9 +18,9 @@ class FlatTaxModifier extends TaxModifier private static $excludedmessage = "%.1f%% %s"; - public function populateDefaults() + public function __construct($record = null, $isSingleton = false, $model = null) { - parent::populateDefaults(); + parent::__construct($record, $isSingleton, $model); $this->Type = self::config()->exclusive ? 'Chargable' : 'Ignored'; }
Setting the Type in constructor Setting the Type in the populateDefaults method was not being picked in the value/totals calculation
silvershop_silvershop-core
train
20f25faf4d096131d2654d0457c8998c13547e8d
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,8 @@ Breaking changes: necessary files yourself - `adLDAP\adLDAPException` now has a new namespace: `adLDAP\Exceptions\adLDAPException` - `$adldap->user()->modify()` now throws an `adLDAPException` when the username parameter is null +- Inserting null/empty values into the username and/or password inside the `authenticate($username, $password)` function will now +result in an `adLDAPException` ## License diff --git a/src/adLDAP/Classes/adLDAPUtils.php b/src/adLDAP/Classes/adLDAPUtils.php index <HASH>..<HASH> 100644 --- a/src/adLDAP/Classes/adLDAPUtils.php +++ b/src/adLDAP/Classes/adLDAPUtils.php @@ -2,6 +2,8 @@ namespace adLDAP\classes; +use adLDAP\Exceptions\adLDAPException; + /** * AdLDAP Utility Functions * @@ -333,4 +335,30 @@ class adLDAPUtils extends adLDAPBase return $dnArr; } + + /** + * Validates that the inserted value is not null or empty. + * + * @param string $parameter + * @param string $value + * @return bool + * @throws adLDAPException + */ + public function validateNotNullOrEmpty($parameter, $value) + { + if($value !== null && ! empty($value)) return true; + + /* + * We'll convert the value to a string to + * make sure we give the devs an explanation + * of what the value inserted was. + */ + if($value === null) $value = 'NULL'; + + if(empty($value)) $value = 'Empty'; + + $message = sprintf('Parameter: %s cannot be null or empty. You inserted: %s', $parameter, $value); + + throw new adLDAPException($message); + } } diff --git a/src/adLDAP/adLDAP.php b/src/adLDAP/adLDAP.php index <HASH>..<HASH> 100644 --- a/src/adLDAP/adLDAP.php +++ b/src/adLDAP/adLDAP.php @@ -779,9 +779,8 @@ class adLDAP */ public function authenticate($username, $password, $preventRebind = false) { - if ($username === NULL || $password === NULL) return false; - - if (empty($username) || empty($password)) return false; + $this->utilities()->validateNotNullOrEmpty('Username', $username); + $this->utilities()->validateNotNullOrEmpty('Password', $password); $remoteUser = $this->getRemoteUserInput(); $kerberos = $this->getKerberosAuthInput();
Added validateNotNullOrEmpty to util class - Authenticate method now uses new utility method validateNotNullOrEmpty to make sure of no null or empty values are being inserted
Adldap2_Adldap2
train
da50fac778b5e14cbecf98415db6ad63a506cecc
diff --git a/packages/bonde-admin-canary/src/components/PageAdmin/index.js b/packages/bonde-admin-canary/src/components/PageAdmin/index.js index <HASH>..<HASH> 100644 --- a/packages/bonde-admin-canary/src/components/PageAdmin/index.js +++ b/packages/bonde-admin-canary/src/components/PageAdmin/index.js @@ -1,4 +1,5 @@ import React from 'react' +import PropTypes from 'prop-types' import { translate } from '../../services/i18n' import { Header, Page, Footer, @@ -13,7 +14,7 @@ const DefaultNavBar = () => ( </Navbar> ) -const DefaultActionButtons = ({ t }) => [ +const DefaultActionButtons = ({ t, noActionButtons }) => noActionButtons ? [] : [ <Button dark onClick={() => alert('Button: onClick')}> {t('actionButtons.mobilization')} </Button>, @@ -22,12 +23,12 @@ const DefaultActionButtons = ({ t }) => [ </Button> ] -const PageAdmin = ({ children, t, title }) => ( +const PageAdmin = ({ children, t, title, noActionButtons }) => ( <React.Fragment> <Header pageTitle={title} navbar={DefaultNavBar} - actionButtons={DefaultActionButtons({ t })} + actionButtons={DefaultActionButtons({ t, noActionButtons })} /> <Page> @@ -48,4 +49,11 @@ const PageAdmin = ({ children, t, title }) => ( </React.Fragment> ) +const { string, bool } = PropTypes + +PageAdmin.propTypes = { + title: string, + noActionButtons: bool, +} + export default translate('components-page-admin')(PageAdmin)
chore(admin-canary): option to hide action buttons on PageAdmin
nossas_bonde-client
train
d0b2b2467a28fce34baecb070d0e7a8f78cd9475
diff --git a/server_timing_test.go b/server_timing_test.go index <HASH>..<HASH> 100644 --- a/server_timing_test.go +++ b/server_timing_test.go @@ -154,25 +154,28 @@ type fakeServerConn struct { net.TCPConn ln *fakeListener requestsCount int + pos int closed uint32 } func (c *fakeServerConn) Read(b []byte) (int, error) { nn := 0 - for len(b) > len(c.ln.request) { + reqLen := len(c.ln.request) + for len(b) > 0 { if c.requestsCount == 0 { if nn == 0 { return 0, io.EOF } return nn, nil } - n := copy(b, c.ln.request) + pos := c.pos % reqLen + n := copy(b, c.ln.request[pos:]) b = b[n:] nn += n - c.requestsCount-- - } - if nn == 0 { - panic("server has too small buffer") + c.pos += n + if n+pos == reqLen { + c.requestsCount-- + } } return nn, nil } @@ -230,6 +233,7 @@ func (ln *fakeListener) Accept() (net.Conn, error) { c := <-ln.ch c.requestsCount = requestsCount c.closed = 0 + c.pos = 0 return c, nil }
Properly handle the case when servers read data by small chunks
valyala_fasthttp
train