hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
577d62fe754650521a74ebbe6c0ae2a37b30129c
diff --git a/bulbs/api/views.py b/bulbs/api/views.py index <HASH>..<HASH> 100644 --- a/bulbs/api/views.py +++ b/bulbs/api/views.py @@ -454,6 +454,8 @@ class ContentResolveViewSet(viewsets.ReadOnlyModelViewSet): content = get_object_or_404(Content, pk=match.kwargs.get('pk')) return Response(ContentSerializer().to_representation(content)) + else: + raise Http404('Must specify content "url" param') class CustomSearchContentViewSet(viewsets.GenericViewSet): diff --git a/tests/api/test_content_api.py b/tests/api/test_content_api.py index <HASH>..<HASH> 100644 --- a/tests/api/test_content_api.py +++ b/tests/api/test_content_api.py @@ -601,3 +601,7 @@ class TestContentResolveAPI(BaseAPITestCase): r = self.api_client.get(reverse("content-resolve-list"), dict(url="/r/1")) self.assertEqual(r.status_code, 404) + + def test_missing_param(self): + r = self.api_client.get(reverse("content-resolve-list")) + self.assertEqual(r.status_code, 404)
Raise <I> on missing "url" param
theonion_django-bulbs
train
89538af207aac90354207274d24e40760b0a350b
diff --git a/src/Fixer/FunctionNotation/VoidReturnFixer.php b/src/Fixer/FunctionNotation/VoidReturnFixer.php index <HASH>..<HASH> 100644 --- a/src/Fixer/FunctionNotation/VoidReturnFixer.php +++ b/src/Fixer/FunctionNotation/VoidReturnFixer.php @@ -21,6 +21,7 @@ use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; /** * @author Mark Nielsen @@ -184,7 +185,21 @@ final class VoidReturnFixer extends AbstractFixer */ private function hasVoidReturn(Tokens $tokens, $startIndex, $endIndex) { + $tokensAnalyzer = new TokensAnalyzer($tokens); + for ($i = $startIndex; $i < $endIndex; ++$i) { + if ( + // skip anonymous classes + ($tokens[$i]->isGivenKind(T_CLASS) && $tokensAnalyzer->isAnonymousClass($i)) || + // skip lambda functions + ($tokens[$i]->isGivenKind(T_FUNCTION) && $tokensAnalyzer->isLambda($i)) + ) { + $i = $tokens->getNextTokenOfKind($i, ['{']); + $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $i); + + continue; + } + if ($tokens[$i]->isGivenKind(T_YIELD)) { return false; // Generators cannot return void. } diff --git a/tests/Fixer/FunctionNotation/VoidReturnFixerTest.php b/tests/Fixer/FunctionNotation/VoidReturnFixerTest.php index <HASH>..<HASH> 100644 --- a/tests/Fixer/FunctionNotation/VoidReturnFixerTest.php +++ b/tests/Fixer/FunctionNotation/VoidReturnFixerTest.php @@ -112,8 +112,58 @@ final class VoidReturnFixerTest extends AbstractFixerTestCase '<?php function foo() { usort([], new class { public function __invoke($a, $b) {} }); }', ], [ - '<?php function foo(): void { (function () {return 1;})(); return; }', - '<?php function foo() { (function () {return 1;})(); return; }', + '<?php + function foo(): void { + $a = function (): void {}; + }', + '<?php + function foo() { + $a = function () {}; + }', + ], + [ + '<?php + function foo(): void { + (function (): void { + return; + })(); + }', + '<?php + function foo() { + (function () { + return; + })(); + }', + ], + [ + '<?php + function foo(): void { + (function () { + return 1; + })(); + }', + '<?php + function foo() { + (function () { + return 1; + })(); + }', + ], + [ + '<?php + function foo(): void { + $b = new class { + public function b1(): void {} + public function b2() { return 2; } + }; + }', + '<?php + function foo() { + $b = new class { + public function b1() {} + public function b2() { return 2; } + }; + }', ], [ '<?php
VoidReturnFixer - handle functions containing anonymous functions/classes
FriendsOfPHP_PHP-CS-Fixer
train
52d6bf98883e5c11d2e167520263a0274bc82618
diff --git a/src/Indatus/Dispatcher/Scheduling/ScheduledCommandInterface.php b/src/Indatus/Dispatcher/Scheduling/ScheduledCommandInterface.php index <HASH>..<HASH> 100644 --- a/src/Indatus/Dispatcher/Scheduling/ScheduledCommandInterface.php +++ b/src/Indatus/Dispatcher/Scheduling/ScheduledCommandInterface.php @@ -23,7 +23,7 @@ interface ScheduledCommandInterface /** * When a command should run * @param Scheduler $scheduler - * @return \Indatus\Dispatcher\Scheduling\Schedulable + * @return \Indatus\Dispatcher\Scheduling\Schedulable|\Indatus\Dispatcher\Scheduling\Schedulable[] */ public function schedule(Schedulable $scheduler); diff --git a/src/Indatus/Dispatcher/ServiceProvider.php b/src/Indatus/Dispatcher/ServiceProvider.php index <HASH>..<HASH> 100644 --- a/src/Indatus/Dispatcher/ServiceProvider.php +++ b/src/Indatus/Dispatcher/ServiceProvider.php @@ -40,6 +40,7 @@ class ServiceProvider extends \Illuminate\Support\ServiceProvider */ public function register() { + /** @var \Indatus\Dispatcher\ConfigResolver $resolver */ $resolver = App::make('\Indatus\Dispatcher\ConfigResolver'); //load the scheduler of the appropriate driver diff --git a/src/Indatus/Dispatcher/Services/ScheduleService.php b/src/Indatus/Dispatcher/Services/ScheduleService.php index <HASH>..<HASH> 100644 --- a/src/Indatus/Dispatcher/Services/ScheduleService.php +++ b/src/Indatus/Dispatcher/Services/ScheduleService.php @@ -40,7 +40,7 @@ abstract class ScheduleService /** * Get all commands that are scheduled * - * @return array + * @return \Indatus\Dispatcher\Scheduling\ScheduledCommandInterface[] */ public function getScheduledCommands() { @@ -64,17 +64,18 @@ abstract class ScheduleService /** @var \Indatus\Dispatcher\Queue $queue */ $queue = App::make('Indatus\Dispatcher\Queue'); - /** @var \Indatus\Dispatcher\Scheduling\Schedulable $scheduler */ - $scheduler = App::make('Indatus\Dispatcher\Scheduling\Schedulable'); - + /** @var \Indatus\Dispatcher\Scheduling\ScheduledCommandInterface $command */ foreach ($this->getScheduledCommands() as $command) { + /** @var \Indatus\Dispatcher\Scheduling\Schedulable $scheduler */ + $scheduler = App::make('Indatus\Dispatcher\Scheduling\Schedulable'); + //could be multiple schedules based on arguments $schedules = $command->schedule($scheduler); if (!is_array($schedules)) { $schedules = array($schedules); } - + //echo $command->getName()." (".count($schedules).")\n"; foreach ($schedules as $schedule) { if (($schedule instanceOf Schedulable) === false) { throw new \InvalidArgumentException('Schedule for "'.$command->getName().'" is not an instance of Schedulable');
Resolved issues with $scheduler instance used within multiple commands
Indatus_dispatcher
train
ea2121610d1cd5c1a12c20b33886b3318edc1d1d
diff --git a/spec/smoke/source/yql_spec.rb b/spec/smoke/source/yql_spec.rb index <HASH>..<HASH> 100644 --- a/spec/smoke/source/yql_spec.rb +++ b/spec/smoke/source/yql_spec.rb @@ -26,6 +26,30 @@ describe "YQL" do Smoke[:search].items.should be_an_instance_of(Array) end + describe "select" do + before do + FakeWeb.register_uri("http://query.yahooapis.com:80/v1/public/yql?q=SELECT%20url%20FROM%20search.images%20WHERE%20query%20=%20'amc%20pacer'&format=json", :response => File.join(SPEC_DIR, 'supports', 'amc_pacer.json.yql')) + + Smoke.yql(:pacer) do + select :url + from "search.images" + where :query, "amc pacer" + + path :query, :results, :result + end + + Smoke[:pacer].output + end + + it "should query correctly" do + Smoke[:pacer].request.uri.should == "http://query.yahooapis.com/v1/public/yql?q=SELECT%20url%20FROM%20search.images%20WHERE%20query%20=%20'amc%20pacer'&format=json" + end + + it "should have urls" do + Smoke[:pacer].output.first.should have_key(:url) + end + end + describe "after dispatch" do before do Smoke[:search].output
Added a test case for selecting single fields in a YQL query and tested output from such a query
benschwarz_smoke
train
bf9a2168e74b0db587043c007e92a30c099bee26
diff --git a/client/allocrunner/interfaces/task_lifecycle.go b/client/allocrunner/interfaces/task_lifecycle.go index <HASH>..<HASH> 100644 --- a/client/allocrunner/interfaces/task_lifecycle.go +++ b/client/allocrunner/interfaces/task_lifecycle.go @@ -117,11 +117,11 @@ type TaskPoststartHook interface { type TaskKillRequest struct{} type TaskKillResponse struct{} -type TaskKillHook interface { +type TaskPreKillHook interface { TaskHook - // Killing is called when a task is going to be Killed or Restarted. - Killing(context.Context, *TaskKillRequest, *TaskKillResponse) error + // PreKilling is called right before a task is going to be killed or restarted. + PreKilling(context.Context, *TaskKillRequest, *TaskKillResponse) error } type TaskExitedRequest struct{} diff --git a/client/allocrunner/taskrunner/lifecycle.go b/client/allocrunner/taskrunner/lifecycle.go index <HASH>..<HASH> 100644 --- a/client/allocrunner/taskrunner/lifecycle.go +++ b/client/allocrunner/taskrunner/lifecycle.go @@ -22,8 +22,8 @@ func (tr *TaskRunner) Restart(ctx context.Context, event *structs.TaskEvent, fai // Emit the event since it may take a long time to kill tr.EmitEvent(event) - // Run the hooks prior to restarting the task - tr.killing() + // Run the pre-kill hooks prior to restarting the task + tr.preKill() // Tell the restart tracker that a restart triggered the exit tr.restartTracker.SetRestartTriggered(failure) diff --git a/client/allocrunner/taskrunner/service_hook.go b/client/allocrunner/taskrunner/service_hook.go index <HASH>..<HASH> 100644 --- a/client/allocrunner/taskrunner/service_hook.go +++ b/client/allocrunner/taskrunner/service_hook.go @@ -200,7 +200,7 @@ func (h *serviceHook) getTaskServices() *agentconsul.TaskServices { // values from the task's environment. func interpolateServices(taskEnv *taskenv.TaskEnv, services []*structs.Service) []*structs.Service { // Guard against not having a valid taskEnv. This can be the case if the - // Killing or Exited hook is run before post-run. + // PreKilling or Exited hook is run before post-run. if taskEnv == nil || len(services) == 0 { return nil } diff --git a/client/allocrunner/taskrunner/task_runner.go b/client/allocrunner/taskrunner/task_runner.go index <HASH>..<HASH> 100644 --- a/client/allocrunner/taskrunner/task_runner.go +++ b/client/allocrunner/taskrunner/task_runner.go @@ -707,8 +707,8 @@ func (tr *TaskRunner) initDriver() error { // the handle exit result if one is available and store any error in the task // runner killErr value. func (tr *TaskRunner) handleKill() *drivers.ExitResult { - // Run the hooks prior to killing the task - tr.killing() + // Run the pre killing hooks + tr.preKill() // Tell the restart tracker that the task has been killed so it doesn't // attempt to restart it. diff --git a/client/allocrunner/taskrunner/task_runner_hooks.go b/client/allocrunner/taskrunner/task_runner_hooks.go index <HASH>..<HASH> 100644 --- a/client/allocrunner/taskrunner/task_runner_hooks.go +++ b/client/allocrunner/taskrunner/task_runner_hooks.go @@ -437,8 +437,10 @@ func (tr *TaskRunner) updateHooks() { } } -// killing is used to run the runners kill hooks. -func (tr *TaskRunner) killing() { +// preKill is used to run the runners preKill hooks +// preKill hooks contain logic that must be executed before +// a task is killed or restarted +func (tr *TaskRunner) preKill() { if tr.logger.IsTrace() { start := time.Now() tr.logger.Trace("running kill hooks", "start", start) @@ -449,24 +451,24 @@ func (tr *TaskRunner) killing() { } for _, hook := range tr.runnerHooks { - killHook, ok := hook.(interfaces.TaskKillHook) + killHook, ok := hook.(interfaces.TaskPreKillHook) if !ok { continue } name := killHook.Name() - // Time the update hook + // Time the pre kill hook var start time.Time if tr.logger.IsTrace() { start = time.Now() tr.logger.Trace("running kill hook", "name", name, "start", start) } - // Run the kill hook + // Run the pre kill hook req := interfaces.TaskKillRequest{} var resp interfaces.TaskKillResponse - if err := killHook.Killing(context.Background(), &req, &resp); err != nil { + if err := killHook.PreKilling(context.Background(), &req, &resp); err != nil { tr.emitHookError(err, name) tr.logger.Error("kill hook failed", "name", name, "error", err) }
Rename TaskKillHook to TaskPreKillHook to more closely match usage Also added/fixed comments
hashicorp_nomad
train
1e81d346da47a509b454e1ba0772bf76bc88b8e3
diff --git a/gutenberg/download.py b/gutenberg/download.py index <HASH>..<HASH> 100644 --- a/gutenberg/download.py +++ b/gutenberg/download.py @@ -107,7 +107,8 @@ def makedirs(path): def download_corpus(todir, filetypes, langs, offset, delay=2): - """Downloads the entire Project Gutenberg corpus to disk. + """Downloads the entire Project Gutenberg corpus to disk. Prefers ISO + encoded files over ASCII encoded files. Args: todir (str): directory to which to download the corpus files @@ -118,14 +119,33 @@ def download_corpus(todir, filetypes, langs, offset, delay=2): """ makedirs(todir) + seen = set() for link in gutenberg_links(filetypes, langs, offset): - try: - logging.info('Downloading file %s' % link) - topath = os.path.join(todir, os.path.basename(link)) - urllib.urlretrieve(link, filename=topath) - except KeyboardInterrupt: - pass - time.sleep(delay) + download = False + filename, ext = os.path.splitext(os.path.basename(link)) + if '-' in filename: + # prefer iso encoded files over ascii encoded versions + asciiname, isoname = filename.split('-')[0], filename + if asciiname in seen: + download = True + seen.add(isoname) + seen.remove(asciiname) + os.remove(os.path.join(todir, asciiname + ext)) + else: + # fetch ascii encoded etext if iso encoded version not downloaded + asciiname, isoname = filename, filename + '-' + if isoname not in seen: + download = True + seen.add(asciiname) + + if download: + try: + logging.info('Downloading file %s' % link) + urllib.urlretrieve(link, os.path.join(todir, filename + ext)) + seen.add(filename) + except KeyboardInterrupt: + pass + time.sleep(delay) if __name__ == '__main__':
Download one of ASCII or ISO etext, never both
c-w_gutenberg
train
d4f65374a95240b4b151fffb0f762fdcc667b065
diff --git a/ssbio/core/protein.py b/ssbio/core/protein.py index <HASH>..<HASH> 100644 --- a/ssbio/core/protein.py +++ b/ssbio/core/protein.py @@ -16,10 +16,10 @@ from six.moves.urllib.error import URLError from Bio.Seq import Seq from Bio import SeqIO -from Bio.SeqFeature import SeqFeature, FeatureLocation +from Bio.SeqFeature import SeqFeature, FeatureLocation, CompoundLocation from Bio.PDB.PDBExceptions import PDBException, PDBConstructionException from msgpack.exceptions import ExtraData - +from more_itertools import locate from cobra.core import DictList import ssbio.utils import ssbio.databases.pdb @@ -1696,6 +1696,65 @@ class Protein(Object): return final_mapping + def get_seqprop_subsequence_from_structchain_property(self, + property_key, property_value, condition, + seqprop=None, structprop=None, chain_id=None, + use_representatives=False): + """Get a subsequence as a new SeqProp object given a certain property you want to find in the + given StructProp's chain's letter_annotation + + This is similar to the :func:`ssbio.protein.sequence.seqprop.SeqProp.get_subsequence_from_property` method but instead of + filtering by the SeqProp's letter_annotation we use the StructProp annotation, and map back to the SeqProp. + + Args: + seqprop (SeqRecord, SeqProp): SeqRecord or SeqProp object that has properties stored in its ``letter_annotations`` attribute + property_key (str): Property key in the ``letter_annotations`` attribute that you want to filter using + property_value (str): Property value that you want to filter by + condition (str): ``<``, ``=``, ``>``, ``>=``, or ``<=`` to filter the values by + + Returns: + SeqProp: New SeqProp object that you can run computations on or just extract its properties + + """ + if use_representatives: + seqprop = self.representative_sequence + structprop = self.representative_structure + chain_id = self.representative_chain + if not structprop: + raise ValueError('No representative structure set, please specify sequence, structure, and chain ID') + else: + if not seqprop or not structprop or not chain_id: + raise ValueError('Please specify sequence, structure, and chain ID') + + chain_prop = structprop.chains.get_by_id(chain_id) + + # Get the subsequence from the structure + chain_subseq, subfeat_resnums = chain_prop.get_subsequence_from_property(property_key=property_key, + property_value=property_value, + condition=condition, + return_resnums=True) + + # Map subsequence feature resnums back to the seqprop + mapping_dict = self.map_structprop_resnums_to_seqprop_resnums(resnums=subfeat_resnums, structprop=structprop, + chain_id=chain_id, + seqprop=seqprop, + use_representatives=use_representatives) + + # Now create a new SeqProp using these resnums + biop_compound_list = [] + for structprop_resnum, seqprop_resnum in mapping_dict.items(): + feat = FeatureLocation(seqprop_resnum - 1, seqprop_resnum) + biop_compound_list.append(feat) + sub_feature_location = CompoundLocation(biop_compound_list) + sub_feature = sub_feature_location.extract(seqprop) + + new_sp = SeqProp(id='{}-{}->{}_{}_{}_{}_extracted'.format(structprop.id, chain_id, seqprop.id, + property_key, condition, property_value), + seq=sub_feature) + new_sp.letter_annotations = chain_subseq.letter_annotations + + return new_sp + def _representative_structure_setter(self, structprop, keep_chain, clean=True, keep_chemicals=None, out_suffix='_clean', outdir=None, force_rerun=False): """Set the representative structure by 1) cleaning it and 2) copying over attributes of the original structure. diff --git a/ssbio/protein/structure/chainprop.py b/ssbio/protein/structure/chainprop.py index <HASH>..<HASH> 100644 --- a/ssbio/protein/structure/chainprop.py +++ b/ssbio/protein/structure/chainprop.py @@ -21,7 +21,7 @@ class ChainProp(Object): def reset_seq_record(self): self.seq_record = None - def get_subsequence_from_property(self, property_key, property_value, condition): + def get_subsequence_from_property(self, property_key, property_value, condition, return_resnums=False): """Get a subsequence as a new SeqProp object given a certain property you want to find in this chain's letter_annotation @@ -31,6 +31,7 @@ class ChainProp(Object): property_key (str): Property key in the ``letter_annotations`` attribute that you want to filter using property_value (str): Property value that you want to filter by condition (str): ``<``, ``=``, ``>``, ``>=``, or ``<=`` to filter the values by + return_resnums (bool): If resnums should be returned as well Returns: SeqProp: New SeqProp object that you can run computations on or just extract its properties @@ -53,8 +54,12 @@ class ChainProp(Object): sub_feature_location = CompoundLocation(biop_compound_list) sub_feature = sub_feature_location.extract(self.seq_record) - new_sp = SeqProp(id='{}_{}_{}_{}_extracted'.format(self.id, property_key, condition, property_value), + new_sp = SeqProp(id='{}-{}_{}_{}_{}_extracted'.format(self.pdb_parent, self.id, property_key, + condition, property_value), seq=sub_feature) new_sp.letter_annotations = sub_feature.letter_annotations - return new_sp \ No newline at end of file + if return_resnums: + return new_sp, [x + 1 for x in subfeat_indices] + else: + return new_sp \ No newline at end of file
Add new methods to extract subsequence based on letter_annotation as well as map from structure residue numbers back to sequence (cherry picked from commit 7cd<I>f8)
SBRG_ssbio
train
d3e82b1114dcdf7a04723c5227255552c369d0be
diff --git a/integration-tests/src/test/java/org/apache/druid/tests/indexer/AbstractStreamIndexingTest.java b/integration-tests/src/test/java/org/apache/druid/tests/indexer/AbstractStreamIndexingTest.java index <HASH>..<HASH> 100644 --- a/integration-tests/src/test/java/org/apache/druid/tests/indexer/AbstractStreamIndexingTest.java +++ b/integration-tests/src/test/java/org/apache/druid/tests/indexer/AbstractStreamIndexingTest.java @@ -373,7 +373,6 @@ public abstract class AbstractStreamIndexingTest extends AbstractIndexerTest try ( final Closeable closer1 = createResourceCloser(generatedTestConfig1); final Closeable closer2 = createResourceCloser(generatedTestConfig2); - final StreamEventWriter streamEventWriter = createStreamEventWriter(config, transactionEnabled) ) { final String taskSpec1 = generatedTestConfig1.getStreamIngestionPropsTransform() .apply(getResourceAsString(SUPERVISOR_SPEC_TEMPLATE_PATH)); @@ -385,44 +384,6 @@ public abstract class AbstractStreamIndexingTest extends AbstractIndexerTest generatedTestConfig1.setSupervisorId(indexer.submitSupervisor(taskSpec1)); generatedTestConfig2.setSupervisorId(indexer.submitSupervisor(taskSpec2)); LOG.info("Submitted supervisors"); - // Start generating the data - final StreamGenerator streamGenerator1 = new WikipediaStreamEventStreamGenerator( - new JsonEventSerializer(jsonMapper), - EVENTS_PER_SECOND, - CYCLE_PADDING_MS - ); - streamGenerator1.run( - generatedTestConfig1.getStreamName(), - streamEventWriter, - TOTAL_NUMBER_OF_SECOND, - FIRST_EVENT_TIME - ); - final StreamGenerator streamGenerator2 = new WikipediaStreamEventStreamGenerator( - new JsonEventSerializer(jsonMapper), - EVENTS_PER_SECOND, - CYCLE_PADDING_MS - ); - streamGenerator2.run( - generatedTestConfig2.getStreamName(), - streamEventWriter, - TOTAL_NUMBER_OF_SECOND, - FIRST_EVENT_TIME - ); - // Verify supervisors are healthy before termination - ITRetryUtil.retryUntil( - () -> SupervisorStateManager.BasicState.RUNNING.equals(indexer.getSupervisorStatus(generatedTestConfig1.getSupervisorId())), - true, - 10000, - 30, - "Waiting for supervisor1 to be healthy" - ); - ITRetryUtil.retryUntil( - () -> SupervisorStateManager.BasicState.RUNNING.equals(indexer.getSupervisorStatus(generatedTestConfig2.getSupervisorId())), - true, - 10000, - 30, - "Waiting for supervisor2 to be healthy" - ); // Sleep for 10 secs to make sure that at least one cycle of supervisor auto cleanup duty ran Thread.sleep(10000);
speed up test (#<I>)
apache_incubator-druid
train
165ac6a21152f9d461c877a67767184bb19e2575
diff --git a/socketio/__init__.py b/socketio/__init__.py index <HASH>..<HASH> 100644 --- a/socketio/__init__.py +++ b/socketio/__init__.py @@ -12,8 +12,33 @@ def socketio_manage(environ, namespaces, request=None): """Main SocketIO management function, call from within your Framework of choice's view. - The request object is not required, but will probably be useful to pass - framework-specific things into your Socket and Namespace functions. + The ``environ`` variable is the WSGI ``environ``. It is used to extract the + Socket object from the underlying server (as the 'socketio' key), and is + otherwise attached to both the Socket and Namespace objects. + + The ``request`` object is not required, but will probably be useful to pass + framework-specific things into your Socket and Namespace functions. It will + simply be attached to the Socket and Namespace object (accessible through + ``self.request`` in both cases), and it is not accessed in any case by the + ``gevent-socketio`` library. + + The ``namespaces`` parameter is a dictionary of the namespace string + representation as key, and the BaseNamespace namespace class descendant as + a value. The empty string ('') namespace is the global namespace. You can + use Socket.GLOBAL_NS to be more explicit. So it would look like: + + namespaces={'': GlobalNamespace, + '/chat': ChatNamespace} + + This function will block the current "view" or "controller" in your + framework to do the recv/send on the socket, and dispatch incoming messages + to your namespaces. + + This is a simple example using Pyramid: + + def my_view(request): + socketio_manage(request.environ, {'': GlobalNamespace}, request) + """ socket = environ['socketio'] socket._set_environ(environ) @@ -28,5 +53,4 @@ def socketio_manage(environ, namespaces, request=None): gevent.joinall([receiver_loop, watcher]) # TODO: double check, what happens to the WSGI request here ? it vanishes ? - return diff --git a/socketio/virtsocket.py b/socketio/virtsocket.py index <HASH>..<HASH> 100644 --- a/socketio/virtsocket.py +++ b/socketio/virtsocket.py @@ -49,7 +49,7 @@ class Socket(object): STATE_DISCONNECTING = "DISCONNECTING" STATE_DISCONNECTED = "DISCONNECTED" - GLOBAL_NS = None + GLOBAL_NS = '' """Use this to be explicit when specifying a Global Namespace (an endpoint with no name, not '/chat' or anything."""
The GLOBAL_NS is now an empty string '', we'll want to have that in the documentation.
abourget_gevent-socketio
train
9f27126779ab1c6e10ac90a7ccfafc3479ea5c5f
diff --git a/test/spec/bundler/chunkedBundleBuilder.js b/test/spec/bundler/chunkedBundleBuilder.js index <HASH>..<HASH> 100644 --- a/test/spec/bundler/chunkedBundleBuilder.js +++ b/test/spec/bundler/chunkedBundleBuilder.js @@ -81,4 +81,31 @@ ${wrapModule(dep2, 3)} expect(combineSourceMap.removeComments(result)).to.equal(expected); }); }); + + describe("When bundling a hello world module with an ES6 dependency", function() { + var input, dep1, result; + + beforeEach(function() { + input = "import './X';\nimport('./X');\nexport default 'hello world';"; + dep1 = "console.log('from X.js');"; + + result = chunkedBundleBuilder.buildBundle({ + 1: { source: input, entry: true, deps: [{ id: 2, name: "./X" }] }, + 2: { source: dep1 } + }); + }); + + it("then the bundler generates the correct result", function() { + var expected = ( +`require=_bb$iter=(${prelude})({ +${wrapModule(input, 1, {"./X": 2})}, +${wrapModule(dep1, 2)} +},[1]); + +`); + + expect(combineSourceMap.removeComments(result)).to.equal(expected); + }); + }); + });
adding unit test to test the bundle builder with ES<I> import/export statements, including dynamic imports
MiguelCastillo_bit-bundler
train
9b46361a7325dd77329b4c26f2e9e9fdf212bce3
diff --git a/src/Config/Loader/FileLoader/Json.php b/src/Config/Loader/FileLoader/Json.php index <HASH>..<HASH> 100644 --- a/src/Config/Loader/FileLoader/Json.php +++ b/src/Config/Loader/FileLoader/Json.php @@ -56,7 +56,7 @@ class Json extends FileLoaderAbstract } /** - * Return whether or not the passed in resrouce is supported by this loader + * Return whether or not the passed in resource is supported by this loader * * @param string $resource Plain string or filepath * @param string $type Not used
fix issue #<I> (#<I>) Corrects a typo in the documentation.
theorchard_monolog-cascade
train
878198cefae028386c6dc800ccbf18f2b9cbff3f
diff --git a/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.php b/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.php @@ -91,6 +91,29 @@ abstract class UserPasswordValidatorTest extends AbstractConstraintValidatorTest } /** + * @dataProvider emptyPasswordData + */ + public function testEmptyPasswordsAreNotValid($password) + { + $constraint = new UserPassword(array( + 'message' => 'myMessage', + )); + + $this->validator->validate($password, $constraint); + + $this->buildViolation('myMessage') + ->assertRaised(); + } + + public function emptyPasswordData() + { + return array( + array(null), + array(''), + ); + } + + /** * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException */ public function testUserIsNotValid() diff --git a/src/Symfony/Component/Security/Core/Validator/Constraints/UserPasswordValidator.php b/src/Symfony/Component/Security/Core/Validator/Constraints/UserPasswordValidator.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Component/Security/Core/Validator/Constraints/UserPasswordValidator.php +++ b/src/Symfony/Component/Security/Core/Validator/Constraints/UserPasswordValidator.php @@ -40,6 +40,8 @@ class UserPasswordValidator extends ConstraintValidator } if (null === $password || '' === $password) { + $this->context->addViolation($constraint->message); + return; }
[Security] validate empty passwords again
symfony_symfony
train
b105952663ccaf9e31be9aedce459269b17d0686
diff --git a/regions/io/read_ds9.py b/regions/io/read_ds9.py index <HASH>..<HASH> 100644 --- a/regions/io/read_ds9.py +++ b/regions/io/read_ds9.py @@ -211,16 +211,18 @@ def ds9_region_list_to_objects(region_list): return output_list -def ds9_string_to_objects(region_string, warn_skipped=False): +def ds9_string_to_objects(region_string, errors='strict'): """Parse ds9 region string to region objects Parameters ---------- region_string : str DS9 region string - warn_skipped : bool - Print a warning if there is a skipped (commented) line? - Can set to ``False`` or ``'raise'`` if you want an exception instead. + errors : ``warn``, ``ignore``, ``strict`` + The error handling scheme to use for handling parsing errors. + The default is 'strict', which will raise a ``ValueError``. + ``warn`` will raise a warning, and ``ignore`` will do nothing + (i.e., be silent). Returns ------- @@ -231,21 +233,24 @@ def ds9_string_to_objects(region_string, warn_skipped=False): -------- TODO """ - region_list = ds9_string_to_region_list(region_string, warn_skipped=warn_skipped) + region_list = ds9_string_to_region_list(region_string, errors=errors) regions = ds9_region_list_to_objects(region_list) return regions -def ds9_string_to_region_list(region_string, warn_skipped=False): +def ds9_string_to_region_list(region_string, errors='strict'): """Parse a DS9 region string. Parameters ---------- region_string : str DS9 region string - warn_skipped : bool - Print a warning if there is a skipped (commented) line? - Can set to ``False`` or ``'raise'`` if you want an exception instead. + errors : ``warn``, ``ignore``, ``strict`` + The error handling scheme to use for handling skipped entries + in a region file that were not parseable. + The default is 'strict', which will raise a ``ValueError``. + ``warn`` will raise a warning, and ``ignore`` will do nothing + (i.e., be silent). Returns ------- @@ -267,7 +272,7 @@ def ds9_string_to_region_list(region_string, warn_skipped=False): for line_ in region_string.split('\n'): for line in line_.split(";"): lines.append(line) - parsed = line_parser(line, coordsys, warn_skipped=warn_skipped) + parsed = line_parser(line, coordsys, errors=errors) if parsed in coordinate_systems: coordsys = parsed elif parsed: @@ -289,7 +294,7 @@ def ds9_string_to_region_list(region_string, warn_skipped=False): return regions -def line_parser(line, coordsys=None, warn_skipped=False): +def line_parser(line, coordsys=None, errors='strict'): """ Parse a single ds9 region line into a string @@ -299,9 +304,12 @@ def line_parser(line, coordsys=None, warn_skipped=False): A single ds9 region contained in a string coordsys : str The global coordinate system name declared at the top of the ds9 file - warn_skipped : bool - Print a warning if there is a skipped (commented) line? - Can set to ``False`` or ``'raise'`` if you want an exception instead. + errors : ``warn``, ``ignore``, ``strict`` + The error handling scheme to use for handling skipped entries + in a region file that were not parseable. + The default is 'strict', which will raise a ``ValueError``. + ``warn`` will raise a warning, and ``ignore`` will do nothing + (i.e., be silent). Returns ------- @@ -314,6 +322,9 @@ def line_parser(line, coordsys=None, warn_skipped=False): include : bool Whether the region is included (False -> excluded) """ + if errors not in ('strict','ignore','warn'): + raise ValueError("``errors`` must be one of strict, ignore, or warn") + region_type_search = region_type_or_coordsys_re.search(line) if region_type_search: include = region_type_search.groups()[0] @@ -391,10 +402,10 @@ def line_parser(line, coordsys=None, warn_skipped=False): # should not result in a warning, but this # rectfangle(1,2,3,4) # probably should! - if warn_skipped: + if errors in ('warn','strict'): message = ("Region type '{0}' was identified, but it is not one of " "the known region types.".format(region_type)) - if warn_skipped == 'raise': + if errors == 'strict': raise ValueError(message) else: warn(message, AstropyUserWarning) diff --git a/regions/io/tests/test_ds9_language.py b/regions/io/tests/test_ds9_language.py index <HASH>..<HASH> 100644 --- a/regions/io/tests/test_ds9_language.py +++ b/regions/io/tests/test_ds9_language.py @@ -133,7 +133,7 @@ def test_missing_region_warns(): # this will warn on both the commented first line and the not_a_region line with catch_warnings(AstropyUserWarning) as ASWarn: - regions = ds9_string_to_objects(ds9_str, warn_skipped=True) + regions = ds9_string_to_objects(ds9_str, errors='warn') assert len(regions) == 1 assert len(ASWarn) == 2
change error handling to @cdeil's recommendations
astropy_regions
train
6ed7378b11fcab952d4c1c683dcb71040934eafc
diff --git a/src/Taskforcedev/User/Controllers/UserController.php b/src/Taskforcedev/User/Controllers/UserController.php index <HASH>..<HASH> 100644 --- a/src/Taskforcedev/User/Controllers/UserController.php +++ b/src/Taskforcedev/User/Controllers/UserController.php @@ -98,13 +98,16 @@ class UserController extends \Controller $data = $this->populateInput(); $data['password'] = Hash::make($data['password']); - \User::create($data); + $user = \User::create($data); // Attempt to authenticate - $default_route = $this->getDefaultRoute(); - if (Auth::attempt($data)) + + if (Auth::attempt($user)) { + $default_route = $this->getDefaultRoute(); return \Redirect::route($default_route); + } else { + return \Redirect::route('tfdev.register.form'); } }
Attempting to finalize registration redirects
taskforcedev_user
train
ca3aa504cf6169966855f3ab7a8e1efe77fced0f
diff --git a/aiogram/bot/api.py b/aiogram/bot/api.py index <HASH>..<HASH> 100644 --- a/aiogram/bot/api.py +++ b/aiogram/bot/api.py @@ -99,17 +99,17 @@ async def _check_result(method_name, response): exceptions.MethodNotKnown.throw() raise exceptions.NotFound(description) elif response.status == HTTPStatus.CONFLICT: - if exceptions.TerminatedByOtherGetUpdates.match(description): + if exceptions.TerminatedByOtherGetUpdates.check(description): exceptions.TerminatedByOtherGetUpdates.throw() - if exceptions.CantGetUpdates.match(description): + if exceptions.CantGetUpdates.check(description): exceptions.CantGetUpdates.throw() raise exceptions.ConflictError(description) elif response.status in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN]: - if exceptions.BotKicked.match(description): + if exceptions.BotKicked.check(description): exceptions.BotKicked.throw() - elif exceptions.BotBlocked.match(description): + elif exceptions.BotBlocked.check(description): exceptions.BotBlocked.throw() - elif exceptions.UserDeactivated.match(description): + elif exceptions.UserDeactivated.check(description): exceptions.UserDeactivated.throw() raise exceptions.Unauthorized(description) elif response.status == HTTPStatus.REQUEST_ENTITY_TOO_LARGE:
Wow. Fail. Wrong method name.
aiogram_aiogram
train
475d1e040b09583929ec528e0f1f68cba85c3048
diff --git a/lib/open_geo_db/database.rb b/lib/open_geo_db/database.rb index <HASH>..<HASH> 100644 --- a/lib/open_geo_db/database.rb +++ b/lib/open_geo_db/database.rb @@ -6,7 +6,7 @@ module OpenGeoDb def initialize(config) @database = config["database"] @username = config["username"] - @password = "-p#{config["password"]}" if config["password"] and config["password"].any? + @password = "-p#{config["password"]}" if config["password"] end def execute(action)
Should not try to check if password is non-empty
kostia_open_geo_db
train
9569507781c68015c6ead38426e67c76e6aae2f5
diff --git a/src/utils/callAjax.js b/src/utils/callAjax.js index <HASH>..<HASH> 100644 --- a/src/utils/callAjax.js +++ b/src/utils/callAjax.js @@ -8,6 +8,7 @@ export default (url, callback)=> { } } } + httpRequest.setRequestHeader("Accept", "application/json") httpRequest.open('GET', url) httpRequest.send() -} \ No newline at end of file +}
explicitly accept json in ajax requests The ajax request is parsing the result as JSON, however this isn't being set in the headers. Firefox adds default headers for text/html, text/xml etc. This means that some frameworks like Laravel, Umbraco etc start to automatically return the data as XML, breaking the typeahead data parsing.
yuche_vue-strap
train
432344eb2ad0c0d1015366e7c23568e6d26c4f7c
diff --git a/dist/aframe-xr.js b/dist/aframe-xr.js index <HASH>..<HASH> 100644 --- a/dist/aframe-xr.js +++ b/dist/aframe-xr.js @@ -6263,7 +6263,7 @@ AFRAME.registerComponent('xranchor', { updateFrame: function updateFrame(data) { var frame = data.detail; - var anchorOffset = this.el.anchorOffset; + var anchorOffset = this.anchorOffset; if (!anchorOffset) { return;
upload dev build (keep forgetting to build it)
mozilla_aframe-xr
train
4c7021da186a56e683c93da6d65459b408373765
diff --git a/pyjade/ext/django/loader.py b/pyjade/ext/django/loader.py index <HASH>..<HASH> 100644 --- a/pyjade/ext/django/loader.py +++ b/pyjade/ext/django/loader.py @@ -71,7 +71,7 @@ class Loader(BaseLoader): if not hasattr(template, 'render'): try: template = get_template_from_string(process(source,filename=template_name,compiler=Compiler), origin, template_name) - except TemplateDoesNotExist: + except TemplateDoesNotExist, UnboundLocalError: # If compiling the template we found raises TemplateDoesNotExist, # back off to returning he source and display name for the template # we were asked to load. This allows for correct identification (later)
Taking in account the case when the source variable is not defined and an UnboundLocalError exception is raised
syrusakbary_pyjade
train
b232003a9c24b3cb4163c11e520debb70d74cdd0
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index <HASH>..<HASH> 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -10,7 +10,6 @@ end require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' -require 'rspec/autorun' require 'rr' require 'webmock/rspec' @@ -49,7 +48,6 @@ RSpec.configure do |config| # --seed 1234 config.order = "random" config.global_fixtures = :all - config.treat_symbols_as_metadata_keys_with_true_values = true config.render_views
Follow the deprecation warnings after upgrading RSpec to 3.
huginn_huginn
train
c87eb4629f9b0049483ddbba369012dfd2d423ba
diff --git a/lib/bugsnag/integrations/rack.rb b/lib/bugsnag/integrations/rack.rb index <HASH>..<HASH> 100644 --- a/lib/bugsnag/integrations/rack.rb +++ b/lib/bugsnag/integrations/rack.rb @@ -25,7 +25,7 @@ module Bugsnag # Hook up rack-based notification middlewares config.middleware.insert_before([Bugsnag::Middleware::Rails3Request,Bugsnag::Middleware::Callbacks], Bugsnag::Middleware::RackRequest) if defined?(::Rack) config.middleware.insert_before(Bugsnag::Middleware::Callbacks, Bugsnag::Middleware::WardenUser) if defined?(Warden) - config.middleware.insert_before(Bugsnag::Middleware::Callbkacs, Bugsnag::Middleware::ClearanceUser) if defined?(Clearance) + config.middleware.insert_before(Bugsnag::Middleware::Callbacks, Bugsnag::Middleware::ClearanceUser) if defined?(Clearance) config.app_type ||= "rack" end
Fix typo in Rack / Clearance integration
bugsnag_bugsnag-ruby
train
56e6eefe943fdbf6dc977e9bdcbf14f5d37d10f5
diff --git a/lib/disneytokyo/index.js b/lib/disneytokyo/index.js index <HASH>..<HASH> 100644 --- a/lib/disneytokyo/index.js +++ b/lib/disneytokyo/index.js @@ -369,33 +369,31 @@ class DisneyTokyoPark extends Park { * @returns {Promise<Object>} `rideID` to English names */ GetRideNames() { - return this.Cache.Wrap("ridenames", function() { - return new Promise(function(resolve, reject) { - // fetch ride names - this.HTTP({ - url: `http://www.tokyodisneyresort.jp/api/v1/wapi_attractions/lists/sort_type:1/locale:1/park_kind:${this[s_parkKind]}/`, - forceJSON: true, - headers: { - "Referer": `http://www.tokyodisneyresort.jp/en/attraction/lists/park:${this[s_parkID]}`, - connection: "keep-alive", - }, - retryDelay: 1000 * 10 - }).then(function(body) { - if (!body || !body.entries || !body.entries.length) { - return reject("Failed to find entries in ride data response"); - } + return this.Cache.Wrap("ridenames", () => { + // fetch ride names + return this.HTTP({ + url: `https://www.tokyodisneyresort.jp/en/${this[s_parkID]}/attraction.html`, + headers: { + "Referer": `https://www.tokyodisneyresort.jp/en/${this[s_parkID]}/attraction.html`, + connection: "keep-alive", + }, + retryDelay: 1000 * 10 + }).then((body) => { + if (!body) { + return Promise.reject("Failed to find entries in ride data response"); + } - // populate data - var rideData = {}; - for (var i = 0, ride; ride = body.entries[i++];) { - // use English if we can, fallback to yomi if we're missing an English name - rideData[ride.str_id] = ride.name || ride.name_yomi; - } + const regexGetRideNames = /detail\/([0-9]+)\/">[\s\n]*<div class="headingArea">[\s\n]*<div class="headingAreaInner">[\s\n]*<h3 class="heading3">([^<]+)<\/h3>/g; - return resolve(rideData); - }.bind(this), reject); - }.bind(this)); - }.bind(this), 86400); + let match; + var rideData = {}; + while (match = regexGetRideNames.exec(body)) { + rideData[Number(match[1])] = match[2]; + } + + return Promise.resolve(rideData); + }); + }, 86400); } }
[!] Fix tokyo disney wait times not fetching because ride names were unavailable * Old API was shutdown, so having to parse them out from HTML manually
cubehouse_themeparks
train
41e0f3a84def77e1a11243e9c1d22d804fb3375e
diff --git a/src/Html/MutableAttributesTrait.php b/src/Html/MutableAttributesTrait.php index <HASH>..<HASH> 100644 --- a/src/Html/MutableAttributesTrait.php +++ b/src/Html/MutableAttributesTrait.php @@ -22,6 +22,8 @@ trait MutableAttributesTrait { * @param string $class * * @return $this + * + * @see MutableAttributesBuilderInterface::addClass() */ function addClass($class) { $this->attributes = $this->attributes->addClass($class); @@ -32,6 +34,8 @@ trait MutableAttributesTrait { * @param string[] $classes * * @return $this + * + * @see MutableAttributesBuilderInterface::addClasses() */ function addClasses(array $classes) { $this->attributes = $this->attributes->addClasses($classes); @@ -41,6 +45,8 @@ trait MutableAttributesTrait { * @return string * The string of all attributes, starting with a space. * E.g. ' class="class0 class1" id="5"' + * + * @see AttributesGetterInterface::renderAttributes() */ protected function renderAttributes() { return $this->attributes->renderAttributes(); @@ -51,6 +57,8 @@ trait MutableAttributesTrait { * @param string $content * * @return string + * + * @see AttributesGetterInterface::renderTag() */ protected function renderTag($tagName, $content) { return $this->attributes->renderTag($tagName, $content); @@ -60,6 +68,8 @@ trait MutableAttributesTrait { * @param $tagName * * @return TagInterface + * + * @see AttributesGetterInterface::createTag() */ protected function createTag($tagName) { return $this->attributes->createTag($tagName);
MutableAttributesTrait: Doc: Add @see comments pointing to interface methods.
donquixote_cellbrush
train
7e59a92f881cc9e240a2feebd34a24e6183bb2ea
diff --git a/plotnine/stats/stat_bin_2d.py b/plotnine/stats/stat_bin_2d.py index <HASH>..<HASH> 100644 --- a/plotnine/stats/stat_bin_2d.py +++ b/plotnine/stats/stat_bin_2d.py @@ -69,7 +69,7 @@ class stat_bin_2d(stat): drop = params['drop'] weight = data.get('weight') - if not weight: + if weight is None: weight = np.ones(len(data['x'])) # The bins will be over the dimension(full size) of the @@ -83,8 +83,10 @@ class stat_bin_2d(stat): y = np.append(data['y'], range_y) # create the cutting parameters - xbreaks = fuzzybreaks(scales.x, breaks.x, binwidth.x, bins.x) - ybreaks = fuzzybreaks(scales.y, breaks.y, binwidth.y, bins.y) + xbreaks = fuzzybreaks(scales.x, breaks=breaks.x, + binwidth=binwidth.x, bins=bins.x) + ybreaks = fuzzybreaks(scales.y, breaks.y, + binwidth=binwidth.y, bins=bins.y) xbins = pd.cut(x, bins=xbreaks, labels=False, right=True) ybins = pd.cut(y, bins=ybreaks, labels=False, right=True)
Fix broken stat_bin_2d plus a `if not array` bug It broke when the `fuzzybreaks()` signature was changed.
has2k1_plotnine
train
9a9f59fcc6e7b93465ce9848b52a473477dff64a
diff --git a/src/Illuminate/Database/Eloquent/Model.php b/src/Illuminate/Database/Eloquent/Model.php index <HASH>..<HASH> 100644 --- a/src/Illuminate/Database/Eloquent/Model.php +++ b/src/Illuminate/Database/Eloquent/Model.php @@ -990,6 +990,16 @@ abstract class Model implements Arrayable, ArrayAccess, Jsonable, JsonSerializab } /** + * Get all of the current attributes on the model for insert. + * + * @return array + */ + protected function getAttributesForInsert() + { + return $this->getAttributes(); + } + + /** * Perform a model insert operation. * * @param \Illuminate\Database\Eloquent\Builder $query @@ -1011,7 +1021,7 @@ abstract class Model implements Arrayable, ArrayAccess, Jsonable, JsonSerializab // If the model has an incrementing key, we can use the "insertGetId" method on // the query builder, which will give us back the final inserted ID for this // table from the database. Not all tables have to be incrementing though. - $attributes = $this->getAttributes(); + $attributes = $this->getAttributesForInsert(); if ($this->getIncrementing()) { $this->insertAndSetId($query, $attributes);
refactor: extract attribute getter for insert.
laravel_framework
train
b857e7497d4b6655b97d4b9a1a4be5222f897e75
diff --git a/src/main/java/com/jamesmurty/utils/XMLBuilder.java b/src/main/java/com/jamesmurty/utils/XMLBuilder.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/jamesmurty/utils/XMLBuilder.java +++ b/src/main/java/com/jamesmurty/utils/XMLBuilder.java @@ -327,6 +327,10 @@ public class XMLBuilder { * Add a named XML element to the document as a child of this builder node, * and return the builder node representing the new child. * + * When adding an element to a namespaced document, the new node will be + * assigned a namespace matching it's qualified name prefix (if any) or + * the document's default namespace. + * * @param name * the name of the XML element. * @@ -338,7 +342,9 @@ public class XMLBuilder { * contains a text node value. */ public XMLBuilder element(String name) { - return element(name, null); + String prefix = getPrefixFromQualifiedName(name); + String namespaceURI = this.xmlElement.lookupNamespaceURI(prefix); + return element(name, namespaceURI); } /** @@ -985,4 +991,13 @@ public class XMLBuilder { return new NamespaceContextImpl(this.root().getElement()); } + protected String getPrefixFromQualifiedName(String qualifiedName) { + int colonPos = qualifiedName.indexOf(':'); + if (colonPos > 0) { + return qualifiedName.substring(0, colonPos); + } else { + return null; + } + } + } diff --git a/src/test/java/com/jamesmurty/utils/TestXmlBuilder.java b/src/test/java/com/jamesmurty/utils/TestXmlBuilder.java index <HASH>..<HASH> 100644 --- a/src/test/java/com/jamesmurty/utils/TestXmlBuilder.java +++ b/src/test/java/com/jamesmurty/utils/TestXmlBuilder.java @@ -244,55 +244,64 @@ public class TestXmlBuilder extends TestCase { .create("NamespaceTest", "urn:default") .namespace("prefix1", "urn:ns1") - .element("NoNamespace").up() - - .element("NSDefault", "urn:default").up() + .element("NSDefaultImplicit").up() + .element("NSDefaultExplicit", "urn:default").up() .element("NS1Explicit", "urn:ns1").up() - .element("prefix1:NS1ByPrefix", "urn:ns1").up(); + .element("prefix1:NS1WithPrefixExplicit", "urn:ns1").up() + .element("prefix1:NS1WithPrefixImplicit").up(); // Build a namespace context from the builder's document NamespaceContextImpl context = builder.buildDocumentNamespaceContext(); - // Find node with no namespace using xpath query with or without context - builder.xpathFind("//NoNamespace"); - builder.xpathFind("//NoNamespace", context); + // All elements in a namespaced document inherit a namespace URI, + // for namespaced document any non-namespaced XPath query will fail. + try { + builder.xpathFind("//:NSDefaultImplicit"); + fail("Namespaced xpath query without context is invalid"); + } catch (XPathExpressionException e) {} + try { + builder.xpathFind("//NSDefaultImplicit", context); + fail("XPath query without prefixes on namespaced docs is invalid"); + } catch (XPathExpressionException e) {} // Find nodes with default namespace builder.xpathFind("/:NamespaceTest", context); - builder.xpathFind("//:NSDefault", context); + builder.xpathFind("//:NSDefaultExplicit", context); + builder.xpathFind("//:NSDefaultImplicit", context); // Must use namespace-aware xpath to find namespaced nodes try { - builder.xpathFind("//NSDefault"); + builder.xpathFind("//NSDefaultExplicit"); fail(); } catch (XPathExpressionException e) {} try { - builder.xpathFind("//:NSDefault"); + builder.xpathFind("//:NSDefaultExplicit"); fail(); } catch (XPathExpressionException e) {} try { - builder.xpathFind("//NSDefault", context); + builder.xpathFind("//NSDefaultExplicit", context); fail(); } catch (XPathExpressionException e) {} // Find node with namespace prefix builder.xpathFind("//prefix1:NS1Explicit", context); - builder.xpathFind("//prefix1:NS1ByPrefix", context); + builder.xpathFind("//prefix1:NS1WithPrefixExplicit", context); + builder.xpathFind("//prefix1:NS1WithPrefixImplicit", context); // Find nodes with user-defined prefix "aliases" context.addNamespace("default-alias", "urn:default"); context.addNamespace("prefix1-alias", "urn:ns1"); - builder.xpathFind("//default-alias:NSDefault", context); + builder.xpathFind("//default-alias:NSDefaultExplicit", context); builder.xpathFind("//prefix1-alias:NS1Explicit", context); // User can override context mappings, for better or worse context.addNamespace("", "urn:default"); - builder.xpathFind("//:NSDefault", context); + builder.xpathFind("//:NSDefaultExplicit", context); context.addNamespace("", "urn:wrong"); try { - builder.xpathFind("//:NSDefault", context); + builder.xpathFind("//:NSDefaultExplicit", context); fail(); } catch (XPathExpressionException e) {}
When adding elements to builder, assignment of namespace URIs is now automatic (and required) within a namespaced document. In short, elements can be added without explicitly specifying the namespace URI every time. git-svn-id: <URL>
jmurty_java-xmlbuilder
train
b504eb28d2d1f77cd48a8207372aacb37884b087
diff --git a/MAVProxy/modules/mavproxy_log.py b/MAVProxy/modules/mavproxy_log.py index <HASH>..<HASH> 100644 --- a/MAVProxy/modules/mavproxy_log.py +++ b/MAVProxy/modules/mavproxy_log.py @@ -136,4 +136,6 @@ def idle_task(): '''handle missing log data''' state = mpstate.log_state if state.download_last_timestamp is not None and time.time() - state.download_last_timestamp > 0.5: + state.download_last_timestamp = time.time() handle_log_data_missing() +
log: prevent flood of log data requests
ArduPilot_MAVProxy
train
69250f339eaeb4974aa33398d833483da893114f
diff --git a/src/Window.js b/src/Window.js index <HASH>..<HASH> 100644 --- a/src/Window.js +++ b/src/Window.js @@ -1010,8 +1010,8 @@ const _makeRequestAnimationFrame = window => (fn, priority = 0) => { const rafCbs = []; window[symbols.rafCbsSymbol] = rafCbs; - const timeouts = []; - const intervals = []; + const timeouts = [null]; + const intervals = [null]; const localCbs = []; const prevSyncs = []; const _cacheLocalCbs = cbs => {
Small timeouts/itervals cleanup
exokitxr_exokit
train
cf9f22a1be6dd5fb5423d52dbf50ce6eb35c2500
diff --git a/src/Rewrite_Command.php b/src/Rewrite_Command.php index <HASH>..<HASH> 100644 --- a/src/Rewrite_Command.php +++ b/src/Rewrite_Command.php @@ -27,6 +27,7 @@ * * @package wp-cli */ +// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- for back compat this class shouldn't be renamed. class Rewrite_Command extends WP_CLI_Command { /**
PHPCS: ignore the class naming convention for this class We should avoid renaming this class to prevent any back-compat issues
wp-cli_rewrite-command
train
31cac625fbbf4518ddd1fb8f3926190ea5da1563
diff --git a/sentry/plugins/sentry_redmine/models.py b/sentry/plugins/sentry_redmine/models.py index <HASH>..<HASH> 100644 --- a/sentry/plugins/sentry_redmine/models.py +++ b/sentry/plugins/sentry_redmine/models.py @@ -28,29 +28,26 @@ class CreateRedmineIssue(GroupActionProvider): if request.POST: form = RedmineIssueForm(request.POST) if form.is_valid(): - data = { + data = simplejson.dumps({ 'issue': { 'subject': form.cleaned_data['subject'], 'description': form.cleaned_data['description'], } - } + }) url = conf.REDMINE_URL + '/projects/' + conf.REDMINE_PROJECT_SLUG + '/issues.json' req = urllib2.Request(url, urllib.urlencode({ 'key': conf.REDMINE_API_KEY, }), headers={ - 'Content-type': 'text/json', + 'Content-type': 'application/json', }) try: - print simplejson.dumps(data) - response = urllib2.urlopen(req, simplejson.dumps(data)).read() + response = urllib2.urlopen(req, data).read() except urllib2.HTTPError, e: raise Exception('%s: %s' % (e.code, e.read())) - - print response - raise Exception - #RedmineIssue.objects.create(group=group, issue_id=response['issue_id']) + data = simplejson.loads(response) + RedmineIssue.objects.create(group=group, issue_id=data['id']) else: description = 'Sentry Message: %s' % request.build_absolute_uri(group.get_absolute_url()) description += '\n\n' + (group.traceback or group.message) diff --git a/sentry/plugins/sentry_redmine/tests/__init__.py b/sentry/plugins/sentry_redmine/tests/__init__.py index <HASH>..<HASH> 100644 --- a/sentry/plugins/sentry_redmine/tests/__init__.py +++ b/sentry/plugins/sentry_redmine/tests/__init__.py @@ -4,7 +4,7 @@ from django.test import TestCase from sentry.models import GroupedMessage from sentry.plugins.sentry_redmine import conf -from sentry.plugins.sentry_redmine.models import CreateRedmineIssue +from sentry.plugins.sentry_redmine.models import CreateRedmineIssue, RedmineIssue class CreateIssueTest(TestCase): fixtures = ['sentry/plugins/sentry_redmine/tests/fixtures/regression.json'] @@ -32,4 +32,5 @@ class CreateIssueTest(TestCase): }) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'sentry/plugins/redmine/create_issue.html') - \ No newline at end of file + + self.assertTrue(RedmineIssue.objects.filter(group=group).exists()) \ No newline at end of file
Communicating with rails API ugliness is not working (Redmine tests pass).
elastic_apm-agent-python
train
f91d6f49087e19320c4ef883fe00b06508e036c6
diff --git a/src/main/java/com/omertron/omdbapi/model/OmdbVideoBasic.java b/src/main/java/com/omertron/omdbapi/model/OmdbVideoBasic.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/omertron/omdbapi/model/OmdbVideoBasic.java +++ b/src/main/java/com/omertron/omdbapi/model/OmdbVideoBasic.java @@ -34,6 +34,8 @@ public class OmdbVideoBasic extends AbstractJsonMapping implements Serializable private String type = ""; @JsonProperty("Poster") private String poster = ""; + @JsonProperty("Plot") + private String plot = ""; //<editor-fold defaultstate="collapsed" desc="Getter Methods"> public String getTitle() { @@ -57,6 +59,14 @@ public class OmdbVideoBasic extends AbstractJsonMapping implements Serializable } //</editor-fold> + public String getPlot() { + return plot; + } + + public void setPlot(String plot) { + this.plot = plot; + } + //<editor-fold defaultstate="collapsed" desc="Setter Methods"> public void setTitle(String title) { this.title = title;
There are two plot lengths, one short, one long. The short should be accessible.
Omertron_api-omdb
train
a8dcf4b5b47601983a55e33a094e260f035e6506
diff --git a/lib/core/Socket.js b/lib/core/Socket.js index <HASH>..<HASH> 100644 --- a/lib/core/Socket.js +++ b/lib/core/Socket.js @@ -240,6 +240,8 @@ this.connected = true; this.connecting = false; this.node.emit('SOCKET_CONNECT'); + + // The testing framework expects this, do not remove. this.node.log('socket connected.'); };
Added "don't remove" comment
nodeGame_nodegame-client
train
fc86a10796be77a6330d496fc69e1d050dad7448
diff --git a/lib/vagrant/ui.rb b/lib/vagrant/ui.rb index <HASH>..<HASH> 100644 --- a/lib/vagrant/ui.rb +++ b/lib/vagrant/ui.rb @@ -288,6 +288,9 @@ module Vagrant opts = @opts.merge(opts) + # Default the bold option if its not given + opts[:bold] = type == :output if !opts.has_key?(:bold) + # Special case some colors for certain message types opts[:color] = :red if type == :error opts[:color] = :yellow if type == :warn @@ -297,7 +300,7 @@ module Vagrant # If it is a detail, it is not bold. Every other message type # is bolded. - bold = type != :detail + bold = !!opts[:bold] color = COLORS[opts[:color]] # Color the message and make sure to reset the color at the end diff --git a/test/unit/vagrant/ui_test.rb b/test/unit/vagrant/ui_test.rb index <HASH>..<HASH> 100644 --- a/test/unit/vagrant/ui_test.rb +++ b/test/unit/vagrant/ui_test.rb @@ -129,7 +129,7 @@ describe Vagrant::UI::Colored do describe "#error" do it "colors red" do subject.should_receive(:safe_puts).with do |message, *args| - expect(message).to start_with("\033[1;31m") + expect(message).to start_with("\033[0;31m") expect(message).to end_with("\033[0m") end @@ -164,12 +164,23 @@ describe Vagrant::UI::Colored do subject.output("foo", color: :green) end + + it "doesn't bold the output if specified" do + subject.opts[:color] = :red + + subject.should_receive(:safe_puts).with do |message, *args| + expect(message).to start_with("\033[0;31m") + expect(message).to end_with("\033[0m") + end + + subject.output("foo", bold: false) + end end describe "#warn" do it "colors yellow" do subject.should_receive(:safe_puts).with do |message, *args| - expect(message).to start_with("\033[1;33m") + expect(message).to start_with("\033[0;33m") expect(message).to end_with("\033[0m") end
core: only bold when output is part of a machine
hashicorp_vagrant
train
750d33f964728227c4926d35692285622d58e95b
diff --git a/elasticmodels/__init__.py b/elasticmodels/__init__.py index <HASH>..<HASH> 100644 --- a/elasticmodels/__init__.py +++ b/elasticmodels/__init__.py @@ -22,9 +22,9 @@ def make_searchable(object, refresh=True): id = index.id(object) body = index.prepare(object) - es().index(index=settings.ELASTIC_SEARCH_INDEX, doc_type=index.doc_type, id=id, body=body) + es().index(index=settings.ELASTIC_SEARCH_CONNECTION['indexes'], doc_type=index.doc_type, id=id, body=body) if refresh: - es().indices.refresh(index=settings.ELASTIC_SEARCH_INDEX) + es().indices.refresh(index=settings.ELASTIC_SEARCH_CONNECTION['indexes']) def make_unsearchable(object, refresh=True): @@ -37,18 +37,18 @@ def make_unsearchable(object, refresh=True): index = index_registry[object.__class__] id = index.id(object) - es().delete(index=settings.ELASTIC_SEARCH_INDEX, doc_type=index.doc_type, id=id) + es().delete(index=settings.ELASTIC_SEARCH_CONNECTION['indexes'], doc_type=index.doc_type, id=id) if refresh: - es().indices.refresh(index=settings.ELASTIC_SEARCH_INDEX) + es().indices.refresh(index=settings.ELASTIC_SEARCH_CONNECTION['indexes']) def clear_index(): """Deletes (if it exists) and recreates the index""" try: - es().indices.delete(index=settings.ELASTIC_SEARCH_INDEX) + es().indices.delete(index=settings.ELASTIC_SEARCH_CONNECTION['indexes']) except elasticsearch.exceptions.NotFoundError: pass - es().indices.create(index=settings.ELASTIC_SEARCH_INDEX, body=settings.ELASTIC_SEARCH_SETTINGS) + es().indices.create(index=settings.ELASTIC_SEARCH_CONNECTION['indexes'], body=settings.ELASTIC_SEARCH_SETTINGS) class IndexableBase(type): diff --git a/elasticmodels/management/commands/rebuild_index.py b/elasticmodels/management/commands/rebuild_index.py index <HASH>..<HASH> 100644 --- a/elasticmodels/management/commands/rebuild_index.py +++ b/elasticmodels/management/commands/rebuild_index.py @@ -13,18 +13,18 @@ class Command(BaseCommand): for model_class, index in index_registry.items(): model = index.model es().indices.put_mapping( - index=settings.ELASTIC_SEARCH_INDEX, + index=settings.ELASTIC_SEARCH_CONNECTION['indexes'], doc_type=index.doc_type, body={ index.doc_type: index.mapping() } ) - es().indices.refresh(index=settings.ELASTIC_SEARCH_INDEX) + es().indices.refresh(index=settings.ELASTIC_SEARCH_CONNECTION['indexes']) #for obj in model.objects.all(): for obj in index.get_queryset(): #for obj in model.objects.filter(**(index.filter_params)): print("indexing %s pk = %d" % (obj.__class__.__name__, obj.pk)) # TODO use a bulk update for this make_searchable(obj, refresh=False) - es().indices.refresh(index=settings.ELASTIC_SEARCH_INDEX) + es().indices.refresh(index=settings.ELASTIC_SEARCH_CONNECTION['indexes']) diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -4,7 +4,7 @@ from setuptools import setup setup( name="elasticmodels", - version="0.0.6", + version="0.0.7", url='https://github.com/PSU-OIT-ARC/elasticmodels', author='Matt Johnson', author_email='mdj2@pdx.edu',
Derp. The ES index setting changed and I forgot to update it here. I need some unit tests
PSU-OIT-ARC_elasticmodels
train
0a4257549019e4b1e512b17e124ac4a6c614fe49
diff --git a/vendor/github.com/astaxie/beego/swagger/swagger.go b/vendor/github.com/astaxie/beego/swagger/swagger.go index <HASH>..<HASH> 100644 --- a/vendor/github.com/astaxie/beego/swagger/swagger.go +++ b/vendor/github.com/astaxie/beego/swagger/swagger.go @@ -141,7 +141,7 @@ type Propertie struct { // Response as they are returned from executing this operation. type Response struct { - Description string `json:"description,omitempty" yaml:"description,omitempty"` + Description string `json:"description" yaml:"description"` Schema *Schema `json:"schema,omitempty" yaml:"schema,omitempty"` Ref string `json:"$ref,omitempty" yaml:"$ref,omitempty"` }
Do no omit response description [swagger specs](<URL>) requires each response to have a description. Otherwise, ignorable error will be generated. This PR makes sure that description field is not omitted in the event that user did not give a description.
beego_bee
train
bb262753b6d27a116ec41bfa58fba8a4aa45b9d7
diff --git a/lib/rango/helpers/assets.rb b/lib/rango/helpers/assets.rb index <HASH>..<HASH> 100644 --- a/lib/rango/helpers/assets.rb +++ b/lib/rango/helpers/assets.rb @@ -1,5 +1,8 @@ # encoding: utf-8 +# TODO: javascript "application" => media/javascripts/application.js +# ... but what if I need full path? It should be tested if file exist, of course +# javascript Path.new("design/whatever.js") module Rango module Helpers # stolen from pupu (but it's OK, it's my code) @@ -11,11 +14,17 @@ module Rango # @since 0.0.2 def stylesheet(basename, attrs = Hash.new) - path = Path.new(File.join(Project.settings.media_root, basename)) + path = Path.new(File.join(Project.settings.media_root, "stylesheets", basename)) default = {href: path.url, media: 'screen', rel: 'stylesheet', type: 'text/css'} single_tag :link, default.merge(attrs) end + def image(basename, attrs = Hash.new) + path = Path.new(File.join(Project.settings.media_root, "images", basename)) + default = {src: path.url, alt: path.basename} + single_tag :img, default.merge(attrs) + end + # @since 0.0.2 def javascripts(*names) names.map { |name| self.javascript(name) }.join("\n")
image helper, fixed stylesheet to look at <media-dir>/stylesheets
botanicus_rango
train
30c10419c0ae6149e520f8355f32980f0ffdad65
diff --git a/fut14/core.py b/fut14/core.py index <HASH>..<HASH> 100644 --- a/fut14/core.py +++ b/fut14/core.py @@ -397,14 +397,17 @@ class Core(object): return self.__sendToPile__('watchlist', trade_id) def relist(self, clean=False): - """Relist all tradepile.""" + """Relist all tradepile. Returns True or number of deleted (sold) if clean was set.""" # TODO: return relisted ids self.__put__(self.urls['fut']['SearchAuctionsReListItem']) #{"tradeIdList":[{"id":139632781208},{"id":139632796467}]} if clean: # remove sold cards + sold = 0 for i in self.tradepile(): if i['tradeState'] == 'closed': self.tradepileDelete(i['tradeId']) + sold += 1 + return sold return True def keepalive(self):
core: relist returns number of delted/sold if clean parameter was set
futapi_fut
train
4129ace5c79deb04f69942c930e4b4d1cd72bd7b
diff --git a/src/com/google/javascript/jscomp/ant/CompileTask.java b/src/com/google/javascript/jscomp/ant/CompileTask.java index <HASH>..<HASH> 100644 --- a/src/com/google/javascript/jscomp/ant/CompileTask.java +++ b/src/com/google/javascript/jscomp/ant/CompileTask.java @@ -83,6 +83,7 @@ public final class CompileTask private boolean generateExports; private boolean replaceProperties; private boolean forceRecompile; + private boolean angularPass; private String replacePropertiesPrefix; private File outputFile; private String outputWrapper; @@ -109,6 +110,7 @@ public final class CompileTask this.generateExports = false; this.replaceProperties = false; this.forceRecompile = false; + this.angularPass = false; this.replacePropertiesPrefix = "closure.define."; this.defineParams = new LinkedList(); this.entryPointParams = new LinkedList(); @@ -274,6 +276,10 @@ public final class CompileTask public void setForceRecompile(boolean forceRecompile) { this.forceRecompile = forceRecompile; } + + public void setAngularPass(boolean angularPass) { + this.angularPass = angularPass; + } /** * Set generateExports option @@ -415,6 +421,7 @@ public final class CompileTask options.setManageClosureDependencies(manageDependencies); convertEntryPointParameters(options); options.setTrustedStrings(true); + options.setAngularPass(angularPass); if (replaceProperties) { convertPropertiesMap(options);
Added pass-through of angularPass option to ant task Although the "--angular-pass" option is available when invoking the compiler from the command line, it was not yet available in the ant plugin. This change adds support for angular pass by accepting it as an attribute and passing in the compiler options.
google_closure-compiler
train
3c56c0637a520e90c0544332b30466815878d7d2
diff --git a/default_handler.go b/default_handler.go index <HASH>..<HASH> 100644 --- a/default_handler.go +++ b/default_handler.go @@ -147,7 +147,7 @@ func (m exportedMethod) Call(args ...interface{}) ([]interface{}, error) { for i, val := range ret { out[i] = val.Interface() } - if nilErr { + if nilErr || err == nil { //concrete type to interface nil is a special case return out, nil } diff --git a/export_test.go b/export_test.go index <HASH>..<HASH> 100644 --- a/export_test.go +++ b/export_test.go @@ -34,6 +34,24 @@ func (export badExport) Foo(param string) string { return "bar" } +type errorExport struct { + message Message +} + +func (export *errorExport) Run(message Message, param string) (string, error) { + export.message = message + return "pass", nil +} + +type noErrorExport struct { + message Message +} + +func (export *noErrorExport) Run(message Message, param string) (string) { + export.message = message + return "cool" +} + // Test typical Export usage. func TestExport(t *testing.T) { connection, err := ConnectSessionBus() @@ -73,6 +91,64 @@ func TestExport(t *testing.T) { } } +// Test that Exported handlers can use a go error type. +func TestExport_goerror(t *testing.T) { + connection, err := ConnectSessionBus() + if err != nil { + t.Fatalf("Unexpected error connecting to session bus: %s", err) + } + defer connection.Close() + + name := connection.Names()[0] + + export := &errorExport{} + connection.ExportAll(export, "/org/guelfey/DBus/Test", "org.guelfey.DBus.Test") + object := connection.Object(name, "/org/guelfey/DBus/Test") + + var response string + err = object.Call("org.guelfey.DBus.Test.Run", 0, "qux").Store(&response) + if err != nil { + t.Errorf("Unexpected error calling Foo: %s", err) + } + + if response != "pass" { + t.Errorf(`Response was %s, expected "foo"`, response) + } + + if export.message.serial == 0 { + t.Error("Expected a valid message to be given to handler") + } +} + +// Test that Exported handlers can have no error. +func TestExport_noerror(t *testing.T) { + connection, err := ConnectSessionBus() + if err != nil { + t.Fatalf("Unexpected error connecting to session bus: %s", err) + } + defer connection.Close() + + name := connection.Names()[0] + + export := &noErrorExport{} + connection.ExportAll(export, "/org/guelfey/DBus/Test", "org.guelfey.DBus.Test") + object := connection.Object(name, "/org/guelfey/DBus/Test") + + var response string + err = object.Call("org.guelfey.DBus.Test.Run", 0, "qux").Store(&response) + if err != nil { + t.Errorf("Unexpected error calling Foo: %s", err) + } + + if response != "cool" { + t.Errorf(`Response was %s, expected "foo"`, response) + } + + if export.message.serial == 0 { + t.Error("Expected a valid message to be given to handler") + } +} + // Test that Exported handlers can obtain raw message. func TestExport_message(t *testing.T) { connection, err := ConnectSessionBus()
Add tests, catch case where developer does not handle error
godbus_dbus
train
ba1450f1d44d064fb3efd34b9b25ba6bcf15457b
diff --git a/gubernator/filters.py b/gubernator/filters.py index <HASH>..<HASH> 100644 --- a/gubernator/filters.py +++ b/gubernator/filters.py @@ -196,7 +196,7 @@ def do_tg_url(testgrid_query, test_name=''): def do_gcs_browse_url(gcs_path): - return 'https://console.cloud.google.com/storage/browser' + gcs_path + return 'http://gcsweb.k8s.io/gcs' + gcs_path static_hashes = {} diff --git a/gubernator/filters_test.py b/gubernator/filters_test.py index <HASH>..<HASH> 100644 --- a/gubernator/filters_test.py +++ b/gubernator/filters_test.py @@ -114,7 +114,7 @@ class HelperTest(unittest.TestCase): def test_gcs_browse_url(self): self.assertEqual( filters.do_gcs_browse_url('/k8s/foo'), - 'https://console.cloud.google.com/storage/browser/k8s/foo') + 'http://gcsweb.k8s.io/gcs/k8s/foo') if __name__ == '__main__': unittest.main() diff --git a/gubernator/view_build_test.py b/gubernator/view_build_test.py index <HASH>..<HASH> 100644 --- a/gubernator/view_build_test.py +++ b/gubernator/view_build_test.py @@ -255,7 +255,7 @@ class BuildTest(main_test.TestBase): """Test that the job page shows a list of builds.""" response = app.get('/builds' + os.path.dirname(self.BUILD_DIR[:-1])) self.assertIn('/1234/">1234', response) - self.assertIn('console.cloud', response) + self.assertIn('gcsweb', response) def test_job_list(self): """Test that the job list shows our job."""
Make Gubernator point at gcsweb for artifact browsing (no login required!).
kubernetes_test-infra
train
acebc2ab3849aef782e3d893999e9f0377f320ce
diff --git a/gulpfile.js b/gulpfile.js index <HASH>..<HASH> 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -12,16 +12,30 @@ var merge = require('merge-stream'); var compilation = tsb.create(assign({ verbose: true }, require('./src/tsconfig.json').compilerOptions)); var tsSources = 'src/**/*.ts'; +var outFolder = 'lib'; + function compileTask() { return merge( gulp.src(tsSources).pipe(compilation()) ) - .pipe(gulp.dest('lib')); + .pipe(gulp.dest(outFolder)); } -gulp.task('clean-out', function(cb) { rimraf('lib', { maxBusyTries: 1 }, cb); }); +gulp.task('clean-out', function(cb) { rimraf(outFolder, { maxBusyTries: 1 }, cb); }); gulp.task('compile', ['clean-out'], compileTask); gulp.task('compile-without-clean', compileTask); gulp.task('watch', ['compile'], function() { gulp.watch(tsSources, ['compile-without-clean']); +}); + + +var vscodeJSONLibFolder = '../vscode/extensions/json/server/node_modules/vscode-json-languageservice/lib'; + +gulp.task('clean-vscode-json', function(cb) { rimraf(vscodeJSONLibFolder, { maxBusyTries: 1 }, cb); }); +gulp.task('compile-vscode-json', ['clean-out', 'clean-vscode-json', 'compile-vscode-json-without-clean']); +gulp.task('compile-vscode-json-without-clean', function() { + return compileTask().pipe(gulp.dest(vscodeJSONLibFolder)); +}); +gulp.task('watch-vscode-json', ['compile-vscode-json'], function() { + gulp.watch(tsSources, ['compile-vscode-json-without-clean']); }); \ No newline at end of file
[gulpfile] compile to vscode-json
Microsoft_vscode-json-languageservice
train
c21dff94cace15b94655116cf2d3c93eed2b1a3c
diff --git a/src/Helper.php b/src/Helper.php index <HASH>..<HASH> 100644 --- a/src/Helper.php +++ b/src/Helper.php @@ -76,7 +76,7 @@ class Helper } $arrIp = explode(',', $the_ip); - return filter_var(trim(trim($arrIp[0]),'[]'), FILTER_VALIDATE_IP); + return filter_var(trim(trim($arrIp[0]), '[]'), FILTER_VALIDATE_IP); } /** @@ -99,7 +99,7 @@ class Helper private static function nearest($number, $numbers) { $output = false; - $number = (int) $number; + $number = (int)$number; if (is_array($numbers) && count($numbers) >= 1) { $NDat = array(); foreach ($numbers as $n) { @@ -144,6 +144,7 @@ class Helper return ($taxAmount / $amountExclTax) * 100; } + /** * Determine the tax class to send to Pay.nl * @@ -197,7 +198,7 @@ class Helper $strStreetName = implode('', $a); } - return array($strStreetName, $strStreetNumber); + return array($strStreetName, substr($strStreetNumber, 0, 45)); } /** @@ -209,7 +210,7 @@ class Helper public static function getBaseUrl() { $protocol = isset($_SERVER['HTTPS']) ? 'https' : 'http'; - $url = $protocol . '://' . $_SERVER['SERVER_NAME'] .':'.$_SERVER['SERVER_PORT']. $_SERVER['REQUEST_URI']; + $url = $protocol . '://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI']; // cut at last '/' (we dont want to see index.php) return substr($url, 0, strrpos($url, '/'));
Updated splitaddress helper to cut the housenumber at <I> characters
paynl_sdk
train
a2d55f72dab30ea754e349496f968f15b037ba9b
diff --git a/nion/swift/ProjectPanel.py b/nion/swift/ProjectPanel.py index <HASH>..<HASH> 100644 --- a/nion/swift/ProjectPanel.py +++ b/nion/swift/ProjectPanel.py @@ -26,7 +26,7 @@ def reveal_project(project_path: pathlib.Path) -> None: if sys.platform == "darwin": subprocess.Popen(["open", "-R", str(project_path)]) elif sys.platform == 'win32': - subprocess.check_call(['explorer', str(project_path.parent)]) + subprocess.run(['explorer', str(project_path.parent)]) elif sys.platform == 'linux': subprocess.check_call(['xdg-open', '--', str(project_path.parent)]) @@ -34,9 +34,9 @@ def open_location(location: pathlib.Path) -> None: if sys.platform == "darwin": subprocess.Popen(["open", str(location)]) elif sys.platform == 'win32': - subprocess.check_call(['explorer', str(location.parent)]) + subprocess.run(['explorer', str(location)]) elif sys.platform == 'linux': - subprocess.check_call(['xdg-open', '--', str(location.parent)]) + subprocess.check_call(['xdg-open', '--', str(location)])
Adjust commands to show project location on Windows.
nion-software_nionswift
train
3fb52687bcded44a8931baa65157b93451adbb2e
diff --git a/app/app.go b/app/app.go index <HASH>..<HASH> 100644 --- a/app/app.go +++ b/app/app.go @@ -25,7 +25,6 @@ import ( "io" "labix.org/v2/mgo/bson" "launchpad.net/~niemeyer/goyaml/beta" - "os" "path" "regexp" "sort" @@ -548,12 +547,7 @@ func (app *App) runHook(w io.Writer, cmds []string, kind string) error { return err } for _, cmd := range cmds { - p, err := deployHookAbsPath(cmd) - if err != nil { - app.Log(fmt.Sprintf("Error obtaining absolute path to hook: %s.", err), "tsuru") - continue - } - err = app.Run(p, w) + err = app.Run(cmd, w) if err != nil { return err } @@ -861,25 +855,3 @@ func List(u *auth.User) ([]App, error) { } return apps, nil } - -// deployHooksAbsPath returns the absolute path to execute the given command. -// It first try to use the given path as a relative path from the app root, -// then uses it as an absolute path. -// -// For example, deployHooksAbsPath("python") will return -// "/home/application/current/python" if this file exist, otherwise, will -// return just "python". -func deployHookAbsPath(p string) (string, error) { - repoPath, err := config.GetString("git:unit-repo") - if err != nil { - return "", nil - } - cmdArgs := strings.Fields(p) - abs := path.Join(repoPath, cmdArgs[0]) - _, err = os.Stat(abs) - if os.IsNotExist(err) { - return p, nil - } - cmdArgs[0] = abs - return strings.Join(cmdArgs, " "), nil -} diff --git a/app/app_test.go b/app/app_test.go index <HASH>..<HASH> 100644 --- a/app/app_test.go +++ b/app/app_test.go @@ -25,8 +25,6 @@ import ( stdlog "log" "net/http" "net/http/httptest" - "os" - "path" "reflect" "sort" "strconv" @@ -1330,28 +1328,6 @@ func (s *S) TestIsValid(c *gocheck.C) { } } -func (s *S) TestDeployHookAbsPath(c *gocheck.C) { - pwd, err := os.Getwd() - c.Assert(err, gocheck.IsNil) - old, err := config.Get("git:unit-repo") - c.Assert(err, gocheck.IsNil) - config.Set("git:unit-repo", pwd) - defer config.Set("git:unit-repo", old) - expected := path.Join(pwd, "testdata", "pre.sh") - command := "testdata/pre.sh" - got, err := deployHookAbsPath(command) - c.Assert(err, gocheck.IsNil) - c.Assert(got, gocheck.Equals, expected) -} - -func (s *S) TestDeployHookAbsPathAbsoluteCommands(c *gocheck.C) { - command := "python manage.py syncdb --noinput" - expected := "python manage.py syncdb --noinput" - got, err := deployHookAbsPath(command) - c.Assert(err, gocheck.IsNil) - c.Assert(got, gocheck.Equals, expected) -} - func (s *S) TestLoadConf(c *gocheck.C) { output := `hooks: pre-restart:
app: delete deployHooksAbsPath It never worked, and it's too hard to get it right. I'm going to update our docs.
tsuru_tsuru
train
767e2802e2815c424c9df81c7159a8b727d3edba
diff --git a/gapy/__init__.py b/gapy/__init__.py index <HASH>..<HASH> 100644 --- a/gapy/__init__.py +++ b/gapy/__init__.py @@ -1,3 +1,3 @@ __title__ = "gapy" -__version__ = "0.0.6" +__version__ = "0.0.7" __author__ = "Rob Young"
Bumpy version to <I>
alphagov_gapy
train
9b34f28aa0ff267c4436c46974cfc47e641e61ad
diff --git a/lib/savon/options.rb b/lib/savon/options.rb index <HASH>..<HASH> 100644 --- a/lib/savon/options.rb +++ b/lib/savon/options.rb @@ -268,6 +268,15 @@ module Savon @options[:ssl_ca_cert] = cert end + # Sets the ca cert path. + def ssl_ca_cert_path(path) + @options[:ssl_ca_cert_path] = path + end + + # Sets the ssl cert store. + def ssl_cert_store(store) + @options[:ssl_cert_store] = store + end # HTTP basic auth credentials. def basic_auth(*credentials) diff --git a/lib/savon/request.rb b/lib/savon/request.rb index <HASH>..<HASH> 100644 --- a/lib/savon/request.rb +++ b/lib/savon/request.rb @@ -28,11 +28,13 @@ module Savon @http_request.auth.ssl.verify_mode = @globals[:ssl_verify_mode] if @globals.include? :ssl_verify_mode @http_request.auth.ssl.cert_key_file = @globals[:ssl_cert_key_file] if @globals.include? :ssl_cert_key_file - @http_request.auth.ssl.cert_key = @globals[:ssl_cert_key] if @globals.include? :ssl_cert_key + @http_request.auth.ssl.cert_key = @globals[:ssl_cert_key] if @globals.include? :ssl_cert_key @http_request.auth.ssl.cert_file = @globals[:ssl_cert_file] if @globals.include? :ssl_cert_file - @http_request.auth.ssl.cert = @globals[:ssl_cert] if @globals.include? :ssl_cert + @http_request.auth.ssl.cert = @globals[:ssl_cert] if @globals.include? :ssl_cert @http_request.auth.ssl.ca_cert_file = @globals[:ssl_ca_cert_file] if @globals.include? :ssl_ca_cert_file - @http_request.auth.ssl.ca_cert = @globals[:ssl_ca_cert] if @globals.include? :ssl_ca_cert + @http_request.auth.ssl.ca_cert_path = @globals[:ssl_ca_cert_path] if @globals.include? :ssl_ca_cert_path + @http_request.auth.ssl.ca_cert = @globals[:ssl_ca_cert] if @globals.include? :ssl_ca_cert + @http_request.auth.ssl.cert_store = @globals[:ssl_cert_store] if @globals.include? :ssl_cert_store @http_request.auth.ssl.cert_key_password = @globals[:ssl_cert_key_password] if @globals.include? :ssl_cert_key_password end diff --git a/spec/savon/options_spec.rb b/spec/savon/options_spec.rb index <HASH>..<HASH> 100644 --- a/spec/savon/options_spec.rb +++ b/spec/savon/options_spec.rb @@ -469,6 +469,26 @@ describe "Options" do end end + context "global :ssl_ca_cert_path" do + it "sets the ca cert path to use" do + ca_cert_path = "../../fixtures/ssl" + HTTPI::Auth::SSL.any_instance.expects(:ca_cert_path=).with(ca_cert_path).twice + + client = new_client(:endpoint => @server.url, :ssl_ca_cert_path => ca_cert_path) + client.call(:authenticate) + end + end + + context "global :ssl_ca_cert_store" do + it "sets the cert store to use" do + cert_store = OpenSSL::X509::Store.new + HTTPI::Auth::SSL.any_instance.expects(:cert_store=).with(cert_store).twice + + client = new_client(:endpoint => @server.url, :ssl_cert_store => cert_store) + client.call(:authenticate) + end + end + context "global :ssl_ca_cert" do it "sets the ca cert file to use" do ca_cert = File.open(File.expand_path("../../fixtures/ssl/client_cert.pem", __FILE__)).read
Added ssl_ca_path and ssl_cert_store to globals (#<I>)
savonrb_savon
train
9e4c59ba415172462da104df8531976fa951cf52
diff --git a/pandas/core/array_algos/putmask.py b/pandas/core/array_algos/putmask.py index <HASH>..<HASH> 100644 --- a/pandas/core/array_algos/putmask.py +++ b/pandas/core/array_algos/putmask.py @@ -126,6 +126,8 @@ def putmask_without_repeat( mask : np.ndarray[bool] new : Any """ + new = setitem_datetimelike_compat(values, mask.sum(), new) + if getattr(new, "ndim", 0) >= 1: new = new.astype(values.dtype, copy=False) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index <HASH>..<HASH> 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -30,7 +30,6 @@ from pandas._typing import ( Shape, npt, ) -from pandas.compat import np_version_under1p20 from pandas.util._decorators import cache_readonly from pandas.util._exceptions import find_stack_level from pandas.util._validators import validate_bool_kwarg @@ -39,7 +38,6 @@ from pandas.core.dtypes.astype import astype_array_safe from pandas.core.dtypes.cast import ( can_hold_element, find_result_type, - infer_dtype_from, maybe_downcast_numeric, maybe_downcast_to_dtype, soft_convert_objects, @@ -977,12 +975,6 @@ class Block(PandasObject): putmask_without_repeat(values.T, mask, new) return [self] - elif np_version_under1p20 and infer_dtype_from(new)[0].kind in ["m", "M"]: - # using putmask with object dtype will incorrectly cast to object - # Having excluded self._can_hold_element, we know we cannot operate - # in-place, so we are safe using `where` - return self.where(new, ~mask) - elif noop: return [self]
REF: remove Block.putmask fallback to where (#<I>)
pandas-dev_pandas
train
a128621340a8b8c6e89b4a054365f671c00fe9e8
diff --git a/packages/create/src/generators/app-lit-element/templates/static-scaffold-testing/components/page-main/test/page-main.test.js b/packages/create/src/generators/app-lit-element/templates/static-scaffold-testing/components/page-main/test/page-main.test.js index <HASH>..<HASH> 100644 --- a/packages/create/src/generators/app-lit-element/templates/static-scaffold-testing/components/page-main/test/page-main.test.js +++ b/packages/create/src/generators/app-lit-element/templates/static-scaffold-testing/components/page-main/test/page-main.test.js @@ -18,4 +18,20 @@ describe('PageMain', () => { expect(el.title).to.equal('attribute title'); }); + + it('matches the snapshot', async () => { + const el = await fixture(html` + <<%= tagName %>></<%= tagName %>> + `); + + expect(el).shadowDom.to.equalSnapshot(); + }); + + it('passes the a11y audit', async () => { + const el = await fixture(html` + <<%= tagName %>></<%= tagName %>> + `); + + await expect(el).shadowDom.to.be.accessible(); + }); }); diff --git a/packages/create/src/generators/testing/templates/_my-el.test.js b/packages/create/src/generators/testing/templates/_my-el.test.js index <HASH>..<HASH> 100644 --- a/packages/create/src/generators/testing/templates/_my-el.test.js +++ b/packages/create/src/generators/testing/templates/_my-el.test.js @@ -12,31 +12,36 @@ describe('<%= className %>', () => { expect(el.counter).to.equal(5); }); - it('shows initially the text "hey there Nr. 5!" and an "increment" button', async () => { + it('increases the counter on button click', async () => { const el = await fixture(html` <<%= tagName %>></<%= tagName %>> `); + el.shadowRoot.querySelector('button').click(); + + expect(el.counter).to.equal(6); + }); - expect(el).shadowDom.to.equal(` - <h2>Hey there Nr. 5!</h2> - <button>increment</button> + it('can override the title via attribute', async () => { + const el = await fixture(html` + <<%= tagName %> title="attribute title"></<%= tagName %>> `); + + expect(el.title).to.equal('attribute title'); }); - it('increases the counter on button click', async () => { + it('shows initially the text "hey there Nr. 5!" and an "increment" button', async () => { const el = await fixture(html` <<%= tagName %>></<%= tagName %>> `); - el.shadowRoot.querySelector('button').click(); - expect(el.counter).to.equal(6); + expect(el).shadowDom.to.equalSnapshot(); }); - it('can override the title via attribute', async () => { + it('passes the a11y audit', async () => { const el = await fixture(html` - <<%= tagName %> title="attribute title"></<%= tagName %>> + <<%= tagName %>></<%= tagName %>> `); - expect(el.title).to.equal('attribute title'); + await expect(el).shadowDom.to.be.accessible(); }); });
feat(create): add a<I>y and snapshot tests
open-wc_open-wc
train
4ccf9cf06f3ff7ca5c49c078b527a192affca759
diff --git a/src/Psalm/Checker/StatementsChecker.php b/src/Psalm/Checker/StatementsChecker.php index <HASH>..<HASH> 100644 --- a/src/Psalm/Checker/StatementsChecker.php +++ b/src/Psalm/Checker/StatementsChecker.php @@ -1747,16 +1747,26 @@ class StatementsChecker } if ($return_type instanceof Type\Generic) { - $value_type = $return_type->type_params[0]; + $value_type_part = $return_type->type_params[0]; + + if (!$value_type) { + $value_type = $value_type_part; + } + else { + $value_type = Type::combineUnionTypes($value_type, $value_type_part); + } + continue; } switch ($return_type->value) { case 'mixed': case 'empty': + $value_type = Type::getMixed(); break; case 'array': case 'object': + $value_type = Type::getMixed(); break; case 'null': @@ -1766,6 +1776,8 @@ class StatementsChecker )) { return false; } + + $value_type = Type::getMixed(); break; case 'string': @@ -1779,6 +1791,7 @@ class StatementsChecker )) { return false; } + $value_type = Type::getMixed(); break; default: @@ -1787,7 +1800,17 @@ class StatementsChecker $iterator_class_type = MethodChecker::getMethodReturnTypes($iterator_method); if ($iterator_class_type) { - $value_type = self::fleshOutTypes($iterator_class_type, [], $return_type->value, $iterator_method); + $value_type_part = self::fleshOutTypes($iterator_class_type, [], $return_type->value, $iterator_method); + + if (!$value_type) { + $value_type = $value_type_part; + } + else { + $value_type = Type::combineUnionTypes($value_type, $value_type_part); + } + } + else { + $value_type = Type::getMixed(); } } @@ -2277,6 +2300,8 @@ class StatementsChecker } if ($class_type && is_string($stmt->name)) { + $return_type = null; + foreach ($class_type->types as $type) { $absolute_class = $type->value; @@ -2377,16 +2402,26 @@ class StatementsChecker return false; } - $return_types = MethodChecker::getMethodReturnTypes($method_id); + $return_type_candidate = MethodChecker::getMethodReturnTypes($method_id); - if ($return_types) { - $return_types = self::fleshOutTypes($return_types, $stmt->args, $absolute_class, $method_id); + if ($return_type_candidate) { + $return_type_candidate = self::fleshOutTypes($return_type_candidate, $stmt->args, $absolute_class, $method_id); - $stmt->inferredType = $return_types; + if (!$return_type) { + $return_type = $return_type_candidate; + } + else { + $return_type = Type::combineUnionTypes($return_type_candidate, $return_type); + } + } + else { + $return_type = Type::getMixed(); } } } } + + $stmt->inferredType = $return_type; } if ($this->checkFunctionArguments($stmt->args, $method_id, $context, $stmt->getLine()) === false) {
Do not just return last successful type found
vimeo_psalm
train
abcb06c5cae417551960b85d9b0257b2c0590260
diff --git a/code/pagetypes/EventHolder.php b/code/pagetypes/EventHolder.php index <HASH>..<HASH> 100644 --- a/code/pagetypes/EventHolder.php +++ b/code/pagetypes/EventHolder.php @@ -407,7 +407,7 @@ class EventHolder_Controller extends Page_Controller { $dateTo->setConfig('showcalendar', true); $actions = new FieldList( - FormAction::create("doDateFilter")->setTitle("Filter")->addExtraClass('btn primary'), + FormAction::create("doDateFilter")->setTitle("Filter")->addExtraClass('btn btn-primary primary'), FormAction::create("doDateReset")->setTitle("Clear")->addExtraClass('btn') );
Add .btn-primary back in, to better support other themes
silverstripe_cwp
train
2363043b1f6849ff279b1d83043b0efa34c20336
diff --git a/fuel/datasets/binarized_mnist.py b/fuel/datasets/binarized_mnist.py index <HASH>..<HASH> 100644 --- a/fuel/datasets/binarized_mnist.py +++ b/fuel/datasets/binarized_mnist.py @@ -49,6 +49,7 @@ class BinarizedMNIST(InMemoryDataset): """ provides_sources = ('features',) + base_path = os.path.join(config.data_path, 'binarized_mnist') def __init__(self, which_set, **kwargs): if which_set not in ('train', 'valid', 'test'): @@ -59,11 +60,11 @@ class BinarizedMNIST(InMemoryDataset): super(BinarizedMNIST, self).__init__(**kwargs) self.which_set = which_set + self.data_path = os.path.join( + self.base_path, 'binarized_mnist_' + self.which_set + '.npy') def load(self): - data = 'binarized_mnist_' + self.which_set + '.npy' - data_path = os.path.join(config.data_path, 'binarized_mnist', data) - x = numpy.load(data_path).astype('float64') + x = numpy.load(self.data_path).astype('float64') self.features = x def get_data(self, state=None, request=None):
Factor out data path in BinarizedMNIST
mila-iqia_fuel
train
66f4b99beeb40fe1bc60b75184ae0f0cd8348f3d
diff --git a/src/components/_gapminder/indicatorpicker/indicatorpicker.js b/src/components/_gapminder/indicatorpicker/indicatorpicker.js index <HASH>..<HASH> 100644 --- a/src/components/_gapminder/indicatorpicker/indicatorpicker.js +++ b/src/components/_gapminder/indicatorpicker/indicatorpicker.js @@ -153,6 +153,7 @@ _setModel: function(what, value) { var mdl = this.model.axis; + mdl.atomic(); mdl[what] = value; if (what == INDICATOR) { @@ -163,6 +164,7 @@ mdl.scaleType = availOpts[value].scales[0]; } } + mdl.atomic(false); } }); diff --git a/src/models/axis.js b/src/models/axis.js index <HASH>..<HASH> 100644 --- a/src/models/axis.js +++ b/src/models/axis.js @@ -66,20 +66,6 @@ //TODO: add min and max to validation }, - /** - * Gets tick values for this hook - * @returns {Number|String} value The value for this tick - */ - tickFormatter: function(x) { - var result = x; - if(utils.isDate(x)) { - //TODO: generalize for any time unit - result = time_formats["year"](x); - }else if (this.use == "indicator") { - result = parseFloat(x); - } - return result; - }, /** * Gets the domain for this hook
Attempt to fix indicator picker problem (atomic)
vizabi_vizabi
train
56784bdebf60dc680c5ed8f312b26e3928ff7701
diff --git a/nhe/mfd/evenly_discretized.py b/nhe/mfd/evenly_discretized.py index <HASH>..<HASH> 100644 --- a/nhe/mfd/evenly_discretized.py +++ b/nhe/mfd/evenly_discretized.py @@ -15,7 +15,7 @@ class EvenlyDiscretized(BaseMFD): See :class:`nhe.mfd.base.BaseMFD`. :param occurrence_rates: The list of non-negative float values representing the actual - occurrence rates. The resulting histogram has as many bins + annual occurrence rates. The resulting histogram has as many bins as this list length. """ def __init__(self, min_mag, bin_width, occurrence_rates): @@ -46,7 +46,7 @@ class EvenlyDiscretized(BaseMFD): def get_annual_occurrence_rates(self): """ - Returns the predefined occurrence rates. + Returns the predefined annual occurrence rates. """ return [ (self.min_mag + i * self.bin_width, occurence_rate) diff --git a/nhe/mfd/truncated_gr.py b/nhe/mfd/truncated_gr.py index <HASH>..<HASH> 100644 --- a/nhe/mfd/truncated_gr.py +++ b/nhe/mfd/truncated_gr.py @@ -6,17 +6,21 @@ from nhe.mfd.base import BaseMFD, MFDError class TruncatedGR(BaseMFD): """ - Gutenberg-Richter MFD is defined in a functional form. + Truncated Gutenberg-Richter MFD is defined in a functional form. - The occurrence rate for a specific bin (magnitude band) is defined as :: + The annual occurrence rate for a specific bin (magnitude band) + is defined as :: rate = 10 ** (a_val - b_val * mag_lo) - 10 ** (a_val - b_val * mag_hi) where - * ``a_val`` is the cumulative ``a`` value (``10 ** a_value`` is the number - of earthquakes per year with magnitude greater or equal to 0), - * ``b_val`` is Gutenberg-Richter ``b`` value, + * ``a_val`` is the cumulative ``a`` value (``10 ** a`` is the number + of earthquakes per year with magnitude greater than or equal to 0), + * ``b_val`` is Gutenberg-Richter ``b`` value -- the decay rate + of exponential distribution. It describes the relative size distribution + of earthquakes: a higher ``b`` value indicates a relatively larger + proportion of small events and vice versa. * ``mag_lo`` and ``mag_hi`` are lower and upper magnitudes of a specific bin respectively. @@ -75,7 +79,7 @@ class TruncatedGR(BaseMFD): def get_annual_occurrence_rates(self): """ - Calculate and return the occurrence rates histogram. + Calculate and return the annual occurrence rates histogram. The result histogram has only one bin if minimum and maximum magnitude values appear equal after rounding.
mfd: docs improvement per review comments
gem_oq-engine
train
8fed5cb0687b3d9f4c62597bea5dec4e1567f6be
diff --git a/host/scan_ext_trigger_stop_mode.py b/host/scan_ext_trigger_stop_mode.py index <HASH>..<HASH> 100644 --- a/host/scan_ext_trigger_stop_mode.py +++ b/host/scan_ext_trigger_stop_mode.py @@ -28,7 +28,7 @@ logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)-8s] (% scan_configuration = { "source": "TPC", - "bcid_window": 100, # the time window hits are read from the pixel matrix, [0:256[ theoretically, [0:120] supported + "bcid_window": 100, # the time window hits are read from the pixel matrix, [0:256[ "trigger_mode": 0, "trigger_latency": 5, "trigger_delay": 192, @@ -43,7 +43,7 @@ scan_configuration = { class ExtTriggerScan(ScanBase): - scan_identifier = "ext_trigger_scan_stop_mode" + scan_id = "ext_trigger_scan_stop_mode" def scan(self, trigger_mode=0, trigger_latency=232, trigger_delay=13, bcid_window=20, col_span=[1, 80], row_span=[1, 336], timeout_no_data=10, scan_timeout=10 * 60, max_triggers=10000, enable_hitbus=False, enable_tdc=False, enable_all_pixel=False, **kwargs): '''Scan loop @@ -86,7 +86,7 @@ class ExtTriggerScan(ScanBase): wait_for_first_trigger = True - with open_raw_data_file(filename=self.scan_data_filename, title=self.scan_identifier, mode='w') as raw_data_file: + with open_raw_data_file(filename=self.scan_data_filename, title=self.scan_id, mode='w') as raw_data_file: self.readout.start() # Stop mode related hacks to read all hits stored with stop mode @@ -251,7 +251,7 @@ class ExtTriggerScan(ScanBase): analyze_raw_data.create_cluster_size_hist = True analyze_raw_data.interpreter.set_warning_output(False) analyze_raw_data.clusterizer.set_warning_output(False) - analyze_raw_data.interpreter.debug_events(0, 10, True) # events to be printed onto the console for debugging, usually deactivated +# analyze_raw_data.interpreter.debug_events(0, 10, True) # events to be printed onto the console for debugging, usually deactivated analyze_raw_data.interpret_word_table(fei4b=scan.register.fei4b) analyze_raw_data.interpreter.print_summary() analyze_raw_data.plot_histograms(scan_data_filename=scan.scan_data_filename) @@ -259,7 +259,7 @@ class ExtTriggerScan(ScanBase): if __name__ == "__main__": import configuration - scan = ExtTriggerScan(**configuration.scc99_configuration) + scan = ExtTriggerScan(**configuration.default_configuration) scan.start(use_thread=True, **scan_configuration) scan.stop() scan.analyze()
MAINT: renaming of variables, deactivating debug output
SiLab-Bonn_pyBAR
train
a2d7231554da608bf7033331ef7e96d136163669
diff --git a/src/flowcode/ceibo/EntityManager.php b/src/flowcode/ceibo/EntityManager.php index <HASH>..<HASH> 100755 --- a/src/flowcode/ceibo/EntityManager.php +++ b/src/flowcode/ceibo/EntityManager.php @@ -125,18 +125,23 @@ class EntityManager { foreach ($mapper->getRelations() as $relation) { if ($relation->getCardinality() == Relation::$manyToMany) { // delete previous relations - $queryDeletePrevious = QueryBuilder::buildDeleteRelationQuery($relation, $entity); - foreach (explode(";", $queryDeletePrevious) as $q) { - if (strlen($q) > 5) - $this->getDataSource()->executeNonQuery($q); - } + $queryDeletePrevious = QueryBuilder::buildDeleteRelationQuery($relation); + $this->getDataSource()->deleteSingleRow($queryDeletePrevious, array(":id" => $entity->getId())); // insert new relations - $queryRel = QueryBuilder::buildRelationQuery($entity, $relation); - foreach (explode(";", $queryRel) as $q) { - if (strlen($q) > 5) - $this->getDataSource()->executeInsert($q); + $insertRelStmt = QueryBuilder::buildRelationQuery($entity, $relation); + $values = array(); + $m = "get" . $relation->getName(); + $getid = "getId"; + foreach ($entity->$m() as $rel) { + $valueRow = array(); + $valueRow[":" . $relation->getLocalColumn()] = $entity->$getid(); + $valueRow[":" . $relation->getForeignColumn()] = $rel->$getid(); + $values[] = $valueRow; } + + $this->getDataSource()->insertMultipleRow($insertRelStmt, $values); + } if ($relation->getCardinality() == Relation::$oneToMany) { $relMapper = MapperBuilder::buildFromName($this->mapping, $relation->getEntity()); diff --git a/src/flowcode/ceibo/builder/QueryBuilder.php b/src/flowcode/ceibo/builder/QueryBuilder.php index <HASH>..<HASH> 100755 --- a/src/flowcode/ceibo/builder/QueryBuilder.php +++ b/src/flowcode/ceibo/builder/QueryBuilder.php @@ -37,9 +37,9 @@ class QueryBuilder { * @param type $entity * @return string */ - public static function buildDeleteRelationQuery(Relation $relation, $entity) { + public static function buildDeleteRelationQuery(Relation $relation) { $query = "DELETE FROM `" . $relation->getTable() . "` "; - $query .= "WHERE " . $relation->getLocalColumn() . " = '" . $entity->getId() . "';"; + $query .= "WHERE " . $relation->getLocalColumn() . " = ':id';"; return $query; } diff --git a/src/flowcode/ceibo/data/PDOMySqlDataSource.php b/src/flowcode/ceibo/data/PDOMySqlDataSource.php index <HASH>..<HASH> 100644 --- a/src/flowcode/ceibo/data/PDOMySqlDataSource.php +++ b/src/flowcode/ceibo/data/PDOMySqlDataSource.php @@ -3,9 +3,7 @@ namespace flowcode\ceibo\data; use Exception; -use flowcode\ceibo\builder\MapperBuilder; use flowcode\ceibo\builder\QueryBuilder; -use flowcode\ceibo\domain\Relation; use PDO; use PDOException; @@ -79,7 +77,6 @@ class PDOMySqlDataSource implements DataSource { } function doInsert($entity, $mapper) { - $affectedRows = 0; $statement = QueryBuilder::buildInsertQuery($entity, $mapper); $stmt = $this->getConnection()->prepare($statement); foreach ($mapper->getPropertys() as $property) {
Implement query builder for PDO statements
flowcode_ceibo
train
03ab2ea391f41ee82a9b005cef48b6bdf5abe9bf
diff --git a/src/main/java/org/unbescape/javascript/JavaScriptEscapeUtil.java b/src/main/java/org/unbescape/javascript/JavaScriptEscapeUtil.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/unbescape/javascript/JavaScriptEscapeUtil.java +++ b/src/main/java/org/unbescape/javascript/JavaScriptEscapeUtil.java @@ -391,8 +391,6 @@ final class JavaScriptEscapeUtil { final boolean useSECs = escapeType.getUseSECs(); final boolean useXHexa = escapeType.getUseXHexa(); - StringBuilder strBuilder = null; - int c0, c1, c2; // c0: last char, c1: current char, c2: next char c1 = -1; diff --git a/src/main/java/org/unbescape/xml/XmlEscapeUtil.java b/src/main/java/org/unbescape/xml/XmlEscapeUtil.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/unbescape/xml/XmlEscapeUtil.java +++ b/src/main/java/org/unbescape/xml/XmlEscapeUtil.java @@ -268,14 +268,12 @@ final class XmlEscapeUtil { final boolean useCERs = escapeType.getUseCERs(); final boolean useHexa = escapeType.getUseHexa(); - int c0, c1, c2; // c0: last char, c1: current char, c2: next char + int c1, c2; // c0: last char, c1: current char, c2: next char - c1 = -1; c2 = reader.read(); while (c2 >= 0) { - c0 = c1; c1 = c2; c2 = reader.read(); @@ -311,7 +309,6 @@ final class XmlEscapeUtil { writer.write(c2); - c0 = c1; c1 = c2; c2 = reader.read(); @@ -329,7 +326,6 @@ final class XmlEscapeUtil { if (Character.charCount(codepoint) > 1) { // This is to compensate that we are actually reading two char positions with a single codepoint. - c0 = c1; c1 = c2; c2 = reader.read(); }
Minor fixes on Reader-based escape operations
unbescape_unbescape
train
92ea2ea8d87051465d79589afd33b3f0c437ee89
diff --git a/spec/poller/http/http_poller_spec.rb b/spec/poller/http/http_poller_spec.rb index <HASH>..<HASH> 100644 --- a/spec/poller/http/http_poller_spec.rb +++ b/spec/poller/http/http_poller_spec.rb @@ -45,7 +45,7 @@ module Poller require 'matchers/http/response_body_contains' it 'succeeds in fetching and matching an http response from example.com', :type => 'integration' do matcher = Matchers::HTTP::ResponseBodyContains.new('<title>Example Domain</title>') - poller = HttpPoller.new("http://example.com", matcher, 5.0, 1.0) + poller = HttpPoller.new('http://example.com', matcher, 5.0, 1.0) result = poller.check result.should be_an_instance_of Array result[0].should be_an_instance_of Net::HTTPOK @@ -57,7 +57,7 @@ module Poller require 'matchers/xml/xpath_contains_text' it 'succeeds in fetching an XML document and in finding a text for given XPath', :type => 'integration' do matcher = Matchers::XML::XPathContainsText.new('/CATALOG/CD/TITLE', 'Empire Burlesque') - poller = HttpPoller.new("https://www.w3schools.com/xml/cd_catalog.xml", matcher, 5.0, 1.0) + poller = HttpPoller.new('https://www.w3schools.com/xml/cd_catalog.xml', matcher, 5.0, 1.0) result = poller.check result.should be_an_instance_of Array result[0].should be_an_instance_of Net::HTTPOK @@ -67,7 +67,7 @@ module Poller # make sure non-existing nodes do not trigger any problems it 'eventually runs into timeout when looking for non-existing text node', :type => 'integration' do matcher = Matchers::XML::XPathContainsText.new('/CATALOG/SCHELLACK/TITLE', 'Empire Burlesque') - poller = HttpPoller.new("https://www.w3schools.com/xml/cd_catalog.xml", matcher, 5.0, 1.0) + poller = HttpPoller.new('https://www.w3schools.com/xml/cd_catalog.xml', matcher, 5.0, 1.0) expect { poller.check }.to raise_error(RuntimeError, /^Timeout period has been exceeded for Poller \(https:\/\/www.w3schools.com\/xml\/cd_catalog.xml\)\. Poller tried \d times which in total took \d\.?\d* seconds\.$/) @@ -78,7 +78,7 @@ module Poller require 'matchers/xml/document_contains_xpath' it 'succeeds in fetching an XML document and in finding a given XPath at least given number of times', :type => 'integration' do matcher = Matchers::XML::DocumentContainsXPath.new('/CATALOG/CD/ARTIST', 11) - poller = HttpPoller.new("https://www.w3schools.com/xml/cd_catalog.xml", matcher, 5.0, 1.0) + poller = HttpPoller.new('https://www.w3schools.com/xml/cd_catalog.xml', matcher, 5.0, 1.0) result = poller.check result.should be_an_instance_of Array result[0].should be_an_instance_of Net::HTTPOK @@ -88,7 +88,7 @@ module Poller # have a failing test to validate error message it 'fails to find a given XPath in document', :type => 'integration' do matcher = Matchers::XML::DocumentContainsXPath.new('/CATALOG/NOT_THERE/LIGHT', 11) - poller = HttpPoller.new("https://www.w3schools.com/xml/plant_catalog.xml", matcher, 5.0, 1.0) + poller = HttpPoller.new('https://www.w3schools.com/xml/plant_catalog.xml', matcher, 5.0, 1.0) expect { poller.check }.to raise_error(RuntimeError, /^Timeout period has been exceeded for Poller \(https:\/\/www.w3schools.com\/xml\/plant_catalog.xml\)\. Poller tried \d times which in total took \d\.?\d* seconds\.$/) @@ -98,4 +98,3 @@ module Poller end end end -
Fix rubocop findings regarding use of quotes
mkrogemann_poller
train
e776ec1bc29c6e1fd72aeb59e6fd0a16f02a0e4c
diff --git a/deisctl/cmd/cmd.go b/deisctl/cmd/cmd.go index <HASH>..<HASH> 100644 --- a/deisctl/cmd/cmd.go +++ b/deisctl/cmd/cmd.go @@ -580,6 +580,8 @@ Options: "deis-store-metadata.service", "deis-store-monitor.service", "deis-store-volume.service", + "deis-swarm-manager.service", + "deis-swarm-node.service", } for _, unit := range units { src := rootURL + tag + "/deisctl/units/" + unit
fix(deisctl): include swarm in refresh-units command
deis_deis
train
0859bdd306c5890d4e495b477e229e24f4cef417
diff --git a/test/MarketContractOraclize.js b/test/MarketContractOraclize.js index <HASH>..<HASH> 100644 --- a/test/MarketContractOraclize.js +++ b/test/MarketContractOraclize.js @@ -5,6 +5,11 @@ const CollateralToken = artifacts.require("CollateralToken"); const OrderLib = artifacts.require("OrderLib"); const utility = require('./utility.js'); +const ErrorCodes = { + ORDER_EXPIRED: 0, + ORDER_DEAD: 1, +} + // basic tests for interacting with market contract. contract('MarketContractOraclize', function(accounts) { @@ -178,16 +183,6 @@ contract('MarketContractOraclize', function(accounts) { ); }); - // TODO: - // - attempt to fill expired order - // - attempt to trade zero qty - // - order with zero qty - // - order with values manipulated - // - fees get transferred to recipient correctly. - // - attempt to trade / cancel post expiration - // - expiration methods - // - settleAndClose() - it("should only allow remaining quantity to be filled for an overfilled trade.", async function() { const timeStamp = ((new Date()).getTime() / 1000) + 60*5; // order expires 5 minute from now. const orderAddresses = [accountMaker, accountTaker, accounts[2]]; @@ -203,7 +198,7 @@ contract('MarketContractOraclize', function(accounts) { const expectedQtyFilled = 5; - // Execute trade between maker and taker for partial amount of order. + // Execute trade between maker and taker for overfilled amount of order. const orderSignature = utility.signMessage(web3, accountMaker, orderHash) const actualQtyFilled = await marketContract.tradeOrder.call( orderAddresses, @@ -256,4 +251,47 @@ contract('MarketContractOraclize', function(accounts) { assert.equal(expectedQtyCancelled, actualQtyCancelled.toNumber(), "Quantity cancelled doesn't match expected."); }) + + it("should fail for attempts to fill expired order", async function() { + const expiredTimestamp = ((new Date()).getTime() / 1000) - 30; // order expired 30 seconds ago. + const orderAddresses = [accountMaker, accountTaker, accounts[2]]; + const unsignedOrderValues = [0, 0, entryOrderPrice, expiredTimestamp, 1]; + const orderQty = 5; // user is attempting to buy 5 + const qtyToFill = 1; // order is to be filled by 1 + const orderHash = await orderLib.createOrderHash.call( + MarketContractOraclize.address, + orderAddresses, + unsignedOrderValues, + orderQty + ); + + // Execute trade between maker and taker for partial amount of order. + const orderSignature = utility.signMessage(web3, accountMaker, orderHash) + await marketContract.tradeOrder( + orderAddresses, + unsignedOrderValues, + orderQty, // 5 + qtyToFill, // fill one slot + orderSignature[0], // v + orderSignature[1], // r + orderSignature[2], // s + {from: accountTaker} + ); + const events = await utility.getEvent(marketContract, 'Error') + assert.equal(ErrorCodes.ORDER_EXPIRED, events[0].args.errorCode.toNumber(), "Error event is not order expired.") + + const orderQtyFilled = await marketContract.getQtyFilledOrCancelledFromOrder.call(orderHash) + assert.equal(0, orderQtyFilled.toNumber(), "Quantity filled is not zero.") + }) + + + + // TODO: + // - attempt to trade zero qty + // - order with zero qty + // - order with values manipulated + // - fees get transferred to recipient correctly. + // - attempt to trade / cancel post expiration + // - expiration methods + // - settleAndClose() }); \ No newline at end of file diff --git a/test/utility.js b/test/utility.js index <HASH>..<HASH> 100644 --- a/test/utility.js +++ b/test/utility.js @@ -6,5 +6,24 @@ module.exports = { var v = web3.toDecimal(`0x${signature.slice(130, 132)}`); if (v !== 27 && v !== 28) v += 27; return [v,r,s]; + }, + + /** + * Returns a promise that resolves to the next set of events of eventName publish by the contract + * + * @param contract + * @param eventName + * @return {Promise} + */ + getEvent(contract, eventName) { + return new Promise((resolve, reject) => { + const event = contract[eventName](); + event.get((error, logs) => { + if (error) { + return reject(error) + } + return resolve(logs) + }); + }); } } \ No newline at end of file
Add test for expired order in MarketContractOraclize
MARKETProtocol_MARKETProtocol
train
4291340b4bb51f28df9711e31c10dbcb14bb64f4
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/computer/traversal/TraversalVertexProgram.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/computer/traversal/TraversalVertexProgram.java index <HASH>..<HASH> 100644 --- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/computer/traversal/TraversalVertexProgram.java +++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/computer/traversal/TraversalVertexProgram.java @@ -122,7 +122,7 @@ public final class TraversalVertexProgram implements VertexProgram<TraverserSet< this.mapReducers.add(mapReducer.getMapReduce()); } if (!(this.traversal.getEndStep().getPreviousStep() instanceof SideEffectCapStep) && !(this.traversal.getEndStep().getPreviousStep() instanceof ReducingBarrierStep)) - this.mapReducers.add(new TraverserMapReduce(this.traversal.getEndStep().getPreviousStep())); + this.mapReducers.add(new TraverserMapReduce(this.traversal)); } @Override diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/computer/traversal/step/sideEffect/mapreduce/TraverserMapReduce.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/computer/traversal/step/sideEffect/mapreduce/TraverserMapReduce.java index <HASH>..<HASH> 100644 --- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/computer/traversal/step/sideEffect/mapreduce/TraverserMapReduce.java +++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/computer/traversal/step/sideEffect/mapreduce/TraverserMapReduce.java @@ -55,18 +55,19 @@ public final class TraverserMapReduce extends StaticMapReduce<Comparable, Traver private TraverserMapReduce() { } - public TraverserMapReduce(final Step traversalEndStep) { - this.traversal = traversalEndStep.getTraversal(); - this.genericLoadState(traversalEndStep); + public TraverserMapReduce(final Traversal.Admin<?, ?> traversal) { + this.traversal = traversal; + this.genericLoadState(); } @Override public void loadState(final Graph graph, final Configuration configuration) { this.traversal = TraversalVertexProgram.getTraversal(graph, configuration); - this.genericLoadState(this.traversal.getEndStep().getPreviousStep()); // don't get the ComputerResultStep + this.genericLoadState(); } - private void genericLoadState(final Step<?, ?> traversalEndStep) { + private void genericLoadState() { + final Step<?, ?> traversalEndStep = traversal.getEndStep().getPreviousStep(); // don't get the ComputerResultStep this.comparator = Optional.ofNullable(traversalEndStep instanceof OrderGlobalStep ? new ChainedComparator<Comparable>(((OrderGlobalStep) traversalEndStep).getComparators()) : null); if (!this.comparator.isPresent() && traversalEndStep instanceof CollectingBarrierStep) this.collectingBarrierStep = Optional.of((CollectingBarrierStep<?>) traversalEndStep);
simplified constructor for TraverserMapReduce.
apache_tinkerpop
train
9fc3343a04a3b389f233dfbb1266cc662e83a68e
diff --git a/src/readStream.js b/src/readStream.js index <HASH>..<HASH> 100644 --- a/src/readStream.js +++ b/src/readStream.js @@ -1,11 +1,11 @@ var combinedStream = require('combined-stream'); -var parse = require('csv-stream'); var fs = require('fs'); var through2 = require('through2'); var path = require('path'); var logger = require( 'pelias-logger' ).get( 'whosonfirst' ); +const parseMetaFiles = require('./components/parseMetaFiles'); var isValidId = require('./components/isValidId'); var loadJSON = require('./components/loadJSON'); var recordHasIdAndProperties = require('./components/recordHasIdAndProperties'); @@ -36,7 +36,7 @@ function createOneMetaRecordStream(metaFilePath) { }; return fs.createReadStream(metaFilePath) - .pipe(parse.createStream(options)); + .pipe(parseMetaFiles.create()); } /*
switched over to abstracted csv-parse
pelias_whosonfirst
train
e9996178aacc065c2c5b04fbeca00f2cd494a755
diff --git a/lib/backup/storage/rsync.rb b/lib/backup/storage/rsync.rb index <HASH>..<HASH> 100644 --- a/lib/backup/storage/rsync.rb +++ b/lib/backup/storage/rsync.rb @@ -68,7 +68,9 @@ module Backup ## # Establishes a connection to the remote server and returns the Net::SSH object. def connection - Net::SSH.start(ip, username, :password => password, :port => port) + Net::SSH.start(ip, username, :password => password, :port => port) do |ssh| + yield ssh + end end ## @@ -106,7 +108,9 @@ module Backup if @local mkdir(remote_path) else - connection.exec!("mkdir -p '#{ remote_path }'") + connection do |ssh| + ssh.exec!("mkdir -p '#{ remote_path }'") + end end end diff --git a/spec/storage/rsync_spec.rb b/spec/storage/rsync_spec.rb index <HASH>..<HASH> 100644 --- a/spec/storage/rsync_spec.rb +++ b/spec/storage/rsync_spec.rb @@ -78,13 +78,17 @@ describe Backup::Storage::RSync do describe '#connection' do it 'should establish a connection to the remote server' do + connection = mock Net::SSH.expects(:start).with( '123.45.678.90', 'my_username', :password => 'my_password', :port => 22 - ) - rsync.send(:connection) + ).yields(connection) + + rsync.send(:connection) do |ssh| + ssh.should be connection + end end end @@ -154,13 +158,13 @@ describe Backup::Storage::RSync do end describe '#create_remote_directories!' do - let(:connection) { mock } context 'when rsync.local is false' do it 'should create directories on the remote server' do + ssh = mock rsync.expects(:mkdir).never - rsync.expects(:connection).returns(connection) - connection.expects(:exec!).with("mkdir -p '#{rsync.remote_path}'") + rsync.expects(:connection).yields(ssh) + ssh.expects(:exec!).with("mkdir -p '#{rsync.remote_path}'") rsync.send(:create_remote_directories!) end
use block with Net::SSH.start to close connection
backup_backup
train
18cd6c2d9b48fca6855c93a976d3729ad8cc03ee
diff --git a/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java b/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java +++ b/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java @@ -225,14 +225,13 @@ public class ODocument extends ORecordVirtualAbstract<Object> implements Iterabl } /** - * Returns the array of field names. + * Returns the set of field names. */ - public String[] fieldNames() { + public Set<String> fieldNames() { checkForLoading(); checkForFields(); - String[] result = new String[_fieldValues.keySet().size()]; - return _fieldValues.keySet().toArray(result); + return _fieldValues.keySet(); } /**
ODocument.fieldNames() now returns a Set<String> instead of String[]. This avoid the creation of an array when you need to iterate over the fields.
orientechnologies_orientdb
train
db1f469168b58d58a86dc1daf6aeb8c896414137
diff --git a/icekit/publishing/utils.py b/icekit/publishing/utils.py index <HASH>..<HASH> 100644 --- a/icekit/publishing/utils.py +++ b/icekit/publishing/utils.py @@ -1,5 +1,6 @@ import urlparse +from django.apps import apps from django.http import QueryDict from django.utils.crypto import get_random_string, salted_hmac from django.utils.encoding import force_bytes @@ -15,6 +16,15 @@ class NotDraftException(PublishingException): pass +def get_publishable_models(): + from .models import PublishingModel + publishable_models = [ + model for model in apps.get_models() + if issubclass(model, PublishingModel) + ] + return publishable_models + + def assert_draft(method): def decorated(self, *args, **kwargs): if not self.is_draft:
Add utility method `get_publishable_models()`, re #5 #<I>
ic-labs_django-icekit
train
316e453ef9fc9411bc13752ac01247529169197c
diff --git a/sonnet/python/modules/base_info.py b/sonnet/python/modules/base_info.py index <HASH>..<HASH> 100644 --- a/sonnet/python/modules/base_info.py +++ b/sonnet/python/modules/base_info.py @@ -59,12 +59,8 @@ def _is_namedtuple(obj): def _is_iterable(obj): - """Returns true if the object is iterable.""" - try: - _ = iter(obj) - return True - except TypeError: - return False + """Returns `True` if the object is a supported iterable.""" + return isinstance(obj, (list, tuple, dict)) def _graph_element_to_path(graph_element): diff --git a/sonnet/python/modules/base_info_test.py b/sonnet/python/modules/base_info_test.py index <HASH>..<HASH> 100644 --- a/sonnet/python/modules/base_info_test.py +++ b/sonnet/python/modules/base_info_test.py @@ -77,8 +77,11 @@ class ModuleInfoTest(tf.test.TestCase): self.assertTrue(base_info._is_iterable((1, 2, 3))) self.assertTrue(base_info._is_iterable([1, 2, 3])) self.assertTrue(base_info._is_iterable({1: 1, 2: 2, 3: 3})) + self.assertTrue(base_info._is_iterable( + collections.OrderedDict([(1, 1), (2, 2)]))) self.assertTrue(base_info._is_iterable(DumbNamedTuple(1, 2))) tensor = tf.placeholder(dtype=tf.float32, shape=(1, 10,)) + self.assertFalse(base_info._is_iterable(set([1, 2, 3]))) self.assertFalse(base_info._is_iterable(tensor)) sparse_tensor = tf.SparseTensor( indices=tf.placeholder(dtype=tf.int64, shape=(10, 2,)), @@ -86,6 +89,12 @@ class ModuleInfoTest(tf.test.TestCase): dense_shape=tf.placeholder(dtype=tf.int64, shape=(2,))) self.assertFalse(base_info._is_iterable(sparse_tensor)) self.assertFalse(base_info._is_iterable(NotATensor())) + self.assertFalse(base_info._is_iterable("foo")) + def generator(): + for count in xrange(3): + self.assertFalse(False) + yield count + self.assertFalse(base_info._is_iterable(generator)) def testModuleInfo_multiple_modules(self): # pylint: disable=not-callable
Make `base_info._is_iterable` safer by only returning True for supported types: list, tuple and dict. PiperOrigin-RevId: <I>
deepmind_sonnet
train
a2912c08cc382496f852a78c1b3c2e41f3be899a
diff --git a/tofu/tests/__init__.py b/tofu/tests/__init__.py index <HASH>..<HASH> 100644 --- a/tofu/tests/__init__.py +++ b/tofu/tests/__init__.py @@ -8,4 +8,5 @@ from . import tests04_spectro from . import tests05_nist from . import tests06_mesh from . import tests07_inversions +from . import tests08_diagnostics from . import tests09_tutorials
[#<I>] Added unit tests on diags to __init__.py
ToFuProject_tofu
train
f79ff8a3914489484b8462d01f523142923d1d66
diff --git a/lib/cluster/worker.js b/lib/cluster/worker.js index <HASH>..<HASH> 100644 --- a/lib/cluster/worker.js +++ b/lib/cluster/worker.js @@ -135,41 +135,37 @@ module.exports = function(context) { function isReady(res, slice, msg, specData, sliceLogger) { //res may return null if no data was received - //TODO this needs to be addressed - if (res && res.errors) { - return Promise.reject('errors in elasticsearch_bulk', res.toJSON()) - } - else { - return state_store.log(ex_id, slice, 'completed') - .then(function(results) { - sentMessage = {worker_id: ID, slice: slice, analytics: specData}; - sliceLogger.info(`completed slice: `, slice); - if (isShuttingDown) { - sentMessage.isShuttingDown = true; - } - messaging.send('worker:slice:complete', sentMessage); + return state_store.log(ex_id, slice, 'completed') + .then(function(results) { + sentMessage = {worker_id: ID, slice: slice, analytics: specData}; + sliceLogger.info(`completed slice: `, slice); + if (isShuttingDown) { + sentMessage.isShuttingDown = true; + } + messaging.send('worker:slice:complete', sentMessage); - if (specData) { - if (job.reporter) { - job.reporter(context, job.jobConfig, specData); - logMessage(sliceLogger, msg); - } - else { - logMessage(sliceLogger, msg, specData); - return analytics_store.log(job, slice, specData) - .catch(function(err) { - logger.error("Failure when storing analytics: ", err) - }); - } + if (specData) { + if (job.reporter) { + job.reporter(context, job.jobConfig, specData); + logMessage(sliceLogger, msg); } else { - return logMessage(sliceLogger, msg) + logMessage(sliceLogger, msg, specData); + return analytics_store.log(job, slice, specData) + .catch(function(err) { + var errMsg = parseError(err); + logger.error(`Failure when storing analytics: ${errMsg}`) + }); } - }) - .finally(function() { - isDone = true; - }); - } + } + else { + return logMessage(sliceLogger, msg) + } + }) + .finally(function() { + isDone = true; + }); + } function runSlice(slice, sliceLogger) { @@ -177,7 +173,7 @@ module.exports = function(context) { function sliceFailed(err) { var errMsg = parseError(err); sentMessage = {worker_id: ID, slice: slice, error: errMsg}; - state_store.log(ex_id, slice, 'error', errMsg) + return state_store.log(ex_id, slice, 'error', errMsg) .then(function() { sliceLogger.error(`failed to process`, sentMessage, `and has slice state is marked as error`); messaging.send('worker:slice:complete', sentMessage); @@ -185,10 +181,12 @@ module.exports = function(context) { .catch(function(err) { var errMsg = parseError(err); sliceLogger.error(`An error has occurred: ${errMsg} on marking slice as failed, message: `, slice); + messaging.send('worker:slice:complete', sentMessage); }); } var msg = slice.request; + var slice_id = slice.slice_id; var finalQueue = queue; var specData; @@ -215,28 +213,32 @@ module.exports = function(context) { sliceLogger.error(`An error has occurred: ${errMsg}, message: `, slice); if (max_retries) { //checking if error has occurred before - if (errorLog[msg]) { - errorLog[msg]++; + if (errorLog[slice_id]) { + errorLog[slice_id]++; - if (errorLog[msg] >= max_retries) { + if (errorLog[slice_id] >= max_retries) { sliceLogger.error('Max retires has been reached for: ', slice); - sliceFailed(err); - isDone = true; + sliceFailed(err) + .finally(function() { + isDone = true + }); } else { runSlice(slice, sliceLogger); } } else { - errorLog[msg] = 1; + errorLog[slice_id] = 1; runSlice(slice, sliceLogger); } } //no retries, proceed to next slice else { - sliceFailed(err); - isDone = true; + sliceFailed(err) + .finally(function() { + isDone = true + }); } }); }
added guards to marking slice as failed (#<I>)
terascope_teraslice
train
3819557abef3bd6d6d42bc73087ba93f6175bf8c
diff --git a/src/client/js/Panels/PartBrowser/PartBrowserPanelControl.js b/src/client/js/Panels/PartBrowser/PartBrowserPanelControl.js index <HASH>..<HASH> 100644 --- a/src/client/js/Panels/PartBrowser/PartBrowserPanelControl.js +++ b/src/client/js/Panels/PartBrowser/PartBrowserPanelControl.js @@ -88,9 +88,13 @@ define(['js/logger', this._nodeEventHandling = function (events) { var metaChange = false, - metaPaths = Object.keys(self._client.getAllMetaNodes() || {}), + metaNodes = self._client.getAllMetaNodes() || [], + metaPaths = [], i; + for (i = 0; i < metaNodes.length; i += 1) { + metaPaths.push(metaNodes[i].getId()); + } metaPaths.push(CONSTANTS.PROJECT_ROOT_ID); for (i = 0; i < events.length; i += 1) { diff --git a/src/client/js/Utils/GMEConcepts.js b/src/client/js/Utils/GMEConcepts.js index <HASH>..<HASH> 100644 --- a/src/client/js/Utils/GMEConcepts.js +++ b/src/client/js/Utils/GMEConcepts.js @@ -329,13 +329,13 @@ define(['jquery', } function getMETAAspectMergedValidChildrenTypes(objID) { - var metaAspectMembers = Object.keys(client.getAllMetaNodes() || {}), + var metaNodes = client.getAllMetaNodes() || [], validChildrenTypes = client.getValidChildrenTypes(objID), - len = metaAspectMembers.length, + len = metaNodes.length, id; while (len--) { - id = metaAspectMembers[len]; + id = metaNodes[len].getId(); if (validChildrenTypes.indexOf(id) === -1) { if (client.isValidChild(objID, id)) { validChildrenTypes.push(id);
#<I> connection drawing the bad type handling of meta nodes were checked and valid target point now visible again Former-commit-id: fa<I>c0b7c<I>c6ff4c<I>e<I>e<I>fd<I>
webgme_webgme-engine
train
4fcc67c19994457f648a5c8eedaa8d50bb66981a
diff --git a/scapy/layers/inet.py b/scapy/layers/inet.py index <HASH>..<HASH> 100644 --- a/scapy/layers/inet.py +++ b/scapy/layers/inet.py @@ -213,7 +213,8 @@ TCPOptions = ( 8 : ("Timestamp","!II"), 14 : ("AltChkSum","!BH"), 15 : ("AltChkSumOpt",None), - 25 : ("Mood","!p") + 25 : ("Mood","!p"), + 28 : ("UTO", "!H") }, { "EOL":0, "NOP":1, @@ -224,7 +225,8 @@ TCPOptions = ( "Timestamp":8, "AltChkSum":14, "AltChkSumOpt":15, - "Mood":25 + "Mood":25, + "UTO":28 } ) class TCPOptionsField(StrField):
add TCP User Timout Option (RFC <I>) Allow one to send the TCP User Timeout Option described in RFC <I> in a crafted TCP segment.
secdev_scapy
train
83b463cc784a71456d312bce5ed4cf8567dd858d
diff --git a/src/docs/formatter.js b/src/docs/formatter.js index <HASH>..<HASH> 100644 --- a/src/docs/formatter.js +++ b/src/docs/formatter.js @@ -27,6 +27,17 @@ function format(docfile) { var fqn = tagValues.fqn !== ''? tagValues.fqn: name; name = tagValues.name !== ''? tagValues.name: name + javadoc.filename = docfile.filename; + + if (fqn in fqnMap) { + var first = fqnMap[fqn].raw; + var second = javadoc; + + throw 'Two elements of the same fully qualified name (fqn) found:\n'+ + ' 1. '+ first.filename +':'+ first.line +'\n'+ + ' 2. '+ second.filename +':'+ second.line; + } + fqnMap[fqn] = { commentId: nextId++, type: type,
+ check for fqn duplication
mchalapuk_hyper-text-slider
train
66d8b9335f86fa02391b10bcd7cc37c2d4650310
diff --git a/README.rst b/README.rst index <HASH>..<HASH> 100644 --- a/README.rst +++ b/README.rst @@ -18,7 +18,7 @@ ToFu **Warning** This Pypi package focuses on tomography for fusion research. -It uses the same name as a previous package dedicated to a testing framework coupling fixtures and tests loosely, now renamed **reahli-tofu** and developped by Iwan Vosloo since 2006. If you ended up here looking for a web-oriented library, you should probably redirect to the more recent [**reahl-tofu**](https://pypi.python.org/pypi/reahl-tofu/3.2.0) page. +It uses the same name as a previous package dedicated to a testing framework coupling fixtures and tests loosely, now renamed **reahl-tofu** and developped by Iwan Vosloo since 2006. If you ended up here looking for a web-oriented library, you should probably redirect to the more recent [**reahl-tofu**](https://pypi.python.org/pypi/reahl-tofu) page. ----- diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -34,14 +34,11 @@ version_git = up.updateversion(os.path.join(here,'tofu')) if sys.version[:3] in ['2.7','3.6']: gg = '_GG0%s' % sys.version[0] poly = 'polygon%s' % sys.version[0] - subv = '.13' if sys.version[0]=='2' else '.1' - pyreq = '~='+sys.version[:3]+subv else: raise Exception("Pb. with python version in setup.py file: "+sys.version) print("") print("Version for setup.py : ", version_git) -print("python_requires : ", pyreq) print("") @@ -150,7 +147,7 @@ setup( 'cython', ], - python_requires = pyreq, + python_requires = '~2.7, ~=3.6', # List additional groups of dependencies here (e.g. development diff --git a/tofu/version.py b/tofu/version.py index <HASH>..<HASH> 100644 --- a/tofu/version.py +++ b/tofu/version.py @@ -1,2 +1,2 @@ # Do not edit this file, pipeline versioning is governed by git tags ! -__version__='1.2.30' \ No newline at end of file +__version__='1.2.31' \ No newline at end of file
Trying to upload on Pypi - <I>
ToFuProject_tofu
train
8f1c1f3d64243b7369fe2d4a71c2f09652d380be
diff --git a/benchexec/localexecution.py b/benchexec/localexecution.py index <HASH>..<HASH> 100644 --- a/benchexec/localexecution.py +++ b/benchexec/localexecution.py @@ -501,7 +501,7 @@ class _Worker(threading.Thread): for key, value in result.items(): if key == 'walltime': - run.walltime == value + run.walltime = value elif key == 'cputime': run.cputime = value elif key == 'memory':
bug fix: walltime measurements were ignored and lost
sosy-lab_benchexec
train
8ec4ecab17e2f35347c1e835859711d4cc68754c
diff --git a/.eslintrc.js b/.eslintrc.js index <HASH>..<HASH> 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -25,7 +25,7 @@ module.exports = { "computed-property-spacing": [ 2, "always" ], "dot-notation": [ 2 ], "indent": [ 2, "tab", { "SwitchCase": 1 } ], - "max-len": [ 2, { "code": 80, "comments": 120, "tabWidth": 2, "ignoreTrailingComments": true, "ignoreUrls": true, "ignoreTemplateLiterals": true, "ignoreRegExpLiterals": true, "ignoreStrings": true } ], + "max-len": [ 2, { "code": 100, "comments": 100, "tabWidth": 2, "ignoreTrailingComments": true, "ignoreUrls": true, "ignoreTemplateLiterals": true, "ignoreRegExpLiterals": true, "ignoreStrings": true } ], "max-lines": [ 2, { "max": 250, "skipBlankLines": true, "skipComments": true } ], "max-statements": [ 2, 30 ], "no-confusing-arrow": [ 2, { "allowParens": false } ],
Switch to <I> col line lengths
ianpaschal_aurora
train
ed922b70029fd4a71af5e7a7e9f7b5a8227be9af
diff --git a/abaaso.js b/abaaso.js index <HASH>..<HASH> 100644 --- a/abaaso.js +++ b/abaaso.js @@ -40,8 +40,8 @@ * See @link for the development roadmap * * Events: ready Fires when the DOM is available (safe for GUI creation) - * render Fires after the window resources have loaded (safe for visual fx) - * resize Fires on window resize + * render Fires when the window resources have loaded (safe for visual fx) + * resize Fires when the window resize * * @author Jason Mulligan <jason.mulligan@avoidwork.com> * @link http://avoidwork.com/products/abaaso abaaso
Revised abaaso event comments
avoidwork_abaaso
train
f8e7137e7f48670b32b97b7f7963777e4e541b7d
diff --git a/Kwc/Shop/Cart/OrderData.php b/Kwc/Shop/Cart/OrderData.php index <HASH>..<HASH> 100644 --- a/Kwc/Shop/Cart/OrderData.php +++ b/Kwc/Shop/Cart/OrderData.php @@ -95,15 +95,17 @@ class Kwc_Shop_Cart_OrderData 'text' => trlKwf('value of goods').':', 'amount' => $subTotal ); - $vat = 1+Kwc_Abstract::getSetting($this->_class, 'vatRate'); - $ret[] = array( - 'text' => trlKwf('net amount').':', - 'amount' => round($subTotal/$vat, 2) - ); - $ret[] = array( - 'text' => trlKwf('+'.(($vat-1 )*100).'% VAT').':', - 'amount' => round($subTotal - $subTotal/$vat, 2) - ); + if (Kwc_Abstract::getSetting($this->_class, 'vatRate')) { + $vat = 1+Kwc_Abstract::getSetting($this->_class, 'vatRate'); + $ret[] = array( + 'text' => trlKwf('net amount').':', + 'amount' => round($subTotal/$vat, 2) + ); + $ret[] = array( + 'text' => trlKwf('+'.(($vat-1 )*100).'% VAT').':', + 'amount' => round($subTotal - $subTotal/$vat, 2) + ); + } $shipping = 0; if ($this->_hasShipping($order)) { $shipping = $this->_getShipping($order);
don't add vat related sumRows if vatRate is not set
koala-framework_koala-framework
train
890536f554f141e606d62a477f1156390d86528d
diff --git a/parquet2hive_modules/parquet2hivelib.py b/parquet2hive_modules/parquet2hivelib.py index <HASH>..<HASH> 100644 --- a/parquet2hive_modules/parquet2hivelib.py +++ b/parquet2hive_modules/parquet2hivelib.py @@ -34,6 +34,8 @@ def get_bash_cmd(dataset, success_only = False, recent_versions = None, version for version in versions: success_exists = False version_prefix = prefix + '/' + version + '/' + dataset_name = prefix.split('/')[-1] + keys = sorted(bucket.objects.filter(Prefix=version_prefix), key = lambda obj : obj.last_modified, reverse = True) for key in keys: @@ -55,7 +57,7 @@ def get_bash_cmd(dataset, success_only = False, recent_versions = None, version sys.stderr.write("Ignoring empty dataset\n") continue - sys.stderr.write("Analyzing dataset {}, {}\n".format(prefix, version)) + sys.stderr.write("Analyzing dataset {}, {}\n".format(dataset_name, version)) s3_client = boto3.client('s3') tmp_file = NamedTemporaryFile() s3_client.download_file(key.bucket_name, key.key, tmp_file.name) @@ -64,9 +66,9 @@ def get_bash_cmd(dataset, success_only = False, recent_versions = None, version schema = json.loads("{" + re.search("(org.apache.spark.sql.parquet.row.metadata|parquet.avro.schema) = {(.+)}", meta).group(2) + "}") partitions = get_partitioning_fields(key.key[len(prefix):]) - bash_cmd += "hive -hiveconf hive.support.sql11.reserved.keywords=false -e '{}'".format(avro2sql(schema, prefix, version, dataset, partitions)) + '\n' + bash_cmd += "hive -hiveconf hive.support.sql11.reserved.keywords=false -e '{}'".format(avro2sql(schema, dataset_name, version, dataset, partitions)) + '\n' if versions_loaded == 0: # Most recent version - bash_cmd += "hive -e '{}'".format(avro2sql(schema, prefix, version, dataset, partitions, with_version=False)) + '\n' + bash_cmd += "hive -e '{}'".format(avro2sql(schema, dataset_name, version, dataset, partitions, with_version=False)) + '\n' versions_loaded += 1 if recent_versions is not None and versions_loaded >= recent_versions: @@ -89,7 +91,12 @@ def get_versions(bucket, prefix): sys.stderr.write("Ignoring incompatible versioning scheme\n") continue - dataset_name = tmp[-2] + #we don't yet support importing multiple datasets with a single command + dataset_prefix = '/'.join(tmp[:-1]) + if dataset_prefix != prefix[:-1]: + sys.stderr.write("Ignoring dataset nested within prefix. To load this dataset, call p2h on it directly: `parquet2hive s3://{}`\n".format(dataset_prefix)) + continue + version = tmp[-1] if not re.match("^v[0-9]+$", version): sys.stderr.write("Ignoring incompatible versioning scheme: version must be an integer prefixed with a 'v'\n") diff --git a/tests/parquet2hive_test.py b/tests/parquet2hive_test.py index <HASH>..<HASH> 100644 --- a/tests/parquet2hive_test.py +++ b/tests/parquet2hive_test.py @@ -162,8 +162,22 @@ class TestGetBashCmd: assert '`id`' in bash_cmd, 'Column from newer file should be in schema, but is not' assert '`country`' not in bash_cmd, 'Column from older file should not be in schema' - + + @mock_s3 + def test_nested_dataset(self): + _setup_module() + + prefix, version, objects = 'prod/churn', 'v1', ['dataset_file'] + filenames = {'dataset_file' : dataset_file, 'new_dataset_file' : new_dataset_file} + for _object in objects: + key = '/'.join((prefix, version, _object)) + s3_client.put_object(Bucket = bucket_name, Key = key, Body = open(filenames[_object], 'rb')) + + dataset = 's3://' + '/'.join((bucket_name, prefix)) + bash_cmd = lib.get_bash_cmd(dataset) + assert 'table prod/churn' not in bash_cmd + assert 'table churn' in bash_cmd class TestGetVersions: @@ -202,6 +216,21 @@ class TestGetVersions: assert lib.get_versions(bucket, prefix) == ['v2', 'v1'], 'versions not returned in descending order' + @mock_s3 + def test_ignore_nested_dataset(self): + _setup_module() + + prefix, version, objects = 'prod/churn', 'v1', ['dataset_file'] + for _object in objects: + key = '/'.join((prefix, version, _object)) + s3_client.put_object(Bucket = bucket_name, Key = key, Body = open(dataset_file, 'rb')) + + dataset = 's3://' + '/'.join((bucket_name, 'prod')) + + assert lib.get_versions(bucket, 'prod') == [], 'Should ignore nested dataset that is not explicitly identified' + + + class TestSuccessExists: @mock_s3
Handle nested datasets correctly Nested datasets were previously incorrectly named. The name of the dataset is now not the entire prefix, but just the last dir in the prefix. In addition, nested datasets that are now called out as ignored. In the future we plan on support these, but not currently.
mozilla_parquet2hive
train
c75ba879bb4d855cba8bd14abfdf7cdb93927ba5
diff --git a/mod/choice/lib.php b/mod/choice/lib.php index <HASH>..<HASH> 100644 --- a/mod/choice/lib.php +++ b/mod/choice/lib.php @@ -242,20 +242,43 @@ function choice_user_submit_response($formanswer, $choice, $userid, $courseid, $ $current = get_record('choice_answers', 'choiceid', $choice->id, 'userid', $userid); $context = get_context_instance(CONTEXT_MODULE, $cm->id); - $countanswers = get_records("choice_answers", "optionid", $formanswer); - if ($countanswers) { - $countans = 0; - foreach ($countanswers as $ca) { //only return enrolled users. - if (has_capability('mod/choice:choose', $context, $ca->userid, false)) { - $countans = $countans+1; - } + + $countanswers=0; + if($choice->limitanswers) { + // Find out whether groups are being used and enabled + if (groups_get_activity_groupmode($cm) > 0) { + $currentgroup = groups_get_activity_group($cm); + } else { + $currentgroup = 0; + } + if($currentgroup) { + // If groups are being used, retrieve responses only for users in + // current group + global $CFG; + $answers = get_records_sql(" +SELECT + ca.* +FROM + {$CFG->prefix}choice_answers ca + INNER JOIN {$CFG->prefix}groups_members gm ON ca.userid=gm.userid +WHERE + optionid=$formanswer + AND gm.groupid=$currentgroup"); + } else { + // Groups are not used, retrieve all answers for this option ID + $answers = get_records("choice_answers", "optionid", $formanswer); } - $countanswers = $countans; - } else { - $countanswers = 0; + $countanswers=0; + if ($answers) { + foreach ($answers as $a) { //only return enrolled users. + if (has_capability('mod/choice:choose', $context, $a->userid, false)) { + $countanswers++; + } + } + } + $maxans = $choice->maxanswers[$formanswer]; } - $maxans = $choice->maxanswers[$formanswer]; if (!($choice->limitanswers && ($countanswers >= $maxans) )) { if ($current) {
MDL-<I>: Choice limited answers don't work with group mode
moodle_moodle
train
eb4fb4f87e9165ebb7282ed3e94b7dc60684c81d
diff --git a/examples/RegexTest.php b/examples/RegexTest.php index <HASH>..<HASH> 100644 --- a/examples/RegexTest.php +++ b/examples/RegexTest.php @@ -11,7 +11,7 @@ class RegexTest extends \PHPUnit_Framework_TestCase Generator\regex("[a-z]{10}"), ]) ->then(function($string) { - var_dump($string); + $this->assertEquals(10, strlen($string)); }); } } diff --git a/test/Eris/ExampleEnd2EndTest.php b/test/Eris/ExampleEnd2EndTest.php index <HASH>..<HASH> 100644 --- a/test/Eris/ExampleEnd2EndTest.php +++ b/test/Eris/ExampleEnd2EndTest.php @@ -44,6 +44,12 @@ class ExampleEnd2EndTest extends \PHPUnit_Framework_TestCase ); } + public function testRegexTests() + { + $this->runExample('RegexTest.php'); + $this->assertAllTestsArePassing(3); + } + public function testSumTests() { $this->runExample('SumTest.php');
Setup RegexTest as example and in end2end
giorgiosironi_eris
train
5a3a504419bdf792b6232caef528f92d7c952257
diff --git a/lib/models/image.rb b/lib/models/image.rb index <HASH>..<HASH> 100644 --- a/lib/models/image.rb +++ b/lib/models/image.rb @@ -34,7 +34,7 @@ module ErnieBrodeur self.height = i[:height] self.format = i[:type] self.transparency = i[:transparency] - self.ratio = width / height + self.ratio = (width / height).round 3 end end @@ -52,7 +52,7 @@ module ErnieBrodeur return nil if !ErnieBrodeur.is_image? filename #TODO not have this unrolled, make it more dynamic. - width, height, type, transparency = %x[identify -ping -format '%w %h %m %z %A' '#{filename}'].split + width, height, type, transparency = %x[identify -ping -format '%w %h %m %A' '#{filename}'].split h = {} h[:width] = width.to_f
Dropped a word in identify so it works, round ratio to 3 digits.
erniebrodeur_bini
train
c5948d1889e3d6c64bdf1572fb6396acb802ca69
diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py index <HASH>..<HASH> 100644 --- a/pandas/core/reshape/tile.py +++ b/pandas/core/reshape/tile.py @@ -4,7 +4,6 @@ Quantilization functions and related stuff import numpy as np from pandas._libs import Timedelta, Timestamp -from pandas._libs.interval import Interval from pandas._libs.lib import infer_dtype from pandas.core.dtypes.common import ( @@ -516,17 +515,11 @@ def _format_labels( adjust = lambda x: x - 10 ** (-precision) breaks = [formatter(b) for b in bins] - labels = IntervalIndex.from_breaks(breaks, closed=closed) - if right and include_lowest: - # we will adjust the left hand side by precision to - # account that we are all right closed - v = adjust(labels[0].left) - - i = IntervalIndex([Interval(v, labels[0].right, closed="right")]) - labels = i.append(labels[1:]) + # adjust lhs of first interval by precision to account for being right closed + breaks[0] = adjust(breaks[0]) - return labels + return IntervalIndex.from_breaks(breaks, closed=closed) def _preprocess_for_cut(x):
CLN: Simplify logic in _format_labels function for cut/qcut (#<I>)
pandas-dev_pandas
train
3c5f7c8c59a1fe29355b3006f7f1d97a955beb1d
diff --git a/java/client/test/org/openqa/selenium/remote/RemotableByTest.java b/java/client/test/org/openqa/selenium/remote/RemotableByTest.java index <HASH>..<HASH> 100644 --- a/java/client/test/org/openqa/selenium/remote/RemotableByTest.java +++ b/java/client/test/org/openqa/selenium/remote/RemotableByTest.java @@ -34,10 +34,13 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; +import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.openqa.selenium.remote.ErrorCodes.SUCCESS_STRING; +import com.google.common.collect.ImmutableMap; + public class RemotableByTest { private final SessionId id = new SessionId(UUID.randomUUID()); @@ -53,7 +56,8 @@ public class RemotableByTest { }); driver.findElement(By.cssSelector("#foo")); - assertThat(parameters.get()).isEqualTo(Map.of("using", "css selector", "value", "#foo")); + assertThat(parameters.get()) + .isEqualTo(ImmutableMap.of("using", "css selector", "value", "#foo")); } @Test @@ -63,7 +67,7 @@ public class RemotableByTest { WebDriver driver = createDriver( cmd -> { parameters.set(cmd.getParameters()); - return createResponse(List.of(new RemoteWebElement())); + return createResponse(singletonList(new RemoteWebElement())); } ); @@ -74,7 +78,8 @@ public class RemotableByTest { } }); - assertThat(parameters.get()).isEqualTo(Map.of("using", "css selector", "value", "#foo")); + assertThat(parameters.get()) + .isEqualTo(ImmutableMap.of("using", "css selector", "value", "#foo")); } @Test @@ -102,7 +107,8 @@ public class RemotableByTest { driver.findElement(new CustomBy()); - assertThat(parameters.get()).isEqualTo(Map.of("using", "magic", "value", "abracadabra")); + assertThat(parameters.get()) + .isEqualTo(ImmutableMap.of("using", "magic", "value", "abracadabra")); } @Test @@ -113,7 +119,7 @@ public class RemotableByTest { cmd -> createError(new InvalidArgumentException("Nope")), cmd -> { parameters.set(cmd.getParameters()); - return createResponse(List.of(new RemoteWebElement())); + return createResponse(singletonList(new RemoteWebElement())); } ); @@ -131,7 +137,8 @@ public class RemotableByTest { driver.findElement(new CustomBy()); - assertThat(parameters.get()).isEqualTo(Map.of("using", "css selector", "value", "not-magic")); + assertThat(parameters.get()) + .isEqualTo(ImmutableMap.of("using", "css selector", "value", "not-magic")); } @Test @@ -151,12 +158,12 @@ public class RemotableByTest { // Second search tries both mechanisms, and succeeds because fallback to search context works cmd -> createError(new InvalidArgumentException("remoting fail")), - cmd -> createResponse(List.of(new RemoteWebElement())), + cmd -> createResponse(singletonList(new RemoteWebElement())), // Third search goes straight to using the fallback cmd -> { parameters.set(cmd.getParameters()); - return createResponse(List.of(new RemoteWebElement())); + return createResponse(singletonList(new RemoteWebElement())); } ); @@ -182,7 +189,8 @@ public class RemotableByTest { driver.findElement(new CustomBy("two")); driver.findElement(new CustomBy("three")); - assertThat(parameters.get()).isEqualTo(Map.of("using", "css selector", "value", "three")); + assertThat(parameters.get()) + .isEqualTo(ImmutableMap.of("using", "css selector", "value", "three")); } private Response createResponse(Object value) { @@ -202,7 +210,7 @@ public class RemotableByTest { } @SafeVarargs - private WebDriver createDriver(Function<Command, Response>... responses) { + private final WebDriver createDriver(Function<Command, Response>... responses) { Iterator<Function<Command, Response>> iterator = Arrays.stream(responses).iterator(); CommandExecutor executor = cmd -> iterator.next().apply(cmd);
[java] Fixing Java 8 compatibility issues
SeleniumHQ_selenium
train
2499f5fa7effb98960b3e09533f4e190b35c3133
diff --git a/ui/src/status/containers/StatusPage.js b/ui/src/status/containers/StatusPage.js index <HASH>..<HASH> 100644 --- a/ui/src/status/containers/StatusPage.js +++ b/ui/src/status/containers/StatusPage.js @@ -1,13 +1,15 @@ import React, {Component, PropTypes} from 'react' +import {connect} from 'react-redux' import ReactGridLayout, {WidthProvider} from 'react-grid-layout' import SourceIndicator from 'shared/components/SourceIndicator' import FancyScrollbar from 'shared/components/FancyScrollbar' +import RefreshingGraph from 'shared/components/RefreshingGraph' import NameableGraph from 'shared/components/NameableGraph' const GridLayout = WidthProvider(ReactGridLayout) -const mockStatusPageCells = [ +const fixtureGraphCells = [ { name: 'Alerts', type: 'bar', @@ -17,6 +19,8 @@ const mockStatusPageCells = [ h: 4, i: 'bar', }, +] +const fixtureNonGraphCells = [ { name: 'Recent Alerts', type: 'alerts', @@ -51,23 +55,16 @@ class StatusPage extends Component { super(props) this.state = { - cells: mockStatusPageCells, + graphCells: fixtureGraphCells, + nonGraphCells: fixtureNonGraphCells, } - this.generateStatusPageCell = ::this.generateStatusPageCell - this.renderStatusPageCells = ::this.renderStatusPageCells + this.generateLayoutCells = ::this.generateLayoutCells this.triggerWindowResize = ::this.triggerWindowResize } - generateStatusPageCell(cell) { + generateNonGraphCell(cell) { switch (cell.type) { - case 'bar': { - return ( - <div className="graph-empty"> - <p>Coming soon: Bar graph</p> - </div> - ) - } case 'alerts': { return ( <div className="graph-empty"> @@ -97,23 +94,41 @@ class StatusPage extends Component { ) } - renderStatusPageCells(cells) { - return cells.map(cell => { - return ( - <div key={cell.i}> - <NameableGraph - cell={{ - name: cell.name, - x: cell.x, - y: cell.y, - }} - shouldNotBeEditable={true} - > - {this.generateStatusPageCell(cell)} - </NameableGraph> - </div> - ) - }) + generateLayoutCells(graphCells, nonGraphCells) { + return [ + ...graphCells.map(cell => { + return ( + <div key={cell.i}> + <NameableGraph + cell={{ + name: cell.name, + x: cell.x, + y: cell.y, + }} + shouldNotBeEditable={true} + > + <RefreshingGraph /> + </NameableGraph> + </div> + ) + }), + ...nonGraphCells.map(cell => { + return ( + <div key={cell.i}> + <NameableGraph + cell={{ + name: cell.name, + x: cell.x, + y: cell.y, + }} + shouldNotBeEditable={true} + > + {this.generateNonGraphCell(cell)} + </NameableGraph> + </div> + ) + }), + ] } triggerWindowResize() { @@ -125,7 +140,7 @@ class StatusPage extends Component { render() { const {source} = this.props - const {cells} = this.state + const {graphCells, nonGraphCells} = this.state const layoutMargin = 4 @@ -145,9 +160,9 @@ class StatusPage extends Component { </div> <FancyScrollbar className={'page-contents'}> <div className="dashboard container-fluid full-width"> - {cells.length + {graphCells.length && nonGraphCells.length ? <GridLayout - layout={cells} + layout={[...graphCells, ...nonGraphCells]} cols={12} rowHeight={83.5} margin={[layoutMargin, layoutMargin]} @@ -159,7 +174,7 @@ class StatusPage extends Component { isDraggable={false} isResizable={false} > - {this.renderStatusPageCells(cells)} + {this.generateLayoutCells(graphCells, nonGraphCells)} </GridLayout> : <span>Loading status...</span>} </div> @@ -177,4 +192,4 @@ StatusPage.propTypes = { }).isRequired, } -export default StatusPage +export default connect(null)(StatusPage)
Refactor skeleton to accommodate graph vs non-graph cells Connect StatusPage to router props, ex. source
influxdata_influxdb
train
95a716d593672ce2e1bf208154785838fba5c9d7
diff --git a/pyrax/cf_wrapper/client.py b/pyrax/cf_wrapper/client.py index <HASH>..<HASH> 100644 --- a/pyrax/cf_wrapper/client.py +++ b/pyrax/cf_wrapper/client.py @@ -346,7 +346,7 @@ class CFClient(object): def move_object(self, container, obj_name, new_container, new_obj_name=None): """ Works just like copy_object, except that the source object is deleted - after a succesful copy. + after a successful copy. """ new_obj_etag = self.copy_object(container, obj_name, new_container, new_obj_name=new_obj_name) @@ -767,7 +767,7 @@ class Connection(_swift_client.Connection): def cdn_request(self, method, path=[], data="", hdrs=None): """ - Given a method (i.e. GET, PUT, POST, etc), a path, data, header and + Given a method (i.e. GET, PUT, POST, etc.), a path, data, header and metadata dicts, performs an http request against the CDN service. Taken directly from the cloudfiles library and modified for use here. diff --git a/pyrax/cloud_databases.py b/pyrax/cloud_databases.py index <HASH>..<HASH> 100644 --- a/pyrax/cloud_databases.py +++ b/pyrax/cloud_databases.py @@ -290,7 +290,7 @@ class CloudDatabaseClient(BaseClient): def create_user(self, instance, name, password, database_names): """ Creates a user with the specified name and password, and gives that - user access to the spcified database(s). + user access to the specified database(s). """ return instance.create_user(name=name, password=password, database_names=database_names) @@ -334,7 +334,7 @@ class CloudDatabaseClient(BaseClient): def list_flavors(self): - """Return a list of all available Flavors.""" + """Returns a list of all available Flavors.""" return self._flavor_manager.list() diff --git a/pyrax/resource.py b/pyrax/resource.py index <HASH>..<HASH> 100644 --- a/pyrax/resource.py +++ b/pyrax/resource.py @@ -28,10 +28,6 @@ class BaseResource(object): """ A resource represents a particular instance of an object (server, flavor, etc). This is pretty much just a bag for attributes. - - :param manager: Manager object - :param info: dictionary representing resource attributes - :param loaded: prevent lazy-loading if set to True """ HUMAN_ID = False NAME_ATTR = "name" @@ -45,7 +41,7 @@ class BaseResource(object): @property def human_id(self): - """Subclasses may override this provide a pretty ID which can be used + """Subclasses may override this to provide a pretty ID which can be used for bash completion. """ if self.NAME_ATTR in self.__dict__ and self.HUMAN_ID:
Fixed some typos in the docstrings.
pycontribs_pyrax
train
ab656051b4bb18d2935b8a4f7c77141503bfb597
diff --git a/src/stats/QueryStats.java b/src/stats/QueryStats.java index <HASH>..<HASH> 100644 --- a/src/stats/QueryStats.java +++ b/src/stats/QueryStats.java @@ -249,7 +249,7 @@ public class QueryStats { executed = 1; query_start_ns = DateTime.nanoTime(); query_start_ms = DateTime.currentTimeMillis(); - overall_stats = new HashMap<QueryStat, Long>(); + overall_stats = new ConcurrentHashMap<QueryStat, Long>(); query_stats = new ConcurrentHashMap<Integer, Map<QueryStat, Long>>(1); scanner_stats = new ConcurrentHashMap<Integer, Map<Integer, Map<QueryStat, Long>>>(1);
Fix #<I> by making the overall stats a concurrent map. Doh.
OpenTSDB_opentsdb
train
edc53a74553f19c2ec83ab7c12945758ba6084bf
diff --git a/flink-java/src/main/java/org/apache/flink/api/java/Utils.java b/flink-java/src/main/java/org/apache/flink/api/java/Utils.java index <HASH>..<HASH> 100644 --- a/flink-java/src/main/java/org/apache/flink/api/java/Utils.java +++ b/flink-java/src/main/java/org/apache/flink/api/java/Utils.java @@ -53,7 +53,7 @@ public final class Utils { public static String getCallLocationName(int depth) { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); - if (stackTrace.length < depth) { + if (stackTrace.length <= depth) { return "<unknown>"; } diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/query/netty/message/KvStateRequestSerializer.java b/flink-runtime/src/main/java/org/apache/flink/runtime/query/netty/message/KvStateRequestSerializer.java index <HASH>..<HASH> 100644 --- a/flink-runtime/src/main/java/org/apache/flink/runtime/query/netty/message/KvStateRequestSerializer.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/query/netty/message/KvStateRequestSerializer.java @@ -224,7 +224,7 @@ public final class KvStateRequestSerializer { // Get the message type int msgType = buf.readInt(); KvStateRequestType[] values = KvStateRequestType.values(); - if (msgType >= 0 && msgType <= values.length) { + if (msgType >= 0 && msgType < values.length) { return values[msgType]; } else { throw new IllegalArgumentException("Illegal message type with index " + msgType);
[FLINK-<I>] [java api] [runtime] Fix array index out of bounds exceptions This closes #<I>
apache_flink
train
6afca2def4858fb4a069c224b2f2041f933e8fe5
diff --git a/proton-j/src/main/java/org/apache/qpid/proton/reactor/impl/IOHandler.java b/proton-j/src/main/java/org/apache/qpid/proton/reactor/impl/IOHandler.java index <HASH>..<HASH> 100644 --- a/proton-j/src/main/java/org/apache/qpid/proton/reactor/impl/IOHandler.java +++ b/proton-j/src/main/java/org/apache/qpid/proton/reactor/impl/IOHandler.java @@ -154,7 +154,7 @@ public class IOHandler extends BaseHandler { socketChannel.configureBlocking(false); socketChannel.connect(new InetSocketAddress(hostname, port)); socket = socketChannel.socket(); - } catch(IOException ioException) { + } catch(Exception ioException) { ErrorCondition condition = new ErrorCondition(); condition.setCondition(Symbol.getSymbol("proton:io")); condition.setDescription(ioException.getMessage());
PROTON-<I>: IOException doesn't necessarily catch java.nio.channels.UnresolvedAddressException which is thrown when server is unavailable. This will cause reactor to fail and require a client restart. changing to Exception and close transport, so client can recover from failure even if 1 server is down without stopping reactor This closes #<I>
apache_qpid-proton
train
1b0b8a2b359f47f2dd2d2d3a39ffee395816d3d6
diff --git a/rkt/list.go b/rkt/list.go index <HASH>..<HASH> 100644 --- a/rkt/list.go +++ b/rkt/list.go @@ -212,18 +212,13 @@ func fmtNets(nis []netinfo.NetInfo) string { } func getImageName(p *pod, appName types.ACName) (string, error) { - aim, err := p.getAppsImageManifests() + aim, err := p.getAppImageManifest(appName) if err != nil { return "", fmt.Errorf("problem retrieving ImageManifests from pod: %v", err) } - im, ok := aim[appName] - if !ok { - return "", fmt.Errorf("could not find appName in pod: %v", err) - } - - imageName := im.Name.String() - if version, ok := im.Labels.Get("version"); ok { + imageName := aim.Name.String() + if version, ok := aim.Labels.Get("version"); ok { imageName = fmt.Sprintf("%s:%s", imageName, version) } diff --git a/rkt/pods.go b/rkt/pods.go index <HASH>..<HASH> 100644 --- a/rkt/pods.go +++ b/rkt/pods.go @@ -915,29 +915,16 @@ func (p *pod) getAppsHashes() ([]types.Hash, error) { return hashes, nil } -type AppsImageManifests map[types.ACName]*schema.ImageManifest - -// getAppsImageManifests returns a map of ImageManifests keyed to the -// corresponding App name. -func (p *pod) getAppsImageManifests() (AppsImageManifests, error) { - apps, err := p.getApps() +// getAppImageManifest returns an ImageManifest for the corresponding AppName. +func (p *pod) getAppImageManifest(appName types.ACName) (*schema.ImageManifest, error) { + imb, err := ioutil.ReadFile(common.AppInfoImageManifestPath(p.path(), appName)) if err != nil { return nil, err } - aim := make(AppsImageManifests) - for _, a := range apps { - imb, err := ioutil.ReadFile(common.AppInfoImageManifestPath(p.path(), a.Name)) - if err != nil { - return nil, err - } - - im := &schema.ImageManifest{} - if err := im.UnmarshalJSON(imb); err != nil { - return nil, fmt.Errorf("invalid image manifest for app %q: %v", a.Name.String(), err) - } - - aim[a.Name] = im + aim := &schema.ImageManifest{} + if err := aim.UnmarshalJSON(imb); err != nil { + return nil, fmt.Errorf("invalid image manifest for app %q: %v", appName.String(), err) } return aim, nil
rkt: change getAppsImageManifests to getAppImageManifest Because we already had the app names, it's better to get a specific app's image manifest rather than getting the image manifests from all the apps and forcing the caller to sort through those.
rkt_rkt
train
229a48d706545eee8bc5a2d1982f755ba09e1ede
diff --git a/pkg/fqdn/dnsproxy/proxy_test.go b/pkg/fqdn/dnsproxy/proxy_test.go index <HASH>..<HASH> 100644 --- a/pkg/fqdn/dnsproxy/proxy_test.go +++ b/pkg/fqdn/dnsproxy/proxy_test.go @@ -179,7 +179,7 @@ var ( dstPort = uint16(53) // Set below when we setup the server! ) -func (s *DNSProxyTestSuite) SetUpSuite(c *C) { +func (s *DNSProxyTestSuite) SetUpTest(c *C) { // Add these identities testSelectorCache.UpdateIdentities(cache.IdentityCache{ dstID1: labels.Labels{"Dst1": labels.NewLabel("Dst1", "test", labels.LabelSourceK8s)}.LabelArray(), @@ -250,9 +250,6 @@ func (s *DNSProxyTestSuite) SetUpSuite(c *C) { func (s *DNSProxyTestSuite) TearDownTest(c *C) { s.proxy.allowed = make(perEPAllow) s.proxy.SetRejectReply(option.FQDNProxyDenyWithRefused) -} - -func (s *DNSProxyTestSuite) TearDownSuite(c *C) { s.dnsServer.Listener.Close() s.proxy.UDPServer.Shutdown() s.proxy.TCPServer.Shutdown()
fqdn/dnsproxy: Close TCP and UDP server after each test To avoid concurrency issues across multiple tests we should shutdown and set up the TCP and UDP servers for each individual test.
cilium_cilium
train
e4859633c8cb0833be91d32f33c007ba5188673a
diff --git a/translator/utils.go b/translator/utils.go index <HASH>..<HASH> 100644 --- a/translator/utils.go +++ b/translator/utils.go @@ -27,8 +27,13 @@ func GetAllDependencies(pkg string, config *types.Config) ([]*types.Package, err if err != nil { return err } + var imps []string for _, imp := range typesPkg.Imports() { - if err := importPkg(imp.Path()); err != nil { + imps = append(imps, imp.Path()) + } + sort.Strings(imps) + for _, imp := range imps { + if err := importPkg(imp); err != nil { return err } }
Trying to get more determinism into package order.
gopherjs_gopherjs
train
d509946bef081161c5c4ceba3b13e4efbabc313a
diff --git a/kv/notification_rule.go b/kv/notification_rule.go index <HASH>..<HASH> 100644 --- a/kv/notification_rule.go +++ b/kv/notification_rule.go @@ -404,19 +404,17 @@ func (s *Service) forEachNotificationRule(ctx context.Context, tx Tx, descending return err } - cur, err := bkt.Cursor() - if err != nil { - return err + direction := CursorAscending + if descending { + direction = CursorDescending } - var k, v []byte - if descending { - k, v = cur.Last() - } else { - k, v = cur.First() + cur, err := bkt.ForwardCursor(nil, WithCursorDirection(direction)) + if err != nil { + return err } - for k != nil { + for k, v := cur.Next(); k != nil; k, v = cur.Next() { nr, err := rule.UnmarshalJSON(v) if err != nil { return err @@ -424,12 +422,6 @@ func (s *Service) forEachNotificationRule(ctx context.Context, tx Tx, descending if !fn(nr) { break } - - if descending { - k, v = cur.Prev() - } else { - k, v = cur.Next() - } } return nil
fix(kv): update notification rules to use the new forward cursor (#<I>)
influxdata_influxdb
train
898ee735e65b4da2985487105c1b38207d1c76cb
diff --git a/src/test/java/org/junit/contrib/truth/delegatetest/DelegationTest.java b/src/test/java/org/junit/contrib/truth/delegatetest/DelegationTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/org/junit/contrib/truth/delegatetest/DelegationTest.java +++ b/src/test/java/org/junit/contrib/truth/delegatetest/DelegationTest.java @@ -1,7 +1,7 @@ /* * Copyright (c) 2011 David Saff * Copyright (c) 2011 Christian Gruber - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -23,12 +23,21 @@ import org.junit.Test; /** * A test that's more or less intended to show how one uses an extended verb. - * + * */ public class DelegationTest { - @Test public void customTypeCompares() { + @Test public void customTypeProposition() { ASSERT.about(FOO).that(new Foo(5)).matches(new Foo(2 + 3)); } + @Test public void customTypePropositionWithFailure() { + try { + ASSERT.about(FOO).that(new Foo(5)).matches(new Foo(4)); + ASSERT.fail("Should have thrown."); + } catch (AssertionError e) { + ASSERT.that(e.getMessage()).contains("Not true that") + .and().contains("matches"); + } + } } diff --git a/src/test/java/org/junit/contrib/truth/extensiontest/ExtensionTest.java b/src/test/java/org/junit/contrib/truth/extensiontest/ExtensionTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/org/junit/contrib/truth/extensiontest/ExtensionTest.java +++ b/src/test/java/org/junit/contrib/truth/extensiontest/ExtensionTest.java @@ -16,7 +16,6 @@ */ package org.junit.contrib.truth.extensiontest; -import static org.junit.Assert.fail; import static org.junit.contrib.truth.extensiontest.ExtendedVerb.ASSERT; import org.junit.Test; @@ -31,14 +30,14 @@ import org.junit.runners.JUnit4; */ @RunWith(JUnit4.class) public class ExtensionTest { - @Test public void customTypeCompares() { + @Test public void customTypeProposition() { ASSERT.that(new MyType(5)).matches(new MyType(2 + 3)); } - @Test public void emptyCollectionWithFailure() { + @Test public void customTypePropositionWithFailure() { try { ASSERT.that(new MyType(5)).matches(new MyType(4)); - fail("Should have thrown."); + ASSERT.fail("Should have thrown."); } catch (AssertionError e) { ASSERT.that(e.getMessage()).contains("Not true that") .and().contains("matches");
fix up extensibility tests with better names, plus a failure test.
google_truth
train
a5ff43d6354f108898e98ef66d07a0650bc9e4ef
diff --git a/src/Projection/PdoEventStoreProjector.php b/src/Projection/PdoEventStoreProjector.php index <HASH>..<HASH> 100644 --- a/src/Projection/PdoEventStoreProjector.php +++ b/src/Projection/PdoEventStoreProjector.php @@ -522,6 +522,7 @@ EOT; try { do { $eventStreams = []; + $streamEvents = []; // free up memory from PDO statement foreach ($this->streamPositions as $streamName => $position) { try { diff --git a/src/Projection/PdoEventStoreReadModelProjector.php b/src/Projection/PdoEventStoreReadModelProjector.php index <HASH>..<HASH> 100644 --- a/src/Projection/PdoEventStoreReadModelProjector.php +++ b/src/Projection/PdoEventStoreReadModelProjector.php @@ -485,6 +485,7 @@ EOT; try { do { $eventStreams = []; + $streamEvents = []; // free up memory from PDO statement foreach ($this->streamPositions as $streamName => $position) { try {
free up memory from PDO statement before next run
prooph_pdo-event-store
train
c18e2681723518ceaf2067bc92a2488fa8ef501c
diff --git a/src/math/shape.js b/src/math/shape.js index <HASH>..<HASH> 100644 --- a/src/math/shape.js +++ b/src/math/shape.js @@ -500,7 +500,8 @@ /* */ /************************************************************************************/ /** - * a ellipse Object + * an ellipse Object + * (Tiled specifies top-left coordinates, and width and height of the ellipse) * @class * @extends Object * @memberOf me @@ -589,29 +590,17 @@ * @ignore */ draw : function(context, color) { - var centerX = this.pos.x; - var centerY = this.pos.y; - - var width = this.radius.x * 2; - var height = this.radius.y * 2; - - context.beginPath(); - - context.moveTo(centerX, centerY - height/2); // A1 - - context.bezierCurveTo( - centerX + width/2, centerY - height/2, // C1 - centerX + width/2, centerY + height/2, // C2 - centerX, centerY + height/2); // A2 - - context.bezierCurveTo( - centerX - width/2, centerY + height/2, // C3 - centerX - width/2, centerY - height/2, // C4 - centerX, centerY - height/2); // A1 - - context.strokeStyle = color || "red"; - context.fill(); - context.closePath(); + // http://tinyurl.com/opnro2r + context.save(); + context.beginPath(); + + context.translate(this.pos.x-this.radius.x, this.pos.y-this.radius.y); + context.scale(this.radius.x, this.radius.y); + context.arc(1, 1, 1, 0, 2 * Math.PI, false); + + context.restore(); + context.strokeStyle = color || "red"; + context.stroke(); } });
Fixed debug drawing of the ellipse
melonjs_melonJS
train
ebf3be7eac70accf3f79ca81190360230c3932a0
diff --git a/gitmediaclient/credentials.go b/gitmediaclient/credentials.go index <HASH>..<HASH> 100644 --- a/gitmediaclient/credentials.go +++ b/gitmediaclient/credentials.go @@ -25,7 +25,7 @@ func execCreds(input Creds, subCommand string) (*CredentialCmd, error) { } if err != nil { - return cmd, fmt.Errorf("'git credential %s' error: %s\n%s", cmd.SubCommand, err.Error(), cmd.StderrString()) + return cmd, fmt.Errorf("'git credential %s' error: %s\n", cmd.SubCommand, err.Error()) } return cmd, nil @@ -33,27 +33,26 @@ func execCreds(input Creds, subCommand string) (*CredentialCmd, error) { type CredentialCmd struct { output *bytes.Buffer - err *bytes.Buffer SubCommand string *exec.Cmd } func NewCommand(input Creds, subCommand string) *CredentialCmd { buf1 := new(bytes.Buffer) - buf2 := new(bytes.Buffer) cmd := exec.Command("git", "credential", subCommand) - cmd.Stdin = input.Buffer() - if commandHasOutput(subCommand) { - cmd.Stdout = buf1 - cmd.Stderr = buf2 - } + cmd.Stdin = input.Buffer() + cmd.Stdout = buf1 + /* + There is a reason we don't hook up stderr here: + Git's credential cache daemon helper does not close its stderr, so if this + process is the process that fires up the daemon, it will wait forever + (until the daemon exits, really) trying to read from stderr. - return &CredentialCmd{buf1, buf2, subCommand, cmd} -} + See https://github.com/github/git-media/issues/117 for more details. + */ -func (c *CredentialCmd) StderrString() string { - return c.err.String() + return &CredentialCmd{buf1, subCommand, cmd} } func (c *CredentialCmd) StdoutString() string { @@ -74,16 +73,6 @@ func (c *CredentialCmd) Credentials() Creds { return creds } -// commandHasOutput returns true if the command that's being run -// produces output. Of the three current subcommands `fill`, `approve`, -// and `reject`, only `fill` produces output. There is a bug in the way -// the git credential helpers launch the daemon if it is not already running -// such that the stderr of the grandchild does not appear to be getting closed, -// causing the git media client to not receive EOF on the pipe and wait forever. -func commandHasOutput(command string) bool { - return command == "fill" -} - type Creds map[string]string func (c Creds) Buffer() *bytes.Buffer {
It's easier if we just don't hook stderr up at all, since we can never use it anyway
git-lfs_git-lfs
train
ef07a9ec4826cc950574d496fa65d5b4488d068a
diff --git a/cassandra/protocol.py b/cassandra/protocol.py index <HASH>..<HASH> 100644 --- a/cassandra/protocol.py +++ b/cassandra/protocol.py @@ -531,6 +531,34 @@ RESULT_KIND_SET_KEYSPACE = 0x0003 RESULT_KIND_PREPARED = 0x0004 RESULT_KIND_SCHEMA_CHANGE = 0x0005 +class CassandraTypeCodes(object): + CUSTOM_TYPE = 0x0000 + AsciiType = 0x0001 + LongType = 0x0002 + BytesType = 0x0003 + BooleanType = 0x0004 + CounterColumnType = 0x0005 + DecimalType = 0x0006 + DoubleType = 0x0007 + FloatType = 0x0008 + Int32Type = 0x0009 + UTF8Type = 0x000A + DateType = 0x000B + UUIDType = 0x000C + UTF8Type = 0x000D + IntegerType = 0x000E + TimeUUIDType = 0x000F + InetAddressType = 0x0010 + SimpleDateType = 0x0011 + TimeType = 0x0012 + ShortType = 0x0013 + ByteType = 0x0014 + ListType = 0x0020 + MapType = 0x0021 + SetType = 0x0022 + UserType = 0x0030 + TupleType = 0x0031 + class ResultMessage(_MessageType): opcode = 0x08 @@ -540,34 +568,8 @@ class ResultMessage(_MessageType): results = None paging_state = None - type_codes = { - 0x0000: CUSTOM_TYPE, - 0x0001: AsciiType, - 0x0002: LongType, - 0x0003: BytesType, - 0x0004: BooleanType, - 0x0005: CounterColumnType, - 0x0006: DecimalType, - 0x0007: DoubleType, - 0x0008: FloatType, - 0x0009: Int32Type, - 0x000A: UTF8Type, - 0x000B: DateType, - 0x000C: UUIDType, - 0x000D: UTF8Type, - 0x000E: IntegerType, - 0x000F: TimeUUIDType, - 0x0010: InetAddressType, - 0x0011: SimpleDateType, - 0x0012: TimeType, - 0x0013: ShortType, - 0x0014: ByteType, - 0x0020: ListType, - 0x0021: MapType, - 0x0022: SetType, - 0x0030: UserType, - 0x0031: TupleType, - } + # Names match type name in module scope. Most are imported from cassandra.cqltypes (except CUSTOM_TYPE) + type_codes = _cqltypes_by_code = dict((v, globals()[k]) for k, v in CassandraTypeCodes.__dict__.items() if not k.startswith('_')) _FLAGS_GLOBAL_TABLES_SPEC = 0x0001 _HAS_MORE_PAGES_FLAG = 0x0002
Type code "enum" in protocol
datastax_python-driver
train
9f3eb3327882d1d346acf176f6f0d8291215d77b
diff --git a/src/index.js b/src/index.js index <HASH>..<HASH> 100644 --- a/src/index.js +++ b/src/index.js @@ -6,6 +6,7 @@ const hasOwnProperty = queue.hasOwnProperty; const origin = "https://cdn.jsdelivr.net/npm/"; const identifierRe = /^((?:@[^/@]+\/)?[^/@]+)(?:@([^/]+))?(?:\/(.*))?$/; const versionRe = /^\d+\.\d+\.\d+(-[\w-.+]+)?$/; +const mains = ["unpkg", "jsdelivr", "browser", "main"]; export class RequireError extends Error { constructor(message) { @@ -15,8 +16,13 @@ export class RequireError extends Error { RequireError.prototype.name = RequireError.name; -function string(value) { - return typeof value === "string" ? value : ""; +function main(meta) { + for (const key of mains) { + const value = meta[key]; + if (typeof value === "string") { + return value; + } + } } function parseIdentifier(identifier) { @@ -53,7 +59,7 @@ async function resolve(name, base) { if (target.path && !/\.[^/]*$/.test(target.path)) target.path += ".js"; if (target.path && target.version && versionRe.test(target.version)) return `${origin}${target.name}@${target.version}/${target.path}`; const meta = await resolveMeta(target); - return `${origin}${meta.name}@${meta.version}/${target.path || string(meta.unpkg) || string(meta.browser) || string(meta.main) || "index.js"}`; + return `${origin}${meta.name}@${meta.version}/${target.path || main(meta) || "index.js"}`; } export const require = requireFrom(resolve);
Observe jsdelivr entry.
d3_d3-require
train
b0d029baf34334c4307a625efbaa195674b995d7
diff --git a/glances/plugins/glances_ip.py b/glances/plugins/glances_ip.py index <HASH>..<HASH> 100644 --- a/glances/plugins/glances_ip.py +++ b/glances/plugins/glances_ip.py @@ -65,7 +65,8 @@ class Plugin(GlancesPlugin): self.display_curse = True # Get the public IP address once - self.public_address = PublicIpAddress().get() + if not self.is_disable(): + self.public_address = PublicIpAddress().get() # Init the stats self.reset()
Don't load public IP address if module disabled
nicolargo_glances
train
1b415e04ff85a151b6b0cf29d9d72328ef515aa9
diff --git a/satsearch/parser.py b/satsearch/parser.py index <HASH>..<HASH> 100644 --- a/satsearch/parser.py +++ b/satsearch/parser.py @@ -1,5 +1,3 @@ -import os -import json import argparse import satsearch.config as config @@ -47,6 +45,8 @@ class SatUtilsParser(argparse.ArgumentParser): config.DATADIR = args.pop('datadir') if 'subdirs' in args: config.SUBDIRS = args.pop('subdirs') + if 'filename' in args: + config.FILENAME = args.pop('filename') return args @@ -73,8 +73,9 @@ class SatUtilsParser(argparse.ArgumentParser): group.add_argument('--datadir', help='Local directory to save images', default=config.DATADIR) group.add_argument('--subdirs', default=config.SUBDIRS, help='Save in subdirs based on these metadata keys') + group.add_argument('--filename', default=config.FILENAME, + help='Save files with this filename pattern based on metadata keys') group.add_argument('--download', help='Download files', default=None, nargs='*') - group.add_argument('--source', help='Download source', default='aws_s3') def add_output_args(self): """ Add arguments for printing output """
remove source as cli arg and add filename
sat-utils_sat-search
train
db91520abe5a1db32928ff7c28ed80a16dd5c11e
diff --git a/api/src/main/java/net/kyori/adventure/text/ComponentBuilder.java b/api/src/main/java/net/kyori/adventure/text/ComponentBuilder.java index <HASH>..<HASH> 100644 --- a/api/src/main/java/net/kyori/adventure/text/ComponentBuilder.java +++ b/api/src/main/java/net/kyori/adventure/text/ComponentBuilder.java @@ -24,6 +24,7 @@ package net.kyori.adventure.text; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; @@ -274,6 +275,24 @@ public interface ComponentBuilder<C extends BuildableComponent<C, B>, B extends } /** + * Sets decorations for this component's style using the specified {@code decorations} map. + * + * <p>If a given decoration does not have a value explicitly set, the value of that particular decoration is not changed.</p> + * + * @param decorations a map containing text decorations and their respective state. + * @return this builder + * @since 4.10.0 + */ + @Contract("_ -> this") + @SuppressWarnings("unchecked") + default @NotNull B decorations(final @NotNull Map<TextDecoration, TextDecoration.State> decorations) { + for (final Map.Entry<TextDecoration, TextDecoration.State> entry : decorations.entrySet()) { + this.decoration(entry.getKey(), entry.getValue()); + } + return (B) this; + } + + /** * Sets the value of a decoration on this component. * * @param decoration the decoration diff --git a/api/src/main/java/net/kyori/adventure/text/format/Style.java b/api/src/main/java/net/kyori/adventure/text/format/Style.java index <HASH>..<HASH> 100644 --- a/api/src/main/java/net/kyori/adventure/text/format/Style.java +++ b/api/src/main/java/net/kyori/adventure/text/format/Style.java @@ -690,6 +690,23 @@ public interface Style extends Buildable<Style, Style.Builder>, Examinable { } /** + * Sets decorations for this style using the specified {@code decorations} map. + * + * <p>If a given decoration does not have a value explicitly set, the value of that particular decoration is not changed.</p> + * + * @param decorations a map containing text decorations and their respective state. + * @return this builder. + * @since 4.10.0 + */ + @Contract("_ -> this") + default @NotNull Builder decorations(final @NotNull Map<TextDecoration, TextDecoration.State> decorations) { + for (final Map.Entry<TextDecoration, TextDecoration.State> entry : decorations.entrySet()) { + this.decoration(entry.getKey(), entry.getValue()); + } + return this; + } + + /** * Sets the value of a decoration. * * @param decoration the decoration
Add decorations(Map) to component/style builders This commit introduces a new decorations method to the component and style builderthat takes in a map of text decorations and their state. This methodalready exists on the Component interface but was previously missing on the respective builders. As the style builder stores the decorations in individual fields and hence cannot natively work with the map layout, the method was implemented as a default method on the interface and simply delegates the map entriess to the normal decorate methods. The main motivation for the addition of this method is the easy application of a preset map of decorations.
KyoriPowered_text
train
8848650bddd00acc27a0d8e67ae1093a57793e16
diff --git a/smokes/protractor-headless.conf.js b/smokes/protractor-headless.conf.js index <HASH>..<HASH> 100644 --- a/smokes/protractor-headless.conf.js +++ b/smokes/protractor-headless.conf.js @@ -18,7 +18,13 @@ exports.config = { capabilities: { 'browserName': 'chrome', 'chromeOptions': { - 'args': ['--headless', '--disable-gpu', '--no-sandbox', '--window-size=1024,768'] + 'args': [ + '--headless', + '--disable-gpu', + '--no-sandbox', + '--window-size=1024,768', + '--user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/56.0.2924.87"', + ] } }, diff --git a/smokes/protractor.conf.js b/smokes/protractor.conf.js index <HASH>..<HASH> 100644 --- a/smokes/protractor.conf.js +++ b/smokes/protractor.conf.js @@ -20,7 +20,10 @@ exports.config = { chromeOptions: { // minimal supported browser size for tests // if smaller we start need to scroll for clicking buttons - args: ['--window-size=1024,768'] + args: [ + '--window-size=1024,768', + '--user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/56.0.2924.87"', + ] } },
smokes: Provide explicit user agent to the test browser
buildbot_buildbot
train