hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
efb5cd0e8892c9c70ff69946f2477db0a7efcfa2
diff --git a/parceler/src/main/java/org/parceler/internal/ParcelableGenerator.java b/parceler/src/main/java/org/parceler/internal/ParcelableGenerator.java index <HASH>..<HASH> 100644 --- a/parceler/src/main/java/org/parceler/internal/ParcelableGenerator.java +++ b/parceler/src/main/java/org/parceler/internal/ParcelableGenerator.java @@ -353,12 +353,12 @@ public class ParcelableGenerator { containsKeyBody._return(value); JConditional nullCondition = readMethodBody._if(parcelParam.invoke("readInt").eq(JExpr.lit(-1))); - nullCondition._then().assign(readWrapped, JExpr._null()); + JBlock nullBlock = nullCondition._then(); - nullCondition._else().assign(readWrapped, buildReadFromParcelExpression(nullCondition._else(), parcelParam, parcelableClass, type, converter, overrideGenerator, identity, identityParam).getExpression()); + nullBlock.assign(readWrapped, JExpr._null()); + nullBlock.add(identityParam.invoke("put").arg(identity).arg(JExpr._null())); - //add to identity map - readMethodBody.add(identityParam.invoke("put").arg(identity).arg(readWrapped)); + nullCondition._else().assign(readWrapped, buildReadFromParcelExpression(nullCondition._else(), parcelParam, parcelableClass, type, converter, overrideGenerator, identity, identityParam).getExpression()); readMethodBody._return(readWrapped);
Moved null value put into conditional block
johncarl81_parceler
train
24e8363b6fedfee2dcd8b414dcfd4b212e6760d6
diff --git a/lib/bitescript/asm3/bytecode.rb b/lib/bitescript/asm3/bytecode.rb index <HASH>..<HASH> 100644 --- a/lib/bitescript/asm3/bytecode.rb +++ b/lib/bitescript/asm3/bytecode.rb @@ -289,6 +289,7 @@ module BiteScript def #{const_down}(cls, name, *call_sig) MethodHandle.new(Opcodes::#{const_name}, path(cls), name, sig(*call_sig)) end + alias #{const_down[1..-1]} #{const_down} ", b, __FILE__, line OpcodeInstructions[const_name] = const_down when "F_FULL", "ACC_ENUM", "ACC_SYNTHETIC", "ACC_INTERFACE", "ACC_PUBLIC",
add aliases for h_* opcodes for asm3 support this means that h_invokestatic will work with both versions of asm, rather than having to switch between h_* and mh_* depending on what asm is on the loadpath
headius_bitescript
train
8f354a0709dfdb9cbd2160dbe494646e81a57ab0
diff --git a/state/watcher.go b/state/watcher.go index <HASH>..<HASH> 100644 --- a/state/watcher.go +++ b/state/watcher.go @@ -1454,7 +1454,6 @@ func (w *cleanupWatcher) loop() (err error) { type actionWatcher struct { commonWatcher out chan []string - filter bool filterFn func(interface{}) bool } @@ -1469,7 +1468,6 @@ func newActionWatcher(st *State, filterBy ...names.Tag) StringsWatcher { w := &actionWatcher{ commonWatcher: commonWatcher{st: st}, out: make(chan []string), - filter: len(filterBy) > 0, filterFn: makeActionWatcherFilter(filterBy...), } go func() { @@ -1481,8 +1479,12 @@ func newActionWatcher(st *State, filterBy ...names.Tag) StringsWatcher { } // makeActionWatcherFilter constructs a predicate to filter keys -// that have the prefix of one of the passed in tags +// that have the prefix of one of the passed in tags, or returns +// nil if tags is empty func makeActionWatcherFilter(tags ...names.Tag) func(interface{}) bool { + if len(tags) == 0 { + return nil + } return func(key interface{}) bool { if k, ok := key.(string); ok { for _, tag := range tags { @@ -1504,7 +1506,7 @@ func (w *actionWatcher) loop() error { in := make(chan watcher.Change) changes := &set.Strings{} - if w.filter { + if w.filterFn != nil { w.st.watcher.WatchCollectionWithFilter(w.st.actions.Name, in, w.filterFn) } else { w.st.watcher.WatchCollection(w.st.actions.Name, in)
one more refactor; simplify watcher struct
juju_juju
train
1c37da88e1254fbe9201fee9fdbd077a443ae12a
diff --git a/src/DcGeneral/Contao/View/Contao2BackendView/ContaoWidgetManager.php b/src/DcGeneral/Contao/View/Contao2BackendView/ContaoWidgetManager.php index <HASH>..<HASH> 100644 --- a/src/DcGeneral/Contao/View/Contao2BackendView/ContaoWidgetManager.php +++ b/src/DcGeneral/Contao/View/Contao2BackendView/ContaoWidgetManager.php @@ -62,6 +62,8 @@ class ContaoWidgetManager { $this->environment = $environment; $this->model = $model; + + $this->preLoadRichTextEditor(); } /** @@ -295,6 +297,40 @@ class ContaoWidgetManager } /** + * Function for pre-loading the tiny mce. + * + * @return void + */ + public function preLoadRichTextEditor() + { + foreach ($this->getEnvironment()->getDataDefinition()->getPropertiesDefinition()->getProperties() as $property) + { + /** @var PropertyInterface $property */ + $extra = $property->getExtra(); + + if (!isset($extra['eval']['rte'])) + { + continue; + } + + if (strncmp($extra['eval']['rte'], 'tiny', 4) !== 0) + { + continue; + } + + list($file, $type) = explode('|', $extra['eval']['rte']); + + $propertyId = 'ctrl_' . $property->getName(); + + $GLOBALS['TL_RTE'][$file][$propertyId] = array( + 'id' => $propertyId, + 'file' => $file, + 'type' => $type + ); + } + } + + /** * Retrieve the instance of a widget for the given property. * * @param string $property Name of the property for which the widget shall be retrieved. diff --git a/src/DcGeneral/DC_General.php b/src/DcGeneral/DC_General.php index <HASH>..<HASH> 100644 --- a/src/DcGeneral/DC_General.php +++ b/src/DcGeneral/DC_General.php @@ -555,49 +555,6 @@ class DC_General } } - /* ///////////////////////////////////////////////////////////////////////// - * ------------------------------------------------------------------------- - * Helper - * ------------------------------------------------------------------------- - * ////////////////////////////////////////////////////////////////////// */ - - /** - * Function for preloading the tiny mce - * - * @return type - */ - public function preloadTinyMce() - { - if (count($this->getEnvironment()->getDataDefinition()->getSubPalettes()) == 0) - { - return; - } - - foreach (array_keys($this->arrFields) as $strField) - { - $arrConfig = $this->getFieldDefinition($strField); - - if (!isset($arrConfig['eval']['rte'])) - { - continue; - } - - if (strncmp($arrConfig['eval']['rte'], 'tiny', 4) !== 0) - { - continue; - } - - list($strFile, $strType) = explode('|', $arrConfig['eval']['rte']); - - $strID = 'ctrl_' . $strField . '_' . $this->mixWidgetID; - - $GLOBALS['TL_RTE'][$strFile][$strID] = array( - 'id' => $strID, - 'file' => $strFile, - 'type' => $strType - ); - } - } /* ///////////////////////////////////////////////////////////////////////// * -------------------------------------------------------------------------
Move pre loading of rich text editors to widget manager.
contao-community-alliance_dc-general
train
50037dea9d8871d5b8edd1a7a6a09a22f6bf838e
diff --git a/commands/release/deploy/command.go b/commands/release/deploy/command.go index <HASH>..<HASH> 100644 --- a/commands/release/deploy/command.go +++ b/commands/release/deploy/command.go @@ -163,11 +163,6 @@ func runMain() error { return errs.NewError(task, errors.New("no deployable releases found"), nil) } - // Invert the inversion. - for i, j := 0, len(releasable)-1; i < j; i, j = i+1, j-1 { - releasable[i], releasable[j] = releasable[j], releasable[i] - } - // Prompt the user to choose the release tag. task = "Prompt the user to choose the release to be deployed" fmt.Printf("\nThe following releases can be deployed:\n\n") @@ -202,7 +197,8 @@ Or you can just press Enter to abort: `, 0, len(tags)-1) // // In case there is an error, tell the details to the user and let them // handle the cleanup since it's not possible to easily rollback the push. - for _, release := range releasable[:index+1] { + for i := len(releasable) - 1; i >= index; i-- { + release := releasable[i] releaseName := release.Version().ReleaseTagString() task := fmt.Sprintf("Mark release '%v' as released", releaseName) log.Run(task)
release deploy: Invert the release list order It makes more sense to list the most recent release as the first and continue like that until the oldest release is printed. Change-Id: b5f<I> Story-Id: SF-<I>
salsaflow_salsaflow
train
a8003c0a166807593b76c4aed89623c42dc80887
diff --git a/course/classes/management_renderer.php b/course/classes/management_renderer.php index <HASH>..<HASH> 100644 --- a/course/classes/management_renderer.php +++ b/course/classes/management_renderer.php @@ -283,7 +283,7 @@ class core_course_management_renderer extends plugin_renderer_base { )); } $menu->actiontext = get_string('createnew'); - $menu->actionicon = new pix_icon('t/add', ' ', 'moodle', array('class' => 'iconsmall', 'title' => '')); + $menu->actionicon = new pix_icon('t/contextmenu', ' ', 'moodle', array('class' => 'iconsmall', 'title' => '')); $actions[] = $this->render($menu); } if (coursecat::can_approve_course_requests()) { @@ -312,7 +312,7 @@ class core_course_management_renderer extends plugin_renderer_base { } else { $menu->actiontext = get_string('resortsubcategories'); } - $menu->actionicon = new pix_icon('t/sort', ' ', 'moodle', array('class' => 'iconsmall', 'title' => '')); + $menu->actionicon = new pix_icon('t/contextmenu', ' ', 'moodle', array('class' => 'iconsmall', 'title' => '')); $actions[] = $this->render($menu); } if (!$hasitems) { @@ -609,7 +609,7 @@ class core_course_management_renderer extends plugin_renderer_base { new action_menu_link_secondary($idnumberurl, null, get_string('resortbyidnumber')) )); $menu->actiontext = get_string('resortcourses'); - $menu->actionicon = new pix_icon('t/sort', ' ', 'moodle', array('class' => 'iconsmall', 'title' => '')); + $menu->actionicon = new pix_icon('t/contextmenu', ' ', 'moodle', array('class' => 'iconsmall', 'title' => '')); $actions[] = $this->render($menu); } $strall = get_string('all');
MDL-<I> course: converted all dropdowns to contextmenu icon
moodle_moodle
train
5ea3579e10fd94eada1ca4a18d6ef07a014a96cf
diff --git a/salt/roster/__init__.py b/salt/roster/__init__.py index <HASH>..<HASH> 100644 --- a/salt/roster/__init__.py +++ b/salt/roster/__init__.py @@ -19,19 +19,33 @@ log = logging.getLogger(__name__) def get_roster_file(options): - if options.get('roster_file'): - template = options.get('roster_file') - elif 'config_dir' in options.get('__master_opts__', {}): - template = os.path.join(options['__master_opts__']['config_dir'], - 'roster') - elif 'config_dir' in options: - template = os.path.join(options['config_dir'], 'roster') - else: - template = os.path.join(salt.syspaths.CONFIG_DIR, 'roster') + template = None + if options.get('__disable_custom_roster') and options.get('roster_file'): + roster = options.get('roster_file').strip('/') + for roster_location in options.get('rosters'): + r_file = os.path.join(roster_location, roster) + if os.path.isfile(r_file): + template = r_file + break + del options['roster_file'] + + if not template: + if options.get('roster_file'): + template = options.get('roster_file') + elif 'config_dir' in options.get('__master_opts__', {}): + template = os.path.join(options['__master_opts__']['config_dir'], + 'roster') + elif 'config_dir' in options: + template = os.path.join(options['config_dir'], 'roster') + else: + template = os.path.join(salt.syspaths.CONFIG_DIR, 'roster') if not os.path.isfile(template): raise IOError('No roster file found') + if not os.access(template, os.R_OK): + raise IOError('Access denied to roster "{}"'.format(template)) + return template
Pick up a specified roster file from the configured locations
saltstack_salt
train
c86ea25338eac43c037c449e149808a563b023b9
diff --git a/lib/octokit/client.rb b/lib/octokit/client.rb index <HASH>..<HASH> 100644 --- a/lib/octokit/client.rb +++ b/lib/octokit/client.rb @@ -19,7 +19,7 @@ require 'octokit/client/users' module Octokit class Client - attr_accessor *Configuration::VALID_OPTIONS_KEYS + attr_accessor(*Configuration::VALID_OPTIONS_KEYS) def initialize(options={}) options = Octokit.options.merge(options) diff --git a/lib/octokit/configuration.rb b/lib/octokit/configuration.rb index <HASH>..<HASH> 100644 --- a/lib/octokit/configuration.rb +++ b/lib/octokit/configuration.rb @@ -22,7 +22,7 @@ module Octokit DEFAULT_OAUTH_TOKEN = nil DEFAULT_USER_AGENT = "Octokit Ruby Gem #{Octokit::VERSION}".freeze - attr_accessor *VALID_OPTIONS_KEYS + attr_accessor(*VALID_OPTIONS_KEYS) def self.extended(base) base.reset
Avoid the following ruby warnings: .../lib/octokit/configuration.rb:<I>: warning: `*' interpreted as argument prefix .../lib/octokit/client.rb:<I>: warning: `*' interpreted as argument prefix (by helping out the ruby interpreter with some parentheses)
octokit_octokit.rb
train
d7e5419a24dbbf96a764c1c4d1793324227d1b02
diff --git a/lib/test-server/client/slave-client.js b/lib/test-server/client/slave-client.js index <HASH>..<HASH> 100644 --- a/lib/test-server/client/slave-client.js +++ b/lib/test-server/client/slave-client.js @@ -109,26 +109,20 @@ userAgent: window.navigator.userAgent, documentMode: document.documentMode }); - socketStatusUpdater('connected'); }); + socket.on('connect', socketStatusUpdater('connected')); socket.on('disconnect', function () { log("slave disconnected"); attester.connected = false; - socketStatusUpdater('disconnected'); }); + socket.on('disconnect', socketStatusUpdater('disconnected')); if (config.onDisconnect) { socket.on('disconnect', config.onDisconnect); } socket.on('reconnecting', socketStatusUpdater('reconnecting in $ ms...', 'disconnected')); socket.on('reconnect', socketStatusUpdater('re-connected', 'connected')); socket.on('reconnect_failed', socketStatusUpdater('failed to reconnect', 'disconnected')); - socket.on('server_disconnect', function () { - log("server disconnected"); - testInfo = "disconnected"; - socket.socket.disconnect(); - socket.socket.reconnect(); - }); socket.on('slave-execute', function (data) { currentTask = data; pendingTestStarts = {};
Fixing status messages in the slave UI Some messages ("connected" or "disconnected") were not displayed because of an incorrect usage of the socketStatusUpdater method (which returns a function). This commit also removes the "server_disconnect" listener because this event is never raised by socket.io.
attester_attester
train
6c2836cd9e4db9fbc780f9934484b703a9f2cd1a
diff --git a/src/Offer/OfferEditingServiceInterface.php b/src/Offer/OfferEditingServiceInterface.php index <HASH>..<HASH> 100644 --- a/src/Offer/OfferEditingServiceInterface.php +++ b/src/Offer/OfferEditingServiceInterface.php @@ -146,4 +146,11 @@ interface OfferEditingServiceInterface * @return string */ public function updateTheme($id, StringLiteral $themeId); + + /** + * @param string $id + * @param array $facilities + * @return string + */ + public function updateFacilities($id, array $facilities); }
III-<I> Add updateFacilities to offer editing service interface.
cultuurnet_udb3-php
train
24eab5026e5b6aca87089415e80deccf40c6395c
diff --git a/spec/unit/cookbook/metadata_spec.rb b/spec/unit/cookbook/metadata_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/cookbook/metadata_spec.rb +++ b/spec/unit/cookbook/metadata_spec.rb @@ -402,7 +402,7 @@ describe Chef::Cookbook::Metadata do @meta.attributes["db/mysql/databases"][:recipes].should == [] end - it "should allow the default value to be a string, array, or hash" do + it "should allow the default value to be a string, array, hash, boolean or numeric" do lambda { @meta.attribute("db/mysql/databases", :default => []) }.should_not raise_error @@ -413,10 +413,54 @@ describe Chef::Cookbook::Metadata do @meta.attribute("db/mysql/databases", :default => "alice in chains") }.should_not raise_error lambda { + @meta.attribute("db/mysql/databases", :default => 1337) + }.should_not raise_error + lambda { + @meta.attribute("db/mysql/databases", :default => true) + }.should_not raise_error + lambda { @meta.attribute("db/mysql/databases", :required => :not_gonna_do_it) }.should raise_error(ArgumentError) end + it "should limit the types allowed in the choice array" do + options = { + :type => "string", + :choice => [ "test1", "test2" ], + :default => "test1" + } + lambda { + @meta.attribute("test_cookbook/test", options) + }.should_not raise_error + + options = { + :type => "boolean", + :choice => [ true, false ], + :default => true + } + lambda { + @meta.attribute("test_cookbook/test", options) + }.should_not raise_error + + options = { + :type => "numeric", + :choice => [ 1337, 420 ], + :default => 1337 + } + lambda { + @meta.attribute("test_cookbook/test", options) + }.should_not raise_error + + options = { + :type => "numeric", + :choice => [ true, "false" ], + :default => false + } + lambda { + @meta.attribute("test_cookbook/test", options) + }.should raise_error + end + it "should error if default used with calculated" do lambda { attrs = {
update tests and add new tests for limiting attribute types
chef_chef
train
a9d7d12a2ef796ba7d8d21ca4a58aa449dc670ab
diff --git a/src/Publisher/SlugGenerator.php b/src/Publisher/SlugGenerator.php index <HASH>..<HASH> 100644 --- a/src/Publisher/SlugGenerator.php +++ b/src/Publisher/SlugGenerator.php @@ -12,24 +12,31 @@ namespace Orpheus\Publisher; */ class SlugGenerator { + const CASE_LOWER = 0; + const CASE_CAMEL = 1 << 0; + const CASE_CAMEL_LOWER = self::CASE_CAMEL; + const CASE_CAMEL_UPPER = self::CASE_CAMEL | 1 << 1; + /** * Should remove space instead of replacing them * - * @var boolean $removeSpaces + * @var boolean */ - protected $removeSpaces = false; + protected bool $removeSpaces = false; - const LOWERCASE = 0; - const CAMELCASE = 1<<0; - const LOWERCAMELCASE = self::CAMELCASE; - const UPPERCAMELCASE = self::CAMELCASE | 1<<1; + /** + * Max length to truncate + * + * @var int|null + */ + protected ?int $maxLength = null; /** * How to process word case * - * @var boolean $caseProcessing + * @var boolean */ - protected $caseProcessing = self::UPPERCAMELCASE; + protected int $caseProcessing = self::CASE_CAMEL_UPPER; /** * Format the $string @@ -47,11 +54,11 @@ class SlugGenerator { $string = strtr($string, ' .\'"', '----'); if( $this->caseProcessing !== null ) { - if( $this->caseProcessing === self::LOWERCASE ) { + if( $this->caseProcessing === self::CASE_LOWER ) { $string = strtolower($string); } if( $this->isCamelCaseProcessing() ) { - if( $this->caseProcessing === self::LOWERCAMELCASE ) { + if( $this->caseProcessing === self::CASE_CAMEL_LOWER ) { $string = lcfirst($string); // } else // if( $case == UPPERCAMELCASE ) { @@ -59,7 +66,13 @@ class SlugGenerator { } } } - return convertSpecialChars($string); + $string = convertSpecialChars($string); + + if( $this->getMaxLength() !== null ) { + $string = substr($string, 0, $this->getMaxLength()); + } + + return $string; } /** @@ -72,6 +85,15 @@ class SlugGenerator { } /** + * Is this generator camel case processing ? + * + * @return boolean + */ + public function isCamelCaseProcessing() { + return bintest($this->caseProcessing, CAMELCASE); + } + + /** * Get is removing spaces * * @return boolean @@ -86,21 +108,13 @@ class SlugGenerator { * @param boolean $removeSpaces * @return SlugGenerator */ - public function setRemoveSpaces($removeSpaces=true) { + public function setRemoveSpaces($removeSpaces = true) { $this->removeSpaces = $removeSpaces; + return $this; } /** - * Is this generator camel case processing ? - * - * @return boolean - */ - public function isCamelCaseProcessing() { - return bintest($this->caseProcessing, CAMELCASE); - } - - /** * Get camel case processing * * @return int @@ -117,9 +131,24 @@ class SlugGenerator { */ public function setCaseProcessing($caseProcessing) { $this->caseProcessing = $caseProcessing; + return $this; } + /** + * @return int|null + */ + public function getMaxLength(): ?int { + return $this->maxLength; + } + /** + * @param int|null $maxLength + */ + public function setMaxLength(?int $maxLength): self { + $this->maxLength = $maxLength; + + return $this; + } }
Add max length to slug generator
Sowapps_orpheus-webtools
train
4a6d6aded82028fb738736b6421e2ab570357138
diff --git a/dock/build.py b/dock/build.py index <HASH>..<HASH> 100644 --- a/dock/build.py +++ b/dock/build.py @@ -146,6 +146,9 @@ class InsideBuilder(LastLogger, LazyGit, BuilderStateMachine): """ logger.info("push built image to registry") self._ensure_is_built() + if not registry: + logger.warning("no registry specified; skipping") + return return self.tasker.tag_and_push_image(self.image, self.image, registry, tag=self.tag) def inspect_base_image(self):
bug: dont try to tag and push image if registry is blank
projectatomic_atomic-reactor
train
5dbdabf16a28c3f96ffa29543aeb0b1d30544c00
diff --git a/src/mappers/statsd-npg.js b/src/mappers/statsd-npg.js index <HASH>..<HASH> 100644 --- a/src/mappers/statsd-npg.js +++ b/src/mappers/statsd-npg.js @@ -49,7 +49,13 @@ function map (prefix, data, referer, userAgent) { var result, refererPrefix, suffix; result = ''; - refererPrefix = getRefererPrefix(url.parse(referer)); + + if (referer) { + refererPrefix = getRefererPrefix(url.parse(referer)); + } else { + refererPrefix = ''; + } + suffix = getUserAgentSuffix(new UserAgentParser(userAgent)); data = normalise(data); diff --git a/src/mappers/statsd.js b/src/mappers/statsd.js index <HASH>..<HASH> 100644 --- a/src/mappers/statsd.js +++ b/src/mappers/statsd.js @@ -77,6 +77,10 @@ function mapRestimingMetrics (prefix, data, referer) { } function base36Encode (string) { + if (!string) { + return 'unknown'; + } + return Array.prototype.map.call(string, function (character) { return character.charCodeAt(0).toString(36); }).join('');
Sanely handle missing referer string.
springernature_boomcatch
train
a8f1fa5c5224eebfcb0d2d1badf14a3d31b3d246
diff --git a/core/src/main/java/com/orientechnologies/common/concur/lock/OSimplePromiseManager.java b/core/src/main/java/com/orientechnologies/common/concur/lock/OSimplePromiseManager.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/orientechnologies/common/concur/lock/OSimplePromiseManager.java +++ b/core/src/main/java/com/orientechnologies/common/concur/lock/OSimplePromiseManager.java @@ -96,6 +96,10 @@ public class OSimplePromiseManager { } } + public long getTimeout() { + return -1; + } + public static class Promise { private final Integer version; private final OTransactionId txId; diff --git a/distributed/src/main/java/com/orientechnologies/orient/server/distributed/impl/ONewDistributedTxContextImpl.java b/distributed/src/main/java/com/orientechnologies/orient/server/distributed/impl/ONewDistributedTxContextImpl.java index <HASH>..<HASH> 100644 --- a/distributed/src/main/java/com/orientechnologies/orient/server/distributed/impl/ONewDistributedTxContextImpl.java +++ b/distributed/src/main/java/com/orientechnologies/orient/server/distributed/impl/ONewDistributedTxContextImpl.java @@ -83,9 +83,23 @@ public class ONewDistributedTxContextImpl implements ODistributedTxContext { public void promise(ORID rid, int version) { OSimplePromiseManager recordPromiseManager = shared.getRecordPromiseManager(); try { - recordPromiseManager.promise(rid, version); + recordPromiseManager.promise(rid, version, transactionId); } catch(OLockException ex) { - // release promises + this.unlock(); + throw new ODistributedRecordLockedException( + shared.getLocalNodeName(), rid, recordPromiseManager.getTimeout()); + } + } + + @Override + public OTransactionId lockPromise(ORID rid, int version, OTransactionId txId, boolean force) { + OSimplePromiseManager recordPromiseManager = shared.getRecordPromiseManager(); + try { + return recordPromiseManager.lock(rid, version, transactionId, force); + } catch(OLockException ex) { + this.unlock(); + throw new ODistributedRecordLockedException( + shared.getLocalNodeName(), rid, recordPromiseManager.getTimeout()); } } diff --git a/server/src/main/java/com/orientechnologies/orient/server/distributed/ODistributedTxContext.java b/server/src/main/java/com/orientechnologies/orient/server/distributed/ODistributedTxContext.java index <HASH>..<HASH> 100644 --- a/server/src/main/java/com/orientechnologies/orient/server/distributed/ODistributedTxContext.java +++ b/server/src/main/java/com/orientechnologies/orient/server/distributed/ODistributedTxContext.java @@ -36,6 +36,8 @@ public interface ODistributedTxContext { void promise(ORID rid, int version); + OTransactionId lockPromise(ORID rid, int version, OTransactionId txId, boolean force); + void lock(ORID rid, long timeout); void lockIndexKey(Object rid);
use promise and lockPromise in distributedTxContext
orientechnologies_orientdb
train
deb505cb93eedc377d4327678e1f936c6b9440e5
diff --git a/src/utils/index.js b/src/utils/index.js index <HASH>..<HASH> 100644 --- a/src/utils/index.js +++ b/src/utils/index.js @@ -341,8 +341,11 @@ export function pUpDownSteps(sequence = [], _checkFn, { onDone, onChange } = {}) let shouldUp = false let prevShouldUp = false const innerQueue = pLimit(1) + + const checkShouldUp = async () => !!(!error && await checkFn()) + async function next(...args) { - shouldUp = !!(!error && await checkFn()) + shouldUp = await checkShouldUp() const didChange = prevShouldUp !== shouldUp prevShouldUp = shouldUp if (didChange && typeof onChange === 'function') { diff --git a/test/unit/utils.test.js b/test/unit/utils.test.js index <HASH>..<HASH> 100644 --- a/test/unit/utils.test.js +++ b/test/unit/utils.test.js @@ -662,6 +662,84 @@ describe('utils', () => { 'done down', ]) }) + + it('can interrupt down while going down', async () => { + const done = Defer() + shouldUp = true + emitter.on('next', async (name, v) => { + if (name === 'down end' && v === 'b') { + shouldUp = true + done.resolve() + } + }) + await next() + shouldUp = false + await next() + await done + expect(order).toEqual([ + ...allUp, + 'change down', + 'down start c', + 'down end c', + 'down start b', + 'down end b', + 'change up', + 'up start b', + 'up end b', + 'up start c', + 'up end c', + 'done up', + ]) + }) + + it('can interrupt down while going down & during change', async () => { + const done1 = Defer() + const done2 = Defer() + const done3 = Defer() + shouldUp = true + let count = 0 + emitter.on('next', async (name, v) => { + if (name === 'down end' && v === 'b') { + count += 1 + shouldUp = true + done1.resolve() + } + + if (name === 'change' && v === 'up' && count === 1) { + count += 1 + shouldUp = false + done2.resolve() + } + + if (name === 'change' && v === 'down' && count === 2) { + count += 1 + shouldUp = true + done3.resolve() + } + }) + await next() + shouldUp = false + await next() + await done1 + await done2 + await done3 + expect(order).toEqual([ + ...allUp, + 'change down', + 'down start c', + 'down end c', + 'down start b', + 'down end b', + 'change up', + 'change down', + 'change up', + 'up start b', + 'up end b', + 'up start c', + 'up end c', + 'done up', + ]) + }) }) }) })
Test pUpDownSteps change direction to up during down behaviour.
streamr-dev_streamr-client-javascript
train
a59373a68eb33dca9b56c482ca8b97b4ac69b4eb
diff --git a/http/src/main/java/io/micronaut/http/HttpHeaders.java b/http/src/main/java/io/micronaut/http/HttpHeaders.java index <HASH>..<HASH> 100644 --- a/http/src/main/java/io/micronaut/http/HttpHeaders.java +++ b/http/src/main/java/io/micronaut/http/HttpHeaders.java @@ -506,10 +506,7 @@ public interface HttpHeaders extends Headers { return getAll(HttpHeaders.ACCEPT) .stream() .flatMap(x -> Arrays.stream(x.split(","))) - .flatMap(s -> ConversionService.SHARED.convert(s, MediaType.class) - .map(Stream::of) - .orElse(Stream.empty()) - ) + .flatMap(s -> ConversionService.SHARED.convert(s, MediaType.class).map(Stream::of).orElse(Stream.empty())) .distinct() .collect(Collectors.toList()); }
Revert: accidental commit (e<I>f2)
micronaut-projects_micronaut-core
train
414cc576cec5b442231250c9556789e5e0844917
diff --git a/spec/backend/exec/build_command_spec.rb b/spec/backend/exec/build_command_spec.rb index <HASH>..<HASH> 100644 --- a/spec/backend/exec/build_command_spec.rb +++ b/spec/backend/exec/build_command_spec.rb @@ -78,7 +78,7 @@ describe 'check_os' do context 'test ubuntu with lsb_release command' do subject { backend.check_os } it do - backend.should_receive(:run_command).at_least(1).times do |args| + expect(backend).to receive(:run_command).at_least(1).times do |args| if ['ls /etc/debian_version', 'lsb_release -ir'].include? args double( :run_command_response, @@ -98,7 +98,7 @@ describe 'check_os' do context 'test ubuntu with /etc/lsb-release' do subject { backend.check_os } it do - backend.should_receive(:run_command).at_least(1).times do |args| + expect(backend).to receive(:run_command).at_least(1).times do |args| if ['ls /etc/debian_version', 'cat /etc/lsb-release'].include? args double( :run_command_response, @@ -123,7 +123,7 @@ EOF context 'test debian (no lsb_release or lsb-release)' do subject { backend.check_os } it do - backend.should_receive(:run_command).at_least(1).times do |args| + expect(backend).to receive(:run_command).at_least(1).times do |args| if args == 'ls /etc/debian_version' double :run_command_response, :success? => true elsif args == 'uname -m'
Use RSpec 3 style stubs.
mizzy_specinfra
train
ab3a8ee142feb1ab8c686bcfb80418939a364816
diff --git a/tests/unit/progressbar/test_BProgressMonitor.py b/tests/unit/progressbar/test_BProgressMonitor.py index <HASH>..<HASH> 100644 --- a/tests/unit/progressbar/test_BProgressMonitor.py +++ b/tests/unit/progressbar/test_BProgressMonitor.py @@ -27,7 +27,8 @@ def monitor(presentation): def test_repr(monitor): repr(monitor) -def test_begin_end(monitor): +def test_begin_end(monitor, presentation): + presentation.nreports.return_value = 0 monitor.begin() assert isinstance(alphatwirl.progressbar._progress_reporter, ProgressReporter) monitor.end() @@ -38,6 +39,7 @@ def test_createReporter(monitor): assert isinstance(reporter, ProgressReporter) def test_send_report(monitor, presentation): + presentation.nreports.return_value = 10 monitor.begin() reporter = monitor.createReporter() report = ProgressReport('task1', 0, 3) diff --git a/tests/unit/progressbar/test_ProgressReportPickup.py b/tests/unit/progressbar/test_ProgressReportPickup.py index <HASH>..<HASH> 100644 --- a/tests/unit/progressbar/test_ProgressReportPickup.py +++ b/tests/unit/progressbar/test_ProgressReportPickup.py @@ -26,6 +26,7 @@ def pickup(queue, presentation): ##__________________________________________________________________|| def test_start_join(pickup, queue, presentation): + presentation.nreports.return_value = 10 pickup.start() queue.put(None) pickup.join()
set return value of mock. MagicMock and int cannot be compared in Python 3
alphatwirl_alphatwirl
train
b73406e5b5694d34727f4f03e4a602162699c140
diff --git a/client/js/templating.js b/client/js/templating.js index <HASH>..<HASH> 100644 --- a/client/js/templating.js +++ b/client/js/templating.js @@ -1,17 +1,23 @@ -// Expected: If any template elements do not exists, fail silently (no unchecked errors, etc) +/** + * Module responsible for rendering all Fine Uploader UI templates. This module also asserts at least + * a limited amount of control over the template elements after they are added to the DOM. + * Wherever possible, this module asserts total control over template elements present in the DOM. + * + * @param spec Specification object used to control various templating behaviors + * @returns various API methods + * @constructor + */ qq.Templating = function(spec) { "use strict"; - var api, isEditElementsExist, isRetryElementExist, - fileIdAttr = "qq-file-id", - fileClassPrefix = "qq-file-id-", + var FILE_ID_ATTR = "qq-file-id", + FILE_CLASS_PREFIX = "qq-file-id-", isCancelDisabled = false, options = { templateIdOrEl: "qq-template", containerEl: null, fileContainerEl: null, button: null, - disableDnd: false, classes: { hide: "qq-hide", editable: "qq-editable" @@ -35,12 +41,19 @@ qq.Templating = function(spec) { dropProcessing: 'qq-drop-processing-selector', dropProcessingSpinner: 'qq-drop-processing-spinner-selector' }, - templateHtml, container, fileList; + api, isEditElementsExist, isRetryElementExist, templateHtml, container, fileList; qq.extend(options, spec); container = options.containerEl; - + /** + * Grabs the HTML from the script tag holding the template markup. This function will also adjust + * some internally-tracked state variables based on the contents of the template. + * The template is filtered so that irrelevant elements (such as the drop zone if DnD is not supported) + * are omitted from the DOM. Useful errors will be thrown if the template cannot be parsed. + * + * @returns {{template: *, fileTemplate: *}} HTML for the top-level file items templates + */ function getTemplateHtml() { var scriptEl, scriptHtml, fileListNode, tempTemplateEl, fileListHtml, defaultButton, dropzone; @@ -48,6 +61,7 @@ qq.Templating = function(spec) { throw new Error("You MUST specify either a template element or ID!"); } + // Grab the contents of the script tag holding the template. if (qq.isString(options.templateIdOrEl)) { scriptEl = document.getElementById(options.templateIdOrEl); @@ -70,6 +84,8 @@ qq.Templating = function(spec) { tempTemplateEl = document.createElement("div"); tempTemplateEl.appendChild(qq.toElement(scriptHtml)); + // Don't include the default template button in the DOM + // if an alternate button container has been specified. if (spec.button) { defaultButton = qq(tempTemplateEl).getByClass(selectorClasses.button)[0]; if (defaultButton) { @@ -77,11 +93,10 @@ qq.Templating = function(spec) { } } - if (spec.disableDnd || !qq.supportedFeatures.fileDrop) { + // Omit the drop zone from the DOM if DnD is not supported by the UA. + if (!qq.supportedFeatures.fileDrop) { dropzone = qq(tempTemplateEl).getByClass(selectorClasses.drop)[0]; - if (dropzone) { - qq(dropzone).remove(); - } + dropzone && qq(dropzone).remove(); } isEditElementsExist = qq(tempTemplateEl).getByClass(selectorClasses.editFilenameInput).length > 0; @@ -98,7 +113,7 @@ qq.Templating = function(spec) { } function getFile(id) { - return qq(fileList).getByClass(fileClassPrefix + id)[0]; + return qq(fileList).getByClass(FILE_CLASS_PREFIX + id)[0]; } function getTemplateEl(context, cssClass) { @@ -203,9 +218,9 @@ qq.Templating = function(spec) { var fileEl = qq.toElement(templateHtml.fileTemplate), fileNameEl = getTemplateEl(fileEl, selectorClasses.file); - qq(fileEl).addClass(fileClassPrefix + id); + qq(fileEl).addClass(FILE_CLASS_PREFIX + id); fileNameEl && qq(fileNameEl).setText(name); - fileEl.setAttribute(fileIdAttr, id); + fileEl.setAttribute(FILE_ID_ATTR, id); if (prependInfo) { prependFile(fileEl, prependInfo.index); @@ -231,11 +246,11 @@ qq.Templating = function(spec) { getFileId: function(el) { var currentNode = el; - while (currentNode.getAttribute(fileIdAttr) == null) { + while (currentNode.getAttribute(FILE_ID_ATTR) == null) { currentNode = el.parentNode; } - return currentNode.getAttribute(fileIdAttr); + return currentNode.getAttribute(FILE_ID_ATTR); }, getFileList: function() {
docs(client/js/templating.js): #<I> - comments mostly
FineUploader_fine-uploader
train
e699c3bec81ecf381d59662b3479b1b88a2609e2
diff --git a/core/src/core-api/config.js b/core/src/core-api/config.js index <HASH>..<HASH> 100644 --- a/core/src/core-api/config.js +++ b/core/src/core-api/config.js @@ -15,11 +15,6 @@ class LuigiConfig { * @memberof Configuration */ constructor() { - this.configReadyTimeout = { - valueMs: 65000, - id: undefined - }; - this.configReadyCallback = function() {}; this.initialized = false; @@ -31,11 +26,6 @@ class LuigiConfig { */ setConfigCallbacks(configReadyCallback) { this.configReadyCallback = configReadyCallback; - this.configReadyTimeout.id = setTimeout(() => { - // Avoid Luigi initialization if timeout reached - this.configReadyCallback = function() {}; - this.configNotReadyCallback(); - }, this.configReadyTimeout.valueMs); } /** @@ -65,7 +55,6 @@ class LuigiConfig { * }) */ setConfig(configInput) { - clearTimeout(this.configReadyTimeout.id); this.config = configInput; window.Luigi._store.set({ config: configInput }); this._configModificationTimestamp = new Date(); @@ -114,16 +103,6 @@ class LuigiConfig { * @private * @memberof Configuration */ - configNotReadyCallback() { - const errorMsg = LuigiI18N.getTranslation('luigi.configNotReadyCallback'); - console.error(errorMsg); - this.setErrorMessage(errorMsg); - } - - /** - * @private - * @memberof Configuration - */ setErrorMessage(errorMsg) { var errorTextNode = document.createTextNode(errorMsg); var fd_ui = document.createElement('div'); diff --git a/core/src/navigation/services/context-switcher.js b/core/src/navigation/services/context-switcher.js index <HASH>..<HASH> 100644 --- a/core/src/navigation/services/context-switcher.js +++ b/core/src/navigation/services/context-switcher.js @@ -19,7 +19,8 @@ export const ContextSwitcherHelpers = { return rawOptions.map(opt => ({ label: opt.label, path: (parentNodePath || '/') + opt.pathValue, - id: opt.pathValue + id: opt.pathValue, + testId: opt.testId })); }, diff --git a/core/src/utilities/defaultLuigiTranslationTable.js b/core/src/utilities/defaultLuigiTranslationTable.js index <HASH>..<HASH> 100644 --- a/core/src/utilities/defaultLuigiTranslationTable.js +++ b/core/src/utilities/defaultLuigiTranslationTable.js @@ -1,7 +1,5 @@ const defaultLuigiInternalTranslationTable = { luigi: { - configNotReadyCallback: - 'Ups.. Looks like Luigi was not configured. Please use Luigi.setConfig(config) function to configure Luigi.', unsavedChangesAlert: { header: 'Unsaved changes detected', body: 'Unsaved changes will be lost. Do you want to continue?'
avoid Luigi not configured alert (#<I>)
kyma-project_luigi
train
5f4ea3eb0d80855f24d50cf05d78f3a12940ce39
diff --git a/bika/lims/browser/js/bika.lims.common.js b/bika/lims/browser/js/bika.lims.common.js index <HASH>..<HASH> 100644 --- a/bika/lims/browser/js/bika.lims.common.js +++ b/bika/lims/browser/js/bika.lims.common.js @@ -123,6 +123,64 @@ function CommonUtils() { } }; + /** + * Update or modify a query filter for a reference widget. + * This will set the options, then re-create the combogrid widget + * with the new filter key/value. + * + * @param {object} element - the input element as combogrid. + * @param {string} filterkey - the new filter key to filter by. + * @param {string} filtervalue - the value of the new filter. + * @param {string} querytype - it can be 'base_query' or 'search_query' + */ + window.bika.lims.update_combogrid_query = function( + element, filterkey, filtervalue, querytype) { + + if (!$(element).is(':visible')) { + return; + }; + if (!querytype) { + querytype = 'base_query'; + }; + // Adding the new query filter + var query = jQuery.parseJSON($(element).attr(querytype)); + query[filterkey] = filtervalue; + $(element).attr(querytype, JSON.stringify(query)); + + var options = jQuery.parseJSON( + $(element).attr("combogrid_options")); + + // Building new ajax request + options.url = window.portal_url + "/" + options.url; + options.url = options.url + "?_authenticator=" + + $("input[name='_authenticator']").val(); + options.url = options.url + "&catalog_name=" + + $(element).attr("catalog_name"); + + options.url = options.url + "&base_query=" + + encodeURIComponent($(element).attr("base_query")); + options.url = options.url + "&search_query=" + + encodeURIComponent($.toJSON(query)); + + var col_model = options.colModel; + var search_fields = options.search_fields; + var discard_empty = options.discard_empty + + options.url = options.url + "&colModel=" + + $.toJSON(col_model); + + options.url = options.url + "&search_fields=" + + $.toJSON(search_fields) + + options.url = options.url + "&discard_empty=" + + $.toJSON(discard_empty); + + options.force_all = "false"; + + // Apply changes + $(element).combogrid(options); + }; + // Priority Selection Widget $('.ArchetypesPrioritySelectionWidget select').change(function(e){ var val = $(this).find('option:selected').val();
common javascript function to update reference widgets (combogrid)
senaite_senaite.core
train
89c86294e1efc168be500d3d8f7753d1a145fa20
diff --git a/lib/rubocop/cop/numeric_literals.rb b/lib/rubocop/cop/numeric_literals.rb index <HASH>..<HASH> 100644 --- a/lib/rubocop/cop/numeric_literals.rb +++ b/lib/rubocop/cop/numeric_literals.rb @@ -6,14 +6,16 @@ module Rubocop MSG = 'Add underscores to large numeric literals to ' + 'improve their readability.' - def inspect(file, source, tokens, ast) - on_node([:int, :float], ast) do |s| - if s.to_a[0] > 10000 && - s.src.expression.to_source.split('.').grep(/\d{6}/).any? - add_offence(:convention, s.src.expression.line, MSG) - end + def on_int(node) + value, = *node + + if value > 10000 && + node.src.expression.to_source.split('.').grep(/\d{6}/).any? + add_offence(:convention, node.src.expression.line, MSG) end end + + alias_method :on_float, :on_int end end end
Port NumericLiterals to AST::Processor
rubocop-hq_rubocop
train
f22786f78e3b8d2116e31db847513f41cfe964eb
diff --git a/library/Phrozn/Runner/CommandLine/Parser.php b/library/Phrozn/Runner/CommandLine/Parser.php index <HASH>..<HASH> 100644 --- a/library/Phrozn/Runner/CommandLine/Parser.php +++ b/library/Phrozn/Runner/CommandLine/Parser.php @@ -90,4 +90,13 @@ class Parser return $this; } + + public function __toString() + { + $out = get_class($this) . "\n"; + $out .= "OPTIONS: " . print_r($this->options, true); + $out .= "ARGS: " . print_r($this->args, true); + $out .= "COMMANDS: " . print_r(array_keys($this->commands), true); + return $out; + } }
CommandLine\Parser: added __toString restrospection method
Pawka_phrozn
train
c9ce28b0d47238f96dfa17a2f67c08be7b162ec1
diff --git a/features/steps/metric_configuration.py b/features/steps/metric_configuration.py index <HASH>..<HASH> 100644 --- a/features/steps/metric_configuration.py +++ b/features/steps/metric_configuration.py @@ -48,10 +48,6 @@ def step_impl(context): except Exception as exception: context.response = exception -@then(u'I should get an error') -def step_impl(context): - assert_is_instance(context.response, KalibroClientNotFoundError) - @given(u'I have a metric configuration within the given kalibro configuration') def step_impl(context): context.metric_configuration = MetricConfigurationFactory.build(
Removed duplicated step from metric_configuration
mezuro_kalibro_client_py
train
283d2502248e928b2af920d52f4c0fcf37419d38
diff --git a/bin/cmd.js b/bin/cmd.js index <HASH>..<HASH> 100755 --- a/bin/cmd.js +++ b/bin/cmd.js @@ -564,7 +564,7 @@ function runDownload (torrentId) { dlnacasts.on('update', player => { const opts = { title: `WebTorrent - ${torrent.files[index].name}`, - type: mime.lookup(torrent.files[index].name) + type: mime.getType(torrent.files[index].name) } if (argv.subtitles) {
fix(mime package): fix issue of using deprecated(missed) method of mime package. <URL>
webtorrent_webtorrent-cli
train
b1a8b92985103e5e4c58b2a7d263077e8eea8383
diff --git a/api/src/main/java/org/jfrog/artifactory/client/model/SystemInfo.java b/api/src/main/java/org/jfrog/artifactory/client/model/SystemInfo.java index <HASH>..<HASH> 100644 --- a/api/src/main/java/org/jfrog/artifactory/client/model/SystemInfo.java +++ b/api/src/main/java/org/jfrog/artifactory/client/model/SystemInfo.java @@ -36,4 +36,6 @@ public interface SystemInfo { long getNoneHeapMemoryMax(); long getHeapMemoryMax(); + + long getJvmUpTime(); } diff --git a/services/src/main/java/org/jfrog/artifactory/client/model/impl/SystemInfoImpl.java b/services/src/main/java/org/jfrog/artifactory/client/model/impl/SystemInfoImpl.java index <HASH>..<HASH> 100644 --- a/services/src/main/java/org/jfrog/artifactory/client/model/impl/SystemInfoImpl.java +++ b/services/src/main/java/org/jfrog/artifactory/client/model/impl/SystemInfoImpl.java @@ -22,6 +22,7 @@ public class SystemInfoImpl implements SystemInfo { private long threadCount; private long noneHeapMemoryMax; private long heapMemoryMax; + private long jvmUpTime; @Override public long getCommittedVirtualMemorySize() { @@ -166,4 +167,13 @@ public class SystemInfoImpl implements SystemInfo { public void setHeapMemoryMax(long heapMemoryMax) { this.heapMemoryMax = heapMemoryMax; } + + @Override + public long getJvmUpTime() { + return jvmUpTime; + } + + public void setJvmUpTime(long jvmUpTime) { + this.jvmUpTime = jvmUpTime; + } }
Extended SystemInfo with jvmUpTime property
jfrog_artifactory-client-java
train
0c8be64eb717fd1ab78f01ea710202c8029872e0
diff --git a/src/toil/lib/ec2.py b/src/toil/lib/ec2.py index <HASH>..<HASH> 100644 --- a/src/toil/lib/ec2.py +++ b/src/toil/lib/ec2.py @@ -187,10 +187,13 @@ variable_ecu = -1 # variable ecu _ec2_instance_types = [ # current generation instance types + InstanceType('t2.nano', 1, variable_ecu, 0.5, [hvm], 0, None, 0, False), InstanceType('t2.micro', 1, variable_ecu, 1, [hvm], 0, None, 0, False), InstanceType('t2.small', 1, variable_ecu, 2, [hvm], 0, None, 0, False), InstanceType('t2.medium', 2, variable_ecu, 4, [hvm], 0, None, 0, False), InstanceType('t2.large', 2, variable_ecu, 8, [hvm], 0, None, 0, False), + InstanceType('t2.xlarge', 4, variable_ecu, 16, [hvm], 0, None, 0, False), + InstanceType('t2.2xlarge', 8, variable_ecu, 32, [hvm], 0, None, 0, False), InstanceType('m3.medium', 1, 3, 3.75, [hvm, pv], 1, ssd, 4, True), InstanceType('m3.large', 2, 6.5, 7.5, [hvm, pv], 1, ssd, 32, True), @@ -202,6 +205,7 @@ _ec2_instance_types = [ InstanceType('m4.2xlarge', 8, 26, 32, [hvm], 0, None, 0, True), InstanceType('m4.4xlarge', 16, 53.5, 64, [hvm], 0, None, 0, True), InstanceType('m4.10xlarge', 40, 124.5, 160, [hvm], 0, None, 0, True), + InstanceType('m4.16xlarge', 64, 188, 256, [hvm], 0, None, 0, True), InstanceType('c4.large', 2, 8, 3.75, [hvm], 0, None, 0, True), InstanceType('c4.xlarge', 4, 16, 7.5, [hvm], 0, None, 0, True), @@ -215,7 +219,19 @@ _ec2_instance_types = [ InstanceType('c3.4xlarge', 16, 55, 30, [hvm, pv], 2, ssd, 160, True), InstanceType('c3.8xlarge', 32, 108, 60, [hvm, pv], 2, ssd, 320, True), + InstanceType('p2.xlarge', 4, 12, 61, [hvm], 0, None, 0, True), + InstanceType('p2.8xlarge', 32, 94, 488, [hvm], 0, None, 0, True), + InstanceType('p2.16xlarge', 64, 188, 732, [hvm], 0, None, 0, True), + InstanceType('g3.4xlarge', 16, 47, 122, [hvm], 0, None, 0, True), + InstanceType('g3.8xlarge', 32, 94, 244, [hvm], 0, None, 0, True), + InstanceType('g3.16xlarge', 64, 188, 488, [hvm], 0, None, 0, True), + InstanceType('g2.2xlarge', 8, 26, 15, [hvm], 1, ssd, 60, True), + InstanceType('g2.8xlarge', 32, 104, 60, [hvm], 2, ssd, 120, True), + + InstanceType('x1.16large', 64, 174.5, 976, [hvm], 1, ssd, 1920, True), + InstanceType('x1.32large', 128, 349, 1952, [hvm], 2, ssd, 1920, True), + InstanceType('x1e.32large', 128, 349, 3904, [hvm], 2, ssd, 1920, True), InstanceType('r3.large', 2, 6.5, 15, [hvm], 1, ssd, 32, True), InstanceType('r3.xlarge', 4, 13, 30.5, [hvm], 1, ssd, 80, True), @@ -223,11 +239,25 @@ _ec2_instance_types = [ InstanceType('r3.4xlarge', 16, 52, 122, [hvm], 1, ssd, 320, True), InstanceType('r3.8xlarge', 32, 104, 244, [hvm], 2, ssd, 320, True), + InstanceType('r4.large', 2, 6.5, 15, [hvm], 0, None, 0, True), + InstanceType('r4.xlarge', 4, 13, 30.5, [hvm], 0, None, 0, True), + InstanceType('r4.2xlarge', 8, 26, 61, [hvm], 0, None, 0, True), + InstanceType('r4.4xlarge', 16, 52, 122, [hvm], 0, None, 0, True), + InstanceType('r4.8xlarge', 32, 104, 244, [hvm], 0, None, 0, True), + InstanceType('r4.16xlarge', 64, 195, 488, [hvm], 0, None, 0, True), + InstanceType('i2.xlarge', 4, 14, 30.5, [hvm], 1, ssd, 800, False), InstanceType('i2.2xlarge', 8, 27, 61, [hvm], 2, ssd, 800, False), InstanceType('i2.4xlarge', 16, 53, 122, [hvm], 4, ssd, 800, False), InstanceType('i2.8xlarge', 32, 104, 244, [hvm], 8, ssd, 800, False), + InstanceType('i3.large', 2, 7, 15.25, [hvm], 1, ssd, 475, True), + InstanceType('i3.xlarge', 4, 13, 30.5, [hvm], 1, ssd, 950, True), + InstanceType('i3.2xlarge', 8, 27, 61, [hvm], 1, ssd, 1900, True), + InstanceType('i3.4xlarge', 16, 53, 122, [hvm], 2, ssd, 1900, True), + InstanceType('i3.8xlarge', 32, 104, 244, [hvm], 4, ssd, 1900, True), + InstanceType('i3.16xlarge', 64, 200, 488, [hvm], 8, ssd, 1900, True), + InstanceType('d2.xlarge', 4, 14, 30.5, [hvm], 3, hdd, 2000, True), InstanceType('d2.2xlarge', 8, 28, 61, [hvm], 6, hdd, 2000, True), InstanceType('d2.4xlarge', 16, 56, 122, [hvm], 12, hdd, 2000, True),
Update ec2 instance list (resolves #<I>)
DataBiosphere_toil
train
a711207c2092f5769f5c83b026df6fddef074d92
diff --git a/lib/nexmo/namespace.rb b/lib/nexmo/namespace.rb index <HASH>..<HASH> 100644 --- a/lib/nexmo/namespace.rb +++ b/lib/nexmo/namespace.rb @@ -76,7 +76,7 @@ module Nexmo return if block - @logger.debug(response.body) + @logger.debug(response.body) if response.body parse(response) end
Fix logging of nil response bodies
Nexmo_nexmo-ruby
train
3beadaad478ad39b04041a191a97cd663041c9ef
diff --git a/pycivic/civic.py b/pycivic/civic.py index <HASH>..<HASH> 100644 --- a/pycivic/civic.py +++ b/pycivic/civic.py @@ -5,6 +5,18 @@ MODULE = importlib.import_module('pycivic.civic') API_URL = 'https://civicdb.org/api' +UNMARKED_PLURALS = {'evidence'} + +CIVIC_TO_PYCLASS = { + 'evidence_items': 'evidence' +} + +def pluralize(element_type): + if element_type in UNMARKED_PLURALS: + return element_type + if element_type.endswith('s'): + return element_type + return element_type + 's' def search_url(element): return '/'.join([API_URL, element, 'search']) @@ -16,16 +28,24 @@ def snake_to_camel(snake_string): return ''.join(cap_words) -CLASS_MAP = { - 'evidence_items': 'evidence' -} - - def map_to_class_string(element_type): - x = CLASS_MAP.get(element_type, element_type) + x = CIVIC_TO_PYCLASS.get(element_type, element_type) + if x == 'evidence_item': + x = 'evidence' return snake_to_camel(x) +def element_lookup_by_id(element_type, element_id): + e_string = pluralize(element_type.lower()) + if e_string == 'evidence': + e_string = 'evidence_items' + url = '/'.join([API_URL, e_string, str(element_id)]) + resp = requests.get(url) + resp.raise_for_status() + resp_dict = resp.json() + return resp_dict + + class CivicRecord: SIMPLE_FIELDS = {'id', 'type', 'name'} @@ -89,12 +109,11 @@ class CivicRecord: """Updates record and returns True if record is complete after update, else False.""" if kwargs: self.__init__(partial=allow_partial, **kwargs) - return self.partial - - raise NotImplementedError + return not self.partial - def lookup_by_id(self): - raise NotImplementedError + resp_dict = element_lookup_by_id(self.type, self.id) + self.__init__(partial=False, **resp_dict) + return True class Variant(CivicRecord): @@ -102,11 +121,12 @@ class Variant(CivicRecord): class Gene(CivicRecord): - pass + SIMPLE_FIELDS = CivicRecord.SIMPLE_FIELDS.union({'description'}) class Evidence(CivicRecord): - pass + + SIMPLE_FIELDS = CivicRecord.SIMPLE_FIELDS.union({'description'}) class Attribute(CivicRecord): @@ -114,9 +134,6 @@ class Attribute(CivicRecord): SIMPLE_FIELDS = {'type'} COMPLEX_FIELDS = set() - def lookup_by_id(self): - raise AttributeError('Attributes do not have lookups') - def __repr__(self): return f'<CIViC Attribute {self.type}>' diff --git a/pycivic/tests/test_civic.py b/pycivic/tests/test_civic.py index <HASH>..<HASH> 100644 --- a/pycivic/tests/test_civic.py +++ b/pycivic/tests/test_civic.py @@ -5,16 +5,12 @@ ELEMENTS = [ 'Assertion' ] -UNMARKED_PLURALS = set( - 'Evidence' -) - @pytest.fixture(scope="module", params=ELEMENTS) def element(request): element_type = request.param t = element_type.lower() - if element_type in UNMARKED_PLURALS: + if element_type.lower() in civic.UNMARKED_PLURALS: f = getattr(civic.MODULE, f'get_{t}') else: f = getattr(civic.MODULE, f'get_{t}s')
finish initializing classes and writing built-in update function
griffithlab_civicpy
train
f31c6367200743c9177e1c23482a440b120e483e
diff --git a/lib/simple_calendar/view_helpers.rb b/lib/simple_calendar/view_helpers.rb index <HASH>..<HASH> 100644 --- a/lib/simple_calendar/view_helpers.rb +++ b/lib/simple_calendar/view_helpers.rb @@ -10,14 +10,12 @@ module SimpleCalendar def start_date(date) start_date = date.beginning_of_month - start_date = start_date.beginning_of_week.advance(:days => -1) unless start_date.sunday? - start_date + start_date.beginning_of_week.advance(:days => -1) unless start_date.sunday? end def end_date(date) end_date = date.end_of_month - end_date = end_date.advance(:days => 1).end_of_week if end_date.sunday? - end_date + end_date.sunday? ? end_date.advance(:days => 1).end_of_week : end_date end def month_header(day)
Shortened start_date + end_date methods. Since the last statement executed is returned, the start/end_date variables don't need to be set and then explicitly called.
excid3_simple_calendar
train
bd68e5503db86c3c0bef0280764b0ede2e9a2001
diff --git a/go/vt/tabletserver/schema_info.go b/go/vt/tabletserver/schema_info.go index <HASH>..<HASH> 100644 --- a/go/vt/tabletserver/schema_info.go +++ b/go/vt/tabletserver/schema_info.go @@ -139,6 +139,7 @@ func (si *SchemaInfo) Open(connFactory CreateConnectionFunc, schemaOverrides []S si.tables = make(map[string]*TableInfo, len(tables.Rows)) si.tables["dual"] = NewTableInfo(conn, "dual", "VIEW", sqltypes.NULL, "", si.cachePool) + si.tables["DUAL"] = NewTableInfo(conn, "DUAL", "VIEW", sqltypes.NULL, "", si.cachePool) for _, row := range tables.Rows { tableName := row[0].String() si.updateLastChange(row[2])
queryservice: Create a DUAL fake table Now that table names are case sensitive, we need to allow both dual and DUAL as fake tables.
vitessio_vitess
train
c4a1d97969db77b508f44050afd33864af93ff75
diff --git a/catapult_base/dependency_manager/dependency_manager.py b/catapult_base/dependency_manager/dependency_manager.py index <HASH>..<HASH> 100644 --- a/catapult_base/dependency_manager/dependency_manager.py +++ b/catapult_base/dependency_manager/dependency_manager.py @@ -89,8 +89,6 @@ class DependencyManager(object): """ dependency_info = self._GetDependencyInfo(dependency, platform) if not dependency_info: - logging.error( - 'The dependency_manager was not initialized with the dependency.') if not try_support_binaries: raise exceptions.NoPathFoundError(dependency, platform) # TODO(aiolos): Remove the support_binaries call and always raise @@ -141,8 +139,6 @@ class DependencyManager(object): # system. dependency_info = self._GetDependencyInfo(dependency, platform) if not dependency_info: - logging.error( - 'The dependency_manager was not initialized with the dependency.') if not try_support_binaries: raise exceptions.NoPathFoundError(dependency, platform) return support_binaries.FindLocallyBuiltPath(dependency)
[Android] Add a configurable environment for devil/. (RELAND) This is a reland of <URL>
catapult-project_catapult
train
5d6c0fc19be62953f75a728996a6b70485739530
diff --git a/ImapClient/ImapConnect.php b/ImapClient/ImapConnect.php index <HASH>..<HASH> 100644 --- a/ImapClient/ImapConnect.php +++ b/ImapClient/ImapConnect.php @@ -149,6 +149,7 @@ class ImapConnect }; /* + // TODO: Needed? $array = [$mailbox, $username , $password, $options, $n_retries, $params]; foreach ($array as $val) { var_dump($val); @@ -179,8 +180,8 @@ class ImapConnect /** * Get string mailbox - * - * @return object + * + * @return object */ public function getMailbox() {
Connect comments Hi dere :>
SSilence_php-imap-client
train
6aed4aaaa8361a39176309bd5f179770f84e2cac
diff --git a/buildbot/status/web/build.py b/buildbot/status/web/build.py index <HASH>..<HASH> 100644 --- a/buildbot/status/web/build.py +++ b/buildbot/status/web/build.py @@ -123,8 +123,8 @@ class StatusResourceBuild(HtmlResource): name, " ".join(s.getText()), time_to_run)) + data += " <ol>\n" if s.getLogs(): - data += " <ol>\n" for logfile in s.getLogs(): logname = logfile.getName() logurl = req.childLink("steps/%s/logs/%s" % @@ -132,8 +132,15 @@ class StatusResourceBuild(HtmlResource): urllib.quote(logname))) data += (" <li><a href=\"%s\">%s</a></li>\n" % (logurl, logfile.getName())) - data += " </ol>\n" - data += " </li>\n" + if s.getURLs(): + for url in s.getURLs().items(): + logname = url[0] + logurl = url[1] + data += (' <li><a href="%s">%s</a></li>\n' % + (logurl, html.escape(logname))) + data += "</ol>\n" + data += " </li>\n" + data += "</ol>\n" data += "<h2>Build Properties:</h2>\n"
Added urls list to the build property page
buildbot_buildbot
train
fff9bd8fba997d49b36c9cb798ec70f428d8f23e
diff --git a/packages/zone.js/rollup-es5.config.js b/packages/zone.js/rollup-es5.config.js index <HASH>..<HASH> 100644 --- a/packages/zone.js/rollup-es5.config.js +++ b/packages/zone.js/rollup-es5.config.js @@ -24,9 +24,9 @@ if (bazel_stamp_file) { // `this` should be `undefined` but is assigned with `Window` instead. const banner = `'use strict'; /** -* @license Angular v${version} -* (c) 2010-2020 Google LLC. https://angular.io/ -* License: MIT + * @license Angular v${version} + * (c) 2010-2020 Google LLC. https://angular.io/ + * License: MIT */`; module.exports = { diff --git a/packages/zone.js/rollup-es5_global-es2015.config.js b/packages/zone.js/rollup-es5_global-es2015.config.js index <HASH>..<HASH> 100644 --- a/packages/zone.js/rollup-es5_global-es2015.config.js +++ b/packages/zone.js/rollup-es5_global-es2015.config.js @@ -24,9 +24,9 @@ if (bazel_stamp_file) { // `this` should be `undefined` but is assigned with `Window` instead. const banner = `'use strict'; /** -* @license Angular v${version} -* (c) 2010-2020 Google LLC. https://angular.io/ -* License: MIT + * @license Angular v${version} + * (c) 2010-2020 Google LLC. https://angular.io/ + * License: MIT */`; module.exports = {
docs(zone.js): add leading space in the license comment of zone.js bundles (#<I>) PR Close #<I>
angular_angular
train
10e6d3437d4ffd615b2c070007db80d5c968bc89
diff --git a/dimod/higherorder/utils.py b/dimod/higherorder/utils.py index <HASH>..<HASH> 100644 --- a/dimod/higherorder/utils.py +++ b/dimod/higherorder/utils.py @@ -26,6 +26,7 @@ from dimod.binary_quadratic_model import BinaryQuadraticModel from dimod.higherorder.polynomial import BinaryPolynomial from dimod.sampleset import as_samples from dimod.vartypes import as_vartype, Vartype +from dimod.generators import and_gate __all__ = ['make_quadratic', 'reduce_terms'] @@ -58,30 +59,6 @@ def _spin_product(variables): 2., Vartype.SPIN) - -def _binary_product(variables): - """A BQM with a gap of 1 that represents the product of two binary variables. - - Args: - variables (list): - multiplier, multiplicand, product - - Returns: - :obj:`.BinaryQuadraticModel` - - """ - multiplier, multiplicand, product = variables - - return BinaryQuadraticModel({multiplier: 0.0, - multiplicand: 0.0, - product: 3.0}, - {(multiplier, multiplicand): 1.0, - (multiplier, product): -2.0, - (multiplicand, product): -2.0}, - 0.0, - Vartype.BINARY) - - def _new_product(variables, u, v): # make a new product variable not in variables, then add it p = '{}*{}'.format(u, v) @@ -244,7 +221,7 @@ def make_quadratic(poly, strength, vartype=None, bqm=None): # add a constraint enforcing the relationship between p == u*v if vartype is Vartype.BINARY: - constraint = _binary_product([u, v, p]) + constraint = and_gate([u, v, p]) bqm.info['reduction'][(u, v)] = {'product': p} elif vartype is Vartype.SPIN: aux = _new_aux(variables, u, v) # need an aux in SPIN-space
replace _binary_product with and_gate
dwavesystems_dimod
train
95c5aa2e895e5e1f5ada01f2708734e58da97f00
diff --git a/docs/conf.py b/docs/conf.py index <HASH>..<HASH> 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -56,7 +56,7 @@ project = u'resampy' copyright = u'2016, Brian McFee' import mock -MOCK_MODULES = ['numpy', 'scipy', 'scipy.signal', 'resampy.resample'] +MOCK_MODULES = ['numpy', 'scipy', 'scipy.signal', 'resampy.interp'] sys.modules.update((mod_name, mock.Mock()) for mod_name in MOCK_MODULES) # The version info for the project you're documenting, acts as replacement for
fixed an outdated ref in doc build
bmcfee_resampy
train
1825edccf258f24479e75481cfe7e14139a1e878
diff --git a/actionview/test/template/sanitizers_test.rb b/actionview/test/template/sanitizers_test.rb index <HASH>..<HASH> 100644 --- a/actionview/test/template/sanitizers_test.rb +++ b/actionview/test/template/sanitizers_test.rb @@ -11,38 +11,38 @@ class SanitizersTest < ActionController::TestCase end end - def test_sanitizer_remove_xpaths_removes_an_xpath + def test_remove_xpaths_removes_an_xpath sanitizer = ActionView::Sanitizer.new html = %(<h1>hello <script>code!</script></h1>) assert_equal %(<h1>hello </h1>), sanitizer.remove_xpaths(html, %w(.//script)) end - def test_sanitizer_remove_xpaths_removes_all_occurences_of_xpath + def test_remove_xpaths_removes_all_occurences_of_xpath sanitizer = ActionView::Sanitizer.new html = %(<section><header><script>code!</script></header><p>hello <script>code!</script></p></section>) assert_equal %(<section><header></header><p>hello </p></section>), sanitizer.remove_xpaths(html, %w(.//script)) end - def test_sanitizer_remove_xpaths_not_enumerable_xpaths_parameter + def test_remove_xpaths_not_enumerable_xpaths_parameter sanitizer = ActionView::Sanitizer.new assert_raises NoMethodError do sanitizer.remove_xpaths('<h1>hello<h1>', './not_enumerable') end end - def test_sanitizer_remove_xpaths_faulty_xpath + def test_remove_xpaths_faulty_xpath sanitizer = ActionView::Sanitizer.new assert_raises Nokogiri::XML::XPath::SyntaxError do sanitizer.remove_xpaths('<h1>hello<h1>', %w(..faulty_xpath)) end end - def test_sanitizer_remove_xpaths_called_with_string_returns_string + def test_remove_xpaths_called_with_string_returns_string sanitizer = ActionView::Sanitizer.new assert '<a></a>', sanitizer.remove_xpaths('<a></a>', []) end - def test_sanitizer_remove_xpaths_called_with_fragment_returns_fragment + def test_remove_xpaths_called_with_fragment_returns_fragment sanitizer = ActionView::Sanitizer.new fragment = sanitizer.remove_xpaths(Loofah.fragment('<a></a>'), []) assert_kind_of Loofah::HTML::DocumentFragment, fragment
Renamed: remove_xpaths tests no longer prefixed with sanitizer.
rails_rails
train
4369e728f77d5a6269b2236690bc7c136a5d9b07
diff --git a/src/main/java/com/github/jsonj/JsonArray.java b/src/main/java/com/github/jsonj/JsonArray.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/github/jsonj/JsonArray.java +++ b/src/main/java/com/github/jsonj/JsonArray.java @@ -132,6 +132,12 @@ public class JsonArray extends ArrayList<JsonElement> implements JsonElement { } } + public void add(JsonDataObject...elements) { + for (JsonDataObject element : elements) { + add(element.getJsonObject()); + } + } + @Override public boolean add(JsonElement e) { if(immutable) { @@ -362,6 +368,7 @@ public class JsonArray extends ArrayList<JsonElement> implements JsonElement { return array; } + @Override public boolean isMutable() { return !immutable; } diff --git a/src/main/java/com/github/jsonj/JsonObject.java b/src/main/java/com/github/jsonj/JsonObject.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/github/jsonj/JsonObject.java +++ b/src/main/java/com/github/jsonj/JsonObject.java @@ -207,6 +207,10 @@ public class JsonObject implements Map<String, JsonElement>, JsonElement { return put(key, primitive(value)); } + public JsonElement put(String key, JsonDataObject object) { + return put(key, object.getJsonObject()); + } + @Override public JsonElement put(String key, JsonElement value) { Validate.notNull(key); @@ -716,6 +720,7 @@ public class JsonObject implements Map<String, JsonElement>, JsonElement { return object; } + @Override public boolean isMutable() { return intMap.isMutable(); } diff --git a/src/main/java/com/github/jsonj/tools/JsonBuilder.java b/src/main/java/com/github/jsonj/tools/JsonBuilder.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/github/jsonj/tools/JsonBuilder.java +++ b/src/main/java/com/github/jsonj/tools/JsonBuilder.java @@ -21,15 +21,15 @@ */ package com.github.jsonj.tools; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - import com.github.jsonj.JsonArray; +import com.github.jsonj.JsonDataObject; import com.github.jsonj.JsonElement; import com.github.jsonj.JsonObject; import com.github.jsonj.JsonPrimitive; import com.github.jsonj.JsonSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; /** * Builder class for json objects. If you plan to work a lot with jsonj, you will @@ -338,6 +338,12 @@ public class JsonBuilder { return jjArray; } + public static JsonArray array(final JsonDataObject... elements) { + JsonArray jjArray = new JsonArray(); + jjArray.add(elements); + return jjArray; + } + /** * @return an empty JsonSet */ @@ -466,6 +472,11 @@ public class JsonBuilder { return jjArray; } + public static JsonSet set(final JsonDataObject... elements) { + JsonSet jjArray = new JsonSet(); + jjArray.add(elements); + return jjArray; + } /** * @param value a boolean @@ -517,6 +528,8 @@ public class JsonBuilder { return new JsonObject((Map)o); } else if(o instanceof List) { return new JsonArray((List)o); + } else if(o instanceof JsonDataObject) { + return ((JsonDataObject) o).getJsonObject(); } return primitive(o); }
allow use of JsonDataObject when adding things so you don't have to call getJsonObject()
jillesvangurp_jsonj
train
009262159dc72dc7d719575a8295c31953b9ed47
diff --git a/src/cli.js b/src/cli.js index <HASH>..<HASH> 100644 --- a/src/cli.js +++ b/src/cli.js @@ -48,6 +48,16 @@ function init() { } }; +// Add handlers for verbose logging. +function initVerboseHandlers() { + if (args.verbose) { + cordova.on('verbose', console.log); + plugman.on('verbose', console.log); + } + +}; + + module.exports = cli function cli(inputArgs) { // When changing command line arguments, update doc/help.txt accordingly.
added verbose mode initialization to set up event handlers
apache_cordova-cli
train
ebd2b87d75b3788821db9a9ed81e891d2301cd98
diff --git a/lib/fluent/plugin/out_google_cloud.rb b/lib/fluent/plugin/out_google_cloud.rb index <HASH>..<HASH> 100644 --- a/lib/fluent/plugin/out_google_cloud.rb +++ b/lib/fluent/plugin/out_google_cloud.rb @@ -1298,6 +1298,9 @@ module Fluent 'FINE' => 'DEBUG', 'FINER' => 'DEBUG', 'FINEST' => 'DEBUG', + # java.util.logging levels (only missing ones from above listed). + 'SEVERE' => 'ERROR', + 'CONFIG' => 'DEBUG', # nginx levels (only missing ones from above listed). 'CRIT' => 'CRITICAL', 'EMERG' => 'EMERGENCY', diff --git a/test/plugin/test_out_google_cloud.rb b/test/plugin/test_out_google_cloud.rb index <HASH>..<HASH> 100644 --- a/test/plugin/test_out_google_cloud.rb +++ b/test/plugin/test_out_google_cloud.rb @@ -185,6 +185,7 @@ class GoogleCloudOutputTest < Test::Unit::TestCase # synonyms for existing log levels assert_equal('ERROR', test_obj.parse_severity('ERR')) + assert_equal('ERROR', test_obj.parse_severity('SEVERE')) assert_equal('WARNING', test_obj.parse_severity('WARN')) assert_equal('CRITICAL', test_obj.parse_severity('FATAL')) assert_equal('DEBUG', test_obj.parse_severity('TRACE')) @@ -192,6 +193,7 @@ class GoogleCloudOutputTest < Test::Unit::TestCase assert_equal('DEBUG', test_obj.parse_severity('FINE')) assert_equal('DEBUG', test_obj.parse_severity('FINER')) assert_equal('DEBUG', test_obj.parse_severity('FINEST')) + assert_equal('DEBUG', test_obj.parse_severity('CONFIG')) # single letters. assert_equal('DEBUG', test_obj.parse_severity('D'))
Add severity translations for java.util.logging. (#<I>) SEVERE -> ERROR, CONFIG -> DEBUG.
GoogleCloudPlatform_fluent-plugin-google-cloud
train
ddcd2e713aab61b75ac83466960faa6bb7409f82
diff --git a/lib/image_info/parser.rb b/lib/image_info/parser.rb index <HASH>..<HASH> 100644 --- a/lib/image_info/parser.rb +++ b/lib/image_info/parser.rb @@ -3,15 +3,15 @@ require 'image_size' module ImageInfo class Parser - attr_reader :image, :bytes, :parser + attr_reader :image def initialize(image, data) - @image = image - @bytes = data.bytes - @parser = ::ImageSize.new(data) + @image = image + @data = data end def call + return unless parser set_image_size set_image_type end @@ -26,6 +26,12 @@ module ImageInfo def set_image_type image.type = parser.format end - + + private + + def parser + @parser ||= ::ImageSize.new(@data) + rescue ImageSize::FormatError + end end end diff --git a/spec/image_info/parser_spec.rb b/spec/image_info/parser_spec.rb index <HASH>..<HASH> 100644 --- a/spec/image_info/parser_spec.rb +++ b/spec/image_info/parser_spec.rb @@ -55,6 +55,25 @@ describe ImageInfo::Parser do end + context 'partial image with not enough data' do + + let(:data) { File.open(File.expand_path('../../fixtures/upload_bird.jpg', __FILE__)).read(50) } + + it { expect { call }.not_to change { image.type } } + it { expect { call }.not_to change { image.size } } + + end + + + context 'partial image with enough data' do + + let(:data) { File.open(File.expand_path('../../fixtures/upload_bird.jpg', __FILE__)).read(400) } + + it { expect { call }.to change { image.type }.to eq(:jpeg) } + it { expect { call }.to change { image.size }.to eq([775, 525]) } + + end + end end
update parser to support partial images
gottfrois_image_info
train
945ce7ae24a6affac5590aa59444d98ac89018ad
diff --git a/network.go b/network.go index <HASH>..<HASH> 100644 --- a/network.go +++ b/network.go @@ -254,70 +254,14 @@ func (n *Graph) Connect(senderName, senderPort, receiverName, receiverPort strin // ConnectBuf connects a sender to a receiver using a channel with a buffer of a given size. // It returns true on success or panics and returns false if error occurs. func (n *Graph) ConnectBuf(senderName, senderPort, receiverName, receiverPort string, bufferSize int) error { - // Ensure sender and receiver processes exist - sender, senderFound := n.procs[senderName] - receiver, receiverFound := n.procs[receiverName] - if !senderFound { - return fmt.Errorf("Connect error: sender process '%s' not found", senderName) - } - if !receiverFound { - return fmt.Errorf("Connect error: receiver process '%s' not found", receiverName) - } - - // Ensure sender and receiver are settable - senderVal := reflect.ValueOf(sender) - if senderVal.Kind() == reflect.Ptr && senderVal.IsValid() { - senderVal = senderVal.Elem() - } - receiverVal := reflect.ValueOf(receiver) - if receiverVal.Kind() == reflect.Ptr && receiverVal.IsValid() { - receiverVal = receiverVal.Elem() - } - - if !senderVal.CanSet() { - return fmt.Errorf("Connect error: sender '%s' is not settable", senderName) - } - if !receiverVal.CanSet() { - return fmt.Errorf("Connect error: receiver '%s' is not settable", receiverName) - } - - // Get the actual ports and link them to the channel - var err error - - // Get the sender port - var senderPortVal reflect.Value - // Check if sender is a net - senderNet, senderIsNet := senderVal.Interface().(Graph) - if senderIsNet { - // Sender is a net - senderPortVal, err = senderNet.getOutPort(senderPort) - } else { - // Sender is a proc - senderPortVal = senderVal.FieldByName(senderPort) - if !senderPortVal.IsValid() { - err = errors.New("") - } - } + senderPortVal, err := n.getProcPort(senderName, senderPort, true) if err != nil { - return fmt.Errorf("Connect error: sender '%s' does not have outport '%s'", senderName, senderPort) + return err } - // Get the sender port - var receiverPortVal reflect.Value - // Check if sender is a net - receiverNet, receiverIsNet := receiverVal.Interface().(Graph) - if receiverIsNet { - // Sender is a net - receiverPortVal, err = receiverNet.getInPort(receiverPort) - } else { - // Sender is a proc - receiverPortVal = receiverVal.FieldByName(receiverPort) - if !receiverPortVal.IsValid() { - err = errors.New("") - } - } + receiverPortVal, err := n.getProcPort(receiverName, receiverPort, false) if err != nil { - return fmt.Errorf("Connect error: receiver '%s' does not have inport '%s'", receiverName, receiverPort) + return err } // Validate receiver port @@ -408,6 +352,50 @@ func (n *Graph) ConnectBuf(senderName, senderPort, receiverName, receiverPort st return nil } +func (n *Graph) getProcPort(procName, portName string, dirOut bool) (reflect.Value, error) { + nilValue := reflect.ValueOf(nil) + // Ensure process exists + proc, ok := n.procs[procName] + if !ok { + return nilValue, fmt.Errorf("Connect error: process '%s' not found", procName) + } + + // Ensure sender is settable + val := reflect.ValueOf(proc) + if val.Kind() == reflect.Ptr && val.IsValid() { + val = val.Elem() + } + if !val.CanSet() { + return nilValue, fmt.Errorf("Connect error: process '%s' is not settable", procName) + } + + // Get the sender port + var portVal reflect.Value + var err error + // Check if sender is a net + net, ok := val.Interface().(Graph) + if ok { + // Sender is a net + if dirOut { + portVal, err = net.getOutPort(portName) + } else { + portVal, err = net.getInPort(portName) + } + + } else { + // Sender is a proc + portVal = val.FieldByName(portName) + if !portVal.IsValid() { + err = errors.New("") + } + } + if err != nil { + return nilValue, fmt.Errorf("Connect error: process '%s' does not have port '%s'", procName, portName) + } + + return portVal, nil +} + // // Unsets an port of a given process // func unsetProcPort(proc interface{}, portName string, isOut bool) bool { // v := reflect.ValueOf(proc)
Extract port getting logic to a function
trustmaster_goflow
train
22fef8c51a807975863b8e60d557e7c768cb3784
diff --git a/src/Composer/Compiler.php b/src/Composer/Compiler.php index <HASH>..<HASH> 100644 --- a/src/Composer/Compiler.php +++ b/src/Composer/Compiler.php @@ -111,6 +111,7 @@ class Compiler $finder->files() ->ignoreVCS(true) ->notPath('/\/(composer\.(json|lock)|[A-Z]+\.md|\.gitignore|phpunit\.xml\.dist|phpstan\.neon\.dist|phpstan-config\.neon)$/') + ->notPath('/bin\/(jsonlint|validate-json)(\.bat)?$/') ->notPath('symfony/debug/Resources/ext/') ->notPath('justinrainbow/json-schema/demo/') ->notPath('justinrainbow/json-schema/dist/') @@ -119,7 +120,6 @@ class Compiler ->exclude('Tests') ->exclude('tests') ->exclude('docs') - ->exclude('bin') ->in(__DIR__.'/../../vendor/') ->sort($finderSort) ; @@ -131,10 +131,13 @@ class Compiler realpath(__DIR__ . '/../../vendor/symfony/console/Resources/bin/hiddeninput.exe'), realpath(__DIR__ . '/../../vendor/symfony/polyfill-mbstring/Resources/mb_convert_variables.php8'), ); + $unexpectedFiles = array(); foreach ($finder as $file) { - if (!preg_match('{(/LICENSE|\.php)$}', $file) && !in_array(realpath($file), $extraFiles, true)) { - throw new \RuntimeException('Unexpected file should be added to the allow or deny lists: '.$file); + if (in_array(realpath($file), $extraFiles, true)) { + unset($extraFiles[array_search(realpath($file), $extraFiles, true)]); + } elseif (!preg_match('{(/LICENSE|\.php)$}', $file)) { + $unexpectedFiles[] = (string) $file; } if (preg_match('{\.php[\d.]*$}', $file)) { @@ -144,6 +147,13 @@ class Compiler } } + if ($extraFiles) { + throw new \RuntimeException('These files were expected but not added to the phar, they might be excluded or gone from the source package:'.PHP_EOL.implode(PHP_EOL, $extraFiles)); + } + if ($unexpectedFiles) { + throw new \RuntimeException('These files were unexpectedly added to the phar, make sure they are excluded or listed in $extraFiles:'.PHP_EOL.implode(PHP_EOL, $unexpectedFiles)); + } + // Add bin/composer $this->addComposerBin($phar);
Make sure no files are missing from the phar, fixes #<I>
composer_composer
train
f6b85ebb2ffa673d4884f29d69d54e5d9c15d22b
diff --git a/src/sap.ui.fl/src/sap/ui/fl/apply/_internal/connectors/Utils.js b/src/sap.ui.fl/src/sap/ui/fl/apply/_internal/connectors/Utils.js index <HASH>..<HASH> 100644 --- a/src/sap.ui.fl/src/sap/ui/fl/apply/_internal/connectors/Utils.js +++ b/src/sap.ui.fl/src/sap/ui/fl/apply/_internal/connectors/Utils.js @@ -132,6 +132,11 @@ sap.ui.define([ // Adding Query-Parameters to the Url if (mParameters) { + Object.keys(mParameters).forEach(function(sKey) { + if (mParameters[sKey] === undefined) { + delete mParameters[sKey]; + } + }); var sQueryParameters = encodeURLParameters(mParameters); if (sQueryParameters.length > 0) { diff --git a/src/sap.ui.fl/test/sap/ui/fl/qunit/write/_internal/connectors/PersonalizationConnector.qunit.js b/src/sap.ui.fl/test/sap/ui/fl/qunit/write/_internal/connectors/PersonalizationConnector.qunit.js index <HASH>..<HASH> 100644 --- a/src/sap.ui.fl/test/sap/ui/fl/qunit/write/_internal/connectors/PersonalizationConnector.qunit.js +++ b/src/sap.ui.fl/test/sap/ui/fl/qunit/write/_internal/connectors/PersonalizationConnector.qunit.js @@ -121,6 +121,31 @@ sap.ui.define([ }); }); + QUnit.test("given reset is called with optional parameters", function (assert) { + var mPropertyBag = { + url: "/flex/personalization", + reference: "reference", + generator: undefined, + selectorIds: undefined, + appVersion: "1.0.1", + changeTypes: undefined, + somethingNotNecessary: "somethingNotNecessary" + }; + var sExpectedUrl = "/flex/personalization/v1/changes/?reference=reference&appVersion=1.0.1"; + var sExpectedMethod = "DELETE"; + + var oStubSendRequest = sandbox.stub(ApplyUtils, "sendRequest").resolves({}); + var oSpyGetUrl = sandbox.spy(ApplyUtils, "getUrl"); + + return WritePersonalizationConnector.reset(mPropertyBag).then(function() { + assert.equal(oSpyGetUrl.getCall(0).args[0], "/v1/changes/", "with correct route path"); + assert.equal(oSpyGetUrl.getCall(0).args[1], mPropertyBag, "with correct property bag"); + assert.ok(oStubSendRequest.calledOnce, "sendRequest is called once"); + assert.equal(oStubSendRequest.getCall(0).args[0], sExpectedUrl, "with correct url"); + assert.equal(oStubSendRequest.getCall(0).args[1], sExpectedMethod, "with correct method"); + }); + }); + QUnit.test("given load features is called", function (assert) { var mExpectedFeatures = { isProductiveSystem: true
[INTERNAL][FIX] sap.ui.fl : Correct getUrl in apply connectors Utils Fixing the issue of constructing urls with undefined parameters Change-Id: I<I>c1b<I>d<I>ef<I>b9da2d6e7ecca4abe6ffbb
SAP_openui5
train
e79a6939f42638bfff45bc4bbddfe95a9f1c27c5
diff --git a/tests/integration/routes/account/delete-account-test.js b/tests/integration/routes/account/delete-account-test.js index <HASH>..<HASH> 100644 --- a/tests/integration/routes/account/delete-account-test.js +++ b/tests/integration/routes/account/delete-account-test.js @@ -98,8 +98,39 @@ getServer(function (error, server) { group.end() }) - test('DELETE /session/account?include=profile', {todo: true}, function (t) { - t.end() + test('DELETE /session/account?include=profile', function (t) { + mockCouchDbUserFound() + var couch = mockCouchDbUserFound({_rev: '1-234'}) + .put('/_users/org.couchdb.user%3Apat-doe', function (body) { + return Joi.object({ + _id: Joi.any().only('org.couchdb.user:pat-doe').required(), + _rev: '1-234', + _deleted: true, + name: Joi.any().only('pat-doe').required(), + type: Joi.any().only('user').required(), + salt: Joi.string().required(), + derived_key: Joi.string().required(), + iterations: Joi.any().only(10).required(), + password_scheme: Joi.any().only('pbkdf2').required(), + roles: Joi.array().items(Joi.string()) + }).validate(body).error === null + }) + .query(true) + .reply(201, { + ok: true, + id: 'org.couchdb.user:pat-doe', + rev: '2-3456' + }) + + var options = _.defaultsDeep({ + url: '/session/account?include=profile' + }, routeOptions) + + server.inject(options, function (response) { + t.is(couch.pendingMocks()[0], undefined, 'all mocks satisfied') + t.is(response.statusCode, 200, 'returns 200 status') + t.end() + }) }) test('DELETE /session/account?include=foobar', function (t) {
test(routes): DELETE /accounts/<I>?include=profile (#<I>) * test(routes): DELETE /accounts/<I>?include=profile * refactor(account): remove console.log
hoodiehq_hoodie-account-server
train
25949306545d15fd627729a2289925cd246e3a77
diff --git a/android/app/src/main/java/com/reactnativenavigation/params/parsers/CollapsingTopBarParamsParser.java b/android/app/src/main/java/com/reactnativenavigation/params/parsers/CollapsingTopBarParamsParser.java index <HASH>..<HASH> 100644 --- a/android/app/src/main/java/com/reactnativenavigation/params/parsers/CollapsingTopBarParamsParser.java +++ b/android/app/src/main/java/com/reactnativenavigation/params/parsers/CollapsingTopBarParamsParser.java @@ -23,7 +23,7 @@ class CollapsingTopBarParamsParser extends Parser { public CollapsingTopBarParams parse() { if (!validateParams()) { - return new CollapsingTopBarParams(); + return null; } CollapsingTopBarParams result = new CollapsingTopBarParams(); result.imageUri = params.getString("collapsingToolBarImage", null); diff --git a/android/app/src/main/java/com/reactnativenavigation/views/collapsingToolbar/ScrollViewDelegate.java b/android/app/src/main/java/com/reactnativenavigation/views/collapsingToolbar/ScrollViewDelegate.java index <HASH>..<HASH> 100644 --- a/android/app/src/main/java/com/reactnativenavigation/views/collapsingToolbar/ScrollViewDelegate.java +++ b/android/app/src/main/java/com/reactnativenavigation/views/collapsingToolbar/ScrollViewDelegate.java @@ -30,7 +30,7 @@ public class ScrollViewDelegate implements View.OnTouchListener { } public boolean didInterceptTouchEvent(MotionEvent ev) { - return listener.onTouch(ev); + return listener.onTouch(ev); } @Override
CollapsingTopTabs params are nullable
wix_react-native-navigation
train
5e602e405063a1f89d7866bba1fbd2887fe36c70
diff --git a/app/models/manifestation.rb b/app/models/manifestation.rb index <HASH>..<HASH> 100644 --- a/app/models/manifestation.rb +++ b/app/models/manifestation.rb @@ -551,6 +551,10 @@ class Manifestation < ActiveRecord::Base identifiers = identifiers.keys.sort header += identifiers header += %w( + classification + ) if defined?(EnjuSubject) + + header += %w( item_id item_identifier call_number @@ -565,6 +569,7 @@ class Manifestation < ActiveRecord::Base item_created_at item_updated_at ) + lines = [] lines << header Manifestation.includes(:items, :identifiers => :identifier_type).find_each do |m| @@ -585,6 +590,9 @@ class Manifestation < ActiveRecord::Base identifiers.each do |identifier_type| item_lines << m.identifier_contents(identifier_type.to_sym).first end + item_lines << m.classifications.map{|classification| + {"#{classification.classification_type.name}": "#{classification.category}"} + }.reduce(Hash.new, :merge).to_json item_lines << i.id item_lines << i.item_identifier item_lines << i.call_number diff --git a/spec/models/manifestation_spec.rb b/spec/models/manifestation_spec.rb index <HASH>..<HASH> 100644 --- a/spec/models/manifestation_spec.rb +++ b/spec/models/manifestation_spec.rb @@ -226,6 +226,7 @@ describe Manifestation, :solr => true do context ".export" do it "should export a header line" do lines = Manifestation.export + CSV.parse(lines) (header, *lines) = lines.split(/\r?\n/) header = header.split(/\t/) expect(header.size).to eq lines.first.split(/\t/).size
export classification next-l/enju_leaf#<I>
next-l_enju_biblio
train
3a0b38f14237d5e6cf334e86a633a54a2c8c957a
diff --git a/package.js b/package.js index <HASH>..<HASH> 100644 --- a/package.js +++ b/package.js @@ -28,7 +28,7 @@ Package.registerBuildPlugin({ Package.on_use(function (api) { api.versionsFrom('[email protected]'); - api.use('angularjs:[email protected]', 'client'); + api.use('angularjs:[email protected]', 'client'); api.use('minimongo'); // for idStringify api.use('observe-sequence'); api.use('dburles:[email protected]', 'client'); // For getCollectionByName
Update Angular dependency to <I>
Urigo_angular-meteor
train
be23c63ea000c08017e23d16666697cae0c0dbba
diff --git a/library.js b/library.js index <HASH>..<HASH> 100644 --- a/library.js +++ b/library.js @@ -72,7 +72,8 @@ plugin.addPrefetchTags = function(tags, callback) { plugin.getFormattingOptions = function(callback) { plugins.fireHook('filter:composer.formatting', { options: [ - { name: 'tags', className: 'fa fa-tags', mobile: true } + { name: 'tags', className: 'fa fa-tags', mobile: true }, + { name: 'zen', className: 'fa fa-arrows-alt', mobile: false } ] }, function(err, payload) { callback(err, payload ? payload.options : null); diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -24,5 +24,8 @@ "readmeFilename": "README.md", "nbbpm": { "compatibility": "^1.0.0" + }, + "dependencies": { + "screenfull": "3.0.0" } } diff --git a/plugin.json b/plugin.json index <HASH>..<HASH> 100644 --- a/plugin.json +++ b/plugin.json @@ -13,7 +13,8 @@ "./static/less/composer.less" ], "scripts": [ - "./static/lib/client.js" + "./static/lib/client.js", + "./node_modules/screenfull/dist/screenfull.js" ], "modules": { "composer.js": "./static/lib/composer.js", diff --git a/static/lib/composer/formatting.js b/static/lib/composer/formatting.js index <HASH>..<HASH> 100644 --- a/static/lib/composer/formatting.js +++ b/static/lib/composer/formatting.js @@ -1,8 +1,8 @@ 'use strict'; -/* globals define */ +/* globals define, screenfull */ -define('composer/formatting', ['composer/controls', 'composer/preview'], function(controls, preview) { +define('composer/formatting', ['composer/controls', 'composer/preview', 'composer/resize'], function(controls, preview, resize) { var formatting = {}; @@ -17,6 +17,25 @@ define('composer/formatting', ['composer/controls', 'composer/preview'], functio tags: function() { $('.tags-container').toggleClass('hidden'); + }, + + zen: function() { + var postContainer = this; + $(window).one('resize', function(e) { + if (screenfull.isFullscreen) { + app.toggleNavbar(false); + resize.maximize(postContainer, true); + postContainer.find('.resizer').hide(); + + $(window).one('resize', function(e) { + app.toggleNavbar(true); + resize.maximize(postContainer, false); + postContainer.find('.resizer').show(); + }); + } + }); + + screenfull.toggle(); } }; @@ -49,7 +68,7 @@ define('composer/formatting', ['composer/controls', 'composer/preview'], functio textarea = $(this).parents('[component="composer"]').find('textarea')[0]; if(formattingDispatchTable.hasOwnProperty(format)){ - formattingDispatchTable[format](textarea, textarea.selectionStart, textarea.selectionEnd); + formattingDispatchTable[format].call(postContainer, textarea, textarea.selectionStart, textarea.selectionEnd); preview.render(postContainer); } }); diff --git a/static/lib/composer/resize.js b/static/lib/composer/resize.js index <HASH>..<HASH> 100644 --- a/static/lib/composer/resize.js +++ b/static/lib/composer/resize.js @@ -26,6 +26,14 @@ define('composer/resize', [], function() { doResize(postContainer, percentage); }; + resize.maximize = function(postContainer, state) { + if (state) { + doResize(postContainer, 1); + } else { + resize.reposition(postContainer); + } + }; + function doResize(postContainer, percentage) { var env = utils.findBootstrapEnvironment();
added support for zen mode, closes nodebb/nodebb#<I>
NodeBB_nodebb-plugin-composer-default
train
3a042e855869faec7961330622fd2c30acb05d4b
diff --git a/test/unexpected.spec.js b/test/unexpected.spec.js index <HASH>..<HASH> 100644 --- a/test/unexpected.spec.js +++ b/test/unexpected.spec.js @@ -1,4 +1,4 @@ -/*global describe, it, expect, beforeEach*/ +/*global describe, it, expect, beforeEach, setTimeout*/ // use this instead of Object.create in order to make the tests run in // browsers that are not es5 compatible. @@ -1140,33 +1140,78 @@ describe('unexpected', function () { describe('error modes', function () { var errorMode = 'default'; var clonedExpect; - beforeEach(function () { - clonedExpect = expect.clone().addAssertion('to be sorted', function (expect, subject) { - this.errorMode = errorMode; - expect(subject, 'to be an array'); - expect(subject, 'to equal', [].concat(subject).sort()); + + describe('for synchronous custom assertions', function () { + beforeEach(function () { + clonedExpect = expect.clone() + .addAssertion('to be sorted', function (expect, subject) { + this.errorMode = errorMode; + expect(subject, 'to be an array'); + expect(subject, 'to equal', [].concat(subject).sort()); + }); }); - }); - it('errorMode=nested nest the error message of expect failures in the assertion under the assertion standard message', function () { - errorMode = 'nested'; - expect(function () { - clonedExpect(42, 'to be sorted'); - }, 'to throw', 'expected 42 to be sorted\n expected 42 to be an array'); - }); + it('errorMode=nested nest the error message of expect failures in the assertion under the assertion standard message', function () { + errorMode = 'nested'; + expect(function () { + clonedExpect(42, 'to be sorted'); + }, 'to throw', 'expected 42 to be sorted\n expected 42 to be an array'); + }); - it('errorMode=bubble bubbles uses the error message of expect failures in the assertion', function () { - errorMode = 'bubble'; - expect(function () { - clonedExpect(42, 'to be sorted'); - }, 'to throw', 'expected 42 to be an array'); + it('errorMode=bubble bubbles uses the error message of expect failures in the assertion', function () { + errorMode = 'bubble'; + expect(function () { + clonedExpect(42, 'to be sorted'); + }, 'to throw', 'expected 42 to be an array'); + }); + + it('errorMode=default uses the standard error message of the assertion', function () { + errorMode = 'default'; + expect(function () { + clonedExpect(42, 'to be sorted'); + }, 'to throw', 'expected 42 to be sorted'); + }); }); - it('errorMode=default uses the standard error message of the assertion', function () { - errorMode = 'default'; - expect(function () { - clonedExpect(42, 'to be sorted'); - }, 'to throw', 'expected 42 to be sorted'); + describe('for asynchronous custom assertions', function () { + beforeEach(function () { + clonedExpect = expect.clone() + .addAssertion('to be sorted after delay', function (expect, subject, delay, done) { + this.errorMode = errorMode; + setTimeout(function () { + try { + expect(subject, 'to be an array'); + expect(subject, 'to equal', [].concat(subject).sort()); + } catch (e) { + done(e); + } + }, delay); + }); + }); + + it('errorMode=nested nest the error message of expect failures in the assertion under the assertion standard message', function (done) { + errorMode = 'nested'; + clonedExpect(42, 'to be sorted after delay', 1, function (err) { + expect(err.message, 'to match', /^expected 42 to be sorted after delay 1.*\n expected 42 to be an array/); + done(); + }); + }); + + it('errorMode=bubble bubbles uses the error message of expect failures in the assertion', function (done) { + errorMode = 'bubble'; + clonedExpect(42, 'to be sorted after delay', 1, function (err) { + expect(err.message, 'to match', /^expected 42 to be an array/); + done(); + }); + }); + + it('errorMode=default uses the standard error message of the assertion', function (done) { + errorMode = 'default'; + clonedExpect(42, 'to be sorted after delay', 1, function (err) { + expect(err.message, 'to match', /^expected 42 to be sorted after delay 1/); + done(); + }); + }); }); });
Test error modes for asynchronous custom assertions
unexpectedjs_unexpected
train
43d8eb2a8ad504fb17c157d5857d9954a200bab9
diff --git a/bika/lims/content/referenceanalysis.py b/bika/lims/content/referenceanalysis.py index <HASH>..<HASH> 100644 --- a/bika/lims/content/referenceanalysis.py +++ b/bika/lims/content/referenceanalysis.py @@ -151,6 +151,30 @@ class ReferenceAnalysis(AbstractAnalysis): """ return [] + @deprecated("[1710] Reference Analyses do not support Interims") + def setInterimFields(self, interims=None , **kwargs): + pass + + @deprecated("[1710] Reference Analyses do not support Interims") + def getInterimFields(self): + return [] + + @deprecated("[1710] Reference Analyses do not support Calculations") + def setCalculation(self, calculation=None, **kwargs): + pass + + @deprecated("[1710] Reference Analyses do not support Calculations") + def getCalculation(self): + return None + + @deprecated("[1710] Reference Analyses do not support Calculations") + def getCalculationTitle(self): + return None + + @deprecated("[1710] Reference Analyses do not support Calculations") + def getCalculationUID(self): + return None + @deprecated('[1705] Use bika.lims.workflow.analysis.events.after_submit') @security.public def workflow_script_submit(self):
Temporary fix. Error when adding reference analysis in a Worksheet
senaite_senaite.core
train
25eb76af1dc60b1c6a1f866792166bf97538cbbc
diff --git a/ladybug/analysisperiod.py b/ladybug/analysisperiod.py index <HASH>..<HASH> 100644 --- a/ladybug/analysisperiod.py +++ b/ladybug/analysisperiod.py @@ -64,7 +64,6 @@ class AnalysisPeriod(object): '_timestamps_data', '_datetimes' ) - # TODO: handle timestep between 1-60 def __init__(self, st_month=1, st_day=1, st_hour=0, end_month=12, end_day=31, end_hour=23, timestep=1, is_leap_year=False): """Init an analysis period. diff --git a/ladybug/cli/_helper.py b/ladybug/cli/_helper.py index <HASH>..<HASH> 100644 --- a/ladybug/cli/_helper.py +++ b/ladybug/cli/_helper.py @@ -7,13 +7,11 @@ import json from ladybug.analysisperiod import AnalysisPeriod -def _load_analysis_period_json(analysis_period_json): +def _load_analysis_period_str(analysis_period_str): """Load an AnalysisPeriod from a JSON file. Args: - analysis_period_json: A JSON file of an AnalysisPeriod to be loaded. + analysis_period_str: A JSON file of an AnalysisPeriod to be loaded. """ - if analysis_period_json is not None and analysis_period_json != 'None': - with open(analysis_period_json) as json_file: - data = json.load(json_file) - return AnalysisPeriod.from_dict(data) + if analysis_period_str is not None and analysis_period_str != 'None': + return AnalysisPeriod.from_string(analysis_period_str) diff --git a/ladybug/cli/translate.py b/ladybug/cli/translate.py index <HASH>..<HASH> 100644 --- a/ladybug/cli/translate.py +++ b/ladybug/cli/translate.py @@ -7,7 +7,7 @@ from ladybug.wea import Wea from ladybug.ddy import DDY from ladybug.epw import EPW -from ._helper import _load_analysis_period_json +from ._helper import _load_analysis_period_str _logger = logging.getLogger(__name__) @@ -20,9 +20,9 @@ def translate(): @translate.command('epw-to-wea') @click.argument('epw-file', type=click.Path( exists=True, file_okay=True, dir_okay=False, resolve_path=True)) [email protected]('--analysis-period', '-ap', help='An AnalysisPeriod JSON to filter ' - 'the datetimes in the resulting Wea. If unspecified, the Wea will ' - 'be annual.', default=None, type=str) [email protected]('--analysis-period', '-ap', help='An AnalysisPeriod string to filter the ' + 'datetimes in the resulting Wea (eg. "6/21 to 9/21 between 8 and 16 @1"). ' + 'If unspecified, the Wea will be annual.', default=None, type=str) @click.option('--timestep', '-t', help='An optional integer to set the number of ' 'time steps per hour. Default is 1 for one value per hour. Note that ' 'this input will only do a linear interpolation over the data in the EPW ' @@ -39,7 +39,7 @@ def epw_to_wea(epw_file, analysis_period, timestep, output_file): """ try: wea_obj = Wea.from_epw_file(epw_file, timestep) - analysis_period = _load_analysis_period_json(analysis_period) + analysis_period = _load_analysis_period_str(analysis_period) if analysis_period is not None: wea_obj = wea_obj.filter_by_analysis_period(analysis_period) output_file.write(wea_obj.to_file_string()) diff --git a/tests/cli_translate_test.py b/tests/cli_translate_test.py index <HASH>..<HASH> 100644 --- a/tests/cli_translate_test.py +++ b/tests/cli_translate_test.py @@ -1,8 +1,11 @@ """Test cli translate module.""" from click.testing import CliRunner +import os + from ladybug.cli.translate import epw_to_wea, epw_to_ddy +from ladybug.analysisperiod import AnalysisPeriod + -import os def test_epw_to_wea(): @@ -19,6 +22,15 @@ def test_epw_to_wea(): os.remove(output_wea) +def test_epw_to_wea_analysis_period(): + runner = CliRunner() + input_epw = './tests/fixtures/epw/chicago.epw' + + a_per = AnalysisPeriod(6, 21, 8, 9, 21, 17) + result = runner.invoke(epw_to_wea, [input_epw, '--analysis-period', str(a_per)]) + assert result.exit_code == 0 + + def test_epw_to_ddy(): runner = CliRunner() input_epw = './tests/fixtures/epw/chicago.epw'
fix(cli): Replace hacky use of analysis period JSON with string I realized that the AnalysisPeriod object already has all of its properties within its string representation. So just having people pass a string of an analysis period to the CLI will be much cleaner. And it allows us to get around the fact that queenbee does not support conditional artifacts.
ladybug-tools_ladybug
train
1e20eb9024add35f9d54d2e52218d61af6ef52be
diff --git a/ibis/mapd/operations.py b/ibis/mapd/operations.py index <HASH>..<HASH> 100644 --- a/ibis/mapd/operations.py +++ b/ibis/mapd/operations.py @@ -783,6 +783,7 @@ _unsupported_ops = [ ops.StringReplace, ops.StringJoin, ops.StringSplit, + ops.StringToTimestamp, ops.Translate, ops.StringAscii, ops.LPad,
Added StringToTimestamp as unsupported Resolves #<I>
ibis-project_ibis
train
91c4a543bb0c3b804cbd852538010f594c6e3c13
diff --git a/lib/cache.js b/lib/cache.js index <HASH>..<HASH> 100644 --- a/lib/cache.js +++ b/lib/cache.js @@ -17,8 +17,7 @@ module.exports = function(){ redis.get(key,function(error,reply){ if(!error && reply){ - reply = JSON.parse(reply); - + res.set('Content-Type', 'application/json'); res.json(reply); }else{ res.cache = function(timeout) {
Speed improvements for the caching layer, suggested by @minigod
apis-is_apis
train
57bd684c74a8e142a0c2678252efeb3d4971f96e
diff --git a/lib/models.js b/lib/models.js index <HASH>..<HASH> 100644 --- a/lib/models.js +++ b/lib/models.js @@ -11,7 +11,7 @@ var id = 1; models.User = Backbone.Model.extend({ defaults: { mode: "", - name: "" + name: "user" } }); diff --git a/lib/server.js b/lib/server.js index <HASH>..<HASH> 100644 --- a/lib/server.js +++ b/lib/server.js @@ -20,10 +20,7 @@ Server.prototype.listen = function(port) { this.networks.on( "all", function(type, data) { - if ([ - "users", - "messages" - ].indexOf(type) != -1) { + if (type == "users" || type == "messages") { self.sockets.emit(type, data); } else { self.sockets.emit("networks", self.networks); @@ -31,11 +28,8 @@ Server.prototype.listen = function(port) { } ); - var options = { - log: false - }; this.sockets = io - .listen(http, options) + .listen(http, {log: false}) .sockets; this.sockets.on("connection", function(socket) { socket.emit( @@ -58,18 +52,39 @@ function handleInput(input) { if (!target) { return; } - + var argv = input.text.substr(1).split(" "); var cmd = input.text.charAt(0) == "/" ? argv[0].toUpperCase() : ""; switch (cmd) { case "": + var irc = target.network.irc; + if (typeof irc !== "undefined") { + irc.say(target.channel.get("name"), input.text); + } target.channel.get("messages").add( - new models.Message({user: "user", text: input.text}) + new models.Message({ + user: target.network.get("nick"), + text: input.text + }) ); break; + case "QUERY": + var irc = target.network.irc; + if (argv[1] && typeof irc !== "undefined") { + var channels = target.network.get("channels"); + if (argv[1].charAt(0) != "#" && !channels.findWhere({name: argv[1]})) { + channels.add( + new models.Channel({ + name: argv[1] + }) + ); + } + } + break; + case "JOIN": var irc = target.network.irc; if (argv[1] && typeof irc !== "undefined") { @@ -79,15 +94,15 @@ function handleInput(input) { case "PART": var irc = target.network.irc; - if (argv[1] && typeof irc !== "undefined") { - irc.part(argv[1]); + if (typeof irc !== "undefined") { + irc.part(argv[1] ? argv[1] : target.channel.get("name")); } break; case "NAMES": var irc = target.network.irc; - if (argv[1] && typeof irc !== "undefined") { - irc.send("NAMES", argv[1]); + if (typeof irc !== "undefined") { + irc.send("NAMES", argv[1] ? argv[1] : target.channel.get("name")); } break; @@ -98,6 +113,9 @@ function handleInput(input) { new models.Network({host: argv[1]}) ); network.irc.addListener( + "error", function() { /* .. */ } + ); + network.irc.addListener( "raw", function() { handleEvent.apply(network, arguments); @@ -135,6 +153,31 @@ function handleEvent(argv) { var event = argv.command; switch (event) { + case "PRIVMSG": + var target = argv.args[0]; + if (target.charAt(0) != "#") { + target = argv.nick; + } + + var channel = channels.findWhere({name: target}); + var message = argv.args[1]; + + if (typeof channel == "undefined") { + channel = channels.add( + new models.Channel({ + name: target + }) + ); + } + + channel.get("messages").add( + new models.Message({ + user: argv.nick, + text: message + }) + ); + break; + case "JOIN": if (argv.nick == network.get("nick")) { channels.add( @@ -205,6 +248,17 @@ function handleEvent(argv) { "add", {}, users ); break; + + case "err_cannotsendtochan": + case "err_nosuchnick": + var channel = network.get("channels").findWhere({name: argv.args[1]}); + var messages = channel.get("messages"); + messages.add( + new models.Message({ + text: argv.args[2] + }) + ); + break; } // Debug
Sending queries and messages to channels now works
erming_shout
train
0c50538cf6649943c66d906271d0cf47a3aaf1cb
diff --git a/katharsis-core/src/main/java/io/katharsis/jackson/serializer/ContainerSerializer.java b/katharsis-core/src/main/java/io/katharsis/jackson/serializer/ContainerSerializer.java index <HASH>..<HASH> 100644 --- a/katharsis-core/src/main/java/io/katharsis/jackson/serializer/ContainerSerializer.java +++ b/katharsis-core/src/main/java/io/katharsis/jackson/serializer/ContainerSerializer.java @@ -118,7 +118,10 @@ public class ContainerSerializer extends JsonSerializer<Container> { writeAttributes(gen, data, includedFields, notAttributesFields); Set<ResourceField> relationshipFields = getRelationshipFields(resourceType, resourceInformation, includedFields); - writeRelationshipFields(container, gen, data, relationshipFields, includedRelations); + + if (!relationshipFields.isEmpty()) { + writeRelationshipFields(container, gen, data, relationshipFields, includedRelations); + } writeMetaField(gen, data, entry); writeLinksField(gen, data, entry); } diff --git a/katharsis-core/src/test/java/io/katharsis/jackson/ContainerSerializerTest.java b/katharsis-core/src/test/java/io/katharsis/jackson/ContainerSerializerTest.java index <HASH>..<HASH> 100644 --- a/katharsis-core/src/test/java/io/katharsis/jackson/ContainerSerializerTest.java +++ b/katharsis-core/src/test/java/io/katharsis/jackson/ContainerSerializerTest.java @@ -5,6 +5,7 @@ import static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson; import java.util.Collections; import java.util.Set; +import io.katharsis.resource.mock.models.*; import org.junit.Test; import com.fasterxml.jackson.annotation.JsonInclude.Include; @@ -14,11 +15,6 @@ import io.katharsis.queryParams.QueryParams; import io.katharsis.queryParams.QueryParamsBuilder; import io.katharsis.request.path.JsonPath; import io.katharsis.request.path.PathBuilder; -import io.katharsis.resource.mock.models.OtherPojo; -import io.katharsis.resource.mock.models.Pojo; -import io.katharsis.resource.mock.models.Project; -import io.katharsis.resource.mock.models.Task; -import io.katharsis.resource.mock.models.User; import io.katharsis.response.Container; import io.katharsis.response.HttpStatus; import io.katharsis.response.JsonApiResponse; @@ -226,4 +222,16 @@ public class ContainerSerializerTest extends BaseSerializerTest { // THEN assertThatJson(result).node("links.self").isEqualTo("https://service.local/projects/1"); } + + @Test + public void onResourceWithoutRelationshipsShouldNotIncludeRelationshipField() throws Exception { + // GIVEN + Memorandum memorandum = new Memorandum(); + + // WHEN + String result = sut.writeValueAsString(new Container(memorandum, testResponse)); + + // THEN + assertThatJson(result).node("relationships").isAbsent(); + } }
#<I> removed relationships object when not allowed (#<I>) closes #<I>
katharsis-project_katharsis-framework
train
dbbb1c1c8a1fa0a51677b5a74fcfe0e2561ced91
diff --git a/src/Illuminate/Database/Query/Builder.php b/src/Illuminate/Database/Query/Builder.php index <HASH>..<HASH> 100755 --- a/src/Illuminate/Database/Query/Builder.php +++ b/src/Illuminate/Database/Query/Builder.php @@ -1204,7 +1204,7 @@ class Builder $value, $operator, func_num_args() === 2 ); - $value = is_array($value) ? head($value) : $value; + $value = $this->scalarValue($value); if ($value instanceof DateTimeInterface) { $value = $value->format('d'); @@ -1294,7 +1294,7 @@ class Builder $value, $operator, func_num_args() === 2 ); - $value = is_array($value) ? head($value) : $value; + $value = $this->scalarValue($value); if ($value instanceof DateTimeInterface) { $value = $value->format('Y');
Update whereDay and whereYear to clean value.
laravel_framework
train
aad8c23d77d3e8e41888c2937569a0ccb50f9680
diff --git a/models/models.go b/models/models.go index <HASH>..<HASH> 100644 --- a/models/models.go +++ b/models/models.go @@ -26,12 +26,24 @@ type DependencyModel struct { // BrewDepModel ... type BrewDepModel struct { + // Name is the package name for Brew Name string `json:"name,omitempty" yaml:"name,omitempty"` + // BinName is the binary's name, if it doesn't match the package's name. + // Can be used for e.g. calling `which`. + // E.g. in case of "AWS CLI" the package is `awscli` and the binary is `aws`. + // If BinName is empty Name will be used as BinName too. + BinName string `json:"bin_name,omitempty" yaml:"bin_name,omitempty"` } // AptGetDepModel ... type AptGetDepModel struct { + // Name is the package name for Apt-get Name string `json:"name,omitempty" yaml:"name,omitempty"` + // BinName is the binary's name, if it doesn't match the package's name. + // Can be used for e.g. calling `which`. + // E.g. in case of "AWS CLI" the package is `awscli` and the binary is `aws`. + // If BinName is empty Name will be used as BinName too. + BinName string `json:"bin_name,omitempty" yaml:"bin_name,omitempty"` } // CheckOnlyDepModel ...
Deps extended with BinName for the use case when the package's name does not match the binary's name
bitrise-io_stepman
train
7af8e0fc20bb104029e6077a2f1fc905aeb2e34f
diff --git a/test/ffi-gobject/g_object_overrides_test.rb b/test/ffi-gobject/g_object_overrides_test.rb index <HASH>..<HASH> 100644 --- a/test/ffi-gobject/g_object_overrides_test.rb +++ b/test/ffi-gobject/g_object_overrides_test.rb @@ -200,6 +200,21 @@ class GObjectOverridesTest < MiniTest::Spec assert_equal :july, res end end + + describe "with info for an interface" do + before do + ifaceinfo = get_introspection_data 'Regress', 'TestInterface' + stub(arg_t = Object.new).interface { ifaceinfo } + stub(arg_t).tag { :interface } + stub(@info = Object.new).argument_type { arg_t } + end + + it "casts the argument by calling #to_object on it" do + mock(ptr = Object.new).to_object { "good-result" } + res = GObject::Helper.cast_signal_argument @info, ptr + res.must_equal "good-result" + end + end end end
Test handling of Interface types in signal callbacks.
mvz_gir_ffi
train
2ba4edf8d7f8a2262c168edff60fb88871b180de
diff --git a/samples/simple-mvvm/mobile/src/main/java/com/shipdream/lib/android/mvc/samples/simple/mvvm/controller/CounterDetailController.java b/samples/simple-mvvm/mobile/src/main/java/com/shipdream/lib/android/mvc/samples/simple/mvvm/controller/CounterDetailController.java index <HASH>..<HASH> 100644 --- a/samples/simple-mvvm/mobile/src/main/java/com/shipdream/lib/android/mvc/samples/simple/mvvm/controller/CounterDetailController.java +++ b/samples/simple-mvvm/mobile/src/main/java/com/shipdream/lib/android/mvc/samples/simple/mvvm/controller/CounterDetailController.java @@ -82,7 +82,7 @@ public class CounterDetailController extends AbstractScreenController< @Override public void onViewReady(Reason reason) { super.onViewReady(reason); - getModel().count = String.valueOf(counterManager.getModel().getCount()); + getModel().count = Integer.toString(counterManager.getModel().getCount()); } public void startContinuousIncrement() { @@ -126,7 +126,7 @@ public class CounterDetailController extends AbstractScreenController< private void onEvent(CounterManager.Event2C.OnCounterUpdated event) { //receive the event from manager and process the data and pass to view through //eventBusV - getModel().count = String.valueOf(event.getCount()); + getModel().count = Integer.toString(event.getCount()); postEvent(new Event.OnCountUpdated(getModel().getCount())); } }
Different way to convert int to string and try if it yields expected result on travis
kejunxia_AndroidMvc
train
e2b8723f28f92423d30646d22322605296eae4b9
diff --git a/angr/analyses/cfg.py b/angr/analyses/cfg.py index <HASH>..<HASH> 100644 --- a/angr/analyses/cfg.py +++ b/angr/analyses/cfg.py @@ -9,7 +9,7 @@ import angr from ..entry_wrapper import EntryWrapper from .cfg_base import CFGBase from ..analysis import Analysis -from ..errors import AngrCFGError +from ..errors import AngrCFGError, AngrError l = logging.getLogger(name="angr.analyses.cfg") @@ -69,7 +69,7 @@ class CFG(Analysis, CFGBase): :param project: The project object. :param context_sensitivity_level: The level of context-sensitivity of this CFG. - It ranges from 1 to infinity. + It ranges from 0 to infinity. :return: ''' CFGBase.__init__(self, self._p, context_sensitivity_level) @@ -1274,7 +1274,7 @@ class CFG(Analysis, CFGBase): func.prepared_registers.add(tuple(regs_overwritten)) func.prepared_stack_variables.add(tuple(stack_overwritten)) - except (simuvex.SimError): + except (simuvex.SimError, AngrError): pass try: @@ -1298,7 +1298,7 @@ class CFG(Analysis, CFGBase): func.registers_read_afterwards.add(tuple(regs_read)) - except simuvex.SimError: + except (simuvex.SimError, AngrError): pass def _remove_non_return_edges(self):
Catching AngrError as well when refining functions in CFG generation.
angr_angr
train
c12f891b1603aa5bb9b63730330c9ef79c13a620
diff --git a/mock_django/http.py b/mock_django/http.py index <HASH>..<HASH> 100644 --- a/mock_django/http.py +++ b/mock_django/http.py @@ -6,7 +6,6 @@ mock_django.http :license: Apache License 2.0, see LICENSE for more details. """ -from mock import Mock from django.contrib.auth.models import AnonymousUser from django.http import HttpRequest from django.utils.datastructures import MergeDict @@ -20,7 +19,6 @@ class WsgiHttpRequest(HttpRequest): super(WsgiHttpRequest, self).__init__(*args, **kwargs) self.user = AnonymousUser() self.session = {} - self.url = '/' self.META = {} self.GET = {} self.POST = {} @@ -31,9 +29,6 @@ class WsgiHttpRequest(HttpRequest): return self._request REQUEST = property(_get_request) - def build_absolute_uri(self, location=None): - return self.url - def _get_raw_post_data(self): if not hasattr(self, '_raw_post_data'): self._raw_post_data = urlencode(self.POST) @@ -45,7 +40,7 @@ class WsgiHttpRequest(HttpRequest): raw_post_data = property(_get_raw_post_data, _set_raw_post_data) -def MockHttpRequest(url='/', method='GET', GET=None, POST=None, META=None): +def MockHttpRequest(path='/', method='GET', GET=None, POST=None, META=None): if GET is None: GET = {} if POST is None: @@ -55,12 +50,13 @@ def MockHttpRequest(url='/', method='GET', GET=None, POST=None, META=None): if META is None: META = { 'REMOTE_ADDR': '127.0.0.1', + 'SERVER_PORT': '8000', 'HTTP_REFERER': '', 'SERVER_NAME': 'testserver', } request = WsgiHttpRequest() - request.url = url + request.path = request.path_info = path request.method = method request.META = META request.GET = GET
Renamed the `url` parameter of the MockHttpRequest to `path` since that's what I expected it to be. Also added a SERVER_PORT value to the default META so the `build_absolute_uri` method actually works.
dcramer_mock-django
train
b2a5506447e614bf0c7bee8100d47fe89c5f8756
diff --git a/salt/modules/boto_ec2.py b/salt/modules/boto_ec2.py index <HASH>..<HASH> 100644 --- a/salt/modules/boto_ec2.py +++ b/salt/modules/boto_ec2.py @@ -153,6 +153,41 @@ def find_instances(instance_id=None, name=None, tags=None, region=None, return False +def create_image(ami_name, instance_id=None, name=None, tags=None, region=None, + key=None, keyid=None, profile=None, description=None, no_reboot=False, + dry_run=False): + ''' + Given instance properties that define exactly one instance, create AMI and return AMI-id. + + CLI Examples: + + .. code-block:: bash + + salt myminion boto_ec2.create_instance ami_name name=myinstance + salt myminion boto_ec2.create_instance another_ami_name tags='{"mytag": "value"}' description='this is my ami' + + ''' + + instances = find_instances(instance_id=instance_id, name=name, tags=tags, + region=region, key=key, keyid=keyid, profile=profile, + return_objs=True) + + if not instances: + log.error('Source instance not found') + return False + if len(instances) > 1: + log.error('Multiple instances found, must match exactly only one instance to create an image from') + return False + + instance = instances[0] + try: + return instance.create_image(ami_name, description=description, + no_reboot=no_reboot, dry_run=dry_run) + except boto.exception.BotoServerError as exc: + log.error(exc) + return False + + def terminate(instance_id=None, name=None, region=None, key=None, keyid=None, profile=None): '''
Create_image function to create an AMI from existing instances
saltstack_salt
train
8567fb1a99467839b3c2c5628a394d608f8eb718
diff --git a/lib/paginate_alphabetically.rb b/lib/paginate_alphabetically.rb index <HASH>..<HASH> 100644 --- a/lib/paginate_alphabetically.rb +++ b/lib/paginate_alphabetically.rb @@ -10,7 +10,7 @@ module PaginateAlphabetically end def first_letter - first_instance = find(:first, :order => @attribute) + first_instance = find(:first, :order => @attribute, :conditions => ["#{@attribute.to_s} >= ?", 'a']) return 'A' if first_instance.nil? first_instance.send(@attribute)[0].chr.upcase end diff --git a/test/test_paginate_alphabetically.rb b/test/test_paginate_alphabetically.rb index <HASH>..<HASH> 100644 --- a/test/test_paginate_alphabetically.rb +++ b/test/test_paginate_alphabetically.rb @@ -13,6 +13,14 @@ class PaginateAlphabeticallyTest < ActiveSupport::TestCase assert_equal 'F', Thing.first_letter end + test "first letter is alphabetical" do + Thing.create!(:name => ' o noes a space :(') + Thing.create!(:name => '1') + Thing.create!(:name => '®') + Thing.create!(:name => '$') + assert_equal 'F', Thing.first_letter + end + test "first letter when there are no things" do Thing.destroy_all assert_equal 'A', Thing.first_letter
Ensure that the first letter is always a letter of the alphabet.
edendevelopment_paginate_alphabetically
train
ed834dbd4a76a2dc25fb353449f345751826b038
diff --git a/impl-tinkerpop-parent/impl/src/main/java/org/hawkular/inventory/impl/tinkerpop/TinkerpopInventory.java b/impl-tinkerpop-parent/impl/src/main/java/org/hawkular/inventory/impl/tinkerpop/TinkerpopInventory.java index <HASH>..<HASH> 100644 --- a/impl-tinkerpop-parent/impl/src/main/java/org/hawkular/inventory/impl/tinkerpop/TinkerpopInventory.java +++ b/impl-tinkerpop-parent/impl/src/main/java/org/hawkular/inventory/impl/tinkerpop/TinkerpopInventory.java @@ -34,11 +34,26 @@ import java.util.ServiceLoader; public final class TinkerpopInventory extends BaseInventory<Element> { @Override protected InventoryBackend<Element> doInitialize(Configuration configuration) { - GraphProvider gp = ServiceLoader.load(GraphProvider.class).iterator().next(); - TransactionalGraph graph = gp.instantiateGraph(configuration); + GraphProvider<? extends TransactionalGraph> gp = loadGraph(); + TransactionalGraph g = ensureIndices(gp, configuration); - gp.ensureIndices(graph, + InventoryContext context = new InventoryContext(this, configuration.getFeedIdStrategy(), + configuration.getResultFilter(), g); + + return new TinkerpopBackend(context); + } + + private <T extends TransactionalGraph> GraphProvider<T> loadGraph() { + @SuppressWarnings("unchecked") + GraphProvider<T> gp = ServiceLoader.load(GraphProvider.class).iterator().next(); + return gp; + } + + private <T extends TransactionalGraph> T ensureIndices(GraphProvider<T> graphProvider, Configuration config) { + T graph = graphProvider.instantiateGraph(config); + + graphProvider.ensureIndices(graph, IndexSpec.builder() .withElementType(Vertex.class) .withProperty(Constants.Property.__type.name(), String.class) @@ -47,9 +62,6 @@ public final class TinkerpopInventory extends BaseInventory<Element> { .withElementType(Vertex.class) .withProperty(Constants.Property.__type.name(), String.class).build()); - InventoryContext context = new InventoryContext(this, configuration.getFeedIdStrategy(), - configuration.getResultFilter(), graph); - - return new TinkerpopBackend(context); + return graph; } }
Trivial - avoid unchecked warnings.
hawkular_hawkular-inventory
train
15bd15790ab1f1e722278e26c22e6530a60348d8
diff --git a/src/wavesurfer.js b/src/wavesurfer.js index <HASH>..<HASH> 100644 --- a/src/wavesurfer.js +++ b/src/wavesurfer.js @@ -171,7 +171,7 @@ var WaveSurfer = { timings: function (offset) { var position = this.backend.getCurrentTime() || 0; var duration = this.backend.getDuration() || 1; - position = Math.max(0, Math.min(duration, position + offset)); + position = Math.max(0, Math.min(duration, position + (isNaN(offset)? 0.0 : offset))); return [ position, duration ]; },
Do not attempt to add an offset to the position timing if the offset is NaN
katspaugh_wavesurfer.js
train
f75ea5c1f4e3d6340b875273ed47e66bbb52e194
diff --git a/docs/Connecting-to-MySQL-via-SSL.md b/docs/Connecting-to-MySQL-via-SSL.md index <HASH>..<HASH> 100644 --- a/docs/Connecting-to-MySQL-via-SSL.md +++ b/docs/Connecting-to-MySQL-via-SSL.md @@ -5,9 +5,12 @@ $sslCa = "/path/to/ca"; $sslKey = "/path/to/Key"; $sslCert = "/path/to/cert"; +$sslCaPath = "/path"; +$sslCipher = "DHE-RSA-AES256-SHA:AES128-SHA"; +$verifySsl = 0; // Since PHP 7.1 $db = \ByJG\AnyDataset\Factory::getDbRelationalInstance( - "mysql://localhost/database?ca=$sslCa&key=$sslKey&cert=$sslCert" + "mysql://localhost/database?ca=$sslCa&key=$sslKey&cert=$sslCert&capath=$sslCaPath&verifyssl=$verifySsl&cipher=$sslCipher" ); $iterator = $db->getIterator('select * from table where field = :value', ['value' => 10]); diff --git a/example.php b/example.php index <HASH>..<HASH> 100644 --- a/example.php +++ b/example.php @@ -1,7 +1,7 @@ <?php require "vendor/autoload.php"; -$db = new \ByJG\AnyDataset\Repository\DBDataset('mysql://root:[email protected]/development'); +$db = \ByJG\AnyDataset\Factory::getDbRelationalInstance('mysql://root:aaaaaaa@localhost/development'); $iterator = $db->getIterator('select * from airports where idairports = [[idairports]]', ['idairports' => 898]); diff --git a/src/Store/PdoMysql.php b/src/Store/PdoMysql.php index <HASH>..<HASH> 100644 --- a/src/Store/PdoMysql.php +++ b/src/Store/PdoMysql.php @@ -8,6 +8,15 @@ use PDO; class PdoMysql extends DbPdoDriver { + protected $mysqlAttr = [ + "ca" => PDO::MYSQL_ATTR_SSL_CA, + "capath" => PDO::MYSQL_ATTR_SSL_CAPATH, + "cert" => PDO::MYSQL_ATTR_SSL_CERT, + "key" => PDO::MYSQL_ATTR_SSL_KEY, + "cipher" => PDO::MYSQL_ATTR_SSL_CIPHER, + "verifyssl" => 1014 // PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT (>=7.1) + ]; + /** * PdoMysql constructor. * @@ -25,13 +34,13 @@ class PdoMysql extends DbPdoDriver PDO::ATTR_EMULATE_PREPARES => true ]; - $sslCa = $connUri->getQueryPart("ca"); - $sslCert = $connUri->getQueryPart("cert"); - $sslKey = $connUri->getQueryPart("key"); - if (!empty($sslCa) && !empty($sslCert) && !empty($sslKey)) { - $preOptions[PDO::MYSQL_ATTR_SSL_KEY] = urldecode($sslKey); - $preOptions[PDO::MYSQL_ATTR_SSL_CERT] = urldecode($sslCert); - $preOptions[PDO::MYSQL_ATTR_SSL_CA] = urldecode($sslCa); + if (!empty($connUri->getQuery())) { + foreach ($this->mysqlAttr as $key => $property) { + $value = $connUri->getQueryPart("key"); + if (!empty($value)) { + $preOptions[$property] = urldecode($value); + } + } } $this->setSupportMultRowset(true);
Added verifyssl, cipher and capath
byjg_anydataset
train
21b5ec5dc34c167fff30e23f61a556cfc5e13ac8
diff --git a/physical/raft/raft.go b/physical/raft/raft.go index <HASH>..<HASH> 100644 --- a/physical/raft/raft.go +++ b/physical/raft/raft.go @@ -542,7 +542,7 @@ func (b *RaftBackend) GetConfiguration(ctx context.Context) (*RaftConfigurationR Address: string(server.Address), Leader: server.Address == b.raft.Leader(), Voter: server.Suffrage == raft.Voter, - ProtocolVersion: string(raft.ProtocolVersionMax), + ProtocolVersion: strconv.Itoa(raft.ProtocolVersionMax), } config.Servers = append(config.Servers, entry) }
Fix raft config response (#<I>)
hashicorp_vault
train
c72c3d6a543ef4ea375323c2844cb5b690b538c1
diff --git a/source.go b/source.go index <HASH>..<HASH> 100644 --- a/source.go +++ b/source.go @@ -50,10 +50,13 @@ type baseSource struct { // TODO(sdboyer) rename to baseVCSSource // Whether the cache has the latest info on versions cvsync bool - // The project metadata cache. This is persisted to disk, for reuse across - // solver runs. - // TODO(sdboyer) protect with mutex + // The project metadata cache. This is (or is intended to be) persisted to + // disk, for reuse across solver runs. dc *sourceMetaCache + + // lvfunc allows the other vcs source types that embed this type to inject + // their listVersions func into the baseSource, for use as needed. + lvfunc func() (vlist []Version, err error) } func (bs *baseSource) getManifestAndLock(r ProjectRoot, v Version) (Manifest, Lock, error) { @@ -61,14 +64,17 @@ func (bs *baseSource) getManifestAndLock(r ProjectRoot, v Version) (Manifest, Lo return nil, nil, err } - if r, exists := bs.dc.vMap[v]; exists { - if pi, exists := bs.dc.infos[r]; exists { - return pi.Manifest, pi.Lock, nil - } + rev, err := bs.toRevOrErr(v) + if err != nil { + return nil, nil, err + } + + // Return the info from the cache, if we already have it + if pi, exists := bs.dc.infos[rev]; exists { + return pi.Manifest, pi.Lock, nil } bs.crepo.mut.Lock() - var err error if !bs.crepo.synced { err = bs.crepo.r.Update() if err != nil { @@ -84,6 +90,7 @@ func (bs *baseSource) getManifestAndLock(r ProjectRoot, v Version) (Manifest, Lo err = bs.crepo.r.UpdateVersion(v.String()) } bs.crepo.mut.Unlock() + if err != nil { // TODO(sdboyer) More-er proper-er error panic(fmt.Sprintf("canary - why is checkout/whatever failing: %s %s %s", bs.crepo.r.LocalPath(), v.String(), err)) @@ -105,11 +112,7 @@ func (bs *baseSource) getManifestAndLock(r ProjectRoot, v Version) (Manifest, Lo Lock: l, } - // TODO(sdboyer) this just clobbers all over and ignores the paired/unpaired - // distinction; serious fix is needed - if r, exists := bs.dc.vMap[v]; exists { - bs.dc.infos[r] = pi - } + bs.dc.infos[rev] = pi return pi.Manifest, pi.Lock, nil } @@ -146,7 +149,7 @@ func (dc *sourceMetaCache) toUnpaired(v Version) UnpairedVersion { case UnpairedVersion: return t case PairedVersion: - return t.Underlying() + return t.Unpair() case Revision: if upv, has := dc.rMap[t]; has && len(upv) > 0 { return upv[0] @@ -282,28 +285,16 @@ func (bs *baseSource) listPackages(pr ProjectRoot, v Version) (ptree PackageTree return } - // See if we can find it in the cache var r Revision - switch v.(type) { - case Revision, PairedVersion: - var ok bool - if r, ok = v.(Revision); !ok { - r = v.(PairedVersion).Underlying() - } - - if ptree, cached := bs.dc.ptrees[r]; cached { - return ptree, nil - } - default: - var has bool - if r, has = bs.dc.vMap[v]; has { - if ptree, cached := bs.dc.ptrees[r]; cached { - return ptree, nil - } - } + if r, err = bs.toRevOrErr(v); err != nil { + return } - // TODO(sdboyer) handle the case where we have a version w/out rev, and not in cache + // Return the ptree from the cache, if we already have it + var exists bool + if ptree, exists = bs.dc.ptrees[r]; exists { + return + } // Not in the cache; check out the version and do the analysis bs.crepo.mut.Lock() @@ -335,6 +326,31 @@ func (bs *baseSource) listPackages(pr ProjectRoot, v Version) (ptree PackageTree return } +// toRevOrErr makes all efforts to convert a Version into a rev, including +// updating the cache repo (if needed). It does not guarantee that the returned +// Revision actually exists in the repository (as one of the cheaper methods may +// have had bad data). +func (bs *baseSource) toRevOrErr(v Version) (r Revision, err error) { + r = bs.dc.toRevision(v) + if r == "" { + // Rev can be empty if: + // - The cache is unsynced + // - A version was passed that used to exist, but no longer does + // - A garbage version was passed. (Functionally indistinguishable from + // the previous) + if !bs.cvsync { + // call the lvfunc to sync the meta cache + _, err = bs.lvfunc() + } + // If we still don't have a rev, then the version's no good + if r == "" { + err = fmt.Errorf("Version %s does not exist in source %s", v, bs.crepo.r.Remote()) + } + } + + return +} + func (bs *baseSource) exportVersionTo(v Version, to string) error { return bs.crepo.exportVersionTo(v, to) }
Refactor baseSource to use UnpairedV in metacache
sdboyer_gps
train
193e60ac15c39b292d93d1d1c00952d0ec32b927
diff --git a/examples/electron-example/main.js b/examples/electron-example/main.js index <HASH>..<HASH> 100644 --- a/examples/electron-example/main.js +++ b/examples/electron-example/main.js @@ -1,22 +1,23 @@ -'use strict'; - -const {app} = require('electron'); -const ioHook = require('../../index'); - -function eventHandler(event) { - console.log(event); -} - -app.on('ready', () => { - ioHook.start(true); - ioHook.on('mouseclick', eventHandler); - ioHook.on('keypress', eventHandler); - ioHook.on('mousewheel', eventHandler); - ioHook.on('mousemove', eventHandler); - console.log('Try move your mouse or press any key'); -}); - -app.on('before-quit', () => { - ioHook.unload(); - ioHook.stop(); -}); +'use strict'; + +const {app} = require('electron'); +const ioHook = require('../../index'); + +function eventHandler(event) { + console.log(event); +} + +app.on('ready', () => { + console.log("node: "+process.versions.node+", chromium: "+process.versions.chrome+", electron: "+process.versions.electron); + ioHook.start(true); + ioHook.on('mouseclick', eventHandler); + ioHook.on('keydown', eventHandler); + ioHook.on('mousewheel', eventHandler); + ioHook.on('mousemove', eventHandler); + console.log('Try move your mouse or press any key'); +}); + +app.on('before-quit', () => { + ioHook.unload(); + ioHook.stop(); +});
replace deprecated "keypress" with "keydown"
wilix-team_iohook
train
962088a499b04fb6cb6052bb6fb1cd287dbd9396
diff --git a/bundles/org.eclipse.orion.client.core/web/orion/explorer-table.js b/bundles/org.eclipse.orion.client.core/web/orion/explorer-table.js index <HASH>..<HASH> 100644 --- a/bundles/org.eclipse.orion.client.core/web/orion/explorer-table.js +++ b/bundles/org.eclipse.orion.client.core/web/orion/explorer-table.js @@ -285,7 +285,7 @@ define(['require', 'dojo', 'orion/util', 'orion/explorer', 'orion/breadcrumbs', new mBreadcrumbs.BreadCrumbs({ container: breadcrumb, resource: this.treeRoot, - firstSegmentName: this.fileClient.fileServiceName(this.treeRoot.Location) + firstSegmentName: this.fileClient.fileServiceName(this.treeRoot.Path) }); } mFileCommands.updateNavTools(this.registry, this, this.toolbarId, this.selectionToolsId, this.treeRoot); diff --git a/bundles/org.eclipse.orion.client.core/web/orion/fileClient.js b/bundles/org.eclipse.orion.client.core/web/orion/fileClient.js index <HASH>..<HASH> 100644 --- a/bundles/org.eclipse.orion.client.core/web/orion/fileClient.js +++ b/bundles/org.eclipse.orion.client.core/web/orion/fileClient.js @@ -128,8 +128,57 @@ define(["dojo", "orion/auth", "dojo/DeferredList"], function(dojo, mAuth){ d.reject("No Matching FileService for location:" + location); return d; } + + var _fileSystemsRoots = []; + var _allFileSystemsService = { + fetchChildren: function() { + var d = new dojo.Deferred(); + d.resolve(_fileSystemsRoots); + return d; + }, + createWorkspace: function() { + var d = new dojo.Deferred(); + d.reject("no file service"); + return d; + }, + loadWorkspaces: function() { + var d = new dojo.Deferred(); + d.reject("no file service"); + return d; + }, + loadWorkspace: function(location) { + var d = new dojo.Deferred(); + d.resolve({ + Directory: true, + Length: 0, + LocalTimeStamp: 0, + Name: "File Servers", + Location: "/", + Children: _fileSystemsRoots + }); + return d; + }, + search: _noMatch, + createProject: _noMatch, + createFolder: _noMatch, + createFile: _noMatch, + deleteFile: _noMatch, + moveFile: _noMatch, + copyFile: _noMatch, + read: _noMatch, + write: _noMatch + }; for(var j = 0; j < _references.length; ++j) { + _fileSystemsRoots[j] = { + Directory: true, + Length: 0, + LocalTimeStamp: 0, + Location: _references[j].getProperty("top"), + ChildrenLocation: _references[j].getProperty("top"), + Name: _references[j].getProperty("Name") + }; + var patternString = _references[j].getProperty("pattern") || ".*"; if (patternString[0] !== "^") { patternString = "^" + patternString; @@ -140,7 +189,10 @@ define(["dojo", "orion/auth", "dojo/DeferredList"], function(dojo, mAuth){ } this._getServiceIndex = function(location) { - if (!location || (location.length && location.length === 0)) { + // client must specify via "/" when a multi file service tree is truly wanted + if (location === "/") { + return -1; + } else if (!location || (location.length && location.length === 0)) { // TODO we could make the default file service a preference but for now we use the first one return 0; } @@ -153,11 +205,13 @@ define(["dojo", "orion/auth", "dojo/DeferredList"], function(dojo, mAuth){ }; this._getService = function(location) { - return _services[this._getServiceIndex(location)]; + var i = this._getServiceIndex(location); + return i === -1 ? _allFileSystemsService : _services[i]; }; this._getServiceName = function(location) { - return _names[this._getServiceIndex(location)]; + var i = this._getServiceIndex(location); + return i === -1 ? _allFileSystemsService.Name : _names[i]; }; }
Bug <I> - meaning of "root" in navigator when there are multiple file systems. Interpret "/" to mean show all file system roots
eclipse_orion.client
train
e2455f797cb0316e6ac487e9380b36dd8812332b
diff --git a/components/upload/ajaxUploader.js b/components/upload/ajaxUploader.js index <HASH>..<HASH> 100644 --- a/components/upload/ajaxUploader.js +++ b/components/upload/ajaxUploader.js @@ -61,6 +61,7 @@ function getError(options, xhr) { err.status = xhr.status; err.method = 'post'; err.url = options.action; + err.response = getBody(xhr); return err; }
feat(Upload): add response field to Error object, close #<I>
ksc-fe_kpc
train
af89a6681beb7740587403a0c2d42b46e2713476
diff --git a/tests/test_common.py b/tests/test_common.py index <HASH>..<HASH> 100644 --- a/tests/test_common.py +++ b/tests/test_common.py @@ -17,7 +17,7 @@ class TestGroupMatches(unittest.TestCase): Match(start=42, end=52, dist=1), Match(start=99, end=109, dist=0), ] - self.assertItemsEqual( + self.assertListEqual( group_matches(matches), [set([m]) for m in matches], ) @@ -28,7 +28,7 @@ class TestGroupMatches(unittest.TestCase): Match(start=42, end=52, dist=1), Match(start=99, end=109, dist=0), ] - self.assertItemsEqual( + self.assertListEqual( group_matches(matches + [matches[1]]), [set([m]) for m in matches], ) diff --git a/tests/test_fuzzysearch.py b/tests/test_fuzzysearch.py index <HASH>..<HASH> 100644 --- a/tests/test_fuzzysearch.py +++ b/tests/test_fuzzysearch.py @@ -272,7 +272,7 @@ class TestFuzzySearchBase(object): '''.split()) pattern = "GGGTTLTTSS" - self.assertItemsEqual( + self.assertListEqual( [Match(start=19, end=29, dist=1), Match(start=42, end=52, dist=0), Match(start=99, end=109, dist=0)], @@ -287,7 +287,7 @@ class TestFuzzySearchBase(object): '''.split()) pattern = "GGGTTLTTSS" - self.assertItemsEqual( + self.assertListEqual( [Match(start=19, end=29, dist=1), Match(start=42, end=52, dist=1), Match(start=99, end=109, dist=0)],
avoid using TestCase.assertItemsEqual() The reason is that it is not avialable in the stdlib's unittest.
taleinat_fuzzysearch
train
e95eed4cbda982d01cc59aa811b1e8c07ad280de
diff --git a/src/node-loaders.js b/src/node-loaders.js index <HASH>..<HASH> 100644 --- a/src/node-loaders.js +++ b/src/node-loaders.js @@ -9,17 +9,19 @@ var existsSync = fs.existsSync ? fs.existsSync : path.existsSync; var FileSystemLoader = Object.extend({ init: function(searchPaths) { if(searchPaths) { - this.searchPaths = lib.isArray(searchPaths) ? searchPaths : [searchPaths]; + searchPaths = lib.isArray(searchPaths) ? searchPaths : [searchPaths]; + // For windows, convert to forward slashes + this.searchPaths = searchPaths.map(path.normalize); } else { this.searchPaths = []; } + }, getSource: function(name) { var fullpath = null; var paths = this.searchPaths.concat(['', __dirname]); - for(var i=0; i<paths.length; i++) { var p = path.join(paths[i], name); if(p.indexOf(paths[i]) === 0 && existsSync(p)) {
Normalize the FileSystemLoader paths to ensure proper path separators on windows. (for running the unittests in windows)
mozilla_nunjucks
train
e04a2b4aa2717413dabd244051fba734cb0078b5
diff --git a/aws/resource_aws_kinesis_firehose_delivery_stream.go b/aws/resource_aws_kinesis_firehose_delivery_stream.go index <HASH>..<HASH> 100644 --- a/aws/resource_aws_kinesis_firehose_delivery_stream.go +++ b/aws/resource_aws_kinesis_firehose_delivery_stream.go @@ -1192,6 +1192,7 @@ func resourceAwsKinesisFirehoseDeliveryStream() *schema.Resource { "s3_backup_mode": { Type: schema.TypeString, + ForceNew: true, Optional: true, Default: "FailedDocumentsOnly", ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
Set ForceNew for s3_backup_mode in aws_kinesis_firehose_delivery_stream Fixes #<I>. Only for Elasticsearch target, because S3, Redshift and Splunk APIs support changes of this parameter.
terraform-providers_terraform-provider-aws
train
d0665e254df066fd3d2cf979c876008947ea5717
diff --git a/src/main/java/org/dita/dost/module/KeyrefModule.java b/src/main/java/org/dita/dost/module/KeyrefModule.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/dita/dost/module/KeyrefModule.java +++ b/src/main/java/org/dita/dost/module/KeyrefModule.java @@ -77,12 +77,9 @@ final class KeyrefModule extends AbstractPipelineModuleImpl { @Override public AbstractPipelineOutput execute(final AbstractPipelineInput input) throws DITAOTException { - final Collection<FileInfo> fis = new HashSet(job.getFileInfo(new Filter<FileInfo>() { - @Override - public boolean accept(final FileInfo f) { - return f.hasKeyref; - } - })); + final Collection<FileInfo> fis = job.getFileInfo(fileInfoFilter).stream() + .filter(f -> f.hasKeyref) + .collect(Collectors.toSet()); if (!fis.isEmpty()) { try { final String cls = Optional
Use configured file info filter in keyref module
dita-ot_dita-ot
train
edeb196465b5580b3f67e4e117842cc49f88aa1d
diff --git a/core/src/main/java/org/cache2k/impl/BaseCache.java b/core/src/main/java/org/cache2k/impl/BaseCache.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/org/cache2k/impl/BaseCache.java +++ b/core/src/main/java/org/cache2k/impl/BaseCache.java @@ -58,6 +58,7 @@ import org.cache2k.impl.util.TunableConstants; import org.cache2k.impl.util.TunableFactory; import java.lang.reflect.Array; +import java.lang.reflect.Field; import java.security.SecureRandom; import java.util.AbstractList; import java.util.AbstractMap; @@ -75,6 +76,7 @@ import java.util.NoSuchElementException; import java.util.Random; import java.util.Set; import java.util.Timer; +import java.util.TimerTask; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; @@ -1249,6 +1251,35 @@ public abstract class BaseCache<E extends Entry, K, T> } } + public String getEntryState(K key) { + E e = getEntryInternal(key); + synchronized (e) { + String _timerState = "n/a"; + if (e.task != null) { + _timerState = "<unavailable>"; + try { + Field f = TimerTask.class.getDeclaredField("state"); + f.setAccessible(true); + int _state = f.getInt(e.task); + _timerState = _state + ""; + } catch (Exception x) { + _timerState = x.toString(); + } + } + return + "Entry{" + System.identityHashCode(e) + "}, " + + "keyIdentityHashCode=" + System.identityHashCode(e.key) + ", " + + "valueIdentityHashCode=" + System.identityHashCode(e.value) + ", " + + "keyHashCode" + e.key.hashCode() + ", " + + "keyModifiedHashCode=" + e.hashCode + ", " + + "keyMutation=" + (modifiedHash(e.key.hashCode()) != e.hashCode) + ", " + + "modified=" + e.getLastModification() + ", " + + "nextRefreshTime(with state)=" + e.nextRefreshTime + ", " + + "hasTimer=" + (e.task != null ? "true" : "false") + ", " + + "timerState=" + _timerState; + } + } + private CacheEntry<K, T> returnCacheEntry(final K _key, final T _value, final Throwable _exception, final long _lastModification) { CacheEntry<K, T> ce = new CacheEntry<K, T>() { @Override
add method getEntryState() for diagnostics
cache2k_cache2k
train
44c518d682d9d9d013bdca8fe1f05ae55ce6f4cf
diff --git a/src/cr/cube/dimension.py b/src/cr/cube/dimension.py index <HASH>..<HASH> 100644 --- a/src/cr/cube/dimension.py +++ b/src/cr/cube/dimension.py @@ -452,12 +452,12 @@ class Dimension(object): Only meaningful when the dimension is known to be categorical (has base-type `categorical`). """ - dimension_type_categories = self._dimension_dict["type"].get("categories", []) - if not dimension_type_categories: + categories = self._dimension_dict["type"].get("categories", []) + if not categories: return False return all( category.get("date") - for category in dimension_type_categories + for category in categories if not category.get("missing", False) ) @@ -1003,10 +1003,6 @@ class _Subtotal(object): class _BaseSmoother(object): """Base class for smoothing objects""" - def __init__(self, dimension_transforms_dict, is_cat_date): - self._dimension_transforms_dict = dimension_transforms_dict - self._is_cat_date = is_cat_date - @classmethod def factory(cls, dimension_transforms_dict, is_cat_date): """Returns appropriate Smoother object according to transforms_dict"""
rfctr: clean name in dimension
Crunch-io_crunch-cube
train
4cf62cd3247dfd5291df33b6da08467623bcfdbf
diff --git a/src/Storage/ImageVersionsTrait.php b/src/Storage/ImageVersionsTrait.php index <HASH>..<HASH> 100644 --- a/src/Storage/ImageVersionsTrait.php +++ b/src/Storage/ImageVersionsTrait.php @@ -9,7 +9,8 @@ use Cake\Event\EventManager; trait ImageVersionsTrait { /** - * Gets a list of image versions for a given record. + * Gets a list of image versions for a file storage entity. + * * Use this method to get a list of ALL versions when needed or to cache all the * versions somewhere. This method will return all configured versions for an * image. For example you could store them serialized along with the file data @@ -22,6 +23,7 @@ trait ImageVersionsTrait { public function getImageVersions(EntityInterface $entity, $options = []) { $versionData = $this->_getImageVersionData($entity, $options); $versions = []; + foreach ($versionData as $version => $data) { $hash = Configure::read('FileStorage.imageHashes.' . $entity->get('model') . '.' . $version); $eventData = [ @@ -30,6 +32,7 @@ trait ImageVersionsTrait { 'version' => $version, 'options' => [] ]; + if (method_exists($this, 'dispatchEvent')) { $event = $this->dispatchEvent('ImageVersion.getVersions', $eventData); } else { @@ -40,6 +43,7 @@ trait ImageVersionsTrait { $versions[$version] = str_replace('\\', '/', $event->data['path']); } } + return $versions; } @@ -58,7 +62,9 @@ trait ImageVersionsTrait { Configure::write('FileStorage.imageSizes.' . $entity->get('model') . '.original', []); $versionData['original'] = []; } + $versionData['original'] = isset($options['originalVersion']) ? $options['originalVersion'] : 'original'; + return $versionData; } diff --git a/src/Storage/Listener/LegacyImageProcessingListener.php b/src/Storage/Listener/LegacyImageProcessingListener.php index <HASH>..<HASH> 100644 --- a/src/Storage/Listener/LegacyImageProcessingListener.php +++ b/src/Storage/Listener/LegacyImageProcessingListener.php @@ -13,6 +13,8 @@ use Burzum\FileStorage\Storage\StorageUtils; * @author Florian Krämer * @copy 2013 - 2015 Florian Krämer * @license MIT + * + * @deprecated This listener class is deprecated */ class LegacyImageProcessingListener extends AbstractListener { diff --git a/src/Storage/Listener/LegacyLocalFileStorageListener.php b/src/Storage/Listener/LegacyLocalFileStorageListener.php index <HASH>..<HASH> 100644 --- a/src/Storage/Listener/LegacyLocalFileStorageListener.php +++ b/src/Storage/Listener/LegacyLocalFileStorageListener.php @@ -15,6 +15,8 @@ use Cake\Event\Event; * @author Florian Krämer * @author Tomenko Yegeny * @license MIT + * + * @deprecated This listener class is deprecated */ class LegacyLocalFileStorageListener extends LocalListener { diff --git a/src/Storage/Listener/LocalListener.php b/src/Storage/Listener/LocalListener.php index <HASH>..<HASH> 100644 --- a/src/Storage/Listener/LocalListener.php +++ b/src/Storage/Listener/LocalListener.php @@ -24,7 +24,7 @@ class LocalListener extends BaseListener { * processed. * * The LocalListener will ONLY work with the '\Gaufrette\Adapter\Local' - * adapter for backward compatiblity reasons for now. Use the BaseListener + * adapter for backward compatibility reasons for now. Use the BaseListener * or extend this one here and add your adapter classes. * * @var array diff --git a/src/Storage/PathBuilder/LegacyPathBuilder.php b/src/Storage/PathBuilder/LegacyPathBuilder.php index <HASH>..<HASH> 100644 --- a/src/Storage/PathBuilder/LegacyPathBuilder.php +++ b/src/Storage/PathBuilder/LegacyPathBuilder.php @@ -10,6 +10,8 @@ namespace Burzum\FileStorage\Storage\PathBuilder; * Includes bugs and workarounds that could not be removed without backward * compatibility breaking changes. Use this path builder for projects that you * migrated from the Cake2 version to Cake3. + * + * DON'T use it if you're not coming from an old version! */ class LegacyPathBuilder extends BasePathBuilder { diff --git a/src/Storage/StorageException.php b/src/Storage/StorageException.php index <HASH>..<HASH> 100644 --- a/src/Storage/StorageException.php +++ b/src/Storage/StorageException.php @@ -2,7 +2,6 @@ namespace Burzum\FileStorage\Storage; use Cake\Datasource\EntityInterface; -use Exception; /** * Storage Exception diff --git a/src/Storage/StorageManager.php b/src/Storage/StorageManager.php index <HASH>..<HASH> 100644 --- a/src/Storage/StorageManager.php +++ b/src/Storage/StorageManager.php @@ -37,6 +37,7 @@ class StorageManager { if (!$instance) { $instance[0] = new self(); } + return $instance[0]; } @@ -118,11 +119,13 @@ class StorageManager { if (!is_array($adapter['adapterOptions'])) { throw new InvalidArgumentException(sprintf('%s: The adapter options must be an array!', $configName)); } + $adapterObject = $Reflection->newInstanceArgs($adapter['adapterOptions']); $engineObject = new $adapter['class']($adapterObject); if ($isConfigured) { $_this->_adapterConfig[$configName]['object'] = &$engineObject; } + return $engineObject; }
Coding conventions and doc blocks
burzum_cakephp-file-storage
train
885f0b2a6ecd054bf90931624b2a0fba9de069f6
diff --git a/spec/unit/provider/link_spec.rb b/spec/unit/provider/link_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/provider/link_spec.rb +++ b/spec/unit/provider/link_spec.rb @@ -25,7 +25,7 @@ if Chef::Platform.windows? require 'chef/win32/file' #probably need this in spec_helper end -describe Chef::Resource::Link do +describe Chef::Resource::Link, :not_supported_on_win2k3 do let(:provider) do node = Chef::Node.new @events = Chef::EventDispatch::Dispatcher.new diff --git a/spec/unit/provider/remote_directory_spec.rb b/spec/unit/provider/remote_directory_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/provider/remote_directory_spec.rb +++ b/spec/unit/provider/remote_directory_spec.rb @@ -181,7 +181,7 @@ describe Chef::Provider::RemoteDirectory do ::File.exist?(@destination_dir + '/a/multiply/nested/directory/qux.txt').should be_false end - it "removes directory symlinks properly" do + it "removes directory symlinks properly", :not_supported_on_win2k3 do symlinked_dir_path = @destination_dir + '/symlinked_dir' @provider.action = :create @provider.run_action
Marking more tests not to run on Win2k3
chef_chef
train
33b57fedc3a7a832453f6ee4bfbc265e2794c611
diff --git a/lib/inq.rb b/lib/inq.rb index <HASH>..<HASH> 100644 --- a/lib/inq.rb +++ b/lib/inq.rb @@ -37,11 +37,11 @@ module Inq # the reports. # @param date [String] A string containing the date (YYYY-MM-DD) that the # report ends on. E.g., for Jan 1-Feb 1 2017, you'd pass 2017-02-01. - def self.from_config(config, date) + def self.from_config(config, start_date, end_date = nil) raise "Expected config to be Hash, got #{config.class}" unless \ config.is_a?(Hash) - ReportCollection.new(config, date) + ReportCollection.new(config, start_date, end_date) end ##
Make self.from_config accept start_date and end_date
duckinator_inq
train
85a3071b70cd95ce67b160db190321a5aa20a98c
diff --git a/lib/commands/app-management.js b/lib/commands/app-management.js index <HASH>..<HASH> 100644 --- a/lib/commands/app-management.js +++ b/lib/commands/app-management.js @@ -20,11 +20,11 @@ commands.mobileInstallApp = async function mobileInstallApp (opts = {}) { const {app} = extractMandatoryOptions(opts, ['app']); const dstPath = await this.helpers.configureApp(app, '.app'); log.info(`Installing '${dstPath}' to the ${this.isRealDevice() ? 'real device' : 'Simulator'} ` + - `with UDID ${this.opts.device.udid}`); + `with UDID '${this.opts.device.udid}'`); if (!await fs.exists(dstPath)) { log.errorAndThrow(`The application at '${dstPath}' does not exist or is not accessible`); } - await this.opts.device.installApp(dstPath); + await this.opts.device.installApp(dstPath, this.opts.appPushTimeout); log.info(`Installation of '${dstPath}' succeeded`); }; @@ -38,7 +38,7 @@ commands.mobileIsAppInstalled = async function mobileIsAppInstalled (opts = {}) commands.mobileRemoveApp = async function mobileRemoveApp (opts = {}) { const {bundleId} = extractMandatoryOptions(opts, ['bundleId']); log.info(`Uninstalling the application with bundle identifier '${bundleId}' ` + - `from the ${this.isRealDevice() ? 'real device' : 'Simulator'} with UDID ${this.opts.device.udid}`); + `from the ${this.isRealDevice() ? 'real device' : 'Simulator'} with UDID '${this.opts.device.udid}'`); try { await this.opts.device.removeApp(bundleId); log.info(`Removal of '${bundleId}' succeeded`); diff --git a/lib/device-log/ios-simulator-log.js b/lib/device-log/ios-simulator-log.js index <HASH>..<HASH> 100644 --- a/lib/device-log/ios-simulator-log.js +++ b/lib/device-log/ios-simulator-log.js @@ -23,7 +23,7 @@ class IOSSimulatorLog extends IOSLog { } if (!await this.sim.isRunning()) { - throw new Error(`iOS Simulator with udid ${this.sim.udid} is not running`); + throw new Error(`iOS Simulator with udid '${this.sim.udid}' is not running`); } const tool = 'xcrun'; let args = [ @@ -127,4 +127,4 @@ class IOSSimulatorLog extends IOSLog { } export { IOSSimulatorLog }; -export default IOSSimulatorLog; \ No newline at end of file +export default IOSSimulatorLog;
fix: make sure appPushTimeout is used for installApp (#<I>)
appium_appium-xcuitest-driver
train
c2230e72681f80aae4aadafe832ed9eba19cfeae
diff --git a/src/com/opencms/flex/jsp/CmsJspTagInclude.java b/src/com/opencms/flex/jsp/CmsJspTagInclude.java index <HASH>..<HASH> 100644 --- a/src/com/opencms/flex/jsp/CmsJspTagInclude.java +++ b/src/com/opencms/flex/jsp/CmsJspTagInclude.java @@ -1,7 +1,7 @@ /* * File : $Source: /alkacon/cvs/opencms/src/com/opencms/flex/jsp/Attic/CmsJspTagInclude.java,v $ - * Date : $Date: 2003/06/13 10:04:21 $ - * Version: $Revision: 1.25 $ + * Date : $Date: 2003/06/30 18:13:04 $ + * Version: $Revision: 1.26 $ * * This library is part of OpenCms - * the Open Source Content Mananagement System @@ -52,7 +52,7 @@ import javax.servlet.jsp.tagext.BodyTagSupport; * Used to include another OpenCms managed resource in a JSP.<p> * * @author Alexander Kandzior ([email protected]) - * @version $Revision: 1.25 $ + * @version $Revision: 1.26 $ */ public class CmsJspTagInclude extends BodyTagSupport implements I_CmsJspTagParamParent { @@ -79,7 +79,7 @@ public class CmsJspTagInclude extends BodyTagSupport implements I_CmsJspTagParam */ public void setPage(String target) { if (target != null) { - m_target = target.toLowerCase(); + m_target = target; } }
Bugfix: Filenames are not longer forced to lower case
alkacon_opencms-core
train
34a12fd177f9e1dd3c0683722f3d809744048569
diff --git a/ObjectManager/FieldType.php b/ObjectManager/FieldType.php index <HASH>..<HASH> 100644 --- a/ObjectManager/FieldType.php +++ b/ObjectManager/FieldType.php @@ -18,11 +18,11 @@ class FieldType extends Base /** * Defines the state of the Construction object, if it's not published, partialy or completely published */ - const FIELD_NOT_CREATED = -1; - const FIELD_CREATED = 0; + const FIELD_TYPE_NOT_CREATED = -1; + const FIELD_TYPE_CREATED = 0; const CONTENT_TYPE_NOT_CREATED = 1; const CONTENT_TYPE_CREATED = 2; - const FIELD_ASSOCIATED = 3; + const FIELD_TYPE_ASSOCIATED = 3; const CONTENT_TYPE_PUBLISHED = 4; const CONTENT_PUBLISHED = 5; @@ -38,7 +38,7 @@ class FieldType extends Base "contentType" => null, "fieldType" => null, "content" => null, - "objectState" => self::FIELD_NOT_CREATED + "objectState" => self::FIELD_TYPE_NOT_CREATED ); /** @@ -106,7 +106,7 @@ class FieldType extends Base $fieldCreateStruct->isRequired = $required; $fieldCreateStruct->defaultValue = $this->defaultValues[ $fieldType ]; $this->fieldConstructionObject[ 'fieldType' ] = $fieldCreateStruct; - $this->fieldConstructionObject[ 'objectState' ] = self::FIELD_CREATED; + $this->fieldConstructionObject[ 'objectState' ] = self::FIELD_TYPE_CREATED; } /** @@ -151,7 +151,7 @@ class FieldType extends Base */ public function setFieldContentState( $stateFlag, $field = null, $value = null ) { - if ( $stateFlag <= $this->fieldConstructionObject[ 'objectState' ] || $stateFlag < self::FIELD_NOT_CREATED ) + if ( $stateFlag <= $this->fieldConstructionObject[ 'objectState' ] || $stateFlag < self::FIELD_TYPE_NOT_CREATED ) { return; } @@ -160,13 +160,13 @@ class FieldType extends Base switch( $stateFlag ) { - case self::FIELD_NOT_CREATED: + case self::FIELD_TYPE_NOT_CREATED: throw new \Exception( 'A field type must be declared before anything else' ); break; case self::CONTENT_TYPE_CREATED: $this->instantiateContentType(); break; - case self::FIELD_ASSOCIATED: + case self::FIELD_TYPE_ASSOCIATED: $this->associateFieldToCotentType(); break; case self::CONTENT_TYPE_PUBLISHED: @@ -219,7 +219,7 @@ class FieldType extends Base { $fieldCreateStruct = $this->fieldConstructionObject[ 'fieldType' ]; $this->fieldConstructionObject[ 'contentType' ]->addFieldDefinition( $fieldCreateStruct ); - $this->fieldConstructionObject[ 'objectState' ] = self::FIELD_ASSOCIATED; + $this->fieldConstructionObject[ 'objectState' ] = self::FIELD_TYPE_ASSOCIATED; } /**
Refactor FIELD constant to FIELD_TYPE
ezsystems_BehatBundle
train
2b4b9eaf12bdfe4dda5be33524e4b4a6d80cd691
diff --git a/hardware/opentrons_hardware/firmware_bindings/messages/fields.py b/hardware/opentrons_hardware/firmware_bindings/messages/fields.py index <HASH>..<HASH> 100644 --- a/hardware/opentrons_hardware/firmware_bindings/messages/fields.py +++ b/hardware/opentrons_hardware/firmware_bindings/messages/fields.py @@ -1,6 +1,8 @@ """Custom payload fields.""" from __future__ import annotations +from typing import Iterable, List, Iterator + import binascii import enum @@ -127,6 +129,28 @@ class SerialField(utils.BinaryFieldBase[bytes]): class SensorOutputBindingField(utils.UInt8Field): """sensor type.""" + @classmethod + def from_flags( + cls, flags: Iterable[SensorOutputBinding] + ) -> "SensorOutputBindingField": + """Build a binding with a set of flags.""" + backing = 0 + for flag in flags: + backing |= flag.value + return cls.build(backing) + + def to_flags(self) -> List[SensorOutputBinding]: + """Get the list of flags in the binding.""" + + def _flags() -> Iterator[SensorOutputBinding]: + for flag in SensorOutputBinding: + if flag == SensorOutputBinding.none: + continue + if bool(flag.value & self.value): + yield flag + + return list(_flags()) + def __repr__(self) -> str: """Print version flags.""" flags_list = [ diff --git a/hardware/opentrons_hardware/firmware_bindings/utils/binary_serializable.py b/hardware/opentrons_hardware/firmware_bindings/utils/binary_serializable.py index <HASH>..<HASH> 100644 --- a/hardware/opentrons_hardware/firmware_bindings/utils/binary_serializable.py +++ b/hardware/opentrons_hardware/firmware_bindings/utils/binary_serializable.py @@ -3,7 +3,7 @@ from __future__ import annotations import struct from dataclasses import dataclass, fields, astuple -from typing import TypeVar, Generic +from typing import TypeVar, Generic, Type class BinarySerializableException(BaseException): @@ -30,6 +30,7 @@ T = TypeVar("T") class BinaryFieldBase(Generic[T]): """Binary serializable field.""" + This = TypeVar("This", bound="BinaryFieldBase[T]") FORMAT = "" """The struct format string for this field.""" @@ -38,7 +39,7 @@ class BinaryFieldBase(Generic[T]): self._t = t @classmethod - def build(cls, t: T) -> BinaryFieldBase[T]: + def build(cls: Type[This], t: T) -> This: """Factory method. Args: @@ -50,7 +51,7 @@ class BinaryFieldBase(Generic[T]): return cls(t) @classmethod - def from_string(cls, t: str) -> BinaryFieldBase[T]: + def from_string(cls: Type[This], t: str) -> This: """Create from a string. Args:
refactor(hardware): types: polymorphic field ctors (#<I>) By making the class arg of BinaryFieldBase factory functions a typevar with a bound of the base itself, when using the factories from child classes of BinaryFieldBase (i.e. UInt8Field.build()) then the return type will be the child class. This means, among other htings, that we can use the base class factories in child class factories that are explicitly noted to return instances of the child class.
Opentrons_opentrons
train
7b28e5d413698f072a34347824ed056083de8a8e
diff --git a/parsl/dataflow/dflow.py b/parsl/dataflow/dflow.py index <HASH>..<HASH> 100644 --- a/parsl/dataflow/dflow.py +++ b/parsl/dataflow/dflow.py @@ -339,7 +339,7 @@ class DataFlowKernel(object): assert isinstance(inner_future, Future) task_record['status'] = States.joining task_record['joins'] = inner_future - inner_future.add_done_callback(partial(self.handle_join_update, task_id)) + inner_future.add_done_callback(partial(self.handle_join_update, task_record)) self._log_std_streams(task_record) @@ -351,7 +351,7 @@ class DataFlowKernel(object): if task_record['status'] == States.pending: self.launch_if_ready(task_record) - def handle_join_update(self, outer_task_id, inner_app_future): + def handle_join_update(self, task_record, inner_app_future): # Use the result of the inner_app_future as the final result of # the outer app future. @@ -359,7 +359,7 @@ class DataFlowKernel(object): # their own retrying, and joining state is responsible for passing # on whatever the result of that retrying was (if any). - task_record = self.tasks[outer_task_id] + outer_task_id = task_record['id'] try: res = self._unwrap_remote_exception_wrapper(inner_app_future)
Eliminate self.tasks[id] calls from joinapp callback (#<I>) see issue #<I>
Parsl_parsl
train
046cce4cbf2ad360abbb62aeee4dc8333d897c2a
diff --git a/timber.php b/timber.php index <HASH>..<HASH> 100644 --- a/timber.php +++ b/timber.php @@ -377,7 +377,14 @@ class Timber { if ($query) { add_action('do_parse_request',function() use ($query) { global $wp; - $wp->query_vars = $query; + + if ( is_array($query) ) + $wp->query_vars = $query; + elseif ( !empty($query) ) + parse_str($query, $wp->query_vars); + else + return true; // Could not interpret query. Let WP try. + return false; }); }
Allow query strings as query in Timber::load_template
timber_timber
train
7451a0df190ae73e2fb7c6ec429d28ea0116d537
diff --git a/spec/controllers/api/systems_packages_controller_spec.rb b/spec/controllers/api/systems_packages_controller_spec.rb index <HASH>..<HASH> 100644 --- a/spec/controllers/api/systems_packages_controller_spec.rb +++ b/spec/controllers/api/systems_packages_controller_spec.rb @@ -41,7 +41,7 @@ describe Api::SystemPackagesController do @organization = Organization.create!(:name => 'test_org', :cp_key => 'test_org') @environment_1 = KTEnvironment.create!(:name => 'test_1', :prior => @organization.locker.id, :organization => @organization) - @system = System.create!(:environment => @environment_1, :uuid => "1234", :name => "system.example.com", :cp_type => 'system', :facts => {}) + @system = System.create!(:environment => @environment_1, :uuid => "1234", :name => "system.example.com", :cp_type => 'system', :facts => {:foo => :bar}) System.stub(:first => @system) end
Temporary fix for jenkins errors
Katello_katello
train
855034b6b7a3b7144977efcaefe72d2c64b0d039
diff --git a/gabs.go b/gabs.go index <HASH>..<HASH> 100644 --- a/gabs.go +++ b/gabs.go @@ -135,20 +135,7 @@ func (g *Container) S(hierarchy ...string) *Container { Exists - Checks whether a path exists. */ func (g *Container) Exists(hierarchy ...string) bool { - var object interface{} - - object = g.object - for target := 0; target < len(hierarchy); target++ { - if mmap, ok := object.(map[string]interface{}); ok { - object, ok = mmap[hierarchy[target]] - if !ok { - return false - } - } else { - return false - } - } - return true + return g.Search(hierarchy...).Data() != nil } /* diff --git a/gabs_test.go b/gabs_test.go index <HASH>..<HASH> 100644 --- a/gabs_test.go +++ b/gabs_test.go @@ -74,6 +74,63 @@ func TestExists(t *testing.T) { } } +func TestExistsWithArrays(t *testing.T) { + sample := []byte(`{"foo":{"bar":{"baz":[10, 2, 3]}}}`) + + val, err := ParseJSON(sample) + if err != nil { + t.Errorf("Failed to parse: %v", err) + return + } + + if exp, actual := true, val.Exists("foo", "bar", "baz"); exp != actual { + t.Errorf("Wrong result from array based Exists: %v != %v", exp, actual) + } + + sample = []byte(`{"foo":{"bar":[{"baz":10},{"baz":2},{"baz":3}]}}`) + + if val, err = ParseJSON(sample); err != nil { + t.Errorf("Failed to parse: %v", err) + return + } + + if exp, actual := true, val.Exists("foo", "bar", "baz"); exp != actual { + t.Errorf("Wrong result from array based Exists: %v != %v", exp, actual) + } + if exp, actual := false, val.Exists("foo", "bar", "baz_NOPE"); exp != actual { + t.Errorf("Wrong result from array based Exists: %v != %v", exp, actual) + } + + sample = []byte(`{"foo":[{"bar":{"baz":10}},{"bar":{"baz":2}},{"bar":{"baz":3}}]}`) + + if val, err = ParseJSON(sample); err != nil { + t.Errorf("Failed to parse: %v", err) + return + } + + if exp, actual := true, val.Exists("foo", "bar", "baz"); exp != actual { + t.Errorf("Wrong result from array based Exists: %v != %v", exp, actual) + } + if exp, actual := false, val.Exists("foo", "bar", "baz_NOPE"); exp != actual { + t.Errorf("Wrong result from array based Exists: %v != %v", exp, actual) + } + + sample = + []byte(`[{"foo":{"bar":{"baz":10}}},{"foo":{"bar":{"baz":2}}},{"foo":{"bar":{"baz":3}}}]`) + + if val, err = ParseJSON(sample); err != nil { + t.Errorf("Failed to parse: %v", err) + return + } + + if exp, actual := true, val.Exists("foo", "bar", "baz"); exp != actual { + t.Errorf("Wrong result from array based Exists: %v != %v", exp, actual) + } + if exp, actual := false, val.Exists("foo", "bar", "baz_NOPE"); exp != actual { + t.Errorf("Wrong result from array based Exists: %v != %v", exp, actual) + } +} + func TestBasicWithBuffer(t *testing.T) { sample := bytes.NewReader([]byte(`{"test":{"value":10},"test2":20}`))
Fix Exists calls for paths containing arrays
Jeffail_gabs
train
a9aaff0ee0574d728fe4379b59efe11fd2d3f49e
diff --git a/pkg/server/httpserver/httpserver.go b/pkg/server/httpserver/httpserver.go index <HASH>..<HASH> 100644 --- a/pkg/server/httpserver/httpserver.go +++ b/pkg/server/httpserver/httpserver.go @@ -19,7 +19,7 @@ package httpserver import ( "log" "net/http" - "time" + // "time" ) type HttpServerConfig struct { @@ -46,10 +46,11 @@ func start(ctrlChannel <-chan string, errorChannel chan<- error, // Minio server config httpServer := &http.Server{ - Addr: config.Address, - Handler: router, - ReadTimeout: 10 * time.Second, - WriteTimeout: 10 * time.Second, + Addr: config.Address, + Handler: router, + // TODO add this later with a proper timer thread + // ReadTimeout: 20 * time.Second, + // WriteTimeout: 20 * time.Second, MaxHeaderBytes: 1 << 20, } log.Println("Starting HTTP Server on:", config.Address)
Remove HTTP server timeouts write and read. Implement it later with a proper timer thread. Large file transfers from 'mc' fail with i/o timeout without this change.
minio_minio
train
f71af0335840987e25eac37bca41eba85ba6818c
diff --git a/radiotool/composer/speech.py b/radiotool/composer/speech.py index <HASH>..<HASH> 100644 --- a/radiotool/composer/speech.py +++ b/radiotool/composer/speech.py @@ -1,5 +1,7 @@ +import numpy as N + from track import Track -from ..utils import segment_array +from ..utils import segment_array, RMS_energy class Speech(Track): """A :py:class:`radiotool.composer.Track` @@ -10,13 +12,17 @@ class Speech(Track): labels_in_file=labels_in_file) def refine_cut(self, cut_point, window_size=1): - self.current_frame = int((cut_point - window_size / 2.0) * self.samplerate) - frames = self.read_frames(window_size * self.samplerate) + cut_point = max(.5 * window_size, cut_point) + + cf = self.current_frame + self.current_frame = max(int((cut_point - window_size / 2.0) * self.samplerate), 0) + frames = self.read_frames(window_size * self.samplerate, channels=1) subwindow_n_frames = int((window_size / 16.0) * self.samplerate) + self.current_frame = cf segments = segment_array(frames, subwindow_n_frames, overlap=.5) - segments = segments.reshape((-1, subwindow_n_frames * 2)) + # segments = segments.reshape((-1, subwindow_n_frames * 2)) volumes = N.apply_along_axis(RMS_energy, 1, segments) @@ -45,7 +51,10 @@ class Speech(Track): new_cut_point = (self.samplerate * (cut_point - window_size / 2.0) + (long_list[0] + 1) * int(subwindow_n_frames / 2.0)) - print "first min subwindow", long_list[0], "total", len(volumes) + # print "first min subwindow", long_list[0], "total", len(volumes) + + print "{} -> {}".format(cut_point, round(new_cut_point / self.samplerate, 2)) + return round(new_cut_point / self.samplerate, 2) # have to add the .5 elsewhere to get that effect! \ No newline at end of file diff --git a/radiotool/utils.py b/radiotool/utils.py index <HASH>..<HASH> 100644 --- a/radiotool/utils.py +++ b/radiotool/utils.py @@ -133,7 +133,7 @@ def segment_array(arr, length, overlap=.5): offset = float(overlap) * length total_segments = int((N.shape(arr)[0] - length) / offset) + 1 - print "total segments", total_segments + # print "total segments", total_segments other_shape = N.shape(arr)[1:] out_shape = [total_segments, length]
actually using the refine cut method. no kidding.
ucbvislab_radiotool
train
4918cc798dd203a0f684b076c36b486ebcac2359
diff --git a/tabu/sampler.py b/tabu/sampler.py index <HASH>..<HASH> 100644 --- a/tabu/sampler.py +++ b/tabu/sampler.py @@ -87,13 +87,14 @@ class TabuSampler(dimod.Sampler): :obj:`~dimod.SampleSet`: A `dimod` :obj:`.~dimod.SampleSet` object. Examples: - This example provides samples for a two-variable QUBO model. + This example samples a simple two-variable Ising model. - >>> from tabu import TabuSampler >>> import dimod - >>> sampler = TabuSampler() - >>> Q = {(0, 0): -1, (1, 1): -1, (0, 1): 2} - >>> bqm = dimod.BinaryQuadraticModel.from_qubo(Q, offset=0.0) + >>> bqm = dimod.BQM.from_ising({}, {'ab': 1}) + + >>> import tabu + >>> sampler = tabu.TabuSampler() + >>> samples = sampler.sample(bqm) >>> samples.record[0].energy -1.0
Simplify TabuSampler example
dwavesystems_dwave-tabu
train
69037175cbb51ce9ad05f830341dfa13a4818bdb
diff --git a/src/main/java/org/takes/rq/RqHeaders.java b/src/main/java/org/takes/rq/RqHeaders.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/takes/rq/RqHeaders.java +++ b/src/main/java/org/takes/rq/RqHeaders.java @@ -32,13 +32,12 @@ import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import lombok.EqualsAndHashCode; import org.takes.HttpException; import org.takes.Request; -import org.takes.misc.Sprintf; -import org.takes.misc.VerboseIterable; /** * HTTP headers parsing @@ -60,7 +59,7 @@ public interface RqHeaders extends Request { * @return List of values (can be empty) * @throws IOException If fails */ - Iterable<String> header(CharSequence key) throws IOException; + List<String> header(CharSequence key) throws IOException; /** * Get all header names. @@ -68,7 +67,7 @@ public interface RqHeaders extends Request { * @return All names * @throws IOException If fails */ - Iterable<String> names() throws IOException; + Set<String> names() throws IOException; /** * Request decorator, for HTTP headers parsing. @@ -89,36 +88,30 @@ public interface RqHeaders extends Request { public Base(final Request req) { super(req); } + + // @checkstyle LineLength (6 lines) + // @todo #490:30min We need to implement a VerboseList and its tests + // like VerboseIterable. It should provide means to throw an exception + // with a given error message when it otherwise throws an + // IndexOutOfBoundsException. With this we must wrap the returned + // list otherwise the diagnostic messages are lost: + // https://github.com/yegor256/takes/pull/503/files#diff-a01b0291ad72ac6fd8e264f47f844b3bL101 @Override - public Iterable<String> header(final CharSequence key) + public List<String> header(final CharSequence key) throws IOException { - final Map<String, List<String>> map = this.map(); - final List<String> values = map.get( + final List<String> values = this.map().get( key.toString().toLowerCase(Locale.ENGLISH) ); - final Iterable<String> iter; + final List<String> list; if (values == null) { - iter = new VerboseIterable<String>( - Collections.<String>emptyList(), - new Sprintf( - // @checkstyle LineLengthCheck (1 line) - "there are no headers by name \"%s\" among %d others: %s", - key, map.size(), map.keySet() - ) - ); + list = Collections.emptyList(); } else { - iter = new VerboseIterable<String>( - values, - new Sprintf( - "there are only %d headers by name \"%s\"", - values.size(), key - ) - ); + list = values; } - return iter; + return list; } @Override - public Iterable<String> names() throws IOException { + public Set<String> names() throws IOException { return this.map().keySet(); } /** @@ -178,12 +171,12 @@ public interface RqHeaders extends Request { this.origin = req; } @Override - public Iterable<String> header(final CharSequence name) + public List<String> header(final CharSequence name) throws IOException { return this.origin.header(name); } @Override - public Iterable<String> names() throws IOException { + public Set<String> names() throws IOException { return this.origin.names(); } @Override
RqHeaders exposes List / Set instead of Iterable Returning List / Set instead of Iterable is much more convenient to use than using an Iterable. Fixes #<I>
yegor256_takes
train
d8de69c8d67705dbc85eb8a5404172683fedc307
diff --git a/src/resource/RefraxResource.js b/src/resource/RefraxResource.js index <HASH>..<HASH> 100644 --- a/src/resource/RefraxResource.js +++ b/src/resource/RefraxResource.js @@ -65,7 +65,7 @@ class RefraxResource extends RefraxResourceBase { this._options.invalidate = {noPropagate: true}; } - // this.invalidate(this._options.invalidate); + this.invalidate(this._options.invalidate); } this._fetchCache();
Re-enable invalidate on Resource construct
netarc_refrax
train
ce973b068efa28abf146940cc714a3fb50693f3d
diff --git a/libraries/joomla/mail/mail.php b/libraries/joomla/mail/mail.php index <HASH>..<HASH> 100644 --- a/libraries/joomla/mail/mail.php +++ b/libraries/joomla/mail/mail.php @@ -148,12 +148,13 @@ class JMail extends PHPMailer * Add recipients to the email * * @param mixed $recipient Either a string or array of strings [email address(es)] + * @param mixed $name Either a string or array of strings [name(s)] * * @return JMail Returns this object for chaining. * * @since 11.1 */ - public function addRecipient($recipient) + public function addRecipient($recipient, $name = '') { // If the recipient is an array, add each recipient... otherwise just add the one if (is_array($recipient)) { @@ -175,12 +176,13 @@ class JMail extends PHPMailer * Add carbon copy recipients to the email * * @param mixed $cc Either a string or array of strings [email address(es)] + * @param mixed $name Either a string or array of strings [name(s)] * * @return JMail Returns this object for chaining. * * @since 11.1 */ - public function addCC($cc) + public function addCC($cc, $name = '') { // If the carbon copy recipient is an array, add each recipient... otherwise just add the one if (isset ($cc)) { @@ -204,12 +206,13 @@ class JMail extends PHPMailer * Add blind carbon copy recipients to the email * * @param mixed $bcc Either a string or array of strings [email address(es)] + * @param mixed $name Either a string or array of strings [name(s)] * * @return JMail Returns this object for chaining. * * @since 11.1 */ - public function addBCC($bcc) + public function addBCC($bcc, $name = '') { // If the blind carbon copy recipient is an array, add each recipient... otherwise just add the one if (isset($bcc)) { @@ -233,12 +236,15 @@ class JMail extends PHPMailer * Add file attachments to the email * * @param mixed $attachment Either a string or array of strings [filenames] + * @param mixed $name Either a string or array of strings [names] + * @param mixed $encoding string + * @param mixed $type string * * @return JMail Returns this object for chaining. * * @since 11.1 */ - public function addAttachment($attachment) + public function addAttachment($attachment, $name = '', $encoding = 'base64', $type = 'application/octet-stream') { // If the file attachments is an array, add each file... otherwise just add the one if (isset($attachment)) { @@ -261,12 +267,13 @@ class JMail extends PHPMailer * * @param array $replyto Either an array or multi-array of form * <code>array([0] => email Address [1] => Name)</code> + * @param array $name Either an array or single string * * @return JMail Returns this object for chaining. * * @since 11.1 */ - public function addReplyTo($replyto) + public function addReplyTo($replyto, $name = '') { // Take care of reply email addresses if (is_array($replyto[0])) {
PHP Strict Fixes for JMail Class
joomla_joomla-framework
train
34edd29177c148cdb464a6dd6039c52c1afdb305
diff --git a/inplaceeditform/media/js/jquery.inplaceeditform.js b/inplaceeditform/media/js/jquery.inplaceeditform.js index <HASH>..<HASH> 100644 --- a/inplaceeditform/media/js/jquery.inplaceeditform.js +++ b/inplaceeditform/media/js/jquery.inplaceeditform.js @@ -156,11 +156,10 @@ if (media.tagName=="SCRIPT"){ //if filename is a external JavaScript file var fileref = document.createElement('script'); fileref.setAttribute("type","text/javascript"); - fileref.setAttribute("id", media.id); if(media.src != null && media.src != "" ){ - fileref.setAttribute("src", media.src.replace("http://localhost:8000", "")); + fileref.setAttribute("src", media.src); } else { - fileref.innerHTML = media.innerHTML; + appendChild(fileref, media.innerHTML); } } else if (media.tagName=="LINK" && media.type == "text/css"){ //if filename is an external CSS file @@ -169,10 +168,18 @@ fileref.setAttribute("type", "text/css"); fileref.setAttribute("href", media.href); } + if (typeof fileref!="undefined") { - document.getElementsByTagName("head")[0].appendChild(fileref) + document.getElementsByTagName("head")[0].appendChild(fileref); } } + function appendChild(node, text) { + if (null == node.canHaveChildren || node.canHaveChildren) { + node.appendChild(document.createTextNode(text)); + } else { + node.text = text; + } + } }); return { enable: function () {
Fixes #<I> Now work in IE
django-inplaceedit_django-inplaceedit
train
997cec92719f5234c29f1938810e6a97fe7ba104
diff --git a/lib/fog/openstack/models/storage/file.rb b/lib/fog/openstack/models/storage/file.rb index <HASH>..<HASH> 100644 --- a/lib/fog/openstack/models/storage/file.rb +++ b/lib/fog/openstack/models/storage/file.rb @@ -69,6 +69,11 @@ module Fog requires :key self.collection.get_url(self.key) end + + def temp_signed_url(expires_secs, method) + requires :directory, :key + service.generate_object_temp_url(directory.key, key, expires_secs, method) + end def save(options = {}) requires :body, :directory, :key diff --git a/lib/fog/openstack/requests/storage/get_object_https_url.rb b/lib/fog/openstack/requests/storage/get_object_https_url.rb index <HASH>..<HASH> 100644 --- a/lib/fog/openstack/requests/storage/get_object_https_url.rb +++ b/lib/fog/openstack/requests/storage/get_object_https_url.rb @@ -18,20 +18,27 @@ module Fog # ==== See Also # http://docs.rackspace.com/files/api/v1/cf-devguide/content/Create_TempURL-d1a444.html def get_object_https_url(container, object, expires, options = {}) - if @openstack_temp_url_key.nil? - raise ArgumentError, "Storage must my instantiated with the :openstack_temp_url_key option" - end - - method = 'GET' - expires = expires.to_i - object_path_escaped = "#{@path}/#{Fog::OpenStack.escape(container)}/#{Fog::OpenStack.escape(object,"/")}" - object_path_unescaped = "#{@path}/#{Fog::OpenStack.escape(container)}/#{object}" - string_to_sign = "#{method}\n#{expires}\n#{object_path_unescaped}" - - hmac = Fog::HMAC.new('sha1', @openstack_temp_url_key) - sig = sig_to_hex(hmac.sign(string_to_sign)) - - "https://#{@host}#{object_path_escaped}?temp_url_sig=#{sig}&temp_url_expires=#{expires}" + create_temp_url(container, object, expires, "GET", "https", options) + end + + # Get an expiring object url from Cloud Files + # The function uses the scheme used by the storage object (http or https) + # + # ==== Parameters + # * container<~String> - Name of container containing object + # * object<~String> - Name of object to get expiring url for + # * expires_secs<~Time> - The duration in seconds of the validity for the generated url + # * method<~String> - The name of the method to be accessible via the url ("GET", "PUT" or "HEAD") + # + # ==== Returns + # * response<~Excon::Response>: + # * body<~String> - url for object + # + # ==== See Also + # http://docs.rackspace.com/files/api/v1/cf-devguide/content/Create_TempURL-d1a444.html + def generate_object_temp_url(container, object, expires_secs, method, options = {}) + expires = (Time.now + expires_secs.to_i).to_i + create_temp_url(container, object, expires, method, @scheme, options) end private @@ -43,6 +50,29 @@ module Fog h.size == 1 ? "0#{h}" : h }.join end + + def create_temp_url(container, object, expires, method, scheme, options = {}) + raise ArgumentError, "Insufficient parameters specified." unless (container && object && expires && method) + raise ArgumentError, "Storage must my instantiated with the :openstack_temp_url_key option" if @openstack_temp_url_key.nil? + + + # POST not allowed + allowed_methods = %w{GET PUT HEAD} + unless allowed_methods.include?(method) + raise ArgumentError.new("Invalid method '#{method}' specified. Valid methods are: #{allowed_methods.join(', ')}") + end + + + expires = expires.to_i + object_path_escaped = "#{@path}/#{Fog::OpenStack.escape(container)}/#{Fog::OpenStack.escape(object,"/")}" + object_path_unescaped = "#{@path}/#{Fog::OpenStack.escape(container)}/#{object}" + string_to_sign = "#{method}\n#{expires}\n#{object_path_unescaped}" + + hmac = Fog::HMAC.new('sha1', @openstack_temp_url_key) + sig = sig_to_hex(hmac.sign(string_to_sign)) + + "#{scheme}://#{@host}#{object_path_escaped}?temp_url_sig=#{sig}&temp_url_expires=#{expires}" + end end
refactors get_object_https_url request, adds temp_signed_url method to file class
fog_fog
train
44ea74f96246e6ce6fb0b6a60212ce0fa75267ab
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -29,7 +29,7 @@ def main(): setup( name='straitlets', # remember to update straitlets/__init__.py! - version='0.3.0', + version='0.3.1', description="Serializable IPython Traitlets", author="Quantopian Team", author_email="[email protected]", diff --git a/straitlets/__init__.py b/straitlets/__init__.py index <HASH>..<HASH> 100644 --- a/straitlets/__init__.py +++ b/straitlets/__init__.py @@ -14,7 +14,7 @@ from .traits import ( ) # remember to update setup.py! -__version__ = '0.3.0' +__version__ = '0.3.1' __all__ = ( 'Bool',
REL: Bump to <I>.
quantopian_serializable-traitlets
train